@lunora/do 1.0.0-alpha.30 → 1.0.0-alpha.32

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 CHANGED
@@ -614,6 +614,13 @@ declare const rankTableName: (table: string, indexName: string) => string;
614
614
  * - `rowId` === `doc._id`, the `__id__` tiebreak.
615
615
  */
616
616
  declare const stableStringify: (value: unknown) => string;
617
+ /**
618
+ * Stable cache/dedup key for a (possibly wire-typed) `value`: the sorted-key
619
+ * stable encoding of its wire form. Byte-identical to `stableStringify(value)`
620
+ * for pure-JSON values; deterministic tagged tokens for `bigint`/`Date`/`Map`/
621
+ * `Set`/`URL`/bytes; throws a `TypeError` on values the wire refuses.
622
+ */
623
+ declare const stableWireKey: (value: unknown) => string;
617
624
  /** A single memoized result, the deps it read, and any active subscribers. */
618
625
  interface CacheEntry {
619
626
  /** Approximate serialized size of `result`, charged against `maxBytes`. */
@@ -2400,6 +2407,11 @@ interface MaterializeResult {
2400
2407
  /** `id → projected-value JSON` — the post-tick membership, to feed back as `baseline` next tick. */
2401
2408
  nextBaseline: Map<string, string>;
2402
2409
  }
2410
+ /** The outcome of one incremental materialize pass. No baseline: incremental applies only the pulled slice, never a full-membership diff. */
2411
+ interface IncrementalMaterializeResult {
2412
+ /** Number of `CdcChange`s applied (upserts + tombstone deletes) for the pulled slice. */
2413
+ applied: number;
2414
+ }
2403
2415
  /**
2404
2416
  * Diff `pulled` against `baseline` and apply the delta to `writer`. Returns the
2405
2417
  * applied count and the next baseline. A steady-state tick (membership unchanged)
@@ -2410,6 +2422,36 @@ declare const materializeExternalRows: (writer: DatabaseWriterLike, pulled: Read
2410
2422
  table: string;
2411
2423
  }) => Promise<MaterializeResult>;
2412
2424
  /**
2425
+ * Apply an **incremental** slice (plan 136): the freshly-pulled rows changed since
2426
+ * the watermark, upsert-only. Unlike {@link materializeExternalRows} this reads no
2427
+ * baseline and never diffs the full membership — an absent row means "unchanged
2428
+ * since the watermark", NOT "deleted". Each pulled row is projected with the SAME
2429
+ * {@link projectExternalSourceRow} full-pull uses, so an incrementally-upserted row
2430
+ * is byte-identical to how the next reconcile sweep's full-pull would store it (no
2431
+ * spurious update on reconcile).
2432
+ *
2433
+ * Delete visibility comes from `deletedIds` — the ids the caller resolved from the
2434
+ * source's soft-delete tombstone column. Every other pulled row is an `insert`,
2435
+ * which {@link applyCdcChanges} upserts (insert, or replace on conflict), so a
2436
+ * changed existing row is updated and a genuinely new row is inserted without the
2437
+ * caller tracking which is which.
2438
+ *
2439
+ * **Content short-circuit.** An incremental cursor query uses `>= watermark` (so
2440
+ * rows sharing the boundary value are never skipped), which means a steady-state
2441
+ * tick re-pulls the boundary row(s) unchanged. Blindly upserting them would append
2442
+ * a `__cdc_log` entry, broadcast a spurious `update` to every `defineShape`
2443
+ * subscriber, re-run search/aggregate/rank sync, and fire `onWrite` (a Vectorize
2444
+ * re-embed = real cost) on every tick — and `replace` would reset `_creationTime`.
2445
+ * So each row is diffed against its stored projection (the SAME
2446
+ * {@link projectExternalSourceRow} + {@link stableStringify} full-pull uses) and
2447
+ * skipped when byte-identical — mirroring the full-pull diff's steady-state no-op.
2448
+ */
2449
+ declare const materializeExternalRowsIncremental: (writer: DatabaseWriterLike, pulled: ReadonlyArray<Record<string, unknown>>, options: {
2450
+ columns?: ReadonlyArray<string>;
2451
+ deletedIds?: ReadonlySet<string>;
2452
+ table: string;
2453
+ }) => Promise<IncrementalMaterializeResult>;
2454
+ /**
2413
2455
  * Read the materialized table's current membership as the canonical full-pull
2414
2456
  * baseline (`id → canonical JSON`). Reuses the shape scanner (`selectShapeRows`)
2415
2457
  * and the SAME {@link projectExternalSourceRow} + {@link stableStringify} the diff
@@ -2438,14 +2480,23 @@ interface SourceClientLike {
2438
2480
  type SourceRefresh = "manual" | {
2439
2481
  everyMs: number;
2440
2482
  };
2483
+ /** The incremental cursor config (plan 136): the watermark column + the watermark-parameterized pull query. */
2484
+ interface SourceCursorLike {
2485
+ column: string;
2486
+ query: string;
2487
+ }
2441
2488
  /** The runtime `.source(...)` config the poll loop reads — a structural mirror of `@lunora/server`'s `ExternalSourceDefinition` (only the fields the tick uses). */
2442
2489
  interface ExternalSourceLike {
2443
2490
  binding: string;
2444
2491
  columns?: ReadonlyArray<string>;
2492
+ cursor?: SourceCursorLike;
2445
2493
  idColumn?: string;
2446
2494
  map?: (row: Record<string, unknown>) => Record<string, unknown>;
2495
+ mode?: string;
2447
2496
  query: string;
2497
+ reconcileEveryMs?: number;
2448
2498
  refresh?: SourceRefresh;
2499
+ softDeleteColumn?: string;
2449
2500
  tenantBy?: (shardKey: string) => ReadonlyArray<unknown>;
2450
2501
  }
2451
2502
  /**
@@ -2475,6 +2526,39 @@ declare const isSourceDue: (refresh: SourceRefresh | undefined, lastPolledMs: nu
2475
2526
  */
2476
2527
  declare const pullExternalSourceTick: (sql: SqlExec, writer: DatabaseWriterLike, client: SourceClientLike, table: string, source: ExternalSourceLike, shardKey: string) => Promise<MaterializeResult>;
2477
2528
  /**
2529
+ * Whether an upstream row is a soft-delete tombstone under `column`. A set
2530
+ * `deleted_at` (any non-null value, e.g. a timestamp), an `is_deleted = true`, or a
2531
+ * non-zero flag all read as deleted; `null` / `undefined` / `false` / `0` mean
2532
+ * live. Note an **empty string** reads as deleted (`"" !== 0`), so an upstream that
2533
+ * clears the column to `""` rather than `NULL` for a live row would mis-signal —
2534
+ * use `NULL` for live rows. The incremental query MUST return tombstoned rows
2535
+ * (don't filter `WHERE deleted_at IS NULL`) or the delete is never observed.
2536
+ */
2537
+ declare const isSoftDeleted: (row: Record<string, unknown>, column: string) => boolean;
2538
+ /**
2539
+ * Run one **incremental** tick (plan 136). Reads the durable watermark for
2540
+ * `(table, shardKey)`; on the first ever poll or when the `reconcileEveryMs` sweep
2541
+ * is due it runs a **full-pull** (seed/GC: {@link runExternalSourceTick} observes
2542
+ * deletes and re-establishes membership), otherwise it pulls only rows past the
2543
+ * watermark via `cursor.query` and upserts them ({@link materializeExternalRowsIncremental},
2544
+ * tombstones → deletes). Either way it advances the watermark to the max cursor
2545
+ * value seen and persists it (and the reconcile timestamp).
2546
+ *
2547
+ * **Crash safety** is by ordering + idempotency, NOT an atomic transaction across
2548
+ * the two write channels (the apply goes through the `writer`; the watermark write
2549
+ * is a raw `sql` write): the watermark advances only AFTER a fully-applied slice,
2550
+ * so a crash between the apply and the watermark write leaves the watermark behind
2551
+ * and the next tick re-pulls the same `>= watermark` slice — which the upsert
2552
+ * short-circuits (unchanged rows) or re-applies idempotently. It only ever replays,
2553
+ * never skips (same self-healing argument as `advanceClientWatermark`).
2554
+ *
2555
+ * Requires `source.cursor` (validated at `defineSchema` for incremental mode); a
2556
+ * missing cursor throws rather than silently degrading to a stuck watermark.
2557
+ */
2558
+ declare const pullExternalSourceIncrementalTick: (sql: SqlExec, writer: DatabaseWriterLike, client: SourceClientLike, table: string, source: ExternalSourceLike, shardKey: string, nowMs: number) => Promise<{
2559
+ applied: number;
2560
+ }>;
2561
+ /**
2478
2562
  * Reserved `functionPath` prefix for admin introspection RPCs. These travel
2479
2563
  * over the same `/_lunora/rpc` → shard `/rpc` path as ordinary functions, but
2480
2564
  * `ShardDO` intercepts them before user dispatch and serves them from the
@@ -6431,7 +6515,12 @@ declare abstract class ShardDO {
6431
6515
  * server logs, browser history, and `Referer` headers on any
6432
6516
  * subresource the upgrade page loads after the handshake. Use a
6433
6517
  * short-lived rotating token in production rather than a long-lived
6434
- * secret.
6518
+ * secret — for the ADMIN credential specifically, the worker mints one
6519
+ * (`POST /_lunora/admin/ws-token`) and {@link isAdminSocket} accepts it, so
6520
+ * the master `LUNORA_ADMIN_TOKEN` never rides the URL.
6521
+ *
6522
+ * Async because the admin fallback ({@link isAdminSocket}) verifies the
6523
+ * ephemeral sub-token with WebCrypto HMAC.
6435
6524
  */
6436
6525
  private isUpgradeAllowed;
6437
6526
  /**
@@ -6442,10 +6531,20 @@ declare abstract class ShardDO {
6442
6531
  */
6443
6532
  private suppliedWsToken;
6444
6533
  /**
6445
- * Whether the upgrade presented a token matching `LUNORA_ADMIN_TOKEN`,
6446
- * constant-time compared. Closed (returns `false`) when the admin token is
6447
- * unset, mirroring `isAdminAuthorized` for the HTTP path so admin
6448
- * streaming is opt-in rather than exposed by default.
6534
+ * Whether the upgrade presented an admin credential: the master
6535
+ * `LUNORA_ADMIN_TOKEN` (constant-time compared) or a short-lived sub-token
6536
+ * the worker minted with it (`POST /_lunora/admin/ws-token`
6537
+ * HMAC-verified statelessly here, since both isolates hold the master token
6538
+ * in `env`). The ephemeral token is what the studio sends in `?token=`, so
6539
+ * the master credential stays out of URLs/logs. Closed (resolves `false`)
6540
+ * when the admin token is unset, mirroring `isAdminAuthorized` for the HTTP
6541
+ * path so admin streaming is opt-in rather than exposed by default.
6542
+ *
6543
+ * Enforcement: with `LUNORA_REQUIRE_EPHEMERAL_WS_TOKEN` set
6544
+ * (`1`/`true`/`on`/`yes`/`enabled`), a raw master token in the
6545
+ * `?token=` query parameter is rejected — the query string is exactly
6546
+ * where it leaks. The `Authorization` header path still takes the master
6547
+ * token: browsers can't set it on a WS upgrade, so it never rides a URL.
6449
6548
  */
6450
6549
  private isAdminSocket;
6451
6550
  /**
@@ -6682,4 +6781,4 @@ interface WhereSqlStrategy {
6682
6781
  * `undefined` when the input imposes no constraint (empty `where`).
6683
6782
  */
6684
6783
  declare const compileWhereSql: (where: WhereInput | undefined, strategy: WhereSqlStrategy) => SQL | undefined;
6685
- 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 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, type GroupByEntry, type GroupByOptions, type HibernatableWebSocket, type IdGenerator, type ImportError, type ImportShardAdminArgs, type ImportShardArgs, type ImportShardResult, 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 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 SourceRefresh, 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 TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, 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, buildFtsMatch, buildSecurityAudit, buildSeekWhere, clearCapturedMail, coerceAggregateNumber, compileWhereSql, containsRelationPredicate, createDependencyTracker, createShardCtxDb, createSystemReader, decodeCursor, depKey, diffExternalSource, encodeAggregateKey, encodeCursor, encodePartitionKey, ensureAuthMetricsTables, ensureFunctionMetricsTables, ensureMailTable, exportShardRows, exportShardTable, facetColumn, fanOutScalarCounts, foldAggregateTally, ftsTableName, guardWriter, hasTrigger, importShardRows, isRelationPredicate, isSourceDue, liftSourceId, listTables, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, mergeWhere, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, parseExportShardArgs, parseImportShardArgs, planAggregateLookup, 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, scoreDocument, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, serveRelationFanout, softDeleteScope, sortColumnName, stableStringify, stringifySearchText, subscriptionListDeltas, throwingScheduler, tokenizeSearch, trimCdcChanges, validateImportRow };
6784
+ 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 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, 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 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 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 TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, 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, buildFtsMatch, buildSecurityAudit, buildSeekWhere, clearCapturedMail, coerceAggregateNumber, compileWhereSql, containsRelationPredicate, createDependencyTracker, createShardCtxDb, createSystemReader, decodeCursor, depKey, diffExternalSource, encodeAggregateKey, encodeCursor, encodePartitionKey, ensureAuthMetricsTables, ensureFunctionMetricsTables, ensureMailTable, exportShardRows, exportShardTable, facetColumn, fanOutScalarCounts, foldAggregateTally, ftsTableName, guardWriter, hasTrigger, importShardRows, isRelationPredicate, isSoftDeleted, isSourceDue, liftSourceId, listTables, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, mergeWhere, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, parseExportShardArgs, parseImportShardArgs, planAggregateLookup, 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, scoreDocument, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, serveRelationFanout, softDeleteScope, sortColumnName, stableStringify, stableWireKey, stringifySearchText, subscriptionListDeltas, throwingScheduler, tokenizeSearch, trimCdcChanges, validateImportRow };
package/dist/index.d.ts CHANGED
@@ -614,6 +614,13 @@ declare const rankTableName: (table: string, indexName: string) => string;
614
614
  * - `rowId` === `doc._id`, the `__id__` tiebreak.
615
615
  */
616
616
  declare const stableStringify: (value: unknown) => string;
617
+ /**
618
+ * Stable cache/dedup key for a (possibly wire-typed) `value`: the sorted-key
619
+ * stable encoding of its wire form. Byte-identical to `stableStringify(value)`
620
+ * for pure-JSON values; deterministic tagged tokens for `bigint`/`Date`/`Map`/
621
+ * `Set`/`URL`/bytes; throws a `TypeError` on values the wire refuses.
622
+ */
623
+ declare const stableWireKey: (value: unknown) => string;
617
624
  /** A single memoized result, the deps it read, and any active subscribers. */
618
625
  interface CacheEntry {
619
626
  /** Approximate serialized size of `result`, charged against `maxBytes`. */
@@ -2400,6 +2407,11 @@ interface MaterializeResult {
2400
2407
  /** `id → projected-value JSON` — the post-tick membership, to feed back as `baseline` next tick. */
2401
2408
  nextBaseline: Map<string, string>;
2402
2409
  }
2410
+ /** The outcome of one incremental materialize pass. No baseline: incremental applies only the pulled slice, never a full-membership diff. */
2411
+ interface IncrementalMaterializeResult {
2412
+ /** Number of `CdcChange`s applied (upserts + tombstone deletes) for the pulled slice. */
2413
+ applied: number;
2414
+ }
2403
2415
  /**
2404
2416
  * Diff `pulled` against `baseline` and apply the delta to `writer`. Returns the
2405
2417
  * applied count and the next baseline. A steady-state tick (membership unchanged)
@@ -2410,6 +2422,36 @@ declare const materializeExternalRows: (writer: DatabaseWriterLike, pulled: Read
2410
2422
  table: string;
2411
2423
  }) => Promise<MaterializeResult>;
2412
2424
  /**
2425
+ * Apply an **incremental** slice (plan 136): the freshly-pulled rows changed since
2426
+ * the watermark, upsert-only. Unlike {@link materializeExternalRows} this reads no
2427
+ * baseline and never diffs the full membership — an absent row means "unchanged
2428
+ * since the watermark", NOT "deleted". Each pulled row is projected with the SAME
2429
+ * {@link projectExternalSourceRow} full-pull uses, so an incrementally-upserted row
2430
+ * is byte-identical to how the next reconcile sweep's full-pull would store it (no
2431
+ * spurious update on reconcile).
2432
+ *
2433
+ * Delete visibility comes from `deletedIds` — the ids the caller resolved from the
2434
+ * source's soft-delete tombstone column. Every other pulled row is an `insert`,
2435
+ * which {@link applyCdcChanges} upserts (insert, or replace on conflict), so a
2436
+ * changed existing row is updated and a genuinely new row is inserted without the
2437
+ * caller tracking which is which.
2438
+ *
2439
+ * **Content short-circuit.** An incremental cursor query uses `>= watermark` (so
2440
+ * rows sharing the boundary value are never skipped), which means a steady-state
2441
+ * tick re-pulls the boundary row(s) unchanged. Blindly upserting them would append
2442
+ * a `__cdc_log` entry, broadcast a spurious `update` to every `defineShape`
2443
+ * subscriber, re-run search/aggregate/rank sync, and fire `onWrite` (a Vectorize
2444
+ * re-embed = real cost) on every tick — and `replace` would reset `_creationTime`.
2445
+ * So each row is diffed against its stored projection (the SAME
2446
+ * {@link projectExternalSourceRow} + {@link stableStringify} full-pull uses) and
2447
+ * skipped when byte-identical — mirroring the full-pull diff's steady-state no-op.
2448
+ */
2449
+ declare const materializeExternalRowsIncremental: (writer: DatabaseWriterLike, pulled: ReadonlyArray<Record<string, unknown>>, options: {
2450
+ columns?: ReadonlyArray<string>;
2451
+ deletedIds?: ReadonlySet<string>;
2452
+ table: string;
2453
+ }) => Promise<IncrementalMaterializeResult>;
2454
+ /**
2413
2455
  * Read the materialized table's current membership as the canonical full-pull
2414
2456
  * baseline (`id → canonical JSON`). Reuses the shape scanner (`selectShapeRows`)
2415
2457
  * and the SAME {@link projectExternalSourceRow} + {@link stableStringify} the diff
@@ -2438,14 +2480,23 @@ interface SourceClientLike {
2438
2480
  type SourceRefresh = "manual" | {
2439
2481
  everyMs: number;
2440
2482
  };
2483
+ /** The incremental cursor config (plan 136): the watermark column + the watermark-parameterized pull query. */
2484
+ interface SourceCursorLike {
2485
+ column: string;
2486
+ query: string;
2487
+ }
2441
2488
  /** The runtime `.source(...)` config the poll loop reads — a structural mirror of `@lunora/server`'s `ExternalSourceDefinition` (only the fields the tick uses). */
2442
2489
  interface ExternalSourceLike {
2443
2490
  binding: string;
2444
2491
  columns?: ReadonlyArray<string>;
2492
+ cursor?: SourceCursorLike;
2445
2493
  idColumn?: string;
2446
2494
  map?: (row: Record<string, unknown>) => Record<string, unknown>;
2495
+ mode?: string;
2447
2496
  query: string;
2497
+ reconcileEveryMs?: number;
2448
2498
  refresh?: SourceRefresh;
2499
+ softDeleteColumn?: string;
2449
2500
  tenantBy?: (shardKey: string) => ReadonlyArray<unknown>;
2450
2501
  }
2451
2502
  /**
@@ -2475,6 +2526,39 @@ declare const isSourceDue: (refresh: SourceRefresh | undefined, lastPolledMs: nu
2475
2526
  */
2476
2527
  declare const pullExternalSourceTick: (sql: SqlExec, writer: DatabaseWriterLike, client: SourceClientLike, table: string, source: ExternalSourceLike, shardKey: string) => Promise<MaterializeResult>;
2477
2528
  /**
2529
+ * Whether an upstream row is a soft-delete tombstone under `column`. A set
2530
+ * `deleted_at` (any non-null value, e.g. a timestamp), an `is_deleted = true`, or a
2531
+ * non-zero flag all read as deleted; `null` / `undefined` / `false` / `0` mean
2532
+ * live. Note an **empty string** reads as deleted (`"" !== 0`), so an upstream that
2533
+ * clears the column to `""` rather than `NULL` for a live row would mis-signal —
2534
+ * use `NULL` for live rows. The incremental query MUST return tombstoned rows
2535
+ * (don't filter `WHERE deleted_at IS NULL`) or the delete is never observed.
2536
+ */
2537
+ declare const isSoftDeleted: (row: Record<string, unknown>, column: string) => boolean;
2538
+ /**
2539
+ * Run one **incremental** tick (plan 136). Reads the durable watermark for
2540
+ * `(table, shardKey)`; on the first ever poll or when the `reconcileEveryMs` sweep
2541
+ * is due it runs a **full-pull** (seed/GC: {@link runExternalSourceTick} observes
2542
+ * deletes and re-establishes membership), otherwise it pulls only rows past the
2543
+ * watermark via `cursor.query` and upserts them ({@link materializeExternalRowsIncremental},
2544
+ * tombstones → deletes). Either way it advances the watermark to the max cursor
2545
+ * value seen and persists it (and the reconcile timestamp).
2546
+ *
2547
+ * **Crash safety** is by ordering + idempotency, NOT an atomic transaction across
2548
+ * the two write channels (the apply goes through the `writer`; the watermark write
2549
+ * is a raw `sql` write): the watermark advances only AFTER a fully-applied slice,
2550
+ * so a crash between the apply and the watermark write leaves the watermark behind
2551
+ * and the next tick re-pulls the same `>= watermark` slice — which the upsert
2552
+ * short-circuits (unchanged rows) or re-applies idempotently. It only ever replays,
2553
+ * never skips (same self-healing argument as `advanceClientWatermark`).
2554
+ *
2555
+ * Requires `source.cursor` (validated at `defineSchema` for incremental mode); a
2556
+ * missing cursor throws rather than silently degrading to a stuck watermark.
2557
+ */
2558
+ declare const pullExternalSourceIncrementalTick: (sql: SqlExec, writer: DatabaseWriterLike, client: SourceClientLike, table: string, source: ExternalSourceLike, shardKey: string, nowMs: number) => Promise<{
2559
+ applied: number;
2560
+ }>;
2561
+ /**
2478
2562
  * Reserved `functionPath` prefix for admin introspection RPCs. These travel
2479
2563
  * over the same `/_lunora/rpc` → shard `/rpc` path as ordinary functions, but
2480
2564
  * `ShardDO` intercepts them before user dispatch and serves them from the
@@ -6431,7 +6515,12 @@ declare abstract class ShardDO {
6431
6515
  * server logs, browser history, and `Referer` headers on any
6432
6516
  * subresource the upgrade page loads after the handshake. Use a
6433
6517
  * short-lived rotating token in production rather than a long-lived
6434
- * secret.
6518
+ * secret — for the ADMIN credential specifically, the worker mints one
6519
+ * (`POST /_lunora/admin/ws-token`) and {@link isAdminSocket} accepts it, so
6520
+ * the master `LUNORA_ADMIN_TOKEN` never rides the URL.
6521
+ *
6522
+ * Async because the admin fallback ({@link isAdminSocket}) verifies the
6523
+ * ephemeral sub-token with WebCrypto HMAC.
6435
6524
  */
6436
6525
  private isUpgradeAllowed;
6437
6526
  /**
@@ -6442,10 +6531,20 @@ declare abstract class ShardDO {
6442
6531
  */
6443
6532
  private suppliedWsToken;
6444
6533
  /**
6445
- * Whether the upgrade presented a token matching `LUNORA_ADMIN_TOKEN`,
6446
- * constant-time compared. Closed (returns `false`) when the admin token is
6447
- * unset, mirroring `isAdminAuthorized` for the HTTP path so admin
6448
- * streaming is opt-in rather than exposed by default.
6534
+ * Whether the upgrade presented an admin credential: the master
6535
+ * `LUNORA_ADMIN_TOKEN` (constant-time compared) or a short-lived sub-token
6536
+ * the worker minted with it (`POST /_lunora/admin/ws-token`
6537
+ * HMAC-verified statelessly here, since both isolates hold the master token
6538
+ * in `env`). The ephemeral token is what the studio sends in `?token=`, so
6539
+ * the master credential stays out of URLs/logs. Closed (resolves `false`)
6540
+ * when the admin token is unset, mirroring `isAdminAuthorized` for the HTTP
6541
+ * path so admin streaming is opt-in rather than exposed by default.
6542
+ *
6543
+ * Enforcement: with `LUNORA_REQUIRE_EPHEMERAL_WS_TOKEN` set
6544
+ * (`1`/`true`/`on`/`yes`/`enabled`), a raw master token in the
6545
+ * `?token=` query parameter is rejected — the query string is exactly
6546
+ * where it leaks. The `Authorization` header path still takes the master
6547
+ * token: browsers can't set it on a WS upgrade, so it never rides a URL.
6449
6548
  */
6450
6549
  private isAdminSocket;
6451
6550
  /**
@@ -6682,4 +6781,4 @@ interface WhereSqlStrategy {
6682
6781
  * `undefined` when the input imposes no constraint (empty `where`).
6683
6782
  */
6684
6783
  declare const compileWhereSql: (where: WhereInput | undefined, strategy: WhereSqlStrategy) => SQL | undefined;
6685
- 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 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, type GroupByEntry, type GroupByOptions, type HibernatableWebSocket, type IdGenerator, type ImportError, type ImportShardAdminArgs, type ImportShardArgs, type ImportShardResult, 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 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 SourceRefresh, 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 TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, 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, buildFtsMatch, buildSecurityAudit, buildSeekWhere, clearCapturedMail, coerceAggregateNumber, compileWhereSql, containsRelationPredicate, createDependencyTracker, createShardCtxDb, createSystemReader, decodeCursor, depKey, diffExternalSource, encodeAggregateKey, encodeCursor, encodePartitionKey, ensureAuthMetricsTables, ensureFunctionMetricsTables, ensureMailTable, exportShardRows, exportShardTable, facetColumn, fanOutScalarCounts, foldAggregateTally, ftsTableName, guardWriter, hasTrigger, importShardRows, isRelationPredicate, isSourceDue, liftSourceId, listTables, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, mergeWhere, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, parseExportShardArgs, parseImportShardArgs, planAggregateLookup, 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, scoreDocument, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, serveRelationFanout, softDeleteScope, sortColumnName, stableStringify, stringifySearchText, subscriptionListDeltas, throwingScheduler, tokenizeSearch, trimCdcChanges, validateImportRow };
6784
+ 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 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, 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 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 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 TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, 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, buildFtsMatch, buildSecurityAudit, buildSeekWhere, clearCapturedMail, coerceAggregateNumber, compileWhereSql, containsRelationPredicate, createDependencyTracker, createShardCtxDb, createSystemReader, decodeCursor, depKey, diffExternalSource, encodeAggregateKey, encodeCursor, encodePartitionKey, ensureAuthMetricsTables, ensureFunctionMetricsTables, ensureMailTable, exportShardRows, exportShardTable, facetColumn, fanOutScalarCounts, foldAggregateTally, ftsTableName, guardWriter, hasTrigger, importShardRows, isRelationPredicate, isSoftDeleted, isSourceDue, liftSourceId, listTables, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, mergeWhere, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, parseExportShardArgs, parseImportShardArgs, planAggregateLookup, 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, scoreDocument, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, serveRelationFanout, softDeleteScope, sortColumnName, stableStringify, stableWireKey, stringifySearchText, subscriptionListDeltas, throwingScheduler, tokenizeSearch, trimCdcChanges, validateImportRow };
package/dist/index.mjs CHANGED
@@ -7,9 +7,9 @@ export { NotUniqueError, assertValidClientId, createShardCtxDb, normalizeIdStruc
7
7
  export { DATA_MIGRATION_STATE_TABLE, readMigrationStatus, runDataMigration } from './packem_shared/DATA_MIGRATION_STATE_TABLE-CYwBpyTr.mjs';
8
8
  export { SCAN_DEP, createDependencyTracker, depKey } from './packem_shared/SCAN_DEP-DLJF8dsj.mjs';
9
9
  export { renderSql } from './packem_shared/renderSql-D6eUcn2N.mjs';
10
- export { diffExternalSource } from './packem_shared/diffExternalSource-Cx9HUPJj.mjs';
11
- export { materializeExternalRows, readExternalSourceBaseline, runExternalSourceTick } from './packem_shared/materializeExternalRows-CTqZisSC.mjs';
12
- export { isSourceDue, liftSourceId, pullExternalSourceTick } from './packem_shared/isSourceDue-CYkt7Ru8.mjs';
10
+ export { diffExternalSource } from './packem_shared/diffExternalSource-CovHfdyo.mjs';
11
+ export { materializeExternalRows, materializeExternalRowsIncremental, readExternalSourceBaseline, runExternalSourceTick } from './packem_shared/materializeExternalRows-FyA5Rwn4.mjs';
12
+ export { isSoftDeleted, isSourceDue, liftSourceId, pullExternalSourceIncrementalTick, pullExternalSourceTick } from './packem_shared/isSoftDeleted-i5kKh6Up.mjs';
13
13
  export { FUNCTION_METRICS_BUCKETS_TABLE, FUNCTION_METRICS_BUCKET_MS, FUNCTION_METRICS_BUCKET_RETENTION, FUNCTION_METRICS_INDEX_TABLE, FUNCTION_METRICS_TABLE, ensureFunctionMetricsTables, readFunctionMetricBuckets, readFunctionMetricIndexHits, readFunctionMetrics, readFunctionMetricsTotals, recordFunctionMetric } from './packem_shared/FUNCTION_METRICS_BUCKETS_TABLE-UDNVD7FS.mjs';
14
14
  export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, FLAGS_FUNCTION_PREFIX, RELATION_FUNCTION_PREFIX, facetColumn, listTables, readTablePage, selectMatchingIds } from './packem_shared/ADMIN_FUNCTIONS-CAHLZMj8.mjs';
15
15
  export { LogBuffer } from './packem_shared/LogBuffer-B_Ezju_N.mjs';
@@ -18,7 +18,7 @@ export { default as NotFoundError } from './packem_shared/NotFoundError-C70b9hLw
18
18
  export { armRestore, readBookmark } from './packem_shared/armRestore-4Px61hHS.mjs';
19
19
  export { applySelect, buildSeekWhere, decodeCursor, encodeCursor, normalizeOrderKeys, softDeleteScope } from './packem_shared/applySelect-WQY8m62C.mjs';
20
20
  export { RANK_TIEBREAK, encodePartitionKey, matchesRankStaticWhere, rankTableName, resolveRankPartition, sortColumnName } from './packem_shared/RANK_TIEBREAK-CXhdcA1o.mjs';
21
- export { ReactiveCache, reactiveCacheKey } from './packem_shared/ReactiveCache-BYlSGY0N.mjs';
21
+ export { ReactiveCache, reactiveCacheKey } from './packem_shared/ReactiveCache-DnSvbjil.mjs';
22
22
  export { serveRelationFanout } from './packem_shared/serveRelationFanout-BgaNg3Hu.mjs';
23
23
  export { DEFAULT_MAX_RELATION_KEYS, assertFlatPredicate, assertShapeShardable, containsRelationPredicate, isRelationPredicate, resolveRelationPredicates } from './packem_shared/DEFAULT_MAX_RELATION_KEYS-BEan1CRD.mjs';
24
24
  export { applyOnDelete, fanOutScalarCounts, resolveWith, runRowValidators } from './packem_shared/applyOnDelete-BXSq3S70.mjs';
@@ -26,9 +26,9 @@ export { RLS_UNWRAP_SYMBOL, RlsRequiredError, guardWriter } from './packem_share
26
26
  export { buildFtsMatch, ftsTableName, scoreDocument, stringifySearchText, tokenizeSearch } from './packem_shared/buildFtsMatch-BLEMawrp.mjs';
27
27
  export { M as MIN_ADMIN_TOKEN_LENGTH, a as MIN_AUTH_SECRET_LENGTH, b as buildSecurityAudit } from './packem_shared/security-audit-CucgBice.mjs';
28
28
  export { SESSION_DO_TTL_DEFAULT, SessionDO } from './packem_shared/SESSION_DO_TTL_DEFAULT-BnSKgVO4.mjs';
29
- export { ROOT_DO_SIZE_WARN_BYTES, ROOT_SHARD_NAME, ShardDO } from './packem_shared/ROOT_DO_SIZE_WARN_BYTES-BA8QOChj.mjs';
29
+ export { ROOT_DO_SIZE_WARN_BYTES, ROOT_SHARD_NAME, ShardDO } from './packem_shared/ROOT_DO_SIZE_WARN_BYTES-BWz51mpB.mjs';
30
30
  export { SHARD_REGISTRY_DO_NAME, ShardRegistryDO } from './packem_shared/SHARD_REGISTRY_DO_NAME-D99roc-r.mjs';
31
- export { MAX_SQL_ROWS, assertReadonly, runReadonlySql } from './packem_shared/MAX_SQL_ROWS-D57CJaT9.mjs';
31
+ export { MAX_SQL_ROWS, assertReadonly, runReadonlySql } from './packem_shared/MAX_SQL_ROWS-iFAA8FbD.mjs';
32
32
  export { createSystemReader } from './packem_shared/createSystemReader-D12eNH13.mjs';
33
33
  export { ConflictError } from './packem_shared/ConflictError-CLoq37xH.mjs';
34
34
  export { hasTrigger, runTriggers } from './packem_shared/hasTrigger-5N6_Fx0A.mjs';
@@ -36,5 +36,6 @@ export { compileWhereSql } from './packem_shared/compileWhereSql-DE6yfRcQ.mjs';
36
36
  export { CDC_LOG_TABLE, applyCdcChanges, readCdcChanges, trimCdcChanges } from './packem_shared/CDC_LOG_TABLE-DjJEHiM2.mjs';
37
37
  export { backfillAggregateIndexes, backfillRankIndexes } from './packem_shared/backfillAggregateIndexes-DDoT-UUI.mjs';
38
38
  export { runShardMigrations } from './packem_shared/runShardMigrations-BGx4v2B6.mjs';
39
- export { stableStringify } from './packem_shared/stableStringify-MydiuScU.mjs';
40
- export { s as subscriptionListDeltas } from './packem_shared/subscription-delivery-CWigSEr3.mjs';
39
+ export { stableStringify } from './packem_shared/stableStringify-mC40mZts.mjs';
40
+ export { stableWireKey } from './packem_shared/stableWireKey-DKuXO7T5.mjs';
41
+ export { subscriptionListDeltas } from './packem_shared/subscriptionListDeltas-CT76bYny.mjs';
@@ -3,9 +3,39 @@ import { LunoraError } from '@lunora/errors';
3
3
  const MAX_SQL_ROWS = 1e3;
4
4
  const READONLY_LEAD = /^(?:explain\s+(?:query\s+plan\s+)?)?(?:select|with)\b/iu;
5
5
  const FORBIDDEN_KEYWORD = /\b(?:alter|attach|create|delete|detach|drop|insert|pragma|reindex|replace|truncate|update|vacuum)\b/iu;
6
- const LEADING_NOISE = /^(?:\s|--[^\n]*\n?|\/\*[\s\S]*?\*\/)+/u;
7
6
  const TRAILING_SEMICOLON = /;\s*$/u;
8
- const stripLeading = (sql) => sql.replace(LEADING_NOISE, "");
7
+ const WHITESPACE = /\s/u;
8
+ const skipLineComment = (sql, from) => {
9
+ let index = from + 2;
10
+ while (index < sql.length && sql[index] !== "\n") {
11
+ index += 1;
12
+ }
13
+ return index;
14
+ };
15
+ const skipBlockComment = (sql, from) => {
16
+ const close = sql.indexOf("*/", from + 2);
17
+ return close === -1 ? -1 : close + 2;
18
+ };
19
+ const stripLeading = (sql) => {
20
+ let index = 0;
21
+ while (index < sql.length) {
22
+ const char = sql[index];
23
+ if (char !== void 0 && WHITESPACE.test(char)) {
24
+ index += 1;
25
+ } else if (char === "-" && sql[index + 1] === "-") {
26
+ index = skipLineComment(sql, index);
27
+ } else if (char === "/" && sql[index + 1] === "*") {
28
+ const next = skipBlockComment(sql, index);
29
+ if (next === -1) {
30
+ break;
31
+ }
32
+ index = next;
33
+ } else {
34
+ break;
35
+ }
36
+ }
37
+ return sql.slice(index);
38
+ };
9
39
  const sqlError = (message, code) => new LunoraError(code, message, { status: 400 });
10
40
  const assertReadonly = (query) => {
11
41
  const trimmed = stripLeading(query).trim();