@lunora/do 1.0.0-alpha.55 → 1.0.0-alpha.57
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 +52 -2
- package/dist/index.d.ts +52 -2
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/ADMIN_FUNCTIONS-B0xlQJ4w.mjs +1 -0
- package/dist/packem_shared/NotUniqueError-CQaRCv1y.mjs +1 -0
- package/dist/packem_shared/{ROOT_DO_SIZE_WARN_BYTES-B7J9OycY.mjs → ROOT_DO_SIZE_WARN_BYTES-BEH-jSP0.mjs} +2 -2
- package/dist/packem_shared/backfillAggregateIndexes-BwW0684A.mjs +1 -0
- package/dist/packem_shared/ctx-db-backfill-Hl48Dr77.mjs +1 -0
- package/dist/packem_shared/runShardMigrations-DBSceD0H.mjs +5 -0
- package/dist/packem_shared/{serveRelationFanout-DBA2hP-k.mjs → serveRelationFanout-BqVyM54k.mjs} +1 -1
- package/package.json +2 -3
- package/dist/packem_shared/ADMIN_FUNCTIONS-BedcYTGD.mjs +0 -1
- package/dist/packem_shared/NotUniqueError-BwZ7vXA6.mjs +0 -1
- package/dist/packem_shared/backfillAggregateIndexes-DUrhkmiz.mjs +0 -1
- package/dist/packem_shared/ctx-db-backfill-C4rAzsQo.mjs +0 -1
- package/dist/packem_shared/runShardMigrations-DATbmCh8.mjs +0 -5
package/dist/index.d.mts
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import { LunoraError } from '@lunora/errors';
|
|
2
|
-
import '@lunora/search-core';
|
|
3
2
|
import { SQL } from 'drizzle-orm';
|
|
4
3
|
import { DrizzleSqliteDODatabase } from 'drizzle-orm/durable-sqlite';
|
|
5
4
|
/**
|
|
@@ -3235,6 +3234,7 @@ declare const ADMIN_FUNCTIONS: {
|
|
|
3235
3234
|
readonly exportShard: "__lunora_admin__:exportShard";
|
|
3236
3235
|
readonly facetColumn: "__lunora_admin__:facetColumn";
|
|
3237
3236
|
readonly getAdvisories: "__lunora_admin__:getAdvisories";
|
|
3237
|
+
readonly getAdvisorProcedures: "__lunora_admin__:getAdvisorProcedures";
|
|
3238
3238
|
readonly getAuditLog: "__lunora_admin__:getAuditLog";
|
|
3239
3239
|
readonly getAuthMetrics: "__lunora_admin__:getAuthMetrics";
|
|
3240
3240
|
readonly getCapturedMail: "__lunora_admin__:getCapturedMail";
|
|
@@ -3440,6 +3440,45 @@ interface AdvisoryFinding {
|
|
|
3440
3440
|
interface AdvisoriesResult {
|
|
3441
3441
|
advisories: AdvisoryFinding[];
|
|
3442
3442
|
}
|
|
3443
|
+
/**
|
|
3444
|
+
* One declared procedure, surfaced by `__lunora_admin__:getAdvisorProcedures`.
|
|
3445
|
+
*
|
|
3446
|
+
* Structurally mirrors `@lunora/advisor`'s `AdvisorProcedureProtection`, for the
|
|
3447
|
+
* same reason `AdvisoryFinding` mirrors `Finding`: the DO serves it without
|
|
3448
|
+
* depending on the advisor package. `@lunora/codegen` asserts the two are
|
|
3449
|
+
* assignable when it emits the list, so a field added there and forgotten here
|
|
3450
|
+
* fails codegen's own typecheck rather than the user's. This is the **denominator** the health map
|
|
3451
|
+
* needs — findings alone say what is wrong, but only the full procedure list
|
|
3452
|
+
* says how much is right, so without it a score cannot be computed at all.
|
|
3453
|
+
*/
|
|
3454
|
+
interface AdvisorProcedure {
|
|
3455
|
+
callsMail: boolean;
|
|
3456
|
+
emitsEvent?: boolean;
|
|
3457
|
+
exempt?: boolean;
|
|
3458
|
+
exemptReason?: string;
|
|
3459
|
+
exportName: string;
|
|
3460
|
+
fanOut: boolean;
|
|
3461
|
+
file: string;
|
|
3462
|
+
handlesErrors?: boolean;
|
|
3463
|
+
hasEmailArg?: boolean;
|
|
3464
|
+
kind: "action" | "mutation" | "query";
|
|
3465
|
+
reachesOutbound?: boolean;
|
|
3466
|
+
runsAiGeneration?: boolean;
|
|
3467
|
+
throwsBareError?: boolean;
|
|
3468
|
+
unboundedAiGeneration: boolean;
|
|
3469
|
+
usesCaptcha: boolean;
|
|
3470
|
+
usesEmailGate: boolean;
|
|
3471
|
+
usesInsertManyUnsafe: boolean;
|
|
3472
|
+
usesMask: boolean;
|
|
3473
|
+
usesRateLimit: boolean;
|
|
3474
|
+
usesRls: boolean;
|
|
3475
|
+
visibility: "internal" | "public";
|
|
3476
|
+
writesUserTable: boolean;
|
|
3477
|
+
}
|
|
3478
|
+
/** Payload of a `__lunora_admin__:getAdvisorProcedures` call: every declared procedure. */
|
|
3479
|
+
interface AdvisorProceduresResult {
|
|
3480
|
+
procedures: AdvisorProcedure[];
|
|
3481
|
+
}
|
|
3443
3482
|
/**
|
|
3444
3483
|
* One row-level-security policy entry, surfaced by `__lunora_admin__:rlsPolicies`
|
|
3445
3484
|
* to the studio's read-only RLS inspector. Mirrors `@lunora/codegen`'s
|
|
@@ -5854,6 +5893,17 @@ declare abstract class ShardDO {
|
|
|
5854
5893
|
* can't see the user's `schema.ts`, so it reports none.
|
|
5855
5894
|
*/
|
|
5856
5895
|
protected advisories(): AdvisoryFinding[];
|
|
5896
|
+
/**
|
|
5897
|
+
* Every declared procedure, surfaced via
|
|
5898
|
+
* `__lunora_admin__:getAdvisorProcedures`. Discovered by the codegen feeder
|
|
5899
|
+
* and emitted into the generated subclass, which overrides this.
|
|
5900
|
+
*
|
|
5901
|
+
* Separate from {@link advisories} because it is the denominator, not the
|
|
5902
|
+
* numerator: findings say what is wrong, this says how much exists to be
|
|
5903
|
+
* right, and the studio's health score needs both. The base class can't see
|
|
5904
|
+
* the user's functions, so it reports none.
|
|
5905
|
+
*/
|
|
5906
|
+
protected advisorProcedures(): AdvisorProcedure[];
|
|
5857
5907
|
/**
|
|
5858
5908
|
* Row-level-security metadata for this deployment, surfaced via
|
|
5859
5909
|
* `__lunora_admin__:rlsPolicies` to the studio's read-only RLS inspector:
|
|
@@ -8053,4 +8103,4 @@ interface WhereSqlStrategy {
|
|
|
8053
8103
|
* `undefined` when the input imposes no constraint (empty `where`).
|
|
8054
8104
|
*/
|
|
8055
8105
|
declare const compileWhereSql: (where: WhereInput | undefined, strategy: WhereSqlStrategy) => SQL | undefined;
|
|
8056
|
-
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 AiRunBinding, 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_EXPLAIN_ISSUE_MODEL, DEFAULT_MAX_RELATION_KEYS, type DataMigrationDocument, type DataMigrationLike, type DataMigrationTransform, type DatabaseWriterLike, type DependencyTracker, type DeployInfo, type ExplainIssueArgs, type ExplainIssueDegradedReason, type ExplainIssueGrounding, type ExplainIssueResult, type ExportRow, type ExportShardAdminArgs, type ExportShardArgs, type ExternalSourceDiffResult, type ExternalSourceLike, FLAGS_FUNCTION_PREFIX, FUNCTION_METRICS_BUCKETS_TABLE, FUNCTION_METRICS_BUCKET_MS, FUNCTION_METRICS_BUCKET_RETENTION, FUNCTION_METRICS_INDEX_TABLE, FUNCTION_METRICS_TABLE, type FacetColumnOptions, type FacetColumnResult, type FacetValue, type FieldOperators, type FlagEvaluation, type FlagsResult, type FunctionCallStat, type FunctionMetricBucket, type FunctionMetricIndexHit, type FunctionStatsResult, GEO_DEFAULT_PRECISION, type GeoBoundingBox, type GeoFilterBuilderLike, type GeoIndexDefinitionLike, type GeoPoint, type GroupByEntry, type GroupByOptions, type HibernatableWebSocket, type IdGenerator, type ImportError, type ImportShardAdminArgs, type ImportShardArgs, type ImportShardResult, type IncrementalMaterializeResult, type IndexDefinitionLike, type IndexRangeBuilderLike, LogBuffer, type LogEntry, type LogEventInput, type LogLevel, type LogSink, MAIL_RETENTION, MAIL_TABLE, MAX_SQL_ROWS, MIN_ADMIN_TOKEN_LENGTH, MIN_AUTH_SECRET_LENGTH, type MaskColumnMetadata, type MaskPoliciesResult, type MaterializeResult, type MetricsDeps, type MigrationDirection, type MigrationRunResult, type MigrationStatus, type MigrationStatusRow, type MutationDelta, type NestedWith, NotFoundError, NotUniqueError, type OnDeleteActionLike, type OrderByInput, type OrderKey, type PaginationOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type QueryArgs, type QueryPage, type QueueMetadata, type QueuesResult, RANK_TIEBREAK, RELATION_FUNCTION_PREFIX, RLS_UNWRAP_SYMBOL, ROOT_DO_SIZE_WARN_BYTES, ROOT_SHARD_NAME, type RankDirection, type RankIndexDefinitionLike, type RankOptions, type RankPage, type RankPageOptions, type RankPageRow, type RankPageRowKey, type RankResult, type RankSortKeyLike, ReactiveCache, type ReactiveCacheOptions, type ReadHook, type ReadTablePageOptions, type RecordAuthEventInput, type RecordFunctionMetricInput, type RecordMailInput, type RelationDefinitionLike, type RenderedSql, type ResolveRelationPredicatesOptions, type ResolveWithOptions, type RestrictableQueryOptions, type RlsPoliciesResult, type RlsPolicyMetadata, RlsRequiredError, type RlsRoleMetadata, type RpcRequest, type RunDataMigrationOptions, type RunShardApplyCdcArgs, type RunShardApplyCdcResult, type RunShardBulkDeleteArgs, type RunShardBulkDeleteResult, type RunShardExportArgs, type RunShardImportArgs, type RunShardMigrationArgs, type RunShardRankBeforeArgs, type RunShardRankPageArgs, type RunShardWriteArgs, type RunShardWriteResult, type RunTriggersOptions, SCAN_DEP, SESSION_DO_TTL_DEFAULT, SHARD_REGISTRY_DO_NAME, type SchedulableWorkflowReferenceLike, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type SearchFilterBuilderLike, type SearchIndexDefinitionLike, type SecurityAuditResult, type SecurityFinding, type SecurityFindingKind, type SecurityFindingLevel, type SelectMatchingIdsOptions, type ServerDefaultContextLike, SessionDO, type SessionRecord, type SettingEntry, type SettingKind, type SettingsResult, type ShapeSubscriptionQuery, ShardDO, type ShardDOOptions, type ShardDOState, type ShardRankPageResult, ShardRegistryDO, type SocketAttachment, type SortDirection, type SourceClientLike, type SourceCursorLike, type SourceRefresh, type SpanHandle, type SqlConsoleResult, type SqlCursor, type SqlEngine, type SqlExec, type StorageRuleMetadata, type StorageRulesResult, type StudioFeaturesResult, type SubscriptionEnvelope, type SubscriptionOutcome, type SubscriptionQuery, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemReaderOptions, type SystemReaderSchedulerLike, type SystemReaderStorageLike, type SystemTableName, type TableColumnsResult, type TableDefinitionLike, type TableIndexInfo, type TableIndexesResult, type TableInfo, type TablePage, type TableReaderLike, type TablesColumnsResult, type TelemetrySink, type TraceAnchor, type TracerDeps, type TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, type TtlSweepSpec, type ValidatorLike, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, aggregateSqlFunction, aggregateTableName, applyCdcChanges, applyOnDelete, applySelect, armRestore, assertFlatPredicate, assertReadonly, assertShapeShardable, assertValidClientId, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, boundingBoxGeohashes, buildSecurityAudit, buildSeekWhere, clearCapturedMail, coerceAggregateNumber, compileWhereSql, containsRelationPredicate, coveringGeohashes, createDependencyTracker, createMetrics, createShardCtxDb, createSystemReader, createTracer, decodeCursor, depKey, diffExternalSource, dispatchRootSpan, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, ensureAuthMetricsTables, ensureFunctionMetricsTables, ensureMailTable, explainIssue, exportShardRows, exportShardTable, facetColumn, fanOutScalarCounts, foldAggregateTally, guardWriter, hasTrigger, haversineMeters, importShardRows, isRelationPredicate, isSoftDeleted, isSourceDue, liftSourceId, listTables, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, mergeWhere, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, parseExplainIssueArgs, parseExportShardArgs, parseImportShardArgs, planAggregateLookup, pointInBoundingBox, pullExternalSourceIncrementalTick, pullExternalSourceTick, rankTableName, reactiveCacheKey, readAggregateValue, readAuthMetrics, readBookmark, readCapturedMail, readCdcChanges, readExternalSourceBaseline, readFunctionMetricBuckets, readFunctionMetricIndexHits, readFunctionMetrics, readFunctionMetricsTotals, readMigrationStatus, readTablePage, recordAuthEvent, recordCapturedMail, recordFunctionMetric, renderSql, resolveRankPartition, resolveRelationPredicates, resolveWith, runDataMigration, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, serveRelationFanout, softDeleteScope, sortColumnName, stableStringify, stableWireKey, subscriptionListDeltas, throwingScheduler, trimCdcChanges, validateImportRow };
|
|
8106
|
+
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 AdvisorProcedure, type AdvisorProceduresResult, type AdvisoriesResult, type AdvisoryFinding, type AggregateIndexDefinitionLike, type AggregateOp, type AggregateOptions, type AggregateResult, type AggregateTally, type AiRunBinding, 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_EXPLAIN_ISSUE_MODEL, DEFAULT_MAX_RELATION_KEYS, type DataMigrationDocument, type DataMigrationLike, type DataMigrationTransform, type DatabaseWriterLike, type DependencyTracker, type DeployInfo, type ExplainIssueArgs, type ExplainIssueDegradedReason, type ExplainIssueGrounding, type ExplainIssueResult, type ExportRow, type ExportShardAdminArgs, type ExportShardArgs, type ExternalSourceDiffResult, type ExternalSourceLike, FLAGS_FUNCTION_PREFIX, FUNCTION_METRICS_BUCKETS_TABLE, FUNCTION_METRICS_BUCKET_MS, FUNCTION_METRICS_BUCKET_RETENTION, FUNCTION_METRICS_INDEX_TABLE, FUNCTION_METRICS_TABLE, type FacetColumnOptions, type FacetColumnResult, type FacetValue, type FieldOperators, type FlagEvaluation, type FlagsResult, type FunctionCallStat, type FunctionMetricBucket, type FunctionMetricIndexHit, type FunctionStatsResult, GEO_DEFAULT_PRECISION, type GeoBoundingBox, type GeoFilterBuilderLike, type GeoIndexDefinitionLike, type GeoPoint, type GroupByEntry, type GroupByOptions, type HibernatableWebSocket, type IdGenerator, type ImportError, type ImportShardAdminArgs, type ImportShardArgs, type ImportShardResult, type IncrementalMaterializeResult, type IndexDefinitionLike, type IndexRangeBuilderLike, LogBuffer, type LogEntry, type LogEventInput, type LogLevel, type LogSink, MAIL_RETENTION, MAIL_TABLE, MAX_SQL_ROWS, MIN_ADMIN_TOKEN_LENGTH, MIN_AUTH_SECRET_LENGTH, type MaskColumnMetadata, type MaskPoliciesResult, type MaterializeResult, type MetricsDeps, type MigrationDirection, type MigrationRunResult, type MigrationStatus, type MigrationStatusRow, type MutationDelta, type NestedWith, NotFoundError, NotUniqueError, type OnDeleteActionLike, type OrderByInput, type OrderKey, type PaginationOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type QueryArgs, type QueryPage, type QueueMetadata, type QueuesResult, RANK_TIEBREAK, RELATION_FUNCTION_PREFIX, RLS_UNWRAP_SYMBOL, ROOT_DO_SIZE_WARN_BYTES, ROOT_SHARD_NAME, type RankDirection, type RankIndexDefinitionLike, type RankOptions, type RankPage, type RankPageOptions, type RankPageRow, type RankPageRowKey, type RankResult, type RankSortKeyLike, ReactiveCache, type ReactiveCacheOptions, type ReadHook, type ReadTablePageOptions, type RecordAuthEventInput, type RecordFunctionMetricInput, type RecordMailInput, type RelationDefinitionLike, type RenderedSql, type ResolveRelationPredicatesOptions, type ResolveWithOptions, type RestrictableQueryOptions, type RlsPoliciesResult, type RlsPolicyMetadata, RlsRequiredError, type RlsRoleMetadata, type RpcRequest, type RunDataMigrationOptions, type RunShardApplyCdcArgs, type RunShardApplyCdcResult, type RunShardBulkDeleteArgs, type RunShardBulkDeleteResult, type RunShardExportArgs, type RunShardImportArgs, type RunShardMigrationArgs, type RunShardRankBeforeArgs, type RunShardRankPageArgs, type RunShardWriteArgs, type RunShardWriteResult, type RunTriggersOptions, SCAN_DEP, SESSION_DO_TTL_DEFAULT, SHARD_REGISTRY_DO_NAME, type SchedulableWorkflowReferenceLike, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type SearchFilterBuilderLike, type SearchIndexDefinitionLike, type SecurityAuditResult, type SecurityFinding, type SecurityFindingKind, type SecurityFindingLevel, type SelectMatchingIdsOptions, type ServerDefaultContextLike, SessionDO, type SessionRecord, type SettingEntry, type SettingKind, type SettingsResult, type ShapeSubscriptionQuery, ShardDO, type ShardDOOptions, type ShardDOState, type ShardRankPageResult, ShardRegistryDO, type SocketAttachment, type SortDirection, type SourceClientLike, type SourceCursorLike, type SourceRefresh, type SpanHandle, type SqlConsoleResult, type SqlCursor, type SqlEngine, type SqlExec, type StorageRuleMetadata, type StorageRulesResult, type StudioFeaturesResult, type SubscriptionEnvelope, type SubscriptionOutcome, type SubscriptionQuery, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemReaderOptions, type SystemReaderSchedulerLike, type SystemReaderStorageLike, type SystemTableName, type TableColumnsResult, type TableDefinitionLike, type TableIndexInfo, type TableIndexesResult, type TableInfo, type TablePage, type TableReaderLike, type TablesColumnsResult, type TelemetrySink, type TraceAnchor, type TracerDeps, type TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, type TtlSweepSpec, type ValidatorLike, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, aggregateSqlFunction, aggregateTableName, applyCdcChanges, applyOnDelete, applySelect, armRestore, assertFlatPredicate, assertReadonly, assertShapeShardable, assertValidClientId, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, boundingBoxGeohashes, buildSecurityAudit, buildSeekWhere, clearCapturedMail, coerceAggregateNumber, compileWhereSql, containsRelationPredicate, coveringGeohashes, createDependencyTracker, createMetrics, createShardCtxDb, createSystemReader, createTracer, decodeCursor, depKey, diffExternalSource, dispatchRootSpan, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, ensureAuthMetricsTables, ensureFunctionMetricsTables, ensureMailTable, explainIssue, exportShardRows, exportShardTable, facetColumn, fanOutScalarCounts, foldAggregateTally, guardWriter, hasTrigger, haversineMeters, importShardRows, isRelationPredicate, isSoftDeleted, isSourceDue, liftSourceId, listTables, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, mergeWhere, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, parseExplainIssueArgs, parseExportShardArgs, parseImportShardArgs, planAggregateLookup, pointInBoundingBox, pullExternalSourceIncrementalTick, pullExternalSourceTick, rankTableName, reactiveCacheKey, readAggregateValue, readAuthMetrics, readBookmark, readCapturedMail, readCdcChanges, readExternalSourceBaseline, readFunctionMetricBuckets, readFunctionMetricIndexHits, readFunctionMetrics, readFunctionMetricsTotals, readMigrationStatus, readTablePage, recordAuthEvent, recordCapturedMail, recordFunctionMetric, renderSql, resolveRankPartition, resolveRelationPredicates, resolveWith, runDataMigration, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, serveRelationFanout, softDeleteScope, sortColumnName, stableStringify, stableWireKey, subscriptionListDeltas, throwingScheduler, trimCdcChanges, validateImportRow };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import { LunoraError } from '@lunora/errors';
|
|
2
|
-
import '@lunora/search-core';
|
|
3
2
|
import { SQL } from 'drizzle-orm';
|
|
4
3
|
import { DrizzleSqliteDODatabase } from 'drizzle-orm/durable-sqlite';
|
|
5
4
|
/**
|
|
@@ -3235,6 +3234,7 @@ declare const ADMIN_FUNCTIONS: {
|
|
|
3235
3234
|
readonly exportShard: "__lunora_admin__:exportShard";
|
|
3236
3235
|
readonly facetColumn: "__lunora_admin__:facetColumn";
|
|
3237
3236
|
readonly getAdvisories: "__lunora_admin__:getAdvisories";
|
|
3237
|
+
readonly getAdvisorProcedures: "__lunora_admin__:getAdvisorProcedures";
|
|
3238
3238
|
readonly getAuditLog: "__lunora_admin__:getAuditLog";
|
|
3239
3239
|
readonly getAuthMetrics: "__lunora_admin__:getAuthMetrics";
|
|
3240
3240
|
readonly getCapturedMail: "__lunora_admin__:getCapturedMail";
|
|
@@ -3440,6 +3440,45 @@ interface AdvisoryFinding {
|
|
|
3440
3440
|
interface AdvisoriesResult {
|
|
3441
3441
|
advisories: AdvisoryFinding[];
|
|
3442
3442
|
}
|
|
3443
|
+
/**
|
|
3444
|
+
* One declared procedure, surfaced by `__lunora_admin__:getAdvisorProcedures`.
|
|
3445
|
+
*
|
|
3446
|
+
* Structurally mirrors `@lunora/advisor`'s `AdvisorProcedureProtection`, for the
|
|
3447
|
+
* same reason `AdvisoryFinding` mirrors `Finding`: the DO serves it without
|
|
3448
|
+
* depending on the advisor package. `@lunora/codegen` asserts the two are
|
|
3449
|
+
* assignable when it emits the list, so a field added there and forgotten here
|
|
3450
|
+
* fails codegen's own typecheck rather than the user's. This is the **denominator** the health map
|
|
3451
|
+
* needs — findings alone say what is wrong, but only the full procedure list
|
|
3452
|
+
* says how much is right, so without it a score cannot be computed at all.
|
|
3453
|
+
*/
|
|
3454
|
+
interface AdvisorProcedure {
|
|
3455
|
+
callsMail: boolean;
|
|
3456
|
+
emitsEvent?: boolean;
|
|
3457
|
+
exempt?: boolean;
|
|
3458
|
+
exemptReason?: string;
|
|
3459
|
+
exportName: string;
|
|
3460
|
+
fanOut: boolean;
|
|
3461
|
+
file: string;
|
|
3462
|
+
handlesErrors?: boolean;
|
|
3463
|
+
hasEmailArg?: boolean;
|
|
3464
|
+
kind: "action" | "mutation" | "query";
|
|
3465
|
+
reachesOutbound?: boolean;
|
|
3466
|
+
runsAiGeneration?: boolean;
|
|
3467
|
+
throwsBareError?: boolean;
|
|
3468
|
+
unboundedAiGeneration: boolean;
|
|
3469
|
+
usesCaptcha: boolean;
|
|
3470
|
+
usesEmailGate: boolean;
|
|
3471
|
+
usesInsertManyUnsafe: boolean;
|
|
3472
|
+
usesMask: boolean;
|
|
3473
|
+
usesRateLimit: boolean;
|
|
3474
|
+
usesRls: boolean;
|
|
3475
|
+
visibility: "internal" | "public";
|
|
3476
|
+
writesUserTable: boolean;
|
|
3477
|
+
}
|
|
3478
|
+
/** Payload of a `__lunora_admin__:getAdvisorProcedures` call: every declared procedure. */
|
|
3479
|
+
interface AdvisorProceduresResult {
|
|
3480
|
+
procedures: AdvisorProcedure[];
|
|
3481
|
+
}
|
|
3443
3482
|
/**
|
|
3444
3483
|
* One row-level-security policy entry, surfaced by `__lunora_admin__:rlsPolicies`
|
|
3445
3484
|
* to the studio's read-only RLS inspector. Mirrors `@lunora/codegen`'s
|
|
@@ -5854,6 +5893,17 @@ declare abstract class ShardDO {
|
|
|
5854
5893
|
* can't see the user's `schema.ts`, so it reports none.
|
|
5855
5894
|
*/
|
|
5856
5895
|
protected advisories(): AdvisoryFinding[];
|
|
5896
|
+
/**
|
|
5897
|
+
* Every declared procedure, surfaced via
|
|
5898
|
+
* `__lunora_admin__:getAdvisorProcedures`. Discovered by the codegen feeder
|
|
5899
|
+
* and emitted into the generated subclass, which overrides this.
|
|
5900
|
+
*
|
|
5901
|
+
* Separate from {@link advisories} because it is the denominator, not the
|
|
5902
|
+
* numerator: findings say what is wrong, this says how much exists to be
|
|
5903
|
+
* right, and the studio's health score needs both. The base class can't see
|
|
5904
|
+
* the user's functions, so it reports none.
|
|
5905
|
+
*/
|
|
5906
|
+
protected advisorProcedures(): AdvisorProcedure[];
|
|
5857
5907
|
/**
|
|
5858
5908
|
* Row-level-security metadata for this deployment, surfaced via
|
|
5859
5909
|
* `__lunora_admin__:rlsPolicies` to the studio's read-only RLS inspector:
|
|
@@ -8053,4 +8103,4 @@ interface WhereSqlStrategy {
|
|
|
8053
8103
|
* `undefined` when the input imposes no constraint (empty `where`).
|
|
8054
8104
|
*/
|
|
8055
8105
|
declare const compileWhereSql: (where: WhereInput | undefined, strategy: WhereSqlStrategy) => SQL | undefined;
|
|
8056
|
-
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 AiRunBinding, 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_EXPLAIN_ISSUE_MODEL, DEFAULT_MAX_RELATION_KEYS, type DataMigrationDocument, type DataMigrationLike, type DataMigrationTransform, type DatabaseWriterLike, type DependencyTracker, type DeployInfo, type ExplainIssueArgs, type ExplainIssueDegradedReason, type ExplainIssueGrounding, type ExplainIssueResult, type ExportRow, type ExportShardAdminArgs, type ExportShardArgs, type ExternalSourceDiffResult, type ExternalSourceLike, FLAGS_FUNCTION_PREFIX, FUNCTION_METRICS_BUCKETS_TABLE, FUNCTION_METRICS_BUCKET_MS, FUNCTION_METRICS_BUCKET_RETENTION, FUNCTION_METRICS_INDEX_TABLE, FUNCTION_METRICS_TABLE, type FacetColumnOptions, type FacetColumnResult, type FacetValue, type FieldOperators, type FlagEvaluation, type FlagsResult, type FunctionCallStat, type FunctionMetricBucket, type FunctionMetricIndexHit, type FunctionStatsResult, GEO_DEFAULT_PRECISION, type GeoBoundingBox, type GeoFilterBuilderLike, type GeoIndexDefinitionLike, type GeoPoint, type GroupByEntry, type GroupByOptions, type HibernatableWebSocket, type IdGenerator, type ImportError, type ImportShardAdminArgs, type ImportShardArgs, type ImportShardResult, type IncrementalMaterializeResult, type IndexDefinitionLike, type IndexRangeBuilderLike, LogBuffer, type LogEntry, type LogEventInput, type LogLevel, type LogSink, MAIL_RETENTION, MAIL_TABLE, MAX_SQL_ROWS, MIN_ADMIN_TOKEN_LENGTH, MIN_AUTH_SECRET_LENGTH, type MaskColumnMetadata, type MaskPoliciesResult, type MaterializeResult, type MetricsDeps, type MigrationDirection, type MigrationRunResult, type MigrationStatus, type MigrationStatusRow, type MutationDelta, type NestedWith, NotFoundError, NotUniqueError, type OnDeleteActionLike, type OrderByInput, type OrderKey, type PaginationOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type QueryArgs, type QueryPage, type QueueMetadata, type QueuesResult, RANK_TIEBREAK, RELATION_FUNCTION_PREFIX, RLS_UNWRAP_SYMBOL, ROOT_DO_SIZE_WARN_BYTES, ROOT_SHARD_NAME, type RankDirection, type RankIndexDefinitionLike, type RankOptions, type RankPage, type RankPageOptions, type RankPageRow, type RankPageRowKey, type RankResult, type RankSortKeyLike, ReactiveCache, type ReactiveCacheOptions, type ReadHook, type ReadTablePageOptions, type RecordAuthEventInput, type RecordFunctionMetricInput, type RecordMailInput, type RelationDefinitionLike, type RenderedSql, type ResolveRelationPredicatesOptions, type ResolveWithOptions, type RestrictableQueryOptions, type RlsPoliciesResult, type RlsPolicyMetadata, RlsRequiredError, type RlsRoleMetadata, type RpcRequest, type RunDataMigrationOptions, type RunShardApplyCdcArgs, type RunShardApplyCdcResult, type RunShardBulkDeleteArgs, type RunShardBulkDeleteResult, type RunShardExportArgs, type RunShardImportArgs, type RunShardMigrationArgs, type RunShardRankBeforeArgs, type RunShardRankPageArgs, type RunShardWriteArgs, type RunShardWriteResult, type RunTriggersOptions, SCAN_DEP, SESSION_DO_TTL_DEFAULT, SHARD_REGISTRY_DO_NAME, type SchedulableWorkflowReferenceLike, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type SearchFilterBuilderLike, type SearchIndexDefinitionLike, type SecurityAuditResult, type SecurityFinding, type SecurityFindingKind, type SecurityFindingLevel, type SelectMatchingIdsOptions, type ServerDefaultContextLike, SessionDO, type SessionRecord, type SettingEntry, type SettingKind, type SettingsResult, type ShapeSubscriptionQuery, ShardDO, type ShardDOOptions, type ShardDOState, type ShardRankPageResult, ShardRegistryDO, type SocketAttachment, type SortDirection, type SourceClientLike, type SourceCursorLike, type SourceRefresh, type SpanHandle, type SqlConsoleResult, type SqlCursor, type SqlEngine, type SqlExec, type StorageRuleMetadata, type StorageRulesResult, type StudioFeaturesResult, type SubscriptionEnvelope, type SubscriptionOutcome, type SubscriptionQuery, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemReaderOptions, type SystemReaderSchedulerLike, type SystemReaderStorageLike, type SystemTableName, type TableColumnsResult, type TableDefinitionLike, type TableIndexInfo, type TableIndexesResult, type TableInfo, type TablePage, type TableReaderLike, type TablesColumnsResult, type TelemetrySink, type TraceAnchor, type TracerDeps, type TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, type TtlSweepSpec, type ValidatorLike, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, aggregateSqlFunction, aggregateTableName, applyCdcChanges, applyOnDelete, applySelect, armRestore, assertFlatPredicate, assertReadonly, assertShapeShardable, assertValidClientId, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, boundingBoxGeohashes, buildSecurityAudit, buildSeekWhere, clearCapturedMail, coerceAggregateNumber, compileWhereSql, containsRelationPredicate, coveringGeohashes, createDependencyTracker, createMetrics, createShardCtxDb, createSystemReader, createTracer, decodeCursor, depKey, diffExternalSource, dispatchRootSpan, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, ensureAuthMetricsTables, ensureFunctionMetricsTables, ensureMailTable, explainIssue, exportShardRows, exportShardTable, facetColumn, fanOutScalarCounts, foldAggregateTally, guardWriter, hasTrigger, haversineMeters, importShardRows, isRelationPredicate, isSoftDeleted, isSourceDue, liftSourceId, listTables, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, mergeWhere, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, parseExplainIssueArgs, parseExportShardArgs, parseImportShardArgs, planAggregateLookup, pointInBoundingBox, pullExternalSourceIncrementalTick, pullExternalSourceTick, rankTableName, reactiveCacheKey, readAggregateValue, readAuthMetrics, readBookmark, readCapturedMail, readCdcChanges, readExternalSourceBaseline, readFunctionMetricBuckets, readFunctionMetricIndexHits, readFunctionMetrics, readFunctionMetricsTotals, readMigrationStatus, readTablePage, recordAuthEvent, recordCapturedMail, recordFunctionMetric, renderSql, resolveRankPartition, resolveRelationPredicates, resolveWith, runDataMigration, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, serveRelationFanout, softDeleteScope, sortColumnName, stableStringify, stableWireKey, subscriptionListDeltas, throwingScheduler, trimCdcChanges, validateImportRow };
|
|
8106
|
+
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 AdvisorProcedure, type AdvisorProceduresResult, type AdvisoriesResult, type AdvisoryFinding, type AggregateIndexDefinitionLike, type AggregateOp, type AggregateOptions, type AggregateResult, type AggregateTally, type AiRunBinding, 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_EXPLAIN_ISSUE_MODEL, DEFAULT_MAX_RELATION_KEYS, type DataMigrationDocument, type DataMigrationLike, type DataMigrationTransform, type DatabaseWriterLike, type DependencyTracker, type DeployInfo, type ExplainIssueArgs, type ExplainIssueDegradedReason, type ExplainIssueGrounding, type ExplainIssueResult, type ExportRow, type ExportShardAdminArgs, type ExportShardArgs, type ExternalSourceDiffResult, type ExternalSourceLike, FLAGS_FUNCTION_PREFIX, FUNCTION_METRICS_BUCKETS_TABLE, FUNCTION_METRICS_BUCKET_MS, FUNCTION_METRICS_BUCKET_RETENTION, FUNCTION_METRICS_INDEX_TABLE, FUNCTION_METRICS_TABLE, type FacetColumnOptions, type FacetColumnResult, type FacetValue, type FieldOperators, type FlagEvaluation, type FlagsResult, type FunctionCallStat, type FunctionMetricBucket, type FunctionMetricIndexHit, type FunctionStatsResult, GEO_DEFAULT_PRECISION, type GeoBoundingBox, type GeoFilterBuilderLike, type GeoIndexDefinitionLike, type GeoPoint, type GroupByEntry, type GroupByOptions, type HibernatableWebSocket, type IdGenerator, type ImportError, type ImportShardAdminArgs, type ImportShardArgs, type ImportShardResult, type IncrementalMaterializeResult, type IndexDefinitionLike, type IndexRangeBuilderLike, LogBuffer, type LogEntry, type LogEventInput, type LogLevel, type LogSink, MAIL_RETENTION, MAIL_TABLE, MAX_SQL_ROWS, MIN_ADMIN_TOKEN_LENGTH, MIN_AUTH_SECRET_LENGTH, type MaskColumnMetadata, type MaskPoliciesResult, type MaterializeResult, type MetricsDeps, type MigrationDirection, type MigrationRunResult, type MigrationStatus, type MigrationStatusRow, type MutationDelta, type NestedWith, NotFoundError, NotUniqueError, type OnDeleteActionLike, type OrderByInput, type OrderKey, type PaginationOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type QueryArgs, type QueryPage, type QueueMetadata, type QueuesResult, RANK_TIEBREAK, RELATION_FUNCTION_PREFIX, RLS_UNWRAP_SYMBOL, ROOT_DO_SIZE_WARN_BYTES, ROOT_SHARD_NAME, type RankDirection, type RankIndexDefinitionLike, type RankOptions, type RankPage, type RankPageOptions, type RankPageRow, type RankPageRowKey, type RankResult, type RankSortKeyLike, ReactiveCache, type ReactiveCacheOptions, type ReadHook, type ReadTablePageOptions, type RecordAuthEventInput, type RecordFunctionMetricInput, type RecordMailInput, type RelationDefinitionLike, type RenderedSql, type ResolveRelationPredicatesOptions, type ResolveWithOptions, type RestrictableQueryOptions, type RlsPoliciesResult, type RlsPolicyMetadata, RlsRequiredError, type RlsRoleMetadata, type RpcRequest, type RunDataMigrationOptions, type RunShardApplyCdcArgs, type RunShardApplyCdcResult, type RunShardBulkDeleteArgs, type RunShardBulkDeleteResult, type RunShardExportArgs, type RunShardImportArgs, type RunShardMigrationArgs, type RunShardRankBeforeArgs, type RunShardRankPageArgs, type RunShardWriteArgs, type RunShardWriteResult, type RunTriggersOptions, SCAN_DEP, SESSION_DO_TTL_DEFAULT, SHARD_REGISTRY_DO_NAME, type SchedulableWorkflowReferenceLike, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type SearchFilterBuilderLike, type SearchIndexDefinitionLike, type SecurityAuditResult, type SecurityFinding, type SecurityFindingKind, type SecurityFindingLevel, type SelectMatchingIdsOptions, type ServerDefaultContextLike, SessionDO, type SessionRecord, type SettingEntry, type SettingKind, type SettingsResult, type ShapeSubscriptionQuery, ShardDO, type ShardDOOptions, type ShardDOState, type ShardRankPageResult, ShardRegistryDO, type SocketAttachment, type SortDirection, type SourceClientLike, type SourceCursorLike, type SourceRefresh, type SpanHandle, type SqlConsoleResult, type SqlCursor, type SqlEngine, type SqlExec, type StorageRuleMetadata, type StorageRulesResult, type StudioFeaturesResult, type SubscriptionEnvelope, type SubscriptionOutcome, type SubscriptionQuery, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemReaderOptions, type SystemReaderSchedulerLike, type SystemReaderStorageLike, type SystemTableName, type TableColumnsResult, type TableDefinitionLike, type TableIndexInfo, type TableIndexesResult, type TableInfo, type TablePage, type TableReaderLike, type TablesColumnsResult, type TelemetrySink, type TraceAnchor, type TracerDeps, type TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, type TtlSweepSpec, type ValidatorLike, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, aggregateSqlFunction, aggregateTableName, applyCdcChanges, applyOnDelete, applySelect, armRestore, assertFlatPredicate, assertReadonly, assertShapeShardable, assertValidClientId, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, boundingBoxGeohashes, buildSecurityAudit, buildSeekWhere, clearCapturedMail, coerceAggregateNumber, compileWhereSql, containsRelationPredicate, coveringGeohashes, createDependencyTracker, createMetrics, createShardCtxDb, createSystemReader, createTracer, decodeCursor, depKey, diffExternalSource, dispatchRootSpan, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, ensureAuthMetricsTables, ensureFunctionMetricsTables, ensureMailTable, explainIssue, exportShardRows, exportShardTable, facetColumn, fanOutScalarCounts, foldAggregateTally, guardWriter, hasTrigger, haversineMeters, importShardRows, isRelationPredicate, isSoftDeleted, isSourceDue, liftSourceId, listTables, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, mergeWhere, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, parseExplainIssueArgs, parseExportShardArgs, parseImportShardArgs, planAggregateLookup, pointInBoundingBox, pullExternalSourceIncrementalTick, pullExternalSourceTick, rankTableName, reactiveCacheKey, readAggregateValue, readAuthMetrics, readBookmark, readCapturedMail, readCdcChanges, readExternalSourceBaseline, readFunctionMetricBuckets, readFunctionMetricIndexHits, readFunctionMetrics, readFunctionMetricsTotals, readMigrationStatus, readTablePage, recordAuthEvent, recordCapturedMail, recordFunctionMetric, renderSql, resolveRankPartition, resolveRelationPredicates, resolveWith, runDataMigration, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, serveRelationFanout, softDeleteScope, sortColumnName, stableStringify, stableWireKey, subscriptionListDeltas, throwingScheduler, trimCdcChanges, validateImportRow };
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{exportShardRows as o,exportShardTable as t,importShardRows as a,parseExportShardArgs as s,parseImportShardArgs as n,selectExportTables as i,validateImportRow as l}from"./packem_shared/exportShardRows-kt42wijd.mjs";import{AGGREGATE_SQL_FUNCTION as T,aggregateSqlFunction as p,matchesStaticWhere as d,normalizeCountArgument as E,throwingScheduler as _}from"./packem_shared/AGGREGATE_SQL_FUNCTION-QYaiuty4.mjs";import{aggregateTableName as m,coerceAggregateNumber as u,encodeAggregateKey as x,foldAggregateTally as I,readAggregateValue as f}from"./packem_shared/aggregateTableName-G-eXyjcz.mjs";import{CountRlsUnsupportedError as R,mergeWhere as N,planAggregateLookup as g,selectIndexForAggregate as C,selectIndexForCount as M,selectIndexForGroupBy as h}from"./packem_shared/CountRlsUnsupportedError-Cl8XpYDL.mjs";import{AUTH_METRICS_BUCKETS_TABLE as F,AUTH_METRICS_BUCKET_MS as L,AUTH_METRICS_BUCKET_RETENTION as U,AUTH_METRICS_TABLE as D,ensureAuthMetricsTables as B,readAuthMetrics as b,recordAuthEvent as y}from"./packem_shared/AUTH_METRICS_BUCKETS_TABLE-D0wNaez7.mjs";import{c as K,a as P,d as G}from"./packem_shared/context-telemetry-BFO0N_e4.mjs";import{NotUniqueError as W,assertValidClientId as v,createShardCtxDb as X,normalizeIdStructurally as w}from"./packem_shared/NotUniqueError-
|
|
1
|
+
import{exportShardRows as o,exportShardTable as t,importShardRows as a,parseExportShardArgs as s,parseImportShardArgs as n,selectExportTables as i,validateImportRow as l}from"./packem_shared/exportShardRows-kt42wijd.mjs";import{AGGREGATE_SQL_FUNCTION as T,aggregateSqlFunction as p,matchesStaticWhere as d,normalizeCountArgument as E,throwingScheduler as _}from"./packem_shared/AGGREGATE_SQL_FUNCTION-QYaiuty4.mjs";import{aggregateTableName as m,coerceAggregateNumber as u,encodeAggregateKey as x,foldAggregateTally as I,readAggregateValue as f}from"./packem_shared/aggregateTableName-G-eXyjcz.mjs";import{CountRlsUnsupportedError as R,mergeWhere as N,planAggregateLookup as g,selectIndexForAggregate as C,selectIndexForCount as M,selectIndexForGroupBy as h}from"./packem_shared/CountRlsUnsupportedError-Cl8XpYDL.mjs";import{AUTH_METRICS_BUCKETS_TABLE as F,AUTH_METRICS_BUCKET_MS as L,AUTH_METRICS_BUCKET_RETENTION as U,AUTH_METRICS_TABLE as D,ensureAuthMetricsTables as B,readAuthMetrics as b,recordAuthEvent as y}from"./packem_shared/AUTH_METRICS_BUCKETS_TABLE-D0wNaez7.mjs";import{c as K,a as P,d as G}from"./packem_shared/context-telemetry-BFO0N_e4.mjs";import{NotUniqueError as W,assertValidClientId as v,createShardCtxDb as X,normalizeIdStructurally as w}from"./packem_shared/NotUniqueError-CQaRCv1y.mjs";import{DATA_MIGRATION_STATE_TABLE as z,readMigrationStatus as Y,runDataMigration as V}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-CaO6L0Ee.mjs";import{SCAN_DEP as Z,createDependencyTracker as j,depKey as J}from"./packem_shared/SCAN_DEP-D_yR9EeV.mjs";import{renderSql as ee}from"./packem_shared/renderSql-B5lF5Jd9.mjs";import{diffExternalSource as oe}from"./packem_shared/diffExternalSource-DMpkJta1.mjs";import{materializeExternalRows as ae,materializeExternalRowsIncremental as se,readExternalSourceBaseline as ne,runExternalSourceTick as ie}from"./packem_shared/materializeExternalRows-BUmj_9WO.mjs";import{isSoftDeleted as ce,isSourceDue as Te,liftSourceId as pe,pullExternalSourceIncrementalTick as de,pullExternalSourceTick as Ee}from"./packem_shared/isSoftDeleted-juJOq515.mjs";import{FUNCTION_METRICS_BUCKETS_TABLE as Se,FUNCTION_METRICS_BUCKET_MS as me,FUNCTION_METRICS_BUCKET_RETENTION as ue,FUNCTION_METRICS_INDEX_TABLE as xe,FUNCTION_METRICS_TABLE as Ie,ensureFunctionMetricsTables as fe,readFunctionMetricBuckets as Ae,readFunctionMetricIndexHits as Re,readFunctionMetrics as Ne,readFunctionMetricsTotals as ge,recordFunctionMetric as Ce}from"./packem_shared/FUNCTION_METRICS_BUCKETS_TABLE-BPPeqM11.mjs";import{GEO_DEFAULT_PRECISION as he,boundingBoxGeohashes as Oe,coveringGeohashes as Fe,encodeGeohash as Le,haversineMeters as Ue,pointInBoundingBox as De}from"./packem_shared/GEO_DEFAULT_PRECISION-okRCkZ6r.mjs";import{ADMIN_FUNCTIONS as be,ADMIN_FUNCTION_PREFIX as ye,FLAGS_FUNCTION_PREFIX as ke,RELATION_FUNCTION_PREFIX as Ke,facetColumn as Pe,listTables as Ge,readTablePage as He,selectMatchingIds as We}from"./packem_shared/ADMIN_FUNCTIONS-B0xlQJ4w.mjs";import{DEFAULT_EXPLAIN_ISSUE_MODEL as Xe,explainIssue as we,parseExplainIssueArgs as qe}from"./packem_shared/DEFAULT_EXPLAIN_ISSUE_MODEL-Dicm4iLF.mjs";import{LogBuffer as Ye}from"./packem_shared/LogBuffer-bIvCelI-.mjs";import{MAIL_RETENTION as Qe,MAIL_TABLE as Ze,clearCapturedMail as je,ensureMailTable as Je,readCapturedMail as $e,recordCapturedMail as er}from"./packem_shared/MAIL_RETENTION-KmozO2NQ.mjs";import{default as or}from"./packem_shared/NotFoundError-J3tjf4Uo.mjs";import{armRestore as ar,readBookmark as sr}from"./packem_shared/armRestore-BNzdvQ_o.mjs";import{applySelect as ir,buildSeekWhere as lr,decodeCursor as cr,encodeCursor as Tr,normalizeOrderKeys as pr,softDeleteScope as dr}from"./packem_shared/applySelect-B0CF8T7y.mjs";import{RANK_TIEBREAK as _r,encodePartitionKey as Sr,matchesRankStaticWhere as mr,rankTableName as ur,resolveRankPartition as xr,sortColumnName as Ir}from"./packem_shared/RANK_TIEBREAK-DtX8zQyc.mjs";import{ReactiveCache as Ar,reactiveCacheKey as Rr}from"./packem_shared/ReactiveCache-1_9Rs7J_.mjs";import{serveRelationFanout as gr}from"./packem_shared/serveRelationFanout-BqVyM54k.mjs";import{DEFAULT_MAX_RELATION_KEYS as Mr,assertFlatPredicate as hr,assertShapeShardable as Or,containsRelationPredicate as Fr,isRelationPredicate as Lr,resolveRelationPredicates as Ur}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-VxD8RtL0.mjs";import{applyOnDelete as Br,fanOutScalarCounts as br,resolveWith as yr,runRowValidators as kr}from"./packem_shared/applyOnDelete-DCeU2Jh0.mjs";import{RLS_UNWRAP_SYMBOL as Pr,RlsRequiredError as Gr,guardWriter as Hr}from"./packem_shared/RLS_UNWRAP_SYMBOL-C6_WX3dG.mjs";import{o as vr,c as Xr,_ as wr}from"./packem_shared/security-audit-BKUOgE0x.mjs";import{SESSION_DO_TTL_DEFAULT as zr,SessionDO as Yr}from"./packem_shared/SESSION_DO_TTL_DEFAULT-GvBy_DBz.mjs";import{ROOT_DO_SIZE_WARN_BYTES as Qr,ROOT_SHARD_NAME as Zr,ShardDO as jr}from"./packem_shared/ROOT_DO_SIZE_WARN_BYTES-BEH-jSP0.mjs";import{SHARD_REGISTRY_DO_NAME as $r,ShardRegistryDO as eo}from"./packem_shared/SHARD_REGISTRY_DO_NAME-Caa0fR4N.mjs";import{a as oo,u as to,d as ao}from"./packem_shared/sql-console-Cln4Xfju.mjs";import{createSystemReader as no}from"./packem_shared/createSystemReader-DcDcrtM3.mjs";import{ConflictError as lo}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{hasTrigger as To,runTriggers as po}from"./packem_shared/hasTrigger-_rexbWMO.mjs";import{selectExpiredIds as _o}from"./packem_shared/selectExpiredIds-BXJDiUtz.mjs";import{compileWhereSql as mo}from"./packem_shared/compileWhereSql-BLcfs4QW.mjs";import{CDC_LOG_TABLE as xo,applyCdcChanges as Io,readCdcChanges as fo,trimCdcChanges as Ao}from"./packem_shared/CDC_LOG_TABLE-E_J5LPoK.mjs";import{H as No,P as go,X as Co}from"./packem_shared/ctx-db-backfill-Hl48Dr77.mjs";import{runShardMigrations as ho}from"./packem_shared/runShardMigrations-DBSceD0H.mjs";import{stableStringify as Fo}from"./packem_shared/stableStringify-BjLh4gvA.mjs";import{stableWireKey as Uo}from"./packem_shared/stableWireKey-YEHLaX6X.mjs";import{subscriptionListDeltas as Bo}from"./packem_shared/subscriptionListDeltas-Bs69JbA8.mjs";export{be as ADMIN_FUNCTIONS,ye as ADMIN_FUNCTION_PREFIX,T as AGGREGATE_SQL_FUNCTION,F as AUTH_METRICS_BUCKETS_TABLE,L as AUTH_METRICS_BUCKET_MS,U as AUTH_METRICS_BUCKET_RETENTION,D as AUTH_METRICS_TABLE,xo as CDC_LOG_TABLE,lo as ConflictError,R as CountRlsUnsupportedError,z as DATA_MIGRATION_STATE_TABLE,Xe as DEFAULT_EXPLAIN_ISSUE_MODEL,Mr as DEFAULT_MAX_RELATION_KEYS,ke as FLAGS_FUNCTION_PREFIX,Se as FUNCTION_METRICS_BUCKETS_TABLE,me as FUNCTION_METRICS_BUCKET_MS,ue as FUNCTION_METRICS_BUCKET_RETENTION,xe as FUNCTION_METRICS_INDEX_TABLE,Ie as FUNCTION_METRICS_TABLE,he as GEO_DEFAULT_PRECISION,Ye as LogBuffer,Qe as MAIL_RETENTION,Ze as MAIL_TABLE,oo as MAX_SQL_ROWS,vr as MIN_ADMIN_TOKEN_LENGTH,Xr as MIN_AUTH_SECRET_LENGTH,or as NotFoundError,W as NotUniqueError,_r as RANK_TIEBREAK,Ke as RELATION_FUNCTION_PREFIX,Pr as RLS_UNWRAP_SYMBOL,Qr as ROOT_DO_SIZE_WARN_BYTES,Zr as ROOT_SHARD_NAME,Ar as ReactiveCache,Gr as RlsRequiredError,Z as SCAN_DEP,zr as SESSION_DO_TTL_DEFAULT,$r as SHARD_REGISTRY_DO_NAME,Yr as SessionDO,jr as ShardDO,eo as ShardRegistryDO,p as aggregateSqlFunction,m as aggregateTableName,Io as applyCdcChanges,Br as applyOnDelete,ir as applySelect,ar as armRestore,hr as assertFlatPredicate,to as assertReadonly,Or as assertShapeShardable,v as assertValidClientId,No as backfillAggregateIndexes,go as backfillRankIndexes,Co as backfillSearchIndexes,Oe as boundingBoxGeohashes,wr as buildSecurityAudit,lr as buildSeekWhere,je as clearCapturedMail,u as coerceAggregateNumber,mo as compileWhereSql,Fr as containsRelationPredicate,Fe as coveringGeohashes,j as createDependencyTracker,K as createMetrics,X as createShardCtxDb,no as createSystemReader,P as createTracer,cr as decodeCursor,J as depKey,oe as diffExternalSource,G as dispatchRootSpan,x as encodeAggregateKey,Tr as encodeCursor,Le as encodeGeohash,Sr as encodePartitionKey,B as ensureAuthMetricsTables,fe as ensureFunctionMetricsTables,Je as ensureMailTable,we as explainIssue,o as exportShardRows,t as exportShardTable,Pe as facetColumn,br as fanOutScalarCounts,I as foldAggregateTally,Hr as guardWriter,To as hasTrigger,Ue as haversineMeters,a as importShardRows,Lr as isRelationPredicate,ce as isSoftDeleted,Te as isSourceDue,pe as liftSourceId,Ge as listTables,mr as matchesRankStaticWhere,d as matchesStaticWhere,ae as materializeExternalRows,se as materializeExternalRowsIncremental,N as mergeWhere,E as normalizeCountArgument,w as normalizeIdStructurally,pr as normalizeOrderKeys,qe as parseExplainIssueArgs,s as parseExportShardArgs,n as parseImportShardArgs,g as planAggregateLookup,De as pointInBoundingBox,de as pullExternalSourceIncrementalTick,Ee as pullExternalSourceTick,ur as rankTableName,Rr as reactiveCacheKey,f as readAggregateValue,b as readAuthMetrics,sr as readBookmark,$e as readCapturedMail,fo as readCdcChanges,ne as readExternalSourceBaseline,Ae as readFunctionMetricBuckets,Re as readFunctionMetricIndexHits,Ne as readFunctionMetrics,ge as readFunctionMetricsTotals,Y as readMigrationStatus,He as readTablePage,y as recordAuthEvent,er as recordCapturedMail,Ce as recordFunctionMetric,ee as renderSql,xr as resolveRankPartition,Ur as resolveRelationPredicates,yr as resolveWith,V as runDataMigration,ie as runExternalSourceTick,ao as runReadonlySql,kr as runRowValidators,ho as runShardMigrations,po as runTriggers,_o as selectExpiredIds,i as selectExportTables,C as selectIndexForAggregate,M as selectIndexForCount,h as selectIndexForGroupBy,We as selectMatchingIds,gr as serveRelationFanout,dr as softDeleteScope,Ir as sortColumnName,Fo as stableStringify,Uo as stableWireKey,Bo as subscriptionListDeltas,_ as throwingScheduler,Ao as trimCdcChanges,l as validateImportRow};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as M}from"@lunora/errors";import{q as d}from"./quote-identifier-CGiYFBvY.mjs";const K="__lunora_admin__:",X="__lunora_relation__:",Y="__lunora_flags__:",z={applyCdc:"__lunora_admin__:applyCdc",aiAvailable:"__lunora_admin__:aiAvailable",aiChartConfig:"__lunora_admin__:aiChartConfig",aiGenerateSql:"__lunora_admin__:aiGenerateSql",aiTableFilter:"__lunora_admin__:aiTableFilter",assignIssue:"__lunora_admin__:assignIssue",backRelationCounts:"__lunora_admin__:backRelationCounts",cdcSync:"__lunora_admin__:cdcSync",clearCapturedMail:"__lunora_admin__:clearCapturedMail",clearQueueMessages:"__lunora_admin__:clearQueueMessages",clearTable:"__lunora_admin__:clearTable",createWorkflowInstance:"__lunora_admin__:createWorkflowInstance",deleteRows:"__lunora_admin__:deleteRows",describeTable:"__lunora_admin__:describeTable",describeTables:"__lunora_admin__:describeTables",explainIssue:"__lunora_admin__:explainIssue",exportShard:"__lunora_admin__:exportShard",facetColumn:"__lunora_admin__:facetColumn",getAdvisories:"__lunora_admin__:getAdvisories",getAdvisorProcedures:"__lunora_admin__:getAdvisorProcedures",getAuditLog:"__lunora_admin__:getAuditLog",getAuthMetrics:"__lunora_admin__:getAuthMetrics",getCapturedMail:"__lunora_admin__:getCapturedMail",getFanoutMetrics:"__lunora_admin__:getFanoutMetrics",getFunctionStats:"__lunora_admin__:getFunctionStats",getIssues:"__lunora_admin__:getIssues",getMetricHistory:"__lunora_admin__:getMetricHistory",getMetricSeries:"__lunora_admin__:getMetricSeries",listSubscriptions:"__lunora_admin__:listSubscriptions",listTableIndexes:"__lunora_admin__:listTableIndexes",getLogs:"__lunora_admin__:getLogs",getMetrics:"__lunora_admin__:getMetrics",getPitrBookmark:"__lunora_admin__:getPitrBookmark",getQueryInsights:"__lunora_admin__:getQueryInsights",getQueueMessages:"__lunora_admin__:getQueueMessages",getRequestLog:"__lunora_admin__:getRequestLog",getSecurityAudit:"__lunora_admin__:getSecurityAudit",getSettings:"__lunora_admin__:getSettings",getTraces:"__lunora_admin__:getTraces",getWorkflowInstanceStatus:"__lunora_admin__:getWorkflowInstanceStatus",ignoreIssue:"__lunora_admin__:ignoreIssue",importShard:"__lunora_admin__:importShard",listFlags:"__lunora_admin__:listFlags",listQueues:"__lunora_admin__:listQueues",lintSql:"__lunora_admin__:lintSql",listTables:"__lunora_admin__:listTables",listWorkflows:"__lunora_admin__:listWorkflows",maskPolicies:"__lunora_admin__:maskPolicies",migrationStatus:"__lunora_admin__:migrationStatus",pitrRestore:"__lunora_admin__:pitrRestore",rankBefore:"__lunora_admin__:rankBefore",rankPage:"__lunora_admin__:rankPage",readTablePage:"__lunora_admin__:readTablePage",recordAuthEvent:"__lunora_admin__:recordAuthEvent",recordContainerEvent:"__lunora_admin__:recordContainerEvent",recordMail:"__lunora_admin__:recordMail",recordQueueMessage:"__lunora_admin__:recordQueueMessage",replayQueueMessage:"__lunora_admin__:replayQueueMessage",resolveIssue:"__lunora_admin__:resolveIssue",rlsPolicies:"__lunora_admin__:rlsPolicies",schemaHistory:"__lunora_admin__:schemaHistory",schemaVersion:"__lunora_admin__:schemaVersion",runAs:"__lunora_admin__:runAs",runMigration:"__lunora_admin__:runMigration",runSql:"__lunora_admin__:runSql",sendQueueMessage:"__lunora_admin__:sendQueueMessage",sendTestMail:"__lunora_admin__:sendTestMail",setIssueSeverity:"__lunora_admin__:setIssueSeverity",storageOrphans:"__lunora_admin__:storageOrphans",storageReferences:"__lunora_admin__:storageReferences",storageRules:"__lunora_admin__:storageRules",studioFeatures:"__lunora_admin__:studioFeatures",writeRow:"__lunora_admin__:writeRow"},N=50,b=500,x=30,F=200,m="__doc__",w=e=>{try{const a=JSON.parse(e);return a!==null&&typeof a=="object"&&!Array.isArray(a)?a:void 0}catch{return}},L=(e,a)=>{if(!e.includes(m))return{columns:e,rows:a};const r=[];for(const s of a){const _=s[m],i=typeof _=="string"?w(_):void 0;if(i===void 0)return{columns:e,rows:a};const u=Object.fromEntries(Object.entries(s).filter(([l])=>l!==m));r.push({...u,...i})}const t=e.filter(s=>s!==m),n=[],o=new Set(t);for(const s of r)for(const _ of Object.keys(s))o.has(_)||(o.add(_),n.push(_));return{columns:[...t,...n],rows:r}},O=e=>e.replaceAll(/[\\%_]/g,a=>`\\${a}`),S=e=>e.startsWith("sqlite_")||e.startsWith("_cf_")||e.startsWith("__miniflare")||e.startsWith("__lunora")||e.includes("__fts_"),I=(e,a,r)=>Math.min(Math.max(e,a),r),k=(e,a)=>{const r=e.exec(`SELECT COUNT(*) AS c FROM ${a}`).one();return Number(r.c)},V=e=>{const a=e.exec("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name").toArray(),r=[];for(const{name:t}of a)S(t)||r.push({name:t,rowCount:k(e,d(t))});return r},A=(e,a)=>e.exec("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ? LIMIT 1",a).toArray().length>0,P={eq:"=",gt:">",gte:">=",lt:"<",lte:"<=",ne:"<>"},U=e=>typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):"",T=(e,a)=>{const r=a.includes(e),t=a.includes(m);if(!(!r&&!t))return r?{expression:d(e),params:[]}:{expression:`json_extract(${d(m)}, ?)`,params:[`$."${e.replaceAll('"','""')}"`]}},W=(e,a)=>{const r=T(e.column,a);if(r===void 0)return;const{expression:t,params:n}=r;return e.operator==="contains"?{params:[...n,`%${O(U(e.value))}%`],sql:String.raw`CAST(${t} AS TEXT) LIKE ? ESCAPE '\'`}:{params:[...n,e.value],sql:`${t} ${P[e.operator]} ?`}},D=/^(\d{4})(?:-(\d{2}))?(?:-(\d{2}))?$/u,q=e=>{const a=D.exec(e.trim());if(a===null)return;const r=Number(a[1]),t=a[2]===void 0?void 0:Number(a[2]),n=a[3]===void 0?void 0:Number(a[3]);if(t!==void 0&&(t<1||t>12)||n!==void 0&&(n<1||n>31)||r<100)return;const o=Date.UTC(r,(t??1)-1,n??1);if(n!==void 0&&new Date(o).getUTCDate()!==n)return;let s;return n!==void 0?s=Date.UTC(r,t===void 0?0:t-1,n+1):t===void 0?s=Date.UTC(r+1,0,1):s=Date.UTC(r,t,1),{from:o,to:s}},v=(e,a,r)=>{const t=[],n=[];if(a!==""&&e.length>0){const o=`%${O(a)}%`,s=e.map(i=>String.raw`CAST(${d(i)} AS TEXT) LIKE ? ESCAPE '\'`);n.push(...e.map(()=>o));const _=q(a);if(_!==void 0)for(const i of e)s.push(`(${d(i)} >= ? AND ${d(i)} < ?)`),n.push(_.from,_.to);t.push(`(${s.join(" OR ")})`)}for(const o of r??[]){const s=W(o,e);s!==void 0&&(t.push(`(${s.sql})`),n.push(...s.params))}return t.length===0?void 0:{parameters:n,where:t.join(" AND ")}},Q=(e,a)=>{if(e===void 0)return;const r=T(e.column,a);if(r===void 0)return;const t=e.direction==="desc"?"DESC":"ASC";return{params:r.params,sql:`${r.expression} ${t}`}},J=(e,a)=>{const{table:r}=a;if(S(r)||!A(e,r))throw new M("UNKNOWN_TABLE",`unknown table: ${r}`,{status:404});const t=I(Math.trunc(a.limit??N),1,b),n=Math.max(0,Math.trunc(a.offset??0)),o=d(r),s=e.exec(`PRAGMA table_info(${o})`).toArray().map(h=>h.name),_=a.search?.trim()??"",i=h=>{if(a.refs===void 0)return h;const C={};for(const R of h.columns){const $=a.refs[R];$!==void 0&&(C[R]=$)}return Object.keys(C).length>0?{...h,refs:C}:h},u=v(s,_,a.filters),l=Q(a.orderBy,s),c=u===void 0?"":` WHERE ${u.where}`,f=l===void 0?"":` ORDER BY ${l.sql}`,g=u?.parameters??[],E=l?.params??[];let p;a.skipCount||(p=u===void 0?k(e,o):Number(e.exec(`SELECT COUNT(*) AS c FROM ${o}${c}`,...g).one().c));const y=e.exec(`SELECT * FROM ${o}${c}${f} LIMIT ? OFFSET ?`,...g,...E,t,n).toArray();return i({...L(s,y),total:p})},Z=(e,a)=>{const{table:r}=a;if(S(r)||!A(e,r))throw new M("UNKNOWN_TABLE",`unknown table: ${r}`,{status:404});const t=I(Math.trunc(a.limit??b),1,b),n=d(r),o=e.exec(`PRAGMA table_info(${n})`).toArray().map(c=>c.name),s=a.search?.trim()??"",_=v(o,s,a.filters),i=_===void 0?e.exec(`SELECT id FROM ${n} LIMIT ?`,t+1).toArray():e.exec(`SELECT id FROM ${n} WHERE ${_.where} LIMIT ?`,..._.parameters,t+1).toArray(),u=i.length>t,l=(u?i.slice(0,t):i).map(c=>c.id);return{hasMore:u,ids:l}},j=(e,a,r)=>{const t=new Set(r.filter(o=>o!==m));if(!r.includes(m))return t;const n=e.exec(`SELECT ${d(m)} AS doc FROM ${a} LIMIT ?`,b).toArray();for(const{doc:o}of n){const s=typeof o=="string"?w(o):void 0;if(s!==void 0)for(const _ of Object.keys(s))t.add(_)}return t},ee=(e,a)=>{const{column:r,table:t}=a;if(S(t)||!A(e,t))throw new M("UNKNOWN_TABLE",`unknown table: ${t}`,{status:404});const n=d(t),o=e.exec(`PRAGMA table_info(${n})`).toArray().map(p=>p.name);if(!j(e,n,o).has(r))throw new M("UNKNOWN_COLUMN",`unknown column: ${r}`,{status:404});const s=T(r,o);if(s===void 0)throw new M("UNKNOWN_COLUMN",`unknown column: ${r}`,{status:404});const _=I(Math.trunc(a.limit??x),1,F),i=a.search?.trim()??"",u=v(o,i,a.filters),l=u===void 0?"":` WHERE ${u.where}`,c=u?.parameters??[],f=e.exec(`SELECT ${s.expression} AS value, COUNT(*) AS count FROM ${n}${l} GROUP BY ${s.expression} ORDER BY count DESC LIMIT ?`,...s.params,...c,...s.params,_+1).toArray(),g=f.length>_,E=g?f.slice(0,_):f;return{truncated:g,values:E.map(p=>({count:Number(p.count),value:p.value}))}},ae=(e,a,r)=>{const t={},n=r.slice(0,b);for(const s of n)t[s]=[];if(n.length===0)return{references:t,storageColumns:a};const o=n.map(()=>"?").join(", ");for(const[s,_]of Object.entries(a)){if(S(s)||!A(e,s))continue;const i=d(s),u=e.exec(`PRAGMA table_info(${i})`).toArray().map(l=>l.name);for(const l of _){const c=T(l,u);if(c===void 0)continue;const f=e.exec(`SELECT id, ${c.expression} AS ref FROM ${i} WHERE ${c.expression} IN (${o})`,...c.params,...c.params,...n).toArray();for(const g of f)t[g.ref]?.push({column:l,id:g.id,table:s})}}return{references:t,storageColumns:a}},te=e=>{const a=e.map((t,n)=>{const o=Object.values(t.subs??{}).map(s=>({args:s.args,functionPath:s.functionPath,table:s.table}));return{admin:t.admin===!0,id:n,subscriptions:o}}),r=a.reduce((t,n)=>t+n.subscriptions.length,0);return{connections:a,totalConnections:a.length,totalSubscriptions:r}},B=20,re=()=>({maxMs:0,passes:0,peakSocketsIterated:0,socketsDelivered:0,socketsIterated:0,totalMs:0}),se=(e,a,r,t)=>({maxMs:Math.max(e.maxMs,t),passes:e.passes+1,peakSocketsIterated:Math.max(e.peakSocketsIterated,a),socketsDelivered:e.socketsDelivered+r,socketsIterated:e.socketsIterated+a,totalMs:e.totalMs+t}),ne=(e,a=B)=>{const r=new Map,t=new Map;for(const o of e){for(const s of Object.values(o.shapes??{})){const _=s.name??"(unknown shape)";r.set(_,(r.get(_)??0)+1)}for(const s of o.whispers??[])t.set(s,(t.get(s)??0)+1)}const n=[...[...r].map(([o,s])=>({kind:"shape",subscribers:s,topic:o})),...[...t].map(([o,s])=>({kind:"whisper",subscribers:s,topic:o}))];return n.sort((o,s)=>s.subscribers-o.subscribers||o.topic.localeCompare(s.topic)),{peakSubscribers:n[0]?.subscribers??0,topics:n.slice(0,a),totalConnections:e.length}};export{z as ADMIN_FUNCTIONS,K as ADMIN_FUNCTION_PREFIX,B as DEFAULT_FANOUT_TOPIC_LIMIT,Y as FLAGS_FUNCTION_PREFIX,b as MAX_PAGE_SIZE,X as RELATION_FUNCTION_PREFIX,re as createFanoutCounters,q as datePrefixRange,ee as facetColumn,ae as findStorageReferences,V as listTables,J as readTablePage,se as recordFanoutPass,Z as selectMatchingIds,ne as summarizeFanoutTopics,te as summarizeSubscriptions};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as y}from"@lunora/errors";import{n as Rt,u as At,T as ye,a as It,y as ht,c as $t,A as Ve,Y as vt}from"./ctx-db-backfill-Hl48Dr77.mjs";import{o as gi,H as Ei,P as bi,X as yi}from"./ctx-db-backfill-Hl48Dr77.mjs";import{sql as e}from"drizzle-orm";import{matchesStaticWhere as qe,aggregateSqlFunction as Se,normalizeCountArgument as Ct,throwingScheduler as xt}from"./AGGREGATE_SQL_FUNCTION-QYaiuty4.mjs";import{encodeAggregateKey as de,foldAggregateTally as Mt,aggregateTableName as Re,coerceAggregateNumber as Ue,readAggregateValue as Pe}from"./aggregateTableName-G-eXyjcz.mjs";import{mergeWhere as oe,CountRlsUnsupportedError as je,selectIndexForGroupBy as kt,selectIndexForCount as Lt,selectIndexForAggregate as Ot}from"./CountRlsUnsupportedError-Cl8XpYDL.mjs";import{appendCdcChange as Dt}from"./CDC_LOG_TABLE-E_J5LPoK.mjs";import{CDC_LOG_TABLE as Ni,applyCdcChanges as Ti,bumpCdcEpoch as Si,minCdcSeq as Ri,readCdcChanges as Ai,readCdcCursor as Ii,readCdcEpoch as vi,trimCdcChanges as Ci}from"./CDC_LOG_TABLE-E_J5LPoK.mjs";import{r as M}from"./do-exec-BLe9lLrN.mjs";import{b as pt,s as Z,g as $e,a as ce,_ as te,m as X,T as mt,E as Le,$ as ee,l as Wt,L as wt,N as gt,S as et}from"./do-sql-x0AjZhaN.mjs";import{param as Ye}from"./renderSql-B5lF5Jd9.mjs";import{encodeGeohash as Bt,GEO_DEFAULT_PRECISION as Ft,coveringGeohashes as qt,boundingBoxGeohashes as Ut,pointInBoundingBox as Pt,haversineMeters as jt}from"./GEO_DEFAULT_PRECISION-okRCkZ6r.mjs";import{sortColumnName as Ie,matchesRankStaticWhere as Et,encodePartitionKey as We,rankTableName as ve,resolveRankPartition as bt,RANK_TIEBREAK as we}from"./RANK_TIEBREAK-DtX8zQyc.mjs";import{t as ue}from"./serialize-sql-DiRzL7A4.mjs";import{SCAN_DEP as z}from"./SCAN_DEP-D_yR9EeV.mjs";import{decodeCursor as De,normalizeOrderKeys as Ht,buildSeekWhere as yt,applySelect as tt,encodeCursor as Je,softDeleteScope as be,buildSeekBeforeWhere as Gt}from"./applySelect-B0CF8T7y.mjs";import Jt from"./NotFoundError-J3tjf4Uo.mjs";import{assertFlatPredicate as He,resolveRelationPredicates as nt}from"./DEFAULT_MAX_RELATION_KEYS-VxD8RtL0.mjs";import{runRowValidators as Ge,resolveWith as it,applyOnDelete as Qt,fanOutScalarCounts as Vt}from"./applyOnDelete-DCeU2Jh0.mjs";import{guardWriter as Yt}from"./RLS_UNWRAP_SYMBOL-C6_WX3dG.mjs";import{createSystemReader as Kt}from"./createSystemReader-DcDcrtM3.mjs";import{ConflictError as Ae}from"./ConflictError-C8GtJmjS.mjs";import{runTriggers as zt}from"./hasTrigger-_rexbWMO.mjs";import{compileWhereSql as he}from"./compileWhereSql-BLcfs4QW.mjs";import{e as Mi,t as ki,r as Li,o as Oi,l as Di,p as Wi,_ as Bi,a as Fi,b as qi,d as Ui,m as Pi,c as ji,S as Hi,T as Gi}from"./schema-history-YGeVjyvV.mjs";import{runShardMigrations as Qi}from"./runShardMigrations-DBSceD0H.mjs";import{a as Yi,s as Ki}from"./ctx-db-shapes-CHC2cS0g.mjs";const Xt=i=>{const o=new TextEncoder().encode(i);let n="";for(const a of o)n+=String.fromCodePoint(a);return btoa(n)},Zt=i=>{const o=atob(i),n=Uint8Array.from(o,a=>a.codePointAt(0)??0);return new TextDecoder().decode(n)},en=()=>new y("BAD_REQUEST","invalid cursor"),rt=16,ot=8,fe=1024,Ke=(i,o)=>o.query(i),tn=(i,o,n)=>{const a=Rt(i,n);if(a.length===0)return 0;let s=0;for(const[d,w]of o.entries()){const $=d===o.length-1;let b=0;for(const S of a)($?S.startsWith(w):S===w)&&(b+=1);if(b===0)return 0;s+=b}return s},nn=(i,o)=>{if(!o)return{exact:!0,lower:i,upper:i};const n=i.codePointAt(i.length-1)??0,a=i.slice(0,Math.max(0,i.length-String.fromCodePoint(n).length));return{exact:!1,lower:i,upper:a+String.fromCodePoint(n+1)}},rn=(i,o,n)=>{const a={eq:(s,d)=>{if(!i.definition.filterFields?.includes(s))throw new y("INTERNAL",`field "${s}" is not a filter field of search index "${i.indexName}" on table "${o}"`);if(i.filters.length>=ot)throw new y("BAD_REQUEST",`search index "${i.indexName}" on table "${o}": at most ${String(ot)} .eq() filters are supported per search query`);return i.filters.push({field:s,value:d}),a},search:(s,d)=>{const w=i;if(s!==w.definition.field)throw new y("INTERNAL",`search index "${w.indexName}" on table "${o}" indexes "${w.definition.field}", not "${s}"`);const $=Ke(d,n).length;if($>rt)throw new y("BAD_REQUEST",`search index "${w.indexName}" on table "${o}": at most ${String(rt)} search terms are supported (got ${String($)})`);return w.field=s,w.query=d,w.hasQuery=!0,a}};return a},on=i=>{if(i.length>fe)throw new y("BAD_REQUEST",`more than ${String(fe)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},an=i=>Math.min(i.offset+i.numItems+1,fe),sn=i=>Xt(`search:${String(i)}`),ln=i=>{let o;try{o=Zt(i)}catch{return}if(!o.startsWith("search:"))return;const n=Number(o.slice(7));return Number.isInteger(n)&&n>=0?n:void 0},dn=i=>{if(typeof i.endCursor=="string")throw new y("BAD_REQUEST","bounded (endCursor) pagination is not supported on search queries — relevance order has no stable range boundary");const o=Math.max(0,Math.floor(i.numItems)),n=i.cursor?ln(i.cursor):0;if(n===void 0)throw en();if(n+o>fe)throw new y("BAD_REQUEST",`search pagination reaches past the ${String(fe)}-document limit (offset ${String(n)} + ${String(o)} requested) — narrow the query or the filters instead`);return{numItems:o,offset:n}},cn=(i,o)=>{const n=o.offset+o.numItems,a=o.numItems>0&&i.length>n;return{continueCursor:a?sn(n):null,isDone:!a,page:i.slice(o.offset,n)}},fn=i=>{if(i===void 0)return fe+1;if(!Number.isFinite(i))return fe;const o=Math.max(0,Math.floor(i));if(o>fe)throw new y("BAD_REQUEST",`search returns at most ${String(fe)} documents (asked for ${String(o)}) — narrow the query or paginate instead`);return o},un=(i,o,n)=>[...i.partitionBy??[],...i.sortBy.map(a=>a.field),...i.where?Object.keys(i.where):[]].every(a=>o[a]===n[a]),hn=(i,o,n,a,s,d)=>{if(s&&d&&un(n,s,d))return;const w=ve(o,n.name);if(s&&M(i,e`DELETE FROM ${e.identifier(w)} WHERE ${e.identifier("__id__")} = ${a}`),!d||n.where&&!Et(d,n.where))return;const $=n.sortBy.map((_,h)=>Ie(h)),b=e.join(["__id__","__partition__",...$].map(_=>e.identifier(_)),e`, `),S=We(n.partitionBy??[],d),k=n.sortBy.map(_=>ue(d[_.field]??null)),T=e.join([a,S,...k].map(_=>Ye(_)),e`, `);M(i,e`INSERT INTO ${e.identifier(w)} (${b}) VALUES (${T})`)},$n=i=>{const{broadcast:o,invalidateCache:n,recordCdc:a,schema:s,sql:d}=i,w=new Set,$=new Set,b=(R,g)=>{const A=`${R}::${g.name}`;if(w.has(A))return;const F=Re(R,g.name),W=g.by??[],H=new Map,q=M(d,e`SELECT id, _creationTime, ${e.identifier(Z)} FROM ${e.identifier(R)}`).toArray();for(const U of q){const L=$e(U);if(!L||g.where&&!qe(L,g.where))continue;const G=de(W,L);Mt(H,G,g,L)}M(d,e`DELETE FROM ${e.identifier(F)}`);const J=32,B=[...H];for(let U=0;U<B.length;U+=J){const L=B.slice(U,U+J),G=e.join(L.map(([j,V])=>e`(${j}, ${V.value}, ${V.count})`),e`, `);M(d,e`INSERT INTO ${e.identifier(F)} (${ce}, ${te}, ${X}) VALUES ${G}`)}w.add(A)},S=(R,g,A)=>{const F=g.by??[],W=Se(g.op),H=g.field??"",q=[];for(const U of F){const L=ue(A[U]??null);L===null?q.push(e`${ee(U)} IS NULL`):q.push(e`${ee(U)} = ${L}`)}for(const[U,L]of Object.entries(g.where??{})){const G=L!==null&&typeof L=="object"&&!Array.isArray(L)?L.eq:L,j=ue(G);j===null?q.push(e`${ee(U)} IS NULL`):q.push(e`${ee(U)} = ${j}`)}const J=q.length>0?e` WHERE ${e.join(q,e` AND `)}`:e``,B=ee(H);return{value:M(d,e`SELECT ${e.raw(W)}(${B}) AS value FROM ${e.identifier(R)}${J}`).one().value??null}},k=(R,g,A,F)=>{const W=Re(R,g.name),{op:H}=g,q=g.field??"",J=L=>{M(d,e`DELETE FROM ${e.identifier(W)} WHERE ${ce} = ${L} AND ${X} <= 0`)},B=A&&(!g.where||qe(A,g.where))?A:void 0,U=F&&(!g.where||qe(F,g.where))?F:void 0;if(!(!B&&!U)){if(H==="count"){for(const[L,G]of[[B,-1],[U,1]]){if(!L)continue;const j=de(g.by??[],L);M(d,Le(W,j,G,G,e`${te} = ${te} + excluded.${te}, ${X} = ${X} + excluded.${X}`))}B&&J(de(g.by??[],B));return}if(H==="sum"||H==="avg"){for(const[L,G]of[[B,-1],[U,1]]){if(!L)continue;const j=Ue(L[q]);if(j===void 0)continue;const V=de(g.by??[],L);M(d,Le(W,V,G*j,G,e`${te} = COALESCE(${te}, 0) + excluded.${te}, ${X} = ${X} + excluded.${X}`))}B&&J(de(g.by??[],B));return}if(B){const L=de(g.by??[],B),G=Ue(B[q]),j=M(d,e`SELECT ${te} AS value, ${X} AS count FROM ${e.identifier(W)} WHERE ${ce} = ${L}`).toArray()[0],V=(j?.count??0)-1;if(V<=0)M(d,e`DELETE FROM ${e.identifier(W)} WHERE ${ce} = ${L}`);else if(j&&G!==void 0&&j.value!==null&&G===j.value){const ie=S(R,g,B);M(d,e`UPDATE ${e.identifier(W)} SET ${te} = ${ie.value}, ${X} = ${V} WHERE ${ce} = ${L}`)}else M(d,e`UPDATE ${e.identifier(W)} SET ${X} = ${X} - 1 WHERE ${ce} = ${L}`)}if(U){const L=de(g.by??[],U),G=Ue(U[q]);if(G===void 0)M(d,Le(W,L,null,1,e`${X} = ${X} + 1`));else{const j=H==="min"?"MIN":"MAX";M(d,Le(W,L,G,1,e`${te} = ${e.raw(j)}(COALESCE(${te}, excluded.${te}), excluded.${te}), ${X} = ${X} + 1`))}}}},T=R=>{const g=s.tables[R]?.aggregateIndexes;if(!(!g||g.length===0))for(const A of g)b(R,A)},_=(R,g,A)=>{const F=s.tables[R]?.aggregateIndexes;if(!(!F||F.length===0))for(const W of F)k(R,W,g,A)},h=(R,g)=>{const A=`${R}::rank::${g.name}`;if($.has(A))return;const F=ve(R,g.name),W=M(d,e`SELECT id, _creationTime, ${e.identifier(Z)} FROM ${e.identifier(R)}`).toArray();M(d,e`DELETE FROM ${e.identifier(F)}`);const H=g.sortBy.map((J,B)=>Ie(B)),q=e.join(["__id__","__partition__",...H].map(J=>e.identifier(J)),e`, `);for(const J of W){const B=$e(J);if(!B||g.where&&!Et(B,g.where))continue;const U=We(g.partitionBy??[],B),L=g.sortBy.map(j=>ue(B[j.field]??null)),G=e.join([B._id,U,...L].map(j=>Ye(j)),e`, `);M(d,e`INSERT INTO ${e.identifier(F)} (${q}) VALUES (${G})`)}$.add(A)},x=R=>{const g=s.tables[R]?.rankIndexes;if(!(!g||g.length===0))for(const A of g)h(R,A)},C=(R,g,A,F)=>{const W=s.tables[R]?.rankIndexes;if(!(!W||W.length===0))for(const H of W)hn(d,R,H,g,A,F)},v=(R,g,A,F)=>{const W=s.tables[R]?.searchIndexes;if(!(!W||W.length===0||!pt(d)))for(const H of W){if(At(F,A,H))continue;const q=$t(R,H.name);M(d,e`DELETE FROM ${e.identifier(q)} WHERE ${e.identifier(ye)} = ${g}`),A&&M(d,e`INSERT INTO ${e.identifier(q)} (${e.identifier(It)}, ${e.identifier(ye)}) VALUES (${ht(A,H)}, ${g})`)}},P=(R,g,A)=>{const F=s.tables[R]?.geoIndexes;if(!(!F||F.length===0))for(const W of F){const H=mt(R,W.name);M(d,e`DELETE FROM ${e.identifier(H)} WHERE ${e.identifier("__id__")} = ${g}`);const q=A?.[W.field];if(q!==null&&typeof q=="object"&&typeof q.lat=="number"&&typeof q.lng=="number"){const{lat:J,lng:B}=q,U=Bt({lat:J,lng:B},W.precision??Ft);M(d,e`INSERT INTO ${e.identifier(H)} (${e.identifier("__id__")}, ${e.identifier("__geohash__")}, ${e.identifier("__lat__")}, ${e.identifier("__lng__")}) VALUES (${g}, ${U}, ${J}, ${B})`)}}};return{ensureBackfilledForTable:T,ensureBackfilledIndex:b,ensureRankBackfilled:h,ensureRankBackfilledForTable:x,syncAggregates:_,syncCompanionsForInsert:(R,g,A)=>{v(R,g,A),P(R,g,A),_(R,void 0,A),C(R,g,void 0,A),n(R,g),a(R,g,"insert",A),o({key:g,op:"insert",row:A,table:R})},syncGeo:P,syncRanks:C,syncSearch:v}},pn="__doc__",mn=i=>{const o=JSON.stringify(i),n=new TextEncoder().encode(o);let a="";for(const s of n)a+=String.fromCodePoint(s);return btoa(a)},wn=i=>i.after?[i.after.partitionKey,...i.after.sortValues,i.after.rowId]:i.cursor?De(i.cursor):void 0,gn=(i,o,n)=>{if(i?.length!==1+o.length+1)return;const a=[{column:"__partition__",direction:"asc"}];for(const[d,w]of o.entries())a.push({column:w,direction:n[d]?.direction??"asc"});a.push({column:we,direction:"asc"});const s=[];for(const[d,w]of a.entries()){const $=[];for(const[S,k]of a.slice(0,d).entries())$.push(e`${e.identifier(k.column)} IS ${i[S]}`);$.push(e`${e.identifier(w.column)} ${e.raw(w.direction==="desc"?"<":">")} ${i[d]}`);const[b]=$;s.push($.length===1&&b!==void 0?b:e`(${e.join($,e` AND `)})`)}return e`(${e.join(s,e` OR `)})`},_t=null,En=(i,o)=>{if(i===void 0)return _t;const n=[i.__partition__,...o.map(a=>i[a]),i[we]];return mn(n)},bn=(i,o,n)=>{const a=[];for(const s of i){const d=s[we];if(typeof d!="string")continue;const w=o.get(d);if(!w)continue;const $=typeof s.__partition__=="string"?s.__partition__:"",b=n.map(S=>s[S]??null);a.push({doc:w,key:{partitionKey:$,rowId:d,sortValues:b}})}return a},yn=(i,o,n)=>{const{rowToDocument:a}=i,s=new Map;if(n.length===0)return s;const d=e.join(n.map($=>Ye($)),e`, `),w=M(i.sql,e`SELECT id, _creationTime, ${e.identifier(pn)} FROM ${e.identifier(o)} WHERE id IN (${d})`).toArray();for(const $ of w){const b=a($),S=$.id;b&&typeof S=="string"&&s.set(S,b)}return s},at=(i,o,n,a)=>{const{assertRankPartitionLocal:s,ensureRankBackfilled:d,onRead:w,schema:$}=i,b=$.tables[o];if(!b)throw new y("INTERNAL",`unknown table: ${o}`);const S=b.rankIndexes?.find(V=>V.name===n);if(!S)throw new y("INTERNAL",`unknown rankIndex "${n}" on table "${o}"`);s(o,b,S),w(o,z),d(o,S);const k=ve(o,S.name),T=S.sortBy.map((V,ie)=>Ie(ie)),_=Math.max(1,Math.min(1e3,Math.floor(a.take??100))),h=oe(a.baseWhere,a.where),x=bt(S,h),C=[e`${e.identifier("__partition__")} ASC`];for(const[V,ie]of T.entries()){const se=S.sortBy[V]?.direction;C.push(e`${e.identifier(ie)} ${e.raw(se==="desc"?"DESC":"ASC")}`)}C.push(e`${e.identifier(we)} ASC`);const v=[];typeof a.partitionKey=="string"?v.push(e`${e.identifier("__partition__")} = ${a.partitionKey}`):x&&v.push(e`${e.identifier("__partition__")} = ${We(S.partitionBy??[],x)}`);const P=wn(a),R=gn(P,T,S.sortBy);R&&v.push(R);const g=e.identifier(we),A=e.identifier("__partition__"),F=v.length>0?e` WHERE ${e.join(v,e` AND `)}`:e``,W=T.length>0?e`${g}, ${A}, ${e.join(T.map(V=>e.identifier(V)),e`, `)}`:e`${g}, ${A}`,H=e`SELECT ${W} FROM ${e.identifier(k)}${F} ORDER BY ${e.join(C,e`, `)} LIMIT ${e.raw(String(_+1))}`,q=M(i.sql,H).toArray(),J=q.length>_,B=J?q.slice(0,_):q,U=B.map(V=>V[we]),L=bn(B,yn(i,o,U),T),G=J?En(B.at(-1),T):_t,j=S.sortBy.map(V=>V.direction==="desc"?"desc":"asc");return{continueCursor:G,directions:j,hasMore:J,rows:L}},_n=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,Nn=i=>{if(!_n.test(i))throw new y("INTERNAL",`invalid clientId ${JSON.stringify(i)}: a client-supplied row id must be a UUID`)},st=50,Nt=500,Ee=(i,o,n)=>{const a=o??Nt;if(i>a)throw new y("BATCH_LIMIT_EXCEEDED",`${n}: batch of ${String(i)} exceeds the limit of ${String(a)} (raise options.limit or chunk the call)`,{status:400})},Tn=i=>{const o={eq:(n,a)=>(i.sqlConditions.push({comparator:"=",field:n,value:a}),o),gt:(n,a)=>(i.sqlConditions.push({comparator:">",field:n,value:a}),o),gte:(n,a)=>(i.sqlConditions.push({comparator:">=",field:n,value:a}),o),lt:(n,a)=>(i.sqlConditions.push({comparator:"<",field:n,value:a}),o),lte:(n,a)=>(i.sqlConditions.push({comparator:"<=",field:n,value:a}),o)};return o},Sn=i=>Math.max(i,fe),Rn=(i,o,n,a,s)=>{const d=Ke(n.query,Ve(n.definition.language));if(d.length===0)return[];const w=$t(o,n.indexName),$=`${w}__vocab`,b=d.length-1,S=d.map((C,v)=>{const P=nn(C,v===b),R=P.exact?e`${e.identifier("term")} = ${P.lower}`:e`${e.identifier("term")} >= ${P.lower} AND ${e.identifier("term")} < ${P.upper}`;return e`SELECT ${e.identifier("doc")}, ${e.raw(String(v))} AS ${e.identifier("__term__")}, COUNT(*) AS ${e.identifier("__n__")} FROM ${e.identifier($)} WHERE ${R} GROUP BY ${e.identifier("doc")}`}),k=d.map((C,v)=>e`SUM(CASE WHEN u.${e.identifier("__term__")} = ${e.raw(String(v))} THEN u.${e.identifier("__n__")} ELSE 0 END)`),T=e`SELECT f.${e.identifier(ye)} AS ${e.identifier(ye)}, ${e.join(k,e` + `)} AS ${e.identifier("__score__")} FROM (${e.join(S,e` UNION ALL `)}) u JOIN ${e.identifier(w)} f ON f.rowid = u.${e.identifier("doc")} GROUP BY f.${e.identifier(ye)} HAVING ${e.join(k.map(C=>e`${C} > 0`),e` AND `)}`,_=[];for(const C of n.filters)_.push(e`${ee(C.field)} = ${ue(C.value)}`);s&&_.push(s);let h=e`SELECT m.id, m._creationTime, m.${e.identifier(Z)} FROM (${T}) s JOIN ${e.identifier(o)} m ON m.id = s.${e.identifier(ye)}`;_.length>0&&(h=e`${h} WHERE ${e.join(_,e` AND `)}`),h=e`${h} ORDER BY s.${e.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${e.raw(String(a))}`;const x=[];for(const C of M(i,h)){const v=gt(C);v&&x.push(v)}return x},An=(i,o,n,a,s)=>{const d=Ve(n.definition.language),w=Ke(n.query,d);if(w.length===0)return[];const $=[];for(const T of n.filters)$.push(e`${ee(T.field)} = ${ue(T.value)}`);s&&$.push(s);let b=e`SELECT id, _creationTime, ${e.identifier(Z)} FROM ${e.identifier(o)}`;$.length>0&&(b=e`${b} WHERE ${e.join($,e` AND `)}`),b=e`${b} ORDER BY _creationTime DESC, id ASC LIMIT ${e.raw(String(Sn(a)))}`;const S=M(i,b).toArray(),k=[];for(const T of S){const _=gt(T);if(!_)continue;const h=tn(ht(_,n.definition),w,d);h>0&&k.push({creationTime:typeof _._creationTime=="number"?_._creationTime:0,doc:_,id:typeof _._id=="string"?_._id:"",score:h})}return k.sort((T,_)=>_.score-T.score||_.creationTime-T.creationTime||T.id.localeCompare(_.id)),k.slice(0,a).map(T=>T.doc)},In=(i,o)=>{const n=i,a={near:(s,d)=>{if(n.within)throw new y("INTERNAL",`geo index "${n.indexName}" on table "${o}": call .near() or .within(), not both`);return n.near={point:{lat:s.lat,lng:s.lng},radiusMeters:d},a},within:s=>{if(n.near)throw new y("INTERNAL",`geo index "${n.indexName}" on table "${o}": call .near() or .within(), not both`);return n.within={ne:{lat:s.ne.lat,lng:s.ne.lng},sw:{lat:s.sw.lat,lng:s.sw.lng}},a}};return a},vn=(i,o)=>{const n=i[o];if(n===null||typeof n!="object")return;const{lat:a,lng:s}=n;return typeof a=="number"&&typeof s=="number"?{lat:a,lng:s}:void 0},Cn=(i,o)=>{const n=vn(i,o.definition.field);if(!n)return;const a=typeof i._creationTime=="number"?i._creationTime:0;if(o.near){const s=jt(o.near.point,n);return s<=o.near.radiusMeters?{creationTime:a,distance:s}:void 0}return Pt(n,o.within)?{creationTime:a,distance:0}:void 0},xn=(i,o,n,a,s)=>{if(!n.near&&!n.within)throw new y("INTERNAL",`geo index "${n.indexName}" on table "${o}": call .near(point, radius) or .within(box)`);const d=n.near?qt(n.near.point,n.near.radiusMeters):Ut(n.within),w=mt(o,n.indexName),$=d.map(h=>e`(g.${e.identifier("__geohash__")} >= ${h} AND g.${e.identifier("__geohash__")} < ${`${h}{`})`),b=[e`(${e.join($,e` OR `)})`];s&&b.push(s);const S=e`SELECT m.id, m._creationTime, m.${e.identifier(Z)} FROM ${e.identifier(w)} g JOIN ${e.identifier(o)} m ON m.id = g.${e.identifier("__id__")} WHERE ${e.join(b,e` AND `)}`,k=M(i,S).toArray(),T=[];for(const h of k){const x=$e(h),C=x?Cn(x,n):void 0;x&&C&&T.push({creationTime:C.creationTime,distance:C.distance,doc:x})}T.sort((h,x)=>h.distance-x.distance||x.creationTime-h.creationTime);const _=T.map(h=>h.doc);return typeof a=="number"?_.slice(0,Math.max(0,Math.floor(a))):_},Mn=(i,o,n,a,s)=>{const{geo:d}=n;if(!d)throw new y("INTERNAL","runGeoTerminal called without a staged geo query");const w=n.inMemoryFilters.length>0,$=xn(i,o,d,w?void 0:s,a);if(!w)return $;const b=[];for(const S of $)if(n.inMemoryFilters.every(k=>k(S))&&(b.push(S),typeof s=="number"&&b.length>=s))break;return b},kn=(i,o,n,a,s,d)=>{const w=[];for(const k of n.sqlConditions)w.push(e`${ee(k.field)} ${e.raw(k.comparator)} ${ue(k.value)}`);a&&w.push(a);let $=e`SELECT id, _creationTime, ${e.identifier(Z)} FROM ${e.identifier(o)}`;w.length>0&&($=e`${$} WHERE ${e.join(w,e` AND `)}`),$=e`${$} ORDER BY ${s}`,typeof d=="number"&&n.inMemoryFilters.length===0&&($=e`${$} LIMIT ${e.raw(String(Math.max(0,Math.floor(d))))}`);const b=M(i,$).toArray(),S=[];for(const k of b){const T=$e(k);if(T&&n.inMemoryFilters.every(_=>_(T))&&(S.push(T),typeof d=="number"&&S.length>=d))break}return S},me={fieldRef:ee,serialize:ue},Ln=i=>{let o=0;const n=[],a={fieldRef:ee,relationExists:s=>{const{childWhere:d,negated:w,parentTable:$,relation:b}=s,S=`__rel_${String(o)}`,k=n.at(-1)??$;o+=1,i(b.table,z);const T=b.kind==="one"?b.field:b.references,_=b.kind==="one"?b.references:b.field,h=e`${et(S,_)} = ${et(k,T)}`;n.push(S);const x=he(d,a);n.pop();const C=x?e`${h} AND ${x}`:h,v=e`EXISTS (SELECT 1 FROM ${e.identifier(b.table)} AS ${e.identifier(S)} WHERE ${C})`;return w?e`NOT ${v}`:v},serialize:ue};return a},Tt=i=>{const o=i.map(n=>e`${ee(n.field)} ${e.raw(n.direction==="desc"?"DESC":"ASC")}`);return i.some(n=>n.field==="_id"||n.field==="id")||o.push(e`${ee("id")} ASC`),e.join(o,e`, `)},On={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},Dn=i=>{const o=i.order;return i.indexFields.length>0?i.indexFields.map(n=>({direction:o,field:n})):[{direction:o,field:"_creationTime"}]},Wn=(i,o,n,a)=>{const s=i.sqlConditions.map(d=>({[d.field]:{[On[d.comparator]??"eq"]:d.value}}));if(n&&s.push(yt(o,De(n))),a&&s.push(Gt(o,De(a))),s.length!==0)return s.length===1?s[0]:{AND:s}},Bn=(i,o,n)=>{const a=[];for(const s of i){const d=$e(s);if(d&&o.every(w=>w(d))&&(a.push(d),n!==void 0&&a.length>n))break}return a},Fn=(i,o,n,a,s)=>{const d=Math.max(0,Math.floor(a.numItems)),w=Dn(n),$=typeof a.endCursor=="string",b=he(Wn(n,w,a.cursor,a.endCursor),me),S=s&&b?e`${b} AND ${s}`:s??b;let k=e`SELECT id, _creationTime, ${e.identifier(Z)} FROM ${e.identifier(o)}`;S&&(k=e`${k} WHERE ${S}`),k=e`${k} ORDER BY ${Tt(w)}`;const T=n.inMemoryFilters.length>0;!T&&!$&&(k=e`${k} LIMIT ${e.raw(String(d+1))}`);const _=M(i,k).toArray(),h=Bn(_,n.inMemoryFilters,T||$?void 0:d);if($){const P=h.length>=2?h[Math.floor(h.length/2)-1]:void 0;return{continueCursor:a.endCursor??null,isDone:!0,page:h,splitCursor:P?Je(P,w):null}}const x=h.length>d,C=x?h.slice(0,d):h,v=C.at(-1);return{continueCursor:x&&v?Je(v,w):null,isDone:!x,page:C}};class qn extends y{constructor(o="unique() found more than one matching document"){super("NOT_UNIQUE",o,{name:"NotUniqueError"})}}const Un=/\s/u,Pn=String.fromCodePoint(0),lt=(i,o,n)=>{if(!i.tables[o])throw new y("INTERNAL",`unknown table: ${o}`);return typeof n!="string"||n.length===0||Un.test(n)||n.includes(Pn)?null:n},jn=(i,o,n,a=()=>{})=>{const s=o.tables[n];if(!s)throw new y("INTERNAL",`unknown table: ${n}`);const d=be(s.softDeleteMode,void 0),w=d?he(d,me):void 0,$={indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[]},b=h=>{const{search:x}=$;if(!x)throw new y("INTERNAL","runSearchFetch called without a staged search");vt(i,n,s);const C=$.inMemoryFilters.length>0,v=fn(C?void 0:h),P=pt(i)?Rn(i,n,x,v,w):An(i,n,x,v,w);if(!C)return h===void 0&&on(P),P;const R=[];for(const g of P)if($.inMemoryFilters.every(A=>A(g))&&(R.push(g),typeof h=="number"&&R.length>=h))break;return R},S=h=>{const x=dn(h);return cn(b(an(x)),x)},k=()=>{const h=$.indexFields.length>0?$.indexFields:["_creationTime"],x=$.order==="desc"?"DESC":"ASC";return e.join(h.map(C=>e`${ee(C)} ${e.raw(x)}`),e`, `)},T=h=>$.search?b(h):$.geo?Mn(i,n,$,w,h):kn(i,n,$,w,k(),h),_={async collect(){return T(void 0)},filter(h){return $.inMemoryFilters.push(h),_},async first(){return T($.inMemoryFilters.length>0?void 0:1)[0]??null},order(h){return $.order=h==="desc"?"desc":"asc",_},async paginate(h){if($.search)return S(h);if($.geo)throw new y("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");return Fn(i,n,$,h,w)},async take(h){return T(h)},async unique(){const h=T($.inMemoryFilters.length>0?void 0:2);if(h.length>1)throw new qn(`unique() on table "${n}" matched ${String(h.length)} documents; expected at most one`);return h[0]??null},withGeoIndex(h,x){const C=(s.geoIndexes??[]).find(P=>P.name===h);if(!C)throw new y("INTERNAL",`unknown geo index "${h}" on table "${n}"`);a(n,h,"geo");const v={definition:C,indexName:h};if($.geo=v,x(In(v,n)),!v.near&&!v.within)throw new y("INTERNAL",`geo index "${h}" on table "${n}" requires a .near(point, radius) or .within(box) call`);return _},withIndex(h,x){const C=s.indexes.find(v=>v.name===h);if(!C)throw new y("INTERNAL",`unknown index "${h}" on table "${n}"`);return a(n,h,"index"),$.indexName=h,$.indexFields=C.fields,x&&x(Tn($)),_},withSearchIndex(h,x){const C=(s.searchIndexes??[]).find(P=>P.name===h);if(!C)throw new y("INTERNAL",`unknown search index "${h}" on table "${n}"`);a(n,h,"search");const v={definition:C,field:C.field,filters:[],hasQuery:!1,indexName:h,query:""};if($.search=v,x(rn(v,n,Ve(C.language))),!v.hasQuery)throw new y("INTERNAL",`search index "${h}" on table "${n}" requires a .search(field, query) call`);return _}};return _},dt=(i,o,n)=>{const a={...o};for(const[s,d]of wt(i)){if(d.serverDefault){a[s]=d.serverDefault({auth:n});continue}a[s]===void 0&&(d.defaultFn?a[s]=d.defaultFn():"defaultValue"in d&&(a[s]=d.defaultValue))}return a},ct=(i,o,n,a)=>{const s=n;for(const[d,w]of wt(i)){if(w.serverDefault){d in o&&(s[d]=w.serverDefault({auth:a}));continue}w.onUpdateFn&&!(d in o)&&(s[d]=w.onUpdateFn())}},ft=(i,o)=>{for(const n of Object.keys(o))if(o[n]===void 0)throw new y("INTERNAL",`Cannot ${i} field '${n}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},Hn=/unique constraint failed/i,Gn=i=>i instanceof Error&&Hn.test(i.message),Qe=(i,o,n)=>{try{M(i,n)}catch(a){throw Gn(a)?new Ae(`unique constraint violation on "${o}"`,"unique"):a}},Oe=(i,o,n)=>{if(Qe(i,o,n),M(i,e`SELECT changes() AS changed`).one().changed===0)throw new Ae(`optimistic concurrency conflict on "${o}" — the row changed during this mutation; refetch and retry`,"occ")},ut=(i,o,n,a,s,d,w)=>{const $=[];for(let T=0;T<n.length+1;T+=1){const _=[];for(let v=0;v<T;v+=1)_.push(e`${e.identifier(n[v])} IS ${d[v]}`);const h=n[T],x=a[T];if(h!==void 0&&x!==void 0){const v=x.direction==="desc"?">":"<";_.push(e`${e.identifier(h)} ${e.raw(v)} ${d[T]}`)}else _.push(e`${e.identifier(we)} < ${w}`);const[C]=_;$.push(_.length===1&&C!==void 0?C:e`(${e.join(_,e` AND `)})`)}const b=e.join($,e` OR `),S=M(i,e`SELECT COUNT(*) AS c FROM ${e.identifier(o)} WHERE ${e.identifier("__partition__")} = ${s} AND (${b})`).one(),k=M(i,e`SELECT COUNT(*) AS c FROM ${e.identifier(o)} WHERE ${e.identifier("__partition__")} = ${s}`).one();return{before:S.c,total:k.c}},pi=i=>{const{sql:o}=i,{schema:n}=i,a=i.broadcast??(()=>{}),s=i.onRead??(()=>{}),d=i.onIndexUse??(()=>{}),w=i.onWrite??(()=>{}),{cache:$}=i,b=i.clock??(()=>Date.now()),S=i.idGenerator??(()=>crypto.randomUUID()),k=i.scheduler??xt,{globalDb:T}=i,_=i.auth??{identity:null,userId:null},h=i.cdc??!1,x=k,C=Kt({scheduler:typeof x.list=="function"&&typeof x.get=="function"?x:void 0,storage:i.storage}),v=(t,r,l,m)=>{h&&Dt(o,b(),t,r,l,m)},P=t=>n.tables[t]?.shardMode?.kind==="global",R=(t,r)=>{if(P(t)){if(!T)throw new y("INTERNAL",`cross-backend ${r} for global table '${t}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return T}return Y},g=t=>R(t,"cascade"),A=(t,r)=>{if(P(t)){if(!T)throw new y("INTERNAL",`${r} on global table '${t}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return T}},F=()=>T,W=(t,r)=>R(t,"relation load").findMany(t,r),H=(t,r)=>(P(t)&&s(t,z),W(t,r)),q=t=>!P(t.table),J=i.relationExistsPushDown??"auto",B=J!=="never",{maxRelationKeys:U}=i,L=(t,r,l)=>nt(t,{fetcher:H,maxRelationKeys:U,relationBaseWhere:l,schema:n,tableName:r}),G=async(t,r,l,m)=>{const p=A(t,"relation grouped count");if(p)return s(t,z),Vt((D,re)=>p.count(D,re),t,r,l,m);const f=n.tables[t];if(!f)throw new y("INTERNAL",`unknown table: ${t}`);s(t,z);const c=be(f.softDeleteMode,void 0),u={[r]:{in:l}},E=oe(oe(u,m),c),I=await L(E,t,void 0),N=he(I,me),O=ee(r);let K=e`SELECT ${O} AS __fk__, COUNT(*) AS count FROM ${e.identifier(t)}`;N&&(K=e`${K} WHERE ${N}`),K=e`${K} GROUP BY ${O}`;const Q=M(o,K).toArray();return new Map(Q.map(D=>[D.__fk__,D.count]))};let j=0;const V=new Set;for(const[t,r]of Object.entries(n.tables))for(const l of Object.values(r.triggerMap??{}))V.add(`${t} ${l.timing} ${l.op}`);const ie=(t,r,l)=>V.has(`${t} ${r} ${l}`),se=async(t,r,l)=>{if(j+=1,j>st)throw j-=1,new Ae(`trigger recursion exceeded ${String(st)} levels on "${l.table}" — check for a self-triggering write`,"trigger");try{await zt({ctx:St,event:l,op:r,schema:n,tableName:l.table,timing:t})}finally{j-=1}},{ensureBackfilledForTable:_e,ensureBackfilledIndex:Be,ensureRankBackfilled:Fe,ensureRankBackfilledForTable:Ne,syncAggregates:Ce,syncCompanionsForInsert:ze,syncGeo:xe,syncRanks:Te,syncSearch:Me}=$n({broadcast:a,invalidateCache:(t,r)=>$?.invalidate(t,r),recordCdc:v,schema:n,sql:o}),Xe=(t,r,l)=>{const{shardMode:m}=r;if(m?.kind==="shardBy"&&!(m.field!==void 0&&(l.partitionBy??[]).includes(m.field)))throw Object.assign(new Error(`rank index "${l.name}" on "${t}" partitions across shards (shard key "${m.field??"?"}" is not in partitionBy) — a shard-local rank()/rankPage() would be wrong; roll it up through the Query Coordinator instead`),{code:"CROSS_SHARD_RANK_UNSUPPORTED",name:"LunoraError",status:400})},pe=(t,r)=>{const l=Object.entries(n.tables).filter(([,I])=>I.shardMode?.kind!=="global").map(([I])=>I).filter(I=>r===void 0||I===r);if(l.length===0)return;const m=l.map(I=>e`SELECT ${e.raw(`'${I.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${e.identifier(Z)} FROM ${e.identifier(I)} WHERE id = ${t}`),p=e`${e.join(m,e` UNION ALL `)} LIMIT 1`,[f]=M(o,p).toArray();if(!f)return;const c=f.__t__,u=$e(f);if(typeof c!="string"||!u)return;const E=f[Z];return{docJson:typeof E=="string"?E:JSON.stringify(E??{}),row:u,tableName:c}},Ze={assertRankPartitionLocal:Xe,ensureRankBackfilled:Fe,onRead:s,rowToDocument:$e,schema:n,sql:o},Y={system:C,async aggregate(t,r){const l=A(t,"aggregate");if(l)return s(t,z),l.aggregate(t,r);const m=n.tables[t];if(!m)throw new y("INTERNAL",`unknown table: ${t}`);if(Se(r.op),r.op==="count")return Y.count(t,{baseWhere:r.baseWhere,relationBaseWhere:r.relationBaseWhere,restrictsCounts:r.restrictsCounts,where:r.where});if(!r.field)throw new y("INTERNAL",`aggregate(${t}, { op: "${r.op}" }): "field" is required for non-count reducers`);s(t,z);const p=be(m.softDeleteMode,void 0),f=oe(oe(r.baseWhere,r.where),p),c=await L(f,t,r.relationBaseWhere),u=c!==f;if(m.aggregateIndexes&&!r.baseWhere&&!u&&!p){const Q=Ot(m.aggregateIndexes,r.op,r.field,r.where);if(Q){Be(t,Q.index);const D=de(Q.index.by??[],Q.key),re=Re(t,Q.index.name),ae=M(o,e`SELECT ${te} AS value, ${X} AS count FROM ${e.identifier(re)} WHERE ${ce} = ${D}`).toArray()[0];return Pe(r.op,ae)}}const E=he(c,me),I=Se(r.op),N=ee(r.field);let O=e`SELECT ${e.raw(I)}(${N}) AS value FROM ${e.identifier(t)}`;return E&&(O=e`${O} WHERE ${E}`),M(o,O).toArray()[0]?.value??null},asId(t,r){const l=lt(n,t,r);if(l===null)throw new y("BAD_REQUEST",`asId("${t}", …): "${r}" is not a valid id for table "${t}"`,{status:400});return l},async count(t,r){const l=A(t,"count");if(l)return s(t,z),l.count(t,r);const m=n.tables[t];if(!m)throw new y("INTERNAL",`unknown table: ${t}`);const p=Ct(r);if(p.restrictsCounts)throw new je(t);s(t,z);const f=be(m.softDeleteMode,void 0),c=oe(oe(p.baseWhere,p.where),f),u=await L(c,t,p.relationBaseWhere),E=u!==c;if(m.aggregateIndexes&&!p.baseWhere&&!E&&!f){const O=Lt(m.aggregateIndexes,p.where);if(O){Be(t,O.index);const K=de(O.index.by??[],O.key),Q=Re(t,O.index.name),D=M(o,e`SELECT ${te} AS value FROM ${e.identifier(Q)} WHERE ${ce} = ${K}`).toArray();return D[0]===void 0?0:D[0].value??0}}const I=he(u,me);let N=e`SELECT COUNT(*) AS count FROM ${e.identifier(t)}`;return I&&(N=e`${N} WHERE ${I}`),M(o,N).one().count},async delete(t,r,l){const m=pe(t,r);if(!m){const N=r===void 0?F():void 0;N&&await N.delete(t,void 0,l);return}const{docJson:p,row:f,tableName:c}=m,u=n.tables[c],E=l?.hard===!0,I=!E&&u?.softDeleteMode?u.softDeleteMode.field:void 0;if(!(I&&f[I]!==null&&f[I]!==void 0)){if(ie(c,"before","delete")&&await se("before","delete",{id:t,op:"delete",previous:f,table:c}),await Qt({deletedId:t,deletedReference:N=>f[N],findHolders:async(N,O,K)=>(await g(N).findMany(N,{includeDeleted:E,where:{[O]:K}})).page,onCascade:(N,O)=>g(N).delete(O,void 0,l),onRestrict:N=>{throw new Ae(N,"restrict")},onSetNull:(N,O,K)=>g(N).patch(O,{[K]:null}),schema:n,tableName:c}),_e(c),Ne(c),I){const N={...f,[I]:b(),_id:t};Oe(o,c,e`UPDATE ${e.identifier(c)} SET ${e.identifier(Z)} = ${JSON.stringify(N)} WHERE id = ${t} AND ${e.identifier(Z)} = ${p}`),Me(c,t,N,f),xe(c,t,void 0),Ce(c,f,N),Te(c,t,f,void 0),$?.invalidate(c,t),v(c,t,"update",N),a({key:t,op:"update",row:N,table:c}),ie(c,"after","delete")&&await se("after","delete",{id:t,op:"delete",previous:f,table:c}),await w({id:t,op:"delete",table:c});return}Oe(o,c,e`DELETE FROM ${e.identifier(c)} WHERE id = ${t} AND ${e.identifier(Z)} = ${p}`),Me(c,t,void 0),xe(c,t,void 0),Ce(c,f,void 0),Te(c,t,f,void 0),$?.invalidate(c,t),v(c,t,"delete"),a({key:t,op:"delete",table:c}),ie(c,"after","delete")&&await se("after","delete",{id:t,op:"delete",previous:f,table:c}),await w({id:t,op:"delete",table:c})}},async deleteAll(t,r){if(!n.tables[t])throw new y("INTERNAL",`unknown table: ${t}`);const l=Math.max(1,r?.chunkSize??Nt),m=r?.hard===void 0?void 0:{hard:r.hard},p=P(t)?void 0:t;let f=0;for(;;){const c=(await Y.findMany(t,{limit:l})).page.map(u=>String(u._id));if(c.length===0)break;for(const u of c)await Y.delete(u,p,m),f+=1;if(c.length<l)break}return{deleted:f}},async deleteMany(t,r,l){Ee(t.length,r?.limit,"deleteMany");for(const m of t)await Y.delete(m,l);return{deleted:t.length}},async deleteWhere(t,r,l){const m=A(t,"deleteWhere");let p;if(m)p=(await m.findMany(t,{where:r})).page.map(f=>String(f._id));else{if(!n.tables[t])throw new y("INTERNAL",`unknown table: ${t}`);p=(await Y.findMany(t,{where:r})).page.map(f=>String(f._id))}if(Ee(p.length,l?.limit,"deleteWhere"),Y.deleteMany===void 0)throw new y("INTERNAL",`ctx.db.${t}.deleteMany is unavailable: this writer has no batch delete`);return Y.deleteMany(p,l)},async findFirst(t,r={}){return(await Y.findMany(t,{...r,limit:1})).page[0]??null},async findFirstOrThrow(t,r={}){const l=await Y.findFirst(t,r);if(l===null)throw new Jt(`findFirstOrThrow: no "${t}" document matched`);return l},async findMany(t,r={}){const l=A(t,"findMany");if(l)return s(t,z),l.findMany(t,r);const m=n.tables[t];if(!m)throw new y("INTERNAL",`unknown table: ${t}`);const p=!r.where&&!r.baseWhere;p?s(t,z):s(t);const f=Ht(r.orderBy),c=r.cursor?yt(f,De(r.cursor)):void 0;let u=oe(r.baseWhere,r.where);u=oe(u,be(m.softDeleteMode,r.includeDeleted)),u=await nt(u,{canPushExists:B?q:void 0,existsPushMode:J==="always"?"always":"auto",fetcher:H,maxRelationKeys:U,relationBaseWhere:r.relationBaseWhere,schema:n,tableName:t}),c&&(u=u?{AND:[u,c]}:c);const E=B?Ln(s):me,I=he(u,E);let N=e`SELECT id, _creationTime, ${e.identifier(Z)} FROM ${e.identifier(t)}`;I&&(N=e`${N} WHERE ${I}`),N=e`${N} ORDER BY ${Tt(f)}`;const O=typeof r.limit=="number"?Math.max(0,Math.floor(r.limit)):void 0;O!==void 0&&(N=e`${N} LIMIT ${e.raw(String(O+1))}`);const K=M(o,N).toArray(),Q=[];for(const le of K){const ne=$e(le);ne&&(Q.push(ne),!p&&typeof ne._id=="string"&&s(t,ne._id))}if(O===void 0)return r.with&&await it({groupedCounter:G,fetcher:W,parents:Q,relationBaseWhere:r.relationBaseWhere,schema:n,tableName:t,with:r.with}),{continueCursor:null,isDone:!0,page:tt(Q,r.select,r.with)};const D=Q.length>O,re=D?Q.slice(0,O):Q,ae=re.at(-1);return r.with&&await it({fetcher:W,groupedCounter:G,parents:re,relationBaseWhere:r.relationBaseWhere,schema:n,tableName:t,with:r.with}),{continueCursor:D&&ae?Je(ae,f):null,isDone:!D,page:tt(re,r.select,r.with)}},async get(t,r){const l=pe(t,r);if(!l){const m=r===void 0?F():void 0;return m?m.get(t):null}return s(l.tableName,t),l.row},async lookupById(t,r){const l=pe(t,r);return l?(s(l.tableName,t),{row:l.row,tableName:l.tableName}):null},async groupBy(t,r){const l=A(t,"groupBy");if(l)return s(t,z),l.groupBy(t,r);const m=n.tables[t];if(!m)throw new y("INTERNAL",`unknown table: ${t}`);s(t,z);const p=r.agg??{op:"count"};if(Se(p.op),p.op!=="count"&&!p.field)throw new y("INTERNAL",`groupBy(${t}, { agg: { op: "${p.op}" } }): "field" is required for non-count reducers`);const f=be(m.softDeleteMode,void 0),c=oe(oe(r.baseWhere,r.where),f),u=await L(c,t,r.relationBaseWhere),E=u!==c;if(m.aggregateIndexes&&!r.baseWhere&&!E&&!f){const D=kt(m.aggregateIndexes,p.op,p.field,r.by,r.where);if(D){Be(t,D.index);const re=Re(t,D.index.name),ae=Object.keys(D.partial),le=[];if(ae.length===(D.index.by??[]).length&&ae.length>0){const ge=de(D.index.by??[],D.partial),ke=M(o,e`SELECT ${te} AS value, ${X} AS count FROM ${e.identifier(re)} WHERE ${ce} = ${ge}`).toArray();return ke.length>0&&le.push({key:{...D.partial},value:Pe(p.op,ke[0])}),le}const ne=M(o,e`SELECT ${ce} AS key, ${te} AS value, ${X} AS count FROM ${e.identifier(re)}`).toArray();for(const ge of ne){const ke=JSON.parse(ge.key);le.push({key:ke,value:Pe(p.op,ge)})}return le}}const I=he(u,me),N=r.by.map(D=>e`${ee(D)} AS ${e.identifier(D)}`);if(p.op==="count")N.push(e`COUNT(*) AS value`);else{const{field:D}=p;if(D===void 0)throw new y("INTERNAL",`groupBy(${t}, { agg: { op: "${p.op}" } }): "field" is required for non-count reducers`);N.push(e`${e.raw(Se(p.op))}(${ee(D)}) AS value`)}let O=e`SELECT ${e.join(N,e`, `)} FROM ${e.identifier(t)}`;I&&(O=e`${O} WHERE ${I}`),O=e`${O} GROUP BY ${e.join(r.by.map(D=>ee(D)),e`, `)}`;const K=M(o,O).toArray(),Q=[];for(const D of K){const re={};for(const le of r.by)re[le]=D[le]??null;const{value:ae}=D;Q.push({key:re,value:ae==null?null:Number(ae)})}return Q},async insert(t,r,l){const m=A(t,"insert");if(m){const I=await m.insert(t,r,l);return a({key:I,op:"insert",row:{...r,_id:I},table:t}),I}const p=n.tables[t];if(!p)throw new y("INTERNAL",`unknown table: ${t}`);const f=dt(p,r,_);Ge(p,f);let c;l?.clientId!==void 0?(Nn(l.clientId),c=l.clientId):l?.allowExplicitId&&typeof f._id=="string"?c=f._id:c=S();const u=l?.allowExplicitId&&typeof f._creationTime=="number"?f._creationTime:b(),E={...f,_creationTime:u,_id:c};return ie(t,"before","insert")&&await se("before","insert",{doc:{...E},id:c,op:"insert",table:t}),_e(t),Ne(t),Qe(o,t,e`INSERT INTO ${e.identifier(t)} (id, _creationTime, ${e.identifier(Z)}) VALUES (${c}, ${u}, ${JSON.stringify(E)})`),ze(t,c,E),ie(t,"after","insert")&&await se("after","insert",{doc:E,id:c,op:"insert",table:t}),await w({doc:E,id:c,op:"insert",table:t}),c},async insertManyUnsafe(t,r,l){if(Ee(r.length,l?.limit,"insertManyUnsafe"),r.length===0)return[];const m=A(t,"insert");if(m){const u=[];for(const E of r){const I=await m.insert(t,E,{allowExplicitId:l?.allowExplicitId});a({key:I,op:"insert",row:{...E,_id:I},table:t}),u.push(I)}return u}const p=n.tables[t];if(!p)throw new y("INTERNAL",`unknown table: ${t}`);_e(t),Ne(t);const f=r.map(u=>{const E=dt(p,u,_),I=l?.allowExplicitId===!0&&typeof E._id=="string"?E._id:S(),N=l?.allowExplicitId===!0&&typeof E._creationTime=="number"?E._creationTime:b();return{creationTime:N,document:{...E,_creationTime:N,_id:I},id:I}}),c=e.join(f.map(u=>e`(${u.id}, ${u.creationTime}, ${JSON.stringify(u.document)})`),e`, `);Qe(o,t,e`INSERT INTO ${e.identifier(t)} (id, _creationTime, ${e.identifier(Z)}) VALUES ${c}`);for(const{document:u,id:E}of f)ze(t,E,u),await w({doc:u,id:E,op:"insert",table:t});return f.map(u=>u.id)},async insertMany(t,r,l){Ee(r.length,l?.limit,"insertMany");const m=l?.skipDuplicates===!0,p=[];for(const f of r)try{p.push(await Y.insert(t,f))}catch(c){if(m&&c instanceof Ae&&c.kind==="unique")p.push(null);else throw c}return p},normalizeId(t,r){return lt(n,t,r)},async patch(t,r,l){const m=pe(t,l);if(!m){const I=l===void 0?F():void 0;if(I){await I.patch(t,r);return}throw new y("INTERNAL",`document not found: ${t}`)}const{docJson:p,row:f,tableName:c}=m,u=n.tables[c];if(!u)throw new y("INTERNAL",`unknown table: ${c}`);s(c,t),ft("patch",r);const E={...f,...r,_id:t};ct(u,r,E,_),Ge(u,E,!0),ie(c,"before","update")&&await se("before","update",{doc:{...E},id:t,op:"update",previous:f,table:c}),_e(c),Ne(c),Oe(o,c,e`UPDATE ${e.identifier(c)} SET ${e.identifier(Z)} = ${JSON.stringify(E)} WHERE id = ${t} AND ${e.identifier(Z)} = ${p}`),Me(c,t,E,f),xe(c,t,E),Ce(c,f,E),Te(c,t,f,E),$?.invalidate(c,t),v(c,t,"update",E),a({key:t,op:"update",row:E,table:c}),ie(c,"after","update")&&await se("after","update",{doc:E,id:t,op:"update",previous:f,table:c}),await w({doc:E,id:t,op:"update",table:c})},async patchMany(t,r,l){Ee(t.length,r?.limit,"patchMany");for(const m of t)await Y.patch(m.id,m.patch,l);return{patched:t.length}},async patchWhere(t,r,l){const m=A(t,"patchWhere");let p;if(m)p=(await m.findMany(t,{where:r.where})).page.map(f=>({id:String(f._id),patch:r.patch}));else{if(!n.tables[t])throw new y("INTERNAL",`unknown table: ${t}`);p=(await Y.findMany(t,{where:r.where})).page.map(f=>({id:String(f._id),patch:r.patch}))}if(Ee(p.length,l?.limit,"patchWhere"),Y.patchMany===void 0)throw new y("INTERNAL",`ctx.db.${t}.patchMany is unavailable: this writer has no batch patch`);return await Y.patchMany(p,l),{patched:p.length}},query(t){const r=A(t,"query");return r?(s(t,z),r.query(t)):(s(t,z),jn(o,n,t,d))},async rank(t,r,l){const m=A(t,"rank");if(m)return s(t,z),m.rank(t,r,l);d(t,r,"rank");const p=n.tables[t];if(!p)throw new y("INTERNAL",`unknown table: ${t}`);const f=p.rankIndexes?.find(ne=>ne.name===r);if(!f)throw new y("INTERNAL",`unknown rankIndex "${r}" on table "${t}"`);if(Xe(t,p,f),l.restrictsCounts)throw new je(t);s(t,z),Fe(t,f);const c=typeof l.row=="string"?l.row:l.row._id;if(!c)return null;const u=ve(t,f.name),E=f.sortBy.map((ne,ge)=>Ie(ge)),I=E.map(ne=>Wt(ne)).join(", "),N=M(o,e`SELECT ${e.identifier("__partition__")}, ${e.raw(I)} FROM ${e.identifier(u)} WHERE ${e.identifier("__id__")} = ${c}`).toArray(),[O]=N;if(O===void 0)return null;let K=O.__partition__;const Q=oe(l.baseWhere,l.where);He(Q,n,t,"rank");const D=bt(f,Q);if(D){const ne=We(f.partitionBy??[],D);if(ne!==K)return null;K=ne}const re=E.map(ne=>O[ne]),{before:ae,total:le}=ut(o,u,E,f.sortBy,K,re,c);return{position:ae+1,total:le}},async rankBefore(t,r,l){if(P(t))throw new y("INTERNAL",`rankBefore is not supported on the global (.global()) table '${t}' — cross-shard rank cursors apply only to sharded tables`);const m=n.tables[t];if(!m)throw new y("INTERNAL",`unknown table: ${t}`);const p=m.rankIndexes?.find(E=>E.name===r);if(!p)throw new y("INTERNAL",`unknown rankIndex "${r}" on table "${t}"`);if(l.restrictsCounts)throw new je(t);s(t,z),Fe(t,p);const f=ve(t,p.name),c=p.sortBy.map((E,I)=>Ie(I)),u=p.sortBy.map((E,I)=>ue(l.sortValues[I]??null));return ut(o,f,c,p.sortBy,l.partitionKey,u,l.rowId)},async rankPage(t,r,l={}){He(oe(l.baseWhere,l.where),n,t,"rankPage");const m=A(t,"rankPage");if(m)return s(t,z),m.rankPage(t,r,l);d(t,r,"rank");const{continueCursor:p,hasMore:f,rows:c}=at(Ze,t,r,l);return{continueCursor:p,isDone:!f,page:c.map(u=>u.doc)}},async rankPageRows(t,r,l={}){He(oe(l.baseWhere,l.where),n,t,"rankPage"),d(t,r,"rank");const{directions:m,hasMore:p,rows:f}=at(Ze,t,r,l);return{directions:m,hasMore:p,rows:f}},async restore(t,r){const l=pe(t,r);if(!l){const f=r===void 0?F():void 0;if(f?.restore){await f.restore(t);return}throw new y("INTERNAL",`document not found: ${t}`)}const m=n.tables[l.tableName]?.softDeleteMode?.field;if(!m)throw new y("INTERNAL",`ctx.db.restore: table "${l.tableName}" is not a .softDelete() table`);const p=l.row[m]!==null&&l.row[m]!==void 0;await Y.patch(t,{[m]:null},r),p&&Te(l.tableName,t,void 0,l.row)},async replace(t,r,l,m){const p=pe(t,l);if(!p){const O=l===void 0?F():void 0;if(O){await O.replace(t,r,void 0,m);return}throw new y("INTERNAL",`document not found: ${t}`)}const{docJson:f,row:c,tableName:u}=p,E=n.tables[u];if(!E)throw new y("INTERNAL",`unknown table: ${u}`);ft("replace",r);const I=m?.allowExplicitId&&typeof r._creationTime=="number"?r._creationTime:b(),N={...r,_creationTime:I,_id:t};ct(E,r,N,_),Ge(E,N),ie(u,"before","update")&&await se("before","update",{doc:{...N},id:t,op:"update",previous:c,table:u}),_e(u),Ne(u),Oe(o,u,e`UPDATE ${e.identifier(u)} SET _creationTime = ${I}, ${e.identifier(Z)} = ${JSON.stringify(N)} WHERE id = ${t} AND ${e.identifier(Z)} = ${f}`),Me(u,t,N,c),xe(u,t,N),Ce(u,c,N),Te(u,t,c,N),$?.invalidate(u,t),v(u,t,"update",N),a({key:t,op:"update",row:N,table:u}),ie(u,"after","update")&&await se("after","update",{doc:N,id:t,op:"update",previous:c,table:u}),await w({doc:N,id:t,op:"update",table:u})},async wipeShard(t){const r=new Set(t?.exclude),l=t?.tables,m=Object.entries(n.tables).filter(([u,E])=>r.has(u)||l!==void 0&&!l.includes(u)?!1:E.shardMode?.kind!=="global").map(([u])=>u);if(l!==void 0){for(const u of l)if(!n.tables[u])throw new y("INTERNAL",`wipeShard: unknown table: ${u}`)}const p={};let f=0;const{deleteAll:c}=Y;if(c===void 0)throw new y("INTERNAL","wipeShard: this writer has no deleteAll");for(const u of m){const E=await c(u,{...t?.chunkSize===void 0?{}:{chunkSize:t.chunkSize},hard:!0});p[u]=E.deleted,f+=E.deleted}return{deleted:f,tables:p}}},St={db:Y,scheduler:k};return i.enforceRls===!0?Yt(Y,n,(t,r)=>pe(t,r)?.tableName):Y};export{Ni as CDC_LOG_TABLE,Mi as CLIENT_WATERMARK_TABLE,ki as GLOBAL_SHAPE_SNAPSHOT_TABLE,Li as IDEMPOTENCY_TABLE,qn as NotUniqueError,gi as SEARCH_STATE_TABLE,Oi as advanceClientWatermark,Ti as applyCdcChanges,Nn as assertValidClientId,Ei as backfillAggregateIndexes,bi as backfillRankIndexes,yi as backfillSearchIndexes,Si as bumpCdcEpoch,pi as createShardCtxDb,Di as deleteGlobalShapeSnapshot,Wi as deleteGlobalShapeSnapshotsForConnection,Bi as migrateClientWatermark,Fi as migrateGlobalShapeSnapshot,Ri as minCdcSeq,lt as normalizeIdStructurally,Ai as readCdcChanges,Ii as readCdcCursor,vi as readCdcEpoch,qi as readClientWatermark,Ui as readGlobalShapeSnapshot,Pi as readIdempotent,Qi as runShardMigrations,Yi as selectShapeMemberIds,Ki as selectShapeRows,Ci as trimCdcChanges,ji as trimIdempotent,Hi as writeGlobalShapeSnapshot,Gi as writeIdempotent};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{LunoraError as f,toErrorBody as q}from"@lunora/errors";import{drizzle as zt}from"drizzle-orm/durable-sqlite";import{c as te}from"./constant-time-equal-BVG05Guz.mjs";import{j as y}from"./json-response-wrh9TBPw.mjs";import{O as Jt,t as Xt,n as We,r as X,A as Yt,a as Vt,b as Zt,c as es,d as ts,w as le,e as ss}from"./context-telemetry-BFO0N_e4.mjs";import{f as R,c as P}from"./wire-codec-Ctnni0h6.mjs";import{parseExportShardArgs as rs,parseImportShardArgs as as}from"./exportShardRows-kt42wijd.mjs";import{recordAuthEvent as ns,readAuthMetrics as is}from"./AUTH_METRICS_BUCKETS_TABLE-D0wNaez7.mjs";import{DATA_MIGRATION_STATE_TABLE as os,readMigrationStatus as cs}from"./DATA_MIGRATION_STATE_TABLE-CaO6L0Ee.mjs";import{SCAN_DEP as He,createDependencyTracker as ds,tableFromDepKey as us}from"./SCAN_DEP-D_yR9EeV.mjs";import{readFunctionMetricsTotals as ls,readFunctionMetricIndexHits as hs,recordFunctionMetric as ps,mergeScanAttribution as fs,readFunctionMetrics as ms,readFunctionMetricBuckets as ys}from"./FUNCTION_METRICS_BUCKETS_TABLE-BPPeqM11.mjs";import{createFanoutCounters as Ke,ADMIN_FUNCTION_PREFIX as _,RELATION_FUNCTION_PREFIX as gs,selectMatchingIds as Ss,ADMIN_FUNCTIONS as h,listTables as je,findStorageReferences as bs,summarizeSubscriptions as Es,summarizeFanoutTopics as ws,readTablePage as Ts,facetColumn as Rs,FLAGS_FUNCTION_PREFIX as As,recordFanoutPass as he,MAX_PAGE_SIZE as vs}from"./ADMIN_FUNCTIONS-
|
|
1
|
+
import{LunoraError as f,toErrorBody as q}from"@lunora/errors";import{drizzle as zt}from"drizzle-orm/durable-sqlite";import{c as te}from"./constant-time-equal-BVG05Guz.mjs";import{j as y}from"./json-response-wrh9TBPw.mjs";import{O as Jt,t as Xt,n as We,r as X,A as Yt,a as Vt,b as Zt,c as es,d as ts,w as le,e as ss}from"./context-telemetry-BFO0N_e4.mjs";import{f as R,c as P}from"./wire-codec-Ctnni0h6.mjs";import{parseExportShardArgs as rs,parseImportShardArgs as as}from"./exportShardRows-kt42wijd.mjs";import{recordAuthEvent as ns,readAuthMetrics as is}from"./AUTH_METRICS_BUCKETS_TABLE-D0wNaez7.mjs";import{DATA_MIGRATION_STATE_TABLE as os,readMigrationStatus as cs}from"./DATA_MIGRATION_STATE_TABLE-CaO6L0Ee.mjs";import{SCAN_DEP as He,createDependencyTracker as ds,tableFromDepKey as us}from"./SCAN_DEP-D_yR9EeV.mjs";import{readFunctionMetricsTotals as ls,readFunctionMetricIndexHits as hs,recordFunctionMetric as ps,mergeScanAttribution as fs,readFunctionMetrics as ms,readFunctionMetricBuckets as ys}from"./FUNCTION_METRICS_BUCKETS_TABLE-BPPeqM11.mjs";import{createFanoutCounters as Ke,ADMIN_FUNCTION_PREFIX as _,RELATION_FUNCTION_PREFIX as gs,selectMatchingIds as Ss,ADMIN_FUNCTIONS as h,listTables as je,findStorageReferences as bs,summarizeSubscriptions as Es,summarizeFanoutTopics as ws,readTablePage as Ts,facetColumn as Rs,FLAGS_FUNCTION_PREFIX as As,recordFanoutPass as he,MAX_PAGE_SIZE as vs}from"./ADMIN_FUNCTIONS-B0xlQJ4w.mjs";import{explainIssue as _s}from"./DEFAULT_EXPLAIN_ISSUE_MODEL-Dicm4iLF.mjs";import{LogBuffer as Is}from"./LogBuffer-bIvCelI-.mjs";import{recordCapturedMail as Ge,clearCapturedMail as ks,readCapturedMail as Ms,MAIL_TABLE as Ns}from"./MAIL_RETENTION-KmozO2NQ.mjs";import{stableStringify as Ne}from"./stableStringify-BjLh4gvA.mjs";import{readBookmark as Os,armRestore as $s}from"./armRestore-BNzdvQ_o.mjs";import{ReactiveCache as Cs,reactiveCacheKey as Qe}from"./ReactiveCache-1_9Rs7J_.mjs";import{stableWireKey as F}from"./stableWireKey-YEHLaX6X.mjs";import{awaitWsDrain as C,trySendFrame as D,subscriptionListDeltas as Ls,sendDeltaFrames as xs}from"./subscriptionListDeltas-Bs69JbA8.mjs";import{fingerprintError as qs}from"@lunora/fingerprint";import{redact as Ps,standardRules as Ds}from"@visulima/redact";import{q as re}from"./quote-identifier-CGiYFBvY.mjs";import{s as ze}from"./do-sql-x0AjZhaN.mjs";import{f as Us,g as Bs,p as Fs,m as Ws,T as Hs,c as Ks,b as pe,_ as js,o as Gs,l as Qs,d as zs,S as Js}from"./schema-history-YGeVjyvV.mjs";import{y as Xs,L as Ys,d as Vs}from"./sql-console-Cln4Xfju.mjs";import{R as Je,E as Zs,_ as er}from"./security-audit-BKUOgE0x.mjs";import{ConflictError as tr}from"./ConflictError-C8GtJmjS.mjs";import{selectExpiredIds as sr}from"./selectExpiredIds-BXJDiUtz.mjs";import{CDC_LOG_TABLE as Xe,readCdcChanges as fe,readCdcCursor as Ye,readCdcEpoch as Ve,minCdcSeq as Ze,bumpCdcEpoch as rr}from"./CDC_LOG_TABLE-E_J5LPoK.mjs";import{a as ar,s as nr}from"./ctx-db-shapes-CHC2cS0g.mjs";const et=500,se=(a,e)=>{if(a.size<e)return;const t=a.keys().next().value;t!==void 0&&a.delete(t)},kt=new TextEncoder,ir=a=>{const e=a.replaceAll("-","+").replaceAll("_","/")+"===".slice((a.length+3)%4),t=atob(e),s=new Uint8Array(t.length);for(let r=0;r<t.length;r+=1)s[r]=t.codePointAt(r)??0;return s},or=64,me=new Map,cr=async a=>{const e=me.get(a);if(e)return e;se(me,or);const t=crypto.subtle.importKey("raw",kt.encode(a),{hash:"SHA-256",name:"HMAC"},!1,["sign","verify"]);return me.set(a,t),t},dr=async(a,e,t)=>{const s=await cr(a);return crypto.subtle.verify("HMAC",s,t,kt.encode(e))},ur="v1",lr=async(a,e,t=Date.now())=>{if(a.length===0||e.length===0)return!1;const s=e.split(".");if(s.length!==3)return!1;const[r,n,i]=s;if(r!==ur||i.length===0)return!1;const o=Number(n);if(!Number.isFinite(o)||o<=t)return!1;let c;try{c=ir(i)}catch{return!1}return dr(a,`${r}.${n}`,c)},H="__lunora_audit__",ae=(a,e,...t)=>a.exec.call(a,e,...t),Oe=a=>{ae(a,`CREATE TABLE IF NOT EXISTS "${H}" (
|
|
2
2
|
seq INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
3
3
|
ts REAL NOT NULL,
|
|
4
4
|
op TEXT NOT NULL,
|
|
@@ -127,4 +127,4 @@ ${e.join(`
|
|
|
127
127
|
`),Ue=a=>typeof a=="object"&&a!==null&&typeof a.run=="function",Be=a=>T(a.model,Ca)||$a,Ga=async(a,e,t)=>{const s={failedError:T(e.failedError,Wt),failedSql:T(e.failedSql,Ft),prompt:T(e.prompt,J)};if(s.prompt==="")return O("empty-response");if(!Ue(a))return O("no-ai-binding");const r=await De(async()=>Pe(a,Be(e),Ka(),ja(s,t)),n=>{const i=Wa(n);return i!==""&&Ys(i)===void 0?i:void 0});return r.degraded?r:{degraded:!1,sql:r.value}},Qa=async(a,e,t)=>{const s=T(e.prompt,J);if(s==="")return O("empty-response");if(!Ue(a))return O("no-ai-binding");const r=`Columns available on this table: ${t.slice(0,qe).join(", ")}`,n=await De(async()=>Pe(a,Be(e),Kt("filter"),jt(r,s)),i=>Ua(Ht(i),t));return n.degraded?n:{clauses:n.value,degraded:!1}},za=async(a,e,t)=>{if(!Ue(a))return O("no-ai-binding");const s=t.columns.slice(0,qe);if(s.length===0)return O("empty-response");const r=`Result columns and types: ${s.map(o=>`${T(o,St)}: ${T(t.types?.[o]??"unknown",St)}`).join(", ")}
|
|
128
128
|
Row count: ${String(t.rowCount)}`,n=T(e.prompt,J)||"choose the most informative chart for this result",i=await De(async()=>Pe(a,Be(e),Kt("chart"),jt(r,n)),o=>Ba(Ht(o),s));return i.degraded?i:{chart:i.value,degraded:!1}},bt="__doc__",Ja=a=>a.startsWith("sqlite_")||a.startsWith("_cf_")||a.startsWith("__miniflare")||a.startsWith("__lunora")||a.includes("__fts_"),ke=a=>`"${a.replaceAll('"','""')}"`,Xa=(a,e)=>Ja(e)?!1:a.exec("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ? LIMIT 1",e).toArray().length>0,Ya=(a,e)=>{const t=e.includes(a),s=e.includes(bt);if(!(!t&&!s))return t?{expression:ke(a),params:[]}:{expression:`json_extract(${ke(bt)}, ?)`,params:[`$."${a.replaceAll('"','""')}"`]}},Va=(a,e,t,s,r,n,i)=>{const o=Ya(s,r);if(o===void 0)return;const c=a.exec(`SELECT id, ${o.expression} AS ref FROM ${e} WHERE ${o.expression} IS NOT NULL AND ${o.expression} <> '' LIMIT ?`,...o.params,...o.params,...o.params,5001).toArray();c.length>5e3&&(i.truncated=!0);for(const d of c.slice(0,5e3))if(i.scanned+=1,!n.has(d.ref)){if(i.references.length>=500){i.truncated=!0;continue}i.references.push({column:s,id:d.id,key:d.ref,table:t})}},Za=(a,e,t)=>{const s=t instanceof Set?t:new Set(t),r={references:[],scanned:0,truncated:!1};for(const[n,i]of Object.entries(e)){if(!Xa(a,n))continue;const o=ke(n),c=a.exec(`PRAGMA table_info(${o})`).toArray().map(d=>d.name);for(const d of i)Va(a,o,n,d,c,s,r)}return r},en="lunora-ping",tn="lunora-pong",sn=new Set(["1","enabled","on","true","yes"]);let Et=!1,ge;const rn=async()=>{if(!Et){Et=!0;try{const a=(await import("cloudflare:workers")).tracing;ge=a!==null&&typeof a=="object"&&typeof a.enterSpan=="function"?a:void 0}catch{ge=void 0}}return ge},an="<undelivered>",nn=1073741824,wt=1e4,on=864e5,cn=36e5,ee="__root__",E="*",Tt=(a,e)=>(a===void 0?"":`,"cursor":${String(a)}`)+(e===void 0?"":`,"epoch":${JSON.stringify(e)}`),dn=(a,e)=>{const[t,s]=a.size<=e.size?[a,e]:[e,a];for(const r of t)if(s.has(r))return!0;return!1},un=a=>{const e=typeof a.id=="string"?a.id:"";if(e.trim()==="")throw new f("MIGRATION_ID_REQUIRED","runMigration: `id` is required",{status:400});return{batchSize:typeof a.batchSize=="number"?a.batchSize:void 0,direction:a.direction==="down"?"down":"up",dryRun:a.dryRun===!0,id:e,maxBatches:typeof a.maxBatches=="number"?a.maxBatches:void 0}},Rt=vs,ln=200,hn=20,pn=3e4,fn=a=>{const{op:e}=a,t=typeof a.table=="string"?a.table:"";if(e!=="insert"&&e!=="patch"&&e!=="replace"&&e!=="delete")throw new f("BAD_REQUEST","writeRow: `op` must be insert|patch|replace|delete");if(t.trim()==="")throw new f("BAD_REQUEST","writeRow: `table` is required");const s=typeof a.id=="string"?a.id:void 0,r=typeof a.doc=="object"&&a.doc!==null&&!Array.isArray(a.doc)?a.doc:void 0;if(e!=="insert"&&(s===void 0||s===""))throw new f("BAD_REQUEST",`writeRow: \`id\` is required for op "${e}"`);if(e!=="delete"&&r===void 0)throw new f("BAD_REQUEST",`writeRow: \`doc\` is required for op "${e}"`);return{doc:r,id:s,op:e,table:t}},mn=a=>typeof a=="string"&&vr.includes(a),yn=a=>typeof a=="string"&&_r.includes(a),gn=a=>{const e=typeof a.hash=="string"?a.hash.trim():"";if(e==="")throw new f("BAD_REQUEST","issue triage: `hash` is required");return e},Gt=null,Sn=a=>{const e=a.assignee;if(e===null)return Gt;if(typeof e=="string"&&e.trim()!=="")return e;throw new f("BAD_REQUEST","assignIssue: `assignee` must be a non-empty string (assign) or null (unassign)")},bn=a=>{const e=a.severity;if(e===null)return Gt;if(yn(e))return e;throw new f("BAD_REQUEST","setIssueSeverity: `severity` must be one of critical|high|medium|low, or null to clear")},En=a=>{const e=typeof a.exportName=="string"?a.exportName.trim():"";if(e==="")throw new f("BAD_REQUEST","createWorkflowInstance: `exportName` is required");const t=typeof a.id=="string"&&a.id!==""?a.id:void 0;return{exportName:e,id:t,params:a.params}},wn=a=>{const e=typeof a.exportName=="string"?a.exportName.trim():"",t=typeof a.id=="string"?a.id.trim():"";if(e==="")throw new f("BAD_REQUEST","getWorkflowInstanceStatus: `exportName` is required");if(t==="")throw new f("BAD_REQUEST","getWorkflowInstanceStatus: `id` is required");return{exportName:e,id:t}},Tn=new Set(["complete","errored","paused","queued","running","terminated","unknown","waiting","waitingForPause"]),At=a=>typeof a=="string"&&Tn.has(a)?a:"unknown",Rn=a=>{if(typeof a!="object"||a===null)return;const{message:e,name:t}=a;return{message:typeof e=="string"?e:"",name:typeof t=="string"?t:"Error"}},An=new Set(["contains","eq","gt","gte","lt","lte","ne"]),Me=a=>{if(!Array.isArray(a))return;const e=[];for(const t of a){if(typeof t!="object"||t===null)continue;const s=t,{column:r,operator:n}=s;typeof r!="string"||r===""||typeof n!="string"||!An.has(n)||e.push({column:r,operator:n,value:s.value})}return e.length>0?e:void 0},vn=a=>{if(typeof a!="object"||a===null)return;const{column:e,direction:t}=a;if(!(typeof e!="string"||e===""))return{column:e,direction:t==="desc"?"desc":"asc"}},_n=a=>{const e=typeof a.table=="string"?a.table:"";if(e.trim()==="")throw new f("BAD_REQUEST","deleteRows: `table` is required");return{filters:Me(a.filters),limit:typeof a.limit=="number"?a.limit:void 0,search:typeof a.search=="string"?a.search:void 0,table:e}},In=a=>{const e=typeof a.table=="string"?a.table:"";if(e.trim()==="")throw new f("BAD_REQUEST","clearTable: `table` is required");return{limit:typeof a.limit=="number"?a.limit:void 0,table:e}},kn=a=>{const{outcome:e}=a;if(e!=="ok"&&e!=="fail")throw new f("BAD_REQUEST",'recordAuthEvent: `outcome` must be "ok" or "fail"');return{outcome:e}},Mn=/\(exit (\d+)\)/,Nn=a=>{const e=a.event;if(typeof e!="object"||e===null||Array.isArray(e))throw new f("BAD_REQUEST","recordContainerEvent: `event` must be an object");const t=e,s=typeof t.container=="string"?t.container:"",r=typeof t.event=="string"?t.event:"";if(s.trim()===""||r.trim()==="")throw new f("BAD_REQUEST","recordContainerEvent: `event.container` and `event.event` are required");const n=t.level==="error"?"error":"info",i=typeof t.message=="string"?t.message:void 0,o=typeof t.ts=="number"?t.ts:Date.now(),c=typeof t.instance=="string"&&t.instance!==""?t.instance:void 0,d=i===void 0?void 0:Mn.exec(i)?.[1];return{exitCode:d===void 0?void 0:Number.parseInt(d,10),functionPath:`container:${s}`,instance:c,level:n,message:i===void 0||i===""?r:`${r}: ${i}`,timestamp:o}},On=a=>{const e=typeof a.functionPath=="string"?a.functionPath:"",t=typeof a.userId=="string"?a.userId:"";if(e.trim()==="")throw new f("BAD_REQUEST","runAs: `functionPath` is required");if(e.startsWith(_))throw new f("BAD_REQUEST","runAs: cannot target a reserved admin function");if(t.trim()==="")throw new f("BAD_REQUEST","runAs: `userId` is required");const s=a.args;if(s!==void 0&&(typeof s!="object"||s===null||Array.isArray(s)))throw new f("BAD_REQUEST","runAs: `args` must be an object");const r=a.identity;if(r!==void 0&&(typeof r!="object"||r===null||Array.isArray(r)))throw new f("BAD_REQUEST","runAs: `identity` must be an object");return{args:s===void 0?{}:s,functionPath:e,userId:t,...r===void 0?{}:{identity:r}}},$n=a=>{const e=p=>{throw new f("BAD_REQUEST",`recordMail: ${p}`)},{bcc:t,cc:s,from:r,headers:n,html:i,replyTo:o,subject:c,text:d,to:u}=a;typeof c!="string"&&e("`subject` must be a string"),typeof u=="string"||Array.isArray(u)&&u.every(p=>typeof p=="string")||e("`to` must be a string or string[]");const l=(p,g)=>{if(p!==void 0)return(!Array.isArray(p)||!p.every(b=>typeof b=="string"))&&e(`\`${g}\` must be a string[]`),p},m=(p,g)=>(p!==void 0&&typeof p!="string"&&e(`\`${g}\` must be a string`),p);return{bcc:l(t,"bcc"),cc:l(s,"cc"),from:m(r,"from"),headers:n!==void 0&&typeof n=="object"&&n!==null?n:void 0,html:m(i,"html"),replyTo:m(o,"replyTo"),subject:c,text:m(d,"text"),to:u}},Cn="test@lunora.sh",Ln=a=>{const{to:e}=a;if(e!==void 0&&typeof e!="string")throw new f("BAD_REQUEST","sendTestMail: `to` must be a string");const t=e??Cn,s="https://example.test/verify?token=demo";return{from:"Lunora <noreply@lunora.sh>",html:`<p>This is a test email from the Lunora dev mail catcher.</p><p><a href="${s}">Verify your email</a></p>`,subject:"Lunora test email",text:`This is a test email from the Lunora dev mail catcher.
|
|
129
129
|
|
|
130
|
-
Verify your email: ${s}`,to:t}},xn=a=>{const e=r=>{throw new f("BAD_REQUEST",`recordQueueMessage: ${r}`)},t=a.messages;Array.isArray(t)||e("`messages` must be an array");const s=new Set(["ack","error","retry"]);return t.map((r,n)=>{(typeof r!="object"||r===null)&&e(`\`messages[${String(n)}]\` must be an object`);const i=r,o=typeof i.messageId=="string"?i.messageId:"",c=typeof i.queue=="string"?i.queue:"",d=typeof i.outcome=="string"?i.outcome:"";o===""&&e(`\`messages[${String(n)}].messageId\` is required`),c===""&&e(`\`messages[${String(n)}].queue\` is required`),s.has(d)||e(`\`messages[${String(n)}].outcome\` must be one of ack | error | retry`);const{attempts:u,timestamp:l}=i;return{attempts:typeof u=="number"&&Number.isFinite(u)?u:1,body:i.body,deadLettered:i.deadLettered===!0,error:typeof i.error=="string"?i.error:void 0,exportName:typeof i.exportName=="string"?i.exportName:void 0,messageId:o,outcome:d,queue:c,timestamp:typeof l=="number"&&Number.isFinite(l)?l:0}})},vt=100,A=a=>`${a.traceId}:${a.rootSpanId}`,Se=256,qn=500,be="lunora.dispatch",Pn=a=>{const e=typeof a.exportName=="string"?a.exportName.trim():"";if(e==="")throw new f("BAD_REQUEST","sendQueueMessage: `exportName` is required");const t=a.delaySeconds;if(t!==void 0&&(typeof t!="number"||!Number.isFinite(t)||t<0))throw new f("BAD_REQUEST","sendQueueMessage: `delaySeconds` must be a non-negative number");const s=Array.isArray(a.batch)?a.batch:void 0;if(s!==void 0&&(s.length===0||s.length>vt))throw new f("BAD_REQUEST",`sendQueueMessage: \`batch\` must contain between 1 and ${String(vt)} messages`);return{batch:s,body:a.body,contentType:typeof a.contentType=="string"?a.contentType:void 0,delaySeconds:t,exportName:e}},Dn=a=>{const e=typeof a.id=="string"?a.id.trim():"";if(e==="")throw new f("BAD_REQUEST","replayQueueMessage: `id` is required");const t=typeof a.target=="string"&&a.target.trim()!==""?a.target.trim():void 0;return{id:e,target:t}},Un=a=>{const e=typeof a.table=="string"?a.table:"",t=typeof a.index=="string"?a.index:"",s=typeof a.rowId=="string"?a.rowId:"";if(e.trim()==="")throw new f("BAD_REQUEST","rankBefore: `table` is required");if(t.trim()==="")throw new f("BAD_REQUEST","rankBefore: `index` is required");if(typeof a.partitionKey!="string")throw new f("BAD_REQUEST","rankBefore: `partitionKey` must be a string");if(s.trim()==="")throw new f("BAD_REQUEST","rankBefore: `rowId` is required");if(!Array.isArray(a.sortValues))throw new f("BAD_REQUEST","rankBefore: `sortValues` must be an array");return{index:t,partitionKey:a.partitionKey,rowId:s,sortValues:a.sortValues,table:e}},L=a=>{throw new f("BAD_REQUEST",a)},_t=(a,e)=>((typeof a!="string"||a.trim()==="")&&L(`rankPage: \`${e}\` is required`),a),Bn=a=>{if(a===void 0)return;(typeof a!="object"||a===null||Array.isArray(a))&&L("rankPage: `after` must be an object");const e=a;return(typeof e.partitionKey!="string"||typeof e.rowId!="string"||!Array.isArray(e.sortValues))&&L("rankPage: `after` must have a string partitionKey, string rowId, and array sortValues"),{partitionKey:e.partitionKey,rowId:e.rowId,sortValues:e.sortValues}},Fn=a=>{const e=_t(a.table,"table"),t=_t(a.index,"index");a.take!==void 0&&typeof a.take!="number"&&L("rankPage: `take` must be a number"),a.cursor!==void 0&&a.cursor!==null&&typeof a.cursor!="string"&&L("rankPage: `cursor` must be a string or null"),a.partitionKey!==void 0&&typeof a.partitionKey!="string"&&L("rankPage: `partitionKey` must be a string"),a.directions!==void 0&&!Array.isArray(a.directions)&&L("rankPage: `directions` must be an array");const s=a.directions===void 0?void 0:a.directions.map(r=>r==="desc"?"desc":"asc");return{after:Bn(a.after),cursor:typeof a.cursor=="string"?a.cursor:void 0,directions:s,index:t,partitionKey:typeof a.partitionKey=="string"?a.partitionKey:void 0,take:typeof a.take=="number"?a.take:void 0,table:e}},Wn=a=>{try{const e=JSON.parse(a);if(Array.isArray(e)&&typeof e[0]=="string"&&typeof e[1]=="string")return{index:e[1],table:e[0]}}catch{}},Hn=a=>{const e=a.changes;if(!Array.isArray(e))throw new f("BAD_REQUEST","applyCdc: `changes` must be an array");return{changes:e.map((t,s)=>{const r=t,{op:n}=r,i=typeof r.table=="string"?r.table:"",o=typeof r.id=="string"?r.id:"";if(i===""||o===""||n!=="insert"&&n!=="update"&&n!=="delete")throw new f("BAD_REQUEST",`applyCdc: changes[${String(s)}] must have a table, id, and op of insert|update|delete`);const c=r.doc;if(c!==void 0&&(typeof c!="object"||c===null||Array.isArray(c)))throw new f("BAD_REQUEST",`applyCdc: changes[${String(s)}].doc must be an object`);const d=c;if(d!==void 0&&typeof d._id=="string"&&d._id!==o)throw new f("BAD_REQUEST",`applyCdc: changes[${String(s)}].doc._id must match the entry id`);return{doc:d,id:o,op:n,seq:typeof r.seq=="number"?r.seq:0,table:i,ts:typeof r.ts=="number"?r.ts:0}})}},Kn=a=>{const e=t=>{const s=typeof t=="number"?t:Number(t);return Number.isFinite(s)&&s>=0?Math.floor(s):void 0};return{limit:e(a.limit),sinceSeq:e(a.sinceSeq)??0}},$=a=>a?{"x-d1-bookmark":a}:void 0,It=a=>{if(a)try{const e=JSON.parse(a);if(e&&typeof e=="object"&&!Array.isArray(e))return e}catch{}},jn=a=>{if(!a)return;const e=Number(a);return Number.isInteger(e)&&e>0?e:void 0},Gn=a=>{const e=new Set;for(const t of a){const s=us(t);s!==""&&e.add(s)}return e},Qn=a=>{if(a===void 0)return;const e=Number.parseInt(a,10);return Number.isFinite(e)&&e>0?e:void 0},zn=(a,e)=>a==="1"||a==="true"?!0:a==="0"||a==="false"?!1:e,Jn=a=>{if(a===void 0)return 1;const e=Number.parseFloat(a);return Number.isFinite(e)?Math.min(1,Math.max(0,e)):1},Xn=a=>a>=1?!0:a<=0?!1:Math.random()<a,Ee=a=>{if(!a)return;const[e,...t]=a.split(" ");if(e?.toLowerCase()!=="bearer")return;const s=t.join(" ").trim();return s.length>0?s:void 0};class S{static MAX_STREAMS_PER_SOCKET=8;static MAX_SUBSCRIPTIONS_PER_SOCKET=32;static GLOBAL_SHAPE_POLL_INTERVAL_MS=2e3;static GLOBAL_SHAPE_MAX_ROWS=5e4;static MAX_WHISPER_TOPICS_PER_SOCKET=64;static MAX_WHISPER_BYTES=4096;static WHISPER_RATE_BURST=50;static WHISPER_RATE_PER_SEC=25;static rootSizeWarned=!1;static resetRootSizeWarning(){S.rootSizeWarned=!1}static nextPollAlarmTarget(e,t,s,r){const n=[e>0?r+S.GLOBAL_SHAPE_POLL_INTERVAL_MS:void 0,t,s].filter(i=>i!==void 0).map(i=>Math.max(i,r));return n.length>0?Math.min(...n):void 0}state;env;reactiveCache;drizzleHandle;transactionDepth=0;currentRequestBookmark;currentResponseBookmark;currentRequestUserId;currentRequestIp;currentRequestTraceparent;currentRequestTrace;traceSampling=new Map;dispatchSpans=new Map;lastTelemetrySink;currentRequestMutationId;currentRequestClientId;currentRequestClientSeq;currentMutatorClass;mutationBookkeepingCommitted=!1;lastIdempotencyTrimAt=0;currentRequestIdentity;currentRequestSystem=!1;pendingChangedTables=void 0;pendingRefreshTables=void 0;refreshInFlight=!1;subMemos=new WeakMap;shapeMemos=new WeakMap;globalShapeSnapshots=new WeakMap;globalPollScheduled=!1;pokeSequence=0;whisperBuckets=new WeakMap;streamCancellers=new WeakMap;metrics={errors:0,requests:0,sinceMs:Date.now()};fanout={shapePoke:Ke(),whisper:Ke()};shardBinding;relay;usedIndexes=new Set;functionStats=new Map;logs=new Is;spans=new _a;metricSeries=new Mr;currentTracker;currentScannedTables;currentIndexHits;currentRequestReadTables;currentStmtSamples;currentRequestCacheHit;constructor(e,t,s={}){this.state=e,this.env=t,s.reactiveCache&&(this.reactiveCache=new Cs(s.reactiveCache));const r={buildShapeDiff:(n,i,o)=>this.buildShapeDiff(this.sql,n,i,o),computeOpLogShapeSeed:(n,i)=>this.computeOpLogShapeSeed(n,i),currentCdcEpoch:()=>this.currentCdcEpoch(),deliverWhisperLocal:(n,i,o)=>this.deliverWhisperLocal(n,i,o),doName:()=>this.state.id?.name,env:()=>this.env,getWebSockets:()=>this.state.getWebSockets(),maskMetadata:()=>this.maskMetadata(),nextPokeId:()=>(this.pokeSequence+=1,`poke-${String(this.pokeSequence)}`),readAttachment:n=>this.readAttachment(n),recordShapePokeFanout:(n,i,o)=>{this.fanout.shapePoke=he(this.fanout.shapePoke,n,i,o)},resolveShape:(n,i,o)=>this.resolveShape(n,i,o),rlsMetadata:()=>this.rlsMetadata(),shardBinding:()=>this.shardBinding,sql:()=>this.sql};this.relay=ca(r),this.armWebSocketKeepalive()}async fetch(e){const t=new URL(e.url);this.shardBinding=e.headers.get("x-lunora-shard-binding")??this.shardBinding;const s=await this.routeNonRpc(t,e);if(s!==void 0)return s;if(t.pathname!=="/rpc"||e.method!=="POST")return new Response("Not found",{status:404});let r;try{r=await e.json()}catch{return y({error:{code:"BAD_REQUEST",message:"invalid JSON body"}},400)}if(r.functionPath.startsWith(_))return this.handleAdminRpc(e,r.functionPath,r.args??{});this.currentRequestBookmark=e.headers.get("x-d1-bookmark")??void 0,this.currentResponseBookmark=void 0,this.currentRequestUserId=e.headers.get("x-lunora-userid")??void 0,this.currentRequestMutationId=e.headers.get("x-lunora-mutation-id")??void 0,this.currentRequestClientId=e.headers.get("x-lunora-client-id")??void 0,this.currentRequestClientSeq=jn(e.headers.get("x-lunora-client-seq")),this.currentMutatorClass=void 0,this.mutationBookkeepingCommitted=!1,this.currentRequestIdentity=It(e.headers.get("x-lunora-identity")),this.currentRequestIp=e.headers.get("x-lunora-client-ip")??void 0,this.currentRequestSystem=e.headers.get("x-lunora-system")==="1",this.currentRequestTraceparent=e.headers.get("traceparent")??void 0,this.currentRequestTrace=X(this.currentRequestTraceparent);const n=this.currentRequestTrace;this.traceSampling.set(n.traceId,{keepErrors:e.headers.get("x-lunora-sample-errors")!=="0",sampled:Yt(this.currentRequestTraceparent)?.sampled??!0}),this.currentRequestReadTables=void 0,this.currentRequestCacheHit=void 0,this.metrics.requests+=1;const i=Date.now();this.currentScannedTables=new Set,this.currentIndexHits=new Set,this.currentStmtSamples=[];let o;try{if(r.functionPath.startsWith(gs)){const b=await this.runRelationFanoutRead(r.functionPath,r.args??{});return y(b,200,$(this.currentResponseBookmark))}const c=this.isCustomMutator(r.functionPath)?this.classifyClientMutation():void 0;this.currentMutatorClass=c;const d=this.rejectNonNextMutation(r.functionPath,c,i);if(d!==void 0)return d;const u=this.readIdempotentResult(this.currentRequestMutationId);if(u!==void 0)return this.respondFromIdempotencyCache(r.functionPath,i,c,u.value);const l=await this.handleRpc(r.functionPath,P(r.args??{}));this.recordPostDispatchBookkeeping(l,c),c?.kind==="next"&&this.advanceClientMutationWatermark();const m=Date.now()-i;this.recordFunctionCall(r.functionPath,m,void 0,this.currentScannedTables,this.currentIndexHits),this.flushStmtSamples();const p=[...this.pendingChangedTables??[]];this.recordRequestLog(r.functionPath,r.args??{},m,"ok",p),this.maybeWarnRootSize();const g=this.buildDispatchResponse(c,R(l));return await this.flushChangedTables(),g}catch(c){this.metrics.errors+=1,o={thrown:c};const d=Date.now()-i,u=c instanceof Error?c.message:String(c),l=c instanceof tr&&c.kind==="occ";return c?.code!=="FUNCTION_NOT_FOUND"&&this.recordFunctionCall(r.functionPath,d,u,this.currentScannedTables,this.currentIndexHits,l),this.flushStmtSamples(),this.recordRequestLog(r.functionPath,r.args??{},d,"error",[...this.pendingChangedTables??[]],u),this.logs.push({functionPath:r.functionPath,level:"error",message:u,timestamp:Date.now()}),this.recordChangedTable(N),await this.flushChangedTables(),this.errorToResponse(c)}finally{const c=this.dispatchSpans.get(A(n));if((this.spans.hasTrace(n.traceId)||c?.collector!==void 0)&&this.recordDispatchRootSpan(r.functionPath,i,o,n),this.dispatchSpans.delete(A(n)),c?.sink?.flush)try{c.sink.flush({waitUntil:this.state.waitUntil?.bind(this.state)})}catch{}this.flushSampledOutTrace(n,o!==void 0),this.traceSampling.delete(n.traceId),this.currentRequestTrace=void 0,this.currentRequestBookmark=void 0,this.currentResponseBookmark=void 0,this.currentRequestUserId=void 0,this.currentRequestMutationId=void 0,this.currentRequestClientId=void 0,this.currentRequestClientSeq=void 0,this.currentMutatorClass=void 0,this.mutationBookkeepingCommitted=!1,this.currentRequestIdentity=void 0,this.currentRequestIp=void 0,this.currentRequestSystem=!1,this.currentRequestTraceparent=void 0,this.currentScannedTables=void 0,this.currentIndexHits=void 0,this.currentRequestReadTables=void 0,this.currentRequestCacheHit=void 0,this.currentStmtSamples=void 0}}async webSocketMessage(e,t){return this.handleWebSocketMessage(e,t)}async webSocketClose(e,t,s,r){const n=this.readAttachment(e);n.connectionId!==void 0&&await this.dispatchLifecycle("disconnect",this.lifecycleInfo(n));const i=this.streamCancellers.get(e);if(i){for(const o of i.values())o.abort();this.streamCancellers.delete(e)}if(this.subMemos.delete(e),this.shapeMemos.delete(e),this.globalShapeSnapshots.delete(e),n.connectionId!==void 0)try{Fs(this.sql,n.connectionId)}catch{}e.serializeAttachment?.(void 0),await this.relay?.announceDrain(e)}webSocketError(e,t){}async alarm(){return this.withTriggerTrace("alarm",async()=>this.handleAlarmBody())}lifecycleHookPaths(e){return[]}async dispatchLifecycle(e,t){for(const s of this.lifecycleHookPaths(e))try{await this.withRequestIdentity(t.userId,t.identity,()=>this.withSystemDispatch(()=>this.handleRpc(s,t.event)))}catch(r){this.logs.push({functionPath:s,level:"error",message:r instanceof Error?r.message:String(r),timestamp:Date.now()})}}runRelationFanoutRead(e,t){throw new f("NOT_IMPLEMENTED","__lunora_relation__: no schema bound — the base ShardDO cannot serve cross-shard relation reads",{status:500})}get sql(){const e=this.state.storage.sql,t=this.currentStmtSamples;if(t===void 0)return e;const s=e.exec;if(typeof s!="function")return e;const r=(n,...i)=>{const o=Date.now(),c=s.call(e,n,...i);if(c!==null&&typeof c=="object"){const d=c;if(typeof d.toArray=="function"){const u=d.toArray.bind(d);d.toArray=()=>{const l=u(),m=Date.now()-o;return t.push([n,m,l.length,0]),l}}if(typeof d.one=="function"){const u=d.one.bind(d);d.one=()=>{const l=u(),m=Date.now()-o;return t.push([n,m,1,0]),l}}if(typeof d.toArray!="function"&&typeof d.one!="function"){const u=Date.now()-o;t.push([n,u,0,0])}}else{const d=Date.now()-o;t.push([n,d,0,0])}return c};return new Proxy(e,{get(n,i){return i==="exec"?r:Reflect.get(n,i,n)}})}get db(){return this.drizzleHandle?this.drizzleHandle:(this.drizzleHandle=zt(this.state.storage,{logger:!1}),this.drizzleHandle)}async runInTransaction(e){if(this.transactionDepth>0)throw new f("NESTED_TRANSACTION","nested transactions are not supported in SQLite-in-DO",{status:500});const t=this.state.storage.sql;if(!t||typeof t.exec!="function")throw new f("SQL_UNAVAILABLE","storage.sql is not available on this ShardDO state",{status:500});const s=this.state.storage,r=async()=>{this.transactionDepth=1;try{return typeof s?.transaction=="function"?await s.transaction(async()=>e()):await e()}finally{this.transactionDepth=0}};return typeof this.state.blockConcurrencyWhile=="function"?this.state.blockConcurrencyWhile(r):r()}getInboundBookmark(){return this.currentRequestBookmark}setOutboundBookmark(e){this.currentResponseBookmark=e}getCurrentUserId(){return this.currentRequestUserId}getCurrentIp(){return this.currentRequestIp}getCurrentTraceparent(){return this.currentRequestTraceparent}getCurrentTrace(){return this.currentRequestTrace}getCurrentIdentity(){return this.currentRequestIdentity}isSystemDispatch(){return this.currentRequestSystem}runShardDataMigration(e){return Promise.reject(new f("MIGRATION_NOT_FOUND",`data migration "${e.id}" is not registered`,{status:404}))}ensureMigrated(){}tableRefs(e){}tableIndexes(e){return[]}tableColumns(e){return[]}storageColumns(){return{}}advisories(){return[]}rlsMetadata(){return{policies:[],roles:[]}}maskMetadata(){return{columns:[]}}storageRulesMetadata(){return{rules:[]}}studioFeatures(){return{analytics:!1,auth:!1,containers:!1,flags:!1,kv:!1,mail:!1,notifications:!1,payments:!1,queues:!1,scheduler:!1,storage:!1,vectors:!1,workflows:!1}}evaluateFlags(e){return Promise.resolve({configured:!1,flags:[]})}runFlagSubscriptionRead(e,t,s){return Promise.resolve(null)}queuesMetadata(){return{queues:[]}}workflowsMetadata(){return{workflows:[]}}runtimeAdvisories(){const e=new Set([...this.usedIndexes].map(s=>s.slice(0,s.indexOf(":")))),t=[];for(const s of e)for(const r of this.tableIndexes(s))r.type==="vector"||this.usedIndexes.has(`${s}:${r.name}`)||t.push({cacheKey:`unused_index:${s}:${r.name}`,categories:["PERFORMANCE"],description:"A declared index has not been exercised by any query since this shard instance started. An unused index costs storage and is maintained on every write for no read benefit.",detail:`Index "${r.name}" on table "${s}" has not been used since this instance woke, though other indexes on "${s}" have — it may be redundant.`,facing:"INTERNAL",level:"INFO",metadata:{index:r.name,indexKind:r.type,since:"instance-woke",table:s},name:"unused_index",remediation:"Confirm over a representative window, then drop the index if no query needs it.",title:"Unused index"});return t}runShardExport(e){return Promise.resolve([])}runShardImport(e){return Promise.resolve({conflicts:0,errors:[],inserted:{}})}runShardWrite(e){return Promise.reject(new f("UNKNOWN_TABLE",`unknown table: ${e.table}`,{status:404}))}deleteRowThroughWriter(e,t){return Promise.reject(new f("UNKNOWN_TABLE",`unknown table: ${e}`,{status:404}))}async runShardBulkDelete(e){const t=Math.min(Math.max(Math.trunc(e.limit??Rt),1),Rt),{hasMore:s,ids:r}=Ss(this.sql,{filters:e.filters,limit:t,search:e.search,table:e.table});let n=0;for(const i of r)await this.deleteRowThroughWriter(e.table,i),n+=1;return{deleted:n,hasMore:s}}runShardRankBefore(e){return Promise.reject(new f("NOT_IMPLEMENTED","rankBefore is not implemented in base ShardDO",{status:500}))}runShardRankPage(e){return Promise.reject(new f("NOT_IMPLEMENTED","rankPage is not implemented in base ShardDO",{status:500}))}runShardCdcSync(e){const t=this.sql;return t.exec("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?",Xe).toArray().length>0?fe(t,{limit:e.limit,sinceSeq:e.sinceSeq}):{changes:[],cursor:e.sinceSeq}}currentCdcCursor(){return this.cdcEnabled()?Ye(this.sql):void 0}currentCdcEpoch(){return this.cdcEnabled()?Ve(this.sql):void 0}evaluateResume(e,t,s){const r=this.sql;if(!this.cdcEnabled())return{cursor:void 0,epoch:void 0,resumable:!1};const n=Ye(r),i=Ve(r);if(s!==i)return{cursor:n,epoch:i,resumable:!1};if(e>n)return{cursor:n,epoch:i,resumable:!1};if(e===n)return{cursor:n,epoch:i,resumable:!0};const o=Ze(r);if(o===void 0||o>e+1)return{cursor:n,epoch:i,resumable:!1};if(t.size===0)return{cursor:n,epoch:i,resumable:!1};const{changes:c}=fe(r,{limit:wt,sinceSeq:e});if(c.length>=wt)return{cursor:n,epoch:i,resumable:!1};const d=c.some(u=>t.has(u.table));return{cursor:n,epoch:i,resumable:!d}}readIdempotentResult(e){if(e!==void 0)try{const t=Ws(this.sql,this.currentRequestUserId??"",e);return t===void 0?void 0:{value:JSON.parse(t.resultJson)}}catch{return}}persistIdempotentResult(e){if(this.currentRequestMutationId===void 0)return;const t=Date.now();try{Hs(this.sql,this.currentRequestUserId??"",this.currentRequestMutationId,JSON.stringify(R(e)),t),t-this.lastIdempotencyTrimAt>cn&&(Ks(this.sql,t-on),this.lastIdempotencyTrimAt=t)}catch{}}isCustomMutator(e){return!1}classifyClientMutation(){const e=this.currentRequestClientId,t=this.currentRequestClientSeq;if(e===void 0||t===void 0)return;const s=this.currentRequestUserId??"";let r;try{r=pe(this.sql,s,e)}catch{try{js(this.sql),r=pe(this.sql,s,e)}catch{return}}const n=r+1;return t<=r?{expected:n,kind:"already"}:t===n?{expected:n,kind:"next"}:{expected:n,kind:"gap"}}rejectNonNextMutation(e,t,s){if(!(t===void 0||t.kind==="next"))return this.recordFunctionCall(e,Date.now()-s,void 0,this.currentScannedTables,this.currentIndexHits),t.kind==="already"?y({lastMutationId:t.expected-1,result:null},200,$(this.currentResponseBookmark)):y({error:{code:"OUT_OF_ORDER",expectedMutationId:t.expected,message:`out-of-order mutation; expected sequence ${String(t.expected)}`}},409,$(this.currentResponseBookmark))}respondFromIdempotencyCache(e,t,s,r){if(this.recordFunctionCall(e,Date.now()-t,void 0,this.currentScannedTables,this.currentIndexHits),s?.kind==="next")return this.advanceClientMutationWatermark(),this.buildDispatchResponse(s,r);const n=this.mutationCommitCursor();return y(n===void 0?{result:r}:{commitCursor:n,result:r},200,$(this.currentResponseBookmark))}mutationCommitCursor(){return this.currentRequestMutationId===void 0?void 0:this.currentCdcCursor()}buildDispatchResponse(e,t){if(e?.kind==="next")return y({lastMutationId:this.currentRequestClientSeq,result:t},200,$(this.currentResponseBookmark));const s=this.mutationCommitCursor();return y(s===void 0?{result:t}:{commitCursor:s,result:t},200,$(this.currentResponseBookmark))}commitMutationBookkeeping(e){this.persistIdempotentResult(e),this.currentMutatorClass?.kind==="next"&&this.advanceClientMutationWatermark({strict:!0}),this.mutationBookkeepingCommitted=!0}recordPostDispatchBookkeeping(e,t){this.mutationBookkeepingCommitted||(this.persistIdempotentResult(e),t?.kind==="next"&&this.advanceClientMutationWatermark())}advanceClientMutationWatermark(e){const t=this.currentRequestClientId,s=this.currentRequestClientSeq;if(!(t===void 0||s===void 0))try{Gs(this.sql,this.currentRequestUserId??"",t,s)}catch(r){if(e?.strict)throw r}}runShardApplyCdc(e){return Promise.reject(new f("NOT_IMPLEMENTED","applyCdc is not implemented in base ShardDO",{status:500}))}subscribe(e,t,s){const r=this.readAttachment(e);if(Object.keys(r.subs).length>=S.MAX_SUBSCRIPTIONS_PER_SOCKET)return"too_many";r.subs[t]=s;try{e.serializeAttachment?.(r)}catch{return delete r.subs[t],"serialize_failed"}return"ok"}unsubscribe(e,t){const s=this.readAttachment(e),r=s.subs[t];delete s.subs[t];try{e.serializeAttachment?.(s)}catch{r!==void 0&&(s.subs[t]=r);return}this.subMemos.get(e)?.delete(t)}shapeSubscribe(e,t,s){const r=this.readAttachment(e),n=r.shapes??{};if(Object.keys(r.subs).length+Object.keys(n).length>=S.MAX_SUBSCRIPTIONS_PER_SOCKET)return"too_many";n[t]=s,r.shapes=n;try{e.serializeAttachment?.(r)}catch{return delete r.shapes[t],"serialize_failed"}return"ok"}shapeUnsubscribe(e,t){const s=this.readAttachment(e),{shapes:r}=s;if(!r)return;const n=r[t];delete r[t];try{e.serializeAttachment?.(s)}catch{n!==void 0&&(r[t]=n);return}if(this.shapeMemos.get(e)?.delete(t),this.globalShapeSnapshots.get(e)?.delete(t),s.connectionId!==void 0)try{Qs(this.sql,s.connectionId,t)}catch{}}matchesSubscription(e,t){if(e.table!==t.table)return!1;const{args:s}=e;if(!s)return!0;const{row:r}=t;if(!r)return!0;for(const[n,i]of Object.entries(s))if(r[n]!==i)return!1;return!0}broadcastDelta(e){const t=this.state.getWebSockets(),s=JSON.stringify(e);for(const r of t){const n=this.readAttachment(r);for(const[i,o]of Object.entries(n.subs))this.matchesSubscription(o,e)&&D(r,`{"type":"delta","id":${JSON.stringify(i)},"delta":${s}}`)}}executeSubscription(e,t,s){return Promise.resolve(null)}resolveShape(e,t,s){}isShapeRelayUniform(e,t){return this.relay?.isShapeRelayUniform(e,t)??!1}readGlobalShapeRows(e,t){return Promise.resolve([])}pollExternalSources(){return Promise.resolve(void 0)}scheduleSourcePoll(){return this.scheduleGlobalPoll()}ttlSweeps(){return[]}async pollTtlSweeps(){const e=this.ttlSweeps();if(e.length===0)return;const t=this.sql,s=Date.now();for(const r of e){let n=0,i=!0;for(;i&&n<hn;){const o=sr(t,r,s,ln);for(const c of o.ids)await this.deleteRowThroughWriter(r.table,c);i=o.hasMore,n+=1}}return s+pn}scheduleTtlSweep(){return this.scheduleGlobalPoll()}currentShardKey(){return this.state.id?.name??ee}recordExternalSourceError(e,t){this.recordShapeError(`source:${e}`,t)}executeStream(e,t){return null}async runCachedQuery(e,t,s){if(!this.reactiveCache)return s();const r=this.currentTracker,n=ds();this.currentTracker=n;const i=this.reactiveCache.stats().hits,o=this.getCurrentUserId(),c=this.getCurrentIdentity(),d=o===void 0&&c===void 0?null:Ne({claims:c??null,userId:o??null});try{const u=await this.reactiveCache.run(Qe(e,t,d),n.collect(),s);return this.currentRequestCacheHit=this.reactiveCache.stats().hits>i,this.currentRequestReadTables=Gn(n.collect()),u}finally{this.currentTracker=r}}getCtxDbReadHook(){return(e,t)=>{this.currentTracker?.recordRead(e,t??He),t===He&&this.currentScannedTables?.add(e)}}getCtxDbIndexUseHook(){return(e,t)=>{this.usedIndexes.add(`${e}:${t}`),this.currentIndexHits?.add(JSON.stringify([e,t]))}}recordChangedTable(e){this.pendingChangedTables??=new Set,this.pendingChangedTables.add(e)}async flushMigrationProgress(){this.recordChangedTable(os),await this.flushChangedTables()}recordUserLog(e,t,s,r,n,i,o,c){const d=c??this.currentRequestTrace,u={args:s,...o===void 0?{}:{eventName:o},fields:n,functionPath:e,level:t,message:r,shardKey:this.state.id?.name,spanId:d?.rootSpanId,traceId:d?.traceId,ts:Date.now(),userId:this.getCurrentUserId()};this.logs.push({fields:n,functionPath:e,level:t,message:r,timestamp:u.ts});try{ya(u)}catch{}if(i?.onLog)try{i.onLog(u,{waitUntil:this.state.waitUntil?.bind(this.state)})}catch{}}makeLogger(e,t,s){const r=(n,i)=>{const{fields:o,message:c}=ma(i,s);this.recordUserLog(e,n,i,c,o,t)};return{debug:(...n)=>{r("debug",n)},error:(...n)=>{r("error",n)},event:(n,i)=>{this.recordUserLog(e,"info",[n],n,s?{...s,...i}:i,t,n)},fatal:(...n)=>{r("fatal",n)},info:(...n)=>{r("info",n)},log:(...n)=>{r("log",n)},trace:(...n)=>{r("trace",n)},warn:(...n)=>{r("warn",n)},with:n=>this.makeLogger(e,t,s?{...s,...n}:n)}}makeTracer(e,t,s){const r=s??X(void 0);return Vt({anchor:r,fuseCloudflareSpans:t?.fuseCloudflareTraces===!0,functionPath:e,record:n=>{this.recordSpan(n,t,r.sampled)},resolveCloudflareTracing:rn,shardKey:this.state.id?.name,userId:()=>this.getCurrentUserId()})}resolveDispatchAnchor(e){return(e?void 0:this.getCurrentTrace())??X(void 0)}instrumentDb(e,t,s,r){const n=r===void 0?"off":r.instrumentDatabase??"summary";return n==="off"?e:Tr(e,{anchor:s,functionPath:t,mode:n,record:i=>{this.recordSpan(i,r,s.sampled)},shardKey:this.state.id?.name,tally:this.dispatchTally(s),userId:()=>this.getCurrentUserId()})}makeFetch(e,t,s){const r=(n,i)=>globalThis.fetch(n,i);return s===void 0||s.traceFetch===!1?r:Zt({anchor:t,functionPath:e,...typeof s.traceFetch=="object"&&s.traceFetch.propagate!==void 0?{propagate:s.traceFetch.propagate}:{},record:n=>{this.recordSpan(n,s,t.sampled)},shardKey:this.state.id?.name,userId:()=>this.getCurrentUserId()},r)}makeDispatchSpan(e,t){this.lastTelemetrySink=t??this.lastTelemetrySink,t!==void 0&&(se(this.dispatchSpans,Se),this.dispatchSpans.set(A(e),this.dispatchSpans.get(A(e))??{sink:t}));const s=()=>{se(this.dispatchSpans,Se);const r=A(e),n=this.dispatchSpans.get(r)??{sink:t};return n.collector??=ss({spanId:e.rootSpanId,traceId:e.traceId}),this.dispatchSpans.set(r,n),n.collector};return{addEvent:(r,n)=>{s().handle.addEvent(r,n)},spanContext:()=>({spanId:e.rootSpanId,traceId:e.traceId}),addLink:r=>{s().handle.addLink(r)},recordEvaluation:r=>{s().handle.recordEvaluation(r)},recordException:r=>{s().handle.recordException(r)},setAttribute:(r,n)=>{s().handle.setAttribute(r,n)},setAttributes:r=>{s().handle.setAttributes(r)}}}makeMetrics(e,t){return es({functionPath:e,record:s=>{this.recordMetric(s,t)},shardKey:this.state.id?.name})}recordMetric(e,t){const s=this.currentRequestTrace?.traceId,r=s===void 0?e:{...e,traceId:s},n=o=>{try{o()}catch{}};n(()=>{this.metricSeries.push(r)});const i=t?.metricHistory;if(i!==void 0&&i!==!1){const o=this.state.storage.sql,c=typeof i=="object"?i:{};n(()=>{xr(o,r,s,c)})}t?.onMetric&&n(()=>t.onMetric?.(r,{waitUntil:this.state.waitUntil?.bind(this.state)}))}async handleWebSocketMessage(e,t){if(this.isSocketExpired(e)){this.dropExpiredSocket(e);return}const s=typeof t=="string"?t:new TextDecoder().decode(t);let r;try{r=JSON.parse(s)}catch{e.send(JSON.stringify({message:"invalid envelope",type:"error"}));return}if(r.type==="connect"){const n=this.readAttachment(e);if(n.connected===!0)return;r.context!==void 0&&(n.context=r.context),r.clientId!==void 0&&(n.clientId=r.clientId),n.connected=!0;try{e.serializeAttachment?.(n)}catch{}await this.dispatchLifecycle("connect",this.lifecycleInfo(n));return}if(r.type==="subscribe"&&r.query){const{functionPath:n}=r.query,i=n?.startsWith(_)===!0;if(i&&this.readAttachment(e).admin!==!0){e.send(JSON.stringify({id:r.id,message:"admin subscription requires admin authorization",type:"error"}));return}let o;try{o=r.query.args===void 0?r.query:{...r.query,args:P(r.query.args)}}catch{try{e.send(JSON.stringify({code:"BAD_SUBSCRIPTION_ARGS",error:{code:"BAD_SUBSCRIPTION_ARGS",message:"subscription args failed wire decoding"},id:r.id,type:"error"}))}catch{}return}const c=this.subscribe(e,r.id,o);if(c!=="ok"){const d=c==="too_many"?"TOO_MANY_SUBSCRIPTIONS":"SUBSCRIPTION_PERSIST_FAILED",u=c==="too_many"?`subscription cap of ${String(S.MAX_SUBSCRIPTIONS_PER_SOCKET)} reached on this socket`:"failed to persist subscription attachment";try{e.send(JSON.stringify({code:d,error:{code:d,message:u},id:r.id,type:"error"}))}catch{}return}e.send(JSON.stringify({id:r.id,type:"ack"})),n&&await this.seedSubscription(e,r.id,o,n,i);return}if(r.type==="shape_subscribe"&&r.shape){let n;try{n=r.shape.args===void 0?void 0:P(r.shape.args)}catch{this.sendShapeSubscribeError(e,r.id,"BAD_SUBSCRIPTION_ARGS","shape args failed wire decoding");return}await this.handleShapeSubscribe(e,r.id,{args:n,name:r.shape.name,sinceEpoch:r.sinceEpoch,sinceSeq:r.sinceCheckpoint});return}if(r.type==="shape_unsubscribe"){this.shapeUnsubscribe(e,r.id),e.send(JSON.stringify({id:r.id,type:"ack"}));return}if(r.type==="stream"&&r.query?.functionPath){if(r.query.functionPath.startsWith(_)){e.send(JSON.stringify({id:r.id,message:"streams must be public",type:"error"}));return}this.handleStream(e,r.id,r.query.functionPath,P(r.query.args??{})).catch(()=>{});return}if(r.type==="whisper_subscribe"||r.type==="whisper_unsubscribe"){if(typeof r.topic=="string"&&r.topic.length>0){const n=r.type==="whisper_subscribe";this.setWhisperMembership(e,r.topic,n),n&&await this.relay?.announce()}return}if(r.type==="whisper"){typeof r.topic=="string"&&r.topic.length>0&&await this.broadcastWhisper(e,r.topic,r.data);return}if(r.type==="unsubscribe"){const n=this.streamCancellers.get(e),i=n?.get(r.id);i&&(i.abort(),n?.delete(r.id)),this.unsubscribe(e,r.id),e.send(JSON.stringify({id:r.id,type:"ack"}))}}async handleAlarmBody(){this.globalPollScheduled=!1;let e;try{e=await this.pollGlobalShapes()}catch(n){this.recordShapeError("shape:poll",n),e=1}let t;try{t=await this.pollExternalSources()}catch(n){this.recordShapeError("source:poll",n),t=Date.now()+S.GLOBAL_SHAPE_POLL_INTERVAL_MS}let s;try{s=await this.pollTtlSweeps()}catch(n){this.recordShapeError("ttl:sweep",n),s=Date.now()+S.GLOBAL_SHAPE_POLL_INTERVAL_MS}await this.flushChangedTables();const r=S.nextPollAlarmTarget(e,t,s,Date.now());r!==void 0&&await this.scheduleGlobalPoll(r)}dispatchTally(e){se(this.dispatchSpans,Se);const t=A(e),s=this.dispatchSpans.get(t)??{};return s.dbTally??=Rr(),this.dispatchSpans.set(t,s),s.dbTally}async withTriggerTrace(e,t){const s=X(void 0),r=Date.now(),n=this.currentRequestTrace===void 0;n&&(this.currentRequestTrace=s);let i;try{return await t()}catch(o){throw i={thrown:o},o}finally{n&&this.currentRequestTrace===s&&(this.currentRequestTrace=void 0),(this.spans.hasTrace(s.traceId)||this.dispatchSpans.get(A(s))?.collector!==void 0)&&this.recordDispatchRootSpan(e,r,i,s),this.dispatchSpans.delete(A(s)),this.flushTelemetry()}}flushTelemetry(){try{this.lastTelemetrySink?.flush?.({waitUntil:this.state.waitUntil?.bind(this.state)})}catch{}}recordDispatchRootSpan(e,t,s,r){const n=this.dispatchSpans.get(A(r)),i=Date.now()-t,o=n?.dbTally===void 0||n.dbTally.calls===0?void 0:Ar(n.dbTally),c=n?.collector===void 0?void 0:{...n.collector.collected,attributes:{...o,...n.collector.collected.attributes}};try{this.spans.push(ts({anchor:r,...c===void 0?{}:{collected:c},durationMs:i,failure:s,functionPath:e,shardKey:this.state.id?.name,startTs:t,userId:this.getCurrentUserId()}))}catch{}n?.collector!==void 0&&this.exportWideEvent(e,i,s,r,{collected:c??n.collector.collected,sink:n.sink})}exportWideEvent(e,t,s,r,n){try{const{attributes:i}=n.collected;this.recordUserLog(e,s===void 0?"info":"error",[be],be,{...i,[le.durationMs]:t,[le.functionPath]:e,[le.ok]:s===void 0},n.sink,be,r)}catch{}}recordSpan(e,t,s){try{this.spans.push(e)}catch{}if(!t?.onSpan)return;const r=this.traceSampling.get(e.traceId);if(r!==void 0){if(!r.sampled){if(r.sink=t,e.dispatch!==!0){const n=r.held??(r.held=[]);n.push(e),n.length>qn&&n.shift()}return}this.emitSpan(e,t);return}s!==!1&&this.emitSpan(e,t)}emitSpan(e,t){if(t.onSpan)try{t.onSpan(e,{waitUntil:this.state.waitUntil?.bind(this.state)})}catch{}}flushSampledOutTrace(e,t){const s=this.traceSampling.get(e.traceId);if(!s||s.sampled||!s.keepErrors)return;const{held:r,sink:n}=s;if(!(!n?.onSpan||r===void 0||r.length===0||!(t||r.some(i=>!i.ok))))for(const i of r)this.emitSpan(i,n)}lifecycleInfo(e){return{event:{connectionId:e.connectionId??"",shardKey:this.state.id?.name??ee,userId:e.userId??null,...e.context===void 0?{}:{context:e.context}},identity:e.identity,userId:e.userId}}async withSystemDispatch(e){const t=this.currentRequestSystem;this.currentRequestSystem=!0;try{return await e()}finally{this.currentRequestSystem=t}}collectMetrics(){const e=this.state.storage.sql?.databaseSize;let{requests:t}=this.metrics,{errors:s}=this.metrics;try{const i=ls(this.state.storage.sql);t=i.requests,s=i.errors}catch{}let r=[];try{r=hs(this.state.storage.sql)}catch{}let n=[];try{n=Kr(this.state.storage.sql)}catch{}return{cache:this.reactiveCache?this.reactiveCache.stats():null,databaseSize:typeof e=="number"?e:null,errors:s,functions:this.collectFunctionStats().functions,history:this.collectFunctionMetricBuckets(),indexHits:r,queryStats:n,requests:t,shard:this.state.id?.name??ee,sinceMs:this.metrics.sinceMs,uptimeMs:Date.now()-this.metrics.sinceMs}}recordFunctionCall(e,t,s,r,n,i=!1){const o=Date.now(),c=r?[...r]:[],d=n?[...n].map(m=>Wn(m)).filter(m=>m!==void 0):[];try{ps(this.state.storage.sql,{conflicted:i,durationMs:t,errored:s!==void 0,errorMessage:s,indexHits:d,path:e,scannedTables:c,ts:o})}catch{}const u=this.functionStats.get(e),l=u??{calls:0,conflicts:0,errors:0,lastCalledAt:o,lastErrorAt:null,lastErrorMessage:null,maxDurationMs:0,path:e,scannedTables:[],scans:0,totalDurationMs:0};l.calls+=1,l.totalDurationMs+=t,l.maxDurationMs=Math.max(l.maxDurationMs,t),l.lastCalledAt=o,c.length>0&&(l.scans+=c.length,fs(l.scannedTables,c)),s!==void 0&&(l.errors+=1,l.lastErrorAt=o,l.lastErrorMessage=s),i&&(l.conflicts+=1),u===void 0&&this.functionStats.set(e,l)}flushStmtSamples(){const e=this.currentStmtSamples;if(!(!e||e.length===0))try{const t=this.state.storage.sql;for(const[s,r,n,i]of e)try{Hr(t,s,r,n,i)}catch{}}catch{}}collectFunctionStats(){try{return{functions:ms(this.state.storage.sql),sinceMs:this.metrics.sinceMs}}catch{return{functions:[...this.functionStats.values()].toSorted((e,t)=>t.lastCalledAt-e.lastCalledAt),sinceMs:this.metrics.sinceMs}}}collectFunctionMetricBuckets(){try{return ys(this.state.storage.sql)}catch{return[]}}maybeWarnRootSize(){if(S.rootSizeWarned||this.state.id?.name!==ee)return;const e=this.state.storage.sql?.databaseSize;typeof e!="number"||e<nn||(S.rootSizeWarned=!0,console.warn(`[@lunora/do] __root__ Durable Object SQLite size is ${String(e)} bytes (>= 1 GiB, 10% of the 10 GiB per-DO ceiling). Plan a \`.shardBy()\` migration before you hit the wall. See https://lunora.sh/docs/concepts/sharding for guidance.`))}errorToResponse(e){const{body:t,redacted:s,status:r}=q(e,{encodeData:R,fallbackCode:"RPC_FAILED",redactedMessage:"internal error"});return s&&console.error("[@lunora/do] internal error:",e),y({error:t},r)}async handleBatchRpc(e){let t;try{t=await e.json()}catch{return y({error:{code:"BAD_REQUEST",message:"invalid JSON body"}},400)}if(!Array.isArray(t.calls))return y({error:{code:"BAD_REQUEST",message:"batch `calls` must be an array"}},400);if(t.calls.length>et)return y({error:{code:"BAD_REQUEST",message:`batch exceeds the ${String(et)}-call limit`}},400);const s=[];let r;for(const n of t.calls){const i=await this.dispatchBatchEntry(e,n);i.bookmark!==void 0&&(r=i.bookmark),s.push({body:i.body,id:i.id,status:i.status})}return y({results:s},200,$(r))}async dispatchBatchEntry(e,t){try{const s=await this.fetch(mr(e,t));return{body:await s.json(),bookmark:s.headers.get("x-d1-bookmark")??void 0,id:t.id,status:s.status}}catch(s){const{body:r,status:n}=q(s,{fallbackCode:"BATCH_ENTRY_FAILED"});return{body:{error:r},bookmark:void 0,id:t?.id,status:n}}}async handleAdminRpc(e,t,s){if(!this.isAdminAuthorized(e))return y({error:{code:"ADMIN_FORBIDDEN",message:"admin introspection is disabled or the bearer token is invalid"}},403);try{const r=this.readAdminOp(t,s);if(r)return y({result:r.result},200);if(t===h.runMigration){const i=un(s),o=await this.runShardDataMigration(i);return await this.flushChangedTables(),this.recordAudit("runMigration",{id:i.id,detail:{changed:o.changed,direction:o.direction,dryRun:o.dryRun,processed:o.processed}}),y({result:o},200)}if(t===h.exportShard){const i=rs(s),o=await this.runShardExport({batchSize:i.batchSize,tables:i.tables});return y({result:{rows:o}},200)}if(t===h.importShard){const i=as(s),o=await this.runShardImport({rows:i.rows,startLine:i.startLine});return await this.flushChangedTables(),this.recordAudit("importShard",{detail:{conflicts:o.conflicts,errors:o.errors.length,inserted:o.inserted}}),y({result:o},200)}if(t===h.writeRow){const i=fn(s),o=await this.runShardWrite(i);return await this.flushChangedTables(),this.recordAudit("writeRow",{table:i.table,id:o.id??i.id,detail:{op:o.op}}),y({result:o},200)}if(t===h.deleteRows){const i=_n(s),o=await this.runShardBulkDelete(i);return await this.flushChangedTables(),this.recordAudit("deleteRows",{table:i.table,detail:{deleted:o.deleted,hasMore:o.hasMore}}),y({result:o},200)}if(t===h.clearTable){const i=In(s),o=await this.runShardBulkDelete(i);return await this.flushChangedTables(),this.recordAudit("clearTable",{table:i.table,detail:{deleted:o.deleted,hasMore:o.hasMore}}),y({result:o},200)}if(t===h.rankBefore){const i=await this.runShardRankBefore(Un(s));return y({result:i},200)}if(t===h.rankPage){const i=await this.runShardRankPage(Fn(s));return y({result:i},200)}if(t===h.cdcSync){const i=this.runShardCdcSync(Kn(s));return y({result:i},200)}if(t===h.applyCdc){const i=await this.runShardApplyCdc(Hn(s));return await this.flushChangedTables(),this.recordAudit("applyCdc",{detail:{applied:i.applied}}),y({result:i},200)}return t===h.runAs?this.handleRunAs(s):await this.handleExtraAdminOp(t,s)||y({error:{code:"UNKNOWN_ADMIN_OP",message:`unknown admin op: ${t}`}},404)}catch(r){return this.errorToResponse(r)}}async handleExtraAdminOp(e,t){if(e===h.recordAuthEvent)return this.handleRecordAuthEvent(t);if(e===h.recordContainerEvent)return this.handleRecordContainerEvent(t);if(e===h.recordMail)return this.handleRecordMail(t);if(e===h.clearCapturedMail)return this.handleClearCapturedMail();if(e===h.sendTestMail)return this.handleSendTestMail(t);if(e===h.recordQueueMessage)return this.handleRecordQueueMessage(t);if(e===h.clearQueueMessages)return this.handleClearQueueMessages();if(e===h.sendQueueMessage)return this.handleSendQueueMessage(t);if(e===h.replayQueueMessage)return this.handleReplayQueueMessage(t);if(e===h.createWorkflowInstance)return this.handleCreateWorkflowInstance(t);if(e===h.getWorkflowInstanceStatus)return this.handleGetWorkflowInstanceStatus(t);if(e===h.listFlags)return this.handleListFlags(t);if(e===h.explainIssue)return this.handleExplainIssue(t);const s=this.aiAdminHandlers()[e];if(s!==void 0)return s(t);const r=await this.handleIssueTriageOp(e,t);return r!==void 0?r:this.handlePitrAdminOp(e,t)}async handleIssueTriageOp(e,t){const s=this.parseIssueTriagePatch(e,t);if(s===void 0)return;const r=gn(t),n=typeof t.updatedBy=="string"?t.updatedBy:void 0,i=this.state.storage.sql,o=kr(i,r,s,Date.now(),n);return this.recordChangedTable(j),await this.flushChangedTables(),this.recordAudit(e.slice(_.length),{detail:{...s,hash:r}}),y({result:{state:o}},200)}parseIssueTriagePatch(e,t){if(e===h.resolveIssue)return{status:"resolved"};if(e===h.ignoreIssue)return{status:"ignored"};if(e===h.assignIssue)return{assignee:Sn(t),status:"open"};if(e===h.setIssueSeverity)return{severity:bn(t)}}handleRecordAuthEvent(e){const t=kn(e);try{ns(this.state.storage.sql,{outcome:t.outcome,ts:Date.now()})}catch{}return y({result:{recorded:!0}},200)}async handleRecordContainerEvent(e){const t=Nn(e);if(this.logs.push(t),t.level==="error"||t.exitCode!==void 0&&t.exitCode!==0){const s={durationMs:0,errorMessage:t.message,functionPath:t.functionPath,outcome:"error",shardKey:this.state.id?.name,ts:t.timestamp};this.persistRequestLog(s,this.requestLogConfig()),this.recordChangedTable(N),await this.flushChangedTables()}return y({result:{recorded:!0}},200)}async handleRunAs(e){const t=On(e),s=await this.withRequestIdentity(t.userId,t.identity,()=>this.handleRpc(t.functionPath,t.args));return await this.flushChangedTables(),this.recordAudit("runAs",{detail:{functionPath:t.functionPath,runAsUserId:t.userId}}),y({result:s},200)}resolveWorkflowBinding(e){const t=this.workflowsMetadata().workflows.find(r=>r.exportName===e);if(!t)throw new f("BAD_REQUEST",`workflow "${e}" is not declared`);const s=this.env?.[t.binding];if(typeof s!="object"||s===null||typeof s.create!="function"||typeof s.get!="function")throw new f("BAD_REQUEST",`workflow binding "${t.binding}" is not available on this deployment`);return s}async handleCreateWorkflowInstance(e){const t=En(e),s=await this.resolveWorkflowBinding(t.exportName).create({id:t.id,params:t.params}),r=await s.status(),n={id:s.id,status:At(r.status)};return this.recordAudit("createWorkflowInstance",{id:s.id,detail:{exportName:t.exportName}}),y({result:n},200)}async handleGetWorkflowInstanceStatus(e){const t=wn(e),s=await(await this.resolveWorkflowBinding(t.exportName).get(t.id)).status(),r={error:Rn(s.error),id:t.id,output:s.output,status:At(s.status)};return y({result:r},200)}async handleListFlags(e){const t=e.context,s=typeof t=="object"&&t!==null&&!Array.isArray(t)?t:void 0,r=await this.evaluateFlags(s);return y({result:r},200)}async withRequestIdentity(e,t,s){const r=this.currentRequestUserId,n=this.currentRequestIdentity;this.currentRequestUserId=e,this.currentRequestIdentity=t;try{return await s()}finally{this.currentRequestUserId=r,this.currentRequestIdentity=n}}handleRecordMail(e){const t=$n(e),s=Ge(this.state.storage.sql,t,Date.now());return y({result:s},200)}handleClearCapturedMail(){const e=ks(this.state.storage.sql);return y({result:e},200)}handleSendTestMail(e){const t=Ln(e),s=Ge(this.state.storage.sql,t,Date.now());return y({result:s},200)}handleRecordQueueMessage(e){const t=xn(e),s=zr(this.state.storage.sql,t,Date.now());return y({result:s},200)}handleClearQueueMessages(){const e=Yr(this.state.storage.sql);return y({result:e},200)}async handleSendQueueMessage(e){const t=Pn(e),{binding:s}=this.resolveQueueBinding(t.exportName);let r;return t.batch===void 0?(await s.send(t.body,{contentType:t.contentType,delaySeconds:t.delaySeconds}),r=1):(await s.sendBatch(t.batch.map(n=>({body:n,contentType:t.contentType,delaySeconds:t.delaySeconds}))),r=t.batch.length),this.recordAudit("sendQueueMessage",{detail:{count:r,exportName:t.exportName}}),y({result:{sent:r}},200)}async handleExplainIssue(e){const t=await _s(this.env?.AI,e);return t.degraded?t.reason!=="no-ai-binding"&&this.recordAudit("explainIssue",{detail:{groundedId:t.groundedId,reason:t.reason}}):this.recordAudit("explainIssue",{detail:{groundedId:t.groundedId,model:t.model}}),y({result:t},200)}async handleGenerateSql(e){this.ensureMigrated();const t=this.state.storage.sql,s=je(t).map(n=>({columns:this.tableColumns(n.name).map(i=>i.name),table:n.name})),r=await Ga(this.env?.AI,e,s);return r.degraded?r.reason!=="no-ai-binding"&&this.recordAudit("aiGenerateSql",{detail:{reason:r.reason}}):this.recordAudit("aiGenerateSql",{detail:{sql:r.sql}}),y({result:r},200)}aiAdminHandlers(){return{[h.aiAvailable]:()=>Promise.resolve(this.handleAiAvailable()),[h.aiChartConfig]:async e=>this.handleAiChartConfig(e),[h.aiGenerateSql]:async e=>this.handleGenerateSql(e),[h.aiTableFilter]:async e=>this.handleAiTableFilter(e)}}async handleAiTableFilter(e){this.ensureMigrated();const t=typeof e.table=="string"?e.table:"",s=t===""?[]:this.tableColumns(t).map(n=>n.name),r=await Qa(this.env?.AI,e,s);return r.degraded&&r.reason!=="no-ai-binding"&&this.recordAudit("aiTableFilter",{detail:{reason:r.reason,table:t}}),y({result:r},200)}handleAiAvailable(){return y({result:{available:this.env?.AI!==void 0}},200)}async handleAiChartConfig(e){const t=Array.isArray(e.columns)?e.columns.filter(o=>typeof o=="string").slice(0,64):[],s=typeof e.types=="object"&&e.types!==null?e.types:void 0,r=s===void 0?void 0:Object.fromEntries(Object.entries(s).filter(o=>typeof o[1]=="string")),n=typeof e.rowCount=="number"?e.rowCount:0,i=await za(this.env?.AI,e,{columns:t,rowCount:n,types:r});return i.degraded&&i.reason!=="no-ai-binding"&&this.recordAudit("aiChartConfig",{detail:{reason:i.reason}}),y({result:i},200)}async handleReplayQueueMessage(e){const t=Dn(e),s=Xr(this.state.storage.sql,t.id);if(s===void 0)throw new f("BAD_REQUEST",`replayQueueMessage: captured message "${t.id}" was not found`,{status:404});if(Gr(s.body))throw new f("BAD_REQUEST",`replayQueueMessage: captured message "${t.id}" has a truncated or unserializable body and can't be replayed faithfully`,{status:422});const r=t.target??this.resolveReplayTarget(s.queue)??s.exportName;if(typeof r!="string"||r==="")throw new f("BAD_REQUEST",`replayQueueMessage: captured message "${t.id}" has no declared producer to replay onto (pass \`target\`)`);const{binding:n}=this.resolveQueueBinding(r);return await n.send(s.body),this.recordAudit("replayQueueMessage",{detail:{messageId:s.messageId,target:r},id:t.id}),y({result:{sent:1,target:r}},200)}resolveQueueBinding(e){const t=this.queuesMetadata().queues.find(r=>r.exportName===e);if(!t)throw new f("BAD_REQUEST",`queue "${e}" is not declared`);const s=this.env?.[t.binding];if(typeof s!="object"||s===null||typeof s.send!="function")throw new f("BAD_REQUEST",`queue binding "${t.binding}" is not available on this deployment`);return{binding:s,metadata:t}}resolveReplayTarget(e){const{queues:t}=this.queuesMetadata(),s=t.find(r=>r.deadLetterQueue===e);return s!==void 0?s.exportName:t.find(r=>r.name===e)?.exportName}recordAudit(e,t={}){const s=this.state.storage.sql,r=this.getCurrentUserId(),n=r===void 0?t.detail:{...t.detail,userId:r};hr(s,{detail:n,id:t.id,op:e,table:t.table,ts:Date.now()})}recordRequestLog(e,t,s,r,n,i){const o=this.requestLogConfig();if(r==="ok"&&!Xn(o.sampleRate))return;const c={cacheHit:this.currentRequestCacheHit,durationMs:s,errorMessage:i,functionPath:e,identity:this.currentRequestIdentity,outcome:r,redactedArgs:Object.keys(t).length===0?void 0:t,shardKey:this.state.id?.name,tablesRead:this.currentRequestReadTables===void 0?[]:[...this.currentRequestReadTables],tablesWritten:n,ts:Date.now(),userId:this.getCurrentUserId()};this.persistRequestLog(c,o)}persistRequestLog(e,t){const s={captureRaw:t.captureRaw,retention:t.retention};try{ua(this.state.storage.sql,e,s)}catch{}if(t.emit||e.outcome==="error")try{la(e,s)}catch{}}requestLogConfig(){const e=this.env??{};return{captureRaw:Je(this.env),emit:zn(e.LUNORA_REQUEST_LOG_EMIT,Je(this.env)),retention:Qn(e.LUNORA_REQUEST_LOG_RETENTION),sampleRate:Jn(e.LUNORA_REQUEST_LOG_SAMPLE)}}async handlePitrAdminOp(e,t){const s=typeof t.time=="number"||typeof t.time=="string"?t.time:void 0;if(e===h.getPitrBookmark)return y({result:await Os(this.state.storage,s)},200);if(e!==h.pitrRestore)return;const r=t.restart===!0,n=typeof t.bookmark=="string"?t.bookmark:void 0,i=await $s(this.state.storage,{bookmark:n,time:s});this.cdcEnabled()&&rr(this.sql),this.recordAudit("pitrRestore",{detail:{restart:r,restoredTo:i.restoredTo,undoBookmark:i.undoBookmark}});const o=y({result:{...i,restarted:r}},200);return r&&this.state.abort?.("lunora PITR restore"),o}readAdminOp(e,t){this.ensureMigrated();const s=this.state.storage.sql,r=this.readAdminWildcardOp(e);if(r!==void 0)return{result:r,tables:new Set([E])};if(e===h.getAuditLog)return this.readAdminAuditLog(s,t);if(e===h.getRequestLog)return this.readAdminRequestLog(s,t);if(e===h.getIssues)return this.readAdminIssues(s,t);const n=this.readAdminDurableSignal(e,s,t);if(n)return n;if(e===h.readTablePage)return this.readAdminTablePage(s,t);if(e===h.facetColumn)return this.readAdminFacetColumn(s,t);if(e===h.runSql)return this.readAdminRunSql(s,t);const i=va(e,_,s,t,E);if(i!==void 0)return i;const o=this.readAdminTableSignal(e,s,t);return o||this.readAdminStorageSignal(e,s,t)||null}readAdminTableSignal(e,t,s){if(e===h.listTableIndexes||e===h.describeTable){const r=typeof s.table=="string"?s.table:"";return{result:e===h.describeTable?{columns:this.tableColumns(r)}:{indexes:this.tableIndexes(r)},tables:new Set([r===""?E:r])}}if(e===h.describeTables){const r=Array.isArray(s.tables)?s.tables.filter(n=>typeof n=="string"):[];return{result:{columnsByTable:Object.fromEntries(r.map(n=>[n,this.tableColumns(n)]))},tables:new Set(r.length===0?[E]:r)}}if(e===h.migrationStatus){const r=typeof s.id=="string"?s.id:void 0;return{result:{migrations:cs(t,r)},tables:new Set([E])}}}readAdminStorageSignal(e,t,s){if(e===h.storageReferences)return this.readAdminStorageReferences(t,s);if(e===h.storageOrphans)return this.readAdminStorageOrphans(t,s)}readAdminStorageReferences(e,t){const s=Array.isArray(t.keys)?t.keys.filter(r=>typeof r=="string"):[];return{result:bs(e,this.storageColumns(),s),tables:new Set([E])}}readAdminStorageOrphans(e,t){const s=Array.isArray(t.liveKeys)?t.liveKeys.filter(n=>typeof n=="string"):[],r=Za(e,this.storageColumns(),s);return r.truncated&&console.warn(`[@lunora/do] storageOrphans scan truncated after checking ${String(r.scanned)} storage references; reporting the first ${String(r.references.length)} dangling reference(s).`),{result:r,tables:new Set([E])}}readAdminWildcardOp(e){if(e===h.listTables)return je(this.state.storage.sql);if(e===h.getMetrics)return this.collectMetrics();if(e===h.getFunctionStats)return this.collectFunctionStats();if(e===h.listSubscriptions)return this.collectSubscriptions();if(e===h.getFanoutMetrics)return this.collectFanoutMetrics();if(e===h.getLogs)return{entries:this.logs.entries()};if(e===h.getTraces){const t=Oa(this.spans.entries());return{total:t.total,traces:t.traces}}if(e===h.getMetricSeries)return{series:this.metricSeries.entries()};if(e===h.getMetricHistory)return Pr(this.sql);if(e===h.getSettings)return Zs(this.env);if(e===h.getSecurityAudit)return er(this.env);if(e===h.getAdvisories)return{advisories:[...this.advisories(),...this.runtimeAdvisories()]};if(e===h.rlsPolicies)return this.rlsMetadata();if(e===h.maskPolicies)return this.maskMetadata();if(e===h.storageRules)return this.storageRulesMetadata();if(e===h.studioFeatures)return this.studioFeatures();if(e===h.listWorkflows)return this.workflowsMetadata();if(e===h.listQueues)return this.queuesMetadata()}collectSubscriptions(){return Es(this.state.getWebSockets().map(e=>this.readAttachment(e)))}collectFanoutMetrics(){const e=ws(this.state.getWebSockets().map(s=>this.readAttachment(s))),t=this.relay?.relayCount()??0;return{...e,maxRelays:this.relay?.maxRelays()??Le,promoted:t>0,relayCount:t,shapePoke:this.fanout.shapePoke,sinceMs:this.metrics.sinceMs,whisper:this.fanout.whisper}}readAdminAuditLog(e,t){Oe(e);const s=typeof t.limit=="number"?t.limit:void 0,r=typeof t.sinceSeq=="number"?t.sinceSeq:void 0;return{result:{entries:pr(e,{limit:s,sinceSeq:r})},tables:new Set([E])}}readAdminRequestLog(e,t){z(e);const s=t.outcome==="ok"||t.outcome==="error"?t.outcome:void 0;return{result:{entries:ga(e,{functionPathPrefix:typeof t.functionPathPrefix=="string"?t.functionPathPrefix:void 0,limit:typeof t.limit=="number"?t.limit:void 0,outcome:s,shardKey:typeof t.shardKey=="string"?t.shardKey:void 0,sinceSeq:typeof t.sinceSeq=="number"?t.sinceSeq:void 0,tableTouched:typeof t.tableTouched=="string"?t.tableTouched:void 0,userId:typeof t.userId=="string"?t.userId:void 0})},tables:new Set([E])}}readAdminIssues(e,t){return z(e),{result:{issues:ba(e,{functionPathPrefix:typeof t.functionPathPrefix=="string"?t.functionPathPrefix:void 0,limit:typeof t.limit=="number"?t.limit:void 0,shardKey:typeof t.shardKey=="string"?t.shardKey:void 0,status:mn(t.status)?t.status:void 0,userId:typeof t.userId=="string"?t.userId:void 0})},tables:new Set([E])}}readAdminDurableSignal(e,t,s){if(e===h.getAuthMetrics)return this.readAdminAuthMetrics(t);if(e===h.getCapturedMail)return this.readAdminCapturedMail(t,s);if(e===h.getQueueMessages)return this.readAdminQueueMessages(t,s)}readAdminAuthMetrics(e){let t;try{t=is(e)}catch{t={attempts:0,failureRate:0,failures:0,history:[],sinceMs:0}}return{result:t,tables:new Set([E])}}readAdminCapturedMail(e,t){const s=typeof t.limit=="number"?t.limit:void 0;let r;try{r=Ms(e,{limit:s})}catch{r={entries:[]}}return{result:r,tables:new Set([Ns])}}readAdminQueueMessages(e,t){const s=typeof t.limit=="number"?t.limit:void 0,r=typeof t.queue=="string"?t.queue:void 0;let n;try{n=Jr(e,{limit:s,queue:r})}catch{n={entries:[]}}return{result:n,tables:new Set([M])}}readAdminTablePage(e,t){const s=typeof t.table=="string"?t.table:"";return{result:Ts(e,{filters:Me(t.filters),limit:typeof t.limit=="number"?t.limit:void 0,offset:typeof t.offset=="number"?t.offset:void 0,orderBy:vn(t.orderBy),refs:this.tableRefs(s),search:typeof t.search=="string"?t.search:void 0,skipCount:typeof t.skipCount=="boolean"?t.skipCount:void 0,table:s}),tables:new Set([s===""?E:s])}}readAdminFacetColumn(e,t){const s=typeof t.table=="string"?t.table:"";return{result:Rs(e,{column:typeof t.column=="string"?t.column:"",filters:Me(t.filters),limit:typeof t.limit=="number"?t.limit:void 0,search:typeof t.search=="string"?t.search:void 0,table:s}),tables:new Set([s===""?E:s])}}readAdminRunSql(e,t){const s=typeof t.sql=="string"?t.sql:"";return{result:Vs(e,s),tables:new Set([E])}}executeAdminSubscription(e,t){const s=this.readAdminOp(e,t);return s?{result:s.result,tables:s.tables}:null}async resolveReactiveOutcome(e,t,s,r){if(s)return this.executeAdminSubscription(e,t);if(e.startsWith(As)){const n=await this.runFlagSubscriptionRead(e,t,r);return n===null?null:{result:n,tables:new Set([E])}}return this.executeSubscription(e,t,r)}isIdentityIndependent(e){return e.startsWith(_)}resolveReactiveOutcomeDeduped(e,t,s,r,n){if(!this.isIdentityIndependent(e))return this.resolveReactiveOutcome(e,t,s,r);const i=Qe(e,t,null),o=n.get(i);if(o!==void 0)return o;const c=this.resolveReactiveOutcome(e,t,s,r);return n.set(i,c),c}isAdminAuthorized(e){const t=(this.env??{}).LUNORA_ADMIN_TOKEN;if(!t||t.length===0)return!1;const s=Ee(e.headers.get("authorization"));return s!==void 0&&te(s,t)}async handleStream(e,t,s,r){const n=this.executeStream(s,r);if(!n){e.send(JSON.stringify({error:{code:"NOT_FOUND",message:`stream not registered: ${s}`},id:t,type:"error"}));return}let i=this.streamCancellers.get(e);if(i||(i=new Map,this.streamCancellers.set(e,i)),i.size>=S.MAX_STREAMS_PER_SOCKET){try{e.send(JSON.stringify({error:{code:"TOO_MANY_STREAMS",message:`stream cap of ${String(S.MAX_STREAMS_PER_SOCKET)} reached on this socket`},id:t,type:"error"}))}catch{}return}const o=new AbortController;i.set(t,o),e.send(JSON.stringify({id:t,type:"ack"}));try{for await(const c of n.iterator(o.signal)){if(o.signal.aborted)break;await C(e),e.send(JSON.stringify({data:R(c),id:t,type:"chunk"}))}o.signal.aborted||e.send(JSON.stringify({id:t,type:"complete"}))}catch(c){const{body:d,redacted:u}=q(c,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"internal error"});u&&console.error("[@lunora/do] unhandled stream error:",c),e.send(JSON.stringify({error:{code:d.code,message:d.message},id:t,type:"error"}))}finally{i.delete(t),i.size===0&&this.streamCancellers.delete(e)}}async flushChangedTables(){const e=this.pendingChangedTables;if(this.pendingChangedTables=void 0,!(!e||e.size===0)){if(this.pendingRefreshTables)for(const t of e)this.pendingRefreshTables.add(t);else this.pendingRefreshTables=e;if(!this.refreshInFlight){if(typeof this.state.waitUntil=="function"){this.state.waitUntil(this.drainSubscriptionRefreshes());return}await this.drainSubscriptionRefreshes()}}}async drainSubscriptionRefreshes(){if(!this.refreshInFlight){this.refreshInFlight=!0;try{let e=this.pendingRefreshTables;for(;e&&e.size>0;){this.pendingRefreshTables=void 0;const t=this.currentCdcCursor(),s=this.currentCdcEpoch();await Promise.all([this.refreshSubscriptions(e),this.pokeShapeSubscribers(e,t,s),this.relay?.onFlush(e,t??0)]),e=this.pendingRefreshTables}}finally{this.refreshInFlight=!1}}}async refreshSubscriptions(e){const t=[...this.state.getWebSockets()],s=this.currentCdcCursor(),r=this.currentCdcEpoch(),n=new Map;await gt(t,async i=>{if(this.isSocketExpired(i)){this.dropExpiredSocket(i);return}const o=this.readAttachment(i);for(const[c,d]of Object.entries(o.subs)){const{functionPath:u}=d;if(!u)continue;const l=u.startsWith(_),m=this.subMemos.get(i)?.get(c);if(!(m&&!m.tables.has(E)&&!dn(m.tables,e)))try{const p=await this.resolveReactiveOutcomeDeduped(u,d.args??{},l,{identity:o.identity,userId:o.userId},n);if(!p)continue;await C(i),this.pushSubscriptionData(i,c,p,s,r)}catch{continue}}})}async seedSubscription(e,t,s,r,n){const i=s.args??{},o=this.readAttachment(e),c=await this.resolveReactiveOutcome(r,i,n,{identity:o.identity,userId:o.userId});if(!c)return;const{sinceEpoch:d,sinceSeq:u}=s,l=n||u===void 0?void 0:this.evaluateResume(u,c.tables,d),m=n?void 0:l?.epoch??this.currentCdcEpoch();if(l?.resumable){this.seedSubscriptionMemo(e,t,c);try{e.send(`{"type":"resume","id":${JSON.stringify(t)}${Tt(l.cursor??0,m)}}`)}catch{}return}this.pushSubscriptionData(e,t,c,l?.cursor??this.currentCdcCursor(),m)}async handleShapeSubscribe(e,t,s){const r=this.shapeSubscribe(e,t,s);if(r!=="ok"){const i=r==="too_many"?"TOO_MANY_SUBSCRIPTIONS":"SUBSCRIPTION_PERSIST_FAILED",o=r==="too_many"?`subscription cap of ${String(S.MAX_SUBSCRIPTIONS_PER_SOCKET)} reached on this socket`:"failed to persist shape subscription attachment";this.sendShapeSubscribeError(e,t,i,o);return}const n=await this.seedShapeSubscription(e,t,s);if(n!=="ok"){this.shapeUnsubscribe(e,t),this.sendShapeSubscribeError(e,t,n.code,n.message);return}try{e.send(JSON.stringify({id:t,type:"ack"}))}catch{}}sendShapeSubscribeError(e,t,s,r){try{e.send(JSON.stringify({code:s,error:{code:s,message:r},id:t,type:"error"}))}catch{}}async seedShapeSubscription(e,t,s){const r=this.readAttachment(e),n={identity:r.identity,userId:r.userId},i=await this.relay?.seedRelayShape(e,t,s,n);if(i!==void 0)return i;let o;try{o=this.resolveShape(s.name,s.args??{},n)}catch(c){this.recordShapeError(`shape:seed:${t}`,c);const{body:d}=q(c,{fallbackCode:"SHAPE_RESOLVE_FAILED",redactedMessage:"shape resolution failed"});return{code:d.code,message:d.message}}if(!o)return{code:"SHAPE_NOT_FOUND",message:`shape "${s.name}" not found or not permitted`};try{return o.global?await this.seedGlobalShape(e,t,o,n,r.connectionId??""):await this.seedOpLogShape(e,t,s,o)}catch(c){this.recordShapeError(`shape:seed:${t}`,c);const{body:d}=q(c,{fallbackCode:"SHAPE_SEED_FAILED",redactedMessage:"shape seed failed"});return{code:d.code,message:d.message}}}async seedOpLogShape(e,t,s,r){const{baseCheckpoint:n,cursor:i,epoch:o,rowsPatch:c}=this.computeOpLogShapeSeed(s,r);return await C(e),this.sendPoke(e,[{rowsPatch:c,shapeId:t}],i,o,n)&&this.recordShapeMemo(e,t,i),"ok"}computeOpLogShapeSeed(e,t){const s=this.sql,r=this.currentCdcCursor()??0,n=this.currentCdcEpoch(),i=this.cdcEnabled()?Ze(s):void 0,o=this.cdcEnabled()&&e.sinceSeq!==void 0&&e.sinceEpoch===n&&e.sinceSeq<=r&&(e.sinceSeq===r||i!==void 0&&i<=e.sinceSeq+1),c=o&&e.sinceSeq!==void 0?this.buildShapeDiff(s,t,e.sinceSeq,r):this.buildShapeSeed(s,t);return{baseCheckpoint:o?e.sinceSeq:void 0,cursor:r,epoch:n,rowsPatch:c}}async pokeShapeSubscribers(e,t,s){const r=[...this.state.getWebSockets()],n=t??this.currentCdcCursor()??0,i=this.sql,o=new Map;let c=0;const d=async l=>{if(this.isSocketExpired(l)){this.dropExpiredSocket(l);return}const m=this.readAttachment(l),{shapes:p}=m;if(p)try{const g={identity:m.identity,userId:m.userId},{emptyAdvanced:b,partAdvanced:Qt,parts:Fe}=this.collectShapePokeParts(l,p,g,e,n,i,o);for(const ue of b)this.recordShapeMemo(l,ue,n);if(Fe.length>0&&(await C(l),this.sendPoke(l,Fe,n,s,void 0))){c+=1;for(const ue of Qt)this.recordShapeMemo(l,ue,n)}}catch{}},u=Date.now();await gt(r,d),this.fanout.shapePoke=he(this.fanout.shapePoke,r.length,c,Date.now()-u)}collectShapePokeParts(e,t,s,r,n,i,o){const c=[],d=[],u=[];for(const[l,m]of Object.entries(t))try{const p=this.resolveShape(m.name,m.args??{},s);if(!p||p.global||!r.has(p.table))continue;const g=this.shapeMemos.get(e)?.get(l)?.cursor??0,b=this.buildShapeDiff(i,p,g,n,o);b.length>0?(c.push({rowsPatch:b,shapeId:l}),u.push(l)):d.push(l)}catch(p){this.recordShapeError(`shape:poke:${l}`,p)}return{emptyAdvanced:d,partAdvanced:u,parts:c}}readShapeOpRange(e,t,s,r,n){const i=`${t}\0${String(s)}\0${String(r)}`,o=n?.get(i);if(o!==void 0)return o;const c=new Map,d=new Set([t]);let u=s;for(;;){const{changes:l,cursor:m}=this.readShapeCdcPage(e,u,d);for(const p of l)c.set(p.id,p);if(l.length===0||m===u||m>=r)break;u=m}return n?.set(i,c),c}readShapeCdcPage(e,t,s){return fe(e,{sinceSeq:t,tables:s})}buildShapeDiff(e,t,s,r,n){const i=this.readShapeOpRange(e,t.table,s,r,n);if(i.size===0)return[];const o=[...i.keys()],c=ar(e,t.table,t.effectiveWhere,o),d=[];for(const[u,l]of i){if(c.has(u)){l.doc!==void 0&&d.push({key:u,op:l.op,table:t.table,value:Ae(l.doc,t.columns)});continue}l.op!=="insert"&&d.push({key:u,op:"delete",table:t.table})}return d}buildShapeSeed(e,t){return nr(e,t.table,t.effectiveWhere).map(s=>({key:s.id,op:"insert",table:t.table,value:Ae(s.doc,t.columns)}))}async seedGlobalShape(e,t,s,r,n){const i=await this.readGlobalShapeRows(s,r);if(!this.withinGlobalShapeBound(i.length,`shape:seed:${t}`,s.table))return{code:"SHAPE_GLOBAL_TOO_LARGE",message:`global shape membership for "${s.table}" exceeds the ${String(S.GLOBAL_SHAPE_MAX_ROWS)}-row cap; narrow it with a shape predicate or an RLS read policy`};const{next:o,rowsPatch:c}=dt(i,new Map,{columns:s.columns,table:s.table});return await C(e),this.sendPoke(e,[{rowsPatch:c,shapeId:t}],this.currentCdcCursor()??0,this.currentCdcEpoch(),void 0)&&(this.recordGlobalSnapshot(e,t,o),this.saveGlobalSnapshot(n,t,o)),await this.scheduleGlobalPoll(),"ok"}async refreshGlobalShape(e,t,s,r,n){const i=await this.readGlobalShapeRows(s,r);if(!this.withinGlobalShapeBound(i.length,`shape:poll:${t}`,s.table))return;const o=this.readGlobalSnapshot(e,t,n),{next:c,rowsPatch:d}=dt(i,o,{columns:s.columns,table:s.table});if(d.length===0){this.recordGlobalSnapshot(e,t,c);return}await C(e),this.sendPoke(e,[{rowsPatch:d,shapeId:t}],this.currentCdcCursor()??0,this.currentCdcEpoch(),void 0)&&(this.recordGlobalSnapshot(e,t,c),this.saveGlobalSnapshot(n,t,c))}readGlobalSnapshot(e,t,s){const r=this.globalShapeSnapshots.get(e)?.get(t);if(r)return r;const n=this.loadGlobalSnapshot(s,t);return this.recordGlobalSnapshot(e,t,n),n}recordGlobalSnapshot(e,t,s){let r=this.globalShapeSnapshots.get(e);r||(r=new Map,this.globalShapeSnapshots.set(e,r)),r.set(t,s)}loadGlobalSnapshot(e,t){if(e==="")return new Map;try{return zs(this.sql,e,t)}catch{return new Map}}saveGlobalSnapshot(e,t,s){if(e!=="")try{Js(this.sql,e,t,s)}catch{}}async scheduleGlobalPoll(e){if(this.globalPollScheduled)return;const{setAlarm:t}=this.state.storage;if(t){this.globalPollScheduled=!0;try{await t.call(this.state.storage,e??Date.now()+S.GLOBAL_SHAPE_POLL_INTERVAL_MS)}catch{this.globalPollScheduled=!1}}}recordShapeError(e,t){this.logs.push({functionPath:e,level:"error",message:t instanceof Error?t.message:String(t),timestamp:Date.now()})}withinGlobalShapeBound(e,t,s){return e<=S.GLOBAL_SHAPE_MAX_ROWS?!0:(this.recordShapeError(t,new Error(`global shape membership for "${s}" (${String(e)} rows) exceeds the ${String(S.GLOBAL_SHAPE_MAX_ROWS)}-row cap; narrow it with a shape predicate or an RLS read policy`)),!1)}async pollGlobalShapes(){const e=[...this.state.getWebSockets()];let t=0;for(const s of e){if(this.isSocketExpired(s)){this.dropExpiredSocket(s);continue}const r=this.readAttachment(s),{shapes:n}=r;if(!n)continue;const i={identity:r.identity,userId:r.userId};t+=await this.pollSocketGlobalShapes(s,n,i,r.connectionId??"")}return t}async pollSocketGlobalShapes(e,t,s,r){let n=0;for(const[i,o]of Object.entries(t)){let c;try{c=this.resolveShape(o.name,o.args??{},s)}catch(d){n+=1,this.recordShapeError(`shape:poll:${i}`,d);continue}if(c?.global){n+=1;try{await this.refreshGlobalShape(e,i,c,s,r)}catch(d){this.recordShapeError(`shape:poll:${i}`,d)}}}return n}sendPoke(e,t,s,r,n){this.pokeSequence+=1;const i=`poke-${String(this.pokeSequence)}`,o=Ce(t,{baseCheckpoint:n,checkpoint:s,epoch:r,lastMutationId:this.socketClientWatermark(e),pokeId:i});try{for(const c of o)e.send(c);return!0}catch{return!1}}socketClientWatermark(e){const t=this.readAttachment(e),{clientId:s}=t;if(s!==void 0)try{return pe(this.sql,t.userId??"",s)}catch{return}}recordShapeMemo(e,t,s){let r=this.shapeMemos.get(e);r||(r=new Map,this.shapeMemos.set(e,r)),r.set(t,{cursor:s})}seedSubscriptionMemo(e,t,s){let r=this.subMemos.get(e);r||(r=new Map,this.subMemos.set(e,r)),r.set(t,{lastJson:JSON.stringify(R(s.result??null)),tables:s.tables})}pushSubscriptionData(e,t,s,r,n){let i=this.subMemos.get(e);i||(i=new Map,this.subMemos.set(e,i));const o=Tt(r,n),c=JSON.stringify(R(s.result??null)),d=i.get(t);if(d?.lastJson===c){d.tables=s.tables;const m=this.socketClientWatermark(e),p=m===void 0?"":`,"lastMutationId":${String(m)}`;D(e,`{"type":"settled","id":${JSON.stringify(t)}${p}${o}}`);return}const u=[],l=(d===void 0?void 0:Ls(d.lastJson,s.result,s.tables.values().next().value??"",u))===void 0?D(e,`{"type":"data","id":${JSON.stringify(t)},"data":${c}${o}}`):xs(e,t,u,o);i.set(t,{lastJson:l?c:d?.lastJson??an,tables:s.tables})}async isUpgradeAllowed(e){const t=this.env??{},s=t.LUNORA_ALLOWED_ORIGINS;if(s&&s.trim()!==""){const n=e.headers.get("origin");if(!n||!s.split(",").map(i=>i.trim()).filter(i=>i.length>0).includes(n))return!1}const r=t.LUNORA_WS_BEARER;if(r&&r.length>0){const n=this.suppliedWsToken(e);if(!n||!te(n,r)&&!await this.isAdminSocket(e))return!1}return!0}suppliedWsToken(e){const t=Ee(e.headers.get("authorization"));return t!==void 0?t:new URL(e.url).searchParams.get("token")??void 0}async isAdminSocket(e){const t=this.env??{},s=t.LUNORA_ADMIN_TOKEN;if(!s||s.length===0)return!1;const r=this.suppliedWsToken(e);if(r===void 0)return!1;if(await lr(s,r))return!0;const n=Ee(e.headers.get("authorization"))===void 0,i=sn.has((t.LUNORA_REQUIRE_EPHEMERAL_WS_TOKEN??"").trim().toLowerCase());return n&&i?!1:te(r,s)}armWebSocketKeepalive(){const e=this.state.setWebSocketAutoResponse;typeof e!="function"||typeof WebSocketRequestResponsePair>"u"||e.call(this.state,new WebSocketRequestResponsePair(en,tn))}async routeNonRpc(e,t){if(e.pathname==="/_lunora/relay"&&t.method==="POST")return this.relay?await this.relay.handleControl(t):new Response("relay tier inactive",{status:404});if(e.pathname==="/_lunora/route"&&t.method==="GET")return y({relayCount:this.relay?.relayCount()??0});if(e.pathname==="/rpc-batch"&&t.method==="POST")return this.handleBatchRpc(t);if(t.headers.get("Upgrade")==="websocket")return this.handleWebSocketUpgrade(t)}async handleWebSocketUpgrade(e){if(!await this.isUpgradeAllowed(e))return new Response("Forbidden",{status:403});const t=await this.isAdminSocket(e),s=new WebSocketPair,r=s[0],n=s[1];this.state.acceptWebSocket(n);const i=e.headers.get("x-lunora-userid")??void 0,o=It(e.headers.get("x-lunora-identity")),c=Number(e.headers.get("x-lunora-identity-exp")),d=Number.isFinite(c)&&c>0?c:void 0;return n.serializeAttachment?.({admin:t,connectionId:crypto.randomUUID(),subs:{},...d===void 0?{}:{expiresAt:d},...o===void 0?{}:{identity:o},...i===void 0?{}:{userId:i}}),new Response(null,{status:101,webSocket:r})}cdcEnabled(){try{return this.sql.exec("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?",Xe).toArray().length>0}catch{return!1}}isSocketExpired(e){const{expiresAt:t}=this.readAttachment(e);return typeof t=="number"&&Date.now()>=t}dropExpiredSocket(e){try{e.send(JSON.stringify({code:"TOKEN_EXPIRED",error:{code:"TOKEN_EXPIRED",message:"authentication token expired"},type:"error"})),e.close(4001,"token_expired")}catch{}}setWhisperMembership(e,t,s){const r=this.readAttachment(e),n=r.whispers??[],i=n.includes(t);if(s){if(i||n.length>=S.MAX_WHISPER_TOPICS_PER_SOCKET)return;r.whispers=[...n,t]}else{if(!i)return;const o=n.filter(c=>c!==t);o.length===0?delete r.whispers:r.whispers=o}try{e.serializeAttachment?.(r)}catch{}}allowWhisper(e){const t=Date.now(),s=this.whisperBuckets.get(e)??{last:t,tokens:S.WHISPER_RATE_BURST},r=Math.min(S.WHISPER_RATE_BURST,s.tokens+(t-s.last)/1e3*S.WHISPER_RATE_PER_SEC);return r<1?(this.whisperBuckets.set(e,{last:t,tokens:r}),!1):(this.whisperBuckets.set(e,{last:t,tokens:r-1}),!0)}async broadcastWhisper(e,t,s){if(!this.allowWhisper(e))return;const r=JSON.stringify(s??null);if(r.length>S.MAX_WHISPER_BYTES)return;const n=this.readAttachment(e).userId,i=n===void 0?"":`,"from":${JSON.stringify(n)}`,o=`{"type":"whisper","topic":${JSON.stringify(t)},"data":${r}${i}}`;this.deliverWhisperLocal(t,o,e),await this.relay?.forwardWhisper(t,o)}deliverWhisperLocal(e,t,s){let r=0,n=0;for(const i of this.state.getWebSockets())r+=1,!(i===s||this.readAttachment(i).whispers?.includes(e)!==!0)&&(D(i,t),n+=1);return this.fanout.whisper=he(this.fanout.whisper,r,n,0),n}readAttachment(e){const t=e.deserializeAttachment?.();return t&&typeof t=="object"&&"subs"in t&&t.subs?t:{subs:{}}}}export{nn as ROOT_DO_SIZE_WARN_BYTES,ee as ROOT_SHARD_NAME,S as ShardDO,Ls as subscriptionListDeltas};
|
|
130
|
+
Verify your email: ${s}`,to:t}},xn=a=>{const e=r=>{throw new f("BAD_REQUEST",`recordQueueMessage: ${r}`)},t=a.messages;Array.isArray(t)||e("`messages` must be an array");const s=new Set(["ack","error","retry"]);return t.map((r,n)=>{(typeof r!="object"||r===null)&&e(`\`messages[${String(n)}]\` must be an object`);const i=r,o=typeof i.messageId=="string"?i.messageId:"",c=typeof i.queue=="string"?i.queue:"",d=typeof i.outcome=="string"?i.outcome:"";o===""&&e(`\`messages[${String(n)}].messageId\` is required`),c===""&&e(`\`messages[${String(n)}].queue\` is required`),s.has(d)||e(`\`messages[${String(n)}].outcome\` must be one of ack | error | retry`);const{attempts:u,timestamp:l}=i;return{attempts:typeof u=="number"&&Number.isFinite(u)?u:1,body:i.body,deadLettered:i.deadLettered===!0,error:typeof i.error=="string"?i.error:void 0,exportName:typeof i.exportName=="string"?i.exportName:void 0,messageId:o,outcome:d,queue:c,timestamp:typeof l=="number"&&Number.isFinite(l)?l:0}})},vt=100,A=a=>`${a.traceId}:${a.rootSpanId}`,Se=256,qn=500,be="lunora.dispatch",Pn=a=>{const e=typeof a.exportName=="string"?a.exportName.trim():"";if(e==="")throw new f("BAD_REQUEST","sendQueueMessage: `exportName` is required");const t=a.delaySeconds;if(t!==void 0&&(typeof t!="number"||!Number.isFinite(t)||t<0))throw new f("BAD_REQUEST","sendQueueMessage: `delaySeconds` must be a non-negative number");const s=Array.isArray(a.batch)?a.batch:void 0;if(s!==void 0&&(s.length===0||s.length>vt))throw new f("BAD_REQUEST",`sendQueueMessage: \`batch\` must contain between 1 and ${String(vt)} messages`);return{batch:s,body:a.body,contentType:typeof a.contentType=="string"?a.contentType:void 0,delaySeconds:t,exportName:e}},Dn=a=>{const e=typeof a.id=="string"?a.id.trim():"";if(e==="")throw new f("BAD_REQUEST","replayQueueMessage: `id` is required");const t=typeof a.target=="string"&&a.target.trim()!==""?a.target.trim():void 0;return{id:e,target:t}},Un=a=>{const e=typeof a.table=="string"?a.table:"",t=typeof a.index=="string"?a.index:"",s=typeof a.rowId=="string"?a.rowId:"";if(e.trim()==="")throw new f("BAD_REQUEST","rankBefore: `table` is required");if(t.trim()==="")throw new f("BAD_REQUEST","rankBefore: `index` is required");if(typeof a.partitionKey!="string")throw new f("BAD_REQUEST","rankBefore: `partitionKey` must be a string");if(s.trim()==="")throw new f("BAD_REQUEST","rankBefore: `rowId` is required");if(!Array.isArray(a.sortValues))throw new f("BAD_REQUEST","rankBefore: `sortValues` must be an array");return{index:t,partitionKey:a.partitionKey,rowId:s,sortValues:a.sortValues,table:e}},L=a=>{throw new f("BAD_REQUEST",a)},_t=(a,e)=>((typeof a!="string"||a.trim()==="")&&L(`rankPage: \`${e}\` is required`),a),Bn=a=>{if(a===void 0)return;(typeof a!="object"||a===null||Array.isArray(a))&&L("rankPage: `after` must be an object");const e=a;return(typeof e.partitionKey!="string"||typeof e.rowId!="string"||!Array.isArray(e.sortValues))&&L("rankPage: `after` must have a string partitionKey, string rowId, and array sortValues"),{partitionKey:e.partitionKey,rowId:e.rowId,sortValues:e.sortValues}},Fn=a=>{const e=_t(a.table,"table"),t=_t(a.index,"index");a.take!==void 0&&typeof a.take!="number"&&L("rankPage: `take` must be a number"),a.cursor!==void 0&&a.cursor!==null&&typeof a.cursor!="string"&&L("rankPage: `cursor` must be a string or null"),a.partitionKey!==void 0&&typeof a.partitionKey!="string"&&L("rankPage: `partitionKey` must be a string"),a.directions!==void 0&&!Array.isArray(a.directions)&&L("rankPage: `directions` must be an array");const s=a.directions===void 0?void 0:a.directions.map(r=>r==="desc"?"desc":"asc");return{after:Bn(a.after),cursor:typeof a.cursor=="string"?a.cursor:void 0,directions:s,index:t,partitionKey:typeof a.partitionKey=="string"?a.partitionKey:void 0,take:typeof a.take=="number"?a.take:void 0,table:e}},Wn=a=>{try{const e=JSON.parse(a);if(Array.isArray(e)&&typeof e[0]=="string"&&typeof e[1]=="string")return{index:e[1],table:e[0]}}catch{}},Hn=a=>{const e=a.changes;if(!Array.isArray(e))throw new f("BAD_REQUEST","applyCdc: `changes` must be an array");return{changes:e.map((t,s)=>{const r=t,{op:n}=r,i=typeof r.table=="string"?r.table:"",o=typeof r.id=="string"?r.id:"";if(i===""||o===""||n!=="insert"&&n!=="update"&&n!=="delete")throw new f("BAD_REQUEST",`applyCdc: changes[${String(s)}] must have a table, id, and op of insert|update|delete`);const c=r.doc;if(c!==void 0&&(typeof c!="object"||c===null||Array.isArray(c)))throw new f("BAD_REQUEST",`applyCdc: changes[${String(s)}].doc must be an object`);const d=c;if(d!==void 0&&typeof d._id=="string"&&d._id!==o)throw new f("BAD_REQUEST",`applyCdc: changes[${String(s)}].doc._id must match the entry id`);return{doc:d,id:o,op:n,seq:typeof r.seq=="number"?r.seq:0,table:i,ts:typeof r.ts=="number"?r.ts:0}})}},Kn=a=>{const e=t=>{const s=typeof t=="number"?t:Number(t);return Number.isFinite(s)&&s>=0?Math.floor(s):void 0};return{limit:e(a.limit),sinceSeq:e(a.sinceSeq)??0}},$=a=>a?{"x-d1-bookmark":a}:void 0,It=a=>{if(a)try{const e=JSON.parse(a);if(e&&typeof e=="object"&&!Array.isArray(e))return e}catch{}},jn=a=>{if(!a)return;const e=Number(a);return Number.isInteger(e)&&e>0?e:void 0},Gn=a=>{const e=new Set;for(const t of a){const s=us(t);s!==""&&e.add(s)}return e},Qn=a=>{if(a===void 0)return;const e=Number.parseInt(a,10);return Number.isFinite(e)&&e>0?e:void 0},zn=(a,e)=>a==="1"||a==="true"?!0:a==="0"||a==="false"?!1:e,Jn=a=>{if(a===void 0)return 1;const e=Number.parseFloat(a);return Number.isFinite(e)?Math.min(1,Math.max(0,e)):1},Xn=a=>a>=1?!0:a<=0?!1:Math.random()<a,Ee=a=>{if(!a)return;const[e,...t]=a.split(" ");if(e?.toLowerCase()!=="bearer")return;const s=t.join(" ").trim();return s.length>0?s:void 0};class S{static MAX_STREAMS_PER_SOCKET=8;static MAX_SUBSCRIPTIONS_PER_SOCKET=32;static GLOBAL_SHAPE_POLL_INTERVAL_MS=2e3;static GLOBAL_SHAPE_MAX_ROWS=5e4;static MAX_WHISPER_TOPICS_PER_SOCKET=64;static MAX_WHISPER_BYTES=4096;static WHISPER_RATE_BURST=50;static WHISPER_RATE_PER_SEC=25;static rootSizeWarned=!1;static resetRootSizeWarning(){S.rootSizeWarned=!1}static nextPollAlarmTarget(e,t,s,r){const n=[e>0?r+S.GLOBAL_SHAPE_POLL_INTERVAL_MS:void 0,t,s].filter(i=>i!==void 0).map(i=>Math.max(i,r));return n.length>0?Math.min(...n):void 0}state;env;reactiveCache;drizzleHandle;transactionDepth=0;currentRequestBookmark;currentResponseBookmark;currentRequestUserId;currentRequestIp;currentRequestTraceparent;currentRequestTrace;traceSampling=new Map;dispatchSpans=new Map;lastTelemetrySink;currentRequestMutationId;currentRequestClientId;currentRequestClientSeq;currentMutatorClass;mutationBookkeepingCommitted=!1;lastIdempotencyTrimAt=0;currentRequestIdentity;currentRequestSystem=!1;pendingChangedTables=void 0;pendingRefreshTables=void 0;refreshInFlight=!1;subMemos=new WeakMap;shapeMemos=new WeakMap;globalShapeSnapshots=new WeakMap;globalPollScheduled=!1;pokeSequence=0;whisperBuckets=new WeakMap;streamCancellers=new WeakMap;metrics={errors:0,requests:0,sinceMs:Date.now()};fanout={shapePoke:Ke(),whisper:Ke()};shardBinding;relay;usedIndexes=new Set;functionStats=new Map;logs=new Is;spans=new _a;metricSeries=new Mr;currentTracker;currentScannedTables;currentIndexHits;currentRequestReadTables;currentStmtSamples;currentRequestCacheHit;constructor(e,t,s={}){this.state=e,this.env=t,s.reactiveCache&&(this.reactiveCache=new Cs(s.reactiveCache));const r={buildShapeDiff:(n,i,o)=>this.buildShapeDiff(this.sql,n,i,o),computeOpLogShapeSeed:(n,i)=>this.computeOpLogShapeSeed(n,i),currentCdcEpoch:()=>this.currentCdcEpoch(),deliverWhisperLocal:(n,i,o)=>this.deliverWhisperLocal(n,i,o),doName:()=>this.state.id?.name,env:()=>this.env,getWebSockets:()=>this.state.getWebSockets(),maskMetadata:()=>this.maskMetadata(),nextPokeId:()=>(this.pokeSequence+=1,`poke-${String(this.pokeSequence)}`),readAttachment:n=>this.readAttachment(n),recordShapePokeFanout:(n,i,o)=>{this.fanout.shapePoke=he(this.fanout.shapePoke,n,i,o)},resolveShape:(n,i,o)=>this.resolveShape(n,i,o),rlsMetadata:()=>this.rlsMetadata(),shardBinding:()=>this.shardBinding,sql:()=>this.sql};this.relay=ca(r),this.armWebSocketKeepalive()}async fetch(e){const t=new URL(e.url);this.shardBinding=e.headers.get("x-lunora-shard-binding")??this.shardBinding;const s=await this.routeNonRpc(t,e);if(s!==void 0)return s;if(t.pathname!=="/rpc"||e.method!=="POST")return new Response("Not found",{status:404});let r;try{r=await e.json()}catch{return y({error:{code:"BAD_REQUEST",message:"invalid JSON body"}},400)}if(r.functionPath.startsWith(_))return this.handleAdminRpc(e,r.functionPath,r.args??{});this.currentRequestBookmark=e.headers.get("x-d1-bookmark")??void 0,this.currentResponseBookmark=void 0,this.currentRequestUserId=e.headers.get("x-lunora-userid")??void 0,this.currentRequestMutationId=e.headers.get("x-lunora-mutation-id")??void 0,this.currentRequestClientId=e.headers.get("x-lunora-client-id")??void 0,this.currentRequestClientSeq=jn(e.headers.get("x-lunora-client-seq")),this.currentMutatorClass=void 0,this.mutationBookkeepingCommitted=!1,this.currentRequestIdentity=It(e.headers.get("x-lunora-identity")),this.currentRequestIp=e.headers.get("x-lunora-client-ip")??void 0,this.currentRequestSystem=e.headers.get("x-lunora-system")==="1",this.currentRequestTraceparent=e.headers.get("traceparent")??void 0,this.currentRequestTrace=X(this.currentRequestTraceparent);const n=this.currentRequestTrace;this.traceSampling.set(n.traceId,{keepErrors:e.headers.get("x-lunora-sample-errors")!=="0",sampled:Yt(this.currentRequestTraceparent)?.sampled??!0}),this.currentRequestReadTables=void 0,this.currentRequestCacheHit=void 0,this.metrics.requests+=1;const i=Date.now();this.currentScannedTables=new Set,this.currentIndexHits=new Set,this.currentStmtSamples=[];let o;try{if(r.functionPath.startsWith(gs)){const b=await this.runRelationFanoutRead(r.functionPath,r.args??{});return y(b,200,$(this.currentResponseBookmark))}const c=this.isCustomMutator(r.functionPath)?this.classifyClientMutation():void 0;this.currentMutatorClass=c;const d=this.rejectNonNextMutation(r.functionPath,c,i);if(d!==void 0)return d;const u=this.readIdempotentResult(this.currentRequestMutationId);if(u!==void 0)return this.respondFromIdempotencyCache(r.functionPath,i,c,u.value);const l=await this.handleRpc(r.functionPath,P(r.args??{}));this.recordPostDispatchBookkeeping(l,c),c?.kind==="next"&&this.advanceClientMutationWatermark();const m=Date.now()-i;this.recordFunctionCall(r.functionPath,m,void 0,this.currentScannedTables,this.currentIndexHits),this.flushStmtSamples();const p=[...this.pendingChangedTables??[]];this.recordRequestLog(r.functionPath,r.args??{},m,"ok",p),this.maybeWarnRootSize();const g=this.buildDispatchResponse(c,R(l));return await this.flushChangedTables(),g}catch(c){this.metrics.errors+=1,o={thrown:c};const d=Date.now()-i,u=c instanceof Error?c.message:String(c),l=c instanceof tr&&c.kind==="occ";return c?.code!=="FUNCTION_NOT_FOUND"&&this.recordFunctionCall(r.functionPath,d,u,this.currentScannedTables,this.currentIndexHits,l),this.flushStmtSamples(),this.recordRequestLog(r.functionPath,r.args??{},d,"error",[...this.pendingChangedTables??[]],u),this.logs.push({functionPath:r.functionPath,level:"error",message:u,timestamp:Date.now()}),this.recordChangedTable(N),await this.flushChangedTables(),this.errorToResponse(c)}finally{const c=this.dispatchSpans.get(A(n));if((this.spans.hasTrace(n.traceId)||c?.collector!==void 0)&&this.recordDispatchRootSpan(r.functionPath,i,o,n),this.dispatchSpans.delete(A(n)),c?.sink?.flush)try{c.sink.flush({waitUntil:this.state.waitUntil?.bind(this.state)})}catch{}this.flushSampledOutTrace(n,o!==void 0),this.traceSampling.delete(n.traceId),this.currentRequestTrace=void 0,this.currentRequestBookmark=void 0,this.currentResponseBookmark=void 0,this.currentRequestUserId=void 0,this.currentRequestMutationId=void 0,this.currentRequestClientId=void 0,this.currentRequestClientSeq=void 0,this.currentMutatorClass=void 0,this.mutationBookkeepingCommitted=!1,this.currentRequestIdentity=void 0,this.currentRequestIp=void 0,this.currentRequestSystem=!1,this.currentRequestTraceparent=void 0,this.currentScannedTables=void 0,this.currentIndexHits=void 0,this.currentRequestReadTables=void 0,this.currentRequestCacheHit=void 0,this.currentStmtSamples=void 0}}async webSocketMessage(e,t){return this.handleWebSocketMessage(e,t)}async webSocketClose(e,t,s,r){const n=this.readAttachment(e);n.connectionId!==void 0&&await this.dispatchLifecycle("disconnect",this.lifecycleInfo(n));const i=this.streamCancellers.get(e);if(i){for(const o of i.values())o.abort();this.streamCancellers.delete(e)}if(this.subMemos.delete(e),this.shapeMemos.delete(e),this.globalShapeSnapshots.delete(e),n.connectionId!==void 0)try{Fs(this.sql,n.connectionId)}catch{}e.serializeAttachment?.(void 0),await this.relay?.announceDrain(e)}webSocketError(e,t){}async alarm(){return this.withTriggerTrace("alarm",async()=>this.handleAlarmBody())}lifecycleHookPaths(e){return[]}async dispatchLifecycle(e,t){for(const s of this.lifecycleHookPaths(e))try{await this.withRequestIdentity(t.userId,t.identity,()=>this.withSystemDispatch(()=>this.handleRpc(s,t.event)))}catch(r){this.logs.push({functionPath:s,level:"error",message:r instanceof Error?r.message:String(r),timestamp:Date.now()})}}runRelationFanoutRead(e,t){throw new f("NOT_IMPLEMENTED","__lunora_relation__: no schema bound — the base ShardDO cannot serve cross-shard relation reads",{status:500})}get sql(){const e=this.state.storage.sql,t=this.currentStmtSamples;if(t===void 0)return e;const s=e.exec;if(typeof s!="function")return e;const r=(n,...i)=>{const o=Date.now(),c=s.call(e,n,...i);if(c!==null&&typeof c=="object"){const d=c;if(typeof d.toArray=="function"){const u=d.toArray.bind(d);d.toArray=()=>{const l=u(),m=Date.now()-o;return t.push([n,m,l.length,0]),l}}if(typeof d.one=="function"){const u=d.one.bind(d);d.one=()=>{const l=u(),m=Date.now()-o;return t.push([n,m,1,0]),l}}if(typeof d.toArray!="function"&&typeof d.one!="function"){const u=Date.now()-o;t.push([n,u,0,0])}}else{const d=Date.now()-o;t.push([n,d,0,0])}return c};return new Proxy(e,{get(n,i){return i==="exec"?r:Reflect.get(n,i,n)}})}get db(){return this.drizzleHandle?this.drizzleHandle:(this.drizzleHandle=zt(this.state.storage,{logger:!1}),this.drizzleHandle)}async runInTransaction(e){if(this.transactionDepth>0)throw new f("NESTED_TRANSACTION","nested transactions are not supported in SQLite-in-DO",{status:500});const t=this.state.storage.sql;if(!t||typeof t.exec!="function")throw new f("SQL_UNAVAILABLE","storage.sql is not available on this ShardDO state",{status:500});const s=this.state.storage,r=async()=>{this.transactionDepth=1;try{return typeof s?.transaction=="function"?await s.transaction(async()=>e()):await e()}finally{this.transactionDepth=0}};return typeof this.state.blockConcurrencyWhile=="function"?this.state.blockConcurrencyWhile(r):r()}getInboundBookmark(){return this.currentRequestBookmark}setOutboundBookmark(e){this.currentResponseBookmark=e}getCurrentUserId(){return this.currentRequestUserId}getCurrentIp(){return this.currentRequestIp}getCurrentTraceparent(){return this.currentRequestTraceparent}getCurrentTrace(){return this.currentRequestTrace}getCurrentIdentity(){return this.currentRequestIdentity}isSystemDispatch(){return this.currentRequestSystem}runShardDataMigration(e){return Promise.reject(new f("MIGRATION_NOT_FOUND",`data migration "${e.id}" is not registered`,{status:404}))}ensureMigrated(){}tableRefs(e){}tableIndexes(e){return[]}tableColumns(e){return[]}storageColumns(){return{}}advisories(){return[]}advisorProcedures(){return[]}rlsMetadata(){return{policies:[],roles:[]}}maskMetadata(){return{columns:[]}}storageRulesMetadata(){return{rules:[]}}studioFeatures(){return{analytics:!1,auth:!1,containers:!1,flags:!1,kv:!1,mail:!1,notifications:!1,payments:!1,queues:!1,scheduler:!1,storage:!1,vectors:!1,workflows:!1}}evaluateFlags(e){return Promise.resolve({configured:!1,flags:[]})}runFlagSubscriptionRead(e,t,s){return Promise.resolve(null)}queuesMetadata(){return{queues:[]}}workflowsMetadata(){return{workflows:[]}}runtimeAdvisories(){const e=new Set([...this.usedIndexes].map(s=>s.slice(0,s.indexOf(":")))),t=[];for(const s of e)for(const r of this.tableIndexes(s))r.type==="vector"||this.usedIndexes.has(`${s}:${r.name}`)||t.push({cacheKey:`unused_index:${s}:${r.name}`,categories:["PERFORMANCE"],description:"A declared index has not been exercised by any query since this shard instance started. An unused index costs storage and is maintained on every write for no read benefit.",detail:`Index "${r.name}" on table "${s}" has not been used since this instance woke, though other indexes on "${s}" have — it may be redundant.`,facing:"INTERNAL",level:"INFO",metadata:{index:r.name,indexKind:r.type,since:"instance-woke",table:s},name:"unused_index",remediation:"Confirm over a representative window, then drop the index if no query needs it.",title:"Unused index"});return t}runShardExport(e){return Promise.resolve([])}runShardImport(e){return Promise.resolve({conflicts:0,errors:[],inserted:{}})}runShardWrite(e){return Promise.reject(new f("UNKNOWN_TABLE",`unknown table: ${e.table}`,{status:404}))}deleteRowThroughWriter(e,t){return Promise.reject(new f("UNKNOWN_TABLE",`unknown table: ${e}`,{status:404}))}async runShardBulkDelete(e){const t=Math.min(Math.max(Math.trunc(e.limit??Rt),1),Rt),{hasMore:s,ids:r}=Ss(this.sql,{filters:e.filters,limit:t,search:e.search,table:e.table});let n=0;for(const i of r)await this.deleteRowThroughWriter(e.table,i),n+=1;return{deleted:n,hasMore:s}}runShardRankBefore(e){return Promise.reject(new f("NOT_IMPLEMENTED","rankBefore is not implemented in base ShardDO",{status:500}))}runShardRankPage(e){return Promise.reject(new f("NOT_IMPLEMENTED","rankPage is not implemented in base ShardDO",{status:500}))}runShardCdcSync(e){const t=this.sql;return t.exec("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?",Xe).toArray().length>0?fe(t,{limit:e.limit,sinceSeq:e.sinceSeq}):{changes:[],cursor:e.sinceSeq}}currentCdcCursor(){return this.cdcEnabled()?Ye(this.sql):void 0}currentCdcEpoch(){return this.cdcEnabled()?Ve(this.sql):void 0}evaluateResume(e,t,s){const r=this.sql;if(!this.cdcEnabled())return{cursor:void 0,epoch:void 0,resumable:!1};const n=Ye(r),i=Ve(r);if(s!==i)return{cursor:n,epoch:i,resumable:!1};if(e>n)return{cursor:n,epoch:i,resumable:!1};if(e===n)return{cursor:n,epoch:i,resumable:!0};const o=Ze(r);if(o===void 0||o>e+1)return{cursor:n,epoch:i,resumable:!1};if(t.size===0)return{cursor:n,epoch:i,resumable:!1};const{changes:c}=fe(r,{limit:wt,sinceSeq:e});if(c.length>=wt)return{cursor:n,epoch:i,resumable:!1};const d=c.some(u=>t.has(u.table));return{cursor:n,epoch:i,resumable:!d}}readIdempotentResult(e){if(e!==void 0)try{const t=Ws(this.sql,this.currentRequestUserId??"",e);return t===void 0?void 0:{value:JSON.parse(t.resultJson)}}catch{return}}persistIdempotentResult(e){if(this.currentRequestMutationId===void 0)return;const t=Date.now();try{Hs(this.sql,this.currentRequestUserId??"",this.currentRequestMutationId,JSON.stringify(R(e)),t),t-this.lastIdempotencyTrimAt>cn&&(Ks(this.sql,t-on),this.lastIdempotencyTrimAt=t)}catch{}}isCustomMutator(e){return!1}classifyClientMutation(){const e=this.currentRequestClientId,t=this.currentRequestClientSeq;if(e===void 0||t===void 0)return;const s=this.currentRequestUserId??"";let r;try{r=pe(this.sql,s,e)}catch{try{js(this.sql),r=pe(this.sql,s,e)}catch{return}}const n=r+1;return t<=r?{expected:n,kind:"already"}:t===n?{expected:n,kind:"next"}:{expected:n,kind:"gap"}}rejectNonNextMutation(e,t,s){if(!(t===void 0||t.kind==="next"))return this.recordFunctionCall(e,Date.now()-s,void 0,this.currentScannedTables,this.currentIndexHits),t.kind==="already"?y({lastMutationId:t.expected-1,result:null},200,$(this.currentResponseBookmark)):y({error:{code:"OUT_OF_ORDER",expectedMutationId:t.expected,message:`out-of-order mutation; expected sequence ${String(t.expected)}`}},409,$(this.currentResponseBookmark))}respondFromIdempotencyCache(e,t,s,r){if(this.recordFunctionCall(e,Date.now()-t,void 0,this.currentScannedTables,this.currentIndexHits),s?.kind==="next")return this.advanceClientMutationWatermark(),this.buildDispatchResponse(s,r);const n=this.mutationCommitCursor();return y(n===void 0?{result:r}:{commitCursor:n,result:r},200,$(this.currentResponseBookmark))}mutationCommitCursor(){return this.currentRequestMutationId===void 0?void 0:this.currentCdcCursor()}buildDispatchResponse(e,t){if(e?.kind==="next")return y({lastMutationId:this.currentRequestClientSeq,result:t},200,$(this.currentResponseBookmark));const s=this.mutationCommitCursor();return y(s===void 0?{result:t}:{commitCursor:s,result:t},200,$(this.currentResponseBookmark))}commitMutationBookkeeping(e){this.persistIdempotentResult(e),this.currentMutatorClass?.kind==="next"&&this.advanceClientMutationWatermark({strict:!0}),this.mutationBookkeepingCommitted=!0}recordPostDispatchBookkeeping(e,t){this.mutationBookkeepingCommitted||(this.persistIdempotentResult(e),t?.kind==="next"&&this.advanceClientMutationWatermark())}advanceClientMutationWatermark(e){const t=this.currentRequestClientId,s=this.currentRequestClientSeq;if(!(t===void 0||s===void 0))try{Gs(this.sql,this.currentRequestUserId??"",t,s)}catch(r){if(e?.strict)throw r}}runShardApplyCdc(e){return Promise.reject(new f("NOT_IMPLEMENTED","applyCdc is not implemented in base ShardDO",{status:500}))}subscribe(e,t,s){const r=this.readAttachment(e);if(Object.keys(r.subs).length>=S.MAX_SUBSCRIPTIONS_PER_SOCKET)return"too_many";r.subs[t]=s;try{e.serializeAttachment?.(r)}catch{return delete r.subs[t],"serialize_failed"}return"ok"}unsubscribe(e,t){const s=this.readAttachment(e),r=s.subs[t];delete s.subs[t];try{e.serializeAttachment?.(s)}catch{r!==void 0&&(s.subs[t]=r);return}this.subMemos.get(e)?.delete(t)}shapeSubscribe(e,t,s){const r=this.readAttachment(e),n=r.shapes??{};if(Object.keys(r.subs).length+Object.keys(n).length>=S.MAX_SUBSCRIPTIONS_PER_SOCKET)return"too_many";n[t]=s,r.shapes=n;try{e.serializeAttachment?.(r)}catch{return delete r.shapes[t],"serialize_failed"}return"ok"}shapeUnsubscribe(e,t){const s=this.readAttachment(e),{shapes:r}=s;if(!r)return;const n=r[t];delete r[t];try{e.serializeAttachment?.(s)}catch{n!==void 0&&(r[t]=n);return}if(this.shapeMemos.get(e)?.delete(t),this.globalShapeSnapshots.get(e)?.delete(t),s.connectionId!==void 0)try{Qs(this.sql,s.connectionId,t)}catch{}}matchesSubscription(e,t){if(e.table!==t.table)return!1;const{args:s}=e;if(!s)return!0;const{row:r}=t;if(!r)return!0;for(const[n,i]of Object.entries(s))if(r[n]!==i)return!1;return!0}broadcastDelta(e){const t=this.state.getWebSockets(),s=JSON.stringify(e);for(const r of t){const n=this.readAttachment(r);for(const[i,o]of Object.entries(n.subs))this.matchesSubscription(o,e)&&D(r,`{"type":"delta","id":${JSON.stringify(i)},"delta":${s}}`)}}executeSubscription(e,t,s){return Promise.resolve(null)}resolveShape(e,t,s){}isShapeRelayUniform(e,t){return this.relay?.isShapeRelayUniform(e,t)??!1}readGlobalShapeRows(e,t){return Promise.resolve([])}pollExternalSources(){return Promise.resolve(void 0)}scheduleSourcePoll(){return this.scheduleGlobalPoll()}ttlSweeps(){return[]}async pollTtlSweeps(){const e=this.ttlSweeps();if(e.length===0)return;const t=this.sql,s=Date.now();for(const r of e){let n=0,i=!0;for(;i&&n<hn;){const o=sr(t,r,s,ln);for(const c of o.ids)await this.deleteRowThroughWriter(r.table,c);i=o.hasMore,n+=1}}return s+pn}scheduleTtlSweep(){return this.scheduleGlobalPoll()}currentShardKey(){return this.state.id?.name??ee}recordExternalSourceError(e,t){this.recordShapeError(`source:${e}`,t)}executeStream(e,t){return null}async runCachedQuery(e,t,s){if(!this.reactiveCache)return s();const r=this.currentTracker,n=ds();this.currentTracker=n;const i=this.reactiveCache.stats().hits,o=this.getCurrentUserId(),c=this.getCurrentIdentity(),d=o===void 0&&c===void 0?null:Ne({claims:c??null,userId:o??null});try{const u=await this.reactiveCache.run(Qe(e,t,d),n.collect(),s);return this.currentRequestCacheHit=this.reactiveCache.stats().hits>i,this.currentRequestReadTables=Gn(n.collect()),u}finally{this.currentTracker=r}}getCtxDbReadHook(){return(e,t)=>{this.currentTracker?.recordRead(e,t??He),t===He&&this.currentScannedTables?.add(e)}}getCtxDbIndexUseHook(){return(e,t)=>{this.usedIndexes.add(`${e}:${t}`),this.currentIndexHits?.add(JSON.stringify([e,t]))}}recordChangedTable(e){this.pendingChangedTables??=new Set,this.pendingChangedTables.add(e)}async flushMigrationProgress(){this.recordChangedTable(os),await this.flushChangedTables()}recordUserLog(e,t,s,r,n,i,o,c){const d=c??this.currentRequestTrace,u={args:s,...o===void 0?{}:{eventName:o},fields:n,functionPath:e,level:t,message:r,shardKey:this.state.id?.name,spanId:d?.rootSpanId,traceId:d?.traceId,ts:Date.now(),userId:this.getCurrentUserId()};this.logs.push({fields:n,functionPath:e,level:t,message:r,timestamp:u.ts});try{ya(u)}catch{}if(i?.onLog)try{i.onLog(u,{waitUntil:this.state.waitUntil?.bind(this.state)})}catch{}}makeLogger(e,t,s){const r=(n,i)=>{const{fields:o,message:c}=ma(i,s);this.recordUserLog(e,n,i,c,o,t)};return{debug:(...n)=>{r("debug",n)},error:(...n)=>{r("error",n)},event:(n,i)=>{this.recordUserLog(e,"info",[n],n,s?{...s,...i}:i,t,n)},fatal:(...n)=>{r("fatal",n)},info:(...n)=>{r("info",n)},log:(...n)=>{r("log",n)},trace:(...n)=>{r("trace",n)},warn:(...n)=>{r("warn",n)},with:n=>this.makeLogger(e,t,s?{...s,...n}:n)}}makeTracer(e,t,s){const r=s??X(void 0);return Vt({anchor:r,fuseCloudflareSpans:t?.fuseCloudflareTraces===!0,functionPath:e,record:n=>{this.recordSpan(n,t,r.sampled)},resolveCloudflareTracing:rn,shardKey:this.state.id?.name,userId:()=>this.getCurrentUserId()})}resolveDispatchAnchor(e){return(e?void 0:this.getCurrentTrace())??X(void 0)}instrumentDb(e,t,s,r){const n=r===void 0?"off":r.instrumentDatabase??"summary";return n==="off"?e:Tr(e,{anchor:s,functionPath:t,mode:n,record:i=>{this.recordSpan(i,r,s.sampled)},shardKey:this.state.id?.name,tally:this.dispatchTally(s),userId:()=>this.getCurrentUserId()})}makeFetch(e,t,s){const r=(n,i)=>globalThis.fetch(n,i);return s===void 0||s.traceFetch===!1?r:Zt({anchor:t,functionPath:e,...typeof s.traceFetch=="object"&&s.traceFetch.propagate!==void 0?{propagate:s.traceFetch.propagate}:{},record:n=>{this.recordSpan(n,s,t.sampled)},shardKey:this.state.id?.name,userId:()=>this.getCurrentUserId()},r)}makeDispatchSpan(e,t){this.lastTelemetrySink=t??this.lastTelemetrySink,t!==void 0&&(se(this.dispatchSpans,Se),this.dispatchSpans.set(A(e),this.dispatchSpans.get(A(e))??{sink:t}));const s=()=>{se(this.dispatchSpans,Se);const r=A(e),n=this.dispatchSpans.get(r)??{sink:t};return n.collector??=ss({spanId:e.rootSpanId,traceId:e.traceId}),this.dispatchSpans.set(r,n),n.collector};return{addEvent:(r,n)=>{s().handle.addEvent(r,n)},spanContext:()=>({spanId:e.rootSpanId,traceId:e.traceId}),addLink:r=>{s().handle.addLink(r)},recordEvaluation:r=>{s().handle.recordEvaluation(r)},recordException:r=>{s().handle.recordException(r)},setAttribute:(r,n)=>{s().handle.setAttribute(r,n)},setAttributes:r=>{s().handle.setAttributes(r)}}}makeMetrics(e,t){return es({functionPath:e,record:s=>{this.recordMetric(s,t)},shardKey:this.state.id?.name})}recordMetric(e,t){const s=this.currentRequestTrace?.traceId,r=s===void 0?e:{...e,traceId:s},n=o=>{try{o()}catch{}};n(()=>{this.metricSeries.push(r)});const i=t?.metricHistory;if(i!==void 0&&i!==!1){const o=this.state.storage.sql,c=typeof i=="object"?i:{};n(()=>{xr(o,r,s,c)})}t?.onMetric&&n(()=>t.onMetric?.(r,{waitUntil:this.state.waitUntil?.bind(this.state)}))}async handleWebSocketMessage(e,t){if(this.isSocketExpired(e)){this.dropExpiredSocket(e);return}const s=typeof t=="string"?t:new TextDecoder().decode(t);let r;try{r=JSON.parse(s)}catch{e.send(JSON.stringify({message:"invalid envelope",type:"error"}));return}if(r.type==="connect"){const n=this.readAttachment(e);if(n.connected===!0)return;r.context!==void 0&&(n.context=r.context),r.clientId!==void 0&&(n.clientId=r.clientId),n.connected=!0;try{e.serializeAttachment?.(n)}catch{}await this.dispatchLifecycle("connect",this.lifecycleInfo(n));return}if(r.type==="subscribe"&&r.query){const{functionPath:n}=r.query,i=n?.startsWith(_)===!0;if(i&&this.readAttachment(e).admin!==!0){e.send(JSON.stringify({id:r.id,message:"admin subscription requires admin authorization",type:"error"}));return}let o;try{o=r.query.args===void 0?r.query:{...r.query,args:P(r.query.args)}}catch{try{e.send(JSON.stringify({code:"BAD_SUBSCRIPTION_ARGS",error:{code:"BAD_SUBSCRIPTION_ARGS",message:"subscription args failed wire decoding"},id:r.id,type:"error"}))}catch{}return}const c=this.subscribe(e,r.id,o);if(c!=="ok"){const d=c==="too_many"?"TOO_MANY_SUBSCRIPTIONS":"SUBSCRIPTION_PERSIST_FAILED",u=c==="too_many"?`subscription cap of ${String(S.MAX_SUBSCRIPTIONS_PER_SOCKET)} reached on this socket`:"failed to persist subscription attachment";try{e.send(JSON.stringify({code:d,error:{code:d,message:u},id:r.id,type:"error"}))}catch{}return}e.send(JSON.stringify({id:r.id,type:"ack"})),n&&await this.seedSubscription(e,r.id,o,n,i);return}if(r.type==="shape_subscribe"&&r.shape){let n;try{n=r.shape.args===void 0?void 0:P(r.shape.args)}catch{this.sendShapeSubscribeError(e,r.id,"BAD_SUBSCRIPTION_ARGS","shape args failed wire decoding");return}await this.handleShapeSubscribe(e,r.id,{args:n,name:r.shape.name,sinceEpoch:r.sinceEpoch,sinceSeq:r.sinceCheckpoint});return}if(r.type==="shape_unsubscribe"){this.shapeUnsubscribe(e,r.id),e.send(JSON.stringify({id:r.id,type:"ack"}));return}if(r.type==="stream"&&r.query?.functionPath){if(r.query.functionPath.startsWith(_)){e.send(JSON.stringify({id:r.id,message:"streams must be public",type:"error"}));return}this.handleStream(e,r.id,r.query.functionPath,P(r.query.args??{})).catch(()=>{});return}if(r.type==="whisper_subscribe"||r.type==="whisper_unsubscribe"){if(typeof r.topic=="string"&&r.topic.length>0){const n=r.type==="whisper_subscribe";this.setWhisperMembership(e,r.topic,n),n&&await this.relay?.announce()}return}if(r.type==="whisper"){typeof r.topic=="string"&&r.topic.length>0&&await this.broadcastWhisper(e,r.topic,r.data);return}if(r.type==="unsubscribe"){const n=this.streamCancellers.get(e),i=n?.get(r.id);i&&(i.abort(),n?.delete(r.id)),this.unsubscribe(e,r.id),e.send(JSON.stringify({id:r.id,type:"ack"}))}}async handleAlarmBody(){this.globalPollScheduled=!1;let e;try{e=await this.pollGlobalShapes()}catch(n){this.recordShapeError("shape:poll",n),e=1}let t;try{t=await this.pollExternalSources()}catch(n){this.recordShapeError("source:poll",n),t=Date.now()+S.GLOBAL_SHAPE_POLL_INTERVAL_MS}let s;try{s=await this.pollTtlSweeps()}catch(n){this.recordShapeError("ttl:sweep",n),s=Date.now()+S.GLOBAL_SHAPE_POLL_INTERVAL_MS}await this.flushChangedTables();const r=S.nextPollAlarmTarget(e,t,s,Date.now());r!==void 0&&await this.scheduleGlobalPoll(r)}dispatchTally(e){se(this.dispatchSpans,Se);const t=A(e),s=this.dispatchSpans.get(t)??{};return s.dbTally??=Rr(),this.dispatchSpans.set(t,s),s.dbTally}async withTriggerTrace(e,t){const s=X(void 0),r=Date.now(),n=this.currentRequestTrace===void 0;n&&(this.currentRequestTrace=s);let i;try{return await t()}catch(o){throw i={thrown:o},o}finally{n&&this.currentRequestTrace===s&&(this.currentRequestTrace=void 0),(this.spans.hasTrace(s.traceId)||this.dispatchSpans.get(A(s))?.collector!==void 0)&&this.recordDispatchRootSpan(e,r,i,s),this.dispatchSpans.delete(A(s)),this.flushTelemetry()}}flushTelemetry(){try{this.lastTelemetrySink?.flush?.({waitUntil:this.state.waitUntil?.bind(this.state)})}catch{}}recordDispatchRootSpan(e,t,s,r){const n=this.dispatchSpans.get(A(r)),i=Date.now()-t,o=n?.dbTally===void 0||n.dbTally.calls===0?void 0:Ar(n.dbTally),c=n?.collector===void 0?void 0:{...n.collector.collected,attributes:{...o,...n.collector.collected.attributes}};try{this.spans.push(ts({anchor:r,...c===void 0?{}:{collected:c},durationMs:i,failure:s,functionPath:e,shardKey:this.state.id?.name,startTs:t,userId:this.getCurrentUserId()}))}catch{}n?.collector!==void 0&&this.exportWideEvent(e,i,s,r,{collected:c??n.collector.collected,sink:n.sink})}exportWideEvent(e,t,s,r,n){try{const{attributes:i}=n.collected;this.recordUserLog(e,s===void 0?"info":"error",[be],be,{...i,[le.durationMs]:t,[le.functionPath]:e,[le.ok]:s===void 0},n.sink,be,r)}catch{}}recordSpan(e,t,s){try{this.spans.push(e)}catch{}if(!t?.onSpan)return;const r=this.traceSampling.get(e.traceId);if(r!==void 0){if(!r.sampled){if(r.sink=t,e.dispatch!==!0){const n=r.held??(r.held=[]);n.push(e),n.length>qn&&n.shift()}return}this.emitSpan(e,t);return}s!==!1&&this.emitSpan(e,t)}emitSpan(e,t){if(t.onSpan)try{t.onSpan(e,{waitUntil:this.state.waitUntil?.bind(this.state)})}catch{}}flushSampledOutTrace(e,t){const s=this.traceSampling.get(e.traceId);if(!s||s.sampled||!s.keepErrors)return;const{held:r,sink:n}=s;if(!(!n?.onSpan||r===void 0||r.length===0||!(t||r.some(i=>!i.ok))))for(const i of r)this.emitSpan(i,n)}lifecycleInfo(e){return{event:{connectionId:e.connectionId??"",shardKey:this.state.id?.name??ee,userId:e.userId??null,...e.context===void 0?{}:{context:e.context}},identity:e.identity,userId:e.userId}}async withSystemDispatch(e){const t=this.currentRequestSystem;this.currentRequestSystem=!0;try{return await e()}finally{this.currentRequestSystem=t}}collectMetrics(){const e=this.state.storage.sql?.databaseSize;let{requests:t}=this.metrics,{errors:s}=this.metrics;try{const i=ls(this.state.storage.sql);t=i.requests,s=i.errors}catch{}let r=[];try{r=hs(this.state.storage.sql)}catch{}let n=[];try{n=Kr(this.state.storage.sql)}catch{}return{cache:this.reactiveCache?this.reactiveCache.stats():null,databaseSize:typeof e=="number"?e:null,errors:s,functions:this.collectFunctionStats().functions,history:this.collectFunctionMetricBuckets(),indexHits:r,queryStats:n,requests:t,shard:this.state.id?.name??ee,sinceMs:this.metrics.sinceMs,uptimeMs:Date.now()-this.metrics.sinceMs}}recordFunctionCall(e,t,s,r,n,i=!1){const o=Date.now(),c=r?[...r]:[],d=n?[...n].map(m=>Wn(m)).filter(m=>m!==void 0):[];try{ps(this.state.storage.sql,{conflicted:i,durationMs:t,errored:s!==void 0,errorMessage:s,indexHits:d,path:e,scannedTables:c,ts:o})}catch{}const u=this.functionStats.get(e),l=u??{calls:0,conflicts:0,errors:0,lastCalledAt:o,lastErrorAt:null,lastErrorMessage:null,maxDurationMs:0,path:e,scannedTables:[],scans:0,totalDurationMs:0};l.calls+=1,l.totalDurationMs+=t,l.maxDurationMs=Math.max(l.maxDurationMs,t),l.lastCalledAt=o,c.length>0&&(l.scans+=c.length,fs(l.scannedTables,c)),s!==void 0&&(l.errors+=1,l.lastErrorAt=o,l.lastErrorMessage=s),i&&(l.conflicts+=1),u===void 0&&this.functionStats.set(e,l)}flushStmtSamples(){const e=this.currentStmtSamples;if(!(!e||e.length===0))try{const t=this.state.storage.sql;for(const[s,r,n,i]of e)try{Hr(t,s,r,n,i)}catch{}}catch{}}collectFunctionStats(){try{return{functions:ms(this.state.storage.sql),sinceMs:this.metrics.sinceMs}}catch{return{functions:[...this.functionStats.values()].toSorted((e,t)=>t.lastCalledAt-e.lastCalledAt),sinceMs:this.metrics.sinceMs}}}collectFunctionMetricBuckets(){try{return ys(this.state.storage.sql)}catch{return[]}}maybeWarnRootSize(){if(S.rootSizeWarned||this.state.id?.name!==ee)return;const e=this.state.storage.sql?.databaseSize;typeof e!="number"||e<nn||(S.rootSizeWarned=!0,console.warn(`[@lunora/do] __root__ Durable Object SQLite size is ${String(e)} bytes (>= 1 GiB, 10% of the 10 GiB per-DO ceiling). Plan a \`.shardBy()\` migration before you hit the wall. See https://lunora.sh/docs/concepts/sharding for guidance.`))}errorToResponse(e){const{body:t,redacted:s,status:r}=q(e,{encodeData:R,fallbackCode:"RPC_FAILED",redactedMessage:"internal error"});return s&&console.error("[@lunora/do] internal error:",e),y({error:t},r)}async handleBatchRpc(e){let t;try{t=await e.json()}catch{return y({error:{code:"BAD_REQUEST",message:"invalid JSON body"}},400)}if(!Array.isArray(t.calls))return y({error:{code:"BAD_REQUEST",message:"batch `calls` must be an array"}},400);if(t.calls.length>et)return y({error:{code:"BAD_REQUEST",message:`batch exceeds the ${String(et)}-call limit`}},400);const s=[];let r;for(const n of t.calls){const i=await this.dispatchBatchEntry(e,n);i.bookmark!==void 0&&(r=i.bookmark),s.push({body:i.body,id:i.id,status:i.status})}return y({results:s},200,$(r))}async dispatchBatchEntry(e,t){try{const s=await this.fetch(mr(e,t));return{body:await s.json(),bookmark:s.headers.get("x-d1-bookmark")??void 0,id:t.id,status:s.status}}catch(s){const{body:r,status:n}=q(s,{fallbackCode:"BATCH_ENTRY_FAILED"});return{body:{error:r},bookmark:void 0,id:t?.id,status:n}}}async handleAdminRpc(e,t,s){if(!this.isAdminAuthorized(e))return y({error:{code:"ADMIN_FORBIDDEN",message:"admin introspection is disabled or the bearer token is invalid"}},403);try{const r=this.readAdminOp(t,s);if(r)return y({result:r.result},200);if(t===h.runMigration){const i=un(s),o=await this.runShardDataMigration(i);return await this.flushChangedTables(),this.recordAudit("runMigration",{id:i.id,detail:{changed:o.changed,direction:o.direction,dryRun:o.dryRun,processed:o.processed}}),y({result:o},200)}if(t===h.exportShard){const i=rs(s),o=await this.runShardExport({batchSize:i.batchSize,tables:i.tables});return y({result:{rows:o}},200)}if(t===h.importShard){const i=as(s),o=await this.runShardImport({rows:i.rows,startLine:i.startLine});return await this.flushChangedTables(),this.recordAudit("importShard",{detail:{conflicts:o.conflicts,errors:o.errors.length,inserted:o.inserted}}),y({result:o},200)}if(t===h.writeRow){const i=fn(s),o=await this.runShardWrite(i);return await this.flushChangedTables(),this.recordAudit("writeRow",{table:i.table,id:o.id??i.id,detail:{op:o.op}}),y({result:o},200)}if(t===h.deleteRows){const i=_n(s),o=await this.runShardBulkDelete(i);return await this.flushChangedTables(),this.recordAudit("deleteRows",{table:i.table,detail:{deleted:o.deleted,hasMore:o.hasMore}}),y({result:o},200)}if(t===h.clearTable){const i=In(s),o=await this.runShardBulkDelete(i);return await this.flushChangedTables(),this.recordAudit("clearTable",{table:i.table,detail:{deleted:o.deleted,hasMore:o.hasMore}}),y({result:o},200)}if(t===h.rankBefore){const i=await this.runShardRankBefore(Un(s));return y({result:i},200)}if(t===h.rankPage){const i=await this.runShardRankPage(Fn(s));return y({result:i},200)}if(t===h.cdcSync){const i=this.runShardCdcSync(Kn(s));return y({result:i},200)}if(t===h.applyCdc){const i=await this.runShardApplyCdc(Hn(s));return await this.flushChangedTables(),this.recordAudit("applyCdc",{detail:{applied:i.applied}}),y({result:i},200)}return t===h.runAs?this.handleRunAs(s):await this.handleExtraAdminOp(t,s)||y({error:{code:"UNKNOWN_ADMIN_OP",message:`unknown admin op: ${t}`}},404)}catch(r){return this.errorToResponse(r)}}async handleExtraAdminOp(e,t){if(e===h.recordAuthEvent)return this.handleRecordAuthEvent(t);if(e===h.recordContainerEvent)return this.handleRecordContainerEvent(t);if(e===h.recordMail)return this.handleRecordMail(t);if(e===h.clearCapturedMail)return this.handleClearCapturedMail();if(e===h.sendTestMail)return this.handleSendTestMail(t);if(e===h.recordQueueMessage)return this.handleRecordQueueMessage(t);if(e===h.clearQueueMessages)return this.handleClearQueueMessages();if(e===h.sendQueueMessage)return this.handleSendQueueMessage(t);if(e===h.replayQueueMessage)return this.handleReplayQueueMessage(t);if(e===h.createWorkflowInstance)return this.handleCreateWorkflowInstance(t);if(e===h.getWorkflowInstanceStatus)return this.handleGetWorkflowInstanceStatus(t);if(e===h.listFlags)return this.handleListFlags(t);if(e===h.explainIssue)return this.handleExplainIssue(t);const s=this.aiAdminHandlers()[e];if(s!==void 0)return s(t);const r=await this.handleIssueTriageOp(e,t);return r!==void 0?r:this.handlePitrAdminOp(e,t)}async handleIssueTriageOp(e,t){const s=this.parseIssueTriagePatch(e,t);if(s===void 0)return;const r=gn(t),n=typeof t.updatedBy=="string"?t.updatedBy:void 0,i=this.state.storage.sql,o=kr(i,r,s,Date.now(),n);return this.recordChangedTable(j),await this.flushChangedTables(),this.recordAudit(e.slice(_.length),{detail:{...s,hash:r}}),y({result:{state:o}},200)}parseIssueTriagePatch(e,t){if(e===h.resolveIssue)return{status:"resolved"};if(e===h.ignoreIssue)return{status:"ignored"};if(e===h.assignIssue)return{assignee:Sn(t),status:"open"};if(e===h.setIssueSeverity)return{severity:bn(t)}}handleRecordAuthEvent(e){const t=kn(e);try{ns(this.state.storage.sql,{outcome:t.outcome,ts:Date.now()})}catch{}return y({result:{recorded:!0}},200)}async handleRecordContainerEvent(e){const t=Nn(e);if(this.logs.push(t),t.level==="error"||t.exitCode!==void 0&&t.exitCode!==0){const s={durationMs:0,errorMessage:t.message,functionPath:t.functionPath,outcome:"error",shardKey:this.state.id?.name,ts:t.timestamp};this.persistRequestLog(s,this.requestLogConfig()),this.recordChangedTable(N),await this.flushChangedTables()}return y({result:{recorded:!0}},200)}async handleRunAs(e){const t=On(e),s=await this.withRequestIdentity(t.userId,t.identity,()=>this.handleRpc(t.functionPath,t.args));return await this.flushChangedTables(),this.recordAudit("runAs",{detail:{functionPath:t.functionPath,runAsUserId:t.userId}}),y({result:s},200)}resolveWorkflowBinding(e){const t=this.workflowsMetadata().workflows.find(r=>r.exportName===e);if(!t)throw new f("BAD_REQUEST",`workflow "${e}" is not declared`);const s=this.env?.[t.binding];if(typeof s!="object"||s===null||typeof s.create!="function"||typeof s.get!="function")throw new f("BAD_REQUEST",`workflow binding "${t.binding}" is not available on this deployment`);return s}async handleCreateWorkflowInstance(e){const t=En(e),s=await this.resolveWorkflowBinding(t.exportName).create({id:t.id,params:t.params}),r=await s.status(),n={id:s.id,status:At(r.status)};return this.recordAudit("createWorkflowInstance",{id:s.id,detail:{exportName:t.exportName}}),y({result:n},200)}async handleGetWorkflowInstanceStatus(e){const t=wn(e),s=await(await this.resolveWorkflowBinding(t.exportName).get(t.id)).status(),r={error:Rn(s.error),id:t.id,output:s.output,status:At(s.status)};return y({result:r},200)}async handleListFlags(e){const t=e.context,s=typeof t=="object"&&t!==null&&!Array.isArray(t)?t:void 0,r=await this.evaluateFlags(s);return y({result:r},200)}async withRequestIdentity(e,t,s){const r=this.currentRequestUserId,n=this.currentRequestIdentity;this.currentRequestUserId=e,this.currentRequestIdentity=t;try{return await s()}finally{this.currentRequestUserId=r,this.currentRequestIdentity=n}}handleRecordMail(e){const t=$n(e),s=Ge(this.state.storage.sql,t,Date.now());return y({result:s},200)}handleClearCapturedMail(){const e=ks(this.state.storage.sql);return y({result:e},200)}handleSendTestMail(e){const t=Ln(e),s=Ge(this.state.storage.sql,t,Date.now());return y({result:s},200)}handleRecordQueueMessage(e){const t=xn(e),s=zr(this.state.storage.sql,t,Date.now());return y({result:s},200)}handleClearQueueMessages(){const e=Yr(this.state.storage.sql);return y({result:e},200)}async handleSendQueueMessage(e){const t=Pn(e),{binding:s}=this.resolveQueueBinding(t.exportName);let r;return t.batch===void 0?(await s.send(t.body,{contentType:t.contentType,delaySeconds:t.delaySeconds}),r=1):(await s.sendBatch(t.batch.map(n=>({body:n,contentType:t.contentType,delaySeconds:t.delaySeconds}))),r=t.batch.length),this.recordAudit("sendQueueMessage",{detail:{count:r,exportName:t.exportName}}),y({result:{sent:r}},200)}async handleExplainIssue(e){const t=await _s(this.env?.AI,e);return t.degraded?t.reason!=="no-ai-binding"&&this.recordAudit("explainIssue",{detail:{groundedId:t.groundedId,reason:t.reason}}):this.recordAudit("explainIssue",{detail:{groundedId:t.groundedId,model:t.model}}),y({result:t},200)}async handleGenerateSql(e){this.ensureMigrated();const t=this.state.storage.sql,s=je(t).map(n=>({columns:this.tableColumns(n.name).map(i=>i.name),table:n.name})),r=await Ga(this.env?.AI,e,s);return r.degraded?r.reason!=="no-ai-binding"&&this.recordAudit("aiGenerateSql",{detail:{reason:r.reason}}):this.recordAudit("aiGenerateSql",{detail:{sql:r.sql}}),y({result:r},200)}aiAdminHandlers(){return{[h.aiAvailable]:()=>Promise.resolve(this.handleAiAvailable()),[h.aiChartConfig]:async e=>this.handleAiChartConfig(e),[h.aiGenerateSql]:async e=>this.handleGenerateSql(e),[h.aiTableFilter]:async e=>this.handleAiTableFilter(e)}}async handleAiTableFilter(e){this.ensureMigrated();const t=typeof e.table=="string"?e.table:"",s=t===""?[]:this.tableColumns(t).map(n=>n.name),r=await Qa(this.env?.AI,e,s);return r.degraded&&r.reason!=="no-ai-binding"&&this.recordAudit("aiTableFilter",{detail:{reason:r.reason,table:t}}),y({result:r},200)}handleAiAvailable(){return y({result:{available:this.env?.AI!==void 0}},200)}async handleAiChartConfig(e){const t=Array.isArray(e.columns)?e.columns.filter(o=>typeof o=="string").slice(0,64):[],s=typeof e.types=="object"&&e.types!==null?e.types:void 0,r=s===void 0?void 0:Object.fromEntries(Object.entries(s).filter(o=>typeof o[1]=="string")),n=typeof e.rowCount=="number"?e.rowCount:0,i=await za(this.env?.AI,e,{columns:t,rowCount:n,types:r});return i.degraded&&i.reason!=="no-ai-binding"&&this.recordAudit("aiChartConfig",{detail:{reason:i.reason}}),y({result:i},200)}async handleReplayQueueMessage(e){const t=Dn(e),s=Xr(this.state.storage.sql,t.id);if(s===void 0)throw new f("BAD_REQUEST",`replayQueueMessage: captured message "${t.id}" was not found`,{status:404});if(Gr(s.body))throw new f("BAD_REQUEST",`replayQueueMessage: captured message "${t.id}" has a truncated or unserializable body and can't be replayed faithfully`,{status:422});const r=t.target??this.resolveReplayTarget(s.queue)??s.exportName;if(typeof r!="string"||r==="")throw new f("BAD_REQUEST",`replayQueueMessage: captured message "${t.id}" has no declared producer to replay onto (pass \`target\`)`);const{binding:n}=this.resolveQueueBinding(r);return await n.send(s.body),this.recordAudit("replayQueueMessage",{detail:{messageId:s.messageId,target:r},id:t.id}),y({result:{sent:1,target:r}},200)}resolveQueueBinding(e){const t=this.queuesMetadata().queues.find(r=>r.exportName===e);if(!t)throw new f("BAD_REQUEST",`queue "${e}" is not declared`);const s=this.env?.[t.binding];if(typeof s!="object"||s===null||typeof s.send!="function")throw new f("BAD_REQUEST",`queue binding "${t.binding}" is not available on this deployment`);return{binding:s,metadata:t}}resolveReplayTarget(e){const{queues:t}=this.queuesMetadata(),s=t.find(r=>r.deadLetterQueue===e);return s!==void 0?s.exportName:t.find(r=>r.name===e)?.exportName}recordAudit(e,t={}){const s=this.state.storage.sql,r=this.getCurrentUserId(),n=r===void 0?t.detail:{...t.detail,userId:r};hr(s,{detail:n,id:t.id,op:e,table:t.table,ts:Date.now()})}recordRequestLog(e,t,s,r,n,i){const o=this.requestLogConfig();if(r==="ok"&&!Xn(o.sampleRate))return;const c={cacheHit:this.currentRequestCacheHit,durationMs:s,errorMessage:i,functionPath:e,identity:this.currentRequestIdentity,outcome:r,redactedArgs:Object.keys(t).length===0?void 0:t,shardKey:this.state.id?.name,tablesRead:this.currentRequestReadTables===void 0?[]:[...this.currentRequestReadTables],tablesWritten:n,ts:Date.now(),userId:this.getCurrentUserId()};this.persistRequestLog(c,o)}persistRequestLog(e,t){const s={captureRaw:t.captureRaw,retention:t.retention};try{ua(this.state.storage.sql,e,s)}catch{}if(t.emit||e.outcome==="error")try{la(e,s)}catch{}}requestLogConfig(){const e=this.env??{};return{captureRaw:Je(this.env),emit:zn(e.LUNORA_REQUEST_LOG_EMIT,Je(this.env)),retention:Qn(e.LUNORA_REQUEST_LOG_RETENTION),sampleRate:Jn(e.LUNORA_REQUEST_LOG_SAMPLE)}}async handlePitrAdminOp(e,t){const s=typeof t.time=="number"||typeof t.time=="string"?t.time:void 0;if(e===h.getPitrBookmark)return y({result:await Os(this.state.storage,s)},200);if(e!==h.pitrRestore)return;const r=t.restart===!0,n=typeof t.bookmark=="string"?t.bookmark:void 0,i=await $s(this.state.storage,{bookmark:n,time:s});this.cdcEnabled()&&rr(this.sql),this.recordAudit("pitrRestore",{detail:{restart:r,restoredTo:i.restoredTo,undoBookmark:i.undoBookmark}});const o=y({result:{...i,restarted:r}},200);return r&&this.state.abort?.("lunora PITR restore"),o}readAdminOp(e,t){this.ensureMigrated();const s=this.state.storage.sql,r=this.readAdminWildcardOp(e);if(r!==void 0)return{result:r,tables:new Set([E])};if(e===h.getAuditLog)return this.readAdminAuditLog(s,t);if(e===h.getRequestLog)return this.readAdminRequestLog(s,t);if(e===h.getIssues)return this.readAdminIssues(s,t);const n=this.readAdminDurableSignal(e,s,t);if(n)return n;if(e===h.readTablePage)return this.readAdminTablePage(s,t);if(e===h.facetColumn)return this.readAdminFacetColumn(s,t);if(e===h.runSql)return this.readAdminRunSql(s,t);const i=va(e,_,s,t,E);if(i!==void 0)return i;const o=this.readAdminTableSignal(e,s,t);return o||this.readAdminStorageSignal(e,s,t)||null}readAdminTableSignal(e,t,s){if(e===h.listTableIndexes||e===h.describeTable){const r=typeof s.table=="string"?s.table:"";return{result:e===h.describeTable?{columns:this.tableColumns(r)}:{indexes:this.tableIndexes(r)},tables:new Set([r===""?E:r])}}if(e===h.describeTables){const r=Array.isArray(s.tables)?s.tables.filter(n=>typeof n=="string"):[];return{result:{columnsByTable:Object.fromEntries(r.map(n=>[n,this.tableColumns(n)]))},tables:new Set(r.length===0?[E]:r)}}if(e===h.migrationStatus){const r=typeof s.id=="string"?s.id:void 0;return{result:{migrations:cs(t,r)},tables:new Set([E])}}}readAdminStorageSignal(e,t,s){if(e===h.storageReferences)return this.readAdminStorageReferences(t,s);if(e===h.storageOrphans)return this.readAdminStorageOrphans(t,s)}readAdminStorageReferences(e,t){const s=Array.isArray(t.keys)?t.keys.filter(r=>typeof r=="string"):[];return{result:bs(e,this.storageColumns(),s),tables:new Set([E])}}readAdminStorageOrphans(e,t){const s=Array.isArray(t.liveKeys)?t.liveKeys.filter(n=>typeof n=="string"):[],r=Za(e,this.storageColumns(),s);return r.truncated&&console.warn(`[@lunora/do] storageOrphans scan truncated after checking ${String(r.scanned)} storage references; reporting the first ${String(r.references.length)} dangling reference(s).`),{result:r,tables:new Set([E])}}readAdminWildcardOp(e){if(e===h.listTables)return je(this.state.storage.sql);if(e===h.getMetrics)return this.collectMetrics();if(e===h.getFunctionStats)return this.collectFunctionStats();if(e===h.listSubscriptions)return this.collectSubscriptions();if(e===h.getFanoutMetrics)return this.collectFanoutMetrics();if(e===h.getLogs)return{entries:this.logs.entries()};if(e===h.getTraces){const t=Oa(this.spans.entries());return{total:t.total,traces:t.traces}}if(e===h.getMetricSeries)return{series:this.metricSeries.entries()};if(e===h.getMetricHistory)return Pr(this.sql);if(e===h.getSettings)return Zs(this.env);if(e===h.getSecurityAudit)return er(this.env);if(e===h.getAdvisories)return{advisories:[...this.advisories(),...this.runtimeAdvisories()]};if(e===h.getAdvisorProcedures)return{procedures:this.advisorProcedures()};if(e===h.rlsPolicies)return this.rlsMetadata();if(e===h.maskPolicies)return this.maskMetadata();if(e===h.storageRules)return this.storageRulesMetadata();if(e===h.studioFeatures)return this.studioFeatures();if(e===h.listWorkflows)return this.workflowsMetadata();if(e===h.listQueues)return this.queuesMetadata()}collectSubscriptions(){return Es(this.state.getWebSockets().map(e=>this.readAttachment(e)))}collectFanoutMetrics(){const e=ws(this.state.getWebSockets().map(s=>this.readAttachment(s))),t=this.relay?.relayCount()??0;return{...e,maxRelays:this.relay?.maxRelays()??Le,promoted:t>0,relayCount:t,shapePoke:this.fanout.shapePoke,sinceMs:this.metrics.sinceMs,whisper:this.fanout.whisper}}readAdminAuditLog(e,t){Oe(e);const s=typeof t.limit=="number"?t.limit:void 0,r=typeof t.sinceSeq=="number"?t.sinceSeq:void 0;return{result:{entries:pr(e,{limit:s,sinceSeq:r})},tables:new Set([E])}}readAdminRequestLog(e,t){z(e);const s=t.outcome==="ok"||t.outcome==="error"?t.outcome:void 0;return{result:{entries:ga(e,{functionPathPrefix:typeof t.functionPathPrefix=="string"?t.functionPathPrefix:void 0,limit:typeof t.limit=="number"?t.limit:void 0,outcome:s,shardKey:typeof t.shardKey=="string"?t.shardKey:void 0,sinceSeq:typeof t.sinceSeq=="number"?t.sinceSeq:void 0,tableTouched:typeof t.tableTouched=="string"?t.tableTouched:void 0,userId:typeof t.userId=="string"?t.userId:void 0})},tables:new Set([E])}}readAdminIssues(e,t){return z(e),{result:{issues:ba(e,{functionPathPrefix:typeof t.functionPathPrefix=="string"?t.functionPathPrefix:void 0,limit:typeof t.limit=="number"?t.limit:void 0,shardKey:typeof t.shardKey=="string"?t.shardKey:void 0,status:mn(t.status)?t.status:void 0,userId:typeof t.userId=="string"?t.userId:void 0})},tables:new Set([E])}}readAdminDurableSignal(e,t,s){if(e===h.getAuthMetrics)return this.readAdminAuthMetrics(t);if(e===h.getCapturedMail)return this.readAdminCapturedMail(t,s);if(e===h.getQueueMessages)return this.readAdminQueueMessages(t,s)}readAdminAuthMetrics(e){let t;try{t=is(e)}catch{t={attempts:0,failureRate:0,failures:0,history:[],sinceMs:0}}return{result:t,tables:new Set([E])}}readAdminCapturedMail(e,t){const s=typeof t.limit=="number"?t.limit:void 0;let r;try{r=Ms(e,{limit:s})}catch{r={entries:[]}}return{result:r,tables:new Set([Ns])}}readAdminQueueMessages(e,t){const s=typeof t.limit=="number"?t.limit:void 0,r=typeof t.queue=="string"?t.queue:void 0;let n;try{n=Jr(e,{limit:s,queue:r})}catch{n={entries:[]}}return{result:n,tables:new Set([M])}}readAdminTablePage(e,t){const s=typeof t.table=="string"?t.table:"";return{result:Ts(e,{filters:Me(t.filters),limit:typeof t.limit=="number"?t.limit:void 0,offset:typeof t.offset=="number"?t.offset:void 0,orderBy:vn(t.orderBy),refs:this.tableRefs(s),search:typeof t.search=="string"?t.search:void 0,skipCount:typeof t.skipCount=="boolean"?t.skipCount:void 0,table:s}),tables:new Set([s===""?E:s])}}readAdminFacetColumn(e,t){const s=typeof t.table=="string"?t.table:"";return{result:Rs(e,{column:typeof t.column=="string"?t.column:"",filters:Me(t.filters),limit:typeof t.limit=="number"?t.limit:void 0,search:typeof t.search=="string"?t.search:void 0,table:s}),tables:new Set([s===""?E:s])}}readAdminRunSql(e,t){const s=typeof t.sql=="string"?t.sql:"";return{result:Vs(e,s),tables:new Set([E])}}executeAdminSubscription(e,t){const s=this.readAdminOp(e,t);return s?{result:s.result,tables:s.tables}:null}async resolveReactiveOutcome(e,t,s,r){if(s)return this.executeAdminSubscription(e,t);if(e.startsWith(As)){const n=await this.runFlagSubscriptionRead(e,t,r);return n===null?null:{result:n,tables:new Set([E])}}return this.executeSubscription(e,t,r)}isIdentityIndependent(e){return e.startsWith(_)}resolveReactiveOutcomeDeduped(e,t,s,r,n){if(!this.isIdentityIndependent(e))return this.resolveReactiveOutcome(e,t,s,r);const i=Qe(e,t,null),o=n.get(i);if(o!==void 0)return o;const c=this.resolveReactiveOutcome(e,t,s,r);return n.set(i,c),c}isAdminAuthorized(e){const t=(this.env??{}).LUNORA_ADMIN_TOKEN;if(!t||t.length===0)return!1;const s=Ee(e.headers.get("authorization"));return s!==void 0&&te(s,t)}async handleStream(e,t,s,r){const n=this.executeStream(s,r);if(!n){e.send(JSON.stringify({error:{code:"NOT_FOUND",message:`stream not registered: ${s}`},id:t,type:"error"}));return}let i=this.streamCancellers.get(e);if(i||(i=new Map,this.streamCancellers.set(e,i)),i.size>=S.MAX_STREAMS_PER_SOCKET){try{e.send(JSON.stringify({error:{code:"TOO_MANY_STREAMS",message:`stream cap of ${String(S.MAX_STREAMS_PER_SOCKET)} reached on this socket`},id:t,type:"error"}))}catch{}return}const o=new AbortController;i.set(t,o),e.send(JSON.stringify({id:t,type:"ack"}));try{for await(const c of n.iterator(o.signal)){if(o.signal.aborted)break;await C(e),e.send(JSON.stringify({data:R(c),id:t,type:"chunk"}))}o.signal.aborted||e.send(JSON.stringify({id:t,type:"complete"}))}catch(c){const{body:d,redacted:u}=q(c,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"internal error"});u&&console.error("[@lunora/do] unhandled stream error:",c),e.send(JSON.stringify({error:{code:d.code,message:d.message},id:t,type:"error"}))}finally{i.delete(t),i.size===0&&this.streamCancellers.delete(e)}}async flushChangedTables(){const e=this.pendingChangedTables;if(this.pendingChangedTables=void 0,!(!e||e.size===0)){if(this.pendingRefreshTables)for(const t of e)this.pendingRefreshTables.add(t);else this.pendingRefreshTables=e;if(!this.refreshInFlight){if(typeof this.state.waitUntil=="function"){this.state.waitUntil(this.drainSubscriptionRefreshes());return}await this.drainSubscriptionRefreshes()}}}async drainSubscriptionRefreshes(){if(!this.refreshInFlight){this.refreshInFlight=!0;try{let e=this.pendingRefreshTables;for(;e&&e.size>0;){this.pendingRefreshTables=void 0;const t=this.currentCdcCursor(),s=this.currentCdcEpoch();await Promise.all([this.refreshSubscriptions(e),this.pokeShapeSubscribers(e,t,s),this.relay?.onFlush(e,t??0)]),e=this.pendingRefreshTables}}finally{this.refreshInFlight=!1}}}async refreshSubscriptions(e){const t=[...this.state.getWebSockets()],s=this.currentCdcCursor(),r=this.currentCdcEpoch(),n=new Map;await gt(t,async i=>{if(this.isSocketExpired(i)){this.dropExpiredSocket(i);return}const o=this.readAttachment(i);for(const[c,d]of Object.entries(o.subs)){const{functionPath:u}=d;if(!u)continue;const l=u.startsWith(_),m=this.subMemos.get(i)?.get(c);if(!(m&&!m.tables.has(E)&&!dn(m.tables,e)))try{const p=await this.resolveReactiveOutcomeDeduped(u,d.args??{},l,{identity:o.identity,userId:o.userId},n);if(!p)continue;await C(i),this.pushSubscriptionData(i,c,p,s,r)}catch{continue}}})}async seedSubscription(e,t,s,r,n){const i=s.args??{},o=this.readAttachment(e),c=await this.resolveReactiveOutcome(r,i,n,{identity:o.identity,userId:o.userId});if(!c)return;const{sinceEpoch:d,sinceSeq:u}=s,l=n||u===void 0?void 0:this.evaluateResume(u,c.tables,d),m=n?void 0:l?.epoch??this.currentCdcEpoch();if(l?.resumable){this.seedSubscriptionMemo(e,t,c);try{e.send(`{"type":"resume","id":${JSON.stringify(t)}${Tt(l.cursor??0,m)}}`)}catch{}return}this.pushSubscriptionData(e,t,c,l?.cursor??this.currentCdcCursor(),m)}async handleShapeSubscribe(e,t,s){const r=this.shapeSubscribe(e,t,s);if(r!=="ok"){const i=r==="too_many"?"TOO_MANY_SUBSCRIPTIONS":"SUBSCRIPTION_PERSIST_FAILED",o=r==="too_many"?`subscription cap of ${String(S.MAX_SUBSCRIPTIONS_PER_SOCKET)} reached on this socket`:"failed to persist shape subscription attachment";this.sendShapeSubscribeError(e,t,i,o);return}const n=await this.seedShapeSubscription(e,t,s);if(n!=="ok"){this.shapeUnsubscribe(e,t),this.sendShapeSubscribeError(e,t,n.code,n.message);return}try{e.send(JSON.stringify({id:t,type:"ack"}))}catch{}}sendShapeSubscribeError(e,t,s,r){try{e.send(JSON.stringify({code:s,error:{code:s,message:r},id:t,type:"error"}))}catch{}}async seedShapeSubscription(e,t,s){const r=this.readAttachment(e),n={identity:r.identity,userId:r.userId},i=await this.relay?.seedRelayShape(e,t,s,n);if(i!==void 0)return i;let o;try{o=this.resolveShape(s.name,s.args??{},n)}catch(c){this.recordShapeError(`shape:seed:${t}`,c);const{body:d}=q(c,{fallbackCode:"SHAPE_RESOLVE_FAILED",redactedMessage:"shape resolution failed"});return{code:d.code,message:d.message}}if(!o)return{code:"SHAPE_NOT_FOUND",message:`shape "${s.name}" not found or not permitted`};try{return o.global?await this.seedGlobalShape(e,t,o,n,r.connectionId??""):await this.seedOpLogShape(e,t,s,o)}catch(c){this.recordShapeError(`shape:seed:${t}`,c);const{body:d}=q(c,{fallbackCode:"SHAPE_SEED_FAILED",redactedMessage:"shape seed failed"});return{code:d.code,message:d.message}}}async seedOpLogShape(e,t,s,r){const{baseCheckpoint:n,cursor:i,epoch:o,rowsPatch:c}=this.computeOpLogShapeSeed(s,r);return await C(e),this.sendPoke(e,[{rowsPatch:c,shapeId:t}],i,o,n)&&this.recordShapeMemo(e,t,i),"ok"}computeOpLogShapeSeed(e,t){const s=this.sql,r=this.currentCdcCursor()??0,n=this.currentCdcEpoch(),i=this.cdcEnabled()?Ze(s):void 0,o=this.cdcEnabled()&&e.sinceSeq!==void 0&&e.sinceEpoch===n&&e.sinceSeq<=r&&(e.sinceSeq===r||i!==void 0&&i<=e.sinceSeq+1),c=o&&e.sinceSeq!==void 0?this.buildShapeDiff(s,t,e.sinceSeq,r):this.buildShapeSeed(s,t);return{baseCheckpoint:o?e.sinceSeq:void 0,cursor:r,epoch:n,rowsPatch:c}}async pokeShapeSubscribers(e,t,s){const r=[...this.state.getWebSockets()],n=t??this.currentCdcCursor()??0,i=this.sql,o=new Map;let c=0;const d=async l=>{if(this.isSocketExpired(l)){this.dropExpiredSocket(l);return}const m=this.readAttachment(l),{shapes:p}=m;if(p)try{const g={identity:m.identity,userId:m.userId},{emptyAdvanced:b,partAdvanced:Qt,parts:Fe}=this.collectShapePokeParts(l,p,g,e,n,i,o);for(const ue of b)this.recordShapeMemo(l,ue,n);if(Fe.length>0&&(await C(l),this.sendPoke(l,Fe,n,s,void 0))){c+=1;for(const ue of Qt)this.recordShapeMemo(l,ue,n)}}catch{}},u=Date.now();await gt(r,d),this.fanout.shapePoke=he(this.fanout.shapePoke,r.length,c,Date.now()-u)}collectShapePokeParts(e,t,s,r,n,i,o){const c=[],d=[],u=[];for(const[l,m]of Object.entries(t))try{const p=this.resolveShape(m.name,m.args??{},s);if(!p||p.global||!r.has(p.table))continue;const g=this.shapeMemos.get(e)?.get(l)?.cursor??0,b=this.buildShapeDiff(i,p,g,n,o);b.length>0?(c.push({rowsPatch:b,shapeId:l}),u.push(l)):d.push(l)}catch(p){this.recordShapeError(`shape:poke:${l}`,p)}return{emptyAdvanced:d,partAdvanced:u,parts:c}}readShapeOpRange(e,t,s,r,n){const i=`${t}\0${String(s)}\0${String(r)}`,o=n?.get(i);if(o!==void 0)return o;const c=new Map,d=new Set([t]);let u=s;for(;;){const{changes:l,cursor:m}=this.readShapeCdcPage(e,u,d);for(const p of l)c.set(p.id,p);if(l.length===0||m===u||m>=r)break;u=m}return n?.set(i,c),c}readShapeCdcPage(e,t,s){return fe(e,{sinceSeq:t,tables:s})}buildShapeDiff(e,t,s,r,n){const i=this.readShapeOpRange(e,t.table,s,r,n);if(i.size===0)return[];const o=[...i.keys()],c=ar(e,t.table,t.effectiveWhere,o),d=[];for(const[u,l]of i){if(c.has(u)){l.doc!==void 0&&d.push({key:u,op:l.op,table:t.table,value:Ae(l.doc,t.columns)});continue}l.op!=="insert"&&d.push({key:u,op:"delete",table:t.table})}return d}buildShapeSeed(e,t){return nr(e,t.table,t.effectiveWhere).map(s=>({key:s.id,op:"insert",table:t.table,value:Ae(s.doc,t.columns)}))}async seedGlobalShape(e,t,s,r,n){const i=await this.readGlobalShapeRows(s,r);if(!this.withinGlobalShapeBound(i.length,`shape:seed:${t}`,s.table))return{code:"SHAPE_GLOBAL_TOO_LARGE",message:`global shape membership for "${s.table}" exceeds the ${String(S.GLOBAL_SHAPE_MAX_ROWS)}-row cap; narrow it with a shape predicate or an RLS read policy`};const{next:o,rowsPatch:c}=dt(i,new Map,{columns:s.columns,table:s.table});return await C(e),this.sendPoke(e,[{rowsPatch:c,shapeId:t}],this.currentCdcCursor()??0,this.currentCdcEpoch(),void 0)&&(this.recordGlobalSnapshot(e,t,o),this.saveGlobalSnapshot(n,t,o)),await this.scheduleGlobalPoll(),"ok"}async refreshGlobalShape(e,t,s,r,n){const i=await this.readGlobalShapeRows(s,r);if(!this.withinGlobalShapeBound(i.length,`shape:poll:${t}`,s.table))return;const o=this.readGlobalSnapshot(e,t,n),{next:c,rowsPatch:d}=dt(i,o,{columns:s.columns,table:s.table});if(d.length===0){this.recordGlobalSnapshot(e,t,c);return}await C(e),this.sendPoke(e,[{rowsPatch:d,shapeId:t}],this.currentCdcCursor()??0,this.currentCdcEpoch(),void 0)&&(this.recordGlobalSnapshot(e,t,c),this.saveGlobalSnapshot(n,t,c))}readGlobalSnapshot(e,t,s){const r=this.globalShapeSnapshots.get(e)?.get(t);if(r)return r;const n=this.loadGlobalSnapshot(s,t);return this.recordGlobalSnapshot(e,t,n),n}recordGlobalSnapshot(e,t,s){let r=this.globalShapeSnapshots.get(e);r||(r=new Map,this.globalShapeSnapshots.set(e,r)),r.set(t,s)}loadGlobalSnapshot(e,t){if(e==="")return new Map;try{return zs(this.sql,e,t)}catch{return new Map}}saveGlobalSnapshot(e,t,s){if(e!=="")try{Js(this.sql,e,t,s)}catch{}}async scheduleGlobalPoll(e){if(this.globalPollScheduled)return;const{setAlarm:t}=this.state.storage;if(t){this.globalPollScheduled=!0;try{await t.call(this.state.storage,e??Date.now()+S.GLOBAL_SHAPE_POLL_INTERVAL_MS)}catch{this.globalPollScheduled=!1}}}recordShapeError(e,t){this.logs.push({functionPath:e,level:"error",message:t instanceof Error?t.message:String(t),timestamp:Date.now()})}withinGlobalShapeBound(e,t,s){return e<=S.GLOBAL_SHAPE_MAX_ROWS?!0:(this.recordShapeError(t,new Error(`global shape membership for "${s}" (${String(e)} rows) exceeds the ${String(S.GLOBAL_SHAPE_MAX_ROWS)}-row cap; narrow it with a shape predicate or an RLS read policy`)),!1)}async pollGlobalShapes(){const e=[...this.state.getWebSockets()];let t=0;for(const s of e){if(this.isSocketExpired(s)){this.dropExpiredSocket(s);continue}const r=this.readAttachment(s),{shapes:n}=r;if(!n)continue;const i={identity:r.identity,userId:r.userId};t+=await this.pollSocketGlobalShapes(s,n,i,r.connectionId??"")}return t}async pollSocketGlobalShapes(e,t,s,r){let n=0;for(const[i,o]of Object.entries(t)){let c;try{c=this.resolveShape(o.name,o.args??{},s)}catch(d){n+=1,this.recordShapeError(`shape:poll:${i}`,d);continue}if(c?.global){n+=1;try{await this.refreshGlobalShape(e,i,c,s,r)}catch(d){this.recordShapeError(`shape:poll:${i}`,d)}}}return n}sendPoke(e,t,s,r,n){this.pokeSequence+=1;const i=`poke-${String(this.pokeSequence)}`,o=Ce(t,{baseCheckpoint:n,checkpoint:s,epoch:r,lastMutationId:this.socketClientWatermark(e),pokeId:i});try{for(const c of o)e.send(c);return!0}catch{return!1}}socketClientWatermark(e){const t=this.readAttachment(e),{clientId:s}=t;if(s!==void 0)try{return pe(this.sql,t.userId??"",s)}catch{return}}recordShapeMemo(e,t,s){let r=this.shapeMemos.get(e);r||(r=new Map,this.shapeMemos.set(e,r)),r.set(t,{cursor:s})}seedSubscriptionMemo(e,t,s){let r=this.subMemos.get(e);r||(r=new Map,this.subMemos.set(e,r)),r.set(t,{lastJson:JSON.stringify(R(s.result??null)),tables:s.tables})}pushSubscriptionData(e,t,s,r,n){let i=this.subMemos.get(e);i||(i=new Map,this.subMemos.set(e,i));const o=Tt(r,n),c=JSON.stringify(R(s.result??null)),d=i.get(t);if(d?.lastJson===c){d.tables=s.tables;const m=this.socketClientWatermark(e),p=m===void 0?"":`,"lastMutationId":${String(m)}`;D(e,`{"type":"settled","id":${JSON.stringify(t)}${p}${o}}`);return}const u=[],l=(d===void 0?void 0:Ls(d.lastJson,s.result,s.tables.values().next().value??"",u))===void 0?D(e,`{"type":"data","id":${JSON.stringify(t)},"data":${c}${o}}`):xs(e,t,u,o);i.set(t,{lastJson:l?c:d?.lastJson??an,tables:s.tables})}async isUpgradeAllowed(e){const t=this.env??{},s=t.LUNORA_ALLOWED_ORIGINS;if(s&&s.trim()!==""){const n=e.headers.get("origin");if(!n||!s.split(",").map(i=>i.trim()).filter(i=>i.length>0).includes(n))return!1}const r=t.LUNORA_WS_BEARER;if(r&&r.length>0){const n=this.suppliedWsToken(e);if(!n||!te(n,r)&&!await this.isAdminSocket(e))return!1}return!0}suppliedWsToken(e){const t=Ee(e.headers.get("authorization"));return t!==void 0?t:new URL(e.url).searchParams.get("token")??void 0}async isAdminSocket(e){const t=this.env??{},s=t.LUNORA_ADMIN_TOKEN;if(!s||s.length===0)return!1;const r=this.suppliedWsToken(e);if(r===void 0)return!1;if(await lr(s,r))return!0;const n=Ee(e.headers.get("authorization"))===void 0,i=sn.has((t.LUNORA_REQUIRE_EPHEMERAL_WS_TOKEN??"").trim().toLowerCase());return n&&i?!1:te(r,s)}armWebSocketKeepalive(){const e=this.state.setWebSocketAutoResponse;typeof e!="function"||typeof WebSocketRequestResponsePair>"u"||e.call(this.state,new WebSocketRequestResponsePair(en,tn))}async routeNonRpc(e,t){if(e.pathname==="/_lunora/relay"&&t.method==="POST")return this.relay?await this.relay.handleControl(t):new Response("relay tier inactive",{status:404});if(e.pathname==="/_lunora/route"&&t.method==="GET")return y({relayCount:this.relay?.relayCount()??0});if(e.pathname==="/rpc-batch"&&t.method==="POST")return this.handleBatchRpc(t);if(t.headers.get("Upgrade")==="websocket")return this.handleWebSocketUpgrade(t)}async handleWebSocketUpgrade(e){if(!await this.isUpgradeAllowed(e))return new Response("Forbidden",{status:403});const t=await this.isAdminSocket(e),s=new WebSocketPair,r=s[0],n=s[1];this.state.acceptWebSocket(n);const i=e.headers.get("x-lunora-userid")??void 0,o=It(e.headers.get("x-lunora-identity")),c=Number(e.headers.get("x-lunora-identity-exp")),d=Number.isFinite(c)&&c>0?c:void 0;return n.serializeAttachment?.({admin:t,connectionId:crypto.randomUUID(),subs:{},...d===void 0?{}:{expiresAt:d},...o===void 0?{}:{identity:o},...i===void 0?{}:{userId:i}}),new Response(null,{status:101,webSocket:r})}cdcEnabled(){try{return this.sql.exec("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?",Xe).toArray().length>0}catch{return!1}}isSocketExpired(e){const{expiresAt:t}=this.readAttachment(e);return typeof t=="number"&&Date.now()>=t}dropExpiredSocket(e){try{e.send(JSON.stringify({code:"TOKEN_EXPIRED",error:{code:"TOKEN_EXPIRED",message:"authentication token expired"},type:"error"})),e.close(4001,"token_expired")}catch{}}setWhisperMembership(e,t,s){const r=this.readAttachment(e),n=r.whispers??[],i=n.includes(t);if(s){if(i||n.length>=S.MAX_WHISPER_TOPICS_PER_SOCKET)return;r.whispers=[...n,t]}else{if(!i)return;const o=n.filter(c=>c!==t);o.length===0?delete r.whispers:r.whispers=o}try{e.serializeAttachment?.(r)}catch{}}allowWhisper(e){const t=Date.now(),s=this.whisperBuckets.get(e)??{last:t,tokens:S.WHISPER_RATE_BURST},r=Math.min(S.WHISPER_RATE_BURST,s.tokens+(t-s.last)/1e3*S.WHISPER_RATE_PER_SEC);return r<1?(this.whisperBuckets.set(e,{last:t,tokens:r}),!1):(this.whisperBuckets.set(e,{last:t,tokens:r-1}),!0)}async broadcastWhisper(e,t,s){if(!this.allowWhisper(e))return;const r=JSON.stringify(s??null);if(r.length>S.MAX_WHISPER_BYTES)return;const n=this.readAttachment(e).userId,i=n===void 0?"":`,"from":${JSON.stringify(n)}`,o=`{"type":"whisper","topic":${JSON.stringify(t)},"data":${r}${i}}`;this.deliverWhisperLocal(t,o,e),await this.relay?.forwardWhisper(t,o)}deliverWhisperLocal(e,t,s){let r=0,n=0;for(const i of this.state.getWebSockets())r+=1,!(i===s||this.readAttachment(i).whispers?.includes(e)!==!0)&&(D(i,t),n+=1);return this.fanout.whisper=he(this.fanout.whisper,r,n,0),n}readAttachment(e){const t=e.deserializeAttachment?.();return t&&typeof t=="object"&&"subs"in t&&t.subs?t:{subs:{}}}}export{nn as ROOT_DO_SIZE_WARN_BYTES,ee as ROOT_SHARD_NAME,S as ShardDO,Ls as subscriptionListDeltas};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{H as b,P as f,X as k,Y as n}from"./ctx-db-backfill-Hl48Dr77.mjs";import"@lunora/errors";import"drizzle-orm";import"./AGGREGATE_SQL_FUNCTION-QYaiuty4.mjs";import"./aggregateTableName-G-eXyjcz.mjs";import"./do-exec-BLe9lLrN.mjs";import"./do-sql-x0AjZhaN.mjs";import"./renderSql-B5lF5Jd9.mjs";import"./RANK_TIEBREAK-DtX8zQyc.mjs";import"./serialize-sql-DiRzL7A4.mjs";export{b as backfillAggregateIndexes,f as backfillRankIndexes,k as backfillSearchIndexes,n as backfillSearchIndexesForTable};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"@lunora/errors";import{sql as i}from"drizzle-orm";import{matchesStaticWhere as A}from"./AGGREGATE_SQL_FUNCTION-QYaiuty4.mjs";import{encodeAggregateKey as L,foldAggregateTally as w,aggregateTableName as I}from"./aggregateTableName-G-eXyjcz.mjs";import{r as f}from"./do-exec-BLe9lLrN.mjs";import{b,s as E,g as y,a as v,_ as M,m as j,N as C}from"./do-sql-x0AjZhaN.mjs";import{param as F}from"./renderSql-B5lF5Jd9.mjs";import{sortColumnName as x,matchesRankStaticWhere as z,encodePartitionKey as q,rankTableName as D}from"./RANK_TIEBREAK-DtX8zQyc.mjs";import{t as k}from"./serialize-sql-DiRzL7A4.mjs";const U=["de","en","es","fr","it","nl","none","pt"],B=e=>U.includes(e),W="a an and are as at be but by for if in into is it no not of on or such that the their then there these they this to was will with",X="aber als am an auch auf aus bei bin bis bist da dass der den des dem die das denn dir du ein eine für hat ich im in ist mit nicht noch nur oder sich sie sind über und von vor war wie wir zu zum zur",H="a al como con de del el en es la las lo los mas no o para pero por que se su sus un una uno y ya",Y="au aux avec ce ces dans de des du elle en et eux il je la le les leur lui ma mais me même mes moi mon ne nos notre nous on ou par pas pour qu que qui sa se ses son sur ta te tes toi ton tu un une vos votre vous y",K="a ai al alla anche che chi ci coi col come con da dal degli dei del della di do e ed gli ha hai hanno i il in la le lo ma mi ne nei nel non o per più quale quanto se si sono su sul tra un una uno vi",P="aan al als bij dan dat de der deze die dit door een en er het hij ij in is je kan me men met mij na naar niet nog nu of om ons ook op over te tot uit van voor was wat we wij zij zijn zo",V="a ao aos as até com como da das de do dos e em entre era essa esse esta este eu foi há isso já mais mas me mesmo meu na nas no nos num numa o os ou para pela pelo por qual que quem se sem seu só sua também te tem um uma você",G=/[\u0300-\u036F]/gu,O=e=>e.normalize("NFD").replaceAll(G,"").normalize("NFC").toLowerCase(),$=e=>new Set(O(e).split(" ")),J={de:$(X),en:$(W),es:$(H),fr:$(Y),it:$(K),nl:$(P),none:new Set,pt:$(V)},Q=2,Z=256,_=new Map,R=e=>{const o=e!==void 0&&B(e)?e:"none",n=_.get(o);if(n)return n;const r=J[o],s=c=>{const a=(O(c).match(/[\p{L}\p{N}]+/gu)??[]).filter(t=>t.length<=Z);return r.size===0?a:a.filter(t=>!r.has(t))},d={document:s,profile:`${o}-v${String(Q)}`,query:c=>{const a=s(c),t=new Set,u=[];for(let m=a.length-1;m>=0;m-=1){const l=a[m];t.has(l)||(t.add(l),u.unshift(l))}return u}};return _.set(o,d),d},ee=(e,o)=>e.profile!==o?{cursor:void 0,finished:!1,wipe:e.cursor!==void 0||e.done}:{cursor:e.cursor,finished:e.done,wipe:!1},ie=(e,o)=>{if(!o.includes("."))return e[o];let n=e;for(const r of o.split(".")){if(n===null||typeof n!="object"||Array.isArray(n))return;n=n[r]}return n},oe=(e,o)=>`${e}__fts_${o}`,ne="__text__",T="__id__",re=1e3,te=(e,o)=>o.document(e),S=(e,o)=>ie(e,o),se=e=>typeof e=="string"?e:e==null?"":typeof e=="number"||typeof e=="bigint"||typeof e=="boolean"?String(e):JSON.stringify(e)??"",ye=(e,o,n)=>e!==void 0&&o!==void 0&&S(e,n.field)===S(o,n.field),ae=(e,o)=>te(se(S(e,o.field)),R(o.language)).slice(0,re).join(" "),h="__lunora_search_state",de=e=>{const o=()=>{try{f(e,i`ALTER TABLE ${i.identifier(h)} ADD COLUMN ${i.identifier("profile")} TEXT`)}catch{}};f(e,i`CREATE TABLE IF NOT EXISTS ${i.identifier(h)} (${i.identifier("companion")} TEXT PRIMARY KEY, ${i.identifier("cursor")} TEXT, ${i.identifier("done")} INTEGER NOT NULL DEFAULT 0, ${i.identifier("profile")} TEXT)`),o()},fe=e=>e===1||e===!0||e==="1",ce=(e,o)=>{const n=f(e,i`SELECT ${i.identifier("cursor")}, ${i.identifier("done")}, ${i.identifier("profile")} FROM ${i.identifier(h)} WHERE ${i.identifier("companion")} = ${o}`).toArray()[0];return n?{cursor:n.cursor??void 0,done:fe(n.done),profile:n.profile??void 0}:{cursor:void 0,done:!1,profile:void 0}},le=(e,o,n,r,s)=>{const d=n??null;f(e,i`INSERT INTO ${i.identifier(h)} (${i.identifier("companion")}, ${i.identifier("cursor")}, ${i.identifier("done")}, ${i.identifier("profile")}) VALUES (${o}, ${d}, ${r?1:0}, ${s}) ON CONFLICT (${i.identifier("companion")}) DO UPDATE SET ${i.identifier("cursor")} = excluded.${i.identifier("cursor")}, ${i.identifier("done")} = excluded.${i.identifier("done")}, ${i.identifier("profile")} = excluded.${i.identifier("profile")}`)},ue=(e,o,n)=>{const r=I(o,n.name);if(f(e,i`SELECT COUNT(*) AS count FROM ${i.identifier(r)}`).one().count>0)return;const s=n.by??[],d=new Map,c=f(e,i`SELECT id, _creationTime, ${i.identifier(E)} FROM ${i.identifier(o)}`).toArray();for(const a of c){const t=y(a);if(!t||n.where&&!A(t,n.where))continue;const u=L(s,t);w(d,u,n,t)}for(const[a,t]of d)f(e,i`INSERT INTO ${i.identifier(r)} (${v}, ${M}, ${j}) VALUES (${a}, ${t.value}, ${t.count})`)},Oe=(e,o)=>{for(const[n,r]of Object.entries(o.tables))if(!(r.shardMode?.kind==="global"||!r.aggregateIndexes))for(const s of r.aggregateIndexes)ue(e,n,s)},me=(e,o,n)=>{const r=D(o,n.name);if(f(e,i`SELECT COUNT(*) AS count FROM ${i.identifier(r)}`).one().count>0)return;const s=n.sortBy.map((a,t)=>x(t)),d=i.join(["__id__","__partition__",...s].map(a=>i.identifier(a)),i`, `),c=f(e,i`SELECT id, _creationTime, ${i.identifier(E)} FROM ${i.identifier(o)}`).toArray();for(const a of c){const t=y(a);if(!t||n.where&&!z(t,n.where))continue;const u=q(n.partitionBy??[],t),m=n.sortBy.map(p=>k(t[p.field]??null)),l=i.join([t._id,u,...m].map(p=>F(p)),i`, `);f(e,i`INSERT INTO ${i.identifier(r)} (${d}) VALUES (${l})`)}},Re=(e,o)=>{for(const[n,r]of Object.entries(o.tables))if(!(r.shardMode?.kind==="global"||!r.rankIndexes))for(const s of r.rankIndexes)me(e,n,s)},g=500,N=(e,o,n)=>{const r=oe(o,n.name),{profile:s}=R(n.language),d=ee(ce(e,r),s);if(d.finished)return!0;d.wipe&&f(e,i`DELETE FROM ${i.identifier(r)}`);const{cursor:c}=d,a=f(e,c===void 0?i`SELECT id, _creationTime, ${i.identifier(E)} FROM ${i.identifier(o)} ORDER BY id ASC LIMIT ${i.raw(String(g))}`:i`SELECT id, _creationTime, ${i.identifier(E)} FROM ${i.identifier(o)} WHERE id > ${c} ORDER BY id ASC LIMIT ${i.raw(String(g))}`).toArray();let t=c;for(const m of a){const{id:l}=m;if(typeof l!="string")continue;t=l;const p=C(m);if(!p){f(e,i`DELETE FROM ${i.identifier(r)} WHERE ${i.identifier(T)} = ${l}`);continue}f(e,i`DELETE FROM ${i.identifier(r)} WHERE ${i.identifier(T)} = ${l}`),f(e,i`INSERT INTO ${i.identifier(r)} (${i.identifier(ne)}, ${i.identifier(T)}) VALUES (${ae(p,n)}, ${l})`)}const u=a.length<g;return le(e,r,t,u,s),u},Ne=(e,o,n)=>{if(b(e))for(const r of n.searchIndexes??[])r.staged||N(e,o,r)},Ae=(e,o)=>{if(b(e)){de(e);for(const[n,r]of Object.entries(o.tables))if(!(r.shardMode?.kind==="global"||!r.searchIndexes))for(const s of r.searchIndexes){let d=!1;for(;!d;)d=N(e,n,s)}}};export{R as A,Oe as H,Re as P,T,Ae as X,Ne as Y,ne as a,oe as c,de as l,te as n,h as o,ye as u,ae as y};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import{l as I,a as N,T as S,Y as g,c as R}from"./ctx-db-backfill-Hl48Dr77.mjs";import"@lunora/errors";import{sql as e}from"drizzle-orm";import{aggregateTableName as h}from"./aggregateTableName-G-eXyjcz.mjs";import{migrateCdcLog as p,migrateCdcMeta as l}from"./CDC_LOG_TABLE-E_J5LPoK.mjs";import{u as O,_ as u,E as C,a as U}from"./schema-history-YGeVjyvV.mjs";import{r as s}from"./do-exec-BLe9lLrN.mjs";import{s as X,$,p as T,L as B,b,a as x,_ as Y,m,T as M}from"./do-sql-x0AjZhaN.mjs";import{sortColumnName as D,rankTableName as F}from"./RANK_TIEBREAK-DtX8zQyc.mjs";const j=(n,t,o)=>{for(const i of o.indexes){const r=`${t}_${i.name}`,a=e.join(i.fields.map(_=>$(_)),e`, `);s(n,T(r,t,a,i.unique??!1))}for(const[i,r]of B(o)){if(!r.unique)continue;const a=`${t}_unique_${i}`;s(n,T(a,t,$(i),!0))}},k=(n,t,o)=>{if(!(!o.searchIndexes||o.searchIndexes.length===0||!b(n))){for(const i of o.searchIndexes){const r=R(t,i.name);s(n,e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(r)} USING fts5(${e.identifier(N)}, ${e.identifier(S)} UNINDEXED)`),s(n,e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(`${r}__vocab`)} USING fts5vocab(${e.identifier(r)}, ${e.raw("instance")})`)}g(n,t,o)}},y=(n,t,o)=>{if(o.geoIndexes)for(const i of o.geoIndexes){const r=M(t,i.name);s(n,e`CREATE TABLE IF NOT EXISTS ${e.identifier(r)} (${e.identifier("__id__")} TEXT PRIMARY KEY, ${e.identifier("__geohash__")} TEXT NOT NULL, ${e.identifier("__lat__")} REAL NOT NULL, ${e.identifier("__lng__")} REAL NOT NULL)`);const a=`${t}__geo_${i.name}__btree`;s(n,T(a,r,e`${e.identifier("__geohash__")} ASC, ${e.identifier("__id__")} ASC`,!1))}},G=(n,t,o)=>{if(o.aggregateIndexes)for(const i of o.aggregateIndexes){const r=h(t,i.name);s(n,e`CREATE TABLE IF NOT EXISTS ${e.identifier(r)} (${x} TEXT PRIMARY KEY, ${Y} REAL, ${m} INTEGER NOT NULL DEFAULT 0)`),s(n,e`PRAGMA table_info(${e.identifier(r)})`).toArray().some(a=>a.name==="__count__")||s(n,e`ALTER TABLE ${e.identifier(r)} ADD COLUMN ${m} INTEGER NOT NULL DEFAULT 0`)}},P=(n,t,o)=>{if(o.rankIndexes)for(const i of o.rankIndexes){const r=F(t,i.name),a=i.sortBy.map((f,d)=>D(d)),_=a.map(f=>e`${e.identifier(f)} BLOB`),c=_.length>0?e`, ${e.join(_,e`, `)}`:e``;s(n,e`CREATE TABLE IF NOT EXISTS ${e.identifier(r)} (${e.identifier("__id__")} TEXT PRIMARY KEY, ${e.identifier("__partition__")} TEXT NOT NULL${c})`);const E=[e`${e.identifier("__partition__")} ASC`];for(const[f,d]of a.entries()){const A=i.sortBy[f]?.direction;E.push(e`${e.identifier(d)} ${e.raw(A==="desc"?"DESC":"ASC")}`)}E.push(e`${e.identifier("__id__")} ASC`);const L=`${t}__rank_${i.name}__btree`;s(n,T(L,r,e.join(E,e`, `),!1))}},W=(n,t,o={})=>{o.schemaSnapshot!==void 0&&O(n,o.schemaSnapshot.hash,o.schemaSnapshot.json),I(n);for(const[i,r]of Object.entries(t.tables))r.shardMode?.kind!=="global"&&(s(n,e`CREATE TABLE IF NOT EXISTS ${e.identifier(i)} (
|
|
2
|
+
id TEXT PRIMARY KEY,
|
|
3
|
+
_creationTime REAL NOT NULL,
|
|
4
|
+
${e.identifier(X)} TEXT NOT NULL
|
|
5
|
+
)`),j(n,i,r),k(n,i,r),y(n,i,r),G(n,i,r),P(n,i,r));o.cdc&&(p(n),l(n),u(n)),C(n),U(n)};export{W as runShardMigrations};
|
package/dist/packem_shared/{serveRelationFanout-DBA2hP-k.mjs → serveRelationFanout-BqVyM54k.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as i}from"@lunora/errors";import{RELATION_FUNCTION_PREFIX as r}from"./ADMIN_FUNCTIONS-
|
|
1
|
+
import{LunoraError as i}from"@lunora/errors";import{RELATION_FUNCTION_PREFIX as r}from"./ADMIN_FUNCTIONS-B0xlQJ4w.mjs";const h=async(s,n,l,t)=>{const o=typeof t.table=="string"?t.table:"",a=s.tables[o];if(!a)throw new i("UNKNOWN_TABLE",`${r} unknown table "${o}"`,{status:404});if(a.shardMode?.kind==="global")throw new i("BAD_REQUEST",`${r} table "${o}" is global, not shard-local`);const e=t.where??void 0;return l===`${r}count`?n.count(o,e):(await n.findMany(o,{orderBy:t.orderBy,where:e,with:t.with})).page};export{h as serveRelationFanout};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/do",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.57",
|
|
4
4
|
"description": "Lunora Durable Objects: ShardDO (SQLite, OCC, hibernated WebSocket subscriptions) and SessionDO",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cloudflare",
|
|
@@ -49,8 +49,7 @@
|
|
|
49
49
|
"@lunora/errors": "1.0.0-alpha.9",
|
|
50
50
|
"@lunora/fingerprint": "1.0.0-alpha.4",
|
|
51
51
|
"@visulima/redact": "3.0.0",
|
|
52
|
-
"drizzle-orm": "^0.45.2"
|
|
53
|
-
"@lunora/search-core": "1.0.0-alpha.0"
|
|
52
|
+
"drizzle-orm": "^0.45.2"
|
|
54
53
|
},
|
|
55
54
|
"engines": {
|
|
56
55
|
"node": "^22.15.0 || >=24.11.0"
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as M}from"@lunora/errors";import{q as d}from"./quote-identifier-CGiYFBvY.mjs";const K="__lunora_admin__:",X="__lunora_relation__:",Y="__lunora_flags__:",z={applyCdc:"__lunora_admin__:applyCdc",aiAvailable:"__lunora_admin__:aiAvailable",aiChartConfig:"__lunora_admin__:aiChartConfig",aiGenerateSql:"__lunora_admin__:aiGenerateSql",aiTableFilter:"__lunora_admin__:aiTableFilter",assignIssue:"__lunora_admin__:assignIssue",backRelationCounts:"__lunora_admin__:backRelationCounts",cdcSync:"__lunora_admin__:cdcSync",clearCapturedMail:"__lunora_admin__:clearCapturedMail",clearQueueMessages:"__lunora_admin__:clearQueueMessages",clearTable:"__lunora_admin__:clearTable",createWorkflowInstance:"__lunora_admin__:createWorkflowInstance",deleteRows:"__lunora_admin__:deleteRows",describeTable:"__lunora_admin__:describeTable",describeTables:"__lunora_admin__:describeTables",explainIssue:"__lunora_admin__:explainIssue",exportShard:"__lunora_admin__:exportShard",facetColumn:"__lunora_admin__:facetColumn",getAdvisories:"__lunora_admin__:getAdvisories",getAuditLog:"__lunora_admin__:getAuditLog",getAuthMetrics:"__lunora_admin__:getAuthMetrics",getCapturedMail:"__lunora_admin__:getCapturedMail",getFanoutMetrics:"__lunora_admin__:getFanoutMetrics",getFunctionStats:"__lunora_admin__:getFunctionStats",getIssues:"__lunora_admin__:getIssues",getMetricHistory:"__lunora_admin__:getMetricHistory",getMetricSeries:"__lunora_admin__:getMetricSeries",listSubscriptions:"__lunora_admin__:listSubscriptions",listTableIndexes:"__lunora_admin__:listTableIndexes",getLogs:"__lunora_admin__:getLogs",getMetrics:"__lunora_admin__:getMetrics",getPitrBookmark:"__lunora_admin__:getPitrBookmark",getQueryInsights:"__lunora_admin__:getQueryInsights",getQueueMessages:"__lunora_admin__:getQueueMessages",getRequestLog:"__lunora_admin__:getRequestLog",getSecurityAudit:"__lunora_admin__:getSecurityAudit",getSettings:"__lunora_admin__:getSettings",getTraces:"__lunora_admin__:getTraces",getWorkflowInstanceStatus:"__lunora_admin__:getWorkflowInstanceStatus",ignoreIssue:"__lunora_admin__:ignoreIssue",importShard:"__lunora_admin__:importShard",listFlags:"__lunora_admin__:listFlags",listQueues:"__lunora_admin__:listQueues",lintSql:"__lunora_admin__:lintSql",listTables:"__lunora_admin__:listTables",listWorkflows:"__lunora_admin__:listWorkflows",maskPolicies:"__lunora_admin__:maskPolicies",migrationStatus:"__lunora_admin__:migrationStatus",pitrRestore:"__lunora_admin__:pitrRestore",rankBefore:"__lunora_admin__:rankBefore",rankPage:"__lunora_admin__:rankPage",readTablePage:"__lunora_admin__:readTablePage",recordAuthEvent:"__lunora_admin__:recordAuthEvent",recordContainerEvent:"__lunora_admin__:recordContainerEvent",recordMail:"__lunora_admin__:recordMail",recordQueueMessage:"__lunora_admin__:recordQueueMessage",replayQueueMessage:"__lunora_admin__:replayQueueMessage",resolveIssue:"__lunora_admin__:resolveIssue",rlsPolicies:"__lunora_admin__:rlsPolicies",schemaHistory:"__lunora_admin__:schemaHistory",schemaVersion:"__lunora_admin__:schemaVersion",runAs:"__lunora_admin__:runAs",runMigration:"__lunora_admin__:runMigration",runSql:"__lunora_admin__:runSql",sendQueueMessage:"__lunora_admin__:sendQueueMessage",sendTestMail:"__lunora_admin__:sendTestMail",setIssueSeverity:"__lunora_admin__:setIssueSeverity",storageOrphans:"__lunora_admin__:storageOrphans",storageReferences:"__lunora_admin__:storageReferences",storageRules:"__lunora_admin__:storageRules",studioFeatures:"__lunora_admin__:studioFeatures",writeRow:"__lunora_admin__:writeRow"},N=50,b=500,x=30,F=200,m="__doc__",w=e=>{try{const a=JSON.parse(e);return a!==null&&typeof a=="object"&&!Array.isArray(a)?a:void 0}catch{return}},L=(e,a)=>{if(!e.includes(m))return{columns:e,rows:a};const r=[];for(const s of a){const _=s[m],i=typeof _=="string"?w(_):void 0;if(i===void 0)return{columns:e,rows:a};const u=Object.fromEntries(Object.entries(s).filter(([l])=>l!==m));r.push({...u,...i})}const t=e.filter(s=>s!==m),n=[],o=new Set(t);for(const s of r)for(const _ of Object.keys(s))o.has(_)||(o.add(_),n.push(_));return{columns:[...t,...n],rows:r}},O=e=>e.replaceAll(/[\\%_]/g,a=>`\\${a}`),S=e=>e.startsWith("sqlite_")||e.startsWith("_cf_")||e.startsWith("__miniflare")||e.startsWith("__lunora")||e.includes("__fts_"),I=(e,a,r)=>Math.min(Math.max(e,a),r),k=(e,a)=>{const r=e.exec(`SELECT COUNT(*) AS c FROM ${a}`).one();return Number(r.c)},V=e=>{const a=e.exec("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name").toArray(),r=[];for(const{name:t}of a)S(t)||r.push({name:t,rowCount:k(e,d(t))});return r},A=(e,a)=>e.exec("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ? LIMIT 1",a).toArray().length>0,P={eq:"=",gt:">",gte:">=",lt:"<",lte:"<=",ne:"<>"},U=e=>typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):"",T=(e,a)=>{const r=a.includes(e),t=a.includes(m);if(!(!r&&!t))return r?{expression:d(e),params:[]}:{expression:`json_extract(${d(m)}, ?)`,params:[`$."${e.replaceAll('"','""')}"`]}},W=(e,a)=>{const r=T(e.column,a);if(r===void 0)return;const{expression:t,params:n}=r;return e.operator==="contains"?{params:[...n,`%${O(U(e.value))}%`],sql:String.raw`CAST(${t} AS TEXT) LIKE ? ESCAPE '\'`}:{params:[...n,e.value],sql:`${t} ${P[e.operator]} ?`}},D=/^(\d{4})(?:-(\d{2}))?(?:-(\d{2}))?$/u,q=e=>{const a=D.exec(e.trim());if(a===null)return;const r=Number(a[1]),t=a[2]===void 0?void 0:Number(a[2]),n=a[3]===void 0?void 0:Number(a[3]);if(t!==void 0&&(t<1||t>12)||n!==void 0&&(n<1||n>31)||r<100)return;const o=Date.UTC(r,(t??1)-1,n??1);if(n!==void 0&&new Date(o).getUTCDate()!==n)return;let s;return n!==void 0?s=Date.UTC(r,t===void 0?0:t-1,n+1):t===void 0?s=Date.UTC(r+1,0,1):s=Date.UTC(r,t,1),{from:o,to:s}},v=(e,a,r)=>{const t=[],n=[];if(a!==""&&e.length>0){const o=`%${O(a)}%`,s=e.map(i=>String.raw`CAST(${d(i)} AS TEXT) LIKE ? ESCAPE '\'`);n.push(...e.map(()=>o));const _=q(a);if(_!==void 0)for(const i of e)s.push(`(${d(i)} >= ? AND ${d(i)} < ?)`),n.push(_.from,_.to);t.push(`(${s.join(" OR ")})`)}for(const o of r??[]){const s=W(o,e);s!==void 0&&(t.push(`(${s.sql})`),n.push(...s.params))}return t.length===0?void 0:{parameters:n,where:t.join(" AND ")}},Q=(e,a)=>{if(e===void 0)return;const r=T(e.column,a);if(r===void 0)return;const t=e.direction==="desc"?"DESC":"ASC";return{params:r.params,sql:`${r.expression} ${t}`}},J=(e,a)=>{const{table:r}=a;if(S(r)||!A(e,r))throw new M("UNKNOWN_TABLE",`unknown table: ${r}`,{status:404});const t=I(Math.trunc(a.limit??N),1,b),n=Math.max(0,Math.trunc(a.offset??0)),o=d(r),s=e.exec(`PRAGMA table_info(${o})`).toArray().map(h=>h.name),_=a.search?.trim()??"",i=h=>{if(a.refs===void 0)return h;const C={};for(const $ of h.columns){const R=a.refs[$];R!==void 0&&(C[$]=R)}return Object.keys(C).length>0?{...h,refs:C}:h},u=v(s,_,a.filters),l=Q(a.orderBy,s),c=u===void 0?"":` WHERE ${u.where}`,f=l===void 0?"":` ORDER BY ${l.sql}`,g=u?.parameters??[],E=l?.params??[];let p;a.skipCount||(p=u===void 0?k(e,o):Number(e.exec(`SELECT COUNT(*) AS c FROM ${o}${c}`,...g).one().c));const y=e.exec(`SELECT * FROM ${o}${c}${f} LIMIT ? OFFSET ?`,...g,...E,t,n).toArray();return i({...L(s,y),total:p})},Z=(e,a)=>{const{table:r}=a;if(S(r)||!A(e,r))throw new M("UNKNOWN_TABLE",`unknown table: ${r}`,{status:404});const t=I(Math.trunc(a.limit??b),1,b),n=d(r),o=e.exec(`PRAGMA table_info(${n})`).toArray().map(c=>c.name),s=a.search?.trim()??"",_=v(o,s,a.filters),i=_===void 0?e.exec(`SELECT id FROM ${n} LIMIT ?`,t+1).toArray():e.exec(`SELECT id FROM ${n} WHERE ${_.where} LIMIT ?`,..._.parameters,t+1).toArray(),u=i.length>t,l=(u?i.slice(0,t):i).map(c=>c.id);return{hasMore:u,ids:l}},j=(e,a,r)=>{const t=new Set(r.filter(o=>o!==m));if(!r.includes(m))return t;const n=e.exec(`SELECT ${d(m)} AS doc FROM ${a} LIMIT ?`,b).toArray();for(const{doc:o}of n){const s=typeof o=="string"?w(o):void 0;if(s!==void 0)for(const _ of Object.keys(s))t.add(_)}return t},ee=(e,a)=>{const{column:r,table:t}=a;if(S(t)||!A(e,t))throw new M("UNKNOWN_TABLE",`unknown table: ${t}`,{status:404});const n=d(t),o=e.exec(`PRAGMA table_info(${n})`).toArray().map(p=>p.name);if(!j(e,n,o).has(r))throw new M("UNKNOWN_COLUMN",`unknown column: ${r}`,{status:404});const s=T(r,o);if(s===void 0)throw new M("UNKNOWN_COLUMN",`unknown column: ${r}`,{status:404});const _=I(Math.trunc(a.limit??x),1,F),i=a.search?.trim()??"",u=v(o,i,a.filters),l=u===void 0?"":` WHERE ${u.where}`,c=u?.parameters??[],f=e.exec(`SELECT ${s.expression} AS value, COUNT(*) AS count FROM ${n}${l} GROUP BY ${s.expression} ORDER BY count DESC LIMIT ?`,...s.params,...c,...s.params,_+1).toArray(),g=f.length>_,E=g?f.slice(0,_):f;return{truncated:g,values:E.map(p=>({count:Number(p.count),value:p.value}))}},ae=(e,a,r)=>{const t={},n=r.slice(0,b);for(const s of n)t[s]=[];if(n.length===0)return{references:t,storageColumns:a};const o=n.map(()=>"?").join(", ");for(const[s,_]of Object.entries(a)){if(S(s)||!A(e,s))continue;const i=d(s),u=e.exec(`PRAGMA table_info(${i})`).toArray().map(l=>l.name);for(const l of _){const c=T(l,u);if(c===void 0)continue;const f=e.exec(`SELECT id, ${c.expression} AS ref FROM ${i} WHERE ${c.expression} IN (${o})`,...c.params,...c.params,...n).toArray();for(const g of f)t[g.ref]?.push({column:l,id:g.id,table:s})}}return{references:t,storageColumns:a}},te=e=>{const a=e.map((t,n)=>{const o=Object.values(t.subs??{}).map(s=>({args:s.args,functionPath:s.functionPath,table:s.table}));return{admin:t.admin===!0,id:n,subscriptions:o}}),r=a.reduce((t,n)=>t+n.subscriptions.length,0);return{connections:a,totalConnections:a.length,totalSubscriptions:r}},B=20,re=()=>({maxMs:0,passes:0,peakSocketsIterated:0,socketsDelivered:0,socketsIterated:0,totalMs:0}),se=(e,a,r,t)=>({maxMs:Math.max(e.maxMs,t),passes:e.passes+1,peakSocketsIterated:Math.max(e.peakSocketsIterated,a),socketsDelivered:e.socketsDelivered+r,socketsIterated:e.socketsIterated+a,totalMs:e.totalMs+t}),ne=(e,a=B)=>{const r=new Map,t=new Map;for(const o of e){for(const s of Object.values(o.shapes??{})){const _=s.name??"(unknown shape)";r.set(_,(r.get(_)??0)+1)}for(const s of o.whispers??[])t.set(s,(t.get(s)??0)+1)}const n=[...[...r].map(([o,s])=>({kind:"shape",subscribers:s,topic:o})),...[...t].map(([o,s])=>({kind:"whisper",subscribers:s,topic:o}))];return n.sort((o,s)=>s.subscribers-o.subscribers||o.topic.localeCompare(s.topic)),{peakSubscribers:n[0]?.subscribers??0,topics:n.slice(0,a),totalConnections:e.length}};export{z as ADMIN_FUNCTIONS,K as ADMIN_FUNCTION_PREFIX,B as DEFAULT_FANOUT_TOPIC_LIMIT,Y as FLAGS_FUNCTION_PREFIX,b as MAX_PAGE_SIZE,X as RELATION_FUNCTION_PREFIX,re as createFanoutCounters,q as datePrefixRange,ee as facetColumn,ae as findStorageReferences,V as listTables,J as readTablePage,se as recordFanoutPass,Z as selectMatchingIds,ne as summarizeFanoutTopics,te as summarizeSubscriptions};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as A}from"@lunora/errors";import{searchTextUnchanged as Tt,ftsTableName as dt,FTS_ID_COLUMN as be,FTS_TEXT_COLUMN as Nt,analyzedSearchText as ct,createSearchBuilder as St,createSearchAnalyzer as Ve,planSearchPage as Rt,finishSearchPage as At,searchPageScan as It,resolveSearchScan as vt,assertSearchWithinCap as Ct,tokenizeSearch as ft,searchTermRange as kt,scoreDocument as Mt,MAX_SEARCH_SCAN as Lt}from"@lunora/search-core";import{sql as e}from"drizzle-orm";import{matchesStaticWhere as Fe,aggregateSqlFunction as Ne,normalizeCountArgument as xt,throwingScheduler as Ot}from"./AGGREGATE_SQL_FUNCTION-QYaiuty4.mjs";import{encodeAggregateKey as de,foldAggregateTally as Dt,aggregateTableName as Se,coerceAggregateNumber as qe,readAggregateValue as Ue}from"./aggregateTableName-G-eXyjcz.mjs";import{mergeWhere as re,CountRlsUnsupportedError as Pe,selectIndexForGroupBy as Wt,selectIndexForCount as Bt,selectIndexForAggregate as Ft}from"./CountRlsUnsupportedError-Cl8XpYDL.mjs";import{Y as qt}from"./ctx-db-backfill-C4rAzsQo.mjs";import{o as fi,H as ui,P as hi,X as $i}from"./ctx-db-backfill-C4rAzsQo.mjs";import{appendCdcChange as Ut}from"./CDC_LOG_TABLE-E_J5LPoK.mjs";import{CDC_LOG_TABLE as mi,applyCdcChanges as wi,bumpCdcEpoch as gi,minCdcSeq as Ei,readCdcChanges as bi,readCdcCursor as yi,readCdcEpoch as _i,trimCdcChanges as Ti}from"./CDC_LOG_TABLE-E_J5LPoK.mjs";import{r as M}from"./do-exec-BLe9lLrN.mjs";import{b as ut,s as Z,g as he,a as ce,_ as te,m as X,T as ht,E as Le,$ as ee,l as Pt,L as $t,N as pt,S as Xe}from"./do-sql-x0AjZhaN.mjs";import{param as Ye}from"./renderSql-B5lF5Jd9.mjs";import{encodeGeohash as Ht,GEO_DEFAULT_PRECISION as jt,coveringGeohashes as Gt,boundingBoxGeohashes as Jt,pointInBoundingBox as Vt,haversineMeters as Yt}from"./GEO_DEFAULT_PRECISION-okRCkZ6r.mjs";import{sortColumnName as Ae,matchesRankStaticWhere as mt,encodePartitionKey as De,rankTableName as Ie,resolveRankPartition as wt,RANK_TIEBREAK as me}from"./RANK_TIEBREAK-DtX8zQyc.mjs";import{t as fe}from"./serialize-sql-DiRzL7A4.mjs";import{SCAN_DEP as Q}from"./SCAN_DEP-D_yR9EeV.mjs";import{decodeCursor as Oe,normalizeOrderKeys as zt,buildSeekWhere as gt,applySelect as Ze,encodeCursor as Ge,softDeleteScope as Ee,buildSeekBeforeWhere as Kt}from"./applySelect-B0CF8T7y.mjs";import Qt from"./NotFoundError-J3tjf4Uo.mjs";import{assertFlatPredicate as He,resolveRelationPredicates as et}from"./DEFAULT_MAX_RELATION_KEYS-VxD8RtL0.mjs";import{runRowValidators as je,resolveWith as tt,applyOnDelete as Xt,fanOutScalarCounts as Zt}from"./applyOnDelete-DCeU2Jh0.mjs";import{guardWriter as en}from"./RLS_UNWRAP_SYMBOL-C6_WX3dG.mjs";import{createSystemReader as tn}from"./createSystemReader-DcDcrtM3.mjs";import{ConflictError as Re}from"./ConflictError-C8GtJmjS.mjs";import{runTriggers as nn}from"./hasTrigger-_rexbWMO.mjs";import{compileWhereSql as ue}from"./compileWhereSql-BLcfs4QW.mjs";import{e as Si,t as Ri,r as Ai,o as Ii,l as vi,p as Ci,_ as ki,a as Mi,b as Li,d as xi,m as Oi,c as Di,S as Wi,T as Bi}from"./schema-history-YGeVjyvV.mjs";import{runShardMigrations as qi}from"./runShardMigrations-DATbmCh8.mjs";import{a as Pi,s as Hi}from"./ctx-db-shapes-CHC2cS0g.mjs";const on=(o,r,n)=>[...o.partitionBy??[],...o.sortBy.map(l=>l.field),...o.where?Object.keys(o.where):[]].every(l=>r[l]===n[l]),rn=(o,r,n,l,s,c)=>{if(s&&c&&on(n,s,c))return;const E=Ie(r,n.name);if(s&&M(o,e`DELETE FROM ${e.identifier(E)} WHERE ${e.identifier("__id__")} = ${l}`),!c||n.where&&!mt(c,n.where))return;const m=n.sortBy.map((b,h)=>Ae(h)),_=e.join(["__id__","__partition__",...m].map(b=>e.identifier(b)),e`, `),v=De(n.partitionBy??[],c),L=n.sortBy.map(b=>fe(c[b.field]??null)),T=e.join([l,v,...L].map(b=>Ye(b)),e`, `);M(o,e`INSERT INTO ${e.identifier(E)} (${_}) VALUES (${T})`)},an=o=>{const{broadcast:r,invalidateCache:n,recordCdc:l,schema:s,sql:c}=o,E=new Set,m=new Set,_=(N,w)=>{const S=`${N}::${w.name}`;if(E.has(S))return;const F=Se(N,w.name),W=w.by??[],j=new Map,q=M(c,e`SELECT id, _creationTime, ${e.identifier(Z)} FROM ${e.identifier(N)}`).toArray();for(const U of q){const x=he(U);if(!x||w.where&&!Fe(x,w.where))continue;const G=de(W,x);Dt(j,G,w,x)}M(c,e`DELETE FROM ${e.identifier(F)}`);const J=32,B=[...j];for(let U=0;U<B.length;U+=J){const x=B.slice(U,U+J),G=e.join(x.map(([H,Y])=>e`(${H}, ${Y.value}, ${Y.count})`),e`, `);M(c,e`INSERT INTO ${e.identifier(F)} (${ce}, ${te}, ${X}) VALUES ${G}`)}E.add(S)},v=(N,w,S)=>{const F=w.by??[],W=Ne(w.op),j=w.field??"",q=[];for(const U of F){const x=fe(S[U]??null);x===null?q.push(e`${ee(U)} IS NULL`):q.push(e`${ee(U)} = ${x}`)}for(const[U,x]of Object.entries(w.where??{})){const G=x!==null&&typeof x=="object"&&!Array.isArray(x)?x.eq:x,H=fe(G);H===null?q.push(e`${ee(U)} IS NULL`):q.push(e`${ee(U)} = ${H}`)}const J=q.length>0?e` WHERE ${e.join(q,e` AND `)}`:e``,B=ee(j);return{value:M(c,e`SELECT ${e.raw(W)}(${B}) AS value FROM ${e.identifier(N)}${J}`).one().value??null}},L=(N,w,S,F)=>{const W=Se(N,w.name),{op:j}=w,q=w.field??"",J=x=>{M(c,e`DELETE FROM ${e.identifier(W)} WHERE ${ce} = ${x} AND ${X} <= 0`)},B=S&&(!w.where||Fe(S,w.where))?S:void 0,U=F&&(!w.where||Fe(F,w.where))?F:void 0;if(!(!B&&!U)){if(j==="count"){for(const[x,G]of[[B,-1],[U,1]]){if(!x)continue;const H=de(w.by??[],x);M(c,Le(W,H,G,G,e`${te} = ${te} + excluded.${te}, ${X} = ${X} + excluded.${X}`))}B&&J(de(w.by??[],B));return}if(j==="sum"||j==="avg"){for(const[x,G]of[[B,-1],[U,1]]){if(!x)continue;const H=qe(x[q]);if(H===void 0)continue;const Y=de(w.by??[],x);M(c,Le(W,Y,G*H,G,e`${te} = COALESCE(${te}, 0) + excluded.${te}, ${X} = ${X} + excluded.${X}`))}B&&J(de(w.by??[],B));return}if(B){const x=de(w.by??[],B),G=qe(B[q]),H=M(c,e`SELECT ${te} AS value, ${X} AS count FROM ${e.identifier(W)} WHERE ${ce} = ${x}`).toArray()[0],Y=(H?.count??0)-1;if(Y<=0)M(c,e`DELETE FROM ${e.identifier(W)} WHERE ${ce} = ${x}`);else if(H&&G!==void 0&&H.value!==null&&G===H.value){const ie=v(N,w,B);M(c,e`UPDATE ${e.identifier(W)} SET ${te} = ${ie.value}, ${X} = ${Y} WHERE ${ce} = ${x}`)}else M(c,e`UPDATE ${e.identifier(W)} SET ${X} = ${X} - 1 WHERE ${ce} = ${x}`)}if(U){const x=de(w.by??[],U),G=qe(U[q]);if(G===void 0)M(c,Le(W,x,null,1,e`${X} = ${X} + 1`));else{const H=j==="min"?"MIN":"MAX";M(c,Le(W,x,G,1,e`${te} = ${e.raw(H)}(COALESCE(${te}, excluded.${te}), excluded.${te}), ${X} = ${X} + 1`))}}}},T=N=>{const w=s.tables[N]?.aggregateIndexes;if(!(!w||w.length===0))for(const S of w)_(N,S)},b=(N,w,S)=>{const F=s.tables[N]?.aggregateIndexes;if(!(!F||F.length===0))for(const W of F)L(N,W,w,S)},h=(N,w)=>{const S=`${N}::rank::${w.name}`;if(m.has(S))return;const F=Ie(N,w.name),W=M(c,e`SELECT id, _creationTime, ${e.identifier(Z)} FROM ${e.identifier(N)}`).toArray();M(c,e`DELETE FROM ${e.identifier(F)}`);const j=w.sortBy.map((J,B)=>Ae(B)),q=e.join(["__id__","__partition__",...j].map(J=>e.identifier(J)),e`, `);for(const J of W){const B=he(J);if(!B||w.where&&!mt(B,w.where))continue;const U=De(w.partitionBy??[],B),x=w.sortBy.map(H=>fe(B[H.field]??null)),G=e.join([B._id,U,...x].map(H=>Ye(H)),e`, `);M(c,e`INSERT INTO ${e.identifier(F)} (${q}) VALUES (${G})`)}m.add(S)},k=N=>{const w=s.tables[N]?.rankIndexes;if(!(!w||w.length===0))for(const S of w)h(N,S)},C=(N,w,S,F)=>{const W=s.tables[N]?.rankIndexes;if(!(!W||W.length===0))for(const j of W)rn(c,N,j,w,S,F)},I=(N,w,S,F)=>{const W=s.tables[N]?.searchIndexes;if(!(!W||W.length===0||!ut(c)))for(const j of W){if(Tt(F,S,j))continue;const q=dt(N,j.name);M(c,e`DELETE FROM ${e.identifier(q)} WHERE ${e.identifier(be)} = ${w}`),S&&M(c,e`INSERT INTO ${e.identifier(q)} (${e.identifier(Nt)}, ${e.identifier(be)}) VALUES (${ct(S,j)}, ${w})`)}},P=(N,w,S)=>{const F=s.tables[N]?.geoIndexes;if(!(!F||F.length===0))for(const W of F){const j=ht(N,W.name);M(c,e`DELETE FROM ${e.identifier(j)} WHERE ${e.identifier("__id__")} = ${w}`);const q=S?.[W.field];if(q!==null&&typeof q=="object"&&typeof q.lat=="number"&&typeof q.lng=="number"){const{lat:J,lng:B}=q,U=Ht({lat:J,lng:B},W.precision??jt);M(c,e`INSERT INTO ${e.identifier(j)} (${e.identifier("__id__")}, ${e.identifier("__geohash__")}, ${e.identifier("__lat__")}, ${e.identifier("__lng__")}) VALUES (${w}, ${U}, ${J}, ${B})`)}}};return{ensureBackfilledForTable:T,ensureBackfilledIndex:_,ensureRankBackfilled:h,ensureRankBackfilledForTable:k,syncAggregates:b,syncCompanionsForInsert:(N,w,S)=>{I(N,w,S),P(N,w,S),b(N,void 0,S),C(N,w,void 0,S),n(N,w),l(N,w,"insert",S),r({key:w,op:"insert",row:S,table:N})},syncGeo:P,syncRanks:C,syncSearch:I}},sn="__doc__",ln=o=>{const r=JSON.stringify(o),n=new TextEncoder().encode(r);let l="";for(const s of n)l+=String.fromCodePoint(s);return btoa(l)},dn=o=>o.after?[o.after.partitionKey,...o.after.sortValues,o.after.rowId]:o.cursor?Oe(o.cursor):void 0,cn=(o,r,n)=>{if(o?.length!==1+r.length+1)return;const l=[{column:"__partition__",direction:"asc"}];for(const[c,E]of r.entries())l.push({column:E,direction:n[c]?.direction??"asc"});l.push({column:me,direction:"asc"});const s=[];for(const[c,E]of l.entries()){const m=[];for(const[v,L]of l.slice(0,c).entries())m.push(e`${e.identifier(L.column)} IS ${o[v]}`);m.push(e`${e.identifier(E.column)} ${e.raw(E.direction==="desc"?"<":">")} ${o[c]}`);const[_]=m;s.push(m.length===1&&_!==void 0?_:e`(${e.join(m,e` AND `)})`)}return e`(${e.join(s,e` OR `)})`},Et=null,fn=(o,r)=>{if(o===void 0)return Et;const n=[o.__partition__,...r.map(l=>o[l]),o[me]];return ln(n)},un=(o,r,n)=>{const l=[];for(const s of o){const c=s[me];if(typeof c!="string")continue;const E=r.get(c);if(!E)continue;const m=typeof s.__partition__=="string"?s.__partition__:"",_=n.map(v=>s[v]??null);l.push({doc:E,key:{partitionKey:m,rowId:c,sortValues:_}})}return l},hn=(o,r,n)=>{const{rowToDocument:l}=o,s=new Map;if(n.length===0)return s;const c=e.join(n.map(m=>Ye(m)),e`, `),E=M(o.sql,e`SELECT id, _creationTime, ${e.identifier(sn)} FROM ${e.identifier(r)} WHERE id IN (${c})`).toArray();for(const m of E){const _=l(m),v=m.id;_&&typeof v=="string"&&s.set(v,_)}return s},nt=(o,r,n,l)=>{const{assertRankPartitionLocal:s,ensureRankBackfilled:c,onRead:E,schema:m}=o,_=m.tables[r];if(!_)throw new A("INTERNAL",`unknown table: ${r}`);const v=_.rankIndexes?.find(Y=>Y.name===n);if(!v)throw new A("INTERNAL",`unknown rankIndex "${n}" on table "${r}"`);s(r,_,v),E(r,Q),c(r,v);const L=Ie(r,v.name),T=v.sortBy.map((Y,ie)=>Ae(ie)),b=Math.max(1,Math.min(1e3,Math.floor(l.take??100))),h=re(l.baseWhere,l.where),k=wt(v,h),C=[e`${e.identifier("__partition__")} ASC`];for(const[Y,ie]of T.entries()){const se=v.sortBy[Y]?.direction;C.push(e`${e.identifier(ie)} ${e.raw(se==="desc"?"DESC":"ASC")}`)}C.push(e`${e.identifier(me)} ASC`);const I=[];typeof l.partitionKey=="string"?I.push(e`${e.identifier("__partition__")} = ${l.partitionKey}`):k&&I.push(e`${e.identifier("__partition__")} = ${De(v.partitionBy??[],k)}`);const P=dn(l),N=cn(P,T,v.sortBy);N&&I.push(N);const w=e.identifier(me),S=e.identifier("__partition__"),F=I.length>0?e` WHERE ${e.join(I,e` AND `)}`:e``,W=T.length>0?e`${w}, ${S}, ${e.join(T.map(Y=>e.identifier(Y)),e`, `)}`:e`${w}, ${S}`,j=e`SELECT ${W} FROM ${e.identifier(L)}${F} ORDER BY ${e.join(C,e`, `)} LIMIT ${e.raw(String(b+1))}`,q=M(o.sql,j).toArray(),J=q.length>b,B=J?q.slice(0,b):q,U=B.map(Y=>Y[me]),x=un(B,hn(o,r,U),T),G=J?fn(B.at(-1),T):Et,H=v.sortBy.map(Y=>Y.direction==="desc"?"desc":"asc");return{continueCursor:G,directions:H,hasMore:J,rows:x}},$n=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,pn=o=>{if(!$n.test(o))throw new A("INTERNAL",`invalid clientId ${JSON.stringify(o)}: a client-supplied row id must be a UUID`)},it=50,bt=500,ge=(o,r,n)=>{const l=r??bt;if(o>l)throw new A("BATCH_LIMIT_EXCEEDED",`${n}: batch of ${String(o)} exceeds the limit of ${String(l)} (raise options.limit or chunk the call)`,{status:400})},mn=o=>{const r={eq:(n,l)=>(o.sqlConditions.push({comparator:"=",field:n,value:l}),r),gt:(n,l)=>(o.sqlConditions.push({comparator:">",field:n,value:l}),r),gte:(n,l)=>(o.sqlConditions.push({comparator:">=",field:n,value:l}),r),lt:(n,l)=>(o.sqlConditions.push({comparator:"<",field:n,value:l}),r),lte:(n,l)=>(o.sqlConditions.push({comparator:"<=",field:n,value:l}),r)};return r},wn=o=>Math.max(o,Lt),gn=(o,r,n,l,s)=>{const c=ft(n.query,Ve(n.definition.language));if(c.length===0)return[];const E=dt(r,n.indexName),m=`${E}__vocab`,_=c.length-1,v=c.map((C,I)=>{const P=kt(C,I===_),N=P.exact?e`${e.identifier("term")} = ${P.lower}`:e`${e.identifier("term")} >= ${P.lower} AND ${e.identifier("term")} < ${P.upper}`;return e`SELECT ${e.identifier("doc")}, ${e.raw(String(I))} AS ${e.identifier("__term__")}, COUNT(*) AS ${e.identifier("__n__")} FROM ${e.identifier(m)} WHERE ${N} GROUP BY ${e.identifier("doc")}`}),L=c.map((C,I)=>e`SUM(CASE WHEN u.${e.identifier("__term__")} = ${e.raw(String(I))} THEN u.${e.identifier("__n__")} ELSE 0 END)`),T=e`SELECT f.${e.identifier(be)} AS ${e.identifier(be)}, ${e.join(L,e` + `)} AS ${e.identifier("__score__")} FROM (${e.join(v,e` UNION ALL `)}) u JOIN ${e.identifier(E)} f ON f.rowid = u.${e.identifier("doc")} GROUP BY f.${e.identifier(be)} HAVING ${e.join(L.map(C=>e`${C} > 0`),e` AND `)}`,b=[];for(const C of n.filters)b.push(e`${ee(C.field)} = ${fe(C.value)}`);s&&b.push(s);let h=e`SELECT m.id, m._creationTime, m.${e.identifier(Z)} FROM (${T}) s JOIN ${e.identifier(r)} m ON m.id = s.${e.identifier(be)}`;b.length>0&&(h=e`${h} WHERE ${e.join(b,e` AND `)}`),h=e`${h} ORDER BY s.${e.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${e.raw(String(l))}`;const k=[];for(const C of M(o,h)){const I=pt(C);I&&k.push(I)}return k},En=(o,r,n,l,s)=>{const c=Ve(n.definition.language),E=ft(n.query,c);if(E.length===0)return[];const m=[];for(const T of n.filters)m.push(e`${ee(T.field)} = ${fe(T.value)}`);s&&m.push(s);let _=e`SELECT id, _creationTime, ${e.identifier(Z)} FROM ${e.identifier(r)}`;m.length>0&&(_=e`${_} WHERE ${e.join(m,e` AND `)}`),_=e`${_} ORDER BY _creationTime DESC, id ASC LIMIT ${e.raw(String(wn(l)))}`;const v=M(o,_).toArray(),L=[];for(const T of v){const b=pt(T);if(!b)continue;const h=Mt(ct(b,n.definition),E,c);h>0&&L.push({creationTime:typeof b._creationTime=="number"?b._creationTime:0,doc:b,id:typeof b._id=="string"?b._id:"",score:h})}return L.sort((T,b)=>b.score-T.score||b.creationTime-T.creationTime||T.id.localeCompare(b.id)),L.slice(0,l).map(T=>T.doc)},bn=(o,r)=>{const n=o,l={near:(s,c)=>{if(n.within)throw new A("INTERNAL",`geo index "${n.indexName}" on table "${r}": call .near() or .within(), not both`);return n.near={point:{lat:s.lat,lng:s.lng},radiusMeters:c},l},within:s=>{if(n.near)throw new A("INTERNAL",`geo index "${n.indexName}" on table "${r}": call .near() or .within(), not both`);return n.within={ne:{lat:s.ne.lat,lng:s.ne.lng},sw:{lat:s.sw.lat,lng:s.sw.lng}},l}};return l},yn=(o,r)=>{const n=o[r];if(n===null||typeof n!="object")return;const{lat:l,lng:s}=n;return typeof l=="number"&&typeof s=="number"?{lat:l,lng:s}:void 0},_n=(o,r)=>{const n=yn(o,r.definition.field);if(!n)return;const l=typeof o._creationTime=="number"?o._creationTime:0;if(r.near){const s=Yt(r.near.point,n);return s<=r.near.radiusMeters?{creationTime:l,distance:s}:void 0}return Vt(n,r.within)?{creationTime:l,distance:0}:void 0},Tn=(o,r,n,l,s)=>{if(!n.near&&!n.within)throw new A("INTERNAL",`geo index "${n.indexName}" on table "${r}": call .near(point, radius) or .within(box)`);const c=n.near?Gt(n.near.point,n.near.radiusMeters):Jt(n.within),E=ht(r,n.indexName),m=c.map(h=>e`(g.${e.identifier("__geohash__")} >= ${h} AND g.${e.identifier("__geohash__")} < ${`${h}{`})`),_=[e`(${e.join(m,e` OR `)})`];s&&_.push(s);const v=e`SELECT m.id, m._creationTime, m.${e.identifier(Z)} FROM ${e.identifier(E)} g JOIN ${e.identifier(r)} m ON m.id = g.${e.identifier("__id__")} WHERE ${e.join(_,e` AND `)}`,L=M(o,v).toArray(),T=[];for(const h of L){const k=he(h),C=k?_n(k,n):void 0;k&&C&&T.push({creationTime:C.creationTime,distance:C.distance,doc:k})}T.sort((h,k)=>h.distance-k.distance||k.creationTime-h.creationTime);const b=T.map(h=>h.doc);return typeof l=="number"?b.slice(0,Math.max(0,Math.floor(l))):b},Nn=(o,r,n,l,s)=>{const{geo:c}=n;if(!c)throw new A("INTERNAL","runGeoTerminal called without a staged geo query");const E=n.inMemoryFilters.length>0,m=Tn(o,r,c,E?void 0:s,l);if(!E)return m;const _=[];for(const v of m)if(n.inMemoryFilters.every(L=>L(v))&&(_.push(v),typeof s=="number"&&_.length>=s))break;return _},Sn=(o,r,n,l,s,c)=>{const E=[];for(const L of n.sqlConditions)E.push(e`${ee(L.field)} ${e.raw(L.comparator)} ${fe(L.value)}`);l&&E.push(l);let m=e`SELECT id, _creationTime, ${e.identifier(Z)} FROM ${e.identifier(r)}`;E.length>0&&(m=e`${m} WHERE ${e.join(E,e` AND `)}`),m=e`${m} ORDER BY ${s}`,typeof c=="number"&&n.inMemoryFilters.length===0&&(m=e`${m} LIMIT ${e.raw(String(Math.max(0,Math.floor(c))))}`);const _=M(o,m).toArray(),v=[];for(const L of _){const T=he(L);if(T&&n.inMemoryFilters.every(b=>b(T))&&(v.push(T),typeof c=="number"&&v.length>=c))break}return v},pe={fieldRef:ee,serialize:fe},Rn=o=>{let r=0;const n=[],l={fieldRef:ee,relationExists:s=>{const{childWhere:c,negated:E,parentTable:m,relation:_}=s,v=`__rel_${String(r)}`,L=n.at(-1)??m;r+=1,o(_.table,Q);const T=_.kind==="one"?_.field:_.references,b=_.kind==="one"?_.references:_.field,h=e`${Xe(v,b)} = ${Xe(L,T)}`;n.push(v);const k=ue(c,l);n.pop();const C=k?e`${h} AND ${k}`:h,I=e`EXISTS (SELECT 1 FROM ${e.identifier(_.table)} AS ${e.identifier(v)} WHERE ${C})`;return E?e`NOT ${I}`:I},serialize:fe};return l},yt=o=>{const r=o.map(n=>e`${ee(n.field)} ${e.raw(n.direction==="desc"?"DESC":"ASC")}`);return o.some(n=>n.field==="_id"||n.field==="id")||r.push(e`${ee("id")} ASC`),e.join(r,e`, `)},An={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},In=o=>{const r=o.order;return o.indexFields.length>0?o.indexFields.map(n=>({direction:r,field:n})):[{direction:r,field:"_creationTime"}]},vn=(o,r,n,l)=>{const s=o.sqlConditions.map(c=>({[c.field]:{[An[c.comparator]??"eq"]:c.value}}));if(n&&s.push(gt(r,Oe(n))),l&&s.push(Kt(r,Oe(l))),s.length!==0)return s.length===1?s[0]:{AND:s}},Cn=(o,r,n)=>{const l=[];for(const s of o){const c=he(s);if(c&&r.every(E=>E(c))&&(l.push(c),n!==void 0&&l.length>n))break}return l},kn=(o,r,n,l,s)=>{const c=Math.max(0,Math.floor(l.numItems)),E=In(n),m=typeof l.endCursor=="string",_=ue(vn(n,E,l.cursor,l.endCursor),pe),v=s&&_?e`${_} AND ${s}`:s??_;let L=e`SELECT id, _creationTime, ${e.identifier(Z)} FROM ${e.identifier(r)}`;v&&(L=e`${L} WHERE ${v}`),L=e`${L} ORDER BY ${yt(E)}`;const T=n.inMemoryFilters.length>0;!T&&!m&&(L=e`${L} LIMIT ${e.raw(String(c+1))}`);const b=M(o,L).toArray(),h=Cn(b,n.inMemoryFilters,T||m?void 0:c);if(m){const P=h.length>=2?h[Math.floor(h.length/2)-1]:void 0;return{continueCursor:l.endCursor??null,isDone:!0,page:h,splitCursor:P?Ge(P,E):null}}const k=h.length>c,C=k?h.slice(0,c):h,I=C.at(-1);return{continueCursor:k&&I?Ge(I,E):null,isDone:!k,page:C}};class Mn extends A{constructor(r="unique() found more than one matching document"){super("NOT_UNIQUE",r,{name:"NotUniqueError"})}}const Ln=/\s/u,xn=String.fromCodePoint(0),ot=(o,r,n)=>{if(!o.tables[r])throw new A("INTERNAL",`unknown table: ${r}`);return typeof n!="string"||n.length===0||Ln.test(n)||n.includes(xn)?null:n},On=(o,r,n,l=()=>{})=>{const s=r.tables[n];if(!s)throw new A("INTERNAL",`unknown table: ${n}`);const c=Ee(s.softDeleteMode,void 0),E=c?ue(c,pe):void 0,m={indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[]},_=h=>{const{search:k}=m;if(!k)throw new A("INTERNAL","runSearchFetch called without a staged search");qt(o,n,s);const C=m.inMemoryFilters.length>0,I=vt(C?void 0:h),P=ut(o)?gn(o,n,k,I,E):En(o,n,k,I,E);if(!C)return h===void 0&&Ct(P),P;const N=[];for(const w of P)if(m.inMemoryFilters.every(S=>S(w))&&(N.push(w),typeof h=="number"&&N.length>=h))break;return N},v=h=>{const k=Rt(h);return At(_(It(k)),k)},L=()=>{const h=m.indexFields.length>0?m.indexFields:["_creationTime"],k=m.order==="desc"?"DESC":"ASC";return e.join(h.map(C=>e`${ee(C)} ${e.raw(k)}`),e`, `)},T=h=>m.search?_(h):m.geo?Nn(o,n,m,E,h):Sn(o,n,m,E,L(),h),b={async collect(){return T(void 0)},filter(h){return m.inMemoryFilters.push(h),b},async first(){return T(m.inMemoryFilters.length>0?void 0:1)[0]??null},order(h){return m.order=h==="desc"?"desc":"asc",b},async paginate(h){if(m.search)return v(h);if(m.geo)throw new A("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");return kn(o,n,m,h,E)},async take(h){return T(h)},async unique(){const h=T(m.inMemoryFilters.length>0?void 0:2);if(h.length>1)throw new Mn(`unique() on table "${n}" matched ${String(h.length)} documents; expected at most one`);return h[0]??null},withGeoIndex(h,k){const C=(s.geoIndexes??[]).find(P=>P.name===h);if(!C)throw new A("INTERNAL",`unknown geo index "${h}" on table "${n}"`);l(n,h,"geo");const I={definition:C,indexName:h};if(m.geo=I,k(bn(I,n)),!I.near&&!I.within)throw new A("INTERNAL",`geo index "${h}" on table "${n}" requires a .near(point, radius) or .within(box) call`);return b},withIndex(h,k){const C=s.indexes.find(I=>I.name===h);if(!C)throw new A("INTERNAL",`unknown index "${h}" on table "${n}"`);return l(n,h,"index"),m.indexName=h,m.indexFields=C.fields,k&&k(mn(m)),b},withSearchIndex(h,k){const C=(s.searchIndexes??[]).find(P=>P.name===h);if(!C)throw new A("INTERNAL",`unknown search index "${h}" on table "${n}"`);l(n,h,"search");const I={definition:C,field:C.field,filters:[],hasQuery:!1,indexName:h,query:""};if(m.search=I,k(St(I,n,Ve(C.language))),!I.hasQuery)throw new A("INTERNAL",`search index "${h}" on table "${n}" requires a .search(field, query) call`);return b}};return b},rt=(o,r,n)=>{const l={...r};for(const[s,c]of $t(o)){if(c.serverDefault){l[s]=c.serverDefault({auth:n});continue}l[s]===void 0&&(c.defaultFn?l[s]=c.defaultFn():"defaultValue"in c&&(l[s]=c.defaultValue))}return l},at=(o,r,n,l)=>{const s=n;for(const[c,E]of $t(o)){if(E.serverDefault){c in r&&(s[c]=E.serverDefault({auth:l}));continue}E.onUpdateFn&&!(c in r)&&(s[c]=E.onUpdateFn())}},st=(o,r)=>{for(const n of Object.keys(r))if(r[n]===void 0)throw new A("INTERNAL",`Cannot ${o} field '${n}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},Dn=/unique constraint failed/i,Wn=o=>o instanceof Error&&Dn.test(o.message),Je=(o,r,n)=>{try{M(o,n)}catch(l){throw Wn(l)?new Re(`unique constraint violation on "${r}"`,"unique"):l}},xe=(o,r,n)=>{if(Je(o,r,n),M(o,e`SELECT changes() AS changed`).one().changed===0)throw new Re(`optimistic concurrency conflict on "${r}" — the row changed during this mutation; refetch and retry`,"occ")},lt=(o,r,n,l,s,c,E)=>{const m=[];for(let T=0;T<n.length+1;T+=1){const b=[];for(let I=0;I<T;I+=1)b.push(e`${e.identifier(n[I])} IS ${c[I]}`);const h=n[T],k=l[T];if(h!==void 0&&k!==void 0){const I=k.direction==="desc"?">":"<";b.push(e`${e.identifier(h)} ${e.raw(I)} ${c[T]}`)}else b.push(e`${e.identifier(me)} < ${E}`);const[C]=b;m.push(b.length===1&&C!==void 0?C:e`(${e.join(b,e` AND `)})`)}const _=e.join(m,e` OR `),v=M(o,e`SELECT COUNT(*) AS c FROM ${e.identifier(r)} WHERE ${e.identifier("__partition__")} = ${s} AND (${_})`).one(),L=M(o,e`SELECT COUNT(*) AS c FROM ${e.identifier(r)} WHERE ${e.identifier("__partition__")} = ${s}`).one();return{before:v.c,total:L.c}},li=o=>{const{sql:r}=o,{schema:n}=o,l=o.broadcast??(()=>{}),s=o.onRead??(()=>{}),c=o.onIndexUse??(()=>{}),E=o.onWrite??(()=>{}),{cache:m}=o,_=o.clock??(()=>Date.now()),v=o.idGenerator??(()=>crypto.randomUUID()),L=o.scheduler??Ot,{globalDb:T}=o,b=o.auth??{identity:null,userId:null},h=o.cdc??!1,k=L,C=tn({scheduler:typeof k.list=="function"&&typeof k.get=="function"?k:void 0,storage:o.storage}),I=(t,i,a,p)=>{h&&Ut(r,_(),t,i,a,p)},P=t=>n.tables[t]?.shardMode?.kind==="global",N=(t,i)=>{if(P(t)){if(!T)throw new A("INTERNAL",`cross-backend ${i} for global table '${t}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return T}return z},w=t=>N(t,"cascade"),S=(t,i)=>{if(P(t)){if(!T)throw new A("INTERNAL",`${i} on global table '${t}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return T}},F=()=>T,W=(t,i)=>N(t,"relation load").findMany(t,i),j=(t,i)=>(P(t)&&s(t,Q),W(t,i)),q=t=>!P(t.table),J=o.relationExistsPushDown??"auto",B=J!=="never",{maxRelationKeys:U}=o,x=(t,i,a)=>et(t,{fetcher:j,maxRelationKeys:U,relationBaseWhere:a,schema:n,tableName:i}),G=async(t,i,a,p)=>{const $=S(t,"relation grouped count");if($)return s(t,Q),Zt((D,oe)=>$.count(D,oe),t,i,a,p);const f=n.tables[t];if(!f)throw new A("INTERNAL",`unknown table: ${t}`);s(t,Q);const d=Ee(f.softDeleteMode,void 0),u={[i]:{in:a}},g=re(re(u,p),d),R=await x(g,t,void 0),y=ue(R,pe),O=ee(i);let K=e`SELECT ${O} AS __fk__, COUNT(*) AS count FROM ${e.identifier(t)}`;y&&(K=e`${K} WHERE ${y}`),K=e`${K} GROUP BY ${O}`;const V=M(r,K).toArray();return new Map(V.map(D=>[D.__fk__,D.count]))};let H=0;const Y=new Set;for(const[t,i]of Object.entries(n.tables))for(const a of Object.values(i.triggerMap??{}))Y.add(`${t} ${a.timing} ${a.op}`);const ie=(t,i,a)=>Y.has(`${t} ${i} ${a}`),se=async(t,i,a)=>{if(H+=1,H>it)throw H-=1,new Re(`trigger recursion exceeded ${String(it)} levels on "${a.table}" — check for a self-triggering write`,"trigger");try{await nn({ctx:_t,event:a,op:i,schema:n,tableName:a.table,timing:t})}finally{H-=1}},{ensureBackfilledForTable:ye,ensureBackfilledIndex:We,ensureRankBackfilled:Be,ensureRankBackfilledForTable:_e,syncAggregates:ve,syncCompanionsForInsert:ze,syncGeo:Ce,syncRanks:Te,syncSearch:ke}=an({broadcast:l,invalidateCache:(t,i)=>m?.invalidate(t,i),recordCdc:I,schema:n,sql:r}),Ke=(t,i,a)=>{const{shardMode:p}=i;if(p?.kind==="shardBy"&&!(p.field!==void 0&&(a.partitionBy??[]).includes(p.field)))throw Object.assign(new Error(`rank index "${a.name}" on "${t}" partitions across shards (shard key "${p.field??"?"}" is not in partitionBy) — a shard-local rank()/rankPage() would be wrong; roll it up through the Query Coordinator instead`),{code:"CROSS_SHARD_RANK_UNSUPPORTED",name:"LunoraError",status:400})},$e=(t,i)=>{const a=Object.entries(n.tables).filter(([,R])=>R.shardMode?.kind!=="global").map(([R])=>R).filter(R=>i===void 0||R===i);if(a.length===0)return;const p=a.map(R=>e`SELECT ${e.raw(`'${R.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${e.identifier(Z)} FROM ${e.identifier(R)} WHERE id = ${t}`),$=e`${e.join(p,e` UNION ALL `)} LIMIT 1`,[f]=M(r,$).toArray();if(!f)return;const d=f.__t__,u=he(f);if(typeof d!="string"||!u)return;const g=f[Z];return{docJson:typeof g=="string"?g:JSON.stringify(g??{}),row:u,tableName:d}},Qe={assertRankPartitionLocal:Ke,ensureRankBackfilled:Be,onRead:s,rowToDocument:he,schema:n,sql:r},z={system:C,async aggregate(t,i){const a=S(t,"aggregate");if(a)return s(t,Q),a.aggregate(t,i);const p=n.tables[t];if(!p)throw new A("INTERNAL",`unknown table: ${t}`);if(Ne(i.op),i.op==="count")return z.count(t,{baseWhere:i.baseWhere,relationBaseWhere:i.relationBaseWhere,restrictsCounts:i.restrictsCounts,where:i.where});if(!i.field)throw new A("INTERNAL",`aggregate(${t}, { op: "${i.op}" }): "field" is required for non-count reducers`);s(t,Q);const $=Ee(p.softDeleteMode,void 0),f=re(re(i.baseWhere,i.where),$),d=await x(f,t,i.relationBaseWhere),u=d!==f;if(p.aggregateIndexes&&!i.baseWhere&&!u&&!$){const V=Ft(p.aggregateIndexes,i.op,i.field,i.where);if(V){We(t,V.index);const D=de(V.index.by??[],V.key),oe=Se(t,V.index.name),ae=M(r,e`SELECT ${te} AS value, ${X} AS count FROM ${e.identifier(oe)} WHERE ${ce} = ${D}`).toArray()[0];return Ue(i.op,ae)}}const g=ue(d,pe),R=Ne(i.op),y=ee(i.field);let O=e`SELECT ${e.raw(R)}(${y}) AS value FROM ${e.identifier(t)}`;return g&&(O=e`${O} WHERE ${g}`),M(r,O).toArray()[0]?.value??null},asId(t,i){const a=ot(n,t,i);if(a===null)throw new A("BAD_REQUEST",`asId("${t}", …): "${i}" is not a valid id for table "${t}"`,{status:400});return a},async count(t,i){const a=S(t,"count");if(a)return s(t,Q),a.count(t,i);const p=n.tables[t];if(!p)throw new A("INTERNAL",`unknown table: ${t}`);const $=xt(i);if($.restrictsCounts)throw new Pe(t);s(t,Q);const f=Ee(p.softDeleteMode,void 0),d=re(re($.baseWhere,$.where),f),u=await x(d,t,$.relationBaseWhere),g=u!==d;if(p.aggregateIndexes&&!$.baseWhere&&!g&&!f){const O=Bt(p.aggregateIndexes,$.where);if(O){We(t,O.index);const K=de(O.index.by??[],O.key),V=Se(t,O.index.name),D=M(r,e`SELECT ${te} AS value FROM ${e.identifier(V)} WHERE ${ce} = ${K}`).toArray();return D[0]===void 0?0:D[0].value??0}}const R=ue(u,pe);let y=e`SELECT COUNT(*) AS count FROM ${e.identifier(t)}`;return R&&(y=e`${y} WHERE ${R}`),M(r,y).one().count},async delete(t,i,a){const p=$e(t,i);if(!p){const y=i===void 0?F():void 0;y&&await y.delete(t,void 0,a);return}const{docJson:$,row:f,tableName:d}=p,u=n.tables[d],g=a?.hard===!0,R=!g&&u?.softDeleteMode?u.softDeleteMode.field:void 0;if(!(R&&f[R]!==null&&f[R]!==void 0)){if(ie(d,"before","delete")&&await se("before","delete",{id:t,op:"delete",previous:f,table:d}),await Xt({deletedId:t,deletedReference:y=>f[y],findHolders:async(y,O,K)=>(await w(y).findMany(y,{includeDeleted:g,where:{[O]:K}})).page,onCascade:(y,O)=>w(y).delete(O,void 0,a),onRestrict:y=>{throw new Re(y,"restrict")},onSetNull:(y,O,K)=>w(y).patch(O,{[K]:null}),schema:n,tableName:d}),ye(d),_e(d),R){const y={...f,[R]:_(),_id:t};xe(r,d,e`UPDATE ${e.identifier(d)} SET ${e.identifier(Z)} = ${JSON.stringify(y)} WHERE id = ${t} AND ${e.identifier(Z)} = ${$}`),ke(d,t,y,f),Ce(d,t,void 0),ve(d,f,y),Te(d,t,f,void 0),m?.invalidate(d,t),I(d,t,"update",y),l({key:t,op:"update",row:y,table:d}),ie(d,"after","delete")&&await se("after","delete",{id:t,op:"delete",previous:f,table:d}),await E({id:t,op:"delete",table:d});return}xe(r,d,e`DELETE FROM ${e.identifier(d)} WHERE id = ${t} AND ${e.identifier(Z)} = ${$}`),ke(d,t,void 0),Ce(d,t,void 0),ve(d,f,void 0),Te(d,t,f,void 0),m?.invalidate(d,t),I(d,t,"delete"),l({key:t,op:"delete",table:d}),ie(d,"after","delete")&&await se("after","delete",{id:t,op:"delete",previous:f,table:d}),await E({id:t,op:"delete",table:d})}},async deleteAll(t,i){if(!n.tables[t])throw new A("INTERNAL",`unknown table: ${t}`);const a=Math.max(1,i?.chunkSize??bt),p=i?.hard===void 0?void 0:{hard:i.hard},$=P(t)?void 0:t;let f=0;for(;;){const d=(await z.findMany(t,{limit:a})).page.map(u=>String(u._id));if(d.length===0)break;for(const u of d)await z.delete(u,$,p),f+=1;if(d.length<a)break}return{deleted:f}},async deleteMany(t,i,a){ge(t.length,i?.limit,"deleteMany");for(const p of t)await z.delete(p,a);return{deleted:t.length}},async deleteWhere(t,i,a){const p=S(t,"deleteWhere");let $;if(p)$=(await p.findMany(t,{where:i})).page.map(f=>String(f._id));else{if(!n.tables[t])throw new A("INTERNAL",`unknown table: ${t}`);$=(await z.findMany(t,{where:i})).page.map(f=>String(f._id))}if(ge($.length,a?.limit,"deleteWhere"),z.deleteMany===void 0)throw new A("INTERNAL",`ctx.db.${t}.deleteMany is unavailable: this writer has no batch delete`);return z.deleteMany($,a)},async findFirst(t,i={}){return(await z.findMany(t,{...i,limit:1})).page[0]??null},async findFirstOrThrow(t,i={}){const a=await z.findFirst(t,i);if(a===null)throw new Qt(`findFirstOrThrow: no "${t}" document matched`);return a},async findMany(t,i={}){const a=S(t,"findMany");if(a)return s(t,Q),a.findMany(t,i);const p=n.tables[t];if(!p)throw new A("INTERNAL",`unknown table: ${t}`);const $=!i.where&&!i.baseWhere;$?s(t,Q):s(t);const f=zt(i.orderBy),d=i.cursor?gt(f,Oe(i.cursor)):void 0;let u=re(i.baseWhere,i.where);u=re(u,Ee(p.softDeleteMode,i.includeDeleted)),u=await et(u,{canPushExists:B?q:void 0,existsPushMode:J==="always"?"always":"auto",fetcher:j,maxRelationKeys:U,relationBaseWhere:i.relationBaseWhere,schema:n,tableName:t}),d&&(u=u?{AND:[u,d]}:d);const g=B?Rn(s):pe,R=ue(u,g);let y=e`SELECT id, _creationTime, ${e.identifier(Z)} FROM ${e.identifier(t)}`;R&&(y=e`${y} WHERE ${R}`),y=e`${y} ORDER BY ${yt(f)}`;const O=typeof i.limit=="number"?Math.max(0,Math.floor(i.limit)):void 0;O!==void 0&&(y=e`${y} LIMIT ${e.raw(String(O+1))}`);const K=M(r,y).toArray(),V=[];for(const le of K){const ne=he(le);ne&&(V.push(ne),!$&&typeof ne._id=="string"&&s(t,ne._id))}if(O===void 0)return i.with&&await tt({groupedCounter:G,fetcher:W,parents:V,relationBaseWhere:i.relationBaseWhere,schema:n,tableName:t,with:i.with}),{continueCursor:null,isDone:!0,page:Ze(V,i.select,i.with)};const D=V.length>O,oe=D?V.slice(0,O):V,ae=oe.at(-1);return i.with&&await tt({fetcher:W,groupedCounter:G,parents:oe,relationBaseWhere:i.relationBaseWhere,schema:n,tableName:t,with:i.with}),{continueCursor:D&&ae?Ge(ae,f):null,isDone:!D,page:Ze(oe,i.select,i.with)}},async get(t,i){const a=$e(t,i);if(!a){const p=i===void 0?F():void 0;return p?p.get(t):null}return s(a.tableName,t),a.row},async lookupById(t,i){const a=$e(t,i);return a?(s(a.tableName,t),{row:a.row,tableName:a.tableName}):null},async groupBy(t,i){const a=S(t,"groupBy");if(a)return s(t,Q),a.groupBy(t,i);const p=n.tables[t];if(!p)throw new A("INTERNAL",`unknown table: ${t}`);s(t,Q);const $=i.agg??{op:"count"};if(Ne($.op),$.op!=="count"&&!$.field)throw new A("INTERNAL",`groupBy(${t}, { agg: { op: "${$.op}" } }): "field" is required for non-count reducers`);const f=Ee(p.softDeleteMode,void 0),d=re(re(i.baseWhere,i.where),f),u=await x(d,t,i.relationBaseWhere),g=u!==d;if(p.aggregateIndexes&&!i.baseWhere&&!g&&!f){const D=Wt(p.aggregateIndexes,$.op,$.field,i.by,i.where);if(D){We(t,D.index);const oe=Se(t,D.index.name),ae=Object.keys(D.partial),le=[];if(ae.length===(D.index.by??[]).length&&ae.length>0){const we=de(D.index.by??[],D.partial),Me=M(r,e`SELECT ${te} AS value, ${X} AS count FROM ${e.identifier(oe)} WHERE ${ce} = ${we}`).toArray();return Me.length>0&&le.push({key:{...D.partial},value:Ue($.op,Me[0])}),le}const ne=M(r,e`SELECT ${ce} AS key, ${te} AS value, ${X} AS count FROM ${e.identifier(oe)}`).toArray();for(const we of ne){const Me=JSON.parse(we.key);le.push({key:Me,value:Ue($.op,we)})}return le}}const R=ue(u,pe),y=i.by.map(D=>e`${ee(D)} AS ${e.identifier(D)}`);if($.op==="count")y.push(e`COUNT(*) AS value`);else{const{field:D}=$;if(D===void 0)throw new A("INTERNAL",`groupBy(${t}, { agg: { op: "${$.op}" } }): "field" is required for non-count reducers`);y.push(e`${e.raw(Ne($.op))}(${ee(D)}) AS value`)}let O=e`SELECT ${e.join(y,e`, `)} FROM ${e.identifier(t)}`;R&&(O=e`${O} WHERE ${R}`),O=e`${O} GROUP BY ${e.join(i.by.map(D=>ee(D)),e`, `)}`;const K=M(r,O).toArray(),V=[];for(const D of K){const oe={};for(const le of i.by)oe[le]=D[le]??null;const{value:ae}=D;V.push({key:oe,value:ae==null?null:Number(ae)})}return V},async insert(t,i,a){const p=S(t,"insert");if(p){const R=await p.insert(t,i,a);return l({key:R,op:"insert",row:{...i,_id:R},table:t}),R}const $=n.tables[t];if(!$)throw new A("INTERNAL",`unknown table: ${t}`);const f=rt($,i,b);je($,f);let d;a?.clientId!==void 0?(pn(a.clientId),d=a.clientId):a?.allowExplicitId&&typeof f._id=="string"?d=f._id:d=v();const u=a?.allowExplicitId&&typeof f._creationTime=="number"?f._creationTime:_(),g={...f,_creationTime:u,_id:d};return ie(t,"before","insert")&&await se("before","insert",{doc:{...g},id:d,op:"insert",table:t}),ye(t),_e(t),Je(r,t,e`INSERT INTO ${e.identifier(t)} (id, _creationTime, ${e.identifier(Z)}) VALUES (${d}, ${u}, ${JSON.stringify(g)})`),ze(t,d,g),ie(t,"after","insert")&&await se("after","insert",{doc:g,id:d,op:"insert",table:t}),await E({doc:g,id:d,op:"insert",table:t}),d},async insertManyUnsafe(t,i,a){if(ge(i.length,a?.limit,"insertManyUnsafe"),i.length===0)return[];const p=S(t,"insert");if(p){const u=[];for(const g of i){const R=await p.insert(t,g,{allowExplicitId:a?.allowExplicitId});l({key:R,op:"insert",row:{...g,_id:R},table:t}),u.push(R)}return u}const $=n.tables[t];if(!$)throw new A("INTERNAL",`unknown table: ${t}`);ye(t),_e(t);const f=i.map(u=>{const g=rt($,u,b),R=a?.allowExplicitId===!0&&typeof g._id=="string"?g._id:v(),y=a?.allowExplicitId===!0&&typeof g._creationTime=="number"?g._creationTime:_();return{creationTime:y,document:{...g,_creationTime:y,_id:R},id:R}}),d=e.join(f.map(u=>e`(${u.id}, ${u.creationTime}, ${JSON.stringify(u.document)})`),e`, `);Je(r,t,e`INSERT INTO ${e.identifier(t)} (id, _creationTime, ${e.identifier(Z)}) VALUES ${d}`);for(const{document:u,id:g}of f)ze(t,g,u),await E({doc:u,id:g,op:"insert",table:t});return f.map(u=>u.id)},async insertMany(t,i,a){ge(i.length,a?.limit,"insertMany");const p=a?.skipDuplicates===!0,$=[];for(const f of i)try{$.push(await z.insert(t,f))}catch(d){if(p&&d instanceof Re&&d.kind==="unique")$.push(null);else throw d}return $},normalizeId(t,i){return ot(n,t,i)},async patch(t,i,a){const p=$e(t,a);if(!p){const R=a===void 0?F():void 0;if(R){await R.patch(t,i);return}throw new A("INTERNAL",`document not found: ${t}`)}const{docJson:$,row:f,tableName:d}=p,u=n.tables[d];if(!u)throw new A("INTERNAL",`unknown table: ${d}`);s(d,t),st("patch",i);const g={...f,...i,_id:t};at(u,i,g,b),je(u,g,!0),ie(d,"before","update")&&await se("before","update",{doc:{...g},id:t,op:"update",previous:f,table:d}),ye(d),_e(d),xe(r,d,e`UPDATE ${e.identifier(d)} SET ${e.identifier(Z)} = ${JSON.stringify(g)} WHERE id = ${t} AND ${e.identifier(Z)} = ${$}`),ke(d,t,g,f),Ce(d,t,g),ve(d,f,g),Te(d,t,f,g),m?.invalidate(d,t),I(d,t,"update",g),l({key:t,op:"update",row:g,table:d}),ie(d,"after","update")&&await se("after","update",{doc:g,id:t,op:"update",previous:f,table:d}),await E({doc:g,id:t,op:"update",table:d})},async patchMany(t,i,a){ge(t.length,i?.limit,"patchMany");for(const p of t)await z.patch(p.id,p.patch,a);return{patched:t.length}},async patchWhere(t,i,a){const p=S(t,"patchWhere");let $;if(p)$=(await p.findMany(t,{where:i.where})).page.map(f=>({id:String(f._id),patch:i.patch}));else{if(!n.tables[t])throw new A("INTERNAL",`unknown table: ${t}`);$=(await z.findMany(t,{where:i.where})).page.map(f=>({id:String(f._id),patch:i.patch}))}if(ge($.length,a?.limit,"patchWhere"),z.patchMany===void 0)throw new A("INTERNAL",`ctx.db.${t}.patchMany is unavailable: this writer has no batch patch`);return await z.patchMany($,a),{patched:$.length}},query(t){const i=S(t,"query");return i?(s(t,Q),i.query(t)):(s(t,Q),On(r,n,t,c))},async rank(t,i,a){const p=S(t,"rank");if(p)return s(t,Q),p.rank(t,i,a);c(t,i,"rank");const $=n.tables[t];if(!$)throw new A("INTERNAL",`unknown table: ${t}`);const f=$.rankIndexes?.find(ne=>ne.name===i);if(!f)throw new A("INTERNAL",`unknown rankIndex "${i}" on table "${t}"`);if(Ke(t,$,f),a.restrictsCounts)throw new Pe(t);s(t,Q),Be(t,f);const d=typeof a.row=="string"?a.row:a.row._id;if(!d)return null;const u=Ie(t,f.name),g=f.sortBy.map((ne,we)=>Ae(we)),R=g.map(ne=>Pt(ne)).join(", "),y=M(r,e`SELECT ${e.identifier("__partition__")}, ${e.raw(R)} FROM ${e.identifier(u)} WHERE ${e.identifier("__id__")} = ${d}`).toArray(),[O]=y;if(O===void 0)return null;let K=O.__partition__;const V=re(a.baseWhere,a.where);He(V,n,t,"rank");const D=wt(f,V);if(D){const ne=De(f.partitionBy??[],D);if(ne!==K)return null;K=ne}const oe=g.map(ne=>O[ne]),{before:ae,total:le}=lt(r,u,g,f.sortBy,K,oe,d);return{position:ae+1,total:le}},async rankBefore(t,i,a){if(P(t))throw new A("INTERNAL",`rankBefore is not supported on the global (.global()) table '${t}' — cross-shard rank cursors apply only to sharded tables`);const p=n.tables[t];if(!p)throw new A("INTERNAL",`unknown table: ${t}`);const $=p.rankIndexes?.find(g=>g.name===i);if(!$)throw new A("INTERNAL",`unknown rankIndex "${i}" on table "${t}"`);if(a.restrictsCounts)throw new Pe(t);s(t,Q),Be(t,$);const f=Ie(t,$.name),d=$.sortBy.map((g,R)=>Ae(R)),u=$.sortBy.map((g,R)=>fe(a.sortValues[R]??null));return lt(r,f,d,$.sortBy,a.partitionKey,u,a.rowId)},async rankPage(t,i,a={}){He(re(a.baseWhere,a.where),n,t,"rankPage");const p=S(t,"rankPage");if(p)return s(t,Q),p.rankPage(t,i,a);c(t,i,"rank");const{continueCursor:$,hasMore:f,rows:d}=nt(Qe,t,i,a);return{continueCursor:$,isDone:!f,page:d.map(u=>u.doc)}},async rankPageRows(t,i,a={}){He(re(a.baseWhere,a.where),n,t,"rankPage"),c(t,i,"rank");const{directions:p,hasMore:$,rows:f}=nt(Qe,t,i,a);return{directions:p,hasMore:$,rows:f}},async restore(t,i){const a=$e(t,i);if(!a){const f=i===void 0?F():void 0;if(f?.restore){await f.restore(t);return}throw new A("INTERNAL",`document not found: ${t}`)}const p=n.tables[a.tableName]?.softDeleteMode?.field;if(!p)throw new A("INTERNAL",`ctx.db.restore: table "${a.tableName}" is not a .softDelete() table`);const $=a.row[p]!==null&&a.row[p]!==void 0;await z.patch(t,{[p]:null},i),$&&Te(a.tableName,t,void 0,a.row)},async replace(t,i,a,p){const $=$e(t,a);if(!$){const O=a===void 0?F():void 0;if(O){await O.replace(t,i,void 0,p);return}throw new A("INTERNAL",`document not found: ${t}`)}const{docJson:f,row:d,tableName:u}=$,g=n.tables[u];if(!g)throw new A("INTERNAL",`unknown table: ${u}`);st("replace",i);const R=p?.allowExplicitId&&typeof i._creationTime=="number"?i._creationTime:_(),y={...i,_creationTime:R,_id:t};at(g,i,y,b),je(g,y),ie(u,"before","update")&&await se("before","update",{doc:{...y},id:t,op:"update",previous:d,table:u}),ye(u),_e(u),xe(r,u,e`UPDATE ${e.identifier(u)} SET _creationTime = ${R}, ${e.identifier(Z)} = ${JSON.stringify(y)} WHERE id = ${t} AND ${e.identifier(Z)} = ${f}`),ke(u,t,y,d),Ce(u,t,y),ve(u,d,y),Te(u,t,d,y),m?.invalidate(u,t),I(u,t,"update",y),l({key:t,op:"update",row:y,table:u}),ie(u,"after","update")&&await se("after","update",{doc:y,id:t,op:"update",previous:d,table:u}),await E({doc:y,id:t,op:"update",table:u})},async wipeShard(t){const i=new Set(t?.exclude),a=t?.tables,p=Object.entries(n.tables).filter(([u,g])=>i.has(u)||a!==void 0&&!a.includes(u)?!1:g.shardMode?.kind!=="global").map(([u])=>u);if(a!==void 0){for(const u of a)if(!n.tables[u])throw new A("INTERNAL",`wipeShard: unknown table: ${u}`)}const $={};let f=0;const{deleteAll:d}=z;if(d===void 0)throw new A("INTERNAL","wipeShard: this writer has no deleteAll");for(const u of p){const g=await d(u,{...t?.chunkSize===void 0?{}:{chunkSize:t.chunkSize},hard:!0});$[u]=g.deleted,f+=g.deleted}return{deleted:f,tables:$}}},_t={db:z,scheduler:L};return o.enforceRls===!0?en(z,n,(t,i)=>$e(t,i)?.tableName):z};export{mi as CDC_LOG_TABLE,Si as CLIENT_WATERMARK_TABLE,Ri as GLOBAL_SHAPE_SNAPSHOT_TABLE,Ai as IDEMPOTENCY_TABLE,Mn as NotUniqueError,fi as SEARCH_STATE_TABLE,Ii as advanceClientWatermark,wi as applyCdcChanges,pn as assertValidClientId,ui as backfillAggregateIndexes,hi as backfillRankIndexes,$i as backfillSearchIndexes,gi as bumpCdcEpoch,li as createShardCtxDb,vi as deleteGlobalShapeSnapshot,Ci as deleteGlobalShapeSnapshotsForConnection,ki as migrateClientWatermark,Mi as migrateGlobalShapeSnapshot,Ei as minCdcSeq,ot as normalizeIdStructurally,bi as readCdcChanges,yi as readCdcCursor,_i as readCdcEpoch,Li as readClientWatermark,xi as readGlobalShapeSnapshot,Oi as readIdempotent,qi as runShardMigrations,Pi as selectShapeMemberIds,Hi as selectShapeRows,Ti as trimCdcChanges,Di as trimIdempotent,Wi as writeGlobalShapeSnapshot,Bi as writeIdempotent};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import"@lunora/search-core";import"drizzle-orm";import"./AGGREGATE_SQL_FUNCTION-QYaiuty4.mjs";import"./aggregateTableName-G-eXyjcz.mjs";import{H as b,P as f,X as k,Y as n}from"./ctx-db-backfill-C4rAzsQo.mjs";import"./do-exec-BLe9lLrN.mjs";import"./do-sql-x0AjZhaN.mjs";import"./renderSql-B5lF5Jd9.mjs";import"./RANK_TIEBREAK-DtX8zQyc.mjs";import"./serialize-sql-DiRzL7A4.mjs";export{b as backfillAggregateIndexes,f as backfillRankIndexes,k as backfillSearchIndexes,n as backfillSearchIndexesForTable};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{ftsTableName as I,createSearchAnalyzer as L,planSearchBackfillPass as N,FTS_ID_COLUMN as p,FTS_TEXT_COLUMN as A,analyzedSearchText as _}from"@lunora/search-core";import{sql as e}from"drizzle-orm";import{matchesStaticWhere as h}from"./AGGREGATE_SQL_FUNCTION-QYaiuty4.mjs";import{encodeAggregateKey as M,foldAggregateTally as C,aggregateTableName as y}from"./aggregateTableName-G-eXyjcz.mjs";import{r as f}from"./do-exec-BLe9lLrN.mjs";import{b as g,s as m,g as O,a as F,_ as b,m as x,N as D}from"./do-sql-x0AjZhaN.mjs";import{param as U}from"./renderSql-B5lF5Jd9.mjs";import{sortColumnName as k,matchesRankStaticWhere as w,encodePartitionKey as B,rankTableName as X}from"./RANK_TIEBREAK-DtX8zQyc.mjs";import{t as v}from"./serialize-sql-DiRzL7A4.mjs";const u="__lunora_search_state",W=i=>{const n=()=>{try{f(i,e`ALTER TABLE ${e.identifier(u)} ADD COLUMN ${e.identifier("profile")} TEXT`)}catch{}};f(i,e`CREATE TABLE IF NOT EXISTS ${e.identifier(u)} (${e.identifier("companion")} TEXT PRIMARY KEY, ${e.identifier("cursor")} TEXT, ${e.identifier("done")} INTEGER NOT NULL DEFAULT 0, ${e.identifier("profile")} TEXT)`),n()},j=i=>i===1||i===!0||i==="1",z=(i,n)=>{const r=f(i,e`SELECT ${e.identifier("cursor")}, ${e.identifier("done")}, ${e.identifier("profile")} FROM ${e.identifier(u)} WHERE ${e.identifier("companion")} = ${n}`).toArray()[0];return r?{cursor:r.cursor??void 0,done:j(r.done),profile:r.profile??void 0}:{cursor:void 0,done:!1,profile:void 0}},H=(i,n,r,o,d)=>{const a=r??null;f(i,e`INSERT INTO ${e.identifier(u)} (${e.identifier("companion")}, ${e.identifier("cursor")}, ${e.identifier("done")}, ${e.identifier("profile")}) VALUES (${n}, ${a}, ${o?1:0}, ${d}) ON CONFLICT (${e.identifier("companion")}) DO UPDATE SET ${e.identifier("cursor")} = excluded.${e.identifier("cursor")}, ${e.identifier("done")} = excluded.${e.identifier("done")}, ${e.identifier("profile")} = excluded.${e.identifier("profile")}`)},P=(i,n,r)=>{const o=y(n,r.name);if(f(i,e`SELECT COUNT(*) AS count FROM ${e.identifier(o)}`).one().count>0)return;const d=r.by??[],a=new Map,c=f(i,e`SELECT id, _creationTime, ${e.identifier(m)} FROM ${e.identifier(n)}`).toArray();for(const s of c){const t=O(s);if(!t||r.where&&!h(t,r.where))continue;const E=M(d,t);C(a,E,r,t)}for(const[s,t]of a)f(i,e`INSERT INTO ${e.identifier(o)} (${F}, ${b}, ${x}) VALUES (${s}, ${t.value}, ${t.count})`)},re=(i,n)=>{for(const[r,o]of Object.entries(n.tables))if(!(o.shardMode?.kind==="global"||!o.aggregateIndexes))for(const d of o.aggregateIndexes)P(i,r,d)},Y=(i,n,r)=>{const o=X(n,r.name);if(f(i,e`SELECT COUNT(*) AS count FROM ${e.identifier(o)}`).one().count>0)return;const d=r.sortBy.map((s,t)=>k(t)),a=e.join(["__id__","__partition__",...d].map(s=>e.identifier(s)),e`, `),c=f(i,e`SELECT id, _creationTime, ${e.identifier(m)} FROM ${e.identifier(n)}`).toArray();for(const s of c){const t=O(s);if(!t||r.where&&!w(t,r.where))continue;const E=B(r.partitionBy??[],t),l=r.sortBy.map(T=>v(t[T.field]??null)),$=e.join([t._id,E,...l].map(T=>U(T)),e`, `);f(i,e`INSERT INTO ${e.identifier(o)} (${a}) VALUES (${$})`)}},oe=(i,n)=>{for(const[r,o]of Object.entries(n.tables))if(!(o.shardMode?.kind==="global"||!o.rankIndexes))for(const d of o.rankIndexes)Y(i,r,d)},S=500,R=(i,n,r)=>{const o=I(n,r.name),{profile:d}=L(r.language),a=N(z(i,o),d);if(a.finished)return!0;a.wipe&&f(i,e`DELETE FROM ${e.identifier(o)}`);const{cursor:c}=a,s=f(i,c===void 0?e`SELECT id, _creationTime, ${e.identifier(m)} FROM ${e.identifier(n)} ORDER BY id ASC LIMIT ${e.raw(String(S))}`:e`SELECT id, _creationTime, ${e.identifier(m)} FROM ${e.identifier(n)} WHERE id > ${c} ORDER BY id ASC LIMIT ${e.raw(String(S))}`).toArray();let t=c;for(const l of s){const{id:$}=l;if(typeof $!="string")continue;t=$;const T=D(l);if(!T){f(i,e`DELETE FROM ${e.identifier(o)} WHERE ${e.identifier(p)} = ${$}`);continue}f(i,e`DELETE FROM ${e.identifier(o)} WHERE ${e.identifier(p)} = ${$}`),f(i,e`INSERT INTO ${e.identifier(o)} (${e.identifier(A)}, ${e.identifier(p)}) VALUES (${_(T,r)}, ${$})`)}const E=s.length<S;return H(i,o,t,E,d),E},ne=(i,n,r)=>{if(g(i))for(const o of r.searchIndexes??[])o.staged||R(i,n,o)},te=(i,n)=>{if(g(i)){W(i);for(const[r,o]of Object.entries(n.tables))if(!(o.shardMode?.kind==="global"||!o.searchIndexes))for(const d of o.searchIndexes){let a=!1;for(;!a;)a=R(i,r,d)}}};export{re as H,oe as P,te as X,ne as Y,W as l,u as o};
|
|
@@ -1,5 +0,0 @@
|
|
|
1
|
-
import{ftsTableName as N,FTS_TEXT_COLUMN as I,FTS_ID_COLUMN as S}from"@lunora/search-core";import{sql as e}from"drizzle-orm";import{aggregateTableName as g}from"./aggregateTableName-G-eXyjcz.mjs";import{l as R,Y as h}from"./ctx-db-backfill-C4rAzsQo.mjs";import{migrateCdcLog as p,migrateCdcMeta as l}from"./CDC_LOG_TABLE-E_J5LPoK.mjs";import{u as O,_ as C,E as U,a as u}from"./schema-history-YGeVjyvV.mjs";import{r as s}from"./do-exec-BLe9lLrN.mjs";import{s as X,$,p as f,L as b,b as B,a as x,_ as M,m,T as Y}from"./do-sql-x0AjZhaN.mjs";import{sortColumnName as F,rankTableName as D}from"./RANK_TIEBREAK-DtX8zQyc.mjs";const j=(n,t,o)=>{for(const i of o.indexes){const r=`${t}_${i.name}`,a=e.join(i.fields.map(_=>$(_)),e`, `);s(n,f(r,t,a,i.unique??!1))}for(const[i,r]of b(o)){if(!r.unique)continue;const a=`${t}_unique_${i}`;s(n,f(a,t,$(i),!0))}},k=(n,t,o)=>{if(!(!o.searchIndexes||o.searchIndexes.length===0||!B(n))){for(const i of o.searchIndexes){const r=N(t,i.name);s(n,e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(r)} USING fts5(${e.identifier(I)}, ${e.identifier(S)} UNINDEXED)`),s(n,e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(`${r}__vocab`)} USING fts5vocab(${e.identifier(r)}, ${e.raw("instance")})`)}h(n,t,o)}},y=(n,t,o)=>{if(o.geoIndexes)for(const i of o.geoIndexes){const r=Y(t,i.name);s(n,e`CREATE TABLE IF NOT EXISTS ${e.identifier(r)} (${e.identifier("__id__")} TEXT PRIMARY KEY, ${e.identifier("__geohash__")} TEXT NOT NULL, ${e.identifier("__lat__")} REAL NOT NULL, ${e.identifier("__lng__")} REAL NOT NULL)`);const a=`${t}__geo_${i.name}__btree`;s(n,f(a,r,e`${e.identifier("__geohash__")} ASC, ${e.identifier("__id__")} ASC`,!1))}},G=(n,t,o)=>{if(o.aggregateIndexes)for(const i of o.aggregateIndexes){const r=g(t,i.name);s(n,e`CREATE TABLE IF NOT EXISTS ${e.identifier(r)} (${x} TEXT PRIMARY KEY, ${M} REAL, ${m} INTEGER NOT NULL DEFAULT 0)`),s(n,e`PRAGMA table_info(${e.identifier(r)})`).toArray().some(a=>a.name==="__count__")||s(n,e`ALTER TABLE ${e.identifier(r)} ADD COLUMN ${m} INTEGER NOT NULL DEFAULT 0`)}},P=(n,t,o)=>{if(o.rankIndexes)for(const i of o.rankIndexes){const r=D(t,i.name),a=i.sortBy.map((T,d)=>F(d)),_=a.map(T=>e`${e.identifier(T)} BLOB`),c=_.length>0?e`, ${e.join(_,e`, `)}`:e``;s(n,e`CREATE TABLE IF NOT EXISTS ${e.identifier(r)} (${e.identifier("__id__")} TEXT PRIMARY KEY, ${e.identifier("__partition__")} TEXT NOT NULL${c})`);const E=[e`${e.identifier("__partition__")} ASC`];for(const[T,d]of a.entries()){const A=i.sortBy[T]?.direction;E.push(e`${e.identifier(d)} ${e.raw(A==="desc"?"DESC":"ASC")}`)}E.push(e`${e.identifier("__id__")} ASC`);const L=`${t}__rank_${i.name}__btree`;s(n,f(L,r,e.join(E,e`, `),!1))}},W=(n,t,o={})=>{o.schemaSnapshot!==void 0&&O(n,o.schemaSnapshot.hash,o.schemaSnapshot.json),R(n);for(const[i,r]of Object.entries(t.tables))r.shardMode?.kind!=="global"&&(s(n,e`CREATE TABLE IF NOT EXISTS ${e.identifier(i)} (
|
|
2
|
-
id TEXT PRIMARY KEY,
|
|
3
|
-
_creationTime REAL NOT NULL,
|
|
4
|
-
${e.identifier(X)} TEXT NOT NULL
|
|
5
|
-
)`),j(n,i,r),k(n,i,r),y(n,i,r),G(n,i,r),P(n,i,r));o.cdc&&(p(n),l(n),C(n)),U(n),u(n)};export{W as runShardMigrations};
|