@lunora/runtime 1.0.0-alpha.42 → 1.0.0-alpha.44
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 +83 -35
- package/dist/index.d.ts +83 -35
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/applyRestCache-DwBDPRf6.mjs +1 -0
- package/dist/packem_shared/argsFromQuery-BkJXnIpe.mjs +1 -0
- package/dist/packem_shared/{composeWorker-IO6LYYK2.mjs → composeWorker-i1cHDFrr.mjs} +2 -2
- package/dist/packem_shared/rest-cache-5unAzdFN.mjs +1 -0
- package/package.json +3 -3
- package/dist/packem_shared/argsFromQuery-0KrWTkNx.mjs +0 -1
package/dist/index.d.mts
CHANGED
|
@@ -150,6 +150,61 @@ interface ExecutionContextLike {
|
|
|
150
150
|
* receives a valid third argument.
|
|
151
151
|
*/
|
|
152
152
|
declare const NOOP_EXECUTION_CONTEXT: ExecutionContextLike;
|
|
153
|
+
/** Procedure kinds that can be exposed over REST (`stream` cannot — it is a WebSocket surface). */
|
|
154
|
+
type RestFunctionKind = "action" | "mutation" | "query";
|
|
155
|
+
/**
|
|
156
|
+
* Declared HTTP caching for an exposed endpoint (`.expose({ cache })`). Lives
|
|
157
|
+
* here, alongside the path/method contract, for the same reason: the runtime
|
|
158
|
+
* WRITES these headers and the OpenAPI emitter DESCRIBES them, and the two must
|
|
159
|
+
* not be able to disagree. Deriving both from {@link cacheControlValue} /
|
|
160
|
+
* {@link cacheVaryValue} makes "the published spec matches what the runtime
|
|
161
|
+
* actually sends" structural rather than a hand-kept invariant.
|
|
162
|
+
*/
|
|
163
|
+
interface RestCachePolicy {
|
|
164
|
+
/**
|
|
165
|
+
* Extra request headers this app authenticates on, beyond
|
|
166
|
+
* {@link CREDENTIAL_HEADERS}. Declare these whenever `resolveIdentity` reads
|
|
167
|
+
* something else (`x-api-key`, a tenant header, …): they join both the
|
|
168
|
+
* credential check and the emitted `Vary`. Without them, a caller
|
|
169
|
+
* authenticating that way is treated as anonymous.
|
|
170
|
+
*/
|
|
171
|
+
readonly credentialHeaders?: ReadonlyArray<string>;
|
|
172
|
+
readonly maxAge: number;
|
|
173
|
+
readonly scope: "private" | "public";
|
|
174
|
+
readonly staleWhileRevalidate?: number;
|
|
175
|
+
readonly tag?: string;
|
|
176
|
+
readonly vary?: string;
|
|
177
|
+
}
|
|
178
|
+
/**
|
|
179
|
+
* The `.expose({ rest: true })` tag stamped onto a registered procedure (runtime,
|
|
180
|
+
* as `fn.expose`) or discovered from its builder chain (codegen, onto the
|
|
181
|
+
* `FunctionIR`). Presence of `rest === true` is the ONLY thing that opts a
|
|
182
|
+
* procedure into the surface — everything is default-closed.
|
|
183
|
+
*/
|
|
184
|
+
interface RestExposure {
|
|
185
|
+
cache?: RestCachePolicy;
|
|
186
|
+
rest?: boolean;
|
|
187
|
+
}
|
|
188
|
+
/** One resolved REST endpoint: the transport method + URL path a procedure is reachable at. */
|
|
189
|
+
interface RestSurfaceEntry {
|
|
190
|
+
functionPath: string;
|
|
191
|
+
kind: RestFunctionKind;
|
|
192
|
+
method: "GET" | "POST";
|
|
193
|
+
name: string;
|
|
194
|
+
namespace: string;
|
|
195
|
+
path: string;
|
|
196
|
+
}
|
|
197
|
+
/**
|
|
198
|
+
* Resolve the full REST surface from a list of procedures, filtering to the ones
|
|
199
|
+
* opted in via `.expose({ rest: true })`. The single source of truth both the
|
|
200
|
+
* runtime router and the OpenAPI emitter derive from — a `stream` procedure or a
|
|
201
|
+
* malformed path is skipped. Ordered by path for stable enumeration.
|
|
202
|
+
*/
|
|
203
|
+
declare const describeRestSurface: (procedures: ReadonlyArray<{
|
|
204
|
+
exposure?: RestExposure;
|
|
205
|
+
functionPath: string;
|
|
206
|
+
kind: "action" | "mutation" | "query" | "stream";
|
|
207
|
+
}>) => RestSurfaceEntry[];
|
|
153
208
|
/**
|
|
154
209
|
* Trace-sampling configuration — the `sampling` block on the worker's
|
|
155
210
|
* observability options.
|
|
@@ -2223,37 +2278,6 @@ declare const emitRpcEvent: (sink: ObservabilitySink | undefined, event: Observa
|
|
|
2223
2278
|
* never break the handler that emitted the line.
|
|
2224
2279
|
*/
|
|
2225
2280
|
declare const emitLogEvent: (sink: ObservabilitySink | undefined, event: LogEvent, context?: ObservabilitySinkContext) => void;
|
|
2226
|
-
/** Procedure kinds that can be exposed over REST (`stream` cannot — it is a WebSocket surface). */
|
|
2227
|
-
type RestFunctionKind = "action" | "mutation" | "query";
|
|
2228
|
-
/**
|
|
2229
|
-
* The `.expose({ rest: true })` tag stamped onto a registered procedure (runtime,
|
|
2230
|
-
* as `fn.expose`) or discovered from its builder chain (codegen, onto the
|
|
2231
|
-
* `FunctionIR`). Presence of `rest === true` is the ONLY thing that opts a
|
|
2232
|
-
* procedure into the surface — everything is default-closed.
|
|
2233
|
-
*/
|
|
2234
|
-
interface RestExposure {
|
|
2235
|
-
rest?: boolean;
|
|
2236
|
-
}
|
|
2237
|
-
/** One resolved REST endpoint: the transport method + URL path a procedure is reachable at. */
|
|
2238
|
-
interface RestSurfaceEntry {
|
|
2239
|
-
functionPath: string;
|
|
2240
|
-
kind: RestFunctionKind;
|
|
2241
|
-
method: "GET" | "POST";
|
|
2242
|
-
name: string;
|
|
2243
|
-
namespace: string;
|
|
2244
|
-
path: string;
|
|
2245
|
-
}
|
|
2246
|
-
/**
|
|
2247
|
-
* Resolve the full REST surface from a list of procedures, filtering to the ones
|
|
2248
|
-
* opted in via `.expose({ rest: true })`. The single source of truth both the
|
|
2249
|
-
* runtime router and the OpenAPI emitter derive from — a `stream` procedure or a
|
|
2250
|
-
* malformed path is skipped. Ordered by path for stable enumeration.
|
|
2251
|
-
*/
|
|
2252
|
-
declare const describeRestSurface: (procedures: ReadonlyArray<{
|
|
2253
|
-
exposure?: RestExposure;
|
|
2254
|
-
functionPath: string;
|
|
2255
|
-
kind: "action" | "mutation" | "query" | "stream";
|
|
2256
|
-
}>) => RestSurfaceEntry[];
|
|
2257
2281
|
/** The bits of a registered function the REST router reads: its kind and its `.expose` tag. */
|
|
2258
2282
|
interface RestRegistryEntry {
|
|
2259
2283
|
expose?: RestExposure;
|
|
@@ -2729,10 +2753,11 @@ interface FunctionRegistryEntry {
|
|
|
2729
2753
|
* routing THROUGH the procedure so auth/RLS/validators are enforced. Rides
|
|
2730
2754
|
* along on the registered function's identity (like `fn.x402` / `fn.rls`), so
|
|
2731
2755
|
* reading it needs no change to the generated registry shape.
|
|
2756
|
+
*
|
|
2757
|
+
* `cache` is the optional response-caching policy the REST router turns into
|
|
2758
|
+
* `Cache-Control` / `Cache-Tag` / `Vary` headers (see `rest-cache`).
|
|
2732
2759
|
*/
|
|
2733
|
-
expose?:
|
|
2734
|
-
readonly rest?: boolean;
|
|
2735
|
-
};
|
|
2760
|
+
expose?: RestExposure;
|
|
2736
2761
|
/**
|
|
2737
2762
|
* The generated registry carries `"stream"` alongside query/mutation/action;
|
|
2738
2763
|
* the discovery endpoint surfaces the latter three only (a `stream` function
|
|
@@ -4449,6 +4474,29 @@ declare const otlpSink: (options: OtlpSinkOptions) => ObservabilitySink;
|
|
|
4449
4474
|
* @param sinks The sinks to fan out to.
|
|
4450
4475
|
*/
|
|
4451
4476
|
declare const combineSinks: (...sinks: ObservabilitySink[]) => ObservabilitySink;
|
|
4477
|
+
/**
|
|
4478
|
+
* True when the request presented credentials, i.e. the response must be treated
|
|
4479
|
+
* as caller-specific. Checks the built-in identity headers plus anything the
|
|
4480
|
+
* policy declares via `credentialHeaders` — an app whose `resolveIdentity` reads
|
|
4481
|
+
* a bespoke header must say so, or its callers read as anonymous here.
|
|
4482
|
+
*/
|
|
4483
|
+
declare const requestCarriesCredentials: (request: Request, policy: RestCachePolicy) => boolean;
|
|
4484
|
+
/**
|
|
4485
|
+
* Build the cache headers for one exchange, or `undefined` when the exchange
|
|
4486
|
+
* isn't cacheable at all (non-`GET`, or a non-2xx result — an error body must
|
|
4487
|
+
* never be stored as if it were the resource).
|
|
4488
|
+
*
|
|
4489
|
+
* The effective scope is `policy.scope` narrowed by {@link requestCarriesCredentials};
|
|
4490
|
+
* `"public"` survives only for a genuinely anonymous request.
|
|
4491
|
+
*/
|
|
4492
|
+
declare const restCacheHeaders: (policy: RestCachePolicy, request: Request, status: number) => Record<string, string> | undefined;
|
|
4493
|
+
/**
|
|
4494
|
+
* Return `response` with the declared cache headers applied. A shard `Response`
|
|
4495
|
+
* has immutable headers, so this rebuilds it (status/statusText/existing headers
|
|
4496
|
+
* are carried over, the body is streamed through untouched). When the exchange
|
|
4497
|
+
* isn't cacheable the original response is returned as-is — no copy.
|
|
4498
|
+
*/
|
|
4499
|
+
declare const applyRestCache: (response: Response, policy: RestCachePolicy | undefined, request: Request) => Response;
|
|
4452
4500
|
/**
|
|
4453
4501
|
* Structural mirror of `@lunora/client`'s `FunctionReference`, re-declared so this
|
|
4454
4502
|
* module carries no `runtime → client` (browser SDK) dependency. The phantom
|
|
@@ -4533,4 +4581,4 @@ interface ShardClient {
|
|
|
4533
4581
|
*/
|
|
4534
4582
|
declare const createShardClient: (namespace: ShardNamespaceLike, options?: ShardClientOptions) => ShardClient;
|
|
4535
4583
|
declare const VERSION: string;
|
|
4536
|
-
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, 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, resolveLogArchiveFromEnv, resolveLunoraOptions, resolveSecurity, resolveShard, restSurfaceFromRegistry, routeIdentityResolvers, runExportTap, sanitizeChange, sentrySink, toAirbyteMessages, toErrorResponse, toFivetranResponse, webhookExportSink, webhookSink, withFrameworkWorker };
|
|
4584
|
+
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 };
|
package/dist/index.d.ts
CHANGED
|
@@ -150,6 +150,61 @@ interface ExecutionContextLike {
|
|
|
150
150
|
* receives a valid third argument.
|
|
151
151
|
*/
|
|
152
152
|
declare const NOOP_EXECUTION_CONTEXT: ExecutionContextLike;
|
|
153
|
+
/** Procedure kinds that can be exposed over REST (`stream` cannot — it is a WebSocket surface). */
|
|
154
|
+
type RestFunctionKind = "action" | "mutation" | "query";
|
|
155
|
+
/**
|
|
156
|
+
* Declared HTTP caching for an exposed endpoint (`.expose({ cache })`). Lives
|
|
157
|
+
* here, alongside the path/method contract, for the same reason: the runtime
|
|
158
|
+
* WRITES these headers and the OpenAPI emitter DESCRIBES them, and the two must
|
|
159
|
+
* not be able to disagree. Deriving both from {@link cacheControlValue} /
|
|
160
|
+
* {@link cacheVaryValue} makes "the published spec matches what the runtime
|
|
161
|
+
* actually sends" structural rather than a hand-kept invariant.
|
|
162
|
+
*/
|
|
163
|
+
interface RestCachePolicy {
|
|
164
|
+
/**
|
|
165
|
+
* Extra request headers this app authenticates on, beyond
|
|
166
|
+
* {@link CREDENTIAL_HEADERS}. Declare these whenever `resolveIdentity` reads
|
|
167
|
+
* something else (`x-api-key`, a tenant header, …): they join both the
|
|
168
|
+
* credential check and the emitted `Vary`. Without them, a caller
|
|
169
|
+
* authenticating that way is treated as anonymous.
|
|
170
|
+
*/
|
|
171
|
+
readonly credentialHeaders?: ReadonlyArray<string>;
|
|
172
|
+
readonly maxAge: number;
|
|
173
|
+
readonly scope: "private" | "public";
|
|
174
|
+
readonly staleWhileRevalidate?: number;
|
|
175
|
+
readonly tag?: string;
|
|
176
|
+
readonly vary?: string;
|
|
177
|
+
}
|
|
178
|
+
/**
|
|
179
|
+
* The `.expose({ rest: true })` tag stamped onto a registered procedure (runtime,
|
|
180
|
+
* as `fn.expose`) or discovered from its builder chain (codegen, onto the
|
|
181
|
+
* `FunctionIR`). Presence of `rest === true` is the ONLY thing that opts a
|
|
182
|
+
* procedure into the surface — everything is default-closed.
|
|
183
|
+
*/
|
|
184
|
+
interface RestExposure {
|
|
185
|
+
cache?: RestCachePolicy;
|
|
186
|
+
rest?: boolean;
|
|
187
|
+
}
|
|
188
|
+
/** One resolved REST endpoint: the transport method + URL path a procedure is reachable at. */
|
|
189
|
+
interface RestSurfaceEntry {
|
|
190
|
+
functionPath: string;
|
|
191
|
+
kind: RestFunctionKind;
|
|
192
|
+
method: "GET" | "POST";
|
|
193
|
+
name: string;
|
|
194
|
+
namespace: string;
|
|
195
|
+
path: string;
|
|
196
|
+
}
|
|
197
|
+
/**
|
|
198
|
+
* Resolve the full REST surface from a list of procedures, filtering to the ones
|
|
199
|
+
* opted in via `.expose({ rest: true })`. The single source of truth both the
|
|
200
|
+
* runtime router and the OpenAPI emitter derive from — a `stream` procedure or a
|
|
201
|
+
* malformed path is skipped. Ordered by path for stable enumeration.
|
|
202
|
+
*/
|
|
203
|
+
declare const describeRestSurface: (procedures: ReadonlyArray<{
|
|
204
|
+
exposure?: RestExposure;
|
|
205
|
+
functionPath: string;
|
|
206
|
+
kind: "action" | "mutation" | "query" | "stream";
|
|
207
|
+
}>) => RestSurfaceEntry[];
|
|
153
208
|
/**
|
|
154
209
|
* Trace-sampling configuration — the `sampling` block on the worker's
|
|
155
210
|
* observability options.
|
|
@@ -2223,37 +2278,6 @@ declare const emitRpcEvent: (sink: ObservabilitySink | undefined, event: Observa
|
|
|
2223
2278
|
* never break the handler that emitted the line.
|
|
2224
2279
|
*/
|
|
2225
2280
|
declare const emitLogEvent: (sink: ObservabilitySink | undefined, event: LogEvent, context?: ObservabilitySinkContext) => void;
|
|
2226
|
-
/** Procedure kinds that can be exposed over REST (`stream` cannot — it is a WebSocket surface). */
|
|
2227
|
-
type RestFunctionKind = "action" | "mutation" | "query";
|
|
2228
|
-
/**
|
|
2229
|
-
* The `.expose({ rest: true })` tag stamped onto a registered procedure (runtime,
|
|
2230
|
-
* as `fn.expose`) or discovered from its builder chain (codegen, onto the
|
|
2231
|
-
* `FunctionIR`). Presence of `rest === true` is the ONLY thing that opts a
|
|
2232
|
-
* procedure into the surface — everything is default-closed.
|
|
2233
|
-
*/
|
|
2234
|
-
interface RestExposure {
|
|
2235
|
-
rest?: boolean;
|
|
2236
|
-
}
|
|
2237
|
-
/** One resolved REST endpoint: the transport method + URL path a procedure is reachable at. */
|
|
2238
|
-
interface RestSurfaceEntry {
|
|
2239
|
-
functionPath: string;
|
|
2240
|
-
kind: RestFunctionKind;
|
|
2241
|
-
method: "GET" | "POST";
|
|
2242
|
-
name: string;
|
|
2243
|
-
namespace: string;
|
|
2244
|
-
path: string;
|
|
2245
|
-
}
|
|
2246
|
-
/**
|
|
2247
|
-
* Resolve the full REST surface from a list of procedures, filtering to the ones
|
|
2248
|
-
* opted in via `.expose({ rest: true })`. The single source of truth both the
|
|
2249
|
-
* runtime router and the OpenAPI emitter derive from — a `stream` procedure or a
|
|
2250
|
-
* malformed path is skipped. Ordered by path for stable enumeration.
|
|
2251
|
-
*/
|
|
2252
|
-
declare const describeRestSurface: (procedures: ReadonlyArray<{
|
|
2253
|
-
exposure?: RestExposure;
|
|
2254
|
-
functionPath: string;
|
|
2255
|
-
kind: "action" | "mutation" | "query" | "stream";
|
|
2256
|
-
}>) => RestSurfaceEntry[];
|
|
2257
2281
|
/** The bits of a registered function the REST router reads: its kind and its `.expose` tag. */
|
|
2258
2282
|
interface RestRegistryEntry {
|
|
2259
2283
|
expose?: RestExposure;
|
|
@@ -2729,10 +2753,11 @@ interface FunctionRegistryEntry {
|
|
|
2729
2753
|
* routing THROUGH the procedure so auth/RLS/validators are enforced. Rides
|
|
2730
2754
|
* along on the registered function's identity (like `fn.x402` / `fn.rls`), so
|
|
2731
2755
|
* reading it needs no change to the generated registry shape.
|
|
2756
|
+
*
|
|
2757
|
+
* `cache` is the optional response-caching policy the REST router turns into
|
|
2758
|
+
* `Cache-Control` / `Cache-Tag` / `Vary` headers (see `rest-cache`).
|
|
2732
2759
|
*/
|
|
2733
|
-
expose?:
|
|
2734
|
-
readonly rest?: boolean;
|
|
2735
|
-
};
|
|
2760
|
+
expose?: RestExposure;
|
|
2736
2761
|
/**
|
|
2737
2762
|
* The generated registry carries `"stream"` alongside query/mutation/action;
|
|
2738
2763
|
* the discovery endpoint surfaces the latter three only (a `stream` function
|
|
@@ -4449,6 +4474,29 @@ declare const otlpSink: (options: OtlpSinkOptions) => ObservabilitySink;
|
|
|
4449
4474
|
* @param sinks The sinks to fan out to.
|
|
4450
4475
|
*/
|
|
4451
4476
|
declare const combineSinks: (...sinks: ObservabilitySink[]) => ObservabilitySink;
|
|
4477
|
+
/**
|
|
4478
|
+
* True when the request presented credentials, i.e. the response must be treated
|
|
4479
|
+
* as caller-specific. Checks the built-in identity headers plus anything the
|
|
4480
|
+
* policy declares via `credentialHeaders` — an app whose `resolveIdentity` reads
|
|
4481
|
+
* a bespoke header must say so, or its callers read as anonymous here.
|
|
4482
|
+
*/
|
|
4483
|
+
declare const requestCarriesCredentials: (request: Request, policy: RestCachePolicy) => boolean;
|
|
4484
|
+
/**
|
|
4485
|
+
* Build the cache headers for one exchange, or `undefined` when the exchange
|
|
4486
|
+
* isn't cacheable at all (non-`GET`, or a non-2xx result — an error body must
|
|
4487
|
+
* never be stored as if it were the resource).
|
|
4488
|
+
*
|
|
4489
|
+
* The effective scope is `policy.scope` narrowed by {@link requestCarriesCredentials};
|
|
4490
|
+
* `"public"` survives only for a genuinely anonymous request.
|
|
4491
|
+
*/
|
|
4492
|
+
declare const restCacheHeaders: (policy: RestCachePolicy, request: Request, status: number) => Record<string, string> | undefined;
|
|
4493
|
+
/**
|
|
4494
|
+
* Return `response` with the declared cache headers applied. A shard `Response`
|
|
4495
|
+
* has immutable headers, so this rebuilds it (status/statusText/existing headers
|
|
4496
|
+
* are carried over, the body is streamed through untouched). When the exchange
|
|
4497
|
+
* isn't cacheable the original response is returned as-is — no copy.
|
|
4498
|
+
*/
|
|
4499
|
+
declare const applyRestCache: (response: Response, policy: RestCachePolicy | undefined, request: Request) => Response;
|
|
4452
4500
|
/**
|
|
4453
4501
|
* Structural mirror of `@lunora/client`'s `FunctionReference`, re-declared so this
|
|
4454
4502
|
* module carries no `runtime → client` (browser SDK) dependency. The phantom
|
|
@@ -4533,4 +4581,4 @@ interface ShardClient {
|
|
|
4533
4581
|
*/
|
|
4534
4582
|
declare const createShardClient: (namespace: ShardNamespaceLike, options?: ShardClientOptions) => ShardClient;
|
|
4535
4583
|
declare const VERSION: string;
|
|
4536
|
-
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, 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, resolveLogArchiveFromEnv, resolveLunoraOptions, resolveSecurity, resolveShard, restSurfaceFromRegistry, routeIdentityResolvers, runExportTap, sanitizeChange, sentrySink, toAirbyteMessages, toErrorResponse, toFivetranResponse, webhookExportSink, webhookSink, withFrameworkWorker };
|
|
4584
|
+
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 };
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{toAirbyteMessages as t,toFivetranResponse as
|
|
1
|
+
import{toAirbyteMessages as t,toFivetranResponse as a}from"./packem_shared/toAirbyteMessages-DBTuFjb5.mjs";import{composeWorker as s,createLunoraHandler as n,createWorker as p,defineRpcEnvelope as m,resolveLunoraOptions as c,withFrameworkWorker as R}from"./packem_shared/composeWorker-i1cHDFrr.mjs";import{createCrossShardRelationCapabilities as E}from"./packem_shared/createCrossShardRelationCapabilities-CMWiFA5s.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-CsNnfJzB.mjs";import{LunoraError as C,toErrorResponse as L}from"./packem_shared/LunoraError-ByasbDmd.mjs";import{createKvCursorStore as y,createMemoryCursorStore as g,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-BEE0A_lZ.mjs";import{LOG_ARCHIVE_PATH as G,resolveLogArchiveFromEnv as M}from"./packem_shared/LOG_ARCHIVE_PATH-DGsEec3K.mjs";import{memoizeIdentity as w,memoizeIdentityPerRequest as z}from"./packem_shared/memoizeIdentity-CZGtDc4H.mjs";import{e as W,a as Y}from"./packem_shared/observability-DYnm-d4g.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-CUWYuLHs.mjs";import{D as ee,a as re,c as oe}from"./packem_shared/pipeline-log-reader-DU_CCGDA.mjs";import{createQueryCoordinator as ae,createStaticShardRegistry as ie,mergeStrategyForAggregate as se}from"./packem_shared/createQueryCoordinator-DqrEvhPD.mjs";import{applyJurisdiction as pe,resolveShard as me}from"./packem_shared/applyJurisdiction-uRQLx282.mjs";import{R as Re,d as Se,o as Ee}from"./packem_shared/rest-cache-5unAzdFN.mjs";import{argsFromQuery as fe,buildRestRoutes as le,createRestRateLimit as xe,readShardKey as _e,restSurfaceFromRegistry as Ce}from"./packem_shared/argsFromQuery-BkJXnIpe.mjs";import{decorateResponse as ue,enforceOrigin as ye,handleCorsPreflight as ge,resolveSecurity as Te}from"./packem_shared/decorateResponse-DBIWsRSZ.mjs";import{createShardClient as he}from"./packem_shared/createShardClient-62qcYKGl.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,C 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,s as composeWorker,X as consoleSink,E as createCrossShardRelationCapabilities,x as createDynamicShardRegistry,y as createKvCursorStore,n as createLunoraHandler,g as createMemoryCursorStore,oe as createPipelineLogReader,ae as createQueryCoordinator,xe as createRestRateLimit,he as createShardClient,ie as createStaticShardRegistry,p as createWorker,F as d1Probe,ue as decorateResponse,T as defineExportSink,m as defineRpcEnvelope,P as durableObjectProbe,W as emitLogEvent,Y as emitRpcEvent,ye as enforceOrigin,ge as handleCorsPreflight,w as memoizeIdentity,z as memoizeIdentityPerRequest,se as mergeStrategyForAggregate,j as otlpSink,J as pipelineLogSink,D as presenceProbe,A as r2Sink,_e as readShardKey,Se as requestCarriesCredentials,M as resolveLogArchiveFromEnv,c as resolveLunoraOptions,Te as resolveSecurity,me as resolveShard,Ee as restCacheHeaders,Ce as restSurfaceFromRegistry,Fe as routeIdentityResolvers,h as runExportTap,k as sanitizeChange,B as sentrySink,t as toAirbyteMessages,L as toErrorResponse,a as toFivetranResponse,O as webhookExportSink,Z as webhookSink,R as withFrameworkWorker};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{R as s,d as r,o as t}from"./rest-cache-5unAzdFN.mjs";export{s as applyRestCache,r as requestCarriesCredentials,t as restCacheHeaders};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{R as g,a as k}from"./rest-cache-5unAzdFN.mjs";import{d as w}from"./method-guard-BbuR0VfS.mjs";const P=r=>Object.entries(r).map(([e,t])=>({exposure:t.expose,functionPath:e,kind:t.kind})),v=r=>k(P(r)),x=(r,e)=>{const t=r.searchParams.get("shardKey");if(t!==null&&t!=="")return t;const a=e.headers.get("x-lunora-shard-key");return a===null||a===""?void 0:a},S=r=>{const e={};for(const[t,a]of r.searchParams.entries())if(t!=="shardKey")try{e[t]=JSON.parse(a)}catch{e[t]=a}return e},K=r=>{const{functions:e,invoke:t,rateLimit:a,readJsonBody:s}=r,i={};for(const o of v(e)){const l=o.kind==="query"?["GET","POST"]:["POST"],m=e[o.functionPath].expose?.cache;i[o.path]=async(n,p,T,d)=>{const f=w(n,l);if(f)return f;const h=new URL(n.url);if(a){const c=await a(n,o.functionPath);if(c)return c}let u;n.method==="GET"?u=S(h):u=n.body===null?{}:await s(n);const y=x(h,n),R=await t({args:u,env:p,functionPath:o.functionPath,request:n,...y===void 0?{}:{shardKey:y},...d?.waitUntil===void 0?{}:{waitUntil:c=>d.waitUntil?.(c)}});return g(R,m,n)}}return i},L=(r,e)=>async(t,a)=>{const s=e.key?e.key(t,a):t.headers.get("cf-connecting-ip")??void 0,i=await r.limit(e.name,s===void 0?{}:{key:s});if(i.ok)return;const o=Math.max(1,Math.ceil(i.retryAfter/1e3));return Response.json({error:{code:"RATE_LIMITED",message:"Rate limit exceeded"}},{headers:{"content-type":"application/json","retry-after":String(o)},status:429})};export{S as argsFromQuery,K as buildRestRoutes,L as createRestRateLimit,x as readShardKey,v as restSurfaceFromRegistry};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{isLunoraError as rr,toErrorBody as nr}from"@lunora/errors";import{NOOP_EXECUTION_CONTEXT as or}from"./NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{O as Re,m as ar,A as sr,R as ir,d as dr,i as ur,s as cr}from"./otlp-resource-B-ByO9qo.mjs";import{LunoraError as s,toErrorResponse as ze}from"./LunoraError-ByasbDmd.mjs";import{runExportTap as lr}from"./createKvCursorStore-C24tEuYk.mjs";import{d as we}from"./method-guard-BbuR0VfS.mjs";import{buildHealthRoutes as hr,durableObjectProbe as pr,d1Probe as fr,presenceProbe as Pe}from"./HEALTH_PATH-BEE0A_lZ.mjs";import{wrapResolverWithContract as wr}from"./composeIdentityResolvers-DwE0Jbww.mjs";import{composeIdentityResolvers as ma,routeIdentityResolvers as ya}from"./composeIdentityResolvers-DwE0Jbww.mjs";import{buildLogArchiveAdminRoutes as mr}from"./LOG_ARCHIVE_PATH-DGsEec3K.mjs";import{o as yr,f as We,a as de}from"./observability-DYnm-d4g.mjs";import{resolveShard as Se,applyJurisdiction as He}from"./applyJurisdiction-uRQLx282.mjs";import{buildRestRoutes as gr}from"./argsFromQuery-0KrWTkNx.mjs";import{resolveSecurity as Je,handleCorsPreflight as br,enforceOrigin as Or,decorateResponse as Ne,enforceWebSocketOrigin as Ve}from"./decorateResponse-DBIWsRSZ.mjs";const mt=(e,t)=>{if(e.size<t)return;const r=e.keys().next().value;r!==void 0&&e.delete(r)},Er="::relay::",Tr=(e,t)=>`${e}${Er}${String(t)}`,Ce=new TextEncoder,_r=e=>{const t=String.fromCodePoint(...e);return btoa(t).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")},Rr=e=>{const t=e.replaceAll("-","+").replaceAll("_","/")+"===".slice((e.length+3)%4),r=atob(t),n=new Uint8Array(r.length);for(let a=0;a<r.length;a+=1)n[a]=r.codePointAt(a)??0;return n},Sr=64,Ue=new Map,yt=async e=>{const t=Ue.get(e);if(t)return t;mt(Ue,Sr);const r=crypto.subtle.importKey("raw",Ce.encode(e),{hash:"SHA-256",name:"HMAC"},!1,["sign","verify"]);return Ue.set(e,r),r},Ar=async(e,t)=>{const r=await yt(e),n=await crypto.subtle.sign("HMAC",r,Ce.encode(t));return _r(new Uint8Array(n))},vr=async(e,t,r)=>{const n=await yt(e);return crypto.subtle.verify("HMAC",n,r,Ce.encode(t))},gt="v1",Dr=6e4,kr=async(e,t={})=>{const r=(t.now??Date.now())+(t.ttlMs??Dr),n=`${gt}.${String(r)}`,a=await Ar(e,n);return{expiresAtMs:r,token:`${n}.${a}`}},Ir=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[a,i,u]=n;if(a!==gt||u.length===0)return!1;const l=Number(i);if(!Number.isFinite(l)||l<=r)return!1;let y;try{y=Rr(u)}catch{return!1}return vr(e,`${a}.${i}`,y)},D="/_lunora/admin/auth",Pr={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},I=(e,t)=>{const r=e[t];if(typeof r!="string"||r==="")throw new s(`\`${t}\` is required`,{code:"BAD_REQUEST",status:400});return r},le=(e,t)=>{const r=e(t);if(r===void 0)throw new s(`\`${t}\` query parameter is required`,{code:"BAD_REQUEST",status:400});return r},qe=e=>{if(typeof e=="string"||Array.isArray(e)&&e.every(t=>typeof t=="string"))return e},X=(e,t)=>typeof e[t]=="string"?e[t]:void 0,Ye=(e,t)=>{const r=e[t];return typeof r=="object"&&r!==null&&!Array.isArray(r)?r:void 0},Xe=e=>{const t=e.permission;if(typeof t!="object"||t===null||Array.isArray(t))throw new s("`permission` object is required",{code:"BAD_REQUEST",status:400});const r={};for(const[n,a]of Object.entries(t))Array.isArray(a)&&a.every(i=>typeof i=="string")&&(r[n]=a);return r},Nr={[`${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:typeof e.data=="object"&&e.data!==null&&!Array.isArray(e.data)?e.data:void 0,email:I(e,"email"),name:I(e,"name"),password:X(e,"password"),role:qe(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 s("`data` object is required",{code:"BAD_REQUEST",status:400});return{data:t,userId:I(e,"userId")}},http:"POST",method:"updateUser"},[`${D}/users/role`]:{build:({body:e})=>{const t=qe(e.role);if(t===void 0||typeof t=="string"&&t.trim()==="")throw new s("`role` is required",{code:"BAD_REQUEST",status:400});return{role:t,userId:I(e,"userId")}},http:"POST",method:"setRole"},[`${D}/users/ban`]:{build:({body:e})=>({expiresInSeconds:typeof e.expiresInSeconds=="number"?e.expiresInSeconds:void 0,reason:X(e,"reason"),userId:I(e,"userId")}),http:"POST",method:"banUser"},[`${D}/users/unban`]:{build:({body:e})=>({userId:I(e,"userId")}),http:"POST",method:"unbanUser"},[`${D}/users/password`]:{build:({body:e})=>({newPassword:I(e,"newPassword"),userId:I(e,"userId")}),http:"POST",method:"setUserPassword",returns:"void"},[`${D}/users/remove`]:{build:({body:e})=>({userId:I(e,"userId")}),http:"POST",method:"removeUser",returns:"void"},[`${D}/users/impersonate`]:{build:({body:e})=>({userId:I(e,"userId")}),http:"POST",method:"impersonateUser"},[`${D}/sessions/revoke`]:{build:({body:e})=>({sessionId:I(e,"sessionId")}),http:"POST",method:"revokeUserSession",returns:"void"},[`${D}/sessions/revoke-all`]:{build:({body:e})=>({userId:I(e,"userId")}),http:"POST",method:"revokeUserSessions",returns:"void"},[`${D}/accounts/unlink`]:{build:({body:e})=>({accountId:I(e,"accountId"),userId:I(e,"userId")}),http:"POST",method:"unlinkAccount",returns:"void"},[`${D}/two-factor/disable`]:{build:({body:e})=>({userId:I(e,"userId")}),http:"POST",method:"disableTwoFactor",returns:"void"},[`${D}/passkeys/delete`]:{build:({body:e})=>({passkeyId:I(e,"passkeyId")}),http:"POST",method:"deletePasskey",returns:"void"},[`${D}/organizations/members/remove`]:{build:({body:e})=>({memberId:I(e,"memberId")}),http:"POST",method:"removeMember",returns:"void"},[`${D}/organizations/invitations/cancel`]:{build:({body:e})=>({invitationId:I(e,"invitationId")}),http:"POST",method:"cancelInvitation",returns:"void"},[`${D}/organizations/create`]:{build:({body:e})=>({logo:X(e,"logo"),metadata:Ye(e,"metadata"),name:I(e,"name"),ownerId:X(e,"ownerId"),slug:X(e,"slug")}),http:"POST",method:"createOrganization"},[`${D}/organizations/update`]:{build:({body:e})=>({logo:X(e,"logo"),metadata:Ye(e,"metadata"),name:X(e,"name"),organizationId:I(e,"organizationId"),slug:X(e,"slug")}),http:"POST",method:"updateOrganization"},[`${D}/organizations/remove`]:{build:({body:e})=>({organizationId:I(e,"organizationId")}),http:"POST",method:"deleteOrganization",returns:"void"},[`${D}/organizations/members/add`]:{build:({body:e})=>({organizationId:I(e,"organizationId"),role:X(e,"role"),userId:I(e,"userId")}),http:"POST",method:"addMember"},[`${D}/organizations/members/invite`]:{build:({body:e})=>({email:I(e,"email"),inviterId:X(e,"inviterId"),organizationId:I(e,"organizationId"),role:X(e,"role")}),http:"POST",method:"inviteMember"},[`${D}/organizations/members/role`]:{build:({body:e})=>{const t=qe(e.role);if(t===void 0||typeof t=="string"&&t.trim()==="")throw new s("`role` is required",{code:"BAD_REQUEST",status:400});return{memberId:I(e,"memberId"),role:t}},http:"POST",method:"updateMemberRole"},[`${D}/organizations/teams/create`]:{build:({body:e})=>({name:I(e,"name"),organizationId:I(e,"organizationId")}),http:"POST",method:"createTeam"},[`${D}/organizations/teams/update`]:{build:({body:e})=>({name:I(e,"name"),teamId:I(e,"teamId")}),http:"POST",method:"updateTeam"},[`${D}/organizations/teams/remove`]:{build:({body:e})=>({teamId:I(e,"teamId")}),http:"POST",method:"removeTeam",returns:"void"},[`${D}/organizations/teams/members/add`]:{build:({body:e})=>({teamId:I(e,"teamId"),userId:I(e,"userId")}),http:"POST",method:"addTeamMember"},[`${D}/organizations/teams/members/remove`]:{build:({body:e})=>({teamMemberId:I(e,"teamMemberId")}),http:"POST",method:"removeTeamMember",returns:"void"},[`${D}/organizations/roles/create`]:{build:({body:e})=>({organizationId:I(e,"organizationId"),permission:Xe(e),role:I(e,"role")}),http:"POST",method:"createOrgRole"},[`${D}/organizations/roles/update`]:{build:({body:e})=>({permission:Xe(e),roleId:I(e,"roleId")}),http:"POST",method:"updateOrgRole"},[`${D}/organizations/roles/remove`]:{build:({body:e})=>({roleId:I(e,"roleId")}),http:"POST",method:"deleteOrgRole",returns:"void"}},Ur=e=>{const t=async a=>{try{return await a()}catch(i){if(i instanceof s)throw i;const u=i,l=typeof u.code=="string"?u.code:"AUTH_ADMIN_ERROR";throw console.error("[lunora] auth admin operation failed:",i),new s("auth admin operation failed",{code:l,status:Pr[l]??500})}},r=async(a,i)=>{if(e.assertAdmin(a),a.method!==i.http)throw new s(`Auth admin endpoint requires ${i.http}`,{code:"METHOD_NOT_ALLOWED",status:405});const u=e.getAuthAdmin();if(u===void 0)throw new s("auth endpoints require an `authAdmin` on the worker",{code:"AUTH_NOT_CONFIGURED",status:400});const l=u[i.method];if(l===void 0)throw new s(`auth admin does not support \`${i.method}\``,{code:"AUTH_OP_NOT_SUPPORTED",status:400});const y=new URL(a.url),O={body:i.http==="POST"?await e.readJsonBody(a):{},paging:e.parsePaging(a),query:g=>e.queryParameter(y,g)},A=i.build(O),m=await t(()=>l(A));return Response.json(i.returns==="void"?{ok:!0}:m,{headers:{"content-type":"application/json"},status:200})},n={};for(const[a,i]of Object.entries(Nr))n[a]=u=>r(u,i);return n},qr="__lunora_admin__:getAuthAuditLog",Ze=e=>typeof e=="string"&&e!==""?e:void 0,et=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0,$r=e=>async(t,r)=>{e.assertAdmin(t);const n=e.getReader();if(n===void 0)throw new s("the auth/security audit endpoint requires an `authAuditReader` on the worker",{code:"AUTH_AUDIT_NOT_CONFIGURED",status:400});const a={},i=Ze(r.actorId),u=Ze(r.event),l=et(r.sinceSeq),y=et(r.limit);i!==void 0&&(a.actorId=i),u!==void 0&&(a.event=u),l!==void 0&&(a.sinceSeq=l),y!==void 0&&(a.limit=y);let O;try{O=await n.read(a)}catch(m){throw m instanceof s?m:(console.error("[lunora] auth audit read failed:",m),new s("auth audit read failed",{code:"AUTH_AUDIT_READ_FAILED",status:500}))}const A={entries:O};return Response.json(A,{headers:{"content-type":"application/json"},status:200})},tt=500,Lr=(e,t,r)=>{if(typeof e!="object"||e===null||Array.isArray(e))throw new s("each batch call must be an object",{code:"BAD_REQUEST",status:400});const n=e;if(typeof n.functionPath!="string")throw new s("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 s("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 s("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}},Br=(e,t)=>{if(e.length>tt)throw new s(`RPC batch exceeds the ${String(tt)}-call limit`,{code:"BAD_REQUEST",status:400});const r=new Map;for(const[n,a]of e.entries()){const{entry:i,shardKey:u}=Lr(a,n,t),l=r.get(u)??[];l.push(i),r.set(u,l)}return r},ge=1048576,ae=async(e,t=ge)=>{if(!e.body)return"";const r=e.body.getReader(),n=new TextDecoder;let a=0,i="";for(;;){const{done:u,value:l}=await r.read();if(u)break;if(l){if(a+=l.byteLength,a>t)throw await r.cancel().catch(()=>{}),new s("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});i+=n.decode(l,{stream:!0})}}return i+=n.decode(),i},xr=async(e,t=ge)=>{if(!e.body)return new ArrayBuffer(0);const r=e.body.getReader(),n=[];let a=0;for(;;){const{done:l,value:y}=await r.read();if(l)break;if(y){if(a+=y.byteLength,a>t)throw await r.cancel().catch(()=>{}),new s("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});n.push(y)}}const i=new Uint8Array(a);let u=0;for(const l of n)i.set(l,u),u+=l.byteLength;return i.buffer},Z=async(e,t=ge)=>{try{const r=await ae(e,t);return r===""?{}:JSON.parse(r)}catch(r){throw r instanceof s?r:new s("Request body must be valid JSON",{code:"BAD_REQUEST",status:400})}},Cr=new TextEncoder,jr=e=>{const t=JSON.stringify(e),r=Cr.encode(t);let n="";for(const a of r)n+=String.fromCodePoint(a);return btoa(n).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")},Gr=e=>{const t={g:0,s:{},v:1};if(typeof e!="string"||e.length===0)return t;try{const r=atob(e.replaceAll("-","+").replaceAll("_","/")),n=new Uint8Array(r.length);for(let l=0;l<r.length;l+=1)n[l]=r.codePointAt(l)??0;const a=JSON.parse(new TextDecoder().decode(n)),i=a.s&&typeof a.s=="object"?a.s:{},u={};for(const[l,y]of Object.entries(i))typeof y=="number"&&Number.isFinite(y)&&(u[l]=y);return{g:typeof a.g=="number"&&Number.isFinite(a.g)?a.g:0,s:u,v:1}}catch{return t}},Mr=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",a=typeof e.id=="string"?e.id:void 0;return{doc:(e.doc&&typeof e.doc=="object"?e.doc:void 0)??(a===void 0?{}:{_id:a}),op:n,table:t}},rt=(e,t,r)=>{for(const n of t)e.push(Mr(n));return r!==void 0&&t.length>=r},Kr="/_lunora/admin/export",Qr="/_lunora/admin/import",Fr="/_lunora/admin/sync",zr="/_lunora/admin/connector/sync",Wr="/_lunora/admin/apply",Hr="/_lunora/admin/export-tap/run",Jr=new TextEncoder,Vr=async e=>{let t;try{const a=await ae(e);t=a===""?{}:JSON.parse(a)}catch(a){throw a instanceof s?a:new s("Export body must be valid JSON",{code:"BAD_REQUEST",status:400})}const r=t??{};if(r.tables===void 0)return{tables:void 0};if(!Array.isArray(r.tables))throw new s("Export `tables` must be a string array",{code:"BAD_REQUEST",status:400});const n=[];for(const a of r.tables){if(typeof a!="string"||a.length===0)throw new s("Export `tables` entries must be non-empty strings",{code:"BAD_REQUEST",status:400});n.push(a)}return{tables:n}},Yr=e=>{const{applyGlobals:t,exportCursorStore:r,exportSinks:n,knownTables:a,queryCoordinator:i,requireAdminOption:u,resolveForwardContext:l,shardDO:y,streamExportRows:O,streamingImport:A,syncGlobals:m}=e,g=async(T,L)=>{const B=we(T,["POST"]);if(B)return B;const M=u(T,i,{code:"BAD_REQUEST",message:"Export endpoint requires a `queryCoordinator` on the worker"}),N=await Vr(T),{headers:K}=await l(T,L),Q=new ReadableStream({async pull(Y){const C=G=>{Y.enqueue(Jr.encode(`${JSON.stringify(G)}
|
|
1
|
+
import{isLunoraError as rr,toErrorBody as nr}from"@lunora/errors";import{NOOP_EXECUTION_CONTEXT as or}from"./NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{O as Re,m as ar,A as sr,R as ir,d as dr,i as ur,s as cr}from"./otlp-resource-B-ByO9qo.mjs";import{LunoraError as s,toErrorResponse as ze}from"./LunoraError-ByasbDmd.mjs";import{runExportTap as lr}from"./createKvCursorStore-C24tEuYk.mjs";import{d as we}from"./method-guard-BbuR0VfS.mjs";import{buildHealthRoutes as hr,durableObjectProbe as pr,d1Probe as fr,presenceProbe as Pe}from"./HEALTH_PATH-BEE0A_lZ.mjs";import{wrapResolverWithContract as wr}from"./composeIdentityResolvers-DwE0Jbww.mjs";import{composeIdentityResolvers as ma,routeIdentityResolvers as ya}from"./composeIdentityResolvers-DwE0Jbww.mjs";import{buildLogArchiveAdminRoutes as mr}from"./LOG_ARCHIVE_PATH-DGsEec3K.mjs";import{o as yr,f as We,a as de}from"./observability-DYnm-d4g.mjs";import{resolveShard as Se,applyJurisdiction as He}from"./applyJurisdiction-uRQLx282.mjs";import{buildRestRoutes as gr}from"./argsFromQuery-BkJXnIpe.mjs";import{resolveSecurity as Je,handleCorsPreflight as br,enforceOrigin as Or,decorateResponse as Ne,enforceWebSocketOrigin as Ve}from"./decorateResponse-DBIWsRSZ.mjs";const mt=(e,t)=>{if(e.size<t)return;const r=e.keys().next().value;r!==void 0&&e.delete(r)},Er="::relay::",Tr=(e,t)=>`${e}${Er}${String(t)}`,Ce=new TextEncoder,_r=e=>{const t=String.fromCodePoint(...e);return btoa(t).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")},Rr=e=>{const t=e.replaceAll("-","+").replaceAll("_","/")+"===".slice((e.length+3)%4),r=atob(t),n=new Uint8Array(r.length);for(let a=0;a<r.length;a+=1)n[a]=r.codePointAt(a)??0;return n},Sr=64,Ue=new Map,yt=async e=>{const t=Ue.get(e);if(t)return t;mt(Ue,Sr);const r=crypto.subtle.importKey("raw",Ce.encode(e),{hash:"SHA-256",name:"HMAC"},!1,["sign","verify"]);return Ue.set(e,r),r},Ar=async(e,t)=>{const r=await yt(e),n=await crypto.subtle.sign("HMAC",r,Ce.encode(t));return _r(new Uint8Array(n))},vr=async(e,t,r)=>{const n=await yt(e);return crypto.subtle.verify("HMAC",n,r,Ce.encode(t))},gt="v1",Dr=6e4,kr=async(e,t={})=>{const r=(t.now??Date.now())+(t.ttlMs??Dr),n=`${gt}.${String(r)}`,a=await Ar(e,n);return{expiresAtMs:r,token:`${n}.${a}`}},Ir=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[a,i,u]=n;if(a!==gt||u.length===0)return!1;const l=Number(i);if(!Number.isFinite(l)||l<=r)return!1;let y;try{y=Rr(u)}catch{return!1}return vr(e,`${a}.${i}`,y)},D="/_lunora/admin/auth",Pr={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},I=(e,t)=>{const r=e[t];if(typeof r!="string"||r==="")throw new s(`\`${t}\` is required`,{code:"BAD_REQUEST",status:400});return r},le=(e,t)=>{const r=e(t);if(r===void 0)throw new s(`\`${t}\` query parameter is required`,{code:"BAD_REQUEST",status:400});return r},qe=e=>{if(typeof e=="string"||Array.isArray(e)&&e.every(t=>typeof t=="string"))return e},X=(e,t)=>typeof e[t]=="string"?e[t]:void 0,Ye=(e,t)=>{const r=e[t];return typeof r=="object"&&r!==null&&!Array.isArray(r)?r:void 0},Xe=e=>{const t=e.permission;if(typeof t!="object"||t===null||Array.isArray(t))throw new s("`permission` object is required",{code:"BAD_REQUEST",status:400});const r={};for(const[n,a]of Object.entries(t))Array.isArray(a)&&a.every(i=>typeof i=="string")&&(r[n]=a);return r},Nr={[`${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:typeof e.data=="object"&&e.data!==null&&!Array.isArray(e.data)?e.data:void 0,email:I(e,"email"),name:I(e,"name"),password:X(e,"password"),role:qe(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 s("`data` object is required",{code:"BAD_REQUEST",status:400});return{data:t,userId:I(e,"userId")}},http:"POST",method:"updateUser"},[`${D}/users/role`]:{build:({body:e})=>{const t=qe(e.role);if(t===void 0||typeof t=="string"&&t.trim()==="")throw new s("`role` is required",{code:"BAD_REQUEST",status:400});return{role:t,userId:I(e,"userId")}},http:"POST",method:"setRole"},[`${D}/users/ban`]:{build:({body:e})=>({expiresInSeconds:typeof e.expiresInSeconds=="number"?e.expiresInSeconds:void 0,reason:X(e,"reason"),userId:I(e,"userId")}),http:"POST",method:"banUser"},[`${D}/users/unban`]:{build:({body:e})=>({userId:I(e,"userId")}),http:"POST",method:"unbanUser"},[`${D}/users/password`]:{build:({body:e})=>({newPassword:I(e,"newPassword"),userId:I(e,"userId")}),http:"POST",method:"setUserPassword",returns:"void"},[`${D}/users/remove`]:{build:({body:e})=>({userId:I(e,"userId")}),http:"POST",method:"removeUser",returns:"void"},[`${D}/users/impersonate`]:{build:({body:e})=>({userId:I(e,"userId")}),http:"POST",method:"impersonateUser"},[`${D}/sessions/revoke`]:{build:({body:e})=>({sessionId:I(e,"sessionId")}),http:"POST",method:"revokeUserSession",returns:"void"},[`${D}/sessions/revoke-all`]:{build:({body:e})=>({userId:I(e,"userId")}),http:"POST",method:"revokeUserSessions",returns:"void"},[`${D}/accounts/unlink`]:{build:({body:e})=>({accountId:I(e,"accountId"),userId:I(e,"userId")}),http:"POST",method:"unlinkAccount",returns:"void"},[`${D}/two-factor/disable`]:{build:({body:e})=>({userId:I(e,"userId")}),http:"POST",method:"disableTwoFactor",returns:"void"},[`${D}/passkeys/delete`]:{build:({body:e})=>({passkeyId:I(e,"passkeyId")}),http:"POST",method:"deletePasskey",returns:"void"},[`${D}/organizations/members/remove`]:{build:({body:e})=>({memberId:I(e,"memberId")}),http:"POST",method:"removeMember",returns:"void"},[`${D}/organizations/invitations/cancel`]:{build:({body:e})=>({invitationId:I(e,"invitationId")}),http:"POST",method:"cancelInvitation",returns:"void"},[`${D}/organizations/create`]:{build:({body:e})=>({logo:X(e,"logo"),metadata:Ye(e,"metadata"),name:I(e,"name"),ownerId:X(e,"ownerId"),slug:X(e,"slug")}),http:"POST",method:"createOrganization"},[`${D}/organizations/update`]:{build:({body:e})=>({logo:X(e,"logo"),metadata:Ye(e,"metadata"),name:X(e,"name"),organizationId:I(e,"organizationId"),slug:X(e,"slug")}),http:"POST",method:"updateOrganization"},[`${D}/organizations/remove`]:{build:({body:e})=>({organizationId:I(e,"organizationId")}),http:"POST",method:"deleteOrganization",returns:"void"},[`${D}/organizations/members/add`]:{build:({body:e})=>({organizationId:I(e,"organizationId"),role:X(e,"role"),userId:I(e,"userId")}),http:"POST",method:"addMember"},[`${D}/organizations/members/invite`]:{build:({body:e})=>({email:I(e,"email"),inviterId:X(e,"inviterId"),organizationId:I(e,"organizationId"),role:X(e,"role")}),http:"POST",method:"inviteMember"},[`${D}/organizations/members/role`]:{build:({body:e})=>{const t=qe(e.role);if(t===void 0||typeof t=="string"&&t.trim()==="")throw new s("`role` is required",{code:"BAD_REQUEST",status:400});return{memberId:I(e,"memberId"),role:t}},http:"POST",method:"updateMemberRole"},[`${D}/organizations/teams/create`]:{build:({body:e})=>({name:I(e,"name"),organizationId:I(e,"organizationId")}),http:"POST",method:"createTeam"},[`${D}/organizations/teams/update`]:{build:({body:e})=>({name:I(e,"name"),teamId:I(e,"teamId")}),http:"POST",method:"updateTeam"},[`${D}/organizations/teams/remove`]:{build:({body:e})=>({teamId:I(e,"teamId")}),http:"POST",method:"removeTeam",returns:"void"},[`${D}/organizations/teams/members/add`]:{build:({body:e})=>({teamId:I(e,"teamId"),userId:I(e,"userId")}),http:"POST",method:"addTeamMember"},[`${D}/organizations/teams/members/remove`]:{build:({body:e})=>({teamMemberId:I(e,"teamMemberId")}),http:"POST",method:"removeTeamMember",returns:"void"},[`${D}/organizations/roles/create`]:{build:({body:e})=>({organizationId:I(e,"organizationId"),permission:Xe(e),role:I(e,"role")}),http:"POST",method:"createOrgRole"},[`${D}/organizations/roles/update`]:{build:({body:e})=>({permission:Xe(e),roleId:I(e,"roleId")}),http:"POST",method:"updateOrgRole"},[`${D}/organizations/roles/remove`]:{build:({body:e})=>({roleId:I(e,"roleId")}),http:"POST",method:"deleteOrgRole",returns:"void"}},Ur=e=>{const t=async a=>{try{return await a()}catch(i){if(i instanceof s)throw i;const u=i,l=typeof u.code=="string"?u.code:"AUTH_ADMIN_ERROR";throw console.error("[lunora] auth admin operation failed:",i),new s("auth admin operation failed",{code:l,status:Pr[l]??500})}},r=async(a,i)=>{if(e.assertAdmin(a),a.method!==i.http)throw new s(`Auth admin endpoint requires ${i.http}`,{code:"METHOD_NOT_ALLOWED",status:405});const u=e.getAuthAdmin();if(u===void 0)throw new s("auth endpoints require an `authAdmin` on the worker",{code:"AUTH_NOT_CONFIGURED",status:400});const l=u[i.method];if(l===void 0)throw new s(`auth admin does not support \`${i.method}\``,{code:"AUTH_OP_NOT_SUPPORTED",status:400});const y=new URL(a.url),O={body:i.http==="POST"?await e.readJsonBody(a):{},paging:e.parsePaging(a),query:g=>e.queryParameter(y,g)},A=i.build(O),m=await t(()=>l(A));return Response.json(i.returns==="void"?{ok:!0}:m,{headers:{"content-type":"application/json"},status:200})},n={};for(const[a,i]of Object.entries(Nr))n[a]=u=>r(u,i);return n},qr="__lunora_admin__:getAuthAuditLog",Ze=e=>typeof e=="string"&&e!==""?e:void 0,et=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0,$r=e=>async(t,r)=>{e.assertAdmin(t);const n=e.getReader();if(n===void 0)throw new s("the auth/security audit endpoint requires an `authAuditReader` on the worker",{code:"AUTH_AUDIT_NOT_CONFIGURED",status:400});const a={},i=Ze(r.actorId),u=Ze(r.event),l=et(r.sinceSeq),y=et(r.limit);i!==void 0&&(a.actorId=i),u!==void 0&&(a.event=u),l!==void 0&&(a.sinceSeq=l),y!==void 0&&(a.limit=y);let O;try{O=await n.read(a)}catch(m){throw m instanceof s?m:(console.error("[lunora] auth audit read failed:",m),new s("auth audit read failed",{code:"AUTH_AUDIT_READ_FAILED",status:500}))}const A={entries:O};return Response.json(A,{headers:{"content-type":"application/json"},status:200})},tt=500,Lr=(e,t,r)=>{if(typeof e!="object"||e===null||Array.isArray(e))throw new s("each batch call must be an object",{code:"BAD_REQUEST",status:400});const n=e;if(typeof n.functionPath!="string")throw new s("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 s("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 s("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}},Br=(e,t)=>{if(e.length>tt)throw new s(`RPC batch exceeds the ${String(tt)}-call limit`,{code:"BAD_REQUEST",status:400});const r=new Map;for(const[n,a]of e.entries()){const{entry:i,shardKey:u}=Lr(a,n,t),l=r.get(u)??[];l.push(i),r.set(u,l)}return r},ge=1048576,ae=async(e,t=ge)=>{if(!e.body)return"";const r=e.body.getReader(),n=new TextDecoder;let a=0,i="";for(;;){const{done:u,value:l}=await r.read();if(u)break;if(l){if(a+=l.byteLength,a>t)throw await r.cancel().catch(()=>{}),new s("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});i+=n.decode(l,{stream:!0})}}return i+=n.decode(),i},xr=async(e,t=ge)=>{if(!e.body)return new ArrayBuffer(0);const r=e.body.getReader(),n=[];let a=0;for(;;){const{done:l,value:y}=await r.read();if(l)break;if(y){if(a+=y.byteLength,a>t)throw await r.cancel().catch(()=>{}),new s("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});n.push(y)}}const i=new Uint8Array(a);let u=0;for(const l of n)i.set(l,u),u+=l.byteLength;return i.buffer},Z=async(e,t=ge)=>{try{const r=await ae(e,t);return r===""?{}:JSON.parse(r)}catch(r){throw r instanceof s?r:new s("Request body must be valid JSON",{code:"BAD_REQUEST",status:400})}},Cr=new TextEncoder,jr=e=>{const t=JSON.stringify(e),r=Cr.encode(t);let n="";for(const a of r)n+=String.fromCodePoint(a);return btoa(n).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")},Gr=e=>{const t={g:0,s:{},v:1};if(typeof e!="string"||e.length===0)return t;try{const r=atob(e.replaceAll("-","+").replaceAll("_","/")),n=new Uint8Array(r.length);for(let l=0;l<r.length;l+=1)n[l]=r.codePointAt(l)??0;const a=JSON.parse(new TextDecoder().decode(n)),i=a.s&&typeof a.s=="object"?a.s:{},u={};for(const[l,y]of Object.entries(i))typeof y=="number"&&Number.isFinite(y)&&(u[l]=y);return{g:typeof a.g=="number"&&Number.isFinite(a.g)?a.g:0,s:u,v:1}}catch{return t}},Mr=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",a=typeof e.id=="string"?e.id:void 0;return{doc:(e.doc&&typeof e.doc=="object"?e.doc:void 0)??(a===void 0?{}:{_id:a}),op:n,table:t}},rt=(e,t,r)=>{for(const n of t)e.push(Mr(n));return r!==void 0&&t.length>=r},Kr="/_lunora/admin/export",Qr="/_lunora/admin/import",Fr="/_lunora/admin/sync",zr="/_lunora/admin/connector/sync",Wr="/_lunora/admin/apply",Hr="/_lunora/admin/export-tap/run",Jr=new TextEncoder,Vr=async e=>{let t;try{const a=await ae(e);t=a===""?{}:JSON.parse(a)}catch(a){throw a instanceof s?a:new s("Export body must be valid JSON",{code:"BAD_REQUEST",status:400})}const r=t??{};if(r.tables===void 0)return{tables:void 0};if(!Array.isArray(r.tables))throw new s("Export `tables` must be a string array",{code:"BAD_REQUEST",status:400});const n=[];for(const a of r.tables){if(typeof a!="string"||a.length===0)throw new s("Export `tables` entries must be non-empty strings",{code:"BAD_REQUEST",status:400});n.push(a)}return{tables:n}},Yr=e=>{const{applyGlobals:t,exportCursorStore:r,exportSinks:n,knownTables:a,queryCoordinator:i,requireAdminOption:u,resolveForwardContext:l,shardDO:y,streamExportRows:O,streamingImport:A,syncGlobals:m}=e,g=async(T,L)=>{const B=we(T,["POST"]);if(B)return B;const M=u(T,i,{code:"BAD_REQUEST",message:"Export endpoint requires a `queryCoordinator` on the worker"}),N=await Vr(T),{headers:K}=await l(T,L),Q=new ReadableStream({async pull(Y){const C=G=>{Y.enqueue(Jr.encode(`${JSON.stringify(G)}
|
|
2
2
|
`))};try{await O(M,K,N.tables,C),Y.close()}catch(G){Y.error(G)}}});return new Response(Q,{headers:{"content-type":"application/x-ndjson"},status:200})},p=async(T,L)=>{const B=we(T,["POST"]);if(B)return B;const M=u(T,i,{code:"BAD_REQUEST",message:"Sync endpoint requires a `queryCoordinator` on the worker"}),N=await Z(T),K=typeof N.cursors=="object"&&N.cursors!==null?N.cursors:{},Q=typeof N.limit=="number"?N.limit:void 0,Y=typeof N.globalCursor=="number"?N.globalCursor:0,C=Array.isArray(N.tables)?N.tables.filter(ne=>typeof ne=="string"):void 0,{headers:G}=await l(T,L),J=C??a(),re=await M.orchestrateCdcSync(y,{cursors:K,headers:G,limit:Q,tables:J}),se=m?await m({limit:Q,sinceSeq:Y}):void 0;return Response.json({global:se,shards:re.shards},{status:200})},w=async(T,L)=>{const B=we(T,["POST"]);if(B)return B;const M=u(T,i,{code:"BAD_REQUEST",message:"Connector sync endpoint requires a `queryCoordinator` on the worker"}),N=await Z(T),K=Gr(N.cursor),Q=typeof N.limit=="number"&&N.limit>0?N.limit:void 0,Y=Array.isArray(N.tables)?N.tables.filter(ee=>typeof ee=="string"):void 0,{headers:C}=await l(T,L),G=Y??a(),J=await M.orchestrateCdcSync(y,{cursors:K.s,headers:C,limit:Q,tables:G}),re=[],se={...K.s};let ne=!1;for(const ee of J.shards)ne=rt(re,ee.changes??[],Q)||ne,se[ee.shardKey]=ee.cursor;let he=K.g;if(m){const ee=await m({limit:Q,sinceSeq:K.g});ne=rt(re,ee.changes,Q)||ne,he=ee.cursor}const me=jr({g:he,s:se,v:1}),be={changes:re,hasMore:ne,nextCursor:me};return Response.json(be,{status:200})},_=async(T,L)=>{const B=we(T,["POST"]);if(B)return B;const M=u(T,i,{code:"BAD_REQUEST",message:"Apply endpoint requires a `queryCoordinator` on the worker"}),N=await Z(T),K=(Array.isArray(N.batches)?N.batches:[]).map(J=>J).filter(J=>J!==null&&typeof J=="object"&&typeof J.shardKey=="string"&&Array.isArray(J.changes)),Q=Array.isArray(N.globalChanges)?N.globalChanges:[],{headers:Y}=await l(T,L),C=await M.orchestrateApplyCdc(y,{batches:K,headers:Y}),G=Q.length>0&&t?await t({changes:Q}):0;return Response.json({applied:C.applied+G,failed:C.failed,ok:C.ok},{status:200})},R=async(T,L)=>{const B=we(T,["POST"]);if(B)return B;u(T,i,{code:"BAD_REQUEST",message:"Import endpoint requires a `queryCoordinator` on the worker"});const{headers:M}=await l(T,L),N=await A(T,M);return Response.json(N,{headers:{"content-type":"application/json"},status:200})},P=async(T,L)=>{const B=we(T,["POST"]);if(B)return B;const M=u(T,i,{code:"BAD_REQUEST",message:"Export-tap endpoint requires a `queryCoordinator` on the worker"});if(n===void 0||Object.keys(n).length===0||r===void 0)throw new s("Export-tap endpoint requires `exportSinks` + `exportCursorStore` on the worker",{code:"EXPORT_TAP_NOT_CONFIGURED",status:400});const N=await Z(T),K=typeof N.sink=="string"?N.sink:void 0,Q=typeof N.limit=="number"&&N.limit>0?N.limit:void 0,Y=Array.isArray(N.tables)?N.tables.filter(se=>typeof se=="string"):void 0;if(K===void 0)throw new s("Export-tap `sink` must name a configured sink",{code:"BAD_REQUEST",status:400});const C=n[K];if(C===void 0)throw new s(`Export-tap sink "${K}" is not configured`,{code:"NOT_FOUND",status:404});const{headers:G}=await l(T,L),J=Y??a(),re=await lr({coordinator:M,cursorStore:r,headers:G,limit:Q,shardDO:y,sink:C,tables:J});return Response.json(re,{headers:{"content-type":"application/json"},status:200})};return{[Wr]:_,[zr]:w,[Kr]:g,[Hr]:P,[Qr]:R,[Fr]:p}},bt=e=>[],Xr=(e,t)=>{const r=[],n=[];if(t&&t.length>0)for(const a of t)e.resolveTableSharding?.(a)?.mode.kind==="global"?n.push(a):r.push(a);return{globalTables:n,shardLocalTables:r}},Zr=async(e,t,r,n,a,i,u)=>{if(n!==void 0&&a.length===0)return;const l=n===void 0?[]:a,y=n===void 0?bt():[],O=l.length>0?l:y,A=await t.orchestrateExport(u,{args:{tables:l},headers:r,tables:O});for(const m of A.shards)if(!m.error)for(const g of m.rows??[])i(g)},nt=async(e,t,r,n,a,i)=>{const{globalTables:u,shardLocalTables:l}=Xr(e,n);await Zr(e,t,r,n,l,a,i);const y=e.exportGlobals;if((n===void 0||u.length>0)&&y){const O=n===void 0?[]:u;for await(const A of y({tables:O}))a(A)}},en=(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}},tn=(e,t,r,n,a)=>{if(r?.mode.kind==="shardBy"&&typeof r.mode.field=="string"){const i=e[r.mode.field];return i==null?{error:{code:"BAD_ROW",line:a,message:`row missing shard field "${r.mode.field}" for table "${t}"`,table:t},ok:!1}:{ok:!0,shardKey:typeof i=="string"?i:JSON.stringify(i)}}return{ok:!0,shardKey:n}},rn=async(e,t,r)=>{if(!e.body)throw new s("Import endpoint requires a request body",{code:"BAD_REQUEST",status:400});const n=[],a=[],i=new Map;let u=0;const l=e.body.getReader(),y=new TextDecoder;let O="",A=0;const m=g=>{u+=1;const p=g.trim();if(p.length===0)return;const w=en(p,u);if(!w.ok){n.push(w.error);return}const{doc:_,table:R}=w,P=t.resolveTableSharding?.(R);if(P?.mode.kind==="global"){a.push({doc:_,line:u,table:R});return}const T=tn(_,R,P,r,u);if(!T.ok){n.push(T.error);return}const L=i.get(T.shardKey);L?L.rows.push({doc:_,table:R}):i.set(T.shardKey,{rows:[{doc:_,table:R}],shardKey:T.shardKey,startLine:u})};for(;;){const{done:g,value:p}=await l.read();if(g)break;if(p&&(A+=p.byteLength,A>ge))throw await l.cancel().catch(()=>{}),new s("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});O+=y.decode(p,{stream:!0});let w=O.indexOf(`
|
|
3
3
|
`);for(;w!==-1;){const _=O.slice(0,w);O=O.slice(w+1),m(_),w=O.indexOf(`
|
|
4
|
-
`)}}return O.length>0&&m(O),{errors:n,globalRows:a,perShard:i}},ot=(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},nn=async(e,t,r,n)=>{const a=t.defaultShardKey??"__root__",{errors:i,globalRows:u,perShard:l}=await rn(e,t,a),y={conflicts:0,errors:i,inserted:{}};if(l.size>0){const O=t.queryCoordinator;if(!O)throw new s("Import endpoint requires a `queryCoordinator` on the worker",{code:"BAD_REQUEST",status:400});const A=await O.orchestrateImport(n,{batches:[...l.values()],headers:r});ot(y,A)}if(u.length>0)if(t.importGlobals){const O=u[0]?.line??1,A=await t.importGlobals({rows:u,startLine:O});ot(y,A)}else for(const O of u)y.errors.push({code:"GLOBAL_NOT_CONFIGURED",line:O.line,message:`row targets global table "${O.table}" but no \`importGlobals\` is configured`,table:O.table});return{conflicts:y.conflicts,errors:y.errors,inserted:y.inserted}},$e=e=>typeof e=="object"&&e!==null?e:{},Le=e=>typeof e.kind=="string"?e.kind:"unknown",on=(e,t)=>{let r=$e(t),n=!1;Le(r)==="optional"&&(n=!0,r=$e(r._meta?.inner));const a=Le(r),i=r._meta??{},u={kind:a,name:e,optional:n};if(a==="id"&&typeof i.tableName=="string"&&(u.table=i.tableName),a==="array"){const l=Le($e(i.inner));l!=="unknown"&&(u.element=l)}return u},an=e=>typeof e!="object"||e===null?[]:Object.entries(e).map(([t,r])=>on(t,r)).toSorted((t,r)=>t.name.localeCompare(r.name)),sn="/_lunora/admin/functions",dn="/_lunora/admin/cron-jobs",un="/_lunora/admin/openapi",cn="/_lunora/admin/openrpc",ln="/_lunora/admin/global/tables",hn="/_lunora/admin/global/table",pn="/_lunora/admin/global/facet",at=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:a,value:i}=n;return[{column:a,value:i}]});return r.length===0?void 0:r},fn=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:{}}),wn=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"}),mn=e=>{const{assertAdmin:t,options:r,parsePaging:n,queryParameter:a,requireAdminOption:i}=e,u=p=>{if(p.method!=="GET")throw new s("Functions endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});const w=i(p,r.functions,{code:"FUNCTIONS_NOT_CONFIGURED",message:"functions endpoint requires a `functions` registry on the worker"}),_=Object.entries(w).flatMap(([R,P])=>P.visibility==="internal"||P.kind==="stream"?[]:[{args:an(P.args),kind:P.kind,path:R}]).toSorted((R,P)=>R.path.localeCompare(P.path));return Response.json({functions:_},{headers:{"content-type":"application/json"},status:200})},l=p=>{if(p.method!=="GET")throw new s("Cron-jobs endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});const w=i(p,r.cronJobs,{code:"CRON_JOBS_NOT_CONFIGURED",message:"cron-jobs endpoint requires a `cronJobs` map on the worker"}),_=Object.entries(w).flatMap(([R,P])=>P.map(T=>({args:T.args,cron:R,functionPath:T.functionPath,name:T.name,shardKey:T.shardKey,workflow:T.workflow}))).toSorted((R,P)=>R.name.localeCompare(P.name));return Response.json({jobs:_},{headers:{"content-type":"application/json"},status:200})},y=p=>{if(p.method!=="GET")throw new s("OpenAPI endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});return t(p),Response.json(r.openApiSpec??fn,{headers:{"content-type":"application/json"},status:200})},O=p=>{if(p.method!=="GET")throw new s("OpenRPC endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});return t(p),Response.json(r.openRpcSpec??wn,{headers:{"content-type":"application/json"},status:200})},A=async p=>{if(p.method!=="GET")throw new s("Global-tables endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});const w=i(p,r.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"});return Response.json(await w.listTables(),{headers:{"content-type":"application/json"},status:200})},m=async p=>{if(p.method!=="GET")throw new s("Global-table endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});const w=i(p,r.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),_=new URL(p.url),R=a(_,"table");if(R===void 0)throw new s("Global-table endpoint requires a `table` query param",{code:"BAD_REQUEST",status:400});const P=await w.readTablePage({...n(p),filters:at(a(_,"filters")),table:R});return Response.json(P,{headers:{"content-type":"application/json"},status:200})},g=async p=>{if(p.method!=="GET")throw new s("Global-facet endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});const w=i(p,r.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),_=new URL(p.url),R=a(_,"table"),P=a(_,"column");if(R===void 0||P===void 0)throw new s("Global-facet endpoint requires `table` and `column` query params",{code:"BAD_REQUEST",status:400});const T=a(_,"limit"),L=T===void 0?void 0:Number(T),B=await w.facetColumn({column:P,filters:at(a(_,"filters")),limit:L!==void 0&&Number.isFinite(L)?L:void 0,table:R});return Response.json(B,{headers:{"content-type":"application/json"},status:200})};return{[dn]:l,[sn]:u,[pn]:g,[hn]:m,[ln]:A,[un]:y,[cn]:O}},yn="/_lunora/admin/kv/namespaces",gn="/_lunora/admin/kv/keys",Ot="/_lunora/admin/kv/value",Et=32*1048576,st=60,bn=e=>{const{readJsonBody:t,requireAdminOption:r}=e,n=m=>r(m,e.kvIntrospector,{code:"KV_NOT_CONFIGURED",message:"KV endpoints require a `kvIntrospector` on the worker"}),a=m=>Response.json(m,{headers:{"content-type":"application/json"},status:200}),i=(m,g)=>{const p=new URL(m.url),w=p.searchParams.get("namespace")??"",_=p.searchParams.get("key")??"";if(w==="")throw new s(`KV-value ${g} request requires a \`namespace\` query parameter`,{code:"BAD_REQUEST",status:400});if(_==="")throw new s(`KV-value ${g} request requires a \`key\` query parameter`,{code:"BAD_REQUEST",status:400});return{key:_,namespace:w}},u=async(m,g)=>{if(!(await m.listNamespaces()).some(p=>p.binding===g))throw new s(`Unknown KV namespace binding \`${g}\``,{code:"NOT_FOUND",status:404})},l=async m=>{if(m.method!=="GET")throw new s("KV-namespaces endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});return a({namespaces:await n(m).listNamespaces()})},y=async m=>{if(m.method!=="GET")throw new s("KV-keys endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});const g=n(m),p=new URL(m.url),w=p.searchParams.get("namespace")??"";if(w==="")throw new s("KV-keys request requires a `namespace` query parameter",{code:"BAD_REQUEST",status:400});const _=p.searchParams.get("prefix")??void 0,R=p.searchParams.get("cursor")??void 0,P=p.searchParams.get("limit"),T=P===null?void 0:Number.parseInt(P,10);if(T!==void 0&&(!Number.isInteger(T)||T<1))throw new s("KV-keys `limit` must be a positive integer",{code:"BAD_REQUEST",status:400});const L=T===void 0?void 0:Math.min(T,1e3);return await u(g,w),a(await g.listKeys({cursor:R,limit:L,namespace:w,prefix:_}))},O={DELETE:async m=>{const g=n(m),p=i(m,"DELETE");return await u(g,p.namespace),await g.deleteKey(p),a({deleted:!0})},GET:async m=>{const g=n(m),p=i(m,"GET");return await u(g,p.namespace),a(await g.getValue(p))},PUT:async m=>{const g=n(m),p=await t(m,Et);if(typeof p.namespace!="string"||p.namespace==="")throw new s("KV-value PUT request requires a `namespace` string",{code:"BAD_REQUEST",status:400});if(typeof p.key!="string"||p.key==="")throw new s("KV-value PUT request requires a `key` string",{code:"BAD_REQUEST",status:400});if(typeof p.value!="string")throw new s("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<st))throw new s("KV-value PUT `expirationTtl` must be an integer ≥ 60",{code:"BAD_REQUEST",status:400});const w=Math.floor(Date.now()/1e3)+st;if(p.expiration!==void 0&&(typeof p.expiration!="number"||!Number.isInteger(p.expiration)||p.expiration<w))throw new s("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(g,p.namespace),await g.putValue({expiration:p.expiration,expirationTtl:p.expirationTtl,key:p.key,metadata:p.metadata,namespace:p.namespace,value:p.value}),a({ok:!0})}},A=m=>{const g=O[m.method];if(!g)throw new s("KV-value endpoint requires GET, PUT, or DELETE",{code:"METHOD_NOT_ALLOWED",status:405});return g(m)};return{[yn]:l,[gn]:y,[Ot]:A}},On="/_lunora/migrate",En="/_lunora/admin/pitr",Tn="/_lunora/admin/rank",_n="/_lunora/admin/rankpage",Rn="/_lunora/admin/shard-traffic",Sn=new Set(["__lunora_admin__:migrationStatus","__lunora_admin__:runMigration"]),An=new Set(["__lunora_admin__:getPitrBookmark","__lunora_admin__:pitrRestore"]),vn=async e=>{let t;try{const n=await ae(e);t=n===""?{}:JSON.parse(n)}catch(n){throw n instanceof s?n:new s("Migration body must be valid JSON",{code:"BAD_REQUEST",status:400})}const r=t??{};if(typeof r.table!="string"||r.table.length===0)throw new s("Migration request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof r.functionPath!="string"||!Sn.has(r.functionPath))throw new s("Migration request `functionPath` must be a migration admin op",{code:"BAD_REQUEST",status:400});return{args:r.args??{},functionPath:r.functionPath,table:r.table}},Dn=async e=>{let t;try{const n=await ae(e);t=n===""?{}:JSON.parse(n)}catch(n){throw n instanceof s?n:new s("Rank body must be valid JSON",{code:"BAD_REQUEST",status:400})}const r=t??{};if(typeof r.table!="string"||r.table.length===0)throw new s("Rank request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof r.index!="string"||r.index.length===0)throw new s("Rank request is missing `index`",{code:"BAD_REQUEST",status:400});if(typeof r.partitionKey!="string")throw new s("Rank request `partitionKey` must be a string",{code:"BAD_REQUEST",status:400});if(typeof r.rowId!="string"||r.rowId.length===0)throw new s("Rank request is missing `rowId`",{code:"BAD_REQUEST",status:400});if(!Array.isArray(r.sortValues))throw new s("Rank request `sortValues` must be an array",{code:"BAD_REQUEST",status:400});return{index:r.index,partitionKey:r.partitionKey,rowId:r.rowId,sortValues:r.sortValues,table:r.table}},kn=e=>{if(e!==void 0){if(!Array.isArray(e)||e.some(t=>t!=="asc"&&t!=="desc"))throw new s('Rank page request `directions` must be an array of "asc"|"desc"',{code:"BAD_REQUEST",status:400});return e}},In=e=>{if(typeof e.table!="string"||e.table.length===0)throw new s("Rank page request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof e.index!="string"||e.index.length===0)throw new s("Rank page request is missing `index`",{code:"BAD_REQUEST",status:400});if(e.partitionKey!==void 0&&typeof e.partitionKey!="string")throw new s("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 s("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 s("Rank page request `cursor` must be a string or null",{code:"BAD_REQUEST",status:400})},Pn=async e=>{let t;try{const a=await ae(e);t=a===""?{}:JSON.parse(a)}catch(a){throw a instanceof s?a:new s("Rank page body must be valid JSON",{code:"BAD_REQUEST",status:400})}const r=t??{};In(r);const n=kn(r.directions);return{cursor:typeof r.cursor=="string"?r.cursor:null,directions:n,index:r.index,partitionKey:typeof r.partitionKey=="string"?r.partitionKey:void 0,table:r.table,take:typeof r.take=="number"?r.take:void 0}},Nn=async e=>{let t;try{const n=await ae(e);t=n===""?{}:JSON.parse(n)}catch(n){throw n instanceof s?n:new s("Shard-traffic body must be valid JSON",{code:"BAD_REQUEST",status:400})}const r=t??{};if(typeof r.table!="string"||r.table.length===0)throw new s("Shard-traffic request is missing `table`",{code:"BAD_REQUEST",status:400});return{table:r.table}},Un=async e=>{const t=await Z(e);if(typeof t.functionPath!="string"||!An.has(t.functionPath))throw new s("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 s("PITR `shardKey` must be a string",{code:"BAD_REQUEST",status:400});return{args:t.args??{},functionPath:t.functionPath,shardKey:t.shardKey}},qn=e=>{const{defaultShard:t,forwardToShard:r,isAdmin:n,queryCoordinator:a,resolveForwardContext:i,shardDO:u}=e,l=async(g,p)=>{if(g.method!=="POST")throw new s("Migration endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});if(!n(g))throw new s("Admin auth required",{code:"FORBIDDEN",status:403});if(!a)throw new s("Migration endpoint requires a `queryCoordinator` on the worker",{code:"BAD_REQUEST",status:400});const w=await vn(g),{headers:_}=await i(g,p),R=await a.orchestrateMigration(u,{args:w.args,functionPath:w.functionPath,headers:_,table:w.table});return Response.json(R,{headers:{"content-type":"application/json"},status:200})},y=async(g,p)=>{if(g.method!=="POST")throw new s("Rank endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});if(!n(g))throw new s("Admin auth required",{code:"FORBIDDEN",status:403});if(!a)throw new s("Rank endpoint requires a `queryCoordinator` on the worker",{code:"BAD_REQUEST",status:400});const w=await Dn(g),{headers:_}=await i(g,p),R=await a.orchestrateRank(u,{headers:_,index:w.index,partitionKey:w.partitionKey,rowId:w.rowId,sortValues:w.sortValues,table:w.table});return Response.json(R,{headers:{"content-type":"application/json"},status:200})},O=async(g,p)=>{if(g.method!=="POST")throw new s("Rank page endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});if(!n(g))throw new s("Admin auth required",{code:"FORBIDDEN",status:403});if(!a)throw new s("Rank page endpoint requires a `queryCoordinator` on the worker",{code:"BAD_REQUEST",status:400});const w=await Pn(g),{headers:_}=await i(g,p),R=await a.orchestrateRankPage(u,{...w,headers:_});return Response.json(R,{headers:{"content-type":"application/json"},status:200})},A=async(g,p)=>{if(g.method!=="POST")throw new s("Shard-traffic endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});if(!n(g))throw new s("Admin auth required",{code:"FORBIDDEN",status:403});if(!a)throw new s("Shard-traffic endpoint requires a `queryCoordinator` on the worker",{code:"BAD_REQUEST",status:400});const w=await Nn(g),{headers:_}=await i(g,p),R=await a.orchestrateShardTraffic(u,{headers:_,table:w.table});return Response.json(R,{headers:{"content-type":"application/json"},status:200})},m=async(g,p)=>{if(g.method!=="POST")throw new s("PITR endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});if(!n(g))throw new s("admin PITR endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403});const w=await Un(g),{headers:_}=await i(g,p),R=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:w.args,functionPath:w.functionPath}),headers:_,method:"POST"});return r(u,w.shardKey??t,R)};return{[On]:l,[En]:m,[Tn]:y,[_n]:O,[Rn]:A}},$n=1,Ln=0,Bn=32,xn=512,Cn=/^[a-z][\d_a-z*/-]{0,255}(?:@[a-z][\d_a-z*/-]{0,13})?=[\u0020-\u002B\u002D-\u003C\u003E-\u007E]{1,256}$/,jn=e=>{if(e==null)return;const t=e.trim();if(t.length===0||t.length>xn)return;const r=t.split(",");if(!(r.length>Bn)){for(const n of r)if(!Cn.test(n.trim()))return;return t}},Gn=e=>{const t=sr(e.headers.get("traceparent"));if(t===void 0)return;const r=jn(e.headers.get("tracestate"));return{parentSpanId:t.parentSpanId,sampled:t.sampled,traceId:t.traceId,...r===void 0?{}:{traceState:r}}},Mn=(e,t={})=>{const r=Gn(e),n=t.trustInbound===!0?r:void 0,a=Re(8),i=n?.traceId??Re(16),u=yr(t.sampling,n===void 0?a:i),l=u.isTraced&&(n===void 0||n.sampled);return{decision:u,ignoredUpstream:r!==void 0&&n===void 0,trace:{sampled:l,spanId:a,traceFlags:l?$n:Ln,traceId:i,...n?.parentSpanId===void 0?{}:{parentSpanId:n.parentSpanId},...n?.traceState===void 0?{}:{traceState:n.traceState}}}},Kn=(e,t)=>{t.traceparent=ar(e.traceId,e.spanId,e.sampled),e.traceState!==void 0&&(t.tracestate=e.traceState)},Qn=(e,t)=>{let r;return()=>{if(r===void 0){const n=cr(e),a=t===void 0?void 0:t.cf;r=ir(ur(n),dr(n,a))}return r}},Fn="/_lunora/admin/scheduled",zn="/_lunora/admin/scheduled/status",Wn="/_lunora/admin/scheduled/ws",Hn="/_lunora/admin/scheduled/cancel",Jn="/_lunora/admin/scheduled/dead",Vn="/_lunora/admin/scheduled/dead/retry",Yn="/_lunora/admin/scheduled/dead/cancel",Xn=e=>{const{checkWsAdmin:t,requireSchedulerNamespace:r,resolveSchedulerStub:n,schedulerInstanceName:a}=e,i=async m=>{if(m.method!=="GET")throw new s("Scheduled-list endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});return n(m).fetch(new Request("https://scheduler.internal/list",{method:"GET"}))},u=async m=>{if(m.method!=="GET")throw new s("Scheduler-status endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});return n(m).fetch(new Request("https://scheduler.internal/status",{method:"GET"}))},l=async m=>{if(m.headers.get("Upgrade")!=="websocket")throw new s("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});if(!await t(m))throw new s("admin authorization required",{code:"ADMIN_FORBIDDEN",status:403});const g=r();return Se(g,a).fetch(new Request("https://scheduler.internal/ws",{headers:{Upgrade:"websocket"}}))},y=async m=>{if(m.method!=="POST")throw new s("Scheduled-cancel endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const g=n(m),p=await m.json().catch(()=>{});if(typeof p?.id!="string"||p.id==="")throw new s("Scheduled-cancel requires a string `id`",{code:"BAD_REQUEST",status:400});return g.fetch(new Request("https://scheduler.internal/cancel",{body:JSON.stringify({id:p.id}),headers:{"content-type":"application/json"},method:"POST"}))},O=async m=>{if(m.method!=="GET")throw new s("Scheduled dead-letter endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});return n(m).fetch(new Request("https://scheduler.internal/dead",{method:"GET"}))},A=m=>async g=>{if(g.method!=="POST")throw new s("Scheduled dead-letter action requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const p=n(g),w=await g.json().catch(()=>{});if(typeof w?.id!="string"||w.id==="")throw new s("Scheduled dead-letter action requires a string `id`",{code:"BAD_REQUEST",status:400});return p.fetch(new Request(`https://scheduler.internal${m}`,{body:JSON.stringify({id:w.id}),headers:{"content-type":"application/json"},method:"POST"}))};return{[Hn]:y,[Yn]:A("/dead/cancel"),[Jn]:O,[Vn]:A("/dead/retry"),[Fn]:i,[zn]:u,[Wn]:l}},Zn="/_lunora/admin/storage",eo="/_lunora/admin/storage/url",to="/_lunora/admin/storage/buckets",ro=10080*60,no=e=>{const{assertAdmin:t,parsePaging:r,queryParameter:n,readBodyBytes:a,requireAdminOption:i,storage:u}=e,l=w=>{const _=n(w,"key");if(_===void 0)throw new s("Storage endpoint requires a `key` query parameter",{code:"BAD_REQUEST",status:400});return _},y=async w=>{const _=i(w,u.storageList,{code:"STORAGE_NOT_CONFIGURED",message:"storage endpoint requires a `storageList` function on the worker"}),R=new URL(w.url),P=await _(n(R,"prefix"),{bucket:n(R,"bucket"),cursor:n(R,"cursor"),...r(w)});return Response.json(P,{headers:{"content-type":"application/json"},status:200})},O=w=>{if(w.method!=="GET")throw new s("Storage-buckets endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});return t(w),Response.json({buckets:u.storageBuckets??[]},{headers:{"content-type":"application/json"},status:200})},A=async w=>{const _=i(w,u.storageDelete,{code:"STORAGE_DELETE_NOT_CONFIGURED",message:"storage delete requires a `storageDelete` function on the worker"}),R=new URL(w.url),P=l(R);return await _(P,{bucket:n(R,"bucket")}),Response.json({deleted:!0,key:P},{headers:{"content-type":"application/json"},status:200})},m=async w=>{const _=i(w,u.storageUpload,{code:"STORAGE_UPLOAD_NOT_CONFIGURED",message:"storage upload requires a `storageUpload` function on the worker"}),R=new URL(w.url),P=l(R),T=await a(w),L=w.headers.get("content-type"),B=L===null||L===""?void 0:L,M=await _(P,T,{bucket:n(R,"bucket"),contentType:B});return Response.json(M,{headers:{"content-type":"application/json"},status:200})},g=async w=>{switch(w.method){case"DELETE":return A(w);case"GET":return y(w);case"POST":case"PUT":return m(w);default:throw new s("Storage endpoint requires GET, PUT, POST, or DELETE",{code:"METHOD_NOT_ALLOWED",status:405})}},p=async w=>{if(w.method!=="GET")throw new s("Storage URL endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});const _=i(w,u.storageSignedUrl,{code:"STORAGE_URL_NOT_CONFIGURED",message:"storage URL endpoint requires a `storageSignedUrl` function on the worker"}),R=new URL(w.url),P=l(R),T=Number(n(R,"expiresIn")??""),L=Number.isFinite(T)&&T>0?Math.min(T,ro):void 0,B=await _(P,{bucket:n(R,"bucket"),expiresInSeconds:L});return Response.json({key:P,url:B},{headers:{"content-type":"application/json"},status:200})};return{[to]:O,[Zn]:g,[eo]:p}},oo=(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},ao={mtls:e=>oo(e,"tlsClientAuth","certVerified")==="SUCCESS"},so=e=>e===void 0||e===!1?()=>!1:e===!0?()=>!0:typeof e=="function"?e:Object.entries(ao).find(([t])=>t===e)?.[1]??(()=>!1),io=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.'))}},uo="/_lunora/admin/vector/indexes",co="/_lunora/admin/vector/query",lo=e=>{const{readJsonBody:t,requireAdminOption:r}=e,n=async i=>{if(i.method!=="GET")throw new s("Vector-indexes endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});const u=r(i,e.vectorIntrospector,{code:"VECTORS_NOT_CONFIGURED",message:"vector endpoints require a `vectorIntrospector` on the worker"});return Response.json({indexes:await u.listIndexes()},{headers:{"content-type":"application/json"},status:200})},a=async i=>{if(i.method!=="POST")throw new s("Vector-query endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const u=r(i,e.vectorIntrospector,{code:"VECTORS_NOT_CONFIGURED",message:"vector endpoints require a `vectorIntrospector` on the worker"});if(u.queryIndex===void 0)throw new s("vector index querying is not enabled on this worker",{code:"VECTOR_QUERY_UNSUPPORTED",status:400});const l=await t(i);if(typeof l.name!="string"||l.name==="")throw new s("Vector-query request requires a `name` string",{code:"BAD_REQUEST",status:400});if(typeof l.text!="string"||l.text==="")throw new s("Vector-query request requires a `text` string",{code:"BAD_REQUEST",status:400});if(l.topK!==void 0&&(typeof l.topK!="number"||!Number.isInteger(l.topK)||l.topK<1))throw new s("Vector-query `topK` must be a positive integer",{code:"BAD_REQUEST",status:400});const y=await u.queryIndex({name:l.name,text:l.text,topK:l.topK});return Response.json(y,{headers:{"content-type":"application/json"},status:200})};return{[uo]:n,[co]:a}},ho="/_lunora/admin/workflows/instances",po="/_lunora/admin/workflows/instance",fo="/_lunora/admin/workflows/status",wo={complete:!0,errored:!0,paused:!0,queued:!0,running:!0,terminated:!0,unknown:!0,waiting:!0,waitingForPause:!0},mo=e=>e!==null&&Object.hasOwn(wo,e)?e:void 0,it=(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},Be=(e,t)=>{const r=e.searchParams.get(t);if(r===null||r==="")throw new s(`Workflows admin endpoint requires a \`${t}\` query parameter`,{code:"BAD_REQUEST",status:400});return r},dt=()=>{throw new s("Workflow inspection is unconfigured. Set CLOUDFLARE_ACCOUNT_ID + CLOUDFLARE_API_TOKEN in your .dev.vars to enable it.",{code:"WORKFLOWS_NOT_CONFIGURED",status:501})},yo=e=>{const{assertAdmin:t,resolveWorkflowsClient:r}=e,n=async(u,l,y)=>{if(u.method!=="GET")throw new s("Workflows instances endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});t(u);const O=r(l);if(!O)return Response.json({configured:!1,instances:[],page:1,perPage:0,totalCount:0});const A=Be(y,"name"),m=mo(y.searchParams.get("status"));return Response.json(await O.listInstances({page:it(y,"page"),perPage:it(y,"perPage"),status:m,workflowName:A}))},a=async(u,l,y)=>{if(u.method!=="GET")throw new s("Workflows instance endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});t(u);const O=r(l);return O?Response.json(await O.getInstance({instanceId:Be(y,"id"),workflowName:Be(y,"name")})):dt()},i=async(u,l)=>{if(u.method!=="POST")throw new s("Workflows status endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});t(u);const y=r(l);if(!y)return dt();const O=await u.json().catch(()=>{});if(typeof O?.name!="string"||O.name===""||typeof O.id!="string"||O.id==="")throw new s("Workflows status action requires string `name` and `id`",{code:"BAD_REQUEST",status:400});const{action:A}=O;if(A!=="pause"&&A!=="resume"&&A!=="terminate")throw new s("Workflows status action must be one of: pause, resume, terminate",{code:"BAD_REQUEST",status:400});return Response.json(await y.setInstanceStatus({action:A,instanceId:O.id,workflowName:O.name}))};return{[po]:a,[ho]:n,[fo]:i}},go=new TextEncoder,ut="/_lunora/rpc",bo="/_lunora/rpc-batch",Oo="/_lunora/ws",Ee=(e,t,r)=>({resourceAttributes:Qn(e,t),...r===void 0?{}:{waitUntil:r}}),ct=e=>e?.waitUntil?{waitUntil:t=>e.waitUntil?.(t)}:{},lt=e=>({spanId:e.spanId,traceFlags:e.traceFlags,traceId:e.traceId,...e.parentSpanId===void 0?{}:{parentSpanId:e.parentSpanId}}),xe=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 a=n.port===""?void 0:Number(n.port);return{host:n.hostname,method:t,path:n.pathname,port:Number.isNaN(a)?void 0:a,scheme:n.protocol.replace(":",""),userAgent:r}},ht="/_lunora/voice/",Eo="/_lunora/scheduler/dispatch",To="/_lunora/admin/cron-jobs/run",_o="/_lunora/admin/ws-token",Ro="/_lunora/admin/",So="/_lunora/migrate",Ao="/_lunora/status",vo=e=>e.startsWith(Ro)||e===So,Do=new Set(["1","enabled","on","true","yes"]),ko=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}}},Io="/api/auth",Po="__lunora_admin__:recordAuthEvent",No="__lunora_admin__:listPushSubscriptions",Uo=["/sign-in","/sign-up","/callback"],qo=(e,t)=>{const r=t.endsWith("/")?t.slice(0,-1):t;if(!e.startsWith(`${r}/`))return!1;const n=e.slice(r.length);return Uo.some(a=>n===a||n.startsWith(`${a}/`))},Te=(e,t,r,n)=>{const a=rr(r),i=a?r.code:"INTERNAL_SERVER_ERROR",u=a?r.status:500,l=r instanceof Error?r.message:String(r);return{durationMs:t,error:{code:i,message:l,status:u},functionPath:e,ok:!1,...n.fanOut?{fanOut:{failed:0,shards:0,table:n.fanOut.table}}:{},...n.shardKey?{shardKey:n.shardKey}:{}}},$o=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},pt=e=>e.waitUntil?{waitUntil:t=>{e.waitUntil?.(t)}}:void 0,Lo=e=>{const t=e?.queue;return typeof t=="string"&&t.length>0?t:"unknown"},ue=async(e,t,r)=>{const n={"content-type":"application/json"},a=e.headers.get("authorization"),i=e.headers.get("cookie"),u=e.headers.get("x-d1-bookmark"),l=e.headers.get("x-lunora-mutation-id"),y=e.headers.get("x-lunora-client-id"),O=e.headers.get("x-lunora-client-seq");a&&(n.authorization=a),i&&(n.cookie=i),u&&(n["x-d1-bookmark"]=u),l&&(n["x-lunora-mutation-id"]=l),y&&(n["x-lunora-client-id"]=y),O&&(n["x-lunora-client-seq"]=O);const A=e.headers.get("cf-connecting-ip");if(A&&(n["x-lunora-client-ip"]=A),!r)return{claims:null,headers:n,identity:null,userId:null};const m=await r(e,t);if(!m||typeof m.userId!="string"||m.userId.length===0)return{claims:null,headers:n,identity:null,userId:null};n["x-lunora-userid"]=m.userId;const g=$o(m);g!==void 0&&(n["x-lunora-identity-exp"]=String(g));const{userId:p,...w}=m,_=Object.keys(w).length>0?w:null;return _&&(n["x-lunora-identity"]=JSON.stringify(_)),{claims:_,headers:n,identity:m,userId:p}},Bo=new Set(["concat","first","groupBy","max","min","rank","sum","topK"]),xo=e=>{if(e===void 0)return;if(!e||typeof e!="object")throw new s("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 s("RPC `fanOut.table` must be a non-empty string",{code:"BAD_REQUEST",status:400});if(!t.merge||typeof t.merge!="object")throw new s("RPC `fanOut.merge` must be an object",{code:"BAD_REQUEST",status:400});const r=t.merge;if(typeof r.kind!="string"||!Bo.has(r.kind))throw new s("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 s("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 s("RPC `fanOut.merge.by` must be a non-empty string",{code:"BAD_REQUEST",status:400})}return t},Co=(e,t)=>{e?.LUNORA_DEBUG_RPC&&console.warn(`[lunora:rpc] ${t.fanOut?"fan-out":`shard=${t.shardKey??"(root)"}`} ${t.functionPath}`)},ft=(e,t)=>{const r=t.functions?.[e.functionPath]?.x402;if(r){if(e.fanOut)throw new s("a paid (`.x402`) function cannot be fanned out",{code:"BAD_REQUEST",status:400});if(!t.x402Charge)throw new s(`function "${e.functionPath}" is marked paid (.x402) but no x402Charge gate is configured on the worker`,{code:"MISCONFIGURED",status:500});return r}},jo=async e=>{const t=await ae(e);let r;try{r=JSON.parse(t)}catch{throw new s("RPC body must be valid JSON",{code:"BAD_REQUEST",status:400})}if(!r||typeof r!="object"||typeof r.functionPath!="string")throw new s("RPC envelope is missing `functionPath`",{code:"BAD_REQUEST",status:400});const n=r;if(n.args!==void 0&&(typeof n.args!="object"||n.args===null||Array.isArray(n.args)))throw new s("RPC `args` must be an object",{code:"BAD_REQUEST",status:400});if(n.shardKey!==void 0&&typeof n.shardKey!="string")throw new s("RPC `shardKey` must be a string",{code:"BAD_REQUEST",status:400});const a=r,i=xo(a.fanOut),u=a.args??{};if(i&&a.functionPath.startsWith("__lunora_relation__:")){const l=u.table;if(typeof l=="string"&&l!==i.table)throw new s("RPC `args.table` must match the authorized `fanOut.table` for a relation fan-out",{code:"BAD_REQUEST",status:400});u.table=i.table}return{args:u,fanOut:i,functionPath:a.functionPath,shardKey:a.shardKey}},oe=async(e,t,r)=>Se(e,t).fetch(r),_e=new Map,Go=5e3,Mo=4096,Ko=async(e,t)=>{const r=Date.now(),n=_e.get(t);if(n!==void 0&&n.expiresMs>r)return n.relayCount;n!==void 0&&_e.delete(t);let a=0;try{const i=await Se(e,t).fetch(new Request("https://shard.internal/_lunora/route"));if(i.ok){const u=(await i.json()).relayCount;typeof u=="number"&&u>0&&(a=Math.floor(u))}}catch{a=0}return mt(_e,Mo),_e.set(t,{expiresMs:r+Go,relayCount:a}),a},Qo=(e,t)=>{if(!(e===null||typeof e!="object")){for(const[r,n]of Object.entries(e))if(n===t)return r}},je=(e,t)=>{const r=Math.max(e.length,t.length);let n=e.length^t.length;for(let a=0;a<r;a+=1){const i=a<e.length?e.codePointAt(a)??0:0,u=a<t.length?t.codePointAt(a)??0:0;n|=i^u}return n===0},Fo=async(e,t,r)=>{if(e.length===0||r.length===0)return!1;const n=new TextEncoder,a=await crypto.subtle.importKey("raw",n.encode(e),{hash:"SHA-256",name:"HMAC"},!1,["sign"]),i=await crypto.subtle.sign("HMAC",a,n.encode(t)),u=new Uint8Array(i);let l="";for(const O of u)l+=String.fromCodePoint(O);const y=btoa(l).replaceAll("+","-").replaceAll("/","_").replaceAll("=","");return je(y,r)},wt=(e,t)=>{if(!t||t.length===0)return!1;const r=e.headers.get("authorization");if(!r)return!1;const[n,...a]=r.split(" ");return n?.toLowerCase()!=="bearer"?!1:je(t,a.join(" ").trim())},zo=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 Ir(t,n)?!0:r?!1:je(t,n)},Wo=(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 fr(`d1:${e}`,t);if(typeof r.list=="function"&&typeof r.head=="function"&&typeof r.createMultipartUpload=="function")return Pe(`r2:${e}`,!0);if(typeof r.send=="function"&&typeof r.sendBatch=="function"&&typeof r.get!="function")return Pe(`queue:${e}`,!0);if(typeof r.connectionString=="string")return Pe(`hyperdrive:${e}`,!0)},Tt=e=>{const t=so(e.trustInboundTraceContext),r=io(e.trustInboundTraceContext),n=e.defaultShardKey??"__root__",a=wr(e.resolveIdentity,e.identity),i=He(e.shardDO,e.jurisdiction),u=e.schedulerDO===void 0?void 0:He(e.schedulerDO,e.jurisdiction);let l;const y=()=>e.adminToken??l;let O;const A=()=>e.requireEphemeralWsToken??O??!1,m=o=>{const d=o??{};if(O===void 0&&e.requireEphemeralWsToken===void 0){const c=d.LUNORA_REQUIRE_EPHEMERAL_WS_TOKEN;typeof c=="string"&&c.length>0&&(O=Do.has(c.trim().toLowerCase()))}if(l!==void 0||e.adminToken!==void 0)return;const h=d.LUNORA_ADMIN_TOKEN;typeof h=="string"&&h.length>0&&(l=h)},g=new WeakSet,p=o=>wt(o,y())||g.has(o),w=async(o,d)=>{const h=await ue(o,d,e.resolveIdentity);if(g.has(o)&&h.headers.authorization===void 0){const c=y();c!==void 0&&(h.headers.authorization=`Bearer ${c}`)}return h};let _=!1;const R=o=>{if(!e.allowUnauthenticatedShardAccess){const d=o==="fan-out"?"authorizeFanOut":"authorizeShard";throw new s(`${o} access is default-denied: configure \`${d}\` on the worker, or set \`allowUnauthenticatedShardAccess: true\` to explicitly allow unauthenticated ${o} access (relying solely on per-row RLS).`,{code:o==="fan-out"?"FORBIDDEN_FANOUT":"FORBIDDEN_SHARD",status:403})}_||(_=!0,console.warn([`[lunora] SECURITY: serving ${o} access with \`allowUnauthenticatedShardAccess: true\` and no \`authorizeShard\`/\`authorizeFanOut\` — `,"any caller (including unauthenticated ones) can target any shard / fan out across the table. ","This is safe only if every table is protected by per-row RLS. Configure `authorizeShard`/`authorizeFanOut` to gate it."].join("")))},P=qn({defaultShard:n,forwardToShard:oe,isAdmin:p,queryCoordinator:e.queryCoordinator,resolveForwardContext:w,shardDO:i}),T=async(o,d,h,c,f)=>{if(e.authorizeShard&&!await e.authorizeShard(null,h))throw new s("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403});const b={"content-type":"application/json","x-lunora-system":"1"};f?.userId!==void 0&&f.userId.length>0&&(b["x-lunora-userid"]=f.userId),f?.identity!==void 0&&f.identity.length>0&&(b["x-lunora-identity"]=f.identity),c!==void 0&&c.length>0&&(b["x-lunora-mutation-id"]=c);const S=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:d,functionPath:o}),headers:b,method:"POST"});return oe(i,h,S)},L=async(o,d,h,c)=>{const f=h?.[o];if(!f||typeof f.create!="function")throw new s(`${c} targets workflow binding "${o}", which is not bound on env`,{code:"CRON_JOB_FAILED",status:500});await f.create({params:d})},B=async(o,d,h)=>L(o,d.args??{},h,`cron job "${d.name}"`),M=async(o,d)=>{if(o.workflow){await B(o.workflow,o,d);return}if(o.functionPath===void 0)throw new s(`cron job "${o.name}" has neither a function target nor a workflow target`,{code:"CRON_JOB_FAILED",status:500});const h=await T(o.functionPath,o.args??{},o.shardKey??n);if(!h.ok)throw new s(`cron job "${o.name}" (${o.functionPath}) failed with shard status ${String(h.status)}`,{code:"CRON_JOB_FAILED",status:500})},N=async(o,d,h,c)=>{const f=e.cronJobs?.[o];if(f)for(const b of f)try{await M(b,d)}catch(S){h.push(c(S))}},K=async(o,d)=>{if(!p(o))throw new s("admin endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403});if(o.method!=="POST")throw new s("cron-jobs run endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});if(!e.cronJobs)throw new s("cron-jobs run endpoint requires a `cronJobs` map on the worker",{code:"CRON_JOBS_NOT_CONFIGURED",status:400});const h=await Z(o),c=typeof h.name=="string"?h.name:"";if(c==="")throw new s("cron-jobs run endpoint requires a job `name`",{code:"BAD_REQUEST",status:400});const f=Object.values(e.cronJobs).flat().find(b=>b.name===c);if(!f)throw new s(`no cron job named "${c}" is registered`,{code:"CRON_JOB_NOT_FOUND",status:404});return await M(f,d),Response.json({name:c,ran:!0},{status:200})},Q=async o=>{const d=typeof o.pool=="string"&&o.pool.length>0?o.pool:void 0;if(!d||!u||typeof o.id!="string")return;const h=typeof o.instanceName=="string"&&o.instanceName.length>0?o.instanceName:"default";try{await u.get(u.idFromName(h)).fetch(new Request("https://scheduler.internal/complete",{body:JSON.stringify({id:o.id,pool:d}),headers:{"content-type":"application/json"},method:"POST"}))}catch{}},Y=async(o,d)=>{if(o.method!=="POST")throw new s("Scheduler dispatch endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const h=await ae(o),c=d??{},f=typeof c.LUNORA_SCHEDULER_SECRET=="string"?c.LUNORA_SCHEDULER_SECRET:void 0,b=e.adminToken??(typeof c.LUNORA_ADMIN_TOKEN=="string"?c.LUNORA_ADMIN_TOKEN:void 0),S=o.headers.get("x-lunora-scheduler-signature");let E=!1;if(S&&f?E=await Fo(f,h,S):b&&(E=wt(o,b)),!E)throw new s("Scheduler dispatch requires a valid signature or admin bearer",{code:"FORBIDDEN",status:403});let v;try{v=JSON.parse(h)}catch{throw new s("Scheduler dispatch body must be valid JSON",{code:"BAD_REQUEST",status:400})}const k=v??{},U=k.args??{};if(typeof k.workflow=="string"&&k.workflow.length>0)return await L(k.workflow,U,d,"scheduled workflow"),Response.json({ok:!0},{status:200});if(typeof k.functionPath!="string"||k.functionPath.length===0)throw new s("Scheduler dispatch is missing `functionPath`",{code:"BAD_REQUEST",status:400});const q=typeof k.shardKey=="string"&&k.shardKey.length>0?k.shardKey:n,$=typeof k.id=="string"&&k.id.length>0?k.id:void 0,x=ko(o),W=await T(k.functionPath,U,q,$,x);return await Q(k),W},C=o=>{if(!p(o))throw new s("admin endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403})},G=(o,d,h)=>{if(C(o),d===void 0)throw new s(h.message,{code:h.code,status:400});return d},J=$r({assertAdmin:C,getReader:()=>e.authAuditReader}),re=async(o,d)=>{C(o);const h=e.notifySubscriptionStore;if(h===void 0)return Response.json({subscriptions:[]},{headers:{"content-type":"application/json"},status:200});const c=d?.kind,f=d?.userId,b=d?.limit,S=c==="fcm"||c==="web-push"?c:void 0,E=typeof f=="string"&&f!==""?f:void 0,v=typeof b=="number"&&Number.isFinite(b)?Math.trunc(b):0,k=v>0?Math.min(v,1e3):1e3,U=(await h.list({kind:S,limit:k,userId:E})).filter(q=>S!==void 0&&q.kind!==S?!1:E===void 0||(q.userId??null)===E).map(({keys:q,token:$,...x})=>x);return Response.json({subscriptions:U},{headers:{"content-type":"application/json"},status:200})},se=async(o,d)=>{if(!d.fanOut){if(d.functionPath===qr)return J(o,d.args??{});if(d.functionPath===No)return re(o,d.args)}},ne=Yr({applyGlobals:e.applyGlobals,exportCursorStore:e.exportCursorStore,exportSinks:e.exportSinks,knownTables:()=>bt(),queryCoordinator:e.queryCoordinator,requireAdminOption:G,resolveForwardContext:w,shardDO:i,streamExportRows:(o,d,h,c)=>nt(e,o,d,h,c,i),streamingImport:(o,d)=>nn(o,e,d,i),syncGlobals:e.syncGlobals}),he=(o,d)=>{const h=o.searchParams.get(d);return h===null||h===""?void 0:h},me=o=>{const d=new URL(o.url),h=d.searchParams.get("limit"),c=d.searchParams.get("offset"),f=h===null?void 0:Number.parseInt(h,10),b=c===null?void 0:Number.parseInt(c,10);return{limit:f!==void 0&&Number.isFinite(f)&&f>=0?f:void 0,offset:b!==void 0&&Number.isFinite(b)&&b>=0?b:void 0}},be=()=>{if(u===void 0)throw new s("scheduled endpoints require a `schedulerDO` namespace on the worker",{code:"SCHEDULER_NOT_CONFIGURED",status:400});return u},ee=Xn({checkWsAdmin:async o=>p(o)||zo(o,y(),A()),requireSchedulerNamespace:be,resolveSchedulerStub:o=>(C(o),Se(be(),e.schedulerInstanceName??"default")),schedulerInstanceName:e.schedulerInstanceName??"default"}),_t=yo({assertAdmin:C,resolveWorkflowsClient:e.workflowsClient??(()=>{})}),Rt=no({assertAdmin:C,parsePaging:me,queryParameter:he,readBodyBytes:xr,requireAdminOption:G,storage:{storageBuckets:e.storageBuckets,storageDelete:e.storageDelete,storageList:e.storageList,storageSignedUrl:e.storageSignedUrl,storageUpload:e.storageUpload}}),St=lo({readJsonBody:Z,requireAdminOption:G,vectorIntrospector:e.vectorIntrospector}),At=bn({kvIntrospector:e.kvIntrospector,readJsonBody:Z,requireAdminOption:G}),vt=mr({logArchive:e.logArchive,readJsonBody:Z,requireAdminOption:G}),Dt=mn({assertAdmin:C,options:{cronJobs:e.cronJobs,functions:e.functions,globalIntrospector:e.globalIntrospector,openApiSpec:e.openApiSpec,openRpcSpec:e.openRpcSpec},parsePaging:me,queryParameter:he,requireAdminOption:G}),kt=o=>{const d=[],h=i??o?.SHARD;if(h!==void 0&&d.push(pr("durable-object:default",h,n)),e.health?.disableBindingProbes!==!0)for(const[c,f]of Object.entries(o??{})){const b=Wo(c,f);b!==void 0&&d.push(b)}for(const c of e.health?.probes??[])d.push(c);return d},It=hr({appName:e.health?.appName,appVersion:e.health?.appVersion,auth:e.health?.auth??"public",cacheTtlMs:e.health?.cacheTtlMs,isAdmin:p,resolveProbes:kt}),Pt=async(o,d,h)=>{const{claims:c,headers:f,userId:b}=await ue(o,d,a),S=async(E,v={})=>{const k=E.__lunoraRef;if(typeof k!="string")throw new s("ctx.run*: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});const U=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:v,functionPath:k}),headers:f,method:"POST"}),q=await oe(i,n,U),$=await q.json();if($.error)throw new s($.error.message??"shard RPC failed",{code:$.error.code??"INTERNAL",status:q.status});return $.result};return{auth:{getIdentity:()=>Promise.resolve(c),userId:b},cache:h.cache,fetch:globalThis.fetch.bind(globalThis),runAction:S,runMutation:S,runQuery:S}},Nt=async(o,d,h)=>{if(!e.httpRouter)return;const c=await Pt(o,d,h);try{return await e.httpRouter.fetch(o,{...d,__lunoraCtx:c},h)}catch(f){return console.error("[lunora] httpRouter (SSR) handler threw:",f),new Response("Internal Server Error",{status:500})}},Ut=async(o,d,h)=>{if(o.headers.get("Upgrade")!=="websocket")throw new s("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});const c=Ve(o,ie);if(c)return c;const f=h.searchParams.get("shard")??n,{headers:b,identity:S}=await ue(o,d,a);if(e.authorizeShard){if(!await e.authorizeShard(S,f))throw new s("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else f!==n&&R("shard");const E=new Headers(o.headers),v=[...E.keys()];for(const x of v)x.startsWith("x-lunora-")&&E.delete(x);const k=b["x-lunora-userid"],U=b["x-lunora-identity"],q=b["x-lunora-identity-exp"];k!==void 0&&E.set("x-lunora-userid",k),U!==void 0&&E.set("x-lunora-identity",U),q!==void 0&&E.set("x-lunora-identity-exp",q);const $=Qo(d,e.shardDO);if($!==void 0){E.set("x-lunora-shard-binding",$);const x=await Ko(i,f);if(x>0){const W=Tr(f,Math.floor(Math.random()*x));return oe(i,W,new Request(o,{headers:E}))}}return oe(i,f,new Request(o,{headers:E}))},qt=async(o,d,h)=>{const{voiceAgents:c}=e;if(c===void 0)return new Response("Not found",{status:404});if(o.headers.get("Upgrade")!=="websocket")return new Response("Expected a WebSocket upgrade",{headers:{allow:"GET"},status:426});const f=Ve(o,ie);if(f)return f;let b;try{b=decodeURIComponent(h.pathname.slice(ht.length))}catch{return new Response("Unknown voice agent",{status:404})}const S=Object.hasOwn(c,b)?c[b]:void 0;if(S===void 0)return new Response("Unknown voice agent",{status:404});const E=h.searchParams.get("threadKey");if(E===null||E.length===0)return new Response("Missing threadKey",{status:400});const{headers:v,identity:k}=await ue(o,d,a);if(e.authorizeShard){if(!await e.authorizeShard(k,E))return new Response("Forbidden",{status:403})}else R("shard");const U=new Headers(o.headers);U.delete("x-lunora-userid"),U.delete("x-lunora-identity"),U.delete("x-lunora-identity-exp");const q=v["x-lunora-userid"],$=v["x-lunora-identity"],x=v["x-lunora-identity-exp"];return q!==void 0&&U.set("x-lunora-userid",q),$!==void 0&&U.set("x-lunora-identity",$),x!==void 0&&U.set("x-lunora-identity-exp",x),oe(S,E,new Request(o,{headers:U}))},$t=async(o,d,h)=>{if(e.authorizeFanOut){if(!await e.authorizeFanOut(h,o.table,d))throw new s("Forbidden fan-out",{code:"FORBIDDEN_FANOUT",status:403});return}if(d.startsWith("__lunora_relation__:"))throw new s("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 s("Fan-out requires `authorizeFanOut` to be configured on the worker when `authorizeShard` is set",{code:"FORBIDDEN_FANOUT",status:403});R("fan-out")},Oe=async(o,d)=>{if(!(!o.fanOut&&o.functionPath.startsWith("__lunora_admin__:"))){if(o.fanOut){await $t(o.fanOut,o.functionPath,d);return}if(e.authorizeShard){const h=o.shardKey??n;if(!await e.authorizeShard(d,h))throw new s("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else o.shardKey!==void 0&&o.shardKey!==n&&R("shard")}},Ae=async(o,d,h,c,f,b)=>{const S=Date.now(),{observability:E,sampling:v}=e,k=xe(o),{decision:U,ignoredUpstream:q,trace:$}=Mn(o,{...v===void 0?{}:{sampling:v},trustInbound:t(o)});q&&r();const x={...f,"x-lunora-sample-errors":U.keepErrors?"1":"0"};Kn($,x);const W=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:h,functionPath:d}),headers:x,method:"POST"});try{const j=await oe(i,c,W);return de(E,{...k,...lt($),durationMs:Date.now()-S,functionPath:d,ok:j.ok,shardKey:c,...j.ok?{}:{error:{code:"SHARD_ERROR",message:`shard returned ${String(j.status)}`,status:j.status}}},b,void 0,{isTraced:$.sampled,keepErrors:U.keepErrors}),j}catch(j){throw de(E,{...k,...lt($),...Te(d,Date.now()-S,j,{shardKey:c})},b,void 0,{isTraced:$.sampled,keepErrors:U.keepErrors}),j}},Lt=o=>{if(o.fanOut&&o.shardKey)throw new s("RPC envelope cannot set both `shardKey` and `fanOut`",{code:"BAD_REQUEST",status:400});if(!o.fanOut&&o.functionPath.startsWith("__lunora_relation__:"))throw new s("`__lunora_relation__:*` is a fan-out-only reserved RPC and cannot be dispatched to a single shard",{code:"FORBIDDEN",status:403});if(o.fanOut&&!e.queryCoordinator)throw new s("RPC envelope set `fanOut` but no `queryCoordinator` is configured on the worker",{code:"BAD_REQUEST",status:400})},Bt=async(o,d,h)=>{if(o.method!=="POST")throw new s("RPC endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const c=await jo(o);Co(d,c),Lt(c);const f=await se(o,c);if(f!==void 0)return f;const{headers:b,identity:S}=await ue(o,d,a);await Oe(c,S);const E=ft(c,e);{const v=Date.now(),{observability:k}=e,U=xe(o),q=Ee(d,o,h&&(W=>h.waitUntil?.(W)));if(c.fanOut){const W=e.queryCoordinator;if(!W)throw new s("RPC envelope set `fanOut` but no `queryCoordinator` is configured on the worker",{code:"BAD_REQUEST",status:400});try{const j=await W.fanOut(i,{args:c.args??{},fanOut:c.fanOut,functionPath:c.functionPath,headers:b});return de(k,{durationMs:Date.now()-v,fanOut:{failed:j.failed,shards:j.ok+j.failed,table:c.fanOut.table},functionPath:c.functionPath,...U,ok:!0},q),Response.json(j,{headers:{"content-type":"application/json"},status:200})}catch(j){throw de(k,{...Te(c.functionPath,Date.now()-v,j,{fanOut:{table:c.fanOut.table}}),...U},q),j}}const $=c.shardKey??n,x=()=>Ae(o,c.functionPath,c.args??{},$,b,q);return E&&e.x402Charge?e.x402Charge(o,{functionPath:c.functionPath,price:E.price},x,ct(h)):x()}},xt=async(o,d,h)=>{if(o.method!=="POST")throw new s("RPC batch endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const c=await ae(o);let f;try{f=JSON.parse(c)}catch{throw new s("RPC batch body must be valid JSON",{code:"BAD_REQUEST",status:400})}if(typeof f!="object"||f===null||Array.isArray(f))throw new s("RPC batch body must be an object",{code:"BAD_REQUEST",status:400});const{calls:b}=f;if(!Array.isArray(b))throw new s("RPC batch `calls` must be an array",{code:"BAD_REQUEST",status:400});const{headers:S,identity:E}=await ue(o,d,a),v=Br(b,n);for(const F of v.values())for(const z of F)if(e.functions?.[z.functionPath]?.x402)throw new s(`paid (\`.x402\`) function "${z.functionPath}" cannot be called in a batch; dispatch it individually over ${ut}`,{code:"BAD_REQUEST",status:400});await Promise.all([...v.entries()].flatMap(([F,z])=>z.map(te=>Oe({functionPath:te.functionPath,shardKey:F},E))));const{observability:k}=e,U=Ee(d,o,h&&(F=>h.waitUntil?.(F))),q=xe(o),$=[],x=[],W=(F,z,te,ce)=>({body:{error:{code:te,message:ce}},id:F.id,status:z}),j=(F,z,te,ce,pe)=>{for(const H of F)de(k,pe(H),U),$.push(W(H,z,te,ce))},Xt=(F,z,te,ce,pe)=>{for(const H of F){const fe=ce.get(H.id)??pe,ye=fe<400;de(k,{durationMs:te,functionPath:H.functionPath,...q,ok:ye,shardKey:z,...ye?{}:{error:{code:"SHARD_ERROR",message:`batched call returned ${String(fe)}`,status:fe}}},U)}};await Promise.all([...v.entries()].map(async([F,z])=>{const te=new Headers(S);te.set("content-type","application/json");const ce=new Request("https://shard.internal/rpc-batch",{body:JSON.stringify({calls:z}),headers:te,method:"POST"}),pe=Date.now();let H;try{H=await oe(i,F,ce)}catch(V){const Ie=Date.now()-pe,{body:Fe}=nr(V,{fallbackCode:"SHARD_UNAVAILABLE",redactedMessage:"shard unavailable"});j(z,502,Fe.code,Fe.message,tr=>({...Te(tr.functionPath,Ie,V,{shardKey:F}),...q}));return}const fe=Date.now()-pe,ye=H.headers.get("x-d1-bookmark");ye&&x.push(ye);let De;try{De=await H.json()}catch{const V=`shard batch returned a non-JSON response (${String(H.status)})`;j(z,H.status,"SHARD_ERROR",V,Ie=>({durationMs:fe,error:{code:"SHARD_ERROR",message:V,status:H.status},functionPath:Ie.functionPath,...q,ok:!1,shardKey:F}));return}const ke=Array.isArray(De.results)?De.results:[],Zt=new Map(ke.map(V=>[V.id,V.status??H.status])),er=new Set(ke.map(V=>V.id));Xt(z,F,fe,Zt,H.status),$.push(...ke);for(const V of z)er.has(V.id)||$.push(W(V,H.status,"SHARD_ERROR",`shard batch omitted result for call ${String(V.id)}`))}));const Ke={"content-type":"application/json"},[Qe]=x;return x.length===1&&Qe!==void 0&&(Ke["x-d1-bookmark"]=Qe),Response.json({results:$},{headers:Ke,status:200})},Ct=async(o,d,h,c={},f={})=>{try{const b=h.__lunoraRef;if(typeof b!="string")throw new s("serverQuery: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});const{headers:S,identity:E}=await ue(o,d,a);await Oe({functionPath:b,shardKey:f.shardKey},E);const v=f.shardKey??n,k=Ee(d,o,f.waitUntil);return await Ae(o,b,c,v,S,k)}catch(b){return ze(b)}},jt=1e3,Gt=async(o,d)=>{const h=e.backupRetain;if(h===void 0||h<=0)return;const c=[];let f;for(let S=0;S<jt;S+=1){const E=await o.list({cursor:f,prefix:d});for(const v of E.objects)v.key.endsWith(".manifest.json")&&c.push(v.key);if(!E.truncated||E.cursor===void 0)break;f=E.cursor}const b=c.toSorted((S,E)=>E.localeCompare(S)).slice(h);await Promise.all(b.flatMap(S=>{const E=S.slice(0,-14);return[o.delete(S),o.delete(E)]}))},Mt=async o=>{const d=e.backupStore,h=e.queryCoordinator;if(!d)throw new s("scheduled backup requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});if(!h)throw new s("scheduled backup requires a `queryCoordinator` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});const c=y();if(!c||c.length===0)throw new s("scheduled backup requires an `adminToken` (or `env.LUNORA_ADMIN_TOKEN`) to authenticate the per-shard export gate",{code:"BACKUP_NOT_CONFIGURED",status:500});const f={authorization:`Bearer ${c}`,"content-type":"application/json"},b=e.backupTables;let S=0,E=0;const v=[];await nt(e,h,f,b,W=>{const j=`${JSON.stringify(W)}
|
|
4
|
+
`)}}return O.length>0&&m(O),{errors:n,globalRows:a,perShard:i}},ot=(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},nn=async(e,t,r,n)=>{const a=t.defaultShardKey??"__root__",{errors:i,globalRows:u,perShard:l}=await rn(e,t,a),y={conflicts:0,errors:i,inserted:{}};if(l.size>0){const O=t.queryCoordinator;if(!O)throw new s("Import endpoint requires a `queryCoordinator` on the worker",{code:"BAD_REQUEST",status:400});const A=await O.orchestrateImport(n,{batches:[...l.values()],headers:r});ot(y,A)}if(u.length>0)if(t.importGlobals){const O=u[0]?.line??1,A=await t.importGlobals({rows:u,startLine:O});ot(y,A)}else for(const O of u)y.errors.push({code:"GLOBAL_NOT_CONFIGURED",line:O.line,message:`row targets global table "${O.table}" but no \`importGlobals\` is configured`,table:O.table});return{conflicts:y.conflicts,errors:y.errors,inserted:y.inserted}},$e=e=>typeof e=="object"&&e!==null?e:{},Le=e=>typeof e.kind=="string"?e.kind:"unknown",on=(e,t)=>{let r=$e(t),n=!1;Le(r)==="optional"&&(n=!0,r=$e(r._meta?.inner));const a=Le(r),i=r._meta??{},u={kind:a,name:e,optional:n};if(a==="id"&&typeof i.tableName=="string"&&(u.table=i.tableName),a==="array"){const l=Le($e(i.inner));l!=="unknown"&&(u.element=l)}return u},an=e=>typeof e!="object"||e===null?[]:Object.entries(e).map(([t,r])=>on(t,r)).toSorted((t,r)=>t.name.localeCompare(r.name)),sn="/_lunora/admin/functions",dn="/_lunora/admin/cron-jobs",un="/_lunora/admin/openapi",cn="/_lunora/admin/openrpc",ln="/_lunora/admin/global/tables",hn="/_lunora/admin/global/table",pn="/_lunora/admin/global/facet",at=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:a,value:i}=n;return[{column:a,value:i}]});return r.length===0?void 0:r},fn=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:{}}),wn=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"}),mn=e=>{const{assertAdmin:t,options:r,parsePaging:n,queryParameter:a,requireAdminOption:i}=e,u=p=>{if(p.method!=="GET")throw new s("Functions endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});const w=i(p,r.functions,{code:"FUNCTIONS_NOT_CONFIGURED",message:"functions endpoint requires a `functions` registry on the worker"}),_=Object.entries(w).flatMap(([R,P])=>P.visibility==="internal"||P.kind==="stream"?[]:[{args:an(P.args),kind:P.kind,path:R}]).toSorted((R,P)=>R.path.localeCompare(P.path));return Response.json({functions:_},{headers:{"content-type":"application/json"},status:200})},l=p=>{if(p.method!=="GET")throw new s("Cron-jobs endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});const w=i(p,r.cronJobs,{code:"CRON_JOBS_NOT_CONFIGURED",message:"cron-jobs endpoint requires a `cronJobs` map on the worker"}),_=Object.entries(w).flatMap(([R,P])=>P.map(T=>({args:T.args,cron:R,functionPath:T.functionPath,name:T.name,shardKey:T.shardKey,workflow:T.workflow}))).toSorted((R,P)=>R.name.localeCompare(P.name));return Response.json({jobs:_},{headers:{"content-type":"application/json"},status:200})},y=p=>{if(p.method!=="GET")throw new s("OpenAPI endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});return t(p),Response.json(r.openApiSpec??fn,{headers:{"content-type":"application/json"},status:200})},O=p=>{if(p.method!=="GET")throw new s("OpenRPC endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});return t(p),Response.json(r.openRpcSpec??wn,{headers:{"content-type":"application/json"},status:200})},A=async p=>{if(p.method!=="GET")throw new s("Global-tables endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});const w=i(p,r.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"});return Response.json(await w.listTables(),{headers:{"content-type":"application/json"},status:200})},m=async p=>{if(p.method!=="GET")throw new s("Global-table endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});const w=i(p,r.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),_=new URL(p.url),R=a(_,"table");if(R===void 0)throw new s("Global-table endpoint requires a `table` query param",{code:"BAD_REQUEST",status:400});const P=await w.readTablePage({...n(p),filters:at(a(_,"filters")),table:R});return Response.json(P,{headers:{"content-type":"application/json"},status:200})},g=async p=>{if(p.method!=="GET")throw new s("Global-facet endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});const w=i(p,r.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),_=new URL(p.url),R=a(_,"table"),P=a(_,"column");if(R===void 0||P===void 0)throw new s("Global-facet endpoint requires `table` and `column` query params",{code:"BAD_REQUEST",status:400});const T=a(_,"limit"),L=T===void 0?void 0:Number(T),B=await w.facetColumn({column:P,filters:at(a(_,"filters")),limit:L!==void 0&&Number.isFinite(L)?L:void 0,table:R});return Response.json(B,{headers:{"content-type":"application/json"},status:200})};return{[dn]:l,[sn]:u,[pn]:g,[hn]:m,[ln]:A,[un]:y,[cn]:O}},yn="/_lunora/admin/kv/namespaces",gn="/_lunora/admin/kv/keys",Ot="/_lunora/admin/kv/value",Et=32*1048576,st=60,bn=e=>{const{readJsonBody:t,requireAdminOption:r}=e,n=m=>r(m,e.kvIntrospector,{code:"KV_NOT_CONFIGURED",message:"KV endpoints require a `kvIntrospector` on the worker"}),a=m=>Response.json(m,{headers:{"content-type":"application/json"},status:200}),i=(m,g)=>{const p=new URL(m.url),w=p.searchParams.get("namespace")??"",_=p.searchParams.get("key")??"";if(w==="")throw new s(`KV-value ${g} request requires a \`namespace\` query parameter`,{code:"BAD_REQUEST",status:400});if(_==="")throw new s(`KV-value ${g} request requires a \`key\` query parameter`,{code:"BAD_REQUEST",status:400});return{key:_,namespace:w}},u=async(m,g)=>{if(!(await m.listNamespaces()).some(p=>p.binding===g))throw new s(`Unknown KV namespace binding \`${g}\``,{code:"NOT_FOUND",status:404})},l=async m=>{if(m.method!=="GET")throw new s("KV-namespaces endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});return a({namespaces:await n(m).listNamespaces()})},y=async m=>{if(m.method!=="GET")throw new s("KV-keys endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});const g=n(m),p=new URL(m.url),w=p.searchParams.get("namespace")??"";if(w==="")throw new s("KV-keys request requires a `namespace` query parameter",{code:"BAD_REQUEST",status:400});const _=p.searchParams.get("prefix")??void 0,R=p.searchParams.get("cursor")??void 0,P=p.searchParams.get("limit"),T=P===null?void 0:Number.parseInt(P,10);if(T!==void 0&&(!Number.isInteger(T)||T<1))throw new s("KV-keys `limit` must be a positive integer",{code:"BAD_REQUEST",status:400});const L=T===void 0?void 0:Math.min(T,1e3);return await u(g,w),a(await g.listKeys({cursor:R,limit:L,namespace:w,prefix:_}))},O={DELETE:async m=>{const g=n(m),p=i(m,"DELETE");return await u(g,p.namespace),await g.deleteKey(p),a({deleted:!0})},GET:async m=>{const g=n(m),p=i(m,"GET");return await u(g,p.namespace),a(await g.getValue(p))},PUT:async m=>{const g=n(m),p=await t(m,Et);if(typeof p.namespace!="string"||p.namespace==="")throw new s("KV-value PUT request requires a `namespace` string",{code:"BAD_REQUEST",status:400});if(typeof p.key!="string"||p.key==="")throw new s("KV-value PUT request requires a `key` string",{code:"BAD_REQUEST",status:400});if(typeof p.value!="string")throw new s("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<st))throw new s("KV-value PUT `expirationTtl` must be an integer ≥ 60",{code:"BAD_REQUEST",status:400});const w=Math.floor(Date.now()/1e3)+st;if(p.expiration!==void 0&&(typeof p.expiration!="number"||!Number.isInteger(p.expiration)||p.expiration<w))throw new s("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(g,p.namespace),await g.putValue({expiration:p.expiration,expirationTtl:p.expirationTtl,key:p.key,metadata:p.metadata,namespace:p.namespace,value:p.value}),a({ok:!0})}},A=m=>{const g=O[m.method];if(!g)throw new s("KV-value endpoint requires GET, PUT, or DELETE",{code:"METHOD_NOT_ALLOWED",status:405});return g(m)};return{[yn]:l,[gn]:y,[Ot]:A}},On="/_lunora/migrate",En="/_lunora/admin/pitr",Tn="/_lunora/admin/rank",_n="/_lunora/admin/rankpage",Rn="/_lunora/admin/shard-traffic",Sn=new Set(["__lunora_admin__:migrationStatus","__lunora_admin__:runMigration"]),An=new Set(["__lunora_admin__:getPitrBookmark","__lunora_admin__:pitrRestore"]),vn=async e=>{let t;try{const n=await ae(e);t=n===""?{}:JSON.parse(n)}catch(n){throw n instanceof s?n:new s("Migration body must be valid JSON",{code:"BAD_REQUEST",status:400})}const r=t??{};if(typeof r.table!="string"||r.table.length===0)throw new s("Migration request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof r.functionPath!="string"||!Sn.has(r.functionPath))throw new s("Migration request `functionPath` must be a migration admin op",{code:"BAD_REQUEST",status:400});return{args:r.args??{},functionPath:r.functionPath,table:r.table}},Dn=async e=>{let t;try{const n=await ae(e);t=n===""?{}:JSON.parse(n)}catch(n){throw n instanceof s?n:new s("Rank body must be valid JSON",{code:"BAD_REQUEST",status:400})}const r=t??{};if(typeof r.table!="string"||r.table.length===0)throw new s("Rank request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof r.index!="string"||r.index.length===0)throw new s("Rank request is missing `index`",{code:"BAD_REQUEST",status:400});if(typeof r.partitionKey!="string")throw new s("Rank request `partitionKey` must be a string",{code:"BAD_REQUEST",status:400});if(typeof r.rowId!="string"||r.rowId.length===0)throw new s("Rank request is missing `rowId`",{code:"BAD_REQUEST",status:400});if(!Array.isArray(r.sortValues))throw new s("Rank request `sortValues` must be an array",{code:"BAD_REQUEST",status:400});return{index:r.index,partitionKey:r.partitionKey,rowId:r.rowId,sortValues:r.sortValues,table:r.table}},kn=e=>{if(e!==void 0){if(!Array.isArray(e)||e.some(t=>t!=="asc"&&t!=="desc"))throw new s('Rank page request `directions` must be an array of "asc"|"desc"',{code:"BAD_REQUEST",status:400});return e}},In=e=>{if(typeof e.table!="string"||e.table.length===0)throw new s("Rank page request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof e.index!="string"||e.index.length===0)throw new s("Rank page request is missing `index`",{code:"BAD_REQUEST",status:400});if(e.partitionKey!==void 0&&typeof e.partitionKey!="string")throw new s("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 s("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 s("Rank page request `cursor` must be a string or null",{code:"BAD_REQUEST",status:400})},Pn=async e=>{let t;try{const a=await ae(e);t=a===""?{}:JSON.parse(a)}catch(a){throw a instanceof s?a:new s("Rank page body must be valid JSON",{code:"BAD_REQUEST",status:400})}const r=t??{};In(r);const n=kn(r.directions);return{cursor:typeof r.cursor=="string"?r.cursor:null,directions:n,index:r.index,partitionKey:typeof r.partitionKey=="string"?r.partitionKey:void 0,table:r.table,take:typeof r.take=="number"?r.take:void 0}},Nn=async e=>{let t;try{const n=await ae(e);t=n===""?{}:JSON.parse(n)}catch(n){throw n instanceof s?n:new s("Shard-traffic body must be valid JSON",{code:"BAD_REQUEST",status:400})}const r=t??{};if(typeof r.table!="string"||r.table.length===0)throw new s("Shard-traffic request is missing `table`",{code:"BAD_REQUEST",status:400});return{table:r.table}},Un=async e=>{const t=await Z(e);if(typeof t.functionPath!="string"||!An.has(t.functionPath))throw new s("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 s("PITR `shardKey` must be a string",{code:"BAD_REQUEST",status:400});return{args:t.args??{},functionPath:t.functionPath,shardKey:t.shardKey}},qn=e=>{const{defaultShard:t,forwardToShard:r,isAdmin:n,queryCoordinator:a,resolveForwardContext:i,shardDO:u}=e,l=async(g,p)=>{if(g.method!=="POST")throw new s("Migration endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});if(!n(g))throw new s("Admin auth required",{code:"FORBIDDEN",status:403});if(!a)throw new s("Migration endpoint requires a `queryCoordinator` on the worker",{code:"BAD_REQUEST",status:400});const w=await vn(g),{headers:_}=await i(g,p),R=await a.orchestrateMigration(u,{args:w.args,functionPath:w.functionPath,headers:_,table:w.table});return Response.json(R,{headers:{"content-type":"application/json"},status:200})},y=async(g,p)=>{if(g.method!=="POST")throw new s("Rank endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});if(!n(g))throw new s("Admin auth required",{code:"FORBIDDEN",status:403});if(!a)throw new s("Rank endpoint requires a `queryCoordinator` on the worker",{code:"BAD_REQUEST",status:400});const w=await Dn(g),{headers:_}=await i(g,p),R=await a.orchestrateRank(u,{headers:_,index:w.index,partitionKey:w.partitionKey,rowId:w.rowId,sortValues:w.sortValues,table:w.table});return Response.json(R,{headers:{"content-type":"application/json"},status:200})},O=async(g,p)=>{if(g.method!=="POST")throw new s("Rank page endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});if(!n(g))throw new s("Admin auth required",{code:"FORBIDDEN",status:403});if(!a)throw new s("Rank page endpoint requires a `queryCoordinator` on the worker",{code:"BAD_REQUEST",status:400});const w=await Pn(g),{headers:_}=await i(g,p),R=await a.orchestrateRankPage(u,{...w,headers:_});return Response.json(R,{headers:{"content-type":"application/json"},status:200})},A=async(g,p)=>{if(g.method!=="POST")throw new s("Shard-traffic endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});if(!n(g))throw new s("Admin auth required",{code:"FORBIDDEN",status:403});if(!a)throw new s("Shard-traffic endpoint requires a `queryCoordinator` on the worker",{code:"BAD_REQUEST",status:400});const w=await Nn(g),{headers:_}=await i(g,p),R=await a.orchestrateShardTraffic(u,{headers:_,table:w.table});return Response.json(R,{headers:{"content-type":"application/json"},status:200})},m=async(g,p)=>{if(g.method!=="POST")throw new s("PITR endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});if(!n(g))throw new s("admin PITR endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403});const w=await Un(g),{headers:_}=await i(g,p),R=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:w.args,functionPath:w.functionPath}),headers:_,method:"POST"});return r(u,w.shardKey??t,R)};return{[On]:l,[En]:m,[Tn]:y,[_n]:O,[Rn]:A}},$n=1,Ln=0,Bn=32,xn=512,Cn=/^[a-z][\d_a-z*/-]{0,255}(?:@[a-z][\d_a-z*/-]{0,13})?=[\u0020-\u002B\u002D-\u003C\u003E-\u007E]{1,256}$/,jn=e=>{if(e==null)return;const t=e.trim();if(t.length===0||t.length>xn)return;const r=t.split(",");if(!(r.length>Bn)){for(const n of r)if(!Cn.test(n.trim()))return;return t}},Gn=e=>{const t=sr(e.headers.get("traceparent"));if(t===void 0)return;const r=jn(e.headers.get("tracestate"));return{parentSpanId:t.parentSpanId,sampled:t.sampled,traceId:t.traceId,...r===void 0?{}:{traceState:r}}},Mn=(e,t={})=>{const r=Gn(e),n=t.trustInbound===!0?r:void 0,a=Re(8),i=n?.traceId??Re(16),u=yr(t.sampling,n===void 0?a:i),l=u.isTraced&&(n===void 0||n.sampled);return{decision:u,ignoredUpstream:r!==void 0&&n===void 0,trace:{sampled:l,spanId:a,traceFlags:l?$n:Ln,traceId:i,...n?.parentSpanId===void 0?{}:{parentSpanId:n.parentSpanId},...n?.traceState===void 0?{}:{traceState:n.traceState}}}},Kn=(e,t)=>{t.traceparent=ar(e.traceId,e.spanId,e.sampled),e.traceState!==void 0&&(t.tracestate=e.traceState)},Qn=(e,t)=>{let r;return()=>{if(r===void 0){const n=cr(e),a=t===void 0?void 0:t.cf;r=ir(ur(n),dr(n,a))}return r}},Fn="/_lunora/admin/scheduled",zn="/_lunora/admin/scheduled/status",Wn="/_lunora/admin/scheduled/ws",Hn="/_lunora/admin/scheduled/cancel",Jn="/_lunora/admin/scheduled/dead",Vn="/_lunora/admin/scheduled/dead/retry",Yn="/_lunora/admin/scheduled/dead/cancel",Xn=e=>{const{checkWsAdmin:t,requireSchedulerNamespace:r,resolveSchedulerStub:n,schedulerInstanceName:a}=e,i=async m=>{if(m.method!=="GET")throw new s("Scheduled-list endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});return n(m).fetch(new Request("https://scheduler.internal/list",{method:"GET"}))},u=async m=>{if(m.method!=="GET")throw new s("Scheduler-status endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});return n(m).fetch(new Request("https://scheduler.internal/status",{method:"GET"}))},l=async m=>{if(m.headers.get("Upgrade")!=="websocket")throw new s("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});if(!await t(m))throw new s("admin authorization required",{code:"ADMIN_FORBIDDEN",status:403});const g=r();return Se(g,a).fetch(new Request("https://scheduler.internal/ws",{headers:{Upgrade:"websocket"}}))},y=async m=>{if(m.method!=="POST")throw new s("Scheduled-cancel endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const g=n(m),p=await m.json().catch(()=>{});if(typeof p?.id!="string"||p.id==="")throw new s("Scheduled-cancel requires a string `id`",{code:"BAD_REQUEST",status:400});return g.fetch(new Request("https://scheduler.internal/cancel",{body:JSON.stringify({id:p.id}),headers:{"content-type":"application/json"},method:"POST"}))},O=async m=>{if(m.method!=="GET")throw new s("Scheduled dead-letter endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});return n(m).fetch(new Request("https://scheduler.internal/dead",{method:"GET"}))},A=m=>async g=>{if(g.method!=="POST")throw new s("Scheduled dead-letter action requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const p=n(g),w=await g.json().catch(()=>{});if(typeof w?.id!="string"||w.id==="")throw new s("Scheduled dead-letter action requires a string `id`",{code:"BAD_REQUEST",status:400});return p.fetch(new Request(`https://scheduler.internal${m}`,{body:JSON.stringify({id:w.id}),headers:{"content-type":"application/json"},method:"POST"}))};return{[Hn]:y,[Yn]:A("/dead/cancel"),[Jn]:O,[Vn]:A("/dead/retry"),[Fn]:i,[zn]:u,[Wn]:l}},Zn="/_lunora/admin/storage",eo="/_lunora/admin/storage/url",to="/_lunora/admin/storage/buckets",ro=10080*60,no=e=>{const{assertAdmin:t,parsePaging:r,queryParameter:n,readBodyBytes:a,requireAdminOption:i,storage:u}=e,l=w=>{const _=n(w,"key");if(_===void 0)throw new s("Storage endpoint requires a `key` query parameter",{code:"BAD_REQUEST",status:400});return _},y=async w=>{const _=i(w,u.storageList,{code:"STORAGE_NOT_CONFIGURED",message:"storage endpoint requires a `storageList` function on the worker"}),R=new URL(w.url),P=await _(n(R,"prefix"),{bucket:n(R,"bucket"),cursor:n(R,"cursor"),...r(w)});return Response.json(P,{headers:{"content-type":"application/json"},status:200})},O=w=>{if(w.method!=="GET")throw new s("Storage-buckets endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});return t(w),Response.json({buckets:u.storageBuckets??[]},{headers:{"content-type":"application/json"},status:200})},A=async w=>{const _=i(w,u.storageDelete,{code:"STORAGE_DELETE_NOT_CONFIGURED",message:"storage delete requires a `storageDelete` function on the worker"}),R=new URL(w.url),P=l(R);return await _(P,{bucket:n(R,"bucket")}),Response.json({deleted:!0,key:P},{headers:{"content-type":"application/json"},status:200})},m=async w=>{const _=i(w,u.storageUpload,{code:"STORAGE_UPLOAD_NOT_CONFIGURED",message:"storage upload requires a `storageUpload` function on the worker"}),R=new URL(w.url),P=l(R),T=await a(w),L=w.headers.get("content-type"),B=L===null||L===""?void 0:L,M=await _(P,T,{bucket:n(R,"bucket"),contentType:B});return Response.json(M,{headers:{"content-type":"application/json"},status:200})},g=async w=>{switch(w.method){case"DELETE":return A(w);case"GET":return y(w);case"POST":case"PUT":return m(w);default:throw new s("Storage endpoint requires GET, PUT, POST, or DELETE",{code:"METHOD_NOT_ALLOWED",status:405})}},p=async w=>{if(w.method!=="GET")throw new s("Storage URL endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});const _=i(w,u.storageSignedUrl,{code:"STORAGE_URL_NOT_CONFIGURED",message:"storage URL endpoint requires a `storageSignedUrl` function on the worker"}),R=new URL(w.url),P=l(R),T=Number(n(R,"expiresIn")??""),L=Number.isFinite(T)&&T>0?Math.min(T,ro):void 0,B=await _(P,{bucket:n(R,"bucket"),expiresInSeconds:L});return Response.json({key:P,url:B},{headers:{"content-type":"application/json"},status:200})};return{[to]:O,[Zn]:g,[eo]:p}},oo=(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},ao={mtls:e=>oo(e,"tlsClientAuth","certVerified")==="SUCCESS"},so=e=>e===void 0||e===!1?()=>!1:e===!0?()=>!0:typeof e=="function"?e:Object.entries(ao).find(([t])=>t===e)?.[1]??(()=>!1),io=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.'))}},uo="/_lunora/admin/vector/indexes",co="/_lunora/admin/vector/query",lo=e=>{const{readJsonBody:t,requireAdminOption:r}=e,n=async i=>{if(i.method!=="GET")throw new s("Vector-indexes endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});const u=r(i,e.vectorIntrospector,{code:"VECTORS_NOT_CONFIGURED",message:"vector endpoints require a `vectorIntrospector` on the worker"});return Response.json({indexes:await u.listIndexes()},{headers:{"content-type":"application/json"},status:200})},a=async i=>{if(i.method!=="POST")throw new s("Vector-query endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const u=r(i,e.vectorIntrospector,{code:"VECTORS_NOT_CONFIGURED",message:"vector endpoints require a `vectorIntrospector` on the worker"});if(u.queryIndex===void 0)throw new s("vector index querying is not enabled on this worker",{code:"VECTOR_QUERY_UNSUPPORTED",status:400});const l=await t(i);if(typeof l.name!="string"||l.name==="")throw new s("Vector-query request requires a `name` string",{code:"BAD_REQUEST",status:400});if(typeof l.text!="string"||l.text==="")throw new s("Vector-query request requires a `text` string",{code:"BAD_REQUEST",status:400});if(l.topK!==void 0&&(typeof l.topK!="number"||!Number.isInteger(l.topK)||l.topK<1))throw new s("Vector-query `topK` must be a positive integer",{code:"BAD_REQUEST",status:400});const y=await u.queryIndex({name:l.name,text:l.text,topK:l.topK});return Response.json(y,{headers:{"content-type":"application/json"},status:200})};return{[uo]:n,[co]:a}},ho="/_lunora/admin/workflows/instances",po="/_lunora/admin/workflows/instance",fo="/_lunora/admin/workflows/status",wo={complete:!0,errored:!0,paused:!0,queued:!0,running:!0,terminated:!0,unknown:!0,waiting:!0,waitingForPause:!0},mo=e=>e!==null&&Object.hasOwn(wo,e)?e:void 0,it=(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},Be=(e,t)=>{const r=e.searchParams.get(t);if(r===null||r==="")throw new s(`Workflows admin endpoint requires a \`${t}\` query parameter`,{code:"BAD_REQUEST",status:400});return r},dt=()=>{throw new s("Workflow inspection is unconfigured. Set CLOUDFLARE_ACCOUNT_ID + CLOUDFLARE_API_TOKEN in your .dev.vars to enable it.",{code:"WORKFLOWS_NOT_CONFIGURED",status:501})},yo=e=>{const{assertAdmin:t,resolveWorkflowsClient:r}=e,n=async(u,l,y)=>{if(u.method!=="GET")throw new s("Workflows instances endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});t(u);const O=r(l);if(!O)return Response.json({configured:!1,instances:[],page:1,perPage:0,totalCount:0});const A=Be(y,"name"),m=mo(y.searchParams.get("status"));return Response.json(await O.listInstances({page:it(y,"page"),perPage:it(y,"perPage"),status:m,workflowName:A}))},a=async(u,l,y)=>{if(u.method!=="GET")throw new s("Workflows instance endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});t(u);const O=r(l);return O?Response.json(await O.getInstance({instanceId:Be(y,"id"),workflowName:Be(y,"name")})):dt()},i=async(u,l)=>{if(u.method!=="POST")throw new s("Workflows status endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});t(u);const y=r(l);if(!y)return dt();const O=await u.json().catch(()=>{});if(typeof O?.name!="string"||O.name===""||typeof O.id!="string"||O.id==="")throw new s("Workflows status action requires string `name` and `id`",{code:"BAD_REQUEST",status:400});const{action:A}=O;if(A!=="pause"&&A!=="resume"&&A!=="terminate")throw new s("Workflows status action must be one of: pause, resume, terminate",{code:"BAD_REQUEST",status:400});return Response.json(await y.setInstanceStatus({action:A,instanceId:O.id,workflowName:O.name}))};return{[po]:a,[ho]:n,[fo]:i}},go=new TextEncoder,ut="/_lunora/rpc",bo="/_lunora/rpc-batch",Oo="/_lunora/ws",Ee=(e,t,r)=>({resourceAttributes:Qn(e,t),...r===void 0?{}:{waitUntil:r}}),ct=e=>e?.waitUntil?{waitUntil:t=>e.waitUntil?.(t)}:{},lt=e=>({spanId:e.spanId,traceFlags:e.traceFlags,traceId:e.traceId,...e.parentSpanId===void 0?{}:{parentSpanId:e.parentSpanId}}),xe=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 a=n.port===""?void 0:Number(n.port);return{host:n.hostname,method:t,path:n.pathname,port:Number.isNaN(a)?void 0:a,scheme:n.protocol.replace(":",""),userAgent:r}},ht="/_lunora/voice/",Eo="/_lunora/scheduler/dispatch",To="/_lunora/admin/cron-jobs/run",_o="/_lunora/admin/ws-token",Ro="/_lunora/admin/",So="/_lunora/migrate",Ao="/_lunora/status",vo=e=>e.startsWith(Ro)||e===So,Do=new Set(["1","enabled","on","true","yes"]),ko=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}}},Io="/api/auth",Po="__lunora_admin__:recordAuthEvent",No="__lunora_admin__:listPushSubscriptions",Uo=["/sign-in","/sign-up","/callback"],qo=(e,t)=>{const r=t.endsWith("/")?t.slice(0,-1):t;if(!e.startsWith(`${r}/`))return!1;const n=e.slice(r.length);return Uo.some(a=>n===a||n.startsWith(`${a}/`))},Te=(e,t,r,n)=>{const a=rr(r),i=a?r.code:"INTERNAL_SERVER_ERROR",u=a?r.status:500,l=r instanceof Error?r.message:String(r);return{durationMs:t,error:{code:i,message:l,status:u},functionPath:e,ok:!1,...n.fanOut?{fanOut:{failed:0,shards:0,table:n.fanOut.table}}:{},...n.shardKey?{shardKey:n.shardKey}:{}}},$o=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},pt=e=>e.waitUntil?{waitUntil:t=>{e.waitUntil?.(t)}}:void 0,Lo=e=>{const t=e?.queue;return typeof t=="string"&&t.length>0?t:"unknown"},ue=async(e,t,r)=>{const n={"content-type":"application/json"},a=e.headers.get("authorization"),i=e.headers.get("cookie"),u=e.headers.get("x-d1-bookmark"),l=e.headers.get("x-lunora-mutation-id"),y=e.headers.get("x-lunora-client-id"),O=e.headers.get("x-lunora-client-seq");a&&(n.authorization=a),i&&(n.cookie=i),u&&(n["x-d1-bookmark"]=u),l&&(n["x-lunora-mutation-id"]=l),y&&(n["x-lunora-client-id"]=y),O&&(n["x-lunora-client-seq"]=O);const A=e.headers.get("cf-connecting-ip");if(A&&(n["x-lunora-client-ip"]=A),!r)return{claims:null,headers:n,identity:null,userId:null};const m=await r(e,t);if(!m||typeof m.userId!="string"||m.userId.length===0)return{claims:null,headers:n,identity:null,userId:null};n["x-lunora-userid"]=m.userId;const g=$o(m);g!==void 0&&(n["x-lunora-identity-exp"]=String(g));const{userId:p,...w}=m,_=Object.keys(w).length>0?w:null;return _&&(n["x-lunora-identity"]=JSON.stringify(_)),{claims:_,headers:n,identity:m,userId:p}},Bo=new Set(["concat","first","groupBy","max","min","rank","sum","topK"]),xo=e=>{if(e===void 0)return;if(!e||typeof e!="object")throw new s("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 s("RPC `fanOut.table` must be a non-empty string",{code:"BAD_REQUEST",status:400});if(!t.merge||typeof t.merge!="object")throw new s("RPC `fanOut.merge` must be an object",{code:"BAD_REQUEST",status:400});const r=t.merge;if(typeof r.kind!="string"||!Bo.has(r.kind))throw new s("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 s("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 s("RPC `fanOut.merge.by` must be a non-empty string",{code:"BAD_REQUEST",status:400})}return t},Co=(e,t)=>{e?.LUNORA_DEBUG_RPC&&console.warn(`[lunora:rpc] ${t.fanOut?"fan-out":`shard=${t.shardKey??"(root)"}`} ${t.functionPath}`)},ft=(e,t)=>{const r=t.functions?.[e.functionPath]?.x402;if(r){if(e.fanOut)throw new s("a paid (`.x402`) function cannot be fanned out",{code:"BAD_REQUEST",status:400});if(!t.x402Charge)throw new s(`function "${e.functionPath}" is marked paid (.x402) but no x402Charge gate is configured on the worker`,{code:"MISCONFIGURED",status:500});return r}},jo=async e=>{const t=await ae(e);let r;try{r=JSON.parse(t)}catch{throw new s("RPC body must be valid JSON",{code:"BAD_REQUEST",status:400})}if(!r||typeof r!="object"||typeof r.functionPath!="string")throw new s("RPC envelope is missing `functionPath`",{code:"BAD_REQUEST",status:400});const n=r;if(n.args!==void 0&&(typeof n.args!="object"||n.args===null||Array.isArray(n.args)))throw new s("RPC `args` must be an object",{code:"BAD_REQUEST",status:400});if(n.shardKey!==void 0&&typeof n.shardKey!="string")throw new s("RPC `shardKey` must be a string",{code:"BAD_REQUEST",status:400});const a=r,i=xo(a.fanOut),u=a.args??{};if(i&&a.functionPath.startsWith("__lunora_relation__:")){const l=u.table;if(typeof l=="string"&&l!==i.table)throw new s("RPC `args.table` must match the authorized `fanOut.table` for a relation fan-out",{code:"BAD_REQUEST",status:400});u.table=i.table}return{args:u,fanOut:i,functionPath:a.functionPath,shardKey:a.shardKey}},oe=async(e,t,r)=>Se(e,t).fetch(r),_e=new Map,Go=5e3,Mo=4096,Ko=async(e,t)=>{const r=Date.now(),n=_e.get(t);if(n!==void 0&&n.expiresMs>r)return n.relayCount;n!==void 0&&_e.delete(t);let a=0;try{const i=await Se(e,t).fetch(new Request("https://shard.internal/_lunora/route"));if(i.ok){const u=(await i.json()).relayCount;typeof u=="number"&&u>0&&(a=Math.floor(u))}}catch{a=0}return mt(_e,Mo),_e.set(t,{expiresMs:r+Go,relayCount:a}),a},Qo=(e,t)=>{if(!(e===null||typeof e!="object")){for(const[r,n]of Object.entries(e))if(n===t)return r}},je=(e,t)=>{const r=Math.max(e.length,t.length);let n=e.length^t.length;for(let a=0;a<r;a+=1){const i=a<e.length?e.codePointAt(a)??0:0,u=a<t.length?t.codePointAt(a)??0:0;n|=i^u}return n===0},Fo=async(e,t,r)=>{if(e.length===0||r.length===0)return!1;const n=new TextEncoder,a=await crypto.subtle.importKey("raw",n.encode(e),{hash:"SHA-256",name:"HMAC"},!1,["sign"]),i=await crypto.subtle.sign("HMAC",a,n.encode(t)),u=new Uint8Array(i);let l="";for(const O of u)l+=String.fromCodePoint(O);const y=btoa(l).replaceAll("+","-").replaceAll("/","_").replaceAll("=","");return je(y,r)},wt=(e,t)=>{if(!t||t.length===0)return!1;const r=e.headers.get("authorization");if(!r)return!1;const[n,...a]=r.split(" ");return n?.toLowerCase()!=="bearer"?!1:je(t,a.join(" ").trim())},zo=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 Ir(t,n)?!0:r?!1:je(t,n)},Wo=(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 fr(`d1:${e}`,t);if(typeof r.list=="function"&&typeof r.head=="function"&&typeof r.createMultipartUpload=="function")return Pe(`r2:${e}`,!0);if(typeof r.send=="function"&&typeof r.sendBatch=="function"&&typeof r.get!="function")return Pe(`queue:${e}`,!0);if(typeof r.connectionString=="string")return Pe(`hyperdrive:${e}`,!0)},Tt=e=>{const t=so(e.trustInboundTraceContext),r=io(e.trustInboundTraceContext),n=e.defaultShardKey??"__root__",a=wr(e.resolveIdentity,e.identity),i=He(e.shardDO,e.jurisdiction),u=e.schedulerDO===void 0?void 0:He(e.schedulerDO,e.jurisdiction);let l;const y=()=>e.adminToken??l;let O;const A=()=>e.requireEphemeralWsToken??O??!1,m=o=>{const d=o??{};if(O===void 0&&e.requireEphemeralWsToken===void 0){const c=d.LUNORA_REQUIRE_EPHEMERAL_WS_TOKEN;typeof c=="string"&&c.length>0&&(O=Do.has(c.trim().toLowerCase()))}if(l!==void 0||e.adminToken!==void 0)return;const h=d.LUNORA_ADMIN_TOKEN;typeof h=="string"&&h.length>0&&(l=h)},g=new WeakSet,p=o=>wt(o,y())||g.has(o),w=async(o,d)=>{const h=await ue(o,d,e.resolveIdentity);if(g.has(o)&&h.headers.authorization===void 0){const c=y();c!==void 0&&(h.headers.authorization=`Bearer ${c}`)}return h};let _=!1;const R=o=>{if(!e.allowUnauthenticatedShardAccess){const d=o==="fan-out"?"authorizeFanOut":"authorizeShard";throw new s(`${o} access is default-denied: configure \`${d}\` on the worker, or set \`allowUnauthenticatedShardAccess: true\` to explicitly allow unauthenticated ${o} access (relying solely on per-row RLS).`,{code:o==="fan-out"?"FORBIDDEN_FANOUT":"FORBIDDEN_SHARD",status:403})}_||(_=!0,console.warn([`[lunora] SECURITY: serving ${o} access with \`allowUnauthenticatedShardAccess: true\` and no \`authorizeShard\`/\`authorizeFanOut\` — `,"any caller (including unauthenticated ones) can target any shard / fan out across the table. ","This is safe only if every table is protected by per-row RLS. Configure `authorizeShard`/`authorizeFanOut` to gate it."].join("")))},P=qn({defaultShard:n,forwardToShard:oe,isAdmin:p,queryCoordinator:e.queryCoordinator,resolveForwardContext:w,shardDO:i}),T=async(o,d,h,c,f)=>{if(e.authorizeShard&&!await e.authorizeShard(null,h))throw new s("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403});const b={"content-type":"application/json","x-lunora-system":"1"};f?.userId!==void 0&&f.userId.length>0&&(b["x-lunora-userid"]=f.userId),f?.identity!==void 0&&f.identity.length>0&&(b["x-lunora-identity"]=f.identity),c!==void 0&&c.length>0&&(b["x-lunora-mutation-id"]=c);const S=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:d,functionPath:o}),headers:b,method:"POST"});return oe(i,h,S)},L=async(o,d,h,c)=>{const f=h?.[o];if(!f||typeof f.create!="function")throw new s(`${c} targets workflow binding "${o}", which is not bound on env`,{code:"CRON_JOB_FAILED",status:500});await f.create({params:d})},B=async(o,d,h)=>L(o,d.args??{},h,`cron job "${d.name}"`),M=async(o,d)=>{if(o.workflow){await B(o.workflow,o,d);return}if(o.functionPath===void 0)throw new s(`cron job "${o.name}" has neither a function target nor a workflow target`,{code:"CRON_JOB_FAILED",status:500});const h=await T(o.functionPath,o.args??{},o.shardKey??n);if(!h.ok)throw new s(`cron job "${o.name}" (${o.functionPath}) failed with shard status ${String(h.status)}`,{code:"CRON_JOB_FAILED",status:500})},N=async(o,d,h,c)=>{const f=e.cronJobs?.[o];if(f)for(const b of f)try{await M(b,d)}catch(S){h.push(c(S))}},K=async(o,d)=>{if(!p(o))throw new s("admin endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403});if(o.method!=="POST")throw new s("cron-jobs run endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});if(!e.cronJobs)throw new s("cron-jobs run endpoint requires a `cronJobs` map on the worker",{code:"CRON_JOBS_NOT_CONFIGURED",status:400});const h=await Z(o),c=typeof h.name=="string"?h.name:"";if(c==="")throw new s("cron-jobs run endpoint requires a job `name`",{code:"BAD_REQUEST",status:400});const f=Object.values(e.cronJobs).flat().find(b=>b.name===c);if(!f)throw new s(`no cron job named "${c}" is registered`,{code:"CRON_JOB_NOT_FOUND",status:404});return await M(f,d),Response.json({name:c,ran:!0},{status:200})},Q=async o=>{const d=typeof o.pool=="string"&&o.pool.length>0?o.pool:void 0;if(!d||!u||typeof o.id!="string")return;const h=typeof o.instanceName=="string"&&o.instanceName.length>0?o.instanceName:"default";try{await u.get(u.idFromName(h)).fetch(new Request("https://scheduler.internal/complete",{body:JSON.stringify({id:o.id,pool:d}),headers:{"content-type":"application/json"},method:"POST"}))}catch{}},Y=async(o,d)=>{if(o.method!=="POST")throw new s("Scheduler dispatch endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const h=await ae(o),c=d??{},f=typeof c.LUNORA_SCHEDULER_SECRET=="string"?c.LUNORA_SCHEDULER_SECRET:void 0,b=e.adminToken??(typeof c.LUNORA_ADMIN_TOKEN=="string"?c.LUNORA_ADMIN_TOKEN:void 0),S=o.headers.get("x-lunora-scheduler-signature");let E=!1;if(S&&f?E=await Fo(f,h,S):b&&(E=wt(o,b)),!E)throw new s("Scheduler dispatch requires a valid signature or admin bearer",{code:"FORBIDDEN",status:403});let v;try{v=JSON.parse(h)}catch{throw new s("Scheduler dispatch body must be valid JSON",{code:"BAD_REQUEST",status:400})}const k=v??{},U=k.args??{};if(typeof k.workflow=="string"&&k.workflow.length>0)return await L(k.workflow,U,d,"scheduled workflow"),Response.json({ok:!0},{status:200});if(typeof k.functionPath!="string"||k.functionPath.length===0)throw new s("Scheduler dispatch is missing `functionPath`",{code:"BAD_REQUEST",status:400});const q=typeof k.shardKey=="string"&&k.shardKey.length>0?k.shardKey:n,$=typeof k.id=="string"&&k.id.length>0?k.id:void 0,x=ko(o),W=await T(k.functionPath,U,q,$,x);return await Q(k),W},C=o=>{if(!p(o))throw new s("admin endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403})},G=(o,d,h)=>{if(C(o),d===void 0)throw new s(h.message,{code:h.code,status:400});return d},J=$r({assertAdmin:C,getReader:()=>e.authAuditReader}),re=async(o,d)=>{C(o);const h=e.notifySubscriptionStore;if(h===void 0)return Response.json({subscriptions:[]},{headers:{"content-type":"application/json"},status:200});const c=d?.kind,f=d?.userId,b=d?.limit,S=c==="fcm"||c==="web-push"?c:void 0,E=typeof f=="string"&&f!==""?f:void 0,v=typeof b=="number"&&Number.isFinite(b)?Math.trunc(b):0,k=v>0?Math.min(v,1e3):1e3,U=(await h.list({kind:S,limit:k,userId:E})).filter(q=>S!==void 0&&q.kind!==S?!1:E===void 0||(q.userId??null)===E).map(({keys:q,token:$,...x})=>x);return Response.json({subscriptions:U},{headers:{"content-type":"application/json"},status:200})},se=async(o,d)=>{if(!d.fanOut){if(d.functionPath===qr)return J(o,d.args??{});if(d.functionPath===No)return re(o,d.args)}},ne=Yr({applyGlobals:e.applyGlobals,exportCursorStore:e.exportCursorStore,exportSinks:e.exportSinks,knownTables:()=>bt(),queryCoordinator:e.queryCoordinator,requireAdminOption:G,resolveForwardContext:w,shardDO:i,streamExportRows:(o,d,h,c)=>nt(e,o,d,h,c,i),streamingImport:(o,d)=>nn(o,e,d,i),syncGlobals:e.syncGlobals}),he=(o,d)=>{const h=o.searchParams.get(d);return h===null||h===""?void 0:h},me=o=>{const d=new URL(o.url),h=d.searchParams.get("limit"),c=d.searchParams.get("offset"),f=h===null?void 0:Number.parseInt(h,10),b=c===null?void 0:Number.parseInt(c,10);return{limit:f!==void 0&&Number.isFinite(f)&&f>=0?f:void 0,offset:b!==void 0&&Number.isFinite(b)&&b>=0?b:void 0}},be=()=>{if(u===void 0)throw new s("scheduled endpoints require a `schedulerDO` namespace on the worker",{code:"SCHEDULER_NOT_CONFIGURED",status:400});return u},ee=Xn({checkWsAdmin:async o=>p(o)||zo(o,y(),A()),requireSchedulerNamespace:be,resolveSchedulerStub:o=>(C(o),Se(be(),e.schedulerInstanceName??"default")),schedulerInstanceName:e.schedulerInstanceName??"default"}),_t=yo({assertAdmin:C,resolveWorkflowsClient:e.workflowsClient??(()=>{})}),Rt=no({assertAdmin:C,parsePaging:me,queryParameter:he,readBodyBytes:xr,requireAdminOption:G,storage:{storageBuckets:e.storageBuckets,storageDelete:e.storageDelete,storageList:e.storageList,storageSignedUrl:e.storageSignedUrl,storageUpload:e.storageUpload}}),St=lo({readJsonBody:Z,requireAdminOption:G,vectorIntrospector:e.vectorIntrospector}),At=bn({kvIntrospector:e.kvIntrospector,readJsonBody:Z,requireAdminOption:G}),vt=mr({logArchive:e.logArchive,readJsonBody:Z,requireAdminOption:G}),Dt=mn({assertAdmin:C,options:{cronJobs:e.cronJobs,functions:e.functions,globalIntrospector:e.globalIntrospector,openApiSpec:e.openApiSpec,openRpcSpec:e.openRpcSpec},parsePaging:me,queryParameter:he,requireAdminOption:G}),kt=o=>{const d=[],h=i??o?.SHARD;if(h!==void 0&&d.push(pr("durable-object:default",h,n)),e.health?.disableBindingProbes!==!0)for(const[c,f]of Object.entries(o??{})){const b=Wo(c,f);b!==void 0&&d.push(b)}for(const c of e.health?.probes??[])d.push(c);return d},It=hr({appName:e.health?.appName,appVersion:e.health?.appVersion,auth:e.health?.auth??"public",cacheTtlMs:e.health?.cacheTtlMs,isAdmin:p,resolveProbes:kt}),Pt=async(o,d,h)=>{const{claims:c,headers:f,userId:b}=await ue(o,d,a),S=async(E,v={})=>{const k=E.__lunoraRef;if(typeof k!="string")throw new s("ctx.run*: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});const U=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:v,functionPath:k}),headers:{...f,"x-lunora-system":"1"},method:"POST"}),q=await oe(i,n,U),$=await q.json();if($.error)throw new s($.error.message??"shard RPC failed",{code:$.error.code??"INTERNAL",status:q.status});return $.result};return{auth:{getIdentity:()=>Promise.resolve(c),userId:b},cache:h.cache,fetch:globalThis.fetch.bind(globalThis),runAction:S,runMutation:S,runQuery:S}},Nt=async(o,d,h)=>{if(!e.httpRouter)return;const c=await Pt(o,d,h);try{return await e.httpRouter.fetch(o,{...d,__lunoraCtx:c},h)}catch(f){return console.error("[lunora] httpRouter (SSR) handler threw:",f),new Response("Internal Server Error",{status:500})}},Ut=async(o,d,h)=>{if(o.headers.get("Upgrade")!=="websocket")throw new s("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});const c=Ve(o,ie);if(c)return c;const f=h.searchParams.get("shard")??n,{headers:b,identity:S}=await ue(o,d,a);if(e.authorizeShard){if(!await e.authorizeShard(S,f))throw new s("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else f!==n&&R("shard");const E=new Headers(o.headers),v=[...E.keys()];for(const x of v)x.startsWith("x-lunora-")&&E.delete(x);const k=b["x-lunora-userid"],U=b["x-lunora-identity"],q=b["x-lunora-identity-exp"];k!==void 0&&E.set("x-lunora-userid",k),U!==void 0&&E.set("x-lunora-identity",U),q!==void 0&&E.set("x-lunora-identity-exp",q);const $=Qo(d,e.shardDO);if($!==void 0){E.set("x-lunora-shard-binding",$);const x=await Ko(i,f);if(x>0){const W=Tr(f,Math.floor(Math.random()*x));return oe(i,W,new Request(o,{headers:E}))}}return oe(i,f,new Request(o,{headers:E}))},qt=async(o,d,h)=>{const{voiceAgents:c}=e;if(c===void 0)return new Response("Not found",{status:404});if(o.headers.get("Upgrade")!=="websocket")return new Response("Expected a WebSocket upgrade",{headers:{allow:"GET"},status:426});const f=Ve(o,ie);if(f)return f;let b;try{b=decodeURIComponent(h.pathname.slice(ht.length))}catch{return new Response("Unknown voice agent",{status:404})}const S=Object.hasOwn(c,b)?c[b]:void 0;if(S===void 0)return new Response("Unknown voice agent",{status:404});const E=h.searchParams.get("threadKey");if(E===null||E.length===0)return new Response("Missing threadKey",{status:400});const{headers:v,identity:k}=await ue(o,d,a);if(e.authorizeShard){if(!await e.authorizeShard(k,E))return new Response("Forbidden",{status:403})}else R("shard");const U=new Headers(o.headers);U.delete("x-lunora-userid"),U.delete("x-lunora-identity"),U.delete("x-lunora-identity-exp");const q=v["x-lunora-userid"],$=v["x-lunora-identity"],x=v["x-lunora-identity-exp"];return q!==void 0&&U.set("x-lunora-userid",q),$!==void 0&&U.set("x-lunora-identity",$),x!==void 0&&U.set("x-lunora-identity-exp",x),oe(S,E,new Request(o,{headers:U}))},$t=async(o,d,h)=>{if(e.authorizeFanOut){if(!await e.authorizeFanOut(h,o.table,d))throw new s("Forbidden fan-out",{code:"FORBIDDEN_FANOUT",status:403});return}if(d.startsWith("__lunora_relation__:"))throw new s("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 s("Fan-out requires `authorizeFanOut` to be configured on the worker when `authorizeShard` is set",{code:"FORBIDDEN_FANOUT",status:403});R("fan-out")},Oe=async(o,d)=>{if(!(!o.fanOut&&o.functionPath.startsWith("__lunora_admin__:"))){if(o.fanOut){await $t(o.fanOut,o.functionPath,d);return}if(e.authorizeShard){const h=o.shardKey??n;if(!await e.authorizeShard(d,h))throw new s("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else o.shardKey!==void 0&&o.shardKey!==n&&R("shard")}},Ae=async(o,d,h,c,f,b)=>{const S=Date.now(),{observability:E,sampling:v}=e,k=xe(o),{decision:U,ignoredUpstream:q,trace:$}=Mn(o,{...v===void 0?{}:{sampling:v},trustInbound:t(o)});q&&r();const x={...f,"x-lunora-sample-errors":U.keepErrors?"1":"0"};Kn($,x);const W=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:h,functionPath:d}),headers:x,method:"POST"});try{const j=await oe(i,c,W);return de(E,{...k,...lt($),durationMs:Date.now()-S,functionPath:d,ok:j.ok,shardKey:c,...j.ok?{}:{error:{code:"SHARD_ERROR",message:`shard returned ${String(j.status)}`,status:j.status}}},b,void 0,{isTraced:$.sampled,keepErrors:U.keepErrors}),j}catch(j){throw de(E,{...k,...lt($),...Te(d,Date.now()-S,j,{shardKey:c})},b,void 0,{isTraced:$.sampled,keepErrors:U.keepErrors}),j}},Lt=o=>{if(o.fanOut&&o.shardKey)throw new s("RPC envelope cannot set both `shardKey` and `fanOut`",{code:"BAD_REQUEST",status:400});if(!o.fanOut&&o.functionPath.startsWith("__lunora_relation__:"))throw new s("`__lunora_relation__:*` is a fan-out-only reserved RPC and cannot be dispatched to a single shard",{code:"FORBIDDEN",status:403});if(o.fanOut&&!e.queryCoordinator)throw new s("RPC envelope set `fanOut` but no `queryCoordinator` is configured on the worker",{code:"BAD_REQUEST",status:400})},Bt=async(o,d,h)=>{if(o.method!=="POST")throw new s("RPC endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const c=await jo(o);Co(d,c),Lt(c);const f=await se(o,c);if(f!==void 0)return f;const{headers:b,identity:S}=await ue(o,d,a);await Oe(c,S);const E=ft(c,e);{const v=Date.now(),{observability:k}=e,U=xe(o),q=Ee(d,o,h&&(W=>h.waitUntil?.(W)));if(c.fanOut){const W=e.queryCoordinator;if(!W)throw new s("RPC envelope set `fanOut` but no `queryCoordinator` is configured on the worker",{code:"BAD_REQUEST",status:400});try{const j=await W.fanOut(i,{args:c.args??{},fanOut:c.fanOut,functionPath:c.functionPath,headers:b});return de(k,{durationMs:Date.now()-v,fanOut:{failed:j.failed,shards:j.ok+j.failed,table:c.fanOut.table},functionPath:c.functionPath,...U,ok:!0},q),Response.json(j,{headers:{"content-type":"application/json"},status:200})}catch(j){throw de(k,{...Te(c.functionPath,Date.now()-v,j,{fanOut:{table:c.fanOut.table}}),...U},q),j}}const $=c.shardKey??n,x=()=>Ae(o,c.functionPath,c.args??{},$,b,q);return E&&e.x402Charge?e.x402Charge(o,{functionPath:c.functionPath,price:E.price},x,ct(h)):x()}},xt=async(o,d,h)=>{if(o.method!=="POST")throw new s("RPC batch endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const c=await ae(o);let f;try{f=JSON.parse(c)}catch{throw new s("RPC batch body must be valid JSON",{code:"BAD_REQUEST",status:400})}if(typeof f!="object"||f===null||Array.isArray(f))throw new s("RPC batch body must be an object",{code:"BAD_REQUEST",status:400});const{calls:b}=f;if(!Array.isArray(b))throw new s("RPC batch `calls` must be an array",{code:"BAD_REQUEST",status:400});const{headers:S,identity:E}=await ue(o,d,a),v=Br(b,n);for(const F of v.values())for(const z of F)if(e.functions?.[z.functionPath]?.x402)throw new s(`paid (\`.x402\`) function "${z.functionPath}" cannot be called in a batch; dispatch it individually over ${ut}`,{code:"BAD_REQUEST",status:400});await Promise.all([...v.entries()].flatMap(([F,z])=>z.map(te=>Oe({functionPath:te.functionPath,shardKey:F},E))));const{observability:k}=e,U=Ee(d,o,h&&(F=>h.waitUntil?.(F))),q=xe(o),$=[],x=[],W=(F,z,te,ce)=>({body:{error:{code:te,message:ce}},id:F.id,status:z}),j=(F,z,te,ce,pe)=>{for(const H of F)de(k,pe(H),U),$.push(W(H,z,te,ce))},Xt=(F,z,te,ce,pe)=>{for(const H of F){const fe=ce.get(H.id)??pe,ye=fe<400;de(k,{durationMs:te,functionPath:H.functionPath,...q,ok:ye,shardKey:z,...ye?{}:{error:{code:"SHARD_ERROR",message:`batched call returned ${String(fe)}`,status:fe}}},U)}};await Promise.all([...v.entries()].map(async([F,z])=>{const te=new Headers(S);te.set("content-type","application/json");const ce=new Request("https://shard.internal/rpc-batch",{body:JSON.stringify({calls:z}),headers:te,method:"POST"}),pe=Date.now();let H;try{H=await oe(i,F,ce)}catch(V){const Ie=Date.now()-pe,{body:Fe}=nr(V,{fallbackCode:"SHARD_UNAVAILABLE",redactedMessage:"shard unavailable"});j(z,502,Fe.code,Fe.message,tr=>({...Te(tr.functionPath,Ie,V,{shardKey:F}),...q}));return}const fe=Date.now()-pe,ye=H.headers.get("x-d1-bookmark");ye&&x.push(ye);let De;try{De=await H.json()}catch{const V=`shard batch returned a non-JSON response (${String(H.status)})`;j(z,H.status,"SHARD_ERROR",V,Ie=>({durationMs:fe,error:{code:"SHARD_ERROR",message:V,status:H.status},functionPath:Ie.functionPath,...q,ok:!1,shardKey:F}));return}const ke=Array.isArray(De.results)?De.results:[],Zt=new Map(ke.map(V=>[V.id,V.status??H.status])),er=new Set(ke.map(V=>V.id));Xt(z,F,fe,Zt,H.status),$.push(...ke);for(const V of z)er.has(V.id)||$.push(W(V,H.status,"SHARD_ERROR",`shard batch omitted result for call ${String(V.id)}`))}));const Ke={"content-type":"application/json"},[Qe]=x;return x.length===1&&Qe!==void 0&&(Ke["x-d1-bookmark"]=Qe),Response.json({results:$},{headers:Ke,status:200})},Ct=async(o,d,h,c={},f={})=>{try{const b=h.__lunoraRef;if(typeof b!="string")throw new s("serverQuery: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});const{headers:S,identity:E}=await ue(o,d,a);await Oe({functionPath:b,shardKey:f.shardKey},E);const v=f.shardKey??n,k=Ee(d,o,f.waitUntil);return await Ae(o,b,c,v,S,k)}catch(b){return ze(b)}},jt=1e3,Gt=async(o,d)=>{const h=e.backupRetain;if(h===void 0||h<=0)return;const c=[];let f;for(let S=0;S<jt;S+=1){const E=await o.list({cursor:f,prefix:d});for(const v of E.objects)v.key.endsWith(".manifest.json")&&c.push(v.key);if(!E.truncated||E.cursor===void 0)break;f=E.cursor}const b=c.toSorted((S,E)=>E.localeCompare(S)).slice(h);await Promise.all(b.flatMap(S=>{const E=S.slice(0,-14);return[o.delete(S),o.delete(E)]}))},Mt=async o=>{const d=e.backupStore,h=e.queryCoordinator;if(!d)throw new s("scheduled backup requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});if(!h)throw new s("scheduled backup requires a `queryCoordinator` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});const c=y();if(!c||c.length===0)throw new s("scheduled backup requires an `adminToken` (or `env.LUNORA_ADMIN_TOKEN`) to authenticate the per-shard export gate",{code:"BACKUP_NOT_CONFIGURED",status:500});const f={authorization:`Bearer ${c}`,"content-type":"application/json"},b=e.backupTables;let S=0,E=0;const v=[];await nt(e,h,f,b,W=>{const j=`${JSON.stringify(W)}
|
|
5
5
|
`;S+=1,E+=go.encode(j).byteLength,v.push(j)},i);const k=e.backupPrefix??"backups/",U=new Date(o.scheduledTime).toISOString(),q=`${k}lunora-backup-${U.replaceAll(/[.:]/gu,"-")}.ndjson`,$=`${q}.manifest.json`;await d.put(q,new Blob(v,{type:"application/x-ndjson"}),{httpMetadata:{contentType:"application/x-ndjson"}});const x={bytes:E,createdAt:U,cron:o.cron,file:q,id:U,rows:S,scheduledTime:o.scheduledTime,...b?{tables:b.join(",")}:{}};await d.put($,`${JSON.stringify(x,void 0,2)}
|
|
6
6
|
`,{httpMetadata:{contentType:"application/json"}}),await Gt(d,k)},Ge=async(o,d,h)=>{const{observability:c}=e,f=Date.now(),b=Re(16),S=Re(8),E=pt(d);try{const v=await h();return de(c,{durationMs:Date.now()-f,functionPath:o,ok:!0,spanId:S,traceId:b},E),v}catch(v){throw de(c,{...Te(o,Date.now()-f,v,{}),spanId:S,traceId:b},E),v}finally{We(c,E)}},Kt=async(o,d,h)=>{m(d);const c=[],f=E=>E instanceof Error?E:new Error(String(E)),b=e.crons?.[o.cron];if(b)try{await b(o,d,h)}catch(E){c.push(f(E))}if(await N(o.cron,d,c,f),e.backupStore&&e.backupCron!==void 0&&e.backupCron===o.cron)try{await Mt(o)}catch(E){c.push(f(E))}const[S]=c;if(c.length===1&&S)throw S;if(c.length>1)throw new AggregateError(c,`scheduled("${o.cron}") had ${String(c.length)} failure(s)`)},Qt=async(o,d)=>{try{const h=o??{},c=e.adminToken??(typeof h.LUNORA_ADMIN_TOKEN=="string"?h.LUNORA_ADMIN_TOKEN:void 0);if(!c||c.length===0)return;const f=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:{outcome:d},functionPath:Po}),headers:{authorization:`Bearer ${c}`,"content-type":"application/json"},method:"POST"});await oe(i,n,f)}catch{}},Ft=async(o,d,h,c)=>{if(!e.authHandler)return;const f=await e.authHandler(o);if(!f)return;const b=e.authBasePath??Io;return qo(h.pathname,b)&&c.waitUntil?.(Qt(d,f.status>=400?"fail":"ok")),f},zt=async({args:o,env:d,functionPath:h,request:c,shardKey:f,waitUntil:b})=>{const S={functionPath:h,...f===void 0?{}:{shardKey:f}},{headers:E,identity:v}=await ue(c,d,a);await Oe(S,v);const k=f??n,U=Ee(d,c,b),q=()=>Ae(c,h,o,k,E,U),$=ft(S,e);return $&&e.x402Charge?e.x402Charge(c,{functionPath:h,price:$.price},q,ct({waitUntil:b})):q()},Wt=gr({functions:e.functions??{},invoke:zt,readJsonBody:Z,...e.restRateLimit?{rateLimit:e.restRateLimit}:{}}),ve=e.routes!==void 0&&Object.keys(e.routes).length>0?e.routes:void 0,Ht={[Ao]:o=>o.method!=="GET"&&o.method!=="HEAD"?new Response(void 0,{headers:{allow:"GET, HEAD"},status:405}):Response.json({ok:!0},{headers:{"cache-control":"no-store"}}),[Oo]:(o,d,h)=>Ut(o,d,h),[ut]:(o,d,h,c)=>Bt(o,d,c),[bo]:(o,d,h,c)=>xt(o,d,c),[Eo]:(o,d)=>Y(o,d),[To]:(o,d)=>K(o,d),[_o]:async o=>{if(o.method!=="POST")throw new s("ws-token endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});C(o);const d=y();if(d===void 0)throw new s("ws-token minting requires a configured admin token",{code:"ADMIN_TOKEN_NOT_CONFIGURED",status:400});const h=await kr(d);return Response.json(h,{headers:{"cache-control":"no-store"}})},...P,...ne,...ee,..._t,...Rt,...St,...At,...vt,...Dt,...It,...Wt,...Ur({assertAdmin:C,getAuthAdmin:()=>e.authAdmin,parsePaging:me,queryParameter:he,readJsonBody:Z})};let ie=Je(e.security),Me=!1;const Jt=o=>{Me||(Me=!0,ie=Je(e.security,o??{}))},Vt=async(o,d)=>{if(!(e.adminGate===void 0||!vo(d)))try{await e.adminGate(o)&&g.add(o)}catch{}},Yt=async(o,d,h)=>{const c=new URL(o.url);if(o.method==="POST"||o.method==="PUT"){const E=Number(o.headers.get("content-length")??""),v=c.pathname===Ot?Et:ge;if(Number.isFinite(E)&&E>v)throw new s("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413})}const f=await Ft(o,d,c,h);if(f)return f;if(ve){const E=`${o.method} ${c.pathname}`,v=ve[E]??ve[c.pathname];if(v)return v(o,d,h)}const b=Ht[c.pathname];return b?(await Vt(o,c.pathname),b(o,d,c,h)):e.voiceAgents!==void 0&&c.pathname.startsWith(ht)?qt(o,d,c):await Nt(o,d,h)||new Response("Not found",{status:404})};return{async fetch(o,d,h){e.passThroughOnException&&h.passThroughOnException?.(),Jt(d),m(d);const c=br(o,ie);if(c)return c;const f=Or(o,ie);if(f)return Ne(f,o,ie);try{const b=await Yt(o,d,h);return Ne(b,o,ie)}catch(b){return Ne(ze(b),o,ie)}finally{We(e.observability,pt(h))}},async queue(o,d,h){await Ge(`queue:${Lo(o)}`,h,async()=>{await e.queue?.(o,d,h)})},async scheduled(o,d,h){await Ge(`cron:${o.cron}`,h,async()=>{await Kt(o,d,h)})},serverQuery:Ct}},Ho=e=>Tt(e),Jo=e=>typeof e=="function"?{fetch:e}:e,Vo=e=>!!(e.crons??e.cronJobs??e.backupCron),la=(e,t)=>{const r=Jo(e),n=typeof e=="object"&&typeof e.scheduled=="function"?e.scheduled:void 0,a=u=>{const l=Ho({...u,httpRouter:r});return n!==void 0&&!Vo(u)?{...l,scheduled:async(y,O,A)=>{await n(y,O,A)}}:l};if(typeof t!="function")return a(t);const i=t;return{fetch:(u,l,y)=>a(i(l)).fetch(u,l,y),queue:(u,l,y)=>a(i(l)).queue?.(u,l,y)??Promise.resolve(),scheduled:(u,l,y)=>a(i(l)).scheduled(u,l,y),serverQuery:(u,l,y,O,A)=>a(i(l)).serverQuery(u,l,y,O,A)}},Yo=(e,t)=>{if(typeof e=="function")return e(t);const r=e.shardDO??t?.SHARD;if(!r)throw new s("@lunora/runtime: no shard Durable Object namespace found. Bind `SHARD` in wrangler.jsonc, or pass `createLunoraHandler({ shardDO: env.MY_SHARD })`.");return{...e,shardDO:r}},ha=(e={})=>(t,r,n)=>Tt(Yo(e,r)).fetch(t,r,n??or),pa=e=>e;export{qr as GET_AUTH_AUDIT_LOG_OP,or as NOOP_EXECUTION_CONTEXT,ma as composeIdentityResolvers,Ho as composeWorker,ha as createLunoraHandler,Tt as createWorker,pa as defineRpcEnvelope,Ko as probeRelayCount,Yo as resolveLunoraOptions,ya as routeIdentityResolvers,la as withFrameworkWorker};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const l="/_lunora/rest",f=["authorization","cf-access-jwt-assertion","cookie"],c=["x-d1-bookmark","x-lunora-shard-key"],u=t=>[...f,...(t.credentialHeaders??[]).map(a=>a.toLowerCase())],d=t=>Number.isFinite(t)?Math.max(0,Math.floor(t)):0,i=(...t)=>{const a=[];for(const o of t)for(const e of o?.split(",")??[]){const n=e.trim().toLowerCase();n!==""&&!a.includes(n)&&a.push(n)}return a.length===0?void 0:a.join(", ")},p=(t,a)=>{const o=[a,`max-age=${String(d(t.maxAge))}`];return t.staleWhileRevalidate!==void 0&&o.push(`stale-while-revalidate=${String(d(t.staleWhileRevalidate))}`),o.join(", ")},m=t=>t.scope==="public"?i(t.vary,...u(t),...c):i(t.vary,...c),h=t=>{const a=t.indexOf(":");if(!(a<=0||a>=t.length-1||t.indexOf(":",a+1)!==-1))return{name:t.slice(a+1),namespace:t.slice(0,a)}},v=t=>{const a=h(t);if(a!==void 0)return`${l}/${a.namespace}/${a.name}`},g=t=>t==="query"?"GET":"POST",y=t=>{const a=[];for(const o of t){if(o.exposure?.rest!==!0||o.kind==="stream")continue;const e=h(o.functionPath),n=v(o.functionPath);e===void 0||n===void 0||a.push({functionPath:o.functionPath,kind:o.kind,method:g(o.kind),name:e.name,namespace:e.namespace,path:n})}return a.sort((o,e)=>o.path.localeCompare(e.path)),a},x=(t,a)=>u(a).some(o=>t.headers.has(o)),k=(t,a,o)=>{if(a.method!=="GET"||o<200||o>299)return;const e=t.scope==="public"&&!x(a,t)?"public":"private",n={"cache-control":p(t,e)};t.tag!==void 0&&t.tag!==""&&(n["cache-tag"]=t.tag);const r=m(t);return r!==void 0&&(n.vary=r),n},$=(t,a,o)=>{if(a===void 0)return t;const e=k(a,o,t.status);if(e===void 0)return t;const n=new Response(t.body,t);for(const[r,s]of Object.entries(e))n.headers.set(r,r==="vary"?i(n.headers.get("vary")??void 0,s)??s:s);return n};export{$ as R,y as a,x as d,k as o};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/runtime",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.44",
|
|
4
4
|
"description": "Lunora Worker runtime: the RPC router, shard resolver, and query coordinator",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cloudflare",
|
|
@@ -46,8 +46,8 @@
|
|
|
46
46
|
"access": "public"
|
|
47
47
|
},
|
|
48
48
|
"dependencies": {
|
|
49
|
-
"@lunora/bindings": "1.0.0-alpha.
|
|
50
|
-
"@lunora/errors": "1.0.0-alpha.
|
|
49
|
+
"@lunora/bindings": "1.0.0-alpha.13",
|
|
50
|
+
"@lunora/errors": "1.0.0-alpha.9"
|
|
51
51
|
},
|
|
52
52
|
"engines": {
|
|
53
53
|
"node": "^22.15.0 || >=24.11.0"
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{d as k}from"./method-guard-BbuR0VfS.mjs";const P="/_lunora/rest",l=n=>{const t=n.indexOf(":");if(!(t<=0||t>=n.length-1||n.indexOf(":",t+1)!==-1))return{name:n.slice(t+1),namespace:n.slice(0,t)}},g=n=>{const t=l(n);if(t!==void 0)return`${P}/${t.namespace}/${t.name}`},v=n=>n==="query"?"GET":"POST",x=n=>{const t=[];for(const e of n){if(e.exposure?.rest!==!0||e.kind==="stream")continue;const r=l(e.functionPath),o=g(e.functionPath);r===void 0||o===void 0||t.push({functionPath:e.functionPath,kind:e.kind,method:v(e.kind),name:r.name,namespace:r.namespace,path:o})}return t.sort((e,r)=>e.path.localeCompare(r.path)),t},R=n=>Object.entries(n).map(([t,e])=>({exposure:e.expose,functionPath:t,kind:e.kind})),T=n=>x(R(n)),w=(n,t)=>{const e=n.searchParams.get("shardKey");if(e!==null&&e!=="")return e;const r=t.headers.get("x-lunora-shard-key");return r===null||r===""?void 0:r},O=n=>{const t={};for(const[e,r]of n.searchParams.entries())if(e!=="shardKey")try{t[e]=JSON.parse(r)}catch{t[e]=r}return t},L=n=>{const{functions:t,invoke:e,rateLimit:r,readJsonBody:o}=n,s={};for(const i of T(t)){const p=i.kind==="query"?["GET","POST"]:["POST"];s[i.path]=async(a,y,S,d)=>{const f=k(a,p);if(f)return f;const h=new URL(a.url);if(r){const c=await r(a,i.functionPath);if(c)return c}let u;a.method==="GET"?u=O(h):u=a.body===null?{}:await o(a);const m=w(h,a);return e({args:u,env:y,functionPath:i.functionPath,request:a,...m===void 0?{}:{shardKey:m},...d?.waitUntil===void 0?{}:{waitUntil:c=>d.waitUntil?.(c)}})}}return s},K=(n,t)=>async(e,r)=>{const o=t.key?t.key(e,r):e.headers.get("cf-connecting-ip")??void 0,s=await n.limit(t.name,o===void 0?{}:{key:o});if(s.ok)return;const i=Math.max(1,Math.ceil(s.retryAfter/1e3));return Response.json({error:{code:"RATE_LIMITED",message:"Rate limit exceeded"}},{headers:{"content-type":"application/json","retry-after":String(i)},status:429})};export{O as argsFromQuery,L as buildRestRoutes,K as createRestRateLimit,w as readShardKey,T as restSurfaceFromRegistry};
|