@lunora/do 1.0.0-alpha.50 → 1.0.0-alpha.52
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +19 -40
- package/dist/index.d.ts +19 -40
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/{DEFAULT_MAX_RELATION_KEYS-BRdmX7WW.mjs → DEFAULT_MAX_RELATION_KEYS-BcW3nUKL.mjs} +1 -1
- package/dist/packem_shared/NotUniqueError-BDYkMtJP.mjs +1 -0
- package/dist/packem_shared/{ROOT_DO_SIZE_WARN_BYTES-oZjI_5uF.mjs → ROOT_DO_SIZE_WARN_BYTES-ChulUZTK.mjs} +1 -1
- package/dist/packem_shared/{applyOnDelete-BvQN7pDL.mjs → applyOnDelete-CafQWSqu.mjs} +1 -1
- package/dist/packem_shared/applySelect-B0CF8T7y.mjs +1 -0
- package/dist/packem_shared/backfillAggregateIndexes-DUrhkmiz.mjs +1 -0
- package/dist/packem_shared/ctx-db-backfill-C4rAzsQo.mjs +1 -0
- package/dist/packem_shared/ctx-db-shapes-CHC2cS0g.mjs +1 -0
- package/dist/packem_shared/do-sql-x0AjZhaN.mjs +1 -0
- package/dist/packem_shared/{isSoftDeleted-BvhQov04.mjs → isSoftDeleted-juJOq515.mjs} +1 -1
- package/dist/packem_shared/{materializeExternalRows-BFmT9gsw.mjs → materializeExternalRows-BUmj_9WO.mjs} +1 -1
- package/dist/packem_shared/runShardMigrations-CcSFXtXZ.mjs +5 -0
- package/dist/packem_shared/{selectExpiredIds-BGVP3d8-.mjs → selectExpiredIds-BXJDiUtz.mjs} +1 -1
- package/package.json +3 -2
- package/dist/packem_shared/NotUniqueError-GI79LNJB.mjs +0 -1
- package/dist/packem_shared/applySelect-Bq2KOrkL.mjs +0 -1
- package/dist/packem_shared/backfillAggregateIndexes-BAQ3Fwwh.mjs +0 -1
- package/dist/packem_shared/buildFtsMatch-CV0Z7PWv.mjs +0 -1
- package/dist/packem_shared/ctx-db-shapes-DzX_H5q8.mjs +0 -1
- package/dist/packem_shared/do-sql-BYIQTG3z.mjs +0 -1
- package/dist/packem_shared/runShardMigrations-bxOHpfID.mjs +0 -5
package/dist/index.d.mts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { LunoraError } from '@lunora/errors';
|
|
2
|
+
import '@lunora/search-core';
|
|
2
3
|
import { SQL } from 'drizzle-orm';
|
|
3
4
|
import { DrizzleSqliteDODatabase } from 'drizzle-orm/durable-sqlite';
|
|
4
5
|
/**
|
|
@@ -1221,6 +1222,16 @@ declare const backfillAggregateIndexes: (sql: SqlExec, schema: SchemaLike) => vo
|
|
|
1221
1222
|
* rank companions that already carry rows.
|
|
1222
1223
|
*/
|
|
1223
1224
|
declare const backfillRankIndexes: (sql: SqlExec, schema: SchemaLike) => void;
|
|
1225
|
+
/**
|
|
1226
|
+
* Run every declared search index — including the `staged: true` ones the
|
|
1227
|
+
* migration pass skips — through to completion. The entry point a host calls
|
|
1228
|
+
* out-of-band (a one-shot admin RPC, a migration step) after deploying a search
|
|
1229
|
+
* index over a table too large to index a page at a time.
|
|
1230
|
+
*
|
|
1231
|
+
* Idempotent and resumable: an index already recorded as complete is skipped,
|
|
1232
|
+
* and an interrupted run picks up from its recorded cursor.
|
|
1233
|
+
*/
|
|
1234
|
+
declare const backfillSearchIndexes: (sql: SqlExec, schema: SchemaLike) => void;
|
|
1224
1235
|
/** Reserved append-only changelog table backing CDC streaming export and replay-PITR. */
|
|
1225
1236
|
declare const CDC_LOG_TABLE = "__cdc_log";
|
|
1226
1237
|
/** One change-data-capture entry: a committed mutation, in monotonic `seq` order. */
|
|
@@ -1362,9 +1373,16 @@ interface IndexDefinitionLike {
|
|
|
1362
1373
|
readonly unique?: boolean;
|
|
1363
1374
|
}
|
|
1364
1375
|
interface SearchIndexDefinitionLike {
|
|
1376
|
+
/** Indexed text column; a dot-separated path reads a nested field. */
|
|
1365
1377
|
readonly field: string;
|
|
1366
1378
|
readonly filterFields?: ReadonlyArray<string>;
|
|
1379
|
+
/** Analysis profile (folding + stopwords) — see `@lunora/server`'s `SearchIndexDefinition`. */
|
|
1380
|
+
readonly language?: string;
|
|
1367
1381
|
readonly name: string;
|
|
1382
|
+
/** Skip the migration-time backfill of the search companion — see `@lunora/server`'s `SearchIndexDefinition`. */
|
|
1383
|
+
readonly staged?: boolean;
|
|
1384
|
+
/** `"native"` opts into the engine's own full-text index where it has one; see `@lunora/server`'s `SearchIndexDefinition`. */
|
|
1385
|
+
readonly strategy?: string;
|
|
1368
1386
|
}
|
|
1369
1387
|
/** Mirror of `@lunora/server`'s `GeoIndexDefinition` — a geohash companion over a `v.geoPoint()` column. */
|
|
1370
1388
|
interface GeoIndexDefinitionLike {
|
|
@@ -4419,45 +4437,6 @@ type TableOfId = (id: string, expectedTable?: string) => Promise<string | undefi
|
|
|
4419
4437
|
* pointing back at `raw`.
|
|
4420
4438
|
*/
|
|
4421
4439
|
declare const guardWriter: <W>(raw: W, schema: GuardableSchema, tableOfId: TableOfId) => W;
|
|
4422
|
-
/**
|
|
4423
|
-
* Shared FTS / text-search primitives for the DO and D1 ctx-db dialects.
|
|
4424
|
-
*
|
|
4425
|
-
* Both backends index `.searchIndex()` columns into an FTS5 shadow table and
|
|
4426
|
-
* fall back to a JS scan-and-score path when FTS5 is unavailable. The
|
|
4427
|
-
* tokenizer, MATCH-expression builder, text coercion, and fallback scorer are
|
|
4428
|
-
* dialect-agnostic, so they live here and are imported by both
|
|
4429
|
-
* `ctx-db.ts` (`@lunora/do`) and `d1-ctx-db.ts` (`@lunora/d1`) — guaranteeing the
|
|
4430
|
-
* two engines tokenize and rank byte-for-byte identically.
|
|
4431
|
-
*/
|
|
4432
|
-
/**
|
|
4433
|
-
* Name of the FTS5 shadow table backing a search index. Kept distinct from any
|
|
4434
|
-
* user table (the `__fts_` infix is reserved) so `runShardMigrations` can create
|
|
4435
|
-
* it alongside the document table without collision.
|
|
4436
|
-
*/
|
|
4437
|
-
declare const ftsTableName: (table: string, indexName: string) => string;
|
|
4438
|
-
/**
|
|
4439
|
-
* Split a search string into lowercased alphanumeric tokens. The Unicode
|
|
4440
|
-
* `\p{L}\p{N}` class guarantees tokens carry no SQL/FTS metacharacters, so they
|
|
4441
|
-
* need no escaping beyond the literal-phrase quoting {@link buildFtsMatch} adds.
|
|
4442
|
-
*/
|
|
4443
|
-
declare const tokenizeSearch: (query: string) => string[];
|
|
4444
|
-
/**
|
|
4445
|
-
* Render tokens as an FTS5 MATCH expression: each token is a quoted literal
|
|
4446
|
-
* phrase (neutralizes reserved words), the final token gains a trailing `*` for
|
|
4447
|
-
* prefix matching (asterisk outside the quotes), and they AND together so every
|
|
4448
|
-
* token must be present — mirroring the fallback scorer's conjunction semantics.
|
|
4449
|
-
*/
|
|
4450
|
-
declare const buildFtsMatch: (tokens: ReadonlyArray<string>) => string;
|
|
4451
|
-
/** Coerce a search/filter field value to the text FTS indexes and the scorer scans. */
|
|
4452
|
-
declare const stringifySearchText: (value: unknown) => string;
|
|
4453
|
-
/**
|
|
4454
|
-
* Score a document's indexed text against the query tokens with AND semantics:
|
|
4455
|
-
* every non-final token must appear exactly, the final token matches as a
|
|
4456
|
-
* prefix. Returns 0 (no match) unless all tokens are present; otherwise the sum
|
|
4457
|
-
* of occurrences, giving a coarse term-frequency relevance order for the
|
|
4458
|
-
* LIKE-scan fallback used when FTS5 is unavailable.
|
|
4459
|
-
*/
|
|
4460
|
-
declare const scoreDocument: (text: string, tokens: ReadonlyArray<string>) => number;
|
|
4461
4440
|
/**
|
|
4462
4441
|
* Ordering/visual weight of a security finding — mirrors the studio's insight
|
|
4463
4442
|
* severities so the Security Advisor and the Performance Advisor (Insights) share
|
|
@@ -7880,4 +7859,4 @@ interface WhereSqlStrategy {
|
|
|
7880
7859
|
* `undefined` when the input imposes no constraint (empty `where`).
|
|
7881
7860
|
*/
|
|
7882
7861
|
declare const compileWhereSql: (where: WhereInput | undefined, strategy: WhereSqlStrategy) => SQL | undefined;
|
|
7883
|
-
export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, AGGREGATE_SQL_FUNCTION, AUTH_METRICS_BUCKETS_TABLE, AUTH_METRICS_BUCKET_MS, AUTH_METRICS_BUCKET_RETENTION, AUTH_METRICS_TABLE, type AdvisoriesResult, type AdvisoryFinding, type AggregateIndexDefinitionLike, type AggregateOp, type AggregateOptions, type AggregateResult, type AggregateTally, type ApplyOnDeleteOptions, type AuditEntry, type AuditLogResult, type AuthMetrics, type AuthMetricsBucket, type BroadcastDelta, CDC_LOG_TABLE, type CacheEntry, type CapturedMailRow, type CdcChange, type Clock, type ColumnMeta, type ColumnMetaLike, ConflictError, type ContextMetrics, type ContextTracer, type CountArgs, CountRlsUnsupportedError, type CtxDbOptions, DATA_MIGRATION_STATE_TABLE, DEFAULT_MAX_RELATION_KEYS, 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, FUNCTION_METRICS_BUCKETS_TABLE, FUNCTION_METRICS_BUCKET_MS, FUNCTION_METRICS_BUCKET_RETENTION, FUNCTION_METRICS_INDEX_TABLE, FUNCTION_METRICS_TABLE, type FacetColumnOptions, type FacetColumnResult, type FacetValue, type FieldOperators, type FlagEvaluation, type FlagsResult, type FunctionCallStat, type FunctionMetricBucket, type FunctionMetricIndexHit, type FunctionStatsResult, GEO_DEFAULT_PRECISION, type GeoBoundingBox, type GeoFilterBuilderLike, type GeoIndexDefinitionLike, type GeoPoint, type GroupByEntry, type GroupByOptions, type HibernatableWebSocket, type IdGenerator, type ImportError, type ImportShardAdminArgs, type ImportShardArgs, type ImportShardResult, type IncrementalMaterializeResult, type IndexDefinitionLike, type IndexRangeBuilderLike, LogBuffer, type LogEntry, type LogEventInput, type LogLevel, type LogSink, MAIL_RETENTION, MAIL_TABLE, MAX_SQL_ROWS, MIN_ADMIN_TOKEN_LENGTH, MIN_AUTH_SECRET_LENGTH, type MaskColumnMetadata, type MaskPoliciesResult, type MaterializeResult, type MetricsDeps, type MigrationDirection, type MigrationRunResult, type MigrationStatus, type MigrationStatusRow, type MutationDelta, type NestedWith, NotFoundError, NotUniqueError, type OnDeleteActionLike, type OrderByInput, type OrderKey, type PaginationOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type QueryArgs, type QueryPage, type QueueMetadata, type QueuesResult, RANK_TIEBREAK, RELATION_FUNCTION_PREFIX, RLS_UNWRAP_SYMBOL, ROOT_DO_SIZE_WARN_BYTES, ROOT_SHARD_NAME, type RankDirection, type RankIndexDefinitionLike, type RankOptions, type RankPage, type RankPageOptions, type RankPageRow, type RankPageRowKey, type RankResult, type RankSortKeyLike, ReactiveCache, type ReactiveCacheOptions, type ReadHook, type ReadTablePageOptions, type RecordAuthEventInput, type RecordFunctionMetricInput, type RecordMailInput, type RelationDefinitionLike, type RenderedSql, type ResolveRelationPredicatesOptions, type ResolveWithOptions, type RestrictableQueryOptions, type RlsPoliciesResult, type RlsPolicyMetadata, RlsRequiredError, type RlsRoleMetadata, type RpcRequest, type RunDataMigrationOptions, type RunShardApplyCdcArgs, type RunShardApplyCdcResult, type RunShardBulkDeleteArgs, type RunShardBulkDeleteResult, type RunShardExportArgs, type RunShardImportArgs, type RunShardMigrationArgs, type RunShardRankBeforeArgs, type RunShardRankPageArgs, type RunShardWriteArgs, type RunShardWriteResult, type RunTriggersOptions, SCAN_DEP, SESSION_DO_TTL_DEFAULT, SHARD_REGISTRY_DO_NAME, type SchedulableWorkflowReferenceLike, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type SearchFilterBuilderLike, type SecurityAuditResult, type SecurityFinding, type SecurityFindingKind, type SecurityFindingLevel, type SelectMatchingIdsOptions, type ServerDefaultContextLike, SessionDO, type SessionRecord, type SettingEntry, type SettingKind, type SettingsResult, type ShapeSubscriptionQuery, ShardDO, type ShardDOOptions, type ShardDOState, type ShardRankPageResult, ShardRegistryDO, type SocketAttachment, type SortDirection, type SourceClientLike, type SourceCursorLike, type SourceRefresh, type SpanHandle, type SqlConsoleResult, type SqlCursor, type SqlEngine, type SqlExec, type StorageRuleMetadata, type StorageRulesResult, type StudioFeaturesResult, type SubscriptionEnvelope, type SubscriptionOutcome, type SubscriptionQuery, 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 TelemetrySink, type TraceAnchor, type TracerDeps, type TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, type TtlSweepSpec, type ValidatorLike, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, aggregateSqlFunction, aggregateTableName, applyCdcChanges, applyOnDelete, applySelect, armRestore, assertFlatPredicate, assertReadonly, assertShapeShardable, assertValidClientId, backfillAggregateIndexes, backfillRankIndexes,
|
|
7862
|
+
export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, AGGREGATE_SQL_FUNCTION, AUTH_METRICS_BUCKETS_TABLE, AUTH_METRICS_BUCKET_MS, AUTH_METRICS_BUCKET_RETENTION, AUTH_METRICS_TABLE, type AdvisoriesResult, type AdvisoryFinding, type AggregateIndexDefinitionLike, type AggregateOp, type AggregateOptions, type AggregateResult, type AggregateTally, type ApplyOnDeleteOptions, type AuditEntry, type AuditLogResult, type AuthMetrics, type AuthMetricsBucket, type BroadcastDelta, CDC_LOG_TABLE, type CacheEntry, type CapturedMailRow, type CdcChange, type Clock, type ColumnMeta, type ColumnMetaLike, ConflictError, type ContextMetrics, type ContextTracer, type CountArgs, CountRlsUnsupportedError, type CtxDbOptions, DATA_MIGRATION_STATE_TABLE, DEFAULT_MAX_RELATION_KEYS, 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, FUNCTION_METRICS_BUCKETS_TABLE, FUNCTION_METRICS_BUCKET_MS, FUNCTION_METRICS_BUCKET_RETENTION, FUNCTION_METRICS_INDEX_TABLE, FUNCTION_METRICS_TABLE, type FacetColumnOptions, type FacetColumnResult, type FacetValue, type FieldOperators, type FlagEvaluation, type FlagsResult, type FunctionCallStat, type FunctionMetricBucket, type FunctionMetricIndexHit, type FunctionStatsResult, GEO_DEFAULT_PRECISION, type GeoBoundingBox, type GeoFilterBuilderLike, type GeoIndexDefinitionLike, type GeoPoint, type GroupByEntry, type GroupByOptions, type HibernatableWebSocket, type IdGenerator, type ImportError, type ImportShardAdminArgs, type ImportShardArgs, type ImportShardResult, type IncrementalMaterializeResult, type IndexDefinitionLike, type IndexRangeBuilderLike, LogBuffer, type LogEntry, type LogEventInput, type LogLevel, type LogSink, MAIL_RETENTION, MAIL_TABLE, MAX_SQL_ROWS, MIN_ADMIN_TOKEN_LENGTH, MIN_AUTH_SECRET_LENGTH, type MaskColumnMetadata, type MaskPoliciesResult, type MaterializeResult, type MetricsDeps, type MigrationDirection, type MigrationRunResult, type MigrationStatus, type MigrationStatusRow, type MutationDelta, type NestedWith, NotFoundError, NotUniqueError, type OnDeleteActionLike, type OrderByInput, type OrderKey, type PaginationOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type QueryArgs, type QueryPage, type QueueMetadata, type QueuesResult, RANK_TIEBREAK, RELATION_FUNCTION_PREFIX, RLS_UNWRAP_SYMBOL, ROOT_DO_SIZE_WARN_BYTES, ROOT_SHARD_NAME, type RankDirection, type RankIndexDefinitionLike, type RankOptions, type RankPage, type RankPageOptions, type RankPageRow, type RankPageRowKey, type RankResult, type RankSortKeyLike, ReactiveCache, type ReactiveCacheOptions, type ReadHook, type ReadTablePageOptions, type RecordAuthEventInput, type RecordFunctionMetricInput, type RecordMailInput, type RelationDefinitionLike, type RenderedSql, type ResolveRelationPredicatesOptions, type ResolveWithOptions, type RestrictableQueryOptions, type RlsPoliciesResult, type RlsPolicyMetadata, RlsRequiredError, type RlsRoleMetadata, type RpcRequest, type RunDataMigrationOptions, type RunShardApplyCdcArgs, type RunShardApplyCdcResult, type RunShardBulkDeleteArgs, type RunShardBulkDeleteResult, type RunShardExportArgs, type RunShardImportArgs, type RunShardMigrationArgs, type RunShardRankBeforeArgs, type RunShardRankPageArgs, type RunShardWriteArgs, type RunShardWriteResult, type RunTriggersOptions, SCAN_DEP, SESSION_DO_TTL_DEFAULT, SHARD_REGISTRY_DO_NAME, type SchedulableWorkflowReferenceLike, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type SearchFilterBuilderLike, type SearchIndexDefinitionLike, type SecurityAuditResult, type SecurityFinding, type SecurityFindingKind, type SecurityFindingLevel, type SelectMatchingIdsOptions, type ServerDefaultContextLike, SessionDO, type SessionRecord, type SettingEntry, type SettingKind, type SettingsResult, type ShapeSubscriptionQuery, ShardDO, type ShardDOOptions, type ShardDOState, type ShardRankPageResult, ShardRegistryDO, type SocketAttachment, type SortDirection, type SourceClientLike, type SourceCursorLike, type SourceRefresh, type SpanHandle, type SqlConsoleResult, type SqlCursor, type SqlEngine, type SqlExec, type StorageRuleMetadata, type StorageRulesResult, type StudioFeaturesResult, type SubscriptionEnvelope, type SubscriptionOutcome, type SubscriptionQuery, 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 TelemetrySink, type TraceAnchor, type TracerDeps, type TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, type TtlSweepSpec, type ValidatorLike, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, aggregateSqlFunction, aggregateTableName, applyCdcChanges, applyOnDelete, applySelect, armRestore, assertFlatPredicate, assertReadonly, assertShapeShardable, assertValidClientId, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, boundingBoxGeohashes, buildSecurityAudit, buildSeekWhere, clearCapturedMail, coerceAggregateNumber, compileWhereSql, containsRelationPredicate, coveringGeohashes, createDependencyTracker, createMetrics, createShardCtxDb, createSystemReader, createTracer, decodeCursor, depKey, diffExternalSource, dispatchRootSpan, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, ensureAuthMetricsTables, ensureFunctionMetricsTables, ensureMailTable, exportShardRows, exportShardTable, facetColumn, fanOutScalarCounts, foldAggregateTally, guardWriter, hasTrigger, haversineMeters, importShardRows, isRelationPredicate, isSoftDeleted, isSourceDue, liftSourceId, listTables, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, mergeWhere, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, parseExportShardArgs, parseImportShardArgs, planAggregateLookup, pointInBoundingBox, pullExternalSourceIncrementalTick, pullExternalSourceTick, rankTableName, reactiveCacheKey, readAggregateValue, readAuthMetrics, readBookmark, readCapturedMail, readCdcChanges, readExternalSourceBaseline, readFunctionMetricBuckets, readFunctionMetricIndexHits, readFunctionMetrics, readFunctionMetricsTotals, readMigrationStatus, readTablePage, recordAuthEvent, recordCapturedMail, recordFunctionMetric, renderSql, resolveRankPartition, resolveRelationPredicates, resolveWith, runDataMigration, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, serveRelationFanout, softDeleteScope, sortColumnName, stableStringify, stableWireKey, subscriptionListDeltas, throwingScheduler, trimCdcChanges, validateImportRow };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { LunoraError } from '@lunora/errors';
|
|
2
|
+
import '@lunora/search-core';
|
|
2
3
|
import { SQL } from 'drizzle-orm';
|
|
3
4
|
import { DrizzleSqliteDODatabase } from 'drizzle-orm/durable-sqlite';
|
|
4
5
|
/**
|
|
@@ -1221,6 +1222,16 @@ declare const backfillAggregateIndexes: (sql: SqlExec, schema: SchemaLike) => vo
|
|
|
1221
1222
|
* rank companions that already carry rows.
|
|
1222
1223
|
*/
|
|
1223
1224
|
declare const backfillRankIndexes: (sql: SqlExec, schema: SchemaLike) => void;
|
|
1225
|
+
/**
|
|
1226
|
+
* Run every declared search index — including the `staged: true` ones the
|
|
1227
|
+
* migration pass skips — through to completion. The entry point a host calls
|
|
1228
|
+
* out-of-band (a one-shot admin RPC, a migration step) after deploying a search
|
|
1229
|
+
* index over a table too large to index a page at a time.
|
|
1230
|
+
*
|
|
1231
|
+
* Idempotent and resumable: an index already recorded as complete is skipped,
|
|
1232
|
+
* and an interrupted run picks up from its recorded cursor.
|
|
1233
|
+
*/
|
|
1234
|
+
declare const backfillSearchIndexes: (sql: SqlExec, schema: SchemaLike) => void;
|
|
1224
1235
|
/** Reserved append-only changelog table backing CDC streaming export and replay-PITR. */
|
|
1225
1236
|
declare const CDC_LOG_TABLE = "__cdc_log";
|
|
1226
1237
|
/** One change-data-capture entry: a committed mutation, in monotonic `seq` order. */
|
|
@@ -1362,9 +1373,16 @@ interface IndexDefinitionLike {
|
|
|
1362
1373
|
readonly unique?: boolean;
|
|
1363
1374
|
}
|
|
1364
1375
|
interface SearchIndexDefinitionLike {
|
|
1376
|
+
/** Indexed text column; a dot-separated path reads a nested field. */
|
|
1365
1377
|
readonly field: string;
|
|
1366
1378
|
readonly filterFields?: ReadonlyArray<string>;
|
|
1379
|
+
/** Analysis profile (folding + stopwords) — see `@lunora/server`'s `SearchIndexDefinition`. */
|
|
1380
|
+
readonly language?: string;
|
|
1367
1381
|
readonly name: string;
|
|
1382
|
+
/** Skip the migration-time backfill of the search companion — see `@lunora/server`'s `SearchIndexDefinition`. */
|
|
1383
|
+
readonly staged?: boolean;
|
|
1384
|
+
/** `"native"` opts into the engine's own full-text index where it has one; see `@lunora/server`'s `SearchIndexDefinition`. */
|
|
1385
|
+
readonly strategy?: string;
|
|
1368
1386
|
}
|
|
1369
1387
|
/** Mirror of `@lunora/server`'s `GeoIndexDefinition` — a geohash companion over a `v.geoPoint()` column. */
|
|
1370
1388
|
interface GeoIndexDefinitionLike {
|
|
@@ -4419,45 +4437,6 @@ type TableOfId = (id: string, expectedTable?: string) => Promise<string | undefi
|
|
|
4419
4437
|
* pointing back at `raw`.
|
|
4420
4438
|
*/
|
|
4421
4439
|
declare const guardWriter: <W>(raw: W, schema: GuardableSchema, tableOfId: TableOfId) => W;
|
|
4422
|
-
/**
|
|
4423
|
-
* Shared FTS / text-search primitives for the DO and D1 ctx-db dialects.
|
|
4424
|
-
*
|
|
4425
|
-
* Both backends index `.searchIndex()` columns into an FTS5 shadow table and
|
|
4426
|
-
* fall back to a JS scan-and-score path when FTS5 is unavailable. The
|
|
4427
|
-
* tokenizer, MATCH-expression builder, text coercion, and fallback scorer are
|
|
4428
|
-
* dialect-agnostic, so they live here and are imported by both
|
|
4429
|
-
* `ctx-db.ts` (`@lunora/do`) and `d1-ctx-db.ts` (`@lunora/d1`) — guaranteeing the
|
|
4430
|
-
* two engines tokenize and rank byte-for-byte identically.
|
|
4431
|
-
*/
|
|
4432
|
-
/**
|
|
4433
|
-
* Name of the FTS5 shadow table backing a search index. Kept distinct from any
|
|
4434
|
-
* user table (the `__fts_` infix is reserved) so `runShardMigrations` can create
|
|
4435
|
-
* it alongside the document table without collision.
|
|
4436
|
-
*/
|
|
4437
|
-
declare const ftsTableName: (table: string, indexName: string) => string;
|
|
4438
|
-
/**
|
|
4439
|
-
* Split a search string into lowercased alphanumeric tokens. The Unicode
|
|
4440
|
-
* `\p{L}\p{N}` class guarantees tokens carry no SQL/FTS metacharacters, so they
|
|
4441
|
-
* need no escaping beyond the literal-phrase quoting {@link buildFtsMatch} adds.
|
|
4442
|
-
*/
|
|
4443
|
-
declare const tokenizeSearch: (query: string) => string[];
|
|
4444
|
-
/**
|
|
4445
|
-
* Render tokens as an FTS5 MATCH expression: each token is a quoted literal
|
|
4446
|
-
* phrase (neutralizes reserved words), the final token gains a trailing `*` for
|
|
4447
|
-
* prefix matching (asterisk outside the quotes), and they AND together so every
|
|
4448
|
-
* token must be present — mirroring the fallback scorer's conjunction semantics.
|
|
4449
|
-
*/
|
|
4450
|
-
declare const buildFtsMatch: (tokens: ReadonlyArray<string>) => string;
|
|
4451
|
-
/** Coerce a search/filter field value to the text FTS indexes and the scorer scans. */
|
|
4452
|
-
declare const stringifySearchText: (value: unknown) => string;
|
|
4453
|
-
/**
|
|
4454
|
-
* Score a document's indexed text against the query tokens with AND semantics:
|
|
4455
|
-
* every non-final token must appear exactly, the final token matches as a
|
|
4456
|
-
* prefix. Returns 0 (no match) unless all tokens are present; otherwise the sum
|
|
4457
|
-
* of occurrences, giving a coarse term-frequency relevance order for the
|
|
4458
|
-
* LIKE-scan fallback used when FTS5 is unavailable.
|
|
4459
|
-
*/
|
|
4460
|
-
declare const scoreDocument: (text: string, tokens: ReadonlyArray<string>) => number;
|
|
4461
4440
|
/**
|
|
4462
4441
|
* Ordering/visual weight of a security finding — mirrors the studio's insight
|
|
4463
4442
|
* severities so the Security Advisor and the Performance Advisor (Insights) share
|
|
@@ -7880,4 +7859,4 @@ interface WhereSqlStrategy {
|
|
|
7880
7859
|
* `undefined` when the input imposes no constraint (empty `where`).
|
|
7881
7860
|
*/
|
|
7882
7861
|
declare const compileWhereSql: (where: WhereInput | undefined, strategy: WhereSqlStrategy) => SQL | undefined;
|
|
7883
|
-
export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, AGGREGATE_SQL_FUNCTION, AUTH_METRICS_BUCKETS_TABLE, AUTH_METRICS_BUCKET_MS, AUTH_METRICS_BUCKET_RETENTION, AUTH_METRICS_TABLE, type AdvisoriesResult, type AdvisoryFinding, type AggregateIndexDefinitionLike, type AggregateOp, type AggregateOptions, type AggregateResult, type AggregateTally, type ApplyOnDeleteOptions, type AuditEntry, type AuditLogResult, type AuthMetrics, type AuthMetricsBucket, type BroadcastDelta, CDC_LOG_TABLE, type CacheEntry, type CapturedMailRow, type CdcChange, type Clock, type ColumnMeta, type ColumnMetaLike, ConflictError, type ContextMetrics, type ContextTracer, type CountArgs, CountRlsUnsupportedError, type CtxDbOptions, DATA_MIGRATION_STATE_TABLE, DEFAULT_MAX_RELATION_KEYS, 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, FUNCTION_METRICS_BUCKETS_TABLE, FUNCTION_METRICS_BUCKET_MS, FUNCTION_METRICS_BUCKET_RETENTION, FUNCTION_METRICS_INDEX_TABLE, FUNCTION_METRICS_TABLE, type FacetColumnOptions, type FacetColumnResult, type FacetValue, type FieldOperators, type FlagEvaluation, type FlagsResult, type FunctionCallStat, type FunctionMetricBucket, type FunctionMetricIndexHit, type FunctionStatsResult, GEO_DEFAULT_PRECISION, type GeoBoundingBox, type GeoFilterBuilderLike, type GeoIndexDefinitionLike, type GeoPoint, type GroupByEntry, type GroupByOptions, type HibernatableWebSocket, type IdGenerator, type ImportError, type ImportShardAdminArgs, type ImportShardArgs, type ImportShardResult, type IncrementalMaterializeResult, type IndexDefinitionLike, type IndexRangeBuilderLike, LogBuffer, type LogEntry, type LogEventInput, type LogLevel, type LogSink, MAIL_RETENTION, MAIL_TABLE, MAX_SQL_ROWS, MIN_ADMIN_TOKEN_LENGTH, MIN_AUTH_SECRET_LENGTH, type MaskColumnMetadata, type MaskPoliciesResult, type MaterializeResult, type MetricsDeps, type MigrationDirection, type MigrationRunResult, type MigrationStatus, type MigrationStatusRow, type MutationDelta, type NestedWith, NotFoundError, NotUniqueError, type OnDeleteActionLike, type OrderByInput, type OrderKey, type PaginationOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type QueryArgs, type QueryPage, type QueueMetadata, type QueuesResult, RANK_TIEBREAK, RELATION_FUNCTION_PREFIX, RLS_UNWRAP_SYMBOL, ROOT_DO_SIZE_WARN_BYTES, ROOT_SHARD_NAME, type RankDirection, type RankIndexDefinitionLike, type RankOptions, type RankPage, type RankPageOptions, type RankPageRow, type RankPageRowKey, type RankResult, type RankSortKeyLike, ReactiveCache, type ReactiveCacheOptions, type ReadHook, type ReadTablePageOptions, type RecordAuthEventInput, type RecordFunctionMetricInput, type RecordMailInput, type RelationDefinitionLike, type RenderedSql, type ResolveRelationPredicatesOptions, type ResolveWithOptions, type RestrictableQueryOptions, type RlsPoliciesResult, type RlsPolicyMetadata, RlsRequiredError, type RlsRoleMetadata, type RpcRequest, type RunDataMigrationOptions, type RunShardApplyCdcArgs, type RunShardApplyCdcResult, type RunShardBulkDeleteArgs, type RunShardBulkDeleteResult, type RunShardExportArgs, type RunShardImportArgs, type RunShardMigrationArgs, type RunShardRankBeforeArgs, type RunShardRankPageArgs, type RunShardWriteArgs, type RunShardWriteResult, type RunTriggersOptions, SCAN_DEP, SESSION_DO_TTL_DEFAULT, SHARD_REGISTRY_DO_NAME, type SchedulableWorkflowReferenceLike, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type SearchFilterBuilderLike, type SecurityAuditResult, type SecurityFinding, type SecurityFindingKind, type SecurityFindingLevel, type SelectMatchingIdsOptions, type ServerDefaultContextLike, SessionDO, type SessionRecord, type SettingEntry, type SettingKind, type SettingsResult, type ShapeSubscriptionQuery, ShardDO, type ShardDOOptions, type ShardDOState, type ShardRankPageResult, ShardRegistryDO, type SocketAttachment, type SortDirection, type SourceClientLike, type SourceCursorLike, type SourceRefresh, type SpanHandle, type SqlConsoleResult, type SqlCursor, type SqlEngine, type SqlExec, type StorageRuleMetadata, type StorageRulesResult, type StudioFeaturesResult, type SubscriptionEnvelope, type SubscriptionOutcome, type SubscriptionQuery, 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 TelemetrySink, type TraceAnchor, type TracerDeps, type TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, type TtlSweepSpec, type ValidatorLike, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, aggregateSqlFunction, aggregateTableName, applyCdcChanges, applyOnDelete, applySelect, armRestore, assertFlatPredicate, assertReadonly, assertShapeShardable, assertValidClientId, backfillAggregateIndexes, backfillRankIndexes,
|
|
7862
|
+
export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, AGGREGATE_SQL_FUNCTION, AUTH_METRICS_BUCKETS_TABLE, AUTH_METRICS_BUCKET_MS, AUTH_METRICS_BUCKET_RETENTION, AUTH_METRICS_TABLE, type AdvisoriesResult, type AdvisoryFinding, type AggregateIndexDefinitionLike, type AggregateOp, type AggregateOptions, type AggregateResult, type AggregateTally, type ApplyOnDeleteOptions, type AuditEntry, type AuditLogResult, type AuthMetrics, type AuthMetricsBucket, type BroadcastDelta, CDC_LOG_TABLE, type CacheEntry, type CapturedMailRow, type CdcChange, type Clock, type ColumnMeta, type ColumnMetaLike, ConflictError, type ContextMetrics, type ContextTracer, type CountArgs, CountRlsUnsupportedError, type CtxDbOptions, DATA_MIGRATION_STATE_TABLE, DEFAULT_MAX_RELATION_KEYS, 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, FUNCTION_METRICS_BUCKETS_TABLE, FUNCTION_METRICS_BUCKET_MS, FUNCTION_METRICS_BUCKET_RETENTION, FUNCTION_METRICS_INDEX_TABLE, FUNCTION_METRICS_TABLE, type FacetColumnOptions, type FacetColumnResult, type FacetValue, type FieldOperators, type FlagEvaluation, type FlagsResult, type FunctionCallStat, type FunctionMetricBucket, type FunctionMetricIndexHit, type FunctionStatsResult, GEO_DEFAULT_PRECISION, type GeoBoundingBox, type GeoFilterBuilderLike, type GeoIndexDefinitionLike, type GeoPoint, type GroupByEntry, type GroupByOptions, type HibernatableWebSocket, type IdGenerator, type ImportError, type ImportShardAdminArgs, type ImportShardArgs, type ImportShardResult, type IncrementalMaterializeResult, type IndexDefinitionLike, type IndexRangeBuilderLike, LogBuffer, type LogEntry, type LogEventInput, type LogLevel, type LogSink, MAIL_RETENTION, MAIL_TABLE, MAX_SQL_ROWS, MIN_ADMIN_TOKEN_LENGTH, MIN_AUTH_SECRET_LENGTH, type MaskColumnMetadata, type MaskPoliciesResult, type MaterializeResult, type MetricsDeps, type MigrationDirection, type MigrationRunResult, type MigrationStatus, type MigrationStatusRow, type MutationDelta, type NestedWith, NotFoundError, NotUniqueError, type OnDeleteActionLike, type OrderByInput, type OrderKey, type PaginationOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type QueryArgs, type QueryPage, type QueueMetadata, type QueuesResult, RANK_TIEBREAK, RELATION_FUNCTION_PREFIX, RLS_UNWRAP_SYMBOL, ROOT_DO_SIZE_WARN_BYTES, ROOT_SHARD_NAME, type RankDirection, type RankIndexDefinitionLike, type RankOptions, type RankPage, type RankPageOptions, type RankPageRow, type RankPageRowKey, type RankResult, type RankSortKeyLike, ReactiveCache, type ReactiveCacheOptions, type ReadHook, type ReadTablePageOptions, type RecordAuthEventInput, type RecordFunctionMetricInput, type RecordMailInput, type RelationDefinitionLike, type RenderedSql, type ResolveRelationPredicatesOptions, type ResolveWithOptions, type RestrictableQueryOptions, type RlsPoliciesResult, type RlsPolicyMetadata, RlsRequiredError, type RlsRoleMetadata, type RpcRequest, type RunDataMigrationOptions, type RunShardApplyCdcArgs, type RunShardApplyCdcResult, type RunShardBulkDeleteArgs, type RunShardBulkDeleteResult, type RunShardExportArgs, type RunShardImportArgs, type RunShardMigrationArgs, type RunShardRankBeforeArgs, type RunShardRankPageArgs, type RunShardWriteArgs, type RunShardWriteResult, type RunTriggersOptions, SCAN_DEP, SESSION_DO_TTL_DEFAULT, SHARD_REGISTRY_DO_NAME, type SchedulableWorkflowReferenceLike, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type SearchFilterBuilderLike, type SearchIndexDefinitionLike, type SecurityAuditResult, type SecurityFinding, type SecurityFindingKind, type SecurityFindingLevel, type SelectMatchingIdsOptions, type ServerDefaultContextLike, SessionDO, type SessionRecord, type SettingEntry, type SettingKind, type SettingsResult, type ShapeSubscriptionQuery, ShardDO, type ShardDOOptions, type ShardDOState, type ShardRankPageResult, ShardRegistryDO, type SocketAttachment, type SortDirection, type SourceClientLike, type SourceCursorLike, type SourceRefresh, type SpanHandle, type SqlConsoleResult, type SqlCursor, type SqlEngine, type SqlExec, type StorageRuleMetadata, type StorageRulesResult, type StudioFeaturesResult, type SubscriptionEnvelope, type SubscriptionOutcome, type SubscriptionQuery, 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 TelemetrySink, type TraceAnchor, type TracerDeps, type TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, type TtlSweepSpec, type ValidatorLike, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, aggregateSqlFunction, aggregateTableName, applyCdcChanges, applyOnDelete, applySelect, armRestore, assertFlatPredicate, assertReadonly, assertShapeShardable, assertValidClientId, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, boundingBoxGeohashes, buildSecurityAudit, buildSeekWhere, clearCapturedMail, coerceAggregateNumber, compileWhereSql, containsRelationPredicate, coveringGeohashes, createDependencyTracker, createMetrics, createShardCtxDb, createSystemReader, createTracer, decodeCursor, depKey, diffExternalSource, dispatchRootSpan, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, ensureAuthMetricsTables, ensureFunctionMetricsTables, ensureMailTable, exportShardRows, exportShardTable, facetColumn, fanOutScalarCounts, foldAggregateTally, guardWriter, hasTrigger, haversineMeters, importShardRows, isRelationPredicate, isSoftDeleted, isSourceDue, liftSourceId, listTables, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, mergeWhere, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, parseExportShardArgs, parseImportShardArgs, planAggregateLookup, pointInBoundingBox, pullExternalSourceIncrementalTick, pullExternalSourceTick, rankTableName, reactiveCacheKey, readAggregateValue, readAuthMetrics, readBookmark, readCapturedMail, readCdcChanges, readExternalSourceBaseline, readFunctionMetricBuckets, readFunctionMetricIndexHits, readFunctionMetrics, readFunctionMetricsTotals, readMigrationStatus, readTablePage, recordAuthEvent, recordCapturedMail, recordFunctionMetric, renderSql, resolveRankPartition, resolveRelationPredicates, resolveWith, runDataMigration, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, serveRelationFanout, softDeleteScope, sortColumnName, stableStringify, stableWireKey, subscriptionListDeltas, throwingScheduler, trimCdcChanges, validateImportRow };
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{exportShardRows as o,exportShardTable as t,importShardRows as a,parseExportShardArgs as n,parseImportShardArgs as
|
|
1
|
+
import{exportShardRows as o,exportShardTable as t,importShardRows as a,parseExportShardArgs as n,parseImportShardArgs as s,selectExportTables as i,validateImportRow as l}from"./packem_shared/exportShardRows-kt42wijd.mjs";import{AGGREGATE_SQL_FUNCTION as T,aggregateSqlFunction as d,matchesStaticWhere as p,normalizeCountArgument as E,throwingScheduler as S}from"./packem_shared/AGGREGATE_SQL_FUNCTION-QYaiuty4.mjs";import{aggregateTableName as m,coerceAggregateNumber as u,encodeAggregateKey as x,foldAggregateTally as I,readAggregateValue as f}from"./packem_shared/aggregateTableName-G-eXyjcz.mjs";import{CountRlsUnsupportedError as A,mergeWhere as C,planAggregateLookup as N,selectIndexForAggregate as g,selectIndexForCount as M,selectIndexForGroupBy as h}from"./packem_shared/CountRlsUnsupportedError-Cl8XpYDL.mjs";import{AUTH_METRICS_BUCKETS_TABLE as F,AUTH_METRICS_BUCKET_MS as L,AUTH_METRICS_BUCKET_RETENTION as U,AUTH_METRICS_TABLE as D,ensureAuthMetricsTables as B,readAuthMetrics as b,recordAuthEvent as y}from"./packem_shared/AUTH_METRICS_BUCKETS_TABLE-D0wNaez7.mjs";import{c as K,a as G,d as P}from"./packem_shared/context-telemetry-BFO0N_e4.mjs";import{NotUniqueError as W,assertValidClientId as v,createShardCtxDb as w,normalizeIdStructurally as X}from"./packem_shared/NotUniqueError-BDYkMtJP.mjs";import{DATA_MIGRATION_STATE_TABLE as z,readMigrationStatus as Y,runDataMigration as V}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-CaO6L0Ee.mjs";import{SCAN_DEP as Z,createDependencyTracker as j,depKey as J}from"./packem_shared/SCAN_DEP-D_yR9EeV.mjs";import{renderSql as ee}from"./packem_shared/renderSql-B5lF5Jd9.mjs";import{diffExternalSource as oe}from"./packem_shared/diffExternalSource-DMpkJta1.mjs";import{materializeExternalRows as ae,materializeExternalRowsIncremental as ne,readExternalSourceBaseline as se,runExternalSourceTick as ie}from"./packem_shared/materializeExternalRows-BUmj_9WO.mjs";import{isSoftDeleted as ce,isSourceDue as Te,liftSourceId as de,pullExternalSourceIncrementalTick as pe,pullExternalSourceTick as Ee}from"./packem_shared/isSoftDeleted-juJOq515.mjs";import{FUNCTION_METRICS_BUCKETS_TABLE as _e,FUNCTION_METRICS_BUCKET_MS as me,FUNCTION_METRICS_BUCKET_RETENTION as ue,FUNCTION_METRICS_INDEX_TABLE as xe,FUNCTION_METRICS_TABLE as Ie,ensureFunctionMetricsTables as fe,readFunctionMetricBuckets as Re,readFunctionMetricIndexHits as Ae,readFunctionMetrics as Ce,readFunctionMetricsTotals as Ne,recordFunctionMetric as ge}from"./packem_shared/FUNCTION_METRICS_BUCKETS_TABLE-BPPeqM11.mjs";import{GEO_DEFAULT_PRECISION as he,boundingBoxGeohashes as Oe,coveringGeohashes as Fe,encodeGeohash as Le,haversineMeters as Ue,pointInBoundingBox as De}from"./packem_shared/GEO_DEFAULT_PRECISION-okRCkZ6r.mjs";import{ADMIN_FUNCTIONS as be,ADMIN_FUNCTION_PREFIX as ye,FLAGS_FUNCTION_PREFIX as ke,RELATION_FUNCTION_PREFIX as Ke,facetColumn as Ge,listTables as Pe,readTablePage as He,selectMatchingIds as We}from"./packem_shared/ADMIN_FUNCTIONS-PxZ8Lr9e.mjs";import{LogBuffer as we}from"./packem_shared/LogBuffer-bIvCelI-.mjs";import{MAIL_RETENTION as qe,MAIL_TABLE as ze,clearCapturedMail as Ye,ensureMailTable as Ve,readCapturedMail as Qe,recordCapturedMail as Ze}from"./packem_shared/MAIL_RETENTION-KmozO2NQ.mjs";import{default as Je}from"./packem_shared/NotFoundError-J3tjf4Uo.mjs";import{armRestore as er,readBookmark as rr}from"./packem_shared/armRestore-BNzdvQ_o.mjs";import{applySelect as tr,buildSeekWhere as ar,decodeCursor as nr,encodeCursor as sr,normalizeOrderKeys as ir,softDeleteScope as lr}from"./packem_shared/applySelect-B0CF8T7y.mjs";import{RANK_TIEBREAK as Tr,encodePartitionKey as dr,matchesRankStaticWhere as pr,rankTableName as Er,resolveRankPartition as Sr,sortColumnName as _r}from"./packem_shared/RANK_TIEBREAK-DtX8zQyc.mjs";import{ReactiveCache as ur,reactiveCacheKey as xr}from"./packem_shared/ReactiveCache-1_9Rs7J_.mjs";import{serveRelationFanout as fr}from"./packem_shared/serveRelationFanout-Ct5D2Tbk.mjs";import{DEFAULT_MAX_RELATION_KEYS as Ar,assertFlatPredicate as Cr,assertShapeShardable as Nr,containsRelationPredicate as gr,isRelationPredicate as Mr,resolveRelationPredicates as hr}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-BcW3nUKL.mjs";import{applyOnDelete as Fr,fanOutScalarCounts as Lr,resolveWith as Ur,runRowValidators as Dr}from"./packem_shared/applyOnDelete-CafQWSqu.mjs";import{RLS_UNWRAP_SYMBOL as br,RlsRequiredError as yr,guardWriter as kr}from"./packem_shared/RLS_UNWRAP_SYMBOL-C6_WX3dG.mjs";import{o as Gr,c as Pr,_ as Hr}from"./packem_shared/security-audit-BKUOgE0x.mjs";import{SESSION_DO_TTL_DEFAULT as vr,SessionDO as wr}from"./packem_shared/SESSION_DO_TTL_DEFAULT-GvBy_DBz.mjs";import{ROOT_DO_SIZE_WARN_BYTES as qr,ROOT_SHARD_NAME as zr,ShardDO as Yr}from"./packem_shared/ROOT_DO_SIZE_WARN_BYTES-ChulUZTK.mjs";import{SHARD_REGISTRY_DO_NAME as Qr,ShardRegistryDO as Zr}from"./packem_shared/SHARD_REGISTRY_DO_NAME-Caa0fR4N.mjs";import{MAX_SQL_ROWS as Jr,assertReadonly as $r,runReadonlySql as eo}from"./packem_shared/MAX_SQL_ROWS-Bdu25ASB.mjs";import{createSystemReader as oo}from"./packem_shared/createSystemReader-DcDcrtM3.mjs";import{ConflictError as ao}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{hasTrigger as so,runTriggers as io}from"./packem_shared/hasTrigger-_rexbWMO.mjs";import{selectExpiredIds as co}from"./packem_shared/selectExpiredIds-BXJDiUtz.mjs";import{compileWhereSql as po}from"./packem_shared/compileWhereSql-BLcfs4QW.mjs";import{CDC_LOG_TABLE as So,applyCdcChanges as _o,readCdcChanges as mo,trimCdcChanges as uo}from"./packem_shared/CDC_LOG_TABLE-E_J5LPoK.mjs";import{H as Io,P as fo,X as Ro}from"./packem_shared/ctx-db-backfill-C4rAzsQo.mjs";import{runShardMigrations as Co}from"./packem_shared/runShardMigrations-CcSFXtXZ.mjs";import{stableStringify as go}from"./packem_shared/stableStringify-BjLh4gvA.mjs";import{stableWireKey as ho}from"./packem_shared/stableWireKey-YEHLaX6X.mjs";import{subscriptionListDeltas as Fo}from"./packem_shared/subscriptionListDeltas-Bs69JbA8.mjs";export{be as ADMIN_FUNCTIONS,ye as ADMIN_FUNCTION_PREFIX,T as AGGREGATE_SQL_FUNCTION,F as AUTH_METRICS_BUCKETS_TABLE,L as AUTH_METRICS_BUCKET_MS,U as AUTH_METRICS_BUCKET_RETENTION,D as AUTH_METRICS_TABLE,So as CDC_LOG_TABLE,ao as ConflictError,A as CountRlsUnsupportedError,z as DATA_MIGRATION_STATE_TABLE,Ar as DEFAULT_MAX_RELATION_KEYS,ke as FLAGS_FUNCTION_PREFIX,_e as FUNCTION_METRICS_BUCKETS_TABLE,me as FUNCTION_METRICS_BUCKET_MS,ue as FUNCTION_METRICS_BUCKET_RETENTION,xe as FUNCTION_METRICS_INDEX_TABLE,Ie as FUNCTION_METRICS_TABLE,he as GEO_DEFAULT_PRECISION,we as LogBuffer,qe as MAIL_RETENTION,ze as MAIL_TABLE,Jr as MAX_SQL_ROWS,Gr as MIN_ADMIN_TOKEN_LENGTH,Pr as MIN_AUTH_SECRET_LENGTH,Je as NotFoundError,W as NotUniqueError,Tr as RANK_TIEBREAK,Ke as RELATION_FUNCTION_PREFIX,br as RLS_UNWRAP_SYMBOL,qr as ROOT_DO_SIZE_WARN_BYTES,zr as ROOT_SHARD_NAME,ur as ReactiveCache,yr as RlsRequiredError,Z as SCAN_DEP,vr as SESSION_DO_TTL_DEFAULT,Qr as SHARD_REGISTRY_DO_NAME,wr as SessionDO,Yr as ShardDO,Zr as ShardRegistryDO,d as aggregateSqlFunction,m as aggregateTableName,_o as applyCdcChanges,Fr as applyOnDelete,tr as applySelect,er as armRestore,Cr as assertFlatPredicate,$r as assertReadonly,Nr as assertShapeShardable,v as assertValidClientId,Io as backfillAggregateIndexes,fo as backfillRankIndexes,Ro as backfillSearchIndexes,Oe as boundingBoxGeohashes,Hr as buildSecurityAudit,ar as buildSeekWhere,Ye as clearCapturedMail,u as coerceAggregateNumber,po as compileWhereSql,gr as containsRelationPredicate,Fe as coveringGeohashes,j as createDependencyTracker,K as createMetrics,w as createShardCtxDb,oo as createSystemReader,G as createTracer,nr as decodeCursor,J as depKey,oe as diffExternalSource,P as dispatchRootSpan,x as encodeAggregateKey,sr as encodeCursor,Le as encodeGeohash,dr as encodePartitionKey,B as ensureAuthMetricsTables,fe as ensureFunctionMetricsTables,Ve as ensureMailTable,o as exportShardRows,t as exportShardTable,Ge as facetColumn,Lr as fanOutScalarCounts,I as foldAggregateTally,kr as guardWriter,so as hasTrigger,Ue as haversineMeters,a as importShardRows,Mr as isRelationPredicate,ce as isSoftDeleted,Te as isSourceDue,de as liftSourceId,Pe as listTables,pr as matchesRankStaticWhere,p as matchesStaticWhere,ae as materializeExternalRows,ne as materializeExternalRowsIncremental,C as mergeWhere,E as normalizeCountArgument,X as normalizeIdStructurally,ir as normalizeOrderKeys,n as parseExportShardArgs,s as parseImportShardArgs,N as planAggregateLookup,De as pointInBoundingBox,pe as pullExternalSourceIncrementalTick,Ee as pullExternalSourceTick,Er as rankTableName,xr as reactiveCacheKey,f as readAggregateValue,b as readAuthMetrics,rr as readBookmark,Qe as readCapturedMail,mo as readCdcChanges,se as readExternalSourceBaseline,Re as readFunctionMetricBuckets,Ae as readFunctionMetricIndexHits,Ce as readFunctionMetrics,Ne as readFunctionMetricsTotals,Y as readMigrationStatus,He as readTablePage,y as recordAuthEvent,Ze as recordCapturedMail,ge as recordFunctionMetric,ee as renderSql,Sr as resolveRankPartition,hr as resolveRelationPredicates,Ur as resolveWith,V as runDataMigration,ie as runExternalSourceTick,eo as runReadonlySql,Dr as runRowValidators,Co as runShardMigrations,io as runTriggers,co as selectExpiredIds,i as selectExportTables,g as selectIndexForAggregate,M as selectIndexForCount,h as selectIndexForGroupBy,We as selectMatchingIds,fr as serveRelationFanout,lr as softDeleteScope,_r as sortColumnName,go as stableStringify,ho as stableWireKey,Fo as subscriptionListDeltas,S as throwingScheduler,uo as trimCdcChanges,l as validateImportRow};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as h}from"@lunora/errors";import{distinctValues as O}from"./applyOnDelete-
|
|
1
|
+
import{LunoraError as h}from"@lunora/errors";import{distinctValues as O}from"./applyOnDelete-CafQWSqu.mjs";const k="__relationExists",f={every:{kind:"many",negateChild:!0,negated:!0},is:{kind:"one",negated:!1},isNot:{kind:"one",negated:!0,nullDisjunct:!0},none:{kind:"many",negated:!0},some:{kind:"many",negated:!1}},R=new Set(Object.keys(f)),A=e=>e.kind==="one"?{clause:e.field,project:e.references}:{clause:e.references,project:e.field},j=5e3,u=Symbol("relation-key-overflow"),b=e=>Array.isArray(e)?e.map(t=>t??{}):[],g=e=>{if(e.length===1){const[t]=e;return t??{}}return e.length===0?{}:{AND:e}},p=e=>{if(e===null||typeof e!="object"||Array.isArray(e))return!1;const t=Object.keys(e);return t.length>0&&t.every(n=>R.has(n))},d=(e,t,n)=>{const a=t.tables[n]?.relationMap??{};return Object.keys(e).some(s=>{const r=e[s];return s==="AND"||s==="OR"?b(r).some(o=>d(o,t,n)):s==="NOT"?d(r??{},t,n):!!a[s]&&p(r)})},I=(e,t,n,a)=>{if(e&&d(e,t,n))throw new h("INTERNAL",`relation-crossing predicates are not supported in ${a}() — use them in findMany/findFirst or an RLS read policy`)},E=async(e,t,n,a,s)=>{const r=await c(t,e.table,a),{page:o}=await a.fetcher(e.table,{baseWhere:a.relationBaseWhere?.(e.table),relationBaseWhere:a.relationBaseWhere,where:r}),i=O(o,n);if(i.length>a.maxRelationKeys){if(s)return u;throw new h("INTERNAL",`relation predicate on "${e.table}" matched ${String(i.length)} rows, exceeding the ${String(a.maxRelationKeys)}-key limit; narrow the predicate (a same-shard EXISTS push-down lifts this cap)`)}return i},T=async(e,t,n,a,s)=>{const r=f[e];if(!r)throw new h("INTERNAL",`unknown relation operator "${e}"`);const{clause:o,project:i}=A(t),l=await E(t,r.negateChild?{NOT:n}:n,i,a,s);return l===u?u:r.negated?r.nullDisjunct?{OR:[{[o]:{notIn:l}},{[o]:{isNull:!0}}]}:{[o]:{notIn:l}}:{[o]:{in:l}}},m=async(e,t,n,a,s)=>{const r=f[e];if(!r)throw new h("INTERNAL",`unknown relation operator "${e}"`);const o=s.relationBaseWhere?.(t.table),i=r.negateChild?{NOT:n}:n,l={childWhere:await c(o?{AND:[o,i]}:i,t.table,s),negated:r.negated,parentTable:a,relation:t};return{[k]:l}},$=(e,t,n)=>{const a=f[e];if(a&&a.kind!==n.kind)throw new h("INTERNAL",`relation operator "${e}" requires a to-${a.kind} relation, but "${t}" is to-${n.kind}`)},x=async(e,t,n,a,s)=>{const r=[];for(const o of Object.keys(n)){$(o,e,t);const i=n[o]??{},l=s.canPushExists?.(t)??!1;if(l&&s.existsPushMode==="always"){r.push(await m(o,t,i,a,s));continue}const w=await T(o,t,i,s,l);w===u?r.push(await m(o,t,i,a,s)):r.push(w)}return g(r)},S=async(e,t,n,a)=>{if(e==="AND"||e==="OR"){const r=[];for(const o of b(t))r.push(await c(o,n,a));return{[e]:r}}if(e==="NOT")return{NOT:await c(t??{},n,a)};const s=a.schema.tables[n]?.relationMap?.[e];return s&&p(t)?x(e,s,t,n,a):{[e]:t}},c=async(e,t,n)=>{const a=[];for(const s of Object.keys(e))a.push(await S(s,e[s],t,n));return g(a)},L=async(e,t)=>!e||!d(e,t.schema,t.tableName)?e:c(e,t.tableName,{canPushExists:t.canPushExists,existsPushMode:t.existsPushMode??"auto",fetcher:t.fetcher,maxRelationKeys:t.maxRelationKeys??j,relationBaseWhere:t.relationBaseWhere,schema:t.schema}),y=(e,t,n)=>{for(const a of e){const s=N(a,t,n);if(s)return s}},D=(e,t,n,a)=>{if(e==="AND"||e==="OR")return y(b(t),n,a);if(e==="NOT")return y([t??{}],n,a);const s=n.tables[a]?.relationMap?.[e];if(!(!s||!p(t)))return n.tables[s.table]?.shardMode?.kind==="shardBy"?{relation:e,target:s.table}:y(Object.values(t),n,s.table)},N=(e,t,n)=>{for(const a of Object.keys(e)){const s=D(a,e[a],t,n);if(s)return s}},M=(e,t,n)=>{if(!e)return;const a=N(e,t,n);if(a)throw Object.assign(new Error(`shape on "${n}" joins the sharded table "${a.target}" via relation "${a.relation}" — a live shape cannot replicate rows that live in another shard's Durable Object. Fix it by (a) denormalizing the joined columns into "${n}", or (b) moving "${a.target}" to .global() so it is served through the latency-tiered D1 shape tier.`),{code:"SHAPE_CROSS_SHARD_JOIN",name:"LunoraError",status:400})};export{j as DEFAULT_MAX_RELATION_KEYS,I as assertFlatPredicate,M as assertShapeShardable,d as containsRelationPredicate,p as isRelationPredicate,L as resolveRelationPredicates};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as A}from"@lunora/errors";import{searchTextUnchanged as Tt,ftsTableName as dt,FTS_ID_COLUMN as be,FTS_TEXT_COLUMN as Nt,analyzedSearchText as ct,createSearchBuilder as St,createSearchAnalyzer as Ve,planSearchPage as Rt,finishSearchPage as At,searchPageScan as It,resolveSearchScan as vt,assertSearchWithinCap as Ct,tokenizeSearch as ft,searchTermRange as kt,scoreDocument as Mt,MAX_SEARCH_SCAN as Lt}from"@lunora/search-core";import{sql as e}from"drizzle-orm";import{matchesStaticWhere as Fe,aggregateSqlFunction as Ne,normalizeCountArgument as xt,throwingScheduler as Ot}from"./AGGREGATE_SQL_FUNCTION-QYaiuty4.mjs";import{encodeAggregateKey as de,foldAggregateTally as Dt,aggregateTableName as Se,coerceAggregateNumber as qe,readAggregateValue as Ue}from"./aggregateTableName-G-eXyjcz.mjs";import{mergeWhere as re,CountRlsUnsupportedError as Pe,selectIndexForGroupBy as Wt,selectIndexForCount as Bt,selectIndexForAggregate as Ft}from"./CountRlsUnsupportedError-Cl8XpYDL.mjs";import{Y as qt}from"./ctx-db-backfill-C4rAzsQo.mjs";import{o as fi,H as ui,P as hi,X as $i}from"./ctx-db-backfill-C4rAzsQo.mjs";import{appendCdcChange as Ut}from"./CDC_LOG_TABLE-E_J5LPoK.mjs";import{CDC_LOG_TABLE as mi,applyCdcChanges as wi,bumpCdcEpoch as gi,minCdcSeq as Ei,readCdcChanges as bi,readCdcCursor as yi,readCdcEpoch as _i,trimCdcChanges as Ti}from"./CDC_LOG_TABLE-E_J5LPoK.mjs";import{r as M}from"./do-exec-BLe9lLrN.mjs";import{b as ut,s as Z,g as he,a as ce,_ as te,m as X,T as ht,E as Le,$ as ee,l as Pt,L as $t,N as pt,S as Xe}from"./do-sql-x0AjZhaN.mjs";import{param as Ye}from"./renderSql-B5lF5Jd9.mjs";import{encodeGeohash as Ht,GEO_DEFAULT_PRECISION as jt,coveringGeohashes as Gt,boundingBoxGeohashes as Jt,pointInBoundingBox as Vt,haversineMeters as Yt}from"./GEO_DEFAULT_PRECISION-okRCkZ6r.mjs";import{sortColumnName as Ae,matchesRankStaticWhere as mt,encodePartitionKey as De,rankTableName as Ie,resolveRankPartition as wt,RANK_TIEBREAK as me}from"./RANK_TIEBREAK-DtX8zQyc.mjs";import{t as fe}from"./serialize-sql-DiRzL7A4.mjs";import{SCAN_DEP as Q}from"./SCAN_DEP-D_yR9EeV.mjs";import{decodeCursor as Oe,normalizeOrderKeys as zt,buildSeekWhere as gt,applySelect as Ze,encodeCursor as Ge,softDeleteScope as Ee,buildSeekBeforeWhere as Kt}from"./applySelect-B0CF8T7y.mjs";import Qt from"./NotFoundError-J3tjf4Uo.mjs";import{assertFlatPredicate as He,resolveRelationPredicates as et}from"./DEFAULT_MAX_RELATION_KEYS-BcW3nUKL.mjs";import{runRowValidators as je,resolveWith as tt,applyOnDelete as Xt,fanOutScalarCounts as Zt}from"./applyOnDelete-CafQWSqu.mjs";import{guardWriter as en}from"./RLS_UNWRAP_SYMBOL-C6_WX3dG.mjs";import{createSystemReader as tn}from"./createSystemReader-DcDcrtM3.mjs";import{ConflictError as Re}from"./ConflictError-C8GtJmjS.mjs";import{runTriggers as nn}from"./hasTrigger-_rexbWMO.mjs";import{compileWhereSql as ue}from"./compileWhereSql-BLcfs4QW.mjs";import{e as Si,t as Ri,r as Ai,o as Ii,l as vi,p as Ci,_ as ki,a as Mi,b as Li,d as xi,m as Oi,u as Di,S as Wi,T as Bi}from"./ctx-db-idempotency-wiVoGnpQ.mjs";import{runShardMigrations as qi}from"./runShardMigrations-CcSFXtXZ.mjs";import{a as Pi,s as Hi}from"./ctx-db-shapes-CHC2cS0g.mjs";const on=(o,r,n)=>[...o.partitionBy??[],...o.sortBy.map(l=>l.field),...o.where?Object.keys(o.where):[]].every(l=>r[l]===n[l]),rn=(o,r,n,l,s,c)=>{if(s&&c&&on(n,s,c))return;const E=Ie(r,n.name);if(s&&M(o,e`DELETE FROM ${e.identifier(E)} WHERE ${e.identifier("__id__")} = ${l}`),!c||n.where&&!mt(c,n.where))return;const m=n.sortBy.map((b,h)=>Ae(h)),_=e.join(["__id__","__partition__",...m].map(b=>e.identifier(b)),e`, `),v=De(n.partitionBy??[],c),L=n.sortBy.map(b=>fe(c[b.field]??null)),T=e.join([l,v,...L].map(b=>Ye(b)),e`, `);M(o,e`INSERT INTO ${e.identifier(E)} (${_}) VALUES (${T})`)},an=o=>{const{broadcast:r,invalidateCache:n,recordCdc:l,schema:s,sql:c}=o,E=new Set,m=new Set,_=(N,w)=>{const S=`${N}::${w.name}`;if(E.has(S))return;const F=Se(N,w.name),W=w.by??[],j=new Map,q=M(c,e`SELECT id, _creationTime, ${e.identifier(Z)} FROM ${e.identifier(N)}`).toArray();for(const U of q){const x=he(U);if(!x||w.where&&!Fe(x,w.where))continue;const G=de(W,x);Dt(j,G,w,x)}M(c,e`DELETE FROM ${e.identifier(F)}`);const J=32,B=[...j];for(let U=0;U<B.length;U+=J){const x=B.slice(U,U+J),G=e.join(x.map(([H,Y])=>e`(${H}, ${Y.value}, ${Y.count})`),e`, `);M(c,e`INSERT INTO ${e.identifier(F)} (${ce}, ${te}, ${X}) VALUES ${G}`)}E.add(S)},v=(N,w,S)=>{const F=w.by??[],W=Ne(w.op),j=w.field??"",q=[];for(const U of F){const x=fe(S[U]??null);x===null?q.push(e`${ee(U)} IS NULL`):q.push(e`${ee(U)} = ${x}`)}for(const[U,x]of Object.entries(w.where??{})){const G=x!==null&&typeof x=="object"&&!Array.isArray(x)?x.eq:x,H=fe(G);H===null?q.push(e`${ee(U)} IS NULL`):q.push(e`${ee(U)} = ${H}`)}const J=q.length>0?e` WHERE ${e.join(q,e` AND `)}`:e``,B=ee(j);return{value:M(c,e`SELECT ${e.raw(W)}(${B}) AS value FROM ${e.identifier(N)}${J}`).one().value??null}},L=(N,w,S,F)=>{const W=Se(N,w.name),{op:j}=w,q=w.field??"",J=x=>{M(c,e`DELETE FROM ${e.identifier(W)} WHERE ${ce} = ${x} AND ${X} <= 0`)},B=S&&(!w.where||Fe(S,w.where))?S:void 0,U=F&&(!w.where||Fe(F,w.where))?F:void 0;if(!(!B&&!U)){if(j==="count"){for(const[x,G]of[[B,-1],[U,1]]){if(!x)continue;const H=de(w.by??[],x);M(c,Le(W,H,G,G,e`${te} = ${te} + excluded.${te}, ${X} = ${X} + excluded.${X}`))}B&&J(de(w.by??[],B));return}if(j==="sum"||j==="avg"){for(const[x,G]of[[B,-1],[U,1]]){if(!x)continue;const H=qe(x[q]);if(H===void 0)continue;const Y=de(w.by??[],x);M(c,Le(W,Y,G*H,G,e`${te} = COALESCE(${te}, 0) + excluded.${te}, ${X} = ${X} + excluded.${X}`))}B&&J(de(w.by??[],B));return}if(B){const x=de(w.by??[],B),G=qe(B[q]),H=M(c,e`SELECT ${te} AS value, ${X} AS count FROM ${e.identifier(W)} WHERE ${ce} = ${x}`).toArray()[0],Y=(H?.count??0)-1;if(Y<=0)M(c,e`DELETE FROM ${e.identifier(W)} WHERE ${ce} = ${x}`);else if(H&&G!==void 0&&H.value!==null&&G===H.value){const ie=v(N,w,B);M(c,e`UPDATE ${e.identifier(W)} SET ${te} = ${ie.value}, ${X} = ${Y} WHERE ${ce} = ${x}`)}else M(c,e`UPDATE ${e.identifier(W)} SET ${X} = ${X} - 1 WHERE ${ce} = ${x}`)}if(U){const x=de(w.by??[],U),G=qe(U[q]);if(G===void 0)M(c,Le(W,x,null,1,e`${X} = ${X} + 1`));else{const H=j==="min"?"MIN":"MAX";M(c,Le(W,x,G,1,e`${te} = ${e.raw(H)}(COALESCE(${te}, excluded.${te}), excluded.${te}), ${X} = ${X} + 1`))}}}},T=N=>{const w=s.tables[N]?.aggregateIndexes;if(!(!w||w.length===0))for(const S of w)_(N,S)},b=(N,w,S)=>{const F=s.tables[N]?.aggregateIndexes;if(!(!F||F.length===0))for(const W of F)L(N,W,w,S)},h=(N,w)=>{const S=`${N}::rank::${w.name}`;if(m.has(S))return;const F=Ie(N,w.name),W=M(c,e`SELECT id, _creationTime, ${e.identifier(Z)} FROM ${e.identifier(N)}`).toArray();M(c,e`DELETE FROM ${e.identifier(F)}`);const j=w.sortBy.map((J,B)=>Ae(B)),q=e.join(["__id__","__partition__",...j].map(J=>e.identifier(J)),e`, `);for(const J of W){const B=he(J);if(!B||w.where&&!mt(B,w.where))continue;const U=De(w.partitionBy??[],B),x=w.sortBy.map(H=>fe(B[H.field]??null)),G=e.join([B._id,U,...x].map(H=>Ye(H)),e`, `);M(c,e`INSERT INTO ${e.identifier(F)} (${q}) VALUES (${G})`)}m.add(S)},k=N=>{const w=s.tables[N]?.rankIndexes;if(!(!w||w.length===0))for(const S of w)h(N,S)},C=(N,w,S,F)=>{const W=s.tables[N]?.rankIndexes;if(!(!W||W.length===0))for(const j of W)rn(c,N,j,w,S,F)},I=(N,w,S,F)=>{const W=s.tables[N]?.searchIndexes;if(!(!W||W.length===0||!ut(c)))for(const j of W){if(Tt(F,S,j))continue;const q=dt(N,j.name);M(c,e`DELETE FROM ${e.identifier(q)} WHERE ${e.identifier(be)} = ${w}`),S&&M(c,e`INSERT INTO ${e.identifier(q)} (${e.identifier(Nt)}, ${e.identifier(be)}) VALUES (${ct(S,j)}, ${w})`)}},P=(N,w,S)=>{const F=s.tables[N]?.geoIndexes;if(!(!F||F.length===0))for(const W of F){const j=ht(N,W.name);M(c,e`DELETE FROM ${e.identifier(j)} WHERE ${e.identifier("__id__")} = ${w}`);const q=S?.[W.field];if(q!==null&&typeof q=="object"&&typeof q.lat=="number"&&typeof q.lng=="number"){const{lat:J,lng:B}=q,U=Ht({lat:J,lng:B},W.precision??jt);M(c,e`INSERT INTO ${e.identifier(j)} (${e.identifier("__id__")}, ${e.identifier("__geohash__")}, ${e.identifier("__lat__")}, ${e.identifier("__lng__")}) VALUES (${w}, ${U}, ${J}, ${B})`)}}};return{ensureBackfilledForTable:T,ensureBackfilledIndex:_,ensureRankBackfilled:h,ensureRankBackfilledForTable:k,syncAggregates:b,syncCompanionsForInsert:(N,w,S)=>{I(N,w,S),P(N,w,S),b(N,void 0,S),C(N,w,void 0,S),n(N,w),l(N,w,"insert",S),r({key:w,op:"insert",row:S,table:N})},syncGeo:P,syncRanks:C,syncSearch:I}},sn="__doc__",ln=o=>{const r=JSON.stringify(o),n=new TextEncoder().encode(r);let l="";for(const s of n)l+=String.fromCodePoint(s);return btoa(l)},dn=o=>o.after?[o.after.partitionKey,...o.after.sortValues,o.after.rowId]:o.cursor?Oe(o.cursor):void 0,cn=(o,r,n)=>{if(o?.length!==1+r.length+1)return;const l=[{column:"__partition__",direction:"asc"}];for(const[c,E]of r.entries())l.push({column:E,direction:n[c]?.direction??"asc"});l.push({column:me,direction:"asc"});const s=[];for(const[c,E]of l.entries()){const m=[];for(const[v,L]of l.slice(0,c).entries())m.push(e`${e.identifier(L.column)} IS ${o[v]}`);m.push(e`${e.identifier(E.column)} ${e.raw(E.direction==="desc"?"<":">")} ${o[c]}`);const[_]=m;s.push(m.length===1&&_!==void 0?_:e`(${e.join(m,e` AND `)})`)}return e`(${e.join(s,e` OR `)})`},Et=null,fn=(o,r)=>{if(o===void 0)return Et;const n=[o.__partition__,...r.map(l=>o[l]),o[me]];return ln(n)},un=(o,r,n)=>{const l=[];for(const s of o){const c=s[me];if(typeof c!="string")continue;const E=r.get(c);if(!E)continue;const m=typeof s.__partition__=="string"?s.__partition__:"",_=n.map(v=>s[v]??null);l.push({doc:E,key:{partitionKey:m,rowId:c,sortValues:_}})}return l},hn=(o,r,n)=>{const{rowToDocument:l}=o,s=new Map;if(n.length===0)return s;const c=e.join(n.map(m=>Ye(m)),e`, `),E=M(o.sql,e`SELECT id, _creationTime, ${e.identifier(sn)} FROM ${e.identifier(r)} WHERE id IN (${c})`).toArray();for(const m of E){const _=l(m),v=m.id;_&&typeof v=="string"&&s.set(v,_)}return s},nt=(o,r,n,l)=>{const{assertRankPartitionLocal:s,ensureRankBackfilled:c,onRead:E,schema:m}=o,_=m.tables[r];if(!_)throw new A("INTERNAL",`unknown table: ${r}`);const v=_.rankIndexes?.find(Y=>Y.name===n);if(!v)throw new A("INTERNAL",`unknown rankIndex "${n}" on table "${r}"`);s(r,_,v),E(r,Q),c(r,v);const L=Ie(r,v.name),T=v.sortBy.map((Y,ie)=>Ae(ie)),b=Math.max(1,Math.min(1e3,Math.floor(l.take??100))),h=re(l.baseWhere,l.where),k=wt(v,h),C=[e`${e.identifier("__partition__")} ASC`];for(const[Y,ie]of T.entries()){const se=v.sortBy[Y]?.direction;C.push(e`${e.identifier(ie)} ${e.raw(se==="desc"?"DESC":"ASC")}`)}C.push(e`${e.identifier(me)} ASC`);const I=[];typeof l.partitionKey=="string"?I.push(e`${e.identifier("__partition__")} = ${l.partitionKey}`):k&&I.push(e`${e.identifier("__partition__")} = ${De(v.partitionBy??[],k)}`);const P=dn(l),N=cn(P,T,v.sortBy);N&&I.push(N);const w=e.identifier(me),S=e.identifier("__partition__"),F=I.length>0?e` WHERE ${e.join(I,e` AND `)}`:e``,W=T.length>0?e`${w}, ${S}, ${e.join(T.map(Y=>e.identifier(Y)),e`, `)}`:e`${w}, ${S}`,j=e`SELECT ${W} FROM ${e.identifier(L)}${F} ORDER BY ${e.join(C,e`, `)} LIMIT ${e.raw(String(b+1))}`,q=M(o.sql,j).toArray(),J=q.length>b,B=J?q.slice(0,b):q,U=B.map(Y=>Y[me]),x=un(B,hn(o,r,U),T),G=J?fn(B.at(-1),T):Et,H=v.sortBy.map(Y=>Y.direction==="desc"?"desc":"asc");return{continueCursor:G,directions:H,hasMore:J,rows:x}},$n=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,pn=o=>{if(!$n.test(o))throw new A("INTERNAL",`invalid clientId ${JSON.stringify(o)}: a client-supplied row id must be a UUID`)},it=50,bt=500,ge=(o,r,n)=>{const l=r??bt;if(o>l)throw new A("BATCH_LIMIT_EXCEEDED",`${n}: batch of ${String(o)} exceeds the limit of ${String(l)} (raise options.limit or chunk the call)`,{status:400})},mn=o=>{const r={eq:(n,l)=>(o.sqlConditions.push({comparator:"=",field:n,value:l}),r),gt:(n,l)=>(o.sqlConditions.push({comparator:">",field:n,value:l}),r),gte:(n,l)=>(o.sqlConditions.push({comparator:">=",field:n,value:l}),r),lt:(n,l)=>(o.sqlConditions.push({comparator:"<",field:n,value:l}),r),lte:(n,l)=>(o.sqlConditions.push({comparator:"<=",field:n,value:l}),r)};return r},wn=o=>Math.max(o,Lt),gn=(o,r,n,l,s)=>{const c=ft(n.query,Ve(n.definition.language));if(c.length===0)return[];const E=dt(r,n.indexName),m=`${E}__vocab`,_=c.length-1,v=c.map((C,I)=>{const P=kt(C,I===_),N=P.exact?e`${e.identifier("term")} = ${P.lower}`:e`${e.identifier("term")} >= ${P.lower} AND ${e.identifier("term")} < ${P.upper}`;return e`SELECT ${e.identifier("doc")}, ${e.raw(String(I))} AS ${e.identifier("__term__")}, COUNT(*) AS ${e.identifier("__n__")} FROM ${e.identifier(m)} WHERE ${N} GROUP BY ${e.identifier("doc")}`}),L=c.map((C,I)=>e`SUM(CASE WHEN u.${e.identifier("__term__")} = ${e.raw(String(I))} THEN u.${e.identifier("__n__")} ELSE 0 END)`),T=e`SELECT f.${e.identifier(be)} AS ${e.identifier(be)}, ${e.join(L,e` + `)} AS ${e.identifier("__score__")} FROM (${e.join(v,e` UNION ALL `)}) u JOIN ${e.identifier(E)} f ON f.rowid = u.${e.identifier("doc")} GROUP BY f.${e.identifier(be)} HAVING ${e.join(L.map(C=>e`${C} > 0`),e` AND `)}`,b=[];for(const C of n.filters)b.push(e`${ee(C.field)} = ${fe(C.value)}`);s&&b.push(s);let h=e`SELECT m.id, m._creationTime, m.${e.identifier(Z)} FROM (${T}) s JOIN ${e.identifier(r)} m ON m.id = s.${e.identifier(be)}`;b.length>0&&(h=e`${h} WHERE ${e.join(b,e` AND `)}`),h=e`${h} ORDER BY s.${e.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${e.raw(String(l))}`;const k=[];for(const C of M(o,h)){const I=pt(C);I&&k.push(I)}return k},En=(o,r,n,l,s)=>{const c=Ve(n.definition.language),E=ft(n.query,c);if(E.length===0)return[];const m=[];for(const T of n.filters)m.push(e`${ee(T.field)} = ${fe(T.value)}`);s&&m.push(s);let _=e`SELECT id, _creationTime, ${e.identifier(Z)} FROM ${e.identifier(r)}`;m.length>0&&(_=e`${_} WHERE ${e.join(m,e` AND `)}`),_=e`${_} ORDER BY _creationTime DESC, id ASC LIMIT ${e.raw(String(wn(l)))}`;const v=M(o,_).toArray(),L=[];for(const T of v){const b=pt(T);if(!b)continue;const h=Mt(ct(b,n.definition),E,c);h>0&&L.push({creationTime:typeof b._creationTime=="number"?b._creationTime:0,doc:b,id:typeof b._id=="string"?b._id:"",score:h})}return L.sort((T,b)=>b.score-T.score||b.creationTime-T.creationTime||T.id.localeCompare(b.id)),L.slice(0,l).map(T=>T.doc)},bn=(o,r)=>{const n=o,l={near:(s,c)=>{if(n.within)throw new A("INTERNAL",`geo index "${n.indexName}" on table "${r}": call .near() or .within(), not both`);return n.near={point:{lat:s.lat,lng:s.lng},radiusMeters:c},l},within:s=>{if(n.near)throw new A("INTERNAL",`geo index "${n.indexName}" on table "${r}": call .near() or .within(), not both`);return n.within={ne:{lat:s.ne.lat,lng:s.ne.lng},sw:{lat:s.sw.lat,lng:s.sw.lng}},l}};return l},yn=(o,r)=>{const n=o[r];if(n===null||typeof n!="object")return;const{lat:l,lng:s}=n;return typeof l=="number"&&typeof s=="number"?{lat:l,lng:s}:void 0},_n=(o,r)=>{const n=yn(o,r.definition.field);if(!n)return;const l=typeof o._creationTime=="number"?o._creationTime:0;if(r.near){const s=Yt(r.near.point,n);return s<=r.near.radiusMeters?{creationTime:l,distance:s}:void 0}return Vt(n,r.within)?{creationTime:l,distance:0}:void 0},Tn=(o,r,n,l,s)=>{if(!n.near&&!n.within)throw new A("INTERNAL",`geo index "${n.indexName}" on table "${r}": call .near(point, radius) or .within(box)`);const c=n.near?Gt(n.near.point,n.near.radiusMeters):Jt(n.within),E=ht(r,n.indexName),m=c.map(h=>e`(g.${e.identifier("__geohash__")} >= ${h} AND g.${e.identifier("__geohash__")} < ${`${h}{`})`),_=[e`(${e.join(m,e` OR `)})`];s&&_.push(s);const v=e`SELECT m.id, m._creationTime, m.${e.identifier(Z)} FROM ${e.identifier(E)} g JOIN ${e.identifier(r)} m ON m.id = g.${e.identifier("__id__")} WHERE ${e.join(_,e` AND `)}`,L=M(o,v).toArray(),T=[];for(const h of L){const k=he(h),C=k?_n(k,n):void 0;k&&C&&T.push({creationTime:C.creationTime,distance:C.distance,doc:k})}T.sort((h,k)=>h.distance-k.distance||k.creationTime-h.creationTime);const b=T.map(h=>h.doc);return typeof l=="number"?b.slice(0,Math.max(0,Math.floor(l))):b},Nn=(o,r,n,l,s)=>{const{geo:c}=n;if(!c)throw new A("INTERNAL","runGeoTerminal called without a staged geo query");const E=n.inMemoryFilters.length>0,m=Tn(o,r,c,E?void 0:s,l);if(!E)return m;const _=[];for(const v of m)if(n.inMemoryFilters.every(L=>L(v))&&(_.push(v),typeof s=="number"&&_.length>=s))break;return _},Sn=(o,r,n,l,s,c)=>{const E=[];for(const L of n.sqlConditions)E.push(e`${ee(L.field)} ${e.raw(L.comparator)} ${fe(L.value)}`);l&&E.push(l);let m=e`SELECT id, _creationTime, ${e.identifier(Z)} FROM ${e.identifier(r)}`;E.length>0&&(m=e`${m} WHERE ${e.join(E,e` AND `)}`),m=e`${m} ORDER BY ${s}`,typeof c=="number"&&n.inMemoryFilters.length===0&&(m=e`${m} LIMIT ${e.raw(String(Math.max(0,Math.floor(c))))}`);const _=M(o,m).toArray(),v=[];for(const L of _){const T=he(L);if(T&&n.inMemoryFilters.every(b=>b(T))&&(v.push(T),typeof c=="number"&&v.length>=c))break}return v},pe={fieldRef:ee,serialize:fe},Rn=o=>{let r=0;const n=[],l={fieldRef:ee,relationExists:s=>{const{childWhere:c,negated:E,parentTable:m,relation:_}=s,v=`__rel_${String(r)}`,L=n.at(-1)??m;r+=1,o(_.table,Q);const T=_.kind==="one"?_.field:_.references,b=_.kind==="one"?_.references:_.field,h=e`${Xe(v,b)} = ${Xe(L,T)}`;n.push(v);const k=ue(c,l);n.pop();const C=k?e`${h} AND ${k}`:h,I=e`EXISTS (SELECT 1 FROM ${e.identifier(_.table)} AS ${e.identifier(v)} WHERE ${C})`;return E?e`NOT ${I}`:I},serialize:fe};return l},yt=o=>{const r=o.map(n=>e`${ee(n.field)} ${e.raw(n.direction==="desc"?"DESC":"ASC")}`);return o.some(n=>n.field==="_id"||n.field==="id")||r.push(e`${ee("id")} ASC`),e.join(r,e`, `)},An={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},In=o=>{const r=o.order;return o.indexFields.length>0?o.indexFields.map(n=>({direction:r,field:n})):[{direction:r,field:"_creationTime"}]},vn=(o,r,n,l)=>{const s=o.sqlConditions.map(c=>({[c.field]:{[An[c.comparator]??"eq"]:c.value}}));if(n&&s.push(gt(r,Oe(n))),l&&s.push(Kt(r,Oe(l))),s.length!==0)return s.length===1?s[0]:{AND:s}},Cn=(o,r,n)=>{const l=[];for(const s of o){const c=he(s);if(c&&r.every(E=>E(c))&&(l.push(c),n!==void 0&&l.length>n))break}return l},kn=(o,r,n,l,s)=>{const c=Math.max(0,Math.floor(l.numItems)),E=In(n),m=typeof l.endCursor=="string",_=ue(vn(n,E,l.cursor,l.endCursor),pe),v=s&&_?e`${_} AND ${s}`:s??_;let L=e`SELECT id, _creationTime, ${e.identifier(Z)} FROM ${e.identifier(r)}`;v&&(L=e`${L} WHERE ${v}`),L=e`${L} ORDER BY ${yt(E)}`;const T=n.inMemoryFilters.length>0;!T&&!m&&(L=e`${L} LIMIT ${e.raw(String(c+1))}`);const b=M(o,L).toArray(),h=Cn(b,n.inMemoryFilters,T||m?void 0:c);if(m){const P=h.length>=2?h[Math.floor(h.length/2)-1]:void 0;return{continueCursor:l.endCursor??null,isDone:!0,page:h,splitCursor:P?Ge(P,E):null}}const k=h.length>c,C=k?h.slice(0,c):h,I=C.at(-1);return{continueCursor:k&&I?Ge(I,E):null,isDone:!k,page:C}};class Mn extends A{constructor(r="unique() found more than one matching document"){super("NOT_UNIQUE",r,{name:"NotUniqueError"})}}const Ln=/\s/u,xn=String.fromCodePoint(0),ot=(o,r,n)=>{if(!o.tables[r])throw new A("INTERNAL",`unknown table: ${r}`);return typeof n!="string"||n.length===0||Ln.test(n)||n.includes(xn)?null:n},On=(o,r,n,l=()=>{})=>{const s=r.tables[n];if(!s)throw new A("INTERNAL",`unknown table: ${n}`);const c=Ee(s.softDeleteMode,void 0),E=c?ue(c,pe):void 0,m={indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[]},_=h=>{const{search:k}=m;if(!k)throw new A("INTERNAL","runSearchFetch called without a staged search");qt(o,n,s);const C=m.inMemoryFilters.length>0,I=vt(C?void 0:h),P=ut(o)?gn(o,n,k,I,E):En(o,n,k,I,E);if(!C)return h===void 0&&Ct(P),P;const N=[];for(const w of P)if(m.inMemoryFilters.every(S=>S(w))&&(N.push(w),typeof h=="number"&&N.length>=h))break;return N},v=h=>{const k=Rt(h);return At(_(It(k)),k)},L=()=>{const h=m.indexFields.length>0?m.indexFields:["_creationTime"],k=m.order==="desc"?"DESC":"ASC";return e.join(h.map(C=>e`${ee(C)} ${e.raw(k)}`),e`, `)},T=h=>m.search?_(h):m.geo?Nn(o,n,m,E,h):Sn(o,n,m,E,L(),h),b={async collect(){return T(void 0)},filter(h){return m.inMemoryFilters.push(h),b},async first(){return T(m.inMemoryFilters.length>0?void 0:1)[0]??null},order(h){return m.order=h==="desc"?"desc":"asc",b},async paginate(h){if(m.search)return v(h);if(m.geo)throw new A("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");return kn(o,n,m,h,E)},async take(h){return T(h)},async unique(){const h=T(m.inMemoryFilters.length>0?void 0:2);if(h.length>1)throw new Mn(`unique() on table "${n}" matched ${String(h.length)} documents; expected at most one`);return h[0]??null},withGeoIndex(h,k){const C=(s.geoIndexes??[]).find(P=>P.name===h);if(!C)throw new A("INTERNAL",`unknown geo index "${h}" on table "${n}"`);l(n,h,"geo");const I={definition:C,indexName:h};if(m.geo=I,k(bn(I,n)),!I.near&&!I.within)throw new A("INTERNAL",`geo index "${h}" on table "${n}" requires a .near(point, radius) or .within(box) call`);return b},withIndex(h,k){const C=s.indexes.find(I=>I.name===h);if(!C)throw new A("INTERNAL",`unknown index "${h}" on table "${n}"`);return l(n,h,"index"),m.indexName=h,m.indexFields=C.fields,k&&k(mn(m)),b},withSearchIndex(h,k){const C=(s.searchIndexes??[]).find(P=>P.name===h);if(!C)throw new A("INTERNAL",`unknown search index "${h}" on table "${n}"`);l(n,h,"search");const I={definition:C,field:C.field,filters:[],hasQuery:!1,indexName:h,query:""};if(m.search=I,k(St(I,n,Ve(C.language))),!I.hasQuery)throw new A("INTERNAL",`search index "${h}" on table "${n}" requires a .search(field, query) call`);return b}};return b},rt=(o,r,n)=>{const l={...r};for(const[s,c]of $t(o)){if(c.serverDefault){l[s]=c.serverDefault({auth:n});continue}l[s]===void 0&&(c.defaultFn?l[s]=c.defaultFn():"defaultValue"in c&&(l[s]=c.defaultValue))}return l},at=(o,r,n,l)=>{const s=n;for(const[c,E]of $t(o)){if(E.serverDefault){c in r&&(s[c]=E.serverDefault({auth:l}));continue}E.onUpdateFn&&!(c in r)&&(s[c]=E.onUpdateFn())}},st=(o,r)=>{for(const n of Object.keys(r))if(r[n]===void 0)throw new A("INTERNAL",`Cannot ${o} field '${n}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},Dn=/unique constraint failed/i,Wn=o=>o instanceof Error&&Dn.test(o.message),Je=(o,r,n)=>{try{M(o,n)}catch(l){throw Wn(l)?new Re(`unique constraint violation on "${r}"`,"unique"):l}},xe=(o,r,n)=>{if(Je(o,r,n),M(o,e`SELECT changes() AS changed`).one().changed===0)throw new Re(`optimistic concurrency conflict on "${r}" — the row changed during this mutation; refetch and retry`,"occ")},lt=(o,r,n,l,s,c,E)=>{const m=[];for(let T=0;T<n.length+1;T+=1){const b=[];for(let I=0;I<T;I+=1)b.push(e`${e.identifier(n[I])} IS ${c[I]}`);const h=n[T],k=l[T];if(h!==void 0&&k!==void 0){const I=k.direction==="desc"?">":"<";b.push(e`${e.identifier(h)} ${e.raw(I)} ${c[T]}`)}else b.push(e`${e.identifier(me)} < ${E}`);const[C]=b;m.push(b.length===1&&C!==void 0?C:e`(${e.join(b,e` AND `)})`)}const _=e.join(m,e` OR `),v=M(o,e`SELECT COUNT(*) AS c FROM ${e.identifier(r)} WHERE ${e.identifier("__partition__")} = ${s} AND (${_})`).one(),L=M(o,e`SELECT COUNT(*) AS c FROM ${e.identifier(r)} WHERE ${e.identifier("__partition__")} = ${s}`).one();return{before:v.c,total:L.c}},li=o=>{const{sql:r}=o,{schema:n}=o,l=o.broadcast??(()=>{}),s=o.onRead??(()=>{}),c=o.onIndexUse??(()=>{}),E=o.onWrite??(()=>{}),{cache:m}=o,_=o.clock??(()=>Date.now()),v=o.idGenerator??(()=>crypto.randomUUID()),L=o.scheduler??Ot,{globalDb:T}=o,b=o.auth??{identity:null,userId:null},h=o.cdc??!1,k=L,C=tn({scheduler:typeof k.list=="function"&&typeof k.get=="function"?k:void 0,storage:o.storage}),I=(t,i,a,p)=>{h&&Ut(r,_(),t,i,a,p)},P=t=>n.tables[t]?.shardMode?.kind==="global",N=(t,i)=>{if(P(t)){if(!T)throw new A("INTERNAL",`cross-backend ${i} for global table '${t}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return T}return z},w=t=>N(t,"cascade"),S=(t,i)=>{if(P(t)){if(!T)throw new A("INTERNAL",`${i} on global table '${t}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return T}},F=()=>T,W=(t,i)=>N(t,"relation load").findMany(t,i),j=(t,i)=>(P(t)&&s(t,Q),W(t,i)),q=t=>!P(t.table),J=o.relationExistsPushDown??"auto",B=J!=="never",{maxRelationKeys:U}=o,x=(t,i,a)=>et(t,{fetcher:j,maxRelationKeys:U,relationBaseWhere:a,schema:n,tableName:i}),G=async(t,i,a,p)=>{const $=S(t,"relation grouped count");if($)return s(t,Q),Zt((D,oe)=>$.count(D,oe),t,i,a,p);const f=n.tables[t];if(!f)throw new A("INTERNAL",`unknown table: ${t}`);s(t,Q);const d=Ee(f.softDeleteMode,void 0),u={[i]:{in:a}},g=re(re(u,p),d),R=await x(g,t,void 0),y=ue(R,pe),O=ee(i);let K=e`SELECT ${O} AS __fk__, COUNT(*) AS count FROM ${e.identifier(t)}`;y&&(K=e`${K} WHERE ${y}`),K=e`${K} GROUP BY ${O}`;const V=M(r,K).toArray();return new Map(V.map(D=>[D.__fk__,D.count]))};let H=0;const Y=new Set;for(const[t,i]of Object.entries(n.tables))for(const a of Object.values(i.triggerMap??{}))Y.add(`${t} ${a.timing} ${a.op}`);const ie=(t,i,a)=>Y.has(`${t} ${i} ${a}`),se=async(t,i,a)=>{if(H+=1,H>it)throw H-=1,new Re(`trigger recursion exceeded ${String(it)} levels on "${a.table}" — check for a self-triggering write`,"trigger");try{await nn({ctx:_t,event:a,op:i,schema:n,tableName:a.table,timing:t})}finally{H-=1}},{ensureBackfilledForTable:ye,ensureBackfilledIndex:We,ensureRankBackfilled:Be,ensureRankBackfilledForTable:_e,syncAggregates:ve,syncCompanionsForInsert:ze,syncGeo:Ce,syncRanks:Te,syncSearch:ke}=an({broadcast:l,invalidateCache:(t,i)=>m?.invalidate(t,i),recordCdc:I,schema:n,sql:r}),Ke=(t,i,a)=>{const{shardMode:p}=i;if(p?.kind==="shardBy"&&!(p.field!==void 0&&(a.partitionBy??[]).includes(p.field)))throw Object.assign(new Error(`rank index "${a.name}" on "${t}" partitions across shards (shard key "${p.field??"?"}" is not in partitionBy) — a shard-local rank()/rankPage() would be wrong; roll it up through the Query Coordinator instead`),{code:"CROSS_SHARD_RANK_UNSUPPORTED",name:"LunoraError",status:400})},$e=(t,i)=>{const a=Object.entries(n.tables).filter(([,R])=>R.shardMode?.kind!=="global").map(([R])=>R).filter(R=>i===void 0||R===i);if(a.length===0)return;const p=a.map(R=>e`SELECT ${e.raw(`'${R.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${e.identifier(Z)} FROM ${e.identifier(R)} WHERE id = ${t}`),$=e`${e.join(p,e` UNION ALL `)} LIMIT 1`,[f]=M(r,$).toArray();if(!f)return;const d=f.__t__,u=he(f);if(typeof d!="string"||!u)return;const g=f[Z];return{docJson:typeof g=="string"?g:JSON.stringify(g??{}),row:u,tableName:d}},Qe={assertRankPartitionLocal:Ke,ensureRankBackfilled:Be,onRead:s,rowToDocument:he,schema:n,sql:r},z={system:C,async aggregate(t,i){const a=S(t,"aggregate");if(a)return s(t,Q),a.aggregate(t,i);const p=n.tables[t];if(!p)throw new A("INTERNAL",`unknown table: ${t}`);if(Ne(i.op),i.op==="count")return z.count(t,{baseWhere:i.baseWhere,relationBaseWhere:i.relationBaseWhere,restrictsCounts:i.restrictsCounts,where:i.where});if(!i.field)throw new A("INTERNAL",`aggregate(${t}, { op: "${i.op}" }): "field" is required for non-count reducers`);s(t,Q);const $=Ee(p.softDeleteMode,void 0),f=re(re(i.baseWhere,i.where),$),d=await x(f,t,i.relationBaseWhere),u=d!==f;if(p.aggregateIndexes&&!i.baseWhere&&!u&&!$){const V=Ft(p.aggregateIndexes,i.op,i.field,i.where);if(V){We(t,V.index);const D=de(V.index.by??[],V.key),oe=Se(t,V.index.name),ae=M(r,e`SELECT ${te} AS value, ${X} AS count FROM ${e.identifier(oe)} WHERE ${ce} = ${D}`).toArray()[0];return Ue(i.op,ae)}}const g=ue(d,pe),R=Ne(i.op),y=ee(i.field);let O=e`SELECT ${e.raw(R)}(${y}) AS value FROM ${e.identifier(t)}`;return g&&(O=e`${O} WHERE ${g}`),M(r,O).toArray()[0]?.value??null},asId(t,i){const a=ot(n,t,i);if(a===null)throw new A("BAD_REQUEST",`asId("${t}", …): "${i}" is not a valid id for table "${t}"`,{status:400});return a},async count(t,i){const a=S(t,"count");if(a)return s(t,Q),a.count(t,i);const p=n.tables[t];if(!p)throw new A("INTERNAL",`unknown table: ${t}`);const $=xt(i);if($.restrictsCounts)throw new Pe(t);s(t,Q);const f=Ee(p.softDeleteMode,void 0),d=re(re($.baseWhere,$.where),f),u=await x(d,t,$.relationBaseWhere),g=u!==d;if(p.aggregateIndexes&&!$.baseWhere&&!g&&!f){const O=Bt(p.aggregateIndexes,$.where);if(O){We(t,O.index);const K=de(O.index.by??[],O.key),V=Se(t,O.index.name),D=M(r,e`SELECT ${te} AS value FROM ${e.identifier(V)} WHERE ${ce} = ${K}`).toArray();return D[0]===void 0?0:D[0].value??0}}const R=ue(u,pe);let y=e`SELECT COUNT(*) AS count FROM ${e.identifier(t)}`;return R&&(y=e`${y} WHERE ${R}`),M(r,y).one().count},async delete(t,i,a){const p=$e(t,i);if(!p){const y=i===void 0?F():void 0;y&&await y.delete(t,void 0,a);return}const{docJson:$,row:f,tableName:d}=p,u=n.tables[d],g=a?.hard===!0,R=!g&&u?.softDeleteMode?u.softDeleteMode.field:void 0;if(!(R&&f[R]!==null&&f[R]!==void 0)){if(ie(d,"before","delete")&&await se("before","delete",{id:t,op:"delete",previous:f,table:d}),await Xt({deletedId:t,deletedReference:y=>f[y],findHolders:async(y,O,K)=>(await w(y).findMany(y,{includeDeleted:g,where:{[O]:K}})).page,onCascade:(y,O)=>w(y).delete(O,void 0,a),onRestrict:y=>{throw new Re(y,"restrict")},onSetNull:(y,O,K)=>w(y).patch(O,{[K]:null}),schema:n,tableName:d}),ye(d),_e(d),R){const y={...f,[R]:_(),_id:t};xe(r,d,e`UPDATE ${e.identifier(d)} SET ${e.identifier(Z)} = ${JSON.stringify(y)} WHERE id = ${t} AND ${e.identifier(Z)} = ${$}`),ke(d,t,y,f),Ce(d,t,void 0),ve(d,f,y),Te(d,t,f,void 0),m?.invalidate(d,t),I(d,t,"update",y),l({key:t,op:"update",row:y,table:d}),ie(d,"after","delete")&&await se("after","delete",{id:t,op:"delete",previous:f,table:d}),await E({id:t,op:"delete",table:d});return}xe(r,d,e`DELETE FROM ${e.identifier(d)} WHERE id = ${t} AND ${e.identifier(Z)} = ${$}`),ke(d,t,void 0),Ce(d,t,void 0),ve(d,f,void 0),Te(d,t,f,void 0),m?.invalidate(d,t),I(d,t,"delete"),l({key:t,op:"delete",table:d}),ie(d,"after","delete")&&await se("after","delete",{id:t,op:"delete",previous:f,table:d}),await E({id:t,op:"delete",table:d})}},async deleteAll(t,i){if(!n.tables[t])throw new A("INTERNAL",`unknown table: ${t}`);const a=Math.max(1,i?.chunkSize??bt),p=i?.hard===void 0?void 0:{hard:i.hard},$=P(t)?void 0:t;let f=0;for(;;){const d=(await z.findMany(t,{limit:a})).page.map(u=>String(u._id));if(d.length===0)break;for(const u of d)await z.delete(u,$,p),f+=1;if(d.length<a)break}return{deleted:f}},async deleteMany(t,i,a){ge(t.length,i?.limit,"deleteMany");for(const p of t)await z.delete(p,a);return{deleted:t.length}},async deleteWhere(t,i,a){const p=S(t,"deleteWhere");let $;if(p)$=(await p.findMany(t,{where:i})).page.map(f=>String(f._id));else{if(!n.tables[t])throw new A("INTERNAL",`unknown table: ${t}`);$=(await z.findMany(t,{where:i})).page.map(f=>String(f._id))}if(ge($.length,a?.limit,"deleteWhere"),z.deleteMany===void 0)throw new A("INTERNAL",`ctx.db.${t}.deleteMany is unavailable: this writer has no batch delete`);return z.deleteMany($,a)},async findFirst(t,i={}){return(await z.findMany(t,{...i,limit:1})).page[0]??null},async findFirstOrThrow(t,i={}){const a=await z.findFirst(t,i);if(a===null)throw new Qt(`findFirstOrThrow: no "${t}" document matched`);return a},async findMany(t,i={}){const a=S(t,"findMany");if(a)return s(t,Q),a.findMany(t,i);const p=n.tables[t];if(!p)throw new A("INTERNAL",`unknown table: ${t}`);const $=!i.where&&!i.baseWhere;$?s(t,Q):s(t);const f=zt(i.orderBy),d=i.cursor?gt(f,Oe(i.cursor)):void 0;let u=re(i.baseWhere,i.where);u=re(u,Ee(p.softDeleteMode,i.includeDeleted)),u=await et(u,{canPushExists:B?q:void 0,existsPushMode:J==="always"?"always":"auto",fetcher:j,maxRelationKeys:U,relationBaseWhere:i.relationBaseWhere,schema:n,tableName:t}),d&&(u=u?{AND:[u,d]}:d);const g=B?Rn(s):pe,R=ue(u,g);let y=e`SELECT id, _creationTime, ${e.identifier(Z)} FROM ${e.identifier(t)}`;R&&(y=e`${y} WHERE ${R}`),y=e`${y} ORDER BY ${yt(f)}`;const O=typeof i.limit=="number"?Math.max(0,Math.floor(i.limit)):void 0;O!==void 0&&(y=e`${y} LIMIT ${e.raw(String(O+1))}`);const K=M(r,y).toArray(),V=[];for(const le of K){const ne=he(le);ne&&(V.push(ne),!$&&typeof ne._id=="string"&&s(t,ne._id))}if(O===void 0)return i.with&&await tt({groupedCounter:G,fetcher:W,parents:V,relationBaseWhere:i.relationBaseWhere,schema:n,tableName:t,with:i.with}),{continueCursor:null,isDone:!0,page:Ze(V,i.select,i.with)};const D=V.length>O,oe=D?V.slice(0,O):V,ae=oe.at(-1);return i.with&&await tt({fetcher:W,groupedCounter:G,parents:oe,relationBaseWhere:i.relationBaseWhere,schema:n,tableName:t,with:i.with}),{continueCursor:D&&ae?Ge(ae,f):null,isDone:!D,page:Ze(oe,i.select,i.with)}},async get(t,i){const a=$e(t,i);if(!a){const p=i===void 0?F():void 0;return p?p.get(t):null}return s(a.tableName,t),a.row},async lookupById(t,i){const a=$e(t,i);return a?(s(a.tableName,t),{row:a.row,tableName:a.tableName}):null},async groupBy(t,i){const a=S(t,"groupBy");if(a)return s(t,Q),a.groupBy(t,i);const p=n.tables[t];if(!p)throw new A("INTERNAL",`unknown table: ${t}`);s(t,Q);const $=i.agg??{op:"count"};if(Ne($.op),$.op!=="count"&&!$.field)throw new A("INTERNAL",`groupBy(${t}, { agg: { op: "${$.op}" } }): "field" is required for non-count reducers`);const f=Ee(p.softDeleteMode,void 0),d=re(re(i.baseWhere,i.where),f),u=await x(d,t,i.relationBaseWhere),g=u!==d;if(p.aggregateIndexes&&!i.baseWhere&&!g&&!f){const D=Wt(p.aggregateIndexes,$.op,$.field,i.by,i.where);if(D){We(t,D.index);const oe=Se(t,D.index.name),ae=Object.keys(D.partial),le=[];if(ae.length===(D.index.by??[]).length&&ae.length>0){const we=de(D.index.by??[],D.partial),Me=M(r,e`SELECT ${te} AS value, ${X} AS count FROM ${e.identifier(oe)} WHERE ${ce} = ${we}`).toArray();return Me.length>0&&le.push({key:{...D.partial},value:Ue($.op,Me[0])}),le}const ne=M(r,e`SELECT ${ce} AS key, ${te} AS value, ${X} AS count FROM ${e.identifier(oe)}`).toArray();for(const we of ne){const Me=JSON.parse(we.key);le.push({key:Me,value:Ue($.op,we)})}return le}}const R=ue(u,pe),y=i.by.map(D=>e`${ee(D)} AS ${e.identifier(D)}`);if($.op==="count")y.push(e`COUNT(*) AS value`);else{const{field:D}=$;if(D===void 0)throw new A("INTERNAL",`groupBy(${t}, { agg: { op: "${$.op}" } }): "field" is required for non-count reducers`);y.push(e`${e.raw(Ne($.op))}(${ee(D)}) AS value`)}let O=e`SELECT ${e.join(y,e`, `)} FROM ${e.identifier(t)}`;R&&(O=e`${O} WHERE ${R}`),O=e`${O} GROUP BY ${e.join(i.by.map(D=>ee(D)),e`, `)}`;const K=M(r,O).toArray(),V=[];for(const D of K){const oe={};for(const le of i.by)oe[le]=D[le]??null;const{value:ae}=D;V.push({key:oe,value:ae==null?null:Number(ae)})}return V},async insert(t,i,a){const p=S(t,"insert");if(p){const R=await p.insert(t,i,a);return l({key:R,op:"insert",row:{...i,_id:R},table:t}),R}const $=n.tables[t];if(!$)throw new A("INTERNAL",`unknown table: ${t}`);const f=rt($,i,b);je($,f);let d;a?.clientId!==void 0?(pn(a.clientId),d=a.clientId):a?.allowExplicitId&&typeof f._id=="string"?d=f._id:d=v();const u=a?.allowExplicitId&&typeof f._creationTime=="number"?f._creationTime:_(),g={...f,_creationTime:u,_id:d};return ie(t,"before","insert")&&await se("before","insert",{doc:{...g},id:d,op:"insert",table:t}),ye(t),_e(t),Je(r,t,e`INSERT INTO ${e.identifier(t)} (id, _creationTime, ${e.identifier(Z)}) VALUES (${d}, ${u}, ${JSON.stringify(g)})`),ze(t,d,g),ie(t,"after","insert")&&await se("after","insert",{doc:g,id:d,op:"insert",table:t}),await E({doc:g,id:d,op:"insert",table:t}),d},async insertManyUnsafe(t,i,a){if(ge(i.length,a?.limit,"insertManyUnsafe"),i.length===0)return[];const p=S(t,"insert");if(p){const u=[];for(const g of i){const R=await p.insert(t,g,{allowExplicitId:a?.allowExplicitId});l({key:R,op:"insert",row:{...g,_id:R},table:t}),u.push(R)}return u}const $=n.tables[t];if(!$)throw new A("INTERNAL",`unknown table: ${t}`);ye(t),_e(t);const f=i.map(u=>{const g=rt($,u,b),R=a?.allowExplicitId===!0&&typeof g._id=="string"?g._id:v(),y=a?.allowExplicitId===!0&&typeof g._creationTime=="number"?g._creationTime:_();return{creationTime:y,document:{...g,_creationTime:y,_id:R},id:R}}),d=e.join(f.map(u=>e`(${u.id}, ${u.creationTime}, ${JSON.stringify(u.document)})`),e`, `);Je(r,t,e`INSERT INTO ${e.identifier(t)} (id, _creationTime, ${e.identifier(Z)}) VALUES ${d}`);for(const{document:u,id:g}of f)ze(t,g,u),await E({doc:u,id:g,op:"insert",table:t});return f.map(u=>u.id)},async insertMany(t,i,a){ge(i.length,a?.limit,"insertMany");const p=a?.skipDuplicates===!0,$=[];for(const f of i)try{$.push(await z.insert(t,f))}catch(d){if(p&&d instanceof Re&&d.kind==="unique")$.push(null);else throw d}return $},normalizeId(t,i){return ot(n,t,i)},async patch(t,i,a){const p=$e(t,a);if(!p){const R=a===void 0?F():void 0;if(R){await R.patch(t,i);return}throw new A("INTERNAL",`document not found: ${t}`)}const{docJson:$,row:f,tableName:d}=p,u=n.tables[d];if(!u)throw new A("INTERNAL",`unknown table: ${d}`);s(d,t),st("patch",i);const g={...f,...i,_id:t};at(u,i,g,b),je(u,g),ie(d,"before","update")&&await se("before","update",{doc:{...g},id:t,op:"update",previous:f,table:d}),ye(d),_e(d),xe(r,d,e`UPDATE ${e.identifier(d)} SET ${e.identifier(Z)} = ${JSON.stringify(g)} WHERE id = ${t} AND ${e.identifier(Z)} = ${$}`),ke(d,t,g,f),Ce(d,t,g),ve(d,f,g),Te(d,t,f,g),m?.invalidate(d,t),I(d,t,"update",g),l({key:t,op:"update",row:g,table:d}),ie(d,"after","update")&&await se("after","update",{doc:g,id:t,op:"update",previous:f,table:d}),await E({doc:g,id:t,op:"update",table:d})},async patchMany(t,i,a){ge(t.length,i?.limit,"patchMany");for(const p of t)await z.patch(p.id,p.patch,a);return{patched:t.length}},async patchWhere(t,i,a){const p=S(t,"patchWhere");let $;if(p)$=(await p.findMany(t,{where:i.where})).page.map(f=>({id:String(f._id),patch:i.patch}));else{if(!n.tables[t])throw new A("INTERNAL",`unknown table: ${t}`);$=(await z.findMany(t,{where:i.where})).page.map(f=>({id:String(f._id),patch:i.patch}))}if(ge($.length,a?.limit,"patchWhere"),z.patchMany===void 0)throw new A("INTERNAL",`ctx.db.${t}.patchMany is unavailable: this writer has no batch patch`);return await z.patchMany($,a),{patched:$.length}},query(t){const i=S(t,"query");return i?(s(t,Q),i.query(t)):(s(t,Q),On(r,n,t,c))},async rank(t,i,a){const p=S(t,"rank");if(p)return s(t,Q),p.rank(t,i,a);c(t,i,"rank");const $=n.tables[t];if(!$)throw new A("INTERNAL",`unknown table: ${t}`);const f=$.rankIndexes?.find(ne=>ne.name===i);if(!f)throw new A("INTERNAL",`unknown rankIndex "${i}" on table "${t}"`);if(Ke(t,$,f),a.restrictsCounts)throw new Pe(t);s(t,Q),Be(t,f);const d=typeof a.row=="string"?a.row:a.row._id;if(!d)return null;const u=Ie(t,f.name),g=f.sortBy.map((ne,we)=>Ae(we)),R=g.map(ne=>Pt(ne)).join(", "),y=M(r,e`SELECT ${e.identifier("__partition__")}, ${e.raw(R)} FROM ${e.identifier(u)} WHERE ${e.identifier("__id__")} = ${d}`).toArray(),[O]=y;if(O===void 0)return null;let K=O.__partition__;const V=re(a.baseWhere,a.where);He(V,n,t,"rank");const D=wt(f,V);if(D){const ne=De(f.partitionBy??[],D);if(ne!==K)return null;K=ne}const oe=g.map(ne=>O[ne]),{before:ae,total:le}=lt(r,u,g,f.sortBy,K,oe,d);return{position:ae+1,total:le}},async rankBefore(t,i,a){if(P(t))throw new A("INTERNAL",`rankBefore is not supported on the global (.global()) table '${t}' — cross-shard rank cursors apply only to sharded tables`);const p=n.tables[t];if(!p)throw new A("INTERNAL",`unknown table: ${t}`);const $=p.rankIndexes?.find(g=>g.name===i);if(!$)throw new A("INTERNAL",`unknown rankIndex "${i}" on table "${t}"`);if(a.restrictsCounts)throw new Pe(t);s(t,Q),Be(t,$);const f=Ie(t,$.name),d=$.sortBy.map((g,R)=>Ae(R)),u=$.sortBy.map((g,R)=>fe(a.sortValues[R]??null));return lt(r,f,d,$.sortBy,a.partitionKey,u,a.rowId)},async rankPage(t,i,a={}){He(re(a.baseWhere,a.where),n,t,"rankPage");const p=S(t,"rankPage");if(p)return s(t,Q),p.rankPage(t,i,a);c(t,i,"rank");const{continueCursor:$,hasMore:f,rows:d}=nt(Qe,t,i,a);return{continueCursor:$,isDone:!f,page:d.map(u=>u.doc)}},async rankPageRows(t,i,a={}){He(re(a.baseWhere,a.where),n,t,"rankPage"),c(t,i,"rank");const{directions:p,hasMore:$,rows:f}=nt(Qe,t,i,a);return{directions:p,hasMore:$,rows:f}},async restore(t,i){const a=$e(t,i);if(!a){const f=i===void 0?F():void 0;if(f?.restore){await f.restore(t);return}throw new A("INTERNAL",`document not found: ${t}`)}const p=n.tables[a.tableName]?.softDeleteMode?.field;if(!p)throw new A("INTERNAL",`ctx.db.restore: table "${a.tableName}" is not a .softDelete() table`);const $=a.row[p]!==null&&a.row[p]!==void 0;await z.patch(t,{[p]:null},i),$&&Te(a.tableName,t,void 0,a.row)},async replace(t,i,a,p){const $=$e(t,a);if(!$){const O=a===void 0?F():void 0;if(O){await O.replace(t,i,void 0,p);return}throw new A("INTERNAL",`document not found: ${t}`)}const{docJson:f,row:d,tableName:u}=$,g=n.tables[u];if(!g)throw new A("INTERNAL",`unknown table: ${u}`);st("replace",i);const R=p?.allowExplicitId&&typeof i._creationTime=="number"?i._creationTime:_(),y={...i,_creationTime:R,_id:t};at(g,i,y,b),je(g,y),ie(u,"before","update")&&await se("before","update",{doc:{...y},id:t,op:"update",previous:d,table:u}),ye(u),_e(u),xe(r,u,e`UPDATE ${e.identifier(u)} SET _creationTime = ${R}, ${e.identifier(Z)} = ${JSON.stringify(y)} WHERE id = ${t} AND ${e.identifier(Z)} = ${f}`),ke(u,t,y,d),Ce(u,t,y),ve(u,d,y),Te(u,t,d,y),m?.invalidate(u,t),I(u,t,"update",y),l({key:t,op:"update",row:y,table:u}),ie(u,"after","update")&&await se("after","update",{doc:y,id:t,op:"update",previous:d,table:u}),await E({doc:y,id:t,op:"update",table:u})},async wipeShard(t){const i=new Set(t?.exclude),a=t?.tables,p=Object.entries(n.tables).filter(([u,g])=>i.has(u)||a!==void 0&&!a.includes(u)?!1:g.shardMode?.kind!=="global").map(([u])=>u);if(a!==void 0){for(const u of a)if(!n.tables[u])throw new A("INTERNAL",`wipeShard: unknown table: ${u}`)}const $={};let f=0;const{deleteAll:d}=z;if(d===void 0)throw new A("INTERNAL","wipeShard: this writer has no deleteAll");for(const u of p){const g=await d(u,{...t?.chunkSize===void 0?{}:{chunkSize:t.chunkSize},hard:!0});$[u]=g.deleted,f+=g.deleted}return{deleted:f,tables:$}}},_t={db:z,scheduler:L};return o.enforceRls===!0?en(z,n,(t,i)=>$e(t,i)?.tableName):z};export{mi as CDC_LOG_TABLE,Si as CLIENT_WATERMARK_TABLE,Ri as GLOBAL_SHAPE_SNAPSHOT_TABLE,Ai as IDEMPOTENCY_TABLE,Mn as NotUniqueError,fi as SEARCH_STATE_TABLE,Ii as advanceClientWatermark,wi as applyCdcChanges,pn as assertValidClientId,ui as backfillAggregateIndexes,hi as backfillRankIndexes,$i as backfillSearchIndexes,gi as bumpCdcEpoch,li as createShardCtxDb,vi as deleteGlobalShapeSnapshot,Ci as deleteGlobalShapeSnapshotsForConnection,ki as migrateClientWatermark,Mi as migrateGlobalShapeSnapshot,Ei as minCdcSeq,ot as normalizeIdStructurally,bi as readCdcChanges,yi as readCdcCursor,_i as readCdcEpoch,Li as readClientWatermark,xi as readGlobalShapeSnapshot,Oi as readIdempotent,qi as runShardMigrations,Pi as selectShapeMemberIds,Hi as selectShapeRows,Ti as trimCdcChanges,Di as trimIdempotent,Wi as writeGlobalShapeSnapshot,Bi as writeIdempotent};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{LunoraError as f,toErrorBody as C}from"@lunora/errors";import{drizzle as gt}from"drizzle-orm/durable-sqlite";import{c as j}from"./constant-time-equal-BVG05Guz.mjs";import{j as y}from"./json-response-wrh9TBPw.mjs";import{O as St,t as bt,n as Ie,r as K,A as Et,a as wt,b as Rt,c as Tt,d as vt,w as se,e as At}from"./context-telemetry-BFO0N_e4.mjs";import{f as w,c as O}from"./wire-codec-Ctnni0h6.mjs";import{parseExportShardArgs as It,parseImportShardArgs as _t}from"./exportShardRows-kt42wijd.mjs";import{recordAuthEvent as kt,readAuthMetrics as Mt}from"./AUTH_METRICS_BUCKETS_TABLE-D0wNaez7.mjs";import{DATA_MIGRATION_STATE_TABLE as Nt,readMigrationStatus as Ct}from"./DATA_MIGRATION_STATE_TABLE-CaO6L0Ee.mjs";import{SCAN_DEP as _e,createDependencyTracker as Ot,tableFromDepKey as Lt}from"./SCAN_DEP-D_yR9EeV.mjs";import{readFunctionMetricsTotals as xt,readFunctionMetricIndexHits as $t,recordFunctionMetric as Pt,mergeScanAttribution as qt,readFunctionMetrics as Dt,readFunctionMetricBuckets as Ut}from"./FUNCTION_METRICS_BUCKETS_TABLE-BPPeqM11.mjs";import{createFanoutCounters as ke,ADMIN_FUNCTION_PREFIX as k,RELATION_FUNCTION_PREFIX as Bt,selectMatchingIds as Ft,ADMIN_FUNCTIONS as h,findStorageReferences as Wt,listTables as Kt,summarizeSubscriptions as Ht,summarizeFanoutTopics as Qt,readTablePage as Gt,facetColumn as zt,FLAGS_FUNCTION_PREFIX as jt,recordFanoutPass as re,MAX_PAGE_SIZE as Jt}from"./ADMIN_FUNCTIONS-PxZ8Lr9e.mjs";import{LogBuffer as Xt}from"./LogBuffer-bIvCelI-.mjs";import{recordCapturedMail as Me,clearCapturedMail as Yt,readCapturedMail as Vt,MAIL_TABLE as Zt}from"./MAIL_RETENTION-KmozO2NQ.mjs";import{stableStringify as Ee}from"./stableStringify-BjLh4gvA.mjs";import{readBookmark as es,armRestore as ts}from"./armRestore-BNzdvQ_o.mjs";import{ReactiveCache as ss,reactiveCacheKey as Ne}from"./ReactiveCache-1_9Rs7J_.mjs";import{stableWireKey as $}from"./stableWireKey-YEHLaX6X.mjs";import{awaitWsDrain as M,trySendFrame as L,subscriptionListDeltas as rs,sendDeltaFrames as as}from"./subscriptionListDeltas-Bs69JbA8.mjs";import{fingerprintError as ns}from"@lunora/fingerprint";import{redact as is,standardRules as os}from"@visulima/redact";import{R as Ce,E as cs,_ as ds}from"./security-audit-BKUOgE0x.mjs";import{runReadonlySql as us}from"./MAX_SQL_ROWS-Bdu25ASB.mjs";import{ConflictError as ls}from"./ConflictError-C8GtJmjS.mjs";import{selectExpiredIds as hs}from"./selectExpiredIds-
|
|
1
|
+
import{LunoraError as f,toErrorBody as C}from"@lunora/errors";import{drizzle as gt}from"drizzle-orm/durable-sqlite";import{c as j}from"./constant-time-equal-BVG05Guz.mjs";import{j as y}from"./json-response-wrh9TBPw.mjs";import{O as St,t as bt,n as Ie,r as K,A as Et,a as wt,b as Rt,c as Tt,d as vt,w as se,e as At}from"./context-telemetry-BFO0N_e4.mjs";import{f as w,c as O}from"./wire-codec-Ctnni0h6.mjs";import{parseExportShardArgs as It,parseImportShardArgs as _t}from"./exportShardRows-kt42wijd.mjs";import{recordAuthEvent as kt,readAuthMetrics as Mt}from"./AUTH_METRICS_BUCKETS_TABLE-D0wNaez7.mjs";import{DATA_MIGRATION_STATE_TABLE as Nt,readMigrationStatus as Ct}from"./DATA_MIGRATION_STATE_TABLE-CaO6L0Ee.mjs";import{SCAN_DEP as _e,createDependencyTracker as Ot,tableFromDepKey as Lt}from"./SCAN_DEP-D_yR9EeV.mjs";import{readFunctionMetricsTotals as xt,readFunctionMetricIndexHits as $t,recordFunctionMetric as Pt,mergeScanAttribution as qt,readFunctionMetrics as Dt,readFunctionMetricBuckets as Ut}from"./FUNCTION_METRICS_BUCKETS_TABLE-BPPeqM11.mjs";import{createFanoutCounters as ke,ADMIN_FUNCTION_PREFIX as k,RELATION_FUNCTION_PREFIX as Bt,selectMatchingIds as Ft,ADMIN_FUNCTIONS as h,findStorageReferences as Wt,listTables as Kt,summarizeSubscriptions as Ht,summarizeFanoutTopics as Qt,readTablePage as Gt,facetColumn as zt,FLAGS_FUNCTION_PREFIX as jt,recordFanoutPass as re,MAX_PAGE_SIZE as Jt}from"./ADMIN_FUNCTIONS-PxZ8Lr9e.mjs";import{LogBuffer as Xt}from"./LogBuffer-bIvCelI-.mjs";import{recordCapturedMail as Me,clearCapturedMail as Yt,readCapturedMail as Vt,MAIL_TABLE as Zt}from"./MAIL_RETENTION-KmozO2NQ.mjs";import{stableStringify as Ee}from"./stableStringify-BjLh4gvA.mjs";import{readBookmark as es,armRestore as ts}from"./armRestore-BNzdvQ_o.mjs";import{ReactiveCache as ss,reactiveCacheKey as Ne}from"./ReactiveCache-1_9Rs7J_.mjs";import{stableWireKey as $}from"./stableWireKey-YEHLaX6X.mjs";import{awaitWsDrain as M,trySendFrame as L,subscriptionListDeltas as rs,sendDeltaFrames as as}from"./subscriptionListDeltas-Bs69JbA8.mjs";import{fingerprintError as ns}from"@lunora/fingerprint";import{redact as is,standardRules as os}from"@visulima/redact";import{R as Ce,E as cs,_ as ds}from"./security-audit-BKUOgE0x.mjs";import{runReadonlySql as us}from"./MAX_SQL_ROWS-Bdu25ASB.mjs";import{ConflictError as ls}from"./ConflictError-C8GtJmjS.mjs";import{selectExpiredIds as hs}from"./selectExpiredIds-BXJDiUtz.mjs";import{p as ps,m as fs,T as ms,u as ys,b as ae,_ as gs,o as Ss,l as bs,d as Es,S as ws}from"./ctx-db-idempotency-wiVoGnpQ.mjs";import{CDC_LOG_TABLE as Oe,readCdcChanges as ne,readCdcCursor as Le,readCdcEpoch as xe,minCdcSeq as $e,bumpCdcEpoch as Rs}from"./CDC_LOG_TABLE-E_J5LPoK.mjs";import{a as Ts,s as vs}from"./ctx-db-shapes-CHC2cS0g.mjs";const Pe=500,J=(a,e)=>{if(a.size<e)return;const t=a.keys().next().value;t!==void 0&&a.delete(t)},at=new TextEncoder,As=a=>{const e=a.replaceAll("-","+").replaceAll("_","/")+"===".slice((a.length+3)%4),t=atob(e),s=new Uint8Array(t.length);for(let r=0;r<t.length;r+=1)s[r]=t.codePointAt(r)??0;return s},Is=64,ie=new Map,_s=async a=>{const e=ie.get(a);if(e)return e;J(ie,Is);const t=crypto.subtle.importKey("raw",at.encode(a),{hash:"SHA-256",name:"HMAC"},!1,["sign","verify"]);return ie.set(a,t),t},ks=async(a,e,t)=>{const s=await _s(a);return crypto.subtle.verify("HMAC",s,t,at.encode(e))},Ms="v1",Ns=async(a,e,t=Date.now())=>{if(a.length===0||e.length===0)return!1;const s=e.split(".");if(s.length!==3)return!1;const[r,n,i]=s;if(r!==Ms||i.length===0)return!1;const o=Number(n);if(!Number.isFinite(o)||o<=t)return!1;let c;try{c=As(i)}catch{return!1}return ks(a,`${r}.${n}`,c)},q="__lunora_audit__",X=(a,e,...t)=>a.exec.call(a,e,...t),we=a=>{X(a,`CREATE TABLE IF NOT EXISTS "${q}" (
|
|
2
2
|
seq INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
3
3
|
ts REAL NOT NULL,
|
|
4
4
|
op TEXT NOT NULL,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as D}from"@lunora/errors";import{applySelect as A}from"./applySelect-
|
|
1
|
+
import{LunoraError as D}from"@lunora/errors";import{applySelect as A}from"./applySelect-B0CF8T7y.mjs";const v=(r,o)=>o.select?A(r,o.select,o.with):r,_=async(r,o,t,a,s)=>{const w=await Promise.all(a.map(async l=>{const m=s?{AND:[{[t]:l},s]}:{[t]:l};return[l,await r(o,m)]}));return new Map(w)},W=(r,o)=>{const t=new Set;for(const a of r){const s=a[o];s!=null&&t.add(s)}return[...t]},C=async r=>{const{groupedCounter:o,fetcher:t,parents:a,relationBaseWhere:s,schema:w,tableName:l,with:m}=r;if(a.length===0)return;const k=w.tables[l];if(!k)throw new D("INTERNAL",`unknown table: ${l}`);const O=k.relationMap??{},g=c=>{const e=O[c];if(!e)throw new D("INTERNAL",`unknown relation "${c}" on table "${l}"`);return e},M=async(c,e,n)=>{const u=W(a,e.field);if(u.length===0){for(const i of a)i[c]=null;return}const{page:p}=await t(e.table,{baseWhere:s?.(e.table),relationBaseWhere:s,where:{[e.references]:{in:u}},with:n.with}),b=new Map;for(const i of p)b.set(i[e.references],i);for(const i of a){const d=b.get(i[e.field]);i[c]=d?v([d],n)[0]??null:null}},R=async(c,e,n)=>{const u=W(a,e.references);if(u.length===0){for(const f of a)f[c]=[];return}const p={[e.field]:{in:u}},b=n.where?{AND:[n.where,p]}:p,{page:i}=await t(e.table,{baseWhere:s?.(e.table),orderBy:n.orderBy,relationBaseWhere:s,where:b,with:n.with}),d=new Map;for(const f of i){const h=f[e.field],$=d.get(h);$?$.push(f):d.set(h,[f])}const y=typeof n.limit=="number"?Math.max(0,Math.floor(n.limit)):void 0;for(const f of a){const h=d.get(f[e.references])??[];f[c]=v(y===void 0?h:h.slice(0,y),n)}},N=async c=>{for(const e of Object.keys(c)){const n=g(e),[u,p]=n.kind==="many"?[n.field,n.references]:[n.references,n.field],b=s?.(n.table),i=W(a,p),d=i.length===0?new Map:await o(n.table,u,i,b);for(const y of a){const f=y._count??{},h=y[p];f[e]=h==null?0:d.get(h)??0,y._count=f}}};for(const[c,e]of Object.entries(m)){if(e===void 0||e===!1)continue;if(c==="_count"){await N(e);continue}const n=g(c),u=e===!0?{}:e;await(n.kind==="one"?M(c,n,u):R(c,n,u))}},B=async(r,o,t)=>{const{deletedId:a,deletedReference:s,findHolders:w,onCascade:l,onRestrict:m,onSetNull:k,tableName:O}=r,g=t.references==="_id"?a:s(t.references);if(g==null)return;const M=await w(o,t.field,g);if(M.length!==0){t.onDelete==="restrict"&&m(`cannot delete "${O}" row: "${o}.${t.field}" still references it`);for(const R of M){const N=R._id;typeof N=="string"&&await(t.onDelete==="cascade"?l(o,N):k(o,N,t.field))}}},E=async r=>{const{schema:o,tableName:t}=r;if(!o.tables[t])throw new D("INTERNAL",`unknown table: ${t}`);for(const[a,s]of Object.entries(o.tables)){const w=s.relationMap;if(w)for(const l of Object.values(w))l.kind!=="one"||l.table!==t||!l.onDelete||await B(r,a,l)}},I=(r,o)=>{for(const[t,a]of Object.entries(r.shape))t in o&&typeof a.parse=="function"&&a.parse(o[t])};export{E as applyOnDelete,W as distinctValues,_ as fanOutScalarCounts,C as resolveWith,I as runRowValidators};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as m}from"@lunora/errors";const u="id",h=new Set(["_id","id"]),b=t=>{const e=[];for(const r of t??[])for(const[o,s]of Object.entries(r))e.push({direction:s,field:o});return e.length===0?[{direction:"asc",field:"_creationTime"}]:e},S=t=>{const e=new TextEncoder().encode(t);let r="";for(const o of e)r+=String.fromCodePoint(o);return btoa(r)},g=t=>{const e=atob(t),r=Uint8Array.from(e,o=>o.codePointAt(0)??0);return new TextDecoder().decode(r)},A=(t,e)=>{const r=e.map(o=>t[o.field]);return r.push(t._id),S(JSON.stringify(r))},l=()=>new m("BAD_REQUEST","invalid cursor"),D=t=>{let e;try{e=JSON.parse(g(t))}catch{throw l()}if(!Array.isArray(e))throw l();return e},_=(t,e)=>{const r=t.some(s=>h.has(s.field))?t:[...t,{direction:"asc",field:u}],o=[];for(const[s,n]of r.entries()){const i=[];for(const[d,a]of r.slice(0,s).entries())i.push({[a.field]:{eq:e[d]}});const f=n.direction==="desc"?"lt":"gt";i.push({[n.field]:{[f]:e[s]}});const[c]=i;o.push(i.length===1&&c!==void 0?c:{AND:i})}return{OR:o}},y=(t,e)=>t==="desc"?e?"gte":"gt":e?"lte":"lt",v=(t,e)=>{const r=t.some(s=>h.has(s.field))?t:[...t,{direction:"asc",field:u}],o=[];for(const[s,n]of r.entries()){const i=[];for(const[a,p]of r.slice(0,s).entries())i.push({[p.field]:{eq:e[a]}});const f=s===r.length-1,c=y(n.direction,f);i.push({[n.field]:{[c]:e[s]}});const[d]=i;o.push(i.length===1&&d!==void 0?d:{AND:i})}return{OR:o}},w=["_id","_creationTime"],E=(t,e,r)=>{if(!e)return t;const o=new Set([...e,...w,...r?Object.keys(r):[]]);return t.map(s=>{const n={};for(const i of o)i in s&&(n[i]=s[i]);return n})},N=(t,e)=>t&&e!==!0?{[t.field]:{isNull:!0}}:void 0;export{E as applySelect,v as buildSeekBeforeWhere,_ as buildSeekWhere,D as decodeCursor,A as encodeCursor,g as fromBase64,l as invalidCursor,b as normalizeOrderKeys,N as softDeleteScope,S as toBase64};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"@lunora/search-core";import"drizzle-orm";import"./AGGREGATE_SQL_FUNCTION-QYaiuty4.mjs";import"./aggregateTableName-G-eXyjcz.mjs";import{H as b,P as f,X as k,Y as n}from"./ctx-db-backfill-C4rAzsQo.mjs";import"./do-exec-BLe9lLrN.mjs";import"./do-sql-x0AjZhaN.mjs";import"./renderSql-B5lF5Jd9.mjs";import"./RANK_TIEBREAK-DtX8zQyc.mjs";import"./serialize-sql-DiRzL7A4.mjs";export{b as backfillAggregateIndexes,f as backfillRankIndexes,k as backfillSearchIndexes,n as backfillSearchIndexesForTable};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{ftsTableName as I,createSearchAnalyzer as L,planSearchBackfillPass as N,FTS_ID_COLUMN as p,FTS_TEXT_COLUMN as A,analyzedSearchText as _}from"@lunora/search-core";import{sql as e}from"drizzle-orm";import{matchesStaticWhere as h}from"./AGGREGATE_SQL_FUNCTION-QYaiuty4.mjs";import{encodeAggregateKey as M,foldAggregateTally as C,aggregateTableName as y}from"./aggregateTableName-G-eXyjcz.mjs";import{r as f}from"./do-exec-BLe9lLrN.mjs";import{b as g,s as m,g as O,a as F,_ as b,m as x,N as D}from"./do-sql-x0AjZhaN.mjs";import{param as U}from"./renderSql-B5lF5Jd9.mjs";import{sortColumnName as k,matchesRankStaticWhere as w,encodePartitionKey as B,rankTableName as X}from"./RANK_TIEBREAK-DtX8zQyc.mjs";import{t as v}from"./serialize-sql-DiRzL7A4.mjs";const u="__lunora_search_state",W=i=>{const n=()=>{try{f(i,e`ALTER TABLE ${e.identifier(u)} ADD COLUMN ${e.identifier("profile")} TEXT`)}catch{}};f(i,e`CREATE TABLE IF NOT EXISTS ${e.identifier(u)} (${e.identifier("companion")} TEXT PRIMARY KEY, ${e.identifier("cursor")} TEXT, ${e.identifier("done")} INTEGER NOT NULL DEFAULT 0, ${e.identifier("profile")} TEXT)`),n()},j=i=>i===1||i===!0||i==="1",z=(i,n)=>{const r=f(i,e`SELECT ${e.identifier("cursor")}, ${e.identifier("done")}, ${e.identifier("profile")} FROM ${e.identifier(u)} WHERE ${e.identifier("companion")} = ${n}`).toArray()[0];return r?{cursor:r.cursor??void 0,done:j(r.done),profile:r.profile??void 0}:{cursor:void 0,done:!1,profile:void 0}},H=(i,n,r,o,d)=>{const a=r??null;f(i,e`INSERT INTO ${e.identifier(u)} (${e.identifier("companion")}, ${e.identifier("cursor")}, ${e.identifier("done")}, ${e.identifier("profile")}) VALUES (${n}, ${a}, ${o?1:0}, ${d}) ON CONFLICT (${e.identifier("companion")}) DO UPDATE SET ${e.identifier("cursor")} = excluded.${e.identifier("cursor")}, ${e.identifier("done")} = excluded.${e.identifier("done")}, ${e.identifier("profile")} = excluded.${e.identifier("profile")}`)},P=(i,n,r)=>{const o=y(n,r.name);if(f(i,e`SELECT COUNT(*) AS count FROM ${e.identifier(o)}`).one().count>0)return;const d=r.by??[],a=new Map,c=f(i,e`SELECT id, _creationTime, ${e.identifier(m)} FROM ${e.identifier(n)}`).toArray();for(const s of c){const t=O(s);if(!t||r.where&&!h(t,r.where))continue;const E=M(d,t);C(a,E,r,t)}for(const[s,t]of a)f(i,e`INSERT INTO ${e.identifier(o)} (${F}, ${b}, ${x}) VALUES (${s}, ${t.value}, ${t.count})`)},re=(i,n)=>{for(const[r,o]of Object.entries(n.tables))if(!(o.shardMode?.kind==="global"||!o.aggregateIndexes))for(const d of o.aggregateIndexes)P(i,r,d)},Y=(i,n,r)=>{const o=X(n,r.name);if(f(i,e`SELECT COUNT(*) AS count FROM ${e.identifier(o)}`).one().count>0)return;const d=r.sortBy.map((s,t)=>k(t)),a=e.join(["__id__","__partition__",...d].map(s=>e.identifier(s)),e`, `),c=f(i,e`SELECT id, _creationTime, ${e.identifier(m)} FROM ${e.identifier(n)}`).toArray();for(const s of c){const t=O(s);if(!t||r.where&&!w(t,r.where))continue;const E=B(r.partitionBy??[],t),l=r.sortBy.map(T=>v(t[T.field]??null)),$=e.join([t._id,E,...l].map(T=>U(T)),e`, `);f(i,e`INSERT INTO ${e.identifier(o)} (${a}) VALUES (${$})`)}},oe=(i,n)=>{for(const[r,o]of Object.entries(n.tables))if(!(o.shardMode?.kind==="global"||!o.rankIndexes))for(const d of o.rankIndexes)Y(i,r,d)},S=500,R=(i,n,r)=>{const o=I(n,r.name),{profile:d}=L(r.language),a=N(z(i,o),d);if(a.finished)return!0;a.wipe&&f(i,e`DELETE FROM ${e.identifier(o)}`);const{cursor:c}=a,s=f(i,c===void 0?e`SELECT id, _creationTime, ${e.identifier(m)} FROM ${e.identifier(n)} ORDER BY id ASC LIMIT ${e.raw(String(S))}`:e`SELECT id, _creationTime, ${e.identifier(m)} FROM ${e.identifier(n)} WHERE id > ${c} ORDER BY id ASC LIMIT ${e.raw(String(S))}`).toArray();let t=c;for(const l of s){const{id:$}=l;if(typeof $!="string")continue;t=$;const T=D(l);if(!T){f(i,e`DELETE FROM ${e.identifier(o)} WHERE ${e.identifier(p)} = ${$}`);continue}f(i,e`DELETE FROM ${e.identifier(o)} WHERE ${e.identifier(p)} = ${$}`),f(i,e`INSERT INTO ${e.identifier(o)} (${e.identifier(A)}, ${e.identifier(p)}) VALUES (${_(T,r)}, ${$})`)}const E=s.length<S;return H(i,o,t,E,d),E},ne=(i,n,r)=>{if(g(i))for(const o of r.searchIndexes??[])o.staged||R(i,n,o)},te=(i,n)=>{if(g(i)){W(i);for(const[r,o]of Object.entries(n.tables))if(!(o.shardMode?.kind==="global"||!o.searchIndexes))for(const d of o.searchIndexes){let a=!1;for(;!a;)a=R(i,r,d)}}};export{re as H,oe as P,te as X,ne as Y,W as l,u as o};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{sql as e}from"drizzle-orm";import{r as m}from"./do-exec-BLe9lLrN.mjs";import{s as c,g as l,$}from"./do-sql-x0AjZhaN.mjs";import{compileWhereSql as h}from"./compileWhereSql-BLcfs4QW.mjs";import{t as u}from"./serialize-sql-DiRzL7A4.mjs";const g={fieldRef:$,serialize:u},S=i=>{if(i.length!==0)return e`id IN (${e.join(i.map(r=>e`${r}`),e`, `)})`},a=(i,r)=>{const t=[];r&&t.push(r);const o=h(i,g);return o&&t.push(o),t.length===0?e``:e` WHERE ${e.join(t,e` AND `)}`},A=(i,r,t)=>{const o=a(t,void 0),d=m(i,e`SELECT id, _creationTime, ${e.identifier(c)} FROM ${e.identifier(r)}${o}`).toArray(),n=[];for(const s of d){const f=l(s),{id:p}=s;f!==void 0&&typeof p=="string"&&n.push({doc:f,id:p})}return n},M=(i,r,t,o)=>{if(o.length===0)return new Set;const d=a(t,S(o)),n=m(i,e`SELECT id FROM ${e.identifier(r)}${d}`).toArray();return new Set(n.map(s=>s.id))};export{M as a,A as s};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{sql as i}from"drizzle-orm";import{r as c}from"./do-exec-BLe9lLrN.mjs";const n="__doc__",m=(e,t)=>`${e}__geo_${t}`,s=e=>`"${e.replaceAll('"','""')}"`,f=e=>e==="_id"||e==="id"?"id":e==="_creationTime"?"_creationTime":`json_extract(${n}, '$.${e.replaceAll("'","''")}')`,I=e=>i.raw(f(e)),T=(e,t)=>{const r=s(e);return t==="_id"||t==="id"?`${r}.id`:t==="_creationTime"?`${r}._creationTime`:`json_extract(${r}.${n}, '$.${t.replaceAll("'","''")}')`},N=(e,t)=>i.raw(T(e,t)),S=(e,t,r,o)=>i`CREATE ${o?i`UNIQUE `:i``}INDEX IF NOT EXISTS ${i.identifier(e)} ON ${i.identifier(t)} (${r})`,a=i.identifier("__key__"),l=i.identifier("__value__"),d=i.identifier("__count__"),A=(e,t,r,o,_)=>i`INSERT INTO ${i.identifier(e)} (${a}, ${l}, ${d}) VALUES (${t}, ${r}, ${o}) ON CONFLICT(${a}) DO UPDATE SET ${_}`,O=e=>{const t=[];for(const[r,o]of Object.entries(e.shape)){const _=o._meta?.column;_&&t.push([r,_])}return t},u=e=>{if(!e)return;const t=e[n];let r;typeof t=="string"?r=JSON.parse(t):t&&typeof t=="object"?r=t:r={};const{id:o}=e;typeof o=="string"&&(r._id=o);const _=e._creationTime;return typeof _=="number"&&(r._creationTime=_),r},y=e=>{try{return u(e)}catch{return}},$=new WeakMap,b=e=>{const t=$.get(e);if(t!==void 0)return t;let r;try{c(e,i`CREATE VIRTUAL TABLE IF NOT EXISTS ${i.identifier("__lunora_fts_probe")} USING fts5(x)`),r=!0}catch{r=!1}finally{try{c(e,i`DROP TABLE IF EXISTS ${i.identifier("__lunora_fts_probe")}`)}catch{}}return $.set(e,r),r};export{I as $,A as E,O as L,y as N,N as S,m as T,l as _,a,b,u as g,s as l,d as m,S as p,n as s};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{LunoraError as f}from"@lunora/errors";import{sql as m}from"drizzle-orm";import{r as T}from"./do-exec-BLe9lLrN.mjs";import{runExternalSourceTick as v,materializeExternalRowsIncremental as A}from"./materializeExternalRows-
|
|
1
|
+
import{LunoraError as f}from"@lunora/errors";import{sql as m}from"drizzle-orm";import{r as T}from"./do-exec-BLe9lLrN.mjs";import{runExternalSourceTick as v,materializeExternalRowsIncremental as A}from"./materializeExternalRows-BUmj_9WO.mjs";const h="__lunora_source_cursor",D=e=>e instanceof Date?`d:${e.toISOString()}`:typeof e=="bigint"?`b:${e.toString()}`:typeof e=="number"?`n:${e.toString()}`:`s:${e}`,O=e=>{const t=e.slice(2);switch(e[0]){case"b":return BigInt(t);case"d":return new Date(t);case"n":return Number(t);default:return t}},N=/^-?\d+$/,I=/^-?\d+(?:\.\d+)?$/,M=(e,t)=>e instanceof Date&&t instanceof Date?e.getTime()>t.getTime():typeof e=="bigint"&&typeof t=="bigint"||typeof e=="number"&&typeof t=="number"?e>t:typeof e=="string"&&typeof t=="string"&&I.test(e)&&I.test(t)?N.test(e)&&N.test(t)?BigInt(e)>BigInt(t):Number(e)>Number(t):String(e)>String(t),q=(e,t,o)=>{let r=o===null?void 0:O(o);for(const n of e){const s=n[t];if(s==null)continue;const c=s;(r===void 0||M(c,r))&&(r=c)}return r===void 0?null:D(r)},C=e=>{T(e,m`CREATE TABLE IF NOT EXISTS ${m.identifier(h)} (
|
|
2
2
|
table_name TEXT NOT NULL,
|
|
3
3
|
shard_key TEXT NOT NULL,
|
|
4
4
|
watermark TEXT,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{applyCdcChanges as m}from"./CDC_LOG_TABLE-E_J5LPoK.mjs";import{s as f}from"./ctx-db-shapes-
|
|
1
|
+
import{applyCdcChanges as m}from"./CDC_LOG_TABLE-E_J5LPoK.mjs";import{s as f}from"./ctx-db-shapes-CHC2cS0g.mjs";import{diffExternalSource as g,projectExternalSourceRow as c}from"./diffExternalSource-DMpkJta1.mjs";import{stableStringify as p}from"./stableStringify-BjLh4gvA.mjs";const x=async(t,s,r,e)=>{const{changes:n,nextBaseline:a}=g(s,r,e);return await m(t,n),{applied:n.length,nextBaseline:a}},E=async(t,s,r)=>{const{columns:e,deletedIds:n,table:a}=r,i=[];for(const u of s){const l=c(u,e),o=String(l._id);if(n?.has(o)){await t.get(o,a)&&i.push({id:o,op:"delete",seq:0,table:a,ts:0});continue}const d=await t.get(o,a);d&&p(c({...d,_id:o},e))===p(l)||i.push({doc:l,id:o,op:"insert",seq:0,table:a,ts:0})}return await m(t,i),{applied:i.length}},w=(t,s,r)=>{const e=new Map;for(const{doc:n,id:a}of f(t,s,void 0))e.set(a,p(c({...n,_id:a},r)));return e},R=async(t,s,r,e)=>{const n=w(t,e.table,e.columns);return x(s,r,n,e)};export{x as materializeExternalRows,E as materializeExternalRowsIncremental,w as readExternalSourceBaseline,R as runExternalSourceTick};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import{ftsTableName as N,FTS_TEXT_COLUMN as I,FTS_ID_COLUMN as g}from"@lunora/search-core";import{sql as e}from"drizzle-orm";import{aggregateTableName as R}from"./aggregateTableName-G-eXyjcz.mjs";import{l as S,Y as l}from"./ctx-db-backfill-C4rAzsQo.mjs";import{migrateCdcLog as O,migrateCdcMeta as p}from"./CDC_LOG_TABLE-E_J5LPoK.mjs";import{_ as C,E as U,a as u}from"./ctx-db-idempotency-wiVoGnpQ.mjs";import{r as _}from"./do-exec-BLe9lLrN.mjs";import{s as X,$,p as f,L as h,b,a as B,_ as M,m,T as x}from"./do-sql-x0AjZhaN.mjs";import{sortColumnName as Y,rankTableName as F}from"./RANK_TIEBREAK-DtX8zQyc.mjs";const D=(i,o,t)=>{for(const n of t.indexes){const r=`${o}_${n.name}`,a=e.join(n.fields.map(s=>$(s)),e`, `);_(i,f(r,o,a,n.unique??!1))}for(const[n,r]of h(t)){if(!r.unique)continue;const a=`${o}_unique_${n}`;_(i,f(a,o,$(n),!0))}},k=(i,o,t)=>{if(!(!t.searchIndexes||t.searchIndexes.length===0||!b(i))){for(const n of t.searchIndexes){const r=N(o,n.name);_(i,e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(r)} USING fts5(${e.identifier(I)}, ${e.identifier(g)} UNINDEXED)`),_(i,e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(`${r}__vocab`)} USING fts5vocab(${e.identifier(r)}, ${e.raw("instance")})`)}l(i,o,t)}},y=(i,o,t)=>{if(t.geoIndexes)for(const n of t.geoIndexes){const r=x(o,n.name);_(i,e`CREATE TABLE IF NOT EXISTS ${e.identifier(r)} (${e.identifier("__id__")} TEXT PRIMARY KEY, ${e.identifier("__geohash__")} TEXT NOT NULL, ${e.identifier("__lat__")} REAL NOT NULL, ${e.identifier("__lng__")} REAL NOT NULL)`);const a=`${o}__geo_${n.name}__btree`;_(i,f(a,r,e`${e.identifier("__geohash__")} ASC, ${e.identifier("__id__")} ASC`,!1))}},G=(i,o,t)=>{if(t.aggregateIndexes)for(const n of t.aggregateIndexes){const r=R(o,n.name);_(i,e`CREATE TABLE IF NOT EXISTS ${e.identifier(r)} (${B} TEXT PRIMARY KEY, ${M} REAL, ${m} INTEGER NOT NULL DEFAULT 0)`),_(i,e`PRAGMA table_info(${e.identifier(r)})`).toArray().some(a=>a.name==="__count__")||_(i,e`ALTER TABLE ${e.identifier(r)} ADD COLUMN ${m} INTEGER NOT NULL DEFAULT 0`)}},P=(i,o,t)=>{if(t.rankIndexes)for(const n of t.rankIndexes){const r=F(o,n.name),a=n.sortBy.map((T,E)=>Y(E)),s=a.map(T=>e`${e.identifier(T)} BLOB`),L=s.length>0?e`, ${e.join(s,e`, `)}`:e``;_(i,e`CREATE TABLE IF NOT EXISTS ${e.identifier(r)} (${e.identifier("__id__")} TEXT PRIMARY KEY, ${e.identifier("__partition__")} TEXT NOT NULL${L})`);const d=[e`${e.identifier("__partition__")} ASC`];for(const[T,E]of a.entries()){const A=n.sortBy[T]?.direction;d.push(e`${e.identifier(E)} ${e.raw(A==="desc"?"DESC":"ASC")}`)}d.push(e`${e.identifier("__id__")} ASC`);const c=`${o}__rank_${n.name}__btree`;_(i,f(c,r,e.join(d,e`, `),!1))}},Q=(i,o,t={})=>{S(i);for(const[n,r]of Object.entries(o.tables))r.shardMode?.kind!=="global"&&(_(i,e`CREATE TABLE IF NOT EXISTS ${e.identifier(n)} (
|
|
2
|
+
id TEXT PRIMARY KEY,
|
|
3
|
+
_creationTime REAL NOT NULL,
|
|
4
|
+
${e.identifier(X)} TEXT NOT NULL
|
|
5
|
+
)`),D(i,n,r),k(i,n,r),y(i,n,r),G(i,n,r),P(i,n,r));t.cdc&&(O(i),p(i),C(i)),U(i),u(i)};export{Q as runShardMigrations};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{sql as e}from"drizzle-orm";import{r as
|
|
1
|
+
import{sql as e}from"drizzle-orm";import{r as p}from"./do-exec-BLe9lLrN.mjs";import{$ as o}from"./do-sql-x0AjZhaN.mjs";const E=(s,i,d,r)=>{const a=d-(i.after??0),t=[e`${o(i.field)} IS NOT NULL`,e`${o(i.field)} < ${a}`];i.softDeleteField!==void 0&&t.push(e`${o(i.softDeleteField)} IS NULL`);const f=e`SELECT id FROM ${e.identifier(i.table)} WHERE ${e.join(t,e` AND `)} LIMIT ${e.raw(String(Math.max(0,Math.floor(r))+1))}`,l=p(s,f).toArray(),n=l.length>r,m=l.slice(0,r).map($=>$.id);return{hasMore:n,ids:m}};export{E as selectExpiredIds};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/do",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.52",
|
|
4
4
|
"description": "Lunora Durable Objects: ShardDO (SQLite, OCC, hibernated WebSocket subscriptions) and SessionDO",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cloudflare",
|
|
@@ -49,7 +49,8 @@
|
|
|
49
49
|
"@lunora/errors": "1.0.0-alpha.8",
|
|
50
50
|
"@lunora/fingerprint": "1.0.0-alpha.4",
|
|
51
51
|
"@visulima/redact": "3.0.0",
|
|
52
|
-
"drizzle-orm": "^0.45.2"
|
|
52
|
+
"drizzle-orm": "^0.45.2",
|
|
53
|
+
"@lunora/search-core": "1.0.0-alpha.0"
|
|
53
54
|
},
|
|
54
55
|
"engines": {
|
|
55
56
|
"node": "^22.15.0 || >=24.11.0"
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as N}from"@lunora/errors";import{sql as t}from"drizzle-orm";import{matchesStaticWhere as Be,aggregateSqlFunction as Ne,normalizeCountArgument as bt,throwingScheduler as yt}from"./AGGREGATE_SQL_FUNCTION-QYaiuty4.mjs";import{encodeAggregateKey as de,foldAggregateTally as _t,aggregateTableName as Te,coerceAggregateNumber as Fe,readAggregateValue as qe}from"./aggregateTableName-G-eXyjcz.mjs";import{mergeWhere as oe,CountRlsUnsupportedError as Ue,selectIndexForGroupBy as Nt,selectIndexForCount as Tt,selectIndexForAggregate as Rt}from"./CountRlsUnsupportedError-Cl8XpYDL.mjs";import{appendCdcChange as St}from"./CDC_LOG_TABLE-E_J5LPoK.mjs";import{CDC_LOG_TABLE as Qn,applyCdcChanges as Xn,bumpCdcEpoch as Zn,minCdcSeq as er,readCdcChanges as tr,readCdcCursor as nr,readCdcEpoch as rr,trimCdcChanges as ir}from"./CDC_LOG_TABLE-E_J5LPoK.mjs";import{r as v}from"./do-exec-BLe9lLrN.mjs";import{N as st,s as X,L as fe,a as ce,d as te,m as Q,g as lt,p as Le,T as ee,u as At,E as dt,$ as Ye}from"./do-sql-BYIQTG3z.mjs";import{param as Ke}from"./renderSql-B5lF5Jd9.mjs";import{encodeGeohash as It,GEO_DEFAULT_PRECISION as vt,coveringGeohashes as kt,boundingBoxGeohashes as Mt,pointInBoundingBox as Lt,haversineMeters as xt}from"./GEO_DEFAULT_PRECISION-okRCkZ6r.mjs";import{sortColumnName as Se,matchesRankStaticWhere as ct,encodePartitionKey as De,rankTableName as Ae,resolveRankPartition as ft,RANK_TIEBREAK as we}from"./RANK_TIEBREAK-DtX8zQyc.mjs";import{stringifySearchText as ut,ftsTableName as ht,tokenizeSearch as $t,buildFtsMatch as Ct,scoreDocument as Dt}from"./buildFtsMatch-CV0Z7PWv.mjs";import{t as ue}from"./serialize-sql-DiRzL7A4.mjs";import{SCAN_DEP as Y}from"./SCAN_DEP-D_yR9EeV.mjs";import{decodeCursor as Ce,normalizeOrderKeys as Ot,buildSeekWhere as pt,applySelect as Qe,encodeCursor as Pe,softDeleteScope as Ee,buildSeekBeforeWhere as Wt}from"./applySelect-Bq2KOrkL.mjs";import Bt from"./NotFoundError-J3tjf4Uo.mjs";import{assertFlatPredicate as je,resolveRelationPredicates as Xe}from"./DEFAULT_MAX_RELATION_KEYS-BRdmX7WW.mjs";import{runRowValidators as He,resolveWith as Ze,applyOnDelete as Ft,fanOutScalarCounts as qt}from"./applyOnDelete-BvQN7pDL.mjs";import{guardWriter as Ut}from"./RLS_UNWRAP_SYMBOL-C6_WX3dG.mjs";import{createSystemReader as jt}from"./createSystemReader-DcDcrtM3.mjs";import{ConflictError as Re}from"./ConflictError-C8GtJmjS.mjs";import{runTriggers as Ht}from"./hasTrigger-_rexbWMO.mjs";import{compileWhereSql as he}from"./compileWhereSql-BLcfs4QW.mjs";import{backfillAggregateIndexes as ar,backfillRankIndexes as sr}from"./backfillAggregateIndexes-BAQ3Fwwh.mjs";import{e as dr,t as cr,r as fr,o as ur,l as hr,p as $r,_ as pr,a as wr,b as mr,d as gr,m as Er,u as br,S as yr,T as _r}from"./ctx-db-idempotency-wiVoGnpQ.mjs";import{runShardMigrations as Tr}from"./runShardMigrations-bxOHpfID.mjs";import{a as Sr,s as Ar}from"./ctx-db-shapes-DzX_H5q8.mjs";const Pt=(i,o,n)=>[...i.partitionBy??[],...i.sortBy.map(s=>s.field),...i.where?Object.keys(i.where):[]].every(s=>o[s]===n[s]),Gt=(i,o,n,s,l,c)=>{if(l&&c&&Pt(n,l,c))return;const E=Ae(o,n.name);if(l&&v(i,t`DELETE FROM ${t.identifier(E)} WHERE ${t.identifier("__id__")} = ${s}`),!c||n.where&&!ct(c,n.where))return;const w=n.sortBy.map((u,S)=>Se(S)),_=t.join(["__id__","__partition__",...w].map(u=>t.identifier(u)),t`, `),T=De(n.partitionBy??[],c),k=n.sortBy.map(u=>ue(c[u.field]??null)),b=t.join([s,T,...k].map(u=>Ke(u)),t`, `);v(i,t`INSERT INTO ${t.identifier(E)} (${_}) VALUES (${b})`)},Kt=i=>{const{broadcast:o,invalidateCache:n,recordCdc:s,schema:l,sql:c}=i,E=new Set,w=new Set,_=(A,m)=>{const I=`${A}::${m.name}`;if(E.has(I))return;const F=Te(A,m.name),W=m.by??[],H=new Map,j=v(c,t`SELECT id, _creationTime, ${t.identifier(X)} FROM ${t.identifier(A)}`).toArray();for(const q of j){const L=fe(q);if(!L||m.where&&!Be(L,m.where))continue;const P=de(W,L);_t(H,P,m,L)}v(c,t`DELETE FROM ${t.identifier(F)}`);const G=32,B=[...H];for(let q=0;q<B.length;q+=G){const L=B.slice(q,q+G),P=t.join(L.map(([U,V])=>t`(${U}, ${V.value}, ${V.count})`),t`, `);v(c,t`INSERT INTO ${t.identifier(F)} (${ce}, ${te}, ${Q}) VALUES ${P}`)}E.add(I)},T=(A,m,I)=>{const F=m.by??[],W=Ne(m.op),H=m.field??"",j=[];for(const q of F){const L=ue(I[q]??null);L===null?j.push(t`${ee(q)} IS NULL`):j.push(t`${ee(q)} = ${L}`)}for(const[q,L]of Object.entries(m.where??{})){const P=L!==null&&typeof L=="object"&&!Array.isArray(L)?L.eq:L,U=ue(P);U===null?j.push(t`${ee(q)} IS NULL`):j.push(t`${ee(q)} = ${U}`)}const G=j.length>0?t` WHERE ${t.join(j,t` AND `)}`:t``,B=ee(H);return{value:v(c,t`SELECT ${t.raw(W)}(${B}) AS value FROM ${t.identifier(A)}${G}`).one().value??null}},k=(A,m,I,F)=>{const W=Te(A,m.name),{op:H}=m,j=m.field??"",G=L=>{v(c,t`DELETE FROM ${t.identifier(W)} WHERE ${ce} = ${L} AND ${Q} <= 0`)},B=I&&(!m.where||Be(I,m.where))?I:void 0,q=F&&(!m.where||Be(F,m.where))?F:void 0;if(!(!B&&!q)){if(H==="count"){for(const[L,P]of[[B,-1],[q,1]]){if(!L)continue;const U=de(m.by??[],L);v(c,Le(W,U,P,P,t`${te} = ${te} + excluded.${te}, ${Q} = ${Q} + excluded.${Q}`))}B&&G(de(m.by??[],B));return}if(H==="sum"||H==="avg"){for(const[L,P]of[[B,-1],[q,1]]){if(!L)continue;const U=Fe(L[j]);if(U===void 0)continue;const V=de(m.by??[],L);v(c,Le(W,V,P*U,P,t`${te} = COALESCE(${te}, 0) + excluded.${te}, ${Q} = ${Q} + excluded.${Q}`))}B&&G(de(m.by??[],B));return}if(B){const L=de(m.by??[],B),P=Fe(B[j]),U=v(c,t`SELECT ${te} AS value, ${Q} AS count FROM ${t.identifier(W)} WHERE ${ce} = ${L}`).toArray()[0],V=(U?.count??0)-1;if(V<=0)v(c,t`DELETE FROM ${t.identifier(W)} WHERE ${ce} = ${L}`);else if(U&&P!==void 0&&U.value!==null&&P===U.value){const re=T(A,m,B);v(c,t`UPDATE ${t.identifier(W)} SET ${te} = ${re.value}, ${Q} = ${V} WHERE ${ce} = ${L}`)}else v(c,t`UPDATE ${t.identifier(W)} SET ${Q} = ${Q} - 1 WHERE ${ce} = ${L}`)}if(q){const L=de(m.by??[],q),P=Fe(q[j]);if(P===void 0)v(c,Le(W,L,null,1,t`${Q} = ${Q} + 1`));else{const U=H==="min"?"MIN":"MAX";v(c,Le(W,L,P,1,t`${te} = ${t.raw(U)}(COALESCE(${te}, excluded.${te}), excluded.${te}), ${Q} = ${Q} + 1`))}}}},b=A=>{const m=l.tables[A]?.aggregateIndexes;if(!(!m||m.length===0))for(const I of m)_(A,I)},u=(A,m,I)=>{const F=l.tables[A]?.aggregateIndexes;if(!(!F||F.length===0))for(const W of F)k(A,W,m,I)},S=(A,m)=>{const I=`${A}::rank::${m.name}`;if(w.has(I))return;const F=Ae(A,m.name),W=v(c,t`SELECT id, _creationTime, ${t.identifier(X)} FROM ${t.identifier(A)}`).toArray();v(c,t`DELETE FROM ${t.identifier(F)}`);const H=m.sortBy.map((G,B)=>Se(B)),j=t.join(["__id__","__partition__",...H].map(G=>t.identifier(G)),t`, `);for(const G of W){const B=fe(G);if(!B||m.where&&!ct(B,m.where))continue;const q=De(m.partitionBy??[],B),L=m.sortBy.map(U=>ue(B[U.field]??null)),P=t.join([B._id,q,...L].map(U=>Ke(U)),t`, `);v(c,t`INSERT INTO ${t.identifier(F)} (${j}) VALUES (${P})`)}w.add(I)},M=A=>{const m=l.tables[A]?.rankIndexes;if(!(!m||m.length===0))for(const I of m)S(A,I)},D=(A,m,I,F)=>{const W=l.tables[A]?.rankIndexes;if(!(!W||W.length===0))for(const H of W)Gt(c,A,H,m,I,F)},O=(A,m,I)=>{const F=l.tables[A]?.searchIndexes;if(!(!F||F.length===0||!st(c)))for(const W of F){const H=ht(A,W.name);v(c,t`DELETE FROM ${t.identifier(H)} WHERE ${t.identifier("__id__")} = ${m}`),I&&v(c,t`INSERT INTO ${t.identifier(H)} (${t.identifier("__text__")}, ${t.identifier("__id__")}) VALUES (${ut(I[W.field])}, ${m})`)}},Z=(A,m,I)=>{const F=l.tables[A]?.geoIndexes;if(!(!F||F.length===0))for(const W of F){const H=lt(A,W.name);v(c,t`DELETE FROM ${t.identifier(H)} WHERE ${t.identifier("__id__")} = ${m}`);const j=I?.[W.field];if(j!==null&&typeof j=="object"&&typeof j.lat=="number"&&typeof j.lng=="number"){const{lat:G,lng:B}=j,q=It({lat:G,lng:B},W.precision??vt);v(c,t`INSERT INTO ${t.identifier(H)} (${t.identifier("__id__")}, ${t.identifier("__geohash__")}, ${t.identifier("__lat__")}, ${t.identifier("__lng__")}) VALUES (${m}, ${q}, ${G}, ${B})`)}}};return{ensureBackfilledForTable:b,ensureBackfilledIndex:_,ensureRankBackfilled:S,ensureRankBackfilledForTable:M,syncAggregates:u,syncCompanionsForInsert:(A,m,I)=>{O(A,m,I),Z(A,m,I),u(A,void 0,I),D(A,m,void 0,I),n(A,m),s(A,m,"insert",I),o({key:m,op:"insert",row:I,table:A})},syncGeo:Z,syncRanks:D,syncSearch:O}},Vt="__doc__",Jt=i=>{const o=JSON.stringify(i),n=new TextEncoder().encode(o);let s="";for(const l of n)s+=String.fromCodePoint(l);return btoa(s)},zt=i=>i.after?[i.after.partitionKey,...i.after.sortValues,i.after.rowId]:i.cursor?Ce(i.cursor):void 0,Yt=(i,o,n)=>{if(i?.length!==1+o.length+1)return;const s=[{column:"__partition__",direction:"asc"}];for(const[c,E]of o.entries())s.push({column:E,direction:n[c]?.direction??"asc"});s.push({column:we,direction:"asc"});const l=[];for(const[c,E]of s.entries()){const w=[];for(const[T,k]of s.slice(0,c).entries())w.push(t`${t.identifier(k.column)} IS ${i[T]}`);w.push(t`${t.identifier(E.column)} ${t.raw(E.direction==="desc"?"<":">")} ${i[c]}`);const[_]=w;l.push(w.length===1&&_!==void 0?_:t`(${t.join(w,t` AND `)})`)}return t`(${t.join(l,t` OR `)})`},wt=null,Qt=(i,o)=>{if(i===void 0)return wt;const n=[i.__partition__,...o.map(s=>i[s]),i[we]];return Jt(n)},Xt=(i,o,n)=>{const s=[];for(const l of i){const c=l[we];if(typeof c!="string")continue;const E=o.get(c);if(!E)continue;const w=typeof l.__partition__=="string"?l.__partition__:"",_=n.map(T=>l[T]??null);s.push({doc:E,key:{partitionKey:w,rowId:c,sortValues:_}})}return s},Zt=(i,o,n)=>{const{rowToDocument:s}=i,l=new Map;if(n.length===0)return l;const c=t.join(n.map(w=>Ke(w)),t`, `),E=v(i.sql,t`SELECT id, _creationTime, ${t.identifier(Vt)} FROM ${t.identifier(o)} WHERE id IN (${c})`).toArray();for(const w of E){const _=s(w),T=w.id;_&&typeof T=="string"&&l.set(T,_)}return l},et=(i,o,n,s)=>{const{assertRankPartitionLocal:l,ensureRankBackfilled:c,onRead:E,schema:w}=i,_=w.tables[o];if(!_)throw new N("INTERNAL",`unknown table: ${o}`);const T=_.rankIndexes?.find(V=>V.name===n);if(!T)throw new N("INTERNAL",`unknown rankIndex "${n}" on table "${o}"`);l(o,_,T),E(o,Y),c(o,T);const k=Ae(o,T.name),b=T.sortBy.map((V,re)=>Se(re)),u=Math.max(1,Math.min(1e3,Math.floor(s.take??100))),S=oe(s.baseWhere,s.where),M=ft(T,S),D=[t`${t.identifier("__partition__")} ASC`];for(const[V,re]of b.entries()){const se=T.sortBy[V]?.direction;D.push(t`${t.identifier(re)} ${t.raw(se==="desc"?"DESC":"ASC")}`)}D.push(t`${t.identifier(we)} ASC`);const O=[];typeof s.partitionKey=="string"?O.push(t`${t.identifier("__partition__")} = ${s.partitionKey}`):M&&O.push(t`${t.identifier("__partition__")} = ${De(T.partitionBy??[],M)}`);const Z=zt(s),A=Yt(Z,b,T.sortBy);A&&O.push(A);const m=t.identifier(we),I=t.identifier("__partition__"),F=O.length>0?t` WHERE ${t.join(O,t` AND `)}`:t``,W=b.length>0?t`${m}, ${I}, ${t.join(b.map(V=>t.identifier(V)),t`, `)}`:t`${m}, ${I}`,H=t`SELECT ${W} FROM ${t.identifier(k)}${F} ORDER BY ${t.join(D,t`, `)} LIMIT ${t.raw(String(u+1))}`,j=v(i.sql,H).toArray(),G=j.length>u,B=G?j.slice(0,u):j,q=B.map(V=>V[we]),L=Xt(B,Zt(i,o,q),b),P=G?Qt(B.at(-1),b):wt,U=T.sortBy.map(V=>V.direction==="desc"?"desc":"asc");return{continueCursor:P,directions:U,hasMore:G,rows:L}},en=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,tn=i=>{if(!en.test(i))throw new N("INTERNAL",`invalid clientId ${JSON.stringify(i)}: a client-supplied row id must be a UUID`)},tt=50,mt=500,ge=(i,o,n)=>{const s=o??mt;if(i>s)throw new N("BATCH_LIMIT_EXCEEDED",`${n}: batch of ${String(i)} exceeds the limit of ${String(s)} (raise options.limit or chunk the call)`,{status:400})},nn=i=>{const o={eq:(n,s)=>(i.sqlConditions.push({comparator:"=",field:n,value:s}),o),gt:(n,s)=>(i.sqlConditions.push({comparator:">",field:n,value:s}),o),gte:(n,s)=>(i.sqlConditions.push({comparator:">=",field:n,value:s}),o),lt:(n,s)=>(i.sqlConditions.push({comparator:"<",field:n,value:s}),o),lte:(n,s)=>(i.sqlConditions.push({comparator:"<=",field:n,value:s}),o)};return o},rn=(i,o)=>{const n={eq:(s,l)=>{if(!i.definition.filterFields?.includes(s))throw new N("INTERNAL",`field "${s}" is not a filter field of search index "${i.indexName}" on table "${o}"`);return i.filters.push({field:s,value:l}),n},search:(s,l)=>{if(s!==i.definition.field)throw new N("INTERNAL",`search index "${i.indexName}" on table "${o}" indexes "${i.definition.field}", not "${s}"`);const c=i;return c.field=s,c.query=l,c.hasQuery=!0,n}};return n},on=(i,o,n,s,l)=>{const c=$t(n.query);if(c.length===0)return[];const E=ht(o,n.indexName),w=[t`f.${t.identifier("__text__")} MATCH ${Ct(c)}`];for(const b of n.filters)w.push(t`${ee(b.field)} = ${ue(b.value)}`);l&&w.push(l);let _=t`SELECT m.id, m._creationTime, m.${t.identifier(X)} FROM ${t.identifier(E)} f JOIN ${t.identifier(o)} m ON m.id = f.${t.identifier("__id__")} WHERE ${t.join(w,t` AND `)} ORDER BY f.rank, m._creationTime DESC`;typeof s=="number"&&(_=t`${_} LIMIT ${t.raw(String(Math.max(0,Math.floor(s))))}`);const T=v(i,_).toArray(),k=[];for(const b of T){const u=fe(b);u&&k.push(u)}return k},an=(i,o,n,s,l)=>{const c=$t(n.query);if(c.length===0)return[];const E=[];for(const b of n.filters)E.push(t`${ee(b.field)} = ${ue(b.value)}`);l&&E.push(l);let w=t`SELECT id, _creationTime, ${t.identifier(X)} FROM ${t.identifier(o)}`;E.length>0&&(w=t`${w} WHERE ${t.join(E,t` AND `)}`);const _=v(i,w).toArray(),T=[];for(const b of _){const u=fe(b);if(!u)continue;const S=Dt(ut(u[n.field]),c);S>0&&T.push({creationTime:typeof u._creationTime=="number"?u._creationTime:0,doc:u,score:S})}T.sort((b,u)=>u.score-b.score||u.creationTime-b.creationTime);const k=T.map(b=>b.doc);return typeof s=="number"?k.slice(0,Math.max(0,Math.floor(s))):k},sn=(i,o)=>{const n=i,s={near:(l,c)=>{if(n.within)throw new N("INTERNAL",`geo index "${n.indexName}" on table "${o}": call .near() or .within(), not both`);return n.near={point:{lat:l.lat,lng:l.lng},radiusMeters:c},s},within:l=>{if(n.near)throw new N("INTERNAL",`geo index "${n.indexName}" on table "${o}": call .near() or .within(), not both`);return n.within={ne:{lat:l.ne.lat,lng:l.ne.lng},sw:{lat:l.sw.lat,lng:l.sw.lng}},s}};return s},ln=(i,o)=>{const n=i[o];if(n===null||typeof n!="object")return;const{lat:s,lng:l}=n;return typeof s=="number"&&typeof l=="number"?{lat:s,lng:l}:void 0},dn=(i,o)=>{const n=ln(i,o.definition.field);if(!n)return;const s=typeof i._creationTime=="number"?i._creationTime:0;if(o.near){const l=xt(o.near.point,n);return l<=o.near.radiusMeters?{creationTime:s,distance:l}:void 0}return Lt(n,o.within)?{creationTime:s,distance:0}:void 0},cn=(i,o,n,s,l)=>{if(!n.near&&!n.within)throw new N("INTERNAL",`geo index "${n.indexName}" on table "${o}": call .near(point, radius) or .within(box)`);const c=n.near?kt(n.near.point,n.near.radiusMeters):Mt(n.within),E=lt(o,n.indexName),w=c.map(S=>t`(g.${t.identifier("__geohash__")} >= ${S} AND g.${t.identifier("__geohash__")} < ${`${S}{`})`),_=[t`(${t.join(w,t` OR `)})`];l&&_.push(l);const T=t`SELECT m.id, m._creationTime, m.${t.identifier(X)} FROM ${t.identifier(E)} g JOIN ${t.identifier(o)} m ON m.id = g.${t.identifier("__id__")} WHERE ${t.join(_,t` AND `)}`,k=v(i,T).toArray(),b=[];for(const S of k){const M=fe(S),D=M?dn(M,n):void 0;M&&D&&b.push({creationTime:D.creationTime,distance:D.distance,doc:M})}b.sort((S,M)=>S.distance-M.distance||M.creationTime-S.creationTime);const u=b.map(S=>S.doc);return typeof s=="number"?u.slice(0,Math.max(0,Math.floor(s))):u},fn=(i,o,n,s,l)=>{const{geo:c}=n;if(!c)throw new N("INTERNAL","runGeoTerminal called without a staged geo query");const E=n.inMemoryFilters.length>0,w=cn(i,o,c,E?void 0:l,s);if(!E)return w;const _=[];for(const T of w)if(n.inMemoryFilters.every(k=>k(T))&&(_.push(T),typeof l=="number"&&_.length>=l))break;return _},un=(i,o,n,s,l,c)=>{const E=[];for(const k of n.sqlConditions)E.push(t`${ee(k.field)} ${t.raw(k.comparator)} ${ue(k.value)}`);s&&E.push(s);let w=t`SELECT id, _creationTime, ${t.identifier(X)} FROM ${t.identifier(o)}`;E.length>0&&(w=t`${w} WHERE ${t.join(E,t` AND `)}`),w=t`${w} ORDER BY ${l}`,typeof c=="number"&&n.inMemoryFilters.length===0&&(w=t`${w} LIMIT ${t.raw(String(Math.max(0,Math.floor(c))))}`);const _=v(i,w).toArray(),T=[];for(const k of _){const b=fe(k);if(b&&n.inMemoryFilters.every(u=>u(b))&&(T.push(b),typeof c=="number"&&T.length>=c))break}return T},pe={fieldRef:ee,serialize:ue},hn=i=>{let o=0;const n=[],s={fieldRef:ee,relationExists:l=>{const{childWhere:c,negated:E,parentTable:w,relation:_}=l,T=`__rel_${String(o)}`,k=n.at(-1)??w;o+=1,i(_.table,Y);const b=_.kind==="one"?_.field:_.references,u=_.kind==="one"?_.references:_.field,S=t`${Ye(T,u)} = ${Ye(k,b)}`;n.push(T);const M=he(c,s);n.pop();const D=M?t`${S} AND ${M}`:S,O=t`EXISTS (SELECT 1 FROM ${t.identifier(_.table)} AS ${t.identifier(T)} WHERE ${D})`;return E?t`NOT ${O}`:O},serialize:ue};return s},gt=i=>{const o=i.map(n=>t`${ee(n.field)} ${t.raw(n.direction==="desc"?"DESC":"ASC")}`);return i.some(n=>n.field==="_id"||n.field==="id")||o.push(t`${ee("id")} ASC`),t.join(o,t`, `)},$n={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},pn=i=>{const o=i.order;return i.indexFields.length>0?i.indexFields.map(n=>({direction:o,field:n})):[{direction:o,field:"_creationTime"}]},wn=(i,o,n,s)=>{const l=i.sqlConditions.map(c=>({[c.field]:{[$n[c.comparator]??"eq"]:c.value}}));if(n&&l.push(pt(o,Ce(n))),s&&l.push(Wt(o,Ce(s))),l.length!==0)return l.length===1?l[0]:{AND:l}},mn=(i,o,n)=>{const s=[];for(const l of i){const c=fe(l);if(c&&o.every(E=>E(c))&&(s.push(c),n!==void 0&&s.length>n))break}return s},gn=(i,o,n,s,l)=>{const c=Math.max(0,Math.floor(s.numItems)),E=pn(n),w=typeof s.endCursor=="string",_=he(wn(n,E,s.cursor,s.endCursor),pe),T=l&&_?t`${_} AND ${l}`:l??_;let k=t`SELECT id, _creationTime, ${t.identifier(X)} FROM ${t.identifier(o)}`;T&&(k=t`${k} WHERE ${T}`),k=t`${k} ORDER BY ${gt(E)}`;const b=n.inMemoryFilters.length>0;!b&&!w&&(k=t`${k} LIMIT ${t.raw(String(c+1))}`);const u=v(i,k).toArray(),S=mn(u,n.inMemoryFilters,b||w?void 0:c);if(w){const Z=S.length>=2?S[Math.floor(S.length/2)-1]:void 0;return{continueCursor:s.endCursor??null,isDone:!0,page:S,splitCursor:Z?Pe(Z,E):null}}const M=S.length>c,D=M?S.slice(0,c):S,O=D.at(-1);return{continueCursor:M&&O?Pe(O,E):null,isDone:!M,page:D}};class En extends N{constructor(o="unique() found more than one matching document"){super("NOT_UNIQUE",o,{name:"NotUniqueError"})}}const bn=/\s/u,yn=String.fromCodePoint(0),nt=(i,o,n)=>{if(!i.tables[o])throw new N("INTERNAL",`unknown table: ${o}`);return typeof n!="string"||n.length===0||bn.test(n)||n.includes(yn)?null:n},_n=(i,o,n,s=()=>{})=>{const l=o.tables[n];if(!l)throw new N("INTERNAL",`unknown table: ${n}`);const c=Ee(l.softDeleteMode,void 0),E=c?he(c,pe):void 0,w={indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[]},_=u=>{const{search:S}=w;if(!S)throw new N("INTERNAL","runSearchFetch called without a staged search");const M=w.inMemoryFilters.length>0,D=M?void 0:u,O=st(i)?on(i,n,S,D,E):an(i,n,S,D,E);if(!M)return O;const Z=[];for(const A of O)if(w.inMemoryFilters.every(m=>m(A))&&(Z.push(A),typeof u=="number"&&Z.length>=u))break;return Z},T=()=>{const u=w.indexFields.length>0?w.indexFields:["_creationTime"],S=w.order==="desc"?"DESC":"ASC";return t.join(u.map(M=>t`${ee(M)} ${t.raw(S)}`),t`, `)},k=u=>w.search?_(u):w.geo?fn(i,n,w,E,u):un(i,n,w,E,T(),u),b={async collect(){return k(void 0)},filter(u){return w.inMemoryFilters.push(u),b},async first(){return k(w.inMemoryFilters.length>0?void 0:1)[0]??null},order(u){return w.order=u==="desc"?"desc":"asc",b},async paginate(u){if(w.search)throw new N("INTERNAL","pagination is not supported on search queries; use .take(n) or .collect()");if(w.geo)throw new N("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");return gn(i,n,w,u,E)},async take(u){return k(u)},async unique(){const u=k(w.inMemoryFilters.length>0?void 0:2);if(u.length>1)throw new En(`unique() on table "${n}" matched ${String(u.length)} documents; expected at most one`);return u[0]??null},withGeoIndex(u,S){const M=(l.geoIndexes??[]).find(O=>O.name===u);if(!M)throw new N("INTERNAL",`unknown geo index "${u}" on table "${n}"`);s(n,u,"geo");const D={definition:M,indexName:u};if(w.geo=D,S(sn(D,n)),!D.near&&!D.within)throw new N("INTERNAL",`geo index "${u}" on table "${n}" requires a .near(point, radius) or .within(box) call`);return b},withIndex(u,S){const M=l.indexes.find(D=>D.name===u);if(!M)throw new N("INTERNAL",`unknown index "${u}" on table "${n}"`);return s(n,u,"index"),w.indexName=u,w.indexFields=M.fields,S&&S(nn(w)),b},withSearchIndex(u,S){const M=(l.searchIndexes??[]).find(O=>O.name===u);if(!M)throw new N("INTERNAL",`unknown search index "${u}" on table "${n}"`);s(n,u,"search");const D={definition:M,field:M.field,filters:[],hasQuery:!1,indexName:u,query:""};if(w.search=D,S(rn(D,n)),!D.hasQuery)throw new N("INTERNAL",`search index "${u}" on table "${n}" requires a .search(field, query) call`);return b}};return b},rt=(i,o,n)=>{const s={...o};for(const[l,c]of dt(i)){if(c.serverDefault){s[l]=c.serverDefault({auth:n});continue}s[l]===void 0&&(c.defaultFn?s[l]=c.defaultFn():"defaultValue"in c&&(s[l]=c.defaultValue))}return s},it=(i,o,n,s)=>{const l=n;for(const[c,E]of dt(i)){if(E.serverDefault){c in o&&(l[c]=E.serverDefault({auth:s}));continue}E.onUpdateFn&&!(c in o)&&(l[c]=E.onUpdateFn())}},ot=(i,o)=>{for(const n of Object.keys(o))if(o[n]===void 0)throw new N("INTERNAL",`Cannot ${i} field '${n}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},Nn=/unique constraint failed/i,Tn=i=>i instanceof Error&&Nn.test(i.message),Ge=(i,o,n)=>{try{v(i,n)}catch(s){throw Tn(s)?new Re(`unique constraint violation on "${o}"`,"unique"):s}},xe=(i,o,n)=>{if(Ge(i,o,n),v(i,t`SELECT changes() AS changed`).one().changed===0)throw new Re(`optimistic concurrency conflict on "${o}" — the row changed during this mutation; refetch and retry`,"occ")},at=(i,o,n,s,l,c,E)=>{const w=[];for(let b=0;b<n.length+1;b+=1){const u=[];for(let O=0;O<b;O+=1)u.push(t`${t.identifier(n[O])} IS ${c[O]}`);const S=n[b],M=s[b];if(S!==void 0&&M!==void 0){const O=M.direction==="desc"?">":"<";u.push(t`${t.identifier(S)} ${t.raw(O)} ${c[b]}`)}else u.push(t`${t.identifier(we)} < ${E}`);const[D]=u;w.push(u.length===1&&D!==void 0?D:t`(${t.join(u,t` AND `)})`)}const _=t.join(w,t` OR `),T=v(i,t`SELECT COUNT(*) AS c FROM ${t.identifier(o)} WHERE ${t.identifier("__partition__")} = ${l} AND (${_})`).one(),k=v(i,t`SELECT COUNT(*) AS c FROM ${t.identifier(o)} WHERE ${t.identifier("__partition__")} = ${l}`).one();return{before:T.c,total:k.c}},Jn=i=>{const{sql:o}=i,{schema:n}=i,s=i.broadcast??(()=>{}),l=i.onRead??(()=>{}),c=i.onIndexUse??(()=>{}),E=i.onWrite??(()=>{}),{cache:w}=i,_=i.clock??(()=>Date.now()),T=i.idGenerator??(()=>crypto.randomUUID()),k=i.scheduler??yt,{globalDb:b}=i,u=i.auth??{identity:null,userId:null},S=i.cdc??!1,M=k,D=jt({scheduler:typeof M.list=="function"&&typeof M.get=="function"?M:void 0,storage:i.storage}),O=(e,r,a,p)=>{S&&St(o,_(),e,r,a,p)},Z=e=>n.tables[e]?.shardMode?.kind==="global",A=(e,r)=>{if(Z(e)){if(!b)throw new N("INTERNAL",`cross-backend ${r} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return b}return J},m=e=>A(e,"cascade"),I=(e,r)=>{if(Z(e)){if(!b)throw new N("INTERNAL",`${r} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return b}},F=()=>b,W=(e,r)=>A(e,"relation load").findMany(e,r),H=(e,r)=>(Z(e)&&l(e,Y),W(e,r)),j=e=>!Z(e.table),G=i.relationExistsPushDown??"auto",B=G!=="never",{maxRelationKeys:q}=i,L=(e,r,a)=>Xe(e,{fetcher:H,maxRelationKeys:q,relationBaseWhere:a,schema:n,tableName:r}),P=async(e,r,a,p)=>{const $=I(e,"relation grouped count");if($)return l(e,Y),qt((C,ie)=>$.count(C,ie),e,r,a,p);const h=n.tables[e];if(!h)throw new N("INTERNAL",`unknown table: ${e}`);l(e,Y);const d=Ee(h.softDeleteMode,void 0),f={[r]:{in:a}},g=oe(oe(f,p),d),R=await L(g,e,void 0),y=he(R,pe),x=ee(r);let z=t`SELECT ${x} AS __fk__, COUNT(*) AS count FROM ${t.identifier(e)}`;y&&(z=t`${z} WHERE ${y}`),z=t`${z} GROUP BY ${x}`;const K=v(o,z).toArray();return new Map(K.map(C=>[C.__fk__,C.count]))};let U=0;const V=new Set;for(const[e,r]of Object.entries(n.tables))for(const a of Object.values(r.triggerMap??{}))V.add(`${e} ${a.timing} ${a.op}`);const re=(e,r,a)=>V.has(`${e} ${r} ${a}`),se=async(e,r,a)=>{if(U+=1,U>tt)throw U-=1,new Re(`trigger recursion exceeded ${String(tt)} levels on "${a.table}" — check for a self-triggering write`,"trigger");try{await Ht({ctx:Et,event:a,op:r,schema:n,tableName:a.table,timing:e})}finally{U-=1}},{ensureBackfilledForTable:be,ensureBackfilledIndex:Oe,ensureRankBackfilled:We,ensureRankBackfilledForTable:ye,syncAggregates:Ie,syncCompanionsForInsert:Ve,syncGeo:ve,syncRanks:_e,syncSearch:ke}=Kt({broadcast:s,invalidateCache:(e,r)=>w?.invalidate(e,r),recordCdc:O,schema:n,sql:o}),Je=(e,r,a)=>{const{shardMode:p}=r;if(p?.kind==="shardBy"&&!(p.field!==void 0&&(a.partitionBy??[]).includes(p.field)))throw Object.assign(new Error(`rank index "${a.name}" on "${e}" partitions across shards (shard key "${p.field??"?"}" is not in partitionBy) — a shard-local rank()/rankPage() would be wrong; roll it up through the Query Coordinator instead`),{code:"CROSS_SHARD_RANK_UNSUPPORTED",name:"LunoraError",status:400})},$e=(e,r)=>{const a=Object.entries(n.tables).filter(([,R])=>R.shardMode?.kind!=="global").map(([R])=>R).filter(R=>r===void 0||R===r);if(a.length===0)return;const p=a.map(R=>t`SELECT ${t.raw(`'${R.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${t.identifier(X)} FROM ${t.identifier(R)} WHERE id = ${e}`),$=t`${t.join(p,t` UNION ALL `)} LIMIT 1`,[h]=v(o,$).toArray();if(!h)return;const d=h.__t__,f=fe(h);if(typeof d!="string"||!f)return;const g=h[X];return{docJson:typeof g=="string"?g:JSON.stringify(g??{}),row:f,tableName:d}},ze={assertRankPartitionLocal:Je,ensureRankBackfilled:We,onRead:l,rowToDocument:fe,schema:n,sql:o},J={system:D,async aggregate(e,r){const a=I(e,"aggregate");if(a)return l(e,Y),a.aggregate(e,r);const p=n.tables[e];if(!p)throw new N("INTERNAL",`unknown table: ${e}`);if(Ne(r.op),r.op==="count")return J.count(e,{baseWhere:r.baseWhere,relationBaseWhere:r.relationBaseWhere,restrictsCounts:r.restrictsCounts,where:r.where});if(!r.field)throw new N("INTERNAL",`aggregate(${e}, { op: "${r.op}" }): "field" is required for non-count reducers`);l(e,Y);const $=Ee(p.softDeleteMode,void 0),h=oe(oe(r.baseWhere,r.where),$),d=await L(h,e,r.relationBaseWhere),f=d!==h;if(p.aggregateIndexes&&!r.baseWhere&&!f&&!$){const K=Rt(p.aggregateIndexes,r.op,r.field,r.where);if(K){Oe(e,K.index);const C=de(K.index.by??[],K.key),ie=Te(e,K.index.name),ae=v(o,t`SELECT ${te} AS value, ${Q} AS count FROM ${t.identifier(ie)} WHERE ${ce} = ${C}`).toArray()[0];return qe(r.op,ae)}}const g=he(d,pe),R=Ne(r.op),y=ee(r.field);let x=t`SELECT ${t.raw(R)}(${y}) AS value FROM ${t.identifier(e)}`;return g&&(x=t`${x} WHERE ${g}`),v(o,x).toArray()[0]?.value??null},asId(e,r){const a=nt(n,e,r);if(a===null)throw new N("BAD_REQUEST",`asId("${e}", …): "${r}" is not a valid id for table "${e}"`,{status:400});return a},async count(e,r){const a=I(e,"count");if(a)return l(e,Y),a.count(e,r);const p=n.tables[e];if(!p)throw new N("INTERNAL",`unknown table: ${e}`);const $=bt(r);if($.restrictsCounts)throw new Ue(e);l(e,Y);const h=Ee(p.softDeleteMode,void 0),d=oe(oe($.baseWhere,$.where),h),f=await L(d,e,$.relationBaseWhere),g=f!==d;if(p.aggregateIndexes&&!$.baseWhere&&!g&&!h){const x=Tt(p.aggregateIndexes,$.where);if(x){Oe(e,x.index);const z=de(x.index.by??[],x.key),K=Te(e,x.index.name),C=v(o,t`SELECT ${te} AS value FROM ${t.identifier(K)} WHERE ${ce} = ${z}`).toArray();return C[0]===void 0?0:C[0].value??0}}const R=he(f,pe);let y=t`SELECT COUNT(*) AS count FROM ${t.identifier(e)}`;return R&&(y=t`${y} WHERE ${R}`),v(o,y).one().count},async delete(e,r,a){const p=$e(e,r);if(!p){const y=r===void 0?F():void 0;y&&await y.delete(e,void 0,a);return}const{docJson:$,row:h,tableName:d}=p,f=n.tables[d],g=a?.hard===!0,R=!g&&f?.softDeleteMode?f.softDeleteMode.field:void 0;if(!(R&&h[R]!==null&&h[R]!==void 0)){if(re(d,"before","delete")&&await se("before","delete",{id:e,op:"delete",previous:h,table:d}),await Ft({deletedId:e,deletedReference:y=>h[y],findHolders:async(y,x,z)=>(await m(y).findMany(y,{includeDeleted:g,where:{[x]:z}})).page,onCascade:(y,x)=>m(y).delete(x,void 0,a),onRestrict:y=>{throw new Re(y,"restrict")},onSetNull:(y,x,z)=>m(y).patch(x,{[z]:null}),schema:n,tableName:d}),be(d),ye(d),R){const y={...h,[R]:_(),_id:e};xe(o,d,t`UPDATE ${t.identifier(d)} SET ${t.identifier(X)} = ${JSON.stringify(y)} WHERE id = ${e} AND ${t.identifier(X)} = ${$}`),ke(d,e,y),ve(d,e,void 0),Ie(d,h,y),_e(d,e,h,void 0),w?.invalidate(d,e),O(d,e,"update",y),s({key:e,op:"update",row:y,table:d}),re(d,"after","delete")&&await se("after","delete",{id:e,op:"delete",previous:h,table:d}),await E({id:e,op:"delete",table:d});return}xe(o,d,t`DELETE FROM ${t.identifier(d)} WHERE id = ${e} AND ${t.identifier(X)} = ${$}`),ke(d,e,void 0),ve(d,e,void 0),Ie(d,h,void 0),_e(d,e,h,void 0),w?.invalidate(d,e),O(d,e,"delete"),s({key:e,op:"delete",table:d}),re(d,"after","delete")&&await se("after","delete",{id:e,op:"delete",previous:h,table:d}),await E({id:e,op:"delete",table:d})}},async deleteAll(e,r){if(!n.tables[e])throw new N("INTERNAL",`unknown table: ${e}`);const a=Math.max(1,r?.chunkSize??mt),p=r?.hard===void 0?void 0:{hard:r.hard},$=Z(e)?void 0:e;let h=0;for(;;){const d=(await J.findMany(e,{limit:a})).page.map(f=>String(f._id));if(d.length===0)break;for(const f of d)await J.delete(f,$,p),h+=1;if(d.length<a)break}return{deleted:h}},async deleteMany(e,r,a){ge(e.length,r?.limit,"deleteMany");for(const p of e)await J.delete(p,a);return{deleted:e.length}},async deleteWhere(e,r,a){const p=I(e,"deleteWhere");let $;if(p)$=(await p.findMany(e,{where:r})).page.map(h=>String(h._id));else{if(!n.tables[e])throw new N("INTERNAL",`unknown table: ${e}`);$=(await J.findMany(e,{where:r})).page.map(h=>String(h._id))}if(ge($.length,a?.limit,"deleteWhere"),J.deleteMany===void 0)throw new N("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return J.deleteMany($,a)},async findFirst(e,r={}){return(await J.findMany(e,{...r,limit:1})).page[0]??null},async findFirstOrThrow(e,r={}){const a=await J.findFirst(e,r);if(a===null)throw new Bt(`findFirstOrThrow: no "${e}" document matched`);return a},async findMany(e,r={}){const a=I(e,"findMany");if(a)return l(e,Y),a.findMany(e,r);const p=n.tables[e];if(!p)throw new N("INTERNAL",`unknown table: ${e}`);const $=!r.where&&!r.baseWhere;$?l(e,Y):l(e);const h=Ot(r.orderBy),d=r.cursor?pt(h,Ce(r.cursor)):void 0;let f=oe(r.baseWhere,r.where);f=oe(f,Ee(p.softDeleteMode,r.includeDeleted)),f=await Xe(f,{canPushExists:B?j:void 0,existsPushMode:G==="always"?"always":"auto",fetcher:H,maxRelationKeys:q,relationBaseWhere:r.relationBaseWhere,schema:n,tableName:e}),d&&(f=f?{AND:[f,d]}:d);const g=B?hn(l):pe,R=he(f,g);let y=t`SELECT id, _creationTime, ${t.identifier(X)} FROM ${t.identifier(e)}`;R&&(y=t`${y} WHERE ${R}`),y=t`${y} ORDER BY ${gt(h)}`;const x=typeof r.limit=="number"?Math.max(0,Math.floor(r.limit)):void 0;x!==void 0&&(y=t`${y} LIMIT ${t.raw(String(x+1))}`);const z=v(o,y).toArray(),K=[];for(const le of z){const ne=fe(le);ne&&(K.push(ne),!$&&typeof ne._id=="string"&&l(e,ne._id))}if(x===void 0)return r.with&&await Ze({groupedCounter:P,fetcher:W,parents:K,relationBaseWhere:r.relationBaseWhere,schema:n,tableName:e,with:r.with}),{continueCursor:null,isDone:!0,page:Qe(K,r.select,r.with)};const C=K.length>x,ie=C?K.slice(0,x):K,ae=ie.at(-1);return r.with&&await Ze({fetcher:W,groupedCounter:P,parents:ie,relationBaseWhere:r.relationBaseWhere,schema:n,tableName:e,with:r.with}),{continueCursor:C&&ae?Pe(ae,h):null,isDone:!C,page:Qe(ie,r.select,r.with)}},async get(e,r){const a=$e(e,r);if(!a){const p=r===void 0?F():void 0;return p?p.get(e):null}return l(a.tableName,e),a.row},async lookupById(e,r){const a=$e(e,r);return a?(l(a.tableName,e),{row:a.row,tableName:a.tableName}):null},async groupBy(e,r){const a=I(e,"groupBy");if(a)return l(e,Y),a.groupBy(e,r);const p=n.tables[e];if(!p)throw new N("INTERNAL",`unknown table: ${e}`);l(e,Y);const $=r.agg??{op:"count"};if(Ne($.op),$.op!=="count"&&!$.field)throw new N("INTERNAL",`groupBy(${e}, { agg: { op: "${$.op}" } }): "field" is required for non-count reducers`);const h=Ee(p.softDeleteMode,void 0),d=oe(oe(r.baseWhere,r.where),h),f=await L(d,e,r.relationBaseWhere),g=f!==d;if(p.aggregateIndexes&&!r.baseWhere&&!g&&!h){const C=Nt(p.aggregateIndexes,$.op,$.field,r.by,r.where);if(C){Oe(e,C.index);const ie=Te(e,C.index.name),ae=Object.keys(C.partial),le=[];if(ae.length===(C.index.by??[]).length&&ae.length>0){const me=de(C.index.by??[],C.partial),Me=v(o,t`SELECT ${te} AS value, ${Q} AS count FROM ${t.identifier(ie)} WHERE ${ce} = ${me}`).toArray();return Me.length>0&&le.push({key:{...C.partial},value:qe($.op,Me[0])}),le}const ne=v(o,t`SELECT ${ce} AS key, ${te} AS value, ${Q} AS count FROM ${t.identifier(ie)}`).toArray();for(const me of ne){const Me=JSON.parse(me.key);le.push({key:Me,value:qe($.op,me)})}return le}}const R=he(f,pe),y=r.by.map(C=>t`${ee(C)} AS ${t.identifier(C)}`);if($.op==="count")y.push(t`COUNT(*) AS value`);else{const{field:C}=$;if(C===void 0)throw new N("INTERNAL",`groupBy(${e}, { agg: { op: "${$.op}" } }): "field" is required for non-count reducers`);y.push(t`${t.raw(Ne($.op))}(${ee(C)}) AS value`)}let x=t`SELECT ${t.join(y,t`, `)} FROM ${t.identifier(e)}`;R&&(x=t`${x} WHERE ${R}`),x=t`${x} GROUP BY ${t.join(r.by.map(C=>ee(C)),t`, `)}`;const z=v(o,x).toArray(),K=[];for(const C of z){const ie={};for(const le of r.by)ie[le]=C[le]??null;const{value:ae}=C;K.push({key:ie,value:ae==null?null:Number(ae)})}return K},async insert(e,r,a){const p=I(e,"insert");if(p){const R=await p.insert(e,r,a);return s({key:R,op:"insert",row:{...r,_id:R},table:e}),R}const $=n.tables[e];if(!$)throw new N("INTERNAL",`unknown table: ${e}`);const h=rt($,r,u);He($,h);let d;a?.clientId!==void 0?(tn(a.clientId),d=a.clientId):a?.allowExplicitId&&typeof h._id=="string"?d=h._id:d=T();const f=a?.allowExplicitId&&typeof h._creationTime=="number"?h._creationTime:_(),g={...h,_creationTime:f,_id:d};return re(e,"before","insert")&&await se("before","insert",{doc:{...g},id:d,op:"insert",table:e}),be(e),ye(e),Ge(o,e,t`INSERT INTO ${t.identifier(e)} (id, _creationTime, ${t.identifier(X)}) VALUES (${d}, ${f}, ${JSON.stringify(g)})`),Ve(e,d,g),re(e,"after","insert")&&await se("after","insert",{doc:g,id:d,op:"insert",table:e}),await E({doc:g,id:d,op:"insert",table:e}),d},async insertManyUnsafe(e,r,a){if(ge(r.length,a?.limit,"insertManyUnsafe"),r.length===0)return[];const p=I(e,"insert");if(p){const f=[];for(const g of r){const R=await p.insert(e,g,{allowExplicitId:a?.allowExplicitId});s({key:R,op:"insert",row:{...g,_id:R},table:e}),f.push(R)}return f}const $=n.tables[e];if(!$)throw new N("INTERNAL",`unknown table: ${e}`);be(e),ye(e);const h=r.map(f=>{const g=rt($,f,u),R=a?.allowExplicitId===!0&&typeof g._id=="string"?g._id:T(),y=a?.allowExplicitId===!0&&typeof g._creationTime=="number"?g._creationTime:_();return{creationTime:y,document:{...g,_creationTime:y,_id:R},id:R}}),d=t.join(h.map(f=>t`(${f.id}, ${f.creationTime}, ${JSON.stringify(f.document)})`),t`, `);Ge(o,e,t`INSERT INTO ${t.identifier(e)} (id, _creationTime, ${t.identifier(X)}) VALUES ${d}`);for(const{document:f,id:g}of h)Ve(e,g,f),await E({doc:f,id:g,op:"insert",table:e});return h.map(f=>f.id)},async insertMany(e,r,a){ge(r.length,a?.limit,"insertMany");const p=a?.skipDuplicates===!0,$=[];for(const h of r)try{$.push(await J.insert(e,h))}catch(d){if(p&&d instanceof Re&&d.kind==="unique")$.push(null);else throw d}return $},normalizeId(e,r){return nt(n,e,r)},async patch(e,r,a){const p=$e(e,a);if(!p){const R=a===void 0?F():void 0;if(R){await R.patch(e,r);return}throw new N("INTERNAL",`document not found: ${e}`)}const{docJson:$,row:h,tableName:d}=p,f=n.tables[d];if(!f)throw new N("INTERNAL",`unknown table: ${d}`);l(d,e),ot("patch",r);const g={...h,...r,_id:e};it(f,r,g,u),He(f,g),re(d,"before","update")&&await se("before","update",{doc:{...g},id:e,op:"update",previous:h,table:d}),be(d),ye(d),xe(o,d,t`UPDATE ${t.identifier(d)} SET ${t.identifier(X)} = ${JSON.stringify(g)} WHERE id = ${e} AND ${t.identifier(X)} = ${$}`),ke(d,e,g),ve(d,e,g),Ie(d,h,g),_e(d,e,h,g),w?.invalidate(d,e),O(d,e,"update",g),s({key:e,op:"update",row:g,table:d}),re(d,"after","update")&&await se("after","update",{doc:g,id:e,op:"update",previous:h,table:d}),await E({doc:g,id:e,op:"update",table:d})},async patchMany(e,r,a){ge(e.length,r?.limit,"patchMany");for(const p of e)await J.patch(p.id,p.patch,a);return{patched:e.length}},async patchWhere(e,r,a){const p=I(e,"patchWhere");let $;if(p)$=(await p.findMany(e,{where:r.where})).page.map(h=>({id:String(h._id),patch:r.patch}));else{if(!n.tables[e])throw new N("INTERNAL",`unknown table: ${e}`);$=(await J.findMany(e,{where:r.where})).page.map(h=>({id:String(h._id),patch:r.patch}))}if(ge($.length,a?.limit,"patchWhere"),J.patchMany===void 0)throw new N("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await J.patchMany($,a),{patched:$.length}},query(e){const r=I(e,"query");return r?(l(e,Y),r.query(e)):(l(e,Y),_n(o,n,e,c))},async rank(e,r,a){const p=I(e,"rank");if(p)return l(e,Y),p.rank(e,r,a);c(e,r,"rank");const $=n.tables[e];if(!$)throw new N("INTERNAL",`unknown table: ${e}`);const h=$.rankIndexes?.find(ne=>ne.name===r);if(!h)throw new N("INTERNAL",`unknown rankIndex "${r}" on table "${e}"`);if(Je(e,$,h),a.restrictsCounts)throw new Ue(e);l(e,Y),We(e,h);const d=typeof a.row=="string"?a.row:a.row._id;if(!d)return null;const f=Ae(e,h.name),g=h.sortBy.map((ne,me)=>Se(me)),R=g.map(ne=>At(ne)).join(", "),y=v(o,t`SELECT ${t.identifier("__partition__")}, ${t.raw(R)} FROM ${t.identifier(f)} WHERE ${t.identifier("__id__")} = ${d}`).toArray(),[x]=y;if(x===void 0)return null;let z=x.__partition__;const K=oe(a.baseWhere,a.where);je(K,n,e,"rank");const C=ft(h,K);if(C){const ne=De(h.partitionBy??[],C);if(ne!==z)return null;z=ne}const ie=g.map(ne=>x[ne]),{before:ae,total:le}=at(o,f,g,h.sortBy,z,ie,d);return{position:ae+1,total:le}},async rankBefore(e,r,a){if(Z(e))throw new N("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const p=n.tables[e];if(!p)throw new N("INTERNAL",`unknown table: ${e}`);const $=p.rankIndexes?.find(g=>g.name===r);if(!$)throw new N("INTERNAL",`unknown rankIndex "${r}" on table "${e}"`);if(a.restrictsCounts)throw new Ue(e);l(e,Y),We(e,$);const h=Ae(e,$.name),d=$.sortBy.map((g,R)=>Se(R)),f=$.sortBy.map((g,R)=>ue(a.sortValues[R]??null));return at(o,h,d,$.sortBy,a.partitionKey,f,a.rowId)},async rankPage(e,r,a={}){je(oe(a.baseWhere,a.where),n,e,"rankPage");const p=I(e,"rankPage");if(p)return l(e,Y),p.rankPage(e,r,a);c(e,r,"rank");const{continueCursor:$,hasMore:h,rows:d}=et(ze,e,r,a);return{continueCursor:$,isDone:!h,page:d.map(f=>f.doc)}},async rankPageRows(e,r,a={}){je(oe(a.baseWhere,a.where),n,e,"rankPage"),c(e,r,"rank");const{directions:p,hasMore:$,rows:h}=et(ze,e,r,a);return{directions:p,hasMore:$,rows:h}},async restore(e,r){const a=$e(e,r);if(!a){const h=r===void 0?F():void 0;if(h?.restore){await h.restore(e);return}throw new N("INTERNAL",`document not found: ${e}`)}const p=n.tables[a.tableName]?.softDeleteMode?.field;if(!p)throw new N("INTERNAL",`ctx.db.restore: table "${a.tableName}" is not a .softDelete() table`);const $=a.row[p]!==null&&a.row[p]!==void 0;await J.patch(e,{[p]:null},r),$&&_e(a.tableName,e,void 0,a.row)},async replace(e,r,a,p){const $=$e(e,a);if(!$){const x=a===void 0?F():void 0;if(x){await x.replace(e,r,void 0,p);return}throw new N("INTERNAL",`document not found: ${e}`)}const{docJson:h,row:d,tableName:f}=$,g=n.tables[f];if(!g)throw new N("INTERNAL",`unknown table: ${f}`);ot("replace",r);const R=p?.allowExplicitId&&typeof r._creationTime=="number"?r._creationTime:_(),y={...r,_creationTime:R,_id:e};it(g,r,y,u),He(g,y),re(f,"before","update")&&await se("before","update",{doc:{...y},id:e,op:"update",previous:d,table:f}),be(f),ye(f),xe(o,f,t`UPDATE ${t.identifier(f)} SET _creationTime = ${R}, ${t.identifier(X)} = ${JSON.stringify(y)} WHERE id = ${e} AND ${t.identifier(X)} = ${h}`),ke(f,e,y),ve(f,e,y),Ie(f,d,y),_e(f,e,d,y),w?.invalidate(f,e),O(f,e,"update",y),s({key:e,op:"update",row:y,table:f}),re(f,"after","update")&&await se("after","update",{doc:y,id:e,op:"update",previous:d,table:f}),await E({doc:y,id:e,op:"update",table:f})},async wipeShard(e){const r=new Set(e?.exclude),a=e?.tables,p=Object.entries(n.tables).filter(([f,g])=>r.has(f)||a!==void 0&&!a.includes(f)?!1:g.shardMode?.kind!=="global").map(([f])=>f);if(a!==void 0){for(const f of a)if(!n.tables[f])throw new N("INTERNAL",`wipeShard: unknown table: ${f}`)}const $={};let h=0;const{deleteAll:d}=J;if(d===void 0)throw new N("INTERNAL","wipeShard: this writer has no deleteAll");for(const f of p){const g=await d(f,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});$[f]=g.deleted,h+=g.deleted}return{deleted:h,tables:$}}},Et={db:J,scheduler:k};return i.enforceRls===!0?Ut(J,n,(e,r)=>$e(e,r)?.tableName):J};export{Qn as CDC_LOG_TABLE,dr as CLIENT_WATERMARK_TABLE,cr as GLOBAL_SHAPE_SNAPSHOT_TABLE,fr as IDEMPOTENCY_TABLE,En as NotUniqueError,ur as advanceClientWatermark,Xn as applyCdcChanges,tn as assertValidClientId,ar as backfillAggregateIndexes,sr as backfillRankIndexes,Zn as bumpCdcEpoch,Jn as createShardCtxDb,hr as deleteGlobalShapeSnapshot,$r as deleteGlobalShapeSnapshotsForConnection,pr as migrateClientWatermark,wr as migrateGlobalShapeSnapshot,er as minCdcSeq,nt as normalizeIdStructurally,tr as readCdcChanges,nr as readCdcCursor,rr as readCdcEpoch,mr as readClientWatermark,gr as readGlobalShapeSnapshot,Er as readIdempotent,Tr as runShardMigrations,Sr as selectShapeMemberIds,Ar as selectShapeRows,ir as trimCdcChanges,br as trimIdempotent,yr as writeGlobalShapeSnapshot,_r as writeIdempotent};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as m}from"@lunora/errors";const a="id",h=new Set(["_id","id"]),b=t=>{const e=[];for(const r of t??[])for(const[o,s]of Object.entries(r))e.push({direction:s,field:o});return e.length===0?[{direction:"asc",field:"_creationTime"}]:e},S=t=>{const e=new TextEncoder().encode(t);let r="";for(const o of e)r+=String.fromCodePoint(o);return btoa(r)},g=t=>{const e=atob(t),r=Uint8Array.from(e,o=>o.codePointAt(0)??0);return new TextDecoder().decode(r)},A=(t,e)=>{const r=e.map(o=>t[o.field]);return r.push(t._id),S(JSON.stringify(r))},u=()=>new m("BAD_REQUEST","invalid cursor"),D=t=>{let e;try{e=JSON.parse(g(t))}catch{throw u()}if(!Array.isArray(e))throw u();return e},_=(t,e)=>{const r=t.some(s=>h.has(s.field))?t:[...t,{direction:"asc",field:a}],o=[];for(const[s,n]of r.entries()){const i=[];for(const[d,l]of r.slice(0,s).entries())i.push({[l.field]:{eq:e[d]}});const f=n.direction==="desc"?"lt":"gt";i.push({[n.field]:{[f]:e[s]}});const[c]=i;o.push(i.length===1&&c!==void 0?c:{AND:i})}return{OR:o}},y=(t,e)=>t==="desc"?e?"gte":"gt":e?"lte":"lt",E=(t,e)=>{const r=t.some(s=>h.has(s.field))?t:[...t,{direction:"asc",field:a}],o=[];for(const[s,n]of r.entries()){const i=[];for(const[l,p]of r.slice(0,s).entries())i.push({[p.field]:{eq:e[l]}});const f=s===r.length-1,c=y(n.direction,f);i.push({[n.field]:{[c]:e[s]}});const[d]=i;o.push(i.length===1&&d!==void 0?d:{AND:i})}return{OR:o}},w=["_id","_creationTime"],N=(t,e,r)=>{if(!e)return t;const o=new Set([...e,...w,...r?Object.keys(r):[]]);return t.map(s=>{const n={};for(const i of o)i in s&&(n[i]=s[i]);return n})},T=(t,e)=>t&&e!==!0?{[t.field]:{isNull:!0}}:void 0;export{N as applySelect,E as buildSeekBeforeWhere,_ as buildSeekWhere,D as decodeCursor,A as encodeCursor,b as normalizeOrderKeys,T as softDeleteScope};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{sql as e}from"drizzle-orm";import{matchesStaticWhere as u}from"./AGGREGATE_SQL_FUNCTION-QYaiuty4.mjs";import{encodeAggregateKey as S,foldAggregateTally as E,aggregateTableName as b}from"./aggregateTableName-G-eXyjcz.mjs";import{r as f}from"./do-exec-BLe9lLrN.mjs";import{s as g,L as p,a as _,d as h,m as k}from"./do-sql-BYIQTG3z.mjs";import{param as y}from"./renderSql-B5lF5Jd9.mjs";import{sortColumnName as I,matchesRankStaticWhere as N,encodePartitionKey as O,rankTableName as A}from"./RANK_TIEBREAK-DtX8zQyc.mjs";import{t as R}from"./serialize-sql-DiRzL7A4.mjs";const M=(t,i,o)=>{const r=b(i,o.name);if(f(t,e`SELECT COUNT(*) AS count FROM ${e.identifier(r)}`).one().count>0)return;const s=o.by??[],c=new Map,m=f(t,e`SELECT id, _creationTime, ${e.identifier(g)} FROM ${e.identifier(i)}`).toArray();for(const a of m){const n=p(a);if(!n||o.where&&!u(n,o.where))continue;const d=S(s,n);E(c,d,o,n)}for(const[a,n]of c)f(t,e`INSERT INTO ${e.identifier(r)} (${_}, ${h}, ${k}) VALUES (${a}, ${n.value}, ${n.count})`)},K=(t,i)=>{for(const[o,r]of Object.entries(i.tables))if(!(r.shardMode?.kind==="global"||!r.aggregateIndexes))for(const s of r.aggregateIndexes)M(t,o,s)},x=(t,i,o)=>{const r=A(i,o.name);if(f(t,e`SELECT COUNT(*) AS count FROM ${e.identifier(r)}`).one().count>0)return;const s=o.sortBy.map((a,n)=>I(n)),c=e.join(["__id__","__partition__",...s].map(a=>e.identifier(a)),e`, `),m=f(t,e`SELECT id, _creationTime, ${e.identifier(g)} FROM ${e.identifier(i)}`).toArray();for(const a of m){const n=p(a);if(!n||o.where&&!N(n,o.where))continue;const d=O(o.partitionBy??[],n),T=o.sortBy.map(l=>R(n[l.field]??null)),$=e.join([n._id,d,...T].map(l=>y(l)),e`, `);f(t,e`INSERT INTO ${e.identifier(r)} (${c}) VALUES (${$})`)}},V=(t,i)=>{for(const[o,r]of Object.entries(i.tables))if(!(r.shardMode?.kind==="global"||!r.rankIndexes))for(const s of r.rankIndexes)x(t,o,s)};export{K as backfillAggregateIndexes,V as backfillRankIndexes};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
const l=(e,t)=>`${e}__fts_${t}`,a=e=>e.toLowerCase().match(/[\p{L}\p{N}]+/gu)??[],g=e=>e.map((t,o)=>o===e.length-1?`"${t}"*`:`"${t}"`).join(" AND "),h=e=>typeof e=="string"?e:e==null?"":typeof e=="number"||typeof e=="bigint"||typeof e=="boolean"?String(e):JSON.stringify(e)??"",p=(e,t)=>{const o=a(e);if(o.length===0)return 0;let r=0;for(const[f,s]of t.entries()){const c=f===t.length-1;let n=0;for(const i of o)(c?i.startsWith(s):i===s)&&(n+=1);if(n===0)return 0;r+=n}return r};export{g as buildFtsMatch,l as ftsTableName,p as scoreDocument,h as stringifySearchText,a as tokenizeSearch};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{sql as e}from"drizzle-orm";import{r as m}from"./do-exec-BLe9lLrN.mjs";import{s as a,L as l,T as h}from"./do-sql-BYIQTG3z.mjs";import{compileWhereSql as u}from"./compileWhereSql-BLcfs4QW.mjs";import{t as $}from"./serialize-sql-DiRzL7A4.mjs";const S={fieldRef:h,serialize:$},E=i=>{if(i.length!==0)return e`id IN (${e.join(i.map(r=>e`${r}`),e`, `)})`},c=(i,r)=>{const t=[];r&&t.push(r);const o=u(i,S);return o&&t.push(o),t.length===0?e``:e` WHERE ${e.join(t,e` AND `)}`},z=(i,r,t)=>{const o=c(t,void 0),d=m(i,e`SELECT id, _creationTime, ${e.identifier(a)} FROM ${e.identifier(r)}${o}`).toArray(),n=[];for(const s of d){const f=l(s),{id:p}=s;f!==void 0&&typeof p=="string"&&n.push({doc:f,id:p})}return n},A=(i,r,t,o)=>{if(o.length===0)return new Set;const d=c(t,E(o)),n=m(i,e`SELECT id FROM ${e.identifier(r)}${d}`).toArray();return new Set(n.map(s=>s.id))};export{A as a,z as s};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{sql as i}from"drizzle-orm";import{r as c}from"./do-exec-BLe9lLrN.mjs";const _="__doc__",E=(t,e)=>`${t}__geo_${e}`,s=t=>`"${t.replaceAll('"','""')}"`,f=t=>t==="_id"||t==="id"?"id":t==="_creationTime"?"_creationTime":`json_extract(${_}, '$.${t.replaceAll("'","''")}')`,m=t=>i.raw(f(t)),T=(t,e)=>{const r=s(t);return e==="_id"||e==="id"?`${r}.id`:e==="_creationTime"?`${r}._creationTime`:`json_extract(${r}.${_}, '$.${e.replaceAll("'","''")}')`},I=(t,e)=>i.raw(T(t,e)),N=(t,e,r,n)=>i`CREATE ${n?i`UNIQUE `:i``}INDEX IF NOT EXISTS ${i.identifier(t)} ON ${i.identifier(e)} (${r})`,$=i.identifier("__key__"),l=i.identifier("__value__"),d=i.identifier("__count__"),S=(t,e,r,n,o)=>i`INSERT INTO ${i.identifier(t)} (${$}, ${l}, ${d}) VALUES (${e}, ${r}, ${n}) ON CONFLICT(${$}) DO UPDATE SET ${o}`,A=t=>{const e=[];for(const[r,n]of Object.entries(t.shape)){const o=n._meta?.column;o&&e.push([r,o])}return e},O=t=>{if(!t)return;const e=t[_];let r;typeof e=="string"?r=JSON.parse(e):e&&typeof e=="object"?r=e:r={};const{id:n}=t;typeof n=="string"&&(r._id=n);const o=t._creationTime;return typeof o=="number"&&(r._creationTime=o),r},a=new WeakMap,y=t=>{const e=a.get(t);if(e!==void 0)return e;let r;try{c(t,i`CREATE VIRTUAL TABLE IF NOT EXISTS ${i.identifier("__lunora_fts_probe")} USING fts5(x)`),r=!0}catch{r=!1}finally{try{c(t,i`DROP TABLE IF EXISTS ${i.identifier("__lunora_fts_probe")}`)}catch{}}return a.set(t,r),r};export{I as $,A as E,O as L,y as N,N as S,m as T,$ as a,l as d,E as g,d as m,S as p,_ as s,s as u};
|
|
@@ -1,5 +0,0 @@
|
|
|
1
|
-
import{sql as e}from"drizzle-orm";import{aggregateTableName as N}from"./aggregateTableName-G-eXyjcz.mjs";import{migrateCdcLog as I,migrateCdcMeta as g}from"./CDC_LOG_TABLE-E_J5LPoK.mjs";import{_ as R,E as S,a as l}from"./ctx-db-idempotency-wiVoGnpQ.mjs";import{r as _}from"./do-exec-BLe9lLrN.mjs";import{s as p,T as $,S as T,E as O,N as u,a as C,d as U,m,g as X}from"./do-sql-BYIQTG3z.mjs";import{sortColumnName as h,rankTableName as x}from"./RANK_TIEBREAK-DtX8zQyc.mjs";import{ftsTableName as B}from"./buildFtsMatch-CV0Z7PWv.mjs";const M=(i,o,r)=>{for(const n of r.indexes){const t=`${o}_${n.name}`,s=e.join(n.fields.map(a=>$(a)),e`, `);_(i,T(t,o,s,n.unique??!1))}for(const[n,t]of O(r)){if(!t.unique)continue;const s=`${o}_unique_${n}`;_(i,T(s,o,$(n),!0))}},b=(i,o,r)=>{if(!(!r.searchIndexes||r.searchIndexes.length===0||!u(i)))for(const n of r.searchIndexes){const t=B(o,n.name);_(i,e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(t)} USING fts5(${e.identifier("__text__")}, ${e.identifier("__id__")} UNINDEXED)`)}},D=(i,o,r)=>{if(r.geoIndexes)for(const n of r.geoIndexes){const t=X(o,n.name);_(i,e`CREATE TABLE IF NOT EXISTS ${e.identifier(t)} (${e.identifier("__id__")} TEXT PRIMARY KEY, ${e.identifier("__geohash__")} TEXT NOT NULL, ${e.identifier("__lat__")} REAL NOT NULL, ${e.identifier("__lng__")} REAL NOT NULL)`);const s=`${o}__geo_${n.name}__btree`;_(i,T(s,t,e`${e.identifier("__geohash__")} ASC, ${e.identifier("__id__")} ASC`,!1))}},Y=(i,o,r)=>{if(r.aggregateIndexes)for(const n of r.aggregateIndexes){const t=N(o,n.name);_(i,e`CREATE TABLE IF NOT EXISTS ${e.identifier(t)} (${C} TEXT PRIMARY KEY, ${U} REAL, ${m} INTEGER NOT NULL DEFAULT 0)`),_(i,e`PRAGMA table_info(${e.identifier(t)})`).toArray().some(s=>s.name==="__count__")||_(i,e`ALTER TABLE ${e.identifier(t)} ADD COLUMN ${m} INTEGER NOT NULL DEFAULT 0`)}},F=(i,o,r)=>{if(r.rankIndexes)for(const n of r.rankIndexes){const t=x(o,n.name),s=n.sortBy.map((f,E)=>h(E)),a=s.map(f=>e`${e.identifier(f)} BLOB`),c=a.length>0?e`, ${e.join(a,e`, `)}`:e``;_(i,e`CREATE TABLE IF NOT EXISTS ${e.identifier(t)} (${e.identifier("__id__")} TEXT PRIMARY KEY, ${e.identifier("__partition__")} TEXT NOT NULL${c})`);const d=[e`${e.identifier("__partition__")} ASC`];for(const[f,E]of s.entries()){const A=n.sortBy[f]?.direction;d.push(e`${e.identifier(E)} ${e.raw(A==="desc"?"DESC":"ASC")}`)}d.push(e`${e.identifier("__id__")} ASC`);const L=`${o}__rank_${n.name}__btree`;_(i,T(L,t,e.join(d,e`, `),!1))}},w=(i,o,r={})=>{for(const[n,t]of Object.entries(o.tables))t.shardMode?.kind!=="global"&&(_(i,e`CREATE TABLE IF NOT EXISTS ${e.identifier(n)} (
|
|
2
|
-
id TEXT PRIMARY KEY,
|
|
3
|
-
_creationTime REAL NOT NULL,
|
|
4
|
-
${e.identifier(p)} TEXT NOT NULL
|
|
5
|
-
)`),M(i,n,t),b(i,n,t),D(i,n,t),Y(i,n,t),F(i,n,t));r.cdc&&(I(i),g(i),R(i)),S(i),l(i)};export{w as runShardMigrations};
|