@lunora/shard-engine 1.0.0-alpha.3 → 1.0.0-alpha.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (138) hide show
  1. package/dist/conformance/index.mjs +1 -1
  2. package/dist/index.d.mts +191 -20
  3. package/dist/index.d.ts +191 -20
  4. package/dist/index.mjs +1 -1
  5. package/dist/packem_shared/ADMIN_FUNCTIONS-Ddr79XHG.mjs +1 -0
  6. package/dist/packem_shared/AGGREGATE_SQL_FUNCTION-m1iUU1rv.mjs +1 -0
  7. package/dist/packem_shared/AGG_COUNT-DOlqqroz.mjs +1 -0
  8. package/dist/packem_shared/AUDIT_LOG_TABLE-uNVU9O1W.mjs +8 -0
  9. package/dist/packem_shared/CDC_LOG_TABLE-B58N8NQO.mjs +8 -0
  10. package/dist/packem_shared/CLIENT_WATERMARK_TABLE-BoS1HEqz.mjs +7 -0
  11. package/dist/packem_shared/CountRlsUnsupportedError-Bdfupt3g.mjs +1 -0
  12. package/dist/packem_shared/DATA_MIGRATION_STATE_TABLE-4l6aU1Vc.mjs +31 -0
  13. package/dist/packem_shared/DEFAULT_MAX_RELATION_KEYS-BAWGIEvC.mjs +1 -0
  14. package/dist/packem_shared/DEFAULT_MAX_RELAYS-DeVcEXBh.mjs +1 -0
  15. package/dist/packem_shared/DEFAULT_PROMOTION_THRESHOLDS-DVTD9iu0.mjs +1 -0
  16. package/dist/packem_shared/DEFAULT_TRANSACTION_LIMITS-Bcoi7Bvf.mjs +1 -0
  17. package/dist/packem_shared/DurableStreamRunner-Bm6KDMBU.mjs +1 -0
  18. package/dist/packem_shared/GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs +1 -0
  19. package/dist/packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-NWaL77m5.mjs +7 -0
  20. package/dist/packem_shared/IDEMPOTENCY_TABLE-DKVe2Ohf.mjs +7 -0
  21. package/dist/packem_shared/MAIL_RETENTION-Cig9Dmc8.mjs +18 -0
  22. package/dist/packem_shared/MAX_SQL_ROWS-DnDyeZph.mjs +2 -0
  23. package/dist/packem_shared/NotUniqueError-BixDiv4O.mjs +1 -0
  24. package/dist/packem_shared/QUEUE_TABLE-zj9Tt6tk.mjs +17 -0
  25. package/dist/packem_shared/RANK_TIEBREAK-ci3MaM65.mjs +1 -0
  26. package/dist/packem_shared/RELATION_EXISTS_KEY-CFUhnZSZ.mjs +1 -0
  27. package/dist/packem_shared/REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs +1 -0
  28. package/dist/packem_shared/RLS_UNWRAP_SYMBOL-BWloGsd3.mjs +1 -0
  29. package/dist/packem_shared/ReactiveCache-DfyeaJOA.mjs +1 -0
  30. package/dist/packem_shared/SCAN_DEP-D7qE3iUe.mjs +1 -0
  31. package/dist/packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-DsycDXWm.mjs +6 -0
  32. package/dist/packem_shared/SEARCH_STATE_TABLE-Dju8ebbU.mjs +1 -0
  33. package/dist/packem_shared/SHAPE_POKE_CURSOR_TABLE-Dh4HfSdC.mjs +7 -0
  34. package/dist/packem_shared/ShardRunner-C9p5DVOx.mjs +1 -0
  35. package/dist/packem_shared/aggregateTableName-Cy5e03oz.mjs +1 -0
  36. package/dist/packem_shared/appendStreamChunk-CH4e4nJn.mjs +19 -0
  37. package/dist/packem_shared/applyOnDelete-BlcwKjuO.mjs +1 -0
  38. package/dist/packem_shared/applySelect-BQbHyo-W.mjs +1 -0
  39. package/dist/packem_shared/{armRestore-BNzdvQ_o.mjs → armRestore-Bu1_8SUa.mjs} +1 -1
  40. package/dist/packem_shared/awaitWsDrain-kSGvAfw1.mjs +1 -0
  41. package/dist/packem_shared/backfillAggregateIndexes-DVQ2sVuV.mjs +1 -0
  42. package/dist/packem_shared/base64-DfpzS4o_.mjs +1 -0
  43. package/dist/packem_shared/buildIndexRange-CBKQmHSS.mjs +1 -0
  44. package/dist/packem_shared/buildPokeFrames-BXejpiII.mjs +1 -0
  45. package/dist/packem_shared/buildReprojectionMigration-8nVn8Qwb.mjs +1 -0
  46. package/dist/packem_shared/buildSettings-B4igo4rJ.mjs +1 -0
  47. package/dist/packem_shared/compileWhereSql-JBpSfQm9.mjs +1 -0
  48. package/dist/packem_shared/computeRankPage-Bby1Npkd.mjs +1 -0
  49. package/dist/packem_shared/createCompanionSync-zCwaB6wj.mjs +1 -0
  50. package/dist/packem_shared/createReadFootprint-MRH1If3F.mjs +1 -0
  51. package/dist/packem_shared/createReplicaLink-C1JuP_DN.mjs +7 -0
  52. package/dist/packem_shared/createSystemReader-BtYeSMDb.mjs +1 -0
  53. package/dist/packem_shared/ctx-db-companions-lTt-rvKG.mjs +1 -0
  54. package/dist/packem_shared/defineEngineContractSuite-0XtjRA7F.mjs +1 -0
  55. package/dist/packem_shared/diffExternalSource-pozJ4UdZ.mjs +1 -0
  56. package/dist/packem_shared/do-sql-Dk_DJxn4.mjs +1 -0
  57. package/dist/packem_shared/estimate-bytes-CzG5x1f8.mjs +1 -0
  58. package/dist/packem_shared/exportShardRows-Cgt3ITwH.mjs +1 -0
  59. package/dist/packem_shared/hasTrigger-CjlwI4le.mjs +1 -0
  60. package/dist/packem_shared/isSoftDeleted-DcGB0pov.mjs +9 -0
  61. package/dist/packem_shared/liftSourceId-CA3ENhXj.mjs +1 -0
  62. package/dist/packem_shared/materializeExternalRows-Drn0FGdb.mjs +1 -0
  63. package/dist/packem_shared/mergeChangedKeys-D1T-TPUb.mjs +1 -0
  64. package/dist/packem_shared/param-Ib8WHnrF.mjs +1 -0
  65. package/dist/packem_shared/quoteIdentifier-CObIFRhb.mjs +1 -0
  66. package/dist/packem_shared/runDrizzle-it6rL9bR.mjs +1 -0
  67. package/dist/packem_shared/runShardMigrations-Crppyq1f.mjs +5 -0
  68. package/dist/packem_shared/runSocketPool-CZJ2X9cF.mjs +1 -0
  69. package/dist/packem_shared/selectExpiredIds-_5514W_v.mjs +1 -0
  70. package/dist/packem_shared/selectShapeMemberIds-B-pQJHAu.mjs +1 -0
  71. package/dist/packem_shared/serializeSqlValue-DbI1VQYM.mjs +1 -0
  72. package/dist/packem_shared/sibling-channel-BRZpLiDA.mjs +1 -0
  73. package/dist/packem_shared/sql-projection-BqmxFxQU.mjs +1 -0
  74. package/dist/packem_shared/stableStringify-CujpENIO.mjs +1 -0
  75. package/dist/packem_shared/stableWireKey-BYB5GQJa.mjs +1 -0
  76. package/dist/packem_shared/wire-codec-BU9T2xJ7.mjs +1 -0
  77. package/package.json +3 -3
  78. package/dist/packem_shared/ADMIN_FUNCTIONS-B0xlQJ4w.mjs +0 -1
  79. package/dist/packem_shared/AGGREGATE_SQL_FUNCTION-QYaiuty4.mjs +0 -1
  80. package/dist/packem_shared/AGG_COUNT-BWXe3gtQ.mjs +0 -1
  81. package/dist/packem_shared/AUDIT_LOG_TABLE-CaA0jL0L.mjs +0 -8
  82. package/dist/packem_shared/CDC_LOG_TABLE-BnqlH2eZ.mjs +0 -8
  83. package/dist/packem_shared/CLIENT_WATERMARK_TABLE-CXsSLU8D.mjs +0 -7
  84. package/dist/packem_shared/CountRlsUnsupportedError-B2WKJD9v.mjs +0 -1
  85. package/dist/packem_shared/DATA_MIGRATION_STATE_TABLE-CaO6L0Ee.mjs +0 -31
  86. package/dist/packem_shared/DEFAULT_MAX_RELATION_KEYS-bq00btqV.mjs +0 -1
  87. package/dist/packem_shared/DEFAULT_MAX_RELAYS-CnCyh6oX.mjs +0 -1
  88. package/dist/packem_shared/DEFAULT_PROMOTION_THRESHOLDS-Dteg0sZF.mjs +0 -1
  89. package/dist/packem_shared/DEFAULT_TRANSACTION_LIMITS--TtB8Gpo.mjs +0 -1
  90. package/dist/packem_shared/FTS_COUNT_COLUMN-D1gY3wwZ-CZHdaRrd.mjs +0 -1
  91. package/dist/packem_shared/GEO_DEFAULT_PRECISION-okRCkZ6r.mjs +0 -1
  92. package/dist/packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-DX-6-gBP.mjs +0 -7
  93. package/dist/packem_shared/IDEMPOTENCY_TABLE-DjkEMp6w.mjs +0 -7
  94. package/dist/packem_shared/MAIL_RETENTION-KmozO2NQ.mjs +0 -18
  95. package/dist/packem_shared/MAX_SQL_ROWS-nMwkxv5f.mjs +0 -2
  96. package/dist/packem_shared/NotUniqueError-iGKd9wRR.mjs +0 -1
  97. package/dist/packem_shared/QUEUE_TABLE-DYCDvzTG.mjs +0 -17
  98. package/dist/packem_shared/RANK_TIEBREAK-9NU5s_mi.mjs +0 -1
  99. package/dist/packem_shared/RELATION_EXISTS_KEY-BaqSIFU1.mjs +0 -1
  100. package/dist/packem_shared/RLS_UNWRAP_SYMBOL-C6_WX3dG.mjs +0 -1
  101. package/dist/packem_shared/ReactiveCache-CF21t8IB.mjs +0 -1
  102. package/dist/packem_shared/SCAN_DEP-D_yR9EeV.mjs +0 -1
  103. package/dist/packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-CHXz6p_z.mjs +0 -6
  104. package/dist/packem_shared/SEARCH_STATE_TABLE-eLN8U5tz.mjs +0 -1
  105. package/dist/packem_shared/ShardRunner-DIqVdWtk.mjs +0 -1
  106. package/dist/packem_shared/aggregateTableName-G-eXyjcz.mjs +0 -1
  107. package/dist/packem_shared/applyOnDelete-uFRC5p1d.mjs +0 -1
  108. package/dist/packem_shared/applySelect-B0CF8T7y.mjs +0 -1
  109. package/dist/packem_shared/awaitWsDrain-Dk50ISgE.mjs +0 -1
  110. package/dist/packem_shared/backfillAggregateIndexes-BHiewuB-.mjs +0 -1
  111. package/dist/packem_shared/buildIndexRange-DIjFVgeO.mjs +0 -1
  112. package/dist/packem_shared/buildPokeFrames-DaPpm5Ss.mjs +0 -1
  113. package/dist/packem_shared/buildSettings-DT18_DkX.mjs +0 -1
  114. package/dist/packem_shared/compileWhereSql-BLcfs4QW.mjs +0 -1
  115. package/dist/packem_shared/computeRankPage-IUSS-zIB.mjs +0 -1
  116. package/dist/packem_shared/createCompanionSync-DWK0Vlg1.mjs +0 -1
  117. package/dist/packem_shared/createReadFootprint-DIrrxRTE.mjs +0 -1
  118. package/dist/packem_shared/createSystemReader-DcDcrtM3.mjs +0 -1
  119. package/dist/packem_shared/defineEngineContractSuite-BefTibvY.mjs +0 -1
  120. package/dist/packem_shared/diffExternalSource-DMpkJta1.mjs +0 -1
  121. package/dist/packem_shared/estimate-bytes-DzD3PdCc.mjs +0 -1
  122. package/dist/packem_shared/exportShardRows-kt42wijd.mjs +0 -1
  123. package/dist/packem_shared/hasTrigger-CbkOHExZ.mjs +0 -1
  124. package/dist/packem_shared/isSoftDeleted-B-SXkGUo.mjs +0 -9
  125. package/dist/packem_shared/liftSourceId-DApAbu7Q.mjs +0 -1
  126. package/dist/packem_shared/materializeExternalRows-DOQJV9p2.mjs +0 -1
  127. package/dist/packem_shared/mergeChangedKeys-CvSHlkv-.mjs +0 -1
  128. package/dist/packem_shared/param-B5lF5Jd9.mjs +0 -1
  129. package/dist/packem_shared/quote-identifier-CGiYFBvY.mjs +0 -1
  130. package/dist/packem_shared/runDrizzle-GKR3y97k.mjs +0 -1
  131. package/dist/packem_shared/runShardMigrations-CPxqCh3O.mjs +0 -5
  132. package/dist/packem_shared/runSocketPool-DPQLVyWF.mjs +0 -1
  133. package/dist/packem_shared/selectExpiredIds-FzhIEeG1.mjs +0 -1
  134. package/dist/packem_shared/selectShapeMemberIds-DvE7K6zG.mjs +0 -1
  135. package/dist/packem_shared/serializeSqlValue-DnpyaLcw.mjs +0 -1
  136. package/dist/packem_shared/stableStringify-BjLh4gvA.mjs +0 -1
  137. package/dist/packem_shared/stableWireKey-YEHLaX6X.mjs +0 -1
  138. package/dist/packem_shared/wire-codec-Ctnni0h6.mjs +0 -1
package/dist/index.d.ts CHANGED
@@ -230,6 +230,7 @@ interface ResolveWithOptions {
230
230
  groupedCounter: (tableName: string, whereField: string, values: unknown[], policyWhere?: WhereInput) => Promise<Map<unknown, number>>;
231
231
  parents: Record<string, unknown>[];
232
232
  relationBaseWhere?: (table: string) => undefined | WhereInput;
233
+ relationMask?: RelationMask;
233
234
  schema: {
234
235
  readonly tables: Record<string, TableDefinitionLike>;
235
236
  };
@@ -250,11 +251,19 @@ interface QueryArgs {
250
251
  limit?: number;
251
252
  orderBy?: OrderByInput[];
252
253
  relationBaseWhere?: (table: string) => undefined | WhereInput;
254
+ relationMask?: RelationMask;
253
255
  restrictsCounts?: boolean;
254
256
  select?: ReadonlyArray<string>;
255
257
  where?: WhereInput;
256
258
  with?: WithInput;
257
259
  }
260
+ interface CrossShardReadArgs {
261
+ orderBy?: OrderByInput[];
262
+ relationPolicies?: Record<string, WhereInput>;
263
+ where?: WhereInput;
264
+ with?: WithInput;
265
+ }
266
+ type RelationMask = (table: string, rows: Record<string, unknown>[]) => Record<string, unknown>[];
258
267
  interface QueryPage {
259
268
  continueCursor: null | string;
260
269
  isDone: boolean;
@@ -359,9 +368,21 @@ interface GeoFilterBuilderLike {
359
368
  };
360
369
  }) => GeoFilterBuilderLike;
361
370
  }
371
+ type ScoredDocument = GeoScoredDocument | SearchScoredDocument;
372
+ interface GeoScoredDocument {
373
+ distanceMeters: null | number;
374
+ document: Record<string, unknown>;
375
+ score?: never;
376
+ }
377
+ interface SearchScoredDocument {
378
+ distanceMeters?: never;
379
+ document: Record<string, unknown>;
380
+ score: number;
381
+ }
362
382
  interface TableReaderLike {
363
383
  [Symbol.asyncIterator]: () => AsyncIterator<Record<string, unknown>>;
364
384
  collect: () => Promise<Record<string, unknown>[]>;
385
+ collectWithScores: () => Promise<ScoredDocument[]>;
365
386
  filter: (predicate: (document: Record<string, unknown>) => boolean) => TableReaderLike;
366
387
  first: () => Promise<Record<string, unknown> | null>;
367
388
  order: (direction: "asc" | "desc") => TableReaderLike;
@@ -600,6 +621,7 @@ declare class ReactiveCache {
600
621
  };
601
622
  private dropRangeDeps;
602
623
  private collectAndDrop;
624
+ private dropKeys;
603
625
  private dropEntry;
604
626
  private evict;
605
627
  }
@@ -817,6 +839,7 @@ interface ShapeSubscriptionQuery {
817
839
  sinceSeq?: number;
818
840
  }
819
841
  interface SubscriptionEnvelope {
842
+ caps?: string[];
820
843
  clientId?: string;
821
844
  context?: Record<string, unknown>;
822
845
  data?: unknown;
@@ -827,6 +850,7 @@ interface SubscriptionEnvelope {
827
850
  name: string;
828
851
  };
829
852
  sinceCheckpoint?: number;
853
+ sinceChunk?: number;
830
854
  sinceEpoch?: string;
831
855
  topic?: string;
832
856
  type: "ack" | "connect" | "shape_subscribe" | "shape_unsubscribe" | "stream" | "subscribe" | "unsubscribe" | "whisper" | "whisper_subscribe" | "whisper_unsubscribe";
@@ -843,6 +867,7 @@ interface SocketAttachment {
843
867
  context?: Record<string, unknown>;
844
868
  expiresAt?: number;
845
869
  identity?: Record<string, unknown>;
870
+ pageDeltas?: boolean;
846
871
  shapes?: Record<string, ShapeSubscriptionQuery>;
847
872
  subs: Record<string, SubscriptionQuery>;
848
873
  userId?: string;
@@ -907,11 +932,21 @@ interface RankPageComputation {
907
932
  }
908
933
  declare const hydrateDocsById: (deps: RankPageDeps, tableName: string, ids: ReadonlyArray<string>) => Map<string, Record<string, unknown>>;
909
934
  declare const computeRankPage: (deps: RankPageDeps, tableName: string, indexName: string, rankPageOptions: RankPageOptions) => RankPageComputation;
935
+ declare const SHAPE_POKE_CURSOR_TABLE = "__shape_poke_cursor";
936
+ declare const migrateShapePokeCursor: (sql: SqlExec) => void;
937
+ declare const readShapePokeCursor: (sql: SqlExec, connectionId: string, subId: string) => number | undefined;
938
+ declare const writeShapePokeCursor: (sql: SqlExec, connectionId: string, subId: string, cursor: number) => void;
939
+ declare const deleteShapePokeCursor: (sql: SqlExec, connectionId: string, subId: string) => void;
940
+ declare const deleteShapePokeCursorsForConnection: (sql: SqlExec, connectionId: string) => void;
910
941
  declare const DATA_MIGRATION_STATE_TABLE = "__lunora_migrations";
911
942
  type MigrationDirection = "down" | "up";
912
943
  type MigrationStatus = "completed" | "failed" | "in_progress";
913
944
  type DataMigrationDocument = Record<string, unknown>;
914
- type DataMigrationTransform = (document: DataMigrationDocument) => DataMigrationDocument | undefined;
945
+ type DataMigrationReader = Pick<DatabaseWriterLike, "count" | "findFirst" | "findMany" | "get">;
946
+ interface DataMigrationContext {
947
+ db: DataMigrationReader;
948
+ }
949
+ type DataMigrationTransform = (document: DataMigrationDocument, context: DataMigrationContext) => DataMigrationDocument | Promise<DataMigrationDocument | undefined> | undefined;
915
950
  interface DataMigrationLike {
916
951
  readonly batchSize?: number;
917
952
  readonly down?: DataMigrationTransform;
@@ -966,10 +1001,10 @@ interface DependencyTracker {
966
1001
  declare const createDependencyTracker: () => DependencyTracker;
967
1002
  declare const runSql: <Row = Record<string, unknown>>(sql: SqlExec, query: string, ...params: unknown[]) => SqlCursor<Row>;
968
1003
  declare const runDrizzle: <Row = Record<string, unknown>>(exec: SqlExec, query: SQL) => SqlCursor<Row>;
1004
+ declare const quoteIdentifier: (name: string) => string;
969
1005
  declare const serializeSqlValue: (value: unknown) => unknown;
970
1006
  declare const DOC_COLUMN = "__doc__";
971
1007
  declare const geoTableName: (table: string, indexName: string) => string;
972
- declare const quoteIdentifier: (name: string) => string;
973
1008
  declare const jsonPath: (field: string) => string;
974
1009
  declare const jsonPathSql: (field: string) => SQL;
975
1010
  declare const qualifiedJsonPath: (table: string, field: string) => string;
@@ -990,6 +1025,72 @@ interface RenderedSql {
990
1025
  }
991
1026
  declare const renderSql: (engine: SqlEngine, query: SQL) => RenderedSql;
992
1027
  declare const param: (value: unknown) => SQL;
1028
+ declare const unionAll: (branches: ReadonlyArray<SQL>) => SQL;
1029
+ declare const sqliteInList: (reference: SQL, items: ReadonlyArray<unknown>, negated: boolean, budget?: number) => SQL;
1030
+ type DurableStreamStatus = "complete" | "error" | "running";
1031
+ interface DurableStreamRun {
1032
+ error?: string;
1033
+ errorCode?: string;
1034
+ lastSeq: number;
1035
+ startedAt: number;
1036
+ status: DurableStreamStatus;
1037
+ }
1038
+ interface DurableStreamChunk {
1039
+ dataJson: string;
1040
+ seq: number;
1041
+ }
1042
+ declare const migrateDurableStreams: (sql: SqlExec) => void;
1043
+ declare const readStreamRun: (sql: SqlExec, runKey: string) => DurableStreamRun | undefined;
1044
+ declare const claimStreamRun: (sql: SqlExec, runKey: string, startedAt: number, ttlMs: number) => boolean;
1045
+ declare const deleteStreamRun: (sql: SqlExec, runKey: string) => void;
1046
+ declare const appendStreamChunk: (sql: SqlExec, runKey: string, seq: number, dataJson: string) => void;
1047
+ declare const readStreamChunks: (sql: SqlExec, runKey: string, sinceSeq: number) => DurableStreamChunk[];
1048
+ declare const finishStreamRun: (sql: SqlExec, runKey: string, status: "complete" | "error", lastSeq: number, failure?: {
1049
+ code: string;
1050
+ message: string;
1051
+ }) => void;
1052
+ declare const trimStreamRuns: (sql: SqlExec, now: number) => void;
1053
+ declare const MAX_DURABLE_STREAM_CHUNKS = 50000;
1054
+ declare const MAX_DURABLE_STREAM_BYTES: number;
1055
+ interface DurableStreamSink {
1056
+ readonly chunk: (chunk: {
1057
+ data: unknown;
1058
+ seq: number;
1059
+ }) => boolean;
1060
+ readonly complete: () => void;
1061
+ readonly fail: (failure: {
1062
+ code: string;
1063
+ message: string;
1064
+ }) => void;
1065
+ }
1066
+ type DurableAttachDecision = "attach" | "interrupted" | "reclaim" | "replay-terminal";
1067
+ declare const decideDurableAttach: (run: DurableStreamRun | undefined, context: {
1068
+ live: boolean;
1069
+ resuming: boolean;
1070
+ }) => DurableAttachDecision;
1071
+ interface DurableStreamAttach {
1072
+ readonly iterator: (signal: AbortSignal) => AsyncIterable<unknown>;
1073
+ readonly runKey: string;
1074
+ readonly sinceChunk: number;
1075
+ readonly sink: DurableStreamSink;
1076
+ readonly ttlMs?: number;
1077
+ }
1078
+ declare class DurableStreamRunner {
1079
+ private lastTrimAt;
1080
+ private readonly runs;
1081
+ private readonly sql;
1082
+ private readonly waitUntil;
1083
+ constructor(dependencies: {
1084
+ sql: () => SqlExec;
1085
+ waitUntil?: (promise: Promise<unknown>) => void;
1086
+ });
1087
+ attach(request: DurableStreamAttach): Promise<void>;
1088
+ detach(runKey: string, sink: DurableStreamSink): void;
1089
+ isLive(runKey: string): boolean;
1090
+ private attachOrThrow;
1091
+ private produce;
1092
+ private trim;
1093
+ }
993
1094
  interface ExternalSourceDiffResult {
994
1095
  changes: CdcChange[];
995
1096
  nextBaseline: Map<string, string>;
@@ -1103,6 +1204,7 @@ declare const ADMIN_FUNCTIONS: {
1103
1204
  readonly getMetricSeries: "__lunora_admin__:getMetricSeries";
1104
1205
  readonly listSubscriptions: "__lunora_admin__:listSubscriptions";
1105
1206
  readonly listTableIndexes: "__lunora_admin__:listTableIndexes";
1207
+ readonly listTablesIndexes: "__lunora_admin__:listTablesIndexes";
1106
1208
  readonly getLogs: "__lunora_admin__:getLogs";
1107
1209
  readonly getMetrics: "__lunora_admin__:getMetrics";
1108
1210
  readonly getPitrBookmark: "__lunora_admin__:getPitrBookmark";
@@ -1195,6 +1297,9 @@ interface TableIndexInfo {
1195
1297
  interface TableIndexesResult {
1196
1298
  indexes: TableIndexInfo[];
1197
1299
  }
1300
+ interface TablesIndexesResult {
1301
+ indexesByTable: Record<string, TableIndexInfo[]>;
1302
+ }
1198
1303
  interface ColumnMeta {
1199
1304
  isStorage?: boolean;
1200
1305
  name: string;
@@ -1225,12 +1330,13 @@ interface AdvisoriesResult {
1225
1330
  advisories: AdvisoryFinding[];
1226
1331
  }
1227
1332
  interface AdvisorProcedure {
1228
- callsMail: boolean;
1333
+ analyzableBody?: boolean;
1334
+ callsMail?: boolean;
1229
1335
  emitsEvent?: boolean;
1230
1336
  exempt?: boolean;
1231
1337
  exemptReason?: string;
1232
1338
  exportName: string;
1233
- fanOut: boolean;
1339
+ fanOut?: boolean;
1234
1340
  file: string;
1235
1341
  handlesErrors?: boolean;
1236
1342
  hasEmailArg?: boolean;
@@ -1238,15 +1344,15 @@ interface AdvisorProcedure {
1238
1344
  reachesOutbound?: boolean;
1239
1345
  runsAiGeneration?: boolean;
1240
1346
  throwsBareError?: boolean;
1241
- unboundedAiGeneration: boolean;
1347
+ unboundedAiGeneration?: boolean;
1242
1348
  usesCaptcha: boolean;
1243
1349
  usesEmailGate: boolean;
1244
- usesInsertManyUnsafe: boolean;
1350
+ usesInsertManyUnsafe?: boolean;
1245
1351
  usesMask: boolean;
1246
1352
  usesRateLimit: boolean;
1247
1353
  usesRls: boolean;
1248
1354
  visibility: "internal" | "public";
1249
- writesUserTable: boolean;
1355
+ writesUserTable?: boolean;
1250
1356
  }
1251
1357
  interface AdvisorProceduresResult {
1252
1358
  procedures: AdvisorProcedure[];
@@ -1588,7 +1694,6 @@ declare const clearQueueMessages: (sql: SqlExec) => {
1588
1694
  declare const encodePartitionKey: (partitionBy: ReadonlyArray<string>, source: Record<string, unknown>) => string;
1589
1695
  declare const RANK_TIEBREAK = "__id__";
1590
1696
  declare const sortColumnName: (i: number) => string;
1591
- declare const matchesRankStaticWhere: (document: Record<string, unknown>, predicate: Record<string, unknown>) => boolean;
1592
1697
  declare const resolveRankPartition: (index: RankIndexDefinitionLike, where: Record<string, unknown> | undefined) => Record<string, unknown> | undefined;
1593
1698
  declare const rankTableName: (table: string, indexName: string) => string;
1594
1699
  declare const rankKeyFromDocument: (index: RankIndexDefinitionLike, document_: Record<string, unknown>) => {
@@ -1596,6 +1701,7 @@ declare const rankKeyFromDocument: (index: RankIndexDefinitionLike, document_: R
1596
1701
  rowId: string;
1597
1702
  sortValues: unknown[];
1598
1703
  };
1704
+ declare const matchesRankStaticWhere: (document: Record<string, unknown>, predicate: Record<string, unknown>) => boolean;
1599
1705
  interface ReadFootprint {
1600
1706
  onRead: (table: string, idOrScan?: string) => void;
1601
1707
  onReadRange: (range: KeyRange) => void;
@@ -1637,6 +1743,7 @@ declare const containsRelationPredicate: (where: WhereInput, schema: ResolveCont
1637
1743
  declare const assertFlatPredicate: (where: WhereInput | undefined, schema: ResolveContext["schema"], tableName: string, op: string) => void;
1638
1744
  declare const resolveRelationPredicates: (where: WhereInput | undefined, options: ResolveRelationPredicatesOptions) => Promise<WhereInput | undefined>;
1639
1745
  declare const assertShapeShardable: (effectiveWhere: WhereInput | undefined, schema: ResolveContext["schema"], table: string) => void;
1746
+ declare const relationHooks: (args: Pick<QueryArgs, "relationBaseWhere" | "relationMask">) => Pick<QueryArgs, "relationBaseWhere" | "relationMask">;
1640
1747
  declare const fanOutScalarCounts: (counter: (tableName: string, where?: WhereInput) => Promise<number>, tableName: string, whereField: string, values: unknown[], policyWhere: WhereInput | undefined) => Promise<Map<unknown, number>>;
1641
1748
  declare const distinctValues: (rows: Record<string, unknown>[], field: string) => unknown[];
1642
1749
  declare const resolveWith: (options: ResolveWithOptions) => Promise<void>;
@@ -1741,15 +1848,10 @@ interface RelayShapePoke {
1741
1848
  type: "relay_shape_poke";
1742
1849
  }
1743
1850
  type OwnerRelayFrame = RelayAttach | RelayDetach | RelayFrame | RelayShapePoke | RelayShapeSubscribe;
1744
- declare const DEFAULT_MAX_RELAYS = 8;
1745
- interface RelayStub {
1851
+ interface SiblingStub {
1746
1852
  fetch: (url: string, init?: RequestInit) => Promise<Response>;
1747
1853
  }
1748
- interface RelayNamespaceLike {
1749
- get: (id: unknown) => RelayStub;
1750
- getByName?: (name: string) => RelayStub;
1751
- idFromName: (name: string) => unknown;
1752
- }
1854
+ declare const DEFAULT_MAX_RELAYS = 8;
1753
1855
  interface RelayHost {
1754
1856
  buildShapeDiff: (resolved: ResolvedShape, fromCursor: number, toCursor: number) => ShapeRowOp[];
1755
1857
  computeOpLogShapeSeed: (shape: ShapeSubscriptionQuery, resolved: ResolvedShape) => {
@@ -1785,7 +1887,7 @@ declare abstract class RelayLink {
1785
1887
  handleControl(request: Request): Promise<Response>;
1786
1888
  maxRelays(): number;
1787
1889
  protected canAddressSiblings(): boolean;
1788
- protected relayNamespace(): RelayNamespaceLike | undefined;
1890
+ protected siblingStub(targetName: string): SiblingStub | undefined;
1789
1891
  protected postRelayMessage(targetName: string, message: OwnerRelayFrame): Promise<void>;
1790
1892
  protected requestRelayMessage(targetName: string, message: OwnerRelayFrame): Promise<Response | undefined>;
1791
1893
  abstract forwardWhisper(topic: string, frame: string): Promise<void>;
@@ -1826,6 +1928,7 @@ declare class OwnerRelay extends RelayLink {
1826
1928
  protected onWhisperFrame(message: RelayFrame): Promise<void>;
1827
1929
  protected onShapeSubscribe(message: RelayShapeSubscribe): RelayShapeSeed;
1828
1930
  protected onShapePoke(): number;
1931
+ private buildShapePoke;
1829
1932
  private multicastShapePokes;
1830
1933
  private proxyShapePokes;
1831
1934
  private buildShapeSeedFrames;
@@ -1859,6 +1962,61 @@ declare class RelayMember extends RelayLink {
1859
1962
  private deliverShapePoke;
1860
1963
  }
1861
1964
  declare const createRelayLink: (host: RelayHost) => OwnerRelay | RelayMember | undefined;
1965
+ declare const REGION_HINTS: readonly ["wnam", "enam", "sam", "weur", "eeur", "apac", "apac-ne", "apac-se", "oc", "afr", "me"];
1966
+ type RegionHint = (typeof REGION_HINTS)[number];
1967
+ type ReplicaReadiness = "fresh" | "stale" | "unavailable";
1968
+ interface ShardSiblingHost {
1969
+ doName: () => string | undefined;
1970
+ env: () => unknown;
1971
+ shardBinding: () => string | undefined;
1972
+ sql: () => SqlExec;
1973
+ }
1974
+ interface ReplicaOwnerHost extends ShardSiblingHost {
1975
+ exportRows: () => Promise<ExportRow[]>;
1976
+ ownerCursor: () => number | undefined;
1977
+ ownerEpoch: () => string | undefined;
1978
+ ownerFloor: () => number | undefined;
1979
+ readChanges: (sinceSeq: number, limit: number) => {
1980
+ changes: CdcChange[];
1981
+ cursor: number;
1982
+ };
1983
+ rowCount: () => number;
1984
+ }
1985
+ interface ReplicaFollowerHost extends ShardSiblingHost {
1986
+ applyChanges: (changes: ReadonlyArray<CdcChange>) => Promise<number>;
1987
+ importRows: (rows: ReadonlyArray<ExportRow>) => Promise<{
1988
+ errors: ReadonlyArray<unknown>;
1989
+ }>;
1990
+ }
1991
+ declare const handleReplicaControl: (host: ReplicaOwnerHost, request: Request) => Promise<Response>;
1992
+ declare class ShardReplica {
1993
+ private readonly host;
1994
+ readonly ownerKey: string;
1995
+ readonly region: RegionHint;
1996
+ private divergent;
1997
+ private inFlight;
1998
+ constructor(host: ReplicaFollowerHost, ownerKey: string, region: RegionHint);
1999
+ ensureFresh(minSeq?: number): Promise<ReplicaReadiness>;
2000
+ appliedSeq(): number;
2001
+ isDivergent(): boolean;
2002
+ private advance;
2003
+ private isCaughtUp;
2004
+ private catchUp;
2005
+ private applyPage;
2006
+ private hasDiverged;
2007
+ private bootstrap;
2008
+ private isFreshEnough;
2009
+ private pull;
2010
+ private request;
2011
+ }
2012
+ declare const createReplicaLink: (host: ReplicaFollowerHost) => ShardReplica | undefined;
2013
+ declare const gateReplicaDispatch: (replica: ShardReplica, request: Request, functionPath: string) => Promise<Response | undefined>;
2014
+ declare const REPROJECTION_MIGRATION_PREFIX = "__lunora_reproject__";
2015
+ declare const reprojectionMigrationId: (table: string) => string;
2016
+ declare const reprojectableFields: (definition: TableDefinitionLike) => string[];
2017
+ declare const reprojectionTables: (schema: SchemaLike) => string[];
2018
+ declare const countLegacyRows: (sql: SqlExec, table: string, fields: ReadonlyArray<string>) => number;
2019
+ declare const buildReprojectionMigration: (id: string, schema: SchemaLike, sql: SqlExec) => DataMigrationLike | undefined;
1862
2020
  declare const RLS_UNWRAP_SYMBOL: symbol;
1863
2021
  declare class RlsRequiredError extends LunoraError {
1864
2022
  readonly table: string;
@@ -1874,7 +2032,8 @@ interface GuardableSchema {
1874
2032
  }>;
1875
2033
  }
1876
2034
  type TableOfId = (id: string, expectedTable?: string) => Promise<string | undefined> | string | undefined;
1877
- declare const guardWriter: <W>(raw: W, schema: GuardableSchema, tableOfId: TableOfId) => W;
2035
+ type TablesOfIds = (ids: ReadonlyArray<string>, expectedTable?: string) => Promise<ReadonlyMap<string, string>> | ReadonlyMap<string, string>;
2036
+ declare const guardWriter: <W>(raw: W, schema: GuardableSchema, tableOfId: TableOfId, tablesOfIds?: TablesOfIds) => W;
1878
2037
  declare const SCHEMA_HISTORY_MAX_VERSIONS = 50;
1879
2038
  interface SchemaVersionRow {
1880
2039
  appliedAt: number;
@@ -1936,7 +2095,17 @@ interface DrainableSink {
1936
2095
  readonly bufferedAmount?: unknown;
1937
2096
  }
1938
2097
  declare const trySendFrame: (ws: FrameSink, frame: string) => boolean;
1939
- declare const sendDeltaFrames: (ws: FrameSink, subId: string, deltaFrames: ReadonlyArray<string>, cursorSuffix: string) => boolean;
2098
+ interface SubscriptionFrameInput {
2099
+ cursorSuffix: string;
2100
+ lastMutationId?: number;
2101
+ nextResult: unknown;
2102
+ pageDeltas?: boolean;
2103
+ previousJson?: string;
2104
+ snapshotJson: string;
2105
+ subId: string;
2106
+ table: string;
2107
+ }
2108
+ declare const subscriptionFrames: (input: SubscriptionFrameInput) => string[];
1940
2109
  declare const awaitWsDrain: (ws: DrainableSink) => Promise<void>;
1941
2110
  interface SubscriptionReadFootprint {
1942
2111
  ranges?: Map<string, KeyRange[]>;
@@ -1967,10 +2136,12 @@ declare const selectExpiredIds: (sql: SqlExec, spec: TtlSweepSpec, now: number,
1967
2136
  type FieldRefSql = (field: string) => SQL;
1968
2137
  type SerializeValue = (value: unknown) => unknown;
1969
2138
  interface WhereSqlStrategy {
2139
+ containsExpr?: (reference: SQL, term: SQL) => SQL;
1970
2140
  fieldRef: FieldRefSql;
1971
- likeContains?: (reference: SQL, term: SQL) => SQL;
2141
+ inList?: (reference: SQL, items: ReadonlyArray<unknown>, negated: boolean, budget?: number) => SQL;
1972
2142
  relationExists?: (request: unknown) => SQL;
1973
2143
  serialize: SerializeValue;
1974
2144
  }
2145
+ declare const literalInList: (reference: SQL, items: ReadonlyArray<unknown>, negated: boolean) => SQL;
1975
2146
  declare const compileWhereSql: (where: WhereInput | undefined, strategy: WhereSqlStrategy) => SQL | undefined;
1976
- export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, AGGREGATE_SQL_FUNCTION, AGG_COUNT, AGG_KEY, AGG_VALUE, AUDIT_LOG_TABLE, type AdvisorProcedure, type AdvisorProceduresResult, type AdvisoriesResult, type AdvisoryFinding, type AggregateIndexDefinitionLike, type AggregateOp, type AggregateOptions, type AggregateResult, type AggregateTally, type AppendAuditEntry, type ApplyOnDeleteOptions$1 as ApplyOnDeleteOptions, type AuditEntry, type AuditLogResult, type BroadcastDelta, CDC_LOG_TABLE, CDC_META_TABLE, CLIENT_WATERMARK_TABLE, type CacheEntry, type CapturedMailRow, type CdcChange, type ChangedKeys, type Clock, type ColumnMeta, type ColumnMetaLike, type CompanionSync, type CompanionSyncDeps, ConflictError, type ConflictKind, type CountArgs, CountRlsUnsupportedError, type CreateWorkflowInstanceResult, type CtxDbOptions, DATA_MIGRATION_STATE_TABLE, DEFAULT_FANOUT_TOPIC_LIMIT, DEFAULT_MAX_RELATION_KEYS, DEFAULT_MAX_RELAYS, DEFAULT_PROMOTION_THRESHOLDS, DEFAULT_TRANSACTION_LIMITS, DOC_COLUMN, type DataMigrationDocument, type DataMigrationLike, type DataMigrationTransform, type DatabaseWriterLike, type DependencyTracker, type DeployInfo, type ExportRow, type ExportShardAdminArgs, type ExportShardArgs, type ExternalSourceDiffResult, type ExternalSourceLike, FLAGS_FUNCTION_PREFIX, type FacetColumnOptions, type FacetColumnResult, type FacetValue, type FanoutMetricsResult, type FanoutPathCounters, type FanoutTopicStat, type FieldOperators, type FilterClause, type FilterOperator, type FlagEvaluation, type FlagsResult, type FunctionCallStat, type FunctionScanAttribution, type FunctionStatsResult, GEO_DEFAULT_PRECISION, GLOBAL_SHAPE_SNAPSHOT_TABLE, type GeoBoundingBox, type GeoFilterBuilderLike, type GeoIndexDefinitionLike, type GeoPoint, type GroupByEntry, type GroupByOptions, type GuardableSchema$1 as GuardableSchema, IDEMPOTENCY_TABLE, type IdGenerator, type IdempotentRecord, type ImportError, type ImportShardAdminArgs, type ImportShardArgs, type ImportShardResult, type IncrementalMaterializeResult, type IndexDefinitionLike, type IndexKeyEntry, type IndexRangeBuilderLike, type KeyRange, type LifecycleDispatchInfo, type LifecycleEvent, MAIL_RETENTION, MAIL_TABLE, MAX_PAGE_SIZE, MAX_SQL_ROWS, type MaskColumnMetadata, type MaskPoliciesResult, type MaterializeResult, type MigrationDirection, type MigrationRunResult, type MigrationStatus, type MigrationStatusRow, type MutationDelta, type NestedWith, NotFoundError, NotUniqueError, type OnDeleteActionLike, type OrderByClause, type OrderByInput, type OrderKey, OwnerRelay, type OwnerRelayFrame, type PaginationOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type PokeFrameMeta, type PromotionState, type PromotionThresholds, QUEUE_TABLE, type QueryArgs, type QueryPage, type QueueMessageOutcome, type QueueMessageRow, type QueueMetadata, type QueuesResult, RANK_TIEBREAK, RELATION_EXISTS_KEY, RELATION_FUNCTION_PREFIX, RLS_UNWRAP_SYMBOL, type RankBeforeOptions, type RankBeforeResult, type RankDirection, type RankIndexDefinitionLike, type RankOptions, type RankPage, type RankPageComputation, type RankPageDeps, type RankPageOptions, type RankPageRow, type RankPageRowKey, type RankResult, type RankSortKeyLike, ReactiveCache, type ReactiveCacheOptions, type ReadFootprint, type ReadHook, type ReadTablePageOptions, type RecordMailInput, type RecordQueueMessageInput, type RelationDefinitionLike, type RelationExistsMarker, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayShapePoke, type RelayShapeSeed, type RelayShapeSubscribe, type RenderedSql, type ResolveRelationPredicatesOptions, type ResolveWithOptions, type ResolveWithResult, type ResolvedShape, type RestrictableQueryOptions, type RlsPoliciesResult, type RlsPolicyMetadata, RlsRequiredError, type RlsRoleMetadata, type RpcRequest, type RunDataMigrationOptions, type RunTriggersOptions, SCAN_DEP, SCHEMA_HISTORY_MAX_VERSIONS, SEARCH_STATE_TABLE, type SchedulableWorkflowReferenceLike, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type SearchFilterBuilderLike, type SearchIndexDefinitionLike, type SelectMatchingIdsOptions, type ServerDefaultContextLike, type SettingEntry, type SettingKind, type SettingsResult, type ShapePokePart, type ShapeRow, type ShapeRowOp, type ShapeSubscriptionQuery, type ShardRankPageResult, ShardRunner, type ShardRunnerOptions, type ShardSocketLike, type SocketAttachment, type SortDirection, type SourceClientLike, type SourceCursorLike, type SourceRefresh, type SqlConsoleResult, type SqlCursor, type SqlEngine, type SqlExec, type SqlLintResult, type StorageMetadata, type StorageReference, type StorageReferenceResult, type StorageRuleMetadata, type StorageRulesResult, type StudioFeaturesResult, type SubscriptionConnection, type SubscriptionEnvelope, type SubscriptionIdentity, type SubscriptionInfo, type SubscriptionQuery, type SubscriptionReadFootprint, type SubscriptionsResult, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemReaderOptions, type SystemReaderSchedulerLike, type SystemReaderStorageLike, type SystemTableName, type TableColumnsResult, type TableDefinitionLike, type TableIndexInfo, type TableIndexesResult, type TableInfo, type TablePage, type TableReaderLike, type TablesColumnsResult, type TransactionHeadroom, TransactionHeadroomTracker, type TransactionLimits, type TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, type TtlSweepSpec, type ValidatorLike, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowInstanceState, type WorkflowInstanceStatusResult, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, advanceClientWatermark, aggUpsertSql, aggregateSqlFunction, aggregateTableName, appendAuditEntry, appendCdcChange, applyCdcChanges, applyOnDelete, applySelect, armRestore, assertFlatPredicate, assertReadonly, assertShapeShardable, assertValidClientId, awaitWsDrain, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, backfillSearchIndexesForTable, boundingBoxCenter, boundingBoxGeohashes, buildIndexRange, buildPokeFrames, buildSeekBeforeWhere, buildSeekWhere, buildSettings, bumpCdcEpoch, clampPromotionThresholds, clearCapturedMail, clearQueueMessages, coerceAggregateNumber, compileWhereSql, computeRankPage, containsRelationPredicate, coveringGeohashes, createCompanionSync, createDependencyTracker, createFanoutCounters, createIndexSql, createReadFootprint, createRelayLink, createShardCtxDb, createSystemReader, decodeCursor, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, depKey, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, exportShardRows, exportShardTable, facetColumn, fanOutScalarCounts, findStorageReferences, foldAggregateTally, geoTableName, guardWriter, hasTrigger, haversineMeters, hydrateDocsById, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, isLossyBody, isRelationPredicate, isSoftDeleted, isSourceDue, jsonPath, jsonPathSql, keysTouchRanges, liftSourceId, lintReadonlySql, listTables, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, mergeChangedKeys, mergeWhere, migrateCdcLog, migrateCdcMeta, migrateClientWatermark, migrateGlobalShapeSnapshot, migrateIdempotency, migrateSearchState, minCdcSeq, nextPromotionState, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, normalizeSourceDocument, normalizeSourceValue, param, parseExportShardArgs, parseImportShardArgs, planAggregateLookup, pointInBoundingBox, projectColumns, pullExternalSourceIncrementalTick, pullExternalSourceTick, qualifiedJsonPath, qualifiedJsonPathSql, quoteIdentifier, rankKeyFromDocument as rankKeyFromDoc, rankTableName, reactiveCacheKey, readAggregateValue, readAuditLog, readBookmark, readCapturedMail, readCdcChanges, readCdcCursor, readCdcEpoch, readClientWatermark, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readMigrationStatus, readQueueMessageById, readQueueMessages, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordQueueMessages, recordSchemaVersion, relayCountFor, renderSql, resolveRankPartition, resolveRelationPredicates, resolveWith, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMemberIds, selectShapeRows, sendDeltaFrames, serializeSqlValue, shapeRoutingKey, softDeleteScope, sortColumnName, stableStringify, stableWireKey, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, trimCdcChanges, trimIdempotent, tryRowToDocument, trySendFrame, validateImportRow, writeGlobalShapeSnapshot, writeIdempotent, writeSearchBackfillState, writeTouchesMemo };
2147
+ export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, AGGREGATE_SQL_FUNCTION, AGG_COUNT, AGG_KEY, AGG_VALUE, AUDIT_LOG_TABLE, type AdvisorProcedure, type AdvisorProceduresResult, type AdvisoriesResult, type AdvisoryFinding, type AggregateIndexDefinitionLike, type AggregateOp, type AggregateOptions, type AggregateResult, type AggregateTally, type AppendAuditEntry, type ApplyOnDeleteOptions$1 as ApplyOnDeleteOptions, type AuditEntry, type AuditLogResult, type BroadcastDelta, CDC_LOG_TABLE, CDC_META_TABLE, CLIENT_WATERMARK_TABLE, type CacheEntry, type CapturedMailRow, type CdcChange, type ChangedKeys, type Clock, type ColumnMeta, type ColumnMetaLike, type CompanionSync, type CompanionSyncDeps, ConflictError, type ConflictKind, type CountArgs, CountRlsUnsupportedError, type CreateWorkflowInstanceResult, type CrossShardReadArgs, type CtxDbOptions, DATA_MIGRATION_STATE_TABLE, DEFAULT_FANOUT_TOPIC_LIMIT, DEFAULT_MAX_RELATION_KEYS, DEFAULT_MAX_RELAYS, DEFAULT_PROMOTION_THRESHOLDS, DEFAULT_TRANSACTION_LIMITS, DOC_COLUMN, type DataMigrationDocument, type DataMigrationLike, type DataMigrationTransform, type DatabaseWriterLike, type DependencyTracker, type DeployInfo, type DurableAttachDecision, type DurableStreamAttach, type DurableStreamRun, DurableStreamRunner, type DurableStreamSink, type ExportRow, type ExportShardAdminArgs, type ExportShardArgs, type ExternalSourceDiffResult, type ExternalSourceLike, FLAGS_FUNCTION_PREFIX, type FacetColumnOptions, type FacetColumnResult, type FacetValue, type FanoutMetricsResult, type FanoutPathCounters, type FanoutTopicStat, type FieldOperators, type FilterClause, type FilterOperator, type FlagEvaluation, type FlagsResult, type FunctionCallStat, type FunctionScanAttribution, type FunctionStatsResult, GEO_DEFAULT_PRECISION, GLOBAL_SHAPE_SNAPSHOT_TABLE, type GeoBoundingBox, type GeoFilterBuilderLike, type GeoIndexDefinitionLike, type GeoPoint, type GeoScoredDocument, type GroupByEntry, type GroupByOptions, type GuardableSchema$1 as GuardableSchema, IDEMPOTENCY_TABLE, type IdGenerator, type IdempotentRecord, type ImportError, type ImportShardAdminArgs, type ImportShardArgs, type ImportShardResult, type IncrementalMaterializeResult, type IndexDefinitionLike, type IndexKeyEntry, type IndexRangeBuilderLike, type KeyRange, type LifecycleDispatchInfo, type LifecycleEvent, MAIL_RETENTION, MAIL_TABLE, MAX_DURABLE_STREAM_BYTES, MAX_DURABLE_STREAM_CHUNKS, MAX_PAGE_SIZE, MAX_SQL_ROWS, type MaskColumnMetadata, type MaskPoliciesResult, type MaterializeResult, type MigrationDirection, type MigrationRunResult, type MigrationStatus, type MigrationStatusRow, type MutationDelta, type NestedWith, NotFoundError, NotUniqueError, type OnDeleteActionLike, type OrderByClause, type OrderByInput, type OrderKey, OwnerRelay, type OwnerRelayFrame, type PaginationOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type PokeFrameMeta, type PromotionState, type PromotionThresholds, QUEUE_TABLE, type QueryArgs, type QueryPage, type QueueMessageOutcome, type QueueMessageRow, type QueueMetadata, type QueuesResult, RANK_TIEBREAK, RELATION_EXISTS_KEY, RELATION_FUNCTION_PREFIX, REPROJECTION_MIGRATION_PREFIX, RLS_UNWRAP_SYMBOL, type RankBeforeOptions, type RankBeforeResult, type RankDirection, type RankIndexDefinitionLike, type RankOptions, type RankPage, type RankPageComputation, type RankPageDeps, type RankPageOptions, type RankPageRow, type RankPageRowKey, type RankResult, type RankSortKeyLike, ReactiveCache, type ReactiveCacheOptions, type ReadFootprint, type ReadHook, type ReadTablePageOptions, type RecordMailInput, type RecordQueueMessageInput, type RelationDefinitionLike, type RelationExistsMarker, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayShapePoke, type RelayShapeSeed, type RelayShapeSubscribe, type RenderedSql, type ReplicaFollowerHost, type ReplicaOwnerHost, type ReplicaReadiness, type ResolveRelationPredicatesOptions, type ResolveWithOptions, type ResolveWithResult, type ResolvedShape, type RestrictableQueryOptions, type RlsPoliciesResult, type RlsPolicyMetadata, RlsRequiredError, type RlsRoleMetadata, type RpcRequest, type RunDataMigrationOptions, type RunTriggersOptions, SCAN_DEP, SCHEMA_HISTORY_MAX_VERSIONS, SEARCH_STATE_TABLE, SHAPE_POKE_CURSOR_TABLE, type SchedulableWorkflowReferenceLike, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type ScoredDocument, type SearchFilterBuilderLike, type SearchIndexDefinitionLike, type SearchScoredDocument, type SelectMatchingIdsOptions, type ServerDefaultContextLike, type SettingEntry, type SettingKind, type SettingsResult, type ShapePokePart, type ShapeRow, type ShapeRowOp, type ShapeSubscriptionQuery, type ShardRankPageResult, ShardRunner, type ShardRunnerOptions, type ShardSiblingHost, type ShardSocketLike, type SocketAttachment, type SortDirection, type SourceClientLike, type SourceCursorLike, type SourceRefresh, type SqlConsoleResult, type SqlCursor, type SqlEngine, type SqlExec, type SqlLintResult, type StorageMetadata, type StorageReference, type StorageReferenceResult, type StorageRuleMetadata, type StorageRulesResult, type StudioFeaturesResult, type SubscriptionConnection, type SubscriptionEnvelope, type SubscriptionIdentity, type SubscriptionInfo, type SubscriptionQuery, type SubscriptionReadFootprint, type SubscriptionsResult, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemReaderOptions, type SystemReaderSchedulerLike, type SystemReaderStorageLike, type SystemTableName, type TableColumnsResult, type TableDefinitionLike, type TableIndexInfo, type TableIndexesResult, type TableInfo, type TablePage, type TableReaderLike, type TablesColumnsResult, type TablesIndexesResult, type TransactionHeadroom, TransactionHeadroomTracker, type TransactionLimits, type TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, type TtlSweepSpec, type ValidatorLike, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowInstanceState, type WorkflowInstanceStatusResult, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, advanceClientWatermark, aggUpsertSql, aggregateSqlFunction, aggregateTableName, appendAuditEntry, appendCdcChange, appendStreamChunk, applyCdcChanges, applyOnDelete, applySelect, armRestore, assertFlatPredicate, assertReadonly, assertShapeShardable, assertValidClientId, awaitWsDrain, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, backfillSearchIndexesForTable, boundingBoxCenter, boundingBoxGeohashes, buildIndexRange, buildPokeFrames, buildReprojectionMigration, buildSeekBeforeWhere, buildSeekWhere, buildSettings, bumpCdcEpoch, claimStreamRun, clampPromotionThresholds, clearCapturedMail, clearQueueMessages, coerceAggregateNumber, compileWhereSql, computeRankPage, containsRelationPredicate, countLegacyRows, coveringGeohashes, createCompanionSync, createDependencyTracker, createFanoutCounters, createIndexSql, createReadFootprint, createRelayLink, createReplicaLink, createShardCtxDb, createSystemReader, decideDurableAttach, decodeCursor, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, deleteShapePokeCursor, deleteShapePokeCursorsForConnection, deleteStreamRun, depKey, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, exportShardRows, exportShardTable, facetColumn, fanOutScalarCounts, findStorageReferences, finishStreamRun, foldAggregateTally, gateReplicaDispatch, geoTableName, guardWriter, handleReplicaControl, hasTrigger, haversineMeters, hydrateDocsById, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, isLossyBody, isRelationPredicate, isSoftDeleted, isSourceDue, jsonPath, jsonPathSql, keysTouchRanges, liftSourceId, lintReadonlySql, listTables, literalInList, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, mergeChangedKeys, mergeWhere, migrateCdcLog, migrateCdcMeta, migrateClientWatermark, migrateDurableStreams, migrateGlobalShapeSnapshot, migrateIdempotency, migrateSearchState, migrateShapePokeCursor, minCdcSeq, nextPromotionState, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, normalizeSourceDocument, normalizeSourceValue, param, parseExportShardArgs, parseImportShardArgs, planAggregateLookup, pointInBoundingBox, projectColumns, pullExternalSourceIncrementalTick, pullExternalSourceTick, qualifiedJsonPath, qualifiedJsonPathSql, quoteIdentifier, rankKeyFromDocument as rankKeyFromDoc, rankTableName, reactiveCacheKey, readAggregateValue, readAuditLog, readBookmark, readCapturedMail, readCdcChanges, readCdcCursor, readCdcEpoch, readClientWatermark, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readMigrationStatus, readQueueMessageById, readQueueMessages, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readShapePokeCursor, readStreamChunks, readStreamRun, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordQueueMessages, recordSchemaVersion, relationHooks, relayCountFor, renderSql, reprojectableFields, reprojectionMigrationId, reprojectionTables, resolveRankPartition, resolveRelationPredicates, resolveWith, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMemberIds, selectShapeRows, serializeSqlValue, shapeRoutingKey, softDeleteScope, sortColumnName, sqliteInList, stableStringify, stableWireKey, subscriptionFrames, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, trimCdcChanges, trimIdempotent, trimStreamRuns, tryRowToDocument, trySendFrame, unionAll, validateImportRow, writeGlobalShapeSnapshot, writeIdempotent, writeSearchBackfillState, writeShapePokeCursor, writeTouchesMemo };
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{exportShardRows as o,exportShardTable as a,importShardRows as t,parseExportShardArgs as n,parseImportShardArgs as l,selectExportTables as i,validateImportRow as s}from"./packem_shared/exportShardRows-kt42wijd.mjs";import{AGGREGATE_SQL_FUNCTION as d,aggregateSqlFunction as p,matchesStaticWhere as c,normalizeCountArgument as S,throwingScheduler as u}from"./packem_shared/AGGREGATE_SQL_FUNCTION-QYaiuty4.mjs";import{aggregateTableName as f,coerceAggregateNumber as T,encodeAggregateKey as g,foldAggregateTally as h,readAggregateValue as A}from"./packem_shared/aggregateTableName-G-eXyjcz.mjs";import{CountRlsUnsupportedError as C,mergeWhere as I,planAggregateLookup as _,selectIndexForAggregate as R,selectIndexForCount as L,selectIndexForGroupBy as b}from"./packem_shared/CountRlsUnsupportedError-B2WKJD9v.mjs";import{AUDIT_LOG_TABLE as N,appendAuditEntry as M,ensureAuditTable as F,readAuditLog as O}from"./packem_shared/AUDIT_LOG_TABLE-CaA0jL0L.mjs";import{NotUniqueError as P,assertValidClientId as k,createShardCtxDb as B,normalizeIdStructurally as G}from"./packem_shared/NotUniqueError-iGKd9wRR.mjs";import{backfillAggregateIndexes as w,backfillRankIndexes as K,backfillSearchIndexes as q,backfillSearchIndexesForTable as W}from"./packem_shared/backfillAggregateIndexes-BHiewuB-.mjs";import{CDC_LOG_TABLE as z,CDC_META_TABLE as V,appendCdcChange as H,applyCdcChanges as X,bumpCdcEpoch as Q,migrateCdcLog as Y,migrateCdcMeta as j,minCdcSeq as J,readCdcChanges as Z,readCdcCursor as $,readCdcEpoch as ee,trimCdcChanges as re}from"./packem_shared/CDC_LOG_TABLE-BnqlH2eZ.mjs";import{CLIENT_WATERMARK_TABLE as ae,advanceClientWatermark as te,migrateClientWatermark as ne,readClientWatermark as le}from"./packem_shared/CLIENT_WATERMARK_TABLE-CXsSLU8D.mjs";import{createCompanionSync as se}from"./packem_shared/createCompanionSync-DWK0Vlg1.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as de,deleteGlobalShapeSnapshot as pe,deleteGlobalShapeSnapshotsForConnection as ce,migrateGlobalShapeSnapshot as Se,readGlobalShapeSnapshot as ue,writeGlobalShapeSnapshot as xe}from"./packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-DX-6-gBP.mjs";import{IDEMPOTENCY_TABLE as Te,migrateIdempotency as ge,readIdempotent as he,trimIdempotent as Ae,writeIdempotent as Ee}from"./packem_shared/IDEMPOTENCY_TABLE-DjkEMp6w.mjs";import{computeRankPage as Ie,hydrateDocsById as _e}from"./packem_shared/computeRankPage-IUSS-zIB.mjs";import{SEARCH_STATE_TABLE as Le,migrateSearchState as be,readSearchBackfillState as ye,writeSearchBackfillState as Ne}from"./packem_shared/SEARCH_STATE_TABLE-eLN8U5tz.mjs";import{selectShapeMemberIds as Fe,selectShapeRows as Oe}from"./packem_shared/selectShapeMemberIds-DvE7K6zG.mjs";import{DATA_MIGRATION_STATE_TABLE as Pe,readMigrationStatus as ke,runDataMigration as Be}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-CaO6L0Ee.mjs";import{SCAN_DEP as Ue,createDependencyTracker as we,depKey as Ke,tableFromDepKey as qe}from"./packem_shared/SCAN_DEP-D_yR9EeV.mjs";import{runDrizzle as ve,runSql as ze}from"./packem_shared/runDrizzle-GKR3y97k.mjs";import{AGG_COUNT as He,AGG_KEY as Xe,AGG_VALUE as Qe,DOC_COLUMN as Ye,aggUpsertSql as je,createIndexSql as Je,geoTableName as Ze,isFtsAvailable as $e,jsonPath as er,jsonPathSql as rr,qualifiedJsonPath as or,qualifiedJsonPathSql as ar,quoteIdentifier as tr,rowToDocument as nr,tableColumns as lr,tryRowToDocument as ir}from"./packem_shared/AGG_COUNT-BWXe3gtQ.mjs";import{param as mr,renderSql as dr}from"./packem_shared/param-B5lF5Jd9.mjs";import{diffExternalSource as cr}from"./packem_shared/diffExternalSource-DMpkJta1.mjs";import{liftSourceId as ur,normalizeSourceDocument as xr,normalizeSourceValue as fr}from"./packem_shared/liftSourceId-DApAbu7Q.mjs";import{materializeExternalRows as gr,materializeExternalRowsIncremental as hr,readExternalSourceBaseline as Ar,runExternalSourceTick as Er}from"./packem_shared/materializeExternalRows-DOQJV9p2.mjs";import{isSoftDeleted as Ir,isSourceDue as _r,pullExternalSourceIncrementalTick as Rr,pullExternalSourceTick as Lr}from"./packem_shared/isSoftDeleted-B-SXkGUo.mjs";import{GEO_DEFAULT_PRECISION as yr,boundingBoxCenter as Nr,boundingBoxGeohashes as Mr,coveringGeohashes as Fr,encodeGeohash as Or,haversineMeters as Dr,pointInBoundingBox as Pr}from"./packem_shared/GEO_DEFAULT_PRECISION-okRCkZ6r.mjs";import{ADMIN_FUNCTIONS as Br,ADMIN_FUNCTION_PREFIX as Gr,DEFAULT_FANOUT_TOPIC_LIMIT as Ur,FLAGS_FUNCTION_PREFIX as wr,MAX_PAGE_SIZE as Kr,RELATION_FUNCTION_PREFIX as qr,createFanoutCounters as Wr,facetColumn as vr,findStorageReferences as zr,listTables as Vr,readTablePage as Hr,recordFanoutPass as Xr,selectMatchingIds as Qr,summarizeFanoutTopics as Yr,summarizeSubscriptions as jr}from"./packem_shared/ADMIN_FUNCTIONS-B0xlQJ4w.mjs";import{MAIL_RETENTION as Zr,MAIL_TABLE as $r,clearCapturedMail as eo,ensureMailTable as ro,readCapturedMail as oo,recordCapturedMail as ao}from"./packem_shared/MAIL_RETENTION-KmozO2NQ.mjs";import{NotFoundError as no}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{armRestore as io,readBookmark as so}from"./packem_shared/armRestore-BNzdvQ_o.mjs";import{applySelect as po,buildSeekBeforeWhere as co,buildSeekWhere as So,decodeCursor as uo,encodeCursor as xo,normalizeOrderKeys as fo,softDeleteScope as To}from"./packem_shared/applySelect-B0CF8T7y.mjs";import{QUEUE_TABLE as ho,clearQueueMessages as Ao,isLossyBody as Eo,readQueueMessageById as Co,readQueueMessages as Io,recordQueueMessages as _o}from"./packem_shared/QUEUE_TABLE-DYCDvzTG.mjs";import{RANK_TIEBREAK as Lo,encodePartitionKey as bo,matchesRankStaticWhere as yo,rankKeyFromDoc as No,rankTableName as Mo,resolveRankPartition as Fo,sortColumnName as Oo}from"./packem_shared/RANK_TIEBREAK-9NU5s_mi.mjs";import{ReactiveCache as Po,reactiveCacheKey as ko}from"./packem_shared/ReactiveCache-CF21t8IB.mjs";import{createReadFootprint as Go}from"./packem_shared/createReadFootprint-DIrrxRTE.mjs";import{buildIndexRange as wo,indexKeysForRow as Ko,keysTouchRanges as qo}from"./packem_shared/buildIndexRange-DIjFVgeO.mjs";import{DEFAULT_MAX_RELATION_KEYS as vo,assertFlatPredicate as zo,assertShapeShardable as Vo,containsRelationPredicate as Ho,isRelationPredicate as Xo,resolveRelationPredicates as Qo}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-bq00btqV.mjs";import{applyOnDelete as jo,distinctValues as Jo,fanOutScalarCounts as Zo,resolveWith as $o,runRowValidators as ea}from"./packem_shared/applyOnDelete-uFRC5p1d.mjs";import{DEFAULT_PROMOTION_THRESHOLDS as oa,clampPromotionThresholds as aa,nextPromotionState as ta,relayCountFor as na,shapeRoutingKey as la}from"./packem_shared/DEFAULT_PROMOTION_THRESHOLDS-Dteg0sZF.mjs";import{DEFAULT_MAX_RELAYS as sa,OwnerRelay as ma,RelayMember as da,createRelayLink as pa}from"./packem_shared/DEFAULT_MAX_RELAYS-CnCyh6oX.mjs";import{RLS_UNWRAP_SYMBOL as Sa,RlsRequiredError as ua,guardWriter as xa}from"./packem_shared/RLS_UNWRAP_SYMBOL-C6_WX3dG.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as Ta,readSchemaHistory as ga,readSchemaVersion as ha,recordSchemaVersion as Aa}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-CHXz6p_z.mjs";import{serializeSqlValue as Ca}from"./packem_shared/serializeSqlValue-DnpyaLcw.mjs";import{buildSettings as _a,isDevEnvironment as Ra}from"./packem_shared/buildSettings-DT18_DkX.mjs";import{buildPokeFrames as ba,diffGlobalMembership as ya,encodeRowsPatch as Na,projectColumns as Ma}from"./packem_shared/buildPokeFrames-DaPpm5Ss.mjs";import{ShardRunner as Oa}from"./packem_shared/ShardRunner-DIqVdWtk.mjs";import{runSocketPool as Pa}from"./packem_shared/runSocketPool-DPQLVyWF.mjs";import{MAX_SQL_ROWS as Ba,assertReadonly as Ga,lintReadonlySql as Ua,runReadonlySql as wa}from"./packem_shared/MAX_SQL_ROWS-nMwkxv5f.mjs";import{awaitWsDrain as qa,sendDeltaFrames as Wa,subscriptionListDeltas as va,trySendFrame as za}from"./packem_shared/awaitWsDrain-Dk50ISgE.mjs";import{mergeChangedKeys as Ha,recordChangedKeys as Xa,writeTouchesMemo as Qa}from"./packem_shared/mergeChangedKeys-CvSHlkv-.mjs";import{createSystemReader as ja}from"./packem_shared/createSystemReader-DcDcrtM3.mjs";import{ConflictError as Za}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as et,TransactionHeadroomTracker as rt}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS--TtB8Gpo.mjs";import{hasTrigger as at,runTriggers as tt}from"./packem_shared/hasTrigger-CbkOHExZ.mjs";import{selectExpiredIds as lt}from"./packem_shared/selectExpiredIds-FzhIEeG1.mjs";import{compileWhereSql as st}from"./packem_shared/compileWhereSql-BLcfs4QW.mjs";import{RELATION_EXISTS_KEY as dt}from"./packem_shared/RELATION_EXISTS_KEY-BaqSIFU1.mjs";import{runShardMigrations as ct}from"./packem_shared/runShardMigrations-CPxqCh3O.mjs";import{stableStringify as ut}from"./packem_shared/stableStringify-BjLh4gvA.mjs";import{stableWireKey as ft}from"./packem_shared/stableWireKey-YEHLaX6X.mjs";export{Br as ADMIN_FUNCTIONS,Gr as ADMIN_FUNCTION_PREFIX,d as AGGREGATE_SQL_FUNCTION,He as AGG_COUNT,Xe as AGG_KEY,Qe as AGG_VALUE,N as AUDIT_LOG_TABLE,z as CDC_LOG_TABLE,V as CDC_META_TABLE,ae as CLIENT_WATERMARK_TABLE,Za as ConflictError,C as CountRlsUnsupportedError,Pe as DATA_MIGRATION_STATE_TABLE,Ur as DEFAULT_FANOUT_TOPIC_LIMIT,vo as DEFAULT_MAX_RELATION_KEYS,sa as DEFAULT_MAX_RELAYS,oa as DEFAULT_PROMOTION_THRESHOLDS,et as DEFAULT_TRANSACTION_LIMITS,Ye as DOC_COLUMN,wr as FLAGS_FUNCTION_PREFIX,yr as GEO_DEFAULT_PRECISION,de as GLOBAL_SHAPE_SNAPSHOT_TABLE,Te as IDEMPOTENCY_TABLE,Zr as MAIL_RETENTION,$r as MAIL_TABLE,Kr as MAX_PAGE_SIZE,Ba as MAX_SQL_ROWS,no as NotFoundError,P as NotUniqueError,ma as OwnerRelay,ho as QUEUE_TABLE,Lo as RANK_TIEBREAK,dt as RELATION_EXISTS_KEY,qr as RELATION_FUNCTION_PREFIX,Sa as RLS_UNWRAP_SYMBOL,Po as ReactiveCache,da as RelayMember,ua as RlsRequiredError,Ue as SCAN_DEP,Ta as SCHEMA_HISTORY_MAX_VERSIONS,Le as SEARCH_STATE_TABLE,Oa as ShardRunner,rt as TransactionHeadroomTracker,te as advanceClientWatermark,je as aggUpsertSql,p as aggregateSqlFunction,f as aggregateTableName,M as appendAuditEntry,H as appendCdcChange,X as applyCdcChanges,jo as applyOnDelete,po as applySelect,io as armRestore,zo as assertFlatPredicate,Ga as assertReadonly,Vo as assertShapeShardable,k as assertValidClientId,qa as awaitWsDrain,w as backfillAggregateIndexes,K as backfillRankIndexes,q as backfillSearchIndexes,W as backfillSearchIndexesForTable,Nr as boundingBoxCenter,Mr as boundingBoxGeohashes,wo as buildIndexRange,ba as buildPokeFrames,co as buildSeekBeforeWhere,So as buildSeekWhere,_a as buildSettings,Q as bumpCdcEpoch,aa as clampPromotionThresholds,eo as clearCapturedMail,Ao as clearQueueMessages,T as coerceAggregateNumber,st as compileWhereSql,Ie as computeRankPage,Ho as containsRelationPredicate,Fr as coveringGeohashes,se as createCompanionSync,we as createDependencyTracker,Wr as createFanoutCounters,Je as createIndexSql,Go as createReadFootprint,pa as createRelayLink,B as createShardCtxDb,ja as createSystemReader,uo as decodeCursor,pe as deleteGlobalShapeSnapshot,ce as deleteGlobalShapeSnapshotsForConnection,Ke as depKey,cr as diffExternalSource,ya as diffGlobalMembership,Jo as distinctValues,g as encodeAggregateKey,xo as encodeCursor,Or as encodeGeohash,bo as encodePartitionKey,Na as encodeRowsPatch,F as ensureAuditTable,ro as ensureMailTable,o as exportShardRows,a as exportShardTable,vr as facetColumn,Zo as fanOutScalarCounts,zr as findStorageReferences,h as foldAggregateTally,Ze as geoTableName,xa as guardWriter,at as hasTrigger,Dr as haversineMeters,_e as hydrateDocsById,t as importShardRows,Ko as indexKeysForRow,Ra as isDevEnvironment,$e as isFtsAvailable,Eo as isLossyBody,Xo as isRelationPredicate,Ir as isSoftDeleted,_r as isSourceDue,er as jsonPath,rr as jsonPathSql,qo as keysTouchRanges,ur as liftSourceId,Ua as lintReadonlySql,Vr as listTables,yo as matchesRankStaticWhere,c as matchesStaticWhere,gr as materializeExternalRows,hr as materializeExternalRowsIncremental,Ha as mergeChangedKeys,I as mergeWhere,Y as migrateCdcLog,j as migrateCdcMeta,ne as migrateClientWatermark,Se as migrateGlobalShapeSnapshot,ge as migrateIdempotency,be as migrateSearchState,J as minCdcSeq,ta as nextPromotionState,S as normalizeCountArgument,G as normalizeIdStructurally,fo as normalizeOrderKeys,xr as normalizeSourceDocument,fr as normalizeSourceValue,mr as param,n as parseExportShardArgs,l as parseImportShardArgs,_ as planAggregateLookup,Pr as pointInBoundingBox,Ma as projectColumns,Rr as pullExternalSourceIncrementalTick,Lr as pullExternalSourceTick,or as qualifiedJsonPath,ar as qualifiedJsonPathSql,tr as quoteIdentifier,No as rankKeyFromDoc,Mo as rankTableName,ko as reactiveCacheKey,A as readAggregateValue,O as readAuditLog,so as readBookmark,oo as readCapturedMail,Z as readCdcChanges,$ as readCdcCursor,ee as readCdcEpoch,le as readClientWatermark,Ar as readExternalSourceBaseline,ue as readGlobalShapeSnapshot,he as readIdempotent,ke as readMigrationStatus,Co as readQueueMessageById,Io as readQueueMessages,ga as readSchemaHistory,ha as readSchemaVersion,ye as readSearchBackfillState,Hr as readTablePage,ao as recordCapturedMail,Xa as recordChangedKeys,Xr as recordFanoutPass,_o as recordQueueMessages,Aa as recordSchemaVersion,na as relayCountFor,dr as renderSql,Fo as resolveRankPartition,Qo as resolveRelationPredicates,$o as resolveWith,nr as rowToDocument,Be as runDataMigration,ve as runDrizzle,Er as runExternalSourceTick,wa as runReadonlySql,ea as runRowValidators,ct as runShardMigrations,Pa as runSocketPool,ze as runSql,tt as runTriggers,lt as selectExpiredIds,i as selectExportTables,R as selectIndexForAggregate,L as selectIndexForCount,b as selectIndexForGroupBy,Qr as selectMatchingIds,Fe as selectShapeMemberIds,Oe as selectShapeRows,Wa as sendDeltaFrames,Ca as serializeSqlValue,la as shapeRoutingKey,To as softDeleteScope,Oo as sortColumnName,ut as stableStringify,ft as stableWireKey,va as subscriptionListDeltas,Yr as summarizeFanoutTopics,jr as summarizeSubscriptions,lr as tableColumns,qe as tableFromDepKey,u as throwingScheduler,re as trimCdcChanges,Ae as trimIdempotent,ir as tryRowToDocument,za as trySendFrame,s as validateImportRow,xe as writeGlobalShapeSnapshot,Ee as writeIdempotent,Ne as writeSearchBackfillState,Qa as writeTouchesMemo};
1
+ import{exportShardRows as o,exportShardTable as a,importShardRows as t,parseExportShardArgs as n,parseImportShardArgs as s,selectExportTables as i,validateImportRow as l}from"./packem_shared/exportShardRows-Cgt3ITwH.mjs";import{AGGREGATE_SQL_FUNCTION as p,aggregateSqlFunction as d,matchesStaticWhere as c,normalizeCountArgument as S,throwingScheduler as u}from"./packem_shared/AGGREGATE_SQL_FUNCTION-m1iUU1rv.mjs";import{aggregateTableName as f,coerceAggregateNumber as h,encodeAggregateKey as A,foldAggregateTally as E,readAggregateValue as T}from"./packem_shared/aggregateTableName-Cy5e03oz.mjs";import{CountRlsUnsupportedError as R,mergeWhere as C,planAggregateLookup as _,selectIndexForAggregate as I,selectIndexForCount as L,selectIndexForGroupBy as b}from"./packem_shared/CountRlsUnsupportedError-Bdfupt3g.mjs";import{AUDIT_LOG_TABLE as N,appendAuditEntry as y,ensureAuditTable as D,readAuditLog as O}from"./packem_shared/AUDIT_LOG_TABLE-uNVU9O1W.mjs";import{NotUniqueError as P,assertValidClientId as k,createShardCtxDb as B,normalizeIdStructurally as G}from"./packem_shared/NotUniqueError-BixDiv4O.mjs";import{backfillAggregateIndexes as w,backfillRankIndexes as K,backfillSearchIndexes as q,backfillSearchIndexesForTable as W}from"./packem_shared/backfillAggregateIndexes-DVQ2sVuV.mjs";import{CDC_LOG_TABLE as z,CDC_META_TABLE as H,appendCdcChange as X,applyCdcChanges as V,bumpCdcEpoch as j,migrateCdcLog as Y,migrateCdcMeta as Q,minCdcSeq as J,readCdcChanges as Z,readCdcCursor as $,readCdcEpoch as ee,trimCdcChanges as re}from"./packem_shared/CDC_LOG_TABLE-B58N8NQO.mjs";import{CLIENT_WATERMARK_TABLE as ae,advanceClientWatermark as te,migrateClientWatermark as ne,readClientWatermark as se}from"./packem_shared/CLIENT_WATERMARK_TABLE-BoS1HEqz.mjs";import{c as le}from"./packem_shared/ctx-db-companions-lTt-rvKG.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as pe,deleteGlobalShapeSnapshot as de,deleteGlobalShapeSnapshotsForConnection as ce,migrateGlobalShapeSnapshot as Se,readGlobalShapeSnapshot as ue,writeGlobalShapeSnapshot as xe}from"./packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-NWaL77m5.mjs";import{IDEMPOTENCY_TABLE as he,migrateIdempotency as Ae,readIdempotent as Ee,trimIdempotent as Te,writeIdempotent as ge}from"./packem_shared/IDEMPOTENCY_TABLE-DKVe2Ohf.mjs";import{computeRankPage as Ce,hydrateDocsById as _e}from"./packem_shared/computeRankPage-Bby1Npkd.mjs";import{SEARCH_STATE_TABLE as Le,migrateSearchState as be,readSearchBackfillState as Me,writeSearchBackfillState as Ne}from"./packem_shared/SEARCH_STATE_TABLE-Dju8ebbU.mjs";import{SHAPE_POKE_CURSOR_TABLE as De,deleteShapePokeCursor as Oe,deleteShapePokeCursorsForConnection as Fe,migrateShapePokeCursor as Pe,readShapePokeCursor as ke,writeShapePokeCursor as Be}from"./packem_shared/SHAPE_POKE_CURSOR_TABLE-Dh4HfSdC.mjs";import{selectShapeMemberIds as Ue,selectShapeRows as we}from"./packem_shared/selectShapeMemberIds-B-pQJHAu.mjs";import{DATA_MIGRATION_STATE_TABLE as qe,readMigrationStatus as We,runDataMigration as ve}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-4l6aU1Vc.mjs";import{SCAN_DEP as He,createDependencyTracker as Xe,depKey as Ve,tableFromDepKey as je}from"./packem_shared/SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as Qe,runSql as Je}from"./packem_shared/runDrizzle-it6rL9bR.mjs";import{A as $e,a as er,b as rr,D as or,c as ar,d as tr,g as nr,i as sr,j as ir,e as lr,q as mr,f as pr,r as dr,t as cr,h as Sr}from"./packem_shared/do-sql-Dk_DJxn4.mjs";import{param as xr,renderSql as fr,sqliteInList as hr,unionAll as Ar}from"./packem_shared/param-Ib8WHnrF.mjs";import{appendStreamChunk as Tr,claimStreamRun as gr,deleteStreamRun as Rr,finishStreamRun as Cr,migrateDurableStreams as _r,readStreamChunks as Ir,readStreamRun as Lr,trimStreamRuns as br}from"./packem_shared/appendStreamChunk-CH4e4nJn.mjs";import{DurableStreamRunner as Nr,MAX_DURABLE_STREAM_BYTES as yr,MAX_DURABLE_STREAM_CHUNKS as Dr,decideDurableAttach as Or}from"./packem_shared/DurableStreamRunner-Bm6KDMBU.mjs";import{diffExternalSource as Pr}from"./packem_shared/diffExternalSource-pozJ4UdZ.mjs";import{liftSourceId as Br,normalizeSourceDocument as Gr,normalizeSourceValue as Ur}from"./packem_shared/liftSourceId-CA3ENhXj.mjs";import{materializeExternalRows as Kr,materializeExternalRowsIncremental as qr,readExternalSourceBaseline as Wr,runExternalSourceTick as vr}from"./packem_shared/materializeExternalRows-Drn0FGdb.mjs";import{isSoftDeleted as Hr,isSourceDue as Xr,pullExternalSourceIncrementalTick as Vr,pullExternalSourceTick as jr}from"./packem_shared/isSoftDeleted-DcGB0pov.mjs";import{GEO_DEFAULT_PRECISION as Qr,boundingBoxCenter as Jr,boundingBoxGeohashes as Zr,coveringGeohashes as $r,encodeGeohash as eo,haversineMeters as ro,pointInBoundingBox as oo}from"./packem_shared/GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{ADMIN_FUNCTIONS as to,ADMIN_FUNCTION_PREFIX as no,DEFAULT_FANOUT_TOPIC_LIMIT as so,FLAGS_FUNCTION_PREFIX as io,MAX_PAGE_SIZE as lo,RELATION_FUNCTION_PREFIX as mo,createFanoutCounters as po,facetColumn as co,findStorageReferences as So,listTables as uo,readTablePage as xo,recordFanoutPass as fo,selectMatchingIds as ho,summarizeFanoutTopics as Ao,summarizeSubscriptions as Eo}from"./packem_shared/ADMIN_FUNCTIONS-Ddr79XHG.mjs";import{MAIL_RETENTION as go,MAIL_TABLE as Ro,clearCapturedMail as Co,ensureMailTable as _o,readCapturedMail as Io,recordCapturedMail as Lo}from"./packem_shared/MAIL_RETENTION-Cig9Dmc8.mjs";import{NotFoundError as Mo}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{armRestore as yo,readBookmark as Do}from"./packem_shared/armRestore-Bu1_8SUa.mjs";import{applySelect as Fo,buildSeekBeforeWhere as Po,buildSeekWhere as ko,decodeCursor as Bo,encodeCursor as Go,normalizeOrderKeys as Uo,softDeleteScope as wo}from"./packem_shared/applySelect-BQbHyo-W.mjs";import{QUEUE_TABLE as qo,clearQueueMessages as Wo,isLossyBody as vo,readQueueMessageById as zo,readQueueMessages as Ho,recordQueueMessages as Xo}from"./packem_shared/QUEUE_TABLE-zj9Tt6tk.mjs";import{RANK_TIEBREAK as jo,encodePartitionKey as Yo,matchesRankStaticWhere as Qo,rankKeyFromDoc as Jo,rankTableName as Zo,resolveRankPartition as $o,sortColumnName as ea}from"./packem_shared/RANK_TIEBREAK-ci3MaM65.mjs";import{ReactiveCache as oa,reactiveCacheKey as aa}from"./packem_shared/ReactiveCache-DfyeaJOA.mjs";import{createReadFootprint as na}from"./packem_shared/createReadFootprint-MRH1If3F.mjs";import{buildIndexRange as ia,indexKeysForRow as la,keysTouchRanges as ma}from"./packem_shared/buildIndexRange-CBKQmHSS.mjs";import{DEFAULT_MAX_RELATION_KEYS as da,assertFlatPredicate as ca,assertShapeShardable as Sa,containsRelationPredicate as ua,isRelationPredicate as xa,resolveRelationPredicates as fa}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-BAWGIEvC.mjs";import{applyOnDelete as Aa,distinctValues as Ea,fanOutScalarCounts as Ta,relationHooks as ga,resolveWith as Ra,runRowValidators as Ca}from"./packem_shared/applyOnDelete-BlcwKjuO.mjs";import{DEFAULT_PROMOTION_THRESHOLDS as Ia,clampPromotionThresholds as La,nextPromotionState as ba,relayCountFor as Ma,shapeRoutingKey as Na}from"./packem_shared/DEFAULT_PROMOTION_THRESHOLDS-DVTD9iu0.mjs";import{DEFAULT_MAX_RELAYS as Da,OwnerRelay as Oa,RelayMember as Fa,createRelayLink as Pa}from"./packem_shared/DEFAULT_MAX_RELAYS-DeVcEXBh.mjs";import{createReplicaLink as Ba,gateReplicaDispatch as Ga,handleReplicaControl as Ua}from"./packem_shared/createReplicaLink-C1JuP_DN.mjs";import{buildReprojectionMigration as Ka,countLegacyRows as qa,reprojectableFields as Wa,reprojectionTables as va}from"./packem_shared/buildReprojectionMigration-8nVn8Qwb.mjs";import{RLS_UNWRAP_SYMBOL as Ha,RlsRequiredError as Xa,guardWriter as Va}from"./packem_shared/RLS_UNWRAP_SYMBOL-BWloGsd3.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as Ya,readSchemaHistory as Qa,readSchemaVersion as Ja,recordSchemaVersion as Za}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-DsycDXWm.mjs";import{serializeSqlValue as et}from"./packem_shared/serializeSqlValue-DbI1VQYM.mjs";import{buildSettings as ot,isDevEnvironment as at}from"./packem_shared/buildSettings-B4igo4rJ.mjs";import{buildPokeFrames as nt,diffGlobalMembership as st,encodeRowsPatch as it,projectColumns as lt}from"./packem_shared/buildPokeFrames-BXejpiII.mjs";import{ShardRunner as pt}from"./packem_shared/ShardRunner-C9p5DVOx.mjs";import{runSocketPool as ct}from"./packem_shared/runSocketPool-CZJ2X9cF.mjs";import{MAX_SQL_ROWS as ut,assertReadonly as xt,lintReadonlySql as ft,runReadonlySql as ht}from"./packem_shared/MAX_SQL_ROWS-DnDyeZph.mjs";import{awaitWsDrain as Et,subscriptionFrames as Tt,subscriptionListDeltas as gt,trySendFrame as Rt}from"./packem_shared/awaitWsDrain-kSGvAfw1.mjs";import{mergeChangedKeys as _t,recordChangedKeys as It,writeTouchesMemo as Lt}from"./packem_shared/mergeChangedKeys-D1T-TPUb.mjs";import{createSystemReader as Mt}from"./packem_shared/createSystemReader-BtYeSMDb.mjs";import{ConflictError as yt}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as Ot,TransactionHeadroomTracker as Ft}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS-Bcoi7Bvf.mjs";import{hasTrigger as kt,runTriggers as Bt}from"./packem_shared/hasTrigger-CjlwI4le.mjs";import{selectExpiredIds as Ut}from"./packem_shared/selectExpiredIds-_5514W_v.mjs";import{compileWhereSql as Kt,literalInList as qt}from"./packem_shared/compileWhereSql-JBpSfQm9.mjs";import{RELATION_EXISTS_KEY as vt}from"./packem_shared/RELATION_EXISTS_KEY-CFUhnZSZ.mjs";import{REPROJECTION_MIGRATION_PREFIX as Ht,reprojectionMigrationId as Xt}from"./packem_shared/REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{quoteIdentifier as jt}from"./packem_shared/quoteIdentifier-CObIFRhb.mjs";import{runShardMigrations as Qt}from"./packem_shared/runShardMigrations-Crppyq1f.mjs";import{stableStringify as Zt}from"./packem_shared/stableStringify-CujpENIO.mjs";import{stableWireKey as en}from"./packem_shared/stableWireKey-BYB5GQJa.mjs";export{to as ADMIN_FUNCTIONS,no as ADMIN_FUNCTION_PREFIX,p as AGGREGATE_SQL_FUNCTION,$e as AGG_COUNT,er as AGG_KEY,rr as AGG_VALUE,N as AUDIT_LOG_TABLE,z as CDC_LOG_TABLE,H as CDC_META_TABLE,ae as CLIENT_WATERMARK_TABLE,yt as ConflictError,R as CountRlsUnsupportedError,qe as DATA_MIGRATION_STATE_TABLE,so as DEFAULT_FANOUT_TOPIC_LIMIT,da as DEFAULT_MAX_RELATION_KEYS,Da as DEFAULT_MAX_RELAYS,Ia as DEFAULT_PROMOTION_THRESHOLDS,Ot as DEFAULT_TRANSACTION_LIMITS,or as DOC_COLUMN,Nr as DurableStreamRunner,io as FLAGS_FUNCTION_PREFIX,Qr as GEO_DEFAULT_PRECISION,pe as GLOBAL_SHAPE_SNAPSHOT_TABLE,he as IDEMPOTENCY_TABLE,go as MAIL_RETENTION,Ro as MAIL_TABLE,yr as MAX_DURABLE_STREAM_BYTES,Dr as MAX_DURABLE_STREAM_CHUNKS,lo as MAX_PAGE_SIZE,ut as MAX_SQL_ROWS,Mo as NotFoundError,P as NotUniqueError,Oa as OwnerRelay,qo as QUEUE_TABLE,jo as RANK_TIEBREAK,vt as RELATION_EXISTS_KEY,mo as RELATION_FUNCTION_PREFIX,Ht as REPROJECTION_MIGRATION_PREFIX,Ha as RLS_UNWRAP_SYMBOL,oa as ReactiveCache,Fa as RelayMember,Xa as RlsRequiredError,He as SCAN_DEP,Ya as SCHEMA_HISTORY_MAX_VERSIONS,Le as SEARCH_STATE_TABLE,De as SHAPE_POKE_CURSOR_TABLE,pt as ShardRunner,Ft as TransactionHeadroomTracker,te as advanceClientWatermark,ar as aggUpsertSql,d as aggregateSqlFunction,f as aggregateTableName,y as appendAuditEntry,X as appendCdcChange,Tr as appendStreamChunk,V as applyCdcChanges,Aa as applyOnDelete,Fo as applySelect,yo as armRestore,ca as assertFlatPredicate,xt as assertReadonly,Sa as assertShapeShardable,k as assertValidClientId,Et as awaitWsDrain,w as backfillAggregateIndexes,K as backfillRankIndexes,q as backfillSearchIndexes,W as backfillSearchIndexesForTable,Jr as boundingBoxCenter,Zr as boundingBoxGeohashes,ia as buildIndexRange,nt as buildPokeFrames,Ka as buildReprojectionMigration,Po as buildSeekBeforeWhere,ko as buildSeekWhere,ot as buildSettings,j as bumpCdcEpoch,gr as claimStreamRun,La as clampPromotionThresholds,Co as clearCapturedMail,Wo as clearQueueMessages,h as coerceAggregateNumber,Kt as compileWhereSql,Ce as computeRankPage,ua as containsRelationPredicate,qa as countLegacyRows,$r as coveringGeohashes,le as createCompanionSync,Xe as createDependencyTracker,po as createFanoutCounters,tr as createIndexSql,na as createReadFootprint,Pa as createRelayLink,Ba as createReplicaLink,B as createShardCtxDb,Mt as createSystemReader,Or as decideDurableAttach,Bo as decodeCursor,de as deleteGlobalShapeSnapshot,ce as deleteGlobalShapeSnapshotsForConnection,Oe as deleteShapePokeCursor,Fe as deleteShapePokeCursorsForConnection,Rr as deleteStreamRun,Ve as depKey,Pr as diffExternalSource,st as diffGlobalMembership,Ea as distinctValues,A as encodeAggregateKey,Go as encodeCursor,eo as encodeGeohash,Yo as encodePartitionKey,it as encodeRowsPatch,D as ensureAuditTable,_o as ensureMailTable,o as exportShardRows,a as exportShardTable,co as facetColumn,Ta as fanOutScalarCounts,So as findStorageReferences,Cr as finishStreamRun,E as foldAggregateTally,Ga as gateReplicaDispatch,nr as geoTableName,Va as guardWriter,Ua as handleReplicaControl,kt as hasTrigger,ro as haversineMeters,_e as hydrateDocsById,t as importShardRows,la as indexKeysForRow,at as isDevEnvironment,sr as isFtsAvailable,vo as isLossyBody,xa as isRelationPredicate,Hr as isSoftDeleted,Xr as isSourceDue,ir as jsonPath,lr as jsonPathSql,ma as keysTouchRanges,Br as liftSourceId,ft as lintReadonlySql,uo as listTables,qt as literalInList,Qo as matchesRankStaticWhere,c as matchesStaticWhere,Kr as materializeExternalRows,qr as materializeExternalRowsIncremental,_t as mergeChangedKeys,C as mergeWhere,Y as migrateCdcLog,Q as migrateCdcMeta,ne as migrateClientWatermark,_r as migrateDurableStreams,Se as migrateGlobalShapeSnapshot,Ae as migrateIdempotency,be as migrateSearchState,Pe as migrateShapePokeCursor,J as minCdcSeq,ba as nextPromotionState,S as normalizeCountArgument,G as normalizeIdStructurally,Uo as normalizeOrderKeys,Gr as normalizeSourceDocument,Ur as normalizeSourceValue,xr as param,n as parseExportShardArgs,s as parseImportShardArgs,_ as planAggregateLookup,oo as pointInBoundingBox,lt as projectColumns,Vr as pullExternalSourceIncrementalTick,jr as pullExternalSourceTick,mr as qualifiedJsonPath,pr as qualifiedJsonPathSql,jt as quoteIdentifier,Jo as rankKeyFromDoc,Zo as rankTableName,aa as reactiveCacheKey,T as readAggregateValue,O as readAuditLog,Do as readBookmark,Io as readCapturedMail,Z as readCdcChanges,$ as readCdcCursor,ee as readCdcEpoch,se as readClientWatermark,Wr as readExternalSourceBaseline,ue as readGlobalShapeSnapshot,Ee as readIdempotent,We as readMigrationStatus,zo as readQueueMessageById,Ho as readQueueMessages,Qa as readSchemaHistory,Ja as readSchemaVersion,Me as readSearchBackfillState,ke as readShapePokeCursor,Ir as readStreamChunks,Lr as readStreamRun,xo as readTablePage,Lo as recordCapturedMail,It as recordChangedKeys,fo as recordFanoutPass,Xo as recordQueueMessages,Za as recordSchemaVersion,ga as relationHooks,Ma as relayCountFor,fr as renderSql,Wa as reprojectableFields,Xt as reprojectionMigrationId,va as reprojectionTables,$o as resolveRankPartition,fa as resolveRelationPredicates,Ra as resolveWith,dr as rowToDocument,ve as runDataMigration,Qe as runDrizzle,vr as runExternalSourceTick,ht as runReadonlySql,Ca as runRowValidators,Qt as runShardMigrations,ct as runSocketPool,Je as runSql,Bt as runTriggers,Ut as selectExpiredIds,i as selectExportTables,I as selectIndexForAggregate,L as selectIndexForCount,b as selectIndexForGroupBy,ho as selectMatchingIds,Ue as selectShapeMemberIds,we as selectShapeRows,et as serializeSqlValue,Na as shapeRoutingKey,wo as softDeleteScope,ea as sortColumnName,hr as sqliteInList,Zt as stableStringify,en as stableWireKey,Tt as subscriptionFrames,gt as subscriptionListDeltas,Ao as summarizeFanoutTopics,Eo as summarizeSubscriptions,cr as tableColumns,je as tableFromDepKey,u as throwingScheduler,re as trimCdcChanges,Te as trimIdempotent,br as trimStreamRuns,Sr as tryRowToDocument,Rt as trySendFrame,Ar as unionAll,l as validateImportRow,xe as writeGlobalShapeSnapshot,ge as writeIdempotent,Ne as writeSearchBackfillState,Be as writeShapePokeCursor,Lt as writeTouchesMemo};
@@ -0,0 +1 @@
1
+ import{LunoraError as v}from"@lunora/errors";import{m as L,n as O}from"./do-sql-Dk_DJxn4.mjs";import{quoteIdentifier as d}from"./quoteIdentifier-CObIFRhb.mjs";import{d as P}from"./wire-codec-BU9T2xJ7.mjs";const te="__lunora_admin__:",ne="__lunora_relation__:",re="__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",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",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__",k=e=>{try{const t=JSON.parse(e);return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:void 0}catch{return}},j=e=>{const{[O]:t,...n}=e;return t===void 0?n:t===null||typeof t!="object"||Array.isArray(t)?{[O]:t,...n}:{...n,...P(t)}},Q=(e,t)=>{if(!e.includes(m))return{columns:e,rows:t};const n=[];for(const s of t){const a=s[m],i=typeof a=="string"?k(a):void 0;if(i===void 0)return{columns:e,rows:t};const c=Object.fromEntries(Object.entries(s).filter(([u])=>u!==m));n.push({...c,...j(i)})}const r=e.filter(s=>s!==m),o=[],_=new Set(r);for(const s of n)for(const a of Object.keys(s))_.has(a)||(_.add(a),o.push(a));return{columns:[...r,...o],rows:n}},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,n)=>Math.min(Math.max(e,t),n),x=(e,t)=>{const n=e.exec(`SELECT COUNT(*) AS c FROM ${t}`).one();return Number(n.c)},oe=e=>{const t=e.exec("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name").toArray(),n=[];for(const{name:r}of t)I(r)||n.push({name:r,rowCount:x(e,d(r))});return n},N=(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)||!N(e,t))throw new v("UNKNOWN_TABLE",`unknown table: ${t}`,{status:404})},M=(e,t)=>e.exec(`PRAGMA table_info(${t})`).toArray().map(n=>n.name),q={eq:"=",gt:">",gte:">=",lt:"<",lte:"<=",ne:"<>"},H=e=>typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):"",S=(e,t)=>{const n=t.includes(e),r=t.includes(m);if(!(!n&&!r))return n?{expression:d(e),params:[]}:{expression:`json_extract(${d(m)}, ?)`,params:[`$.${L(e)}`]}},B=(e,t)=>{const n=S(e.column,t);if(n===void 0)return;const{expression:r,params:o}=n;return e.operator==="contains"?{params:[...o,H(e.value)],sql:F(r)}:{params:[...o,e.value],sql:`${r} ${q[e.operator]} ?`}},G=/^(\d{4})(?:-(\d{2}))?(?:-(\d{2}))?$/u,X=e=>{const t=G.exec(e.trim());if(t===null)return;const n=Number(t[1]),r=t[2]===void 0?void 0:Number(t[2]),o=t[3]===void 0?void 0:Number(t[3]);if(r!==void 0&&(r<1||r>12)||o!==void 0&&(o<1||o>31)||n<100)return;const _=Date.UTC(n,(r??1)-1,o??1);if(o!==void 0&&new Date(_).getUTCDate()!==o)return;let s;return o!==void 0?s=Date.UTC(n,(r??1)-1,o+1):r===void 0?s=Date.UTC(n+1,0,1):s=Date.UTC(n,r,1),{from:_,to:s}},A=(e,t,n)=>{const r=[],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);r.push(`(${_.join(" OR ")})`)}for(const _ of n??[]){const s=B(_,e);s!==void 0&&(r.push(`(${s.sql})`),o.push(...s.params))}return r.length===0?void 0:{parameters:o,where:r.join(" AND ")}},K=(e,t)=>{if(e===void 0)return;const n=S(e.column,t);if(n===void 0)return;const r=e.direction==="desc"?"DESC":"ASC";return{params:n.params,sql:`${n.expression} ${r}`}},ae=(e,t)=>{const{table:n}=t;C(e,n);const r=E(Math.trunc(t.limit??D),1,g),o=Math.max(0,Math.trunc(t.offset??0)),_=d(n),s=M(e,_),a=t.search?.trim()??"",i=b=>{if(t.refs===void 0)return b;const T={};for(const w of b.columns){const y=t.refs[w];y!==void 0&&(T[w]=y)}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 $=e.exec(`SELECT * FROM ${_}${l}${f} LIMIT ? OFFSET ?`,...p,...h,r,o).toArray();return i({...Q(s,$),total:R})},_e=(e,t)=>{const{table:n}=t;C(e,n);const r=E(Math.trunc(t.limit??g),1,g),o=d(n),_=M(e,o),s=t.search?.trim()??"",a=A(_,s,t.filters),i=a===void 0?e.exec(`SELECT id FROM ${o} LIMIT ?`,r+1).toArray():e.exec(`SELECT id FROM ${o} WHERE ${a.where} LIMIT ?`,...a.parameters,r+1).toArray(),c=i.length>r,u=i.slice(0,r).map(l=>l.id);return{hasMore:c,ids:u}},Y=(e,t,n)=>{const r=new Set(n.filter(_=>_!==m));if(!n.includes(m))return r;const o=e.exec(`SELECT ${d(m)} AS doc FROM ${t} LIMIT ?`,g).toArray();for(const{doc:_}of o){const s=typeof _=="string"?k(_):void 0;if(s!==void 0)for(const a of Object.keys(s))r.add(a)}return r},ie=(e,t)=>{const{column:n,table:r}=t;C(e,r);const o=d(r),_=M(e,o);if(!Y(e,o,_).has(n))throw new v("UNKNOWN_COLUMN",`unknown column: ${n}`,{status:404});const s=S(n,_);if(s===void 0)throw new v("UNKNOWN_COLUMN",`unknown column: ${n}`,{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,n)=>{const r={},o=n.slice(0,g);for(const s of o)r[s]=[];if(o.length===0)return{references:r,storageColumns:t};const _=o.map(()=>"?").join(", ");for(const[s,a]of Object.entries(t)){if(I(s)||!N(e,s))continue;const i=d(s),c=M(e,i);for(const u of a){const l=S(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)r[p.ref]?.push({column:u,id:p.id,table:s})}}return{references:r,storageColumns:t}},ue=e=>{const t=e.map((r,o)=>{const _=Object.values(r.subs??{}).map(s=>({args:s.args,functionPath:s.functionPath,table:s.table}));return{admin:r.admin===!0,id:o,subscriptions:_}}),n=t.reduce((r,o)=>r+o.subscriptions.length,0);return{connections:t,totalConnections:t.length,totalSubscriptions:n}},V=20,le=()=>({maxMs:0,passes:0,peakSocketsIterated:0,socketsDelivered:0,socketsIterated:0,totalMs:0}),de=(e,t,n,r)=>({maxMs:Math.max(e.maxMs,r),passes:e.passes+1,peakSocketsIterated:Math.max(e.peakSocketsIterated,t),socketsDelivered:e.socketsDelivered+n,socketsIterated:e.socketsIterated+t,totalMs:e.totalMs+r}),me=(e,t=V)=>{const n=new Map,r=new Map;for(const s of e){for(const a of Object.values(s.shapes??{})){const i=a.name??"(unknown shape)";n.set(i,(n.get(i)??0)+1)}for(const a of s.whispers??[])r.set(a,(r.get(a)??0)+1)}const o=[...[...n].map(([s,a])=>({kind:"shape",subscribers:a,topic:s})),...[...r].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,re as FLAGS_FUNCTION_PREFIX,g as MAX_PAGE_SIZE,ne as RELATION_FUNCTION_PREFIX,le as createFanoutCounters,X as datePrefixRange,ie as facetColumn,ce as findStorageReferences,oe as listTables,ae as readTablePage,de as recordFanoutPass,_e as selectMatchingIds,me as summarizeFanoutTopics,ue as summarizeSubscriptions};
@@ -0,0 +1 @@
1
+ import{LunoraError as u}from"@lunora/errors";const f=new Set(["baseWhere","relationBaseWhere","restrictsCounts","where"]),c=()=>{throw new u("INTERNAL","ctx.scheduler: no scheduler configured for triggers. Pass `scheduler` to the ctx-db factory.")},h=(e,r)=>{for(const[n,t]of Object.entries(r)){const o=e[n];if(t!==null&&typeof t=="object"&&!Array.isArray(t)){const s=Object.keys(t);if(s.length===1&&s[0]==="eq"){if(o!==t.eq)return!1;continue}return!1}if(o!==t)return!1}return!0},l=e=>{if(e===void 0)return{};if(typeof e!="object"||Array.isArray(e))return{where:e};const r=Object.keys(e);return r.length===0?{}:r.every(n=>f.has(n))?e:{where:e}},i={avg:"AVG",count:"COUNT",max:"MAX",min:"MIN",sum:"SUM"},y=e=>{const r=i[e];if(r===void 0)throw new u("INTERNAL",`unknown aggregate op "${e}": expected one of ${Object.keys(i).join(", ")}`);return r},A={runAfter:c,runAt:c};export{i as AGGREGATE_SQL_FUNCTION,y as aggregateSqlFunction,h as matchesStaticWhere,l as normalizeCountArgument,A as throwingScheduler};
@@ -0,0 +1 @@
1
+ import{A as r,a as l,b as i,D as n,n as m,c as q,d as c,l as d,k as f,g as p,i as u,j as A,e as D,q as G,f as S,r as _,t as h,h as C}from"./do-sql-Dk_DJxn4.mjs";import{quoteIdentifier as b}from"./quoteIdentifier-CObIFRhb.mjs";import"./wire-codec-BU9T2xJ7.mjs";import"./runDrizzle-it6rL9bR.mjs";import"./sql-projection-BqmxFxQU.mjs";import{serializeSqlValue as x}from"./serializeSqlValue-DbI1VQYM.mjs";export{r as AGG_COUNT,l as AGG_KEY,i as AGG_VALUE,n as DOC_COLUMN,m as DOC_ORIGINALS_KEY,q as aggUpsertSql,c as createIndexSql,d as decodeDocJson,f as encodeDocJson,p as geoTableName,u as isFtsAvailable,A as jsonPath,D as jsonPathSql,G as qualifiedJsonPath,S as qualifiedJsonPathSql,b as quoteIdentifier,_ as rowToDocument,x as serializeSqlValue,h as tableColumns,C as tryRowToDocument};
@@ -0,0 +1,8 @@
1
+ import{runSql as T}from"./runDrizzle-it6rL9bR.mjs";const i="__lunora_audit__",a=1e3,s=E=>{T(E,`CREATE TABLE IF NOT EXISTS "${i}" (
2
+ seq INTEGER PRIMARY KEY AUTOINCREMENT,
3
+ ts REAL NOT NULL,
4
+ op TEXT NOT NULL,
5
+ "table" TEXT,
6
+ id TEXT,
7
+ detail TEXT
8
+ )`)},R=(E,t)=>{s(E),T(E,`INSERT INTO "${i}" (ts, op, "table", id, detail) VALUES (?, ?, ?, ?, ?)`,t.ts,t.op,t.table??null,t.id??null,t.detail===void 0?null:JSON.stringify(t.detail)),T(E,`DELETE FROM "${i}" WHERE seq <= (SELECT MAX(seq) - ? FROM "${i}")`,a)},o=(E,t={})=>{s(E);const d=t.sinceSeq??0,n=Math.max(1,Math.min(t.limit??a,1e4));return T(E,`SELECT seq, ts, op, "table", id, detail FROM "${i}" WHERE seq > ? ORDER BY seq DESC LIMIT ?`,d,n).toArray().map(e=>{const l={op:e.op,seq:e.seq,ts:e.ts};return e.table!==null&&(l.table=e.table),e.id!==null&&(l.id=e.id),e.detail!==null&&(l.detail=JSON.parse(e.detail)),l})};export{i as AUDIT_LOG_TABLE,R as appendAuditEntry,s as ensureAuditTable,o as readAuditLog};
@@ -0,0 +1,8 @@
1
+ import{sql as e}from"drizzle-orm";import{runDrizzle as n}from"./runDrizzle-it6rL9bR.mjs";import{k as p,l as f}from"./do-sql-Dk_DJxn4.mjs";import{ConflictError as L}from"./ConflictError-C8GtJmjS.mjs";const s="__cdc_log",$=t=>{n(t,e`CREATE TABLE IF NOT EXISTS ${e.identifier(s)} (
2
+ seq INTEGER PRIMARY KEY AUTOINCREMENT,
3
+ ts REAL NOT NULL,
4
+ ${e.identifier("table")} TEXT NOT NULL,
5
+ id TEXT NOT NULL,
6
+ op TEXT NOT NULL,
7
+ doc TEXT
8
+ )`)},u=(t,o,i,r,d,T)=>{const E=T===void 0?null:p(T);n(t,e`INSERT INTO ${e.identifier(s)} (ts, ${e.identifier("table")}, id, op, doc) VALUES (${o}, ${i}, ${r}, ${d}, ${E})`)},S=(t,o={})=>{const i=o.sinceSeq??0,r=Math.max(1,Math.min(o.limit??1e3,1e4)),d=o.tables&&o.tables.size>0?e` AND ${e.identifier("table")} IN (${e.join([...o.tables].map(c=>e`${c}`),e`, `)})`:e``,E=n(t,e`SELECT seq, ts, ${e.identifier("table")}, id, op, doc FROM ${e.identifier(s)} WHERE seq > ${i}${d} ORDER BY seq ASC LIMIT ${r}`).toArray().map(c=>{const l={id:c.id,op:c.op,seq:c.seq,table:c.table,ts:c.ts};return c.doc===null?l:{...l,doc:f(c.doc)}});return{changes:E,cursor:E.at(-1)?.seq??i}},O=(t,o)=>{n(t,e`DELETE FROM ${e.identifier(s)} WHERE seq <= ${o}`)},q=t=>{const i=n(t,e`SELECT seq FROM sqlite_sequence WHERE name = ${s}`).toArray()[0]?.seq;return typeof i=="number"?i:n(t,e`SELECT MAX(seq) AS seq FROM ${e.identifier(s)}`).toArray()[0]?.seq??0},h=t=>n(t,e`SELECT MIN(seq) AS seq FROM ${e.identifier(s)}`).toArray()[0]?.seq??void 0,a="__cdc_meta",C=t=>{n(t,e`CREATE TABLE IF NOT EXISTS ${e.identifier(a)} (id INTEGER PRIMARY KEY CHECK (id = 1), epoch TEXT NOT NULL)`)},M=t=>{C(t);const i=n(t,e`SELECT epoch FROM ${e.identifier(a)} WHERE id = 1`).toArray()[0]?.epoch;if(typeof i=="string"&&i.length>0)return i;const r=crypto.randomUUID();return n(t,e`INSERT INTO ${e.identifier(a)} (id, epoch) VALUES (1, ${r})`),r},b=t=>{C(t);const o=crypto.randomUUID();return n(t,e`INSERT INTO ${e.identifier(a)} (id, epoch) VALUES (1, ${o}) ON CONFLICT(id) DO UPDATE SET epoch = excluded.epoch`),o},m=async(t,o)=>{if(o.op==="delete"){await t.delete(o.id,o.table);return}const i=o.doc??{};try{await t.insert(o.table,i,{allowExplicitId:!0})}catch(r){if(!(r instanceof L))throw r;const d={...i};delete d._id,await t.replace(o.id,d,void 0,{allowExplicitId:!0})}},y=async(t,o)=>{for(const i of o)await m(t,i)};export{s as CDC_LOG_TABLE,a as CDC_META_TABLE,u as appendCdcChange,y as applyCdcChanges,b as bumpCdcEpoch,$ as migrateCdcLog,C as migrateCdcMeta,h as minCdcSeq,S as readCdcChanges,q as readCdcCursor,M as readCdcEpoch,O as trimCdcChanges};
@@ -0,0 +1,7 @@
1
+ import{sql as t}from"drizzle-orm";import{runDrizzle as a}from"./runDrizzle-it6rL9bR.mjs";const r="__client_watermark",o=i=>{a(i,t`CREATE TABLE IF NOT EXISTS ${t.identifier(r)} (
2
+ identity TEXT NOT NULL,
3
+ client_id TEXT NOT NULL,
4
+ last_mutation_id INTEGER NOT NULL,
5
+ PRIMARY KEY (identity, client_id)
6
+ )`)},E=(i,e,n)=>a(i,t`SELECT last_mutation_id FROM ${t.identifier(r)} WHERE identity = ${e} AND client_id = ${n} LIMIT 1`).toArray()[0]?.last_mutation_id??0,l=(i,e,n,d)=>{a(i,t`INSERT INTO ${t.identifier(r)} (identity, client_id, last_mutation_id) VALUES (${e}, ${n}, ${d})
7
+ ON CONFLICT(identity, client_id) DO UPDATE SET last_mutation_id = MAX(last_mutation_id, excluded.last_mutation_id)`)};export{r as CLIENT_WATERMARK_TABLE,l as advanceClientWatermark,o as migrateClientWatermark,E as readClientWatermark};
@@ -0,0 +1 @@
1
+ import{LunoraError as p}from"@lunora/errors";class R extends p{constructor(n){super("COUNT_RLS_UNSUPPORTED",n===void 0?"count() is not supported in an RLS-restricted context":`count() is not supported on table "${n}" inside an RLS-restricted context`)}}const S=(e,n)=>e?n?{AND:[e,n]}:e:n,v=new Set(["AND","NOT","OR"]),d=Symbol("not-eq"),O=e=>{if(e!==null&&typeof e=="object"&&!Array.isArray(e)){const n=Object.keys(e);return n.length===1&&n[0]==="eq"?e.eq:d}return e},f=(e,n)=>{const i={};for(const[t,o]of Object.entries(e)){if(v.has(t)||!n(t))return;const r=O(o);if(r===d)return;i[t]=r}return i},l=(e,n,i)=>{const t={...n};if(!e)return t;for(const[o,r]of Object.entries(e))if(o in t){if(t[o]!==r)return}else if(o in i){if(i[o]!==r)return}else t[o]=r;return t},b=(e,n)=>{const i=e.by??[],t=n??{},o=f(t,r=>i.includes(r));if(o!==void 0){for(const r of i)if(!(r in o))return;return l(e.where,o,t)}},x=(e,n,i)=>{const t=f(n??{},o=>i.has(o));if(t!==void 0)return l(e.where,t,{})},y=(e,n,i,t)=>{let o;for(const r of e){if(r.op!==n||n!=="count"&&r.field!==i)continue;const s=b(r,t);s&&(!o||(r.by?.length??0)>(o.index.by?.length??0))&&(o={index:r,key:s})}return o},h=(e,n)=>y(e,"count",void 0,n),A=(e,n,i,t)=>y(e,n,i,t),N=(e,n,i,t,o)=>{const r=new Set(t);for(const s of e){if(s.op!==n||n!=="count"&&s.field!==i)continue;const c=s.by??[];if(c.length!==r.size||!c.every(a=>r.has(a)))continue;const u=x(s,o,r);if(u!==void 0)return{index:s,partial:u}}};export{R as CountRlsUnsupportedError,S as mergeWhere,b as planAggregateLookup,A as selectIndexForAggregate,h as selectIndexForCount,N as selectIndexForGroupBy};
@@ -0,0 +1,31 @@
1
+ import{LunoraError as b}from"@lunora/errors";import{runSql as c}from"./runDrizzle-it6rL9bR.mjs";const n="__lunora_migrations",x=100,D=3e4,y=1e4,M=e=>{c(e,`CREATE TABLE IF NOT EXISTS "${n}" (
2
+ id TEXT PRIMARY KEY,
3
+ direction TEXT NOT NULL,
4
+ status TEXT NOT NULL,
5
+ cursor TEXT,
6
+ processed INTEGER NOT NULL DEFAULT 0,
7
+ changed INTEGER NOT NULL DEFAULT 0,
8
+ started_at REAL,
9
+ updated_at REAL,
10
+ error TEXT
11
+ )`)},N=e=>({changed:e.changed,cursor:typeof e.cursor=="string"?e.cursor:null,direction:e.direction==="down"?"down":"up",processed:e.processed,status:e.status==="completed"||e.status==="failed"?e.status:"in_progress"}),h=(e,t)=>{const r=c(e,`SELECT * FROM "${n}" WHERE id = ?`,t).toArray()[0];if(r)return{...N(r),startedAt:typeof r.started_at=="number"?r.started_at:void 0}},C=(e,t)=>{c(e,`DELETE FROM "${n}" WHERE id = ?`,t)},S=(e,t)=>{c(e,`INSERT INTO "${n}"
12
+ (id, direction, status, cursor, processed, changed, started_at, updated_at, error)
13
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
14
+ ON CONFLICT(id) DO UPDATE SET
15
+ direction = excluded.direction,
16
+ status = excluded.status,
17
+ cursor = excluded.cursor,
18
+ processed = excluded.processed,
19
+ changed = excluded.changed,
20
+ updated_at = excluded.updated_at,
21
+ error = excluded.error`,t.id,t.direction,t.status,t.cursor,t.processed,t.changed,t.startedAt,t.updatedAt,t.error)},U=(e,t,s,r)=>(c(e,`INSERT INTO "${n}"
22
+ (id, direction, status, cursor, processed, changed, started_at, updated_at, error)
23
+ VALUES (?, ?, 'in_progress', NULL, 0, 0, ?, ?, NULL)
24
+ ON CONFLICT(id) DO UPDATE SET
25
+ status = 'in_progress',
26
+ updated_at = excluded.updated_at
27
+ WHERE
28
+ "${n}".direction <> excluded.direction
29
+ OR "${n}".status <> 'in_progress'
30
+ OR "${n}".updated_at IS NULL
31
+ OR "${n}".updated_at <= excluded.updated_at - ${String(D)}`,t,s,r,r),c(e,"SELECT changes() AS changed").one().changed>0),$=(e,t,s)=>{c(e,`UPDATE "${n}" SET updated_at = ? WHERE id = ? AND status = 'in_progress'`,s,t)},F=(e,t)=>{c(e,`UPDATE "${n}" SET updated_at = 0 WHERE id = ? AND status = 'in_progress'`,t)},B=(e,t)=>{if(c(e,"SELECT name FROM sqlite_master WHERE type = 'table' AND name = ? LIMIT 1",n).toArray().length===0)return[];const r=t===void 0?" ORDER BY id":" WHERE id = ?",i=t===void 0?[]:[t];return c(e,`SELECT * FROM "${n}"${r}`,...i).toArray().map(a=>({...N(a),error:typeof a.error=="string"?a.error:null,id:a.id,startedAt:typeof a.started_at=="number"?a.started_at:null,updatedAt:typeof a.updated_at=="number"?a.updated_at:null}))},w=async e=>{const{migration:t,sql:s,writer:r}=e,i=e.direction??"up",o=e.dryRun??!1,a=e.clock??(()=>Date.now()),R=e.maxBatches??Number.POSITIVE_INFINITY,I=e.batchSize??t.batchSize??x,L=i==="up"?t.up:t.down;if(!L)throw new b("INTERNAL",`data migration "${t.id}" has no \`${i}\` transform`);const O={db:{count:r.count.bind(r),findFirst:r.findFirst.bind(r),findMany:r.findMany.bind(r),get:r.get.bind(r)}};let T=null,_=0,g=0,A=a();if(!o){M(s);const d=h(s,t.id);if(d?.direction===i&&d.status==="completed")return{changed:d.changed,cursor:null,direction:i,dryRun:o,id:t.id,processed:d.processed,status:"completed"};if(d&&d.direction!==i&&C(s,t.id),!U(s,t.id,i,a())){const E=h(s,t.id);return{changed:E?.changed??0,cursor:E?.cursor??T,direction:i,dryRun:o,id:t.id,processed:E?.processed??0,status:E?.status??"in_progress"}}const l=d?.direction===i?d:void 0;l&&(T=l.cursor,_=l.processed,g=l.changed,A=l.startedAt??A)}let p=!1,m=0,f=A;try{for(;!p&&m<R;){const d=await r.findMany(t.table,{cursor:T,limit:I});for(const u of d.page){_+=1;const l=await L(u,O);if(l!==void 0&&(g+=1,o||await r.replace(String(u._id),{...l,_creationTime:u._creationTime,_id:u._id},void 0,{allowExplicitId:!0})),!o){const E=a();E-f>=y&&($(s,t.id,E),f=E)}}if(T=d.continueCursor,p=d.isDone,m+=1,!o){const u=a();S(s,{changed:g,cursor:p?null:T,direction:i,error:null,id:t.id,processed:_,startedAt:A,status:p?"completed":"in_progress",updatedAt:u}),f=u;try{await e.onBatch?.({batches:m,changed:g,processed:_})}catch{}}}}catch(d){throw o||S(s,{changed:g,cursor:T,direction:i,error:d instanceof Error?d.message:String(d),id:t.id,processed:_,startedAt:A,status:"failed",updatedAt:a()}),d}if(!o&&!p)try{F(s,t.id)}catch(d){console.warn(`data migration "${t.id}": releaseClaim failed`,d)}return{changed:g,cursor:p?null:T,direction:i,dryRun:o,id:t.id,processed:_,status:p?"completed":"in_progress"}};export{n as DATA_MIGRATION_STATE_TABLE,B as readMigrationStatus,w as runDataMigration};