@lunora/runtime 1.0.0-alpha.62 → 1.0.0-alpha.63
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 +8 -1
- package/dist/index.d.ts +8 -1
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/BACKUP_KEY_PREFIX-BOtSu-_3.mjs +1 -0
- package/dist/packem_shared/DEFAULT_LOG_COLUMNS-B8FFcwsX.mjs +1 -0
- package/dist/packem_shared/DEFAULT_REGISTRY_CACHE_TTL_MS-D5O7elXI.mjs +1 -0
- package/dist/packem_shared/HEALTH_PATH-jZsuCmSs.mjs +1 -0
- package/dist/packem_shared/LOG_ARCHIVE_PATH-jgHjdsz2.mjs +1 -0
- package/dist/packem_shared/{LunoraError-ByasbDmd.mjs → LunoraError-DksAgIpa.mjs} +1 -1
- package/dist/packem_shared/STORAGE_UPLOAD_MAX_BODY_BYTES-BqyO-1l6.mjs +1 -0
- package/dist/packem_shared/analyticsEngineSink-D7qu89f2.mjs +1 -0
- package/dist/packem_shared/applyJurisdiction-C0ddU7Tg.mjs +1 -0
- package/dist/packem_shared/applyRestCache-DZiEz7Db.mjs +1 -0
- package/dist/packem_shared/argsFromQuery-BASPTYw0.mjs +1 -0
- package/dist/packem_shared/base64-CMlwEPti.mjs +1 -0
- package/dist/packem_shared/composeIdentityResolvers-DdDFfuTV.mjs +1 -0
- package/dist/packem_shared/composeWorker-BtABY25U.mjs +6 -0
- package/dist/packem_shared/createCrossShardRelationCapabilities-DgQYQzd1.mjs +1 -0
- package/dist/packem_shared/createKvCursorStore-VOd1DFsf.mjs +3 -0
- package/dist/packem_shared/createQueryCoordinator-CnNyazLX.mjs +1 -0
- package/dist/packem_shared/createShardClient-Yb6_Mzd6.mjs +1 -0
- package/dist/packem_shared/decorateResponse-D3NzOIvB.mjs +1 -0
- package/dist/packem_shared/emitLogEvent-qlixolZi.mjs +1 -0
- package/dist/packem_shared/evict-oldest-BNXsKx4s.mjs +1 -0
- package/dist/packem_shared/identity-header-JF5q3H5w.mjs +1 -0
- package/dist/packem_shared/memoizeIdentity-DVd9yDW1.mjs +1 -0
- package/dist/packem_shared/method-guard-BG_vJNTl.mjs +1 -0
- package/dist/packem_shared/observability-vDK-rMbs.mjs +1 -0
- package/dist/packem_shared/otlp-resource-B4Yylr0V.mjs +1 -0
- package/dist/packem_shared/pipeline-log-reader-BGrl66P5.mjs +1 -0
- package/dist/packem_shared/rest-cache-D6nWkevc.mjs +1 -0
- package/dist/packem_shared/rest-routes-3l718ENH.mjs +1 -0
- package/dist/packem_shared/toAirbyteMessages-Cy3uaySU.mjs +1 -0
- package/package.json +4 -4
- package/dist/packem_shared/BACKUP_KEY_PREFIX-DhFUE3VL.mjs +0 -1
- package/dist/packem_shared/DEFAULT_LOG_COLUMNS-CzsNuTZj.mjs +0 -1
- package/dist/packem_shared/DEFAULT_REGISTRY_CACHE_TTL_MS-DqWtiFAk.mjs +0 -1
- package/dist/packem_shared/HEALTH_PATH-BwWsxoqV.mjs +0 -1
- package/dist/packem_shared/LOG_ARCHIVE_PATH-CuHKuDCS.mjs +0 -1
- package/dist/packem_shared/STORAGE_UPLOAD_MAX_BODY_BYTES-K0uZPIUj.mjs +0 -1
- package/dist/packem_shared/analyticsEngineSink-iIRy11I9.mjs +0 -1
- package/dist/packem_shared/applyJurisdiction-DX_lQ6fY.mjs +0 -1
- package/dist/packem_shared/applyRestCache-DwBDPRf6.mjs +0 -1
- package/dist/packem_shared/argsFromQuery-nMGzM5bK.mjs +0 -1
- package/dist/packem_shared/base64-DPPVK6s_.mjs +0 -1
- package/dist/packem_shared/composeIdentityResolvers-DwE0Jbww.mjs +0 -1
- package/dist/packem_shared/composeWorker-rVokGnPq.mjs +0 -6
- package/dist/packem_shared/createCrossShardRelationCapabilities-CQfrCIWR.mjs +0 -1
- package/dist/packem_shared/createKvCursorStore-C24tEuYk.mjs +0 -3
- package/dist/packem_shared/createQueryCoordinator-D8GY_boW.mjs +0 -1
- package/dist/packem_shared/createShardClient-DoSOeXwx.mjs +0 -1
- package/dist/packem_shared/decorateResponse-BeLVRQuJ.mjs +0 -1
- package/dist/packem_shared/emitLogEvent-BxJ6jRKW.mjs +0 -1
- package/dist/packem_shared/evict-oldest-C2XU6HBR.mjs +0 -1
- package/dist/packem_shared/identity-header-pdXOyDU4.mjs +0 -1
- package/dist/packem_shared/memoizeIdentity-CX3xEPYw.mjs +0 -1
- package/dist/packem_shared/method-guard-rzvo19pa.mjs +0 -1
- package/dist/packem_shared/observability-DWlkDJJw.mjs +0 -1
- package/dist/packem_shared/otlp-resource-B-ByO9qo.mjs +0 -1
- package/dist/packem_shared/pipeline-log-reader-FF1V32O2.mjs +0 -1
- package/dist/packem_shared/rest-cache-5unAzdFN.mjs +0 -1
- package/dist/packem_shared/rest-routes-BqldHiaH.mjs +0 -1
- package/dist/packem_shared/toAirbyteMessages-DTk8e2f9.mjs +0 -1
package/dist/index.d.mts
CHANGED
|
@@ -4910,4 +4910,11 @@ declare const createShardClient: (namespace: ShardNamespaceLike, options?: Shard
|
|
|
4910
4910
|
*/
|
|
4911
4911
|
declare const STORAGE_UPLOAD_MAX_BODY_BYTES: number;
|
|
4912
4912
|
declare const VERSION: string;
|
|
4913
|
-
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,
|
|
4913
|
+
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,
|
|
4914
|
+
/**
|
|
4915
|
+
* Resource attribute bag used by OTLP exporters. Re-exported from `shared/otlp`
|
|
4916
|
+
* because {@link OtlpSinkOptions.resourceAttributes} is part of the public
|
|
4917
|
+
* surface — without a name for it, a caller cannot hoist a shared attribute bag
|
|
4918
|
+
* into a typed constant.
|
|
4919
|
+
*/
|
|
4920
|
+
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
|
@@ -4910,4 +4910,11 @@ declare const createShardClient: (namespace: ShardNamespaceLike, options?: Shard
|
|
|
4910
4910
|
*/
|
|
4911
4911
|
declare const STORAGE_UPLOAD_MAX_BODY_BYTES: number;
|
|
4912
4912
|
declare const VERSION: string;
|
|
4913
|
-
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,
|
|
4913
|
+
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,
|
|
4914
|
+
/**
|
|
4915
|
+
* Resource attribute bag used by OTLP exporters. Re-exported from `shared/otlp`
|
|
4916
|
+
* because {@link OtlpSinkOptions.resourceAttributes} is part of the public
|
|
4917
|
+
* surface — without a name for it, a caller cannot hoist a shared attribute bag
|
|
4918
|
+
* into a typed constant.
|
|
4919
|
+
*/
|
|
4920
|
+
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,backupObjectKeyOfManifest as i,isBackupManifestEntry as n,isBackupManifestKey as p,normalizeBackupPrefix as
|
|
1
|
+
import{BACKUP_KEY_PREFIX as t,backupManifestKey as a,backupObjectKey as s,backupObjectKeyOfManifest as i,isBackupManifestEntry as n,isBackupManifestKey as p,normalizeBackupPrefix as c}from"./packem_shared/BACKUP_KEY_PREFIX-BOtSu-_3.mjs";import{toAirbyteMessages as f,toFivetranResponse as E}from"./packem_shared/toAirbyteMessages-Cy3uaySU.mjs";import{composeWorker as S,createLunoraHandler as x,createWorker as _,defineRpcEnvelope as d,resolveLunoraOptions as l,withFrameworkWorker as u}from"./packem_shared/composeWorker-BtABY25U.mjs";import{createCrossShardRelationCapabilities as k}from"./packem_shared/createCrossShardRelationCapabilities-DgQYQzd1.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-D5O7elXI.mjs";import{LunoraError as b,toErrorResponse as g}from"./packem_shared/LunoraError-DksAgIpa.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-VOd1DFsf.mjs";import{HEALTH_PATH as K,HEALTH_READY_PATH as N,buildHealthRoutes as U,d1Probe as B,durableObjectProbe as Y,presenceProbe as w}from"./packem_shared/HEALTH_PATH-jZsuCmSs.mjs";import{LOG_ARCHIVE_PATH as X,resolveLogArchiveFromEnv as j}from"./packem_shared/LOG_ARCHIVE_PATH-jgHjdsz2.mjs";import{memoizeIdentity as W,memoizeIdentityPerRequest as q}from"./packem_shared/memoizeIdentity-DVd9yDW1.mjs";import{e as J,a as Z}from"./packem_shared/observability-vDK-rMbs.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-D7qu89f2.mjs";import{D as pe,a as ce,c as me}from"./packem_shared/pipeline-log-reader-BGrl66P5.mjs";import{createQueryCoordinator as Ee,createStaticShardRegistry as Re,mergeStrategyForAggregate as Se}from"./packem_shared/createQueryCoordinator-CnNyazLX.mjs";import{applyJurisdiction as _e,resolveShard as de}from"./packem_shared/applyJurisdiction-C0ddU7Tg.mjs";import{a as ue,r as ye,b as ke}from"./packem_shared/rest-cache-D6nWkevc.mjs";import{a as Ae,b as Ce,c as Le,r as Te,d as be}from"./packem_shared/rest-routes-3l718ENH.mjs";import{decorateResponse as he,enforceOrigin as He,handleCorsPreflight as Ie,resolveSecurity as Pe}from"./packem_shared/decorateResponse-D3NzOIvB.mjs";import{createShardClient as De}from"./packem_shared/createShardClient-Yb6_Mzd6.mjs";import{STORAGE_UPLOAD_MAX_BODY_BYTES as Me}from"./packem_shared/STORAGE_UPLOAD_MAX_BODY_BYTES-BqyO-1l6.mjs";import{LOG_ARCHIVE_NOT_CONFIGURED as Ke}from"./packem_shared/LOG_ARCHIVE_NOT_CONFIGURED-CDpi4yFD.mjs";import{NOOP_EXECUTION_CONTEXT as Ue}from"./packem_shared/NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{composeIdentityResolvers as Ye,routeIdentityResolvers as we}from"./packem_shared/composeIdentityResolvers-DdDFfuTV.mjs";const e="0.0.0";export{t as BACKUP_KEY_PREFIX,pe as DEFAULT_LOG_COLUMNS,ce as DEFAULT_LOG_LIMIT,A as DEFAULT_REGISTRY_CACHE_TTL_MS,K as HEALTH_PATH,N as HEALTH_READY_PATH,Ke as LOG_ARCHIVE_NOT_CONFIGURED,X as LOG_ARCHIVE_PATH,b as LunoraError,Ue 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,U 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,me 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,c 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,be as restSurfaceFromRegistry,we as routeIdentityResolvers,D as runExportTap,F as sanitizeChange,se as sentrySink,f as toAirbyteMessages,g as toErrorResponse,E as toFivetranResponse,M as webhookExportSink,ie as webhookSink,u as withFrameworkWorker};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const e="backups/",c=t=>t===""||t.endsWith("/")?t:`${t}/`,n=".manifest.json",o=(t,s)=>`${c(t)}lunora-backup-${s.replaceAll(/[.:]/gu,"-")}.ndjson`,a=t=>`${t}${n}`,i=t=>t.endsWith(n),p=t=>t.slice(0,-n.length),b=t=>typeof t=="object"&&t!==null&&typeof t.id=="string"&&typeof t.file=="string";export{e as BACKUP_KEY_PREFIX,a as backupManifestKey,o as backupObjectKey,p as backupObjectKeyOfManifest,b as isBackupManifestEntry,i as isBackupManifestKey,c as normalizeBackupPrefix};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{D as a,a as r,c as _}from"./pipeline-log-reader-BGrl66P5.mjs";export{a as DEFAULT_LOG_COLUMNS,r as DEFAULT_LOG_LIMIT,_ as createPipelineLogReader};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as a}from"./LunoraError-DksAgIpa.mjs";import{applyJurisdiction as _,resolveShard as l}from"./applyJurisdiction-C0ddU7Tg.mjs";const f="__lunora_shard_registry__",m=3e4,g="https://shard-registry.internal",p=async r=>await r.json(),E=r=>{const w=r.instanceName??f,c=r.cacheTtlMs??m,n=new Map,S=_(r.namespace,r.jurisdiction);let i;const d=()=>(i??=l(S,w),i),h=async(e,t)=>d().fetch(new Request(`${g}${e}`,{body:JSON.stringify(t),headers:{"content-type":"application/json"},method:"POST"})),u=async e=>d().fetch(new Request(`${g}${e}`,{method:"GET"}));return{invalidate(e){e===void 0?n.clear():n.delete(e)},async listShardKeys(e){const t=Date.now(),s=n.get(e);if(s&&s.expiresAt>t)return s.shardKeys;const o=await u(`/list?table=${encodeURIComponent(e)}`);if(!o.ok)throw new a(`shard registry /list returned ${String(o.status)}`);const{shardKeys:y}=await p(o);return c>0&&n.set(e,{expiresAt:t+c,shardKeys:y}),y},async register(e,t){const s=await h("/register",{shardKey:t,table:e});if(!s.ok)throw new a(`shard registry /register returned ${String(s.status)}`);n.delete(e)},async snapshot(){const e=await u("/snapshot");if(!e.ok)throw new a(`shard registry /snapshot returned ${String(e.status)}`);const{tables:t}=await p(e);return t},async unregister(e,t){const s=await h("/unregister",{shardKey:t,table:e});if(!s.ok)throw new a(`shard registry /unregister returned ${String(s.status)}`);n.delete(e)}}};export{m as DEFAULT_REGISTRY_CACHE_TTL_MS,f as SHARD_REGISTRY_DO_NAME,E as createDynamicShardRegistry};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as T}from"./LunoraError-DksAgIpa.mjs";import{m as A}from"./method-guard-BG_vJNTl.mjs";import{resolveShard as R}from"./applyJurisdiction-C0ddU7Tg.mjs";const C="/_lunora/health",H="/_lunora/health/ready",N=t=>t==="liveness"?["liveness"]:t==="readiness"?["readiness"]:["liveness","readiness"];class P{#e=new Map;addChecker(e,s,r){this.#e.set(e,{run:s,types:r.type})}async getReport(e){const s=[...this.#e].filter(([,a])=>e===void 0||a.types.includes(e)),r=await Promise.all(s.map(async([a,o])=>[a,await o.run()]));return{healthy:r.every(([,a])=>a.health.healthy),report:Object.fromEntries(r)}}}const S=t=>{const e=new P,s=new Set;for(const r of t)r.critical&&s.add(r.name),e.addChecker(r.name,async()=>{let a;try{a=await r.check()}catch(o){a={healthy:!1,message:o instanceof Error?o.message:"probe failed"}}return{health:{healthy:a.healthy,...a.message===void 0?{}:{message:a.message}}}},{type:N(r.kind)});return{criticalNames:s,registry:e}},_=(t,e)=>{const s=t.includes(":")?t.slice(0,t.indexOf(":")):"probe",r=(e.get(s)??0)+1;return e.set(s,r),r===1?s:`${s}#${String(r)}`},j=(t,e)=>t?"unhealthy":e?"degraded":"healthy",M=(t,e,s,r,a)=>{const o=[];let u=!1,d=!1;const y=new Map;for(const[h,i]of Object.entries(t)){const n=e.has(h),c=i.health.healthy;d=d||!c,u=u||!c&&n;const l=s==="admin"?h:_(h,y);o.push({critical:n,...s==="admin"&&i.health.message!==void 0?{message:i.health.message}:{},name:l,status:c?"up":"down"})}return o.sort((h,i)=>h.name.localeCompare(i.name)),{anyCriticalDown:u,body:{appName:r,appVersion:a,checks:o,status:j(u,d),timestamp:new Date().toISOString()}}},G=t=>{const{appName:e="lunora",appVersion:s="0.0.0",auth:r="public",cacheTtlMs:a,isAdmin:o,resolveProbes:u}=t,d=n=>a!==void 0?a:n==="readiness"?0:r==="public"?5e3:0,y={},h=n=>{if(r==="admin"&&!o(n))throw new T("health endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403})},i=async(n,c,l)=>{const p=A(n,["GET","HEAD"]);if(p)return p;h(n);const f=d(l);if(f>0){const m=y[l];if(m!==void 0&&Date.now()<m.expiresAt)return Response.json(m.body,{headers:{"cache-control":"no-store"},status:m.down?503:200})}const{criticalNames:b,registry:v}=S(u(c)),{healthy:E,report:k}=await v.getReport(l==="readiness"?"readiness":void 0),{anyCriticalDown:D,body:g}=M(k,b,r,e,s),w=l==="readiness"?!E:D;return f>0&&(y[l]={body:g,down:w,expiresAt:Date.now()+f}),Response.json(g,{headers:{"cache-control":"no-store"},status:w?503:200})};return{[C]:(n,c)=>i(n,c,"aggregate"),[H]:(n,c)=>i(n,c,"readiness")}},I=(t,e,s)=>({check:async()=>{try{return await R(e,s).fetch(new Request("https://shard.internal/_lunora/status",{method:"GET"})),{healthy:!0}}catch{return{healthy:!1,message:"durable object unreachable"}}},critical:!0,name:t}),q=(t,e)=>({check:async()=>{try{return await e.prepare("SELECT 1").first(),{healthy:!0}}catch{return{healthy:!1,message:"d1 query failed"}}},critical:!0,name:t}),B=(t,e)=>({check:()=>e?{healthy:!0}:{healthy:!1,message:"binding not configured"},critical:!1,name:t});export{C as HEALTH_PATH,H as HEALTH_READY_PATH,G as buildHealthRoutes,q as d1Probe,I as durableObjectProbe,B as presenceProbe};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createR2Sql as R}from"@lunora/bindings/r2sql";import{LOG_ARCHIVE_NOT_CONFIGURED as _}from"./LOG_ARCHIVE_NOT_CONFIGURED-CDpi4yFD.mjs";import{L as d,c as h}from"./pipeline-log-reader-BGrl66P5.mjs";import{LunoraError as a}from"./LunoraError-DksAgIpa.mjs";import{a as A}from"./method-guard-BG_vJNTl.mjs";const m="/_lunora/admin/logs/archive",v="LUNORA_LOG_ARCHIVE_TABLE",C="LUNORA_LOG_ARCHIVE_NAMESPACE",V=o=>{if(typeof o!="object"||o===null)return;const e=o,t=e[v];if(typeof t!="string"||t==="")return;const r=e[C];return{table:t,...typeof r=="string"&&r!==""?{namespace:r}:{}}},O=new Set(d),T=o=>typeof o=="string"&&o!==""?o:void 0,S=(o,e)=>{if(o!==void 0){if(typeof o!="string"||!O.has(o))throw new a(`logs archive: invalid \`${e}\` — expected one of ${d.join(", ")}`,{code:"BAD_REQUEST",status:400});return o}},u=(o,e)=>{if(o!==void 0){if(typeof o!="number"||!Number.isFinite(o))throw new a(`logs archive: invalid \`${e}\` — expected a finite number`,{code:"BAD_REQUEST",status:400});return o}},b=o=>{const e={},t=s=>{const n=T(o[s]);n!==void 0&&(e[s]=n)},r=s=>{const n=S(o[s],s);n!==void 0&&(e[s]=n)},i=s=>{const n=u(o[s],s);n!==void 0&&(e[s]=n)};t("functionPath"),t("functionPathPrefix"),t("traceId"),t("shardKey"),t("userId"),r("level"),r("minLevel"),i("sinceTs"),i("untilTs"),i("limit");const c=o.cursor;if(typeof c=="object"&&c!==null){const s=u(c.ts,"cursor.ts");s!==void 0&&(e.cursor={ts:s})}return e},N=o=>{const e=o.R2_SQL_ACCOUNT_ID??o.CLOUDFLARE_ACCOUNT_ID,t=o.R2_SQL_TOKEN,r=o.R2_SQL_BUCKET,i=[];if((e===void 0||e==="")&&i.push("R2_SQL_ACCOUNT_ID"),(t===void 0||t==="")&&i.push("R2_SQL_TOKEN"),(r===void 0||r==="")&&i.push("R2_SQL_BUCKET"),i.length>0)throw new a(`log archive not configured (missing ${i.join(", ")}). The Pipeline must write to an R2 Data Catalog (Iceberg) table, and R2_SQL_ACCOUNT_ID / R2_SQL_TOKEN / R2_SQL_BUCKET must be set — see the observability docs.`,{code:_,status:400});return{accountId:e,apiToken:t,bucket:r}},G=o=>{const{createReader:e=h,readJsonBody:t,requireAdminOption:r}=o,i=async(c,s)=>{A(c,"POST","Log-archive");const n=r(c,o.logArchive,{code:_,message:"log archive requires a `logArchive` config (an R2 Data Catalog table) on the worker — see the observability docs"}),{accountId:L,apiToken:p,bucket:l}=N(s??{}),E=b(await t(c)),g=R({accountId:L,apiToken:p,bucket:l}),f=await e(g,{columnMap:n.columnMap,namespace:n.namespace,table:n.table}).query(E);return Response.json(f,{headers:{"content-type":"application/json"},status:200})};return{[m]:i}};export{_ as LOG_ARCHIVE_NOT_CONFIGURED,m as LOG_ARCHIVE_PATH,G as buildLogArchiveAdminRoutes,V as resolveLogArchiveFromEnv};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as t,toErrorBody as
|
|
1
|
+
import{LunoraError as t,toErrorBody as a}from"@lunora/errors";const n=e=>{const{body:o,redacted:r,status:s}=a(e,{fallbackCode:"INTERNAL",redactedMessage:"Internal error"});return r&&console.error("[lunora] internal error:",e),Response.json({error:o},{headers:{"content-type":"application/json"},status:s})};class u extends t{constructor(o,r){super(r?.code??"INTERNAL",o,{cause:r?.cause,status:r?.status})}toResponse(){return n(this)}}export{u as LunoraError,n as toErrorResponse};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as p}from"./LunoraError-DksAgIpa.mjs";import{a as _}from"./method-guard-BG_vJNTl.mjs";const N="/_lunora/admin/storage",f="/_lunora/admin/storage/object",j="/_lunora/admin/storage/url",P="/_lunora/admin/storage/buckets",C=10080*60,B=32*1048576,I=new Set(["GET","PUT"]),M=E=>{const h=new Uint8Array(E);let S="";for(const o of h)S+=o.toString(16).padStart(2,"0");return S},x=E=>{const{assertAdmin:h,parsePaging:S,queryParameter:o,readBodyBytes:w,requireAdminOption:i,storage:c}=E,T=e=>{const s=o(e,"key");if(s===void 0)throw new p("Storage endpoint requires a `key` query parameter",{code:"BAD_REQUEST",status:400});return s},y=async e=>{const s=i(e,c.storageList,{code:"STORAGE_NOT_CONFIGURED",message:"storage endpoint requires a `storageList` function on the worker"}),t=new URL(e.url),a=await s(o(t,"prefix"),{bucket:o(t,"bucket"),cursor:o(t,"cursor"),...S(e)});return Response.json(a,{headers:{"content-type":"application/json"},status:200})},R=e=>(_(e,"GET","Storage-buckets"),h(e),Response.json({buckets:c.storageBuckets??[]},{headers:{"content-type":"application/json"},status:200})),U=async e=>{const s=i(e,c.storageDelete,{code:"STORAGE_DELETE_NOT_CONFIGURED",message:"storage delete requires a `storageDelete` function on the worker"}),t=new URL(e.url),a=T(t);return await s(a,{bucket:o(t,"bucket")}),Response.json({deleted:!0,key:a},{headers:{"content-type":"application/json"},status:200})},m=async e=>{const s=i(e,c.storageUpload,{code:"STORAGE_UPLOAD_NOT_CONFIGURED",message:"storage upload requires a `storageUpload` function on the worker"}),t=new URL(e.url),a=T(t),n=await w(e,B),d=e.headers.get("content-type"),u=d===null||d===""?void 0:d,l=o(t,"expectedSha256"),g=o(t,"expectedSize");let r;if(l!==void 0||g!==void 0){const D=await crypto.subtle.digest("SHA-256",n);r=M(D);const G=g!==void 0&&n.byteLength!==Number(g),L=l!==void 0&&r!==l.toLowerCase();if(G||L)throw new p("Upload failed verification — the body did not match the declared size or SHA-256 checksum, so nothing was written",{code:"STORAGE_CHECKSUM_MISMATCH",status:400})}const O=await s(a,n,{bucket:o(t,"bucket"),contentType:u,sha256:r});return Response.json(r===void 0?O:{...O,sha256:r},{headers:{"content-type":"application/json"},status:200})},A=async e=>{switch(e.method){case"DELETE":return U(e);case"GET":return y(e);case"POST":case"PUT":return m(e);default:throw new p("Storage endpoint requires GET, PUT, POST, or DELETE",{code:"METHOD_NOT_ALLOWED",status:405})}},b=async e=>{_(e,"GET","Storage-object");const s=i(e,c.storageDownload,{code:"STORAGE_DOWNLOAD_NOT_CONFIGURED",message:"storage download requires a `storageDownload` function on the worker"}),t=new URL(e.url),a=T(t),n=await s(a,{bucket:o(t,"bucket")});if(!n?.body)throw new p(`No object at key ${a}`,{code:"STORAGE_OBJECT_NOT_FOUND",status:404});return new Response(n.body,{headers:{"content-type":n.httpMetadata?.contentType??"application/octet-stream",...n.size===void 0?{}:{"content-length":String(n.size)}},status:200})},k=async e=>{_(e,"GET","Storage URL");const s=i(e,c.storageSignedUrl,{code:"STORAGE_URL_NOT_CONFIGURED",message:"storage URL endpoint requires a `storageSignedUrl` function on the worker"}),t=new URL(e.url),a=T(t),n=Number(o(t,"expiresIn")??""),d=Number.isFinite(n)&&n>0?Math.min(n,C):void 0,u=o(t,"method");if(u!==void 0&&!I.has(u))throw new p("Storage URL `method` must be GET or PUT",{code:"BAD_REQUEST",status:400});const l=u,g=o(t,"contentType"),r=await s(a,{bucket:o(t,"bucket"),contentType:g,expiresInSeconds:d,method:l});return Response.json({key:a,url:r},{headers:{"content-type":"application/json"},status:200})};return{[P]:R,[f]:b,[N]:A,[j]:k}};export{P as STORAGE_BUCKETS_PATH,N as STORAGE_PATH,B as STORAGE_UPLOAD_MAX_BODY_BYTES,j as STORAGE_URL_PATH,x as buildStorageAdminRoutes,M as toHex};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{e as d,L as y,o as j,c as S,O as $,f as C,g as X,h as B,w as Y,i as q,j as G,m as Z}from"./otlp-resource-B4Yylr0V.mjs";const Q=r=>{if(typeof r=="string")return r;try{return JSON.stringify(r)??String(r)}catch{return String(r)}},J=r=>typeof r=="boolean"||typeof r=="number"||typeof r=="string"?r:Q(r),v=512,rr=200,tr=r=>{const s=r.maxItems??v,t=r.maxDelayMs??rr;let o=[],e,i,l;const f=()=>{e!==void 0&&(clearTimeout(e),e=void 0)},h=async()=>{f();const u=o;o=[];const a=l;i=void 0,l=void 0;try{u.length>0&&await r.export(u)}catch{}finally{a?.()}},m=u=>{i===void 0&&(i=new Promise(a=>{l=a}),e=setTimeout(()=>{h()},t)),u?.(i)};return{add:(u,a)=>{for(o.push(u);o.length>s;)o.shift();m(a),o.length>=s&&h()},flush:async u=>{if(o.length===0){f();return}const a=h();return u?.(a),a},get size(){return o.length}}},or=(r,s)=>r<s?-1:r>s?1:0,L=r=>{if(r===void 0)return"null";if(typeof r=="bigint")throw new TypeError("stableStringify: cannot use a bigint in a stable JSON cache key — pass it as a string, or use stableWireKey");if(r===null||typeof r!="object")return JSON.stringify(r);if(Array.isArray(r))return`[${r.map(i=>L(i)).join(",")}]`;const s=Object.getPrototypeOf(r);if(s!==null&&s!==Object.prototype){const i=r.constructor?.name??"value";throw new TypeError(`stableStringify: cannot use a ${i} in a stable JSON cache key — only plain objects, arrays, and JSON primitives are supported (wire-typed values key via stableWireKey)`)}const t=r,o=Object.keys(t).toSorted(or),e=[];for(const i of o){const l=t[i];l!==void 0&&e.push(`${JSON.stringify(i)}:${L(l)}`)}return`{${e.join(",")}}`},sr=(r,s)=>{const t=[d(y.functionPath,r.functionPath),d(y.ok,r.ok)];r.method!==void 0&&t.push(d("http.request.method",r.method)),r.path!==void 0&&t.push(d("url.path",r.path)),t.push(d("http.route",r.functionPath)),r.scheme!==void 0&&t.push(d("url.scheme",r.scheme)),r.host!==void 0&&t.push(d("server.address",r.host)),r.port!==void 0&&t.push(d("server.port",r.port)),r.userAgent!==void 0&&t.push(d("user_agent.original",r.userAgent)),r.shardKey!==void 0&&t.push(d(y.shardKey,r.shardKey)),t.push(d("http.response.status_code",r.error?.status??200)),r.error&&t.push(d(y.errorType,r.error.code),d("lunora.error_status",r.error.status)),r.fanOut&&t.push(d("lunora.fanout.table",r.fanOut.table),d("lunora.fanout.shards",r.fanOut.shards),d("lunora.fanout.failed",r.fanOut.failed));const o={attributes:t,endTimeUnixNano:S(s),kind:$.server,name:r.functionPath,...r.parentSpanId===void 0?{}:{parentSpanId:r.parentSpanId},spanId:r.spanId??j(8),startTimeUnixNano:S(s-r.durationMs),status:r.ok?{code:1}:{code:2,message:r.error?.message??""},traceId:r.traceId??j(16)};return r.traceFlags!==void 0&&(o.flags=r.traceFlags),r.error&&(o.events=[{attributes:[d("exception.type",r.error.code),d("exception.message",r.error.message)],name:"exception",timeUnixNano:S(s)}]),o},R=(r,s)=>{const t=new Map([[y.functionPath,d(y.functionPath,r.functionPath)]]);r.shardKey!==void 0&&t.set(y.shardKey,d(y.shardKey,r.shardKey)),r.userId!==void 0&&t.set(y.userId,d(y.userId,r.userId)),r.errorType!==void 0&&t.set(y.errorType,d(y.errorType,r.errorType));for(const[o,e]of Object.entries(s??{}))t.set(o,d(o,J(e)));return[...t.values()]},er=r=>{const s={attributes:R({errorType:r.error?.type,functionPath:r.functionPath,shardKey:r.shardKey,userId:r.userId},r.attributes),endTimeUnixNano:S(r.startTs+r.durationMs),kind:$[r.kind??"internal"],name:r.name,parentSpanId:r.parentSpanId,spanId:r.spanId,startTimeUnixNano:S(r.startTs),status:r.ok?{code:1}:{code:2,message:r.error?.message??""},traceId:r.traceId},t=o=>X(Object.fromEntries(Object.entries(o??{}).map(([e,i])=>[e,J(i)])));return r.events!==void 0&&r.events.length>0&&(s.events=r.events.map(o=>({attributes:t(o.attributes),name:o.name,timeUnixNano:S(o.ts)}))),r.links!==void 0&&r.links.length>0&&(s.links=r.links.map(o=>({attributes:t(o.attributes),spanId:o.spanId,traceId:o.traceId}))),s},nr=r=>{const s=S(r.ts),t=R({functionPath:r.functionPath,shardKey:r.shardKey},r.attributes),o={asDouble:r.value,attributes:t,timeUnixNano:s};return r.kind==="gauge"?{gauge:{dataPoints:[o]},name:r.name}:r.kind==="histogram"?{histogram:{aggregationTemporality:1,dataPoints:[{attributes:t,bucketCounts:["1"],count:"1",explicitBounds:[],max:r.value,min:r.value,sum:r.value,timeUnixNano:s}]},name:r.name}:{name:r.name,sum:{aggregationTemporality:1,dataPoints:[o],isMonotonic:!0}}},ir=r=>{const s={attributes:R({functionPath:r.functionPath,shardKey:r.shardKey,userId:r.userId},r.fields),body:{stringValue:r.message},severityNumber:C[r.level],severityText:r.level.toUpperCase(),timeUnixNano:S(r.ts)};return r.traceId!==void 0&&(s.traceId=r.traceId),r.spanId!==void 0&&(s.spanId=r.spanId),r.eventName!==void 0&&(s.eventName=r.eventName,s.attributes.push(d("event.name",r.eventName))),s},ar=1024,cr=async r=>{const s=new Blob([r]).stream().pipeThrough(new CompressionStream("gzip"));return new Response(s).arrayBuffer()},z=async(r,s,t,o)=>{try{const e=JSON.stringify(s),{byteLength:i}=new TextEncoder().encode(e),l=(i<ar?fetch(r,{body:e,headers:t,method:"POST"}):cr(e).then(f=>fetch(r,{body:f,headers:{...t,"content-encoding":"gzip"},method:"POST"}))).then(()=>{},()=>{});o?.(l),await l}catch{}},dr=(r,s,t,o)=>{z(r,s,t,o?.waitUntil).catch(()=>{})},O=(r,s)=>s===!0&&r.ok,ur=r=>r.kind==="metric"?void 0:r.event.traceId,pr=r=>{const s=Map.groupBy(r,o=>ur(o)),t=s.get(void 0)??[];return s.delete(void 0),{byTrace:s,untraced:t}},D=5,lr=(r,s,t)=>{if(s===void 0)return r;const{byTrace:o,untraced:e}=pr(r),i=[...e];let l=0,f;for(const[h,m]of o){let u;try{u=s({logs:m.filter(a=>a.kind==="log").map(a=>a.event),rpc:m.filter(a=>a.kind==="rpc").map(a=>a.event),spans:m.filter(a=>a.kind==="span").map(a=>a.event),traceId:h})}catch(a){l+=1,l===1&&(f=a),u=!0}u&&i.push(...m)}return l>0&&t(f,l),i},P=(r,s)=>{if(s===void 0)return r;try{return s(r)??void 0}catch{return}},F=(r,s)=>{if(r.kind==="rpc"){const o=P(r.event,s?.rpc);return o===void 0?void 0:{bucket:"spans",encoded:sr(o,r.endMs)}}if(r.kind==="span"){const o=P(r.event,s?.span);return o===void 0?void 0:{bucket:"spans",encoded:er(o)}}if(r.kind==="log"){const o=P(r.event,s?.log);return o===void 0?void 0:{bucket:"logs",encoded:ir(o)}}const t=P(r.event,s?.metric);return t===void 0?void 0:{bucket:"metrics",encoded:nr(t)}},mr=(r={})=>{const{onlyErrors:s}=r;return{onLog:t=>{t.level==="error"||t.level==="fatal"?console.error("[lunora:log]",t.functionPath,t.message):console.log("[lunora:log]",t.functionPath,t.message)},onMetric:t=>{console.log("[lunora:metric]",`${t.name}=${String(t.value)}`,t.kind,t.functionPath)},onRpc:t=>{O(t,s)||(t.ok?console.log("[lunora:rpc]",t):console.error("[lunora:rpc]",t))},onSpan:t=>{const o=t.ok?"ok":`error ${t.error?.type??""}`.trim();console.log("[lunora:span]",t.name,`${String(t.durationMs)}ms`,o,t.functionPath)}}},hr=r=>{const{headers:s,onlyErrors:t,transform:o,transformLog:e,url:i}=r,l=B({"content-type":"application/json"},s),f=(h,m)=>{try{const u=fetch(i,{body:JSON.stringify(h),headers:l,method:"POST"}).catch(()=>{});m?.waitUntil&&m.waitUntil(u)}catch{}};return{onLog:(h,m)=>{const u=P(h,e);u!==void 0&&f(u,m)},onRpc:(h,m)=>{if(O(h,t))return;const u=P(h,o);u!==void 0&&f(u,m)}}},yr=r=>{const{capture:s,captureLog:t}=r,o=r.onlyErrors??!0;return{onLog:t?e=>{try{t(e)}catch{}}:void 0,onRpc:e=>{if(!O(e,o))try{s(e)}catch{}}}},gr=r=>{const{dataset:s,onlyErrors:t}=r;return{onRpc:o=>{if(!O(o,t))try{s.writeDataPoint({blobs:[o.functionPath,o.ok?"ok":"error",o.shardKey??"",o.error?.code??"",o.fanOut?.table??""],doubles:[o.durationMs,o.ok?0:1,o.fanOut?.shards??0,o.fanOut?.failed??0],indexes:[o.functionPath]})}catch{}}}},br=r=>{const{pipeline:s,serializeFields:t}=r;return{onLog:(o,e)=>{try{const i={functionPath:o.functionPath,level:o.level,message:o.message,ts:o.ts};o.fields&&(i.fields=t===!0?JSON.stringify(o.fields):o.fields);for(const f of["shardKey","userId","traceId","spanId"])o[f]!==void 0&&(i[f]=o[f]);const l=s.send([i]).catch(()=>{});e?.waitUntil&&e.waitUntil(l)}catch{}}}},kr=r=>{const{batch:s,deploymentEnvironment:t,detectResources:o,endpoint:e,headers:i,onlyErrors:l,postProcessor:f,resourceAttributes:h,serviceNamespace:m,serviceVersion:u,tailSampler:a,token:H}=r,U=r.serviceName??"lunora",E={...u===void 0?{}:{"service.version":u},...m===void 0?{}:{"service.namespace":m},...t===void 0?{}:{"deployment.environment":t},...h},x=new WeakMap,k=c=>{if(o!==!0||c?.resourceAttributes===void 0)return E;const n=x.get(c);if(n!==void 0)return n;const p=Z(c.resourceAttributes(),E);return x.set(c,p),p};let I=e;for(;I.endsWith("/");)I=I.slice(0,-1);const K={logs:{url:`${I}/v1/logs`,wrap:G},metrics:{url:`${I}/v1/metrics`,wrap:q},spans:{url:`${I}/v1/traces`,wrap:Y}},_=B({"content-type":"application/json"},i,H);let A=0;const V=(c,n)=>{if(A>=D)return;A+=1;const p=A===D?" Further tailSampler failures from this sink are silenced until the isolate restarts.":"";console.error(`[lunora:otlp] tailSampler threw for ${String(n)} trace(s) in this flush window; keeping them (fail-open), so the sampling policy did NOT apply.${p}`,c)},W=async c=>{const n=lr(c,a,V),p=new Map;for(const g of n){const b=F(g,f);if(b===void 0)continue;const M=L(g.resource);let T=p.get(M);T===void 0&&(T={logs:[],metrics:[],resource:g.resource,spans:[]},p.set(M,T)),T[b.bucket].push(b.encoded)}const w=[];for(const[,g]of p)for(const b of["spans","logs","metrics"])if(g[b].length>0){const{url:M,wrap:T}=K[b];w.push(z(M,T(g[b],"@lunora/runtime",U,g.resource),_))}await Promise.all(w)};if(s===!1){const c=(n,p)=>{const w=F(n,f);if(w!==void 0){const{url:g,wrap:b}=K[w.bucket];dr(g,b(w.encoded,"@lunora/runtime",U,n.resource),_,p)}};return{onLog:(n,p)=>{c({event:n,kind:"log",resource:k(p)},p)},onMetric:(n,p)=>{c({event:n,kind:"metric",resource:k(p)},p)},onRpc:(n,p)=>{O(n,l)||c({endMs:Date.now(),event:n,kind:"rpc",resource:k(p)},p)},onSpan:(n,p)=>{c({event:n,kind:"span",resource:k(p)},p)}}}const N=tr({export:W,...s?.maxDelayMs===void 0?{}:{maxDelayMs:s.maxDelayMs},...s?.maxItems===void 0?{}:{maxItems:s.maxItems}});return{flush:c=>{N.flush(c?.waitUntil).catch(()=>{})},onLog:(c,n)=>{N.add({event:c,kind:"log",resource:k(n)},n?.waitUntil)},onMetric:(c,n)=>{N.add({event:c,kind:"metric",resource:k(n)},n?.waitUntil)},onRpc:(c,n)=>{O(c,l)||N.add({endMs:Date.now(),event:c,kind:"rpc",resource:k(n)},n?.waitUntil)},onSpan:(c,n)=>{N.add({event:c,kind:"span",resource:k(n)},n?.waitUntil)}}},Sr=(...r)=>{const s=(t,o)=>{for(const e of r){const i=e[t];if(i)try{i.apply(e,o)}catch{}}};return{flush:t=>{s("flush",[t])},onLog:(t,o)=>{s("onLog",[t,o])},onMetric:(t,o)=>{s("onMetric",[t,o])},onRpc:(t,o)=>{s("onRpc",[t,o])},onSpan:(t,o)=>{s("onSpan",[t,o])}}};export{gr as analyticsEngineSink,Sr as combineSinks,mr as consoleSink,kr as otlpSink,br as pipelineLogSink,yr as sentrySink,hr as webhookSink};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{resolveShard as u}from"@lunora/platform";const s=new WeakMap,n=o=>o===void 0?void 0:{locationHint:o},f=o=>typeof o.idFromName=="function",a=o=>{if(!f(o))return o;const e=o,i=s.get(o);if(i!==void 0)return i;const c=typeof e.jurisdiction=="function"?r=>a(e.jurisdiction(r)):void 0,d=typeof e.getByName=="function"?{get:(r,t)=>e.get(r,n(t)),getByName:(r,t)=>e.getByName(r,n(t)),idForName:r=>e.idFromName(r),jurisdiction:c}:{get:(r,t)=>e.get(r,n(t)),idForName:r=>e.idFromName(r),jurisdiction:c};return s.set(o,d),d},y=(o,e)=>{if(e===void 0)return o;if(typeof o.jurisdiction!="function")throw new TypeError(`@lunora/runtime: Durable Object namespace does not support jurisdiction("${e}") — update @cloudflare/workers-types or remove the jurisdiction option`);return o.jurisdiction(e)},p=(o,e,i)=>u(a(o),e,i);export{y as applyJurisdiction,p as resolveShard};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as r,r as s,b as t}from"./rest-cache-D6nWkevc.mjs";export{r as applyRestCache,s as requestCarriesCredentials,t as restCacheHeaders};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"./rest-cache-D6nWkevc.mjs";import{a as t,b as o,c as i,r as m,d as R}from"./rest-routes-3l718ENH.mjs";import"./method-guard-BG_vJNTl.mjs";export{t as argsFromQuery,o as buildRestRoutes,i as createRestRateLimit,m as readShardKey,R as restSurfaceFromRegistry};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const a=e=>{let n="";for(let t=0;t<e.length;t+=32768)n+=String.fromCharCode(...e.subarray(t,t+32768));return btoa(n)},o=e=>{const n=atob(e),r=new Uint8Array(n.length);for(let t=0;t<n.length;t+=1)r[t]=n.codePointAt(t)??0;return r},l=e=>a(e).replaceAll("+","-").replaceAll("/","_").replace(/=+$/,"");export{l as a,o as f,a as t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as c}from"./LunoraError-DksAgIpa.mjs";const d=(t,o={})=>{const r=o.onError??"fail-closed";return async(n,e)=>{for(const s of t){let i;try{i=await s(n,e)}catch(l){if(r==="skip")continue;throw l}if(i)return i}return null}},u=t=>{const o=Object.keys(t).filter(r=>r!=="*").toSorted((r,n)=>n.length-r.length);return(r,n)=>{const{pathname:e}=new URL(r.url),s=o.find(l=>e===l||e.startsWith(l.endsWith("/")?l:`${l}/`)),i=s===void 0?t["*"]:t[s];return i===void 0?null:i(r,n)}},f=(t,o)=>o===void 0||t===void 0?t:async(r,n)=>{const e=await t(r,n);if(!e)return e;const s=o.validate(e);if(s.ok)return e;if(o.onInvalid==="reject")throw new c(`identity claims failed the declared contract: ${s.error}`,{code:"UNAUTHENTICATED",status:401});return null};export{d as composeIdentityResolvers,u as routeIdentityResolvers,f as wrapResolverWithContract};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import{isLunoraError as Pn,toErrorBody as Dn}from"@lunora/errors";import{e as Pt}from"./evict-oldest-BNXsKx4s.mjs";import{NOOP_EXECUTION_CONTEXT as Nn}from"./NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{e as Un,a as Cn}from"./identity-header-JF5q3H5w.mjs";import{o as Se,b as Bn,p as xn,m as Hn,d as Ln,a as jn,r as Mn}from"./otlp-resource-B4Yylr0V.mjs";import{e as Z,f as be,M as Dt,b as $n,g as Kn,h as Nt,i as Ut}from"./rest-routes-3l718ENH.mjs";import{LunoraError as d,toErrorResponse as et}from"./LunoraError-DksAgIpa.mjs";import{a as M,m as me}from"./method-guard-BG_vJNTl.mjs";import{normalizeBackupPrefix as Fe,BACKUP_KEY_PREFIX as Ge,isBackupManifestKey as Fn,backupObjectKeyOfManifest as Ct,backupObjectKey as Gn,backupManifestKey as Qn}from"./BACKUP_KEY_PREFIX-BOtSu-_3.mjs";import{toHex as zn,buildStorageAdminRoutes as Wn,STORAGE_UPLOAD_MAX_BODY_BYTES as Vn,STORAGE_PATH as qn}from"./STORAGE_UPLOAD_MAX_BODY_BYTES-BqyO-1l6.mjs";import{runExportTap as Jn}from"./createKvCursorStore-VOd1DFsf.mjs";import{buildHealthRoutes as Yn,durableObjectProbe as Xn,d1Probe as Zn,presenceProbe as Ce}from"./HEALTH_PATH-jZsuCmSs.mjs";import{wrapResolverWithContract as er}from"./composeIdentityResolvers-DdDFfuTV.mjs";import{composeIdentityResolvers as bs,routeIdentityResolvers as _s}from"./composeIdentityResolvers-DdDFfuTV.mjs";import{buildLogArchiveAdminRoutes as tr}from"./LOG_ARCHIVE_PATH-jgHjdsz2.mjs";import{r as nr,f as tt,a as ce}from"./observability-vDK-rMbs.mjs";import{resolveShard as we,applyJurisdiction as nt}from"./applyJurisdiction-C0ddU7Tg.mjs";import{resolveSecurity as rt,handleCorsPreflight as rr,enforceOrigin as or,decorateResponse as Be,enforceWebSocketOrigin as ot}from"./decorateResponse-D3NzOIvB.mjs";const ar=e=>{const n=e??{};if(typeof n.bucket=="function")return n;const t={...n,bucketName:"default"};return t.bucket=()=>t,t},Bt="__lunoraBranch",sr=e=>typeof e=="object"&&e!==null&&Object.hasOwn(e,Bt),ir=`may not contain the reserved workflow branch-marker key ("${Bt}")`,Qe=(e,n)=>{const t=Math.max(e.length,n.length);let r=e.length^n.length;for(let a=0;a<t;a+=1){const s=a<e.length?e.charCodeAt(a):0,l=a<n.length?n.charCodeAt(a):0;r|=s^l}return r===0},ze=new TextEncoder,cr=Array.from({length:32},(e,n)=>n);new RegExp(`[${cr.map(e=>String.fromCodePoint(e)).join("")}]`,"u");const dr=e=>{const n=String.fromCodePoint(...e);return btoa(n).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")},ur=e=>{const n=e.replaceAll("-","+").replaceAll("_","/")+"===".slice((e.length+3)%4),t=atob(n),r=new Uint8Array(t.length);for(let a=0;a<t.length;a+=1)r[a]=t.codePointAt(a)??0;return r},lr=64,xe=new Map,xt=async e=>{const n=xe.get(e);if(n)return n;Pt(xe,lr);const t=crypto.subtle.importKey("raw",ze.encode(e),{hash:"SHA-256",name:"HMAC"},!1,["sign","verify"]);return xe.set(e,t),t},Ht=async(e,n)=>{const t=await xt(e),r=await crypto.subtle.sign("HMAC",t,ze.encode(n));return dr(new Uint8Array(r))},hr=async(e,n,t)=>{const r=await xt(e);return crypto.subtle.verify("HMAC",r,t,ze.encode(n))},fr=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"];new Set(fr);const pr=new Set(["AE","BH","IL","IQ","IR","JO","KW","LB","OM","PS","QA","SA","SY","TR","YE"]),mr=-100,wr=15,gr=e=>{const n=Number(e.longitude??Number.NaN);switch(e.continent){case"AF":return"afr";case"AS":return e.country!==void 0&&pr.has(e.country)?"me":"apac";case"EU":return Number.isFinite(n)&&n>wr?"eeur":"weur";case"NA":return Number.isFinite(n)&&n<mr?"wnam":"enam";case"OC":return"oc";case"SA":return"sam";default:return}},at=e=>{const n=e.cf;return n===void 0?void 0:gr(n)},Lt="::relay::",yr=(e,n)=>`${e}${Lt}${String(n)}`,jt="::replica::",br=(e,n)=>`${e}${jt}${n}`,_r=e=>{if(e==null||!/^\d+$/.test(e))return;const n=Number.parseInt(e,10);return Number.isSafeInteger(n)&&n>0?n:void 0},Rr=new Set(["1","enabled","on","true","yes"]),Er=new Set(["0","disabled","false","no","off"]),Ar=(e,n)=>{const t=(e??"").trim().toLowerCase();return Rr.has(t)?!0:Er.has(t)?!1:n},Mt="v1",Sr=6e4,Tr=async(e,n={})=>{const t=(n.now??Date.now())+(n.ttlMs??Sr),r=`${Mt}.${String(t)}`,a=await Ht(e,r);return{expiresAtMs:t,token:`${r}.${a}`}},Or=async(e,n,t=Date.now())=>{if(e.length===0||n.length===0)return!1;const r=n.split(".");if(r.length!==3)return!1;const[a,s,l]=r;if(a!==Mt||l.length===0)return!1;const u=Number(s);if(!Number.isFinite(u)||u<=t)return!1;let f;try{f=ur(l)}catch{return!1}return hr(e,`${a}.${s}`,f)},P="/_lunora/admin/auth",vr={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},N=(e,n)=>{const t=e[n];if(typeof t!="string"||t==="")throw new d(`\`${n}\` is required`,{code:"BAD_REQUEST",status:400});return t},le=(e,n)=>{const t=e(n);if(t===void 0)throw new d(`\`${n}\` query parameter is required`,{code:"BAD_REQUEST",status:400});return t},$t=e=>{if(typeof e=="string"||Array.isArray(e)&&e.every(n=>typeof n=="string"))return e},re=(e,n)=>typeof e[n]=="string"?e[n]:void 0,He=(e,n)=>{const t=e[n];return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:void 0},st=e=>{const n=$t(e.role);if(n===void 0||typeof n=="string"&&n.trim()==="")throw new d("`role` is required",{code:"BAD_REQUEST",status:400});return n},it=e=>{const n=e.permission;if(typeof n!="object"||n===null||Array.isArray(n))throw new d("`permission` object is required",{code:"BAD_REQUEST",status:400});const t={};for(const[r,a]of Object.entries(n))Array.isArray(a)&&a.every(s=>typeof s=="string")&&(t[r]=a);return t},kr={[`${P}/capabilities`]:{build:()=>({}),http:"GET",method:"capabilities"},[`${P}/users`]:{build:({paging:e,query:n})=>{const t=n("sortDirection");return{...e,filterField:n("filterField"),filterValue:n("filterValue"),search:n("search"),searchField:n("searchField"),sortBy:n("sortBy"),sortDirection:t==="asc"||t==="desc"?t:void 0}},http:"GET",method:"listUsers"},[`${P}/sessions`]:{build:({paging:e,query:n})=>({...e,userId:n("userId")}),http:"GET",method:"listSessions"},[`${P}/accounts`]:{build:({query:e})=>({userId:le(e,"userId")}),http:"GET",method:"listAccounts"},[`${P}/passkeys`]:{build:({query:e})=>({userId:le(e,"userId")}),http:"GET",method:"listPasskeys"},[`${P}/organizations`]:{build:({paging:e})=>({...e}),http:"GET",method:"listOrganizations"},[`${P}/organizations/members`]:{build:({paging:e,query:n})=>({...e,organizationId:le(n,"organizationId")}),http:"GET",method:"listMembers"},[`${P}/organizations/invitations`]:{build:({paging:e,query:n})=>({...e,organizationId:le(n,"organizationId")}),http:"GET",method:"listInvitations"},[`${P}/config`]:{build:()=>({}),http:"GET",method:"config"},[`${P}/organizations/teams`]:{build:({paging:e,query:n})=>({...e,organizationId:le(n,"organizationId")}),http:"GET",method:"listTeams"},[`${P}/organizations/teams/members`]:{build:({paging:e,query:n})=>({...e,teamId:le(n,"teamId")}),http:"GET",method:"listTeamMembers"},[`${P}/organizations/roles`]:{build:({paging:e,query:n})=>({...e,organizationId:le(n,"organizationId")}),http:"GET",method:"listOrgRoles"},[`${P}/users/create`]:{build:({body:e})=>({data:He(e,"data"),email:N(e,"email"),name:N(e,"name"),password:re(e,"password"),role:$t(e.role)}),http:"POST",method:"createUser"},[`${P}/users/update`]:{build:({body:e})=>{const{data:n}=e;if(typeof n!="object"||n===null||Array.isArray(n))throw new d("`data` object is required",{code:"BAD_REQUEST",status:400});return{data:n,userId:N(e,"userId")}},http:"POST",method:"updateUser"},[`${P}/users/role`]:{build:({body:e})=>({role:st(e),userId:N(e,"userId")}),http:"POST",method:"setRole"},[`${P}/users/ban`]:{build:({body:e})=>({expiresInSeconds:typeof e.expiresInSeconds=="number"?e.expiresInSeconds:void 0,reason:re(e,"reason"),userId:N(e,"userId")}),http:"POST",method:"banUser"},[`${P}/users/unban`]:{build:({body:e})=>({userId:N(e,"userId")}),http:"POST",method:"unbanUser"},[`${P}/users/password`]:{build:({body:e})=>({newPassword:N(e,"newPassword"),userId:N(e,"userId")}),http:"POST",method:"setUserPassword",returns:"void"},[`${P}/users/remove`]:{build:({body:e})=>({userId:N(e,"userId")}),http:"POST",method:"removeUser",returns:"void"},[`${P}/users/impersonate`]:{build:({body:e})=>({userId:N(e,"userId")}),http:"POST",method:"impersonateUser"},[`${P}/sessions/revoke`]:{build:({body:e})=>({sessionId:N(e,"sessionId")}),http:"POST",method:"revokeUserSession",returns:"void"},[`${P}/sessions/revoke-all`]:{build:({body:e})=>({userId:N(e,"userId")}),http:"POST",method:"revokeUserSessions",returns:"void"},[`${P}/accounts/unlink`]:{build:({body:e})=>({accountId:N(e,"accountId"),userId:N(e,"userId")}),http:"POST",method:"unlinkAccount",returns:"void"},[`${P}/two-factor/disable`]:{build:({body:e})=>({userId:N(e,"userId")}),http:"POST",method:"disableTwoFactor",returns:"void"},[`${P}/passkeys/delete`]:{build:({body:e})=>({passkeyId:N(e,"passkeyId")}),http:"POST",method:"deletePasskey",returns:"void"},[`${P}/organizations/members/remove`]:{build:({body:e})=>({memberId:N(e,"memberId")}),http:"POST",method:"removeMember",returns:"void"},[`${P}/organizations/invitations/cancel`]:{build:({body:e})=>({invitationId:N(e,"invitationId")}),http:"POST",method:"cancelInvitation",returns:"void"},[`${P}/organizations/create`]:{build:({body:e})=>({logo:re(e,"logo"),metadata:He(e,"metadata"),name:N(e,"name"),ownerId:re(e,"ownerId"),slug:re(e,"slug")}),http:"POST",method:"createOrganization"},[`${P}/organizations/update`]:{build:({body:e})=>({logo:re(e,"logo"),metadata:He(e,"metadata"),name:re(e,"name"),organizationId:N(e,"organizationId"),slug:re(e,"slug")}),http:"POST",method:"updateOrganization"},[`${P}/organizations/remove`]:{build:({body:e})=>({organizationId:N(e,"organizationId")}),http:"POST",method:"deleteOrganization",returns:"void"},[`${P}/organizations/members/add`]:{build:({body:e})=>({organizationId:N(e,"organizationId"),role:re(e,"role"),userId:N(e,"userId")}),http:"POST",method:"addMember"},[`${P}/organizations/members/invite`]:{build:({body:e})=>({email:N(e,"email"),inviterId:re(e,"inviterId"),organizationId:N(e,"organizationId"),role:re(e,"role")}),http:"POST",method:"inviteMember"},[`${P}/organizations/members/role`]:{build:({body:e})=>({memberId:N(e,"memberId"),role:st(e)}),http:"POST",method:"updateMemberRole"},[`${P}/organizations/teams/create`]:{build:({body:e})=>({name:N(e,"name"),organizationId:N(e,"organizationId")}),http:"POST",method:"createTeam"},[`${P}/organizations/teams/update`]:{build:({body:e})=>({name:N(e,"name"),teamId:N(e,"teamId")}),http:"POST",method:"updateTeam"},[`${P}/organizations/teams/remove`]:{build:({body:e})=>({teamId:N(e,"teamId")}),http:"POST",method:"removeTeam",returns:"void"},[`${P}/organizations/teams/members/add`]:{build:({body:e})=>({teamId:N(e,"teamId"),userId:N(e,"userId")}),http:"POST",method:"addTeamMember"},[`${P}/organizations/teams/members/remove`]:{build:({body:e})=>({teamMemberId:N(e,"teamMemberId")}),http:"POST",method:"removeTeamMember",returns:"void"},[`${P}/organizations/roles/create`]:{build:({body:e})=>({organizationId:N(e,"organizationId"),permission:it(e),role:N(e,"role")}),http:"POST",method:"createOrgRole"},[`${P}/organizations/roles/update`]:{build:({body:e})=>({permission:it(e),roleId:N(e,"roleId")}),http:"POST",method:"updateOrgRole"},[`${P}/organizations/roles/remove`]:{build:({body:e})=>({roleId:N(e,"roleId")}),http:"POST",method:"deleteOrgRole",returns:"void"}},Ir=e=>{const n=async a=>{try{return await a()}catch(s){if(s instanceof d)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 d("auth admin operation failed",{code:u,status:vr[u]??500})}},t=async(a,s)=>{if(e.assertAdmin(a),a.method!==s.http)throw new d(`Auth admin endpoint requires ${s.http}`,{code:"METHOD_NOT_ALLOWED",status:405});const l=e.getAuthAdmin();if(l===void 0)throw new d("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 d(`auth admin does not support \`${s.method}\``,{code:"AUTH_OP_NOT_SUPPORTED",status:400});const f=new URL(a.url),w={body:s.http==="POST"?await e.readJsonBody(a):{},paging:e.parsePaging(a),query:I=>e.queryParameter(f,I)},E=s.build(w),O=await n(()=>u(E));return Response.json(s.returns==="void"?{ok:!0}:O,{headers:{"content-type":"application/json"},status:200})},r={};for(const[a,s]of Object.entries(kr))r[a]=l=>t(l,s);return r},Pr="__lunora_admin__:getAuthAuditLog",ct=e=>typeof e=="string"&&e!==""?e:void 0,dt=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0,Dr=e=>async(t,r)=>{e.assertAdmin(t);const a=e.getReader();if(a===void 0)throw new d("the auth/security audit endpoint requires an `authAuditReader` on the worker",{code:"AUTH_AUDIT_NOT_CONFIGURED",status:400});const s=ct(r.actorId),l=ct(r.event),u=dt(r.sinceSeq),f=dt(r.limit),w={...s===void 0?{}:{actorId:s},...l===void 0?{}:{event:l},...u===void 0?{}:{sinceSeq:u},...f===void 0?{}:{limit:f}};let E;try{E=await a.read(w)}catch(I){throw I instanceof d?I:(console.error("[lunora] auth audit read failed:",I),new d("auth audit read failed",{code:"AUTH_AUDIT_READ_FAILED",status:500}))}const O={entries:E};return Response.json(O,{headers:{"content-type":"application/json"},status:200})},Nr=(e,n)=>{const t=[],r=[];if(n&&n.length>0)for(const a of n)e.resolveTableSharding?.(a)?.mode.kind==="global"?r.push(a):t.push(a);return{globalTables:r,shardLocalTables:t}},Ur=async(e,n,t,r,a,s)=>{if(t!==void 0&&r.length===0)return;const l=await e.orchestrateExport(s,{args:{tables:r},headers:n,tables:r});for(const u of l.shards)if(!u.error)for(const f of u.rows??[])a(f)},Kt=async(e,n,t,r,a,s)=>{const{globalTables:l,shardLocalTables:u}=Nr(e,r);await Ur(n,t,r,u,a,s);const f=e.exportGlobals;if((r===void 0||l.length>0)&&f)for await(const E of f({tables:l}))a(E)},Cr=new TextEncoder,Br=1e3,Ft=10,xr=200,ut=8,Gt="lunoraBackupCron",lt=24*1048576,ht=e=>{const n=e.slice(0,Ft).map(r=>Ct(r)),t=e.length-n.length;return`${n.join(", ")}${t>0?` (+${String(t)} more)`:""}`},Hr=(e,n)=>{const t=new Uint8Array(new ArrayBuffer(n));let r=0;for(const a of e)t.set(a,r),r+=a.byteLength;return t},We=async(e,n,t,r)=>{if(t===void 0||!Number.isInteger(t)||t<=0)return{eligible:0,stale:[]};const a=[];let s;for(let l=0;l<Br;l+=1){const u=await e.list({cursor:s,include:["customMetadata"],prefix:n});for(const f of u.objects)Fn(f.key)&&f.customMetadata?.[Gt]===r&&a.push(f.key);if(!u.truncated||u.cursor===void 0)break;s=u.cursor}return{eligible:a.length,stale:a.toSorted((l,u)=>u.localeCompare(l)).slice(t)}},Lr=async(e,n,t,r,a)=>{const{stale:s}=await We(e,n,t,r),l=new Set(a),u=s.filter(g=>l.has(g)),f=u.slice(0,xr),w=s.length-f.length,E=a.length-u.length;if(f.length===0)return{deleted:[],failed:[],ignored:E,remaining:w};const O=[],I=[];for(let g=0;g<f.length;g+=ut){const b=await Promise.allSettled(f.slice(g,g+ut).map(async _=>(await e.delete(Ct(_)),await e.delete(_),_)));for(const[_,p]of b.entries())p.status==="fulfilled"?O.push(p.value):I.push(f[g+_])}return O.length>0&&console.info(`[lunora] backup prune kept the newest ${String(t)} and deleted ${String(O.length)}: ${ht(O)}`),I.length>0&&console.warn(`[lunora] backup prune failed to remove ${String(I.length)}: ${ht(I)}`),{deleted:O,failed:I,ignored:E,remaining:w}},jr=async e=>{const n=e.backupStore;if(!n)throw new d("backup retention preview requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});const t=Fe(e.backupPrefix??Ge),r=e.backupCron,{eligible:a,stale:s}=r===void 0?{eligible:0,stale:[]}:await We(n,t,e.backupRetain,r);return{cron:r,eligible:a,keep:e.backupRetain??0,prefix:t,wouldDelete:s}},Mr=async(e,n,t,r)=>{const a=e.backupStore,s=e.queryCoordinator;if(!a)throw new d("scheduled backup requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});if(!s)throw new d("scheduled backup requires a `queryCoordinator` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});if(!t||t.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 l={authorization:`Bearer ${t}`,"content-type":"application/json"},u=e.backupTables;let f=0,w=0,E=[];await Kt(e,s,l,u,D=>{const T=Cr.encode(`${JSON.stringify(D)}
|
|
2
|
+
`);if(f+=1,w+=T.byteLength,w>lt)throw new d(`scheduled backup reached ${String(w)} bytes of NDJSON, past the ${String(lt)}-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(T)},n);const I=Fe(e.backupPrefix??Ge),g=new Date(r.scheduledTime).toISOString(),b=Gn(I,g),_=Hr(E,w);E=[];const p=zn(await crypto.subtle.digest("SHA-256",_));await a.put(b,_,{httpMetadata:{contentType:"application/x-ndjson"},sha256:p});const S={bytes:w,createdAt:g,cron:r.cron,file:b,id:g,rows:f,scheduledTime:r.scheduledTime,sha256:p,...u?{tables:u.join(",")}:{}};await a.put(Qn(b),`${JSON.stringify(S,void 0,2)}
|
|
3
|
+
`,{customMetadata:{[Gt]:r.cron},httpMetadata:{contentType:"application/json"}});try{const{stale:D}=await We(a,I,e.backupRetain,r.cron);if(D.length>0){const T=D.slice(0,Ft),x=D.length-T.length;console.info(`[lunora] backup retention: ${String(D.length)} snapshot(s) past the newest ${String(e.backupRetain)} — run \`lunora backup prune\` to remove them: ${T.join(", ")}${x>0?` (+${String(x)} more)`:""}`)}}catch(D){console.warn(`[lunora] backup ${b} was written, but the retention report failed:`,D)}},$r=async(e,n)=>{const t=e.backupStore;if(!t)throw new d("backup prune requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});const r=e.backupCron,a=e.backupRetain;if(r===void 0||a===void 0||!Number.isInteger(a)||a<=0)throw new d("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 Lr(t,Fe(e.backupPrefix??Ge),a,r,n)},Kr="/_lunora/admin/backup/retention",Fr="/_lunora/admin/backup/prune",Gr=e=>{const{options:n,readJsonBody:t,requireAdminOption:r}=e,a=(u,f)=>{r(u,n.backupStore,{code:"BACKUP_NOT_CONFIGURED",message:`backup ${f} requires a \`backupStore\` on the worker`})},s=async u=>(M(u,"GET","Backup-retention"),a(u,"retention preview"),Response.json(await jr(n),{headers:{"cache-control":"no-store"}})),l=async u=>{M(u,"POST","Backup-prune"),a(u,"prune");const{confirm:f}=await t(u);if(!Array.isArray(f)||f.some(w=>typeof w!="string"))throw new d("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 $r(n,f),{headers:{"cache-control":"no-store"}})};return{[Fr]:l,[Kr]:s}},ft=500,Qr=(e,n,t)=>{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 r=e;if(typeof r.functionPath!="string")throw new d("each batch call needs a string `functionPath`",{code:"BAD_REQUEST",status:400});if(r.functionPath.startsWith("__lunora_relation__:")||r.functionPath.startsWith("__lunora_admin__"))throw new d("reserved function path cannot be batched",{code:"FORBIDDEN",status:403});if(r.args!==void 0&&(typeof r.args!="object"||r.args===null||Array.isArray(r.args)))throw new d("each batch call `args` must be an object",{code:"BAD_REQUEST",status:400});return{entry:{args:r.args===void 0?{}:r.args,clientId:typeof r.clientId=="string"?r.clientId:void 0,clientSeq:typeof r.clientSeq=="number"?r.clientSeq:void 0,functionPath:r.functionPath,id:typeof r.id=="number"?r.id:n,mutationId:typeof r.mutationId=="string"?r.mutationId:void 0},shardKey:typeof r.shardKey=="string"?r.shardKey:t}},zr=(e,n)=>{if(e.length>ft)throw new d(`RPC batch exceeds the ${String(ft)}-call limit`,{code:"BAD_REQUEST",status:400});const t=new Map;for(const[r,a]of e.entries()){const{entry:s,shardKey:l}=Qr(a,r,n),u=t.get(l)??[];u.push(s),t.set(l,u)}return t},Wr=new TextEncoder,Vr=e=>{const n=JSON.stringify(e),t=Wr.encode(n);let r="";for(const a of t)r+=String.fromCodePoint(a);return btoa(r).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")},qr=e=>{const n={g:0,s:{},v:1};if(typeof e!="string"||e.length===0)return n;try{const t=atob(e.replaceAll("-","+").replaceAll("_","/")),r=new Uint8Array(t.length);for(let u=0;u<t.length;u+=1)r[u]=t.codePointAt(u)??0;const a=JSON.parse(new TextDecoder().decode(r)),s=a.s&&typeof a.s=="object"?a.s:{},l={};for(const[u,f]of Object.entries(s))typeof f=="number"&&Number.isFinite(f)&&(l[u]=f);return{g:typeof a.g=="number"&&Number.isFinite(a.g)?a.g:0,s:l,v:1}}catch{return n}},Jr=e=>{const n=typeof e.table=="string"?e.table:"",t=typeof e.op=="string"?e.op:"",r=t==="delete"||t==="insert"||t==="update"?t:"upsert",a=typeof e.id=="string"?e.id:void 0;return{doc:(e.doc&&typeof e.doc=="object"?e.doc:void 0)??(a===void 0?{}:{_id:a}),op:r,table:n}},pt=(e,n,t)=>{for(const r of n)e.push(Jr(r));return t!==void 0&&n.length>=t},Yr="/_lunora/admin/export",Xr="/_lunora/admin/import",Zr="/_lunora/admin/sync",eo="/_lunora/admin/connector/sync",to="/_lunora/admin/apply",no="/_lunora/admin/export-tap/run",ro=new TextEncoder,oo=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 a of t.tables){if(typeof a!="string"||a.length===0)throw new d("Export `tables` entries must be non-empty strings",{code:"BAD_REQUEST",status:400});r.push(a)}return{tables:r}},Le=e=>Array.isArray(e)?e.filter(n=>typeof n=="string"):void 0,ao=e=>{const{applyGlobals:n,exportCursorStore:t,exportSinks:r,knownTables:a,queryCoordinator:s,assertAdmin:l,requireAdminOption:u,resolveForwardContext:f,shardDO:w,streamExportRows:E,streamingImport:O,syncGlobals:I}=e,g=async(T,x)=>{const H=me(T,["POST"]);if(H)return H;const $=u(T,s,{code:"BAD_REQUEST",message:"Export endpoint requires a `queryCoordinator` on the worker"}),U=await oo(T),{headers:W}=await f(T,x),K=new ReadableStream({async pull(V){const X=q=>{V.enqueue(ro.encode(`${JSON.stringify(q)}
|
|
4
|
+
`))};try{await E($,W,U.tables,X),V.close()}catch(q){V.error(q)}}});return new Response(K,{headers:{"content-type":"application/x-ndjson"},status:200})},b=async(T,x)=>{const H=me(T,["POST"]);if(H)return H;const $=u(T,s,{code:"BAD_REQUEST",message:"Sync endpoint requires a `queryCoordinator` on the worker"}),U=await Z(T),W=typeof U.cursors=="object"&&U.cursors!==null?U.cursors:{},K=typeof U.limit=="number"?U.limit:void 0,V=typeof U.globalCursor=="number"?U.globalCursor:0,X=Le(U.tables),{headers:q}=await f(T,x),ae=X??a(),F=await $.orchestrateCdcSync(w,{cursors:W,headers:q,limit:K,tables:ae}),he=I?await I({limit:K,sinceSeq:V}):void 0;return Response.json({global:he,shards:F.shards},{status:200})},_=async(T,x)=>{const H=me(T,["POST"]);if(H)return H;const $=u(T,s,{code:"BAD_REQUEST",message:"Connector sync endpoint requires a `queryCoordinator` on the worker"}),U=await Z(T),W=qr(U.cursor),K=typeof U.limit=="number"&&U.limit>0?U.limit:void 0,V=Le(U.tables),{headers:X}=await f(T,x),q=V??a(),ae=await $.orchestrateCdcSync(w,{cursors:W.s,headers:X,limit:K,tables:q}),F=[],he={...W.s};let G=!1;for(const se of ae.shards)G=pt(F,se.changes??[],K)||G,he[se.shardKey]=se.cursor;let oe=W.g;if(I){const se=await I({limit:K,sinceSeq:W.g});G=pt(F,se.changes,K)||G,oe=se.cursor}const Te=Vr({g:oe,s:he,v:1}),Oe={changes:F,hasMore:G,nextCursor:Te};return Response.json(Oe,{status:200})},p=async(T,x)=>{const H=me(T,["POST"]);if(H)return H;const $=u(T,s,{code:"BAD_REQUEST",message:"Apply endpoint requires a `queryCoordinator` on the worker"}),U=await Z(T),K=(Array.isArray(U.batches)?U.batches:[]).map(F=>F).filter(F=>F!==null&&typeof F=="object"&&typeof F.shardKey=="string"&&Array.isArray(F.changes)),V=Array.isArray(U.globalChanges)?U.globalChanges:[],{headers:X}=await f(T,x),q=await $.orchestrateApplyCdc(w,{batches:K,headers:X}),ae=V.length>0&&n?await n({changes:V}):0;return Response.json({applied:q.applied+ae,failed:q.failed,ok:q.ok},{status:200})},S=async(T,x)=>{const H=me(T,["POST"]);if(H)return H;l(T);const{headers:$}=await f(T,x),U=await O(T,$);return Response.json(U,{headers:{"content-type":"application/json"},status:200})},D=async(T,x)=>{const H=me(T,["POST"]);if(H)return H;const $=u(T,s,{code:"BAD_REQUEST",message:"Export-tap endpoint requires a `queryCoordinator` on the worker"});if(r===void 0||Object.keys(r).length===0||t===void 0)throw new d("Export-tap endpoint requires `exportSinks` + `exportCursorStore` on the worker",{code:"EXPORT_TAP_NOT_CONFIGURED",status:400});const U=await Z(T),W=typeof U.sink=="string"?U.sink:void 0,K=typeof U.limit=="number"&&U.limit>0?U.limit:void 0,V=Le(U.tables);if(W===void 0)throw new d("Export-tap `sink` must name a configured sink",{code:"BAD_REQUEST",status:400});const X=r[W];if(X===void 0)throw new d(`Export-tap sink "${W}" is not configured`,{code:"NOT_FOUND",status:404});const{headers:q}=await f(T,x),ae=V??a(),F=await Jn({coordinator:$,cursorStore:t,headers:q,limit:K,shardDO:w,sink:X,tables:ae});return Response.json(F,{headers:{"content-type":"application/json"},status:200})};return{[to]:p,[eo]:_,[Yr]:g,[no]:D,[Xr]:S,[Zr]:b}},so=(e,n)=>{let t;try{t=JSON.parse(e)}catch{return{error:{code:"BAD_ROW",line:n,message:"line is not valid JSON",table:""},ok:!1}}if(!t||typeof t!="object"||Array.isArray(t))return{error:{code:"BAD_ROW",line:n,message:"row must be a JSON object",table:""},ok:!1};const r=t;return typeof r.table!="string"||r.table.length===0?{error:{code:"BAD_ROW",line:n,message:"row is missing `table`",table:""},ok:!1}:!r.doc||typeof r.doc!="object"||Array.isArray(r.doc)?{error:{code:"BAD_ROW",line:n,message:"row is missing or malformed `doc`",table:r.table},ok:!1}:{doc:r.doc,ok:!0,table:r.table}},io=(e,n,t,r,a)=>{if(t?.mode.kind==="shardBy"&&typeof t.mode.field=="string"){const s=e[t.mode.field];return s==null?{error:{code:"BAD_ROW",line:a,message:`row missing shard field "${t.mode.field}" for table "${n}"`,table:n},ok:!1}:{ok:!0,shardKey:typeof s=="string"?s:JSON.stringify(s)}}return{ok:!0,shardKey:r}},co=async(e,n,t)=>{if(!e.body)throw new d("Import endpoint requires a request body",{code:"BAD_REQUEST",status:400});const r=[],a=[],s=new Map;let l=0,u=0;const f=e.body.getReader(),w=new TextDecoder;let E="",O=0;const I=g=>{u+=1;const b=g.trim();if(b.length===0)return;l+=1;const _=so(b,u);if(!_.ok){r.push(_.error);return}const{doc:p,table:S}=_,D=n.resolveTableSharding?.(S);if(D?.mode.kind==="global"){a.push({doc:p,line:u,table:S});return}const T=io(p,S,D,t,u);if(!T.ok){r.push(T.error);return}const x=s.get(T.shardKey);x?x.rows.push({doc:p,table:S}):s.set(T.shardKey,{rows:[{doc:p,table:S}],shardKey:T.shardKey,startLine:u})};for(;;){const{done:g,value:b}=await f.read();if(g)break;if(b&&(O+=b.byteLength,O>Dt))throw await f.cancel().catch(()=>{}),new d("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});E+=w.decode(b,{stream:!0});let _=E.indexOf(`
|
|
5
|
+
`);for(;_!==-1;){const p=E.slice(0,_);E=E.slice(_+1),I(p),_=E.indexOf(`
|
|
6
|
+
`)}}return E.length>0&&I(E),{errors:r,globalRows:a,perShard:s,received:l}},mt=(e,n)=>{for(const[t,r]of Object.entries(n.inserted))e.inserted[t]=(e.inserted[t]??0)+r;for(const t of n.errors)e.errors.push({...t});e.conflicts+=n.conflicts},uo=async(e,n,t,r)=>{const a=n.defaultShardKey??"__root__",{errors:s,globalRows:l,perShard:u,received:f}=await co(e,n,a),w={conflicts:0,errors:s,inserted:{}},E=[];if(n.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 O=n.queryCoordinator;if(!O)throw new d("Import endpoint requires a `queryCoordinator` on the worker",{code:"BAD_REQUEST",status:400});const I=await O.orchestrateImport(r,{batches:[...u.values()],headers:t});mt(w,I)}if(l.length>0)if(n.importGlobals){const O=l[0]?.line??1,I=await n.importGlobals({rows:l,startLine:O});mt(w,I)}else for(const O of l)w.errors.push({code:"GLOBAL_NOT_CONFIGURED",line:O.line,message:`row targets global table "${O.table}" but no \`importGlobals\` is configured`,table:O.table});return{conflicts:w.conflicts,errors:w.errors,inserted:w.inserted,received:f,...E.length>0?{warnings:E}:{}}},je=e=>typeof e=="object"&&e!==null?e:{},Me=e=>typeof e.kind=="string"?e.kind:"unknown",lo=(e,n)=>{let t=je(n),r=!1;Me(t)==="optional"&&(r=!0,t=je(t._meta?.inner));const a=Me(t),s=t._meta??{},l={kind:a,name:e,optional:r};if(a==="id"&&typeof s.tableName=="string"&&(l.table=s.tableName),a==="array"){const u=Me(je(s.inner));u!=="unknown"&&(l.element=u)}return l},ho=e=>typeof e!="object"||e===null?[]:Object.entries(e).map(([n,t])=>lo(n,t)).toSorted((n,t)=>n.name.localeCompare(t.name)),fo="/_lunora/admin/functions",po="/_lunora/admin/cron-jobs",mo="/_lunora/admin/openapi",wo="/_lunora/admin/openrpc",go="/_lunora/admin/global/tables",yo="/_lunora/admin/global/table",bo="/_lunora/admin/global/facet",wt=e=>{if(e===void 0||e==="")return;let n;try{n=JSON.parse(e)}catch{return}if(!Array.isArray(n))return;const t=n.flatMap(r=>{if(typeof r!="object"||r===null||typeof r.column!="string")return[];const{column:a,value:s}=r;return[{column:a,value:s}]});return t.length===0?void 0:t},_o=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:{}}),Ro=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"}),Eo=e=>{const{assertAdmin:n,options:t,parsePaging:r,queryParameter:a,requireAdminOption:s}=e,l=g=>{M(g,"GET","Functions");const b=s(g,t.functions,{code:"FUNCTIONS_NOT_CONFIGURED",message:"functions endpoint requires a `functions` registry on the worker"}),_=Object.entries(b).flatMap(([p,S])=>S.visibility==="internal"||S.kind==="stream"?[]:[{args:ho(S.args),kind:S.kind,path:p}]).toSorted((p,S)=>p.path.localeCompare(S.path));return Response.json({functions:_},{headers:{"content-type":"application/json"},status:200})},u=g=>{M(g,"GET","Cron-jobs");const b=s(g,t.cronJobs,{code:"CRON_JOBS_NOT_CONFIGURED",message:"cron-jobs endpoint requires a `cronJobs` map on the worker"}),_=Object.entries(b).flatMap(([p,S])=>S.map(D=>({args:D.args,cron:p,functionPath:D.functionPath,name:D.name,shardKey:D.shardKey,workflow:D.workflow}))).toSorted((p,S)=>p.name.localeCompare(S.name));return Response.json({jobs:_},{headers:{"content-type":"application/json"},status:200})},f=g=>(M(g,"GET","OpenAPI"),n(g),Response.json(t.openApiSpec??_o,{headers:{"content-type":"application/json"},status:200})),w=g=>(M(g,"GET","OpenRPC"),n(g),Response.json(t.openRpcSpec??Ro,{headers:{"content-type":"application/json"},status:200})),E=async g=>{M(g,"GET","Global-tables");const b=s(g,t.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"});return Response.json(await b.listTables(),{headers:{"content-type":"application/json"},status:200})},O=async g=>{M(g,"GET","Global-table");const b=s(g,t.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),_=new URL(g.url),p=a(_,"table");if(p===void 0)throw new d("Global-table endpoint requires a `table` query param",{code:"BAD_REQUEST",status:400});const S=await b.readTablePage({...r(g),filters:wt(a(_,"filters")),table:p});return Response.json(S,{headers:{"content-type":"application/json"},status:200})},I=async g=>{M(g,"GET","Global-facet");const b=s(g,t.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),_=new URL(g.url),p=a(_,"table"),S=a(_,"column");if(p===void 0||S===void 0)throw new d("Global-facet endpoint requires `table` and `column` query params",{code:"BAD_REQUEST",status:400});const D=a(_,"limit"),T=D===void 0?void 0:Number(D),x=await b.facetColumn({column:S,filters:wt(a(_,"filters")),limit:T!==void 0&&Number.isFinite(T)?T:void 0,table:p});return Response.json(x,{headers:{"content-type":"application/json"},status:200})};return{[po]:u,[fo]:l,[bo]:I,[yo]:O,[go]:E,[mo]:f,[wo]:w}},Ao="/_lunora/admin/kv/namespaces",So="/_lunora/admin/kv/keys",Qt="/_lunora/admin/kv/value",zt=32*1048576,gt=60,To=e=>{const{readJsonBody:n,requireAdminOption:t}=e,r=b=>t(b,e.kvIntrospector,{code:"KV_NOT_CONFIGURED",message:"KV endpoints require a `kvIntrospector` on the worker"}),a=b=>Response.json(b,{headers:{"content-type":"application/json"},status:200}),s=(b,_)=>{const p=new URL(b.url),S=p.searchParams.get("namespace")??"",D=p.searchParams.get("key")??"";if(S==="")throw new d(`KV-value ${_} request requires a \`namespace\` query parameter`,{code:"BAD_REQUEST",status:400});if(D==="")throw new d(`KV-value ${_} request requires a \`key\` query parameter`,{code:"BAD_REQUEST",status:400});return{key:D,namespace:S}},l=async(b,_)=>{if(!(await b.listNamespaces()).some(S=>S.binding===_))throw new d(`Unknown KV namespace binding \`${_}\``,{code:"NOT_FOUND",status:404})},u=async b=>(M(b,"GET","KV-namespaces"),a({namespaces:await r(b).listNamespaces()})),f=async b=>{M(b,"GET","KV-keys");const _=r(b),p=new URL(b.url),S=p.searchParams.get("namespace")??"";if(S==="")throw new d("KV-keys request requires a `namespace` query parameter",{code:"BAD_REQUEST",status:400});const D=p.searchParams.get("prefix")??void 0,T=p.searchParams.get("cursor")??void 0,x=p.searchParams.get("limit"),H=x===null?void 0:Number.parseInt(x,10);if(H!==void 0&&(!Number.isInteger(H)||H<1))throw new d("KV-keys `limit` must be a positive integer",{code:"BAD_REQUEST",status:400});const $=H===void 0?void 0:Math.min(H,1e3);return await l(_,S),a(await _.listKeys({cursor:T,limit:$,namespace:S,prefix:D}))},I={DELETE:async b=>{const _=r(b),p=s(b,"DELETE");return await l(_,p.namespace),await _.deleteKey(p),a({deleted:!0})},GET:async b=>{const _=r(b),p=s(b,"GET");return await l(_,p.namespace),a(await _.getValue(p))},PUT:async b=>{const _=r(b),p=await n(b,zt);if(typeof p.namespace!="string"||p.namespace==="")throw new d("KV-value PUT request requires a `namespace` string",{code:"BAD_REQUEST",status:400});if(typeof p.key!="string"||p.key==="")throw new d("KV-value PUT request requires a `key` string",{code:"BAD_REQUEST",status:400});if(typeof p.value!="string")throw new d("KV-value PUT request requires a `value` string",{code:"BAD_REQUEST",status:400});if(p.expirationTtl!==void 0&&(typeof p.expirationTtl!="number"||!Number.isInteger(p.expirationTtl)||p.expirationTtl<gt))throw new d("KV-value PUT `expirationTtl` must be an integer ≥ 60",{code:"BAD_REQUEST",status:400});const S=Math.floor(Date.now()/1e3)+gt;if(p.expiration!==void 0&&(typeof p.expiration!="number"||!Number.isInteger(p.expiration)||p.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 l(_,p.namespace),await _.putValue({expiration:p.expiration,expirationTtl:p.expirationTtl,key:p.key,metadata:p.metadata,namespace:p.namespace,value:p.value}),a({ok:!0})}},g=b=>{const _=I[b.method];if(!_)throw new d("KV-value endpoint requires GET, PUT, or DELETE",{code:"METHOD_NOT_ALLOWED",status:405});return _(b)};return{[Ao]:u,[So]:f,[Qt]:g}},Oo="/_lunora/migrate",vo="/_lunora/admin/pitr",ko="/_lunora/admin/rank",Io="/_lunora/admin/rankpage",Po="/_lunora/admin/shard-traffic",Do=new Set(["__lunora_admin__:migrationStatus","__lunora_admin__:runMigration"]),No=new Set(["__lunora_admin__:getPitrBookmark","__lunora_admin__:pitrRestore"]),Uo=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"||!Do.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}},Co=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}},Bo=e=>{if(e!==void 0){if(!Array.isArray(e)||e.some(n=>n!=="asc"&&n!=="desc"))throw new d('Rank page request `directions` must be an array of "asc"|"desc"',{code:"BAD_REQUEST",status:400});return e}},xo=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})},Ho=async e=>{const t=await be(e,"Rank page")??{};xo(t);const r=Bo(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}},Lo=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}},jo=async e=>{const t=await Z(e);if(typeof t.functionPath!="string"||!No.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}},Mo=e=>{const{defaultShard:n,forwardToShard:t,isAdmin:r,queryCoordinator:a,resolveForwardContext:s,shardDO:l}=e,u=(g,b)=>{if(g.method!=="POST")throw new d(`${b} endpoint requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});if(!r(g))throw new d("Admin auth required",{code:"FORBIDDEN",status:403});if(!a)throw new d(`${b} endpoint requires a \`queryCoordinator\` on the worker`,{code:"BAD_REQUEST",status:400});return a},f=async(g,b)=>{const _=u(g,"Migration"),p=await Uo(g),{headers:S}=await s(g,b),D=await _.orchestrateMigration(l,{args:p.args,functionPath:p.functionPath,headers:S,table:p.table});return Response.json(D,{headers:{"content-type":"application/json"},status:200})},w=async(g,b)=>{const _=u(g,"Rank"),p=await Co(g),{headers:S}=await s(g,b),D=await _.orchestrateRank(l,{headers:S,index:p.index,partitionKey:p.partitionKey,rowId:p.rowId,sortValues:p.sortValues,table:p.table});return Response.json(D,{headers:{"content-type":"application/json"},status:200})},E=async(g,b)=>{const _=u(g,"Rank page"),p=await Ho(g),{headers:S}=await s(g,b),D=await _.orchestrateRankPage(l,{...p,headers:S});return Response.json(D,{headers:{"content-type":"application/json"},status:200})},O=async(g,b)=>{const _=u(g,"Shard-traffic"),p=await Lo(g),{headers:S}=await s(g,b),D=await _.orchestrateShardTraffic(l,{headers:S,table:p.table});return Response.json(D,{headers:{"content-type":"application/json"},status:200})},I=async(g,b)=>{if(M(g,"POST","PITR"),!r(g))throw new d("admin PITR endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403});const _=await jo(g),{headers:p}=await s(g,b),S=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:_.args,functionPath:_.functionPath}),headers:p,method:"POST"});return t(l,_.shardKey??n,S)};return{[Oo]:f,[vo]:I,[ko]:w,[Io]:E,[Po]:O}},$o=1,Ko=0,Fo=32,Go=512,Qo=/^[a-z][\d_a-z*/-]{0,255}(?:@[a-z][\d_a-z*/-]{0,13})?=[\u0020-\u002B\u002D-\u003C\u003E-\u007E]{1,256}$/,zo=e=>{if(e==null)return;const n=e.trim();if(n.length===0||n.length>Go)return;const t=n.split(",");if(!(t.length>Fo)){for(const r of t)if(!Qo.test(r.trim()))return;return n}},Wo=e=>{const n=xn(e.headers.get("traceparent"));if(n===void 0)return;const t=zo(e.headers.get("tracestate"));return{parentSpanId:n.parentSpanId,sampled:n.sampled,traceId:n.traceId,...t===void 0?{}:{traceState:t}}},Vo=(e,n={})=>{const t=Wo(e),r=n.trustInbound===!0?t:void 0,a=Se(8),s=r?.traceId??Se(16),l=nr(n.sampling,r===void 0?a:s),u=l.isTraced&&(r===void 0||r.sampled);return{decision:l,ignoredUpstream:t!==void 0&&r===void 0,trace:{sampled:u,spanId:a,traceFlags:u?$o:Ko,traceId:s,...r?.parentSpanId===void 0?{}:{parentSpanId:r.parentSpanId},...r?.traceState===void 0?{}:{traceState:r.traceState}}}},qo=(e,n)=>{n.traceparent=Bn(e.traceId,e.spanId,e.sampled),e.traceState!==void 0&&(n.tracestate=e.traceState)},Jo=(e,n)=>{let t;return()=>{if(t===void 0){const r=Mn(e),a=n===void 0?void 0:n.cf;t=Hn(jn(r),Ln(r,a))}return t}},Yo="/_lunora/admin/scheduled",Xo="/_lunora/admin/scheduled/status",Zo="/_lunora/admin/scheduled/ws",ea="/_lunora/admin/scheduled/cancel",ta="/_lunora/admin/scheduled/dead",na="/_lunora/admin/scheduled/dead/retry",ra="/_lunora/admin/scheduled/dead/cancel",oa=e=>{const{checkWsAdmin:n,requireSchedulerNamespace:t,resolveSchedulerStub:r,schedulerInstanceName:a}=e,s=(f,w)=>E=>{if(E.method!=="GET")throw new d(`${w} endpoint requires GET`,{code:"METHOD_NOT_ALLOWED",status:405});return r(E).fetch(new Request(`https://scheduler.internal${f}`,{method:"GET"}))},l=(f,w,E=w)=>async O=>{if(O.method!=="POST")throw new d(`${E} requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});const I=r(O),g=await O.json().catch(()=>{});if(typeof g?.id!="string"||g.id==="")throw new d(`${w} requires a string \`id\``,{code:"BAD_REQUEST",status:400});return I.fetch(new Request(`https://scheduler.internal${f}`,{body:JSON.stringify({id:g.id}),headers:{"content-type":"application/json"},method:"POST"}))},u=async f=>{if(f.headers.get("Upgrade")!=="websocket")throw new d("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});if(!await n(f))throw new d("admin authorization required",{code:"ADMIN_FORBIDDEN",status:403});const w=t();return we(w,a).fetch(new Request("https://scheduler.internal/ws",{headers:{Upgrade:"websocket"}}))};return{[ea]:l("/cancel","Scheduled-cancel","Scheduled-cancel endpoint"),[ra]:l("/dead/cancel","Scheduled dead-letter action"),[ta]:s("/dead","Scheduled dead-letter"),[na]:l("/dead/retry","Scheduled dead-letter action"),[Yo]:s("/list","Scheduled-list"),[Xo]:s("/status","Scheduler-status"),[Zo]:u}},aa=(e,...n)=>{let t=e.cf;for(const r of n){if(typeof t!="object"||t===null)return;t=t[r]}return typeof t=="string"?t:void 0},yt={mtls:e=>aa(e,"tlsClientAuth","certVerified")==="SUCCESS"},sa=e=>e===void 0||e===!1?()=>!1:e===!0?()=>!0:typeof e=="function"?e:(Object.hasOwn(yt,e)?yt[e]:void 0)??(()=>!1),ia=e=>{if(e!==void 0)return()=>{};let n=!1;return()=>{n||(n=!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.'))}},ca="/_lunora/admin/vector/indexes",da="/_lunora/admin/vector/query",ua=e=>{const{readJsonBody:n,requireAdminOption:t}=e,r=async s=>{M(s,"GET","Vector-indexes");const l=t(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})},a=async s=>{M(s,"POST","Vector-query");const l=t(s,e.vectorIntrospector,{code:"VECTORS_NOT_CONFIGURED",message:"vector endpoints require a `vectorIntrospector` on the worker"});if(l.queryIndex===void 0)throw new d("vector index querying is not enabled on this worker",{code:"VECTOR_QUERY_UNSUPPORTED",status:400});const f=await n(s);if(typeof f.name!="string"||f.name==="")throw new d("Vector-query request requires a `name` string",{code:"BAD_REQUEST",status:400});if(typeof f.text!="string"||f.text==="")throw new d("Vector-query request requires a `text` string",{code:"BAD_REQUEST",status:400});if(f.topK!==void 0&&(typeof f.topK!="number"||!Number.isInteger(f.topK)||f.topK<1))throw new d("Vector-query `topK` must be a positive integer",{code:"BAD_REQUEST",status:400});const w=await l.queryIndex({name:f.name,text:f.text,topK:f.topK});return Response.json(w,{headers:{"content-type":"application/json"},status:200})};return{[ca]:r,[da]:a}},la="/_lunora/admin/workflows/instances",ha="/_lunora/admin/workflows/instance",fa="/_lunora/admin/workflows/status",pa={complete:!0,errored:!0,paused:!0,queued:!0,running:!0,terminated:!0,unknown:!0,waiting:!0,waitingForPause:!0},ma=e=>e!==null&&Object.hasOwn(pa,e)?e:void 0,bt=(e,n)=>{const t=e.searchParams.get(n);if(t===null)return;const r=Number(t);return Number.isInteger(r)&&r>0?r:void 0},$e=(e,n)=>{const t=e.searchParams.get(n);if(t===null||t==="")throw new d(`Workflows admin endpoint requires a \`${n}\` query parameter`,{code:"BAD_REQUEST",status:400});return t},_t=()=>{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})},wa=e=>{const{assertAdmin:n,resolveWorkflowsClient:t}=e,r=async(l,u,f)=>{M(l,"GET","Workflows instances"),n(l);const w=t(u);if(!w)return Response.json({configured:!1,instances:[],page:1,perPage:0,totalCount:0});const E=$e(f,"name"),O=ma(f.searchParams.get("status"));return Response.json(await w.listInstances({page:bt(f,"page"),perPage:bt(f,"perPage"),status:O,workflowName:E}))},a=async(l,u,f)=>{M(l,"GET","Workflows instance"),n(l);const w=t(u);return w?Response.json(await w.getInstance({instanceId:$e(f,"id"),workflowName:$e(f,"name")})):_t()},s=async(l,u)=>{M(l,"POST","Workflows status"),n(l);const f=t(u);if(!f)return _t();const w=await l.json().catch(()=>{});if(typeof w?.name!="string"||w.name===""||typeof w.id!="string"||w.id==="")throw new d("Workflows status action requires string `name` and `id`",{code:"BAD_REQUEST",status:400});const{action:E}=w;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:w.id,workflowName:w.name}))};return{[ha]:a,[la]:r,[fa]:s}},ga={[Qt]:zt,[qn]:Vn},Rt="/_lunora/rpc",ya="/_lunora/rpc-batch",ba="/_lunora/ws",Re=(e,n,t)=>({resourceAttributes:Jo(e,n),...t===void 0?{}:{waitUntil:t}}),Et=e=>e?.waitUntil?{waitUntil:n=>e.waitUntil?.(n)}:{},At=e=>({spanId:e.spanId,traceFlags:e.traceFlags,traceId:e.traceId,...e.parentSpanId===void 0?{}:{parentSpanId:e.parentSpanId}}),Ke=e=>{const{method:n}=e,t=e.headers.get("user-agent")??void 0;let r;try{r=new URL(e.url)}catch{return{method:n,userAgent:t}}const a=r.port===""?void 0:Number(r.port);return{host:r.hostname,method:n,path:r.pathname,port:Number.isNaN(a)?void 0:a,scheme:r.protocol.replace(":",""),userAgent:t}},St="/_lunora/voice/",_a="/_lunora/scheduler/dispatch",Ra="/_lunora/admin/cron-jobs/run",Ea="/_lunora/admin/ws-token",Aa="/_lunora/admin/",Sa="/_lunora/migrate",Ta="/_lunora/status",Oa=e=>e.startsWith(Aa)||e===Sa,va=e=>{const n=e.headers.get("x-lunora-userid"),t=e.headers.get("x-lunora-identity");if(!(n===null&&t===null))return{...t===null?{}:{identity:t},...n===null?{}:{userId:n}}},ka="/api/auth",Ia="__lunora_admin__:recordAuthEvent",Pa="__lunora_admin__:listPushSubscriptions",Da=["/sign-in","/sign-up","/callback"],Na=(e,n)=>{const t=n.endsWith("/")?n.slice(0,-1):n;if(!e.startsWith(`${t}/`))return!1;const r=e.slice(t.length);return Da.some(a=>r===a||r.startsWith(`${a}/`))},Ee=(e,n,t,r)=>{const a=Pn(t),s=a?t.code:"INTERNAL_SERVER_ERROR",l=a?t.status:500,u=t instanceof Error?t.message:String(t);return{durationMs:n,error:{code:s,message:u,status:l},functionPath:e,ok:!1,...r.fanOut?{fanOut:{failed:0,shards:0,table:r.fanOut.table}}:{},...r.shardKey?{shardKey:r.shardKey}:{}}},Ua=e=>{const{exp:n,expiresAtMs:t}=e;if(typeof t=="number"&&Number.isFinite(t))return t;if(typeof n=="number"&&Number.isFinite(n))return n*1e3},Tt=e=>e.waitUntil?{waitUntil:n=>{e.waitUntil?.(n)}}:void 0,Ca=e=>{const n=e?.queue;return typeof n=="string"&&n.length>0?n:"unknown"},de=async(e,n,t)=>{const r={"content-type":"application/json"},a=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"),w=e.headers.get("x-lunora-client-seq");a&&(r.authorization=a),s&&(r.cookie=s),l&&(r["x-d1-bookmark"]=l),u&&(r["x-lunora-mutation-id"]=u),f&&(r["x-lunora-client-id"]=f),w&&(r["x-lunora-client-seq"]=w);const E=e.headers.get("cf-connecting-ip");if(E&&(r["x-lunora-client-ip"]=E),!t)return{claims:null,headers:r,identity:null,userId:null};const O=await t(e,n);if(!O||typeof O.userId!="string"||O.userId.length===0)return{claims:null,headers:r,identity:null,userId:null};r["x-lunora-userid"]=Un(O.userId);const I=Ua(O);I!==void 0&&(r["x-lunora-identity-exp"]=String(I));const{userId:g,...b}=O,_=Object.keys(b).length>0?b:null;return _&&(r["x-lunora-identity"]=Cn(_)),{claims:_,headers:r,identity:O,userId:g}},Ba=new Set(["concat","first","groupBy","max","min","rank","sum","topK"]),xa=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 n=e;if(typeof n.table!="string"||n.table.length===0)throw new d("RPC `fanOut.table` must be a non-empty string",{code:"BAD_REQUEST",status:400});if(!n.merge||typeof n.merge!="object")throw new d("RPC `fanOut.merge` must be an object",{code:"BAD_REQUEST",status:400});const t=n.merge;if(typeof t.kind!="string"||!Ba.has(t.kind))throw new d("RPC `fanOut.merge.kind` is not a recognized merge strategy",{code:"BAD_REQUEST",status:400});if(t.kind==="topK"){if(typeof t.k!="number"||!Number.isInteger(t.k)||t.k<0)throw new d("RPC `fanOut.merge.k` must be a non-negative integer",{code:"BAD_REQUEST",status:400});if(typeof t.by!="string"||t.by.length===0)throw new d("RPC `fanOut.merge.by` must be a non-empty string",{code:"BAD_REQUEST",status:400})}return n},Ha=(e,n)=>{e?.LUNORA_DEBUG_RPC&&console.warn(`[lunora:rpc] ${n.fanOut?"fan-out":`shard=${n.shardKey??"(root)"}`} ${n.functionPath}`)},Ot=(e,n)=>{const t=n.functions?.[e.functionPath]?.x402;if(t){if(e.fanOut)throw new d("a paid (`.x402`) function cannot be fanned out",{code:"BAD_REQUEST",status:400});if(!n.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 t}},La=async e=>{const n=await Ut(e);let t;try{t=JSON.parse(n)}catch{throw new d("RPC body must be valid JSON",{code:"BAD_REQUEST",status:400})}if(!t||typeof t!="object"||typeof t.functionPath!="string")throw new d("RPC envelope is missing `functionPath`",{code:"BAD_REQUEST",status:400});const r=t;if(r.args!==void 0&&Nt(r.args,"RPC"),r.shardKey!==void 0&&typeof r.shardKey!="string")throw new d("RPC `shardKey` must be a string",{code:"BAD_REQUEST",status:400});const a=t,s=xa(a.fanOut),l=a.args??{};if(s&&a.functionPath.startsWith("__lunora_relation__:")){const u=l.table;if(typeof u=="string"&&u!==s.table)throw new d("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:a.functionPath,shardKey:a.shardKey}},Ae=new Map,ja=5e3,Ma=4096,$a=async(e,n)=>{const t=Date.now(),r=Ae.get(n);if(r!==void 0&&r.expiresMs>t)return r.relayCount;r!==void 0&&Ae.delete(n);let a=0;try{const s=await we(e,n).fetch(new Request("https://shard.internal/_lunora/route"));if(s.ok){const u=(await s.json()).relayCount;typeof u=="number"&&u>0&&(a=Math.floor(u))}}catch{a=0}return Pt(Ae,Ma),Ae.set(n,{expiresMs:t+ja,relayCount:a}),a},vt=(e,n)=>{if(!(e===null||typeof e!="object"))return Object.entries(e).find(([,t])=>t===n)?.[0]},ye=(e,n,t)=>new Request("https://shard.internal/rpc",{body:JSON.stringify({args:n,functionPath:e}),headers:t,method:"POST"}),Ka=["x-lunora-userid","x-lunora-identity","x-lunora-identity-exp"],kt=(e,n)=>{for(const t of Ka){e.delete(t);const r=n[t];r!==void 0&&e.set(t,r)}},Fa=async(e,n,t)=>e.length===0||t.length===0?!1:Qe(await Ht(e,n),t),It=(e,n)=>{if(!n||n.length===0)return!1;const t=e.headers.get("authorization");if(!t)return!1;const[r,...a]=t.split(" ");return r?.toLowerCase()!=="bearer"?!1:Qe(n,a.join(" ").trim())},Ga=async(e,n,t)=>{if(!n||n.length===0)return!1;const r=new URL(e.url).searchParams.get("token");return r===null?!1:await Or(n,r)?!0:t?!1:Qe(n,r)},Qa=(e,n)=>{if(n===null||typeof n!="object"&&typeof n!="function")return;const t=n;if(typeof t.prepare=="function"&&typeof t.batch=="function"&&typeof t.dump=="function")return Zn(`d1:${e}`,n);if(typeof t.list=="function"&&typeof t.head=="function"&&typeof t.createMultipartUpload=="function")return Ce(`r2:${e}`,!0);if(typeof t.send=="function"&&typeof t.sendBatch=="function"&&typeof t.get!="function")return Ce(`queue:${e}`,!0);if(typeof t.connectionString=="string")return Ce(`hyperdrive:${e}`,!0)},Wt=e=>{const n=sa(e.trustInboundTraceContext),t=ia(e.trustInboundTraceContext),r=e.defaultShardKey??"__root__",a=er(e.resolveIdentity,e.identity),s=nt(e.shardDO,e.jurisdiction),l=e.schedulerDO===void 0?void 0:nt(e.schedulerDO,e.jurisdiction);let u=!1;const f=o=>{if(o===void 0||e.jurisdiction===void 0)return o;u||(u=!0,console.warn(`[lunora] jurisdiction "${e.jurisdiction}" pins placement, so region hints (\`shardRegion\`, replica and relay placement) are not sent. Residency wins.`))},w=async(o,i,h,c=e.shardRegion?.(i))=>we(o,i,f(c)).fetch(h);let E;const O=()=>e.adminToken??E;let I;const g=()=>e.requireEphemeralWsToken??I??!0;let b;const _=o=>{const i=o??{};if(b??=vt(o,e.shardDO),I===void 0&&e.requireEphemeralWsToken===void 0){const c=i.LUNORA_REQUIRE_EPHEMERAL_WS_TOKEN;typeof c=="string"&&c.length>0&&(I=Ar(c,!0))}if(E!==void 0||e.adminToken!==void 0)return;const h=i.LUNORA_ADMIN_TOKEN;typeof h=="string"&&h.length>0&&(E=h)},p=new WeakSet,S=o=>It(o,O())||p.has(o),D=async(o,i)=>{const h=await de(o,i,e.resolveIdentity);if(p.has(o)&&h.headers.authorization===void 0){const c=O();c!==void 0&&(h.headers.authorization=`Bearer ${c}`)}return h};let T=!1,x=!1;const H=()=>{x||(x=!0,console.warn("[lunora] `replicaReads: true` has no effect without `functions` — read eligibility is decided from the function registry."))},$=o=>{if(!e.allowUnauthenticatedShardAccess){const i=o==="fan-out"?"authorizeFanOut":"authorizeShard";throw new d(`${o} access is default-denied: configure \`${i}\` on the worker, or set \`allowUnauthenticatedShardAccess: true\` to explicitly allow unauthenticated ${o} access (relying solely on per-row RLS).`,{code:o==="fan-out"?"FORBIDDEN_FANOUT":"FORBIDDEN_SHARD",status:403})}T||(T=!0,console.warn([`[lunora] SECURITY: serving ${o} 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("")))},U=async(o,i,h=!0)=>{if(e.authorizeShard){if(!await e.authorizeShard(o,i))throw new d("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else h&&i!==r&&$("shard")},W=Mo({defaultShard:r,forwardToShard:w,isAdmin:S,queryCoordinator:e.queryCoordinator,resolveForwardContext:D,shardDO:s}),K=async(o,i,h,c,m)=>{await U(null,h,!1);const R={"content-type":"application/json","x-lunora-system":"1"};return m?.userId!==void 0&&m.userId.length>0&&(R["x-lunora-userid"]=m.userId),m?.identity!==void 0&&m.identity.length>0&&(R["x-lunora-identity"]=m.identity),c!==void 0&&c.length>0&&(R["x-lunora-mutation-id"]=c),w(s,h,ye(o,i,R))},V=async(o,i,h,c)=>{const m=h?.[o];if(!m||typeof m.create!="function")throw new d(`${c} targets workflow binding "${o}", which is not bound on env`,{code:"CRON_JOB_FAILED",status:500});if(sr(i))throw new d(`${c} params ${ir}`,{code:"BAD_REQUEST",status:400});await m.create({params:i})},X=async(o,i)=>{if(o.workflow){await V(o.workflow,o.args??{},i,`cron job "${o.name}"`);return}if(o.functionPath===void 0)throw new d(`cron job "${o.name}" has neither a function target nor a workflow target`,{code:"CRON_JOB_FAILED",status:500});const h=await K(o.functionPath,o.args??{},o.shardKey??r);if(!h.ok)throw new d(`cron job "${o.name}" (${o.functionPath}) failed with shard status ${String(h.status)}`,{code:"CRON_JOB_FAILED",status:500})},q=async(o,i,h,c)=>{const m=e.cronJobs?.[o];if(m)for(const R of m)try{await X(R,i)}catch(k){h.push(c(k))}},ae=async(o,i)=>{if(!S(o))throw new d("admin endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403});if(M(o,"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 h=await Z(o),c=typeof h.name=="string"?h.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(R=>R.name===c);if(!m)throw new d(`no cron job named "${c}" is registered`,{code:"CRON_JOB_NOT_FOUND",status:404});return await X(m,i),Response.json({name:c,ran:!0},{status:200})},F=async o=>{const i=typeof o.pool=="string"&&o.pool.length>0?o.pool:void 0;if(!i||!l||typeof o.id!="string")return;const h=typeof o.instanceName=="string"&&o.instanceName.length>0?o.instanceName:"default";try{await we(l,h).fetch(new Request("https://scheduler.internal/complete",{body:JSON.stringify({id:o.id,pool:i}),headers:{"content-type":"application/json"},method:"POST"}))}catch{}},he=async(o,i)=>{M(o,"POST","Scheduler dispatch");const h=await Ut(o),c=i??{},m=typeof c.LUNORA_SCHEDULER_SECRET=="string"?c.LUNORA_SCHEDULER_SECRET:void 0,R=e.adminToken??(typeof c.LUNORA_ADMIN_TOKEN=="string"?c.LUNORA_ADMIN_TOKEN:void 0),k=o.headers.get("x-lunora-scheduler-signature");let y=!1;if(k&&m?y=await Fa(m,h,k):R&&(y=It(o,R)),!y)throw new d("Scheduler dispatch requires a valid signature or admin bearer",{code:"FORBIDDEN",status:403});let A;try{A=JSON.parse(h)}catch{throw new d("Scheduler dispatch body must be valid JSON",{code:"BAD_REQUEST",status:400})}const v=A??{},C=v.args??{};if(typeof v.workflow=="string"&&v.workflow.length>0)return await V(v.workflow,C,i,"scheduled workflow"),Response.json({ok:!0},{status:200});if(typeof v.functionPath!="string"||v.functionPath.length===0)throw new d("Scheduler dispatch is missing `functionPath`",{code:"BAD_REQUEST",status:400});const B=typeof v.shardKey=="string"&&v.shardKey.length>0?v.shardKey:r,L=typeof v.id=="string"&&v.id.length>0?v.id:void 0,te=va(o),j=await K(v.functionPath,C,B,L,te);return await F(v),j},G=o=>{if(!S(o))throw new d("admin endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403})},oe=(o,i,h)=>{if(G(o),i===void 0)throw new d(h.message,{code:h.code,status:400});return i},Te=Dr({assertAdmin:G,getReader:()=>e.authAuditReader}),Oe=async(o,i)=>{G(o);const h=e.notifySubscriptionStore;if(h===void 0)return Response.json({subscriptions:[]},{headers:{"content-type":"application/json"},status:200});const c=i?.kind,m=i?.userId,R=i?.limit,k=c==="fcm"||c==="web-push"?c:void 0,y=typeof m=="string"&&m!==""?m:void 0,A=typeof R=="number"&&Number.isFinite(R)?Math.trunc(R):0,v=A>0?Math.min(A,1e3):1e3,B=(await h.list({kind:k,limit:v,userId:y})).filter(L=>k!==void 0&&L.kind!==k?!1:y===void 0||(L.userId??null)===y).map(({keys:L,token:te,...j})=>j);return Response.json({subscriptions:B},{headers:{"content-type":"application/json"},status:200})},se=async(o,i)=>{if(!i.fanOut){if(i.functionPath===Pr)return Te(o,i.args??{});if(i.functionPath===Pa)return Oe(o,i.args)}},Vt=ao({applyGlobals:e.applyGlobals,assertAdmin:G,exportCursorStore:e.exportCursorStore,exportSinks:e.exportSinks,knownTables:()=>[],queryCoordinator:e.queryCoordinator,requireAdminOption:oe,resolveForwardContext:D,shardDO:s,streamExportRows:(o,i,h,c)=>Kt(e,o,i,h,c,s),streamingImport:(o,i)=>uo(o,e,i,s),syncGlobals:e.syncGlobals}),ve=(o,i)=>{const h=o.searchParams.get(i);return h===null||h===""?void 0:h},ke=o=>{const i=new URL(o.url),h=i.searchParams.get("limit"),c=i.searchParams.get("offset"),m=h===null?void 0:Number.parseInt(h,10),R=c===null?void 0:Number.parseInt(c,10);return{limit:m!==void 0&&Number.isFinite(m)&&m>=0?m:void 0,offset:R!==void 0&&Number.isFinite(R)&&R>=0?R:void 0}},Ve=()=>{if(l===void 0)throw new d("scheduled endpoints require a `schedulerDO` namespace on the worker",{code:"SCHEDULER_NOT_CONFIGURED",status:400});return l},qt=oa({checkWsAdmin:async o=>S(o)||Ga(o,O(),g()),requireSchedulerNamespace:Ve,resolveSchedulerStub:o=>(G(o),we(Ve(),e.schedulerInstanceName??"default")),schedulerInstanceName:e.schedulerInstanceName??"default"}),Jt=wa({assertAdmin:G,resolveWorkflowsClient:e.workflowsClient??(()=>{})}),Yt=Wn({assertAdmin:G,parsePaging:ke,queryParameter:ve,readBodyBytes:Kn,requireAdminOption:oe,storage:{storageBuckets:e.storageBuckets,storageDelete:e.storageDelete,storageDownload:e.storageDownload,storageList:e.storageList,storageSignedUrl:e.storageSignedUrl,storageUpload:e.storageUpload}}),Xt=Gr({options:e,readJsonBody:Z,requireAdminOption:oe}),Zt=ua({readJsonBody:Z,requireAdminOption:oe,vectorIntrospector:e.vectorIntrospector}),en=To({kvIntrospector:e.kvIntrospector,readJsonBody:Z,requireAdminOption:oe}),tn=tr({logArchive:e.logArchive,readJsonBody:Z,requireAdminOption:oe}),nn=Eo({assertAdmin:G,options:{cronJobs:e.cronJobs,functions:e.functions,globalIntrospector:e.globalIntrospector,openApiSpec:e.openApiSpec,openRpcSpec:e.openRpcSpec},parsePaging:ke,queryParameter:ve,requireAdminOption:oe}),rn=o=>{const i=[],h=s??o?.SHARD;if(h!==void 0&&i.push(Xn("durable-object:default",h,r)),e.health?.disableBindingProbes!==!0)for(const[c,m]of Object.entries(o??{})){const R=Qa(c,m);R!==void 0&&i.push(R)}for(const c of e.health?.probes??[])i.push(c);return i},on=Yn({appName:e.health?.appName,appVersion:e.health?.appVersion,auth:e.health?.auth??"public",cacheTtlMs:e.health?.cacheTtlMs,isAdmin:S,resolveProbes:rn}),an=o=>{const i=e.schedulerInstanceName??"default",h=()=>we(o,i),c=async(y,A)=>{const v=await h().fetch(new Request(`https://scheduler.internal${y}`,A));if(!v.ok)throw new d(`ctx.scheduler: SchedulerDO ${y} failed (${String(v.status)}): ${await v.text()}`,{code:"INTERNAL",status:500});return await v.json()},m=async(y,A)=>await c(y,{body:JSON.stringify(A),headers:{"content-type":"application/json"},method:"POST"}),R=y=>{const A=y;if(A==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 A.binding=="string"&&A.binding.length>0)return{workflow:A.binding};if(typeof A.__lunoraRef=="string")return{functionPath:A.__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})},k=async(y,A,v={})=>{const{id:C}=await m("/schedule",{args:v,scheduledFor:y,...R(A)});return C};return{cancel:async y=>await m("/cancel",{id:y}),get:async y=>await c(`/get?id=${encodeURIComponent(y)}`,{method:"GET"}),list:async()=>await c("/list",{method:"GET"}),runAfter:async(y,A,v)=>{if(!Number.isFinite(y)||y<0)throw new d("ctx.scheduler.runAfter: `delayMs` must be a non-negative finite number",{code:"BAD_REQUEST",status:400});return await k(Date.now()+y,A,v)},runAt:async(y,A,v)=>{if(!Number.isFinite(y))throw new d("ctx.scheduler.runAt: `timestampMs` must be a finite epoch-millisecond number",{code:"BAD_REQUEST",status:400});return await k(y,A,v)}}},sn=async(o,i,h)=>{const{claims:c,headers:m,userId:R}=await de(o,i,a),k=async(y,A={})=>{const v=y.__lunoraRef;if(typeof v!="string")throw new d("ctx.run*: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});const C=ye(v,A,{...m,"x-lunora-system":"1"}),B=await w(s,r,C),L=await B.json();if(L.error)throw new d(L.error.message??"shard RPC failed",{code:L.error.code??"INTERNAL",status:B.status});return L.result};return{auth:{getIdentity:()=>Promise.resolve(c),userId:R},cache:h.cache,fetch:globalThis.fetch.bind(globalThis),runAction:k,runMutation:k,runQuery:k,...l===void 0?{}:{scheduler:an(l)},...e.storage===void 0?{}:{storage:ar(e.storage(i))}}},cn=async(o,i,h)=>{if(!e.httpRouter)return;const c=await sn(o,i,h);try{return await e.httpRouter.fetch(o,{...i,__lunoraCtx:c},h)}catch(m){return console.error("[lunora] httpRouter (SSR) handler threw:",m),new Response("Internal Server Error",{status:500})}},dn=async(o,i,h)=>{if(o.headers.get("Upgrade")!=="websocket")throw new d("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});const c=ot(o,ie);if(c)return c;const m=h.searchParams.get("shard")??r,{headers:R,identity:k}=await de(o,i,a);await U(k,m);const y=new Headers(o.headers),A=[...y.keys()];for(const C of A)C.startsWith("x-lunora-")&&y.delete(C);kt(y,R);const v=vt(i,e.shardDO);if(v!==void 0){y.set("x-lunora-shard-binding",v);const C=await $a(s,m);if(C>0){const B=yr(m,Math.floor(Math.random()*C));return w(s,B,new Request(o,{headers:y}),at(o))}}return w(s,m,new Request(o,{headers:y}))},un=async(o,i,h)=>{const{voiceAgents:c}=e;if(c===void 0)return new Response("Not found",{status:404});if(o.headers.get("Upgrade")!=="websocket")return new Response("Expected a WebSocket upgrade",{headers:{allow:"GET"},status:426});const m=ot(o,ie);if(m)return m;let R;try{R=decodeURIComponent(h.pathname.slice(St.length))}catch{return new Response("Unknown voice agent",{status:404})}const k=Object.hasOwn(c,R)?c[R]:void 0;if(k===void 0)return new Response("Unknown voice agent",{status:404});const y=h.searchParams.get("threadKey");if(y===null||y.length===0)return new Response("Missing threadKey",{status:400});const{headers:A,identity:v}=await de(o,i,a);if(e.authorizeShard){if(!await e.authorizeShard(v,y))return new Response("Forbidden",{status:403})}else $("shard");const C=new Headers(o.headers);for(const B of C.keys())B.startsWith("x-lunora-")&&C.delete(B);return kt(C,A),w(k,y,new Request(o,{headers:C}))},ln=async(o,i,h)=>{if(e.authorizeFanOut){if(!await e.authorizeFanOut(h,o.table,i))throw new d("Forbidden fan-out",{code:"FORBIDDEN_FANOUT",status:403});return}if(i.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});$("fan-out")},_e=async(o,i)=>{if(!(!o.fanOut&&o.functionPath.startsWith("__lunora_admin__:"))){if(o.fanOut){await ln(o.fanOut,o.functionPath,i);return}await U(i,o.shardKey??r)}},hn=(o,i,h)=>{if(e.replicaReads!==!0)return;if(e.functions===void 0){H();return}if(e.functions[i]?.kind!=="query"||h.includes(jt)||h.includes(Lt))return;const c=at(o);return c===void 0?void 0:{name:br(h,c),region:c}},fn=async(o,i,h,c,m)=>{const R=hn(o,i,c);if(R!==void 0){const k={...m,"x-lunora-replica-read":"1",...b===void 0?{}:{"x-lunora-shard-binding":b}},y=_r(o.headers.get("x-lunora-min-seq"));y!==void 0&&(k["x-lunora-min-seq"]=String(y));const A=await w(s,R.name,ye(i,h,k),R.region);if(A.status!==421)return A}return w(s,c,ye(i,h,m))},Ie=async(o,i,h,c,m,R)=>{const k=Date.now(),{observability:y,sampling:A}=e,v=Ke(o),{decision:C,ignoredUpstream:B,trace:L}=Vo(o,{...A===void 0?{}:{sampling:A},trustInbound:n(o)});B&&t();const te={...m,"x-lunora-sample-errors":C.keepErrors?"1":"0"};qo(L,te);try{const j=await fn(o,i,h,c,te);ce(y,{...v,...At(L),durationMs:Date.now()-k,functionPath:i,ok:j.ok,shardKey:c,...j.ok?{}:{error:{code:"SHARD_ERROR",message:`shard returned ${String(j.status)}`,status:j.status}}},R,void 0,{isTraced:L.sampled,keepErrors:C.keepErrors});const ee=new Response(j.body,{headers:j.headers,status:j.status,statusText:j.statusText});return ee.headers.set("x-lunora-shard-key",c),ee}catch(j){throw ce(y,{...v,...At(L),...Ee(i,Date.now()-k,j,{shardKey:c})},R,void 0,{isTraced:L.sampled,keepErrors:C.keepErrors}),j}},pn=o=>{if(o.fanOut&&o.shardKey)throw new d("RPC envelope cannot set both `shardKey` and `fanOut`",{code:"BAD_REQUEST",status:400});if(!o.fanOut&&o.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(o.fanOut&&!e.queryCoordinator)throw new d("RPC envelope set `fanOut` but no `queryCoordinator` is configured on the worker",{code:"BAD_REQUEST",status:400})},mn=async(o,i,h)=>{M(o,"POST","RPC");const c=await La(o);Ha(i,c),pn(c);const m=await se(o,c);if(m!==void 0)return m;const{headers:R,identity:k}=await de(o,i,a);await _e(c,k);const y=Ot(c,e);{const A=Date.now(),{observability:v}=e,C=Ke(o),B=Re(i,o,h&&(j=>h.waitUntil?.(j)));if(c.fanOut){const j=e.queryCoordinator;if(!j)throw new d("RPC envelope set `fanOut` but no `queryCoordinator` is configured on the worker",{code:"BAD_REQUEST",status:400});try{const ee=await j.fanOut(s,{args:c.args??{},fanOut:c.fanOut,functionPath:c.functionPath,headers:R});return ce(v,{durationMs:Date.now()-A,fanOut:{failed:ee.failed,shards:ee.ok+ee.failed,table:c.fanOut.table},functionPath:c.functionPath,...C,ok:!0},B),Response.json(ee,{headers:{"content-type":"application/json"},status:200})}catch(ee){throw ce(v,{...Ee(c.functionPath,Date.now()-A,ee,{fanOut:{table:c.fanOut.table}}),...C},B),ee}}const L=c.shardKey??r,te=()=>Ie(o,c.functionPath,c.args??{},L,R,B);return y&&e.x402Charge?e.x402Charge(o,{functionPath:c.functionPath,price:y.price},te,Et(h)):te()}},wn=async(o,i,h)=>{M(o,"POST","RPC batch");const c=await Z(o),{calls:m}=c;if(!Array.isArray(m))throw new d("RPC batch `calls` must be an array",{code:"BAD_REQUEST",status:400});const{headers:R,identity:k}=await de(o,i,a),y=zr(m,r);for(const Q of y.values())for(const z of Q)if(e.functions?.[z.functionPath]?.x402)throw new d(`paid (\`.x402\`) function "${z.functionPath}" cannot be called in a batch; dispatch it individually over ${Rt}`,{code:"BAD_REQUEST",status:400});await Promise.all([...y.entries()].flatMap(([Q,z])=>z.map(ne=>_e({args:ne.args,functionPath:ne.functionPath,shardKey:Q},k))));const{observability:A}=e,v=Re(i,o,h&&(Q=>h.waitUntil?.(Q))),C=Ke(o),B=[],L=[],te=(Q,z,ne,ue)=>({body:{error:{code:ne,message:ue}},id:Q.id,status:z}),j=(Q,z,ne,ue,fe)=>{for(const J of Q)ce(A,fe(J),v),B.push(te(J,z,ne,ue))},ee=(Q,z,ne,ue,fe)=>{for(const J of Q){const pe=ue.get(J.id)??fe,ge=pe<400;ce(A,{durationMs:ne,functionPath:J.functionPath,...C,ok:ge,shardKey:z,...ge?{}:{error:{code:"SHARD_ERROR",message:`batched call returned ${String(pe)}`,status:pe}}},v)}};await Promise.all([...y.entries()].map(async([Q,z])=>{const ne=new Headers(R);ne.set("content-type","application/json");const ue=new Request("https://shard.internal/rpc-batch",{body:JSON.stringify({calls:z}),headers:ne,method:"POST"}),fe=Date.now();let J;try{J=await w(s,Q,ue)}catch(Y){const Ue=Date.now()-fe,{body:Ze}=Dn(Y,{fallbackCode:"SHARD_UNAVAILABLE",redactedMessage:"shard unavailable"});j(z,502,Ze.code,Ze.message,In=>({...Ee(In.functionPath,Ue,Y,{shardKey:Q}),...C}));return}const pe=Date.now()-fe,ge=J.headers.get("x-d1-bookmark");ge&&L.push(ge);let De;try{De=await J.json()}catch{const Y=`shard batch returned a non-JSON response (${String(J.status)})`;j(z,J.status,"SHARD_ERROR",Y,Ue=>({durationMs:pe,error:{code:"SHARD_ERROR",message:Y,status:J.status},functionPath:Ue.functionPath,...C,ok:!1,shardKey:Q}));return}const Ne=Array.isArray(De.results)?De.results:[],vn=new Map(Ne.map(Y=>[Y.id,Y.status??J.status])),kn=new Set(Ne.map(Y=>Y.id));ee(z,Q,pe,vn,J.status),B.push(...Ne);for(const Y of z)kn.has(Y.id)||B.push(te(Y,J.status,"SHARD_ERROR",`shard batch omitted result for call ${String(Y.id)}`))}));const Ye={"content-type":"application/json"},[Xe]=L;return L.length===1&&Xe!==void 0&&(Ye["x-d1-bookmark"]=Xe),Response.json({results:B},{headers:Ye,status:200})},gn=async(o,i,h,c={},m={})=>{try{const R=h.__lunoraRef;if(typeof R!="string")throw new d("serverQuery: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});const{headers:k,identity:y}=await de(o,i,a);await _e({args:c,functionPath:R,shardKey:m.shardKey},y);const A=m.shardKey??r,v=Re(i,o,m.waitUntil);return await Ie(o,R,c,A,k,v)}catch(R){return et(R)}},qe=async(o,i,h)=>{const{observability:c}=e,m=Date.now(),R=Se(16),k=Se(8),y=Tt(i);try{const A=await h();return ce(c,{durationMs:Date.now()-m,functionPath:o,ok:!0,spanId:k,traceId:R},y),A}catch(A){throw ce(c,{...Ee(o,Date.now()-m,A,{}),spanId:k,traceId:R},y),A}finally{tt(c,y)}},yn=async(o,i,h)=>{_(i);const c=[],m=y=>y instanceof Error?y:new Error(String(y)),R=e.crons?.[o.cron];if(R)try{await R(o,i,h)}catch(y){c.push(m(y))}if(await q(o.cron,i,c,m),e.backupStore&&e.backupCron!==void 0&&e.backupCron===o.cron)try{await Mr(e,s,O(),o)}catch(y){c.push(m(y))}const[k]=c;if(c.length===1&&k)throw k;if(c.length>1)throw new AggregateError(c,`scheduled("${o.cron}") had ${String(c.length)} failure(s)`)},bn=async(o,i)=>{try{const h=o??{},c=e.adminToken??(typeof h.LUNORA_ADMIN_TOKEN=="string"?h.LUNORA_ADMIN_TOKEN:void 0);if(!c||c.length===0)return;await w(s,r,ye(Ia,{outcome:i},{authorization:`Bearer ${c}`,"content-type":"application/json"}))}catch{}},_n=async(o,i,h,c)=>{if(!e.authHandler)return;const m=await e.authHandler(o);if(!m)return;const R=e.authBasePath??ka;return Na(h.pathname,R)&&c.waitUntil?.(bn(i,m.status>=400?"fail":"ok")),m},Rn=async({args:o,env:i,functionPath:h,request:c,shardKey:m,waitUntil:R})=>{Nt(o,"REST");const k={functionPath:h,...m===void 0?{}:{shardKey:m}},{headers:y,identity:A}=await de(c,i,a);await _e(k,A);const v=m??r,C=Re(i,c,R),B=()=>Ie(c,h,o,v,y,C),L=Ot(k,e);return L&&e.x402Charge?e.x402Charge(c,{functionPath:h,price:L.price},B,Et({waitUntil:R})):B()},En=$n({functions:e.functions??{},invoke:Rn,readJsonBody:Z,...e.restRateLimit?{rateLimit:e.restRateLimit}:{}}),Pe=e.routes!==void 0&&Object.keys(e.routes).length>0?e.routes:void 0,An={[Ta]:o=>o.method!=="GET"&&o.method!=="HEAD"?new Response(void 0,{headers:{allow:"GET, HEAD"},status:405}):Response.json({ok:!0},{headers:{"cache-control":"no-store"}}),[ba]:(o,i,h)=>dn(o,i,h),[Rt]:(o,i,h,c)=>mn(o,i,c),[ya]:(o,i,h,c)=>wn(o,i,c),[_a]:(o,i)=>he(o,i),[Ra]:(o,i)=>ae(o,i),[Ea]:async o=>{M(o,"POST","ws-token"),G(o);const i=O();if(i===void 0)throw new d("ws-token minting requires a configured admin token",{code:"ADMIN_TOKEN_NOT_CONFIGURED",status:400});const h=await Tr(i);return Response.json(h,{headers:{"cache-control":"no-store"}})},...W,...Vt,...qt,...Jt,...Yt,...Xt,...Zt,...en,...tn,...nn,...on,...En,...Ir({assertAdmin:G,getAuthAdmin:()=>e.authAdmin,parsePaging:ke,queryParameter:ve,readJsonBody:Z})};let ie=rt(e.security),Je=!1;const Sn=o=>{Je||(Je=!0,ie=rt(e.security,o??{}))},Tn=async(o,i)=>{if(!(e.adminGate===void 0||!Oa(i)))try{await e.adminGate(o)&&p.add(o)}catch{}},On=async(o,i,h)=>{const c=new URL(o.url);if(o.method==="POST"||o.method==="PUT"){const y=Number(o.headers.get("content-length")??""),A=ga[c.pathname]??Dt;if(Number.isFinite(y)&&y>A)throw new d("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413})}const m=await _n(o,i,c,h);if(m)return m;if(Pe){const y=`${o.method} ${c.pathname}`,A=Pe[y]??Pe[c.pathname];if(A)return A(o,i,h)}const R=An[c.pathname];if(R)return await Tn(o,c.pathname),R(o,i,c,h);if(e.voiceAgents!==void 0&&c.pathname.startsWith(St))return un(o,i,c);const k=await cn(o,i,h);return k||new Response("Not found",{status:404})};return{async fetch(o,i,h){e.passThroughOnException&&h.passThroughOnException?.(),Sn(i),_(i);const c=rr(o,ie);if(c)return c;const m=or(o,ie);if(m)return Be(m,o,ie);try{const R=await On(o,i,h);return Be(R,o,ie)}catch(R){return Be(et(R),o,ie)}finally{tt(e.observability,Tt(h))}},async queue(o,i,h){await qe(`queue:${Ca(o)}`,h,async()=>{await e.queue?.(o,i,h)})},async scheduled(o,i,h){await qe(`cron:${o.cron}`,h,async()=>{await yn(o,i,h)})},serverQuery:gn}},za=e=>Wt(e),Wa=e=>typeof e=="function"?{fetch:e}:e,Va=e=>!!(e.crons??e.cronJobs??e.backupCron),ps=(e,n)=>{const t=Wa(e),r=typeof e=="object"&&typeof e.scheduled=="function"?e.scheduled:void 0,a=l=>{const u=za({...l,httpRouter:t});return r!==void 0&&!Va(l)?{...u,scheduled:async(f,w,E)=>{await r(f,w,E)}}:u};if(typeof n!="function")return a(n);const s=n;return{fetch:(l,u,f)=>a(s(u)).fetch(l,u,f),queue:(l,u,f)=>a(s(u)).queue?.(l,u,f)??Promise.resolve(),scheduled:(l,u,f)=>a(s(u)).scheduled(l,u,f),serverQuery:(l,u,f,w,E)=>a(s(u)).serverQuery(l,u,f,w,E)}},qa=(e,n)=>{if(typeof e=="function")return e(n);const t=e.shardDO??n?.SHARD;if(!t)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:t}},ms=(e={})=>(n,t,r)=>Wt(qa(e,t)).fetch(n,t,r??Nn),ws=e=>e;export{Pr as GET_AUTH_AUDIT_LOG_OP,Nn as NOOP_EXECUTION_CONTEXT,bs as composeIdentityResolvers,za as composeWorker,ms as createLunoraHandler,Wt as createWorker,ws as defineRpcEnvelope,$a as probeRelayCount,qa as resolveLunoraOptions,_s as routeIdentityResolvers,ps as withFrameworkWorker};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{e as c,a as u}from"./identity-header-JF5q3H5w.mjs";import{LunoraError as s}from"./LunoraError-DksAgIpa.mjs";const f="/_lunora/rpc",l=e=>{const a={"content-type":"application/json"};return e.userId!==void 0&&e.userId.length>0&&(a["x-lunora-userid"]=c(e.userId)),e.identity!==void 0&&(a["x-lunora-identity"]=u(e.identity)),a},d=async(e,a,o)=>{const t=await(e.fetch??globalThis.fetch)(new Request(`${e.origin}${f}`,{body:JSON.stringify(a),headers:l(e),method:"POST"}));if(!t.ok)throw new s(`cross-shard relation ${o} failed: worker returned ${String(t.status)}`);const r=await t.json();if(typeof r.failed=="number"&&r.failed>0){const i=(typeof r.ok=="number"?r.ok:0)+r.failed;throw new s(`cross-shard relation ${o} failed on ${String(r.failed)} of ${String(i)} shard(s) — refusing to return a partial result`)}return r.data},g=e=>({crossShardCounter:async(n,t)=>{const r=await d(e,{args:{table:n,where:t},fanOut:{merge:{kind:"sum"},table:n},functionPath:"__lunora_relation__:count"},"count");return typeof r=="number"?r:0},crossShardReader:async(n,t)=>{const r=await d(e,{args:{...t,table:n},fanOut:{merge:{kind:"concat"},table:n},functionPath:"__lunora_relation__:read"},"read");return{continueCursor:null,isDone:!0,page:Array.isArray(r)?r:[]}}});export{g as createCrossShardRelationCapabilities};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
const E=e=>new Promise(t=>{setTimeout(t,e)}),j=e=>{const t=typeof e.table=="string"?e.table:"",r=typeof e.op=="string"?e.op:"",s=r==="delete"||r==="insert"||r==="update"?r:"upsert",o=typeof e.id=="string"?e.id:void 0,n=e.doc&&typeof e.doc=="object"?e.doc:void 0,i=typeof e.seq=="number"&&Number.isFinite(e.seq)?e.seq:void 0,c=typeof e.ts=="number"&&Number.isFinite(e.ts)?e.ts:void 0;return{op:s,table:t,...n===void 0?{}:{doc:n},...o===void 0?{}:{id:o},...i===void 0?{}:{seq:i},...c===void 0?{}:{ts:c}}},C=async(e,t,r,s,o,n)=>{let i=0;for(;;)try{await e.deliver(t);return}catch(c){if(i>=r)throw c instanceof Error?c:new Error(String(c));const d=Math.min(s*2**i,o);await n(d),i+=1}},$=async e=>{const{coordinator:t,cursorStore:r,headers:s,initialBackoffMs:o=100,limit:n,maxBackoffMs:i=5e3,maxRetries:c=3,shardDO:d,sink:h,sleep:w=E,tables:b}=e,f=await r.read(h.name),v=await t.orchestrateCdcSync(d,{cursors:f,headers:s,limit:n,tables:b}),p={...f},y=[];let x=0,l=!1;for(const a of v.shards){if(a.error){y.push({error:a.error.message,shardKey:a.shardKey}),l=!0;continue}const m=a.changes??[];if(m.length===0){p[a.shardKey]=a.cursor;continue}const k=m.map(u=>j(u)),K={changes:k,cursor:a.cursor,shardKey:a.shardKey,sink:h.name};try{await C(h,K,c,o,i,w),p[a.shardKey]=a.cursor,x+=k.length,n!==void 0&&m.length>=n&&(l=!0)}catch(u){y.push({error:u instanceof Error?u.message:String(u),shardKey:a.shardKey}),l=!0}}return await r.write(h.name,p),{cursors:p,delivered:x,failures:y,hasMore:l,shards:v.shards.length}},S=e=>{if(typeof e.name!="string"||e.name.length===0)throw new Error("defineExportSink: `name` must be a non-empty string");if(typeof e.deliver!="function")throw new TypeError("defineExportSink: `deliver` must be a function");return{deliver:e.deliver,name:e.name}},g=e=>`${e.map(t=>JSON.stringify(t)).join(`
|
|
2
|
+
`)}
|
|
3
|
+
`,M=e=>{const t=e.fetchImpl??((r,s)=>fetch(r,s));return S({deliver:async r=>{const s=await t(e.url,{body:g(r.changes),headers:{"content-type":"application/x-ndjson","x-lunora-cursor":String(r.cursor),"x-lunora-shard":r.shardKey,"x-lunora-sink":r.sink,...e.headers},method:"POST"});if(!s.ok)throw new Error(`webhook export sink "${e.name}" returned ${String(s.status)}`)},name:e.name})},N=e=>{let t=e.prefix??"cdc";for(;t.endsWith("/");)t=t.slice(0,-1);return S({deliver:async r=>{const s=`${t}/${r.shardKey}/${String(r.cursor)}.ndjson`;await e.bucket.put(s,g(r.changes),{httpMetadata:{contentType:"application/x-ndjson"}})},name:e.name})},O=()=>{const e={};return{read:t=>Promise.resolve({...e[t]}),snapshot:()=>structuredClone(e),write:(t,r)=>(e[t]={...r},Promise.resolve())}},P=(e,t)=>{const r=t?.keyPrefix??"__lunora_source_cursor:export",s=o=>`${r}:${o}`;return{read:async o=>{const n=await e.get(s(o),"json");if(n===null||typeof n!="object")return{};const i={};for(const[c,d]of Object.entries(n))typeof d=="number"&&Number.isFinite(d)&&(i[c]=d);return i},write:async(o,n)=>{await e.put(s(o),JSON.stringify(n))}}};export{P as createKvCursorStore,O as createMemoryCursorStore,S as defineExportSink,N as r2Sink,$ as runExportTap,j as sanitizeChange,M as webhookExportSink};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{f as T,t as E}from"./base64-CMlwEPti.mjs";import{LunoraError as O}from"./LunoraError-DksAgIpa.mjs";import{resolveShard as B}from"./applyJurisdiction-C0ddU7Tg.mjs";const me=r=>({listShardKeys(e){return r[e]??[]}}),pe=r=>{if(r.kind==="count")return{kind:"sum"};if(r.kind==="scalar"){if(r.op==="count"||r.op==="sum")return{kind:"sum"};if(r.op==="max")return{kind:"max"};if(r.op==="min")return{kind:"min"};throw new O('aggregate({ op: "avg" }) is not supported across shards in v1 — fan out sum + count separately',{code:"BAD_REQUEST",status:400})}const e=r.agg?.op??"count";if(e==="count"||e==="sum")return{kind:"groupBy",op:"sum"};if(e==="max")return{kind:"groupBy",op:"max"};if(e==="min")return{kind:"groupBy",op:"min"};throw new O('groupBy({ agg: { op: "avg" } }) is not supported across shards in v1 — fan out sum + count separately',{code:"BAD_REQUEST",status:400})},U=16,F=5e3,h=r=>r!==null&&typeof r=="object"&&"result"in r?r.result:r,I=r=>{const e=r??{};return{changed:typeof e.changed=="number"?e.changed:0,processed:typeof e.processed=="number"?e.processed:0,status:typeof e.status=="string"?e.status:void 0}},V=(r,e)=>r?"failed":e?"in_progress":"completed",D=r=>{const e=[];let s=0,o=0,t=0,n=0,a=!1,c=!1;for(const i of r){if(i.kind==="err"){o+=1,e.push({error:{message:i.message,timedOut:i.timedOut},shardKey:i.shardKey});continue}s+=1;const d=h(i.value),u=I(d);t+=u.changed,n+=u.processed,a||=u.status==="in_progress",c||=u.status==="failed",e.push({result:d,shardKey:i.shardKey})}return{changed:t,failed:o,ok:s,processed:n,shards:e,status:V(c,a||o>0)}},L=r=>{const e=r??{};return{before:typeof e.before=="number"&&Number.isFinite(e.before)?e.before:0,total:typeof e.total=="number"&&Number.isFinite(e.total)?e.total:0}},j=r=>{const e=[];let s=0,o=0,t=0,n=0;for(const a of r){if(a.kind==="err"){o+=1,e.push({error:{message:a.message,timedOut:a.timedOut},shardKey:a.shardKey});continue}s+=1;const c=L(h(a.value));t+=c.before,n+=c.total,e.push({result:c,shardKey:a.shardKey})}return{failed:o,ok:s,partial:o>0,position:t+1,shards:e,total:n}},v=0,P=1,J=2,w=(r,e)=>r<e?-1:r>e?1:0,x=r=>r==null?v:typeof r=="number"?P:J,R=(r,e)=>{const s=x(r),o=x(e);return s!==o?s<o?-1:1:s===v?0:s===P?w(r,e):w(String(r),String(e))},$=(r,e,s)=>{const o=R(r.partitionKey,e.partitionKey);if(o!==0)return o;const t=Math.max(r.sortValues.length,e.sortValues.length);for(let n=0;n<t;n+=1){const a=R(r.sortValues[n],e.sortValues[n]);if(a!==0)return s[n]==="desc"?-a:a}return R(r.rowId,e.rowId)},G=r=>E(new TextEncoder().encode(JSON.stringify(r))),Q=r=>{try{const e=JSON.parse(new TextDecoder().decode(T(r)));if(e!==null&&typeof e=="object"&&"perShard"in e){const{perShard:s}=e;if(s!==null&&typeof s=="object")return{perShard:s}}}catch{}return{perShard:{}}},Y=r=>{const e=r??{},s=Array.isArray(e.rows)?e.rows:[];return{directions:Array.isArray(e.directions)?e.directions:[],hasMore:e.hasMore===!0,rows:s}},H=(r,e)=>{let s;for(const o of r){const t=o.rows[o.head];t!==void 0&&(s===void 0||$(t.key,s.row.key,e)<0)&&(s={row:t,slice:o})}return s},W=(r,e)=>{let s=!1;const o=new Set;for(const n of r)o.add(n.shardKey),(n.head<n.rows.length||n.hasMore)&&(s=!0);const t={...e};for(const n of Object.keys(e))o.has(n)||(s=!0);return s?G({perShard:t}):null},X=(r,e,s,o)=>{const t=[],n={...o};for(;t.length<e;){const c=H(r,s);if(c===void 0)break;t.push(c.row.doc),n[c.slice.shardKey]=c.row.key,c.slice.head+=1}const a=W(r,n);return{isDone:a===null,nextCursor:a,page:t}},z=r=>{const e=[];let s=0,o=0;for(const t of r){if(t.kind==="err"){o+=1,e.push({error:{message:t.message,timedOut:t.timedOut},shardKey:t.shardKey});continue}s+=1;const n=h(t.value),a=Array.isArray(n?.rows)?n.rows:[];e.push({rows:a,shardKey:t.shardKey})}return{failed:o,ok:s,shards:e}},Z=r=>{const e=[];let s=0,o=0;for(const{outcome:t,sinceSeq:n}of r){if(t.kind==="err"){o+=1,e.push({cursor:n,error:{message:t.message,timedOut:t.timedOut},shardKey:t.shardKey});continue}s+=1;const a=h(t.value),c=Array.isArray(a?.changes)?a.changes:[],i=typeof a?.cursor=="number"?a.cursor:n;e.push({changes:c,cursor:i,shardKey:t.shardKey})}return{failed:o,ok:s,shards:e}},q=r=>{let e=0,s=0,o=0;for(const t of r){if(t.kind==="err"){s+=1;continue}e+=1;const n=h(t.value);o+=typeof n?.applied=="number"?n.applied:0}return{applied:o,failed:s,ok:e}},ee=r=>{const e=r??{};return typeof e.requests=="number"&&Number.isFinite(e.requests)&&e.requests>=0?e.requests:0},re=r=>{const e=[];let s=0,o=0;for(const t of r){if(t.kind==="err"){o+=1,e.push({requests:0,shardKey:t.shardKey});continue}s+=1,e.push({requests:ee(h(t.value)),shardKey:t.shardKey})}return{failed:o,ok:s,shards:e}},te=r=>{const e=[],s={},o=[];let t=0,n=0,a=0;for(const c of r){if(c.kind==="err"){a+=1,e.push({error:{message:c.message,timedOut:c.timedOut},shardKey:c.shardKey});continue}n+=1;const i=h(c.value),d=i?.inserted??{};for(const[f,y]of Object.entries(d))s[f]=(s[f]??0)+y;const u=i?.errors;Array.isArray(u)&&o.push(...u),t+=i?.conflicts??0,e.push({result:{conflicts:i?.conflicts??0,errors:i?.errors??[],inserted:d},shardKey:c.shardKey})}return{conflicts:t,errors:o,failed:a,inserted:s,ok:n,shards:e}},p=r=>({body:JSON.stringify({args:r.args??{},functionPath:r.functionPath}),headers:{"content-type":"application/json",...r.headers}}),g=async(r,e,s,o)=>{const t=B(r,e),n=new AbortController,a=new Request("https://shard.internal/rpc",{body:s.body,headers:s.headers,method:"POST",signal:n.signal});let c;const i=new Promise(u=>{c=setTimeout(()=>{try{n.abort()}catch{}u({kind:"err",message:`shard "${e}" timed out after ${String(o)}ms`,shardKey:e,timedOut:!0})},o)}),d=(async()=>{try{const u=await t.fetch(a);if(!u.ok)return{kind:"err",message:`shard "${e}" returned ${String(u.status)}`,shardKey:e,timedOut:!1};const f=await u.json();return{kind:"ok",shardKey:e,value:f}}catch(u){const f=u instanceof Error?u.message:String(u);return{kind:"err",message:`shard "${e}" threw: ${f}`,shardKey:e,timedOut:!1}}})();try{return await Promise.race([d,i])}finally{c!==void 0&&clearTimeout(c)}},k=async(r,e,s)=>{if(r.length===0)return[];const o=Array.from({length:r.length});let t=0;const n=async()=>{for(;;){const c=t;t+=1;const i=r[c];if(c>=r.length||i===void 0)return;o[c]=await s(i,c)}},a=Math.min(e,r.length);return await Promise.all(Array.from({length:a},()=>n())),o},M=async(r,e)=>{const s=await Promise.all(e.map(async o=>r.listShardKeys(o)));return[...new Set(s.flat())]},m=async(r,e,s,o,t)=>{const n=p(s);return k(e,o,async a=>g(r,a,n,t))},se=r=>{const e={};for(const s of Object.keys(r).toSorted(w))e[s]=r[s]??null;return JSON.stringify(e)},oe=r=>r.flatMap(e=>Array.isArray(e)?e:[]),ne=(r,e,s)=>{switch(s){case"max":return Math.max(r,e);case"min":return Math.min(r,e);case"sum":return r+e;default:return r}},ae=(r,e,s)=>{if(e===null||typeof e!="object")return;const o=e.key??{},t=e.value??null,n=se(o),a=r.get(n);if(!a){r.set(n,{key:o,value:t});return}if(a.value===null){a.value=t;return}t!==null&&(a.value=ne(a.value,t,s))},ce=(r,e)=>{const s=new Map;for(const o of r)if(Array.isArray(o))for(const t of o)ae(s,t,e);return[...s.values()]},N=(r,e)=>{let s=null;for(const o of r)typeof o=="number"&&Number.isFinite(o)&&(s=s===null?o:e(s,o));return s},ie=r=>{let e=0;for(const s of r)typeof s=="number"&&Number.isFinite(s)&&(e+=s);return e},ue=r=>{let e=0,s=0;for(const o of r){if(o===null||typeof o!="object")continue;const t=o;typeof t.before=="number"&&Number.isFinite(t.before)&&(e+=t.before),typeof t.total=="number"&&Number.isFinite(t.total)&&(s+=t.total)}return{position:e+1,total:s}},de=(r,e)=>{const s=[];for(const t of r)if(Array.isArray(t))for(const n of t){if(n===null||typeof n!="object")continue;const a=n[e.by],c=typeof a=="number"&&Number.isFinite(a)?a:Number.NEGATIVE_INFINITY;s.push({row:n,score:c})}const o=e.direction??"desc";return s.sort((t,n)=>o==="asc"?w(t.score,n.score):w(n.score,t.score)),s.slice(0,e.k).map(t=>t.row)},le=(r,e)=>{switch(e.kind){case"concat":return oe(r);case"first":return r[0];case"groupBy":return ce(r,e.op??"sum");case"max":return N(r,Math.max);case"min":return N(r,Math.min);case"rank":return ue(r);case"sum":return ie(r);case"topK":return de(r,e);default:return r}},ge=r=>{const e=r.maxConcurrency??U,s=r.perShardTimeoutMs??F;if(e<1)throw new O("maxConcurrency must be >= 1",{code:"BAD_REQUEST",status:400});return{async fanOut(o,t){const n=await r.registry.listShardKeys(t.fanOut.table),a=await m(o,n,t,e,s),c=[],i=[];for(const d of a)d.kind==="ok"?c.push(d.value):i.push({message:d.message,shardKey:d.shardKey,timedOut:d.timedOut});return{data:le(c,t.fanOut.merge),errors:i,failed:i.length,ok:c.length}},async orchestrateExport(o,t){const n=await M(r.registry,t.tables),a={args:{...t.args,tables:[...t.tables]},functionPath:"__lunora_admin__:exportShard",headers:t.headers},c=await m(o,n,a,e,s);return z(c)},async orchestrateCdcSync(o,t){const n=await M(r.registry,t.tables),a=t.cursors??{},c=await k(n,e,async i=>{const d=a[i]??0;return{outcome:await g(o,i,p({args:{limit:t.limit,sinceSeq:d},functionPath:"__lunora_admin__:cdcSync",headers:t.headers}),s),sinceSeq:d}});return Z(c)},async orchestrateImport(o,t){const{batches:n}=t,a=await k(n,e,async c=>g(o,c.shardKey,p({args:{rows:[...c.rows],startLine:c.startLine??1},functionPath:"__lunora_admin__:importShard",headers:t.headers}),s));return te(a)},async orchestrateApplyCdc(o,t){const{batches:n}=t,a=await k(n,e,async c=>g(o,c.shardKey,p({args:{changes:[...c.changes]},functionPath:"__lunora_admin__:applyCdc",headers:t.headers}),s));return q(a)},async orchestrateMigration(o,t){const n=await r.registry.listShardKeys(t.table),a=await m(o,n,t,e,s);return D(a)},async orchestrateRank(o,t){const n=await r.registry.listShardKeys(t.table),a={args:{index:t.index,partitionKey:t.partitionKey,rowId:t.rowId,sortValues:[...t.sortValues],table:t.table},functionPath:"__lunora_admin__:rankBefore",headers:t.headers},c=await m(o,n,a,e,s);return j(c)},async orchestrateRankPage(o,t){const n=await r.registry.listShardKeys(t.table),a=Math.max(1,Math.min(1e3,Math.floor(t.take??100))),c=t.directions??[],i=t.cursor?Q(t.cursor):{perShard:{}},d=await k(n,e,async l=>{const C=i.perShard[l],_={index:t.index,table:t.table,take:a};t.partitionKey!==void 0&&(_.partitionKey=t.partitionKey),C!==void 0&&(_.after=C);const b=await g(o,l,p({args:_,functionPath:"__lunora_admin__:rankPage",headers:t.headers}),s);if(b.kind==="err")return{error:{message:b.message,timedOut:b.timedOut},shardKey:l};const A=Y(h(b.value));return{directions:A.directions,hasMore:A.hasMore,rows:A.rows,shardKey:l}}),u=[];let f=0,y=0,S;for(const l of d){if(l.error){y+=1;continue}f+=1,S===void 0&&l.directions&&l.directions.length>0&&(S=l.directions),u.push({hasMore:l.hasMore??!1,head:0,rows:l.rows??[],shardKey:l.shardKey})}const K=X(u,a,S??c,i.perShard);return{continueCursor:K.nextCursor,failed:y,isDone:K.isDone,ok:f,page:K.page,partial:y>0,shards:d}},async orchestrateShardTraffic(o,t){const n=await r.registry.listShardKeys(t.table),a={functionPath:"__lunora_admin__:getMetrics",headers:t.headers},c=await m(o,n,a,e,s);return re(c)},registry:r.registry}};export{ge as createQueryCoordinator,me as createStaticShardRegistry,pe as mergeStrategyForAggregate};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as g}from"@lunora/errors";import{e as R,a as j}from"./identity-header-JF5q3H5w.mjs";import{t as h,f as N}from"./base64-CMlwEPti.mjs";import{applyJurisdiction as O,resolveShard as T}from"./applyJurisdiction-C0ddU7Tg.mjs";const s="$lunora.wire$",l=64,E=1024,p="__proto__",S={BigInt64Array,BigUint64Array,Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array},I={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError},$=e=>{if(e===null||typeof e!="object")return!1;const t=Object.getPrototypeOf(e);return t===null||t===Object.prototype},u=(e,t=0)=>{if(t>l)throw new RangeError(`wire-codec: value nesting exceeds the ${l}-level limit`);if(e===void 0)return[s,"undefined"];if(e===null)return null;const y=typeof e;if(y==="bigint")return[s,"bigint",e.toString()];if(y==="number"){const r=e;return Number.isNaN(r)?[s,"nan"]:r===1/0?[s,"inf"]:r===-1/0?[s,"-inf"]:r}if(y!=="object")return e;if(e instanceof Date)return[s,"date",u(e.getTime(),t+1)];if(e instanceof Error){const r=e,n={};for(const a of Object.keys(r))r[a]!==void 0&&(n[a]=u(r[a],t+1));const o=[s,"error",r.name,r.message,n];return r.cause!==void 0&&o.push(u(r.cause,t+1)),o}if(e instanceof URL)return[s,"url",e.href];if(e instanceof Map)return[s,"map",[...e.entries()].map(([r,n])=>[u(r,t+1),u(n,t+1)])];if(e instanceof Set)return[s,"set",[...e].map(r=>u(r,t+1))];if(e instanceof ArrayBuffer)return[s,"bytes",h(new Uint8Array(e)),"ArrayBuffer"];if(ArrayBuffer.isView(e)){const r=e,n=r.constructor.name,o=new Uint8Array(r.buffer,r.byteOffset,r.byteLength);return n==="Uint8Array"?[s,"bytes",h(o)]:[s,"bytes",h(o),n]}if(Array.isArray(e)){const r=e.map(n=>u(n,t+1));return r.length>0&&r[0]===s?[s,"arr",r]:r}if(!$(e)){const r=e.constructor?.name??"value";throw new TypeError(`wire-codec: cannot encode a ${r} over the Lunora wire — only plain objects, arrays, and the supported built-ins (Date, Error, URL, Map, Set, ArrayBuffer/typed arrays, bigint) round-trip`)}const d=e,i={};for(const r of Object.keys(d)){const n=d[r];if(n===void 0)continue;const o=u(n,t+1);r===p?Object.defineProperty(i,r,{configurable:!0,enumerable:!0,value:o,writable:!0}):i[r]=o}return i},c=(e,t=0)=>{if(t>l)throw new RangeError(`wire-codec: value nesting exceeds the ${l}-level limit`);if(e===null||typeof e!="object")return e;if(Array.isArray(e)){if(e[0]===s)switch(e[1]){case"-inf":return-1/0;case"arr":return e[2].map(r=>c(r,t+1));case"bigint":{const r=e[2];if(typeof r!="string"||r.length>E||!/^-?\d+$/.test(r))throw new RangeError(`wire-codec: invalid or over-long bigint (max ${E} digits)`);return BigInt(r)}case"date":return new Date(c(e[2],t+1));case"map":return new Map(e[2].map(([r,n])=>[c(r,t+1),c(n,t+1)]));case"set":return new Set(e[2].map(r=>c(r,t+1)));case"url":return new URL(e[2]);case"error":{const r=e[2],n=e[3],o=(Object.hasOwn(I,r)?I[r]:void 0)??Error,a=new o(n);a.name!==r&&Object.defineProperty(a,"name",{configurable:!0,value:r,writable:!0});const b=c(e[4],t+1);for(const f of Object.keys(b))f===p?Object.defineProperty(a,f,{configurable:!0,enumerable:!0,value:b[f],writable:!0}):a[f]=b[f];return e.length>5&&Object.defineProperty(a,"cause",{configurable:!0,value:c(e[5],t+1),writable:!0}),a}case"bytes":{const r=N(e[2]),n=e[3]??"Uint8Array";if(n==="ArrayBuffer")return r.buffer.byteLength===r.byteLength?r.buffer:r.slice().buffer;const o=Object.hasOwn(S,n)?S[n]:void 0;return o?new o(r.slice().buffer):r}case"inf":return 1/0;case"nan":return Number.NaN;case"undefined":return;default:return e.map(r=>c(r,t+1))}return e.map(i=>c(i,t+1))}const y=e,d={};for(const i of Object.keys(y)){const r=c(y[i],t+1);i===p?Object.defineProperty(d,i,{configurable:!0,enumerable:!0,value:r,writable:!0}):d[i]=r}return d},U=e=>{if(typeof e=="string")return e;const t=e?.__lunoraRef;if(typeof t!="string"||t.length===0)throw new g("INTERNAL","createShardClient: expected a generated function reference (api.*/internal.*) or a 'namespace:fn' string");return t},x=e=>{const t=new g(e.code,e.message);return e.data!==void 0&&(t.data=c(e.data)),t},L=(e,t={})=>{const y=O(e,t.jurisdiction),d=t.system??!0,i=r=>L(e,{...t,...r});return{as:r=>i({as:r}),asSystem:()=>i({as:void 0}),call:async(r,n,o)=>{const a=U(r),b=o?.shardKey??t.shardKey;if(b===void 0||b.length===0)throw new g("INTERNAL",`createShardClient: no shard key for "${a}" — pass one to createShardClient({ shardKey }), .forShard(key), or the call's options`);const f={"content-type":"application/json"};d&&(f["x-lunora-system"]="1"),t.as&&(f["x-lunora-userid"]=R(t.as.userId),t.as.claims&&(f["x-lunora-identity"]=j(t.as.claims))),o?.mutationId!==void 0&&o.mutationId.length>0&&(f["x-lunora-mutation-id"]=o.mutationId);const m=await T(y,b).fetch(new Request("https://shard.internal/rpc",{body:JSON.stringify({args:u(n??{}),functionPath:a}),headers:f,method:"POST"})),A=m.statusText?` ${m.statusText}`:"";let w;try{w=await m.json()}catch{throw new g("INTERNAL",`createShardClient: shard response for "${a}" was not JSON (status ${String(m.status)}${A})`)}if("error"in w)throw x(w.error);if(!m.ok)throw new g("INTERNAL",`createShardClient: shard call "${a}" failed (status ${String(m.status)}${A})`);return c(w.result)},forShard:r=>i({shardKey:r})}};export{L as createShardClient};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as g}from"./LunoraError-DksAgIpa.mjs";const O="default-src 'none'; frame-ancestors 'none'; base-uri 'none'; form-action 'none'",y=e=>{const o=["base-uri 'none'","object-src 'none'"];return e==="DENY"?o.push("frame-ancestors 'none'"):e==="SAMEORIGIN"&&o.push("frame-ancestors 'self'"),o.join("; ")},E="accelerometer=(), autoplay=(), camera=(), display-capture=(), geolocation=(), gyroscope=(), magnetometer=(), microphone=(), payment=(), usb=()",d=["Authorization","Content-Type","X-D1-Bookmark","X-Lunora-Client-Id","X-Lunora-Client-Seq","X-Lunora-Min-Seq","X-Lunora-Mutation-Id"],u=["DELETE","GET","HEAD","PATCH","POST","PUT"],S=31536e3,A=new Set(["GET","HEAD","OPTIONS"]),L=e=>{if(e===!1)return;const o=e===void 0||e===!0?{}:e,s=o.maxAge??S,r=o.includeSubDomains??!0;return`max-age=${String(s)}${r?"; includeSubDomains":""}${o.preload?"; preload":""}`},b=(e,o)=>{if(e!==!1)return typeof e=="string"?{htmlValue:e,value:e}:{htmlValue:o,value:O}},v=e=>{if(e===!1)return{coop:void 0,csp:void 0,enabled:!1,frameOptions:void 0,hsts:void 0,permissionsPolicy:void 0,referrerPolicy:void 0};const o=e===void 0||e===!0?{}:e,s=o.frameOptions===!1?void 0:o.frameOptions??"SAMEORIGIN";return{coop:"same-origin",csp:b(o.csp,y(s)),enabled:!0,frameOptions:s,hsts:L(o.hsts),permissionsPolicy:o.permissionsPolicy===!1?void 0:o.permissionsPolicy??E,referrerPolicy:o.referrerPolicy===!1?void 0:o.referrerPolicy??"strict-origin-when-cross-origin"}},C=e=>{const o={allowCredentials:!1,allowedHeaders:d,allowedMethods:u,enabled:!1,isAllowed:()=>!1,isExplicitlyAllowed:()=>!1,maxAge:600};if(e===void 0||e===!1)return o;const s=e.allowCredentials??!1,r=e.allowedOrigins;let t,n;if(typeof r=="function")t=r,n=r,console.warn(`@lunora/runtime: security.cors uses a custom \`allowedOrigins\` predicate. It is trusted by the CSRF and WebSocket origin checks${s?" AND reflects matching origins with credentials (`allowCredentials: true`)":""} — ensure it matches ONLY trusted origins by exact equality; an over-broad predicate (e.g. \`() => true\`, or \`endsWith\`/\`includes\` checks) defeats the allowlist.`);else{const l=r;if(l.includes("*")&&s)throw new g('@lunora/runtime: security.cors cannot combine a wildcard origin ("*") with allowCredentials: true — browsers reject it and it defeats the allowlist.');t=i=>l.includes("*")||l.includes(i),n=i=>l.includes(i)}return{allowCredentials:s,allowedHeaders:e.allowedHeaders??d,allowedMethods:e.allowedMethods??u,enabled:!0,isAllowed:t,isExplicitlyAllowed:n,maxAge:e.maxAge??600}},R=e=>{if(e===!1)return{allowLoopback:!1,enabled:!1,trustedOrigins:[]};const o=e===void 0||e===!0?{}:e;return{allowLoopback:o.allowLoopback??!0,enabled:!0,trustedOrigins:o.trustedOrigins??[]}},D=new Set(["0","disabled","false","no","off"]),_=new Set(["1","enabled","on","true","yes"]),f=e=>typeof e=="string"&&D.has(e.trim().toLowerCase()),N=e=>typeof e=="string"&&_.has(e.trim().toLowerCase()),H=e=>{const o=e?.LUNORA_ALLOWED_ORIGINS;if(typeof o!="string")return;const s=o.split(",").map(n=>n.trim()).filter(n=>n.length>0);return s.length===0?void 0:{allowCredentials:!s.includes("*")&&N(e?.LUNORA_CORS_ALLOW_CREDENTIALS),allowedOrigins:s}},M=(e,o)=>{const s=e?.headers??(f(o?.LUNORA_SECURITY_HEADERS)?!1:void 0),r=e?.csrf??(f(o?.LUNORA_SECURITY_CSRF)?!1:void 0),t=e?.cors??H(o);return{cors:C(t),csrf:R(r),headers:v(s)}},I=new Set(["127.0.0.1","::1","[::1]","localhost"]),p=e=>{try{return I.has(new URL(e).hostname)}catch{return!1}},c=e=>{if(e)try{return new URL(e).origin}catch{return}},w=(e,o,s)=>e===o||s.csrf.trustedOrigins.includes(e)||s.csrf.allowLoopback&&p(o)&&p(e)?!0:s.cors.enabled&&s.cors.isExplicitlyAllowed(e),h=(e,o,s)=>Response.json({error:{code:"FORBIDDEN_ORIGIN",expectedOrigin:s,message:`${e} rejected: Origin ${o===void 0?"was missing":`"${o}"`} is not trusted (this worker serves "${s}"). Add it to \`security.csrf.trustedOrigins\` (or LUNORA_ALLOWED_ORIGINS) if it is yours. Behind a dev proxy this usually means the proxy rewrote the host: keep both ends on loopback, or list the dev-server origin.`,receivedOrigin:o}},{headers:{"content-type":"application/json"},status:403}),j=(e,o)=>{if(!o.csrf.enabled||A.has(e.method)||!e.headers.get("cookie"))return;const s=new URL(e.url).origin,r=c(e.headers.get("origin"))??c(e.headers.get("referer"));if(!(r!==void 0&&w(r,s,o)))return h("cross-origin state-changing request",r,s)},F=(e,o)=>{if(!o.csrf.enabled||!e.headers.get("cookie"))return;const s=new URL(e.url).origin,r=c(e.headers.get("origin"));if(!(r!==void 0&&w(r,s,o)))return h("cross-origin websocket upgrade",r,s)},P=["X-D1-Bookmark","X-Lunora-Shard-Key"],m=(e,o)=>{const s=new Headers;return s.set("access-control-allow-origin",e),s.set("access-control-expose-headers",P.join(", ")),s.append("vary","Origin"),o.allowCredentials&&s.set("access-control-allow-credentials","true"),s},B=(e,o)=>{if(!o.cors.enabled||e.method!=="OPTIONS")return;const s=e.headers.get("origin");if(!s||!e.headers.get("access-control-request-method")||!o.cors.isAllowed(s))return;const r=m(s,o.cors),t=e.headers.get("access-control-request-headers");r.set("access-control-allow-methods",o.cors.allowedMethods.join(", "));let n;if(t===null)n=o.cors.allowedHeaders.join(", ");else{const l=new Set(o.cors.allowedHeaders.map(i=>i.toLowerCase()));n=t.split(",").map(i=>i.trim()).filter(i=>i.length>0&&l.has(i.toLowerCase())).join(", ")}return r.set("access-control-allow-headers",n),r.set("access-control-max-age",String(o.cors.maxAge)),new Response(null,{headers:r,status:204})},T=e=>(e.headers.get("content-type")??"").toLowerCase().includes("text/html"),a=(e,o,s)=>{e.has(o)||e.set(o,s)},x=(e,o,s,r)=>{if(r.hsts!==void 0&&new URL(o.url).protocol==="https:"&&a(e,"strict-transport-security",r.hsts),a(e,"x-content-type-options","nosniff"),r.frameOptions!==void 0&&a(e,"x-frame-options",r.frameOptions),r.referrerPolicy!==void 0&&a(e,"referrer-policy",r.referrerPolicy),r.permissionsPolicy!==void 0&&a(e,"permissions-policy",r.permissionsPolicy),r.coop!==void 0&&a(e,"cross-origin-opener-policy",r.coop),r.csp!==void 0){const t=T(s)?r.csp.htmlValue:r.csp.value;t!==void 0&&a(e,"content-security-policy",t)}},k=(e,o,s)=>{const r=o.headers.get("origin");if(!(!r||!s.isAllowed(r)))for(const[t,n]of m(r,s).entries())t==="vary"?e.append("vary",n):a(e,t,n)},V=(e,o,s)=>{if(e.status===101||e.webSocket)return e;const r=new Headers(e.headers);return s.headers.enabled&&x(r,o,e,s.headers),s.cors.enabled&&k(r,o,s.cors),new Response(e.body,{headers:r,status:e.status,statusText:e.statusText})};export{V as decorateResponse,j as enforceOrigin,F as enforceWebSocketOrigin,B as handleCorsPreflight,M as resolveSecurity};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{e as a,a as s,f}from"./observability-vDK-rMbs.mjs";export{a as emitLogEvent,s as emitRpcEvent,f as flushSink};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const i=(e,s)=>{if(e.size<s)return;const t=e.keys().next().value;t!==void 0&&e.delete(t)};export{i as e};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as r}from"./base64-CMlwEPti.mjs";new TextDecoder;const o=new TextEncoder,n="=",c=e=>{for(let t=0;t<e.length;t+=1)if(e.charCodeAt(t)>255)return!1;return!0},a=e=>r(o.encode(JSON.stringify(e))),d=e=>!e.startsWith(n)&&c(e)?e:`${n}${r(o.encode(e))}`;export{a,d as e};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{e as m}from"./evict-oldest-BNXsKx4s.mjs";const g=n=>{const e=new WeakMap;return(t,a)=>{const i=e.get(t);if(i)return i;const c=Promise.resolve(n(t,a));return e.set(t,c),c}},v=5e3,f=500,p=n=>{const e=n.headers.get("cookie")??"",t=n.headers.get("authorization")??"";if(!(e===""&&t===""))return`${t}\0${e}`},E=(n,e={})=>{const t=e.ttlMs??v,a=Math.max(1,e.maxEntries??f),i=e.cacheKey??p,c=g(n),o=new Map;return(d,u)=>{const r=i(d);if(r===void 0)return c(d,u);const h=Date.now(),l=o.get(r);if(l&&l.expiresAt>h)return l.value;const s=Promise.resolve(c(d,u));return s.catch(()=>{o.get(r)?.value===s&&o.delete(r)}),o.delete(r),m(o,a),o.set(r,{expiresAt:h+t,value:s}),s}};export{E as memoizeIdentity,g as memoizeIdentityPerRequest};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as t}from"./LunoraError-DksAgIpa.mjs";const n=(e,o)=>o.includes(e.method)?void 0:new Response(void 0,{headers:{allow:o.join(", ")},status:405}),a=(e,o,s)=>{if(e.method!==o)throw new t(`${s} endpoint requires ${o}`,{code:"METHOD_NOT_ALLOWED",status:405})};export{a,n as m};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const n=t=>{const r=Number.parseInt(t.slice(0,8),16);return Number.isFinite(r)?r/4294967296:0},a=(t,r=1)=>r>=1?!0:r<=0?!1:n(t)<r,u=(t,r)=>({isTraced:a(r,t?.headRate??1),keepErrors:t?.alwaysSampleErrors??!0}),E=(t,r)=>t.isTraced||t.keepErrors&&r,i=(t,r,e,o,s)=>{if(!t?.onRpc)return;const c=s??(o!==void 0&&r.traceId!==void 0?u(o,r.traceId):void 0);if(!(c!==void 0&&!E(c,!r.ok)))try{t.onRpc(r,e)}catch{}},T=(t,r,e)=>{if(t?.onLog)try{t.onLog(r,e)}catch{}},A=(t,r)=>{if(t?.flush)try{t.flush(r)}catch{}};export{i as a,T as e,A as f,u as r};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const v={debug:5,error:17,fatal:21,info:9,log:9,trace:1,warn:13},m=e=>`${String(Math.round(e))}000000`,O=e=>{const t=new Uint8Array(e);crypto.getRandomValues(t);let r="";for(const o of t)r+=o.toString(16).padStart(2,"0");return r},a=/^[0-9a-f]+$/,b=(e,t,r=!0)=>`00-${e}-${t}-${r?"01":"00"}`,_=e=>{if(e==null)return;const t=e.trim().toLowerCase().split("-"),[r,o,n,s]=t;if(!(t.length<4||r===void 0||r.length!==2||!a.test(r)||r==="ff"||r==="00"&&t.length!==4||o===void 0||n===void 0||s===void 0||s.length!==2||!a.test(s)||o.length!==32||n.length!==16||!a.test(o)||!a.test(n)||o==="00000000000000000000000000000000"||n==="0000000000000000"))return{parentSpanId:n,sampled:(Number.parseInt(s,16)&1)===1,traceId:o}},p=(e,t)=>typeof t=="boolean"?{key:e,value:{boolValue:t}}:typeof t=="number"?Number.isFinite(t)?Number.isSafeInteger(t)?{key:e,value:{intValue:String(t)}}:{key:e,value:{doubleValue:t}}:{key:e,value:{stringValue:String(t)}}:{key:e,value:{stringValue:t}},R=e=>e===void 0?[]:Object.entries(e).map(([t,r])=>p(t,r)),E=(e,t,r)=>{const o={},n=new Map,s=(c,i)=>{const d=c.toLowerCase(),f=n.get(d);f===void 0?(n.set(d,c),o[c]=i):o[f]=i};for(const[c,i]of Object.entries(e))s(c,i);for(const[c,i]of Object.entries(t??{}))s(c,i);return r!==void 0&&r.length>0&&s("authorization",`Bearer ${r}`),o},u=e=>Array.isArray(e)?e:[e],A={client:3,consumer:5,internal:1,producer:4,server:2},N=Object.freeze({durationMs:"lunora.duration_ms",errorMessage:"error.message",errorType:"error.type",functionPath:"lunora.function_path",ok:"lunora.ok",shardKey:"lunora.shard_key",userId:"lunora.user_id"}),l=(e,t)=>{const r={"service.name":e};for(const[o,n]of Object.entries(t??{}))r[o]=n;return Object.entries(r).map(([o,n])=>p(o,n))},S=(e,t,r,o)=>({resourceSpans:[{resource:{attributes:l(r,o)},scopeSpans:[{scope:{name:t},spans:u(e)}]}]}),C=(e,t,r,o)=>({resourceLogs:[{resource:{attributes:l(r,o)},scopeLogs:[{logRecords:u(e),scope:{name:t}}]}]}),L=(e,t,r,o)=>({resourceMetrics:[{resource:{attributes:l(r,o)},scopeMetrics:[{metrics:u(e),scope:{name:t}}]}]}),T=e=>t=>{const r=e?.[t];return typeof r=="string"&&r.length>0?r:void 0},g=(e,t)=>{if(typeof e!="object"||e===null)return;const r=e[t];return typeof r=="string"&&r.length>0?r:void 0},I=e=>{const t={},r=e("SERVICE_VERSION")??e("CF_VERSION_METADATA")??e("VERCEL_GIT_COMMIT_SHA")??e("GITHUB_SHA")??e("COMMIT_SHA");r!==void 0&&(t["service.version"]=r);const o=e("DEPLOYMENT_ENVIRONMENT")??e("ENVIRONMENT")??e("NODE_ENV");return o!==void 0&&(t["deployment.environment"]=o),t},y=(e,t)=>{if(!(t!==void 0||e("CLOUDFLARE")!==void 0||e("CF_ACCOUNT_ID")!==void 0))return{};const o={"cloud.provider":"cloudflare"},n=g(t,"colo")??e("CF_COLO")??e("CLOUDFLARE_COLO");return n!==void 0&&(o["cloud.region"]=n),o},h=(...e)=>{const t={};for(const r of e)if(r!==void 0)for(const[o,n]of Object.entries(r))t[o]=n;return t};export{N as L,A as O,I as a,b,m as c,y as d,p as e,v as f,R as g,E as h,L as i,C as j,h as m,O as o,_ as p,T as r,S as w};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{raw as n,desc as F,sql as r}from"@lunora/bindings/r2sql";const u=["trace","debug","log","info","warn","error","fatal"],S={fields:"fields",functionPath:"functionPath",level:"level",message:"message",shardKey:"shardKey",spanId:"spanId",traceId:"traceId",ts:"ts",userId:"userId"},_=500,w=1e4,N=e=>e===void 0||!Number.isFinite(e)?_:Math.min(Math.max(Math.floor(e),1),w),D=e=>typeof e=="number"?e:Number(e),p=e=>e==null?"":String(e),U=e=>{if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}},K=e=>{const s=JSON.stringify([e.ts,e.level,e.functionPath,e.message,e.traceId,e.spanId,e.shardKey,e.userId,e.fields]);let t=0,l=0;for(const I of s){const v=I.codePointAt(0)??0;t=(t*31+v)%2147483647,l=(l*131+v)%4294967291}return`${t.toString(36)}.${l.toString(36)}`},y=(e,s,t,l)=>{if(s.sinceTs!==void 0&&e.where(r`${n(t.ts)} >= ${s.sinceTs}`),s.untilTs!==void 0&&e.where(r`${n(t.ts)} <= ${s.untilTs}`),s.level!==void 0)e.where(r`${n(t.level)} = ${s.level}`);else if(s.minLevel!==void 0){const I=u.indexOf(s.minLevel),v=I===-1?[...u]:u.slice(I);e.where(r`${n(t.level)} IN ${v}`)}s.functionPath!==void 0&&e.where(r`${n(t.functionPath)} = ${s.functionPath}`),s.functionPathPrefix!==void 0&&e.where(r`${n(t.functionPath)} LIKE ${`${s.functionPathPrefix}%`}`),s.traceId!==void 0&&e.where(r`${n(t.traceId)} = ${s.traceId}`),s.shardKey!==void 0&&e.where(r`${n(t.shardKey)} = ${s.shardKey}`),s.userId!==void 0&&e.where(r`${n(t.userId)} = ${s.userId}`),l!==void 0&&e.where(r`${n(t.ts)} <= ${l}`)},G=S,J=_,k=(e,s)=>{const t={...S,...s.columnMap},l=s.namespace===void 0?s.table:`${s.namespace}.${s.table}`,I=a=>{const c={functionPath:p(a[t.functionPath]),level:p(a[t.level]),message:p(a[t.message]),ts:D(a[t.ts])},o=a[t.fields];o!=null&&(c.fields=U(o));for(const d of["shardKey","userId","traceId","spanId"]){const i=a[t[d]];i!=null&&(c[d]=p(i))}return c},v=async(a,c,o)=>{const d=e.from(l).select(n(t.functionPath),n(t.level),n(t.message),n(t.ts),n(t.fields),n(t.shardKey),n(t.userId),n(t.traceId),n(t.spanId));y(d,a,t,c),d.orderBy(F(n(t.ts))).limit(o);const{rows:i}=await d.run();return i},A=async(a,c,o,d)=>{const i=await v(a,c,d),$=[];for(const P of i){const f=I(P);o!==void 0&&c!==void 0&&f.ts===c&&o.has(K(f))||$.push(f)}return{decoded:$,truncated:i.length>=d}};return{query:async(a={})=>{const c=N(a.limit),{cursor:o}=a,d=o?.ts,i=o?.seen!==void 0&&o.seen.length>0?new Set(o.seen):void 0,$=Math.min(c+1,w),P=3;let f=[],m=!1;for(let h=0;h<P;h+=1){const O=Math.min($*2**h,w),x=await A(a,d,i,O);if(f=x.decoded,m=x.truncated,f.length>c||!m||O>=w)break}const R=f.length>c,L=R?f.slice(0,c):f,M=L.at(-1);if(M===void 0||!(R||m))return{rows:L};const g=M.ts,E=L.filter(h=>h.ts===g).map(h=>K(h)),T=[...d===g&&o?.seen!==void 0?o.seen:[],...E];return{nextCursor:T.length>0?{seen:T,ts:g}:{ts:g},rows:L}}}};export{G as D,u as L,J as a,k as c};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const f="/_lunora/rest",v=["authorization","cf-access-jwt-assertion","cookie"],i=["x-d1-bookmark","x-lunora-shard-key"],u=e=>[...v,...(e.credentialHeaders??[]).map(t=>t.toLowerCase())],d=e=>Number.isFinite(e)?Math.max(0,Math.floor(e)):0,c=(...e)=>{const t=[];for(const a of e)for(const n of a?.split(",")??[]){const r=n.trim().toLowerCase();r!==""&&!t.includes(r)&&t.push(r)}return t.length===0?void 0:t.join(", ")},m=(e,t)=>{const a=[t,`max-age=${String(d(e.maxAge))}`];return e.staleWhileRevalidate!==void 0&&a.push(`stale-while-revalidate=${String(d(e.staleWhileRevalidate))}`),a.join(", ")},l=e=>e.scope==="public"?c(e.vary,...u(e),...i):c(e.vary,...i),h=e=>{const t=e.indexOf(":");if(!(t<=0||t>=e.length-1||e.indexOf(":",t+1)!==-1))return{name:e.slice(t+1),namespace:e.slice(0,t)}},p=e=>{const t=h(e);if(t!==void 0)return`${f}/${t.namespace}/${t.name}`},g=e=>e==="query"?"GET":"POST",R=e=>{const t=[];for(const a of e){if(a.exposure?.rest!==!0||a.kind==="stream")continue;const n=h(a.functionPath),r=p(a.functionPath);n===void 0||r===void 0||t.push({functionPath:a.functionPath,kind:a.kind,method:g(a.kind),name:n.name,namespace:n.namespace,path:r})}return t.sort((a,n)=>a.path.localeCompare(n.path)),t},E=(e,t)=>u(t).some(a=>e.headers.has(a)),C=(e,t,a)=>{if(t.method!=="GET"||a<200||a>299)return;const n=e.scope==="public"&&!E(t,e)?"public":"private",r={"cache-control":m(e,n)};e.tag!==void 0&&e.tag!==""&&(r["cache-tag"]=e.tag);const s=l(e);return s!==void 0&&(r.vary=s),r},S=(e,t,a)=>{if(t===void 0)return e;const n=C(t,a,e.status);if(n===void 0)return e;const r=new Response(e.body,e);for(const[s,o]of Object.entries(n))r.headers.set(s,s==="vary"?c(r.headers.get("vary")??void 0,o)??o:o);return r};export{S as a,C as b,R as d,E as r};
|