@lunora/runtime 1.0.0-alpha.56 → 1.0.0-alpha.57

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { RankDirection, RankPageRow, DatabaseWriterLike, CrossShardReadArgs, QueryPage } from '@lunora/shard-engine';
2
2
  export type { RankDirection as RankPageDirection, RankPageRowKey as RankPageKey, RankPageRow, ShardRankPageResult } from '@lunora/shard-engine';
3
+ import { ShardDirectory } from '@lunora/platform';
3
4
  import { R2SqlClient } from '@lunora/bindings/r2sql';
4
5
  import { WorkflowsRestClient } from '@lunora/workflow';
5
6
  import { LunoraError as LunoraError$1, ErrorBody } from '@lunora/errors';
@@ -607,6 +608,7 @@ type DurableObjectJurisdiction = "eu" | "fedramp" | "us";
607
608
  * unit-test doubles without coupling to `@cloudflare/workers-types`.
608
609
  */
609
610
  interface ShardNamespaceLike {
611
+ /** Materialize a stub from an opaque id. */
610
612
  get: (id: unknown) => {
611
613
  fetch: (request: Request) => Promise<Response>;
612
614
  };
@@ -618,6 +620,7 @@ interface ShardNamespaceLike {
618
620
  getByName?: (name: string) => {
619
621
  fetch: (request: Request) => Promise<Response>;
620
622
  };
623
+ /** Cloudflare's `DurableObjectNamespace` spelling of `idForName`. */
621
624
  idFromName: (name: string) => unknown;
622
625
  /**
623
626
  * Derive a jurisdiction-restricted subnamespace. Every ID and stub created
@@ -628,6 +631,24 @@ interface ShardNamespaceLike {
628
631
  */
629
632
  jurisdiction?: (jurisdiction: DurableObjectJurisdiction) => ShardNamespaceLike;
630
633
  }
634
+ /**
635
+ * What a fan-out entry point accepts: a Cloudflare binding **or** a
636
+ * `@lunora/platform` `ShardDirectory`.
637
+ *
638
+ * The two shapes differ by one method name — the contract spells `idFromName`
639
+ * as `idForName` — and that one letter made every entry point
640
+ * (`QueryCoordinator.fanOut`, the `orchestrate*` family) reject a fully
641
+ * conforming directory. A porting blocker, found by construction the first time
642
+ * `@lunora/platform-node` fanned out.
643
+ *
644
+ * It is a **union, not a loosened `ShardNamespaceLike`**. Making `get` and
645
+ * `idFromName` optional on that interface fixed fan-out and broke everything
646
+ * else: it is the projection of a real `DurableObjectNamespace`, so ~74 call
647
+ * sites and every app's `env.SHARD` inherited two members that were suddenly
648
+ * `possibly undefined`. Widening the input is what was wanted; widening the
649
+ * binding type was collateral.
650
+ */
651
+ type ShardNamespaceInput = ShardDirectory | ShardNamespaceLike;
631
652
  interface ResolvedShard {
632
653
  fetch: (request: Request) => Promise<Response>;
633
654
  }
@@ -648,7 +669,7 @@ declare const applyJurisdiction: (namespace: ShardNamespaceLike, jurisdiction?:
648
669
  * else `idFromName` + `get` — but the preference now lives in one place (the
649
670
  * contract's `resolveShard`) rather than being restated per resolution path.
650
671
  */
651
- declare const resolveShard: (namespace: ShardNamespaceLike, shardKey: string) => ResolvedShard;
672
+ declare const resolveShard: (namespace: ShardNamespaceInput, shardKey: string) => ResolvedShard;
652
673
  /**
653
674
  * Source of "which shard keys exist for a given table right now". Returning
654
675
  * an empty array is valid — the coordinator will respond with the merge
@@ -933,43 +954,43 @@ interface RankPageFanOutResult {
933
954
  shards: ReadonlyArray<ShardRankPageOutcome>;
934
955
  }
935
956
  interface QueryCoordinator {
936
- fanOut: <T = unknown>(namespace: ShardNamespaceLike, request: FanOutRequest) => Promise<FanOutResult<T>>;
957
+ fanOut: <T = unknown>(namespace: ShardNamespaceInput, request: FanOutRequest) => Promise<FanOutResult<T>>;
937
958
  /**
938
959
  * Fan the `__lunora_admin__:applyCdc` admin RPC out by forwarding each
939
960
  * pre-bucketed per-shard batch of CDC changes, rolling up the applied/failed
940
961
  * counts. The replay half of point-in-time recovery.
941
962
  */
942
- orchestrateApplyCdc: (namespace: ShardNamespaceLike, request: ApplyCdcFanOutRequest) => Promise<ApplyCdcFanOutResult>;
963
+ orchestrateApplyCdc: (namespace: ShardNamespaceInput, request: ApplyCdcFanOutRequest) => Promise<ApplyCdcFanOutResult>;
943
964
  /**
944
965
  * Fan the `__lunora_admin__:cdcSync` admin RPC out to every live shard,
945
966
  * each resumed from its own cursor in `request.cursors` (shardKey → seq).
946
967
  * Returns the per-shard change pages plus their new cursors so the caller
947
968
  * can checkpoint each shard independently — the streaming-export feed.
948
969
  */
949
- orchestrateCdcSync: (namespace: ShardNamespaceLike, request: CdcSyncFanOutRequest) => Promise<CdcSyncFanOutResult>;
970
+ orchestrateCdcSync: (namespace: ShardNamespaceInput, request: CdcSyncFanOutRequest) => Promise<CdcSyncFanOutResult>;
950
971
  /**
951
972
  * Fan an export admin RPC out to every live shard, returning the
952
973
  * per-shard `{rows}` payloads alongside any per-shard errors. Each shard
953
974
  * returns a JSON envelope (not a streaming body) so this method is the
954
975
  * collector — the worker assembles the NDJSON stream.
955
976
  */
956
- orchestrateExport: (namespace: ShardNamespaceLike, request: ExportFanOutRequest) => Promise<ExportFanOutResult>;
977
+ orchestrateExport: (namespace: ShardNamespaceInput, request: ExportFanOutRequest) => Promise<ExportFanOutResult>;
957
978
  /**
958
979
  * Fan an import admin RPC out by routing each row to its owning shard. The
959
980
  * shard registry resolves which shards exist; rows whose table has a
960
981
  * `shardBy(field)` are bucketed using that field's value as the shard key,
961
982
  * other tables fall back to the runtime's default `__root__` shard.
962
983
  */
963
- orchestrateImport: (namespace: ShardNamespaceLike, request: ImportFanOutRequest) => Promise<ImportFanOutResult>;
984
+ orchestrateImport: (namespace: ShardNamespaceInput, request: ImportFanOutRequest) => Promise<ImportFanOutResult>;
964
985
  /** Fan a migration admin RPC out to every live shard of a table and roll up the per-shard outcomes. */
965
- orchestrateMigration: (namespace: ShardNamespaceLike, request: MigrationFanOutRequest) => Promise<MigrationFanOutResult>;
986
+ orchestrateMigration: (namespace: ShardNamespaceInput, request: MigrationFanOutRequest) => Promise<MigrationFanOutResult>;
966
987
  /**
967
988
  * Fan the `__lunora_admin__:rankBefore` admin RPC out to every live shard of
968
989
  * a table and roll up the per-shard `{before, total}` payloads into the
969
990
  * global rank (`{position: Σbefore + 1, total: Σtotal}`). The cross-shard
970
991
  * `rank()` path for a partition that spans shards.
971
992
  */
972
- orchestrateRank: (namespace: ShardNamespaceLike, request: RankFanOutRequest) => Promise<RankFanOutResult>;
993
+ orchestrateRank: (namespace: ShardNamespaceInput, request: RankFanOutRequest) => Promise<RankFanOutResult>;
973
994
  /**
974
995
  * Page a ranked query across every live shard of a `.shardBy(...)` table.
975
996
  * Fans `__lunora_admin__:rankPage` out to each shard, gathers each shard's
@@ -980,7 +1001,7 @@ interface QueryCoordinator {
980
1001
  * consumed from it — pages never drop or duplicate a row at a shard
981
1002
  * boundary. The cross-shard `rankPage()` path (PLAN5 §7.1 / PLAN2 #3).
982
1003
  */
983
- orchestrateRankPage: (namespace: ShardNamespaceLike, request: RankPageFanOutRequest) => Promise<RankPageFanOutResult>;
1004
+ orchestrateRankPage: (namespace: ShardNamespaceInput, request: RankPageFanOutRequest) => Promise<RankPageFanOutResult>;
984
1005
  /**
985
1006
  * Fan the `__lunora_admin__:getMetrics` admin RPC out to every live shard of
986
1007
  * a table and collect each shard's lifetime `requests` total into a per-shard
@@ -989,7 +1010,7 @@ interface QueryCoordinator {
989
1010
  * skew, so this fans the cheap metrics read out and returns the whole shard
990
1011
  * set's request volumes (a failed shard surfaces as `requests: 0`).
991
1012
  */
992
- orchestrateShardTraffic: (namespace: ShardNamespaceLike, request: ShardTrafficFanOutRequest) => Promise<ShardTrafficFanOutResult>;
1013
+ orchestrateShardTraffic: (namespace: ShardNamespaceInput, request: ShardTrafficFanOutRequest) => Promise<ShardTrafficFanOutResult>;
993
1014
  readonly registry: ShardRegistry;
994
1015
  }
995
1016
  /**
@@ -4671,4 +4692,4 @@ interface ShardClient {
4671
4692
  */
4672
4693
  declare const createShardClient: (namespace: ShardNamespaceLike, options?: ShardClientOptions) => ShardClient;
4673
4694
  declare const VERSION: string;
4674
- 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, type BackupManifest, type BackupStore, type ComposeIdentityResolversErrorMode, type ComposeIdentityResolversOptions, type ConnectorChange, type ConnectorSyncPage, type CorsOptions, type CronHandler, type CronJobDispatch, type CronJobInfo, type CrossShardCounter, type CrossShardReader, type CrossShardRelationCapabilities, type CrossShardRelationOptions, type CsrfOptions, DEFAULT_LOG_COLUMNS, DEFAULT_LOG_LIMIT, DEFAULT_REGISTRY_CACHE_TTL_MS, type DurableObjectJurisdiction, type DynamicShardRegistry, type DynamicShardRegistryOptions, type ExecutionContextLike, type ExportBatch, type ExportChange, type ExportCursorStore, type ExportFanOutRequest, type ExportFanOutResult, type ExportSink, type ExportTapFailure, type ExportTapResult, type FanOutRequest, type FanOutResult, type FanOutSpec, type FivetranResponse, type FrameworkHostHandler, type FrameworkWorkerOptions, type FrameworkWorkerOptionsInput, type FunctionDescriptor, type FunctionRegistryEntry, type FunctionRegistryLike, type GlobalExportFunction as GlobalExportFn, type GlobalImportFunction as GlobalImportFn, type GlobalIntrospector, type GlobalTableInfo as GlobalTableInfoMeta, type GlobalTablePage as GlobalTablePageMeta, HEALTH_PATH, HEALTH_READY_PATH, type HealthAuthPosture, type HealthBody, type HealthCheckReport, type HealthProbe, type HealthProbeKind, type HealthProbeResult, type HealthRouteDeps, type HttpActionContext, type HttpActionLike, type HttpRouterLike, type IdentityContractLike, type IdentityResolver, type IdentityValidation, type ImportFanOutRequest, type ImportFanOutResult, type KvIntrospector, type KvKeyEntry, type KvKeyListResult, type KvNamespaceSummary, type KvValueResult, LOG_ARCHIVE_NOT_CONFIGURED, LOG_ARCHIVE_PATH, type ListAuthUsersOptions, type LogArchiveConfig, type LogEvent, type LogFields, type LogLevel, LunoraError, type LunoraErrorBody, type LunoraHandlerOptions, type LunoraWorker, type MemoizeIdentityOptions, type MergeStrategy, type MetricEvent, type MetricKind, type MigrationFanOutRequest, type MigrationFanOutResult, NOOP_EXECUTION_CONTEXT, type NotifySubscriptionDevice, type NotifySubscriptionStoreLike, type ObservabilityEvent, type ObservabilitySink, type ObservabilitySinkContext, type OtlpResourceAttributes, type OtlpSinkOptions, type PipelineLike, type PipelineLogColumnMap, type PipelineLogCursor, type PipelineLogField, type PipelineLogPage, type PipelineLogQuery, type PipelineLogReader, type PipelineLogReaderOptions, type PipelineLogRow, type PipelineLogSinkOptions, type QueryCoordinator, type QueryCoordinatorOptions, type RankFanOutRequest, type RankFanOutResult, type RankPageFanOutRequest, type RankPageFanOutResult, type RateLimiterLike, type ResolvedSecurity, type ResolvedShard, type RestInvoke, type RestRateLimit, type RestRegistryEntry, type RestRegistryLike, type RestRoute, type RestRouteDeps, type Route, type RpcContext, type RpcEnvelope, type RunExportTapOptions, SHARD_REGISTRY_DO_NAME, 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 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, 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, memoizeIdentity, memoizeIdentityPerRequest, mergeStrategyForAggregate, otlpSink, pipelineLogSink, presenceProbe, r2Sink, readShardKey, requestCarriesCredentials, resolveLogArchiveFromEnv, resolveLunoraOptions, resolveSecurity, resolveShard, restCacheHeaders, restSurfaceFromRegistry, routeIdentityResolvers, runExportTap, sanitizeChange, sentrySink, toAirbyteMessages, toErrorResponse, toFivetranResponse, webhookExportSink, webhookSink, withFrameworkWorker };
4695
+ 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, type BackupManifest, type BackupStore, type ComposeIdentityResolversErrorMode, type ComposeIdentityResolversOptions, type ConnectorChange, type ConnectorSyncPage, type CorsOptions, type CronHandler, type CronJobDispatch, type CronJobInfo, type CrossShardCounter, type CrossShardReader, type CrossShardRelationCapabilities, type CrossShardRelationOptions, type CsrfOptions, DEFAULT_LOG_COLUMNS, DEFAULT_LOG_LIMIT, DEFAULT_REGISTRY_CACHE_TTL_MS, type DurableObjectJurisdiction, type DynamicShardRegistry, type DynamicShardRegistryOptions, type ExecutionContextLike, type ExportBatch, type ExportChange, type ExportCursorStore, type ExportFanOutRequest, type ExportFanOutResult, type ExportSink, type ExportTapFailure, type ExportTapResult, type FanOutRequest, type FanOutResult, type FanOutSpec, type FivetranResponse, type FrameworkHostHandler, type FrameworkWorkerOptions, type FrameworkWorkerOptionsInput, type FunctionDescriptor, type FunctionRegistryEntry, type FunctionRegistryLike, type GlobalExportFunction as GlobalExportFn, type GlobalImportFunction as GlobalImportFn, type GlobalIntrospector, type GlobalTableInfo as GlobalTableInfoMeta, type GlobalTablePage as GlobalTablePageMeta, HEALTH_PATH, HEALTH_READY_PATH, type HealthAuthPosture, type HealthBody, type HealthCheckReport, type HealthProbe, type HealthProbeKind, type HealthProbeResult, type HealthRouteDeps, type HttpActionContext, type HttpActionLike, type HttpRouterLike, type IdentityContractLike, type IdentityResolver, type IdentityValidation, type ImportFanOutRequest, type ImportFanOutResult, type KvIntrospector, type KvKeyEntry, type KvKeyListResult, type KvNamespaceSummary, type KvValueResult, LOG_ARCHIVE_NOT_CONFIGURED, LOG_ARCHIVE_PATH, type ListAuthUsersOptions, type LogArchiveConfig, type LogEvent, type LogFields, type LogLevel, LunoraError, type LunoraErrorBody, type LunoraHandlerOptions, type LunoraWorker, type MemoizeIdentityOptions, type MergeStrategy, type MetricEvent, type MetricKind, type MigrationFanOutRequest, type MigrationFanOutResult, NOOP_EXECUTION_CONTEXT, type NotifySubscriptionDevice, type NotifySubscriptionStoreLike, type ObservabilityEvent, type ObservabilitySink, type ObservabilitySinkContext, type OtlpResourceAttributes, type OtlpSinkOptions, type PipelineLike, type PipelineLogColumnMap, type PipelineLogCursor, type PipelineLogField, type PipelineLogPage, type PipelineLogQuery, type PipelineLogReader, type PipelineLogReaderOptions, type PipelineLogRow, type PipelineLogSinkOptions, type QueryCoordinator, type QueryCoordinatorOptions, type RankFanOutRequest, type RankFanOutResult, type RankPageFanOutRequest, type RankPageFanOutResult, type RateLimiterLike, type ResolvedSecurity, type ResolvedShard, type RestInvoke, type RestRateLimit, type RestRegistryEntry, type RestRegistryLike, type RestRoute, type RestRouteDeps, type Route, type RpcContext, type RpcEnvelope, type RunExportTapOptions, SHARD_REGISTRY_DO_NAME, 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, 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, memoizeIdentity, memoizeIdentityPerRequest, mergeStrategyForAggregate, 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
@@ -1,5 +1,6 @@
1
1
  import { RankDirection, RankPageRow, DatabaseWriterLike, CrossShardReadArgs, QueryPage } from '@lunora/shard-engine';
2
2
  export type { RankDirection as RankPageDirection, RankPageRowKey as RankPageKey, RankPageRow, ShardRankPageResult } from '@lunora/shard-engine';
3
+ import { ShardDirectory } from '@lunora/platform';
3
4
  import { R2SqlClient } from '@lunora/bindings/r2sql';
4
5
  import { WorkflowsRestClient } from '@lunora/workflow';
5
6
  import { LunoraError as LunoraError$1, ErrorBody } from '@lunora/errors';
@@ -607,6 +608,7 @@ type DurableObjectJurisdiction = "eu" | "fedramp" | "us";
607
608
  * unit-test doubles without coupling to `@cloudflare/workers-types`.
608
609
  */
609
610
  interface ShardNamespaceLike {
611
+ /** Materialize a stub from an opaque id. */
610
612
  get: (id: unknown) => {
611
613
  fetch: (request: Request) => Promise<Response>;
612
614
  };
@@ -618,6 +620,7 @@ interface ShardNamespaceLike {
618
620
  getByName?: (name: string) => {
619
621
  fetch: (request: Request) => Promise<Response>;
620
622
  };
623
+ /** Cloudflare's `DurableObjectNamespace` spelling of `idForName`. */
621
624
  idFromName: (name: string) => unknown;
622
625
  /**
623
626
  * Derive a jurisdiction-restricted subnamespace. Every ID and stub created
@@ -628,6 +631,24 @@ interface ShardNamespaceLike {
628
631
  */
629
632
  jurisdiction?: (jurisdiction: DurableObjectJurisdiction) => ShardNamespaceLike;
630
633
  }
634
+ /**
635
+ * What a fan-out entry point accepts: a Cloudflare binding **or** a
636
+ * `@lunora/platform` `ShardDirectory`.
637
+ *
638
+ * The two shapes differ by one method name — the contract spells `idFromName`
639
+ * as `idForName` — and that one letter made every entry point
640
+ * (`QueryCoordinator.fanOut`, the `orchestrate*` family) reject a fully
641
+ * conforming directory. A porting blocker, found by construction the first time
642
+ * `@lunora/platform-node` fanned out.
643
+ *
644
+ * It is a **union, not a loosened `ShardNamespaceLike`**. Making `get` and
645
+ * `idFromName` optional on that interface fixed fan-out and broke everything
646
+ * else: it is the projection of a real `DurableObjectNamespace`, so ~74 call
647
+ * sites and every app's `env.SHARD` inherited two members that were suddenly
648
+ * `possibly undefined`. Widening the input is what was wanted; widening the
649
+ * binding type was collateral.
650
+ */
651
+ type ShardNamespaceInput = ShardDirectory | ShardNamespaceLike;
631
652
  interface ResolvedShard {
632
653
  fetch: (request: Request) => Promise<Response>;
633
654
  }
@@ -648,7 +669,7 @@ declare const applyJurisdiction: (namespace: ShardNamespaceLike, jurisdiction?:
648
669
  * else `idFromName` + `get` — but the preference now lives in one place (the
649
670
  * contract's `resolveShard`) rather than being restated per resolution path.
650
671
  */
651
- declare const resolveShard: (namespace: ShardNamespaceLike, shardKey: string) => ResolvedShard;
672
+ declare const resolveShard: (namespace: ShardNamespaceInput, shardKey: string) => ResolvedShard;
652
673
  /**
653
674
  * Source of "which shard keys exist for a given table right now". Returning
654
675
  * an empty array is valid — the coordinator will respond with the merge
@@ -933,43 +954,43 @@ interface RankPageFanOutResult {
933
954
  shards: ReadonlyArray<ShardRankPageOutcome>;
934
955
  }
935
956
  interface QueryCoordinator {
936
- fanOut: <T = unknown>(namespace: ShardNamespaceLike, request: FanOutRequest) => Promise<FanOutResult<T>>;
957
+ fanOut: <T = unknown>(namespace: ShardNamespaceInput, request: FanOutRequest) => Promise<FanOutResult<T>>;
937
958
  /**
938
959
  * Fan the `__lunora_admin__:applyCdc` admin RPC out by forwarding each
939
960
  * pre-bucketed per-shard batch of CDC changes, rolling up the applied/failed
940
961
  * counts. The replay half of point-in-time recovery.
941
962
  */
942
- orchestrateApplyCdc: (namespace: ShardNamespaceLike, request: ApplyCdcFanOutRequest) => Promise<ApplyCdcFanOutResult>;
963
+ orchestrateApplyCdc: (namespace: ShardNamespaceInput, request: ApplyCdcFanOutRequest) => Promise<ApplyCdcFanOutResult>;
943
964
  /**
944
965
  * Fan the `__lunora_admin__:cdcSync` admin RPC out to every live shard,
945
966
  * each resumed from its own cursor in `request.cursors` (shardKey → seq).
946
967
  * Returns the per-shard change pages plus their new cursors so the caller
947
968
  * can checkpoint each shard independently — the streaming-export feed.
948
969
  */
949
- orchestrateCdcSync: (namespace: ShardNamespaceLike, request: CdcSyncFanOutRequest) => Promise<CdcSyncFanOutResult>;
970
+ orchestrateCdcSync: (namespace: ShardNamespaceInput, request: CdcSyncFanOutRequest) => Promise<CdcSyncFanOutResult>;
950
971
  /**
951
972
  * Fan an export admin RPC out to every live shard, returning the
952
973
  * per-shard `{rows}` payloads alongside any per-shard errors. Each shard
953
974
  * returns a JSON envelope (not a streaming body) so this method is the
954
975
  * collector — the worker assembles the NDJSON stream.
955
976
  */
956
- orchestrateExport: (namespace: ShardNamespaceLike, request: ExportFanOutRequest) => Promise<ExportFanOutResult>;
977
+ orchestrateExport: (namespace: ShardNamespaceInput, request: ExportFanOutRequest) => Promise<ExportFanOutResult>;
957
978
  /**
958
979
  * Fan an import admin RPC out by routing each row to its owning shard. The
959
980
  * shard registry resolves which shards exist; rows whose table has a
960
981
  * `shardBy(field)` are bucketed using that field's value as the shard key,
961
982
  * other tables fall back to the runtime's default `__root__` shard.
962
983
  */
963
- orchestrateImport: (namespace: ShardNamespaceLike, request: ImportFanOutRequest) => Promise<ImportFanOutResult>;
984
+ orchestrateImport: (namespace: ShardNamespaceInput, request: ImportFanOutRequest) => Promise<ImportFanOutResult>;
964
985
  /** Fan a migration admin RPC out to every live shard of a table and roll up the per-shard outcomes. */
965
- orchestrateMigration: (namespace: ShardNamespaceLike, request: MigrationFanOutRequest) => Promise<MigrationFanOutResult>;
986
+ orchestrateMigration: (namespace: ShardNamespaceInput, request: MigrationFanOutRequest) => Promise<MigrationFanOutResult>;
966
987
  /**
967
988
  * Fan the `__lunora_admin__:rankBefore` admin RPC out to every live shard of
968
989
  * a table and roll up the per-shard `{before, total}` payloads into the
969
990
  * global rank (`{position: Σbefore + 1, total: Σtotal}`). The cross-shard
970
991
  * `rank()` path for a partition that spans shards.
971
992
  */
972
- orchestrateRank: (namespace: ShardNamespaceLike, request: RankFanOutRequest) => Promise<RankFanOutResult>;
993
+ orchestrateRank: (namespace: ShardNamespaceInput, request: RankFanOutRequest) => Promise<RankFanOutResult>;
973
994
  /**
974
995
  * Page a ranked query across every live shard of a `.shardBy(...)` table.
975
996
  * Fans `__lunora_admin__:rankPage` out to each shard, gathers each shard's
@@ -980,7 +1001,7 @@ interface QueryCoordinator {
980
1001
  * consumed from it — pages never drop or duplicate a row at a shard
981
1002
  * boundary. The cross-shard `rankPage()` path (PLAN5 §7.1 / PLAN2 #3).
982
1003
  */
983
- orchestrateRankPage: (namespace: ShardNamespaceLike, request: RankPageFanOutRequest) => Promise<RankPageFanOutResult>;
1004
+ orchestrateRankPage: (namespace: ShardNamespaceInput, request: RankPageFanOutRequest) => Promise<RankPageFanOutResult>;
984
1005
  /**
985
1006
  * Fan the `__lunora_admin__:getMetrics` admin RPC out to every live shard of
986
1007
  * a table and collect each shard's lifetime `requests` total into a per-shard
@@ -989,7 +1010,7 @@ interface QueryCoordinator {
989
1010
  * skew, so this fans the cheap metrics read out and returns the whole shard
990
1011
  * set's request volumes (a failed shard surfaces as `requests: 0`).
991
1012
  */
992
- orchestrateShardTraffic: (namespace: ShardNamespaceLike, request: ShardTrafficFanOutRequest) => Promise<ShardTrafficFanOutResult>;
1013
+ orchestrateShardTraffic: (namespace: ShardNamespaceInput, request: ShardTrafficFanOutRequest) => Promise<ShardTrafficFanOutResult>;
993
1014
  readonly registry: ShardRegistry;
994
1015
  }
995
1016
  /**
@@ -4671,4 +4692,4 @@ interface ShardClient {
4671
4692
  */
4672
4693
  declare const createShardClient: (namespace: ShardNamespaceLike, options?: ShardClientOptions) => ShardClient;
4673
4694
  declare const VERSION: string;
4674
- 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, type BackupManifest, type BackupStore, type ComposeIdentityResolversErrorMode, type ComposeIdentityResolversOptions, type ConnectorChange, type ConnectorSyncPage, type CorsOptions, type CronHandler, type CronJobDispatch, type CronJobInfo, type CrossShardCounter, type CrossShardReader, type CrossShardRelationCapabilities, type CrossShardRelationOptions, type CsrfOptions, DEFAULT_LOG_COLUMNS, DEFAULT_LOG_LIMIT, DEFAULT_REGISTRY_CACHE_TTL_MS, type DurableObjectJurisdiction, type DynamicShardRegistry, type DynamicShardRegistryOptions, type ExecutionContextLike, type ExportBatch, type ExportChange, type ExportCursorStore, type ExportFanOutRequest, type ExportFanOutResult, type ExportSink, type ExportTapFailure, type ExportTapResult, type FanOutRequest, type FanOutResult, type FanOutSpec, type FivetranResponse, type FrameworkHostHandler, type FrameworkWorkerOptions, type FrameworkWorkerOptionsInput, type FunctionDescriptor, type FunctionRegistryEntry, type FunctionRegistryLike, type GlobalExportFunction as GlobalExportFn, type GlobalImportFunction as GlobalImportFn, type GlobalIntrospector, type GlobalTableInfo as GlobalTableInfoMeta, type GlobalTablePage as GlobalTablePageMeta, HEALTH_PATH, HEALTH_READY_PATH, type HealthAuthPosture, type HealthBody, type HealthCheckReport, type HealthProbe, type HealthProbeKind, type HealthProbeResult, type HealthRouteDeps, type HttpActionContext, type HttpActionLike, type HttpRouterLike, type IdentityContractLike, type IdentityResolver, type IdentityValidation, type ImportFanOutRequest, type ImportFanOutResult, type KvIntrospector, type KvKeyEntry, type KvKeyListResult, type KvNamespaceSummary, type KvValueResult, LOG_ARCHIVE_NOT_CONFIGURED, LOG_ARCHIVE_PATH, type ListAuthUsersOptions, type LogArchiveConfig, type LogEvent, type LogFields, type LogLevel, LunoraError, type LunoraErrorBody, type LunoraHandlerOptions, type LunoraWorker, type MemoizeIdentityOptions, type MergeStrategy, type MetricEvent, type MetricKind, type MigrationFanOutRequest, type MigrationFanOutResult, NOOP_EXECUTION_CONTEXT, type NotifySubscriptionDevice, type NotifySubscriptionStoreLike, type ObservabilityEvent, type ObservabilitySink, type ObservabilitySinkContext, type OtlpResourceAttributes, type OtlpSinkOptions, type PipelineLike, type PipelineLogColumnMap, type PipelineLogCursor, type PipelineLogField, type PipelineLogPage, type PipelineLogQuery, type PipelineLogReader, type PipelineLogReaderOptions, type PipelineLogRow, type PipelineLogSinkOptions, type QueryCoordinator, type QueryCoordinatorOptions, type RankFanOutRequest, type RankFanOutResult, type RankPageFanOutRequest, type RankPageFanOutResult, type RateLimiterLike, type ResolvedSecurity, type ResolvedShard, type RestInvoke, type RestRateLimit, type RestRegistryEntry, type RestRegistryLike, type RestRoute, type RestRouteDeps, type Route, type RpcContext, type RpcEnvelope, type RunExportTapOptions, SHARD_REGISTRY_DO_NAME, 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 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, 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, memoizeIdentity, memoizeIdentityPerRequest, mergeStrategyForAggregate, otlpSink, pipelineLogSink, presenceProbe, r2Sink, readShardKey, requestCarriesCredentials, resolveLogArchiveFromEnv, resolveLunoraOptions, resolveSecurity, resolveShard, restCacheHeaders, restSurfaceFromRegistry, routeIdentityResolvers, runExportTap, sanitizeChange, sentrySink, toAirbyteMessages, toErrorResponse, toFivetranResponse, webhookExportSink, webhookSink, withFrameworkWorker };
4695
+ 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, type BackupManifest, type BackupStore, type ComposeIdentityResolversErrorMode, type ComposeIdentityResolversOptions, type ConnectorChange, type ConnectorSyncPage, type CorsOptions, type CronHandler, type CronJobDispatch, type CronJobInfo, type CrossShardCounter, type CrossShardReader, type CrossShardRelationCapabilities, type CrossShardRelationOptions, type CsrfOptions, DEFAULT_LOG_COLUMNS, DEFAULT_LOG_LIMIT, DEFAULT_REGISTRY_CACHE_TTL_MS, type DurableObjectJurisdiction, type DynamicShardRegistry, type DynamicShardRegistryOptions, type ExecutionContextLike, type ExportBatch, type ExportChange, type ExportCursorStore, type ExportFanOutRequest, type ExportFanOutResult, type ExportSink, type ExportTapFailure, type ExportTapResult, type FanOutRequest, type FanOutResult, type FanOutSpec, type FivetranResponse, type FrameworkHostHandler, type FrameworkWorkerOptions, type FrameworkWorkerOptionsInput, type FunctionDescriptor, type FunctionRegistryEntry, type FunctionRegistryLike, type GlobalExportFunction as GlobalExportFn, type GlobalImportFunction as GlobalImportFn, type GlobalIntrospector, type GlobalTableInfo as GlobalTableInfoMeta, type GlobalTablePage as GlobalTablePageMeta, HEALTH_PATH, HEALTH_READY_PATH, type HealthAuthPosture, type HealthBody, type HealthCheckReport, type HealthProbe, type HealthProbeKind, type HealthProbeResult, type HealthRouteDeps, type HttpActionContext, type HttpActionLike, type HttpRouterLike, type IdentityContractLike, type IdentityResolver, type IdentityValidation, type ImportFanOutRequest, type ImportFanOutResult, type KvIntrospector, type KvKeyEntry, type KvKeyListResult, type KvNamespaceSummary, type KvValueResult, LOG_ARCHIVE_NOT_CONFIGURED, LOG_ARCHIVE_PATH, type ListAuthUsersOptions, type LogArchiveConfig, type LogEvent, type LogFields, type LogLevel, LunoraError, type LunoraErrorBody, type LunoraHandlerOptions, type LunoraWorker, type MemoizeIdentityOptions, type MergeStrategy, type MetricEvent, type MetricKind, type MigrationFanOutRequest, type MigrationFanOutResult, NOOP_EXECUTION_CONTEXT, type NotifySubscriptionDevice, type NotifySubscriptionStoreLike, type ObservabilityEvent, type ObservabilitySink, type ObservabilitySinkContext, type OtlpResourceAttributes, type OtlpSinkOptions, type PipelineLike, type PipelineLogColumnMap, type PipelineLogCursor, type PipelineLogField, type PipelineLogPage, type PipelineLogQuery, type PipelineLogReader, type PipelineLogReaderOptions, type PipelineLogRow, type PipelineLogSinkOptions, type QueryCoordinator, type QueryCoordinatorOptions, type RankFanOutRequest, type RankFanOutResult, type RankPageFanOutRequest, type RankPageFanOutResult, type RateLimiterLike, type ResolvedSecurity, type ResolvedShard, type RestInvoke, type RestRateLimit, type RestRegistryEntry, type RestRegistryLike, type RestRoute, type RestRouteDeps, type Route, type RpcContext, type RpcEnvelope, type RunExportTapOptions, SHARD_REGISTRY_DO_NAME, 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, 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, memoizeIdentity, memoizeIdentityPerRequest, mergeStrategyForAggregate, 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{toAirbyteMessages as t,toFivetranResponse as a}from"./packem_shared/toAirbyteMessages-DTk8e2f9.mjs";import{composeWorker as i,createLunoraHandler as n,createWorker as p,defineRpcEnvelope as m,resolveLunoraOptions as c,withFrameworkWorker as R}from"./packem_shared/composeWorker-MnGFIJTe.mjs";import{createCrossShardRelationCapabilities as S}from"./packem_shared/createCrossShardRelationCapabilities-CQfrCIWR.mjs";import{DEFAULT_REGISTRY_CACHE_TTL_MS as f,SHARD_REGISTRY_DO_NAME as l,createDynamicShardRegistry as x}from"./packem_shared/DEFAULT_REGISTRY_CACHE_TTL_MS-BclNO0yc.mjs";import{LunoraError as y,toErrorResponse as C}from"./packem_shared/LunoraError-ByasbDmd.mjs";import{createKvCursorStore as g,createMemoryCursorStore as u,defineExportSink as T,r2Sink as A,runExportTap as h,sanitizeChange as k,webhookExportSink as O}from"./packem_shared/createKvCursorStore-C24tEuYk.mjs";import{HEALTH_PATH as v,HEALTH_READY_PATH as I,buildHealthRoutes as b,d1Probe as F,durableObjectProbe as P,presenceProbe as D}from"./packem_shared/HEALTH_PATH-Cqrg0Dq3.mjs";import{LOG_ARCHIVE_PATH as G,resolveLogArchiveFromEnv as U}from"./packem_shared/LOG_ARCHIVE_PATH-CuHKuDCS.mjs";import{memoizeIdentity as w,memoizeIdentityPerRequest as z}from"./packem_shared/memoizeIdentity-CX3xEPYw.mjs";import{e as W,a as Y}from"./packem_shared/observability-DWlkDJJw.mjs";import{analyticsEngineSink as K,combineSinks as Q,consoleSink as X,otlpSink as j,pipelineLogSink as J,sentrySink as B,webhookSink as Z}from"./packem_shared/analyticsEngineSink-iIRy11I9.mjs";import{D as ee,a as re,c as oe}from"./packem_shared/pipeline-log-reader-FF1V32O2.mjs";import{createQueryCoordinator as ae,createStaticShardRegistry as se,mergeStrategyForAggregate as ie}from"./packem_shared/createQueryCoordinator-D7NpIHuQ.mjs";import{applyJurisdiction as pe,resolveShard as me}from"./packem_shared/applyJurisdiction-8bzZjAPR.mjs";import{R as Re,d as Ee,o as Se}from"./packem_shared/rest-cache-5unAzdFN.mjs";import{g as fe,E as le,U as xe,p as _e,y as ye}from"./packem_shared/rest-routes-BqldHiaH.mjs";import{decorateResponse as Le,enforceOrigin as ge,handleCorsPreflight as ue,resolveSecurity as Te}from"./packem_shared/decorateResponse-DBIWsRSZ.mjs";import{createShardClient as he}from"./packem_shared/createShardClient-D4mXb3vL.mjs";import{LOG_ARCHIVE_NOT_CONFIGURED as Oe}from"./packem_shared/LOG_ARCHIVE_NOT_CONFIGURED-CDpi4yFD.mjs";import{NOOP_EXECUTION_CONTEXT as ve}from"./packem_shared/NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{composeIdentityResolvers as be,routeIdentityResolvers as Fe}from"./packem_shared/composeIdentityResolvers-DwE0Jbww.mjs";const e="0.0.0";export{ee as DEFAULT_LOG_COLUMNS,re as DEFAULT_LOG_LIMIT,f as DEFAULT_REGISTRY_CACHE_TTL_MS,v as HEALTH_PATH,I as HEALTH_READY_PATH,Oe as LOG_ARCHIVE_NOT_CONFIGURED,G as LOG_ARCHIVE_PATH,y as LunoraError,ve as NOOP_EXECUTION_CONTEXT,l as SHARD_REGISTRY_DO_NAME,e as VERSION,K as analyticsEngineSink,pe as applyJurisdiction,Re as applyRestCache,fe as argsFromQuery,b as buildHealthRoutes,le as buildRestRoutes,Q as combineSinks,be as composeIdentityResolvers,i as composeWorker,X as consoleSink,S as createCrossShardRelationCapabilities,x as createDynamicShardRegistry,g as createKvCursorStore,n as createLunoraHandler,u as createMemoryCursorStore,oe as createPipelineLogReader,ae as createQueryCoordinator,xe as createRestRateLimit,he as createShardClient,se as createStaticShardRegistry,p as createWorker,F as d1Probe,Le as decorateResponse,T as defineExportSink,m as defineRpcEnvelope,P as durableObjectProbe,W as emitLogEvent,Y as emitRpcEvent,ge as enforceOrigin,ue as handleCorsPreflight,w as memoizeIdentity,z as memoizeIdentityPerRequest,ie as mergeStrategyForAggregate,j as otlpSink,J as pipelineLogSink,D as presenceProbe,A as r2Sink,_e as readShardKey,Ee as requestCarriesCredentials,U as resolveLogArchiveFromEnv,c as resolveLunoraOptions,Te as resolveSecurity,me as resolveShard,Se as restCacheHeaders,ye as restSurfaceFromRegistry,Fe as routeIdentityResolvers,h as runExportTap,k as sanitizeChange,B as sentrySink,t as toAirbyteMessages,C as toErrorResponse,a as toFivetranResponse,O as webhookExportSink,Z as webhookSink,R as withFrameworkWorker};
1
+ import{toAirbyteMessages as t,toFivetranResponse as a}from"./packem_shared/toAirbyteMessages-DTk8e2f9.mjs";import{composeWorker as i,createLunoraHandler as n,createWorker as p,defineRpcEnvelope as m,resolveLunoraOptions as c,withFrameworkWorker as R}from"./packem_shared/composeWorker-DxXwbTng.mjs";import{createCrossShardRelationCapabilities as S}from"./packem_shared/createCrossShardRelationCapabilities-CQfrCIWR.mjs";import{DEFAULT_REGISTRY_CACHE_TTL_MS as f,SHARD_REGISTRY_DO_NAME as l,createDynamicShardRegistry as x}from"./packem_shared/DEFAULT_REGISTRY_CACHE_TTL_MS-CCDyswsf.mjs";import{LunoraError as y,toErrorResponse as C}from"./packem_shared/LunoraError-ByasbDmd.mjs";import{createKvCursorStore as g,createMemoryCursorStore as u,defineExportSink as T,r2Sink as A,runExportTap as h,sanitizeChange as k,webhookExportSink as O}from"./packem_shared/createKvCursorStore-C24tEuYk.mjs";import{HEALTH_PATH as v,HEALTH_READY_PATH as I,buildHealthRoutes as b,d1Probe as F,durableObjectProbe as P,presenceProbe as D}from"./packem_shared/HEALTH_PATH-BuLCcWNS.mjs";import{LOG_ARCHIVE_PATH as G,resolveLogArchiveFromEnv as U}from"./packem_shared/LOG_ARCHIVE_PATH-CuHKuDCS.mjs";import{memoizeIdentity as w,memoizeIdentityPerRequest as z}from"./packem_shared/memoizeIdentity-CX3xEPYw.mjs";import{e as W,a as Y}from"./packem_shared/observability-DWlkDJJw.mjs";import{analyticsEngineSink as K,combineSinks as Q,consoleSink as X,otlpSink as j,pipelineLogSink as J,sentrySink as B,webhookSink as Z}from"./packem_shared/analyticsEngineSink-iIRy11I9.mjs";import{D as ee,a as re,c as oe}from"./packem_shared/pipeline-log-reader-FF1V32O2.mjs";import{createQueryCoordinator as ae,createStaticShardRegistry as se,mergeStrategyForAggregate as ie}from"./packem_shared/createQueryCoordinator-BkPfcxUG.mjs";import{applyJurisdiction as pe,resolveShard as me}from"./packem_shared/applyJurisdiction-Dsm_m5zW.mjs";import{R as Re,d as Ee,o as Se}from"./packem_shared/rest-cache-5unAzdFN.mjs";import{g as fe,E as le,U as xe,p as _e,y as ye}from"./packem_shared/rest-routes-BqldHiaH.mjs";import{decorateResponse as Le,enforceOrigin as ge,handleCorsPreflight as ue,resolveSecurity as Te}from"./packem_shared/decorateResponse-DBIWsRSZ.mjs";import{createShardClient as he}from"./packem_shared/createShardClient-BYYzDbMc.mjs";import{LOG_ARCHIVE_NOT_CONFIGURED as Oe}from"./packem_shared/LOG_ARCHIVE_NOT_CONFIGURED-CDpi4yFD.mjs";import{NOOP_EXECUTION_CONTEXT as ve}from"./packem_shared/NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{composeIdentityResolvers as be,routeIdentityResolvers as Fe}from"./packem_shared/composeIdentityResolvers-DwE0Jbww.mjs";const e="0.0.0";export{ee as DEFAULT_LOG_COLUMNS,re as DEFAULT_LOG_LIMIT,f as DEFAULT_REGISTRY_CACHE_TTL_MS,v as HEALTH_PATH,I as HEALTH_READY_PATH,Oe as LOG_ARCHIVE_NOT_CONFIGURED,G as LOG_ARCHIVE_PATH,y as LunoraError,ve as NOOP_EXECUTION_CONTEXT,l as SHARD_REGISTRY_DO_NAME,e as VERSION,K as analyticsEngineSink,pe as applyJurisdiction,Re as applyRestCache,fe as argsFromQuery,b as buildHealthRoutes,le as buildRestRoutes,Q as combineSinks,be as composeIdentityResolvers,i as composeWorker,X as consoleSink,S as createCrossShardRelationCapabilities,x as createDynamicShardRegistry,g as createKvCursorStore,n as createLunoraHandler,u as createMemoryCursorStore,oe as createPipelineLogReader,ae as createQueryCoordinator,xe as createRestRateLimit,he as createShardClient,se as createStaticShardRegistry,p as createWorker,F as d1Probe,Le as decorateResponse,T as defineExportSink,m as defineRpcEnvelope,P as durableObjectProbe,W as emitLogEvent,Y as emitRpcEvent,ge as enforceOrigin,ue as handleCorsPreflight,w as memoizeIdentity,z as memoizeIdentityPerRequest,ie as mergeStrategyForAggregate,j as otlpSink,J as pipelineLogSink,D as presenceProbe,A as r2Sink,_e as readShardKey,Ee as requestCarriesCredentials,U as resolveLogArchiveFromEnv,c as resolveLunoraOptions,Te as resolveSecurity,me as resolveShard,Se as restCacheHeaders,ye as restSurfaceFromRegistry,Fe as routeIdentityResolvers,h as runExportTap,k as sanitizeChange,B as sentrySink,t as toAirbyteMessages,C as toErrorResponse,a as toFivetranResponse,O as webhookExportSink,Z as webhookSink,R as withFrameworkWorker};
@@ -1 +1 @@
1
- import{LunoraError as n}from"./LunoraError-ByasbDmd.mjs";import{applyJurisdiction as S,resolveShard as _}from"./applyJurisdiction-8bzZjAPR.mjs";const m="__lunora_shard_registry__",f=3e4,g="https://shard-registry.internal",l=async r=>await r.json(),T=r=>{const w=r.instanceName??m,o=r.cacheTtlMs??f,a=new Map,p=S(r.namespace,r.jurisdiction);let c;const d=()=>(c??=_(p,w),c),h=async(t,e)=>d().fetch(new Request(`${g}${t}`,{body:JSON.stringify(e),headers:{"content-type":"application/json"},method:"POST"})),y=async t=>d().fetch(new Request(`${g}${t}`,{method:"GET"}));return{invalidate(t){t===void 0?a.clear():a.delete(t)},async listShardKeys(t){const e=Date.now(),s=a.get(t);if(s&&s.expiresAt>e)return s.shardKeys;const i=await y(`/list?table=${encodeURIComponent(t)}`);if(!i.ok)throw new n(`shard registry /list returned ${String(i.status)}`);const{shardKeys:u}=await l(i);return o>0&&a.set(t,{expiresAt:e+o,shardKeys:u}),u},async register(t,e){const s=await h("/register",{shardKey:e,table:t});if(!s.ok)throw new n(`shard registry /register returned ${String(s.status)}`);a.delete(t)},async snapshot(){const t=await y("/snapshot");if(!t.ok)throw new n(`shard registry /snapshot returned ${String(t.status)}`);const{tables:e}=await l(t);return e},async unregister(t,e){const s=await h("/unregister",{shardKey:e,table:t});if(!s.ok)throw new n(`shard registry /unregister returned ${String(s.status)}`);a.delete(t)}}};export{f as DEFAULT_REGISTRY_CACHE_TTL_MS,m as SHARD_REGISTRY_DO_NAME,T as createDynamicShardRegistry};
1
+ import{LunoraError as n}from"./LunoraError-ByasbDmd.mjs";import{applyJurisdiction as S,resolveShard as _}from"./applyJurisdiction-Dsm_m5zW.mjs";const m="__lunora_shard_registry__",f=3e4,g="https://shard-registry.internal",l=async r=>await r.json(),T=r=>{const w=r.instanceName??m,o=r.cacheTtlMs??f,a=new Map,p=S(r.namespace,r.jurisdiction);let c;const d=()=>(c??=_(p,w),c),h=async(t,e)=>d().fetch(new Request(`${g}${t}`,{body:JSON.stringify(e),headers:{"content-type":"application/json"},method:"POST"})),y=async t=>d().fetch(new Request(`${g}${t}`,{method:"GET"}));return{invalidate(t){t===void 0?a.clear():a.delete(t)},async listShardKeys(t){const e=Date.now(),s=a.get(t);if(s&&s.expiresAt>e)return s.shardKeys;const i=await y(`/list?table=${encodeURIComponent(t)}`);if(!i.ok)throw new n(`shard registry /list returned ${String(i.status)}`);const{shardKeys:u}=await l(i);return o>0&&a.set(t,{expiresAt:e+o,shardKeys:u}),u},async register(t,e){const s=await h("/register",{shardKey:e,table:t});if(!s.ok)throw new n(`shard registry /register returned ${String(s.status)}`);a.delete(t)},async snapshot(){const t=await y("/snapshot");if(!t.ok)throw new n(`shard registry /snapshot returned ${String(t.status)}`);const{tables:e}=await l(t);return e},async unregister(t,e){const s=await h("/unregister",{shardKey:e,table:t});if(!s.ok)throw new n(`shard registry /unregister returned ${String(s.status)}`);a.delete(t)}}};export{f as DEFAULT_REGISTRY_CACHE_TTL_MS,m as SHARD_REGISTRY_DO_NAME,T as createDynamicShardRegistry};
@@ -1 +1 @@
1
- import{LunoraError as k}from"./LunoraError-ByasbDmd.mjs";import{t as H}from"./method-guard-rzvo19pa.mjs";import{resolveShard as R}from"./applyJurisdiction-8bzZjAPR.mjs";const T="/_lunora/health",P="/_lunora/health/ready",_=a=>a==="liveness"?["liveness"]:a==="readiness"?["readiness"]:["liveness","readiness"];class j{#e=new Map;addChecker(e,s,t){this.#e.set(e,{run:s,types:t.type})}async getReport(e){const s=[...this.#e].filter(([,r])=>e===void 0||r.types.includes(e)),t=await Promise.all(s.map(async([r,o])=>[r,await o.run()]));return{healthy:t.every(([,r])=>r.health.healthy),report:Object.fromEntries(t)}}}const N=a=>{const e=new j,s=new Set;for(const t of a)t.critical&&s.add(t.name),e.addChecker(t.name,async()=>{let r;try{r=await t.check()}catch(o){r={healthy:!1,message:o instanceof Error?o.message:"probe failed"}}return{health:{healthy:r.healthy,...r.message===void 0?{}:{message:r.message}}}},{type:_(t.kind)});return{criticalNames:s,registry:e}},S=(a,e)=>{const s=a.includes(":")?a.slice(0,a.indexOf(":")):"probe",t=(e.get(s)??0)+1;return e.set(s,t),t===1?s:`${s}#${String(t)}`},C=(a,e)=>a?"unhealthy":e?"degraded":"healthy",O=(a,e,s,t,r)=>{const o=[];let d=!1,u=!1;const m=new Map;for(const[h,c]of Object.entries(a)){const n=e.has(h),i=c.health.healthy;u=u||!i,d=d||!i&&n;const l=s==="admin"?h:S(h,m);o.push({critical:n,...s==="admin"&&c.health.message!==void 0?{message:c.health.message}:{},name:l,status:i?"up":"down"})}return o.sort((h,c)=>h.name.localeCompare(c.name)),{anyCriticalDown:d,body:{appName:t,appVersion:r,checks:o,status:C(d,u),timestamp:new Date().toISOString()}}},q=a=>{const{appName:e="lunora",appVersion:s="0.0.0",auth:t="public",cacheTtlMs:r,isAdmin:o,resolveProbes:d}=a,u=n=>r!==void 0?r:n==="readiness"?0:t==="public"?5e3:0,m={},h=n=>{if(t==="admin"&&!o(n))throw new k("health endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403})},c=async(n,i,l)=>{const f=H(n,["GET","HEAD"]);if(f)return f;h(n);const y=u(l);if(y>0){const p=m[l];if(p!==void 0&&Date.now()<p.expiresAt)return Response.json(p.body,{headers:{"cache-control":"no-store"},status:p.down?503:200})}const{criticalNames:w,registry:v}=N(d(i)),{healthy:E,report:A}=await v.getReport(l==="readiness"?"readiness":void 0),{anyCriticalDown:D,body:g}=O(A,w,t,e,s),b=l==="readiness"?!E:D;return y>0&&(m[l]={body:g,down:b,expiresAt:Date.now()+y}),Response.json(g,{headers:{"cache-control":"no-store"},status:b?503:200})};return{[T]:(n,i)=>c(n,i,"aggregate"),[P]:(n,i)=>c(n,i,"readiness")}},I=(a,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:a}),$=(a,e)=>({check:async()=>{try{return await e.prepare("SELECT 1").first(),{healthy:!0}}catch{return{healthy:!1,message:"d1 query failed"}}},critical:!0,name:a}),B=(a,e)=>({check:()=>e?{healthy:!0}:{healthy:!1,message:"binding not configured"},critical:!1,name:a});export{T as HEALTH_PATH,P as HEALTH_READY_PATH,q as buildHealthRoutes,$ as d1Probe,I as durableObjectProbe,B as presenceProbe};
1
+ import{LunoraError as k}from"./LunoraError-ByasbDmd.mjs";import{t as H}from"./method-guard-rzvo19pa.mjs";import{resolveShard as R}from"./applyJurisdiction-Dsm_m5zW.mjs";const T="/_lunora/health",P="/_lunora/health/ready",_=a=>a==="liveness"?["liveness"]:a==="readiness"?["readiness"]:["liveness","readiness"];class j{#e=new Map;addChecker(e,s,t){this.#e.set(e,{run:s,types:t.type})}async getReport(e){const s=[...this.#e].filter(([,r])=>e===void 0||r.types.includes(e)),t=await Promise.all(s.map(async([r,o])=>[r,await o.run()]));return{healthy:t.every(([,r])=>r.health.healthy),report:Object.fromEntries(t)}}}const N=a=>{const e=new j,s=new Set;for(const t of a)t.critical&&s.add(t.name),e.addChecker(t.name,async()=>{let r;try{r=await t.check()}catch(o){r={healthy:!1,message:o instanceof Error?o.message:"probe failed"}}return{health:{healthy:r.healthy,...r.message===void 0?{}:{message:r.message}}}},{type:_(t.kind)});return{criticalNames:s,registry:e}},S=(a,e)=>{const s=a.includes(":")?a.slice(0,a.indexOf(":")):"probe",t=(e.get(s)??0)+1;return e.set(s,t),t===1?s:`${s}#${String(t)}`},C=(a,e)=>a?"unhealthy":e?"degraded":"healthy",O=(a,e,s,t,r)=>{const o=[];let d=!1,u=!1;const m=new Map;for(const[h,c]of Object.entries(a)){const n=e.has(h),i=c.health.healthy;u=u||!i,d=d||!i&&n;const l=s==="admin"?h:S(h,m);o.push({critical:n,...s==="admin"&&c.health.message!==void 0?{message:c.health.message}:{},name:l,status:i?"up":"down"})}return o.sort((h,c)=>h.name.localeCompare(c.name)),{anyCriticalDown:d,body:{appName:t,appVersion:r,checks:o,status:C(d,u),timestamp:new Date().toISOString()}}},q=a=>{const{appName:e="lunora",appVersion:s="0.0.0",auth:t="public",cacheTtlMs:r,isAdmin:o,resolveProbes:d}=a,u=n=>r!==void 0?r:n==="readiness"?0:t==="public"?5e3:0,m={},h=n=>{if(t==="admin"&&!o(n))throw new k("health endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403})},c=async(n,i,l)=>{const f=H(n,["GET","HEAD"]);if(f)return f;h(n);const y=u(l);if(y>0){const p=m[l];if(p!==void 0&&Date.now()<p.expiresAt)return Response.json(p.body,{headers:{"cache-control":"no-store"},status:p.down?503:200})}const{criticalNames:w,registry:v}=N(d(i)),{healthy:E,report:A}=await v.getReport(l==="readiness"?"readiness":void 0),{anyCriticalDown:D,body:g}=O(A,w,t,e,s),b=l==="readiness"?!E:D;return y>0&&(m[l]={body:g,down:b,expiresAt:Date.now()+y}),Response.json(g,{headers:{"cache-control":"no-store"},status:b?503:200})};return{[T]:(n,i)=>c(n,i,"aggregate"),[P]:(n,i)=>c(n,i,"readiness")}},I=(a,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:a}),$=(a,e)=>({check:async()=>{try{return await e.prepare("SELECT 1").first(),{healthy:!0}}catch{return{healthy:!1,message:"d1 query failed"}}},critical:!0,name:a}),B=(a,e)=>({check:()=>e?{healthy:!0}:{healthy:!1,message:"binding not configured"},critical:!1,name:a});export{T as HEALTH_PATH,P as HEALTH_READY_PATH,q as buildHealthRoutes,$ as d1Probe,I as durableObjectProbe,B as presenceProbe};
@@ -0,0 +1 @@
1
+ import{resolveShard as u}from"@lunora/platform";const d=new WeakMap,a=o=>typeof o.idFromName=="function",s=o=>{if(!a(o))return o;const e=o,t=d.get(o);if(t!==void 0)return t;const r=typeof e.jurisdiction=="function"?i=>s(e.jurisdiction(i)):void 0,n=typeof e.getByName=="function"?{get:i=>e.get(i),getByName:i=>e.getByName(i),idForName:i=>e.idFromName(i),jurisdiction:r}:{get:i=>e.get(i),idForName:i=>e.idFromName(i),jurisdiction:r};return d.set(o,n),n},m=(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)=>u(s(o),e);export{m as applyJurisdiction,p as resolveShard};
@@ -1,6 +1,6 @@
1
- import{isLunoraError as pr,toErrorBody as fr}from"@lunora/errors";import{d as Rt}from"./evict-oldest-C2XU6HBR.mjs";import{NOOP_EXECUTION_CONTEXT as mr}from"./NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{f as wr,u as gr}from"./identity-header-pdXOyDU4.mjs";import{O as Oe,m as yr,A as br,R as _r,d as Rr,i as Er,s as Sr}from"./otlp-resource-B-ByO9qo.mjs";import{h as ee,f as ye,i as Et,E as Tr,w as St,e as Tt,b as Or}from"./rest-routes-BqldHiaH.mjs";import{LunoraError as i,toErrorResponse as Je}from"./LunoraError-ByasbDmd.mjs";import{runExportTap as Ar}from"./createKvCursorStore-C24tEuYk.mjs";import{t as we,r as L}from"./method-guard-rzvo19pa.mjs";import{buildHealthRoutes as vr,durableObjectProbe as kr,d1Probe as Ir,presenceProbe as Ne}from"./HEALTH_PATH-Cqrg0Dq3.mjs";import{wrapResolverWithContract as Dr}from"./composeIdentityResolvers-DwE0Jbww.mjs";import{composeIdentityResolvers as Bo,routeIdentityResolvers as $o}from"./composeIdentityResolvers-DwE0Jbww.mjs";import{buildLogArchiveAdminRoutes as Pr}from"./LOG_ARCHIVE_PATH-CuHKuDCS.mjs";import{o as Ur,f as Ve,a as ce}from"./observability-DWlkDJJw.mjs";import{resolveShard as Ae,applyJurisdiction as Ye}from"./applyJurisdiction-8bzZjAPR.mjs";import{resolveSecurity as Xe,handleCorsPreflight as Nr,enforceOrigin as qr,decorateResponse as qe,enforceWebSocketOrigin as Ze}from"./decorateResponse-DBIWsRSZ.mjs";const Cr=e=>{const t=e??{};if(typeof t.bucket=="function")return t;const r={...t,bucketName:"default"};return r.bucket=()=>r,r},Ot="__lunoraBranch",xr=e=>typeof e=="object"&&e!==null&&Object.hasOwn(e,Ot),jr=`may not contain the reserved workflow branch-marker key ("${Ot}")`,Ge=(e,t)=>{const r=Math.max(e.length,t.length);let n=e.length^t.length;for(let o=0;o<r;o+=1){const d=o<e.length?e.charCodeAt(o):0,u=o<t.length?t.charCodeAt(o):0;n|=d^u}return n===0},Fe=new TextEncoder,Br=Array.from({length:32},(e,t)=>t);new RegExp(`[${Br.map(e=>String.fromCodePoint(e)).join("")}]`,"u");const $r=e=>{const t=String.fromCodePoint(...e);return btoa(t).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")},Lr=e=>{const t=e.replaceAll("-","+").replaceAll("_","/")+"===".slice((e.length+3)%4),r=atob(t),n=new Uint8Array(r.length);for(let o=0;o<r.length;o+=1)n[o]=r.codePointAt(o)??0;return n},Kr=64,Ce=new Map,At=async e=>{const t=Ce.get(e);if(t)return t;Rt(Ce,Kr);const r=crypto.subtle.importKey("raw",Fe.encode(e),{hash:"SHA-256",name:"HMAC"},!1,["sign","verify"]);return Ce.set(e,r),r},vt=async(e,t)=>{const r=await At(e),n=await crypto.subtle.sign("HMAC",r,Fe.encode(t));return $r(new Uint8Array(n))},Gr=async(e,t,r)=>{const n=await At(e);return crypto.subtle.verify("HMAC",n,r,Fe.encode(t))},Fr="::relay::",Qr=(e,t)=>`${e}${Fr}${String(t)}`,Mr=new Set(["1","enabled","on","true","yes"]),zr=new Set(["0","disabled","false","no","off"]),Wr=(e,t)=>{const r=(e??"").trim().toLowerCase();return Mr.has(r)?!0:zr.has(r)?!1:t},kt="v1",Hr=6e4,Jr=async(e,t={})=>{const r=(t.now??Date.now())+(t.ttlMs??Hr),n=`${kt}.${String(r)}`,o=await vt(e,n);return{expiresAtMs:r,token:`${n}.${o}`}},Vr=async(e,t,r=Date.now())=>{if(e.length===0||t.length===0)return!1;const n=t.split(".");if(n.length!==3)return!1;const[o,d,u]=n;if(o!==kt||u.length===0)return!1;const h=Number(d);if(!Number.isFinite(h)||h<=r)return!1;let w;try{w=Lr(u)}catch{return!1}return Gr(e,`${o}.${d}`,w)},D="/_lunora/admin/auth",Yr={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},U=(e,t)=>{const r=e[t];if(typeof r!="string"||r==="")throw new i(`\`${t}\` is required`,{code:"BAD_REQUEST",status:400});return r},le=(e,t)=>{const r=e(t);if(r===void 0)throw new i(`\`${t}\` query parameter is required`,{code:"BAD_REQUEST",status:400});return r},It=e=>{if(typeof e=="string"||Array.isArray(e)&&e.every(t=>typeof t=="string"))return e},te=(e,t)=>typeof e[t]=="string"?e[t]:void 0,xe=(e,t)=>{const r=e[t];return typeof r=="object"&&r!==null&&!Array.isArray(r)?r:void 0},et=e=>{const t=It(e.role);if(t===void 0||typeof t=="string"&&t.trim()==="")throw new i("`role` is required",{code:"BAD_REQUEST",status:400});return t},tt=e=>{const t=e.permission;if(typeof t!="object"||t===null||Array.isArray(t))throw new i("`permission` object is required",{code:"BAD_REQUEST",status:400});const r={};for(const[n,o]of Object.entries(t))Array.isArray(o)&&o.every(d=>typeof d=="string")&&(r[n]=o);return r},Xr={[`${D}/capabilities`]:{build:()=>({}),http:"GET",method:"capabilities"},[`${D}/users`]:{build:({paging:e,query:t})=>{const r=t("sortDirection");return{...e,filterField:t("filterField"),filterValue:t("filterValue"),search:t("search"),searchField:t("searchField"),sortBy:t("sortBy"),sortDirection:r==="asc"||r==="desc"?r:void 0}},http:"GET",method:"listUsers"},[`${D}/sessions`]:{build:({paging:e,query:t})=>({...e,userId:t("userId")}),http:"GET",method:"listSessions"},[`${D}/accounts`]:{build:({query:e})=>({userId:le(e,"userId")}),http:"GET",method:"listAccounts"},[`${D}/passkeys`]:{build:({query:e})=>({userId:le(e,"userId")}),http:"GET",method:"listPasskeys"},[`${D}/organizations`]:{build:({paging:e})=>({...e}),http:"GET",method:"listOrganizations"},[`${D}/organizations/members`]:{build:({paging:e,query:t})=>({...e,organizationId:le(t,"organizationId")}),http:"GET",method:"listMembers"},[`${D}/organizations/invitations`]:{build:({paging:e,query:t})=>({...e,organizationId:le(t,"organizationId")}),http:"GET",method:"listInvitations"},[`${D}/config`]:{build:()=>({}),http:"GET",method:"config"},[`${D}/organizations/teams`]:{build:({paging:e,query:t})=>({...e,organizationId:le(t,"organizationId")}),http:"GET",method:"listTeams"},[`${D}/organizations/teams/members`]:{build:({paging:e,query:t})=>({...e,teamId:le(t,"teamId")}),http:"GET",method:"listTeamMembers"},[`${D}/organizations/roles`]:{build:({paging:e,query:t})=>({...e,organizationId:le(t,"organizationId")}),http:"GET",method:"listOrgRoles"},[`${D}/users/create`]:{build:({body:e})=>({data:xe(e,"data"),email:U(e,"email"),name:U(e,"name"),password:te(e,"password"),role:It(e.role)}),http:"POST",method:"createUser"},[`${D}/users/update`]:{build:({body:e})=>{const{data:t}=e;if(typeof t!="object"||t===null||Array.isArray(t))throw new i("`data` object is required",{code:"BAD_REQUEST",status:400});return{data:t,userId:U(e,"userId")}},http:"POST",method:"updateUser"},[`${D}/users/role`]:{build:({body:e})=>({role:et(e),userId:U(e,"userId")}),http:"POST",method:"setRole"},[`${D}/users/ban`]:{build:({body:e})=>({expiresInSeconds:typeof e.expiresInSeconds=="number"?e.expiresInSeconds:void 0,reason:te(e,"reason"),userId:U(e,"userId")}),http:"POST",method:"banUser"},[`${D}/users/unban`]:{build:({body:e})=>({userId:U(e,"userId")}),http:"POST",method:"unbanUser"},[`${D}/users/password`]:{build:({body:e})=>({newPassword:U(e,"newPassword"),userId:U(e,"userId")}),http:"POST",method:"setUserPassword",returns:"void"},[`${D}/users/remove`]:{build:({body:e})=>({userId:U(e,"userId")}),http:"POST",method:"removeUser",returns:"void"},[`${D}/users/impersonate`]:{build:({body:e})=>({userId:U(e,"userId")}),http:"POST",method:"impersonateUser"},[`${D}/sessions/revoke`]:{build:({body:e})=>({sessionId:U(e,"sessionId")}),http:"POST",method:"revokeUserSession",returns:"void"},[`${D}/sessions/revoke-all`]:{build:({body:e})=>({userId:U(e,"userId")}),http:"POST",method:"revokeUserSessions",returns:"void"},[`${D}/accounts/unlink`]:{build:({body:e})=>({accountId:U(e,"accountId"),userId:U(e,"userId")}),http:"POST",method:"unlinkAccount",returns:"void"},[`${D}/two-factor/disable`]:{build:({body:e})=>({userId:U(e,"userId")}),http:"POST",method:"disableTwoFactor",returns:"void"},[`${D}/passkeys/delete`]:{build:({body:e})=>({passkeyId:U(e,"passkeyId")}),http:"POST",method:"deletePasskey",returns:"void"},[`${D}/organizations/members/remove`]:{build:({body:e})=>({memberId:U(e,"memberId")}),http:"POST",method:"removeMember",returns:"void"},[`${D}/organizations/invitations/cancel`]:{build:({body:e})=>({invitationId:U(e,"invitationId")}),http:"POST",method:"cancelInvitation",returns:"void"},[`${D}/organizations/create`]:{build:({body:e})=>({logo:te(e,"logo"),metadata:xe(e,"metadata"),name:U(e,"name"),ownerId:te(e,"ownerId"),slug:te(e,"slug")}),http:"POST",method:"createOrganization"},[`${D}/organizations/update`]:{build:({body:e})=>({logo:te(e,"logo"),metadata:xe(e,"metadata"),name:te(e,"name"),organizationId:U(e,"organizationId"),slug:te(e,"slug")}),http:"POST",method:"updateOrganization"},[`${D}/organizations/remove`]:{build:({body:e})=>({organizationId:U(e,"organizationId")}),http:"POST",method:"deleteOrganization",returns:"void"},[`${D}/organizations/members/add`]:{build:({body:e})=>({organizationId:U(e,"organizationId"),role:te(e,"role"),userId:U(e,"userId")}),http:"POST",method:"addMember"},[`${D}/organizations/members/invite`]:{build:({body:e})=>({email:U(e,"email"),inviterId:te(e,"inviterId"),organizationId:U(e,"organizationId"),role:te(e,"role")}),http:"POST",method:"inviteMember"},[`${D}/organizations/members/role`]:{build:({body:e})=>({memberId:U(e,"memberId"),role:et(e)}),http:"POST",method:"updateMemberRole"},[`${D}/organizations/teams/create`]:{build:({body:e})=>({name:U(e,"name"),organizationId:U(e,"organizationId")}),http:"POST",method:"createTeam"},[`${D}/organizations/teams/update`]:{build:({body:e})=>({name:U(e,"name"),teamId:U(e,"teamId")}),http:"POST",method:"updateTeam"},[`${D}/organizations/teams/remove`]:{build:({body:e})=>({teamId:U(e,"teamId")}),http:"POST",method:"removeTeam",returns:"void"},[`${D}/organizations/teams/members/add`]:{build:({body:e})=>({teamId:U(e,"teamId"),userId:U(e,"userId")}),http:"POST",method:"addTeamMember"},[`${D}/organizations/teams/members/remove`]:{build:({body:e})=>({teamMemberId:U(e,"teamMemberId")}),http:"POST",method:"removeTeamMember",returns:"void"},[`${D}/organizations/roles/create`]:{build:({body:e})=>({organizationId:U(e,"organizationId"),permission:tt(e),role:U(e,"role")}),http:"POST",method:"createOrgRole"},[`${D}/organizations/roles/update`]:{build:({body:e})=>({permission:tt(e),roleId:U(e,"roleId")}),http:"POST",method:"updateOrgRole"},[`${D}/organizations/roles/remove`]:{build:({body:e})=>({roleId:U(e,"roleId")}),http:"POST",method:"deleteOrgRole",returns:"void"}},Zr=e=>{const t=async o=>{try{return await o()}catch(d){if(d instanceof i)throw d;const u=d,h=typeof u.code=="string"?u.code:"AUTH_ADMIN_ERROR";throw console.error("[lunora] auth admin operation failed:",d),new i("auth admin operation failed",{code:h,status:Yr[h]??500})}},r=async(o,d)=>{if(e.assertAdmin(o),o.method!==d.http)throw new i(`Auth admin endpoint requires ${d.http}`,{code:"METHOD_NOT_ALLOWED",status:405});const u=e.getAuthAdmin();if(u===void 0)throw new i("auth endpoints require an `authAdmin` on the worker",{code:"AUTH_NOT_CONFIGURED",status:400});const h=u[d.method];if(h===void 0)throw new i(`auth admin does not support \`${d.method}\``,{code:"AUTH_OP_NOT_SUPPORTED",status:400});const w=new URL(o.url),R={body:d.http==="POST"?await e.readJsonBody(o):{},paging:e.parsePaging(o),query:k=>e.queryParameter(w,k)},I=d.build(R),b=await t(()=>h(I));return Response.json(d.returns==="void"?{ok:!0}:b,{headers:{"content-type":"application/json"},status:200})},n={};for(const[o,d]of Object.entries(Xr))n[o]=u=>r(u,d);return n},en="__lunora_admin__:getAuthAuditLog",rt=e=>typeof e=="string"&&e!==""?e:void 0,nt=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0,tn=e=>async(t,r)=>{e.assertAdmin(t);const n=e.getReader();if(n===void 0)throw new i("the auth/security audit endpoint requires an `authAuditReader` on the worker",{code:"AUTH_AUDIT_NOT_CONFIGURED",status:400});const o=rt(r.actorId),d=rt(r.event),u=nt(r.sinceSeq),h=nt(r.limit),w={...o===void 0?{}:{actorId:o},...d===void 0?{}:{event:d},...u===void 0?{}:{sinceSeq:u},...h===void 0?{}:{limit:h}};let R;try{R=await n.read(w)}catch(b){throw b instanceof i?b:(console.error("[lunora] auth audit read failed:",b),new i("auth audit read failed",{code:"AUTH_AUDIT_READ_FAILED",status:500}))}const I={entries:R};return Response.json(I,{headers:{"content-type":"application/json"},status:200})},at=500,rn=(e,t,r)=>{if(typeof e!="object"||e===null||Array.isArray(e))throw new i("each batch call must be an object",{code:"BAD_REQUEST",status:400});const n=e;if(typeof n.functionPath!="string")throw new i("each batch call needs a string `functionPath`",{code:"BAD_REQUEST",status:400});if(n.functionPath.startsWith("__lunora_relation__:")||n.functionPath.startsWith("__lunora_admin__"))throw new i("reserved function path cannot be batched",{code:"FORBIDDEN",status:403});if(n.args!==void 0&&(typeof n.args!="object"||n.args===null||Array.isArray(n.args)))throw new i("each batch call `args` must be an object",{code:"BAD_REQUEST",status:400});return{entry:{args:n.args===void 0?{}:n.args,clientId:typeof n.clientId=="string"?n.clientId:void 0,clientSeq:typeof n.clientSeq=="number"?n.clientSeq:void 0,functionPath:n.functionPath,id:typeof n.id=="number"?n.id:t,mutationId:typeof n.mutationId=="string"?n.mutationId:void 0},shardKey:typeof n.shardKey=="string"?n.shardKey:r}},nn=(e,t)=>{if(e.length>at)throw new i(`RPC batch exceeds the ${String(at)}-call limit`,{code:"BAD_REQUEST",status:400});const r=new Map;for(const[n,o]of e.entries()){const{entry:d,shardKey:u}=rn(o,n,t),h=r.get(u)??[];h.push(d),r.set(u,h)}return r},an=new TextEncoder,on=e=>{const t=JSON.stringify(e),r=an.encode(t);let n="";for(const o of r)n+=String.fromCodePoint(o);return btoa(n).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")},sn=e=>{const t={g:0,s:{},v:1};if(typeof e!="string"||e.length===0)return t;try{const r=atob(e.replaceAll("-","+").replaceAll("_","/")),n=new Uint8Array(r.length);for(let h=0;h<r.length;h+=1)n[h]=r.codePointAt(h)??0;const o=JSON.parse(new TextDecoder().decode(n)),d=o.s&&typeof o.s=="object"?o.s:{},u={};for(const[h,w]of Object.entries(d))typeof w=="number"&&Number.isFinite(w)&&(u[h]=w);return{g:typeof o.g=="number"&&Number.isFinite(o.g)?o.g:0,s:u,v:1}}catch{return t}},cn=e=>{const t=typeof e.table=="string"?e.table:"",r=typeof e.op=="string"?e.op:"",n=r==="delete"||r==="insert"||r==="update"?r:"upsert",o=typeof e.id=="string"?e.id:void 0;return{doc:(e.doc&&typeof e.doc=="object"?e.doc:void 0)??(o===void 0?{}:{_id:o}),op:n,table:t}},ot=(e,t,r)=>{for(const n of t)e.push(cn(n));return r!==void 0&&t.length>=r},dn="/_lunora/admin/export",un="/_lunora/admin/import",ln="/_lunora/admin/sync",hn="/_lunora/admin/connector/sync",pn="/_lunora/admin/apply",fn="/_lunora/admin/export-tap/run",mn=new TextEncoder,wn=async e=>{const t=await ye(e,"Export")??{};if(t.tables===void 0)return{tables:void 0};if(!Array.isArray(t.tables))throw new i("Export `tables` must be a string array",{code:"BAD_REQUEST",status:400});const r=[];for(const n of t.tables){if(typeof n!="string"||n.length===0)throw new i("Export `tables` entries must be non-empty strings",{code:"BAD_REQUEST",status:400});r.push(n)}return{tables:r}},je=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):void 0,gn=e=>{const{applyGlobals:t,exportCursorStore:r,exportSinks:n,knownTables:o,queryCoordinator:d,assertAdmin:u,requireAdminOption:h,resolveForwardContext:w,shardDO:R,streamExportRows:I,streamingImport:b,syncGlobals:k}=e,p=async(A,j)=>{const x=we(A,["POST"]);if(x)return x;const F=h(A,d,{code:"BAD_REQUEST",message:"Export endpoint requires a `queryCoordinator` on the worker"}),P=await wn(A),{headers:Q}=await w(A,j),M=new ReadableStream({async pull(B){const K=X=>{B.enqueue(mn.encode(`${JSON.stringify(X)}
2
- `))};try{await I(F,Q,P.tables,K),B.close()}catch(X){B.error(X)}}});return new Response(M,{headers:{"content-type":"application/x-ndjson"},status:200})},g=async(A,j)=>{const x=we(A,["POST"]);if(x)return x;const F=h(A,d,{code:"BAD_REQUEST",message:"Sync endpoint requires a `queryCoordinator` on the worker"}),P=await ee(A),Q=typeof P.cursors=="object"&&P.cursors!==null?P.cursors:{},M=typeof P.limit=="number"?P.limit:void 0,B=typeof P.globalCursor=="number"?P.globalCursor:0,K=je(P.tables),{headers:X}=await w(A,j),J=K??o(),ne=await F.orchestrateCdcSync(R,{cursors:Q,headers:X,limit:M,tables:J}),he=k?await k({limit:M,sinceSeq:B}):void 0;return Response.json({global:he,shards:ne.shards},{status:200})},E=async(A,j)=>{const x=we(A,["POST"]);if(x)return x;const F=h(A,d,{code:"BAD_REQUEST",message:"Connector sync endpoint requires a `queryCoordinator` on the worker"}),P=await ee(A),Q=sn(P.cursor),M=typeof P.limit=="number"&&P.limit>0?P.limit:void 0,B=je(P.tables),{headers:K}=await w(A,j),X=B??o(),J=await F.orchestrateCdcSync(R,{cursors:Q.s,headers:K,limit:M,tables:X}),ne=[],he={...Q.s};let ae=!1;for(const se of J.shards)ae=ot(ne,se.changes??[],M)||ae,he[se.shardKey]=se.cursor;let pe=Q.g;if(k){const se=await k({limit:M,sinceSeq:Q.g});ae=ot(ne,se.changes,M)||ae,pe=se.cursor}const be=on({g:pe,s:he,v:1}),ve={changes:ne,hasMore:ae,nextCursor:be};return Response.json(ve,{status:200})},_=async(A,j)=>{const x=we(A,["POST"]);if(x)return x;const F=h(A,d,{code:"BAD_REQUEST",message:"Apply endpoint requires a `queryCoordinator` on the worker"}),P=await ee(A),Q=(Array.isArray(P.batches)?P.batches:[]).map(J=>J).filter(J=>J!==null&&typeof J=="object"&&typeof J.shardKey=="string"&&Array.isArray(J.changes)),M=Array.isArray(P.globalChanges)?P.globalChanges:[],{headers:B}=await w(A,j),K=await F.orchestrateApplyCdc(R,{batches:Q,headers:B}),X=M.length>0&&t?await t({changes:M}):0;return Response.json({applied:K.applied+X,failed:K.failed,ok:K.ok},{status:200})},O=async(A,j)=>{const x=we(A,["POST"]);if(x)return x;u(A);const{headers:F}=await w(A,j),P=await b(A,F);return Response.json(P,{headers:{"content-type":"application/json"},status:200})},N=async(A,j)=>{const x=we(A,["POST"]);if(x)return x;const F=h(A,d,{code:"BAD_REQUEST",message:"Export-tap endpoint requires a `queryCoordinator` on the worker"});if(n===void 0||Object.keys(n).length===0||r===void 0)throw new i("Export-tap endpoint requires `exportSinks` + `exportCursorStore` on the worker",{code:"EXPORT_TAP_NOT_CONFIGURED",status:400});const P=await ee(A),Q=typeof P.sink=="string"?P.sink:void 0,M=typeof P.limit=="number"&&P.limit>0?P.limit:void 0,B=je(P.tables);if(Q===void 0)throw new i("Export-tap `sink` must name a configured sink",{code:"BAD_REQUEST",status:400});const K=n[Q];if(K===void 0)throw new i(`Export-tap sink "${Q}" is not configured`,{code:"NOT_FOUND",status:404});const{headers:X}=await w(A,j),J=B??o(),ne=await Ar({coordinator:F,cursorStore:r,headers:X,limit:M,shardDO:R,sink:K,tables:J});return Response.json(ne,{headers:{"content-type":"application/json"},status:200})};return{[pn]:_,[hn]:E,[dn]:p,[fn]:N,[un]:O,[ln]:g}},yn=(e,t)=>{const r=[],n=[];if(t&&t.length>0)for(const o of t)e.resolveTableSharding?.(o)?.mode.kind==="global"?n.push(o):r.push(o);return{globalTables:n,shardLocalTables:r}},bn=async(e,t,r,n,o,d)=>{if(r!==void 0&&n.length===0)return;const u=await e.orchestrateExport(d,{args:{tables:n},headers:t,tables:n});for(const h of u.shards)if(!h.error)for(const w of h.rows??[])o(w)},st=async(e,t,r,n,o,d)=>{const{globalTables:u,shardLocalTables:h}=yn(e,n);await bn(t,r,n,h,o,d);const w=e.exportGlobals;if((n===void 0||u.length>0)&&w)for await(const R of w({tables:u}))o(R)},_n=(e,t)=>{let r;try{r=JSON.parse(e)}catch{return{error:{code:"BAD_ROW",line:t,message:"line is not valid JSON",table:""},ok:!1}}if(!r||typeof r!="object"||Array.isArray(r))return{error:{code:"BAD_ROW",line:t,message:"row must be a JSON object",table:""},ok:!1};const n=r;return typeof n.table!="string"||n.table.length===0?{error:{code:"BAD_ROW",line:t,message:"row is missing `table`",table:""},ok:!1}:!n.doc||typeof n.doc!="object"||Array.isArray(n.doc)?{error:{code:"BAD_ROW",line:t,message:"row is missing or malformed `doc`",table:n.table},ok:!1}:{doc:n.doc,ok:!0,table:n.table}},Rn=(e,t,r,n,o)=>{if(r?.mode.kind==="shardBy"&&typeof r.mode.field=="string"){const d=e[r.mode.field];return d==null?{error:{code:"BAD_ROW",line:o,message:`row missing shard field "${r.mode.field}" for table "${t}"`,table:t},ok:!1}:{ok:!0,shardKey:typeof d=="string"?d:JSON.stringify(d)}}return{ok:!0,shardKey:n}},En=async(e,t,r)=>{if(!e.body)throw new i("Import endpoint requires a request body",{code:"BAD_REQUEST",status:400});const n=[],o=[],d=new Map;let u=0,h=0;const w=e.body.getReader(),R=new TextDecoder;let I="",b=0;const k=p=>{h+=1;const g=p.trim();if(g.length===0)return;u+=1;const E=_n(g,h);if(!E.ok){n.push(E.error);return}const{doc:_,table:O}=E,N=t.resolveTableSharding?.(O);if(N?.mode.kind==="global"){o.push({doc:_,line:h,table:O});return}const A=Rn(_,O,N,r,h);if(!A.ok){n.push(A.error);return}const j=d.get(A.shardKey);j?j.rows.push({doc:_,table:O}):d.set(A.shardKey,{rows:[{doc:_,table:O}],shardKey:A.shardKey,startLine:h})};for(;;){const{done:p,value:g}=await w.read();if(p)break;if(g&&(b+=g.byteLength,b>Et))throw await w.cancel().catch(()=>{}),new i("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});I+=R.decode(g,{stream:!0});let E=I.indexOf(`
1
+ import{isLunoraError as pr,toErrorBody as fr}from"@lunora/errors";import{d as Rt}from"./evict-oldest-C2XU6HBR.mjs";import{NOOP_EXECUTION_CONTEXT as mr}from"./NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{f as wr,u as gr}from"./identity-header-pdXOyDU4.mjs";import{O as Ae,m as yr,A as br,R as _r,d as Rr,i as Er,s as Sr}from"./otlp-resource-B-ByO9qo.mjs";import{h as ee,f as be,i as Et,E as Tr,w as St,e as Tt,b as Or}from"./rest-routes-BqldHiaH.mjs";import{LunoraError as i,toErrorResponse as Je}from"./LunoraError-ByasbDmd.mjs";import{runExportTap as Ar}from"./createKvCursorStore-C24tEuYk.mjs";import{t as we,r as L}from"./method-guard-rzvo19pa.mjs";import{buildHealthRoutes as vr,durableObjectProbe as kr,d1Probe as Ir,presenceProbe as Ne}from"./HEALTH_PATH-BuLCcWNS.mjs";import{wrapResolverWithContract as Dr}from"./composeIdentityResolvers-DwE0Jbww.mjs";import{composeIdentityResolvers as Bo,routeIdentityResolvers as $o}from"./composeIdentityResolvers-DwE0Jbww.mjs";import{buildLogArchiveAdminRoutes as Pr}from"./LOG_ARCHIVE_PATH-CuHKuDCS.mjs";import{o as Ur,f as Ve,a as ce}from"./observability-DWlkDJJw.mjs";import{resolveShard as ge,applyJurisdiction as Ye}from"./applyJurisdiction-Dsm_m5zW.mjs";import{resolveSecurity as Xe,handleCorsPreflight as Nr,enforceOrigin as qr,decorateResponse as qe,enforceWebSocketOrigin as Ze}from"./decorateResponse-DBIWsRSZ.mjs";const Cr=e=>{const t=e??{};if(typeof t.bucket=="function")return t;const r={...t,bucketName:"default"};return r.bucket=()=>r,r},Ot="__lunoraBranch",xr=e=>typeof e=="object"&&e!==null&&Object.hasOwn(e,Ot),jr=`may not contain the reserved workflow branch-marker key ("${Ot}")`,Ge=(e,t)=>{const r=Math.max(e.length,t.length);let n=e.length^t.length;for(let o=0;o<r;o+=1){const d=o<e.length?e.charCodeAt(o):0,u=o<t.length?t.charCodeAt(o):0;n|=d^u}return n===0},Fe=new TextEncoder,Br=Array.from({length:32},(e,t)=>t);new RegExp(`[${Br.map(e=>String.fromCodePoint(e)).join("")}]`,"u");const $r=e=>{const t=String.fromCodePoint(...e);return btoa(t).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")},Lr=e=>{const t=e.replaceAll("-","+").replaceAll("_","/")+"===".slice((e.length+3)%4),r=atob(t),n=new Uint8Array(r.length);for(let o=0;o<r.length;o+=1)n[o]=r.codePointAt(o)??0;return n},Kr=64,Ce=new Map,At=async e=>{const t=Ce.get(e);if(t)return t;Rt(Ce,Kr);const r=crypto.subtle.importKey("raw",Fe.encode(e),{hash:"SHA-256",name:"HMAC"},!1,["sign","verify"]);return Ce.set(e,r),r},vt=async(e,t)=>{const r=await At(e),n=await crypto.subtle.sign("HMAC",r,Fe.encode(t));return $r(new Uint8Array(n))},Gr=async(e,t,r)=>{const n=await At(e);return crypto.subtle.verify("HMAC",n,r,Fe.encode(t))},Fr="::relay::",Qr=(e,t)=>`${e}${Fr}${String(t)}`,Mr=new Set(["1","enabled","on","true","yes"]),zr=new Set(["0","disabled","false","no","off"]),Wr=(e,t)=>{const r=(e??"").trim().toLowerCase();return Mr.has(r)?!0:zr.has(r)?!1:t},kt="v1",Hr=6e4,Jr=async(e,t={})=>{const r=(t.now??Date.now())+(t.ttlMs??Hr),n=`${kt}.${String(r)}`,o=await vt(e,n);return{expiresAtMs:r,token:`${n}.${o}`}},Vr=async(e,t,r=Date.now())=>{if(e.length===0||t.length===0)return!1;const n=t.split(".");if(n.length!==3)return!1;const[o,d,u]=n;if(o!==kt||u.length===0)return!1;const h=Number(d);if(!Number.isFinite(h)||h<=r)return!1;let w;try{w=Lr(u)}catch{return!1}return Gr(e,`${o}.${d}`,w)},D="/_lunora/admin/auth",Yr={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},U=(e,t)=>{const r=e[t];if(typeof r!="string"||r==="")throw new i(`\`${t}\` is required`,{code:"BAD_REQUEST",status:400});return r},le=(e,t)=>{const r=e(t);if(r===void 0)throw new i(`\`${t}\` query parameter is required`,{code:"BAD_REQUEST",status:400});return r},It=e=>{if(typeof e=="string"||Array.isArray(e)&&e.every(t=>typeof t=="string"))return e},te=(e,t)=>typeof e[t]=="string"?e[t]:void 0,xe=(e,t)=>{const r=e[t];return typeof r=="object"&&r!==null&&!Array.isArray(r)?r:void 0},et=e=>{const t=It(e.role);if(t===void 0||typeof t=="string"&&t.trim()==="")throw new i("`role` is required",{code:"BAD_REQUEST",status:400});return t},tt=e=>{const t=e.permission;if(typeof t!="object"||t===null||Array.isArray(t))throw new i("`permission` object is required",{code:"BAD_REQUEST",status:400});const r={};for(const[n,o]of Object.entries(t))Array.isArray(o)&&o.every(d=>typeof d=="string")&&(r[n]=o);return r},Xr={[`${D}/capabilities`]:{build:()=>({}),http:"GET",method:"capabilities"},[`${D}/users`]:{build:({paging:e,query:t})=>{const r=t("sortDirection");return{...e,filterField:t("filterField"),filterValue:t("filterValue"),search:t("search"),searchField:t("searchField"),sortBy:t("sortBy"),sortDirection:r==="asc"||r==="desc"?r:void 0}},http:"GET",method:"listUsers"},[`${D}/sessions`]:{build:({paging:e,query:t})=>({...e,userId:t("userId")}),http:"GET",method:"listSessions"},[`${D}/accounts`]:{build:({query:e})=>({userId:le(e,"userId")}),http:"GET",method:"listAccounts"},[`${D}/passkeys`]:{build:({query:e})=>({userId:le(e,"userId")}),http:"GET",method:"listPasskeys"},[`${D}/organizations`]:{build:({paging:e})=>({...e}),http:"GET",method:"listOrganizations"},[`${D}/organizations/members`]:{build:({paging:e,query:t})=>({...e,organizationId:le(t,"organizationId")}),http:"GET",method:"listMembers"},[`${D}/organizations/invitations`]:{build:({paging:e,query:t})=>({...e,organizationId:le(t,"organizationId")}),http:"GET",method:"listInvitations"},[`${D}/config`]:{build:()=>({}),http:"GET",method:"config"},[`${D}/organizations/teams`]:{build:({paging:e,query:t})=>({...e,organizationId:le(t,"organizationId")}),http:"GET",method:"listTeams"},[`${D}/organizations/teams/members`]:{build:({paging:e,query:t})=>({...e,teamId:le(t,"teamId")}),http:"GET",method:"listTeamMembers"},[`${D}/organizations/roles`]:{build:({paging:e,query:t})=>({...e,organizationId:le(t,"organizationId")}),http:"GET",method:"listOrgRoles"},[`${D}/users/create`]:{build:({body:e})=>({data:xe(e,"data"),email:U(e,"email"),name:U(e,"name"),password:te(e,"password"),role:It(e.role)}),http:"POST",method:"createUser"},[`${D}/users/update`]:{build:({body:e})=>{const{data:t}=e;if(typeof t!="object"||t===null||Array.isArray(t))throw new i("`data` object is required",{code:"BAD_REQUEST",status:400});return{data:t,userId:U(e,"userId")}},http:"POST",method:"updateUser"},[`${D}/users/role`]:{build:({body:e})=>({role:et(e),userId:U(e,"userId")}),http:"POST",method:"setRole"},[`${D}/users/ban`]:{build:({body:e})=>({expiresInSeconds:typeof e.expiresInSeconds=="number"?e.expiresInSeconds:void 0,reason:te(e,"reason"),userId:U(e,"userId")}),http:"POST",method:"banUser"},[`${D}/users/unban`]:{build:({body:e})=>({userId:U(e,"userId")}),http:"POST",method:"unbanUser"},[`${D}/users/password`]:{build:({body:e})=>({newPassword:U(e,"newPassword"),userId:U(e,"userId")}),http:"POST",method:"setUserPassword",returns:"void"},[`${D}/users/remove`]:{build:({body:e})=>({userId:U(e,"userId")}),http:"POST",method:"removeUser",returns:"void"},[`${D}/users/impersonate`]:{build:({body:e})=>({userId:U(e,"userId")}),http:"POST",method:"impersonateUser"},[`${D}/sessions/revoke`]:{build:({body:e})=>({sessionId:U(e,"sessionId")}),http:"POST",method:"revokeUserSession",returns:"void"},[`${D}/sessions/revoke-all`]:{build:({body:e})=>({userId:U(e,"userId")}),http:"POST",method:"revokeUserSessions",returns:"void"},[`${D}/accounts/unlink`]:{build:({body:e})=>({accountId:U(e,"accountId"),userId:U(e,"userId")}),http:"POST",method:"unlinkAccount",returns:"void"},[`${D}/two-factor/disable`]:{build:({body:e})=>({userId:U(e,"userId")}),http:"POST",method:"disableTwoFactor",returns:"void"},[`${D}/passkeys/delete`]:{build:({body:e})=>({passkeyId:U(e,"passkeyId")}),http:"POST",method:"deletePasskey",returns:"void"},[`${D}/organizations/members/remove`]:{build:({body:e})=>({memberId:U(e,"memberId")}),http:"POST",method:"removeMember",returns:"void"},[`${D}/organizations/invitations/cancel`]:{build:({body:e})=>({invitationId:U(e,"invitationId")}),http:"POST",method:"cancelInvitation",returns:"void"},[`${D}/organizations/create`]:{build:({body:e})=>({logo:te(e,"logo"),metadata:xe(e,"metadata"),name:U(e,"name"),ownerId:te(e,"ownerId"),slug:te(e,"slug")}),http:"POST",method:"createOrganization"},[`${D}/organizations/update`]:{build:({body:e})=>({logo:te(e,"logo"),metadata:xe(e,"metadata"),name:te(e,"name"),organizationId:U(e,"organizationId"),slug:te(e,"slug")}),http:"POST",method:"updateOrganization"},[`${D}/organizations/remove`]:{build:({body:e})=>({organizationId:U(e,"organizationId")}),http:"POST",method:"deleteOrganization",returns:"void"},[`${D}/organizations/members/add`]:{build:({body:e})=>({organizationId:U(e,"organizationId"),role:te(e,"role"),userId:U(e,"userId")}),http:"POST",method:"addMember"},[`${D}/organizations/members/invite`]:{build:({body:e})=>({email:U(e,"email"),inviterId:te(e,"inviterId"),organizationId:U(e,"organizationId"),role:te(e,"role")}),http:"POST",method:"inviteMember"},[`${D}/organizations/members/role`]:{build:({body:e})=>({memberId:U(e,"memberId"),role:et(e)}),http:"POST",method:"updateMemberRole"},[`${D}/organizations/teams/create`]:{build:({body:e})=>({name:U(e,"name"),organizationId:U(e,"organizationId")}),http:"POST",method:"createTeam"},[`${D}/organizations/teams/update`]:{build:({body:e})=>({name:U(e,"name"),teamId:U(e,"teamId")}),http:"POST",method:"updateTeam"},[`${D}/organizations/teams/remove`]:{build:({body:e})=>({teamId:U(e,"teamId")}),http:"POST",method:"removeTeam",returns:"void"},[`${D}/organizations/teams/members/add`]:{build:({body:e})=>({teamId:U(e,"teamId"),userId:U(e,"userId")}),http:"POST",method:"addTeamMember"},[`${D}/organizations/teams/members/remove`]:{build:({body:e})=>({teamMemberId:U(e,"teamMemberId")}),http:"POST",method:"removeTeamMember",returns:"void"},[`${D}/organizations/roles/create`]:{build:({body:e})=>({organizationId:U(e,"organizationId"),permission:tt(e),role:U(e,"role")}),http:"POST",method:"createOrgRole"},[`${D}/organizations/roles/update`]:{build:({body:e})=>({permission:tt(e),roleId:U(e,"roleId")}),http:"POST",method:"updateOrgRole"},[`${D}/organizations/roles/remove`]:{build:({body:e})=>({roleId:U(e,"roleId")}),http:"POST",method:"deleteOrgRole",returns:"void"}},Zr=e=>{const t=async o=>{try{return await o()}catch(d){if(d instanceof i)throw d;const u=d,h=typeof u.code=="string"?u.code:"AUTH_ADMIN_ERROR";throw console.error("[lunora] auth admin operation failed:",d),new i("auth admin operation failed",{code:h,status:Yr[h]??500})}},r=async(o,d)=>{if(e.assertAdmin(o),o.method!==d.http)throw new i(`Auth admin endpoint requires ${d.http}`,{code:"METHOD_NOT_ALLOWED",status:405});const u=e.getAuthAdmin();if(u===void 0)throw new i("auth endpoints require an `authAdmin` on the worker",{code:"AUTH_NOT_CONFIGURED",status:400});const h=u[d.method];if(h===void 0)throw new i(`auth admin does not support \`${d.method}\``,{code:"AUTH_OP_NOT_SUPPORTED",status:400});const w=new URL(o.url),R={body:d.http==="POST"?await e.readJsonBody(o):{},paging:e.parsePaging(o),query:k=>e.queryParameter(w,k)},I=d.build(R),b=await t(()=>h(I));return Response.json(d.returns==="void"?{ok:!0}:b,{headers:{"content-type":"application/json"},status:200})},n={};for(const[o,d]of Object.entries(Xr))n[o]=u=>r(u,d);return n},en="__lunora_admin__:getAuthAuditLog",rt=e=>typeof e=="string"&&e!==""?e:void 0,nt=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0,tn=e=>async(t,r)=>{e.assertAdmin(t);const n=e.getReader();if(n===void 0)throw new i("the auth/security audit endpoint requires an `authAuditReader` on the worker",{code:"AUTH_AUDIT_NOT_CONFIGURED",status:400});const o=rt(r.actorId),d=rt(r.event),u=nt(r.sinceSeq),h=nt(r.limit),w={...o===void 0?{}:{actorId:o},...d===void 0?{}:{event:d},...u===void 0?{}:{sinceSeq:u},...h===void 0?{}:{limit:h}};let R;try{R=await n.read(w)}catch(b){throw b instanceof i?b:(console.error("[lunora] auth audit read failed:",b),new i("auth audit read failed",{code:"AUTH_AUDIT_READ_FAILED",status:500}))}const I={entries:R};return Response.json(I,{headers:{"content-type":"application/json"},status:200})},at=500,rn=(e,t,r)=>{if(typeof e!="object"||e===null||Array.isArray(e))throw new i("each batch call must be an object",{code:"BAD_REQUEST",status:400});const n=e;if(typeof n.functionPath!="string")throw new i("each batch call needs a string `functionPath`",{code:"BAD_REQUEST",status:400});if(n.functionPath.startsWith("__lunora_relation__:")||n.functionPath.startsWith("__lunora_admin__"))throw new i("reserved function path cannot be batched",{code:"FORBIDDEN",status:403});if(n.args!==void 0&&(typeof n.args!="object"||n.args===null||Array.isArray(n.args)))throw new i("each batch call `args` must be an object",{code:"BAD_REQUEST",status:400});return{entry:{args:n.args===void 0?{}:n.args,clientId:typeof n.clientId=="string"?n.clientId:void 0,clientSeq:typeof n.clientSeq=="number"?n.clientSeq:void 0,functionPath:n.functionPath,id:typeof n.id=="number"?n.id:t,mutationId:typeof n.mutationId=="string"?n.mutationId:void 0},shardKey:typeof n.shardKey=="string"?n.shardKey:r}},nn=(e,t)=>{if(e.length>at)throw new i(`RPC batch exceeds the ${String(at)}-call limit`,{code:"BAD_REQUEST",status:400});const r=new Map;for(const[n,o]of e.entries()){const{entry:d,shardKey:u}=rn(o,n,t),h=r.get(u)??[];h.push(d),r.set(u,h)}return r},an=new TextEncoder,on=e=>{const t=JSON.stringify(e),r=an.encode(t);let n="";for(const o of r)n+=String.fromCodePoint(o);return btoa(n).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")},sn=e=>{const t={g:0,s:{},v:1};if(typeof e!="string"||e.length===0)return t;try{const r=atob(e.replaceAll("-","+").replaceAll("_","/")),n=new Uint8Array(r.length);for(let h=0;h<r.length;h+=1)n[h]=r.codePointAt(h)??0;const o=JSON.parse(new TextDecoder().decode(n)),d=o.s&&typeof o.s=="object"?o.s:{},u={};for(const[h,w]of Object.entries(d))typeof w=="number"&&Number.isFinite(w)&&(u[h]=w);return{g:typeof o.g=="number"&&Number.isFinite(o.g)?o.g:0,s:u,v:1}}catch{return t}},cn=e=>{const t=typeof e.table=="string"?e.table:"",r=typeof e.op=="string"?e.op:"",n=r==="delete"||r==="insert"||r==="update"?r:"upsert",o=typeof e.id=="string"?e.id:void 0;return{doc:(e.doc&&typeof e.doc=="object"?e.doc:void 0)??(o===void 0?{}:{_id:o}),op:n,table:t}},ot=(e,t,r)=>{for(const n of t)e.push(cn(n));return r!==void 0&&t.length>=r},dn="/_lunora/admin/export",un="/_lunora/admin/import",ln="/_lunora/admin/sync",hn="/_lunora/admin/connector/sync",pn="/_lunora/admin/apply",fn="/_lunora/admin/export-tap/run",mn=new TextEncoder,wn=async e=>{const t=await be(e,"Export")??{};if(t.tables===void 0)return{tables:void 0};if(!Array.isArray(t.tables))throw new i("Export `tables` must be a string array",{code:"BAD_REQUEST",status:400});const r=[];for(const n of t.tables){if(typeof n!="string"||n.length===0)throw new i("Export `tables` entries must be non-empty strings",{code:"BAD_REQUEST",status:400});r.push(n)}return{tables:r}},je=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):void 0,gn=e=>{const{applyGlobals:t,exportCursorStore:r,exportSinks:n,knownTables:o,queryCoordinator:d,assertAdmin:u,requireAdminOption:h,resolveForwardContext:w,shardDO:R,streamExportRows:I,streamingImport:b,syncGlobals:k}=e,p=async(A,j)=>{const x=we(A,["POST"]);if(x)return x;const F=h(A,d,{code:"BAD_REQUEST",message:"Export endpoint requires a `queryCoordinator` on the worker"}),P=await wn(A),{headers:Q}=await w(A,j),M=new ReadableStream({async pull(B){const K=X=>{B.enqueue(mn.encode(`${JSON.stringify(X)}
2
+ `))};try{await I(F,Q,P.tables,K),B.close()}catch(X){B.error(X)}}});return new Response(M,{headers:{"content-type":"application/x-ndjson"},status:200})},g=async(A,j)=>{const x=we(A,["POST"]);if(x)return x;const F=h(A,d,{code:"BAD_REQUEST",message:"Sync endpoint requires a `queryCoordinator` on the worker"}),P=await ee(A),Q=typeof P.cursors=="object"&&P.cursors!==null?P.cursors:{},M=typeof P.limit=="number"?P.limit:void 0,B=typeof P.globalCursor=="number"?P.globalCursor:0,K=je(P.tables),{headers:X}=await w(A,j),J=K??o(),ne=await F.orchestrateCdcSync(R,{cursors:Q,headers:X,limit:M,tables:J}),he=k?await k({limit:M,sinceSeq:B}):void 0;return Response.json({global:he,shards:ne.shards},{status:200})},E=async(A,j)=>{const x=we(A,["POST"]);if(x)return x;const F=h(A,d,{code:"BAD_REQUEST",message:"Connector sync endpoint requires a `queryCoordinator` on the worker"}),P=await ee(A),Q=sn(P.cursor),M=typeof P.limit=="number"&&P.limit>0?P.limit:void 0,B=je(P.tables),{headers:K}=await w(A,j),X=B??o(),J=await F.orchestrateCdcSync(R,{cursors:Q.s,headers:K,limit:M,tables:X}),ne=[],he={...Q.s};let ae=!1;for(const se of J.shards)ae=ot(ne,se.changes??[],M)||ae,he[se.shardKey]=se.cursor;let pe=Q.g;if(k){const se=await k({limit:M,sinceSeq:Q.g});ae=ot(ne,se.changes,M)||ae,pe=se.cursor}const _e=on({g:pe,s:he,v:1}),ve={changes:ne,hasMore:ae,nextCursor:_e};return Response.json(ve,{status:200})},_=async(A,j)=>{const x=we(A,["POST"]);if(x)return x;const F=h(A,d,{code:"BAD_REQUEST",message:"Apply endpoint requires a `queryCoordinator` on the worker"}),P=await ee(A),Q=(Array.isArray(P.batches)?P.batches:[]).map(J=>J).filter(J=>J!==null&&typeof J=="object"&&typeof J.shardKey=="string"&&Array.isArray(J.changes)),M=Array.isArray(P.globalChanges)?P.globalChanges:[],{headers:B}=await w(A,j),K=await F.orchestrateApplyCdc(R,{batches:Q,headers:B}),X=M.length>0&&t?await t({changes:M}):0;return Response.json({applied:K.applied+X,failed:K.failed,ok:K.ok},{status:200})},O=async(A,j)=>{const x=we(A,["POST"]);if(x)return x;u(A);const{headers:F}=await w(A,j),P=await b(A,F);return Response.json(P,{headers:{"content-type":"application/json"},status:200})},N=async(A,j)=>{const x=we(A,["POST"]);if(x)return x;const F=h(A,d,{code:"BAD_REQUEST",message:"Export-tap endpoint requires a `queryCoordinator` on the worker"});if(n===void 0||Object.keys(n).length===0||r===void 0)throw new i("Export-tap endpoint requires `exportSinks` + `exportCursorStore` on the worker",{code:"EXPORT_TAP_NOT_CONFIGURED",status:400});const P=await ee(A),Q=typeof P.sink=="string"?P.sink:void 0,M=typeof P.limit=="number"&&P.limit>0?P.limit:void 0,B=je(P.tables);if(Q===void 0)throw new i("Export-tap `sink` must name a configured sink",{code:"BAD_REQUEST",status:400});const K=n[Q];if(K===void 0)throw new i(`Export-tap sink "${Q}" is not configured`,{code:"NOT_FOUND",status:404});const{headers:X}=await w(A,j),J=B??o(),ne=await Ar({coordinator:F,cursorStore:r,headers:X,limit:M,shardDO:R,sink:K,tables:J});return Response.json(ne,{headers:{"content-type":"application/json"},status:200})};return{[pn]:_,[hn]:E,[dn]:p,[fn]:N,[un]:O,[ln]:g}},yn=(e,t)=>{const r=[],n=[];if(t&&t.length>0)for(const o of t)e.resolveTableSharding?.(o)?.mode.kind==="global"?n.push(o):r.push(o);return{globalTables:n,shardLocalTables:r}},bn=async(e,t,r,n,o,d)=>{if(r!==void 0&&n.length===0)return;const u=await e.orchestrateExport(d,{args:{tables:n},headers:t,tables:n});for(const h of u.shards)if(!h.error)for(const w of h.rows??[])o(w)},st=async(e,t,r,n,o,d)=>{const{globalTables:u,shardLocalTables:h}=yn(e,n);await bn(t,r,n,h,o,d);const w=e.exportGlobals;if((n===void 0||u.length>0)&&w)for await(const R of w({tables:u}))o(R)},_n=(e,t)=>{let r;try{r=JSON.parse(e)}catch{return{error:{code:"BAD_ROW",line:t,message:"line is not valid JSON",table:""},ok:!1}}if(!r||typeof r!="object"||Array.isArray(r))return{error:{code:"BAD_ROW",line:t,message:"row must be a JSON object",table:""},ok:!1};const n=r;return typeof n.table!="string"||n.table.length===0?{error:{code:"BAD_ROW",line:t,message:"row is missing `table`",table:""},ok:!1}:!n.doc||typeof n.doc!="object"||Array.isArray(n.doc)?{error:{code:"BAD_ROW",line:t,message:"row is missing or malformed `doc`",table:n.table},ok:!1}:{doc:n.doc,ok:!0,table:n.table}},Rn=(e,t,r,n,o)=>{if(r?.mode.kind==="shardBy"&&typeof r.mode.field=="string"){const d=e[r.mode.field];return d==null?{error:{code:"BAD_ROW",line:o,message:`row missing shard field "${r.mode.field}" for table "${t}"`,table:t},ok:!1}:{ok:!0,shardKey:typeof d=="string"?d:JSON.stringify(d)}}return{ok:!0,shardKey:n}},En=async(e,t,r)=>{if(!e.body)throw new i("Import endpoint requires a request body",{code:"BAD_REQUEST",status:400});const n=[],o=[],d=new Map;let u=0,h=0;const w=e.body.getReader(),R=new TextDecoder;let I="",b=0;const k=p=>{h+=1;const g=p.trim();if(g.length===0)return;u+=1;const E=_n(g,h);if(!E.ok){n.push(E.error);return}const{doc:_,table:O}=E,N=t.resolveTableSharding?.(O);if(N?.mode.kind==="global"){o.push({doc:_,line:h,table:O});return}const A=Rn(_,O,N,r,h);if(!A.ok){n.push(A.error);return}const j=d.get(A.shardKey);j?j.rows.push({doc:_,table:O}):d.set(A.shardKey,{rows:[{doc:_,table:O}],shardKey:A.shardKey,startLine:h})};for(;;){const{done:p,value:g}=await w.read();if(p)break;if(g&&(b+=g.byteLength,b>Et))throw await w.cancel().catch(()=>{}),new i("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});I+=R.decode(g,{stream:!0});let E=I.indexOf(`
3
3
  `);for(;E!==-1;){const _=I.slice(0,E);I=I.slice(E+1),k(_),E=I.indexOf(`
4
- `)}}return I.length>0&&k(I),{errors:n,globalRows:o,perShard:d,received:u}},it=(e,t)=>{for(const[r,n]of Object.entries(t.inserted))e.inserted[r]=(e.inserted[r]??0)+n;for(const r of t.errors)e.errors.push({...r});e.conflicts+=t.conflicts},Sn=async(e,t,r,n)=>{const o=t.defaultShardKey??"__root__",{errors:d,globalRows:u,perShard:h,received:w}=await En(e,t,o),R={conflicts:0,errors:d,inserted:{}},I=[];if(t.resolveTableSharding===void 0&&h.size>0&&I.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"),h.size>0){const b=t.queryCoordinator;if(!b)throw new i("Import endpoint requires a `queryCoordinator` on the worker",{code:"BAD_REQUEST",status:400});const k=await b.orchestrateImport(n,{batches:[...h.values()],headers:r});it(R,k)}if(u.length>0)if(t.importGlobals){const b=u[0]?.line??1,k=await t.importGlobals({rows:u,startLine:b});it(R,k)}else for(const b of u)R.errors.push({code:"GLOBAL_NOT_CONFIGURED",line:b.line,message:`row targets global table "${b.table}" but no \`importGlobals\` is configured`,table:b.table});return{conflicts:R.conflicts,errors:R.errors,inserted:R.inserted,received:w,...I.length>0?{warnings:I}:{}}},Be=e=>typeof e=="object"&&e!==null?e:{},$e=e=>typeof e.kind=="string"?e.kind:"unknown",Tn=(e,t)=>{let r=Be(t),n=!1;$e(r)==="optional"&&(n=!0,r=Be(r._meta?.inner));const o=$e(r),d=r._meta??{},u={kind:o,name:e,optional:n};if(o==="id"&&typeof d.tableName=="string"&&(u.table=d.tableName),o==="array"){const h=$e(Be(d.inner));h!=="unknown"&&(u.element=h)}return u},On=e=>typeof e!="object"||e===null?[]:Object.entries(e).map(([t,r])=>Tn(t,r)).toSorted((t,r)=>t.name.localeCompare(r.name)),An="/_lunora/admin/functions",vn="/_lunora/admin/cron-jobs",kn="/_lunora/admin/openapi",In="/_lunora/admin/openrpc",Dn="/_lunora/admin/global/tables",Pn="/_lunora/admin/global/table",Un="/_lunora/admin/global/facet",ct=e=>{if(e===void 0||e==="")return;let t;try{t=JSON.parse(e)}catch{return}if(!Array.isArray(t))return;const r=t.flatMap(n=>{if(typeof n!="object"||n===null||typeof n.column!="string")return[];const{column:o,value:d}=n;return[{column:o,value:d}]});return r.length===0?void 0:r},Nn=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:{}}),qn=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"}),Cn=e=>{const{assertAdmin:t,options:r,parsePaging:n,queryParameter:o,requireAdminOption:d}=e,u=p=>{L(p,"GET","Functions");const g=d(p,r.functions,{code:"FUNCTIONS_NOT_CONFIGURED",message:"functions endpoint requires a `functions` registry on the worker"}),E=Object.entries(g).flatMap(([_,O])=>O.visibility==="internal"||O.kind==="stream"?[]:[{args:On(O.args),kind:O.kind,path:_}]).toSorted((_,O)=>_.path.localeCompare(O.path));return Response.json({functions:E},{headers:{"content-type":"application/json"},status:200})},h=p=>{L(p,"GET","Cron-jobs");const g=d(p,r.cronJobs,{code:"CRON_JOBS_NOT_CONFIGURED",message:"cron-jobs endpoint requires a `cronJobs` map on the worker"}),E=Object.entries(g).flatMap(([_,O])=>O.map(N=>({args:N.args,cron:_,functionPath:N.functionPath,name:N.name,shardKey:N.shardKey,workflow:N.workflow}))).toSorted((_,O)=>_.name.localeCompare(O.name));return Response.json({jobs:E},{headers:{"content-type":"application/json"},status:200})},w=p=>(L(p,"GET","OpenAPI"),t(p),Response.json(r.openApiSpec??Nn,{headers:{"content-type":"application/json"},status:200})),R=p=>(L(p,"GET","OpenRPC"),t(p),Response.json(r.openRpcSpec??qn,{headers:{"content-type":"application/json"},status:200})),I=async p=>{L(p,"GET","Global-tables");const g=d(p,r.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"});return Response.json(await g.listTables(),{headers:{"content-type":"application/json"},status:200})},b=async p=>{L(p,"GET","Global-table");const g=d(p,r.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),E=new URL(p.url),_=o(E,"table");if(_===void 0)throw new i("Global-table endpoint requires a `table` query param",{code:"BAD_REQUEST",status:400});const O=await g.readTablePage({...n(p),filters:ct(o(E,"filters")),table:_});return Response.json(O,{headers:{"content-type":"application/json"},status:200})},k=async p=>{L(p,"GET","Global-facet");const g=d(p,r.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),E=new URL(p.url),_=o(E,"table"),O=o(E,"column");if(_===void 0||O===void 0)throw new i("Global-facet endpoint requires `table` and `column` query params",{code:"BAD_REQUEST",status:400});const N=o(E,"limit"),A=N===void 0?void 0:Number(N),j=await g.facetColumn({column:O,filters:ct(o(E,"filters")),limit:A!==void 0&&Number.isFinite(A)?A:void 0,table:_});return Response.json(j,{headers:{"content-type":"application/json"},status:200})};return{[vn]:h,[An]:u,[Un]:k,[Pn]:b,[Dn]:I,[kn]:w,[In]:R}},xn="/_lunora/admin/kv/namespaces",jn="/_lunora/admin/kv/keys",Dt="/_lunora/admin/kv/value",Pt=32*1048576,dt=60,Bn=e=>{const{readJsonBody:t,requireAdminOption:r}=e,n=b=>r(b,e.kvIntrospector,{code:"KV_NOT_CONFIGURED",message:"KV endpoints require a `kvIntrospector` on the worker"}),o=b=>Response.json(b,{headers:{"content-type":"application/json"},status:200}),d=(b,k)=>{const p=new URL(b.url),g=p.searchParams.get("namespace")??"",E=p.searchParams.get("key")??"";if(g==="")throw new i(`KV-value ${k} request requires a \`namespace\` query parameter`,{code:"BAD_REQUEST",status:400});if(E==="")throw new i(`KV-value ${k} request requires a \`key\` query parameter`,{code:"BAD_REQUEST",status:400});return{key:E,namespace:g}},u=async(b,k)=>{if(!(await b.listNamespaces()).some(p=>p.binding===k))throw new i(`Unknown KV namespace binding \`${k}\``,{code:"NOT_FOUND",status:404})},h=async b=>(L(b,"GET","KV-namespaces"),o({namespaces:await n(b).listNamespaces()})),w=async b=>{L(b,"GET","KV-keys");const k=n(b),p=new URL(b.url),g=p.searchParams.get("namespace")??"";if(g==="")throw new i("KV-keys request requires a `namespace` query parameter",{code:"BAD_REQUEST",status:400});const E=p.searchParams.get("prefix")??void 0,_=p.searchParams.get("cursor")??void 0,O=p.searchParams.get("limit"),N=O===null?void 0:Number.parseInt(O,10);if(N!==void 0&&(!Number.isInteger(N)||N<1))throw new i("KV-keys `limit` must be a positive integer",{code:"BAD_REQUEST",status:400});const A=N===void 0?void 0:Math.min(N,1e3);return await u(k,g),o(await k.listKeys({cursor:_,limit:A,namespace:g,prefix:E}))},R={DELETE:async b=>{const k=n(b),p=d(b,"DELETE");return await u(k,p.namespace),await k.deleteKey(p),o({deleted:!0})},GET:async b=>{const k=n(b),p=d(b,"GET");return await u(k,p.namespace),o(await k.getValue(p))},PUT:async b=>{const k=n(b),p=await t(b,Pt);if(typeof p.namespace!="string"||p.namespace==="")throw new i("KV-value PUT request requires a `namespace` string",{code:"BAD_REQUEST",status:400});if(typeof p.key!="string"||p.key==="")throw new i("KV-value PUT request requires a `key` string",{code:"BAD_REQUEST",status:400});if(typeof p.value!="string")throw new i("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<dt))throw new i("KV-value PUT `expirationTtl` must be an integer ≥ 60",{code:"BAD_REQUEST",status:400});const g=Math.floor(Date.now()/1e3)+dt;if(p.expiration!==void 0&&(typeof p.expiration!="number"||!Number.isInteger(p.expiration)||p.expiration<g))throw new i("KV-value PUT `expiration` must be a Unix-seconds timestamp at least 60 seconds in the future",{code:"BAD_REQUEST",status:400});return await u(k,p.namespace),await k.putValue({expiration:p.expiration,expirationTtl:p.expirationTtl,key:p.key,metadata:p.metadata,namespace:p.namespace,value:p.value}),o({ok:!0})}},I=b=>{const k=R[b.method];if(!k)throw new i("KV-value endpoint requires GET, PUT, or DELETE",{code:"METHOD_NOT_ALLOWED",status:405});return k(b)};return{[xn]:h,[jn]:w,[Dt]:I}},$n="/_lunora/migrate",Ln="/_lunora/admin/pitr",Kn="/_lunora/admin/rank",Gn="/_lunora/admin/rankpage",Fn="/_lunora/admin/shard-traffic",Qn=new Set(["__lunora_admin__:migrationStatus","__lunora_admin__:runMigration"]),Mn=new Set(["__lunora_admin__:getPitrBookmark","__lunora_admin__:pitrRestore"]),zn=async e=>{const t=await ye(e,"Migration")??{};if(typeof t.table!="string"||t.table.length===0)throw new i("Migration request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof t.functionPath!="string"||!Qn.has(t.functionPath))throw new i("Migration request `functionPath` must be a migration admin op",{code:"BAD_REQUEST",status:400});return{args:t.args??{},functionPath:t.functionPath,table:t.table}},Wn=async e=>{const t=await ye(e,"Rank")??{};if(typeof t.table!="string"||t.table.length===0)throw new i("Rank request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof t.index!="string"||t.index.length===0)throw new i("Rank request is missing `index`",{code:"BAD_REQUEST",status:400});if(typeof t.partitionKey!="string")throw new i("Rank request `partitionKey` must be a string",{code:"BAD_REQUEST",status:400});if(typeof t.rowId!="string"||t.rowId.length===0)throw new i("Rank request is missing `rowId`",{code:"BAD_REQUEST",status:400});if(!Array.isArray(t.sortValues))throw new i("Rank request `sortValues` must be an array",{code:"BAD_REQUEST",status:400});return{index:t.index,partitionKey:t.partitionKey,rowId:t.rowId,sortValues:t.sortValues,table:t.table}},Hn=e=>{if(e!==void 0){if(!Array.isArray(e)||e.some(t=>t!=="asc"&&t!=="desc"))throw new i('Rank page request `directions` must be an array of "asc"|"desc"',{code:"BAD_REQUEST",status:400});return e}},Jn=e=>{if(typeof e.table!="string"||e.table.length===0)throw new i("Rank page request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof e.index!="string"||e.index.length===0)throw new i("Rank page request is missing `index`",{code:"BAD_REQUEST",status:400});if(e.partitionKey!==void 0&&typeof e.partitionKey!="string")throw new i("Rank page request `partitionKey` must be a string",{code:"BAD_REQUEST",status:400});if(e.take!==void 0&&(typeof e.take!="number"||!Number.isFinite(e.take)))throw new i("Rank page request `take` must be a number",{code:"BAD_REQUEST",status:400});if(e.cursor!==void 0&&e.cursor!==null&&typeof e.cursor!="string")throw new i("Rank page request `cursor` must be a string or null",{code:"BAD_REQUEST",status:400})},Vn=async e=>{const t=await ye(e,"Rank page")??{};Jn(t);const r=Hn(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}},Yn=async e=>{const t=await ye(e,"Shard-traffic")??{};if(typeof t.table!="string"||t.table.length===0)throw new i("Shard-traffic request is missing `table`",{code:"BAD_REQUEST",status:400});return{table:t.table}},Xn=async e=>{const t=await ee(e);if(typeof t.functionPath!="string"||!Mn.has(t.functionPath))throw new i("PITR request `functionPath` must be a PITR admin op",{code:"BAD_REQUEST",status:400});if(t.shardKey!==void 0&&typeof t.shardKey!="string")throw new i("PITR `shardKey` must be a string",{code:"BAD_REQUEST",status:400});return{args:t.args??{},functionPath:t.functionPath,shardKey:t.shardKey}},Zn=e=>{const{defaultShard:t,forwardToShard:r,isAdmin:n,queryCoordinator:o,resolveForwardContext:d,shardDO:u}=e,h=(p,g)=>{if(p.method!=="POST")throw new i(`${g} endpoint requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});if(!n(p))throw new i("Admin auth required",{code:"FORBIDDEN",status:403});if(!o)throw new i(`${g} endpoint requires a \`queryCoordinator\` on the worker`,{code:"BAD_REQUEST",status:400});return o},w=async(p,g)=>{const E=h(p,"Migration"),_=await zn(p),{headers:O}=await d(p,g),N=await E.orchestrateMigration(u,{args:_.args,functionPath:_.functionPath,headers:O,table:_.table});return Response.json(N,{headers:{"content-type":"application/json"},status:200})},R=async(p,g)=>{const E=h(p,"Rank"),_=await Wn(p),{headers:O}=await d(p,g),N=await E.orchestrateRank(u,{headers:O,index:_.index,partitionKey:_.partitionKey,rowId:_.rowId,sortValues:_.sortValues,table:_.table});return Response.json(N,{headers:{"content-type":"application/json"},status:200})},I=async(p,g)=>{const E=h(p,"Rank page"),_=await Vn(p),{headers:O}=await d(p,g),N=await E.orchestrateRankPage(u,{..._,headers:O});return Response.json(N,{headers:{"content-type":"application/json"},status:200})},b=async(p,g)=>{const E=h(p,"Shard-traffic"),_=await Yn(p),{headers:O}=await d(p,g),N=await E.orchestrateShardTraffic(u,{headers:O,table:_.table});return Response.json(N,{headers:{"content-type":"application/json"},status:200})},k=async(p,g)=>{if(L(p,"POST","PITR"),!n(p))throw new i("admin PITR endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403});const E=await Xn(p),{headers:_}=await d(p,g),O=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:E.args,functionPath:E.functionPath}),headers:_,method:"POST"});return r(u,E.shardKey??t,O)};return{[$n]:w,[Ln]:k,[Kn]:R,[Gn]:I,[Fn]:b}},ea=1,ta=0,ra=32,na=512,aa=/^[a-z][\d_a-z*/-]{0,255}(?:@[a-z][\d_a-z*/-]{0,13})?=[\u0020-\u002B\u002D-\u003C\u003E-\u007E]{1,256}$/,oa=e=>{if(e==null)return;const t=e.trim();if(t.length===0||t.length>na)return;const r=t.split(",");if(!(r.length>ra)){for(const n of r)if(!aa.test(n.trim()))return;return t}},sa=e=>{const t=br(e.headers.get("traceparent"));if(t===void 0)return;const r=oa(e.headers.get("tracestate"));return{parentSpanId:t.parentSpanId,sampled:t.sampled,traceId:t.traceId,...r===void 0?{}:{traceState:r}}},ia=(e,t={})=>{const r=sa(e),n=t.trustInbound===!0?r:void 0,o=Oe(8),d=n?.traceId??Oe(16),u=Ur(t.sampling,n===void 0?o:d),h=u.isTraced&&(n===void 0||n.sampled);return{decision:u,ignoredUpstream:r!==void 0&&n===void 0,trace:{sampled:h,spanId:o,traceFlags:h?ea:ta,traceId:d,...n?.parentSpanId===void 0?{}:{parentSpanId:n.parentSpanId},...n?.traceState===void 0?{}:{traceState:n.traceState}}}},ca=(e,t)=>{t.traceparent=yr(e.traceId,e.spanId,e.sampled),e.traceState!==void 0&&(t.tracestate=e.traceState)},da=(e,t)=>{let r;return()=>{if(r===void 0){const n=Sr(e),o=t===void 0?void 0:t.cf;r=_r(Er(n),Rr(n,o))}return r}},ua="/_lunora/admin/scheduled",la="/_lunora/admin/scheduled/status",ha="/_lunora/admin/scheduled/ws",pa="/_lunora/admin/scheduled/cancel",fa="/_lunora/admin/scheduled/dead",ma="/_lunora/admin/scheduled/dead/retry",wa="/_lunora/admin/scheduled/dead/cancel",ga=e=>{const{checkWsAdmin:t,requireSchedulerNamespace:r,resolveSchedulerStub:n,schedulerInstanceName:o}=e,d=(w,R)=>I=>{if(I.method!=="GET")throw new i(`${R} endpoint requires GET`,{code:"METHOD_NOT_ALLOWED",status:405});return n(I).fetch(new Request(`https://scheduler.internal${w}`,{method:"GET"}))},u=(w,R,I=R)=>async b=>{if(b.method!=="POST")throw new i(`${I} requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});const k=n(b),p=await b.json().catch(()=>{});if(typeof p?.id!="string"||p.id==="")throw new i(`${R} requires a string \`id\``,{code:"BAD_REQUEST",status:400});return k.fetch(new Request(`https://scheduler.internal${w}`,{body:JSON.stringify({id:p.id}),headers:{"content-type":"application/json"},method:"POST"}))},h=async w=>{if(w.headers.get("Upgrade")!=="websocket")throw new i("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});if(!await t(w))throw new i("admin authorization required",{code:"ADMIN_FORBIDDEN",status:403});const R=r();return Ae(R,o).fetch(new Request("https://scheduler.internal/ws",{headers:{Upgrade:"websocket"}}))};return{[pa]:u("/cancel","Scheduled-cancel","Scheduled-cancel endpoint"),[wa]:u("/dead/cancel","Scheduled dead-letter action"),[fa]:d("/dead","Scheduled dead-letter"),[ma]:u("/dead/retry","Scheduled dead-letter action"),[ua]:d("/list","Scheduled-list"),[la]:d("/status","Scheduler-status"),[ha]:h}},Ut="/_lunora/admin/storage",ya="/_lunora/admin/storage/url",ba="/_lunora/admin/storage/buckets",_a=10080*60,Nt=32*1048576,Ra=new Set(["GET","PUT"]),Ea=e=>{const t=new Uint8Array(e);let r="";for(const n of t)r+=n.toString(16).padStart(2,"0");return r},Sa=e=>{const{assertAdmin:t,parsePaging:r,queryParameter:n,readBodyBytes:o,requireAdminOption:d,storage:u}=e,h=g=>{const E=n(g,"key");if(E===void 0)throw new i("Storage endpoint requires a `key` query parameter",{code:"BAD_REQUEST",status:400});return E},w=async g=>{const E=d(g,u.storageList,{code:"STORAGE_NOT_CONFIGURED",message:"storage endpoint requires a `storageList` function on the worker"}),_=new URL(g.url),O=await E(n(_,"prefix"),{bucket:n(_,"bucket"),cursor:n(_,"cursor"),...r(g)});return Response.json(O,{headers:{"content-type":"application/json"},status:200})},R=g=>(L(g,"GET","Storage-buckets"),t(g),Response.json({buckets:u.storageBuckets??[]},{headers:{"content-type":"application/json"},status:200})),I=async g=>{const E=d(g,u.storageDelete,{code:"STORAGE_DELETE_NOT_CONFIGURED",message:"storage delete requires a `storageDelete` function on the worker"}),_=new URL(g.url),O=h(_);return await E(O,{bucket:n(_,"bucket")}),Response.json({deleted:!0,key:O},{headers:{"content-type":"application/json"},status:200})},b=async g=>{const E=d(g,u.storageUpload,{code:"STORAGE_UPLOAD_NOT_CONFIGURED",message:"storage upload requires a `storageUpload` function on the worker"}),_=new URL(g.url),O=h(_),N=await o(g,Nt),A=g.headers.get("content-type"),j=A===null||A===""?void 0:A,x=n(_,"expectedSha256"),F=n(_,"expectedSize");let P;if(x!==void 0||F!==void 0){const M=await crypto.subtle.digest("SHA-256",N);P=Ea(M);const B=F!==void 0&&N.byteLength!==Number(F),K=x!==void 0&&P!==x.toLowerCase();if(B||K)throw new i("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 Q=await E(O,N,{bucket:n(_,"bucket"),contentType:j,sha256:P});return Response.json(P===void 0?Q:{...Q,sha256:P},{headers:{"content-type":"application/json"},status:200})},k=async g=>{switch(g.method){case"DELETE":return I(g);case"GET":return w(g);case"POST":case"PUT":return b(g);default:throw new i("Storage endpoint requires GET, PUT, POST, or DELETE",{code:"METHOD_NOT_ALLOWED",status:405})}},p=async g=>{L(g,"GET","Storage URL");const E=d(g,u.storageSignedUrl,{code:"STORAGE_URL_NOT_CONFIGURED",message:"storage URL endpoint requires a `storageSignedUrl` function on the worker"}),_=new URL(g.url),O=h(_),N=Number(n(_,"expiresIn")??""),A=Number.isFinite(N)&&N>0?Math.min(N,_a):void 0,j=n(_,"method");if(j!==void 0&&!Ra.has(j))throw new i("Storage URL `method` must be GET or PUT",{code:"BAD_REQUEST",status:400});const x=j,F=n(_,"contentType"),P=await E(O,{bucket:n(_,"bucket"),contentType:F,expiresInSeconds:A,method:x});return Response.json({key:O,url:P},{headers:{"content-type":"application/json"},status:200})};return{[ba]:R,[Ut]:k,[ya]:p}},Ta=(e,...t)=>{let r=e.cf;for(const n of t){if(typeof r!="object"||r===null)return;r=r[n]}return typeof r=="string"?r:void 0},ut={mtls:e=>Ta(e,"tlsClientAuth","certVerified")==="SUCCESS"},Oa=e=>e===void 0||e===!1?()=>!1:e===!0?()=>!0:typeof e=="function"?e:(Object.hasOwn(ut,e)?ut[e]:void 0)??(()=>!1),Aa=e=>{if(e!==void 0)return()=>{};let t=!1;return()=>{t||(t=!0,console.warn('[lunora] Ignored an inbound `traceparent`, so this request starts a new trace instead of joining the caller\'s. That is the safe default: the header is caller-supplied, and trusting it lets any client choose which trace its spans and logs join. If this worker sits behind a gateway, service mesh, or Cloudflare Access that sets `traceparent` itself, set `trustInboundTraceContext: true` on createWorker() (or `"mtls"` to trust only edge-verified client certificates). Set it to `false` to keep this behaviour and silence this message.'))}},va="/_lunora/admin/vector/indexes",ka="/_lunora/admin/vector/query",Ia=e=>{const{readJsonBody:t,requireAdminOption:r}=e,n=async d=>{L(d,"GET","Vector-indexes");const u=r(d,e.vectorIntrospector,{code:"VECTORS_NOT_CONFIGURED",message:"vector endpoints require a `vectorIntrospector` on the worker"});return Response.json({indexes:await u.listIndexes()},{headers:{"content-type":"application/json"},status:200})},o=async d=>{L(d,"POST","Vector-query");const u=r(d,e.vectorIntrospector,{code:"VECTORS_NOT_CONFIGURED",message:"vector endpoints require a `vectorIntrospector` on the worker"});if(u.queryIndex===void 0)throw new i("vector index querying is not enabled on this worker",{code:"VECTOR_QUERY_UNSUPPORTED",status:400});const h=await t(d);if(typeof h.name!="string"||h.name==="")throw new i("Vector-query request requires a `name` string",{code:"BAD_REQUEST",status:400});if(typeof h.text!="string"||h.text==="")throw new i("Vector-query request requires a `text` string",{code:"BAD_REQUEST",status:400});if(h.topK!==void 0&&(typeof h.topK!="number"||!Number.isInteger(h.topK)||h.topK<1))throw new i("Vector-query `topK` must be a positive integer",{code:"BAD_REQUEST",status:400});const w=await u.queryIndex({name:h.name,text:h.text,topK:h.topK});return Response.json(w,{headers:{"content-type":"application/json"},status:200})};return{[va]:n,[ka]:o}},Da="/_lunora/admin/workflows/instances",Pa="/_lunora/admin/workflows/instance",Ua="/_lunora/admin/workflows/status",Na={complete:!0,errored:!0,paused:!0,queued:!0,running:!0,terminated:!0,unknown:!0,waiting:!0,waitingForPause:!0},qa=e=>e!==null&&Object.hasOwn(Na,e)?e:void 0,lt=(e,t)=>{const r=e.searchParams.get(t);if(r===null)return;const n=Number(r);return Number.isInteger(n)&&n>0?n:void 0},Le=(e,t)=>{const r=e.searchParams.get(t);if(r===null||r==="")throw new i(`Workflows admin endpoint requires a \`${t}\` query parameter`,{code:"BAD_REQUEST",status:400});return r},ht=()=>{throw new i("Workflow inspection is unconfigured. Set CLOUDFLARE_ACCOUNT_ID + CLOUDFLARE_API_TOKEN in your .dev.vars to enable it.",{code:"WORKFLOWS_NOT_CONFIGURED",status:501})},Ca=e=>{const{assertAdmin:t,resolveWorkflowsClient:r}=e,n=async(u,h,w)=>{L(u,"GET","Workflows instances"),t(u);const R=r(h);if(!R)return Response.json({configured:!1,instances:[],page:1,perPage:0,totalCount:0});const I=Le(w,"name"),b=qa(w.searchParams.get("status"));return Response.json(await R.listInstances({page:lt(w,"page"),perPage:lt(w,"perPage"),status:b,workflowName:I}))},o=async(u,h,w)=>{L(u,"GET","Workflows instance"),t(u);const R=r(h);return R?Response.json(await R.getInstance({instanceId:Le(w,"id"),workflowName:Le(w,"name")})):ht()},d=async(u,h)=>{L(u,"POST","Workflows status"),t(u);const w=r(h);if(!w)return ht();const R=await u.json().catch(()=>{});if(typeof R?.name!="string"||R.name===""||typeof R.id!="string"||R.id==="")throw new i("Workflows status action requires string `name` and `id`",{code:"BAD_REQUEST",status:400});const{action:I}=R;if(I!=="pause"&&I!=="resume"&&I!=="terminate")throw new i("Workflows status action must be one of: pause, resume, terminate",{code:"BAD_REQUEST",status:400});return Response.json(await w.setInstanceStatus({action:I,instanceId:R.id,workflowName:R.name}))};return{[Pa]:o,[Da]:n,[Ua]:d}},xa={[Dt]:Pt,[Ut]:Nt},ja=new TextEncoder,pt="/_lunora/rpc",Ba="/_lunora/rpc-batch",$a="/_lunora/ws",Re=(e,t,r)=>({resourceAttributes:da(e,t),...r===void 0?{}:{waitUntil:r}}),ft=e=>e?.waitUntil?{waitUntil:t=>e.waitUntil?.(t)}:{},mt=e=>({spanId:e.spanId,traceFlags:e.traceFlags,traceId:e.traceId,...e.parentSpanId===void 0?{}:{parentSpanId:e.parentSpanId}}),Ke=e=>{const{method:t}=e,r=e.headers.get("user-agent")??void 0;let n;try{n=new URL(e.url)}catch{return{method:t,userAgent:r}}const o=n.port===""?void 0:Number(n.port);return{host:n.hostname,method:t,path:n.pathname,port:Number.isNaN(o)?void 0:o,scheme:n.protocol.replace(":",""),userAgent:r}},wt="/_lunora/voice/",La="/_lunora/scheduler/dispatch",Ka="/_lunora/admin/cron-jobs/run",Ga="/_lunora/admin/ws-token",Fa="/_lunora/admin/",Qa="/_lunora/migrate",Ma="/_lunora/status",za=e=>e.startsWith(Fa)||e===Qa,Wa=e=>{const t=e.headers.get("x-lunora-userid"),r=e.headers.get("x-lunora-identity");if(!(t===null&&r===null))return{...r===null?{}:{identity:r},...t===null?{}:{userId:t}}},Ha="/api/auth",Ja="__lunora_admin__:recordAuthEvent",Va="__lunora_admin__:listPushSubscriptions",Ya=["/sign-in","/sign-up","/callback"],Xa=(e,t)=>{const r=t.endsWith("/")?t.slice(0,-1):t;if(!e.startsWith(`${r}/`))return!1;const n=e.slice(r.length);return Ya.some(o=>n===o||n.startsWith(`${o}/`))},Ee=(e,t,r,n)=>{const o=pr(r),d=o?r.code:"INTERNAL_SERVER_ERROR",u=o?r.status:500,h=r instanceof Error?r.message:String(r);return{durationMs:t,error:{code:d,message:h,status:u},functionPath:e,ok:!1,...n.fanOut?{fanOut:{failed:0,shards:0,table:n.fanOut.table}}:{},...n.shardKey?{shardKey:n.shardKey}:{}}},Za=e=>{const{exp:t,expiresAtMs:r}=e;if(typeof r=="number"&&Number.isFinite(r))return r;if(typeof t=="number"&&Number.isFinite(t))return t*1e3},gt=e=>e.waitUntil?{waitUntil:t=>{e.waitUntil?.(t)}}:void 0,eo=e=>{const t=e?.queue;return typeof t=="string"&&t.length>0?t:"unknown"},de=async(e,t,r)=>{const n={"content-type":"application/json"},o=e.headers.get("authorization"),d=e.headers.get("cookie"),u=e.headers.get("x-d1-bookmark"),h=e.headers.get("x-lunora-mutation-id"),w=e.headers.get("x-lunora-client-id"),R=e.headers.get("x-lunora-client-seq");o&&(n.authorization=o),d&&(n.cookie=d),u&&(n["x-d1-bookmark"]=u),h&&(n["x-lunora-mutation-id"]=h),w&&(n["x-lunora-client-id"]=w),R&&(n["x-lunora-client-seq"]=R);const I=e.headers.get("cf-connecting-ip");if(I&&(n["x-lunora-client-ip"]=I),!r)return{claims:null,headers:n,identity:null,userId:null};const b=await r(e,t);if(!b||typeof b.userId!="string"||b.userId.length===0)return{claims:null,headers:n,identity:null,userId:null};n["x-lunora-userid"]=wr(b.userId);const k=Za(b);k!==void 0&&(n["x-lunora-identity-exp"]=String(k));const{userId:p,...g}=b,E=Object.keys(g).length>0?g:null;return E&&(n["x-lunora-identity"]=gr(E)),{claims:E,headers:n,identity:b,userId:p}},to=new Set(["concat","first","groupBy","max","min","rank","sum","topK"]),ro=e=>{if(e===void 0)return;if(!e||typeof e!="object")throw new i("RPC `fanOut` must be an object",{code:"BAD_REQUEST",status:400});const t=e;if(typeof t.table!="string"||t.table.length===0)throw new i("RPC `fanOut.table` must be a non-empty string",{code:"BAD_REQUEST",status:400});if(!t.merge||typeof t.merge!="object")throw new i("RPC `fanOut.merge` must be an object",{code:"BAD_REQUEST",status:400});const r=t.merge;if(typeof r.kind!="string"||!to.has(r.kind))throw new i("RPC `fanOut.merge.kind` is not a recognized merge strategy",{code:"BAD_REQUEST",status:400});if(r.kind==="topK"){if(typeof r.k!="number"||!Number.isInteger(r.k)||r.k<0)throw new i("RPC `fanOut.merge.k` must be a non-negative integer",{code:"BAD_REQUEST",status:400});if(typeof r.by!="string"||r.by.length===0)throw new i("RPC `fanOut.merge.by` must be a non-empty string",{code:"BAD_REQUEST",status:400})}return t},no=(e,t)=>{e?.LUNORA_DEBUG_RPC&&console.warn(`[lunora:rpc] ${t.fanOut?"fan-out":`shard=${t.shardKey??"(root)"}`} ${t.functionPath}`)},yt=(e,t)=>{const r=t.functions?.[e.functionPath]?.x402;if(r){if(e.fanOut)throw new i("a paid (`.x402`) function cannot be fanned out",{code:"BAD_REQUEST",status:400});if(!t.x402Charge)throw new i(`function "${e.functionPath}" is marked paid (.x402) but no x402Charge gate is configured on the worker`,{code:"MISCONFIGURED",status:500});return r}},ao=async e=>{const t=await St(e);let r;try{r=JSON.parse(t)}catch{throw new i("RPC body must be valid JSON",{code:"BAD_REQUEST",status:400})}if(!r||typeof r!="object"||typeof r.functionPath!="string")throw new i("RPC envelope is missing `functionPath`",{code:"BAD_REQUEST",status:400});const n=r;if(n.args!==void 0&&Tt(n.args,"RPC"),n.shardKey!==void 0&&typeof n.shardKey!="string")throw new i("RPC `shardKey` must be a string",{code:"BAD_REQUEST",status:400});const o=r,d=ro(o.fanOut),u=o.args??{};if(d&&o.functionPath.startsWith("__lunora_relation__:")){const h=u.table;if(typeof h=="string"&&h!==d.table)throw new i("RPC `args.table` must match the authorized `fanOut.table` for a relation fan-out",{code:"BAD_REQUEST",status:400});u.table=d.table}return{args:u,fanOut:d,functionPath:o.functionPath,shardKey:o.shardKey}},oe=async(e,t,r)=>Ae(e,t).fetch(r),Se=new Map,oo=5e3,so=4096,io=async(e,t)=>{const r=Date.now(),n=Se.get(t);if(n!==void 0&&n.expiresMs>r)return n.relayCount;n!==void 0&&Se.delete(t);let o=0;try{const d=await Ae(e,t).fetch(new Request("https://shard.internal/_lunora/route"));if(d.ok){const u=(await d.json()).relayCount;typeof u=="number"&&u>0&&(o=Math.floor(u))}}catch{o=0}return Rt(Se,so),Se.set(t,{expiresMs:r+oo,relayCount:o}),o},co=(e,t)=>{if(!(e===null||typeof e!="object"))return Object.entries(e).find(([,r])=>r===t)?.[0]},Te=(e,t,r)=>new Request("https://shard.internal/rpc",{body:JSON.stringify({args:t,functionPath:e}),headers:r,method:"POST"}),uo=["x-lunora-userid","x-lunora-identity","x-lunora-identity-exp"],bt=(e,t)=>{for(const r of uo){e.delete(r);const n=t[r];n!==void 0&&e.set(r,n)}},lo=async(e,t,r)=>e.length===0||r.length===0?!1:Ge(await vt(e,t),r),_t=(e,t)=>{if(!t||t.length===0)return!1;const r=e.headers.get("authorization");if(!r)return!1;const[n,...o]=r.split(" ");return n?.toLowerCase()!=="bearer"?!1:Ge(t,o.join(" ").trim())},ho=async(e,t,r)=>{if(!t||t.length===0)return!1;const n=new URL(e.url).searchParams.get("token");return n===null?!1:await Vr(t,n)?!0:r?!1:Ge(t,n)},po=(e,t)=>{if(t===null||typeof t!="object"&&typeof t!="function")return;const r=t;if(typeof r.prepare=="function"&&typeof r.batch=="function"&&typeof r.dump=="function")return Ir(`d1:${e}`,t);if(typeof r.list=="function"&&typeof r.head=="function"&&typeof r.createMultipartUpload=="function")return Ne(`r2:${e}`,!0);if(typeof r.send=="function"&&typeof r.sendBatch=="function"&&typeof r.get!="function")return Ne(`queue:${e}`,!0);if(typeof r.connectionString=="string")return Ne(`hyperdrive:${e}`,!0)},qt=e=>{const t=Oa(e.trustInboundTraceContext),r=Aa(e.trustInboundTraceContext),n=e.defaultShardKey??"__root__",o=Dr(e.resolveIdentity,e.identity),d=Ye(e.shardDO,e.jurisdiction),u=e.schedulerDO===void 0?void 0:Ye(e.schedulerDO,e.jurisdiction);let h;const w=()=>e.adminToken??h;let R;const I=()=>e.requireEphemeralWsToken??R??!0,b=a=>{const s=a??{};if(R===void 0&&e.requireEphemeralWsToken===void 0){const c=s.LUNORA_REQUIRE_EPHEMERAL_WS_TOKEN;typeof c=="string"&&c.length>0&&(R=Wr(c,!0))}if(h!==void 0||e.adminToken!==void 0)return;const l=s.LUNORA_ADMIN_TOKEN;typeof l=="string"&&l.length>0&&(h=l)},k=new WeakSet,p=a=>_t(a,w())||k.has(a),g=async(a,s)=>{const l=await de(a,s,e.resolveIdentity);if(k.has(a)&&l.headers.authorization===void 0){const c=w();c!==void 0&&(l.headers.authorization=`Bearer ${c}`)}return l};let E=!1;const _=a=>{if(!e.allowUnauthenticatedShardAccess){const s=a==="fan-out"?"authorizeFanOut":"authorizeShard";throw new i(`${a} access is default-denied: configure \`${s}\` on the worker, or set \`allowUnauthenticatedShardAccess: true\` to explicitly allow unauthenticated ${a} access (relying solely on per-row RLS).`,{code:a==="fan-out"?"FORBIDDEN_FANOUT":"FORBIDDEN_SHARD",status:403})}E||(E=!0,console.warn([`[lunora] SECURITY: serving ${a} access with \`allowUnauthenticatedShardAccess: true\` and no \`authorizeShard\`/\`authorizeFanOut\` — `,"any caller (including unauthenticated ones) can target any shard / fan out across the table. ","This is safe only if every table is protected by per-row RLS. Configure `authorizeShard`/`authorizeFanOut` to gate it."].join("")))},O=async(a,s,l=!0)=>{if(e.authorizeShard){if(!await e.authorizeShard(a,s))throw new i("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else l&&s!==n&&_("shard")},N=Zn({defaultShard:n,forwardToShard:oe,isAdmin:p,queryCoordinator:e.queryCoordinator,resolveForwardContext:g,shardDO:d}),A=async(a,s,l,c,m)=>{await O(null,l,!1);const y={"content-type":"application/json","x-lunora-system":"1"};return m?.userId!==void 0&&m.userId.length>0&&(y["x-lunora-userid"]=m.userId),m?.identity!==void 0&&m.identity.length>0&&(y["x-lunora-identity"]=m.identity),c!==void 0&&c.length>0&&(y["x-lunora-mutation-id"]=c),oe(d,l,Te(a,s,y))},j=async(a,s,l,c)=>{const m=l?.[a];if(!m||typeof m.create!="function")throw new i(`${c} targets workflow binding "${a}", which is not bound on env`,{code:"CRON_JOB_FAILED",status:500});if(xr(s))throw new i(`${c} params ${jr}`,{code:"BAD_REQUEST",status:400});await m.create({params:s})},x=async(a,s)=>{if(a.workflow){await j(a.workflow,a.args??{},s,`cron job "${a.name}"`);return}if(a.functionPath===void 0)throw new i(`cron job "${a.name}" has neither a function target nor a workflow target`,{code:"CRON_JOB_FAILED",status:500});const l=await A(a.functionPath,a.args??{},a.shardKey??n);if(!l.ok)throw new i(`cron job "${a.name}" (${a.functionPath}) failed with shard status ${String(l.status)}`,{code:"CRON_JOB_FAILED",status:500})},F=async(a,s,l,c)=>{const m=e.cronJobs?.[a];if(m)for(const y of m)try{await x(y,s)}catch(v){l.push(c(v))}},P=async(a,s)=>{if(!p(a))throw new i("admin endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403});if(L(a,"POST","cron-jobs run"),!e.cronJobs)throw new i("cron-jobs run endpoint requires a `cronJobs` map on the worker",{code:"CRON_JOBS_NOT_CONFIGURED",status:400});const l=await ee(a),c=typeof l.name=="string"?l.name:"";if(c==="")throw new i("cron-jobs run endpoint requires a job `name`",{code:"BAD_REQUEST",status:400});const m=Object.values(e.cronJobs).flat().find(y=>y.name===c);if(!m)throw new i(`no cron job named "${c}" is registered`,{code:"CRON_JOB_NOT_FOUND",status:404});return await x(m,s),Response.json({name:c,ran:!0},{status:200})},Q=async a=>{const s=typeof a.pool=="string"&&a.pool.length>0?a.pool:void 0;if(!s||!u||typeof a.id!="string")return;const l=typeof a.instanceName=="string"&&a.instanceName.length>0?a.instanceName:"default";try{await u.get(u.idFromName(l)).fetch(new Request("https://scheduler.internal/complete",{body:JSON.stringify({id:a.id,pool:s}),headers:{"content-type":"application/json"},method:"POST"}))}catch{}},M=async(a,s)=>{L(a,"POST","Scheduler dispatch");const l=await St(a),c=s??{},m=typeof c.LUNORA_SCHEDULER_SECRET=="string"?c.LUNORA_SCHEDULER_SECRET:void 0,y=e.adminToken??(typeof c.LUNORA_ADMIN_TOKEN=="string"?c.LUNORA_ADMIN_TOKEN:void 0),v=a.headers.get("x-lunora-scheduler-signature");let f=!1;if(v&&m?f=await lo(m,l,v):y&&(f=_t(a,y)),!f)throw new i("Scheduler dispatch requires a valid signature or admin bearer",{code:"FORBIDDEN",status:403});let S;try{S=JSON.parse(l)}catch{throw new i("Scheduler dispatch body must be valid JSON",{code:"BAD_REQUEST",status:400})}const T=S??{},q=T.args??{};if(typeof T.workflow=="string"&&T.workflow.length>0)return await j(T.workflow,q,s,"scheduled workflow"),Response.json({ok:!0},{status:200});if(typeof T.functionPath!="string"||T.functionPath.length===0)throw new i("Scheduler dispatch is missing `functionPath`",{code:"BAD_REQUEST",status:400});const C=typeof T.shardKey=="string"&&T.shardKey.length>0?T.shardKey:n,$=typeof T.id=="string"&&T.id.length>0?T.id:void 0,V=Wa(a),Z=await A(T.functionPath,q,C,$,V);return await Q(T),Z},B=a=>{if(!p(a))throw new i("admin endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403})},K=(a,s,l)=>{if(B(a),s===void 0)throw new i(l.message,{code:l.code,status:400});return s},X=tn({assertAdmin:B,getReader:()=>e.authAuditReader}),J=async(a,s)=>{B(a);const l=e.notifySubscriptionStore;if(l===void 0)return Response.json({subscriptions:[]},{headers:{"content-type":"application/json"},status:200});const c=s?.kind,m=s?.userId,y=s?.limit,v=c==="fcm"||c==="web-push"?c:void 0,f=typeof m=="string"&&m!==""?m:void 0,S=typeof y=="number"&&Number.isFinite(y)?Math.trunc(y):0,T=S>0?Math.min(S,1e3):1e3,q=(await l.list({kind:v,limit:T,userId:f})).filter(C=>v!==void 0&&C.kind!==v?!1:f===void 0||(C.userId??null)===f).map(({keys:C,token:$,...V})=>V);return Response.json({subscriptions:q},{headers:{"content-type":"application/json"},status:200})},ne=async(a,s)=>{if(!s.fanOut){if(s.functionPath===en)return X(a,s.args??{});if(s.functionPath===Va)return J(a,s.args)}},he=gn({applyGlobals:e.applyGlobals,assertAdmin:B,exportCursorStore:e.exportCursorStore,exportSinks:e.exportSinks,knownTables:()=>[],queryCoordinator:e.queryCoordinator,requireAdminOption:K,resolveForwardContext:g,shardDO:d,streamExportRows:(a,s,l,c)=>st(e,a,s,l,c,d),streamingImport:(a,s)=>Sn(a,e,s,d),syncGlobals:e.syncGlobals}),ae=(a,s)=>{const l=a.searchParams.get(s);return l===null||l===""?void 0:l},pe=a=>{const s=new URL(a.url),l=s.searchParams.get("limit"),c=s.searchParams.get("offset"),m=l===null?void 0:Number.parseInt(l,10),y=c===null?void 0:Number.parseInt(c,10);return{limit:m!==void 0&&Number.isFinite(m)&&m>=0?m:void 0,offset:y!==void 0&&Number.isFinite(y)&&y>=0?y:void 0}},be=()=>{if(u===void 0)throw new i("scheduled endpoints require a `schedulerDO` namespace on the worker",{code:"SCHEDULER_NOT_CONFIGURED",status:400});return u},ve=ga({checkWsAdmin:async a=>p(a)||ho(a,w(),I()),requireSchedulerNamespace:be,resolveSchedulerStub:a=>(B(a),Ae(be(),e.schedulerInstanceName??"default")),schedulerInstanceName:e.schedulerInstanceName??"default"}),se=Ca({assertAdmin:B,resolveWorkflowsClient:e.workflowsClient??(()=>{})}),Ct=Sa({assertAdmin:B,parsePaging:pe,queryParameter:ae,readBodyBytes:Or,requireAdminOption:K,storage:{storageBuckets:e.storageBuckets,storageDelete:e.storageDelete,storageList:e.storageList,storageSignedUrl:e.storageSignedUrl,storageUpload:e.storageUpload}}),xt=Ia({readJsonBody:ee,requireAdminOption:K,vectorIntrospector:e.vectorIntrospector}),jt=Bn({kvIntrospector:e.kvIntrospector,readJsonBody:ee,requireAdminOption:K}),Bt=Pr({logArchive:e.logArchive,readJsonBody:ee,requireAdminOption:K}),$t=Cn({assertAdmin:B,options:{cronJobs:e.cronJobs,functions:e.functions,globalIntrospector:e.globalIntrospector,openApiSpec:e.openApiSpec,openRpcSpec:e.openRpcSpec},parsePaging:pe,queryParameter:ae,requireAdminOption:K}),Lt=a=>{const s=[],l=d??a?.SHARD;if(l!==void 0&&s.push(kr("durable-object:default",l,n)),e.health?.disableBindingProbes!==!0)for(const[c,m]of Object.entries(a??{})){const y=po(c,m);y!==void 0&&s.push(y)}for(const c of e.health?.probes??[])s.push(c);return s},Kt=vr({appName:e.health?.appName,appVersion:e.health?.appVersion,auth:e.health?.auth??"public",cacheTtlMs:e.health?.cacheTtlMs,isAdmin:p,resolveProbes:Lt}),Gt=a=>{const s=e.schedulerInstanceName??"default",l=()=>a.get(a.idFromName(s)),c=async(f,S)=>{const T=await l().fetch(new Request(`https://scheduler.internal${f}`,S));if(!T.ok)throw new i(`ctx.scheduler: SchedulerDO ${f} failed (${String(T.status)}): ${await T.text()}`,{code:"INTERNAL",status:500});return await T.json()},m=async(f,S)=>await c(f,{body:JSON.stringify(S),headers:{"content-type":"application/json"},method:"POST"}),y=f=>{const S=f;if(S==null)throw new i("ctx.scheduler: target is required — pass a reference from the generated `internal` / `workflows` / `agents`",{code:"BAD_REQUEST",status:400});if(typeof S.binding=="string"&&S.binding.length>0)return{workflow:S.binding};if(typeof S.__lunoraRef=="string")return{functionPath:S.__lunoraRef};throw new i("ctx.scheduler: expected a reference from the generated `internal` / `workflows` / `agents` — a bare function-path string is refused here, because an HTTP action can be reached unauthenticated",{code:"BAD_REQUEST",status:400})},v=async(f,S,T={})=>{const{id:q}=await m("/schedule",{args:T,scheduledFor:f,...y(S)});return q};return{cancel:async f=>await m("/cancel",{id:f}),get:async f=>await c(`/get?id=${encodeURIComponent(f)}`,{method:"GET"}),list:async()=>await c("/list",{method:"GET"}),runAfter:async(f,S,T)=>{if(!Number.isFinite(f)||f<0)throw new i("ctx.scheduler.runAfter: `delayMs` must be a non-negative finite number",{code:"BAD_REQUEST",status:400});return await v(Date.now()+f,S,T)},runAt:async(f,S,T)=>{if(!Number.isFinite(f))throw new i("ctx.scheduler.runAt: `timestampMs` must be a finite epoch-millisecond number",{code:"BAD_REQUEST",status:400});return await v(f,S,T)}}},Ft=async(a,s,l)=>{const{claims:c,headers:m,userId:y}=await de(a,s,o),v=async(f,S={})=>{const T=f.__lunoraRef;if(typeof T!="string")throw new i("ctx.run*: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});const q=Te(T,S,{...m,"x-lunora-system":"1"}),C=await oe(d,n,q),$=await C.json();if($.error)throw new i($.error.message??"shard RPC failed",{code:$.error.code??"INTERNAL",status:C.status});return $.result};return{auth:{getIdentity:()=>Promise.resolve(c),userId:y},cache:l.cache,fetch:globalThis.fetch.bind(globalThis),runAction:v,runMutation:v,runQuery:v,...u===void 0?{}:{scheduler:Gt(u)},...e.storage===void 0?{}:{storage:Cr(e.storage(s))}}},Qt=async(a,s,l)=>{if(!e.httpRouter)return;const c=await Ft(a,s,l);try{return await e.httpRouter.fetch(a,{...s,__lunoraCtx:c},l)}catch(m){return console.error("[lunora] httpRouter (SSR) handler threw:",m),new Response("Internal Server Error",{status:500})}},Mt=async(a,s,l)=>{if(a.headers.get("Upgrade")!=="websocket")throw new i("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});const c=Ze(a,ie);if(c)return c;const m=l.searchParams.get("shard")??n,{headers:y,identity:v}=await de(a,s,o);await O(v,m);const f=new Headers(a.headers),S=[...f.keys()];for(const q of S)q.startsWith("x-lunora-")&&f.delete(q);bt(f,y);const T=co(s,e.shardDO);if(T!==void 0){f.set("x-lunora-shard-binding",T);const q=await io(d,m);if(q>0){const C=Qr(m,Math.floor(Math.random()*q));return oe(d,C,new Request(a,{headers:f}))}}return oe(d,m,new Request(a,{headers:f}))},zt=async(a,s,l)=>{const{voiceAgents:c}=e;if(c===void 0)return new Response("Not found",{status:404});if(a.headers.get("Upgrade")!=="websocket")return new Response("Expected a WebSocket upgrade",{headers:{allow:"GET"},status:426});const m=Ze(a,ie);if(m)return m;let y;try{y=decodeURIComponent(l.pathname.slice(wt.length))}catch{return new Response("Unknown voice agent",{status:404})}const v=Object.hasOwn(c,y)?c[y]:void 0;if(v===void 0)return new Response("Unknown voice agent",{status:404});const f=l.searchParams.get("threadKey");if(f===null||f.length===0)return new Response("Missing threadKey",{status:400});const{headers:S,identity:T}=await de(a,s,o);if(e.authorizeShard){if(!await e.authorizeShard(T,f))return new Response("Forbidden",{status:403})}else _("shard");const q=new Headers(a.headers);for(const C of q.keys())C.startsWith("x-lunora-")&&q.delete(C);return bt(q,S),oe(v,f,new Request(a,{headers:q}))},Wt=async(a,s,l)=>{if(e.authorizeFanOut){if(!await e.authorizeFanOut(l,a.table,s))throw new i("Forbidden fan-out",{code:"FORBIDDEN_FANOUT",status:403});return}if(s.startsWith("__lunora_relation__:"))throw new i("reverse cross-backend relation reads (`__lunora_relation__:*`) require `authorizeFanOut` to be configured on the worker",{code:"FORBIDDEN_FANOUT",status:403});if(e.authorizeShard)throw new i("Fan-out requires `authorizeFanOut` to be configured on the worker when `authorizeShard` is set",{code:"FORBIDDEN_FANOUT",status:403});_("fan-out")},_e=async(a,s)=>{if(!(!a.fanOut&&a.functionPath.startsWith("__lunora_admin__:"))){if(a.fanOut){await Wt(a.fanOut,a.functionPath,s);return}await O(s,a.shardKey??n)}},ke=async(a,s,l,c,m,y)=>{const v=Date.now(),{observability:f,sampling:S}=e,T=Ke(a),{decision:q,ignoredUpstream:C,trace:$}=ia(a,{...S===void 0?{}:{sampling:S},trustInbound:t(a)});C&&r();const V={...m,"x-lunora-sample-errors":q.keepErrors?"1":"0"};ca($,V);const Z=Te(s,l,V);try{const G=await oe(d,c,Z);return ce(f,{...T,...mt($),durationMs:Date.now()-v,functionPath:s,ok:G.ok,shardKey:c,...G.ok?{}:{error:{code:"SHARD_ERROR",message:`shard returned ${String(G.status)}`,status:G.status}}},y,void 0,{isTraced:$.sampled,keepErrors:q.keepErrors}),G}catch(G){throw ce(f,{...T,...mt($),...Ee(s,Date.now()-v,G,{shardKey:c})},y,void 0,{isTraced:$.sampled,keepErrors:q.keepErrors}),G}},Ht=a=>{if(a.fanOut&&a.shardKey)throw new i("RPC envelope cannot set both `shardKey` and `fanOut`",{code:"BAD_REQUEST",status:400});if(!a.fanOut&&a.functionPath.startsWith("__lunora_relation__:"))throw new i("`__lunora_relation__:*` is a fan-out-only reserved RPC and cannot be dispatched to a single shard",{code:"FORBIDDEN",status:403});if(a.fanOut&&!e.queryCoordinator)throw new i("RPC envelope set `fanOut` but no `queryCoordinator` is configured on the worker",{code:"BAD_REQUEST",status:400})},Jt=async(a,s,l)=>{L(a,"POST","RPC");const c=await ao(a);no(s,c),Ht(c);const m=await ne(a,c);if(m!==void 0)return m;const{headers:y,identity:v}=await de(a,s,o);await _e(c,v);const f=yt(c,e);{const S=Date.now(),{observability:T}=e,q=Ke(a),C=Re(s,a,l&&(Z=>l.waitUntil?.(Z)));if(c.fanOut){const Z=e.queryCoordinator;if(!Z)throw new i("RPC envelope set `fanOut` but no `queryCoordinator` is configured on the worker",{code:"BAD_REQUEST",status:400});try{const G=await Z.fanOut(d,{args:c.args??{},fanOut:c.fanOut,functionPath:c.functionPath,headers:y});return ce(T,{durationMs:Date.now()-S,fanOut:{failed:G.failed,shards:G.ok+G.failed,table:c.fanOut.table},functionPath:c.functionPath,...q,ok:!0},C),Response.json(G,{headers:{"content-type":"application/json"},status:200})}catch(G){throw ce(T,{...Ee(c.functionPath,Date.now()-S,G,{fanOut:{table:c.fanOut.table}}),...q},C),G}}const $=c.shardKey??n,V=()=>ke(a,c.functionPath,c.args??{},$,y,C);return f&&e.x402Charge?e.x402Charge(a,{functionPath:c.functionPath,price:f.price},V,ft(l)):V()}},Vt=async(a,s,l)=>{L(a,"POST","RPC batch");const c=await ee(a),{calls:m}=c;if(!Array.isArray(m))throw new i("RPC batch `calls` must be an array",{code:"BAD_REQUEST",status:400});const{headers:y,identity:v}=await de(a,s,o),f=nn(m,n);for(const z of f.values())for(const W of z)if(e.functions?.[W.functionPath]?.x402)throw new i(`paid (\`.x402\`) function "${W.functionPath}" cannot be called in a batch; dispatch it individually over ${pt}`,{code:"BAD_REQUEST",status:400});await Promise.all([...f.entries()].flatMap(([z,W])=>W.map(re=>_e({functionPath:re.functionPath,shardKey:z},v))));const{observability:S}=e,T=Re(s,a,l&&(z=>l.waitUntil?.(z))),q=Ke(a),C=[],$=[],V=(z,W,re,ue)=>({body:{error:{code:re,message:ue}},id:z.id,status:W}),Z=(z,W,re,ue,fe)=>{for(const H of z)ce(S,fe(H),T),C.push(V(H,W,re,ue))},G=(z,W,re,ue,fe)=>{for(const H of z){const me=ue.get(H.id)??fe,ge=me<400;ce(S,{durationMs:re,functionPath:H.functionPath,...q,ok:ge,shardKey:W,...ge?{}:{error:{code:"SHARD_ERROR",message:`batched call returned ${String(me)}`,status:me}}},T)}};await Promise.all([...f.entries()].map(async([z,W])=>{const re=new Headers(y);re.set("content-type","application/json");const ue=new Request("https://shard.internal/rpc-batch",{body:JSON.stringify({calls:W}),headers:re,method:"POST"}),fe=Date.now();let H;try{H=await oe(d,z,ue)}catch(Y){const Ue=Date.now()-fe,{body:He}=fr(Y,{fallbackCode:"SHARD_UNAVAILABLE",redactedMessage:"shard unavailable"});Z(W,502,He.code,He.message,hr=>({...Ee(hr.functionPath,Ue,Y,{shardKey:z}),...q}));return}const me=Date.now()-fe,ge=H.headers.get("x-d1-bookmark");ge&&$.push(ge);let De;try{De=await H.json()}catch{const Y=`shard batch returned a non-JSON response (${String(H.status)})`;Z(W,H.status,"SHARD_ERROR",Y,Ue=>({durationMs:me,error:{code:"SHARD_ERROR",message:Y,status:H.status},functionPath:Ue.functionPath,...q,ok:!1,shardKey:z}));return}const Pe=Array.isArray(De.results)?De.results:[],ur=new Map(Pe.map(Y=>[Y.id,Y.status??H.status])),lr=new Set(Pe.map(Y=>Y.id));G(W,z,me,ur,H.status),C.push(...Pe);for(const Y of W)lr.has(Y.id)||C.push(V(Y,H.status,"SHARD_ERROR",`shard batch omitted result for call ${String(Y.id)}`))}));const ze={"content-type":"application/json"},[We]=$;return $.length===1&&We!==void 0&&(ze["x-d1-bookmark"]=We),Response.json({results:C},{headers:ze,status:200})},Yt=async(a,s,l,c={},m={})=>{try{const y=l.__lunoraRef;if(typeof y!="string")throw new i("serverQuery: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});const{headers:v,identity:f}=await de(a,s,o);await _e({functionPath:y,shardKey:m.shardKey},f);const S=m.shardKey??n,T=Re(s,a,m.waitUntil);return await ke(a,y,c,S,v,T)}catch(y){return Je(y)}},Xt=1e3,Zt=async(a,s)=>{const l=e.backupRetain;if(l===void 0||l<=0)return;const c=[];let m;for(let v=0;v<Xt;v+=1){const f=await a.list({cursor:m,prefix:s});for(const S of f.objects)S.key.endsWith(".manifest.json")&&c.push(S.key);if(!f.truncated||f.cursor===void 0)break;m=f.cursor}const y=c.toSorted((v,f)=>f.localeCompare(v)).slice(l);await Promise.all(y.flatMap(v=>{const f=v.slice(0,-14);return[a.delete(v),a.delete(f)]}))},er=async a=>{const s=e.backupStore,l=e.queryCoordinator;if(!s)throw new i("scheduled backup requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});if(!l)throw new i("scheduled backup requires a `queryCoordinator` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});const c=w();if(!c||c.length===0)throw new i("scheduled backup requires an `adminToken` (or `env.LUNORA_ADMIN_TOKEN`) to authenticate the per-shard export gate",{code:"BACKUP_NOT_CONFIGURED",status:500});const m={authorization:`Bearer ${c}`,"content-type":"application/json"},y=e.backupTables;let v=0,f=0;const S=[];await st(e,l,m,y,Z=>{const G=`${JSON.stringify(Z)}
4
+ `)}}return I.length>0&&k(I),{errors:n,globalRows:o,perShard:d,received:u}},it=(e,t)=>{for(const[r,n]of Object.entries(t.inserted))e.inserted[r]=(e.inserted[r]??0)+n;for(const r of t.errors)e.errors.push({...r});e.conflicts+=t.conflicts},Sn=async(e,t,r,n)=>{const o=t.defaultShardKey??"__root__",{errors:d,globalRows:u,perShard:h,received:w}=await En(e,t,o),R={conflicts:0,errors:d,inserted:{}},I=[];if(t.resolveTableSharding===void 0&&h.size>0&&I.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"),h.size>0){const b=t.queryCoordinator;if(!b)throw new i("Import endpoint requires a `queryCoordinator` on the worker",{code:"BAD_REQUEST",status:400});const k=await b.orchestrateImport(n,{batches:[...h.values()],headers:r});it(R,k)}if(u.length>0)if(t.importGlobals){const b=u[0]?.line??1,k=await t.importGlobals({rows:u,startLine:b});it(R,k)}else for(const b of u)R.errors.push({code:"GLOBAL_NOT_CONFIGURED",line:b.line,message:`row targets global table "${b.table}" but no \`importGlobals\` is configured`,table:b.table});return{conflicts:R.conflicts,errors:R.errors,inserted:R.inserted,received:w,...I.length>0?{warnings:I}:{}}},Be=e=>typeof e=="object"&&e!==null?e:{},$e=e=>typeof e.kind=="string"?e.kind:"unknown",Tn=(e,t)=>{let r=Be(t),n=!1;$e(r)==="optional"&&(n=!0,r=Be(r._meta?.inner));const o=$e(r),d=r._meta??{},u={kind:o,name:e,optional:n};if(o==="id"&&typeof d.tableName=="string"&&(u.table=d.tableName),o==="array"){const h=$e(Be(d.inner));h!=="unknown"&&(u.element=h)}return u},On=e=>typeof e!="object"||e===null?[]:Object.entries(e).map(([t,r])=>Tn(t,r)).toSorted((t,r)=>t.name.localeCompare(r.name)),An="/_lunora/admin/functions",vn="/_lunora/admin/cron-jobs",kn="/_lunora/admin/openapi",In="/_lunora/admin/openrpc",Dn="/_lunora/admin/global/tables",Pn="/_lunora/admin/global/table",Un="/_lunora/admin/global/facet",ct=e=>{if(e===void 0||e==="")return;let t;try{t=JSON.parse(e)}catch{return}if(!Array.isArray(t))return;const r=t.flatMap(n=>{if(typeof n!="object"||n===null||typeof n.column!="string")return[];const{column:o,value:d}=n;return[{column:o,value:d}]});return r.length===0?void 0:r},Nn=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:{}}),qn=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"}),Cn=e=>{const{assertAdmin:t,options:r,parsePaging:n,queryParameter:o,requireAdminOption:d}=e,u=p=>{L(p,"GET","Functions");const g=d(p,r.functions,{code:"FUNCTIONS_NOT_CONFIGURED",message:"functions endpoint requires a `functions` registry on the worker"}),E=Object.entries(g).flatMap(([_,O])=>O.visibility==="internal"||O.kind==="stream"?[]:[{args:On(O.args),kind:O.kind,path:_}]).toSorted((_,O)=>_.path.localeCompare(O.path));return Response.json({functions:E},{headers:{"content-type":"application/json"},status:200})},h=p=>{L(p,"GET","Cron-jobs");const g=d(p,r.cronJobs,{code:"CRON_JOBS_NOT_CONFIGURED",message:"cron-jobs endpoint requires a `cronJobs` map on the worker"}),E=Object.entries(g).flatMap(([_,O])=>O.map(N=>({args:N.args,cron:_,functionPath:N.functionPath,name:N.name,shardKey:N.shardKey,workflow:N.workflow}))).toSorted((_,O)=>_.name.localeCompare(O.name));return Response.json({jobs:E},{headers:{"content-type":"application/json"},status:200})},w=p=>(L(p,"GET","OpenAPI"),t(p),Response.json(r.openApiSpec??Nn,{headers:{"content-type":"application/json"},status:200})),R=p=>(L(p,"GET","OpenRPC"),t(p),Response.json(r.openRpcSpec??qn,{headers:{"content-type":"application/json"},status:200})),I=async p=>{L(p,"GET","Global-tables");const g=d(p,r.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"});return Response.json(await g.listTables(),{headers:{"content-type":"application/json"},status:200})},b=async p=>{L(p,"GET","Global-table");const g=d(p,r.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),E=new URL(p.url),_=o(E,"table");if(_===void 0)throw new i("Global-table endpoint requires a `table` query param",{code:"BAD_REQUEST",status:400});const O=await g.readTablePage({...n(p),filters:ct(o(E,"filters")),table:_});return Response.json(O,{headers:{"content-type":"application/json"},status:200})},k=async p=>{L(p,"GET","Global-facet");const g=d(p,r.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),E=new URL(p.url),_=o(E,"table"),O=o(E,"column");if(_===void 0||O===void 0)throw new i("Global-facet endpoint requires `table` and `column` query params",{code:"BAD_REQUEST",status:400});const N=o(E,"limit"),A=N===void 0?void 0:Number(N),j=await g.facetColumn({column:O,filters:ct(o(E,"filters")),limit:A!==void 0&&Number.isFinite(A)?A:void 0,table:_});return Response.json(j,{headers:{"content-type":"application/json"},status:200})};return{[vn]:h,[An]:u,[Un]:k,[Pn]:b,[Dn]:I,[kn]:w,[In]:R}},xn="/_lunora/admin/kv/namespaces",jn="/_lunora/admin/kv/keys",Dt="/_lunora/admin/kv/value",Pt=32*1048576,dt=60,Bn=e=>{const{readJsonBody:t,requireAdminOption:r}=e,n=b=>r(b,e.kvIntrospector,{code:"KV_NOT_CONFIGURED",message:"KV endpoints require a `kvIntrospector` on the worker"}),o=b=>Response.json(b,{headers:{"content-type":"application/json"},status:200}),d=(b,k)=>{const p=new URL(b.url),g=p.searchParams.get("namespace")??"",E=p.searchParams.get("key")??"";if(g==="")throw new i(`KV-value ${k} request requires a \`namespace\` query parameter`,{code:"BAD_REQUEST",status:400});if(E==="")throw new i(`KV-value ${k} request requires a \`key\` query parameter`,{code:"BAD_REQUEST",status:400});return{key:E,namespace:g}},u=async(b,k)=>{if(!(await b.listNamespaces()).some(p=>p.binding===k))throw new i(`Unknown KV namespace binding \`${k}\``,{code:"NOT_FOUND",status:404})},h=async b=>(L(b,"GET","KV-namespaces"),o({namespaces:await n(b).listNamespaces()})),w=async b=>{L(b,"GET","KV-keys");const k=n(b),p=new URL(b.url),g=p.searchParams.get("namespace")??"";if(g==="")throw new i("KV-keys request requires a `namespace` query parameter",{code:"BAD_REQUEST",status:400});const E=p.searchParams.get("prefix")??void 0,_=p.searchParams.get("cursor")??void 0,O=p.searchParams.get("limit"),N=O===null?void 0:Number.parseInt(O,10);if(N!==void 0&&(!Number.isInteger(N)||N<1))throw new i("KV-keys `limit` must be a positive integer",{code:"BAD_REQUEST",status:400});const A=N===void 0?void 0:Math.min(N,1e3);return await u(k,g),o(await k.listKeys({cursor:_,limit:A,namespace:g,prefix:E}))},R={DELETE:async b=>{const k=n(b),p=d(b,"DELETE");return await u(k,p.namespace),await k.deleteKey(p),o({deleted:!0})},GET:async b=>{const k=n(b),p=d(b,"GET");return await u(k,p.namespace),o(await k.getValue(p))},PUT:async b=>{const k=n(b),p=await t(b,Pt);if(typeof p.namespace!="string"||p.namespace==="")throw new i("KV-value PUT request requires a `namespace` string",{code:"BAD_REQUEST",status:400});if(typeof p.key!="string"||p.key==="")throw new i("KV-value PUT request requires a `key` string",{code:"BAD_REQUEST",status:400});if(typeof p.value!="string")throw new i("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<dt))throw new i("KV-value PUT `expirationTtl` must be an integer ≥ 60",{code:"BAD_REQUEST",status:400});const g=Math.floor(Date.now()/1e3)+dt;if(p.expiration!==void 0&&(typeof p.expiration!="number"||!Number.isInteger(p.expiration)||p.expiration<g))throw new i("KV-value PUT `expiration` must be a Unix-seconds timestamp at least 60 seconds in the future",{code:"BAD_REQUEST",status:400});return await u(k,p.namespace),await k.putValue({expiration:p.expiration,expirationTtl:p.expirationTtl,key:p.key,metadata:p.metadata,namespace:p.namespace,value:p.value}),o({ok:!0})}},I=b=>{const k=R[b.method];if(!k)throw new i("KV-value endpoint requires GET, PUT, or DELETE",{code:"METHOD_NOT_ALLOWED",status:405});return k(b)};return{[xn]:h,[jn]:w,[Dt]:I}},$n="/_lunora/migrate",Ln="/_lunora/admin/pitr",Kn="/_lunora/admin/rank",Gn="/_lunora/admin/rankpage",Fn="/_lunora/admin/shard-traffic",Qn=new Set(["__lunora_admin__:migrationStatus","__lunora_admin__:runMigration"]),Mn=new Set(["__lunora_admin__:getPitrBookmark","__lunora_admin__:pitrRestore"]),zn=async e=>{const t=await be(e,"Migration")??{};if(typeof t.table!="string"||t.table.length===0)throw new i("Migration request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof t.functionPath!="string"||!Qn.has(t.functionPath))throw new i("Migration request `functionPath` must be a migration admin op",{code:"BAD_REQUEST",status:400});return{args:t.args??{},functionPath:t.functionPath,table:t.table}},Wn=async e=>{const t=await be(e,"Rank")??{};if(typeof t.table!="string"||t.table.length===0)throw new i("Rank request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof t.index!="string"||t.index.length===0)throw new i("Rank request is missing `index`",{code:"BAD_REQUEST",status:400});if(typeof t.partitionKey!="string")throw new i("Rank request `partitionKey` must be a string",{code:"BAD_REQUEST",status:400});if(typeof t.rowId!="string"||t.rowId.length===0)throw new i("Rank request is missing `rowId`",{code:"BAD_REQUEST",status:400});if(!Array.isArray(t.sortValues))throw new i("Rank request `sortValues` must be an array",{code:"BAD_REQUEST",status:400});return{index:t.index,partitionKey:t.partitionKey,rowId:t.rowId,sortValues:t.sortValues,table:t.table}},Hn=e=>{if(e!==void 0){if(!Array.isArray(e)||e.some(t=>t!=="asc"&&t!=="desc"))throw new i('Rank page request `directions` must be an array of "asc"|"desc"',{code:"BAD_REQUEST",status:400});return e}},Jn=e=>{if(typeof e.table!="string"||e.table.length===0)throw new i("Rank page request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof e.index!="string"||e.index.length===0)throw new i("Rank page request is missing `index`",{code:"BAD_REQUEST",status:400});if(e.partitionKey!==void 0&&typeof e.partitionKey!="string")throw new i("Rank page request `partitionKey` must be a string",{code:"BAD_REQUEST",status:400});if(e.take!==void 0&&(typeof e.take!="number"||!Number.isFinite(e.take)))throw new i("Rank page request `take` must be a number",{code:"BAD_REQUEST",status:400});if(e.cursor!==void 0&&e.cursor!==null&&typeof e.cursor!="string")throw new i("Rank page request `cursor` must be a string or null",{code:"BAD_REQUEST",status:400})},Vn=async e=>{const t=await be(e,"Rank page")??{};Jn(t);const r=Hn(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}},Yn=async e=>{const t=await be(e,"Shard-traffic")??{};if(typeof t.table!="string"||t.table.length===0)throw new i("Shard-traffic request is missing `table`",{code:"BAD_REQUEST",status:400});return{table:t.table}},Xn=async e=>{const t=await ee(e);if(typeof t.functionPath!="string"||!Mn.has(t.functionPath))throw new i("PITR request `functionPath` must be a PITR admin op",{code:"BAD_REQUEST",status:400});if(t.shardKey!==void 0&&typeof t.shardKey!="string")throw new i("PITR `shardKey` must be a string",{code:"BAD_REQUEST",status:400});return{args:t.args??{},functionPath:t.functionPath,shardKey:t.shardKey}},Zn=e=>{const{defaultShard:t,forwardToShard:r,isAdmin:n,queryCoordinator:o,resolveForwardContext:d,shardDO:u}=e,h=(p,g)=>{if(p.method!=="POST")throw new i(`${g} endpoint requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});if(!n(p))throw new i("Admin auth required",{code:"FORBIDDEN",status:403});if(!o)throw new i(`${g} endpoint requires a \`queryCoordinator\` on the worker`,{code:"BAD_REQUEST",status:400});return o},w=async(p,g)=>{const E=h(p,"Migration"),_=await zn(p),{headers:O}=await d(p,g),N=await E.orchestrateMigration(u,{args:_.args,functionPath:_.functionPath,headers:O,table:_.table});return Response.json(N,{headers:{"content-type":"application/json"},status:200})},R=async(p,g)=>{const E=h(p,"Rank"),_=await Wn(p),{headers:O}=await d(p,g),N=await E.orchestrateRank(u,{headers:O,index:_.index,partitionKey:_.partitionKey,rowId:_.rowId,sortValues:_.sortValues,table:_.table});return Response.json(N,{headers:{"content-type":"application/json"},status:200})},I=async(p,g)=>{const E=h(p,"Rank page"),_=await Vn(p),{headers:O}=await d(p,g),N=await E.orchestrateRankPage(u,{..._,headers:O});return Response.json(N,{headers:{"content-type":"application/json"},status:200})},b=async(p,g)=>{const E=h(p,"Shard-traffic"),_=await Yn(p),{headers:O}=await d(p,g),N=await E.orchestrateShardTraffic(u,{headers:O,table:_.table});return Response.json(N,{headers:{"content-type":"application/json"},status:200})},k=async(p,g)=>{if(L(p,"POST","PITR"),!n(p))throw new i("admin PITR endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403});const E=await Xn(p),{headers:_}=await d(p,g),O=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:E.args,functionPath:E.functionPath}),headers:_,method:"POST"});return r(u,E.shardKey??t,O)};return{[$n]:w,[Ln]:k,[Kn]:R,[Gn]:I,[Fn]:b}},ea=1,ta=0,ra=32,na=512,aa=/^[a-z][\d_a-z*/-]{0,255}(?:@[a-z][\d_a-z*/-]{0,13})?=[\u0020-\u002B\u002D-\u003C\u003E-\u007E]{1,256}$/,oa=e=>{if(e==null)return;const t=e.trim();if(t.length===0||t.length>na)return;const r=t.split(",");if(!(r.length>ra)){for(const n of r)if(!aa.test(n.trim()))return;return t}},sa=e=>{const t=br(e.headers.get("traceparent"));if(t===void 0)return;const r=oa(e.headers.get("tracestate"));return{parentSpanId:t.parentSpanId,sampled:t.sampled,traceId:t.traceId,...r===void 0?{}:{traceState:r}}},ia=(e,t={})=>{const r=sa(e),n=t.trustInbound===!0?r:void 0,o=Ae(8),d=n?.traceId??Ae(16),u=Ur(t.sampling,n===void 0?o:d),h=u.isTraced&&(n===void 0||n.sampled);return{decision:u,ignoredUpstream:r!==void 0&&n===void 0,trace:{sampled:h,spanId:o,traceFlags:h?ea:ta,traceId:d,...n?.parentSpanId===void 0?{}:{parentSpanId:n.parentSpanId},...n?.traceState===void 0?{}:{traceState:n.traceState}}}},ca=(e,t)=>{t.traceparent=yr(e.traceId,e.spanId,e.sampled),e.traceState!==void 0&&(t.tracestate=e.traceState)},da=(e,t)=>{let r;return()=>{if(r===void 0){const n=Sr(e),o=t===void 0?void 0:t.cf;r=_r(Er(n),Rr(n,o))}return r}},ua="/_lunora/admin/scheduled",la="/_lunora/admin/scheduled/status",ha="/_lunora/admin/scheduled/ws",pa="/_lunora/admin/scheduled/cancel",fa="/_lunora/admin/scheduled/dead",ma="/_lunora/admin/scheduled/dead/retry",wa="/_lunora/admin/scheduled/dead/cancel",ga=e=>{const{checkWsAdmin:t,requireSchedulerNamespace:r,resolveSchedulerStub:n,schedulerInstanceName:o}=e,d=(w,R)=>I=>{if(I.method!=="GET")throw new i(`${R} endpoint requires GET`,{code:"METHOD_NOT_ALLOWED",status:405});return n(I).fetch(new Request(`https://scheduler.internal${w}`,{method:"GET"}))},u=(w,R,I=R)=>async b=>{if(b.method!=="POST")throw new i(`${I} requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});const k=n(b),p=await b.json().catch(()=>{});if(typeof p?.id!="string"||p.id==="")throw new i(`${R} requires a string \`id\``,{code:"BAD_REQUEST",status:400});return k.fetch(new Request(`https://scheduler.internal${w}`,{body:JSON.stringify({id:p.id}),headers:{"content-type":"application/json"},method:"POST"}))},h=async w=>{if(w.headers.get("Upgrade")!=="websocket")throw new i("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});if(!await t(w))throw new i("admin authorization required",{code:"ADMIN_FORBIDDEN",status:403});const R=r();return ge(R,o).fetch(new Request("https://scheduler.internal/ws",{headers:{Upgrade:"websocket"}}))};return{[pa]:u("/cancel","Scheduled-cancel","Scheduled-cancel endpoint"),[wa]:u("/dead/cancel","Scheduled dead-letter action"),[fa]:d("/dead","Scheduled dead-letter"),[ma]:u("/dead/retry","Scheduled dead-letter action"),[ua]:d("/list","Scheduled-list"),[la]:d("/status","Scheduler-status"),[ha]:h}},Ut="/_lunora/admin/storage",ya="/_lunora/admin/storage/url",ba="/_lunora/admin/storage/buckets",_a=10080*60,Nt=32*1048576,Ra=new Set(["GET","PUT"]),Ea=e=>{const t=new Uint8Array(e);let r="";for(const n of t)r+=n.toString(16).padStart(2,"0");return r},Sa=e=>{const{assertAdmin:t,parsePaging:r,queryParameter:n,readBodyBytes:o,requireAdminOption:d,storage:u}=e,h=g=>{const E=n(g,"key");if(E===void 0)throw new i("Storage endpoint requires a `key` query parameter",{code:"BAD_REQUEST",status:400});return E},w=async g=>{const E=d(g,u.storageList,{code:"STORAGE_NOT_CONFIGURED",message:"storage endpoint requires a `storageList` function on the worker"}),_=new URL(g.url),O=await E(n(_,"prefix"),{bucket:n(_,"bucket"),cursor:n(_,"cursor"),...r(g)});return Response.json(O,{headers:{"content-type":"application/json"},status:200})},R=g=>(L(g,"GET","Storage-buckets"),t(g),Response.json({buckets:u.storageBuckets??[]},{headers:{"content-type":"application/json"},status:200})),I=async g=>{const E=d(g,u.storageDelete,{code:"STORAGE_DELETE_NOT_CONFIGURED",message:"storage delete requires a `storageDelete` function on the worker"}),_=new URL(g.url),O=h(_);return await E(O,{bucket:n(_,"bucket")}),Response.json({deleted:!0,key:O},{headers:{"content-type":"application/json"},status:200})},b=async g=>{const E=d(g,u.storageUpload,{code:"STORAGE_UPLOAD_NOT_CONFIGURED",message:"storage upload requires a `storageUpload` function on the worker"}),_=new URL(g.url),O=h(_),N=await o(g,Nt),A=g.headers.get("content-type"),j=A===null||A===""?void 0:A,x=n(_,"expectedSha256"),F=n(_,"expectedSize");let P;if(x!==void 0||F!==void 0){const M=await crypto.subtle.digest("SHA-256",N);P=Ea(M);const B=F!==void 0&&N.byteLength!==Number(F),K=x!==void 0&&P!==x.toLowerCase();if(B||K)throw new i("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 Q=await E(O,N,{bucket:n(_,"bucket"),contentType:j,sha256:P});return Response.json(P===void 0?Q:{...Q,sha256:P},{headers:{"content-type":"application/json"},status:200})},k=async g=>{switch(g.method){case"DELETE":return I(g);case"GET":return w(g);case"POST":case"PUT":return b(g);default:throw new i("Storage endpoint requires GET, PUT, POST, or DELETE",{code:"METHOD_NOT_ALLOWED",status:405})}},p=async g=>{L(g,"GET","Storage URL");const E=d(g,u.storageSignedUrl,{code:"STORAGE_URL_NOT_CONFIGURED",message:"storage URL endpoint requires a `storageSignedUrl` function on the worker"}),_=new URL(g.url),O=h(_),N=Number(n(_,"expiresIn")??""),A=Number.isFinite(N)&&N>0?Math.min(N,_a):void 0,j=n(_,"method");if(j!==void 0&&!Ra.has(j))throw new i("Storage URL `method` must be GET or PUT",{code:"BAD_REQUEST",status:400});const x=j,F=n(_,"contentType"),P=await E(O,{bucket:n(_,"bucket"),contentType:F,expiresInSeconds:A,method:x});return Response.json({key:O,url:P},{headers:{"content-type":"application/json"},status:200})};return{[ba]:R,[Ut]:k,[ya]:p}},Ta=(e,...t)=>{let r=e.cf;for(const n of t){if(typeof r!="object"||r===null)return;r=r[n]}return typeof r=="string"?r:void 0},ut={mtls:e=>Ta(e,"tlsClientAuth","certVerified")==="SUCCESS"},Oa=e=>e===void 0||e===!1?()=>!1:e===!0?()=>!0:typeof e=="function"?e:(Object.hasOwn(ut,e)?ut[e]:void 0)??(()=>!1),Aa=e=>{if(e!==void 0)return()=>{};let t=!1;return()=>{t||(t=!0,console.warn('[lunora] Ignored an inbound `traceparent`, so this request starts a new trace instead of joining the caller\'s. That is the safe default: the header is caller-supplied, and trusting it lets any client choose which trace its spans and logs join. If this worker sits behind a gateway, service mesh, or Cloudflare Access that sets `traceparent` itself, set `trustInboundTraceContext: true` on createWorker() (or `"mtls"` to trust only edge-verified client certificates). Set it to `false` to keep this behaviour and silence this message.'))}},va="/_lunora/admin/vector/indexes",ka="/_lunora/admin/vector/query",Ia=e=>{const{readJsonBody:t,requireAdminOption:r}=e,n=async d=>{L(d,"GET","Vector-indexes");const u=r(d,e.vectorIntrospector,{code:"VECTORS_NOT_CONFIGURED",message:"vector endpoints require a `vectorIntrospector` on the worker"});return Response.json({indexes:await u.listIndexes()},{headers:{"content-type":"application/json"},status:200})},o=async d=>{L(d,"POST","Vector-query");const u=r(d,e.vectorIntrospector,{code:"VECTORS_NOT_CONFIGURED",message:"vector endpoints require a `vectorIntrospector` on the worker"});if(u.queryIndex===void 0)throw new i("vector index querying is not enabled on this worker",{code:"VECTOR_QUERY_UNSUPPORTED",status:400});const h=await t(d);if(typeof h.name!="string"||h.name==="")throw new i("Vector-query request requires a `name` string",{code:"BAD_REQUEST",status:400});if(typeof h.text!="string"||h.text==="")throw new i("Vector-query request requires a `text` string",{code:"BAD_REQUEST",status:400});if(h.topK!==void 0&&(typeof h.topK!="number"||!Number.isInteger(h.topK)||h.topK<1))throw new i("Vector-query `topK` must be a positive integer",{code:"BAD_REQUEST",status:400});const w=await u.queryIndex({name:h.name,text:h.text,topK:h.topK});return Response.json(w,{headers:{"content-type":"application/json"},status:200})};return{[va]:n,[ka]:o}},Da="/_lunora/admin/workflows/instances",Pa="/_lunora/admin/workflows/instance",Ua="/_lunora/admin/workflows/status",Na={complete:!0,errored:!0,paused:!0,queued:!0,running:!0,terminated:!0,unknown:!0,waiting:!0,waitingForPause:!0},qa=e=>e!==null&&Object.hasOwn(Na,e)?e:void 0,lt=(e,t)=>{const r=e.searchParams.get(t);if(r===null)return;const n=Number(r);return Number.isInteger(n)&&n>0?n:void 0},Le=(e,t)=>{const r=e.searchParams.get(t);if(r===null||r==="")throw new i(`Workflows admin endpoint requires a \`${t}\` query parameter`,{code:"BAD_REQUEST",status:400});return r},ht=()=>{throw new i("Workflow inspection is unconfigured. Set CLOUDFLARE_ACCOUNT_ID + CLOUDFLARE_API_TOKEN in your .dev.vars to enable it.",{code:"WORKFLOWS_NOT_CONFIGURED",status:501})},Ca=e=>{const{assertAdmin:t,resolveWorkflowsClient:r}=e,n=async(u,h,w)=>{L(u,"GET","Workflows instances"),t(u);const R=r(h);if(!R)return Response.json({configured:!1,instances:[],page:1,perPage:0,totalCount:0});const I=Le(w,"name"),b=qa(w.searchParams.get("status"));return Response.json(await R.listInstances({page:lt(w,"page"),perPage:lt(w,"perPage"),status:b,workflowName:I}))},o=async(u,h,w)=>{L(u,"GET","Workflows instance"),t(u);const R=r(h);return R?Response.json(await R.getInstance({instanceId:Le(w,"id"),workflowName:Le(w,"name")})):ht()},d=async(u,h)=>{L(u,"POST","Workflows status"),t(u);const w=r(h);if(!w)return ht();const R=await u.json().catch(()=>{});if(typeof R?.name!="string"||R.name===""||typeof R.id!="string"||R.id==="")throw new i("Workflows status action requires string `name` and `id`",{code:"BAD_REQUEST",status:400});const{action:I}=R;if(I!=="pause"&&I!=="resume"&&I!=="terminate")throw new i("Workflows status action must be one of: pause, resume, terminate",{code:"BAD_REQUEST",status:400});return Response.json(await w.setInstanceStatus({action:I,instanceId:R.id,workflowName:R.name}))};return{[Pa]:o,[Da]:n,[Ua]:d}},xa={[Dt]:Pt,[Ut]:Nt},ja=new TextEncoder,pt="/_lunora/rpc",Ba="/_lunora/rpc-batch",$a="/_lunora/ws",Ee=(e,t,r)=>({resourceAttributes:da(e,t),...r===void 0?{}:{waitUntil:r}}),ft=e=>e?.waitUntil?{waitUntil:t=>e.waitUntil?.(t)}:{},mt=e=>({spanId:e.spanId,traceFlags:e.traceFlags,traceId:e.traceId,...e.parentSpanId===void 0?{}:{parentSpanId:e.parentSpanId}}),Ke=e=>{const{method:t}=e,r=e.headers.get("user-agent")??void 0;let n;try{n=new URL(e.url)}catch{return{method:t,userAgent:r}}const o=n.port===""?void 0:Number(n.port);return{host:n.hostname,method:t,path:n.pathname,port:Number.isNaN(o)?void 0:o,scheme:n.protocol.replace(":",""),userAgent:r}},wt="/_lunora/voice/",La="/_lunora/scheduler/dispatch",Ka="/_lunora/admin/cron-jobs/run",Ga="/_lunora/admin/ws-token",Fa="/_lunora/admin/",Qa="/_lunora/migrate",Ma="/_lunora/status",za=e=>e.startsWith(Fa)||e===Qa,Wa=e=>{const t=e.headers.get("x-lunora-userid"),r=e.headers.get("x-lunora-identity");if(!(t===null&&r===null))return{...r===null?{}:{identity:r},...t===null?{}:{userId:t}}},Ha="/api/auth",Ja="__lunora_admin__:recordAuthEvent",Va="__lunora_admin__:listPushSubscriptions",Ya=["/sign-in","/sign-up","/callback"],Xa=(e,t)=>{const r=t.endsWith("/")?t.slice(0,-1):t;if(!e.startsWith(`${r}/`))return!1;const n=e.slice(r.length);return Ya.some(o=>n===o||n.startsWith(`${o}/`))},Se=(e,t,r,n)=>{const o=pr(r),d=o?r.code:"INTERNAL_SERVER_ERROR",u=o?r.status:500,h=r instanceof Error?r.message:String(r);return{durationMs:t,error:{code:d,message:h,status:u},functionPath:e,ok:!1,...n.fanOut?{fanOut:{failed:0,shards:0,table:n.fanOut.table}}:{},...n.shardKey?{shardKey:n.shardKey}:{}}},Za=e=>{const{exp:t,expiresAtMs:r}=e;if(typeof r=="number"&&Number.isFinite(r))return r;if(typeof t=="number"&&Number.isFinite(t))return t*1e3},gt=e=>e.waitUntil?{waitUntil:t=>{e.waitUntil?.(t)}}:void 0,eo=e=>{const t=e?.queue;return typeof t=="string"&&t.length>0?t:"unknown"},de=async(e,t,r)=>{const n={"content-type":"application/json"},o=e.headers.get("authorization"),d=e.headers.get("cookie"),u=e.headers.get("x-d1-bookmark"),h=e.headers.get("x-lunora-mutation-id"),w=e.headers.get("x-lunora-client-id"),R=e.headers.get("x-lunora-client-seq");o&&(n.authorization=o),d&&(n.cookie=d),u&&(n["x-d1-bookmark"]=u),h&&(n["x-lunora-mutation-id"]=h),w&&(n["x-lunora-client-id"]=w),R&&(n["x-lunora-client-seq"]=R);const I=e.headers.get("cf-connecting-ip");if(I&&(n["x-lunora-client-ip"]=I),!r)return{claims:null,headers:n,identity:null,userId:null};const b=await r(e,t);if(!b||typeof b.userId!="string"||b.userId.length===0)return{claims:null,headers:n,identity:null,userId:null};n["x-lunora-userid"]=wr(b.userId);const k=Za(b);k!==void 0&&(n["x-lunora-identity-exp"]=String(k));const{userId:p,...g}=b,E=Object.keys(g).length>0?g:null;return E&&(n["x-lunora-identity"]=gr(E)),{claims:E,headers:n,identity:b,userId:p}},to=new Set(["concat","first","groupBy","max","min","rank","sum","topK"]),ro=e=>{if(e===void 0)return;if(!e||typeof e!="object")throw new i("RPC `fanOut` must be an object",{code:"BAD_REQUEST",status:400});const t=e;if(typeof t.table!="string"||t.table.length===0)throw new i("RPC `fanOut.table` must be a non-empty string",{code:"BAD_REQUEST",status:400});if(!t.merge||typeof t.merge!="object")throw new i("RPC `fanOut.merge` must be an object",{code:"BAD_REQUEST",status:400});const r=t.merge;if(typeof r.kind!="string"||!to.has(r.kind))throw new i("RPC `fanOut.merge.kind` is not a recognized merge strategy",{code:"BAD_REQUEST",status:400});if(r.kind==="topK"){if(typeof r.k!="number"||!Number.isInteger(r.k)||r.k<0)throw new i("RPC `fanOut.merge.k` must be a non-negative integer",{code:"BAD_REQUEST",status:400});if(typeof r.by!="string"||r.by.length===0)throw new i("RPC `fanOut.merge.by` must be a non-empty string",{code:"BAD_REQUEST",status:400})}return t},no=(e,t)=>{e?.LUNORA_DEBUG_RPC&&console.warn(`[lunora:rpc] ${t.fanOut?"fan-out":`shard=${t.shardKey??"(root)"}`} ${t.functionPath}`)},yt=(e,t)=>{const r=t.functions?.[e.functionPath]?.x402;if(r){if(e.fanOut)throw new i("a paid (`.x402`) function cannot be fanned out",{code:"BAD_REQUEST",status:400});if(!t.x402Charge)throw new i(`function "${e.functionPath}" is marked paid (.x402) but no x402Charge gate is configured on the worker`,{code:"MISCONFIGURED",status:500});return r}},ao=async e=>{const t=await St(e);let r;try{r=JSON.parse(t)}catch{throw new i("RPC body must be valid JSON",{code:"BAD_REQUEST",status:400})}if(!r||typeof r!="object"||typeof r.functionPath!="string")throw new i("RPC envelope is missing `functionPath`",{code:"BAD_REQUEST",status:400});const n=r;if(n.args!==void 0&&Tt(n.args,"RPC"),n.shardKey!==void 0&&typeof n.shardKey!="string")throw new i("RPC `shardKey` must be a string",{code:"BAD_REQUEST",status:400});const o=r,d=ro(o.fanOut),u=o.args??{};if(d&&o.functionPath.startsWith("__lunora_relation__:")){const h=u.table;if(typeof h=="string"&&h!==d.table)throw new i("RPC `args.table` must match the authorized `fanOut.table` for a relation fan-out",{code:"BAD_REQUEST",status:400});u.table=d.table}return{args:u,fanOut:d,functionPath:o.functionPath,shardKey:o.shardKey}},oe=async(e,t,r)=>ge(e,t).fetch(r),Te=new Map,oo=5e3,so=4096,io=async(e,t)=>{const r=Date.now(),n=Te.get(t);if(n!==void 0&&n.expiresMs>r)return n.relayCount;n!==void 0&&Te.delete(t);let o=0;try{const d=await ge(e,t).fetch(new Request("https://shard.internal/_lunora/route"));if(d.ok){const u=(await d.json()).relayCount;typeof u=="number"&&u>0&&(o=Math.floor(u))}}catch{o=0}return Rt(Te,so),Te.set(t,{expiresMs:r+oo,relayCount:o}),o},co=(e,t)=>{if(!(e===null||typeof e!="object"))return Object.entries(e).find(([,r])=>r===t)?.[0]},Oe=(e,t,r)=>new Request("https://shard.internal/rpc",{body:JSON.stringify({args:t,functionPath:e}),headers:r,method:"POST"}),uo=["x-lunora-userid","x-lunora-identity","x-lunora-identity-exp"],bt=(e,t)=>{for(const r of uo){e.delete(r);const n=t[r];n!==void 0&&e.set(r,n)}},lo=async(e,t,r)=>e.length===0||r.length===0?!1:Ge(await vt(e,t),r),_t=(e,t)=>{if(!t||t.length===0)return!1;const r=e.headers.get("authorization");if(!r)return!1;const[n,...o]=r.split(" ");return n?.toLowerCase()!=="bearer"?!1:Ge(t,o.join(" ").trim())},ho=async(e,t,r)=>{if(!t||t.length===0)return!1;const n=new URL(e.url).searchParams.get("token");return n===null?!1:await Vr(t,n)?!0:r?!1:Ge(t,n)},po=(e,t)=>{if(t===null||typeof t!="object"&&typeof t!="function")return;const r=t;if(typeof r.prepare=="function"&&typeof r.batch=="function"&&typeof r.dump=="function")return Ir(`d1:${e}`,t);if(typeof r.list=="function"&&typeof r.head=="function"&&typeof r.createMultipartUpload=="function")return Ne(`r2:${e}`,!0);if(typeof r.send=="function"&&typeof r.sendBatch=="function"&&typeof r.get!="function")return Ne(`queue:${e}`,!0);if(typeof r.connectionString=="string")return Ne(`hyperdrive:${e}`,!0)},qt=e=>{const t=Oa(e.trustInboundTraceContext),r=Aa(e.trustInboundTraceContext),n=e.defaultShardKey??"__root__",o=Dr(e.resolveIdentity,e.identity),d=Ye(e.shardDO,e.jurisdiction),u=e.schedulerDO===void 0?void 0:Ye(e.schedulerDO,e.jurisdiction);let h;const w=()=>e.adminToken??h;let R;const I=()=>e.requireEphemeralWsToken??R??!0,b=a=>{const s=a??{};if(R===void 0&&e.requireEphemeralWsToken===void 0){const c=s.LUNORA_REQUIRE_EPHEMERAL_WS_TOKEN;typeof c=="string"&&c.length>0&&(R=Wr(c,!0))}if(h!==void 0||e.adminToken!==void 0)return;const l=s.LUNORA_ADMIN_TOKEN;typeof l=="string"&&l.length>0&&(h=l)},k=new WeakSet,p=a=>_t(a,w())||k.has(a),g=async(a,s)=>{const l=await de(a,s,e.resolveIdentity);if(k.has(a)&&l.headers.authorization===void 0){const c=w();c!==void 0&&(l.headers.authorization=`Bearer ${c}`)}return l};let E=!1;const _=a=>{if(!e.allowUnauthenticatedShardAccess){const s=a==="fan-out"?"authorizeFanOut":"authorizeShard";throw new i(`${a} access is default-denied: configure \`${s}\` on the worker, or set \`allowUnauthenticatedShardAccess: true\` to explicitly allow unauthenticated ${a} access (relying solely on per-row RLS).`,{code:a==="fan-out"?"FORBIDDEN_FANOUT":"FORBIDDEN_SHARD",status:403})}E||(E=!0,console.warn([`[lunora] SECURITY: serving ${a} access with \`allowUnauthenticatedShardAccess: true\` and no \`authorizeShard\`/\`authorizeFanOut\` — `,"any caller (including unauthenticated ones) can target any shard / fan out across the table. ","This is safe only if every table is protected by per-row RLS. Configure `authorizeShard`/`authorizeFanOut` to gate it."].join("")))},O=async(a,s,l=!0)=>{if(e.authorizeShard){if(!await e.authorizeShard(a,s))throw new i("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else l&&s!==n&&_("shard")},N=Zn({defaultShard:n,forwardToShard:oe,isAdmin:p,queryCoordinator:e.queryCoordinator,resolveForwardContext:g,shardDO:d}),A=async(a,s,l,c,m)=>{await O(null,l,!1);const y={"content-type":"application/json","x-lunora-system":"1"};return m?.userId!==void 0&&m.userId.length>0&&(y["x-lunora-userid"]=m.userId),m?.identity!==void 0&&m.identity.length>0&&(y["x-lunora-identity"]=m.identity),c!==void 0&&c.length>0&&(y["x-lunora-mutation-id"]=c),oe(d,l,Oe(a,s,y))},j=async(a,s,l,c)=>{const m=l?.[a];if(!m||typeof m.create!="function")throw new i(`${c} targets workflow binding "${a}", which is not bound on env`,{code:"CRON_JOB_FAILED",status:500});if(xr(s))throw new i(`${c} params ${jr}`,{code:"BAD_REQUEST",status:400});await m.create({params:s})},x=async(a,s)=>{if(a.workflow){await j(a.workflow,a.args??{},s,`cron job "${a.name}"`);return}if(a.functionPath===void 0)throw new i(`cron job "${a.name}" has neither a function target nor a workflow target`,{code:"CRON_JOB_FAILED",status:500});const l=await A(a.functionPath,a.args??{},a.shardKey??n);if(!l.ok)throw new i(`cron job "${a.name}" (${a.functionPath}) failed with shard status ${String(l.status)}`,{code:"CRON_JOB_FAILED",status:500})},F=async(a,s,l,c)=>{const m=e.cronJobs?.[a];if(m)for(const y of m)try{await x(y,s)}catch(v){l.push(c(v))}},P=async(a,s)=>{if(!p(a))throw new i("admin endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403});if(L(a,"POST","cron-jobs run"),!e.cronJobs)throw new i("cron-jobs run endpoint requires a `cronJobs` map on the worker",{code:"CRON_JOBS_NOT_CONFIGURED",status:400});const l=await ee(a),c=typeof l.name=="string"?l.name:"";if(c==="")throw new i("cron-jobs run endpoint requires a job `name`",{code:"BAD_REQUEST",status:400});const m=Object.values(e.cronJobs).flat().find(y=>y.name===c);if(!m)throw new i(`no cron job named "${c}" is registered`,{code:"CRON_JOB_NOT_FOUND",status:404});return await x(m,s),Response.json({name:c,ran:!0},{status:200})},Q=async a=>{const s=typeof a.pool=="string"&&a.pool.length>0?a.pool:void 0;if(!s||!u||typeof a.id!="string")return;const l=typeof a.instanceName=="string"&&a.instanceName.length>0?a.instanceName:"default";try{await ge(u,l).fetch(new Request("https://scheduler.internal/complete",{body:JSON.stringify({id:a.id,pool:s}),headers:{"content-type":"application/json"},method:"POST"}))}catch{}},M=async(a,s)=>{L(a,"POST","Scheduler dispatch");const l=await St(a),c=s??{},m=typeof c.LUNORA_SCHEDULER_SECRET=="string"?c.LUNORA_SCHEDULER_SECRET:void 0,y=e.adminToken??(typeof c.LUNORA_ADMIN_TOKEN=="string"?c.LUNORA_ADMIN_TOKEN:void 0),v=a.headers.get("x-lunora-scheduler-signature");let f=!1;if(v&&m?f=await lo(m,l,v):y&&(f=_t(a,y)),!f)throw new i("Scheduler dispatch requires a valid signature or admin bearer",{code:"FORBIDDEN",status:403});let S;try{S=JSON.parse(l)}catch{throw new i("Scheduler dispatch body must be valid JSON",{code:"BAD_REQUEST",status:400})}const T=S??{},q=T.args??{};if(typeof T.workflow=="string"&&T.workflow.length>0)return await j(T.workflow,q,s,"scheduled workflow"),Response.json({ok:!0},{status:200});if(typeof T.functionPath!="string"||T.functionPath.length===0)throw new i("Scheduler dispatch is missing `functionPath`",{code:"BAD_REQUEST",status:400});const C=typeof T.shardKey=="string"&&T.shardKey.length>0?T.shardKey:n,$=typeof T.id=="string"&&T.id.length>0?T.id:void 0,V=Wa(a),Z=await A(T.functionPath,q,C,$,V);return await Q(T),Z},B=a=>{if(!p(a))throw new i("admin endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403})},K=(a,s,l)=>{if(B(a),s===void 0)throw new i(l.message,{code:l.code,status:400});return s},X=tn({assertAdmin:B,getReader:()=>e.authAuditReader}),J=async(a,s)=>{B(a);const l=e.notifySubscriptionStore;if(l===void 0)return Response.json({subscriptions:[]},{headers:{"content-type":"application/json"},status:200});const c=s?.kind,m=s?.userId,y=s?.limit,v=c==="fcm"||c==="web-push"?c:void 0,f=typeof m=="string"&&m!==""?m:void 0,S=typeof y=="number"&&Number.isFinite(y)?Math.trunc(y):0,T=S>0?Math.min(S,1e3):1e3,q=(await l.list({kind:v,limit:T,userId:f})).filter(C=>v!==void 0&&C.kind!==v?!1:f===void 0||(C.userId??null)===f).map(({keys:C,token:$,...V})=>V);return Response.json({subscriptions:q},{headers:{"content-type":"application/json"},status:200})},ne=async(a,s)=>{if(!s.fanOut){if(s.functionPath===en)return X(a,s.args??{});if(s.functionPath===Va)return J(a,s.args)}},he=gn({applyGlobals:e.applyGlobals,assertAdmin:B,exportCursorStore:e.exportCursorStore,exportSinks:e.exportSinks,knownTables:()=>[],queryCoordinator:e.queryCoordinator,requireAdminOption:K,resolveForwardContext:g,shardDO:d,streamExportRows:(a,s,l,c)=>st(e,a,s,l,c,d),streamingImport:(a,s)=>Sn(a,e,s,d),syncGlobals:e.syncGlobals}),ae=(a,s)=>{const l=a.searchParams.get(s);return l===null||l===""?void 0:l},pe=a=>{const s=new URL(a.url),l=s.searchParams.get("limit"),c=s.searchParams.get("offset"),m=l===null?void 0:Number.parseInt(l,10),y=c===null?void 0:Number.parseInt(c,10);return{limit:m!==void 0&&Number.isFinite(m)&&m>=0?m:void 0,offset:y!==void 0&&Number.isFinite(y)&&y>=0?y:void 0}},_e=()=>{if(u===void 0)throw new i("scheduled endpoints require a `schedulerDO` namespace on the worker",{code:"SCHEDULER_NOT_CONFIGURED",status:400});return u},ve=ga({checkWsAdmin:async a=>p(a)||ho(a,w(),I()),requireSchedulerNamespace:_e,resolveSchedulerStub:a=>(B(a),ge(_e(),e.schedulerInstanceName??"default")),schedulerInstanceName:e.schedulerInstanceName??"default"}),se=Ca({assertAdmin:B,resolveWorkflowsClient:e.workflowsClient??(()=>{})}),Ct=Sa({assertAdmin:B,parsePaging:pe,queryParameter:ae,readBodyBytes:Or,requireAdminOption:K,storage:{storageBuckets:e.storageBuckets,storageDelete:e.storageDelete,storageList:e.storageList,storageSignedUrl:e.storageSignedUrl,storageUpload:e.storageUpload}}),xt=Ia({readJsonBody:ee,requireAdminOption:K,vectorIntrospector:e.vectorIntrospector}),jt=Bn({kvIntrospector:e.kvIntrospector,readJsonBody:ee,requireAdminOption:K}),Bt=Pr({logArchive:e.logArchive,readJsonBody:ee,requireAdminOption:K}),$t=Cn({assertAdmin:B,options:{cronJobs:e.cronJobs,functions:e.functions,globalIntrospector:e.globalIntrospector,openApiSpec:e.openApiSpec,openRpcSpec:e.openRpcSpec},parsePaging:pe,queryParameter:ae,requireAdminOption:K}),Lt=a=>{const s=[],l=d??a?.SHARD;if(l!==void 0&&s.push(kr("durable-object:default",l,n)),e.health?.disableBindingProbes!==!0)for(const[c,m]of Object.entries(a??{})){const y=po(c,m);y!==void 0&&s.push(y)}for(const c of e.health?.probes??[])s.push(c);return s},Kt=vr({appName:e.health?.appName,appVersion:e.health?.appVersion,auth:e.health?.auth??"public",cacheTtlMs:e.health?.cacheTtlMs,isAdmin:p,resolveProbes:Lt}),Gt=a=>{const s=e.schedulerInstanceName??"default",l=()=>ge(a,s),c=async(f,S)=>{const T=await l().fetch(new Request(`https://scheduler.internal${f}`,S));if(!T.ok)throw new i(`ctx.scheduler: SchedulerDO ${f} failed (${String(T.status)}): ${await T.text()}`,{code:"INTERNAL",status:500});return await T.json()},m=async(f,S)=>await c(f,{body:JSON.stringify(S),headers:{"content-type":"application/json"},method:"POST"}),y=f=>{const S=f;if(S==null)throw new i("ctx.scheduler: target is required — pass a reference from the generated `internal` / `workflows` / `agents`",{code:"BAD_REQUEST",status:400});if(typeof S.binding=="string"&&S.binding.length>0)return{workflow:S.binding};if(typeof S.__lunoraRef=="string")return{functionPath:S.__lunoraRef};throw new i("ctx.scheduler: expected a reference from the generated `internal` / `workflows` / `agents` — a bare function-path string is refused here, because an HTTP action can be reached unauthenticated",{code:"BAD_REQUEST",status:400})},v=async(f,S,T={})=>{const{id:q}=await m("/schedule",{args:T,scheduledFor:f,...y(S)});return q};return{cancel:async f=>await m("/cancel",{id:f}),get:async f=>await c(`/get?id=${encodeURIComponent(f)}`,{method:"GET"}),list:async()=>await c("/list",{method:"GET"}),runAfter:async(f,S,T)=>{if(!Number.isFinite(f)||f<0)throw new i("ctx.scheduler.runAfter: `delayMs` must be a non-negative finite number",{code:"BAD_REQUEST",status:400});return await v(Date.now()+f,S,T)},runAt:async(f,S,T)=>{if(!Number.isFinite(f))throw new i("ctx.scheduler.runAt: `timestampMs` must be a finite epoch-millisecond number",{code:"BAD_REQUEST",status:400});return await v(f,S,T)}}},Ft=async(a,s,l)=>{const{claims:c,headers:m,userId:y}=await de(a,s,o),v=async(f,S={})=>{const T=f.__lunoraRef;if(typeof T!="string")throw new i("ctx.run*: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});const q=Oe(T,S,{...m,"x-lunora-system":"1"}),C=await oe(d,n,q),$=await C.json();if($.error)throw new i($.error.message??"shard RPC failed",{code:$.error.code??"INTERNAL",status:C.status});return $.result};return{auth:{getIdentity:()=>Promise.resolve(c),userId:y},cache:l.cache,fetch:globalThis.fetch.bind(globalThis),runAction:v,runMutation:v,runQuery:v,...u===void 0?{}:{scheduler:Gt(u)},...e.storage===void 0?{}:{storage:Cr(e.storage(s))}}},Qt=async(a,s,l)=>{if(!e.httpRouter)return;const c=await Ft(a,s,l);try{return await e.httpRouter.fetch(a,{...s,__lunoraCtx:c},l)}catch(m){return console.error("[lunora] httpRouter (SSR) handler threw:",m),new Response("Internal Server Error",{status:500})}},Mt=async(a,s,l)=>{if(a.headers.get("Upgrade")!=="websocket")throw new i("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});const c=Ze(a,ie);if(c)return c;const m=l.searchParams.get("shard")??n,{headers:y,identity:v}=await de(a,s,o);await O(v,m);const f=new Headers(a.headers),S=[...f.keys()];for(const q of S)q.startsWith("x-lunora-")&&f.delete(q);bt(f,y);const T=co(s,e.shardDO);if(T!==void 0){f.set("x-lunora-shard-binding",T);const q=await io(d,m);if(q>0){const C=Qr(m,Math.floor(Math.random()*q));return oe(d,C,new Request(a,{headers:f}))}}return oe(d,m,new Request(a,{headers:f}))},zt=async(a,s,l)=>{const{voiceAgents:c}=e;if(c===void 0)return new Response("Not found",{status:404});if(a.headers.get("Upgrade")!=="websocket")return new Response("Expected a WebSocket upgrade",{headers:{allow:"GET"},status:426});const m=Ze(a,ie);if(m)return m;let y;try{y=decodeURIComponent(l.pathname.slice(wt.length))}catch{return new Response("Unknown voice agent",{status:404})}const v=Object.hasOwn(c,y)?c[y]:void 0;if(v===void 0)return new Response("Unknown voice agent",{status:404});const f=l.searchParams.get("threadKey");if(f===null||f.length===0)return new Response("Missing threadKey",{status:400});const{headers:S,identity:T}=await de(a,s,o);if(e.authorizeShard){if(!await e.authorizeShard(T,f))return new Response("Forbidden",{status:403})}else _("shard");const q=new Headers(a.headers);for(const C of q.keys())C.startsWith("x-lunora-")&&q.delete(C);return bt(q,S),oe(v,f,new Request(a,{headers:q}))},Wt=async(a,s,l)=>{if(e.authorizeFanOut){if(!await e.authorizeFanOut(l,a.table,s))throw new i("Forbidden fan-out",{code:"FORBIDDEN_FANOUT",status:403});return}if(s.startsWith("__lunora_relation__:"))throw new i("reverse cross-backend relation reads (`__lunora_relation__:*`) require `authorizeFanOut` to be configured on the worker",{code:"FORBIDDEN_FANOUT",status:403});if(e.authorizeShard)throw new i("Fan-out requires `authorizeFanOut` to be configured on the worker when `authorizeShard` is set",{code:"FORBIDDEN_FANOUT",status:403});_("fan-out")},Re=async(a,s)=>{if(!(!a.fanOut&&a.functionPath.startsWith("__lunora_admin__:"))){if(a.fanOut){await Wt(a.fanOut,a.functionPath,s);return}await O(s,a.shardKey??n)}},ke=async(a,s,l,c,m,y)=>{const v=Date.now(),{observability:f,sampling:S}=e,T=Ke(a),{decision:q,ignoredUpstream:C,trace:$}=ia(a,{...S===void 0?{}:{sampling:S},trustInbound:t(a)});C&&r();const V={...m,"x-lunora-sample-errors":q.keepErrors?"1":"0"};ca($,V);const Z=Oe(s,l,V);try{const G=await oe(d,c,Z);return ce(f,{...T,...mt($),durationMs:Date.now()-v,functionPath:s,ok:G.ok,shardKey:c,...G.ok?{}:{error:{code:"SHARD_ERROR",message:`shard returned ${String(G.status)}`,status:G.status}}},y,void 0,{isTraced:$.sampled,keepErrors:q.keepErrors}),G}catch(G){throw ce(f,{...T,...mt($),...Se(s,Date.now()-v,G,{shardKey:c})},y,void 0,{isTraced:$.sampled,keepErrors:q.keepErrors}),G}},Ht=a=>{if(a.fanOut&&a.shardKey)throw new i("RPC envelope cannot set both `shardKey` and `fanOut`",{code:"BAD_REQUEST",status:400});if(!a.fanOut&&a.functionPath.startsWith("__lunora_relation__:"))throw new i("`__lunora_relation__:*` is a fan-out-only reserved RPC and cannot be dispatched to a single shard",{code:"FORBIDDEN",status:403});if(a.fanOut&&!e.queryCoordinator)throw new i("RPC envelope set `fanOut` but no `queryCoordinator` is configured on the worker",{code:"BAD_REQUEST",status:400})},Jt=async(a,s,l)=>{L(a,"POST","RPC");const c=await ao(a);no(s,c),Ht(c);const m=await ne(a,c);if(m!==void 0)return m;const{headers:y,identity:v}=await de(a,s,o);await Re(c,v);const f=yt(c,e);{const S=Date.now(),{observability:T}=e,q=Ke(a),C=Ee(s,a,l&&(Z=>l.waitUntil?.(Z)));if(c.fanOut){const Z=e.queryCoordinator;if(!Z)throw new i("RPC envelope set `fanOut` but no `queryCoordinator` is configured on the worker",{code:"BAD_REQUEST",status:400});try{const G=await Z.fanOut(d,{args:c.args??{},fanOut:c.fanOut,functionPath:c.functionPath,headers:y});return ce(T,{durationMs:Date.now()-S,fanOut:{failed:G.failed,shards:G.ok+G.failed,table:c.fanOut.table},functionPath:c.functionPath,...q,ok:!0},C),Response.json(G,{headers:{"content-type":"application/json"},status:200})}catch(G){throw ce(T,{...Se(c.functionPath,Date.now()-S,G,{fanOut:{table:c.fanOut.table}}),...q},C),G}}const $=c.shardKey??n,V=()=>ke(a,c.functionPath,c.args??{},$,y,C);return f&&e.x402Charge?e.x402Charge(a,{functionPath:c.functionPath,price:f.price},V,ft(l)):V()}},Vt=async(a,s,l)=>{L(a,"POST","RPC batch");const c=await ee(a),{calls:m}=c;if(!Array.isArray(m))throw new i("RPC batch `calls` must be an array",{code:"BAD_REQUEST",status:400});const{headers:y,identity:v}=await de(a,s,o),f=nn(m,n);for(const z of f.values())for(const W of z)if(e.functions?.[W.functionPath]?.x402)throw new i(`paid (\`.x402\`) function "${W.functionPath}" cannot be called in a batch; dispatch it individually over ${pt}`,{code:"BAD_REQUEST",status:400});await Promise.all([...f.entries()].flatMap(([z,W])=>W.map(re=>Re({functionPath:re.functionPath,shardKey:z},v))));const{observability:S}=e,T=Ee(s,a,l&&(z=>l.waitUntil?.(z))),q=Ke(a),C=[],$=[],V=(z,W,re,ue)=>({body:{error:{code:re,message:ue}},id:z.id,status:W}),Z=(z,W,re,ue,fe)=>{for(const H of z)ce(S,fe(H),T),C.push(V(H,W,re,ue))},G=(z,W,re,ue,fe)=>{for(const H of z){const me=ue.get(H.id)??fe,ye=me<400;ce(S,{durationMs:re,functionPath:H.functionPath,...q,ok:ye,shardKey:W,...ye?{}:{error:{code:"SHARD_ERROR",message:`batched call returned ${String(me)}`,status:me}}},T)}};await Promise.all([...f.entries()].map(async([z,W])=>{const re=new Headers(y);re.set("content-type","application/json");const ue=new Request("https://shard.internal/rpc-batch",{body:JSON.stringify({calls:W}),headers:re,method:"POST"}),fe=Date.now();let H;try{H=await oe(d,z,ue)}catch(Y){const Ue=Date.now()-fe,{body:He}=fr(Y,{fallbackCode:"SHARD_UNAVAILABLE",redactedMessage:"shard unavailable"});Z(W,502,He.code,He.message,hr=>({...Se(hr.functionPath,Ue,Y,{shardKey:z}),...q}));return}const me=Date.now()-fe,ye=H.headers.get("x-d1-bookmark");ye&&$.push(ye);let De;try{De=await H.json()}catch{const Y=`shard batch returned a non-JSON response (${String(H.status)})`;Z(W,H.status,"SHARD_ERROR",Y,Ue=>({durationMs:me,error:{code:"SHARD_ERROR",message:Y,status:H.status},functionPath:Ue.functionPath,...q,ok:!1,shardKey:z}));return}const Pe=Array.isArray(De.results)?De.results:[],ur=new Map(Pe.map(Y=>[Y.id,Y.status??H.status])),lr=new Set(Pe.map(Y=>Y.id));G(W,z,me,ur,H.status),C.push(...Pe);for(const Y of W)lr.has(Y.id)||C.push(V(Y,H.status,"SHARD_ERROR",`shard batch omitted result for call ${String(Y.id)}`))}));const ze={"content-type":"application/json"},[We]=$;return $.length===1&&We!==void 0&&(ze["x-d1-bookmark"]=We),Response.json({results:C},{headers:ze,status:200})},Yt=async(a,s,l,c={},m={})=>{try{const y=l.__lunoraRef;if(typeof y!="string")throw new i("serverQuery: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});const{headers:v,identity:f}=await de(a,s,o);await Re({functionPath:y,shardKey:m.shardKey},f);const S=m.shardKey??n,T=Ee(s,a,m.waitUntil);return await ke(a,y,c,S,v,T)}catch(y){return Je(y)}},Xt=1e3,Zt=async(a,s)=>{const l=e.backupRetain;if(l===void 0||l<=0)return;const c=[];let m;for(let v=0;v<Xt;v+=1){const f=await a.list({cursor:m,prefix:s});for(const S of f.objects)S.key.endsWith(".manifest.json")&&c.push(S.key);if(!f.truncated||f.cursor===void 0)break;m=f.cursor}const y=c.toSorted((v,f)=>f.localeCompare(v)).slice(l);await Promise.all(y.flatMap(v=>{const f=v.slice(0,-14);return[a.delete(v),a.delete(f)]}))},er=async a=>{const s=e.backupStore,l=e.queryCoordinator;if(!s)throw new i("scheduled backup requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});if(!l)throw new i("scheduled backup requires a `queryCoordinator` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});const c=w();if(!c||c.length===0)throw new i("scheduled backup requires an `adminToken` (or `env.LUNORA_ADMIN_TOKEN`) to authenticate the per-shard export gate",{code:"BACKUP_NOT_CONFIGURED",status:500});const m={authorization:`Bearer ${c}`,"content-type":"application/json"},y=e.backupTables;let v=0,f=0;const S=[];await st(e,l,m,y,Z=>{const G=`${JSON.stringify(Z)}
5
5
  `;v+=1,f+=ja.encode(G).byteLength,S.push(G)},d);const T=e.backupPrefix??"backups/",q=new Date(a.scheduledTime).toISOString(),C=`${T}lunora-backup-${q.replaceAll(/[.:]/gu,"-")}.ndjson`,$=`${C}.manifest.json`;await s.put(C,new Blob(S,{type:"application/x-ndjson"}),{httpMetadata:{contentType:"application/x-ndjson"}});const V={bytes:f,createdAt:q,cron:a.cron,file:C,id:q,rows:v,scheduledTime:a.scheduledTime,...y?{tables:y.join(",")}:{}};await s.put($,`${JSON.stringify(V,void 0,2)}
6
- `,{httpMetadata:{contentType:"application/json"}}),await Zt(s,T)},Qe=async(a,s,l)=>{const{observability:c}=e,m=Date.now(),y=Oe(16),v=Oe(8),f=gt(s);try{const S=await l();return ce(c,{durationMs:Date.now()-m,functionPath:a,ok:!0,spanId:v,traceId:y},f),S}catch(S){throw ce(c,{...Ee(a,Date.now()-m,S,{}),spanId:v,traceId:y},f),S}finally{Ve(c,f)}},tr=async(a,s,l)=>{b(s);const c=[],m=f=>f instanceof Error?f:new Error(String(f)),y=e.crons?.[a.cron];if(y)try{await y(a,s,l)}catch(f){c.push(m(f))}if(await F(a.cron,s,c,m),e.backupStore&&e.backupCron!==void 0&&e.backupCron===a.cron)try{await er(a)}catch(f){c.push(m(f))}const[v]=c;if(c.length===1&&v)throw v;if(c.length>1)throw new AggregateError(c,`scheduled("${a.cron}") had ${String(c.length)} failure(s)`)},rr=async(a,s)=>{try{const l=a??{},c=e.adminToken??(typeof l.LUNORA_ADMIN_TOKEN=="string"?l.LUNORA_ADMIN_TOKEN:void 0);if(!c||c.length===0)return;await oe(d,n,Te(Ja,{outcome:s},{authorization:`Bearer ${c}`,"content-type":"application/json"}))}catch{}},nr=async(a,s,l,c)=>{if(!e.authHandler)return;const m=await e.authHandler(a);if(!m)return;const y=e.authBasePath??Ha;return Xa(l.pathname,y)&&c.waitUntil?.(rr(s,m.status>=400?"fail":"ok")),m},ar=async({args:a,env:s,functionPath:l,request:c,shardKey:m,waitUntil:y})=>{Tt(a,"REST");const v={functionPath:l,...m===void 0?{}:{shardKey:m}},{headers:f,identity:S}=await de(c,s,o);await _e(v,S);const T=m??n,q=Re(s,c,y),C=()=>ke(c,l,a,T,f,q),$=yt(v,e);return $&&e.x402Charge?e.x402Charge(c,{functionPath:l,price:$.price},C,ft({waitUntil:y})):C()},or=Tr({functions:e.functions??{},invoke:ar,readJsonBody:ee,...e.restRateLimit?{rateLimit:e.restRateLimit}:{}}),Ie=e.routes!==void 0&&Object.keys(e.routes).length>0?e.routes:void 0,sr={[Ma]:a=>a.method!=="GET"&&a.method!=="HEAD"?new Response(void 0,{headers:{allow:"GET, HEAD"},status:405}):Response.json({ok:!0},{headers:{"cache-control":"no-store"}}),[$a]:(a,s,l)=>Mt(a,s,l),[pt]:(a,s,l,c)=>Jt(a,s,c),[Ba]:(a,s,l,c)=>Vt(a,s,c),[La]:(a,s)=>M(a,s),[Ka]:(a,s)=>P(a,s),[Ga]:async a=>{L(a,"POST","ws-token"),B(a);const s=w();if(s===void 0)throw new i("ws-token minting requires a configured admin token",{code:"ADMIN_TOKEN_NOT_CONFIGURED",status:400});const l=await Jr(s);return Response.json(l,{headers:{"cache-control":"no-store"}})},...N,...he,...ve,...se,...Ct,...xt,...jt,...Bt,...$t,...Kt,...or,...Zr({assertAdmin:B,getAuthAdmin:()=>e.authAdmin,parsePaging:pe,queryParameter:ae,readJsonBody:ee})};let ie=Xe(e.security),Me=!1;const ir=a=>{Me||(Me=!0,ie=Xe(e.security,a??{}))},cr=async(a,s)=>{if(!(e.adminGate===void 0||!za(s)))try{await e.adminGate(a)&&k.add(a)}catch{}},dr=async(a,s,l)=>{const c=new URL(a.url);if(a.method==="POST"||a.method==="PUT"){const f=Number(a.headers.get("content-length")??""),S=xa[c.pathname]??Et;if(Number.isFinite(f)&&f>S)throw new i("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413})}const m=await nr(a,s,c,l);if(m)return m;if(Ie){const f=`${a.method} ${c.pathname}`,S=Ie[f]??Ie[c.pathname];if(S)return S(a,s,l)}const y=sr[c.pathname];return y?(await cr(a,c.pathname),y(a,s,c,l)):e.voiceAgents!==void 0&&c.pathname.startsWith(wt)?zt(a,s,c):await Qt(a,s,l)||new Response("Not found",{status:404})};return{async fetch(a,s,l){e.passThroughOnException&&l.passThroughOnException?.(),ir(s),b(s);const c=Nr(a,ie);if(c)return c;const m=qr(a,ie);if(m)return qe(m,a,ie);try{const y=await dr(a,s,l);return qe(y,a,ie)}catch(y){return qe(Je(y),a,ie)}finally{Ve(e.observability,gt(l))}},async queue(a,s,l){await Qe(`queue:${eo(a)}`,l,async()=>{await e.queue?.(a,s,l)})},async scheduled(a,s,l){await Qe(`cron:${a.cron}`,l,async()=>{await tr(a,s,l)})},serverQuery:Yt}},fo=e=>qt(e),mo=e=>typeof e=="function"?{fetch:e}:e,wo=e=>!!(e.crons??e.cronJobs??e.backupCron),No=(e,t)=>{const r=mo(e),n=typeof e=="object"&&typeof e.scheduled=="function"?e.scheduled:void 0,o=u=>{const h=fo({...u,httpRouter:r});return n!==void 0&&!wo(u)?{...h,scheduled:async(w,R,I)=>{await n(w,R,I)}}:h};if(typeof t!="function")return o(t);const d=t;return{fetch:(u,h,w)=>o(d(h)).fetch(u,h,w),queue:(u,h,w)=>o(d(h)).queue?.(u,h,w)??Promise.resolve(),scheduled:(u,h,w)=>o(d(h)).scheduled(u,h,w),serverQuery:(u,h,w,R,I)=>o(d(h)).serverQuery(u,h,w,R,I)}},go=(e,t)=>{if(typeof e=="function")return e(t);const r=e.shardDO??t?.SHARD;if(!r)throw new i("@lunora/runtime: no shard Durable Object namespace found. Bind `SHARD` in wrangler.jsonc, or pass `createLunoraHandler({ shardDO: env.MY_SHARD })`.");return{...e,shardDO:r}},qo=(e={})=>(t,r,n)=>qt(go(e,r)).fetch(t,r,n??mr),Co=e=>e;export{en as GET_AUTH_AUDIT_LOG_OP,mr as NOOP_EXECUTION_CONTEXT,Bo as composeIdentityResolvers,fo as composeWorker,qo as createLunoraHandler,qt as createWorker,Co as defineRpcEnvelope,io as probeRelayCount,go as resolveLunoraOptions,$o as routeIdentityResolvers,No as withFrameworkWorker};
6
+ `,{httpMetadata:{contentType:"application/json"}}),await Zt(s,T)},Qe=async(a,s,l)=>{const{observability:c}=e,m=Date.now(),y=Ae(16),v=Ae(8),f=gt(s);try{const S=await l();return ce(c,{durationMs:Date.now()-m,functionPath:a,ok:!0,spanId:v,traceId:y},f),S}catch(S){throw ce(c,{...Se(a,Date.now()-m,S,{}),spanId:v,traceId:y},f),S}finally{Ve(c,f)}},tr=async(a,s,l)=>{b(s);const c=[],m=f=>f instanceof Error?f:new Error(String(f)),y=e.crons?.[a.cron];if(y)try{await y(a,s,l)}catch(f){c.push(m(f))}if(await F(a.cron,s,c,m),e.backupStore&&e.backupCron!==void 0&&e.backupCron===a.cron)try{await er(a)}catch(f){c.push(m(f))}const[v]=c;if(c.length===1&&v)throw v;if(c.length>1)throw new AggregateError(c,`scheduled("${a.cron}") had ${String(c.length)} failure(s)`)},rr=async(a,s)=>{try{const l=a??{},c=e.adminToken??(typeof l.LUNORA_ADMIN_TOKEN=="string"?l.LUNORA_ADMIN_TOKEN:void 0);if(!c||c.length===0)return;await oe(d,n,Oe(Ja,{outcome:s},{authorization:`Bearer ${c}`,"content-type":"application/json"}))}catch{}},nr=async(a,s,l,c)=>{if(!e.authHandler)return;const m=await e.authHandler(a);if(!m)return;const y=e.authBasePath??Ha;return Xa(l.pathname,y)&&c.waitUntil?.(rr(s,m.status>=400?"fail":"ok")),m},ar=async({args:a,env:s,functionPath:l,request:c,shardKey:m,waitUntil:y})=>{Tt(a,"REST");const v={functionPath:l,...m===void 0?{}:{shardKey:m}},{headers:f,identity:S}=await de(c,s,o);await Re(v,S);const T=m??n,q=Ee(s,c,y),C=()=>ke(c,l,a,T,f,q),$=yt(v,e);return $&&e.x402Charge?e.x402Charge(c,{functionPath:l,price:$.price},C,ft({waitUntil:y})):C()},or=Tr({functions:e.functions??{},invoke:ar,readJsonBody:ee,...e.restRateLimit?{rateLimit:e.restRateLimit}:{}}),Ie=e.routes!==void 0&&Object.keys(e.routes).length>0?e.routes:void 0,sr={[Ma]:a=>a.method!=="GET"&&a.method!=="HEAD"?new Response(void 0,{headers:{allow:"GET, HEAD"},status:405}):Response.json({ok:!0},{headers:{"cache-control":"no-store"}}),[$a]:(a,s,l)=>Mt(a,s,l),[pt]:(a,s,l,c)=>Jt(a,s,c),[Ba]:(a,s,l,c)=>Vt(a,s,c),[La]:(a,s)=>M(a,s),[Ka]:(a,s)=>P(a,s),[Ga]:async a=>{L(a,"POST","ws-token"),B(a);const s=w();if(s===void 0)throw new i("ws-token minting requires a configured admin token",{code:"ADMIN_TOKEN_NOT_CONFIGURED",status:400});const l=await Jr(s);return Response.json(l,{headers:{"cache-control":"no-store"}})},...N,...he,...ve,...se,...Ct,...xt,...jt,...Bt,...$t,...Kt,...or,...Zr({assertAdmin:B,getAuthAdmin:()=>e.authAdmin,parsePaging:pe,queryParameter:ae,readJsonBody:ee})};let ie=Xe(e.security),Me=!1;const ir=a=>{Me||(Me=!0,ie=Xe(e.security,a??{}))},cr=async(a,s)=>{if(!(e.adminGate===void 0||!za(s)))try{await e.adminGate(a)&&k.add(a)}catch{}},dr=async(a,s,l)=>{const c=new URL(a.url);if(a.method==="POST"||a.method==="PUT"){const f=Number(a.headers.get("content-length")??""),S=xa[c.pathname]??Et;if(Number.isFinite(f)&&f>S)throw new i("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413})}const m=await nr(a,s,c,l);if(m)return m;if(Ie){const f=`${a.method} ${c.pathname}`,S=Ie[f]??Ie[c.pathname];if(S)return S(a,s,l)}const y=sr[c.pathname];return y?(await cr(a,c.pathname),y(a,s,c,l)):e.voiceAgents!==void 0&&c.pathname.startsWith(wt)?zt(a,s,c):await Qt(a,s,l)||new Response("Not found",{status:404})};return{async fetch(a,s,l){e.passThroughOnException&&l.passThroughOnException?.(),ir(s),b(s);const c=Nr(a,ie);if(c)return c;const m=qr(a,ie);if(m)return qe(m,a,ie);try{const y=await dr(a,s,l);return qe(y,a,ie)}catch(y){return qe(Je(y),a,ie)}finally{Ve(e.observability,gt(l))}},async queue(a,s,l){await Qe(`queue:${eo(a)}`,l,async()=>{await e.queue?.(a,s,l)})},async scheduled(a,s,l){await Qe(`cron:${a.cron}`,l,async()=>{await tr(a,s,l)})},serverQuery:Yt}},fo=e=>qt(e),mo=e=>typeof e=="function"?{fetch:e}:e,wo=e=>!!(e.crons??e.cronJobs??e.backupCron),No=(e,t)=>{const r=mo(e),n=typeof e=="object"&&typeof e.scheduled=="function"?e.scheduled:void 0,o=u=>{const h=fo({...u,httpRouter:r});return n!==void 0&&!wo(u)?{...h,scheduled:async(w,R,I)=>{await n(w,R,I)}}:h};if(typeof t!="function")return o(t);const d=t;return{fetch:(u,h,w)=>o(d(h)).fetch(u,h,w),queue:(u,h,w)=>o(d(h)).queue?.(u,h,w)??Promise.resolve(),scheduled:(u,h,w)=>o(d(h)).scheduled(u,h,w),serverQuery:(u,h,w,R,I)=>o(d(h)).serverQuery(u,h,w,R,I)}},go=(e,t)=>{if(typeof e=="function")return e(t);const r=e.shardDO??t?.SHARD;if(!r)throw new i("@lunora/runtime: no shard Durable Object namespace found. Bind `SHARD` in wrangler.jsonc, or pass `createLunoraHandler({ shardDO: env.MY_SHARD })`.");return{...e,shardDO:r}},qo=(e={})=>(t,r,n)=>qt(go(e,r)).fetch(t,r,n??mr),Co=e=>e;export{en as GET_AUTH_AUDIT_LOG_OP,mr as NOOP_EXECUTION_CONTEXT,Bo as composeIdentityResolvers,fo as composeWorker,qo as createLunoraHandler,qt as createWorker,Co as defineRpcEnvelope,io as probeRelayCount,go as resolveLunoraOptions,$o as routeIdentityResolvers,No as withFrameworkWorker};
@@ -1 +1 @@
1
- import{o as E,a as C}from"./base64-DPPVK6s_.mjs";import{LunoraError as A}from"./LunoraError-ByasbDmd.mjs";import{resolveShard as q}from"./applyJurisdiction-8bzZjAPR.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 A('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 A('groupBy({ agg: { op: "avg" } }) is not supported across shards in v1 — fan out sum + count separately',{code:"BAD_REQUEST",status:400})},B=16,F=5e3,f=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}},D=(r,e)=>r?"failed":e?"in_progress":"completed",R=r=>{const e=[];let s=0,a=0,t=0,o=0,n=!1,i=!1;for(const u of r){if(u.kind==="err"){a+=1,e.push({error:{message:u.message,timedOut:u.timedOut},shardKey:u.shardKey});continue}s+=1;const d=f(u.value),c=I(d);t+=c.changed,o+=c.processed,n||=c.status==="in_progress",i||=c.status==="failed",e.push({result:d,shardKey:u.shardKey})}return{changed:t,failed:a,ok:s,processed:o,shards:e,status:D(i,n||a>0)}},V=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}},$=r=>{const e=[];let s=0,a=0,t=0,o=0;for(const n of r){if(n.kind==="err"){a+=1,e.push({error:{message:n.message,timedOut:n.timedOut},shardKey:n.shardKey});continue}s+=1;const i=V(f(n.value));t+=i.before,o+=i.total,e.push({result:i,shardKey:n.shardKey})}return{failed:a,ok:s,partial:a>0,position:t+1,shards:e,total:o}},T=0,j=1,J=2,b=(r,e)=>r<e?-1:r>e?1:0,M=r=>r==null?T:typeof r=="number"?j:J,O=(r,e)=>{const s=M(r),a=M(e);return s!==a?s<a?-1:1:s===T?0:s===j?b(r,e):b(String(r),String(e))},Q=(r,e,s)=>{const a=O(r.partitionKey,e.partitionKey);if(a!==0)return a;const t=Math.max(r.sortValues.length,e.sortValues.length);for(let o=0;o<t;o+=1){const n=O(r.sortValues[o],e.sortValues[o]);if(n!==0)return s[o]==="desc"?-n:n}return O(r.rowId,e.rowId)},L=r=>C(new TextEncoder().encode(JSON.stringify(r))),U=r=>{try{const e=JSON.parse(new TextDecoder().decode(E(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:{}}},G=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}},Y=(r,e)=>{let s;for(const a of r){const t=a.rows[a.head];t!==void 0&&(s===void 0||Q(t.key,s.row.key,e)<0)&&(s={row:t,slice:a})}return s},z=(r,e)=>{let s=!1;const a=new Set;for(const o of r)a.add(o.shardKey),(o.head<o.rows.length||o.hasMore)&&(s=!0);const t={...e};for(const o of Object.keys(e))a.has(o)||(s=!0);return s?L({perShard:t}):null},H=(r,e,s,a)=>{const t=[],o={...a};for(;t.length<e;){const i=Y(r,s);if(i===void 0)break;t.push(i.row.doc),o[i.slice.shardKey]=i.row.key,i.slice.head+=1}const n=z(r,o);return{isDone:n===null,nextCursor:n,page:t}},W=r=>{const e=[];let s=0,a=0;for(const t of r){if(t.kind==="err"){a+=1,e.push({error:{message:t.message,timedOut:t.timedOut},shardKey:t.shardKey});continue}s+=1;const o=f(t.value),n=Array.isArray(o?.rows)?o.rows:[];e.push({rows:n,shardKey:t.shardKey})}return{failed:a,ok:s,shards:e}},X=r=>{const e=[];let s=0,a=0;for(const{outcome:t,sinceSeq:o}of r){if(t.kind==="err"){a+=1,e.push({cursor:o,error:{message:t.message,timedOut:t.timedOut},shardKey:t.shardKey});continue}s+=1;const n=f(t.value),i=Array.isArray(n?.changes)?n.changes:[],u=typeof n?.cursor=="number"?n.cursor:o;e.push({changes:i,cursor:u,shardKey:t.shardKey})}return{failed:a,ok:s,shards:e}},Z=r=>{let e=0,s=0,a=0;for(const t of r){if(t.kind==="err"){s+=1;continue}e+=1;const o=f(t.value);a+=typeof o?.applied=="number"?o.applied:0}return{applied:a,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,a=0;for(const t of r){if(t.kind==="err"){a+=1,e.push({requests:0,shardKey:t.shardKey});continue}s+=1,e.push({requests:ee(f(t.value)),shardKey:t.shardKey})}return{failed:a,ok:s,shards:e}},te=r=>{const e=[],s={},a=[];let t=0,o=0,n=0;for(const i of r){if(i.kind==="err"){n+=1,e.push({error:{message:i.message,timedOut:i.timedOut},shardKey:i.shardKey});continue}o+=1;const u=f(i.value),d=u?.inserted??{};for(const[l,y]of Object.entries(d))s[l]=(s[l]??0)+y;const c=u?.errors;Array.isArray(c)&&a.push(...c),t+=u?.conflicts??0,e.push({result:{conflicts:u?.conflicts??0,errors:u?.errors??[],inserted:d},shardKey:i.shardKey})}return{conflicts:t,errors:a,failed:n,inserted:s,ok:o,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,a)=>{const t=q(r,e),o=new AbortController,n=new Request("https://shard.internal/rpc",{body:s.body,headers:s.headers,method:"POST",signal:o.signal});let i;const u=new Promise(c=>{i=setTimeout(()=>{try{o.abort()}catch{}c({kind:"err",message:`shard "${e}" timed out after ${String(a)}ms`,shardKey:e,timedOut:!0})},a)}),d=(async()=>{try{const c=await t.fetch(n);if(!c.ok)return{kind:"err",message:`shard "${e}" returned ${String(c.status)}`,shardKey:e,timedOut:!1};const l=await c.json();return{kind:"ok",shardKey:e,value:l}}catch(c){const l=c instanceof Error?c.message:String(c);return{kind:"err",message:`shard "${e}" threw: ${l}`,shardKey:e,timedOut:!1}}})();try{return await Promise.race([d,u])}finally{i!==void 0&&clearTimeout(i)}},w=async(r,e,s)=>{if(r.length===0)return[];const a=Array.from({length:r.length});let t=0;const o=async()=>{for(;;){const i=t;t+=1;const u=r[i];if(i>=r.length||u===void 0)return;a[i]=await s(u,i)}},n=Math.min(e,r.length);return await Promise.all(Array.from({length:n},()=>o())),a},P=async(r,e)=>{const s=await Promise.all(e.map(async a=>r.listShardKeys(a)));return[...new Set(s.flat())]},m=async(r,e,s,a,t)=>{const o=p(s);return w(e,a,async n=>g(r,n,o,t))},se=r=>{const e={};for(const s of Object.keys(r).toSorted(b))e[s]=r[s]??null;return JSON.stringify(e)},ae=r=>r.flatMap(e=>Array.isArray(e)?e:[]),oe=(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}},ne=(r,e,s)=>{if(e===null||typeof e!="object")return;const a=e.key??{},t=e.value??null,o=se(a),n=r.get(o);if(!n){r.set(o,{key:a,value:t});return}if(n.value===null){n.value=t;return}t!==null&&(n.value=oe(n.value,t,s))},ie=(r,e)=>{const s=new Map;for(const a of r)if(Array.isArray(a))for(const t of a)ne(s,t,e);return[...s.values()]},N=(r,e)=>{let s=null;for(const a of r)typeof a=="number"&&Number.isFinite(a)&&(s=s===null?a:e(s,a));return s},ue=r=>{let e=0;for(const s of r)typeof s=="number"&&Number.isFinite(s)&&(e+=s);return e},ce=r=>{let e=0,s=0;for(const a of r){if(a===null||typeof a!="object")continue;const t=a;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 o of t){if(o===null||typeof o!="object")continue;const n=o[e.by],i=typeof n=="number"&&Number.isFinite(n)?n:Number.NEGATIVE_INFINITY;s.push({row:o,score:i})}const a=e.direction??"desc";return s.sort((t,o)=>a==="asc"?b(t.score,o.score):b(o.score,t.score)),s.slice(0,e.k).map(t=>t.row)},he=(r,e)=>{switch(e.kind){case"concat":return ae(r);case"first":return r[0];case"groupBy":return ie(r,e.op??"sum");case"max":return N(r,Math.max);case"min":return N(r,Math.min);case"rank":return ce(r);case"sum":return ue(r);case"topK":return de(r,e);default:return r}},ge=r=>{const e=r.maxConcurrency??B,s=r.perShardTimeoutMs??F;if(e<1)throw new A("maxConcurrency must be >= 1",{code:"BAD_REQUEST",status:400});return{async fanOut(a,t){const o=await r.registry.listShardKeys(t.fanOut.table),n=await m(a,o,t,e,s),i=[],u=[];for(const d of n)d.kind==="ok"?i.push(d.value):u.push({message:d.message,shardKey:d.shardKey,timedOut:d.timedOut});return{data:he(i,t.fanOut.merge),errors:u,failed:u.length,ok:i.length}},async orchestrateExport(a,t){const o=await P(r.registry,t.tables),n={args:{...t.args,tables:[...t.tables]},functionPath:"__lunora_admin__:exportShard",headers:t.headers},i=await m(a,o,n,e,s);return W(i)},async orchestrateCdcSync(a,t){const o=await P(r.registry,t.tables),n=t.cursors??{},i=await w(o,e,async u=>{const d=n[u]??0;return{outcome:await g(a,u,p({args:{limit:t.limit,sinceSeq:d},functionPath:"__lunora_admin__:cdcSync",headers:t.headers}),s),sinceSeq:d}});return X(i)},async orchestrateImport(a,t){const{batches:o}=t,n=await w(o,e,async i=>g(a,i.shardKey,p({args:{rows:[...i.rows],startLine:i.startLine??1},functionPath:"__lunora_admin__:importShard",headers:t.headers}),s));return te(n)},async orchestrateApplyCdc(a,t){const{batches:o}=t,n=await w(o,e,async i=>g(a,i.shardKey,p({args:{changes:[...i.changes]},functionPath:"__lunora_admin__:applyCdc",headers:t.headers}),s));return Z(n)},async orchestrateMigration(a,t){const o=await r.registry.listShardKeys(t.table),n=await m(a,o,t,e,s);return R(n)},async orchestrateRank(a,t){const o=await r.registry.listShardKeys(t.table),n={args:{index:t.index,partitionKey:t.partitionKey,rowId:t.rowId,sortValues:[...t.sortValues],table:t.table},functionPath:"__lunora_admin__:rankBefore",headers:t.headers},i=await m(a,o,n,e,s);return $(i)},async orchestrateRankPage(a,t){const o=await r.registry.listShardKeys(t.table),n=Math.max(1,Math.min(1e3,Math.floor(t.take??100))),i=t.directions??[],u=t.cursor?U(t.cursor):{perShard:{}},d=await w(o,e,async h=>{const x=u.perShard[h],_={index:t.index,table:t.table,take:n};t.partitionKey!==void 0&&(_.partitionKey=t.partitionKey),x!==void 0&&(_.after=x);const K=await g(a,h,p({args:_,functionPath:"__lunora_admin__:rankPage",headers:t.headers}),s);if(K.kind==="err")return{error:{message:K.message,timedOut:K.timedOut},shardKey:h};const v=G(f(K.value));return{directions:v.directions,hasMore:v.hasMore,rows:v.rows,shardKey:h}}),c=[];let l=0,y=0,k;for(const h of d){if(h.error){y+=1;continue}l+=1,k===void 0&&h.directions&&h.directions.length>0&&(k=h.directions),c.push({hasMore:h.hasMore??!1,head:0,rows:h.rows??[],shardKey:h.shardKey})}const S=H(c,n,k??i,u.perShard);return{continueCursor:S.nextCursor,failed:y,isDone:S.isDone,ok:l,page:S.page,partial:y>0,shards:d}},async orchestrateShardTraffic(a,t){const o=await r.registry.listShardKeys(t.table),n={functionPath:"__lunora_admin__:getMetrics",headers:t.headers},i=await m(a,o,n,e,s);return re(i)},registry:r.registry}};export{ge as createQueryCoordinator,me as createStaticShardRegistry,pe as mergeStrategyForAggregate};
1
+ import{o as T,a as q}from"./base64-DPPVK6s_.mjs";import{LunoraError as A}from"./LunoraError-ByasbDmd.mjs";import{resolveShard as C}from"./applyJurisdiction-Dsm_m5zW.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 A('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 A('groupBy({ agg: { op: "avg" } }) is not supported across shards in v1 — fan out sum + count separately',{code:"BAD_REQUEST",status:400})},B=16,F=5e3,f=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}},D=(r,e)=>r?"failed":e?"in_progress":"completed",R=r=>{const e=[];let s=0,a=0,t=0,o=0,n=!1,i=!1;for(const u of r){if(u.kind==="err"){a+=1,e.push({error:{message:u.message,timedOut:u.timedOut},shardKey:u.shardKey});continue}s+=1;const d=f(u.value),c=I(d);t+=c.changed,o+=c.processed,n||=c.status==="in_progress",i||=c.status==="failed",e.push({result:d,shardKey:u.shardKey})}return{changed:t,failed:a,ok:s,processed:o,shards:e,status:D(i,n||a>0)}},V=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}},$=r=>{const e=[];let s=0,a=0,t=0,o=0;for(const n of r){if(n.kind==="err"){a+=1,e.push({error:{message:n.message,timedOut:n.timedOut},shardKey:n.shardKey});continue}s+=1;const i=V(f(n.value));t+=i.before,o+=i.total,e.push({result:i,shardKey:n.shardKey})}return{failed:a,ok:s,partial:a>0,position:t+1,shards:e,total:o}},j=0,E=1,J=2,b=(r,e)=>r<e?-1:r>e?1:0,M=r=>r==null?j:typeof r=="number"?E:J,O=(r,e)=>{const s=M(r),a=M(e);return s!==a?s<a?-1:1:s===j?0:s===E?b(r,e):b(String(r),String(e))},Q=(r,e,s)=>{const a=O(r.partitionKey,e.partitionKey);if(a!==0)return a;const t=Math.max(r.sortValues.length,e.sortValues.length);for(let o=0;o<t;o+=1){const n=O(r.sortValues[o],e.sortValues[o]);if(n!==0)return s[o]==="desc"?-n:n}return O(r.rowId,e.rowId)},L=r=>q(new TextEncoder().encode(JSON.stringify(r))),U=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:{}}},G=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}},Y=(r,e)=>{let s;for(const a of r){const t=a.rows[a.head];t!==void 0&&(s===void 0||Q(t.key,s.row.key,e)<0)&&(s={row:t,slice:a})}return s},z=(r,e)=>{let s=!1;const a=new Set;for(const o of r)a.add(o.shardKey),(o.head<o.rows.length||o.hasMore)&&(s=!0);const t={...e};for(const o of Object.keys(e))a.has(o)||(s=!0);return s?L({perShard:t}):null},H=(r,e,s,a)=>{const t=[],o={...a};for(;t.length<e;){const i=Y(r,s);if(i===void 0)break;t.push(i.row.doc),o[i.slice.shardKey]=i.row.key,i.slice.head+=1}const n=z(r,o);return{isDone:n===null,nextCursor:n,page:t}},W=r=>{const e=[];let s=0,a=0;for(const t of r){if(t.kind==="err"){a+=1,e.push({error:{message:t.message,timedOut:t.timedOut},shardKey:t.shardKey});continue}s+=1;const o=f(t.value),n=Array.isArray(o?.rows)?o.rows:[];e.push({rows:n,shardKey:t.shardKey})}return{failed:a,ok:s,shards:e}},X=r=>{const e=[];let s=0,a=0;for(const{outcome:t,sinceSeq:o}of r){if(t.kind==="err"){a+=1,e.push({cursor:o,error:{message:t.message,timedOut:t.timedOut},shardKey:t.shardKey});continue}s+=1;const n=f(t.value),i=Array.isArray(n?.changes)?n.changes:[],u=typeof n?.cursor=="number"?n.cursor:o;e.push({changes:i,cursor:u,shardKey:t.shardKey})}return{failed:a,ok:s,shards:e}},Z=r=>{let e=0,s=0,a=0;for(const t of r){if(t.kind==="err"){s+=1;continue}e+=1;const o=f(t.value);a+=typeof o?.applied=="number"?o.applied:0}return{applied:a,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,a=0;for(const t of r){if(t.kind==="err"){a+=1,e.push({requests:0,shardKey:t.shardKey});continue}s+=1,e.push({requests:ee(f(t.value)),shardKey:t.shardKey})}return{failed:a,ok:s,shards:e}},te=r=>{const e=[],s={},a=[];let t=0,o=0,n=0;for(const i of r){if(i.kind==="err"){n+=1,e.push({error:{message:i.message,timedOut:i.timedOut},shardKey:i.shardKey});continue}o+=1;const u=f(i.value),d=u?.inserted??{};for(const[l,y]of Object.entries(d))s[l]=(s[l]??0)+y;const c=u?.errors;Array.isArray(c)&&a.push(...c),t+=u?.conflicts??0,e.push({result:{conflicts:u?.conflicts??0,errors:u?.errors??[],inserted:d},shardKey:i.shardKey})}return{conflicts:t,errors:a,failed:n,inserted:s,ok:o,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,a)=>{const t=C(r,e),o=new AbortController,n=new Request("https://shard.internal/rpc",{body:s.body,headers:s.headers,method:"POST",signal:o.signal});let i;const u=new Promise(c=>{i=setTimeout(()=>{try{o.abort()}catch{}c({kind:"err",message:`shard "${e}" timed out after ${String(a)}ms`,shardKey:e,timedOut:!0})},a)}),d=(async()=>{try{const c=await t.fetch(n);if(!c.ok)return{kind:"err",message:`shard "${e}" returned ${String(c.status)}`,shardKey:e,timedOut:!1};const l=await c.json();return{kind:"ok",shardKey:e,value:l}}catch(c){const l=c instanceof Error?c.message:String(c);return{kind:"err",message:`shard "${e}" threw: ${l}`,shardKey:e,timedOut:!1}}})();try{return await Promise.race([d,u])}finally{i!==void 0&&clearTimeout(i)}},w=async(r,e,s)=>{if(r.length===0)return[];const a=Array.from({length:r.length});let t=0;const o=async()=>{for(;;){const i=t;t+=1;const u=r[i];if(i>=r.length||u===void 0)return;a[i]=await s(u,i)}},n=Math.min(e,r.length);return await Promise.all(Array.from({length:n},()=>o())),a},P=async(r,e)=>{const s=await Promise.all(e.map(async a=>r.listShardKeys(a)));return[...new Set(s.flat())]},m=async(r,e,s,a,t)=>{const o=p(s);return w(e,a,async n=>g(r,n,o,t))},se=r=>{const e={};for(const s of Object.keys(r).toSorted(b))e[s]=r[s]??null;return JSON.stringify(e)},ae=r=>r.flatMap(e=>Array.isArray(e)?e:[]),oe=(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}},ne=(r,e,s)=>{if(e===null||typeof e!="object")return;const a=e.key??{},t=e.value??null,o=se(a),n=r.get(o);if(!n){r.set(o,{key:a,value:t});return}if(n.value===null){n.value=t;return}t!==null&&(n.value=oe(n.value,t,s))},ie=(r,e)=>{const s=new Map;for(const a of r)if(Array.isArray(a))for(const t of a)ne(s,t,e);return[...s.values()]},N=(r,e)=>{let s=null;for(const a of r)typeof a=="number"&&Number.isFinite(a)&&(s=s===null?a:e(s,a));return s},ue=r=>{let e=0;for(const s of r)typeof s=="number"&&Number.isFinite(s)&&(e+=s);return e},ce=r=>{let e=0,s=0;for(const a of r){if(a===null||typeof a!="object")continue;const t=a;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 o of t){if(o===null||typeof o!="object")continue;const n=o[e.by],i=typeof n=="number"&&Number.isFinite(n)?n:Number.NEGATIVE_INFINITY;s.push({row:o,score:i})}const a=e.direction??"desc";return s.sort((t,o)=>a==="asc"?b(t.score,o.score):b(o.score,t.score)),s.slice(0,e.k).map(t=>t.row)},he=(r,e)=>{switch(e.kind){case"concat":return ae(r);case"first":return r[0];case"groupBy":return ie(r,e.op??"sum");case"max":return N(r,Math.max);case"min":return N(r,Math.min);case"rank":return ce(r);case"sum":return ue(r);case"topK":return de(r,e);default:return r}},ge=r=>{const e=r.maxConcurrency??B,s=r.perShardTimeoutMs??F;if(e<1)throw new A("maxConcurrency must be >= 1",{code:"BAD_REQUEST",status:400});return{async fanOut(a,t){const o=await r.registry.listShardKeys(t.fanOut.table),n=await m(a,o,t,e,s),i=[],u=[];for(const d of n)d.kind==="ok"?i.push(d.value):u.push({message:d.message,shardKey:d.shardKey,timedOut:d.timedOut});return{data:he(i,t.fanOut.merge),errors:u,failed:u.length,ok:i.length}},async orchestrateExport(a,t){const o=await P(r.registry,t.tables),n={args:{...t.args,tables:[...t.tables]},functionPath:"__lunora_admin__:exportShard",headers:t.headers},i=await m(a,o,n,e,s);return W(i)},async orchestrateCdcSync(a,t){const o=await P(r.registry,t.tables),n=t.cursors??{},i=await w(o,e,async u=>{const d=n[u]??0;return{outcome:await g(a,u,p({args:{limit:t.limit,sinceSeq:d},functionPath:"__lunora_admin__:cdcSync",headers:t.headers}),s),sinceSeq:d}});return X(i)},async orchestrateImport(a,t){const{batches:o}=t,n=await w(o,e,async i=>g(a,i.shardKey,p({args:{rows:[...i.rows],startLine:i.startLine??1},functionPath:"__lunora_admin__:importShard",headers:t.headers}),s));return te(n)},async orchestrateApplyCdc(a,t){const{batches:o}=t,n=await w(o,e,async i=>g(a,i.shardKey,p({args:{changes:[...i.changes]},functionPath:"__lunora_admin__:applyCdc",headers:t.headers}),s));return Z(n)},async orchestrateMigration(a,t){const o=await r.registry.listShardKeys(t.table),n=await m(a,o,t,e,s);return R(n)},async orchestrateRank(a,t){const o=await r.registry.listShardKeys(t.table),n={args:{index:t.index,partitionKey:t.partitionKey,rowId:t.rowId,sortValues:[...t.sortValues],table:t.table},functionPath:"__lunora_admin__:rankBefore",headers:t.headers},i=await m(a,o,n,e,s);return $(i)},async orchestrateRankPage(a,t){const o=await r.registry.listShardKeys(t.table),n=Math.max(1,Math.min(1e3,Math.floor(t.take??100))),i=t.directions??[],u=t.cursor?U(t.cursor):{perShard:{}},d=await w(o,e,async h=>{const x=u.perShard[h],_={index:t.index,table:t.table,take:n};t.partitionKey!==void 0&&(_.partitionKey=t.partitionKey),x!==void 0&&(_.after=x);const K=await g(a,h,p({args:_,functionPath:"__lunora_admin__:rankPage",headers:t.headers}),s);if(K.kind==="err")return{error:{message:K.message,timedOut:K.timedOut},shardKey:h};const v=G(f(K.value));return{directions:v.directions,hasMore:v.hasMore,rows:v.rows,shardKey:h}}),c=[];let l=0,y=0,k;for(const h of d){if(h.error){y+=1;continue}l+=1,k===void 0&&h.directions&&h.directions.length>0&&(k=h.directions),c.push({hasMore:h.hasMore??!1,head:0,rows:h.rows??[],shardKey:h.shardKey})}const S=H(c,n,k??i,u.perShard);return{continueCursor:S.nextCursor,failed:y,isDone:S.isDone,ok:l,page:S.page,partial:y>0,shards:d}},async orchestrateShardTraffic(a,t){const o=await r.registry.listShardKeys(t.table),n={functionPath:"__lunora_admin__:getMetrics",headers:t.headers},i=await m(a,o,n,e,s);return re(i)},registry:r.registry}};export{ge as createQueryCoordinator,me as createStaticShardRegistry,pe as mergeStrategyForAggregate};
@@ -1 +1 @@
1
- import{LunoraError as b}from"@lunora/errors";import{f as j,u as E}from"./identity-header-pdXOyDU4.mjs";import{a as w,o as O}from"./base64-DPPVK6s_.mjs";import{applyJurisdiction as N,resolveShard as R}from"./applyJurisdiction-8bzZjAPR.mjs";const i="$lunora.wire$",m=64,v=1024,g="__proto__",S={BigInt64Array,BigUint64Array,Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array},$={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError},I=r=>{if(r===null||typeof r!="object")return!1;const t=Object.getPrototypeOf(r);return t===null||t===Object.prototype},f=(r,t=0)=>{if(t>m)throw new RangeError(`wire-codec: value nesting exceeds the ${m}-level limit`);if(r===void 0)return[i,"undefined"];if(r===null)return null;const l=typeof r;if(l==="bigint")return[i,"bigint",r.toString()];if(l==="number"){const e=r;return Number.isNaN(e)?[i,"nan"]:e===1/0?[i,"inf"]:e===-1/0?[i,"-inf"]:e}if(l!=="object")return r;if(r instanceof Date)return[i,"date",f(r.getTime(),t+1)];if(r instanceof Error){const e=r,o={};for(const s of Object.keys(e))e[s]!==void 0&&(o[s]=f(e[s],t+1));const n=[i,"error",e.name,e.message,o];return e.cause!==void 0&&n.push(f(e.cause,t+1)),n}if(r instanceof URL)return[i,"url",r.href];if(r instanceof Map)return[i,"map",[...r.entries()].map(([e,o])=>[f(e,t+1),f(o,t+1)])];if(r instanceof Set)return[i,"set",[...r].map(e=>f(e,t+1))];if(r instanceof ArrayBuffer)return[i,"bytes",w(new Uint8Array(r)),"ArrayBuffer"];if(ArrayBuffer.isView(r)){const e=r,o=e.constructor.name,n=new Uint8Array(e.buffer,e.byteOffset,e.byteLength);return o==="Uint8Array"?[i,"bytes",w(n)]:[i,"bytes",w(n),o]}if(Array.isArray(r)){const e=r.map(o=>f(o,t+1));return e.length>0&&e[0]===i?[i,"arr",e]:e}if(!I(r)){const e=r.constructor?.name??"value";throw new TypeError(`wire-codec: cannot encode a ${e} 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=r,a={};for(const e of Object.keys(d)){const o=d[e];if(o===void 0)continue;const n=f(o,t+1);e===g?Object.defineProperty(a,e,{configurable:!0,enumerable:!0,value:n,writable:!0}):a[e]=n}return a},u=(r,t=0)=>{if(t>m)throw new RangeError(`wire-codec: value nesting exceeds the ${m}-level limit`);if(r===null||typeof r!="object")return r;if(Array.isArray(r)){if(r[0]===i)switch(r[1]){case"-inf":return-1/0;case"arr":return r[2].map(a=>u(a,t+1));case"bigint":{const a=r[2];if(typeof a!="string"||a.length>v||!/^-?\d+$/.test(a))throw new RangeError(`wire-codec: invalid or over-long bigint (max ${v} digits)`);return BigInt(a)}case"date":return new Date(u(r[2],t+1));case"map":return new Map(r[2].map(([a,e])=>[u(a,t+1),u(e,t+1)]));case"set":return new Set(r[2].map(a=>u(a,t+1)));case"url":return new URL(r[2]);case"error":{const a=r[2],e=r[3],o=(Object.hasOwn($,a)?$[a]:void 0)??Error,n=new o(e);n.name!==a&&Object.defineProperty(n,"name",{configurable:!0,value:a,writable:!0});const s=u(r[4],t+1);for(const c of Object.keys(s))c===g?Object.defineProperty(n,c,{configurable:!0,enumerable:!0,value:s[c],writable:!0}):n[c]=s[c];return r.length>5&&Object.defineProperty(n,"cause",{configurable:!0,value:u(r[5],t+1),writable:!0}),n}case"bytes":{const a=O(r[2]),e=r[3]??"Uint8Array";if(e==="ArrayBuffer")return a.buffer.byteLength===a.byteLength?a.buffer:a.slice().buffer;const o=Object.hasOwn(S,e)?S[e]:void 0;return o?new o(a.slice().buffer):a}case"inf":return 1/0;case"nan":return Number.NaN;case"undefined":return;default:return r.map(a=>u(a,t+1))}return r.map(a=>u(a,t+1))}const l=r,d={};for(const a of Object.keys(l)){const e=u(l[a],t+1);a===g?Object.defineProperty(d,a,{configurable:!0,enumerable:!0,value:e,writable:!0}):d[a]=e}return d},U=r=>{if(typeof r=="string")return r;const t=r?.__lunoraRef;if(typeof t!="string"||t.length===0)throw new b("INTERNAL","createShardClient: expected a generated function reference (api.*/internal.*) or a 'namespace:fn' string");return t},x=r=>{const t=new b(r.code,r.message);return r.data!==void 0&&(t.data=u(r.data)),t},L=(r,t={})=>{const l=N(r,t.jurisdiction),d=t.system??!0,a=e=>L(r,{...t,...e});return{as:e=>a({as:e}),asSystem:()=>a({as:void 0}),call:async(e,o,n)=>{const s=U(e),c=n?.shardKey??t.shardKey;if(c===void 0||c.length===0)throw new b("INTERNAL",`createShardClient: no shard key for "${s}" — pass one to createShardClient({ shardKey }), .forShard(key), or the call's options`);const p={"content-type":"application/json"};d&&(p["x-lunora-system"]="1"),t.as&&(p["x-lunora-userid"]=j(t.as.userId),t.as.claims&&(p["x-lunora-identity"]=E(t.as.claims))),n?.mutationId!==void 0&&n.mutationId.length>0&&(p["x-lunora-mutation-id"]=n.mutationId);const y=await R(l,c).fetch(new Request("https://shard.internal/rpc",{body:JSON.stringify({args:f(o??{}),functionPath:s}),headers:p,method:"POST"})),A=y.statusText?` ${y.statusText}`:"";let h;try{h=await y.json()}catch{throw new b("INTERNAL",`createShardClient: shard response for "${s}" was not JSON (status ${String(y.status)}${A})`)}if("error"in h)throw x(h.error);if(!y.ok)throw new b("INTERNAL",`createShardClient: shard call "${s}" failed (status ${String(y.status)}${A})`);return u(h.result)},forShard:e=>a({shardKey:e})}};export{L as createShardClient};
1
+ import{LunoraError as b}from"@lunora/errors";import{f as j,u as E}from"./identity-header-pdXOyDU4.mjs";import{a as w,o as O}from"./base64-DPPVK6s_.mjs";import{applyJurisdiction as N,resolveShard as R}from"./applyJurisdiction-Dsm_m5zW.mjs";const i="$lunora.wire$",m=64,v=1024,g="__proto__",S={BigInt64Array,BigUint64Array,Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array},$={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError},I=r=>{if(r===null||typeof r!="object")return!1;const t=Object.getPrototypeOf(r);return t===null||t===Object.prototype},f=(r,t=0)=>{if(t>m)throw new RangeError(`wire-codec: value nesting exceeds the ${m}-level limit`);if(r===void 0)return[i,"undefined"];if(r===null)return null;const l=typeof r;if(l==="bigint")return[i,"bigint",r.toString()];if(l==="number"){const e=r;return Number.isNaN(e)?[i,"nan"]:e===1/0?[i,"inf"]:e===-1/0?[i,"-inf"]:e}if(l!=="object")return r;if(r instanceof Date)return[i,"date",f(r.getTime(),t+1)];if(r instanceof Error){const e=r,o={};for(const s of Object.keys(e))e[s]!==void 0&&(o[s]=f(e[s],t+1));const n=[i,"error",e.name,e.message,o];return e.cause!==void 0&&n.push(f(e.cause,t+1)),n}if(r instanceof URL)return[i,"url",r.href];if(r instanceof Map)return[i,"map",[...r.entries()].map(([e,o])=>[f(e,t+1),f(o,t+1)])];if(r instanceof Set)return[i,"set",[...r].map(e=>f(e,t+1))];if(r instanceof ArrayBuffer)return[i,"bytes",w(new Uint8Array(r)),"ArrayBuffer"];if(ArrayBuffer.isView(r)){const e=r,o=e.constructor.name,n=new Uint8Array(e.buffer,e.byteOffset,e.byteLength);return o==="Uint8Array"?[i,"bytes",w(n)]:[i,"bytes",w(n),o]}if(Array.isArray(r)){const e=r.map(o=>f(o,t+1));return e.length>0&&e[0]===i?[i,"arr",e]:e}if(!I(r)){const e=r.constructor?.name??"value";throw new TypeError(`wire-codec: cannot encode a ${e} 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=r,a={};for(const e of Object.keys(d)){const o=d[e];if(o===void 0)continue;const n=f(o,t+1);e===g?Object.defineProperty(a,e,{configurable:!0,enumerable:!0,value:n,writable:!0}):a[e]=n}return a},u=(r,t=0)=>{if(t>m)throw new RangeError(`wire-codec: value nesting exceeds the ${m}-level limit`);if(r===null||typeof r!="object")return r;if(Array.isArray(r)){if(r[0]===i)switch(r[1]){case"-inf":return-1/0;case"arr":return r[2].map(a=>u(a,t+1));case"bigint":{const a=r[2];if(typeof a!="string"||a.length>v||!/^-?\d+$/.test(a))throw new RangeError(`wire-codec: invalid or over-long bigint (max ${v} digits)`);return BigInt(a)}case"date":return new Date(u(r[2],t+1));case"map":return new Map(r[2].map(([a,e])=>[u(a,t+1),u(e,t+1)]));case"set":return new Set(r[2].map(a=>u(a,t+1)));case"url":return new URL(r[2]);case"error":{const a=r[2],e=r[3],o=(Object.hasOwn($,a)?$[a]:void 0)??Error,n=new o(e);n.name!==a&&Object.defineProperty(n,"name",{configurable:!0,value:a,writable:!0});const s=u(r[4],t+1);for(const c of Object.keys(s))c===g?Object.defineProperty(n,c,{configurable:!0,enumerable:!0,value:s[c],writable:!0}):n[c]=s[c];return r.length>5&&Object.defineProperty(n,"cause",{configurable:!0,value:u(r[5],t+1),writable:!0}),n}case"bytes":{const a=O(r[2]),e=r[3]??"Uint8Array";if(e==="ArrayBuffer")return a.buffer.byteLength===a.byteLength?a.buffer:a.slice().buffer;const o=Object.hasOwn(S,e)?S[e]:void 0;return o?new o(a.slice().buffer):a}case"inf":return 1/0;case"nan":return Number.NaN;case"undefined":return;default:return r.map(a=>u(a,t+1))}return r.map(a=>u(a,t+1))}const l=r,d={};for(const a of Object.keys(l)){const e=u(l[a],t+1);a===g?Object.defineProperty(d,a,{configurable:!0,enumerable:!0,value:e,writable:!0}):d[a]=e}return d},U=r=>{if(typeof r=="string")return r;const t=r?.__lunoraRef;if(typeof t!="string"||t.length===0)throw new b("INTERNAL","createShardClient: expected a generated function reference (api.*/internal.*) or a 'namespace:fn' string");return t},x=r=>{const t=new b(r.code,r.message);return r.data!==void 0&&(t.data=u(r.data)),t},L=(r,t={})=>{const l=N(r,t.jurisdiction),d=t.system??!0,a=e=>L(r,{...t,...e});return{as:e=>a({as:e}),asSystem:()=>a({as:void 0}),call:async(e,o,n)=>{const s=U(e),c=n?.shardKey??t.shardKey;if(c===void 0||c.length===0)throw new b("INTERNAL",`createShardClient: no shard key for "${s}" — pass one to createShardClient({ shardKey }), .forShard(key), or the call's options`);const p={"content-type":"application/json"};d&&(p["x-lunora-system"]="1"),t.as&&(p["x-lunora-userid"]=j(t.as.userId),t.as.claims&&(p["x-lunora-identity"]=E(t.as.claims))),n?.mutationId!==void 0&&n.mutationId.length>0&&(p["x-lunora-mutation-id"]=n.mutationId);const y=await R(l,c).fetch(new Request("https://shard.internal/rpc",{body:JSON.stringify({args:f(o??{}),functionPath:s}),headers:p,method:"POST"})),A=y.statusText?` ${y.statusText}`:"";let h;try{h=await y.json()}catch{throw new b("INTERNAL",`createShardClient: shard response for "${s}" was not JSON (status ${String(y.status)}${A})`)}if("error"in h)throw x(h.error);if(!y.ok)throw new b("INTERNAL",`createShardClient: shard call "${s}" failed (status ${String(y.status)}${A})`);return u(h.result)},forShard:e=>a({shardKey:e})}};export{L as createShardClient};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/runtime",
3
- "version": "1.0.0-alpha.56",
3
+ "version": "1.0.0-alpha.57",
4
4
  "description": "Lunora Worker runtime: the RPC router, shard resolver, and query coordinator",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -46,9 +46,9 @@
46
46
  "access": "public"
47
47
  },
48
48
  "dependencies": {
49
- "@lunora/bindings": "1.0.0-alpha.22",
49
+ "@lunora/bindings": "1.0.0-alpha.23",
50
50
  "@lunora/errors": "1.0.0-alpha.16",
51
- "@lunora/platform": "1.0.0-alpha.6"
51
+ "@lunora/platform": "1.0.0-alpha.7"
52
52
  },
53
53
  "engines": {
54
54
  "node": "^22.15.0 || >=24.11.0"
@@ -1 +0,0 @@
1
- import{resolveShard as s}from"@lunora/platform";const n=new WeakMap,d=o=>{const r=n.get(o);if(r!==void 0)return r;const t=typeof o.jurisdiction=="function"?i=>d(o.jurisdiction(i)):void 0,e=typeof o.getByName=="function"?{get:i=>o.get(i),getByName:i=>o.getByName(i),idForName:i=>o.idFromName(i),jurisdiction:t}:{get:i=>o.get(i),idForName:i=>o.idFromName(i),jurisdiction:t};return n.set(o,e),e},a=(o,r)=>{if(r===void 0)return o;if(typeof o.jurisdiction!="function")throw new TypeError(`@lunora/runtime: Durable Object namespace does not support jurisdiction("${r}") — update @cloudflare/workers-types or remove the jurisdiction option`);return o.jurisdiction(r)},c=(o,r)=>s(d(o),r);export{a as applyJurisdiction,c as resolveShard};