@lunora/do 1.0.0-alpha.37 → 1.0.0-alpha.39

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
@@ -1312,6 +1312,13 @@ interface SchemaLike {
1312
1312
  }
1313
1313
  interface TableDefinitionLike {
1314
1314
  readonly aggregateIndexes?: ReadonlyArray<AggregateIndexDefinitionLike>;
1315
+ /**
1316
+ * Mirror of `@lunora/server`'s `TableDefinition.geoIndexes` (set by
1317
+ * `.geoIndex()`). Each declares a geohash companion over a `v.geoPoint()`
1318
+ * column so `withGeoIndex(name, q => q.near(...) | q.within(...))` resolves
1319
+ * proximity / bounding-box reads. Empty/absent ⇒ the table has no geo index.
1320
+ */
1321
+ readonly geoIndexes?: ReadonlyArray<GeoIndexDefinitionLike>;
1315
1322
  readonly indexes: ReadonlyArray<IndexDefinitionLike>;
1316
1323
  /**
1317
1324
  * `true` when `.public()` opted this table OUT of secure-by-default RLS
@@ -1339,6 +1346,15 @@ interface TableDefinitionLike {
1339
1346
  field: string;
1340
1347
  };
1341
1348
  readonly triggerMap?: Record<string, TriggerDefinitionLike>;
1349
+ /**
1350
+ * Mirror of `@lunora/server`'s `TableDefinition.ttlPolicy` (set by `.ttl()`).
1351
+ * Drives the DO alarm-driven expiry sweep — see `ttl-sweep.ts`. Absent ⇒ rows
1352
+ * never auto-expire.
1353
+ */
1354
+ readonly ttlPolicy?: {
1355
+ after?: number;
1356
+ field: string;
1357
+ };
1342
1358
  }
1343
1359
  interface IndexDefinitionLike {
1344
1360
  readonly fields: ReadonlyArray<string>;
@@ -1350,6 +1366,12 @@ interface SearchIndexDefinitionLike {
1350
1366
  readonly filterFields?: ReadonlyArray<string>;
1351
1367
  readonly name: string;
1352
1368
  }
1369
+ /** Mirror of `@lunora/server`'s `GeoIndexDefinition` — a geohash companion over a `v.geoPoint()` column. */
1370
+ interface GeoIndexDefinitionLike {
1371
+ readonly field: string;
1372
+ readonly name: string;
1373
+ readonly precision?: number;
1374
+ }
1353
1375
  /**
1354
1376
  * Column constraints/defaults the write layer honors, mirrored structurally
1355
1377
  * from `@lunora/values`' `ColumnMeta` (kept local so this package doesn't take
@@ -1423,7 +1445,7 @@ type ReadHook = (table: string, idOrScan?: string) => void;
1423
1445
  * No-op by default; called at most once per read (not per row), so it adds no
1424
1446
  * meaningful hot-path cost.
1425
1447
  */
1426
- type IndexUseHook = (table: string, indexName: string, kind: "index" | "rank" | "search") => void;
1448
+ type IndexUseHook = (table: string, indexName: string, kind: "geo" | "index" | "rank" | "search") => void;
1427
1449
  /** Pluggable wall clock — defaults to `Date.now`. */
1428
1450
  type Clock = () => number;
1429
1451
  /** Pluggable ID minter — defaults to `crypto.randomUUID()`. */
@@ -1566,6 +1588,22 @@ interface SearchFilterBuilderLike {
1566
1588
  eq: (field: string, value: unknown) => SearchFilterBuilderLike;
1567
1589
  search: (field: string, query: string) => SearchFilterBuilderLike;
1568
1590
  }
1591
+ interface GeoFilterBuilderLike {
1592
+ near: (point: {
1593
+ lat: number;
1594
+ lng: number;
1595
+ }, radiusMeters: number) => GeoFilterBuilderLike;
1596
+ within: (box: {
1597
+ ne: {
1598
+ lat: number;
1599
+ lng: number;
1600
+ };
1601
+ sw: {
1602
+ lat: number;
1603
+ lng: number;
1604
+ };
1605
+ }) => GeoFilterBuilderLike;
1606
+ }
1569
1607
  /** Options accepted by {@link TableReaderLike.paginate} — Convex-compatible. */
1570
1608
  interface PaginationOptions {
1571
1609
  /** Opaque cursor from a prior page's `continueCursor`; `null`/omitted starts at the first page. */
@@ -1603,6 +1641,7 @@ interface TableReaderLike {
1603
1641
  * more than one matches. Mirrors Convex's `.unique()`.
1604
1642
  */
1605
1643
  unique: () => Promise<Record<string, unknown> | null>;
1644
+ withGeoIndex: (indexName: string, build: (q: GeoFilterBuilderLike) => GeoFilterBuilderLike) => TableReaderLike;
1606
1645
  withIndex: (indexName: string, range?: (q: IndexRangeBuilderLike) => IndexRangeBuilderLike) => TableReaderLike;
1607
1646
  withSearchIndex: (indexName: string, search: (q: SearchFilterBuilderLike) => SearchFilterBuilderLike) => TableReaderLike;
1608
1647
  }
@@ -2218,6 +2257,13 @@ interface MetricEvent {
2218
2257
  name: string;
2219
2258
  /** Shard key for single-shard calls; absent for the unnamed root DO. */
2220
2259
  shardKey?: string;
2260
+ /**
2261
+ * Trace id of the dispatch that recorded this measurement, when it ran inside
2262
+ * one — the measurement's **exemplar**, letting a consumer jump from a metric
2263
+ * point to a trace that produced it (OpenTelemetry's exemplar model). Stamped
2264
+ * by the shard from the current request's trace context, not by the caller.
2265
+ */
2266
+ traceId?: string;
2221
2267
  /** Wall-clock millis when the measurement was recorded. */
2222
2268
  ts: number;
2223
2269
  /**
@@ -2235,6 +2281,21 @@ interface MetricEvent {
2235
2281
  * (32-hex trace, 16-hex span), so a `SpanEvent` composes into an OTLP span with
2236
2282
  * no reformatting.
2237
2283
  */
2284
+ /**
2285
+ * Handle the enclosing `ctx.trace` span hands its body, so the body can attach
2286
+ * attributes only known *after* it resolves — an AI call's token usage or dollar
2287
+ * cost, a downstream response's status, a computed row count. The start
2288
+ * attributes passed to `ctx.trace(name, fn, attributes)` are snapshotted before
2289
+ * the body runs (so a mid-span mutation can't rewrite them); anything set through
2290
+ * this handle is merged over that snapshot at record time, with the post-hoc
2291
+ * value winning on a key clash.
2292
+ */
2293
+ interface SpanHandle {
2294
+ /** Set one attribute on the enclosing span (merged at record time; post-hoc wins on key clash). */
2295
+ setAttribute: (key: string, value: LogFields[string]) => void;
2296
+ /** Merge attributes onto the enclosing span (post-hoc wins on key clash). */
2297
+ setAttributes: (fields: LogFields) => void;
2298
+ }
2238
2299
  interface SpanEvent {
2239
2300
  /**
2240
2301
  * Structured attributes the caller attached, already normalized to a fresh
@@ -2300,8 +2361,12 @@ interface SpanEvent {
2300
2361
  * `LunoraTracer`). Declared here rather than imported so `@lunora/do` takes no
2301
2362
  * dependency on `@lunora/server`; a cross-package assignability guard in
2302
2363
  * `@lunora/testing` fails the build if the two drift apart.
2364
+ *
2365
+ * The body's second argument is the enclosing span's {@link SpanHandle}, through
2366
+ * which it can attach attributes only known *after* it resolves (post-hoc). It is
2367
+ * a trailing parameter, so a `(trace) => …` body that ignores it still conforms.
2303
2368
  */
2304
- type ContextTracer = <T>(name: string, function_: (trace: ContextTracer) => Promise<T> | T, attributes?: LogFields) => Promise<T>;
2369
+ type ContextTracer = <T>(name: string, function_: (trace: ContextTracer, span: SpanHandle) => Promise<T> | T, attributes?: LogFields) => Promise<T>;
2305
2370
  /** Structural shape of the `ctx.metrics` recorder (see the server `LunoraMetrics`). */
2306
2371
  interface ContextMetrics {
2307
2372
  count: (name: string, value?: number, attributes?: LogFields) => void;
@@ -2775,6 +2840,7 @@ declare const ADMIN_FUNCTIONS: {
2775
2840
  readonly getFanoutMetrics: "__lunora_admin__:getFanoutMetrics";
2776
2841
  readonly getFunctionStats: "__lunora_admin__:getFunctionStats";
2777
2842
  readonly getIssues: "__lunora_admin__:getIssues";
2843
+ readonly getMetricHistory: "__lunora_admin__:getMetricHistory";
2778
2844
  readonly getMetricSeries: "__lunora_admin__:getMetricSeries";
2779
2845
  readonly listSubscriptions: "__lunora_admin__:listSubscriptions";
2780
2846
  readonly listTableIndexes: "__lunora_admin__:listTableIndexes";
@@ -2899,7 +2965,7 @@ interface FunctionCallStat {
2899
2965
  interface TableIndexInfo {
2900
2966
  fields: string[];
2901
2967
  name: string;
2902
- type: "index" | "rank" | "search" | "vector";
2968
+ type: "geo" | "index" | "rank" | "search" | "vector";
2903
2969
  unique?: boolean;
2904
2970
  }
2905
2971
  /** Payload of a `__lunora_admin__:listTableIndexes` call: every declared index on the table. */
@@ -3079,7 +3145,12 @@ interface StudioFeaturesResult {
3079
3145
  kv: boolean;
3080
3146
  /** `@lunora/mail` is imported by a `lunora/` source or a declared dependency. */
3081
3147
  mail: boolean;
3082
- /** `@lunora/payment` is used (import or `ctx.payments`) or a declared dependency. */
3148
+ /**
3149
+ * `@lunora/payment` is used (import or `ctx.payments`), or the app declares the store's
3150
+ * `subscriptions`/`events` tables that the Payments panel reads. Unlike the other flags this
3151
+ * has no declared-dependency arm: the panel queries those tables directly, so a bare dependency
3152
+ * (e.g. reusing the package's pure webhook helpers) must not show a page that would then error.
3153
+ */
3083
3154
  payments: boolean;
3084
3155
  /** `@lunora/queue` / `ctx.queues` is used, the app declares queues, or it is a declared dependency. */
3085
3156
  queues: boolean;
@@ -3543,6 +3614,39 @@ declare const readFunctionMetricsTotals: (sql: SqlExec) => {
3543
3614
  errors: number;
3544
3615
  requests: number;
3545
3616
  };
3617
+ /** Default geohash precision (characters) maintained by a `.geoIndex()` companion — ~4.8 m cells. */
3618
+ declare const GEO_DEFAULT_PRECISION = 9;
3619
+ /** A latitude/longitude point (WGS84 decimal degrees). */
3620
+ interface GeoPoint {
3621
+ lat: number;
3622
+ lng: number;
3623
+ }
3624
+ /** An axis-aligned latitude/longitude bounding box (`sw`/`ne` corners). */
3625
+ interface GeoBoundingBox {
3626
+ ne: GeoPoint;
3627
+ sw: GeoPoint;
3628
+ }
3629
+ /**
3630
+ * Encode `point` to a geohash of `precision` characters. Standard interleaved
3631
+ * lat/lng bisection over the base-32 alphabet.
3632
+ */
3633
+ declare const encodeGeohash: (point: GeoPoint, precision: number) => string;
3634
+ /** Great-circle distance between two points in metres (Haversine). */
3635
+ declare const haversineMeters: (a: GeoPoint, b: GeoPoint) => number;
3636
+ /**
3637
+ * The center cell plus its eight neighbours at a precision chosen so each cell is
3638
+ * at least `radiusMeters` wide — the geohash prefixes to range-scan for a
3639
+ * proximity query. Deduplicated (near a pole neighbours can collapse).
3640
+ */
3641
+ declare const coveringGeohashes: (center: GeoPoint, radiusMeters: number) => string[];
3642
+ /** Whether `point` falls inside `box` (inclusive edges). */
3643
+ declare const pointInBoundingBox: (point: GeoPoint, box: GeoBoundingBox) => boolean;
3644
+ /**
3645
+ * Geohash prefixes covering `box`: the covering cells of the circle centered on
3646
+ * the box whose radius reaches the north-east corner, guaranteeing every point
3647
+ * in the box is scanned before the exact `pointInBoundingBox` refine.
3648
+ */
3649
+ declare const boundingBoxGeohashes: (box: GeoBoundingBox) => string[];
3546
3650
  /**
3547
3651
  * Severity of a `ctx.log.*` call. The five console method names (`log` is the
3548
3652
  * default level, distinct from `info`) plus `trace`/`fatal`, so the logger spans
@@ -4152,6 +4256,28 @@ declare class SessionDO {
4152
4256
  private handleGet;
4153
4257
  private handleRevoke;
4154
4258
  }
4259
+ /** One table's resolved TTL policy, as surfaced to the DO alarm by the generated shard subclass. */
4260
+ interface TtlSweepSpec {
4261
+ /** Millisecond offset added to `field` to derive the expiry (`field + after`); absent ⇒ `field` is the absolute expiry. */
4262
+ after?: number;
4263
+ /** The epoch-millisecond expiry column. */
4264
+ field: string;
4265
+ /** The `.softDelete()` marker column, when the table soft-deletes — expired-but-already-tombstoned rows are skipped. */
4266
+ softDeleteField?: string;
4267
+ /** The table whose expired rows are swept. */
4268
+ table: string;
4269
+ }
4270
+ /**
4271
+ * Select up to `limit` ids of rows in `spec.table` whose TTL expired at `now`
4272
+ * (i.e. `field + (after ?? 0) < now`). `hasMore` is `true` when matches remained
4273
+ * beyond `limit`, so the caller can loop a bounded batch. When `spec.softDeleteField`
4274
+ * is set, rows already soft-deleted (marker non-null) are excluded so the sweep
4275
+ * never re-touches a tombstone.
4276
+ */
4277
+ declare const selectExpiredIds: (sql: SqlExec, spec: TtlSweepSpec, now: number, limit: number) => {
4278
+ hasMore: boolean;
4279
+ ids: string[];
4280
+ };
4155
4281
  /**
4156
4282
  * Diff the previously-sent list snapshot (`previousJson`, the memo's
4157
4283
  * `lastJson`) against the new query result and produce per-row
@@ -5631,6 +5757,35 @@ declare abstract class ShardDO {
5631
5757
  * no-op when the runtime exposes no `setAlarm` (unit harness).
5632
5758
  */
5633
5759
  protected scheduleSourcePoll(): Promise<void>;
5760
+ /**
5761
+ * The resolved TTL policies (`.ttl(field, { after })`) for this DO's schema —
5762
+ * one {@link TtlSweepSpec} per table that declares a TTL. The base `ShardDO`
5763
+ * has no schema, so it returns `[]` and the TTL tier stays dormant. The
5764
+ * codegen subclass overrides it to read each table's `ttlPolicy` (+ its
5765
+ * `.softDelete()` marker) off the imported schema.
5766
+ */
5767
+ protected ttlSweeps(): ReadonlyArray<TtlSweepSpec>;
5768
+ /**
5769
+ * Sweep every `.ttl()` table once: page the rows past their expiry and remove
5770
+ * each THROUGH the schema-aware writer (`deleteRowThroughWriter`) so companions
5771
+ * / CDC / live subscriptions stay correct and a `.softDelete()` table soft-deletes
5772
+ * instead of physically removing the row. Work is bounded per tick
5773
+ * ({@link TTL_SWEEP_BATCH} × {@link TTL_SWEEP_MAX_BATCHES}) so a large backlog
5774
+ * drains across several alarms without stalling the shard.
5775
+ *
5776
+ * Returns the next-due timestamp (a coarse {@link TTL_SWEEP_INTERVAL_MS}
5777
+ * cadence, so freshly-written rows expire within a bounded window) while any
5778
+ * TTL table exists, or `undefined` when there are none — so a DO with no TTL
5779
+ * table never arms this tier.
5780
+ */
5781
+ protected pollTtlSweeps(): Promise<number | undefined>;
5782
+ /**
5783
+ * Arm the shared poll alarm for the TTL sweep. Mirrors {@link scheduleSourcePoll};
5784
+ * the codegen subclass calls it once on construction when the schema declares a
5785
+ * `.ttl()` table so the sweep loop starts, after which {@link ShardDO.alarm}
5786
+ * re-arms itself. Idempotent; a no-op when the runtime exposes no `setAlarm`.
5787
+ */
5788
+ protected scheduleTtlSweep(): Promise<void>;
5634
5789
  /** This DO's shard key (its DO name), or `__root__` for the single-DO default. The `tenantBy` mapper binds it into the source query. */
5635
5790
  protected currentShardKey(): string;
5636
5791
  /** Record a contained external-source ingest failure (one sourced table's poll) into the log ring without aborting the others. */
@@ -7083,4 +7238,4 @@ interface WhereSqlStrategy {
7083
7238
  * `undefined` when the input imposes no constraint (empty `where`).
7084
7239
  */
7085
7240
  declare const compileWhereSql: (where: WhereInput | undefined, strategy: WhereSqlStrategy) => SQL | undefined;
7086
- 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, 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 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 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, createMetrics, createShardCtxDb, createSystemReader, createTracer, decodeCursor, depKey, diffExternalSource, dispatchRootSpan, 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 };
7241
+ 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, boundingBoxGeohashes, buildFtsMatch, 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, ftsTableName, 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, scoreDocument, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, serveRelationFanout, softDeleteScope, sortColumnName, stableStringify, stableWireKey, stringifySearchText, subscriptionListDeltas, throwingScheduler, tokenizeSearch, trimCdcChanges, validateImportRow };
package/dist/index.d.ts CHANGED
@@ -1312,6 +1312,13 @@ interface SchemaLike {
1312
1312
  }
1313
1313
  interface TableDefinitionLike {
1314
1314
  readonly aggregateIndexes?: ReadonlyArray<AggregateIndexDefinitionLike>;
1315
+ /**
1316
+ * Mirror of `@lunora/server`'s `TableDefinition.geoIndexes` (set by
1317
+ * `.geoIndex()`). Each declares a geohash companion over a `v.geoPoint()`
1318
+ * column so `withGeoIndex(name, q => q.near(...) | q.within(...))` resolves
1319
+ * proximity / bounding-box reads. Empty/absent ⇒ the table has no geo index.
1320
+ */
1321
+ readonly geoIndexes?: ReadonlyArray<GeoIndexDefinitionLike>;
1315
1322
  readonly indexes: ReadonlyArray<IndexDefinitionLike>;
1316
1323
  /**
1317
1324
  * `true` when `.public()` opted this table OUT of secure-by-default RLS
@@ -1339,6 +1346,15 @@ interface TableDefinitionLike {
1339
1346
  field: string;
1340
1347
  };
1341
1348
  readonly triggerMap?: Record<string, TriggerDefinitionLike>;
1349
+ /**
1350
+ * Mirror of `@lunora/server`'s `TableDefinition.ttlPolicy` (set by `.ttl()`).
1351
+ * Drives the DO alarm-driven expiry sweep — see `ttl-sweep.ts`. Absent ⇒ rows
1352
+ * never auto-expire.
1353
+ */
1354
+ readonly ttlPolicy?: {
1355
+ after?: number;
1356
+ field: string;
1357
+ };
1342
1358
  }
1343
1359
  interface IndexDefinitionLike {
1344
1360
  readonly fields: ReadonlyArray<string>;
@@ -1350,6 +1366,12 @@ interface SearchIndexDefinitionLike {
1350
1366
  readonly filterFields?: ReadonlyArray<string>;
1351
1367
  readonly name: string;
1352
1368
  }
1369
+ /** Mirror of `@lunora/server`'s `GeoIndexDefinition` — a geohash companion over a `v.geoPoint()` column. */
1370
+ interface GeoIndexDefinitionLike {
1371
+ readonly field: string;
1372
+ readonly name: string;
1373
+ readonly precision?: number;
1374
+ }
1353
1375
  /**
1354
1376
  * Column constraints/defaults the write layer honors, mirrored structurally
1355
1377
  * from `@lunora/values`' `ColumnMeta` (kept local so this package doesn't take
@@ -1423,7 +1445,7 @@ type ReadHook = (table: string, idOrScan?: string) => void;
1423
1445
  * No-op by default; called at most once per read (not per row), so it adds no
1424
1446
  * meaningful hot-path cost.
1425
1447
  */
1426
- type IndexUseHook = (table: string, indexName: string, kind: "index" | "rank" | "search") => void;
1448
+ type IndexUseHook = (table: string, indexName: string, kind: "geo" | "index" | "rank" | "search") => void;
1427
1449
  /** Pluggable wall clock — defaults to `Date.now`. */
1428
1450
  type Clock = () => number;
1429
1451
  /** Pluggable ID minter — defaults to `crypto.randomUUID()`. */
@@ -1566,6 +1588,22 @@ interface SearchFilterBuilderLike {
1566
1588
  eq: (field: string, value: unknown) => SearchFilterBuilderLike;
1567
1589
  search: (field: string, query: string) => SearchFilterBuilderLike;
1568
1590
  }
1591
+ interface GeoFilterBuilderLike {
1592
+ near: (point: {
1593
+ lat: number;
1594
+ lng: number;
1595
+ }, radiusMeters: number) => GeoFilterBuilderLike;
1596
+ within: (box: {
1597
+ ne: {
1598
+ lat: number;
1599
+ lng: number;
1600
+ };
1601
+ sw: {
1602
+ lat: number;
1603
+ lng: number;
1604
+ };
1605
+ }) => GeoFilterBuilderLike;
1606
+ }
1569
1607
  /** Options accepted by {@link TableReaderLike.paginate} — Convex-compatible. */
1570
1608
  interface PaginationOptions {
1571
1609
  /** Opaque cursor from a prior page's `continueCursor`; `null`/omitted starts at the first page. */
@@ -1603,6 +1641,7 @@ interface TableReaderLike {
1603
1641
  * more than one matches. Mirrors Convex's `.unique()`.
1604
1642
  */
1605
1643
  unique: () => Promise<Record<string, unknown> | null>;
1644
+ withGeoIndex: (indexName: string, build: (q: GeoFilterBuilderLike) => GeoFilterBuilderLike) => TableReaderLike;
1606
1645
  withIndex: (indexName: string, range?: (q: IndexRangeBuilderLike) => IndexRangeBuilderLike) => TableReaderLike;
1607
1646
  withSearchIndex: (indexName: string, search: (q: SearchFilterBuilderLike) => SearchFilterBuilderLike) => TableReaderLike;
1608
1647
  }
@@ -2218,6 +2257,13 @@ interface MetricEvent {
2218
2257
  name: string;
2219
2258
  /** Shard key for single-shard calls; absent for the unnamed root DO. */
2220
2259
  shardKey?: string;
2260
+ /**
2261
+ * Trace id of the dispatch that recorded this measurement, when it ran inside
2262
+ * one — the measurement's **exemplar**, letting a consumer jump from a metric
2263
+ * point to a trace that produced it (OpenTelemetry's exemplar model). Stamped
2264
+ * by the shard from the current request's trace context, not by the caller.
2265
+ */
2266
+ traceId?: string;
2221
2267
  /** Wall-clock millis when the measurement was recorded. */
2222
2268
  ts: number;
2223
2269
  /**
@@ -2235,6 +2281,21 @@ interface MetricEvent {
2235
2281
  * (32-hex trace, 16-hex span), so a `SpanEvent` composes into an OTLP span with
2236
2282
  * no reformatting.
2237
2283
  */
2284
+ /**
2285
+ * Handle the enclosing `ctx.trace` span hands its body, so the body can attach
2286
+ * attributes only known *after* it resolves — an AI call's token usage or dollar
2287
+ * cost, a downstream response's status, a computed row count. The start
2288
+ * attributes passed to `ctx.trace(name, fn, attributes)` are snapshotted before
2289
+ * the body runs (so a mid-span mutation can't rewrite them); anything set through
2290
+ * this handle is merged over that snapshot at record time, with the post-hoc
2291
+ * value winning on a key clash.
2292
+ */
2293
+ interface SpanHandle {
2294
+ /** Set one attribute on the enclosing span (merged at record time; post-hoc wins on key clash). */
2295
+ setAttribute: (key: string, value: LogFields[string]) => void;
2296
+ /** Merge attributes onto the enclosing span (post-hoc wins on key clash). */
2297
+ setAttributes: (fields: LogFields) => void;
2298
+ }
2238
2299
  interface SpanEvent {
2239
2300
  /**
2240
2301
  * Structured attributes the caller attached, already normalized to a fresh
@@ -2300,8 +2361,12 @@ interface SpanEvent {
2300
2361
  * `LunoraTracer`). Declared here rather than imported so `@lunora/do` takes no
2301
2362
  * dependency on `@lunora/server`; a cross-package assignability guard in
2302
2363
  * `@lunora/testing` fails the build if the two drift apart.
2364
+ *
2365
+ * The body's second argument is the enclosing span's {@link SpanHandle}, through
2366
+ * which it can attach attributes only known *after* it resolves (post-hoc). It is
2367
+ * a trailing parameter, so a `(trace) => …` body that ignores it still conforms.
2303
2368
  */
2304
- type ContextTracer = <T>(name: string, function_: (trace: ContextTracer) => Promise<T> | T, attributes?: LogFields) => Promise<T>;
2369
+ type ContextTracer = <T>(name: string, function_: (trace: ContextTracer, span: SpanHandle) => Promise<T> | T, attributes?: LogFields) => Promise<T>;
2305
2370
  /** Structural shape of the `ctx.metrics` recorder (see the server `LunoraMetrics`). */
2306
2371
  interface ContextMetrics {
2307
2372
  count: (name: string, value?: number, attributes?: LogFields) => void;
@@ -2775,6 +2840,7 @@ declare const ADMIN_FUNCTIONS: {
2775
2840
  readonly getFanoutMetrics: "__lunora_admin__:getFanoutMetrics";
2776
2841
  readonly getFunctionStats: "__lunora_admin__:getFunctionStats";
2777
2842
  readonly getIssues: "__lunora_admin__:getIssues";
2843
+ readonly getMetricHistory: "__lunora_admin__:getMetricHistory";
2778
2844
  readonly getMetricSeries: "__lunora_admin__:getMetricSeries";
2779
2845
  readonly listSubscriptions: "__lunora_admin__:listSubscriptions";
2780
2846
  readonly listTableIndexes: "__lunora_admin__:listTableIndexes";
@@ -2899,7 +2965,7 @@ interface FunctionCallStat {
2899
2965
  interface TableIndexInfo {
2900
2966
  fields: string[];
2901
2967
  name: string;
2902
- type: "index" | "rank" | "search" | "vector";
2968
+ type: "geo" | "index" | "rank" | "search" | "vector";
2903
2969
  unique?: boolean;
2904
2970
  }
2905
2971
  /** Payload of a `__lunora_admin__:listTableIndexes` call: every declared index on the table. */
@@ -3079,7 +3145,12 @@ interface StudioFeaturesResult {
3079
3145
  kv: boolean;
3080
3146
  /** `@lunora/mail` is imported by a `lunora/` source or a declared dependency. */
3081
3147
  mail: boolean;
3082
- /** `@lunora/payment` is used (import or `ctx.payments`) or a declared dependency. */
3148
+ /**
3149
+ * `@lunora/payment` is used (import or `ctx.payments`), or the app declares the store's
3150
+ * `subscriptions`/`events` tables that the Payments panel reads. Unlike the other flags this
3151
+ * has no declared-dependency arm: the panel queries those tables directly, so a bare dependency
3152
+ * (e.g. reusing the package's pure webhook helpers) must not show a page that would then error.
3153
+ */
3083
3154
  payments: boolean;
3084
3155
  /** `@lunora/queue` / `ctx.queues` is used, the app declares queues, or it is a declared dependency. */
3085
3156
  queues: boolean;
@@ -3543,6 +3614,39 @@ declare const readFunctionMetricsTotals: (sql: SqlExec) => {
3543
3614
  errors: number;
3544
3615
  requests: number;
3545
3616
  };
3617
+ /** Default geohash precision (characters) maintained by a `.geoIndex()` companion — ~4.8 m cells. */
3618
+ declare const GEO_DEFAULT_PRECISION = 9;
3619
+ /** A latitude/longitude point (WGS84 decimal degrees). */
3620
+ interface GeoPoint {
3621
+ lat: number;
3622
+ lng: number;
3623
+ }
3624
+ /** An axis-aligned latitude/longitude bounding box (`sw`/`ne` corners). */
3625
+ interface GeoBoundingBox {
3626
+ ne: GeoPoint;
3627
+ sw: GeoPoint;
3628
+ }
3629
+ /**
3630
+ * Encode `point` to a geohash of `precision` characters. Standard interleaved
3631
+ * lat/lng bisection over the base-32 alphabet.
3632
+ */
3633
+ declare const encodeGeohash: (point: GeoPoint, precision: number) => string;
3634
+ /** Great-circle distance between two points in metres (Haversine). */
3635
+ declare const haversineMeters: (a: GeoPoint, b: GeoPoint) => number;
3636
+ /**
3637
+ * The center cell plus its eight neighbours at a precision chosen so each cell is
3638
+ * at least `radiusMeters` wide — the geohash prefixes to range-scan for a
3639
+ * proximity query. Deduplicated (near a pole neighbours can collapse).
3640
+ */
3641
+ declare const coveringGeohashes: (center: GeoPoint, radiusMeters: number) => string[];
3642
+ /** Whether `point` falls inside `box` (inclusive edges). */
3643
+ declare const pointInBoundingBox: (point: GeoPoint, box: GeoBoundingBox) => boolean;
3644
+ /**
3645
+ * Geohash prefixes covering `box`: the covering cells of the circle centered on
3646
+ * the box whose radius reaches the north-east corner, guaranteeing every point
3647
+ * in the box is scanned before the exact `pointInBoundingBox` refine.
3648
+ */
3649
+ declare const boundingBoxGeohashes: (box: GeoBoundingBox) => string[];
3546
3650
  /**
3547
3651
  * Severity of a `ctx.log.*` call. The five console method names (`log` is the
3548
3652
  * default level, distinct from `info`) plus `trace`/`fatal`, so the logger spans
@@ -4152,6 +4256,28 @@ declare class SessionDO {
4152
4256
  private handleGet;
4153
4257
  private handleRevoke;
4154
4258
  }
4259
+ /** One table's resolved TTL policy, as surfaced to the DO alarm by the generated shard subclass. */
4260
+ interface TtlSweepSpec {
4261
+ /** Millisecond offset added to `field` to derive the expiry (`field + after`); absent ⇒ `field` is the absolute expiry. */
4262
+ after?: number;
4263
+ /** The epoch-millisecond expiry column. */
4264
+ field: string;
4265
+ /** The `.softDelete()` marker column, when the table soft-deletes — expired-but-already-tombstoned rows are skipped. */
4266
+ softDeleteField?: string;
4267
+ /** The table whose expired rows are swept. */
4268
+ table: string;
4269
+ }
4270
+ /**
4271
+ * Select up to `limit` ids of rows in `spec.table` whose TTL expired at `now`
4272
+ * (i.e. `field + (after ?? 0) < now`). `hasMore` is `true` when matches remained
4273
+ * beyond `limit`, so the caller can loop a bounded batch. When `spec.softDeleteField`
4274
+ * is set, rows already soft-deleted (marker non-null) are excluded so the sweep
4275
+ * never re-touches a tombstone.
4276
+ */
4277
+ declare const selectExpiredIds: (sql: SqlExec, spec: TtlSweepSpec, now: number, limit: number) => {
4278
+ hasMore: boolean;
4279
+ ids: string[];
4280
+ };
4155
4281
  /**
4156
4282
  * Diff the previously-sent list snapshot (`previousJson`, the memo's
4157
4283
  * `lastJson`) against the new query result and produce per-row
@@ -5631,6 +5757,35 @@ declare abstract class ShardDO {
5631
5757
  * no-op when the runtime exposes no `setAlarm` (unit harness).
5632
5758
  */
5633
5759
  protected scheduleSourcePoll(): Promise<void>;
5760
+ /**
5761
+ * The resolved TTL policies (`.ttl(field, { after })`) for this DO's schema —
5762
+ * one {@link TtlSweepSpec} per table that declares a TTL. The base `ShardDO`
5763
+ * has no schema, so it returns `[]` and the TTL tier stays dormant. The
5764
+ * codegen subclass overrides it to read each table's `ttlPolicy` (+ its
5765
+ * `.softDelete()` marker) off the imported schema.
5766
+ */
5767
+ protected ttlSweeps(): ReadonlyArray<TtlSweepSpec>;
5768
+ /**
5769
+ * Sweep every `.ttl()` table once: page the rows past their expiry and remove
5770
+ * each THROUGH the schema-aware writer (`deleteRowThroughWriter`) so companions
5771
+ * / CDC / live subscriptions stay correct and a `.softDelete()` table soft-deletes
5772
+ * instead of physically removing the row. Work is bounded per tick
5773
+ * ({@link TTL_SWEEP_BATCH} × {@link TTL_SWEEP_MAX_BATCHES}) so a large backlog
5774
+ * drains across several alarms without stalling the shard.
5775
+ *
5776
+ * Returns the next-due timestamp (a coarse {@link TTL_SWEEP_INTERVAL_MS}
5777
+ * cadence, so freshly-written rows expire within a bounded window) while any
5778
+ * TTL table exists, or `undefined` when there are none — so a DO with no TTL
5779
+ * table never arms this tier.
5780
+ */
5781
+ protected pollTtlSweeps(): Promise<number | undefined>;
5782
+ /**
5783
+ * Arm the shared poll alarm for the TTL sweep. Mirrors {@link scheduleSourcePoll};
5784
+ * the codegen subclass calls it once on construction when the schema declares a
5785
+ * `.ttl()` table so the sweep loop starts, after which {@link ShardDO.alarm}
5786
+ * re-arms itself. Idempotent; a no-op when the runtime exposes no `setAlarm`.
5787
+ */
5788
+ protected scheduleTtlSweep(): Promise<void>;
5634
5789
  /** This DO's shard key (its DO name), or `__root__` for the single-DO default. The `tenantBy` mapper binds it into the source query. */
5635
5790
  protected currentShardKey(): string;
5636
5791
  /** Record a contained external-source ingest failure (one sourced table's poll) into the log ring without aborting the others. */
@@ -7083,4 +7238,4 @@ interface WhereSqlStrategy {
7083
7238
  * `undefined` when the input imposes no constraint (empty `where`).
7084
7239
  */
7085
7240
  declare const compileWhereSql: (where: WhereInput | undefined, strategy: WhereSqlStrategy) => SQL | undefined;
7086
- 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, 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 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 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, createMetrics, createShardCtxDb, createSystemReader, createTracer, decodeCursor, depKey, diffExternalSource, dispatchRootSpan, 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 };
7241
+ 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, boundingBoxGeohashes, buildFtsMatch, 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, ftsTableName, 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, scoreDocument, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, serveRelationFanout, softDeleteScope, sortColumnName, stableStringify, stableWireKey, stringifySearchText, subscriptionListDeltas, throwingScheduler, tokenizeSearch, trimCdcChanges, validateImportRow };