@lunora/runtime 1.0.0-alpha.58 → 1.0.0-alpha.59

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -44,6 +44,8 @@ declare const backupObjectKey: (prefix: string, id: string) => string;
44
44
  declare const backupManifestKey: (objectKey: string) => string;
45
45
  /** Is this the sidecar of a snapshot, rather than the snapshot itself? */
46
46
  declare const isBackupManifestKey: (key: string) => boolean;
47
+ /** The snapshot key a sidecar describes — the inverse of {@link backupManifestKey}. */
48
+ declare const backupObjectKeyOfManifest: (manifestKey: string) => string;
47
49
  /**
48
50
  * What every snapshot records about itself, whichever writer took it.
49
51
  *
@@ -2676,6 +2678,34 @@ type TraceTrustSignal = "mtls";
2676
2678
  * can reach the worker.
2677
2679
  */
2678
2680
  type TrustInboundTraceContext = boolean | TraceTrustSignal | ((request: Request) => boolean);
2681
+ /** What a prune did. Keys are sidecar keys; each names a snapshot at the same key without the suffix. */
2682
+ interface PrunedBackups {
2683
+ /** Removed, snapshot and sidecar both. */
2684
+ deleted: string[];
2685
+ /** Attempted and not removed. The snapshot may already be gone — the sidecar survives, so the next run retries. */
2686
+ failed: string[];
2687
+ /** Confirmed keys retention no longer owns: already pruned, or no longer eligible. */
2688
+ ignored: number;
2689
+ /** Still past the window afterwards — they appeared after the preview, or the run stopped at its cap. Run again. */
2690
+ remaining: number;
2691
+ }
2692
+ /** What retention would delete on the next run, and the configuration that decides it. */
2693
+ interface BackupRetentionPreview {
2694
+ /** The trigger retention belongs to. `undefined` when no scheduled backup is configured. */
2695
+ cron?: string;
2696
+ /**
2697
+ * Snapshots this cron owns — legacy sidecars and other writers' are not
2698
+ * counted, because retention never touches them. `0` when there is no
2699
+ * window (`keep === 0`): with nothing to select against, the bucket is not
2700
+ * listed at all.
2701
+ */
2702
+ eligible: number;
2703
+ /** `backupRetain`; `0` when unset, which is what makes the selection empty. */
2704
+ keep: number;
2705
+ prefix: string;
2706
+ /** Sidecar keys, newest-first. Each names a snapshot at the same key without the suffix. */
2707
+ wouldDelete: string[];
2708
+ }
2679
2709
  /** A snapshot the scheduled backup took: the shared fields plus which trigger produced it. */
2680
2710
  interface BackupManifest extends BackupManifestEntry {
2681
2711
  cron: string;
@@ -4802,4 +4832,4 @@ declare const createShardClient: (namespace: ShardNamespaceLike, options?: Shard
4802
4832
  */
4803
4833
  declare const STORAGE_UPLOAD_MAX_BODY_BYTES: number;
4804
4834
  declare const VERSION: string;
4805
- export { type AdminTableResolver, type AirbyteMessage, type AnalyticsEngineDataPointLike, type AnalyticsEngineDatasetLike, type AnalyticsEngineSinkOptions, type AuthAdmin, type AuthCapabilities, type AuthConfigInfo, type AuthImpersonation, type AuthPage, type AuthSession, type AuthUser, type AuthUserFieldSpec, BACKUP_KEY_PREFIX, type BackupManifest, type BackupManifestEntry, type BackupStore, type ComposeIdentityResolversErrorMode, type ComposeIdentityResolversOptions, type ConnectorChange, type ConnectorSyncPage, type CorsOptions, type CronHandler, type CronJobDispatch, type CronJobInfo, type CrossShardCounter, type CrossShardReader, type CrossShardRelationCapabilities, type CrossShardRelationOptions, type CsrfOptions, DEFAULT_LOG_COLUMNS, DEFAULT_LOG_LIMIT, DEFAULT_REGISTRY_CACHE_TTL_MS, type DurableObjectJurisdiction, type DynamicShardRegistry, type DynamicShardRegistryOptions, type ExecutionContextLike, type ExportBatch, type ExportChange, type ExportCursorStore, type ExportFanOutRequest, type ExportFanOutResult, type ExportSink, type ExportTapFailure, type ExportTapResult, type FanOutRequest, type FanOutResult, type FanOutSpec, type FivetranResponse, type FrameworkHostHandler, type FrameworkWorkerOptions, type FrameworkWorkerOptionsInput, type FunctionDescriptor, type FunctionRegistryEntry, type FunctionRegistryLike, type GlobalExportFunction as GlobalExportFn, type GlobalImportFunction as GlobalImportFn, type GlobalIntrospector, type GlobalTableInfo as GlobalTableInfoMeta, type GlobalTablePage as GlobalTablePageMeta, HEALTH_PATH, HEALTH_READY_PATH, type HealthAuthPosture, type HealthBody, type HealthCheckReport, type HealthProbe, type HealthProbeKind, type HealthProbeResult, type HealthRouteDeps, type HttpActionContext, type HttpActionLike, type HttpRouterLike, type IdentityContractLike, type IdentityResolver, type IdentityValidation, type ImportFanOutRequest, type ImportFanOutResult, type KvIntrospector, type KvKeyEntry, type KvKeyListResult, type KvNamespaceSummary, type KvValueResult, LOG_ARCHIVE_NOT_CONFIGURED, LOG_ARCHIVE_PATH, type ListAuthUsersOptions, type LogArchiveConfig, type LogEvent, type LogFields, type LogLevel, LunoraError, type LunoraErrorBody, type LunoraHandlerOptions, type LunoraWorker, type MemoizeIdentityOptions, type MergeStrategy, type MetricEvent, type MetricKind, type MigrationFanOutRequest, type MigrationFanOutResult, NOOP_EXECUTION_CONTEXT, type NotifySubscriptionDevice, type NotifySubscriptionStoreLike, type ObservabilityEvent, type ObservabilitySink, type ObservabilitySinkContext, type OtlpResourceAttributes, type OtlpSinkOptions, type PipelineLike, type PipelineLogColumnMap, type PipelineLogCursor, type PipelineLogField, type PipelineLogPage, type PipelineLogQuery, type PipelineLogReader, type PipelineLogReaderOptions, type PipelineLogRow, type PipelineLogSinkOptions, type QueryCoordinator, type QueryCoordinatorOptions, type RankFanOutRequest, type RankFanOutResult, type RankPageFanOutRequest, type RankPageFanOutResult, type RateLimiterLike, type ResolvedSecurity, type ResolvedShard, type RestInvoke, type RestRateLimit, type RestRegistryEntry, type RestRegistryLike, type RestRoute, type RestRouteDeps, type Route, type RpcContext, type RpcEnvelope, type RunExportTapOptions, SHARD_REGISTRY_DO_NAME, STORAGE_UPLOAD_MAX_BODY_BYTES, type ScheduledControllerLike, type SecurityHeadersOptions, type SecurityOptions, type SentrySinkOptions, type ShardCallArgs, type ShardCallOptions, type ShardCallReturn, type ShardCallerIdentity, type ShardClient, type ShardClientOptions, type ShardError, type ShardExportOutcome, type ShardFunctionReference, type ShardImportOutcome, type ShardMigrationOutcome, type ShardNamespaceInput, type ShardNamespaceLike, type ShardRankOutcome, type ShardRankPageOutcome, type ShardRegistry, type ShardTrafficEntry, type ShardTrafficFanOutRequest, type ShardTrafficFanOutResult, type ShardingInfo, type SpanEvent, type StorageListFunction as StorageListFn, type StorageObject, type TraceSamplingConfig, type TraceTrustSignal, type TrustInboundTraceContext, VERSION, type VectorIndexSummary, type VectorIntrospector, type VectorQueryMatch, type WebhookSinkOptions, type WorkerOptions, analyticsEngineSink, applyJurisdiction, applyRestCache, argsFromQuery, backupManifestKey, backupObjectKey, buildHealthRoutes, buildRestRoutes, combineSinks, composeIdentityResolvers, composeWorker, consoleSink, createCrossShardRelationCapabilities, createDynamicShardRegistry, createKvCursorStore, createLunoraHandler, createMemoryCursorStore, createPipelineLogReader, createQueryCoordinator, createRestRateLimit, createShardClient, createStaticShardRegistry, createWorker, d1Probe, decorateResponse, defineExportSink, defineRpcEnvelope, durableObjectProbe, emitLogEvent, emitRpcEvent, enforceOrigin, handleCorsPreflight, isBackupManifestEntry, isBackupManifestKey, memoizeIdentity, memoizeIdentityPerRequest, mergeStrategyForAggregate, normalizeBackupPrefix, otlpSink, pipelineLogSink, presenceProbe, r2Sink, readShardKey, requestCarriesCredentials, resolveLogArchiveFromEnv, resolveLunoraOptions, resolveSecurity, resolveShard, restCacheHeaders, restSurfaceFromRegistry, routeIdentityResolvers, runExportTap, sanitizeChange, sentrySink, toAirbyteMessages, toErrorResponse, toFivetranResponse, webhookExportSink, webhookSink, withFrameworkWorker };
4835
+ export { type AdminTableResolver, type AirbyteMessage, type AnalyticsEngineDataPointLike, type AnalyticsEngineDatasetLike, type AnalyticsEngineSinkOptions, type AuthAdmin, type AuthCapabilities, type AuthConfigInfo, type AuthImpersonation, type AuthPage, type AuthSession, type AuthUser, type AuthUserFieldSpec, BACKUP_KEY_PREFIX, type BackupManifest, type BackupManifestEntry, type BackupRetentionPreview, type BackupStore, type ComposeIdentityResolversErrorMode, type ComposeIdentityResolversOptions, type ConnectorChange, type ConnectorSyncPage, type CorsOptions, type CronHandler, type CronJobDispatch, type CronJobInfo, type CrossShardCounter, type CrossShardReader, type CrossShardRelationCapabilities, type CrossShardRelationOptions, type CsrfOptions, DEFAULT_LOG_COLUMNS, DEFAULT_LOG_LIMIT, DEFAULT_REGISTRY_CACHE_TTL_MS, type DurableObjectJurisdiction, type DynamicShardRegistry, type DynamicShardRegistryOptions, type ExecutionContextLike, type ExportBatch, type ExportChange, type ExportCursorStore, type ExportFanOutRequest, type ExportFanOutResult, type ExportSink, type ExportTapFailure, type ExportTapResult, type FanOutRequest, type FanOutResult, type FanOutSpec, type FivetranResponse, type FrameworkHostHandler, type FrameworkWorkerOptions, type FrameworkWorkerOptionsInput, type FunctionDescriptor, type FunctionRegistryEntry, type FunctionRegistryLike, type GlobalExportFunction as GlobalExportFn, type GlobalImportFunction as GlobalImportFn, type GlobalIntrospector, type GlobalTableInfo as GlobalTableInfoMeta, type GlobalTablePage as GlobalTablePageMeta, HEALTH_PATH, HEALTH_READY_PATH, type HealthAuthPosture, type HealthBody, type HealthCheckReport, type HealthProbe, type HealthProbeKind, type HealthProbeResult, type HealthRouteDeps, type HttpActionContext, type HttpActionLike, type HttpRouterLike, type IdentityContractLike, type IdentityResolver, type IdentityValidation, type ImportFanOutRequest, type ImportFanOutResult, type KvIntrospector, type KvKeyEntry, type KvKeyListResult, type KvNamespaceSummary, type KvValueResult, LOG_ARCHIVE_NOT_CONFIGURED, LOG_ARCHIVE_PATH, type ListAuthUsersOptions, type LogArchiveConfig, type LogEvent, type LogFields, type LogLevel, LunoraError, type LunoraErrorBody, type LunoraHandlerOptions, type LunoraWorker, type MemoizeIdentityOptions, type MergeStrategy, type MetricEvent, type MetricKind, type MigrationFanOutRequest, type MigrationFanOutResult, NOOP_EXECUTION_CONTEXT, type NotifySubscriptionDevice, type NotifySubscriptionStoreLike, type ObservabilityEvent, type ObservabilitySink, type ObservabilitySinkContext, type OtlpResourceAttributes, type OtlpSinkOptions, type PipelineLike, type PipelineLogColumnMap, type PipelineLogCursor, type PipelineLogField, type PipelineLogPage, type PipelineLogQuery, type PipelineLogReader, type PipelineLogReaderOptions, type PipelineLogRow, type PipelineLogSinkOptions, type PrunedBackups, type QueryCoordinator, type QueryCoordinatorOptions, type RankFanOutRequest, type RankFanOutResult, type RankPageFanOutRequest, type RankPageFanOutResult, type RateLimiterLike, type ResolvedSecurity, type ResolvedShard, type RestInvoke, type RestRateLimit, type RestRegistryEntry, type RestRegistryLike, type RestRoute, type RestRouteDeps, type Route, type RpcContext, type RpcEnvelope, type RunExportTapOptions, SHARD_REGISTRY_DO_NAME, STORAGE_UPLOAD_MAX_BODY_BYTES, type ScheduledControllerLike, type SecurityHeadersOptions, type SecurityOptions, type SentrySinkOptions, type ShardCallArgs, type ShardCallOptions, type ShardCallReturn, type ShardCallerIdentity, type ShardClient, type ShardClientOptions, type ShardError, type ShardExportOutcome, type ShardFunctionReference, type ShardImportOutcome, type ShardMigrationOutcome, type ShardNamespaceInput, type ShardNamespaceLike, type ShardRankOutcome, type ShardRankPageOutcome, type ShardRegistry, type ShardTrafficEntry, type ShardTrafficFanOutRequest, type ShardTrafficFanOutResult, type ShardingInfo, type SpanEvent, type StorageListFunction as StorageListFn, type StorageObject, type TraceSamplingConfig, type TraceTrustSignal, type TrustInboundTraceContext, VERSION, type VectorIndexSummary, type VectorIntrospector, type VectorQueryMatch, type WebhookSinkOptions, type WorkerOptions, analyticsEngineSink, applyJurisdiction, applyRestCache, argsFromQuery, backupManifestKey, backupObjectKey, backupObjectKeyOfManifest, buildHealthRoutes, buildRestRoutes, combineSinks, composeIdentityResolvers, composeWorker, consoleSink, createCrossShardRelationCapabilities, createDynamicShardRegistry, createKvCursorStore, createLunoraHandler, createMemoryCursorStore, createPipelineLogReader, createQueryCoordinator, createRestRateLimit, createShardClient, createStaticShardRegistry, createWorker, d1Probe, decorateResponse, defineExportSink, defineRpcEnvelope, durableObjectProbe, emitLogEvent, emitRpcEvent, enforceOrigin, handleCorsPreflight, isBackupManifestEntry, isBackupManifestKey, memoizeIdentity, memoizeIdentityPerRequest, mergeStrategyForAggregate, normalizeBackupPrefix, otlpSink, pipelineLogSink, presenceProbe, r2Sink, readShardKey, requestCarriesCredentials, resolveLogArchiveFromEnv, resolveLunoraOptions, resolveSecurity, resolveShard, restCacheHeaders, restSurfaceFromRegistry, routeIdentityResolvers, runExportTap, sanitizeChange, sentrySink, toAirbyteMessages, toErrorResponse, toFivetranResponse, webhookExportSink, webhookSink, withFrameworkWorker };
package/dist/index.d.ts CHANGED
@@ -44,6 +44,8 @@ declare const backupObjectKey: (prefix: string, id: string) => string;
44
44
  declare const backupManifestKey: (objectKey: string) => string;
45
45
  /** Is this the sidecar of a snapshot, rather than the snapshot itself? */
46
46
  declare const isBackupManifestKey: (key: string) => boolean;
47
+ /** The snapshot key a sidecar describes — the inverse of {@link backupManifestKey}. */
48
+ declare const backupObjectKeyOfManifest: (manifestKey: string) => string;
47
49
  /**
48
50
  * What every snapshot records about itself, whichever writer took it.
49
51
  *
@@ -2676,6 +2678,34 @@ type TraceTrustSignal = "mtls";
2676
2678
  * can reach the worker.
2677
2679
  */
2678
2680
  type TrustInboundTraceContext = boolean | TraceTrustSignal | ((request: Request) => boolean);
2681
+ /** What a prune did. Keys are sidecar keys; each names a snapshot at the same key without the suffix. */
2682
+ interface PrunedBackups {
2683
+ /** Removed, snapshot and sidecar both. */
2684
+ deleted: string[];
2685
+ /** Attempted and not removed. The snapshot may already be gone — the sidecar survives, so the next run retries. */
2686
+ failed: string[];
2687
+ /** Confirmed keys retention no longer owns: already pruned, or no longer eligible. */
2688
+ ignored: number;
2689
+ /** Still past the window afterwards — they appeared after the preview, or the run stopped at its cap. Run again. */
2690
+ remaining: number;
2691
+ }
2692
+ /** What retention would delete on the next run, and the configuration that decides it. */
2693
+ interface BackupRetentionPreview {
2694
+ /** The trigger retention belongs to. `undefined` when no scheduled backup is configured. */
2695
+ cron?: string;
2696
+ /**
2697
+ * Snapshots this cron owns — legacy sidecars and other writers' are not
2698
+ * counted, because retention never touches them. `0` when there is no
2699
+ * window (`keep === 0`): with nothing to select against, the bucket is not
2700
+ * listed at all.
2701
+ */
2702
+ eligible: number;
2703
+ /** `backupRetain`; `0` when unset, which is what makes the selection empty. */
2704
+ keep: number;
2705
+ prefix: string;
2706
+ /** Sidecar keys, newest-first. Each names a snapshot at the same key without the suffix. */
2707
+ wouldDelete: string[];
2708
+ }
2679
2709
  /** A snapshot the scheduled backup took: the shared fields plus which trigger produced it. */
2680
2710
  interface BackupManifest extends BackupManifestEntry {
2681
2711
  cron: string;
@@ -4802,4 +4832,4 @@ declare const createShardClient: (namespace: ShardNamespaceLike, options?: Shard
4802
4832
  */
4803
4833
  declare const STORAGE_UPLOAD_MAX_BODY_BYTES: number;
4804
4834
  declare const VERSION: string;
4805
- export { type AdminTableResolver, type AirbyteMessage, type AnalyticsEngineDataPointLike, type AnalyticsEngineDatasetLike, type AnalyticsEngineSinkOptions, type AuthAdmin, type AuthCapabilities, type AuthConfigInfo, type AuthImpersonation, type AuthPage, type AuthSession, type AuthUser, type AuthUserFieldSpec, BACKUP_KEY_PREFIX, type BackupManifest, type BackupManifestEntry, type BackupStore, type ComposeIdentityResolversErrorMode, type ComposeIdentityResolversOptions, type ConnectorChange, type ConnectorSyncPage, type CorsOptions, type CronHandler, type CronJobDispatch, type CronJobInfo, type CrossShardCounter, type CrossShardReader, type CrossShardRelationCapabilities, type CrossShardRelationOptions, type CsrfOptions, DEFAULT_LOG_COLUMNS, DEFAULT_LOG_LIMIT, DEFAULT_REGISTRY_CACHE_TTL_MS, type DurableObjectJurisdiction, type DynamicShardRegistry, type DynamicShardRegistryOptions, type ExecutionContextLike, type ExportBatch, type ExportChange, type ExportCursorStore, type ExportFanOutRequest, type ExportFanOutResult, type ExportSink, type ExportTapFailure, type ExportTapResult, type FanOutRequest, type FanOutResult, type FanOutSpec, type FivetranResponse, type FrameworkHostHandler, type FrameworkWorkerOptions, type FrameworkWorkerOptionsInput, type FunctionDescriptor, type FunctionRegistryEntry, type FunctionRegistryLike, type GlobalExportFunction as GlobalExportFn, type GlobalImportFunction as GlobalImportFn, type GlobalIntrospector, type GlobalTableInfo as GlobalTableInfoMeta, type GlobalTablePage as GlobalTablePageMeta, HEALTH_PATH, HEALTH_READY_PATH, type HealthAuthPosture, type HealthBody, type HealthCheckReport, type HealthProbe, type HealthProbeKind, type HealthProbeResult, type HealthRouteDeps, type HttpActionContext, type HttpActionLike, type HttpRouterLike, type IdentityContractLike, type IdentityResolver, type IdentityValidation, type ImportFanOutRequest, type ImportFanOutResult, type KvIntrospector, type KvKeyEntry, type KvKeyListResult, type KvNamespaceSummary, type KvValueResult, LOG_ARCHIVE_NOT_CONFIGURED, LOG_ARCHIVE_PATH, type ListAuthUsersOptions, type LogArchiveConfig, type LogEvent, type LogFields, type LogLevel, LunoraError, type LunoraErrorBody, type LunoraHandlerOptions, type LunoraWorker, type MemoizeIdentityOptions, type MergeStrategy, type MetricEvent, type MetricKind, type MigrationFanOutRequest, type MigrationFanOutResult, NOOP_EXECUTION_CONTEXT, type NotifySubscriptionDevice, type NotifySubscriptionStoreLike, type ObservabilityEvent, type ObservabilitySink, type ObservabilitySinkContext, type OtlpResourceAttributes, type OtlpSinkOptions, type PipelineLike, type PipelineLogColumnMap, type PipelineLogCursor, type PipelineLogField, type PipelineLogPage, type PipelineLogQuery, type PipelineLogReader, type PipelineLogReaderOptions, type PipelineLogRow, type PipelineLogSinkOptions, type QueryCoordinator, type QueryCoordinatorOptions, type RankFanOutRequest, type RankFanOutResult, type RankPageFanOutRequest, type RankPageFanOutResult, type RateLimiterLike, type ResolvedSecurity, type ResolvedShard, type RestInvoke, type RestRateLimit, type RestRegistryEntry, type RestRegistryLike, type RestRoute, type RestRouteDeps, type Route, type RpcContext, type RpcEnvelope, type RunExportTapOptions, SHARD_REGISTRY_DO_NAME, STORAGE_UPLOAD_MAX_BODY_BYTES, type ScheduledControllerLike, type SecurityHeadersOptions, type SecurityOptions, type SentrySinkOptions, type ShardCallArgs, type ShardCallOptions, type ShardCallReturn, type ShardCallerIdentity, type ShardClient, type ShardClientOptions, type ShardError, type ShardExportOutcome, type ShardFunctionReference, type ShardImportOutcome, type ShardMigrationOutcome, type ShardNamespaceInput, type ShardNamespaceLike, type ShardRankOutcome, type ShardRankPageOutcome, type ShardRegistry, type ShardTrafficEntry, type ShardTrafficFanOutRequest, type ShardTrafficFanOutResult, type ShardingInfo, type SpanEvent, type StorageListFunction as StorageListFn, type StorageObject, type TraceSamplingConfig, type TraceTrustSignal, type TrustInboundTraceContext, VERSION, type VectorIndexSummary, type VectorIntrospector, type VectorQueryMatch, type WebhookSinkOptions, type WorkerOptions, analyticsEngineSink, applyJurisdiction, applyRestCache, argsFromQuery, backupManifestKey, backupObjectKey, buildHealthRoutes, buildRestRoutes, combineSinks, composeIdentityResolvers, composeWorker, consoleSink, createCrossShardRelationCapabilities, createDynamicShardRegistry, createKvCursorStore, createLunoraHandler, createMemoryCursorStore, createPipelineLogReader, createQueryCoordinator, createRestRateLimit, createShardClient, createStaticShardRegistry, createWorker, d1Probe, decorateResponse, defineExportSink, defineRpcEnvelope, durableObjectProbe, emitLogEvent, emitRpcEvent, enforceOrigin, handleCorsPreflight, isBackupManifestEntry, isBackupManifestKey, memoizeIdentity, memoizeIdentityPerRequest, mergeStrategyForAggregate, normalizeBackupPrefix, otlpSink, pipelineLogSink, presenceProbe, r2Sink, readShardKey, requestCarriesCredentials, resolveLogArchiveFromEnv, resolveLunoraOptions, resolveSecurity, resolveShard, restCacheHeaders, restSurfaceFromRegistry, routeIdentityResolvers, runExportTap, sanitizeChange, sentrySink, toAirbyteMessages, toErrorResponse, toFivetranResponse, webhookExportSink, webhookSink, withFrameworkWorker };
4835
+ export { type AdminTableResolver, type AirbyteMessage, type AnalyticsEngineDataPointLike, type AnalyticsEngineDatasetLike, type AnalyticsEngineSinkOptions, type AuthAdmin, type AuthCapabilities, type AuthConfigInfo, type AuthImpersonation, type AuthPage, type AuthSession, type AuthUser, type AuthUserFieldSpec, BACKUP_KEY_PREFIX, type BackupManifest, type BackupManifestEntry, type BackupRetentionPreview, type BackupStore, type ComposeIdentityResolversErrorMode, type ComposeIdentityResolversOptions, type ConnectorChange, type ConnectorSyncPage, type CorsOptions, type CronHandler, type CronJobDispatch, type CronJobInfo, type CrossShardCounter, type CrossShardReader, type CrossShardRelationCapabilities, type CrossShardRelationOptions, type CsrfOptions, DEFAULT_LOG_COLUMNS, DEFAULT_LOG_LIMIT, DEFAULT_REGISTRY_CACHE_TTL_MS, type DurableObjectJurisdiction, type DynamicShardRegistry, type DynamicShardRegistryOptions, type ExecutionContextLike, type ExportBatch, type ExportChange, type ExportCursorStore, type ExportFanOutRequest, type ExportFanOutResult, type ExportSink, type ExportTapFailure, type ExportTapResult, type FanOutRequest, type FanOutResult, type FanOutSpec, type FivetranResponse, type FrameworkHostHandler, type FrameworkWorkerOptions, type FrameworkWorkerOptionsInput, type FunctionDescriptor, type FunctionRegistryEntry, type FunctionRegistryLike, type GlobalExportFunction as GlobalExportFn, type GlobalImportFunction as GlobalImportFn, type GlobalIntrospector, type GlobalTableInfo as GlobalTableInfoMeta, type GlobalTablePage as GlobalTablePageMeta, HEALTH_PATH, HEALTH_READY_PATH, type HealthAuthPosture, type HealthBody, type HealthCheckReport, type HealthProbe, type HealthProbeKind, type HealthProbeResult, type HealthRouteDeps, type HttpActionContext, type HttpActionLike, type HttpRouterLike, type IdentityContractLike, type IdentityResolver, type IdentityValidation, type ImportFanOutRequest, type ImportFanOutResult, type KvIntrospector, type KvKeyEntry, type KvKeyListResult, type KvNamespaceSummary, type KvValueResult, LOG_ARCHIVE_NOT_CONFIGURED, LOG_ARCHIVE_PATH, type ListAuthUsersOptions, type LogArchiveConfig, type LogEvent, type LogFields, type LogLevel, LunoraError, type LunoraErrorBody, type LunoraHandlerOptions, type LunoraWorker, type MemoizeIdentityOptions, type MergeStrategy, type MetricEvent, type MetricKind, type MigrationFanOutRequest, type MigrationFanOutResult, NOOP_EXECUTION_CONTEXT, type NotifySubscriptionDevice, type NotifySubscriptionStoreLike, type ObservabilityEvent, type ObservabilitySink, type ObservabilitySinkContext, type OtlpResourceAttributes, type OtlpSinkOptions, type PipelineLike, type PipelineLogColumnMap, type PipelineLogCursor, type PipelineLogField, type PipelineLogPage, type PipelineLogQuery, type PipelineLogReader, type PipelineLogReaderOptions, type PipelineLogRow, type PipelineLogSinkOptions, type PrunedBackups, type QueryCoordinator, type QueryCoordinatorOptions, type RankFanOutRequest, type RankFanOutResult, type RankPageFanOutRequest, type RankPageFanOutResult, type RateLimiterLike, type ResolvedSecurity, type ResolvedShard, type RestInvoke, type RestRateLimit, type RestRegistryEntry, type RestRegistryLike, type RestRoute, type RestRouteDeps, type Route, type RpcContext, type RpcEnvelope, type RunExportTapOptions, SHARD_REGISTRY_DO_NAME, STORAGE_UPLOAD_MAX_BODY_BYTES, type ScheduledControllerLike, type SecurityHeadersOptions, type SecurityOptions, type SentrySinkOptions, type ShardCallArgs, type ShardCallOptions, type ShardCallReturn, type ShardCallerIdentity, type ShardClient, type ShardClientOptions, type ShardError, type ShardExportOutcome, type ShardFunctionReference, type ShardImportOutcome, type ShardMigrationOutcome, type ShardNamespaceInput, type ShardNamespaceLike, type ShardRankOutcome, type ShardRankPageOutcome, type ShardRegistry, type ShardTrafficEntry, type ShardTrafficFanOutRequest, type ShardTrafficFanOutResult, type ShardingInfo, type SpanEvent, type StorageListFunction as StorageListFn, type StorageObject, type TraceSamplingConfig, type TraceTrustSignal, type TrustInboundTraceContext, VERSION, type VectorIndexSummary, type VectorIntrospector, type VectorQueryMatch, type WebhookSinkOptions, type WorkerOptions, analyticsEngineSink, applyJurisdiction, applyRestCache, argsFromQuery, backupManifestKey, backupObjectKey, backupObjectKeyOfManifest, buildHealthRoutes, buildRestRoutes, combineSinks, composeIdentityResolvers, composeWorker, consoleSink, createCrossShardRelationCapabilities, createDynamicShardRegistry, createKvCursorStore, createLunoraHandler, createMemoryCursorStore, createPipelineLogReader, createQueryCoordinator, createRestRateLimit, createShardClient, createStaticShardRegistry, createWorker, d1Probe, decorateResponse, defineExportSink, defineRpcEnvelope, durableObjectProbe, emitLogEvent, emitRpcEvent, enforceOrigin, handleCorsPreflight, isBackupManifestEntry, isBackupManifestKey, memoizeIdentity, memoizeIdentityPerRequest, mergeStrategyForAggregate, normalizeBackupPrefix, otlpSink, pipelineLogSink, presenceProbe, r2Sink, readShardKey, requestCarriesCredentials, resolveLogArchiveFromEnv, resolveLunoraOptions, resolveSecurity, resolveShard, restCacheHeaders, restSurfaceFromRegistry, routeIdentityResolvers, runExportTap, sanitizeChange, sentrySink, toAirbyteMessages, toErrorResponse, toFivetranResponse, webhookExportSink, webhookSink, withFrameworkWorker };
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{BACKUP_KEY_PREFIX as t,backupManifestKey as a,backupObjectKey as s,isBackupManifestEntry as i,isBackupManifestKey as n,normalizeBackupPrefix as p}from"./packem_shared/BACKUP_KEY_PREFIX-DhFUE3VL.mjs";import{toAirbyteMessages as c,toFivetranResponse as E}from"./packem_shared/toAirbyteMessages-DTk8e2f9.mjs";import{composeWorker as R,createLunoraHandler as S,createWorker as x,defineRpcEnvelope as _,resolveLunoraOptions as d,withFrameworkWorker as l}from"./packem_shared/composeWorker-3QukUt7p.mjs";import{createCrossShardRelationCapabilities as y}from"./packem_shared/createCrossShardRelationCapabilities-CQfrCIWR.mjs";import{DEFAULT_REGISTRY_CACHE_TTL_MS as A,SHARD_REGISTRY_DO_NAME as C,createDynamicShardRegistry as L}from"./packem_shared/DEFAULT_REGISTRY_CACHE_TTL_MS-CCDyswsf.mjs";import{LunoraError as T,toErrorResponse as g}from"./packem_shared/LunoraError-ByasbDmd.mjs";import{createKvCursorStore as b,createMemoryCursorStore as H,defineExportSink as I,r2Sink as P,runExportTap as v,sanitizeChange as D,webhookExportSink as F}from"./packem_shared/createKvCursorStore-C24tEuYk.mjs";import{HEALTH_PATH as U,HEALTH_READY_PATH as G,buildHealthRoutes as N,d1Probe as K,durableObjectProbe as B,presenceProbe as Y}from"./packem_shared/HEALTH_PATH-BuLCcWNS.mjs";import{LOG_ARCHIVE_PATH as z,resolveLogArchiveFromEnv as X}from"./packem_shared/LOG_ARCHIVE_PATH-CuHKuDCS.mjs";import{memoizeIdentity as W,memoizeIdentityPerRequest as j}from"./packem_shared/memoizeIdentity-CX3xEPYw.mjs";import{e as Q,a as J}from"./packem_shared/observability-DWlkDJJw.mjs";import{analyticsEngineSink as $,combineSinks as ee,consoleSink as re,otlpSink as oe,pipelineLogSink as te,sentrySink as ae,webhookSink as se}from"./packem_shared/analyticsEngineSink-iIRy11I9.mjs";import{D as ne,a as pe,c as me}from"./packem_shared/pipeline-log-reader-FF1V32O2.mjs";import{createQueryCoordinator as Ee,createStaticShardRegistry as fe,mergeStrategyForAggregate as Re}from"./packem_shared/createQueryCoordinator-BkPfcxUG.mjs";import{applyJurisdiction as xe,resolveShard as _e}from"./packem_shared/applyJurisdiction-Dsm_m5zW.mjs";import{R as le,d as ue,o as ye}from"./packem_shared/rest-cache-5unAzdFN.mjs";import{g as Ae,E as Ce,U as Le,p as Oe,y as Te}from"./packem_shared/rest-routes-BqldHiaH.mjs";import{decorateResponse as he,enforceOrigin as be,handleCorsPreflight as He,resolveSecurity as Ie}from"./packem_shared/decorateResponse-DBIWsRSZ.mjs";import{createShardClient as ve}from"./packem_shared/createShardClient-BYYzDbMc.mjs";import{STORAGE_UPLOAD_MAX_BODY_BYTES as Fe}from"./packem_shared/STORAGE_UPLOAD_MAX_BODY_BYTES-K0uZPIUj.mjs";import{LOG_ARCHIVE_NOT_CONFIGURED as Ue}from"./packem_shared/LOG_ARCHIVE_NOT_CONFIGURED-CDpi4yFD.mjs";import{NOOP_EXECUTION_CONTEXT as Ne}from"./packem_shared/NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{composeIdentityResolvers as Be,routeIdentityResolvers as Ye}from"./packem_shared/composeIdentityResolvers-DwE0Jbww.mjs";const e="0.0.0";export{t as BACKUP_KEY_PREFIX,ne as DEFAULT_LOG_COLUMNS,pe as DEFAULT_LOG_LIMIT,A as DEFAULT_REGISTRY_CACHE_TTL_MS,U as HEALTH_PATH,G as HEALTH_READY_PATH,Ue as LOG_ARCHIVE_NOT_CONFIGURED,z as LOG_ARCHIVE_PATH,T as LunoraError,Ne as NOOP_EXECUTION_CONTEXT,C as SHARD_REGISTRY_DO_NAME,Fe as STORAGE_UPLOAD_MAX_BODY_BYTES,e as VERSION,$ as analyticsEngineSink,xe as applyJurisdiction,le as applyRestCache,Ae as argsFromQuery,a as backupManifestKey,s as backupObjectKey,N as buildHealthRoutes,Ce as buildRestRoutes,ee as combineSinks,Be as composeIdentityResolvers,R as composeWorker,re as consoleSink,y as createCrossShardRelationCapabilities,L as createDynamicShardRegistry,b as createKvCursorStore,S as createLunoraHandler,H as createMemoryCursorStore,me as createPipelineLogReader,Ee as createQueryCoordinator,Le as createRestRateLimit,ve as createShardClient,fe as createStaticShardRegistry,x as createWorker,K as d1Probe,he as decorateResponse,I as defineExportSink,_ as defineRpcEnvelope,B as durableObjectProbe,Q as emitLogEvent,J as emitRpcEvent,be as enforceOrigin,He as handleCorsPreflight,i as isBackupManifestEntry,n as isBackupManifestKey,W as memoizeIdentity,j as memoizeIdentityPerRequest,Re as mergeStrategyForAggregate,p as normalizeBackupPrefix,oe as otlpSink,te as pipelineLogSink,Y as presenceProbe,P as r2Sink,Oe as readShardKey,ue as requestCarriesCredentials,X as resolveLogArchiveFromEnv,d as resolveLunoraOptions,Ie as resolveSecurity,_e as resolveShard,ye as restCacheHeaders,Te as restSurfaceFromRegistry,Ye as routeIdentityResolvers,v as runExportTap,D as sanitizeChange,ae as sentrySink,c as toAirbyteMessages,g as toErrorResponse,E as toFivetranResponse,F as webhookExportSink,se as webhookSink,l as withFrameworkWorker};
1
+ import{BACKUP_KEY_PREFIX as t,backupManifestKey as a,backupObjectKey as s,backupObjectKeyOfManifest as i,isBackupManifestEntry as n,isBackupManifestKey as p,normalizeBackupPrefix as m}from"./packem_shared/BACKUP_KEY_PREFIX-DhFUE3VL.mjs";import{toAirbyteMessages as f,toFivetranResponse as E}from"./packem_shared/toAirbyteMessages-DTk8e2f9.mjs";import{composeWorker as S,createLunoraHandler as x,createWorker as _,defineRpcEnvelope as d,resolveLunoraOptions as l,withFrameworkWorker as u}from"./packem_shared/composeWorker-y5QruLqo.mjs";import{createCrossShardRelationCapabilities as k}from"./packem_shared/createCrossShardRelationCapabilities-CQfrCIWR.mjs";import{DEFAULT_REGISTRY_CACHE_TTL_MS as A,SHARD_REGISTRY_DO_NAME as C,createDynamicShardRegistry as L}from"./packem_shared/DEFAULT_REGISTRY_CACHE_TTL_MS-CCDyswsf.mjs";import{LunoraError as g,toErrorResponse as b}from"./packem_shared/LunoraError-ByasbDmd.mjs";import{createKvCursorStore as H,createMemoryCursorStore as I,defineExportSink as P,r2Sink as v,runExportTap as D,sanitizeChange as F,webhookExportSink as M}from"./packem_shared/createKvCursorStore-C24tEuYk.mjs";import{HEALTH_PATH as G,HEALTH_READY_PATH as K,buildHealthRoutes as N,d1Probe as B,durableObjectProbe as Y,presenceProbe as w}from"./packem_shared/HEALTH_PATH-BuLCcWNS.mjs";import{LOG_ARCHIVE_PATH as X,resolveLogArchiveFromEnv as j}from"./packem_shared/LOG_ARCHIVE_PATH-CuHKuDCS.mjs";import{memoizeIdentity as W,memoizeIdentityPerRequest as q}from"./packem_shared/memoizeIdentity-CX3xEPYw.mjs";import{e as J,a as Z}from"./packem_shared/observability-DWlkDJJw.mjs";import{analyticsEngineSink as ee,combineSinks as re,consoleSink as oe,otlpSink as te,pipelineLogSink as ae,sentrySink as se,webhookSink as ie}from"./packem_shared/analyticsEngineSink-iIRy11I9.mjs";import{D as pe,a as me,c as ce}from"./packem_shared/pipeline-log-reader-FF1V32O2.mjs";import{createQueryCoordinator as Ee,createStaticShardRegistry as Re,mergeStrategyForAggregate as Se}from"./packem_shared/createQueryCoordinator-BkPfcxUG.mjs";import{applyJurisdiction as _e,resolveShard as de}from"./packem_shared/applyJurisdiction-Dsm_m5zW.mjs";import{R as ue,d as ye,o as ke}from"./packem_shared/rest-cache-5unAzdFN.mjs";import{g as Ae,E as Ce,U as Le,p as Te,y as ge}from"./packem_shared/rest-routes-BqldHiaH.mjs";import{decorateResponse as he,enforceOrigin as He,handleCorsPreflight as Ie,resolveSecurity as Pe}from"./packem_shared/decorateResponse-DBIWsRSZ.mjs";import{createShardClient as De}from"./packem_shared/createShardClient-BYYzDbMc.mjs";import{STORAGE_UPLOAD_MAX_BODY_BYTES as Me}from"./packem_shared/STORAGE_UPLOAD_MAX_BODY_BYTES-K0uZPIUj.mjs";import{LOG_ARCHIVE_NOT_CONFIGURED as Ge}from"./packem_shared/LOG_ARCHIVE_NOT_CONFIGURED-CDpi4yFD.mjs";import{NOOP_EXECUTION_CONTEXT as Ne}from"./packem_shared/NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{composeIdentityResolvers as Ye,routeIdentityResolvers as we}from"./packem_shared/composeIdentityResolvers-DwE0Jbww.mjs";const e="0.0.0";export{t as BACKUP_KEY_PREFIX,pe as DEFAULT_LOG_COLUMNS,me as DEFAULT_LOG_LIMIT,A as DEFAULT_REGISTRY_CACHE_TTL_MS,G as HEALTH_PATH,K as HEALTH_READY_PATH,Ge as LOG_ARCHIVE_NOT_CONFIGURED,X as LOG_ARCHIVE_PATH,g as LunoraError,Ne as NOOP_EXECUTION_CONTEXT,C as SHARD_REGISTRY_DO_NAME,Me as STORAGE_UPLOAD_MAX_BODY_BYTES,e as VERSION,ee as analyticsEngineSink,_e as applyJurisdiction,ue as applyRestCache,Ae as argsFromQuery,a as backupManifestKey,s as backupObjectKey,i as backupObjectKeyOfManifest,N as buildHealthRoutes,Ce as buildRestRoutes,re as combineSinks,Ye as composeIdentityResolvers,S as composeWorker,oe as consoleSink,k as createCrossShardRelationCapabilities,L as createDynamicShardRegistry,H as createKvCursorStore,x as createLunoraHandler,I as createMemoryCursorStore,ce as createPipelineLogReader,Ee as createQueryCoordinator,Le as createRestRateLimit,De as createShardClient,Re as createStaticShardRegistry,_ as createWorker,B as d1Probe,he as decorateResponse,P as defineExportSink,d as defineRpcEnvelope,Y as durableObjectProbe,J as emitLogEvent,Z as emitRpcEvent,He as enforceOrigin,Ie as handleCorsPreflight,n as isBackupManifestEntry,p as isBackupManifestKey,W as memoizeIdentity,q as memoizeIdentityPerRequest,Se as mergeStrategyForAggregate,m as normalizeBackupPrefix,te as otlpSink,ae as pipelineLogSink,w as presenceProbe,v as r2Sink,Te as readShardKey,ye as requestCarriesCredentials,j as resolveLogArchiveFromEnv,l as resolveLunoraOptions,Pe as resolveSecurity,de as resolveShard,ke as restCacheHeaders,ge as restSurfaceFromRegistry,we as routeIdentityResolvers,D as runExportTap,F as sanitizeChange,se as sentrySink,f as toAirbyteMessages,b as toErrorResponse,E as toFivetranResponse,M as webhookExportSink,ie as webhookSink,u as withFrameworkWorker};
@@ -0,0 +1,6 @@
1
+ import{isLunoraError as yr,toErrorBody as br}from"@lunora/errors";import{d as At}from"./evict-oldest-C2XU6HBR.mjs";import{NOOP_EXECUTION_CONTEXT as _r}from"./NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{f as Rr,u as Er}from"./identity-header-pdXOyDU4.mjs";import{O as Ae,m as Sr,A as Or,R as Tr,d as Ar,i as kr,s as vr}from"./otlp-resource-B-ByO9qo.mjs";import{h as X,f as be,i as kt,E as Ir,w as vt,e as It,b as Dr}from"./rest-routes-BqldHiaH.mjs";import{LunoraError as i,toErrorResponse as Xe}from"./LunoraError-ByasbDmd.mjs";import{r as x,t as we}from"./method-guard-rzvo19pa.mjs";import{normalizeBackupPrefix as Fe,BACKUP_KEY_PREFIX as Ge,isBackupManifestKey as Pr,backupObjectKeyOfManifest as Dt,backupObjectKey as Ur,backupManifestKey as Nr}from"./BACKUP_KEY_PREFIX-DhFUE3VL.mjs";import{toHex as qr,STORAGE_UPLOAD_MAX_BODY_BYTES as Cr,STORAGE_PATH as $r,buildStorageAdminRoutes as Br}from"./STORAGE_UPLOAD_MAX_BODY_BYTES-K0uZPIUj.mjs";import{runExportTap as xr}from"./createKvCursorStore-C24tEuYk.mjs";import{buildHealthRoutes as jr,durableObjectProbe as Kr,d1Probe as Lr,presenceProbe as Ne}from"./HEALTH_PATH-BuLCcWNS.mjs";import{wrapResolverWithContract as Fr}from"./composeIdentityResolvers-DwE0Jbww.mjs";import{composeIdentityResolvers as rs,routeIdentityResolvers as ns}from"./composeIdentityResolvers-DwE0Jbww.mjs";import{buildLogArchiveAdminRoutes as Gr}from"./LOG_ARCHIVE_PATH-CuHKuDCS.mjs";import{o as Qr,f as Ze,a as ce}from"./observability-DWlkDJJw.mjs";import{resolveShard as ge,applyJurisdiction as et}from"./applyJurisdiction-Dsm_m5zW.mjs";import{resolveSecurity as tt,handleCorsPreflight as Mr,enforceOrigin as zr,decorateResponse as qe,enforceWebSocketOrigin as rt}from"./decorateResponse-DBIWsRSZ.mjs";const Wr=e=>{const t=e??{};if(typeof t.bucket=="function")return t;const r={...t,bucketName:"default"};return r.bucket=()=>r,r},Pt="__lunoraBranch",Jr=e=>typeof e=="object"&&e!==null&&Object.hasOwn(e,Pt),Hr=`may not contain the reserved workflow branch-marker key ("${Pt}")`,Qe=(e,t)=>{const r=Math.max(e.length,t.length);let n=e.length^t.length;for(let o=0;o<r;o+=1){const s=o<e.length?e.charCodeAt(o):0,l=o<t.length?t.charCodeAt(o):0;n|=s^l}return n===0},Me=new TextEncoder,Vr=Array.from({length:32},(e,t)=>t);new RegExp(`[${Vr.map(e=>String.fromCodePoint(e)).join("")}]`,"u");const Yr=e=>{const t=String.fromCodePoint(...e);return btoa(t).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")},Xr=e=>{const t=e.replaceAll("-","+").replaceAll("_","/")+"===".slice((e.length+3)%4),r=atob(t),n=new Uint8Array(r.length);for(let o=0;o<r.length;o+=1)n[o]=r.codePointAt(o)??0;return n},Zr=64,Ce=new Map,Ut=async e=>{const t=Ce.get(e);if(t)return t;At(Ce,Zr);const r=crypto.subtle.importKey("raw",Me.encode(e),{hash:"SHA-256",name:"HMAC"},!1,["sign","verify"]);return Ce.set(e,r),r},Nt=async(e,t)=>{const r=await Ut(e),n=await crypto.subtle.sign("HMAC",r,Me.encode(t));return Yr(new Uint8Array(n))},en=async(e,t,r)=>{const n=await Ut(e);return crypto.subtle.verify("HMAC",n,r,Me.encode(t))},tn="::relay::",rn=(e,t)=>`${e}${tn}${String(t)}`,nn=new Set(["1","enabled","on","true","yes"]),an=new Set(["0","disabled","false","no","off"]),on=(e,t)=>{const r=(e??"").trim().toLowerCase();return nn.has(r)?!0:an.has(r)?!1:t},qt="v1",sn=6e4,cn=async(e,t={})=>{const r=(t.now??Date.now())+(t.ttlMs??sn),n=`${qt}.${String(r)}`,o=await Nt(e,n);return{expiresAtMs:r,token:`${n}.${o}`}},un=async(e,t,r=Date.now())=>{if(e.length===0||t.length===0)return!1;const n=t.split(".");if(n.length!==3)return!1;const[o,s,l]=n;if(o!==qt||l.length===0)return!1;const u=Number(s);if(!Number.isFinite(u)||u<=r)return!1;let f;try{f=Xr(l)}catch{return!1}return en(e,`${o}.${s}`,f)},I="/_lunora/admin/auth",dn={INVITER_REQUIRED:400,ORG_SLUG_INVALID:400,ORG_SLUG_TAKEN:409,PASSWORD_TOO_LONG:400,PASSWORD_TOO_SHORT:400,USER_ALREADY_EXISTS:409,USER_NOT_FOUND:404},P=(e,t)=>{const r=e[t];if(typeof r!="string"||r==="")throw new i(`\`${t}\` is required`,{code:"BAD_REQUEST",status:400});return r},le=(e,t)=>{const r=e(t);if(r===void 0)throw new i(`\`${t}\` query parameter is required`,{code:"BAD_REQUEST",status:400});return r},Ct=e=>{if(typeof e=="string"||Array.isArray(e)&&e.every(t=>typeof t=="string"))return e},te=(e,t)=>typeof e[t]=="string"?e[t]:void 0,$e=(e,t)=>{const r=e[t];return typeof r=="object"&&r!==null&&!Array.isArray(r)?r:void 0},nt=e=>{const t=Ct(e.role);if(t===void 0||typeof t=="string"&&t.trim()==="")throw new i("`role` is required",{code:"BAD_REQUEST",status:400});return t},at=e=>{const t=e.permission;if(typeof t!="object"||t===null||Array.isArray(t))throw new i("`permission` object is required",{code:"BAD_REQUEST",status:400});const r={};for(const[n,o]of Object.entries(t))Array.isArray(o)&&o.every(s=>typeof s=="string")&&(r[n]=o);return r},ln={[`${I}/capabilities`]:{build:()=>({}),http:"GET",method:"capabilities"},[`${I}/users`]:{build:({paging:e,query:t})=>{const r=t("sortDirection");return{...e,filterField:t("filterField"),filterValue:t("filterValue"),search:t("search"),searchField:t("searchField"),sortBy:t("sortBy"),sortDirection:r==="asc"||r==="desc"?r:void 0}},http:"GET",method:"listUsers"},[`${I}/sessions`]:{build:({paging:e,query:t})=>({...e,userId:t("userId")}),http:"GET",method:"listSessions"},[`${I}/accounts`]:{build:({query:e})=>({userId:le(e,"userId")}),http:"GET",method:"listAccounts"},[`${I}/passkeys`]:{build:({query:e})=>({userId:le(e,"userId")}),http:"GET",method:"listPasskeys"},[`${I}/organizations`]:{build:({paging:e})=>({...e}),http:"GET",method:"listOrganizations"},[`${I}/organizations/members`]:{build:({paging:e,query:t})=>({...e,organizationId:le(t,"organizationId")}),http:"GET",method:"listMembers"},[`${I}/organizations/invitations`]:{build:({paging:e,query:t})=>({...e,organizationId:le(t,"organizationId")}),http:"GET",method:"listInvitations"},[`${I}/config`]:{build:()=>({}),http:"GET",method:"config"},[`${I}/organizations/teams`]:{build:({paging:e,query:t})=>({...e,organizationId:le(t,"organizationId")}),http:"GET",method:"listTeams"},[`${I}/organizations/teams/members`]:{build:({paging:e,query:t})=>({...e,teamId:le(t,"teamId")}),http:"GET",method:"listTeamMembers"},[`${I}/organizations/roles`]:{build:({paging:e,query:t})=>({...e,organizationId:le(t,"organizationId")}),http:"GET",method:"listOrgRoles"},[`${I}/users/create`]:{build:({body:e})=>({data:$e(e,"data"),email:P(e,"email"),name:P(e,"name"),password:te(e,"password"),role:Ct(e.role)}),http:"POST",method:"createUser"},[`${I}/users/update`]:{build:({body:e})=>{const{data:t}=e;if(typeof t!="object"||t===null||Array.isArray(t))throw new i("`data` object is required",{code:"BAD_REQUEST",status:400});return{data:t,userId:P(e,"userId")}},http:"POST",method:"updateUser"},[`${I}/users/role`]:{build:({body:e})=>({role:nt(e),userId:P(e,"userId")}),http:"POST",method:"setRole"},[`${I}/users/ban`]:{build:({body:e})=>({expiresInSeconds:typeof e.expiresInSeconds=="number"?e.expiresInSeconds:void 0,reason:te(e,"reason"),userId:P(e,"userId")}),http:"POST",method:"banUser"},[`${I}/users/unban`]:{build:({body:e})=>({userId:P(e,"userId")}),http:"POST",method:"unbanUser"},[`${I}/users/password`]:{build:({body:e})=>({newPassword:P(e,"newPassword"),userId:P(e,"userId")}),http:"POST",method:"setUserPassword",returns:"void"},[`${I}/users/remove`]:{build:({body:e})=>({userId:P(e,"userId")}),http:"POST",method:"removeUser",returns:"void"},[`${I}/users/impersonate`]:{build:({body:e})=>({userId:P(e,"userId")}),http:"POST",method:"impersonateUser"},[`${I}/sessions/revoke`]:{build:({body:e})=>({sessionId:P(e,"sessionId")}),http:"POST",method:"revokeUserSession",returns:"void"},[`${I}/sessions/revoke-all`]:{build:({body:e})=>({userId:P(e,"userId")}),http:"POST",method:"revokeUserSessions",returns:"void"},[`${I}/accounts/unlink`]:{build:({body:e})=>({accountId:P(e,"accountId"),userId:P(e,"userId")}),http:"POST",method:"unlinkAccount",returns:"void"},[`${I}/two-factor/disable`]:{build:({body:e})=>({userId:P(e,"userId")}),http:"POST",method:"disableTwoFactor",returns:"void"},[`${I}/passkeys/delete`]:{build:({body:e})=>({passkeyId:P(e,"passkeyId")}),http:"POST",method:"deletePasskey",returns:"void"},[`${I}/organizations/members/remove`]:{build:({body:e})=>({memberId:P(e,"memberId")}),http:"POST",method:"removeMember",returns:"void"},[`${I}/organizations/invitations/cancel`]:{build:({body:e})=>({invitationId:P(e,"invitationId")}),http:"POST",method:"cancelInvitation",returns:"void"},[`${I}/organizations/create`]:{build:({body:e})=>({logo:te(e,"logo"),metadata:$e(e,"metadata"),name:P(e,"name"),ownerId:te(e,"ownerId"),slug:te(e,"slug")}),http:"POST",method:"createOrganization"},[`${I}/organizations/update`]:{build:({body:e})=>({logo:te(e,"logo"),metadata:$e(e,"metadata"),name:te(e,"name"),organizationId:P(e,"organizationId"),slug:te(e,"slug")}),http:"POST",method:"updateOrganization"},[`${I}/organizations/remove`]:{build:({body:e})=>({organizationId:P(e,"organizationId")}),http:"POST",method:"deleteOrganization",returns:"void"},[`${I}/organizations/members/add`]:{build:({body:e})=>({organizationId:P(e,"organizationId"),role:te(e,"role"),userId:P(e,"userId")}),http:"POST",method:"addMember"},[`${I}/organizations/members/invite`]:{build:({body:e})=>({email:P(e,"email"),inviterId:te(e,"inviterId"),organizationId:P(e,"organizationId"),role:te(e,"role")}),http:"POST",method:"inviteMember"},[`${I}/organizations/members/role`]:{build:({body:e})=>({memberId:P(e,"memberId"),role:nt(e)}),http:"POST",method:"updateMemberRole"},[`${I}/organizations/teams/create`]:{build:({body:e})=>({name:P(e,"name"),organizationId:P(e,"organizationId")}),http:"POST",method:"createTeam"},[`${I}/organizations/teams/update`]:{build:({body:e})=>({name:P(e,"name"),teamId:P(e,"teamId")}),http:"POST",method:"updateTeam"},[`${I}/organizations/teams/remove`]:{build:({body:e})=>({teamId:P(e,"teamId")}),http:"POST",method:"removeTeam",returns:"void"},[`${I}/organizations/teams/members/add`]:{build:({body:e})=>({teamId:P(e,"teamId"),userId:P(e,"userId")}),http:"POST",method:"addTeamMember"},[`${I}/organizations/teams/members/remove`]:{build:({body:e})=>({teamMemberId:P(e,"teamMemberId")}),http:"POST",method:"removeTeamMember",returns:"void"},[`${I}/organizations/roles/create`]:{build:({body:e})=>({organizationId:P(e,"organizationId"),permission:at(e),role:P(e,"role")}),http:"POST",method:"createOrgRole"},[`${I}/organizations/roles/update`]:{build:({body:e})=>({permission:at(e),roleId:P(e,"roleId")}),http:"POST",method:"updateOrgRole"},[`${I}/organizations/roles/remove`]:{build:({body:e})=>({roleId:P(e,"roleId")}),http:"POST",method:"deleteOrgRole",returns:"void"}},hn=e=>{const t=async o=>{try{return await o()}catch(s){if(s instanceof i)throw s;const l=s,u=typeof l.code=="string"?l.code:"AUTH_ADMIN_ERROR";throw console.error("[lunora] auth admin operation failed:",s),new i("auth admin operation failed",{code:u,status:dn[u]??500})}},r=async(o,s)=>{if(e.assertAdmin(o),o.method!==s.http)throw new i(`Auth admin endpoint requires ${s.http}`,{code:"METHOD_NOT_ALLOWED",status:405});const l=e.getAuthAdmin();if(l===void 0)throw new i("auth endpoints require an `authAdmin` on the worker",{code:"AUTH_NOT_CONFIGURED",status:400});const u=l[s.method];if(u===void 0)throw new i(`auth admin does not support \`${s.method}\``,{code:"AUTH_OP_NOT_SUPPORTED",status:400});const f=new URL(o.url),y={body:s.http==="POST"?await e.readJsonBody(o):{},paging:e.parsePaging(o),query:_=>e.queryParameter(f,_)},E=s.build(y),w=await t(()=>u(E));return Response.json(s.returns==="void"?{ok:!0}:w,{headers:{"content-type":"application/json"},status:200})},n={};for(const[o,s]of Object.entries(ln))n[o]=l=>r(l,s);return n},pn="__lunora_admin__:getAuthAuditLog",ot=e=>typeof e=="string"&&e!==""?e:void 0,st=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0,fn=e=>async(t,r)=>{e.assertAdmin(t);const n=e.getReader();if(n===void 0)throw new i("the auth/security audit endpoint requires an `authAuditReader` on the worker",{code:"AUTH_AUDIT_NOT_CONFIGURED",status:400});const o=ot(r.actorId),s=ot(r.event),l=st(r.sinceSeq),u=st(r.limit),f={...o===void 0?{}:{actorId:o},...s===void 0?{}:{event:s},...l===void 0?{}:{sinceSeq:l},...u===void 0?{}:{limit:u}};let y;try{y=await n.read(f)}catch(w){throw w instanceof i?w:(console.error("[lunora] auth audit read failed:",w),new i("auth audit read failed",{code:"AUTH_AUDIT_READ_FAILED",status:500}))}const E={entries:y};return Response.json(E,{headers:{"content-type":"application/json"},status:200})},mn=(e,t)=>{const r=[],n=[];if(t&&t.length>0)for(const o of t)e.resolveTableSharding?.(o)?.mode.kind==="global"?n.push(o):r.push(o);return{globalTables:n,shardLocalTables:r}},wn=async(e,t,r,n,o,s)=>{if(r!==void 0&&n.length===0)return;const l=await e.orchestrateExport(s,{args:{tables:n},headers:t,tables:n});for(const u of l.shards)if(!u.error)for(const f of u.rows??[])o(f)},$t=async(e,t,r,n,o,s)=>{const{globalTables:l,shardLocalTables:u}=mn(e,n);await wn(t,r,n,u,o,s);const f=e.exportGlobals;if((n===void 0||l.length>0)&&f)for await(const y of f({tables:l}))o(y)},gn=new TextEncoder,yn=1e3,Bt=10,bn=200,it=8,xt="lunoraBackupCron",ct=24*1048576,ut=e=>{const t=e.slice(0,Bt).map(n=>Dt(n)),r=e.length-t.length;return`${t.join(", ")}${r>0?` (+${String(r)} more)`:""}`},_n=(e,t)=>{const r=new Uint8Array(new ArrayBuffer(t));let n=0;for(const o of e)r.set(o,n),n+=o.byteLength;return r},ze=async(e,t,r,n)=>{if(r===void 0||!Number.isInteger(r)||r<=0)return{eligible:0,stale:[]};const o=[];let s;for(let l=0;l<yn;l+=1){const u=await e.list({cursor:s,include:["customMetadata"],prefix:t});for(const f of u.objects)Pr(f.key)&&f.customMetadata?.[xt]===n&&o.push(f.key);if(!u.truncated||u.cursor===void 0)break;s=u.cursor}return{eligible:o.length,stale:o.toSorted((l,u)=>u.localeCompare(l)).slice(r)}},Rn=async(e,t,r,n,o)=>{const{stale:s}=await ze(e,t,r,n),l=new Set(o),u=s.filter(h=>l.has(h)),f=u.slice(0,bn),y=s.length-f.length,E=o.length-u.length;if(f.length===0)return{deleted:[],failed:[],ignored:E,remaining:y};const w=[],_=[];for(let h=0;h<f.length;h+=it){const S=await Promise.allSettled(f.slice(h,h+it).map(async R=>(await e.delete(Dt(R)),await e.delete(R),R)));for(const[R,T]of S.entries())T.status==="fulfilled"?w.push(T.value):_.push(f[h+R])}return w.length>0&&console.info(`[lunora] backup prune kept the newest ${String(r)} and deleted ${String(w.length)}: ${ut(w)}`),_.length>0&&console.warn(`[lunora] backup prune failed to remove ${String(_.length)}: ${ut(_)}`),{deleted:w,failed:_,ignored:E,remaining:y}},En=async e=>{const t=e.backupStore;if(!t)throw new i("backup retention preview requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});const r=Fe(e.backupPrefix??Ge),n=e.backupCron,{eligible:o,stale:s}=n===void 0?{eligible:0,stale:[]}:await ze(t,r,e.backupRetain,n);return{cron:n,eligible:o,keep:e.backupRetain??0,prefix:r,wouldDelete:s}},Sn=async(e,t,r,n)=>{const o=e.backupStore,s=e.queryCoordinator;if(!o)throw new i("scheduled backup requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});if(!s)throw new i("scheduled backup requires a `queryCoordinator` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});if(!r||r.length===0)throw new i("scheduled backup requires an `adminToken` (or `env.LUNORA_ADMIN_TOKEN`) to authenticate the per-shard export gate",{code:"BACKUP_NOT_CONFIGURED",status:500});const l={authorization:`Bearer ${r}`,"content-type":"application/json"},u=e.backupTables;let f=0,y=0,E=[];await $t(e,s,l,u,A=>{const U=gn.encode(`${JSON.stringify(A)}
2
+ `);if(f+=1,y+=U.byteLength,y>ct)throw new i(`scheduled backup reached ${String(y)} bytes of NDJSON, past the ${String(ct)}-byte limit for a snapshot assembled inside a Worker — nothing was written. Narrow it with \`backupTables\`, or take this snapshot off-platform with \`lunora backup create --bucket\`.`,{code:"BACKUP_TOO_LARGE",status:507});E.push(U)},t);const w=Fe(e.backupPrefix??Ge),_=new Date(n.scheduledTime).toISOString(),h=Ur(w,_),S=_n(E,y);E=[];const R=qr(await crypto.subtle.digest("SHA-256",S));await o.put(h,S,{httpMetadata:{contentType:"application/x-ndjson"},sha256:R});const T={bytes:y,createdAt:_,cron:n.cron,file:h,id:_,rows:f,scheduledTime:n.scheduledTime,sha256:R,...u?{tables:u.join(",")}:{}};await o.put(Nr(h),`${JSON.stringify(T,void 0,2)}
3
+ `,{customMetadata:{[xt]:n.cron},httpMetadata:{contentType:"application/json"}});try{const{stale:A}=await ze(o,w,e.backupRetain,n.cron);if(A.length>0){const U=A.slice(0,Bt),v=A.length-U.length;console.info(`[lunora] backup retention: ${String(A.length)} snapshot(s) past the newest ${String(e.backupRetain)} — run \`lunora backup prune\` to remove them: ${U.join(", ")}${v>0?` (+${String(v)} more)`:""}`)}}catch(A){console.warn(`[lunora] backup ${h} was written, but the retention report failed:`,A)}},On=async(e,t)=>{const r=e.backupStore;if(!r)throw new i("backup prune requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});const n=e.backupCron,o=e.backupRetain;if(n===void 0||o===void 0||!Number.isInteger(o)||o<=0)throw new i("backup prune needs a retention window: set `backupRetain` (and `backupCron`, which decides whose snapshots retention owns) on the worker. Without one there is nothing past the window to remove.",{code:"BACKUP_RETENTION_NOT_CONFIGURED",status:400});return Rn(r,Fe(e.backupPrefix??Ge),o,n,t)},Tn="/_lunora/admin/backup/retention",An="/_lunora/admin/backup/prune",kn=e=>{const{options:t,readJsonBody:r,requireAdminOption:n}=e,o=(u,f)=>{n(u,t.backupStore,{code:"BACKUP_NOT_CONFIGURED",message:`backup ${f} requires a \`backupStore\` on the worker`})},s=async u=>(x(u,"GET","Backup-retention"),o(u,"retention preview"),Response.json(await En(t),{headers:{"cache-control":"no-store"}})),l=async u=>{x(u,"POST","Backup-prune"),o(u,"prune");const{confirm:f}=await r(u);if(!Array.isArray(f)||f.some(y=>typeof y!="string"))throw new i("backup prune requires a `confirm` array of the sidecar keys to remove — read them from `GET /_lunora/admin/backup/retention` and pass back the ones you mean to delete",{code:"BAD_REQUEST",status:400});return Response.json(await On(t,f),{headers:{"cache-control":"no-store"}})};return{[An]:l,[Tn]:s}},dt=500,vn=(e,t,r)=>{if(typeof e!="object"||e===null||Array.isArray(e))throw new i("each batch call must be an object",{code:"BAD_REQUEST",status:400});const n=e;if(typeof n.functionPath!="string")throw new i("each batch call needs a string `functionPath`",{code:"BAD_REQUEST",status:400});if(n.functionPath.startsWith("__lunora_relation__:")||n.functionPath.startsWith("__lunora_admin__"))throw new i("reserved function path cannot be batched",{code:"FORBIDDEN",status:403});if(n.args!==void 0&&(typeof n.args!="object"||n.args===null||Array.isArray(n.args)))throw new i("each batch call `args` must be an object",{code:"BAD_REQUEST",status:400});return{entry:{args:n.args===void 0?{}:n.args,clientId:typeof n.clientId=="string"?n.clientId:void 0,clientSeq:typeof n.clientSeq=="number"?n.clientSeq:void 0,functionPath:n.functionPath,id:typeof n.id=="number"?n.id:t,mutationId:typeof n.mutationId=="string"?n.mutationId:void 0},shardKey:typeof n.shardKey=="string"?n.shardKey:r}},In=(e,t)=>{if(e.length>dt)throw new i(`RPC batch exceeds the ${String(dt)}-call limit`,{code:"BAD_REQUEST",status:400});const r=new Map;for(const[n,o]of e.entries()){const{entry:s,shardKey:l}=vn(o,n,t),u=r.get(l)??[];u.push(s),r.set(l,u)}return r},Dn=new TextEncoder,Pn=e=>{const t=JSON.stringify(e),r=Dn.encode(t);let n="";for(const o of r)n+=String.fromCodePoint(o);return btoa(n).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")},Un=e=>{const t={g:0,s:{},v:1};if(typeof e!="string"||e.length===0)return t;try{const r=atob(e.replaceAll("-","+").replaceAll("_","/")),n=new Uint8Array(r.length);for(let u=0;u<r.length;u+=1)n[u]=r.codePointAt(u)??0;const o=JSON.parse(new TextDecoder().decode(n)),s=o.s&&typeof o.s=="object"?o.s:{},l={};for(const[u,f]of Object.entries(s))typeof f=="number"&&Number.isFinite(f)&&(l[u]=f);return{g:typeof o.g=="number"&&Number.isFinite(o.g)?o.g:0,s:l,v:1}}catch{return t}},Nn=e=>{const t=typeof e.table=="string"?e.table:"",r=typeof e.op=="string"?e.op:"",n=r==="delete"||r==="insert"||r==="update"?r:"upsert",o=typeof e.id=="string"?e.id:void 0;return{doc:(e.doc&&typeof e.doc=="object"?e.doc:void 0)??(o===void 0?{}:{_id:o}),op:n,table:t}},lt=(e,t,r)=>{for(const n of t)e.push(Nn(n));return r!==void 0&&t.length>=r},qn="/_lunora/admin/export",Cn="/_lunora/admin/import",$n="/_lunora/admin/sync",Bn="/_lunora/admin/connector/sync",xn="/_lunora/admin/apply",jn="/_lunora/admin/export-tap/run",Kn=new TextEncoder,Ln=async e=>{const t=await be(e,"Export")??{};if(t.tables===void 0)return{tables:void 0};if(!Array.isArray(t.tables))throw new i("Export `tables` must be a string array",{code:"BAD_REQUEST",status:400});const r=[];for(const n of t.tables){if(typeof n!="string"||n.length===0)throw new i("Export `tables` entries must be non-empty strings",{code:"BAD_REQUEST",status:400});r.push(n)}return{tables:r}},Be=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):void 0,Fn=e=>{const{applyGlobals:t,exportCursorStore:r,exportSinks:n,knownTables:o,queryCoordinator:s,assertAdmin:l,requireAdminOption:u,resolveForwardContext:f,shardDO:y,streamExportRows:E,streamingImport:w,syncGlobals:_}=e,h=async(v,L)=>{const j=we(v,["POST"]);if(j)return j;const V=u(v,s,{code:"BAD_REQUEST",message:"Export endpoint requires a `queryCoordinator` on the worker"}),N=await Ln(v),{headers:G}=await f(v,L),Q=new ReadableStream({async pull($){const K=Y=>{$.enqueue(Kn.encode(`${JSON.stringify(Y)}
4
+ `))};try{await E(V,G,N.tables,K),$.close()}catch(Y){$.error(Y)}}});return new Response(Q,{headers:{"content-type":"application/x-ndjson"},status:200})},S=async(v,L)=>{const j=we(v,["POST"]);if(j)return j;const V=u(v,s,{code:"BAD_REQUEST",message:"Sync endpoint requires a `queryCoordinator` on the worker"}),N=await X(v),G=typeof N.cursors=="object"&&N.cursors!==null?N.cursors:{},Q=typeof N.limit=="number"?N.limit:void 0,$=typeof N.globalCursor=="number"?N.globalCursor:0,K=Be(N.tables),{headers:Y}=await f(v,L),J=K??o(),ne=await V.orchestrateCdcSync(y,{cursors:G,headers:Y,limit:Q,tables:J}),he=_?await _({limit:Q,sinceSeq:$}):void 0;return Response.json({global:he,shards:ne.shards},{status:200})},R=async(v,L)=>{const j=we(v,["POST"]);if(j)return j;const V=u(v,s,{code:"BAD_REQUEST",message:"Connector sync endpoint requires a `queryCoordinator` on the worker"}),N=await X(v),G=Un(N.cursor),Q=typeof N.limit=="number"&&N.limit>0?N.limit:void 0,$=Be(N.tables),{headers:K}=await f(v,L),Y=$??o(),J=await V.orchestrateCdcSync(y,{cursors:G.s,headers:K,limit:Q,tables:Y}),ne=[],he={...G.s};let ae=!1;for(const se of J.shards)ae=lt(ne,se.changes??[],Q)||ae,he[se.shardKey]=se.cursor;let pe=G.g;if(_){const se=await _({limit:Q,sinceSeq:G.g});ae=lt(ne,se.changes,Q)||ae,pe=se.cursor}const _e=Pn({g:pe,s:he,v:1}),ke={changes:ne,hasMore:ae,nextCursor:_e};return Response.json(ke,{status:200})},T=async(v,L)=>{const j=we(v,["POST"]);if(j)return j;const V=u(v,s,{code:"BAD_REQUEST",message:"Apply endpoint requires a `queryCoordinator` on the worker"}),N=await X(v),G=(Array.isArray(N.batches)?N.batches:[]).map(J=>J).filter(J=>J!==null&&typeof J=="object"&&typeof J.shardKey=="string"&&Array.isArray(J.changes)),Q=Array.isArray(N.globalChanges)?N.globalChanges:[],{headers:$}=await f(v,L),K=await V.orchestrateApplyCdc(y,{batches:G,headers:$}),Y=Q.length>0&&t?await t({changes:Q}):0;return Response.json({applied:K.applied+Y,failed:K.failed,ok:K.ok},{status:200})},A=async(v,L)=>{const j=we(v,["POST"]);if(j)return j;l(v);const{headers:V}=await f(v,L),N=await w(v,V);return Response.json(N,{headers:{"content-type":"application/json"},status:200})},U=async(v,L)=>{const j=we(v,["POST"]);if(j)return j;const V=u(v,s,{code:"BAD_REQUEST",message:"Export-tap endpoint requires a `queryCoordinator` on the worker"});if(n===void 0||Object.keys(n).length===0||r===void 0)throw new i("Export-tap endpoint requires `exportSinks` + `exportCursorStore` on the worker",{code:"EXPORT_TAP_NOT_CONFIGURED",status:400});const N=await X(v),G=typeof N.sink=="string"?N.sink:void 0,Q=typeof N.limit=="number"&&N.limit>0?N.limit:void 0,$=Be(N.tables);if(G===void 0)throw new i("Export-tap `sink` must name a configured sink",{code:"BAD_REQUEST",status:400});const K=n[G];if(K===void 0)throw new i(`Export-tap sink "${G}" is not configured`,{code:"NOT_FOUND",status:404});const{headers:Y}=await f(v,L),J=$??o(),ne=await xr({coordinator:V,cursorStore:r,headers:Y,limit:Q,shardDO:y,sink:K,tables:J});return Response.json(ne,{headers:{"content-type":"application/json"},status:200})};return{[xn]:T,[Bn]:R,[qn]:h,[jn]:U,[Cn]:A,[$n]:S}},Gn=(e,t)=>{let r;try{r=JSON.parse(e)}catch{return{error:{code:"BAD_ROW",line:t,message:"line is not valid JSON",table:""},ok:!1}}if(!r||typeof r!="object"||Array.isArray(r))return{error:{code:"BAD_ROW",line:t,message:"row must be a JSON object",table:""},ok:!1};const n=r;return typeof n.table!="string"||n.table.length===0?{error:{code:"BAD_ROW",line:t,message:"row is missing `table`",table:""},ok:!1}:!n.doc||typeof n.doc!="object"||Array.isArray(n.doc)?{error:{code:"BAD_ROW",line:t,message:"row is missing or malformed `doc`",table:n.table},ok:!1}:{doc:n.doc,ok:!0,table:n.table}},Qn=(e,t,r,n,o)=>{if(r?.mode.kind==="shardBy"&&typeof r.mode.field=="string"){const s=e[r.mode.field];return s==null?{error:{code:"BAD_ROW",line:o,message:`row missing shard field "${r.mode.field}" for table "${t}"`,table:t},ok:!1}:{ok:!0,shardKey:typeof s=="string"?s:JSON.stringify(s)}}return{ok:!0,shardKey:n}},Mn=async(e,t,r)=>{if(!e.body)throw new i("Import endpoint requires a request body",{code:"BAD_REQUEST",status:400});const n=[],o=[],s=new Map;let l=0,u=0;const f=e.body.getReader(),y=new TextDecoder;let E="",w=0;const _=h=>{u+=1;const S=h.trim();if(S.length===0)return;l+=1;const R=Gn(S,u);if(!R.ok){n.push(R.error);return}const{doc:T,table:A}=R,U=t.resolveTableSharding?.(A);if(U?.mode.kind==="global"){o.push({doc:T,line:u,table:A});return}const v=Qn(T,A,U,r,u);if(!v.ok){n.push(v.error);return}const L=s.get(v.shardKey);L?L.rows.push({doc:T,table:A}):s.set(v.shardKey,{rows:[{doc:T,table:A}],shardKey:v.shardKey,startLine:u})};for(;;){const{done:h,value:S}=await f.read();if(h)break;if(S&&(w+=S.byteLength,w>kt))throw await f.cancel().catch(()=>{}),new i("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});E+=y.decode(S,{stream:!0});let R=E.indexOf(`
5
+ `);for(;R!==-1;){const T=E.slice(0,R);E=E.slice(R+1),_(T),R=E.indexOf(`
6
+ `)}}return E.length>0&&_(E),{errors:n,globalRows:o,perShard:s,received:l}},ht=(e,t)=>{for(const[r,n]of Object.entries(t.inserted))e.inserted[r]=(e.inserted[r]??0)+n;for(const r of t.errors)e.errors.push({...r});e.conflicts+=t.conflicts},zn=async(e,t,r,n)=>{const o=t.defaultShardKey??"__root__",{errors:s,globalRows:l,perShard:u,received:f}=await Mn(e,t,o),y={conflicts:0,errors:s,inserted:{}},E=[];if(t.resolveTableSharding===void 0&&u.size>0&&E.push("no `resolveTableSharding` is configured, so every row was routed to the default shard and no row could be recognised as `.global()` — correct for a single-shard app, silent misplacement for a sharded one"),u.size>0){const w=t.queryCoordinator;if(!w)throw new i("Import endpoint requires a `queryCoordinator` on the worker",{code:"BAD_REQUEST",status:400});const _=await w.orchestrateImport(n,{batches:[...u.values()],headers:r});ht(y,_)}if(l.length>0)if(t.importGlobals){const w=l[0]?.line??1,_=await t.importGlobals({rows:l,startLine:w});ht(y,_)}else for(const w of l)y.errors.push({code:"GLOBAL_NOT_CONFIGURED",line:w.line,message:`row targets global table "${w.table}" but no \`importGlobals\` is configured`,table:w.table});return{conflicts:y.conflicts,errors:y.errors,inserted:y.inserted,received:f,...E.length>0?{warnings:E}:{}}},xe=e=>typeof e=="object"&&e!==null?e:{},je=e=>typeof e.kind=="string"?e.kind:"unknown",Wn=(e,t)=>{let r=xe(t),n=!1;je(r)==="optional"&&(n=!0,r=xe(r._meta?.inner));const o=je(r),s=r._meta??{},l={kind:o,name:e,optional:n};if(o==="id"&&typeof s.tableName=="string"&&(l.table=s.tableName),o==="array"){const u=je(xe(s.inner));u!=="unknown"&&(l.element=u)}return l},Jn=e=>typeof e!="object"||e===null?[]:Object.entries(e).map(([t,r])=>Wn(t,r)).toSorted((t,r)=>t.name.localeCompare(r.name)),Hn="/_lunora/admin/functions",Vn="/_lunora/admin/cron-jobs",Yn="/_lunora/admin/openapi",Xn="/_lunora/admin/openrpc",Zn="/_lunora/admin/global/tables",ea="/_lunora/admin/global/table",ta="/_lunora/admin/global/facet",pt=e=>{if(e===void 0||e==="")return;let t;try{t=JSON.parse(e)}catch{return}if(!Array.isArray(t))return;const r=t.flatMap(n=>{if(typeof n!="object"||n===null||typeof n.column!="string")return[];const{column:o,value:s}=n;return[{column:o,value:s}]});return r.length===0?void 0:r},ra=Object.freeze({info:{description:'No OpenAPI spec is configured on this worker. Run `lunora codegen`, then wire the generated module to `createWorker`: `import { openApiSpec } from "./lunora/_generated/openapi"`.',title:"Lunora API",version:"0.0.0"},openapi:"3.1.0",paths:{}}),na=Object.freeze({info:{description:'No OpenRPC spec is configured on this worker. Run `lunora codegen --api-spec openrpc` (or `both`), then wire the generated module to `createWorker`: `import { openRpcSpec } from "./lunora/_generated/openrpc"`.',title:"Lunora RPC",version:"0.0.0"},methods:[],openrpc:"1.3.2"}),aa=e=>{const{assertAdmin:t,options:r,parsePaging:n,queryParameter:o,requireAdminOption:s}=e,l=h=>{x(h,"GET","Functions");const S=s(h,r.functions,{code:"FUNCTIONS_NOT_CONFIGURED",message:"functions endpoint requires a `functions` registry on the worker"}),R=Object.entries(S).flatMap(([T,A])=>A.visibility==="internal"||A.kind==="stream"?[]:[{args:Jn(A.args),kind:A.kind,path:T}]).toSorted((T,A)=>T.path.localeCompare(A.path));return Response.json({functions:R},{headers:{"content-type":"application/json"},status:200})},u=h=>{x(h,"GET","Cron-jobs");const S=s(h,r.cronJobs,{code:"CRON_JOBS_NOT_CONFIGURED",message:"cron-jobs endpoint requires a `cronJobs` map on the worker"}),R=Object.entries(S).flatMap(([T,A])=>A.map(U=>({args:U.args,cron:T,functionPath:U.functionPath,name:U.name,shardKey:U.shardKey,workflow:U.workflow}))).toSorted((T,A)=>T.name.localeCompare(A.name));return Response.json({jobs:R},{headers:{"content-type":"application/json"},status:200})},f=h=>(x(h,"GET","OpenAPI"),t(h),Response.json(r.openApiSpec??ra,{headers:{"content-type":"application/json"},status:200})),y=h=>(x(h,"GET","OpenRPC"),t(h),Response.json(r.openRpcSpec??na,{headers:{"content-type":"application/json"},status:200})),E=async h=>{x(h,"GET","Global-tables");const S=s(h,r.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"});return Response.json(await S.listTables(),{headers:{"content-type":"application/json"},status:200})},w=async h=>{x(h,"GET","Global-table");const S=s(h,r.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),R=new URL(h.url),T=o(R,"table");if(T===void 0)throw new i("Global-table endpoint requires a `table` query param",{code:"BAD_REQUEST",status:400});const A=await S.readTablePage({...n(h),filters:pt(o(R,"filters")),table:T});return Response.json(A,{headers:{"content-type":"application/json"},status:200})},_=async h=>{x(h,"GET","Global-facet");const S=s(h,r.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),R=new URL(h.url),T=o(R,"table"),A=o(R,"column");if(T===void 0||A===void 0)throw new i("Global-facet endpoint requires `table` and `column` query params",{code:"BAD_REQUEST",status:400});const U=o(R,"limit"),v=U===void 0?void 0:Number(U),L=await S.facetColumn({column:A,filters:pt(o(R,"filters")),limit:v!==void 0&&Number.isFinite(v)?v:void 0,table:T});return Response.json(L,{headers:{"content-type":"application/json"},status:200})};return{[Vn]:u,[Hn]:l,[ta]:_,[ea]:w,[Zn]:E,[Yn]:f,[Xn]:y}},oa="/_lunora/admin/kv/namespaces",sa="/_lunora/admin/kv/keys",jt="/_lunora/admin/kv/value",Kt=32*1048576,ft=60,ia=e=>{const{readJsonBody:t,requireAdminOption:r}=e,n=w=>r(w,e.kvIntrospector,{code:"KV_NOT_CONFIGURED",message:"KV endpoints require a `kvIntrospector` on the worker"}),o=w=>Response.json(w,{headers:{"content-type":"application/json"},status:200}),s=(w,_)=>{const h=new URL(w.url),S=h.searchParams.get("namespace")??"",R=h.searchParams.get("key")??"";if(S==="")throw new i(`KV-value ${_} request requires a \`namespace\` query parameter`,{code:"BAD_REQUEST",status:400});if(R==="")throw new i(`KV-value ${_} request requires a \`key\` query parameter`,{code:"BAD_REQUEST",status:400});return{key:R,namespace:S}},l=async(w,_)=>{if(!(await w.listNamespaces()).some(h=>h.binding===_))throw new i(`Unknown KV namespace binding \`${_}\``,{code:"NOT_FOUND",status:404})},u=async w=>(x(w,"GET","KV-namespaces"),o({namespaces:await n(w).listNamespaces()})),f=async w=>{x(w,"GET","KV-keys");const _=n(w),h=new URL(w.url),S=h.searchParams.get("namespace")??"";if(S==="")throw new i("KV-keys request requires a `namespace` query parameter",{code:"BAD_REQUEST",status:400});const R=h.searchParams.get("prefix")??void 0,T=h.searchParams.get("cursor")??void 0,A=h.searchParams.get("limit"),U=A===null?void 0:Number.parseInt(A,10);if(U!==void 0&&(!Number.isInteger(U)||U<1))throw new i("KV-keys `limit` must be a positive integer",{code:"BAD_REQUEST",status:400});const v=U===void 0?void 0:Math.min(U,1e3);return await l(_,S),o(await _.listKeys({cursor:T,limit:v,namespace:S,prefix:R}))},y={DELETE:async w=>{const _=n(w),h=s(w,"DELETE");return await l(_,h.namespace),await _.deleteKey(h),o({deleted:!0})},GET:async w=>{const _=n(w),h=s(w,"GET");return await l(_,h.namespace),o(await _.getValue(h))},PUT:async w=>{const _=n(w),h=await t(w,Kt);if(typeof h.namespace!="string"||h.namespace==="")throw new i("KV-value PUT request requires a `namespace` string",{code:"BAD_REQUEST",status:400});if(typeof h.key!="string"||h.key==="")throw new i("KV-value PUT request requires a `key` string",{code:"BAD_REQUEST",status:400});if(typeof h.value!="string")throw new i("KV-value PUT request requires a `value` string",{code:"BAD_REQUEST",status:400});if(h.expirationTtl!==void 0&&(typeof h.expirationTtl!="number"||!Number.isInteger(h.expirationTtl)||h.expirationTtl<ft))throw new i("KV-value PUT `expirationTtl` must be an integer ≥ 60",{code:"BAD_REQUEST",status:400});const S=Math.floor(Date.now()/1e3)+ft;if(h.expiration!==void 0&&(typeof h.expiration!="number"||!Number.isInteger(h.expiration)||h.expiration<S))throw new i("KV-value PUT `expiration` must be a Unix-seconds timestamp at least 60 seconds in the future",{code:"BAD_REQUEST",status:400});return await l(_,h.namespace),await _.putValue({expiration:h.expiration,expirationTtl:h.expirationTtl,key:h.key,metadata:h.metadata,namespace:h.namespace,value:h.value}),o({ok:!0})}},E=w=>{const _=y[w.method];if(!_)throw new i("KV-value endpoint requires GET, PUT, or DELETE",{code:"METHOD_NOT_ALLOWED",status:405});return _(w)};return{[oa]:u,[sa]:f,[jt]:E}},ca="/_lunora/migrate",ua="/_lunora/admin/pitr",da="/_lunora/admin/rank",la="/_lunora/admin/rankpage",ha="/_lunora/admin/shard-traffic",pa=new Set(["__lunora_admin__:migrationStatus","__lunora_admin__:runMigration"]),fa=new Set(["__lunora_admin__:getPitrBookmark","__lunora_admin__:pitrRestore"]),ma=async e=>{const t=await be(e,"Migration")??{};if(typeof t.table!="string"||t.table.length===0)throw new i("Migration request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof t.functionPath!="string"||!pa.has(t.functionPath))throw new i("Migration request `functionPath` must be a migration admin op",{code:"BAD_REQUEST",status:400});return{args:t.args??{},functionPath:t.functionPath,table:t.table}},wa=async e=>{const t=await be(e,"Rank")??{};if(typeof t.table!="string"||t.table.length===0)throw new i("Rank request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof t.index!="string"||t.index.length===0)throw new i("Rank request is missing `index`",{code:"BAD_REQUEST",status:400});if(typeof t.partitionKey!="string")throw new i("Rank request `partitionKey` must be a string",{code:"BAD_REQUEST",status:400});if(typeof t.rowId!="string"||t.rowId.length===0)throw new i("Rank request is missing `rowId`",{code:"BAD_REQUEST",status:400});if(!Array.isArray(t.sortValues))throw new i("Rank request `sortValues` must be an array",{code:"BAD_REQUEST",status:400});return{index:t.index,partitionKey:t.partitionKey,rowId:t.rowId,sortValues:t.sortValues,table:t.table}},ga=e=>{if(e!==void 0){if(!Array.isArray(e)||e.some(t=>t!=="asc"&&t!=="desc"))throw new i('Rank page request `directions` must be an array of "asc"|"desc"',{code:"BAD_REQUEST",status:400});return e}},ya=e=>{if(typeof e.table!="string"||e.table.length===0)throw new i("Rank page request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof e.index!="string"||e.index.length===0)throw new i("Rank page request is missing `index`",{code:"BAD_REQUEST",status:400});if(e.partitionKey!==void 0&&typeof e.partitionKey!="string")throw new i("Rank page request `partitionKey` must be a string",{code:"BAD_REQUEST",status:400});if(e.take!==void 0&&(typeof e.take!="number"||!Number.isFinite(e.take)))throw new i("Rank page request `take` must be a number",{code:"BAD_REQUEST",status:400});if(e.cursor!==void 0&&e.cursor!==null&&typeof e.cursor!="string")throw new i("Rank page request `cursor` must be a string or null",{code:"BAD_REQUEST",status:400})},ba=async e=>{const t=await be(e,"Rank page")??{};ya(t);const r=ga(t.directions);return{cursor:typeof t.cursor=="string"?t.cursor:null,directions:r,index:t.index,partitionKey:typeof t.partitionKey=="string"?t.partitionKey:void 0,table:t.table,take:typeof t.take=="number"?t.take:void 0}},_a=async e=>{const t=await be(e,"Shard-traffic")??{};if(typeof t.table!="string"||t.table.length===0)throw new i("Shard-traffic request is missing `table`",{code:"BAD_REQUEST",status:400});return{table:t.table}},Ra=async e=>{const t=await X(e);if(typeof t.functionPath!="string"||!fa.has(t.functionPath))throw new i("PITR request `functionPath` must be a PITR admin op",{code:"BAD_REQUEST",status:400});if(t.shardKey!==void 0&&typeof t.shardKey!="string")throw new i("PITR `shardKey` must be a string",{code:"BAD_REQUEST",status:400});return{args:t.args??{},functionPath:t.functionPath,shardKey:t.shardKey}},Ea=e=>{const{defaultShard:t,forwardToShard:r,isAdmin:n,queryCoordinator:o,resolveForwardContext:s,shardDO:l}=e,u=(h,S)=>{if(h.method!=="POST")throw new i(`${S} endpoint requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});if(!n(h))throw new i("Admin auth required",{code:"FORBIDDEN",status:403});if(!o)throw new i(`${S} endpoint requires a \`queryCoordinator\` on the worker`,{code:"BAD_REQUEST",status:400});return o},f=async(h,S)=>{const R=u(h,"Migration"),T=await ma(h),{headers:A}=await s(h,S),U=await R.orchestrateMigration(l,{args:T.args,functionPath:T.functionPath,headers:A,table:T.table});return Response.json(U,{headers:{"content-type":"application/json"},status:200})},y=async(h,S)=>{const R=u(h,"Rank"),T=await wa(h),{headers:A}=await s(h,S),U=await R.orchestrateRank(l,{headers:A,index:T.index,partitionKey:T.partitionKey,rowId:T.rowId,sortValues:T.sortValues,table:T.table});return Response.json(U,{headers:{"content-type":"application/json"},status:200})},E=async(h,S)=>{const R=u(h,"Rank page"),T=await ba(h),{headers:A}=await s(h,S),U=await R.orchestrateRankPage(l,{...T,headers:A});return Response.json(U,{headers:{"content-type":"application/json"},status:200})},w=async(h,S)=>{const R=u(h,"Shard-traffic"),T=await _a(h),{headers:A}=await s(h,S),U=await R.orchestrateShardTraffic(l,{headers:A,table:T.table});return Response.json(U,{headers:{"content-type":"application/json"},status:200})},_=async(h,S)=>{if(x(h,"POST","PITR"),!n(h))throw new i("admin PITR endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403});const R=await Ra(h),{headers:T}=await s(h,S),A=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:R.args,functionPath:R.functionPath}),headers:T,method:"POST"});return r(l,R.shardKey??t,A)};return{[ca]:f,[ua]:_,[da]:y,[la]:E,[ha]:w}},Sa=1,Oa=0,Ta=32,Aa=512,ka=/^[a-z][\d_a-z*/-]{0,255}(?:@[a-z][\d_a-z*/-]{0,13})?=[\u0020-\u002B\u002D-\u003C\u003E-\u007E]{1,256}$/,va=e=>{if(e==null)return;const t=e.trim();if(t.length===0||t.length>Aa)return;const r=t.split(",");if(!(r.length>Ta)){for(const n of r)if(!ka.test(n.trim()))return;return t}},Ia=e=>{const t=Or(e.headers.get("traceparent"));if(t===void 0)return;const r=va(e.headers.get("tracestate"));return{parentSpanId:t.parentSpanId,sampled:t.sampled,traceId:t.traceId,...r===void 0?{}:{traceState:r}}},Da=(e,t={})=>{const r=Ia(e),n=t.trustInbound===!0?r:void 0,o=Ae(8),s=n?.traceId??Ae(16),l=Qr(t.sampling,n===void 0?o:s),u=l.isTraced&&(n===void 0||n.sampled);return{decision:l,ignoredUpstream:r!==void 0&&n===void 0,trace:{sampled:u,spanId:o,traceFlags:u?Sa:Oa,traceId:s,...n?.parentSpanId===void 0?{}:{parentSpanId:n.parentSpanId},...n?.traceState===void 0?{}:{traceState:n.traceState}}}},Pa=(e,t)=>{t.traceparent=Sr(e.traceId,e.spanId,e.sampled),e.traceState!==void 0&&(t.tracestate=e.traceState)},Ua=(e,t)=>{let r;return()=>{if(r===void 0){const n=vr(e),o=t===void 0?void 0:t.cf;r=Tr(kr(n),Ar(n,o))}return r}},Na="/_lunora/admin/scheduled",qa="/_lunora/admin/scheduled/status",Ca="/_lunora/admin/scheduled/ws",$a="/_lunora/admin/scheduled/cancel",Ba="/_lunora/admin/scheduled/dead",xa="/_lunora/admin/scheduled/dead/retry",ja="/_lunora/admin/scheduled/dead/cancel",Ka=e=>{const{checkWsAdmin:t,requireSchedulerNamespace:r,resolveSchedulerStub:n,schedulerInstanceName:o}=e,s=(f,y)=>E=>{if(E.method!=="GET")throw new i(`${y} endpoint requires GET`,{code:"METHOD_NOT_ALLOWED",status:405});return n(E).fetch(new Request(`https://scheduler.internal${f}`,{method:"GET"}))},l=(f,y,E=y)=>async w=>{if(w.method!=="POST")throw new i(`${E} requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});const _=n(w),h=await w.json().catch(()=>{});if(typeof h?.id!="string"||h.id==="")throw new i(`${y} requires a string \`id\``,{code:"BAD_REQUEST",status:400});return _.fetch(new Request(`https://scheduler.internal${f}`,{body:JSON.stringify({id:h.id}),headers:{"content-type":"application/json"},method:"POST"}))},u=async f=>{if(f.headers.get("Upgrade")!=="websocket")throw new i("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});if(!await t(f))throw new i("admin authorization required",{code:"ADMIN_FORBIDDEN",status:403});const y=r();return ge(y,o).fetch(new Request("https://scheduler.internal/ws",{headers:{Upgrade:"websocket"}}))};return{[$a]:l("/cancel","Scheduled-cancel","Scheduled-cancel endpoint"),[ja]:l("/dead/cancel","Scheduled dead-letter action"),[Ba]:s("/dead","Scheduled dead-letter"),[xa]:l("/dead/retry","Scheduled dead-letter action"),[Na]:s("/list","Scheduled-list"),[qa]:s("/status","Scheduler-status"),[Ca]:u}},La=(e,...t)=>{let r=e.cf;for(const n of t){if(typeof r!="object"||r===null)return;r=r[n]}return typeof r=="string"?r:void 0},mt={mtls:e=>La(e,"tlsClientAuth","certVerified")==="SUCCESS"},Fa=e=>e===void 0||e===!1?()=>!1:e===!0?()=>!0:typeof e=="function"?e:(Object.hasOwn(mt,e)?mt[e]:void 0)??(()=>!1),Ga=e=>{if(e!==void 0)return()=>{};let t=!1;return()=>{t||(t=!0,console.warn('[lunora] Ignored an inbound `traceparent`, so this request starts a new trace instead of joining the caller\'s. That is the safe default: the header is caller-supplied, and trusting it lets any client choose which trace its spans and logs join. If this worker sits behind a gateway, service mesh, or Cloudflare Access that sets `traceparent` itself, set `trustInboundTraceContext: true` on createWorker() (or `"mtls"` to trust only edge-verified client certificates). Set it to `false` to keep this behaviour and silence this message.'))}},Qa="/_lunora/admin/vector/indexes",Ma="/_lunora/admin/vector/query",za=e=>{const{readJsonBody:t,requireAdminOption:r}=e,n=async s=>{x(s,"GET","Vector-indexes");const l=r(s,e.vectorIntrospector,{code:"VECTORS_NOT_CONFIGURED",message:"vector endpoints require a `vectorIntrospector` on the worker"});return Response.json({indexes:await l.listIndexes()},{headers:{"content-type":"application/json"},status:200})},o=async s=>{x(s,"POST","Vector-query");const l=r(s,e.vectorIntrospector,{code:"VECTORS_NOT_CONFIGURED",message:"vector endpoints require a `vectorIntrospector` on the worker"});if(l.queryIndex===void 0)throw new i("vector index querying is not enabled on this worker",{code:"VECTOR_QUERY_UNSUPPORTED",status:400});const u=await t(s);if(typeof u.name!="string"||u.name==="")throw new i("Vector-query request requires a `name` string",{code:"BAD_REQUEST",status:400});if(typeof u.text!="string"||u.text==="")throw new i("Vector-query request requires a `text` string",{code:"BAD_REQUEST",status:400});if(u.topK!==void 0&&(typeof u.topK!="number"||!Number.isInteger(u.topK)||u.topK<1))throw new i("Vector-query `topK` must be a positive integer",{code:"BAD_REQUEST",status:400});const f=await l.queryIndex({name:u.name,text:u.text,topK:u.topK});return Response.json(f,{headers:{"content-type":"application/json"},status:200})};return{[Qa]:n,[Ma]:o}},Wa="/_lunora/admin/workflows/instances",Ja="/_lunora/admin/workflows/instance",Ha="/_lunora/admin/workflows/status",Va={complete:!0,errored:!0,paused:!0,queued:!0,running:!0,terminated:!0,unknown:!0,waiting:!0,waitingForPause:!0},Ya=e=>e!==null&&Object.hasOwn(Va,e)?e:void 0,wt=(e,t)=>{const r=e.searchParams.get(t);if(r===null)return;const n=Number(r);return Number.isInteger(n)&&n>0?n:void 0},Ke=(e,t)=>{const r=e.searchParams.get(t);if(r===null||r==="")throw new i(`Workflows admin endpoint requires a \`${t}\` query parameter`,{code:"BAD_REQUEST",status:400});return r},gt=()=>{throw new i("Workflow inspection is unconfigured. Set CLOUDFLARE_ACCOUNT_ID + CLOUDFLARE_API_TOKEN in your .dev.vars to enable it.",{code:"WORKFLOWS_NOT_CONFIGURED",status:501})},Xa=e=>{const{assertAdmin:t,resolveWorkflowsClient:r}=e,n=async(l,u,f)=>{x(l,"GET","Workflows instances"),t(l);const y=r(u);if(!y)return Response.json({configured:!1,instances:[],page:1,perPage:0,totalCount:0});const E=Ke(f,"name"),w=Ya(f.searchParams.get("status"));return Response.json(await y.listInstances({page:wt(f,"page"),perPage:wt(f,"perPage"),status:w,workflowName:E}))},o=async(l,u,f)=>{x(l,"GET","Workflows instance"),t(l);const y=r(u);return y?Response.json(await y.getInstance({instanceId:Ke(f,"id"),workflowName:Ke(f,"name")})):gt()},s=async(l,u)=>{x(l,"POST","Workflows status"),t(l);const f=r(u);if(!f)return gt();const y=await l.json().catch(()=>{});if(typeof y?.name!="string"||y.name===""||typeof y.id!="string"||y.id==="")throw new i("Workflows status action requires string `name` and `id`",{code:"BAD_REQUEST",status:400});const{action:E}=y;if(E!=="pause"&&E!=="resume"&&E!=="terminate")throw new i("Workflows status action must be one of: pause, resume, terminate",{code:"BAD_REQUEST",status:400});return Response.json(await f.setInstanceStatus({action:E,instanceId:y.id,workflowName:y.name}))};return{[Ja]:o,[Wa]:n,[Ha]:s}},Za={[jt]:Kt,[$r]:Cr},yt="/_lunora/rpc",eo="/_lunora/rpc-batch",to="/_lunora/ws",Ee=(e,t,r)=>({resourceAttributes:Ua(e,t),...r===void 0?{}:{waitUntil:r}}),bt=e=>e?.waitUntil?{waitUntil:t=>e.waitUntil?.(t)}:{},_t=e=>({spanId:e.spanId,traceFlags:e.traceFlags,traceId:e.traceId,...e.parentSpanId===void 0?{}:{parentSpanId:e.parentSpanId}}),Le=e=>{const{method:t}=e,r=e.headers.get("user-agent")??void 0;let n;try{n=new URL(e.url)}catch{return{method:t,userAgent:r}}const o=n.port===""?void 0:Number(n.port);return{host:n.hostname,method:t,path:n.pathname,port:Number.isNaN(o)?void 0:o,scheme:n.protocol.replace(":",""),userAgent:r}},Rt="/_lunora/voice/",ro="/_lunora/scheduler/dispatch",no="/_lunora/admin/cron-jobs/run",ao="/_lunora/admin/ws-token",oo="/_lunora/admin/",so="/_lunora/migrate",io="/_lunora/status",co=e=>e.startsWith(oo)||e===so,uo=e=>{const t=e.headers.get("x-lunora-userid"),r=e.headers.get("x-lunora-identity");if(!(t===null&&r===null))return{...r===null?{}:{identity:r},...t===null?{}:{userId:t}}},lo="/api/auth",ho="__lunora_admin__:recordAuthEvent",po="__lunora_admin__:listPushSubscriptions",fo=["/sign-in","/sign-up","/callback"],mo=(e,t)=>{const r=t.endsWith("/")?t.slice(0,-1):t;if(!e.startsWith(`${r}/`))return!1;const n=e.slice(r.length);return fo.some(o=>n===o||n.startsWith(`${o}/`))},Se=(e,t,r,n)=>{const o=yr(r),s=o?r.code:"INTERNAL_SERVER_ERROR",l=o?r.status:500,u=r instanceof Error?r.message:String(r);return{durationMs:t,error:{code:s,message:u,status:l},functionPath:e,ok:!1,...n.fanOut?{fanOut:{failed:0,shards:0,table:n.fanOut.table}}:{},...n.shardKey?{shardKey:n.shardKey}:{}}},wo=e=>{const{exp:t,expiresAtMs:r}=e;if(typeof r=="number"&&Number.isFinite(r))return r;if(typeof t=="number"&&Number.isFinite(t))return t*1e3},Et=e=>e.waitUntil?{waitUntil:t=>{e.waitUntil?.(t)}}:void 0,go=e=>{const t=e?.queue;return typeof t=="string"&&t.length>0?t:"unknown"},ue=async(e,t,r)=>{const n={"content-type":"application/json"},o=e.headers.get("authorization"),s=e.headers.get("cookie"),l=e.headers.get("x-d1-bookmark"),u=e.headers.get("x-lunora-mutation-id"),f=e.headers.get("x-lunora-client-id"),y=e.headers.get("x-lunora-client-seq");o&&(n.authorization=o),s&&(n.cookie=s),l&&(n["x-d1-bookmark"]=l),u&&(n["x-lunora-mutation-id"]=u),f&&(n["x-lunora-client-id"]=f),y&&(n["x-lunora-client-seq"]=y);const E=e.headers.get("cf-connecting-ip");if(E&&(n["x-lunora-client-ip"]=E),!r)return{claims:null,headers:n,identity:null,userId:null};const w=await r(e,t);if(!w||typeof w.userId!="string"||w.userId.length===0)return{claims:null,headers:n,identity:null,userId:null};n["x-lunora-userid"]=Rr(w.userId);const _=wo(w);_!==void 0&&(n["x-lunora-identity-exp"]=String(_));const{userId:h,...S}=w,R=Object.keys(S).length>0?S:null;return R&&(n["x-lunora-identity"]=Er(R)),{claims:R,headers:n,identity:w,userId:h}},yo=new Set(["concat","first","groupBy","max","min","rank","sum","topK"]),bo=e=>{if(e===void 0)return;if(!e||typeof e!="object")throw new i("RPC `fanOut` must be an object",{code:"BAD_REQUEST",status:400});const t=e;if(typeof t.table!="string"||t.table.length===0)throw new i("RPC `fanOut.table` must be a non-empty string",{code:"BAD_REQUEST",status:400});if(!t.merge||typeof t.merge!="object")throw new i("RPC `fanOut.merge` must be an object",{code:"BAD_REQUEST",status:400});const r=t.merge;if(typeof r.kind!="string"||!yo.has(r.kind))throw new i("RPC `fanOut.merge.kind` is not a recognized merge strategy",{code:"BAD_REQUEST",status:400});if(r.kind==="topK"){if(typeof r.k!="number"||!Number.isInteger(r.k)||r.k<0)throw new i("RPC `fanOut.merge.k` must be a non-negative integer",{code:"BAD_REQUEST",status:400});if(typeof r.by!="string"||r.by.length===0)throw new i("RPC `fanOut.merge.by` must be a non-empty string",{code:"BAD_REQUEST",status:400})}return t},_o=(e,t)=>{e?.LUNORA_DEBUG_RPC&&console.warn(`[lunora:rpc] ${t.fanOut?"fan-out":`shard=${t.shardKey??"(root)"}`} ${t.functionPath}`)},St=(e,t)=>{const r=t.functions?.[e.functionPath]?.x402;if(r){if(e.fanOut)throw new i("a paid (`.x402`) function cannot be fanned out",{code:"BAD_REQUEST",status:400});if(!t.x402Charge)throw new i(`function "${e.functionPath}" is marked paid (.x402) but no x402Charge gate is configured on the worker`,{code:"MISCONFIGURED",status:500});return r}},Ro=async e=>{const t=await vt(e);let r;try{r=JSON.parse(t)}catch{throw new i("RPC body must be valid JSON",{code:"BAD_REQUEST",status:400})}if(!r||typeof r!="object"||typeof r.functionPath!="string")throw new i("RPC envelope is missing `functionPath`",{code:"BAD_REQUEST",status:400});const n=r;if(n.args!==void 0&&It(n.args,"RPC"),n.shardKey!==void 0&&typeof n.shardKey!="string")throw new i("RPC `shardKey` must be a string",{code:"BAD_REQUEST",status:400});const o=r,s=bo(o.fanOut),l=o.args??{};if(s&&o.functionPath.startsWith("__lunora_relation__:")){const u=l.table;if(typeof u=="string"&&u!==s.table)throw new i("RPC `args.table` must match the authorized `fanOut.table` for a relation fan-out",{code:"BAD_REQUEST",status:400});l.table=s.table}return{args:l,fanOut:s,functionPath:o.functionPath,shardKey:o.shardKey}},oe=async(e,t,r)=>ge(e,t).fetch(r),Oe=new Map,Eo=5e3,So=4096,Oo=async(e,t)=>{const r=Date.now(),n=Oe.get(t);if(n!==void 0&&n.expiresMs>r)return n.relayCount;n!==void 0&&Oe.delete(t);let o=0;try{const s=await ge(e,t).fetch(new Request("https://shard.internal/_lunora/route"));if(s.ok){const l=(await s.json()).relayCount;typeof l=="number"&&l>0&&(o=Math.floor(l))}}catch{o=0}return At(Oe,So),Oe.set(t,{expiresMs:r+Eo,relayCount:o}),o},To=(e,t)=>{if(!(e===null||typeof e!="object"))return Object.entries(e).find(([,r])=>r===t)?.[0]},Te=(e,t,r)=>new Request("https://shard.internal/rpc",{body:JSON.stringify({args:t,functionPath:e}),headers:r,method:"POST"}),Ao=["x-lunora-userid","x-lunora-identity","x-lunora-identity-exp"],Ot=(e,t)=>{for(const r of Ao){e.delete(r);const n=t[r];n!==void 0&&e.set(r,n)}},ko=async(e,t,r)=>e.length===0||r.length===0?!1:Qe(await Nt(e,t),r),Tt=(e,t)=>{if(!t||t.length===0)return!1;const r=e.headers.get("authorization");if(!r)return!1;const[n,...o]=r.split(" ");return n?.toLowerCase()!=="bearer"?!1:Qe(t,o.join(" ").trim())},vo=async(e,t,r)=>{if(!t||t.length===0)return!1;const n=new URL(e.url).searchParams.get("token");return n===null?!1:await un(t,n)?!0:r?!1:Qe(t,n)},Io=(e,t)=>{if(t===null||typeof t!="object"&&typeof t!="function")return;const r=t;if(typeof r.prepare=="function"&&typeof r.batch=="function"&&typeof r.dump=="function")return Lr(`d1:${e}`,t);if(typeof r.list=="function"&&typeof r.head=="function"&&typeof r.createMultipartUpload=="function")return Ne(`r2:${e}`,!0);if(typeof r.send=="function"&&typeof r.sendBatch=="function"&&typeof r.get!="function")return Ne(`queue:${e}`,!0);if(typeof r.connectionString=="string")return Ne(`hyperdrive:${e}`,!0)},Lt=e=>{const t=Fa(e.trustInboundTraceContext),r=Ga(e.trustInboundTraceContext),n=e.defaultShardKey??"__root__",o=Fr(e.resolveIdentity,e.identity),s=et(e.shardDO,e.jurisdiction),l=e.schedulerDO===void 0?void 0:et(e.schedulerDO,e.jurisdiction);let u;const f=()=>e.adminToken??u;let y;const E=()=>e.requireEphemeralWsToken??y??!0,w=a=>{const c=a??{};if(y===void 0&&e.requireEphemeralWsToken===void 0){const d=c.LUNORA_REQUIRE_EPHEMERAL_WS_TOKEN;typeof d=="string"&&d.length>0&&(y=on(d,!0))}if(u!==void 0||e.adminToken!==void 0)return;const p=c.LUNORA_ADMIN_TOKEN;typeof p=="string"&&p.length>0&&(u=p)},_=new WeakSet,h=a=>Tt(a,f())||_.has(a),S=async(a,c)=>{const p=await ue(a,c,e.resolveIdentity);if(_.has(a)&&p.headers.authorization===void 0){const d=f();d!==void 0&&(p.headers.authorization=`Bearer ${d}`)}return p};let R=!1;const T=a=>{if(!e.allowUnauthenticatedShardAccess){const c=a==="fan-out"?"authorizeFanOut":"authorizeShard";throw new i(`${a} access is default-denied: configure \`${c}\` on the worker, or set \`allowUnauthenticatedShardAccess: true\` to explicitly allow unauthenticated ${a} access (relying solely on per-row RLS).`,{code:a==="fan-out"?"FORBIDDEN_FANOUT":"FORBIDDEN_SHARD",status:403})}R||(R=!0,console.warn([`[lunora] SECURITY: serving ${a} access with \`allowUnauthenticatedShardAccess: true\` and no \`authorizeShard\`/\`authorizeFanOut\` — `,"any caller (including unauthenticated ones) can target any shard / fan out across the table. ","This is safe only if every table is protected by per-row RLS. Configure `authorizeShard`/`authorizeFanOut` to gate it."].join("")))},A=async(a,c,p=!0)=>{if(e.authorizeShard){if(!await e.authorizeShard(a,c))throw new i("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else p&&c!==n&&T("shard")},U=Ea({defaultShard:n,forwardToShard:oe,isAdmin:h,queryCoordinator:e.queryCoordinator,resolveForwardContext:S,shardDO:s}),v=async(a,c,p,d,m)=>{await A(null,p,!1);const b={"content-type":"application/json","x-lunora-system":"1"};return m?.userId!==void 0&&m.userId.length>0&&(b["x-lunora-userid"]=m.userId),m?.identity!==void 0&&m.identity.length>0&&(b["x-lunora-identity"]=m.identity),d!==void 0&&d.length>0&&(b["x-lunora-mutation-id"]=d),oe(s,p,Te(a,c,b))},L=async(a,c,p,d)=>{const m=p?.[a];if(!m||typeof m.create!="function")throw new i(`${d} targets workflow binding "${a}", which is not bound on env`,{code:"CRON_JOB_FAILED",status:500});if(Jr(c))throw new i(`${d} params ${Hr}`,{code:"BAD_REQUEST",status:400});await m.create({params:c})},j=async(a,c)=>{if(a.workflow){await L(a.workflow,a.args??{},c,`cron job "${a.name}"`);return}if(a.functionPath===void 0)throw new i(`cron job "${a.name}" has neither a function target nor a workflow target`,{code:"CRON_JOB_FAILED",status:500});const p=await v(a.functionPath,a.args??{},a.shardKey??n);if(!p.ok)throw new i(`cron job "${a.name}" (${a.functionPath}) failed with shard status ${String(p.status)}`,{code:"CRON_JOB_FAILED",status:500})},V=async(a,c,p,d)=>{const m=e.cronJobs?.[a];if(m)for(const b of m)try{await j(b,c)}catch(D){p.push(d(D))}},N=async(a,c)=>{if(!h(a))throw new i("admin endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403});if(x(a,"POST","cron-jobs run"),!e.cronJobs)throw new i("cron-jobs run endpoint requires a `cronJobs` map on the worker",{code:"CRON_JOBS_NOT_CONFIGURED",status:400});const p=await X(a),d=typeof p.name=="string"?p.name:"";if(d==="")throw new i("cron-jobs run endpoint requires a job `name`",{code:"BAD_REQUEST",status:400});const m=Object.values(e.cronJobs).flat().find(b=>b.name===d);if(!m)throw new i(`no cron job named "${d}" is registered`,{code:"CRON_JOB_NOT_FOUND",status:404});return await j(m,c),Response.json({name:d,ran:!0},{status:200})},G=async a=>{const c=typeof a.pool=="string"&&a.pool.length>0?a.pool:void 0;if(!c||!l||typeof a.id!="string")return;const p=typeof a.instanceName=="string"&&a.instanceName.length>0?a.instanceName:"default";try{await ge(l,p).fetch(new Request("https://scheduler.internal/complete",{body:JSON.stringify({id:a.id,pool:c}),headers:{"content-type":"application/json"},method:"POST"}))}catch{}},Q=async(a,c)=>{x(a,"POST","Scheduler dispatch");const p=await vt(a),d=c??{},m=typeof d.LUNORA_SCHEDULER_SECRET=="string"?d.LUNORA_SCHEDULER_SECRET:void 0,b=e.adminToken??(typeof d.LUNORA_ADMIN_TOKEN=="string"?d.LUNORA_ADMIN_TOKEN:void 0),D=a.headers.get("x-lunora-scheduler-signature");let g=!1;if(D&&m?g=await ko(m,p,D):b&&(g=Tt(a,b)),!g)throw new i("Scheduler dispatch requires a valid signature or admin bearer",{code:"FORBIDDEN",status:403});let O;try{O=JSON.parse(p)}catch{throw new i("Scheduler dispatch body must be valid JSON",{code:"BAD_REQUEST",status:400})}const k=O??{},q=k.args??{};if(typeof k.workflow=="string"&&k.workflow.length>0)return await L(k.workflow,q,c,"scheduled workflow"),Response.json({ok:!0},{status:200});if(typeof k.functionPath!="string"||k.functionPath.length===0)throw new i("Scheduler dispatch is missing `functionPath`",{code:"BAD_REQUEST",status:400});const C=typeof k.shardKey=="string"&&k.shardKey.length>0?k.shardKey:n,B=typeof k.id=="string"&&k.id.length>0?k.id:void 0,Z=uo(a),ee=await v(k.functionPath,q,C,B,Z);return await G(k),ee},$=a=>{if(!h(a))throw new i("admin endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403})},K=(a,c,p)=>{if($(a),c===void 0)throw new i(p.message,{code:p.code,status:400});return c},Y=fn({assertAdmin:$,getReader:()=>e.authAuditReader}),J=async(a,c)=>{$(a);const p=e.notifySubscriptionStore;if(p===void 0)return Response.json({subscriptions:[]},{headers:{"content-type":"application/json"},status:200});const d=c?.kind,m=c?.userId,b=c?.limit,D=d==="fcm"||d==="web-push"?d:void 0,g=typeof m=="string"&&m!==""?m:void 0,O=typeof b=="number"&&Number.isFinite(b)?Math.trunc(b):0,k=O>0?Math.min(O,1e3):1e3,q=(await p.list({kind:D,limit:k,userId:g})).filter(C=>D!==void 0&&C.kind!==D?!1:g===void 0||(C.userId??null)===g).map(({keys:C,token:B,...Z})=>Z);return Response.json({subscriptions:q},{headers:{"content-type":"application/json"},status:200})},ne=async(a,c)=>{if(!c.fanOut){if(c.functionPath===pn)return Y(a,c.args??{});if(c.functionPath===po)return J(a,c.args)}},he=Fn({applyGlobals:e.applyGlobals,assertAdmin:$,exportCursorStore:e.exportCursorStore,exportSinks:e.exportSinks,knownTables:()=>[],queryCoordinator:e.queryCoordinator,requireAdminOption:K,resolveForwardContext:S,shardDO:s,streamExportRows:(a,c,p,d)=>$t(e,a,c,p,d,s),streamingImport:(a,c)=>zn(a,e,c,s),syncGlobals:e.syncGlobals}),ae=(a,c)=>{const p=a.searchParams.get(c);return p===null||p===""?void 0:p},pe=a=>{const c=new URL(a.url),p=c.searchParams.get("limit"),d=c.searchParams.get("offset"),m=p===null?void 0:Number.parseInt(p,10),b=d===null?void 0:Number.parseInt(d,10);return{limit:m!==void 0&&Number.isFinite(m)&&m>=0?m:void 0,offset:b!==void 0&&Number.isFinite(b)&&b>=0?b:void 0}},_e=()=>{if(l===void 0)throw new i("scheduled endpoints require a `schedulerDO` namespace on the worker",{code:"SCHEDULER_NOT_CONFIGURED",status:400});return l},ke=Ka({checkWsAdmin:async a=>h(a)||vo(a,f(),E()),requireSchedulerNamespace:_e,resolveSchedulerStub:a=>($(a),ge(_e(),e.schedulerInstanceName??"default")),schedulerInstanceName:e.schedulerInstanceName??"default"}),se=Xa({assertAdmin:$,resolveWorkflowsClient:e.workflowsClient??(()=>{})}),Ft=Br({assertAdmin:$,parsePaging:pe,queryParameter:ae,readBodyBytes:Dr,requireAdminOption:K,storage:{storageBuckets:e.storageBuckets,storageDelete:e.storageDelete,storageDownload:e.storageDownload,storageList:e.storageList,storageSignedUrl:e.storageSignedUrl,storageUpload:e.storageUpload}}),Gt=kn({options:e,readJsonBody:X,requireAdminOption:K}),Qt=za({readJsonBody:X,requireAdminOption:K,vectorIntrospector:e.vectorIntrospector}),Mt=ia({kvIntrospector:e.kvIntrospector,readJsonBody:X,requireAdminOption:K}),zt=Gr({logArchive:e.logArchive,readJsonBody:X,requireAdminOption:K}),Wt=aa({assertAdmin:$,options:{cronJobs:e.cronJobs,functions:e.functions,globalIntrospector:e.globalIntrospector,openApiSpec:e.openApiSpec,openRpcSpec:e.openRpcSpec},parsePaging:pe,queryParameter:ae,requireAdminOption:K}),Jt=a=>{const c=[],p=s??a?.SHARD;if(p!==void 0&&c.push(Kr("durable-object:default",p,n)),e.health?.disableBindingProbes!==!0)for(const[d,m]of Object.entries(a??{})){const b=Io(d,m);b!==void 0&&c.push(b)}for(const d of e.health?.probes??[])c.push(d);return c},Ht=jr({appName:e.health?.appName,appVersion:e.health?.appVersion,auth:e.health?.auth??"public",cacheTtlMs:e.health?.cacheTtlMs,isAdmin:h,resolveProbes:Jt}),Vt=a=>{const c=e.schedulerInstanceName??"default",p=()=>ge(a,c),d=async(g,O)=>{const k=await p().fetch(new Request(`https://scheduler.internal${g}`,O));if(!k.ok)throw new i(`ctx.scheduler: SchedulerDO ${g} failed (${String(k.status)}): ${await k.text()}`,{code:"INTERNAL",status:500});return await k.json()},m=async(g,O)=>await d(g,{body:JSON.stringify(O),headers:{"content-type":"application/json"},method:"POST"}),b=g=>{const O=g;if(O==null)throw new i("ctx.scheduler: target is required — pass a reference from the generated `internal` / `workflows` / `agents`",{code:"BAD_REQUEST",status:400});if(typeof O.binding=="string"&&O.binding.length>0)return{workflow:O.binding};if(typeof O.__lunoraRef=="string")return{functionPath:O.__lunoraRef};throw new i("ctx.scheduler: expected a reference from the generated `internal` / `workflows` / `agents` — a bare function-path string is refused here, because an HTTP action can be reached unauthenticated",{code:"BAD_REQUEST",status:400})},D=async(g,O,k={})=>{const{id:q}=await m("/schedule",{args:k,scheduledFor:g,...b(O)});return q};return{cancel:async g=>await m("/cancel",{id:g}),get:async g=>await d(`/get?id=${encodeURIComponent(g)}`,{method:"GET"}),list:async()=>await d("/list",{method:"GET"}),runAfter:async(g,O,k)=>{if(!Number.isFinite(g)||g<0)throw new i("ctx.scheduler.runAfter: `delayMs` must be a non-negative finite number",{code:"BAD_REQUEST",status:400});return await D(Date.now()+g,O,k)},runAt:async(g,O,k)=>{if(!Number.isFinite(g))throw new i("ctx.scheduler.runAt: `timestampMs` must be a finite epoch-millisecond number",{code:"BAD_REQUEST",status:400});return await D(g,O,k)}}},Yt=async(a,c,p)=>{const{claims:d,headers:m,userId:b}=await ue(a,c,o),D=async(g,O={})=>{const k=g.__lunoraRef;if(typeof k!="string")throw new i("ctx.run*: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});const q=Te(k,O,{...m,"x-lunora-system":"1"}),C=await oe(s,n,q),B=await C.json();if(B.error)throw new i(B.error.message??"shard RPC failed",{code:B.error.code??"INTERNAL",status:C.status});return B.result};return{auth:{getIdentity:()=>Promise.resolve(d),userId:b},cache:p.cache,fetch:globalThis.fetch.bind(globalThis),runAction:D,runMutation:D,runQuery:D,...l===void 0?{}:{scheduler:Vt(l)},...e.storage===void 0?{}:{storage:Wr(e.storage(c))}}},Xt=async(a,c,p)=>{if(!e.httpRouter)return;const d=await Yt(a,c,p);try{return await e.httpRouter.fetch(a,{...c,__lunoraCtx:d},p)}catch(m){return console.error("[lunora] httpRouter (SSR) handler threw:",m),new Response("Internal Server Error",{status:500})}},Zt=async(a,c,p)=>{if(a.headers.get("Upgrade")!=="websocket")throw new i("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});const d=rt(a,ie);if(d)return d;const m=p.searchParams.get("shard")??n,{headers:b,identity:D}=await ue(a,c,o);await A(D,m);const g=new Headers(a.headers),O=[...g.keys()];for(const q of O)q.startsWith("x-lunora-")&&g.delete(q);Ot(g,b);const k=To(c,e.shardDO);if(k!==void 0){g.set("x-lunora-shard-binding",k);const q=await Oo(s,m);if(q>0){const C=rn(m,Math.floor(Math.random()*q));return oe(s,C,new Request(a,{headers:g}))}}return oe(s,m,new Request(a,{headers:g}))},er=async(a,c,p)=>{const{voiceAgents:d}=e;if(d===void 0)return new Response("Not found",{status:404});if(a.headers.get("Upgrade")!=="websocket")return new Response("Expected a WebSocket upgrade",{headers:{allow:"GET"},status:426});const m=rt(a,ie);if(m)return m;let b;try{b=decodeURIComponent(p.pathname.slice(Rt.length))}catch{return new Response("Unknown voice agent",{status:404})}const D=Object.hasOwn(d,b)?d[b]:void 0;if(D===void 0)return new Response("Unknown voice agent",{status:404});const g=p.searchParams.get("threadKey");if(g===null||g.length===0)return new Response("Missing threadKey",{status:400});const{headers:O,identity:k}=await ue(a,c,o);if(e.authorizeShard){if(!await e.authorizeShard(k,g))return new Response("Forbidden",{status:403})}else T("shard");const q=new Headers(a.headers);for(const C of q.keys())C.startsWith("x-lunora-")&&q.delete(C);return Ot(q,O),oe(D,g,new Request(a,{headers:q}))},tr=async(a,c,p)=>{if(e.authorizeFanOut){if(!await e.authorizeFanOut(p,a.table,c))throw new i("Forbidden fan-out",{code:"FORBIDDEN_FANOUT",status:403});return}if(c.startsWith("__lunora_relation__:"))throw new i("reverse cross-backend relation reads (`__lunora_relation__:*`) require `authorizeFanOut` to be configured on the worker",{code:"FORBIDDEN_FANOUT",status:403});if(e.authorizeShard)throw new i("Fan-out requires `authorizeFanOut` to be configured on the worker when `authorizeShard` is set",{code:"FORBIDDEN_FANOUT",status:403});T("fan-out")},Re=async(a,c)=>{if(!(!a.fanOut&&a.functionPath.startsWith("__lunora_admin__:"))){if(a.fanOut){await tr(a.fanOut,a.functionPath,c);return}await A(c,a.shardKey??n)}},ve=async(a,c,p,d,m,b)=>{const D=Date.now(),{observability:g,sampling:O}=e,k=Le(a),{decision:q,ignoredUpstream:C,trace:B}=Da(a,{...O===void 0?{}:{sampling:O},trustInbound:t(a)});C&&r();const Z={...m,"x-lunora-sample-errors":q.keepErrors?"1":"0"};Pa(B,Z);const ee=Te(c,p,Z);try{const F=await oe(s,d,ee);return ce(g,{...k,..._t(B),durationMs:Date.now()-D,functionPath:c,ok:F.ok,shardKey:d,...F.ok?{}:{error:{code:"SHARD_ERROR",message:`shard returned ${String(F.status)}`,status:F.status}}},b,void 0,{isTraced:B.sampled,keepErrors:q.keepErrors}),F}catch(F){throw ce(g,{...k,..._t(B),...Se(c,Date.now()-D,F,{shardKey:d})},b,void 0,{isTraced:B.sampled,keepErrors:q.keepErrors}),F}},rr=a=>{if(a.fanOut&&a.shardKey)throw new i("RPC envelope cannot set both `shardKey` and `fanOut`",{code:"BAD_REQUEST",status:400});if(!a.fanOut&&a.functionPath.startsWith("__lunora_relation__:"))throw new i("`__lunora_relation__:*` is a fan-out-only reserved RPC and cannot be dispatched to a single shard",{code:"FORBIDDEN",status:403});if(a.fanOut&&!e.queryCoordinator)throw new i("RPC envelope set `fanOut` but no `queryCoordinator` is configured on the worker",{code:"BAD_REQUEST",status:400})},nr=async(a,c,p)=>{x(a,"POST","RPC");const d=await Ro(a);_o(c,d),rr(d);const m=await ne(a,d);if(m!==void 0)return m;const{headers:b,identity:D}=await ue(a,c,o);await Re(d,D);const g=St(d,e);{const O=Date.now(),{observability:k}=e,q=Le(a),C=Ee(c,a,p&&(ee=>p.waitUntil?.(ee)));if(d.fanOut){const ee=e.queryCoordinator;if(!ee)throw new i("RPC envelope set `fanOut` but no `queryCoordinator` is configured on the worker",{code:"BAD_REQUEST",status:400});try{const F=await ee.fanOut(s,{args:d.args??{},fanOut:d.fanOut,functionPath:d.functionPath,headers:b});return ce(k,{durationMs:Date.now()-O,fanOut:{failed:F.failed,shards:F.ok+F.failed,table:d.fanOut.table},functionPath:d.functionPath,...q,ok:!0},C),Response.json(F,{headers:{"content-type":"application/json"},status:200})}catch(F){throw ce(k,{...Se(d.functionPath,Date.now()-O,F,{fanOut:{table:d.fanOut.table}}),...q},C),F}}const B=d.shardKey??n,Z=()=>ve(a,d.functionPath,d.args??{},B,b,C);return g&&e.x402Charge?e.x402Charge(a,{functionPath:d.functionPath,price:g.price},Z,bt(p)):Z()}},ar=async(a,c,p)=>{x(a,"POST","RPC batch");const d=await X(a),{calls:m}=d;if(!Array.isArray(m))throw new i("RPC batch `calls` must be an array",{code:"BAD_REQUEST",status:400});const{headers:b,identity:D}=await ue(a,c,o),g=In(m,n);for(const M of g.values())for(const z of M)if(e.functions?.[z.functionPath]?.x402)throw new i(`paid (\`.x402\`) function "${z.functionPath}" cannot be called in a batch; dispatch it individually over ${yt}`,{code:"BAD_REQUEST",status:400});await Promise.all([...g.entries()].flatMap(([M,z])=>z.map(re=>Re({functionPath:re.functionPath,shardKey:M},D))));const{observability:O}=e,k=Ee(c,a,p&&(M=>p.waitUntil?.(M))),q=Le(a),C=[],B=[],Z=(M,z,re,de)=>({body:{error:{code:re,message:de}},id:M.id,status:z}),ee=(M,z,re,de,fe)=>{for(const W of M)ce(O,fe(W),k),C.push(Z(W,z,re,de))},F=(M,z,re,de,fe)=>{for(const W of M){const me=de.get(W.id)??fe,ye=me<400;ce(O,{durationMs:re,functionPath:W.functionPath,...q,ok:ye,shardKey:z,...ye?{}:{error:{code:"SHARD_ERROR",message:`batched call returned ${String(me)}`,status:me}}},k)}};await Promise.all([...g.entries()].map(async([M,z])=>{const re=new Headers(b);re.set("content-type","application/json");const de=new Request("https://shard.internal/rpc-batch",{body:JSON.stringify({calls:z}),headers:re,method:"POST"}),fe=Date.now();let W;try{W=await oe(s,M,de)}catch(H){const Ue=Date.now()-fe,{body:Ye}=br(H,{fallbackCode:"SHARD_UNAVAILABLE",redactedMessage:"shard unavailable"});ee(z,502,Ye.code,Ye.message,gr=>({...Se(gr.functionPath,Ue,H,{shardKey:M}),...q}));return}const me=Date.now()-fe,ye=W.headers.get("x-d1-bookmark");ye&&B.push(ye);let De;try{De=await W.json()}catch{const H=`shard batch returned a non-JSON response (${String(W.status)})`;ee(z,W.status,"SHARD_ERROR",H,Ue=>({durationMs:me,error:{code:"SHARD_ERROR",message:H,status:W.status},functionPath:Ue.functionPath,...q,ok:!1,shardKey:M}));return}const Pe=Array.isArray(De.results)?De.results:[],mr=new Map(Pe.map(H=>[H.id,H.status??W.status])),wr=new Set(Pe.map(H=>H.id));F(z,M,me,mr,W.status),C.push(...Pe);for(const H of z)wr.has(H.id)||C.push(Z(H,W.status,"SHARD_ERROR",`shard batch omitted result for call ${String(H.id)}`))}));const He={"content-type":"application/json"},[Ve]=B;return B.length===1&&Ve!==void 0&&(He["x-d1-bookmark"]=Ve),Response.json({results:C},{headers:He,status:200})},or=async(a,c,p,d={},m={})=>{try{const b=p.__lunoraRef;if(typeof b!="string")throw new i("serverQuery: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});const{headers:D,identity:g}=await ue(a,c,o);await Re({functionPath:b,shardKey:m.shardKey},g);const O=m.shardKey??n,k=Ee(c,a,m.waitUntil);return await ve(a,b,d,O,D,k)}catch(b){return Xe(b)}},We=async(a,c,p)=>{const{observability:d}=e,m=Date.now(),b=Ae(16),D=Ae(8),g=Et(c);try{const O=await p();return ce(d,{durationMs:Date.now()-m,functionPath:a,ok:!0,spanId:D,traceId:b},g),O}catch(O){throw ce(d,{...Se(a,Date.now()-m,O,{}),spanId:D,traceId:b},g),O}finally{Ze(d,g)}},sr=async(a,c,p)=>{w(c);const d=[],m=g=>g instanceof Error?g:new Error(String(g)),b=e.crons?.[a.cron];if(b)try{await b(a,c,p)}catch(g){d.push(m(g))}if(await V(a.cron,c,d,m),e.backupStore&&e.backupCron!==void 0&&e.backupCron===a.cron)try{await Sn(e,s,f(),a)}catch(g){d.push(m(g))}const[D]=d;if(d.length===1&&D)throw D;if(d.length>1)throw new AggregateError(d,`scheduled("${a.cron}") had ${String(d.length)} failure(s)`)},ir=async(a,c)=>{try{const p=a??{},d=e.adminToken??(typeof p.LUNORA_ADMIN_TOKEN=="string"?p.LUNORA_ADMIN_TOKEN:void 0);if(!d||d.length===0)return;await oe(s,n,Te(ho,{outcome:c},{authorization:`Bearer ${d}`,"content-type":"application/json"}))}catch{}},cr=async(a,c,p,d)=>{if(!e.authHandler)return;const m=await e.authHandler(a);if(!m)return;const b=e.authBasePath??lo;return mo(p.pathname,b)&&d.waitUntil?.(ir(c,m.status>=400?"fail":"ok")),m},ur=async({args:a,env:c,functionPath:p,request:d,shardKey:m,waitUntil:b})=>{It(a,"REST");const D={functionPath:p,...m===void 0?{}:{shardKey:m}},{headers:g,identity:O}=await ue(d,c,o);await Re(D,O);const k=m??n,q=Ee(c,d,b),C=()=>ve(d,p,a,k,g,q),B=St(D,e);return B&&e.x402Charge?e.x402Charge(d,{functionPath:p,price:B.price},C,bt({waitUntil:b})):C()},dr=Ir({functions:e.functions??{},invoke:ur,readJsonBody:X,...e.restRateLimit?{rateLimit:e.restRateLimit}:{}}),Ie=e.routes!==void 0&&Object.keys(e.routes).length>0?e.routes:void 0,lr={[io]:a=>a.method!=="GET"&&a.method!=="HEAD"?new Response(void 0,{headers:{allow:"GET, HEAD"},status:405}):Response.json({ok:!0},{headers:{"cache-control":"no-store"}}),[to]:(a,c,p)=>Zt(a,c,p),[yt]:(a,c,p,d)=>nr(a,c,d),[eo]:(a,c,p,d)=>ar(a,c,d),[ro]:(a,c)=>Q(a,c),[no]:(a,c)=>N(a,c),[ao]:async a=>{x(a,"POST","ws-token"),$(a);const c=f();if(c===void 0)throw new i("ws-token minting requires a configured admin token",{code:"ADMIN_TOKEN_NOT_CONFIGURED",status:400});const p=await cn(c);return Response.json(p,{headers:{"cache-control":"no-store"}})},...U,...he,...ke,...se,...Ft,...Gt,...Qt,...Mt,...zt,...Wt,...Ht,...dr,...hn({assertAdmin:$,getAuthAdmin:()=>e.authAdmin,parsePaging:pe,queryParameter:ae,readJsonBody:X})};let ie=tt(e.security),Je=!1;const hr=a=>{Je||(Je=!0,ie=tt(e.security,a??{}))},pr=async(a,c)=>{if(!(e.adminGate===void 0||!co(c)))try{await e.adminGate(a)&&_.add(a)}catch{}},fr=async(a,c,p)=>{const d=new URL(a.url);if(a.method==="POST"||a.method==="PUT"){const g=Number(a.headers.get("content-length")??""),O=Za[d.pathname]??kt;if(Number.isFinite(g)&&g>O)throw new i("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413})}const m=await cr(a,c,d,p);if(m)return m;if(Ie){const g=`${a.method} ${d.pathname}`,O=Ie[g]??Ie[d.pathname];if(O)return O(a,c,p)}const b=lr[d.pathname];return b?(await pr(a,d.pathname),b(a,c,d,p)):e.voiceAgents!==void 0&&d.pathname.startsWith(Rt)?er(a,c,d):await Xt(a,c,p)||new Response("Not found",{status:404})};return{async fetch(a,c,p){e.passThroughOnException&&p.passThroughOnException?.(),hr(c),w(c);const d=Mr(a,ie);if(d)return d;const m=zr(a,ie);if(m)return qe(m,a,ie);try{const b=await fr(a,c,p);return qe(b,a,ie)}catch(b){return qe(Xe(b),a,ie)}finally{Ze(e.observability,Et(p))}},async queue(a,c,p){await We(`queue:${go(a)}`,p,async()=>{await e.queue?.(a,c,p)})},async scheduled(a,c,p){await We(`cron:${a.cron}`,p,async()=>{await sr(a,c,p)})},serverQuery:or}},Do=e=>Lt(e),Po=e=>typeof e=="function"?{fetch:e}:e,Uo=e=>!!(e.crons??e.cronJobs??e.backupCron),Yo=(e,t)=>{const r=Po(e),n=typeof e=="object"&&typeof e.scheduled=="function"?e.scheduled:void 0,o=l=>{const u=Do({...l,httpRouter:r});return n!==void 0&&!Uo(l)?{...u,scheduled:async(f,y,E)=>{await n(f,y,E)}}:u};if(typeof t!="function")return o(t);const s=t;return{fetch:(l,u,f)=>o(s(u)).fetch(l,u,f),queue:(l,u,f)=>o(s(u)).queue?.(l,u,f)??Promise.resolve(),scheduled:(l,u,f)=>o(s(u)).scheduled(l,u,f),serverQuery:(l,u,f,y,E)=>o(s(u)).serverQuery(l,u,f,y,E)}},No=(e,t)=>{if(typeof e=="function")return e(t);const r=e.shardDO??t?.SHARD;if(!r)throw new i("@lunora/runtime: no shard Durable Object namespace found. Bind `SHARD` in wrangler.jsonc, or pass `createLunoraHandler({ shardDO: env.MY_SHARD })`.");return{...e,shardDO:r}},Xo=(e={})=>(t,r,n)=>Lt(No(e,r)).fetch(t,r,n??_r),Zo=e=>e;export{pn as GET_AUTH_AUDIT_LOG_OP,_r as NOOP_EXECUTION_CONTEXT,rs as composeIdentityResolvers,Do as composeWorker,Xo as createLunoraHandler,Lt as createWorker,Zo as defineRpcEnvelope,Oo as probeRelayCount,No as resolveLunoraOptions,ns as routeIdentityResolvers,Yo as withFrameworkWorker};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/runtime",
3
- "version": "1.0.0-alpha.58",
3
+ "version": "1.0.0-alpha.59",
4
4
  "description": "Lunora Worker runtime: the RPC router, shard resolver, and query coordinator",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -46,8 +46,8 @@
46
46
  "access": "public"
47
47
  },
48
48
  "dependencies": {
49
- "@lunora/bindings": "1.0.0-alpha.24",
50
- "@lunora/errors": "1.0.0-alpha.17",
49
+ "@lunora/bindings": "1.0.0-alpha.25",
50
+ "@lunora/errors": "1.0.0-alpha.18",
51
51
  "@lunora/platform": "1.0.0-alpha.8"
52
52
  },
53
53
  "engines": {
@@ -1,6 +0,0 @@
1
- import{isLunoraError as ur,toErrorBody as lr}from"@lunora/errors";import{d as Rt}from"./evict-oldest-C2XU6HBR.mjs";import{NOOP_EXECUTION_CONTEXT as hr}from"./NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{f as pr,u as fr}from"./identity-header-pdXOyDU4.mjs";import{O as Ae,m as mr,A as wr,R as yr,d as gr,i as br,s as _r}from"./otlp-resource-B-ByO9qo.mjs";import{h as Z,f as be,i as Et,E as Rr,w as St,e as Ot,b as Er}from"./rest-routes-BqldHiaH.mjs";import{LunoraError as d,toErrorResponse as Je}from"./LunoraError-ByasbDmd.mjs";import{runExportTap as Sr}from"./createKvCursorStore-C24tEuYk.mjs";import{t as we,r as j}from"./method-guard-rzvo19pa.mjs";import{buildHealthRoutes as Or,durableObjectProbe as Tr,d1Probe as Ar,presenceProbe as Ne}from"./HEALTH_PATH-BuLCcWNS.mjs";import{wrapResolverWithContract as vr}from"./composeIdentityResolvers-DwE0Jbww.mjs";import{composeIdentityResolvers as Mo,routeIdentityResolvers as zo}from"./composeIdentityResolvers-DwE0Jbww.mjs";import{buildLogArchiveAdminRoutes as kr}from"./LOG_ARCHIVE_PATH-CuHKuDCS.mjs";import{o as Ir,f as Ve,a as de}from"./observability-DWlkDJJw.mjs";import{resolveShard as ye,applyJurisdiction as Ye}from"./applyJurisdiction-Dsm_m5zW.mjs";import{normalizeBackupPrefix as Dr,BACKUP_KEY_PREFIX as Pr,backupObjectKey as Ur,backupManifestKey as Nr,isBackupManifestKey as qr,backupObjectKeyOfManifest as Cr}from"./BACKUP_KEY_PREFIX-DhFUE3VL.mjs";import{toHex as xr,STORAGE_UPLOAD_MAX_BODY_BYTES as Br,STORAGE_PATH as $r,buildStorageAdminRoutes as jr}from"./STORAGE_UPLOAD_MAX_BODY_BYTES-K0uZPIUj.mjs";import{resolveSecurity as Xe,handleCorsPreflight as Kr,enforceOrigin as Lr,decorateResponse as qe,enforceWebSocketOrigin as Ze}from"./decorateResponse-DBIWsRSZ.mjs";const Fr=e=>{const t=e??{};if(typeof t.bucket=="function")return t;const r={...t,bucketName:"default"};return r.bucket=()=>r,r},Tt="__lunoraBranch",Qr=e=>typeof e=="object"&&e!==null&&Object.hasOwn(e,Tt),Gr=`may not contain the reserved workflow branch-marker key ("${Tt}")`,Fe=(e,t)=>{const r=Math.max(e.length,t.length);let n=e.length^t.length;for(let o=0;o<r;o+=1){const i=o<e.length?e.charCodeAt(o):0,u=o<t.length?t.charCodeAt(o):0;n|=i^u}return n===0},Qe=new TextEncoder,Mr=Array.from({length:32},(e,t)=>t);new RegExp(`[${Mr.map(e=>String.fromCodePoint(e)).join("")}]`,"u");const zr=e=>{const t=String.fromCodePoint(...e);return btoa(t).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")},Wr=e=>{const t=e.replaceAll("-","+").replaceAll("_","/")+"===".slice((e.length+3)%4),r=atob(t),n=new Uint8Array(r.length);for(let o=0;o<r.length;o+=1)n[o]=r.codePointAt(o)??0;return n},Hr=64,Ce=new Map,At=async e=>{const t=Ce.get(e);if(t)return t;Rt(Ce,Hr);const r=crypto.subtle.importKey("raw",Qe.encode(e),{hash:"SHA-256",name:"HMAC"},!1,["sign","verify"]);return Ce.set(e,r),r},vt=async(e,t)=>{const r=await At(e),n=await crypto.subtle.sign("HMAC",r,Qe.encode(t));return zr(new Uint8Array(n))},Jr=async(e,t,r)=>{const n=await At(e);return crypto.subtle.verify("HMAC",n,r,Qe.encode(t))},Vr="::relay::",Yr=(e,t)=>`${e}${Vr}${String(t)}`,Xr=new Set(["1","enabled","on","true","yes"]),Zr=new Set(["0","disabled","false","no","off"]),en=(e,t)=>{const r=(e??"").trim().toLowerCase();return Xr.has(r)?!0:Zr.has(r)?!1:t},kt="v1",tn=6e4,rn=async(e,t={})=>{const r=(t.now??Date.now())+(t.ttlMs??tn),n=`${kt}.${String(r)}`,o=await vt(e,n);return{expiresAtMs:r,token:`${n}.${o}`}},nn=async(e,t,r=Date.now())=>{if(e.length===0||t.length===0)return!1;const n=t.split(".");if(n.length!==3)return!1;const[o,i,u]=n;if(o!==kt||u.length===0)return!1;const l=Number(i);if(!Number.isFinite(l)||l<=r)return!1;let f;try{f=Wr(u)}catch{return!1}return Jr(e,`${o}.${i}`,f)},I="/_lunora/admin/auth",an={INVITER_REQUIRED:400,ORG_SLUG_INVALID:400,ORG_SLUG_TAKEN:409,PASSWORD_TOO_LONG:400,PASSWORD_TOO_SHORT:400,USER_ALREADY_EXISTS:409,USER_NOT_FOUND:404},P=(e,t)=>{const r=e[t];if(typeof r!="string"||r==="")throw new d(`\`${t}\` is required`,{code:"BAD_REQUEST",status:400});return r},le=(e,t)=>{const r=e(t);if(r===void 0)throw new d(`\`${t}\` query parameter is required`,{code:"BAD_REQUEST",status:400});return r},It=e=>{if(typeof e=="string"||Array.isArray(e)&&e.every(t=>typeof t=="string"))return e},te=(e,t)=>typeof e[t]=="string"?e[t]:void 0,xe=(e,t)=>{const r=e[t];return typeof r=="object"&&r!==null&&!Array.isArray(r)?r:void 0},et=e=>{const t=It(e.role);if(t===void 0||typeof t=="string"&&t.trim()==="")throw new d("`role` is required",{code:"BAD_REQUEST",status:400});return t},tt=e=>{const t=e.permission;if(typeof t!="object"||t===null||Array.isArray(t))throw new d("`permission` object is required",{code:"BAD_REQUEST",status:400});const r={};for(const[n,o]of Object.entries(t))Array.isArray(o)&&o.every(i=>typeof i=="string")&&(r[n]=o);return r},on={[`${I}/capabilities`]:{build:()=>({}),http:"GET",method:"capabilities"},[`${I}/users`]:{build:({paging:e,query:t})=>{const r=t("sortDirection");return{...e,filterField:t("filterField"),filterValue:t("filterValue"),search:t("search"),searchField:t("searchField"),sortBy:t("sortBy"),sortDirection:r==="asc"||r==="desc"?r:void 0}},http:"GET",method:"listUsers"},[`${I}/sessions`]:{build:({paging:e,query:t})=>({...e,userId:t("userId")}),http:"GET",method:"listSessions"},[`${I}/accounts`]:{build:({query:e})=>({userId:le(e,"userId")}),http:"GET",method:"listAccounts"},[`${I}/passkeys`]:{build:({query:e})=>({userId:le(e,"userId")}),http:"GET",method:"listPasskeys"},[`${I}/organizations`]:{build:({paging:e})=>({...e}),http:"GET",method:"listOrganizations"},[`${I}/organizations/members`]:{build:({paging:e,query:t})=>({...e,organizationId:le(t,"organizationId")}),http:"GET",method:"listMembers"},[`${I}/organizations/invitations`]:{build:({paging:e,query:t})=>({...e,organizationId:le(t,"organizationId")}),http:"GET",method:"listInvitations"},[`${I}/config`]:{build:()=>({}),http:"GET",method:"config"},[`${I}/organizations/teams`]:{build:({paging:e,query:t})=>({...e,organizationId:le(t,"organizationId")}),http:"GET",method:"listTeams"},[`${I}/organizations/teams/members`]:{build:({paging:e,query:t})=>({...e,teamId:le(t,"teamId")}),http:"GET",method:"listTeamMembers"},[`${I}/organizations/roles`]:{build:({paging:e,query:t})=>({...e,organizationId:le(t,"organizationId")}),http:"GET",method:"listOrgRoles"},[`${I}/users/create`]:{build:({body:e})=>({data:xe(e,"data"),email:P(e,"email"),name:P(e,"name"),password:te(e,"password"),role:It(e.role)}),http:"POST",method:"createUser"},[`${I}/users/update`]:{build:({body:e})=>{const{data:t}=e;if(typeof t!="object"||t===null||Array.isArray(t))throw new d("`data` object is required",{code:"BAD_REQUEST",status:400});return{data:t,userId:P(e,"userId")}},http:"POST",method:"updateUser"},[`${I}/users/role`]:{build:({body:e})=>({role:et(e),userId:P(e,"userId")}),http:"POST",method:"setRole"},[`${I}/users/ban`]:{build:({body:e})=>({expiresInSeconds:typeof e.expiresInSeconds=="number"?e.expiresInSeconds:void 0,reason:te(e,"reason"),userId:P(e,"userId")}),http:"POST",method:"banUser"},[`${I}/users/unban`]:{build:({body:e})=>({userId:P(e,"userId")}),http:"POST",method:"unbanUser"},[`${I}/users/password`]:{build:({body:e})=>({newPassword:P(e,"newPassword"),userId:P(e,"userId")}),http:"POST",method:"setUserPassword",returns:"void"},[`${I}/users/remove`]:{build:({body:e})=>({userId:P(e,"userId")}),http:"POST",method:"removeUser",returns:"void"},[`${I}/users/impersonate`]:{build:({body:e})=>({userId:P(e,"userId")}),http:"POST",method:"impersonateUser"},[`${I}/sessions/revoke`]:{build:({body:e})=>({sessionId:P(e,"sessionId")}),http:"POST",method:"revokeUserSession",returns:"void"},[`${I}/sessions/revoke-all`]:{build:({body:e})=>({userId:P(e,"userId")}),http:"POST",method:"revokeUserSessions",returns:"void"},[`${I}/accounts/unlink`]:{build:({body:e})=>({accountId:P(e,"accountId"),userId:P(e,"userId")}),http:"POST",method:"unlinkAccount",returns:"void"},[`${I}/two-factor/disable`]:{build:({body:e})=>({userId:P(e,"userId")}),http:"POST",method:"disableTwoFactor",returns:"void"},[`${I}/passkeys/delete`]:{build:({body:e})=>({passkeyId:P(e,"passkeyId")}),http:"POST",method:"deletePasskey",returns:"void"},[`${I}/organizations/members/remove`]:{build:({body:e})=>({memberId:P(e,"memberId")}),http:"POST",method:"removeMember",returns:"void"},[`${I}/organizations/invitations/cancel`]:{build:({body:e})=>({invitationId:P(e,"invitationId")}),http:"POST",method:"cancelInvitation",returns:"void"},[`${I}/organizations/create`]:{build:({body:e})=>({logo:te(e,"logo"),metadata:xe(e,"metadata"),name:P(e,"name"),ownerId:te(e,"ownerId"),slug:te(e,"slug")}),http:"POST",method:"createOrganization"},[`${I}/organizations/update`]:{build:({body:e})=>({logo:te(e,"logo"),metadata:xe(e,"metadata"),name:te(e,"name"),organizationId:P(e,"organizationId"),slug:te(e,"slug")}),http:"POST",method:"updateOrganization"},[`${I}/organizations/remove`]:{build:({body:e})=>({organizationId:P(e,"organizationId")}),http:"POST",method:"deleteOrganization",returns:"void"},[`${I}/organizations/members/add`]:{build:({body:e})=>({organizationId:P(e,"organizationId"),role:te(e,"role"),userId:P(e,"userId")}),http:"POST",method:"addMember"},[`${I}/organizations/members/invite`]:{build:({body:e})=>({email:P(e,"email"),inviterId:te(e,"inviterId"),organizationId:P(e,"organizationId"),role:te(e,"role")}),http:"POST",method:"inviteMember"},[`${I}/organizations/members/role`]:{build:({body:e})=>({memberId:P(e,"memberId"),role:et(e)}),http:"POST",method:"updateMemberRole"},[`${I}/organizations/teams/create`]:{build:({body:e})=>({name:P(e,"name"),organizationId:P(e,"organizationId")}),http:"POST",method:"createTeam"},[`${I}/organizations/teams/update`]:{build:({body:e})=>({name:P(e,"name"),teamId:P(e,"teamId")}),http:"POST",method:"updateTeam"},[`${I}/organizations/teams/remove`]:{build:({body:e})=>({teamId:P(e,"teamId")}),http:"POST",method:"removeTeam",returns:"void"},[`${I}/organizations/teams/members/add`]:{build:({body:e})=>({teamId:P(e,"teamId"),userId:P(e,"userId")}),http:"POST",method:"addTeamMember"},[`${I}/organizations/teams/members/remove`]:{build:({body:e})=>({teamMemberId:P(e,"teamMemberId")}),http:"POST",method:"removeTeamMember",returns:"void"},[`${I}/organizations/roles/create`]:{build:({body:e})=>({organizationId:P(e,"organizationId"),permission:tt(e),role:P(e,"role")}),http:"POST",method:"createOrgRole"},[`${I}/organizations/roles/update`]:{build:({body:e})=>({permission:tt(e),roleId:P(e,"roleId")}),http:"POST",method:"updateOrgRole"},[`${I}/organizations/roles/remove`]:{build:({body:e})=>({roleId:P(e,"roleId")}),http:"POST",method:"deleteOrgRole",returns:"void"}},sn=e=>{const t=async o=>{try{return await o()}catch(i){if(i instanceof d)throw i;const u=i,l=typeof u.code=="string"?u.code:"AUTH_ADMIN_ERROR";throw console.error("[lunora] auth admin operation failed:",i),new d("auth admin operation failed",{code:l,status:an[l]??500})}},r=async(o,i)=>{if(e.assertAdmin(o),o.method!==i.http)throw new d(`Auth admin endpoint requires ${i.http}`,{code:"METHOD_NOT_ALLOWED",status:405});const u=e.getAuthAdmin();if(u===void 0)throw new d("auth endpoints require an `authAdmin` on the worker",{code:"AUTH_NOT_CONFIGURED",status:400});const l=u[i.method];if(l===void 0)throw new d(`auth admin does not support \`${i.method}\``,{code:"AUTH_OP_NOT_SUPPORTED",status:400});const f=new URL(o.url),b={body:i.http==="POST"?await e.readJsonBody(o):{},paging:e.parsePaging(o),query:_=>e.queryParameter(f,_)},E=i.build(b),y=await t(()=>l(E));return Response.json(i.returns==="void"?{ok:!0}:y,{headers:{"content-type":"application/json"},status:200})},n={};for(const[o,i]of Object.entries(on))n[o]=u=>r(u,i);return n},dn="__lunora_admin__:getAuthAuditLog",rt=e=>typeof e=="string"&&e!==""?e:void 0,nt=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0,cn=e=>async(t,r)=>{e.assertAdmin(t);const n=e.getReader();if(n===void 0)throw new d("the auth/security audit endpoint requires an `authAuditReader` on the worker",{code:"AUTH_AUDIT_NOT_CONFIGURED",status:400});const o=rt(r.actorId),i=rt(r.event),u=nt(r.sinceSeq),l=nt(r.limit),f={...o===void 0?{}:{actorId:o},...i===void 0?{}:{event:i},...u===void 0?{}:{sinceSeq:u},...l===void 0?{}:{limit:l}};let b;try{b=await n.read(f)}catch(y){throw y instanceof d?y:(console.error("[lunora] auth audit read failed:",y),new d("auth audit read failed",{code:"AUTH_AUDIT_READ_FAILED",status:500}))}const E={entries:b};return Response.json(E,{headers:{"content-type":"application/json"},status:200})},at=500,un=(e,t,r)=>{if(typeof e!="object"||e===null||Array.isArray(e))throw new d("each batch call must be an object",{code:"BAD_REQUEST",status:400});const n=e;if(typeof n.functionPath!="string")throw new d("each batch call needs a string `functionPath`",{code:"BAD_REQUEST",status:400});if(n.functionPath.startsWith("__lunora_relation__:")||n.functionPath.startsWith("__lunora_admin__"))throw new d("reserved function path cannot be batched",{code:"FORBIDDEN",status:403});if(n.args!==void 0&&(typeof n.args!="object"||n.args===null||Array.isArray(n.args)))throw new d("each batch call `args` must be an object",{code:"BAD_REQUEST",status:400});return{entry:{args:n.args===void 0?{}:n.args,clientId:typeof n.clientId=="string"?n.clientId:void 0,clientSeq:typeof n.clientSeq=="number"?n.clientSeq:void 0,functionPath:n.functionPath,id:typeof n.id=="number"?n.id:t,mutationId:typeof n.mutationId=="string"?n.mutationId:void 0},shardKey:typeof n.shardKey=="string"?n.shardKey:r}},ln=(e,t)=>{if(e.length>at)throw new d(`RPC batch exceeds the ${String(at)}-call limit`,{code:"BAD_REQUEST",status:400});const r=new Map;for(const[n,o]of e.entries()){const{entry:i,shardKey:u}=un(o,n,t),l=r.get(u)??[];l.push(i),r.set(u,l)}return r},hn=new TextEncoder,pn=e=>{const t=JSON.stringify(e),r=hn.encode(t);let n="";for(const o of r)n+=String.fromCodePoint(o);return btoa(n).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")},fn=e=>{const t={g:0,s:{},v:1};if(typeof e!="string"||e.length===0)return t;try{const r=atob(e.replaceAll("-","+").replaceAll("_","/")),n=new Uint8Array(r.length);for(let l=0;l<r.length;l+=1)n[l]=r.codePointAt(l)??0;const o=JSON.parse(new TextDecoder().decode(n)),i=o.s&&typeof o.s=="object"?o.s:{},u={};for(const[l,f]of Object.entries(i))typeof f=="number"&&Number.isFinite(f)&&(u[l]=f);return{g:typeof o.g=="number"&&Number.isFinite(o.g)?o.g:0,s:u,v:1}}catch{return t}},mn=e=>{const t=typeof e.table=="string"?e.table:"",r=typeof e.op=="string"?e.op:"",n=r==="delete"||r==="insert"||r==="update"?r:"upsert",o=typeof e.id=="string"?e.id:void 0;return{doc:(e.doc&&typeof e.doc=="object"?e.doc:void 0)??(o===void 0?{}:{_id:o}),op:n,table:t}},ot=(e,t,r)=>{for(const n of t)e.push(mn(n));return r!==void 0&&t.length>=r},wn="/_lunora/admin/export",yn="/_lunora/admin/import",gn="/_lunora/admin/sync",bn="/_lunora/admin/connector/sync",_n="/_lunora/admin/apply",Rn="/_lunora/admin/export-tap/run",En=new TextEncoder,Sn=async e=>{const t=await be(e,"Export")??{};if(t.tables===void 0)return{tables:void 0};if(!Array.isArray(t.tables))throw new d("Export `tables` must be a string array",{code:"BAD_REQUEST",status:400});const r=[];for(const n of t.tables){if(typeof n!="string"||n.length===0)throw new d("Export `tables` entries must be non-empty strings",{code:"BAD_REQUEST",status:400});r.push(n)}return{tables:r}},Be=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):void 0,On=e=>{const{applyGlobals:t,exportCursorStore:r,exportSinks:n,knownTables:o,queryCoordinator:i,assertAdmin:u,requireAdminOption:l,resolveForwardContext:f,shardDO:b,streamExportRows:E,streamingImport:y,syncGlobals:_}=e,h=async(k,K)=>{const $=we(k,["POST"]);if($)return $;const V=l(k,i,{code:"BAD_REQUEST",message:"Export endpoint requires a `queryCoordinator` on the worker"}),N=await Sn(k),{headers:Q}=await f(k,K),G=new ReadableStream({async pull(x){const L=Y=>{x.enqueue(En.encode(`${JSON.stringify(Y)}
2
- `))};try{await E(V,Q,N.tables,L),x.close()}catch(Y){x.error(Y)}}});return new Response(G,{headers:{"content-type":"application/x-ndjson"},status:200})},S=async(k,K)=>{const $=we(k,["POST"]);if($)return $;const V=l(k,i,{code:"BAD_REQUEST",message:"Sync endpoint requires a `queryCoordinator` on the worker"}),N=await Z(k),Q=typeof N.cursors=="object"&&N.cursors!==null?N.cursors:{},G=typeof N.limit=="number"?N.limit:void 0,x=typeof N.globalCursor=="number"?N.globalCursor:0,L=Be(N.tables),{headers:Y}=await f(k,K),H=L??o(),ne=await V.orchestrateCdcSync(b,{cursors:Q,headers:Y,limit:G,tables:H}),he=_?await _({limit:G,sinceSeq:x}):void 0;return Response.json({global:he,shards:ne.shards},{status:200})},O=async(k,K)=>{const $=we(k,["POST"]);if($)return $;const V=l(k,i,{code:"BAD_REQUEST",message:"Connector sync endpoint requires a `queryCoordinator` on the worker"}),N=await Z(k),Q=fn(N.cursor),G=typeof N.limit=="number"&&N.limit>0?N.limit:void 0,x=Be(N.tables),{headers:L}=await f(k,K),Y=x??o(),H=await V.orchestrateCdcSync(b,{cursors:Q.s,headers:L,limit:G,tables:Y}),ne=[],he={...Q.s};let ae=!1;for(const se of H.shards)ae=ot(ne,se.changes??[],G)||ae,he[se.shardKey]=se.cursor;let pe=Q.g;if(_){const se=await _({limit:G,sinceSeq:Q.g});ae=ot(ne,se.changes,G)||ae,pe=se.cursor}const _e=pn({g:pe,s:he,v:1}),ve={changes:ne,hasMore:ae,nextCursor:_e};return Response.json(ve,{status:200})},A=async(k,K)=>{const $=we(k,["POST"]);if($)return $;const V=l(k,i,{code:"BAD_REQUEST",message:"Apply endpoint requires a `queryCoordinator` on the worker"}),N=await Z(k),Q=(Array.isArray(N.batches)?N.batches:[]).map(H=>H).filter(H=>H!==null&&typeof H=="object"&&typeof H.shardKey=="string"&&Array.isArray(H.changes)),G=Array.isArray(N.globalChanges)?N.globalChanges:[],{headers:x}=await f(k,K),L=await V.orchestrateApplyCdc(b,{batches:Q,headers:x}),Y=G.length>0&&t?await t({changes:G}):0;return Response.json({applied:L.applied+Y,failed:L.failed,ok:L.ok},{status:200})},v=async(k,K)=>{const $=we(k,["POST"]);if($)return $;u(k);const{headers:V}=await f(k,K),N=await y(k,V);return Response.json(N,{headers:{"content-type":"application/json"},status:200})},U=async(k,K)=>{const $=we(k,["POST"]);if($)return $;const V=l(k,i,{code:"BAD_REQUEST",message:"Export-tap endpoint requires a `queryCoordinator` on the worker"});if(n===void 0||Object.keys(n).length===0||r===void 0)throw new d("Export-tap endpoint requires `exportSinks` + `exportCursorStore` on the worker",{code:"EXPORT_TAP_NOT_CONFIGURED",status:400});const N=await Z(k),Q=typeof N.sink=="string"?N.sink:void 0,G=typeof N.limit=="number"&&N.limit>0?N.limit:void 0,x=Be(N.tables);if(Q===void 0)throw new d("Export-tap `sink` must name a configured sink",{code:"BAD_REQUEST",status:400});const L=n[Q];if(L===void 0)throw new d(`Export-tap sink "${Q}" is not configured`,{code:"NOT_FOUND",status:404});const{headers:Y}=await f(k,K),H=x??o(),ne=await Sr({coordinator:V,cursorStore:r,headers:Y,limit:G,shardDO:b,sink:L,tables:H});return Response.json(ne,{headers:{"content-type":"application/json"},status:200})};return{[_n]:A,[bn]:O,[wn]:h,[Rn]:U,[yn]:v,[gn]:S}},Tn=(e,t)=>{const r=[],n=[];if(t&&t.length>0)for(const o of t)e.resolveTableSharding?.(o)?.mode.kind==="global"?n.push(o):r.push(o);return{globalTables:n,shardLocalTables:r}},An=async(e,t,r,n,o,i)=>{if(r!==void 0&&n.length===0)return;const u=await e.orchestrateExport(i,{args:{tables:n},headers:t,tables:n});for(const l of u.shards)if(!l.error)for(const f of l.rows??[])o(f)},Dt=async(e,t,r,n,o,i)=>{const{globalTables:u,shardLocalTables:l}=Tn(e,n);await An(t,r,n,l,o,i);const f=e.exportGlobals;if((n===void 0||u.length>0)&&f)for await(const b of f({tables:u}))o(b)},vn=(e,t)=>{let r;try{r=JSON.parse(e)}catch{return{error:{code:"BAD_ROW",line:t,message:"line is not valid JSON",table:""},ok:!1}}if(!r||typeof r!="object"||Array.isArray(r))return{error:{code:"BAD_ROW",line:t,message:"row must be a JSON object",table:""},ok:!1};const n=r;return typeof n.table!="string"||n.table.length===0?{error:{code:"BAD_ROW",line:t,message:"row is missing `table`",table:""},ok:!1}:!n.doc||typeof n.doc!="object"||Array.isArray(n.doc)?{error:{code:"BAD_ROW",line:t,message:"row is missing or malformed `doc`",table:n.table},ok:!1}:{doc:n.doc,ok:!0,table:n.table}},kn=(e,t,r,n,o)=>{if(r?.mode.kind==="shardBy"&&typeof r.mode.field=="string"){const i=e[r.mode.field];return i==null?{error:{code:"BAD_ROW",line:o,message:`row missing shard field "${r.mode.field}" for table "${t}"`,table:t},ok:!1}:{ok:!0,shardKey:typeof i=="string"?i:JSON.stringify(i)}}return{ok:!0,shardKey:n}},In=async(e,t,r)=>{if(!e.body)throw new d("Import endpoint requires a request body",{code:"BAD_REQUEST",status:400});const n=[],o=[],i=new Map;let u=0,l=0;const f=e.body.getReader(),b=new TextDecoder;let E="",y=0;const _=h=>{l+=1;const S=h.trim();if(S.length===0)return;u+=1;const O=vn(S,l);if(!O.ok){n.push(O.error);return}const{doc:A,table:v}=O,U=t.resolveTableSharding?.(v);if(U?.mode.kind==="global"){o.push({doc:A,line:l,table:v});return}const k=kn(A,v,U,r,l);if(!k.ok){n.push(k.error);return}const K=i.get(k.shardKey);K?K.rows.push({doc:A,table:v}):i.set(k.shardKey,{rows:[{doc:A,table:v}],shardKey:k.shardKey,startLine:l})};for(;;){const{done:h,value:S}=await f.read();if(h)break;if(S&&(y+=S.byteLength,y>Et))throw await f.cancel().catch(()=>{}),new d("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});E+=b.decode(S,{stream:!0});let O=E.indexOf(`
3
- `);for(;O!==-1;){const A=E.slice(0,O);E=E.slice(O+1),_(A),O=E.indexOf(`
4
- `)}}return E.length>0&&_(E),{errors:n,globalRows:o,perShard:i,received:u}},st=(e,t)=>{for(const[r,n]of Object.entries(t.inserted))e.inserted[r]=(e.inserted[r]??0)+n;for(const r of t.errors)e.errors.push({...r});e.conflicts+=t.conflicts},Dn=async(e,t,r,n)=>{const o=t.defaultShardKey??"__root__",{errors:i,globalRows:u,perShard:l,received:f}=await In(e,t,o),b={conflicts:0,errors:i,inserted:{}},E=[];if(t.resolveTableSharding===void 0&&l.size>0&&E.push("no `resolveTableSharding` is configured, so every row was routed to the default shard and no row could be recognised as `.global()` — correct for a single-shard app, silent misplacement for a sharded one"),l.size>0){const y=t.queryCoordinator;if(!y)throw new d("Import endpoint requires a `queryCoordinator` on the worker",{code:"BAD_REQUEST",status:400});const _=await y.orchestrateImport(n,{batches:[...l.values()],headers:r});st(b,_)}if(u.length>0)if(t.importGlobals){const y=u[0]?.line??1,_=await t.importGlobals({rows:u,startLine:y});st(b,_)}else for(const y of u)b.errors.push({code:"GLOBAL_NOT_CONFIGURED",line:y.line,message:`row targets global table "${y.table}" but no \`importGlobals\` is configured`,table:y.table});return{conflicts:b.conflicts,errors:b.errors,inserted:b.inserted,received:f,...E.length>0?{warnings:E}:{}}},$e=e=>typeof e=="object"&&e!==null?e:{},je=e=>typeof e.kind=="string"?e.kind:"unknown",Pn=(e,t)=>{let r=$e(t),n=!1;je(r)==="optional"&&(n=!0,r=$e(r._meta?.inner));const o=je(r),i=r._meta??{},u={kind:o,name:e,optional:n};if(o==="id"&&typeof i.tableName=="string"&&(u.table=i.tableName),o==="array"){const l=je($e(i.inner));l!=="unknown"&&(u.element=l)}return u},Un=e=>typeof e!="object"||e===null?[]:Object.entries(e).map(([t,r])=>Pn(t,r)).toSorted((t,r)=>t.name.localeCompare(r.name)),Nn="/_lunora/admin/functions",qn="/_lunora/admin/cron-jobs",Cn="/_lunora/admin/openapi",xn="/_lunora/admin/openrpc",Bn="/_lunora/admin/global/tables",$n="/_lunora/admin/global/table",jn="/_lunora/admin/global/facet",it=e=>{if(e===void 0||e==="")return;let t;try{t=JSON.parse(e)}catch{return}if(!Array.isArray(t))return;const r=t.flatMap(n=>{if(typeof n!="object"||n===null||typeof n.column!="string")return[];const{column:o,value:i}=n;return[{column:o,value:i}]});return r.length===0?void 0:r},Kn=Object.freeze({info:{description:'No OpenAPI spec is configured on this worker. Run `lunora codegen`, then wire the generated module to `createWorker`: `import { openApiSpec } from "./lunora/_generated/openapi"`.',title:"Lunora API",version:"0.0.0"},openapi:"3.1.0",paths:{}}),Ln=Object.freeze({info:{description:'No OpenRPC spec is configured on this worker. Run `lunora codegen --api-spec openrpc` (or `both`), then wire the generated module to `createWorker`: `import { openRpcSpec } from "./lunora/_generated/openrpc"`.',title:"Lunora RPC",version:"0.0.0"},methods:[],openrpc:"1.3.2"}),Fn=e=>{const{assertAdmin:t,options:r,parsePaging:n,queryParameter:o,requireAdminOption:i}=e,u=h=>{j(h,"GET","Functions");const S=i(h,r.functions,{code:"FUNCTIONS_NOT_CONFIGURED",message:"functions endpoint requires a `functions` registry on the worker"}),O=Object.entries(S).flatMap(([A,v])=>v.visibility==="internal"||v.kind==="stream"?[]:[{args:Un(v.args),kind:v.kind,path:A}]).toSorted((A,v)=>A.path.localeCompare(v.path));return Response.json({functions:O},{headers:{"content-type":"application/json"},status:200})},l=h=>{j(h,"GET","Cron-jobs");const S=i(h,r.cronJobs,{code:"CRON_JOBS_NOT_CONFIGURED",message:"cron-jobs endpoint requires a `cronJobs` map on the worker"}),O=Object.entries(S).flatMap(([A,v])=>v.map(U=>({args:U.args,cron:A,functionPath:U.functionPath,name:U.name,shardKey:U.shardKey,workflow:U.workflow}))).toSorted((A,v)=>A.name.localeCompare(v.name));return Response.json({jobs:O},{headers:{"content-type":"application/json"},status:200})},f=h=>(j(h,"GET","OpenAPI"),t(h),Response.json(r.openApiSpec??Kn,{headers:{"content-type":"application/json"},status:200})),b=h=>(j(h,"GET","OpenRPC"),t(h),Response.json(r.openRpcSpec??Ln,{headers:{"content-type":"application/json"},status:200})),E=async h=>{j(h,"GET","Global-tables");const S=i(h,r.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"});return Response.json(await S.listTables(),{headers:{"content-type":"application/json"},status:200})},y=async h=>{j(h,"GET","Global-table");const S=i(h,r.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),O=new URL(h.url),A=o(O,"table");if(A===void 0)throw new d("Global-table endpoint requires a `table` query param",{code:"BAD_REQUEST",status:400});const v=await S.readTablePage({...n(h),filters:it(o(O,"filters")),table:A});return Response.json(v,{headers:{"content-type":"application/json"},status:200})},_=async h=>{j(h,"GET","Global-facet");const S=i(h,r.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),O=new URL(h.url),A=o(O,"table"),v=o(O,"column");if(A===void 0||v===void 0)throw new d("Global-facet endpoint requires `table` and `column` query params",{code:"BAD_REQUEST",status:400});const U=o(O,"limit"),k=U===void 0?void 0:Number(U),K=await S.facetColumn({column:v,filters:it(o(O,"filters")),limit:k!==void 0&&Number.isFinite(k)?k:void 0,table:A});return Response.json(K,{headers:{"content-type":"application/json"},status:200})};return{[qn]:l,[Nn]:u,[jn]:_,[$n]:y,[Bn]:E,[Cn]:f,[xn]:b}},Qn="/_lunora/admin/kv/namespaces",Gn="/_lunora/admin/kv/keys",Pt="/_lunora/admin/kv/value",Ut=32*1048576,dt=60,Mn=e=>{const{readJsonBody:t,requireAdminOption:r}=e,n=y=>r(y,e.kvIntrospector,{code:"KV_NOT_CONFIGURED",message:"KV endpoints require a `kvIntrospector` on the worker"}),o=y=>Response.json(y,{headers:{"content-type":"application/json"},status:200}),i=(y,_)=>{const h=new URL(y.url),S=h.searchParams.get("namespace")??"",O=h.searchParams.get("key")??"";if(S==="")throw new d(`KV-value ${_} request requires a \`namespace\` query parameter`,{code:"BAD_REQUEST",status:400});if(O==="")throw new d(`KV-value ${_} request requires a \`key\` query parameter`,{code:"BAD_REQUEST",status:400});return{key:O,namespace:S}},u=async(y,_)=>{if(!(await y.listNamespaces()).some(h=>h.binding===_))throw new d(`Unknown KV namespace binding \`${_}\``,{code:"NOT_FOUND",status:404})},l=async y=>(j(y,"GET","KV-namespaces"),o({namespaces:await n(y).listNamespaces()})),f=async y=>{j(y,"GET","KV-keys");const _=n(y),h=new URL(y.url),S=h.searchParams.get("namespace")??"";if(S==="")throw new d("KV-keys request requires a `namespace` query parameter",{code:"BAD_REQUEST",status:400});const O=h.searchParams.get("prefix")??void 0,A=h.searchParams.get("cursor")??void 0,v=h.searchParams.get("limit"),U=v===null?void 0:Number.parseInt(v,10);if(U!==void 0&&(!Number.isInteger(U)||U<1))throw new d("KV-keys `limit` must be a positive integer",{code:"BAD_REQUEST",status:400});const k=U===void 0?void 0:Math.min(U,1e3);return await u(_,S),o(await _.listKeys({cursor:A,limit:k,namespace:S,prefix:O}))},b={DELETE:async y=>{const _=n(y),h=i(y,"DELETE");return await u(_,h.namespace),await _.deleteKey(h),o({deleted:!0})},GET:async y=>{const _=n(y),h=i(y,"GET");return await u(_,h.namespace),o(await _.getValue(h))},PUT:async y=>{const _=n(y),h=await t(y,Ut);if(typeof h.namespace!="string"||h.namespace==="")throw new d("KV-value PUT request requires a `namespace` string",{code:"BAD_REQUEST",status:400});if(typeof h.key!="string"||h.key==="")throw new d("KV-value PUT request requires a `key` string",{code:"BAD_REQUEST",status:400});if(typeof h.value!="string")throw new d("KV-value PUT request requires a `value` string",{code:"BAD_REQUEST",status:400});if(h.expirationTtl!==void 0&&(typeof h.expirationTtl!="number"||!Number.isInteger(h.expirationTtl)||h.expirationTtl<dt))throw new d("KV-value PUT `expirationTtl` must be an integer ≥ 60",{code:"BAD_REQUEST",status:400});const S=Math.floor(Date.now()/1e3)+dt;if(h.expiration!==void 0&&(typeof h.expiration!="number"||!Number.isInteger(h.expiration)||h.expiration<S))throw new d("KV-value PUT `expiration` must be a Unix-seconds timestamp at least 60 seconds in the future",{code:"BAD_REQUEST",status:400});return await u(_,h.namespace),await _.putValue({expiration:h.expiration,expirationTtl:h.expirationTtl,key:h.key,metadata:h.metadata,namespace:h.namespace,value:h.value}),o({ok:!0})}},E=y=>{const _=b[y.method];if(!_)throw new d("KV-value endpoint requires GET, PUT, or DELETE",{code:"METHOD_NOT_ALLOWED",status:405});return _(y)};return{[Qn]:l,[Gn]:f,[Pt]:E}},zn="/_lunora/migrate",Wn="/_lunora/admin/pitr",Hn="/_lunora/admin/rank",Jn="/_lunora/admin/rankpage",Vn="/_lunora/admin/shard-traffic",Yn=new Set(["__lunora_admin__:migrationStatus","__lunora_admin__:runMigration"]),Xn=new Set(["__lunora_admin__:getPitrBookmark","__lunora_admin__:pitrRestore"]),Zn=async e=>{const t=await be(e,"Migration")??{};if(typeof t.table!="string"||t.table.length===0)throw new d("Migration request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof t.functionPath!="string"||!Yn.has(t.functionPath))throw new d("Migration request `functionPath` must be a migration admin op",{code:"BAD_REQUEST",status:400});return{args:t.args??{},functionPath:t.functionPath,table:t.table}},ea=async e=>{const t=await be(e,"Rank")??{};if(typeof t.table!="string"||t.table.length===0)throw new d("Rank request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof t.index!="string"||t.index.length===0)throw new d("Rank request is missing `index`",{code:"BAD_REQUEST",status:400});if(typeof t.partitionKey!="string")throw new d("Rank request `partitionKey` must be a string",{code:"BAD_REQUEST",status:400});if(typeof t.rowId!="string"||t.rowId.length===0)throw new d("Rank request is missing `rowId`",{code:"BAD_REQUEST",status:400});if(!Array.isArray(t.sortValues))throw new d("Rank request `sortValues` must be an array",{code:"BAD_REQUEST",status:400});return{index:t.index,partitionKey:t.partitionKey,rowId:t.rowId,sortValues:t.sortValues,table:t.table}},ta=e=>{if(e!==void 0){if(!Array.isArray(e)||e.some(t=>t!=="asc"&&t!=="desc"))throw new d('Rank page request `directions` must be an array of "asc"|"desc"',{code:"BAD_REQUEST",status:400});return e}},ra=e=>{if(typeof e.table!="string"||e.table.length===0)throw new d("Rank page request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof e.index!="string"||e.index.length===0)throw new d("Rank page request is missing `index`",{code:"BAD_REQUEST",status:400});if(e.partitionKey!==void 0&&typeof e.partitionKey!="string")throw new d("Rank page request `partitionKey` must be a string",{code:"BAD_REQUEST",status:400});if(e.take!==void 0&&(typeof e.take!="number"||!Number.isFinite(e.take)))throw new d("Rank page request `take` must be a number",{code:"BAD_REQUEST",status:400});if(e.cursor!==void 0&&e.cursor!==null&&typeof e.cursor!="string")throw new d("Rank page request `cursor` must be a string or null",{code:"BAD_REQUEST",status:400})},na=async e=>{const t=await be(e,"Rank page")??{};ra(t);const r=ta(t.directions);return{cursor:typeof t.cursor=="string"?t.cursor:null,directions:r,index:t.index,partitionKey:typeof t.partitionKey=="string"?t.partitionKey:void 0,table:t.table,take:typeof t.take=="number"?t.take:void 0}},aa=async e=>{const t=await be(e,"Shard-traffic")??{};if(typeof t.table!="string"||t.table.length===0)throw new d("Shard-traffic request is missing `table`",{code:"BAD_REQUEST",status:400});return{table:t.table}},oa=async e=>{const t=await Z(e);if(typeof t.functionPath!="string"||!Xn.has(t.functionPath))throw new d("PITR request `functionPath` must be a PITR admin op",{code:"BAD_REQUEST",status:400});if(t.shardKey!==void 0&&typeof t.shardKey!="string")throw new d("PITR `shardKey` must be a string",{code:"BAD_REQUEST",status:400});return{args:t.args??{},functionPath:t.functionPath,shardKey:t.shardKey}},sa=e=>{const{defaultShard:t,forwardToShard:r,isAdmin:n,queryCoordinator:o,resolveForwardContext:i,shardDO:u}=e,l=(h,S)=>{if(h.method!=="POST")throw new d(`${S} endpoint requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});if(!n(h))throw new d("Admin auth required",{code:"FORBIDDEN",status:403});if(!o)throw new d(`${S} endpoint requires a \`queryCoordinator\` on the worker`,{code:"BAD_REQUEST",status:400});return o},f=async(h,S)=>{const O=l(h,"Migration"),A=await Zn(h),{headers:v}=await i(h,S),U=await O.orchestrateMigration(u,{args:A.args,functionPath:A.functionPath,headers:v,table:A.table});return Response.json(U,{headers:{"content-type":"application/json"},status:200})},b=async(h,S)=>{const O=l(h,"Rank"),A=await ea(h),{headers:v}=await i(h,S),U=await O.orchestrateRank(u,{headers:v,index:A.index,partitionKey:A.partitionKey,rowId:A.rowId,sortValues:A.sortValues,table:A.table});return Response.json(U,{headers:{"content-type":"application/json"},status:200})},E=async(h,S)=>{const O=l(h,"Rank page"),A=await na(h),{headers:v}=await i(h,S),U=await O.orchestrateRankPage(u,{...A,headers:v});return Response.json(U,{headers:{"content-type":"application/json"},status:200})},y=async(h,S)=>{const O=l(h,"Shard-traffic"),A=await aa(h),{headers:v}=await i(h,S),U=await O.orchestrateShardTraffic(u,{headers:v,table:A.table});return Response.json(U,{headers:{"content-type":"application/json"},status:200})},_=async(h,S)=>{if(j(h,"POST","PITR"),!n(h))throw new d("admin PITR endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403});const O=await oa(h),{headers:A}=await i(h,S),v=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:O.args,functionPath:O.functionPath}),headers:A,method:"POST"});return r(u,O.shardKey??t,v)};return{[zn]:f,[Wn]:_,[Hn]:b,[Jn]:E,[Vn]:y}},ia=1,da=0,ca=32,ua=512,la=/^[a-z][\d_a-z*/-]{0,255}(?:@[a-z][\d_a-z*/-]{0,13})?=[\u0020-\u002B\u002D-\u003C\u003E-\u007E]{1,256}$/,ha=e=>{if(e==null)return;const t=e.trim();if(t.length===0||t.length>ua)return;const r=t.split(",");if(!(r.length>ca)){for(const n of r)if(!la.test(n.trim()))return;return t}},pa=e=>{const t=wr(e.headers.get("traceparent"));if(t===void 0)return;const r=ha(e.headers.get("tracestate"));return{parentSpanId:t.parentSpanId,sampled:t.sampled,traceId:t.traceId,...r===void 0?{}:{traceState:r}}},fa=(e,t={})=>{const r=pa(e),n=t.trustInbound===!0?r:void 0,o=Ae(8),i=n?.traceId??Ae(16),u=Ir(t.sampling,n===void 0?o:i),l=u.isTraced&&(n===void 0||n.sampled);return{decision:u,ignoredUpstream:r!==void 0&&n===void 0,trace:{sampled:l,spanId:o,traceFlags:l?ia:da,traceId:i,...n?.parentSpanId===void 0?{}:{parentSpanId:n.parentSpanId},...n?.traceState===void 0?{}:{traceState:n.traceState}}}},ma=(e,t)=>{t.traceparent=mr(e.traceId,e.spanId,e.sampled),e.traceState!==void 0&&(t.tracestate=e.traceState)},wa=(e,t)=>{let r;return()=>{if(r===void 0){const n=_r(e),o=t===void 0?void 0:t.cf;r=yr(br(n),gr(n,o))}return r}},ya="/_lunora/admin/scheduled",ga="/_lunora/admin/scheduled/status",ba="/_lunora/admin/scheduled/ws",_a="/_lunora/admin/scheduled/cancel",Ra="/_lunora/admin/scheduled/dead",Ea="/_lunora/admin/scheduled/dead/retry",Sa="/_lunora/admin/scheduled/dead/cancel",Oa=e=>{const{checkWsAdmin:t,requireSchedulerNamespace:r,resolveSchedulerStub:n,schedulerInstanceName:o}=e,i=(f,b)=>E=>{if(E.method!=="GET")throw new d(`${b} endpoint requires GET`,{code:"METHOD_NOT_ALLOWED",status:405});return n(E).fetch(new Request(`https://scheduler.internal${f}`,{method:"GET"}))},u=(f,b,E=b)=>async y=>{if(y.method!=="POST")throw new d(`${E} requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});const _=n(y),h=await y.json().catch(()=>{});if(typeof h?.id!="string"||h.id==="")throw new d(`${b} requires a string \`id\``,{code:"BAD_REQUEST",status:400});return _.fetch(new Request(`https://scheduler.internal${f}`,{body:JSON.stringify({id:h.id}),headers:{"content-type":"application/json"},method:"POST"}))},l=async f=>{if(f.headers.get("Upgrade")!=="websocket")throw new d("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});if(!await t(f))throw new d("admin authorization required",{code:"ADMIN_FORBIDDEN",status:403});const b=r();return ye(b,o).fetch(new Request("https://scheduler.internal/ws",{headers:{Upgrade:"websocket"}}))};return{[_a]:u("/cancel","Scheduled-cancel","Scheduled-cancel endpoint"),[Sa]:u("/dead/cancel","Scheduled dead-letter action"),[Ra]:i("/dead","Scheduled dead-letter"),[Ea]:u("/dead/retry","Scheduled dead-letter action"),[ya]:i("/list","Scheduled-list"),[ga]:i("/status","Scheduler-status"),[ba]:l}},Ta=new TextEncoder,Aa=1e3,Nt="lunoraBackupCron",ct=24*1048576,va=(e,t)=>{const r=new Uint8Array(new ArrayBuffer(t));let n=0;for(const o of e)r.set(o,n),n+=o.byteLength;return r},ka=async(e,t,r,n)=>{if(r===void 0||r<=0)return;const o=[];let i;for(let u=0;u<Aa;u+=1){const l=await e.list({cursor:i,include:["customMetadata"],prefix:t});for(const f of l.objects)qr(f.key)&&f.customMetadata?.[Nt]===n&&o.push(f.key);if(!l.truncated||l.cursor===void 0)break;i=l.cursor}await Promise.all(o.toSorted((u,l)=>l.localeCompare(u)).slice(r).map(async u=>{await e.delete(Cr(u)),await e.delete(u)}))},Ia=async(e,t,r,n)=>{const o=e.backupStore,i=e.queryCoordinator;if(!o)throw new d("scheduled backup requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});if(!i)throw new d("scheduled backup requires a `queryCoordinator` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});if(!r||r.length===0)throw new d("scheduled backup requires an `adminToken` (or `env.LUNORA_ADMIN_TOKEN`) to authenticate the per-shard export gate",{code:"BACKUP_NOT_CONFIGURED",status:500});const u={authorization:`Bearer ${r}`,"content-type":"application/json"},l=e.backupTables;let f=0,b=0,E=[];await Dt(e,i,u,l,v=>{const U=Ta.encode(`${JSON.stringify(v)}
5
- `);if(f+=1,b+=U.byteLength,b>ct)throw new d(`scheduled backup reached ${String(b)} bytes of NDJSON, past the ${String(ct)}-byte limit for a snapshot assembled inside a Worker — nothing was written. Narrow it with \`backupTables\`, or take this snapshot off-platform with \`lunora backup create --bucket\`.`,{code:"BACKUP_TOO_LARGE",status:507});E.push(U)},t);const y=Dr(e.backupPrefix??Pr),_=new Date(n.scheduledTime).toISOString(),h=Ur(y,_),S=va(E,b);E=[];const O=xr(await crypto.subtle.digest("SHA-256",S));await o.put(h,S,{httpMetadata:{contentType:"application/x-ndjson"},sha256:O});const A={bytes:b,createdAt:_,cron:n.cron,file:h,id:_,rows:f,scheduledTime:n.scheduledTime,sha256:O,...l?{tables:l.join(",")}:{}};await o.put(Nr(h),`${JSON.stringify(A,void 0,2)}
6
- `,{customMetadata:{[Nt]:n.cron},httpMetadata:{contentType:"application/json"}});try{await ka(o,y,e.backupRetain,n.cron)}catch(v){console.warn(`[lunora] backup ${h} was written, but retention failed:`,v)}},Da=(e,...t)=>{let r=e.cf;for(const n of t){if(typeof r!="object"||r===null)return;r=r[n]}return typeof r=="string"?r:void 0},ut={mtls:e=>Da(e,"tlsClientAuth","certVerified")==="SUCCESS"},Pa=e=>e===void 0||e===!1?()=>!1:e===!0?()=>!0:typeof e=="function"?e:(Object.hasOwn(ut,e)?ut[e]:void 0)??(()=>!1),Ua=e=>{if(e!==void 0)return()=>{};let t=!1;return()=>{t||(t=!0,console.warn('[lunora] Ignored an inbound `traceparent`, so this request starts a new trace instead of joining the caller\'s. That is the safe default: the header is caller-supplied, and trusting it lets any client choose which trace its spans and logs join. If this worker sits behind a gateway, service mesh, or Cloudflare Access that sets `traceparent` itself, set `trustInboundTraceContext: true` on createWorker() (or `"mtls"` to trust only edge-verified client certificates). Set it to `false` to keep this behaviour and silence this message.'))}},Na="/_lunora/admin/vector/indexes",qa="/_lunora/admin/vector/query",Ca=e=>{const{readJsonBody:t,requireAdminOption:r}=e,n=async i=>{j(i,"GET","Vector-indexes");const u=r(i,e.vectorIntrospector,{code:"VECTORS_NOT_CONFIGURED",message:"vector endpoints require a `vectorIntrospector` on the worker"});return Response.json({indexes:await u.listIndexes()},{headers:{"content-type":"application/json"},status:200})},o=async i=>{j(i,"POST","Vector-query");const u=r(i,e.vectorIntrospector,{code:"VECTORS_NOT_CONFIGURED",message:"vector endpoints require a `vectorIntrospector` on the worker"});if(u.queryIndex===void 0)throw new d("vector index querying is not enabled on this worker",{code:"VECTOR_QUERY_UNSUPPORTED",status:400});const l=await t(i);if(typeof l.name!="string"||l.name==="")throw new d("Vector-query request requires a `name` string",{code:"BAD_REQUEST",status:400});if(typeof l.text!="string"||l.text==="")throw new d("Vector-query request requires a `text` string",{code:"BAD_REQUEST",status:400});if(l.topK!==void 0&&(typeof l.topK!="number"||!Number.isInteger(l.topK)||l.topK<1))throw new d("Vector-query `topK` must be a positive integer",{code:"BAD_REQUEST",status:400});const f=await u.queryIndex({name:l.name,text:l.text,topK:l.topK});return Response.json(f,{headers:{"content-type":"application/json"},status:200})};return{[Na]:n,[qa]:o}},xa="/_lunora/admin/workflows/instances",Ba="/_lunora/admin/workflows/instance",$a="/_lunora/admin/workflows/status",ja={complete:!0,errored:!0,paused:!0,queued:!0,running:!0,terminated:!0,unknown:!0,waiting:!0,waitingForPause:!0},Ka=e=>e!==null&&Object.hasOwn(ja,e)?e:void 0,lt=(e,t)=>{const r=e.searchParams.get(t);if(r===null)return;const n=Number(r);return Number.isInteger(n)&&n>0?n:void 0},Ke=(e,t)=>{const r=e.searchParams.get(t);if(r===null||r==="")throw new d(`Workflows admin endpoint requires a \`${t}\` query parameter`,{code:"BAD_REQUEST",status:400});return r},ht=()=>{throw new d("Workflow inspection is unconfigured. Set CLOUDFLARE_ACCOUNT_ID + CLOUDFLARE_API_TOKEN in your .dev.vars to enable it.",{code:"WORKFLOWS_NOT_CONFIGURED",status:501})},La=e=>{const{assertAdmin:t,resolveWorkflowsClient:r}=e,n=async(u,l,f)=>{j(u,"GET","Workflows instances"),t(u);const b=r(l);if(!b)return Response.json({configured:!1,instances:[],page:1,perPage:0,totalCount:0});const E=Ke(f,"name"),y=Ka(f.searchParams.get("status"));return Response.json(await b.listInstances({page:lt(f,"page"),perPage:lt(f,"perPage"),status:y,workflowName:E}))},o=async(u,l,f)=>{j(u,"GET","Workflows instance"),t(u);const b=r(l);return b?Response.json(await b.getInstance({instanceId:Ke(f,"id"),workflowName:Ke(f,"name")})):ht()},i=async(u,l)=>{j(u,"POST","Workflows status"),t(u);const f=r(l);if(!f)return ht();const b=await u.json().catch(()=>{});if(typeof b?.name!="string"||b.name===""||typeof b.id!="string"||b.id==="")throw new d("Workflows status action requires string `name` and `id`",{code:"BAD_REQUEST",status:400});const{action:E}=b;if(E!=="pause"&&E!=="resume"&&E!=="terminate")throw new d("Workflows status action must be one of: pause, resume, terminate",{code:"BAD_REQUEST",status:400});return Response.json(await f.setInstanceStatus({action:E,instanceId:b.id,workflowName:b.name}))};return{[Ba]:o,[xa]:n,[$a]:i}},Fa={[Pt]:Ut,[$r]:Br},pt="/_lunora/rpc",Qa="/_lunora/rpc-batch",Ga="/_lunora/ws",Ee=(e,t,r)=>({resourceAttributes:wa(e,t),...r===void 0?{}:{waitUntil:r}}),ft=e=>e?.waitUntil?{waitUntil:t=>e.waitUntil?.(t)}:{},mt=e=>({spanId:e.spanId,traceFlags:e.traceFlags,traceId:e.traceId,...e.parentSpanId===void 0?{}:{parentSpanId:e.parentSpanId}}),Le=e=>{const{method:t}=e,r=e.headers.get("user-agent")??void 0;let n;try{n=new URL(e.url)}catch{return{method:t,userAgent:r}}const o=n.port===""?void 0:Number(n.port);return{host:n.hostname,method:t,path:n.pathname,port:Number.isNaN(o)?void 0:o,scheme:n.protocol.replace(":",""),userAgent:r}},wt="/_lunora/voice/",Ma="/_lunora/scheduler/dispatch",za="/_lunora/admin/cron-jobs/run",Wa="/_lunora/admin/ws-token",Ha="/_lunora/admin/",Ja="/_lunora/migrate",Va="/_lunora/status",Ya=e=>e.startsWith(Ha)||e===Ja,Xa=e=>{const t=e.headers.get("x-lunora-userid"),r=e.headers.get("x-lunora-identity");if(!(t===null&&r===null))return{...r===null?{}:{identity:r},...t===null?{}:{userId:t}}},Za="/api/auth",eo="__lunora_admin__:recordAuthEvent",to="__lunora_admin__:listPushSubscriptions",ro=["/sign-in","/sign-up","/callback"],no=(e,t)=>{const r=t.endsWith("/")?t.slice(0,-1):t;if(!e.startsWith(`${r}/`))return!1;const n=e.slice(r.length);return ro.some(o=>n===o||n.startsWith(`${o}/`))},Se=(e,t,r,n)=>{const o=ur(r),i=o?r.code:"INTERNAL_SERVER_ERROR",u=o?r.status:500,l=r instanceof Error?r.message:String(r);return{durationMs:t,error:{code:i,message:l,status:u},functionPath:e,ok:!1,...n.fanOut?{fanOut:{failed:0,shards:0,table:n.fanOut.table}}:{},...n.shardKey?{shardKey:n.shardKey}:{}}},ao=e=>{const{exp:t,expiresAtMs:r}=e;if(typeof r=="number"&&Number.isFinite(r))return r;if(typeof t=="number"&&Number.isFinite(t))return t*1e3},yt=e=>e.waitUntil?{waitUntil:t=>{e.waitUntil?.(t)}}:void 0,oo=e=>{const t=e?.queue;return typeof t=="string"&&t.length>0?t:"unknown"},ce=async(e,t,r)=>{const n={"content-type":"application/json"},o=e.headers.get("authorization"),i=e.headers.get("cookie"),u=e.headers.get("x-d1-bookmark"),l=e.headers.get("x-lunora-mutation-id"),f=e.headers.get("x-lunora-client-id"),b=e.headers.get("x-lunora-client-seq");o&&(n.authorization=o),i&&(n.cookie=i),u&&(n["x-d1-bookmark"]=u),l&&(n["x-lunora-mutation-id"]=l),f&&(n["x-lunora-client-id"]=f),b&&(n["x-lunora-client-seq"]=b);const E=e.headers.get("cf-connecting-ip");if(E&&(n["x-lunora-client-ip"]=E),!r)return{claims:null,headers:n,identity:null,userId:null};const y=await r(e,t);if(!y||typeof y.userId!="string"||y.userId.length===0)return{claims:null,headers:n,identity:null,userId:null};n["x-lunora-userid"]=pr(y.userId);const _=ao(y);_!==void 0&&(n["x-lunora-identity-exp"]=String(_));const{userId:h,...S}=y,O=Object.keys(S).length>0?S:null;return O&&(n["x-lunora-identity"]=fr(O)),{claims:O,headers:n,identity:y,userId:h}},so=new Set(["concat","first","groupBy","max","min","rank","sum","topK"]),io=e=>{if(e===void 0)return;if(!e||typeof e!="object")throw new d("RPC `fanOut` must be an object",{code:"BAD_REQUEST",status:400});const t=e;if(typeof t.table!="string"||t.table.length===0)throw new d("RPC `fanOut.table` must be a non-empty string",{code:"BAD_REQUEST",status:400});if(!t.merge||typeof t.merge!="object")throw new d("RPC `fanOut.merge` must be an object",{code:"BAD_REQUEST",status:400});const r=t.merge;if(typeof r.kind!="string"||!so.has(r.kind))throw new d("RPC `fanOut.merge.kind` is not a recognized merge strategy",{code:"BAD_REQUEST",status:400});if(r.kind==="topK"){if(typeof r.k!="number"||!Number.isInteger(r.k)||r.k<0)throw new d("RPC `fanOut.merge.k` must be a non-negative integer",{code:"BAD_REQUEST",status:400});if(typeof r.by!="string"||r.by.length===0)throw new d("RPC `fanOut.merge.by` must be a non-empty string",{code:"BAD_REQUEST",status:400})}return t},co=(e,t)=>{e?.LUNORA_DEBUG_RPC&&console.warn(`[lunora:rpc] ${t.fanOut?"fan-out":`shard=${t.shardKey??"(root)"}`} ${t.functionPath}`)},gt=(e,t)=>{const r=t.functions?.[e.functionPath]?.x402;if(r){if(e.fanOut)throw new d("a paid (`.x402`) function cannot be fanned out",{code:"BAD_REQUEST",status:400});if(!t.x402Charge)throw new d(`function "${e.functionPath}" is marked paid (.x402) but no x402Charge gate is configured on the worker`,{code:"MISCONFIGURED",status:500});return r}},uo=async e=>{const t=await St(e);let r;try{r=JSON.parse(t)}catch{throw new d("RPC body must be valid JSON",{code:"BAD_REQUEST",status:400})}if(!r||typeof r!="object"||typeof r.functionPath!="string")throw new d("RPC envelope is missing `functionPath`",{code:"BAD_REQUEST",status:400});const n=r;if(n.args!==void 0&&Ot(n.args,"RPC"),n.shardKey!==void 0&&typeof n.shardKey!="string")throw new d("RPC `shardKey` must be a string",{code:"BAD_REQUEST",status:400});const o=r,i=io(o.fanOut),u=o.args??{};if(i&&o.functionPath.startsWith("__lunora_relation__:")){const l=u.table;if(typeof l=="string"&&l!==i.table)throw new d("RPC `args.table` must match the authorized `fanOut.table` for a relation fan-out",{code:"BAD_REQUEST",status:400});u.table=i.table}return{args:u,fanOut:i,functionPath:o.functionPath,shardKey:o.shardKey}},oe=async(e,t,r)=>ye(e,t).fetch(r),Oe=new Map,lo=5e3,ho=4096,po=async(e,t)=>{const r=Date.now(),n=Oe.get(t);if(n!==void 0&&n.expiresMs>r)return n.relayCount;n!==void 0&&Oe.delete(t);let o=0;try{const i=await ye(e,t).fetch(new Request("https://shard.internal/_lunora/route"));if(i.ok){const u=(await i.json()).relayCount;typeof u=="number"&&u>0&&(o=Math.floor(u))}}catch{o=0}return Rt(Oe,ho),Oe.set(t,{expiresMs:r+lo,relayCount:o}),o},fo=(e,t)=>{if(!(e===null||typeof e!="object"))return Object.entries(e).find(([,r])=>r===t)?.[0]},Te=(e,t,r)=>new Request("https://shard.internal/rpc",{body:JSON.stringify({args:t,functionPath:e}),headers:r,method:"POST"}),mo=["x-lunora-userid","x-lunora-identity","x-lunora-identity-exp"],bt=(e,t)=>{for(const r of mo){e.delete(r);const n=t[r];n!==void 0&&e.set(r,n)}},wo=async(e,t,r)=>e.length===0||r.length===0?!1:Fe(await vt(e,t),r),_t=(e,t)=>{if(!t||t.length===0)return!1;const r=e.headers.get("authorization");if(!r)return!1;const[n,...o]=r.split(" ");return n?.toLowerCase()!=="bearer"?!1:Fe(t,o.join(" ").trim())},yo=async(e,t,r)=>{if(!t||t.length===0)return!1;const n=new URL(e.url).searchParams.get("token");return n===null?!1:await nn(t,n)?!0:r?!1:Fe(t,n)},go=(e,t)=>{if(t===null||typeof t!="object"&&typeof t!="function")return;const r=t;if(typeof r.prepare=="function"&&typeof r.batch=="function"&&typeof r.dump=="function")return Ar(`d1:${e}`,t);if(typeof r.list=="function"&&typeof r.head=="function"&&typeof r.createMultipartUpload=="function")return Ne(`r2:${e}`,!0);if(typeof r.send=="function"&&typeof r.sendBatch=="function"&&typeof r.get!="function")return Ne(`queue:${e}`,!0);if(typeof r.connectionString=="string")return Ne(`hyperdrive:${e}`,!0)},qt=e=>{const t=Pa(e.trustInboundTraceContext),r=Ua(e.trustInboundTraceContext),n=e.defaultShardKey??"__root__",o=vr(e.resolveIdentity,e.identity),i=Ye(e.shardDO,e.jurisdiction),u=e.schedulerDO===void 0?void 0:Ye(e.schedulerDO,e.jurisdiction);let l;const f=()=>e.adminToken??l;let b;const E=()=>e.requireEphemeralWsToken??b??!0,y=a=>{const s=a??{};if(b===void 0&&e.requireEphemeralWsToken===void 0){const c=s.LUNORA_REQUIRE_EPHEMERAL_WS_TOKEN;typeof c=="string"&&c.length>0&&(b=en(c,!0))}if(l!==void 0||e.adminToken!==void 0)return;const p=s.LUNORA_ADMIN_TOKEN;typeof p=="string"&&p.length>0&&(l=p)},_=new WeakSet,h=a=>_t(a,f())||_.has(a),S=async(a,s)=>{const p=await ce(a,s,e.resolveIdentity);if(_.has(a)&&p.headers.authorization===void 0){const c=f();c!==void 0&&(p.headers.authorization=`Bearer ${c}`)}return p};let O=!1;const A=a=>{if(!e.allowUnauthenticatedShardAccess){const s=a==="fan-out"?"authorizeFanOut":"authorizeShard";throw new d(`${a} access is default-denied: configure \`${s}\` on the worker, or set \`allowUnauthenticatedShardAccess: true\` to explicitly allow unauthenticated ${a} access (relying solely on per-row RLS).`,{code:a==="fan-out"?"FORBIDDEN_FANOUT":"FORBIDDEN_SHARD",status:403})}O||(O=!0,console.warn([`[lunora] SECURITY: serving ${a} access with \`allowUnauthenticatedShardAccess: true\` and no \`authorizeShard\`/\`authorizeFanOut\` — `,"any caller (including unauthenticated ones) can target any shard / fan out across the table. ","This is safe only if every table is protected by per-row RLS. Configure `authorizeShard`/`authorizeFanOut` to gate it."].join("")))},v=async(a,s,p=!0)=>{if(e.authorizeShard){if(!await e.authorizeShard(a,s))throw new d("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else p&&s!==n&&A("shard")},U=sa({defaultShard:n,forwardToShard:oe,isAdmin:h,queryCoordinator:e.queryCoordinator,resolveForwardContext:S,shardDO:i}),k=async(a,s,p,c,m)=>{await v(null,p,!1);const g={"content-type":"application/json","x-lunora-system":"1"};return m?.userId!==void 0&&m.userId.length>0&&(g["x-lunora-userid"]=m.userId),m?.identity!==void 0&&m.identity.length>0&&(g["x-lunora-identity"]=m.identity),c!==void 0&&c.length>0&&(g["x-lunora-mutation-id"]=c),oe(i,p,Te(a,s,g))},K=async(a,s,p,c)=>{const m=p?.[a];if(!m||typeof m.create!="function")throw new d(`${c} targets workflow binding "${a}", which is not bound on env`,{code:"CRON_JOB_FAILED",status:500});if(Qr(s))throw new d(`${c} params ${Gr}`,{code:"BAD_REQUEST",status:400});await m.create({params:s})},$=async(a,s)=>{if(a.workflow){await K(a.workflow,a.args??{},s,`cron job "${a.name}"`);return}if(a.functionPath===void 0)throw new d(`cron job "${a.name}" has neither a function target nor a workflow target`,{code:"CRON_JOB_FAILED",status:500});const p=await k(a.functionPath,a.args??{},a.shardKey??n);if(!p.ok)throw new d(`cron job "${a.name}" (${a.functionPath}) failed with shard status ${String(p.status)}`,{code:"CRON_JOB_FAILED",status:500})},V=async(a,s,p,c)=>{const m=e.cronJobs?.[a];if(m)for(const g of m)try{await $(g,s)}catch(D){p.push(c(D))}},N=async(a,s)=>{if(!h(a))throw new d("admin endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403});if(j(a,"POST","cron-jobs run"),!e.cronJobs)throw new d("cron-jobs run endpoint requires a `cronJobs` map on the worker",{code:"CRON_JOBS_NOT_CONFIGURED",status:400});const p=await Z(a),c=typeof p.name=="string"?p.name:"";if(c==="")throw new d("cron-jobs run endpoint requires a job `name`",{code:"BAD_REQUEST",status:400});const m=Object.values(e.cronJobs).flat().find(g=>g.name===c);if(!m)throw new d(`no cron job named "${c}" is registered`,{code:"CRON_JOB_NOT_FOUND",status:404});return await $(m,s),Response.json({name:c,ran:!0},{status:200})},Q=async a=>{const s=typeof a.pool=="string"&&a.pool.length>0?a.pool:void 0;if(!s||!u||typeof a.id!="string")return;const p=typeof a.instanceName=="string"&&a.instanceName.length>0?a.instanceName:"default";try{await ye(u,p).fetch(new Request("https://scheduler.internal/complete",{body:JSON.stringify({id:a.id,pool:s}),headers:{"content-type":"application/json"},method:"POST"}))}catch{}},G=async(a,s)=>{j(a,"POST","Scheduler dispatch");const p=await St(a),c=s??{},m=typeof c.LUNORA_SCHEDULER_SECRET=="string"?c.LUNORA_SCHEDULER_SECRET:void 0,g=e.adminToken??(typeof c.LUNORA_ADMIN_TOKEN=="string"?c.LUNORA_ADMIN_TOKEN:void 0),D=a.headers.get("x-lunora-scheduler-signature");let w=!1;if(D&&m?w=await wo(m,p,D):g&&(w=_t(a,g)),!w)throw new d("Scheduler dispatch requires a valid signature or admin bearer",{code:"FORBIDDEN",status:403});let R;try{R=JSON.parse(p)}catch{throw new d("Scheduler dispatch body must be valid JSON",{code:"BAD_REQUEST",status:400})}const T=R??{},q=T.args??{};if(typeof T.workflow=="string"&&T.workflow.length>0)return await K(T.workflow,q,s,"scheduled workflow"),Response.json({ok:!0},{status:200});if(typeof T.functionPath!="string"||T.functionPath.length===0)throw new d("Scheduler dispatch is missing `functionPath`",{code:"BAD_REQUEST",status:400});const C=typeof T.shardKey=="string"&&T.shardKey.length>0?T.shardKey:n,B=typeof T.id=="string"&&T.id.length>0?T.id:void 0,X=Xa(a),ee=await k(T.functionPath,q,C,B,X);return await Q(T),ee},x=a=>{if(!h(a))throw new d("admin endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403})},L=(a,s,p)=>{if(x(a),s===void 0)throw new d(p.message,{code:p.code,status:400});return s},Y=cn({assertAdmin:x,getReader:()=>e.authAuditReader}),H=async(a,s)=>{x(a);const p=e.notifySubscriptionStore;if(p===void 0)return Response.json({subscriptions:[]},{headers:{"content-type":"application/json"},status:200});const c=s?.kind,m=s?.userId,g=s?.limit,D=c==="fcm"||c==="web-push"?c:void 0,w=typeof m=="string"&&m!==""?m:void 0,R=typeof g=="number"&&Number.isFinite(g)?Math.trunc(g):0,T=R>0?Math.min(R,1e3):1e3,q=(await p.list({kind:D,limit:T,userId:w})).filter(C=>D!==void 0&&C.kind!==D?!1:w===void 0||(C.userId??null)===w).map(({keys:C,token:B,...X})=>X);return Response.json({subscriptions:q},{headers:{"content-type":"application/json"},status:200})},ne=async(a,s)=>{if(!s.fanOut){if(s.functionPath===dn)return Y(a,s.args??{});if(s.functionPath===to)return H(a,s.args)}},he=On({applyGlobals:e.applyGlobals,assertAdmin:x,exportCursorStore:e.exportCursorStore,exportSinks:e.exportSinks,knownTables:()=>[],queryCoordinator:e.queryCoordinator,requireAdminOption:L,resolveForwardContext:S,shardDO:i,streamExportRows:(a,s,p,c)=>Dt(e,a,s,p,c,i),streamingImport:(a,s)=>Dn(a,e,s,i),syncGlobals:e.syncGlobals}),ae=(a,s)=>{const p=a.searchParams.get(s);return p===null||p===""?void 0:p},pe=a=>{const s=new URL(a.url),p=s.searchParams.get("limit"),c=s.searchParams.get("offset"),m=p===null?void 0:Number.parseInt(p,10),g=c===null?void 0:Number.parseInt(c,10);return{limit:m!==void 0&&Number.isFinite(m)&&m>=0?m:void 0,offset:g!==void 0&&Number.isFinite(g)&&g>=0?g:void 0}},_e=()=>{if(u===void 0)throw new d("scheduled endpoints require a `schedulerDO` namespace on the worker",{code:"SCHEDULER_NOT_CONFIGURED",status:400});return u},ve=Oa({checkWsAdmin:async a=>h(a)||yo(a,f(),E()),requireSchedulerNamespace:_e,resolveSchedulerStub:a=>(x(a),ye(_e(),e.schedulerInstanceName??"default")),schedulerInstanceName:e.schedulerInstanceName??"default"}),se=La({assertAdmin:x,resolveWorkflowsClient:e.workflowsClient??(()=>{})}),Ct=jr({assertAdmin:x,parsePaging:pe,queryParameter:ae,readBodyBytes:Er,requireAdminOption:L,storage:{storageBuckets:e.storageBuckets,storageDelete:e.storageDelete,storageDownload:e.storageDownload,storageList:e.storageList,storageSignedUrl:e.storageSignedUrl,storageUpload:e.storageUpload}}),xt=Ca({readJsonBody:Z,requireAdminOption:L,vectorIntrospector:e.vectorIntrospector}),Bt=Mn({kvIntrospector:e.kvIntrospector,readJsonBody:Z,requireAdminOption:L}),$t=kr({logArchive:e.logArchive,readJsonBody:Z,requireAdminOption:L}),jt=Fn({assertAdmin:x,options:{cronJobs:e.cronJobs,functions:e.functions,globalIntrospector:e.globalIntrospector,openApiSpec:e.openApiSpec,openRpcSpec:e.openRpcSpec},parsePaging:pe,queryParameter:ae,requireAdminOption:L}),Kt=a=>{const s=[],p=i??a?.SHARD;if(p!==void 0&&s.push(Tr("durable-object:default",p,n)),e.health?.disableBindingProbes!==!0)for(const[c,m]of Object.entries(a??{})){const g=go(c,m);g!==void 0&&s.push(g)}for(const c of e.health?.probes??[])s.push(c);return s},Lt=Or({appName:e.health?.appName,appVersion:e.health?.appVersion,auth:e.health?.auth??"public",cacheTtlMs:e.health?.cacheTtlMs,isAdmin:h,resolveProbes:Kt}),Ft=a=>{const s=e.schedulerInstanceName??"default",p=()=>ye(a,s),c=async(w,R)=>{const T=await p().fetch(new Request(`https://scheduler.internal${w}`,R));if(!T.ok)throw new d(`ctx.scheduler: SchedulerDO ${w} failed (${String(T.status)}): ${await T.text()}`,{code:"INTERNAL",status:500});return await T.json()},m=async(w,R)=>await c(w,{body:JSON.stringify(R),headers:{"content-type":"application/json"},method:"POST"}),g=w=>{const R=w;if(R==null)throw new d("ctx.scheduler: target is required — pass a reference from the generated `internal` / `workflows` / `agents`",{code:"BAD_REQUEST",status:400});if(typeof R.binding=="string"&&R.binding.length>0)return{workflow:R.binding};if(typeof R.__lunoraRef=="string")return{functionPath:R.__lunoraRef};throw new d("ctx.scheduler: expected a reference from the generated `internal` / `workflows` / `agents` — a bare function-path string is refused here, because an HTTP action can be reached unauthenticated",{code:"BAD_REQUEST",status:400})},D=async(w,R,T={})=>{const{id:q}=await m("/schedule",{args:T,scheduledFor:w,...g(R)});return q};return{cancel:async w=>await m("/cancel",{id:w}),get:async w=>await c(`/get?id=${encodeURIComponent(w)}`,{method:"GET"}),list:async()=>await c("/list",{method:"GET"}),runAfter:async(w,R,T)=>{if(!Number.isFinite(w)||w<0)throw new d("ctx.scheduler.runAfter: `delayMs` must be a non-negative finite number",{code:"BAD_REQUEST",status:400});return await D(Date.now()+w,R,T)},runAt:async(w,R,T)=>{if(!Number.isFinite(w))throw new d("ctx.scheduler.runAt: `timestampMs` must be a finite epoch-millisecond number",{code:"BAD_REQUEST",status:400});return await D(w,R,T)}}},Qt=async(a,s,p)=>{const{claims:c,headers:m,userId:g}=await ce(a,s,o),D=async(w,R={})=>{const T=w.__lunoraRef;if(typeof T!="string")throw new d("ctx.run*: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});const q=Te(T,R,{...m,"x-lunora-system":"1"}),C=await oe(i,n,q),B=await C.json();if(B.error)throw new d(B.error.message??"shard RPC failed",{code:B.error.code??"INTERNAL",status:C.status});return B.result};return{auth:{getIdentity:()=>Promise.resolve(c),userId:g},cache:p.cache,fetch:globalThis.fetch.bind(globalThis),runAction:D,runMutation:D,runQuery:D,...u===void 0?{}:{scheduler:Ft(u)},...e.storage===void 0?{}:{storage:Fr(e.storage(s))}}},Gt=async(a,s,p)=>{if(!e.httpRouter)return;const c=await Qt(a,s,p);try{return await e.httpRouter.fetch(a,{...s,__lunoraCtx:c},p)}catch(m){return console.error("[lunora] httpRouter (SSR) handler threw:",m),new Response("Internal Server Error",{status:500})}},Mt=async(a,s,p)=>{if(a.headers.get("Upgrade")!=="websocket")throw new d("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});const c=Ze(a,ie);if(c)return c;const m=p.searchParams.get("shard")??n,{headers:g,identity:D}=await ce(a,s,o);await v(D,m);const w=new Headers(a.headers),R=[...w.keys()];for(const q of R)q.startsWith("x-lunora-")&&w.delete(q);bt(w,g);const T=fo(s,e.shardDO);if(T!==void 0){w.set("x-lunora-shard-binding",T);const q=await po(i,m);if(q>0){const C=Yr(m,Math.floor(Math.random()*q));return oe(i,C,new Request(a,{headers:w}))}}return oe(i,m,new Request(a,{headers:w}))},zt=async(a,s,p)=>{const{voiceAgents:c}=e;if(c===void 0)return new Response("Not found",{status:404});if(a.headers.get("Upgrade")!=="websocket")return new Response("Expected a WebSocket upgrade",{headers:{allow:"GET"},status:426});const m=Ze(a,ie);if(m)return m;let g;try{g=decodeURIComponent(p.pathname.slice(wt.length))}catch{return new Response("Unknown voice agent",{status:404})}const D=Object.hasOwn(c,g)?c[g]:void 0;if(D===void 0)return new Response("Unknown voice agent",{status:404});const w=p.searchParams.get("threadKey");if(w===null||w.length===0)return new Response("Missing threadKey",{status:400});const{headers:R,identity:T}=await ce(a,s,o);if(e.authorizeShard){if(!await e.authorizeShard(T,w))return new Response("Forbidden",{status:403})}else A("shard");const q=new Headers(a.headers);for(const C of q.keys())C.startsWith("x-lunora-")&&q.delete(C);return bt(q,R),oe(D,w,new Request(a,{headers:q}))},Wt=async(a,s,p)=>{if(e.authorizeFanOut){if(!await e.authorizeFanOut(p,a.table,s))throw new d("Forbidden fan-out",{code:"FORBIDDEN_FANOUT",status:403});return}if(s.startsWith("__lunora_relation__:"))throw new d("reverse cross-backend relation reads (`__lunora_relation__:*`) require `authorizeFanOut` to be configured on the worker",{code:"FORBIDDEN_FANOUT",status:403});if(e.authorizeShard)throw new d("Fan-out requires `authorizeFanOut` to be configured on the worker when `authorizeShard` is set",{code:"FORBIDDEN_FANOUT",status:403});A("fan-out")},Re=async(a,s)=>{if(!(!a.fanOut&&a.functionPath.startsWith("__lunora_admin__:"))){if(a.fanOut){await Wt(a.fanOut,a.functionPath,s);return}await v(s,a.shardKey??n)}},ke=async(a,s,p,c,m,g)=>{const D=Date.now(),{observability:w,sampling:R}=e,T=Le(a),{decision:q,ignoredUpstream:C,trace:B}=fa(a,{...R===void 0?{}:{sampling:R},trustInbound:t(a)});C&&r();const X={...m,"x-lunora-sample-errors":q.keepErrors?"1":"0"};ma(B,X);const ee=Te(s,p,X);try{const F=await oe(i,c,ee);return de(w,{...T,...mt(B),durationMs:Date.now()-D,functionPath:s,ok:F.ok,shardKey:c,...F.ok?{}:{error:{code:"SHARD_ERROR",message:`shard returned ${String(F.status)}`,status:F.status}}},g,void 0,{isTraced:B.sampled,keepErrors:q.keepErrors}),F}catch(F){throw de(w,{...T,...mt(B),...Se(s,Date.now()-D,F,{shardKey:c})},g,void 0,{isTraced:B.sampled,keepErrors:q.keepErrors}),F}},Ht=a=>{if(a.fanOut&&a.shardKey)throw new d("RPC envelope cannot set both `shardKey` and `fanOut`",{code:"BAD_REQUEST",status:400});if(!a.fanOut&&a.functionPath.startsWith("__lunora_relation__:"))throw new d("`__lunora_relation__:*` is a fan-out-only reserved RPC and cannot be dispatched to a single shard",{code:"FORBIDDEN",status:403});if(a.fanOut&&!e.queryCoordinator)throw new d("RPC envelope set `fanOut` but no `queryCoordinator` is configured on the worker",{code:"BAD_REQUEST",status:400})},Jt=async(a,s,p)=>{j(a,"POST","RPC");const c=await uo(a);co(s,c),Ht(c);const m=await ne(a,c);if(m!==void 0)return m;const{headers:g,identity:D}=await ce(a,s,o);await Re(c,D);const w=gt(c,e);{const R=Date.now(),{observability:T}=e,q=Le(a),C=Ee(s,a,p&&(ee=>p.waitUntil?.(ee)));if(c.fanOut){const ee=e.queryCoordinator;if(!ee)throw new d("RPC envelope set `fanOut` but no `queryCoordinator` is configured on the worker",{code:"BAD_REQUEST",status:400});try{const F=await ee.fanOut(i,{args:c.args??{},fanOut:c.fanOut,functionPath:c.functionPath,headers:g});return de(T,{durationMs:Date.now()-R,fanOut:{failed:F.failed,shards:F.ok+F.failed,table:c.fanOut.table},functionPath:c.functionPath,...q,ok:!0},C),Response.json(F,{headers:{"content-type":"application/json"},status:200})}catch(F){throw de(T,{...Se(c.functionPath,Date.now()-R,F,{fanOut:{table:c.fanOut.table}}),...q},C),F}}const B=c.shardKey??n,X=()=>ke(a,c.functionPath,c.args??{},B,g,C);return w&&e.x402Charge?e.x402Charge(a,{functionPath:c.functionPath,price:w.price},X,ft(p)):X()}},Vt=async(a,s,p)=>{j(a,"POST","RPC batch");const c=await Z(a),{calls:m}=c;if(!Array.isArray(m))throw new d("RPC batch `calls` must be an array",{code:"BAD_REQUEST",status:400});const{headers:g,identity:D}=await ce(a,s,o),w=ln(m,n);for(const M of w.values())for(const z of M)if(e.functions?.[z.functionPath]?.x402)throw new d(`paid (\`.x402\`) function "${z.functionPath}" cannot be called in a batch; dispatch it individually over ${pt}`,{code:"BAD_REQUEST",status:400});await Promise.all([...w.entries()].flatMap(([M,z])=>z.map(re=>Re({functionPath:re.functionPath,shardKey:M},D))));const{observability:R}=e,T=Ee(s,a,p&&(M=>p.waitUntil?.(M))),q=Le(a),C=[],B=[],X=(M,z,re,ue)=>({body:{error:{code:re,message:ue}},id:M.id,status:z}),ee=(M,z,re,ue,fe)=>{for(const W of M)de(R,fe(W),T),C.push(X(W,z,re,ue))},F=(M,z,re,ue,fe)=>{for(const W of M){const me=ue.get(W.id)??fe,ge=me<400;de(R,{durationMs:re,functionPath:W.functionPath,...q,ok:ge,shardKey:z,...ge?{}:{error:{code:"SHARD_ERROR",message:`batched call returned ${String(me)}`,status:me}}},T)}};await Promise.all([...w.entries()].map(async([M,z])=>{const re=new Headers(g);re.set("content-type","application/json");const ue=new Request("https://shard.internal/rpc-batch",{body:JSON.stringify({calls:z}),headers:re,method:"POST"}),fe=Date.now();let W;try{W=await oe(i,M,ue)}catch(J){const Ue=Date.now()-fe,{body:He}=lr(J,{fallbackCode:"SHARD_UNAVAILABLE",redactedMessage:"shard unavailable"});ee(z,502,He.code,He.message,cr=>({...Se(cr.functionPath,Ue,J,{shardKey:M}),...q}));return}const me=Date.now()-fe,ge=W.headers.get("x-d1-bookmark");ge&&B.push(ge);let De;try{De=await W.json()}catch{const J=`shard batch returned a non-JSON response (${String(W.status)})`;ee(z,W.status,"SHARD_ERROR",J,Ue=>({durationMs:me,error:{code:"SHARD_ERROR",message:J,status:W.status},functionPath:Ue.functionPath,...q,ok:!1,shardKey:M}));return}const Pe=Array.isArray(De.results)?De.results:[],ir=new Map(Pe.map(J=>[J.id,J.status??W.status])),dr=new Set(Pe.map(J=>J.id));F(z,M,me,ir,W.status),C.push(...Pe);for(const J of z)dr.has(J.id)||C.push(X(J,W.status,"SHARD_ERROR",`shard batch omitted result for call ${String(J.id)}`))}));const ze={"content-type":"application/json"},[We]=B;return B.length===1&&We!==void 0&&(ze["x-d1-bookmark"]=We),Response.json({results:C},{headers:ze,status:200})},Yt=async(a,s,p,c={},m={})=>{try{const g=p.__lunoraRef;if(typeof g!="string")throw new d("serverQuery: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});const{headers:D,identity:w}=await ce(a,s,o);await Re({functionPath:g,shardKey:m.shardKey},w);const R=m.shardKey??n,T=Ee(s,a,m.waitUntil);return await ke(a,g,c,R,D,T)}catch(g){return Je(g)}},Ge=async(a,s,p)=>{const{observability:c}=e,m=Date.now(),g=Ae(16),D=Ae(8),w=yt(s);try{const R=await p();return de(c,{durationMs:Date.now()-m,functionPath:a,ok:!0,spanId:D,traceId:g},w),R}catch(R){throw de(c,{...Se(a,Date.now()-m,R,{}),spanId:D,traceId:g},w),R}finally{Ve(c,w)}},Xt=async(a,s,p)=>{y(s);const c=[],m=w=>w instanceof Error?w:new Error(String(w)),g=e.crons?.[a.cron];if(g)try{await g(a,s,p)}catch(w){c.push(m(w))}if(await V(a.cron,s,c,m),e.backupStore&&e.backupCron!==void 0&&e.backupCron===a.cron)try{await Ia(e,i,f(),a)}catch(w){c.push(m(w))}const[D]=c;if(c.length===1&&D)throw D;if(c.length>1)throw new AggregateError(c,`scheduled("${a.cron}") had ${String(c.length)} failure(s)`)},Zt=async(a,s)=>{try{const p=a??{},c=e.adminToken??(typeof p.LUNORA_ADMIN_TOKEN=="string"?p.LUNORA_ADMIN_TOKEN:void 0);if(!c||c.length===0)return;await oe(i,n,Te(eo,{outcome:s},{authorization:`Bearer ${c}`,"content-type":"application/json"}))}catch{}},er=async(a,s,p,c)=>{if(!e.authHandler)return;const m=await e.authHandler(a);if(!m)return;const g=e.authBasePath??Za;return no(p.pathname,g)&&c.waitUntil?.(Zt(s,m.status>=400?"fail":"ok")),m},tr=async({args:a,env:s,functionPath:p,request:c,shardKey:m,waitUntil:g})=>{Ot(a,"REST");const D={functionPath:p,...m===void 0?{}:{shardKey:m}},{headers:w,identity:R}=await ce(c,s,o);await Re(D,R);const T=m??n,q=Ee(s,c,g),C=()=>ke(c,p,a,T,w,q),B=gt(D,e);return B&&e.x402Charge?e.x402Charge(c,{functionPath:p,price:B.price},C,ft({waitUntil:g})):C()},rr=Rr({functions:e.functions??{},invoke:tr,readJsonBody:Z,...e.restRateLimit?{rateLimit:e.restRateLimit}:{}}),Ie=e.routes!==void 0&&Object.keys(e.routes).length>0?e.routes:void 0,nr={[Va]:a=>a.method!=="GET"&&a.method!=="HEAD"?new Response(void 0,{headers:{allow:"GET, HEAD"},status:405}):Response.json({ok:!0},{headers:{"cache-control":"no-store"}}),[Ga]:(a,s,p)=>Mt(a,s,p),[pt]:(a,s,p,c)=>Jt(a,s,c),[Qa]:(a,s,p,c)=>Vt(a,s,c),[Ma]:(a,s)=>G(a,s),[za]:(a,s)=>N(a,s),[Wa]:async a=>{j(a,"POST","ws-token"),x(a);const s=f();if(s===void 0)throw new d("ws-token minting requires a configured admin token",{code:"ADMIN_TOKEN_NOT_CONFIGURED",status:400});const p=await rn(s);return Response.json(p,{headers:{"cache-control":"no-store"}})},...U,...he,...ve,...se,...Ct,...xt,...Bt,...$t,...jt,...Lt,...rr,...sn({assertAdmin:x,getAuthAdmin:()=>e.authAdmin,parsePaging:pe,queryParameter:ae,readJsonBody:Z})};let ie=Xe(e.security),Me=!1;const ar=a=>{Me||(Me=!0,ie=Xe(e.security,a??{}))},or=async(a,s)=>{if(!(e.adminGate===void 0||!Ya(s)))try{await e.adminGate(a)&&_.add(a)}catch{}},sr=async(a,s,p)=>{const c=new URL(a.url);if(a.method==="POST"||a.method==="PUT"){const w=Number(a.headers.get("content-length")??""),R=Fa[c.pathname]??Et;if(Number.isFinite(w)&&w>R)throw new d("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413})}const m=await er(a,s,c,p);if(m)return m;if(Ie){const w=`${a.method} ${c.pathname}`,R=Ie[w]??Ie[c.pathname];if(R)return R(a,s,p)}const g=nr[c.pathname];return g?(await or(a,c.pathname),g(a,s,c,p)):e.voiceAgents!==void 0&&c.pathname.startsWith(wt)?zt(a,s,c):await Gt(a,s,p)||new Response("Not found",{status:404})};return{async fetch(a,s,p){e.passThroughOnException&&p.passThroughOnException?.(),ar(s),y(s);const c=Kr(a,ie);if(c)return c;const m=Lr(a,ie);if(m)return qe(m,a,ie);try{const g=await sr(a,s,p);return qe(g,a,ie)}catch(g){return qe(Je(g),a,ie)}finally{Ve(e.observability,yt(p))}},async queue(a,s,p){await Ge(`queue:${oo(a)}`,p,async()=>{await e.queue?.(a,s,p)})},async scheduled(a,s,p){await Ge(`cron:${a.cron}`,p,async()=>{await Xt(a,s,p)})},serverQuery:Yt}},bo=e=>qt(e),_o=e=>typeof e=="function"?{fetch:e}:e,Ro=e=>!!(e.crons??e.cronJobs??e.backupCron),Ko=(e,t)=>{const r=_o(e),n=typeof e=="object"&&typeof e.scheduled=="function"?e.scheduled:void 0,o=u=>{const l=bo({...u,httpRouter:r});return n!==void 0&&!Ro(u)?{...l,scheduled:async(f,b,E)=>{await n(f,b,E)}}:l};if(typeof t!="function")return o(t);const i=t;return{fetch:(u,l,f)=>o(i(l)).fetch(u,l,f),queue:(u,l,f)=>o(i(l)).queue?.(u,l,f)??Promise.resolve(),scheduled:(u,l,f)=>o(i(l)).scheduled(u,l,f),serverQuery:(u,l,f,b,E)=>o(i(l)).serverQuery(u,l,f,b,E)}},Eo=(e,t)=>{if(typeof e=="function")return e(t);const r=e.shardDO??t?.SHARD;if(!r)throw new d("@lunora/runtime: no shard Durable Object namespace found. Bind `SHARD` in wrangler.jsonc, or pass `createLunoraHandler({ shardDO: env.MY_SHARD })`.");return{...e,shardDO:r}},Lo=(e={})=>(t,r,n)=>qt(Eo(e,r)).fetch(t,r,n??hr),Fo=e=>e;export{dn as GET_AUTH_AUDIT_LOG_OP,hr as NOOP_EXECUTION_CONTEXT,Mo as composeIdentityResolvers,bo as composeWorker,Lo as createLunoraHandler,qt as createWorker,Fo as defineRpcEnvelope,po as probeRelayCount,Eo as resolveLunoraOptions,zo as routeIdentityResolvers,Ko as withFrameworkWorker};