@lunora/runtime 1.0.0-alpha.96 → 1.0.0-alpha.98

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -2578,8 +2578,15 @@ interface RateLimiterLike {
2578
2578
  /**
2579
2579
  * Adapt a `@lunora/ratelimit` limiter into a {@link RestRateLimit} gate for the
2580
2580
  * public REST surface (plan 167). Pass the limiter and the rate name to charge;
2581
- * `key` isolates the limit per caller (IP / user / API key — defaults to the
2582
- * `cf-connecting-ip` header, else {@link UNRESOLVED_IP_BUCKET}).
2581
+ * `key` isolates the limit per caller (IP / user / API key — defaults to
2582
+ * {@link trustedClientIp}, else {@link UNRESOLVED_IP_BUCKET}).
2583
+ *
2584
+ * That default resolves an IP only ON Cloudflare, where the edge stamps
2585
+ * `cf-connecting-ip` over anything the client sent. On any other host it is a
2586
+ * header the caller types, so trusting it would give an attacker a fresh bucket
2587
+ * per request and the limit would stop applying to exactly the traffic it exists
2588
+ * to stop; those deployments pool into {@link UNRESOLVED_IP_BUCKET} instead, and
2589
+ * should pass `key` to identify callers by something they cannot forge.
2583
2590
  *
2584
2591
  * A rate rejection becomes a `429` with a `Retry-After` header (seconds, ceil of
2585
2592
  * the limiter's ms). A deny-list hit becomes a `403` and no `Retry-After` —
@@ -3335,12 +3342,21 @@ interface ScheduledControllerLike {
3335
3342
  * trigger's `cron` expression. Runs server-side with no end-user identity.
3336
3343
  */
3337
3344
  type CronHandler = (controller: ScheduledControllerLike, env: unknown, context: ExecutionContextLike) => Promise<void> | void;
3345
+ /**
3346
+ * The trigger's own trace, handed to a consumer so every function it dispatches
3347
+ * is a child of the trigger span instead of an unrelated root trace.
3348
+ */
3349
+ interface TriggerTrace {
3350
+ /** W3C `traceparent` naming the trigger's SERVER span. */
3351
+ traceparent: string;
3352
+ }
3338
3353
  /**
3339
3354
  * A Cloudflare Queues push-consumer handler — the worker's `queue()` entry
3340
3355
  * forwards each delivered `MessageBatch` (typed `unknown` here to keep the
3341
- * runtime decoupled from `@lunora/queue`'s structural batch type).
3356
+ * runtime decoupled from `@lunora/queue`'s structural batch type) along with the
3357
+ * invocation's own {@link TriggerTrace}.
3342
3358
  */
3343
- type QueueConsumerHandler = (batch: unknown, env: unknown, context: ExecutionContextLike) => Promise<void>;
3359
+ type QueueConsumerHandler = (batch: unknown, env: unknown, context: ExecutionContextLike, trigger: TriggerTrace) => Promise<void>;
3344
3360
  /**
3345
3361
  * A single code-defined cron job, shaped like an entry of the generated
3346
3362
  * `LUNORA_CRONS` map. `functionPath` is the `"namespace:fn"` to run, `args` its
@@ -5170,4 +5186,4 @@ export { type AccessContextLike, type AccessIdentityLike, type AdminTableResolve
5170
5186
  * surface — without a name for it, a caller cannot hoist a shared attribute bag
5171
5187
  * into a typed constant.
5172
5188
  */
5173
- type OtlpResourceAttributes, type OtlpSinkOptions, type PipelineLike, type PipelineLogColumnMap, type PipelineLogCursor, type PipelineLogField, type PipelineLogPage, type PipelineLogQuery, type PipelineLogReader, type PipelineLogReaderOptions, type PipelineLogRow, type PipelineLogSinkOptions, type PrunedBackups, type QueryCoordinator, type QueryCoordinatorOptions, type RankFanOutRequest, type RankFanOutResult, type RankPageFanOutRequest, type RankPageFanOutResult, type RateLimiterLike, type ResolvedSecurity, type ResolvedShard, type RestInvoke, type RestRateLimit, type RestRegistryEntry, type RestRegistryLike, type RestRoute, type RestRouteDeps, type Route, type RpcContext, type RpcEnvelope, type RunExportTapOptions, SHARD_REGISTRY_DO_NAME, STORAGE_UPLOAD_MAX_BODY_BYTES, type ScheduledControllerLike, type SecurityHeadersOptions, type SecurityOptions, type SentrySinkOptions, type ShardCallArgs, type ShardCallOptions, type ShardCallReturn, type ShardCaller, type ShardCallerIdentity, type ShardClient, type ShardClientOptions, type ShardError, type ShardExportOutcome, type ShardFunctionReference, type ShardImportOutcome, type ShardMigrationOutcome, type ShardNamespaceInput, type ShardNamespaceLike, type ShardRankOutcome, type ShardRankPageOutcome, type ShardRegistry, type ShardTrafficEntry, type ShardTrafficFanOutRequest, type ShardTrafficFanOutResult, type ShardingInfo, type SpanEvent, type StorageListFunction as StorageListFn, type StorageObject, type TraceSamplingConfig, type TraceTrustSignal, type TrustInboundTraceContext, VERSION, type VectorIndexSummary, type VectorIntrospector, type VectorQueryMatch, type WebhookSinkOptions, type WorkerOptions, analyticsEngineSink, applyJurisdiction, applyRestCache, argsFromQuery, backupManifestKey, backupObjectKey, backupObjectKeyOfManifest, buildHealthRoutes, buildRestRoutes, combineSinks, composeIdentityResolvers, composeWorker, consoleSink, createCrossShardRelationCapabilities, createDynamicShardRegistry, createKvCursorStore, createLunoraHandler, createMemoryCursorStore, createPipelineLogReader, createQueryCoordinator, createRestRateLimit, createShardClient, createStaticShardRegistry, createWorker, d1Probe, decorateResponse, defineExportSink, defineRpcEnvelope, durableObjectProbe, emitLogEvent, emitRpcEvent, enforceOrigin, handleCorsPreflight, isBackupManifestEntry, isBackupManifestKey, memoizeIdentity, memoizeIdentityPerRequest, normalizeBackupPrefix, otlpSink, pipelineLogSink, presenceProbe, r2Sink, requestCarriesCredentials, resolveLogArchiveFromEnv, resolveLunoraOptions, resolveSecurity, resolveShard, restCacheHeaders, restSurfaceFromRegistry, routeIdentityResolvers, runExportTap, sanitizeChange, sentrySink, toAirbyteMessages, toErrorResponse, toFivetranResponse, webhookExportSink, webhookSink, withFrameworkWorker };
5189
+ type OtlpResourceAttributes, type OtlpSinkOptions, type PipelineLike, type PipelineLogColumnMap, type PipelineLogCursor, type PipelineLogField, type PipelineLogPage, type PipelineLogQuery, type PipelineLogReader, type PipelineLogReaderOptions, type PipelineLogRow, type PipelineLogSinkOptions, type PrunedBackups, type QueryCoordinator, type QueryCoordinatorOptions, type RankFanOutRequest, type RankFanOutResult, type RankPageFanOutRequest, type RankPageFanOutResult, type RateLimiterLike, type ResolvedSecurity, type ResolvedShard, type RestInvoke, type RestRateLimit, type RestRegistryEntry, type RestRegistryLike, type RestRoute, type RestRouteDeps, type Route, type RpcContext, type RpcEnvelope, type RunExportTapOptions, SHARD_REGISTRY_DO_NAME, STORAGE_UPLOAD_MAX_BODY_BYTES, type ScheduledControllerLike, type SecurityHeadersOptions, type SecurityOptions, type SentrySinkOptions, type ShardCallArgs, type ShardCallOptions, type ShardCallReturn, type ShardCaller, type ShardCallerIdentity, type ShardClient, type ShardClientOptions, type ShardError, type ShardExportOutcome, type ShardFunctionReference, type ShardImportOutcome, type ShardMigrationOutcome, type ShardNamespaceInput, type ShardNamespaceLike, type ShardRankOutcome, type ShardRankPageOutcome, type ShardRegistry, type ShardTrafficEntry, type ShardTrafficFanOutRequest, type ShardTrafficFanOutResult, type ShardingInfo, type SpanEvent, type StorageListFunction as StorageListFn, type StorageObject, type TraceSamplingConfig, type TraceTrustSignal, type TriggerTrace, type TrustInboundTraceContext, VERSION, type VectorIndexSummary, type VectorIntrospector, type VectorQueryMatch, type WebhookSinkOptions, type WorkerOptions, analyticsEngineSink, applyJurisdiction, applyRestCache, argsFromQuery, backupManifestKey, backupObjectKey, backupObjectKeyOfManifest, buildHealthRoutes, buildRestRoutes, combineSinks, composeIdentityResolvers, composeWorker, consoleSink, createCrossShardRelationCapabilities, createDynamicShardRegistry, createKvCursorStore, createLunoraHandler, createMemoryCursorStore, createPipelineLogReader, createQueryCoordinator, createRestRateLimit, createShardClient, createStaticShardRegistry, createWorker, d1Probe, decorateResponse, defineExportSink, defineRpcEnvelope, durableObjectProbe, emitLogEvent, emitRpcEvent, enforceOrigin, handleCorsPreflight, isBackupManifestEntry, isBackupManifestKey, memoizeIdentity, memoizeIdentityPerRequest, normalizeBackupPrefix, otlpSink, pipelineLogSink, presenceProbe, r2Sink, requestCarriesCredentials, resolveLogArchiveFromEnv, resolveLunoraOptions, resolveSecurity, resolveShard, restCacheHeaders, restSurfaceFromRegistry, routeIdentityResolvers, runExportTap, sanitizeChange, sentrySink, toAirbyteMessages, toErrorResponse, toFivetranResponse, webhookExportSink, webhookSink, withFrameworkWorker };
package/dist/index.d.ts CHANGED
@@ -2578,8 +2578,15 @@ interface RateLimiterLike {
2578
2578
  /**
2579
2579
  * Adapt a `@lunora/ratelimit` limiter into a {@link RestRateLimit} gate for the
2580
2580
  * public REST surface (plan 167). Pass the limiter and the rate name to charge;
2581
- * `key` isolates the limit per caller (IP / user / API key — defaults to the
2582
- * `cf-connecting-ip` header, else {@link UNRESOLVED_IP_BUCKET}).
2581
+ * `key` isolates the limit per caller (IP / user / API key — defaults to
2582
+ * {@link trustedClientIp}, else {@link UNRESOLVED_IP_BUCKET}).
2583
+ *
2584
+ * That default resolves an IP only ON Cloudflare, where the edge stamps
2585
+ * `cf-connecting-ip` over anything the client sent. On any other host it is a
2586
+ * header the caller types, so trusting it would give an attacker a fresh bucket
2587
+ * per request and the limit would stop applying to exactly the traffic it exists
2588
+ * to stop; those deployments pool into {@link UNRESOLVED_IP_BUCKET} instead, and
2589
+ * should pass `key` to identify callers by something they cannot forge.
2583
2590
  *
2584
2591
  * A rate rejection becomes a `429` with a `Retry-After` header (seconds, ceil of
2585
2592
  * the limiter's ms). A deny-list hit becomes a `403` and no `Retry-After` —
@@ -3335,12 +3342,21 @@ interface ScheduledControllerLike {
3335
3342
  * trigger's `cron` expression. Runs server-side with no end-user identity.
3336
3343
  */
3337
3344
  type CronHandler = (controller: ScheduledControllerLike, env: unknown, context: ExecutionContextLike) => Promise<void> | void;
3345
+ /**
3346
+ * The trigger's own trace, handed to a consumer so every function it dispatches
3347
+ * is a child of the trigger span instead of an unrelated root trace.
3348
+ */
3349
+ interface TriggerTrace {
3350
+ /** W3C `traceparent` naming the trigger's SERVER span. */
3351
+ traceparent: string;
3352
+ }
3338
3353
  /**
3339
3354
  * A Cloudflare Queues push-consumer handler — the worker's `queue()` entry
3340
3355
  * forwards each delivered `MessageBatch` (typed `unknown` here to keep the
3341
- * runtime decoupled from `@lunora/queue`'s structural batch type).
3356
+ * runtime decoupled from `@lunora/queue`'s structural batch type) along with the
3357
+ * invocation's own {@link TriggerTrace}.
3342
3358
  */
3343
- type QueueConsumerHandler = (batch: unknown, env: unknown, context: ExecutionContextLike) => Promise<void>;
3359
+ type QueueConsumerHandler = (batch: unknown, env: unknown, context: ExecutionContextLike, trigger: TriggerTrace) => Promise<void>;
3344
3360
  /**
3345
3361
  * A single code-defined cron job, shaped like an entry of the generated
3346
3362
  * `LUNORA_CRONS` map. `functionPath` is the `"namespace:fn"` to run, `args` its
@@ -5170,4 +5186,4 @@ export { type AccessContextLike, type AccessIdentityLike, type AdminTableResolve
5170
5186
  * surface — without a name for it, a caller cannot hoist a shared attribute bag
5171
5187
  * into a typed constant.
5172
5188
  */
5173
- type OtlpResourceAttributes, type OtlpSinkOptions, type PipelineLike, type PipelineLogColumnMap, type PipelineLogCursor, type PipelineLogField, type PipelineLogPage, type PipelineLogQuery, type PipelineLogReader, type PipelineLogReaderOptions, type PipelineLogRow, type PipelineLogSinkOptions, type PrunedBackups, type QueryCoordinator, type QueryCoordinatorOptions, type RankFanOutRequest, type RankFanOutResult, type RankPageFanOutRequest, type RankPageFanOutResult, type RateLimiterLike, type ResolvedSecurity, type ResolvedShard, type RestInvoke, type RestRateLimit, type RestRegistryEntry, type RestRegistryLike, type RestRoute, type RestRouteDeps, type Route, type RpcContext, type RpcEnvelope, type RunExportTapOptions, SHARD_REGISTRY_DO_NAME, STORAGE_UPLOAD_MAX_BODY_BYTES, type ScheduledControllerLike, type SecurityHeadersOptions, type SecurityOptions, type SentrySinkOptions, type ShardCallArgs, type ShardCallOptions, type ShardCallReturn, type ShardCaller, type ShardCallerIdentity, type ShardClient, type ShardClientOptions, type ShardError, type ShardExportOutcome, type ShardFunctionReference, type ShardImportOutcome, type ShardMigrationOutcome, type ShardNamespaceInput, type ShardNamespaceLike, type ShardRankOutcome, type ShardRankPageOutcome, type ShardRegistry, type ShardTrafficEntry, type ShardTrafficFanOutRequest, type ShardTrafficFanOutResult, type ShardingInfo, type SpanEvent, type StorageListFunction as StorageListFn, type StorageObject, type TraceSamplingConfig, type TraceTrustSignal, type TrustInboundTraceContext, VERSION, type VectorIndexSummary, type VectorIntrospector, type VectorQueryMatch, type WebhookSinkOptions, type WorkerOptions, analyticsEngineSink, applyJurisdiction, applyRestCache, argsFromQuery, backupManifestKey, backupObjectKey, backupObjectKeyOfManifest, buildHealthRoutes, buildRestRoutes, combineSinks, composeIdentityResolvers, composeWorker, consoleSink, createCrossShardRelationCapabilities, createDynamicShardRegistry, createKvCursorStore, createLunoraHandler, createMemoryCursorStore, createPipelineLogReader, createQueryCoordinator, createRestRateLimit, createShardClient, createStaticShardRegistry, createWorker, d1Probe, decorateResponse, defineExportSink, defineRpcEnvelope, durableObjectProbe, emitLogEvent, emitRpcEvent, enforceOrigin, handleCorsPreflight, isBackupManifestEntry, isBackupManifestKey, memoizeIdentity, memoizeIdentityPerRequest, normalizeBackupPrefix, otlpSink, pipelineLogSink, presenceProbe, r2Sink, requestCarriesCredentials, resolveLogArchiveFromEnv, resolveLunoraOptions, resolveSecurity, resolveShard, restCacheHeaders, restSurfaceFromRegistry, routeIdentityResolvers, runExportTap, sanitizeChange, sentrySink, toAirbyteMessages, toErrorResponse, toFivetranResponse, webhookExportSink, webhookSink, withFrameworkWorker };
5189
+ type OtlpResourceAttributes, type OtlpSinkOptions, type PipelineLike, type PipelineLogColumnMap, type PipelineLogCursor, type PipelineLogField, type PipelineLogPage, type PipelineLogQuery, type PipelineLogReader, type PipelineLogReaderOptions, type PipelineLogRow, type PipelineLogSinkOptions, type PrunedBackups, type QueryCoordinator, type QueryCoordinatorOptions, type RankFanOutRequest, type RankFanOutResult, type RankPageFanOutRequest, type RankPageFanOutResult, type RateLimiterLike, type ResolvedSecurity, type ResolvedShard, type RestInvoke, type RestRateLimit, type RestRegistryEntry, type RestRegistryLike, type RestRoute, type RestRouteDeps, type Route, type RpcContext, type RpcEnvelope, type RunExportTapOptions, SHARD_REGISTRY_DO_NAME, STORAGE_UPLOAD_MAX_BODY_BYTES, type ScheduledControllerLike, type SecurityHeadersOptions, type SecurityOptions, type SentrySinkOptions, type ShardCallArgs, type ShardCallOptions, type ShardCallReturn, type ShardCaller, type ShardCallerIdentity, type ShardClient, type ShardClientOptions, type ShardError, type ShardExportOutcome, type ShardFunctionReference, type ShardImportOutcome, type ShardMigrationOutcome, type ShardNamespaceInput, type ShardNamespaceLike, type ShardRankOutcome, type ShardRankPageOutcome, type ShardRegistry, type ShardTrafficEntry, type ShardTrafficFanOutRequest, type ShardTrafficFanOutResult, type ShardingInfo, type SpanEvent, type StorageListFunction as StorageListFn, type StorageObject, type TraceSamplingConfig, type TraceTrustSignal, type TriggerTrace, type TrustInboundTraceContext, VERSION, type VectorIndexSummary, type VectorIntrospector, type VectorQueryMatch, type WebhookSinkOptions, type WorkerOptions, analyticsEngineSink, applyJurisdiction, applyRestCache, argsFromQuery, backupManifestKey, backupObjectKey, backupObjectKeyOfManifest, buildHealthRoutes, buildRestRoutes, combineSinks, composeIdentityResolvers, composeWorker, consoleSink, createCrossShardRelationCapabilities, createDynamicShardRegistry, createKvCursorStore, createLunoraHandler, createMemoryCursorStore, createPipelineLogReader, createQueryCoordinator, createRestRateLimit, createShardClient, createStaticShardRegistry, createWorker, d1Probe, decorateResponse, defineExportSink, defineRpcEnvelope, durableObjectProbe, emitLogEvent, emitRpcEvent, enforceOrigin, handleCorsPreflight, isBackupManifestEntry, isBackupManifestKey, memoizeIdentity, memoizeIdentityPerRequest, normalizeBackupPrefix, otlpSink, pipelineLogSink, presenceProbe, r2Sink, requestCarriesCredentials, resolveLogArchiveFromEnv, resolveLunoraOptions, resolveSecurity, resolveShard, restCacheHeaders, restSurfaceFromRegistry, routeIdentityResolvers, runExportTap, sanitizeChange, sentrySink, toAirbyteMessages, toErrorResponse, toFivetranResponse, webhookExportSink, webhookSink, withFrameworkWorker };
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{BACKUP_KEY_PREFIX as t,backupManifestKey as a,backupObjectKey as s,backupObjectKeyOfManifest as i,isBackupManifestEntry as n,isBackupManifestKey as p,normalizeBackupPrefix as c}from"./packem_shared/BACKUP_KEY_PREFIX-BOtSu-_3.mjs";import{toAirbyteMessages as f,toFivetranResponse as E}from"./packem_shared/toAirbyteMessages-BX5SK-Ss.mjs";import{composeWorker as x,createLunoraHandler as S,createWorker as l,defineRpcEnvelope as u,resolveLunoraOptions as _,withFrameworkWorker as d}from"./packem_shared/composeWorker-B_dbXCev.mjs";import{createCrossShardRelationCapabilities as y}from"./packem_shared/createCrossShardRelationCapabilities-B6jWmfjn.mjs";import{DEFAULT_REGISTRY_CACHE_TTL_MS as O,SHARD_REGISTRY_DO_NAME as b,createDynamicShardRegistry as A}from"./packem_shared/DEFAULT_REGISTRY_CACHE_TTL_MS-D5O7elXI.mjs";import{LunoraError as T,toErrorResponse as h}from"./packem_shared/LunoraError-DksAgIpa.mjs";import{c as P,a as g,d as v,r as I,b as D,s as M,w as F}from"./packem_shared/export-tap-mRfLykiL.mjs";import{HEALTH_PATH as G,HEALTH_READY_PATH as K,buildHealthRoutes as U,d1Probe as B,durableObjectProbe as Y,presenceProbe as w}from"./packem_shared/HEALTH_PATH-D0i8LhwT.mjs";import{LOG_ARCHIVE_PATH as X,resolveLogArchiveFromEnv as j}from"./packem_shared/LOG_ARCHIVE_PATH-Hmjpz_Ko.mjs";import{memoizeIdentity as W,memoizeIdentityPerRequest as q}from"./packem_shared/memoizeIdentity-DnOj3QRi.mjs";import{e as J,a as Z}from"./packem_shared/observability-B1hLjwgx.mjs";import{analyticsEngineSink as ee,combineSinks as re,consoleSink as oe,otlpSink as te,pipelineLogSink as ae,sentrySink as se,webhookSink as ie}from"./packem_shared/analyticsEngineSink-DOreZlpn.mjs";import{D as pe,c as ce}from"./packem_shared/pipeline-log-reader-C-nuWG_e.mjs";import{createQueryCoordinator as fe,createStaticShardRegistry as Ee}from"./packem_shared/createQueryCoordinator-DlWITOu1.mjs";import{applyJurisdiction as xe,resolveShard as Se}from"./packem_shared/applyJurisdiction-C0ddU7Tg.mjs";import{a as ue,r as _e,b as de}from"./packem_shared/rest-cache-D1BlbZb1.mjs";import{a as ye,b as Ce,c as Oe,r as be}from"./packem_shared/rest-routes-BbMQwlSV.mjs";import{decorateResponse as Le,enforceOrigin as Te,handleCorsPreflight as he,resolveSecurity as He}from"./packem_shared/decorateResponse-Y2sCM0w1.mjs";import{createShardClient as ge}from"./packem_shared/createShardClient-CECfFWIM.mjs";import{STORAGE_UPLOAD_MAX_BODY_BYTES as Ie}from"./packem_shared/STORAGE_UPLOAD_MAX_BODY_BYTES-BqyO-1l6.mjs";import{LOG_ARCHIVE_NOT_CONFIGURED as Me}from"./packem_shared/LOG_ARCHIVE_NOT_CONFIGURED-CDpi4yFD.mjs";import{NOOP_EXECUTION_CONTEXT as Ne}from"./packem_shared/NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{composeIdentityResolvers as Ke,routeIdentityResolvers as Ue}from"./packem_shared/composeIdentityResolvers-BHZ4jH8o.mjs";const e="0.0.0";export{t as BACKUP_KEY_PREFIX,pe as DEFAULT_LOG_COLUMNS,O as DEFAULT_REGISTRY_CACHE_TTL_MS,G as HEALTH_PATH,K as HEALTH_READY_PATH,Me as LOG_ARCHIVE_NOT_CONFIGURED,X as LOG_ARCHIVE_PATH,T as LunoraError,Ne as NOOP_EXECUTION_CONTEXT,b as SHARD_REGISTRY_DO_NAME,Ie as STORAGE_UPLOAD_MAX_BODY_BYTES,e as VERSION,ee as analyticsEngineSink,xe as applyJurisdiction,ue as applyRestCache,ye as argsFromQuery,a as backupManifestKey,s as backupObjectKey,i as backupObjectKeyOfManifest,U as buildHealthRoutes,Ce as buildRestRoutes,re as combineSinks,Ke as composeIdentityResolvers,x as composeWorker,oe as consoleSink,y as createCrossShardRelationCapabilities,A as createDynamicShardRegistry,P as createKvCursorStore,S as createLunoraHandler,g as createMemoryCursorStore,ce as createPipelineLogReader,fe as createQueryCoordinator,Oe as createRestRateLimit,ge as createShardClient,Ee as createStaticShardRegistry,l as createWorker,B as d1Probe,Le as decorateResponse,v as defineExportSink,u as defineRpcEnvelope,Y as durableObjectProbe,J as emitLogEvent,Z as emitRpcEvent,Te as enforceOrigin,he as handleCorsPreflight,n as isBackupManifestEntry,p as isBackupManifestKey,W as memoizeIdentity,q as memoizeIdentityPerRequest,c as normalizeBackupPrefix,te as otlpSink,ae as pipelineLogSink,w as presenceProbe,I as r2Sink,_e as requestCarriesCredentials,j as resolveLogArchiveFromEnv,_ as resolveLunoraOptions,He as resolveSecurity,Se as resolveShard,de as restCacheHeaders,be as restSurfaceFromRegistry,Ue as routeIdentityResolvers,D as runExportTap,M as sanitizeChange,se as sentrySink,f as toAirbyteMessages,h as toErrorResponse,E as toFivetranResponse,F as webhookExportSink,ie as webhookSink,d as withFrameworkWorker};
1
+ import{BACKUP_KEY_PREFIX as t,backupManifestKey as a,backupObjectKey as s,backupObjectKeyOfManifest as i,isBackupManifestEntry as n,isBackupManifestKey as p,normalizeBackupPrefix as c}from"./packem_shared/BACKUP_KEY_PREFIX-BOtSu-_3.mjs";import{toAirbyteMessages as f,toFivetranResponse as E}from"./packem_shared/toAirbyteMessages-2d_iJXPf.mjs";import{composeWorker as x,createLunoraHandler as S,createWorker as l,defineRpcEnvelope as u,resolveLunoraOptions as _,withFrameworkWorker as d}from"./packem_shared/composeWorker-TSwsCtpP.mjs";import{createCrossShardRelationCapabilities as y}from"./packem_shared/createCrossShardRelationCapabilities-D_S3beMO.mjs";import{DEFAULT_REGISTRY_CACHE_TTL_MS as O,SHARD_REGISTRY_DO_NAME as b,createDynamicShardRegistry as A}from"./packem_shared/DEFAULT_REGISTRY_CACHE_TTL_MS-D5O7elXI.mjs";import{LunoraError as T,toErrorResponse as h}from"./packem_shared/LunoraError-DksAgIpa.mjs";import{c as P,a as g,d as v,r as I,b as D,s as M,w as F}from"./packem_shared/export-tap-CAyZ2TWC.mjs";import{HEALTH_PATH as G,HEALTH_READY_PATH as K,buildHealthRoutes as U,d1Probe as B,durableObjectProbe as Y,presenceProbe as w}from"./packem_shared/HEALTH_PATH-D0i8LhwT.mjs";import{LOG_ARCHIVE_PATH as X,resolveLogArchiveFromEnv as j}from"./packem_shared/LOG_ARCHIVE_PATH-Hmjpz_Ko.mjs";import{memoizeIdentity as W,memoizeIdentityPerRequest as q}from"./packem_shared/memoizeIdentity-DnOj3QRi.mjs";import{e as J,a as Z}from"./packem_shared/observability-B1hLjwgx.mjs";import{analyticsEngineSink as ee,combineSinks as re,consoleSink as oe,otlpSink as te,pipelineLogSink as ae,sentrySink as se,webhookSink as ie}from"./packem_shared/analyticsEngineSink-JUcPmzoo.mjs";import{D as pe,c as ce}from"./packem_shared/pipeline-log-reader-C-nuWG_e.mjs";import{createQueryCoordinator as fe,createStaticShardRegistry as Ee}from"./packem_shared/createQueryCoordinator-DlWITOu1.mjs";import{applyJurisdiction as xe,resolveShard as Se}from"./packem_shared/applyJurisdiction-C0ddU7Tg.mjs";import{a as ue,r as _e,b as de}from"./packem_shared/rest-cache-D1BlbZb1.mjs";import{a as ye,b as Ce,c as Oe,r as be}from"./packem_shared/rest-routes-CyXGd_yB.mjs";import{decorateResponse as Le,enforceOrigin as Te,handleCorsPreflight as he,resolveSecurity as He}from"./packem_shared/decorateResponse-Y2sCM0w1.mjs";import{createShardClient as ge}from"./packem_shared/createShardClient-CAv0OrEW.mjs";import{STORAGE_UPLOAD_MAX_BODY_BYTES as Ie}from"./packem_shared/STORAGE_UPLOAD_MAX_BODY_BYTES-BqyO-1l6.mjs";import{LOG_ARCHIVE_NOT_CONFIGURED as Me}from"./packem_shared/LOG_ARCHIVE_NOT_CONFIGURED-CDpi4yFD.mjs";import{NOOP_EXECUTION_CONTEXT as Ne}from"./packem_shared/NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{composeIdentityResolvers as Ke,routeIdentityResolvers as Ue}from"./packem_shared/composeIdentityResolvers-BHZ4jH8o.mjs";const e="0.0.0";export{t as BACKUP_KEY_PREFIX,pe as DEFAULT_LOG_COLUMNS,O as DEFAULT_REGISTRY_CACHE_TTL_MS,G as HEALTH_PATH,K as HEALTH_READY_PATH,Me as LOG_ARCHIVE_NOT_CONFIGURED,X as LOG_ARCHIVE_PATH,T as LunoraError,Ne as NOOP_EXECUTION_CONTEXT,b as SHARD_REGISTRY_DO_NAME,Ie as STORAGE_UPLOAD_MAX_BODY_BYTES,e as VERSION,ee as analyticsEngineSink,xe as applyJurisdiction,ue as applyRestCache,ye as argsFromQuery,a as backupManifestKey,s as backupObjectKey,i as backupObjectKeyOfManifest,U as buildHealthRoutes,Ce as buildRestRoutes,re as combineSinks,Ke as composeIdentityResolvers,x as composeWorker,oe as consoleSink,y as createCrossShardRelationCapabilities,A as createDynamicShardRegistry,P as createKvCursorStore,S as createLunoraHandler,g as createMemoryCursorStore,ce as createPipelineLogReader,fe as createQueryCoordinator,Oe as createRestRateLimit,ge as createShardClient,Ee as createStaticShardRegistry,l as createWorker,B as d1Probe,Le as decorateResponse,v as defineExportSink,u as defineRpcEnvelope,Y as durableObjectProbe,J as emitLogEvent,Z as emitRpcEvent,Te as enforceOrigin,he as handleCorsPreflight,n as isBackupManifestEntry,p as isBackupManifestKey,W as memoizeIdentity,q as memoizeIdentityPerRequest,c as normalizeBackupPrefix,te as otlpSink,ae as pipelineLogSink,w as presenceProbe,I as r2Sink,_e as requestCarriesCredentials,j as resolveLogArchiveFromEnv,_ as resolveLunoraOptions,He as resolveSecurity,Se as resolveShard,de as restCacheHeaders,be as restSurfaceFromRegistry,Ue as routeIdentityResolvers,D as runExportTap,M as sanitizeChange,se as sentrySink,f as toAirbyteMessages,h as toErrorResponse,E as toFivetranResponse,F as webhookExportSink,ie as webhookSink,d as withFrameworkWorker};
@@ -1 +1 @@
1
- import{LunoraError as Z}from"@lunora/errors";import{redactArgs as j}from"@lunora/observability";import{e as l,L as y,o as $,c as S,O as V,f as Q,g as v,h as z,w as rr,i as tr,j as or,m as er}from"./otlp-resource-DeXhb949.mjs";const sr=r=>{if(typeof r=="string")return r;try{return JSON.stringify(r)??String(r)}catch{return String(r)}},W=r=>typeof r=="boolean"||typeof r=="number"||typeof r=="string"?r:sr(r),nr=512,ir=200,ar=r=>{const e=r.maxItems??nr,o=r.maxDelayMs??ir;let t=[],s,c,n;const a=()=>{s!==void 0&&(clearTimeout(s),s=void 0)},h=async()=>{a();const p=t;t=[];const d=n;c=void 0,n=void 0;try{p.length>0&&await r.export(p)}catch{}finally{d?.()}},m=p=>{c===void 0&&(c=new Promise(d=>{n=d}),s=setTimeout(()=>{h()},o)),p?.(c)};return{add:(p,d)=>{for(t.push(p);t.length>e;)t.shift();m(d),t.length>=e&&h()},flush:async p=>{if(t.length===0){a();return}const d=h();return p?.(d),d},get size(){return t.length}}},cr=/["\\\u0000-\u001F\uD800-\uDFFF]/,B=r=>cr.test(r)?JSON.stringify(r):`"${r}"`,A=r=>{if(r===void 0)return"null";if(typeof r=="bigint")throw new TypeError("stableStringify: cannot use a bigint in a stable JSON cache key — pass it as a string, or use stableWireKey");if(typeof r=="number"){if(Number.isNaN(r))return"nan";if(r===1/0)return"inf";if(r===-1/0)return"-inf";if(Object.is(r,-0))return"-0"}if(typeof r=="string")return B(r);if(r===null||typeof r!="object")return JSON.stringify(r);if(Array.isArray(r)){let n="[";for(let a=0;a<r.length;a++)a>0&&(n+=","),n+=A(r[a]);return n+"]"}const e=Object.getPrototypeOf(r);if(e!==null&&e!==Object.prototype){const n=r.constructor?.name??"value";throw new TypeError(`stableStringify: cannot use a ${n} in a stable JSON cache key — only plain objects, arrays, and JSON primitives are supported (wire-typed values key via stableWireKey)`)}const o=r,t=Object.keys(o).sort();let s="{",c=!0;for(const n of t){const a=o[n];a!==void 0&&(c?c=!1:s+=",",s+=B(n),s+=":",s+=A(a))}return s+"}"},dr=(r,e)=>{const o=[l(y.functionPath,r.functionPath),l(y.ok,r.ok)];r.method!==void 0&&o.push(l("http.request.method",r.method)),r.path!==void 0&&o.push(l("url.path",r.path)),o.push(l("http.route",r.functionPath)),r.scheme!==void 0&&o.push(l("url.scheme",r.scheme)),r.host!==void 0&&o.push(l("server.address",r.host)),r.port!==void 0&&o.push(l("server.port",r.port)),r.userAgent!==void 0&&o.push(l("user_agent.original",r.userAgent)),r.shardKey!==void 0&&o.push(l(y.shardKey,r.shardKey)),o.push(l("http.response.status_code",r.error?.status??200)),r.error&&o.push(l(y.errorType,r.error.code),l("lunora.error_status",r.error.status)),r.fanOut&&o.push(l("lunora.fanout.table",r.fanOut.table),l("lunora.fanout.shards",r.fanOut.shards),l("lunora.fanout.failed",r.fanOut.failed));const t={attributes:o,endTimeUnixNano:S(e),kind:V.server,name:r.functionPath,...r.parentSpanId===void 0?{}:{parentSpanId:r.parentSpanId},spanId:r.spanId??$(8),startTimeUnixNano:S(e-r.durationMs),status:r.ok?{code:1}:{code:2,message:r.error?.message??""},traceId:r.traceId??$(16)};return r.traceFlags!==void 0&&(t.flags=r.traceFlags),r.error&&(t.events=[{attributes:[l("exception.type",r.error.code),l("exception.message",r.error.message)],name:"exception",timeUnixNano:S(e)}]),t},M=(r,e)=>{const o=new Map([[y.functionPath,l(y.functionPath,r.functionPath)]]);r.shardKey!==void 0&&o.set(y.shardKey,l(y.shardKey,r.shardKey)),r.userId!==void 0&&o.set(y.userId,l(y.userId,r.userId)),r.errorType!==void 0&&o.set(y.errorType,l(y.errorType,r.errorType));for(const[t,s]of Object.entries(e??{}))o.set(t,l(t,W(s)));return[...o.values()]},ur=r=>{const e={attributes:M({errorType:r.error?.type,functionPath:r.functionPath,shardKey:r.shardKey,userId:r.userId},r.attributes),endTimeUnixNano:S(r.startTs+r.durationMs),kind:V[r.kind??"internal"],name:r.name,parentSpanId:r.parentSpanId,spanId:r.spanId,startTimeUnixNano:S(r.startTs),status:r.ok?{code:1}:{code:2,message:r.error?.message??""},traceId:r.traceId},o=t=>v(Object.fromEntries(Object.entries(t??{}).map(([s,c])=>[s,W(c)])));return r.events!==void 0&&r.events.length>0&&(e.events=r.events.map(t=>({attributes:o(t.attributes),name:t.name,timeUnixNano:S(t.ts)}))),r.links!==void 0&&r.links.length>0&&(e.links=r.links.map(t=>({attributes:o(t.attributes),spanId:t.spanId,traceId:t.traceId}))),e},lr=r=>{const e=S(r.ts),o=M({functionPath:r.functionPath,shardKey:r.shardKey},r.attributes),t={asDouble:r.value,attributes:o,timeUnixNano:e};return r.kind==="gauge"?{gauge:{dataPoints:[t]},name:r.name}:r.kind==="histogram"?{histogram:{aggregationTemporality:1,dataPoints:[{attributes:o,bucketCounts:["1"],count:"1",explicitBounds:[],max:r.value,min:r.value,sum:r.value,timeUnixNano:e}]},name:r.name}:{name:r.name,sum:{aggregationTemporality:1,dataPoints:[t],isMonotonic:!0}}},pr=r=>{const e={attributes:M({functionPath:r.functionPath,shardKey:r.shardKey,userId:r.userId},r.fields),body:{stringValue:r.message},severityNumber:Q[r.level],severityText:r.level.toUpperCase(),timeUnixNano:S(r.ts)};return r.traceId!==void 0&&(e.traceId=r.traceId),r.spanId!==void 0&&(e.spanId=r.spanId),r.eventName!==void 0&&(e.eventName=r.eventName,e.attributes.push(l("event.name",r.eventName))),e},fr=1024,J=5;let R=0;const mr=(r,e)=>{if(R>=J)return;R+=1;let o;try{o=new URL(r).host}catch{o="<unparseable endpoint>"}const t=R===J?" Further OTLP rejections are silenced until the isolate restarts.":"";console.error(`[lunora:otlp] collector ${o} rejected the export with HTTP ${String(e)}; the batch is DROPPED (there is no retry).${t}`)},hr=async r=>{const e=new Blob([r]).stream().pipeThrough(new CompressionStream("gzip"));return new Response(e).arrayBuffer()},X=async(r,e,o,t)=>{try{const s=JSON.stringify(e),{byteLength:c}=new TextEncoder().encode(s),n=(c<fr?fetch(r,{body:s,headers:o,method:"POST"}):hr(s).then(a=>fetch(r,{body:a,headers:{...o,"content-encoding":"gzip"},method:"POST"}))).then(a=>{a.ok||mr(r,a.status)},()=>{});t?.(n),await n}catch{}},yr=(r,e,o,t)=>{X(r,e,o,t?.waitUntil).catch(()=>{})},O=(r,e)=>e===!0&&r.ok,gr=r=>r.kind==="metric"?void 0:r.event.traceId,br=r=>{const e=Map.groupBy(r,t=>gr(t)),o=e.get(void 0)??[];return e.delete(void 0),{byTrace:e,untraced:o}},C=5,kr=(r,e,o)=>{if(e===void 0)return r;const{byTrace:t,untraced:s}=br(r),c=[...s];let n=0,a;for(const[h,m]of t){let p;try{p=e({logs:m.filter(d=>d.kind==="log").map(d=>d.event),rpc:m.filter(d=>d.kind==="rpc").map(d=>d.event),spans:m.filter(d=>d.kind==="span").map(d=>d.event),traceId:h})}catch(d){n+=1,n===1&&(a=d),p=!0}p&&c.push(...m)}return n>0&&o(a,n),c},P=(r,e)=>{if(e===void 0)return r;try{return e(r)??void 0}catch{return}},Sr=r=>({...r,...r.fields===void 0?{}:{fields:j(r.fields)},message:j(r.message)}),H=(r,e,o)=>{if(r.kind==="rpc"){const s=P(r.event,e?.rpc);return s===void 0?void 0:{bucket:"spans",encoded:dr(s,r.endMs)}}if(r.kind==="span"){const s=P(r.event,e?.span);return s===void 0?void 0:{bucket:"spans",encoded:ur(s)}}if(r.kind==="log"){const s=P(o?Sr(r.event):r.event,e?.log);return s===void 0?void 0:{bucket:"logs",encoded:pr(s)}}const t=P(r.event,e?.metric);return t===void 0?void 0:{bucket:"metrics",encoded:lr(t)}},Ir=["fuseCloudflareTraces","instrumentDatabase","metricHistory","traceFetch"],Or=(r={})=>{const{onlyErrors:e}=r;return{onLog:o=>{o.level==="error"||o.level==="fatal"?console.error("[lunora:log]",o.functionPath,o.message):console.log("[lunora:log]",o.functionPath,o.message)},onMetric:o=>{console.log("[lunora:metric]",`${o.name}=${String(o.value)}`,o.kind,o.functionPath)},onRpc:o=>{O(o,e)||(o.ok?console.log("[lunora:rpc]",o):console.error("[lunora:rpc]",o))},onSpan:o=>{const t=o.ok?"ok":`error ${o.error?.type??""}`.trim();console.log("[lunora:span]",o.name,`${String(o.durationMs)}ms`,t,o.functionPath)}}},Nr=r=>{const{headers:e,onlyErrors:o,transform:t,transformLog:s,url:c}=r,n=z({"content-type":"application/json"},e),a=(h,m)=>{try{const p=fetch(c,{body:JSON.stringify(h),headers:n,method:"POST"}).catch(()=>{});m?.waitUntil&&m.waitUntil(p)}catch{}};return{onLog:(h,m)=>{const p=P(h,s);p!==void 0&&a(p,m)},onRpc:(h,m)=>{if(O(h,o))return;const p=P(h,t);p!==void 0&&a(p,m)}}},Er=r=>{const{capture:e,captureLog:o}=r;if(typeof e!="function")throw new TypeError("sentrySink requires a `capture` callback — wire your own Sentry client, e.g. `sentrySink({ capture: (event) => Sentry.captureMessage(event.name) })`. There is no `dsn` option; the runtime bundles no Sentry client.");const t=r.onlyErrors??!0;return{onLog:o?s=>{try{o(s)}catch{}}:void 0,onRpc:s=>{if(!O(s,t))try{e(s)}catch{}}}},Lr=r=>{const{dataset:e,onlyErrors:o}=r;return{onRpc:t=>{if(!O(t,o))try{e.writeDataPoint({blobs:[t.functionPath,t.ok?"ok":"error",t.shardKey??"",t.error?.code??"",t.fanOut?.table??""],doubles:[t.durationMs,t.ok?0:1,t.fanOut?.shards??0,t.fanOut?.failed??0],indexes:[t.functionPath]})}catch{}}}},Rr=r=>{const{pipeline:e,serializeFields:o}=r;return{onLog:(t,s)=>{try{const c={functionPath:t.functionPath,level:t.level,message:t.message,ts:t.ts};t.fields&&(c.fields=o===!0?JSON.stringify(t.fields):t.fields);for(const a of["shardKey","userId","traceId","spanId"])t[a]!==void 0&&(c[a]=t[a]);const n=e.send([c]).catch(()=>{});s?.waitUntil&&s.waitUntil(n)}catch{}}}},Ar=r=>{const{batch:e,deploymentEnvironment:o,detectResources:t,endpoint:s,headers:c,onlyErrors:n,postProcessor:a,resourceAttributes:h,serviceNamespace:m,serviceVersion:p,tailSampler:d,token:q}=r,x=r.serviceName??"lunora",U=r.redactLogs??!0;if(e!==!1&&e?.maxItems!==void 0&&(!Number.isInteger(e.maxItems)||e.maxItems<1))throw new Z("ENV_INVALID",`otlpSink: \`batch.maxItems\` must be a positive integer, received ${String(e.maxItems)}.`);const _={...p===void 0?{}:{"service.version":p},...m===void 0?{}:{"service.namespace":m},...o===void 0?{}:{"deployment.environment":o},...h},D=new WeakMap,k=u=>{if(t!==!0||u?.resourceAttributes===void 0)return _;const i=D.get(u);if(i!==void 0)return i;const f=er(u.resourceAttributes(),_);return D.set(u,f),f};let I=s;for(;I.endsWith("/");)I=I.slice(0,-1);const F={logs:{url:`${I}/v1/logs`,wrap:or},metrics:{url:`${I}/v1/metrics`,wrap:tr},spans:{url:`${I}/v1/traces`,wrap:rr}},K=z({"content-type":"application/json"},c,q);let L=0;const G=(u,i)=>{if(L>=C)return;L+=1;const f=L===C?" Further tailSampler failures from this sink are silenced until the isolate restarts.":"";console.error(`[lunora:otlp] tailSampler threw for ${String(i)} trace(s) in this flush window; keeping them (fail-open), so the sampling policy did NOT apply.${f}`,u)},Y=async u=>{const i=kr(u,d,G),f=new Map;for(const g of i){const b=H(g,a,U);if(b===void 0)continue;const E=A(g.resource);let T=f.get(E);T===void 0&&(T={logs:[],metrics:[],resource:g.resource,spans:[]},f.set(E,T)),T[b.bucket].push(b.encoded)}const w=[];for(const[,g]of f)for(const b of["spans","logs","metrics"])if(g[b].length>0){const{url:E,wrap:T}=F[b];w.push(X(E,T(g[b],"@lunora/runtime",x,g.resource),K))}await Promise.all(w)};if(e===!1){const u=(i,f)=>{const w=H(i,a,U);if(w!==void 0){const{url:g,wrap:b}=F[w.bucket];yr(g,b(w.encoded,"@lunora/runtime",x,i.resource),K,f)}};return{onLog:(i,f)=>{u({event:i,kind:"log",resource:k(f)},f)},onMetric:(i,f)=>{u({event:i,kind:"metric",resource:k(f)},f)},onRpc:(i,f)=>{O(i,n)||u({endMs:Date.now(),event:i,kind:"rpc",resource:k(f)},f)},onSpan:(i,f)=>{u({event:i,kind:"span",resource:k(f)},f)}}}const N=ar({export:Y,...e?.maxDelayMs===void 0?{}:{maxDelayMs:e.maxDelayMs},...e?.maxItems===void 0?{}:{maxItems:e.maxItems}});return{flush:u=>{N.flush(u?.waitUntil).catch(()=>{})},onLog:(u,i)=>{N.add({event:u,kind:"log",resource:k(i)},i?.waitUntil)},onMetric:(u,i)=>{N.add({event:u,kind:"metric",resource:k(i)},i?.waitUntil)},onRpc:(u,i)=>{O(u,n)||N.add({endMs:Date.now(),event:u,kind:"rpc",resource:k(i)},i?.waitUntil)},onSpan:(u,i)=>{N.add({event:u,kind:"span",resource:k(i)},i?.waitUntil)}}},Mr=(...r)=>{const e=(t,s)=>{for(const c of r){const n=c[t];if(n)try{n.apply(c,s)}catch{}}},o={};for(const t of r)for(const s of Ir)o[s]===void 0&&t[s]!==void 0&&(o[s]=t[s]);return{...o,flush:t=>{e("flush",[t])},onLog:(t,s)=>{e("onLog",[t,s])},onMetric:(t,s)=>{e("onMetric",[t,s])},onRpc:(t,s)=>{e("onRpc",[t,s])},onSpan:(t,s)=>{e("onSpan",[t,s])}}};export{Lr as analyticsEngineSink,Mr as combineSinks,Or as consoleSink,Ar as otlpSink,Rr as pipelineLogSink,Er as sentrySink,Nr as webhookSink};
1
+ import{LunoraError as Z}from"@lunora/errors";import{redactArgs as j}from"@lunora/observability";import{e as l,L as y,o as $,c as S,O as V,f as Q,g as v,h as z,w as rr,i as tr,j as or,m as er}from"./otlp-resource-JKBCWf6c.mjs";const sr=r=>{if(typeof r=="string")return r;try{return JSON.stringify(r)??String(r)}catch{return String(r)}},W=r=>typeof r=="boolean"||typeof r=="number"||typeof r=="string"?r:sr(r),nr=512,ir=200,ar=r=>{const e=r.maxItems??nr,o=r.maxDelayMs??ir;let t=[],s,c,n;const a=()=>{s!==void 0&&(clearTimeout(s),s=void 0)},h=async()=>{a();const p=t;t=[];const d=n;c=void 0,n=void 0;try{p.length>0&&await r.export(p)}catch{}finally{d?.()}},m=p=>{c===void 0&&(c=new Promise(d=>{n=d}),s=setTimeout(()=>{h()},o)),p?.(c)};return{add:(p,d)=>{for(t.push(p);t.length>e;)t.shift();m(d),t.length>=e&&h()},flush:async p=>{if(t.length===0){a();return}const d=h();return p?.(d),d},get size(){return t.length}}},cr=/["\\\u0000-\u001F\uD800-\uDFFF]/,B=r=>cr.test(r)?JSON.stringify(r):`"${r}"`,A=r=>{if(r===void 0)return"null";if(typeof r=="bigint")throw new TypeError("stableStringify: cannot use a bigint in a stable JSON cache key — pass it as a string, or use stableWireKey");if(typeof r=="number"){if(Number.isNaN(r))return"nan";if(r===1/0)return"inf";if(r===-1/0)return"-inf";if(Object.is(r,-0))return"-0"}if(typeof r=="string")return B(r);if(r===null||typeof r!="object")return JSON.stringify(r);if(Array.isArray(r)){let n="[";for(let a=0;a<r.length;a++)a>0&&(n+=","),n+=A(r[a]);return n+"]"}const e=Object.getPrototypeOf(r);if(e!==null&&e!==Object.prototype){const n=r.constructor?.name??"value";throw new TypeError(`stableStringify: cannot use a ${n} in a stable JSON cache key — only plain objects, arrays, and JSON primitives are supported (wire-typed values key via stableWireKey)`)}const o=r,t=Object.keys(o).sort();let s="{",c=!0;for(const n of t){const a=o[n];a!==void 0&&(c?c=!1:s+=",",s+=B(n),s+=":",s+=A(a))}return s+"}"},dr=(r,e)=>{const o=[l(y.functionPath,r.functionPath),l(y.ok,r.ok)];r.method!==void 0&&o.push(l("http.request.method",r.method)),r.path!==void 0&&o.push(l("url.path",r.path)),o.push(l("http.route",r.functionPath)),r.scheme!==void 0&&o.push(l("url.scheme",r.scheme)),r.host!==void 0&&o.push(l("server.address",r.host)),r.port!==void 0&&o.push(l("server.port",r.port)),r.userAgent!==void 0&&o.push(l("user_agent.original",r.userAgent)),r.shardKey!==void 0&&o.push(l(y.shardKey,r.shardKey)),o.push(l("http.response.status_code",r.error?.status??200)),r.error&&o.push(l(y.errorType,r.error.code),l("lunora.error_status",r.error.status)),r.fanOut&&o.push(l("lunora.fanout.table",r.fanOut.table),l("lunora.fanout.shards",r.fanOut.shards),l("lunora.fanout.failed",r.fanOut.failed));const t={attributes:o,endTimeUnixNano:S(e),kind:V.server,name:r.functionPath,...r.parentSpanId===void 0?{}:{parentSpanId:r.parentSpanId},spanId:r.spanId??$(8),startTimeUnixNano:S(e-r.durationMs),status:r.ok?{code:1}:{code:2,message:r.error?.message??""},traceId:r.traceId??$(16)};return r.traceFlags!==void 0&&(t.flags=r.traceFlags),r.error&&(t.events=[{attributes:[l("exception.type",r.error.code),l("exception.message",r.error.message)],name:"exception",timeUnixNano:S(e)}]),t},M=(r,e)=>{const o=new Map([[y.functionPath,l(y.functionPath,r.functionPath)]]);r.shardKey!==void 0&&o.set(y.shardKey,l(y.shardKey,r.shardKey)),r.userId!==void 0&&o.set(y.userId,l(y.userId,r.userId)),r.errorType!==void 0&&o.set(y.errorType,l(y.errorType,r.errorType));for(const[t,s]of Object.entries(e??{}))o.set(t,l(t,W(s)));return[...o.values()]},ur=r=>{const e={attributes:M({errorType:r.error?.type,functionPath:r.functionPath,shardKey:r.shardKey,userId:r.userId},r.attributes),endTimeUnixNano:S(r.startTs+r.durationMs),kind:V[r.kind??"internal"],name:r.name,parentSpanId:r.parentSpanId,spanId:r.spanId,startTimeUnixNano:S(r.startTs),status:r.ok?{code:1}:{code:2,message:r.error?.message??""},traceId:r.traceId},o=t=>v(Object.fromEntries(Object.entries(t??{}).map(([s,c])=>[s,W(c)])));return r.events!==void 0&&r.events.length>0&&(e.events=r.events.map(t=>({attributes:o(t.attributes),name:t.name,timeUnixNano:S(t.ts)}))),r.links!==void 0&&r.links.length>0&&(e.links=r.links.map(t=>({attributes:o(t.attributes),spanId:t.spanId,traceId:t.traceId}))),e},lr=r=>{const e=S(r.ts),o=M({functionPath:r.functionPath,shardKey:r.shardKey},r.attributes),t={asDouble:r.value,attributes:o,timeUnixNano:e};return r.kind==="gauge"?{gauge:{dataPoints:[t]},name:r.name}:r.kind==="histogram"?{histogram:{aggregationTemporality:1,dataPoints:[{attributes:o,bucketCounts:["1"],count:"1",explicitBounds:[],max:r.value,min:r.value,sum:r.value,timeUnixNano:e}]},name:r.name}:{name:r.name,sum:{aggregationTemporality:1,dataPoints:[t],isMonotonic:!0}}},pr=r=>{const e={attributes:M({functionPath:r.functionPath,shardKey:r.shardKey,userId:r.userId},r.fields),body:{stringValue:r.message},severityNumber:Q[r.level],severityText:r.level.toUpperCase(),timeUnixNano:S(r.ts)};return r.traceId!==void 0&&(e.traceId=r.traceId),r.spanId!==void 0&&(e.spanId=r.spanId),r.eventName!==void 0&&(e.eventName=r.eventName,e.attributes.push(l("event.name",r.eventName))),e},fr=1024,J=5;let R=0;const mr=(r,e)=>{if(R>=J)return;R+=1;let o;try{o=new URL(r).host}catch{o="<unparseable endpoint>"}const t=R===J?" Further OTLP rejections are silenced until the isolate restarts.":"";console.error(`[lunora:otlp] collector ${o} rejected the export with HTTP ${String(e)}; the batch is DROPPED (there is no retry).${t}`)},hr=async r=>{const e=new Blob([r]).stream().pipeThrough(new CompressionStream("gzip"));return new Response(e).arrayBuffer()},X=async(r,e,o,t)=>{try{const s=JSON.stringify(e),{byteLength:c}=new TextEncoder().encode(s),n=(c<fr?fetch(r,{body:s,headers:o,method:"POST"}):hr(s).then(a=>fetch(r,{body:a,headers:{...o,"content-encoding":"gzip"},method:"POST"}))).then(a=>{a.ok||mr(r,a.status)},()=>{});t?.(n),await n}catch{}},yr=(r,e,o,t)=>{X(r,e,o,t?.waitUntil).catch(()=>{})},O=(r,e)=>e===!0&&r.ok,gr=r=>r.kind==="metric"?void 0:r.event.traceId,br=r=>{const e=Map.groupBy(r,t=>gr(t)),o=e.get(void 0)??[];return e.delete(void 0),{byTrace:e,untraced:o}},C=5,kr=(r,e,o)=>{if(e===void 0)return r;const{byTrace:t,untraced:s}=br(r),c=[...s];let n=0,a;for(const[h,m]of t){let p;try{p=e({logs:m.filter(d=>d.kind==="log").map(d=>d.event),rpc:m.filter(d=>d.kind==="rpc").map(d=>d.event),spans:m.filter(d=>d.kind==="span").map(d=>d.event),traceId:h})}catch(d){n+=1,n===1&&(a=d),p=!0}p&&c.push(...m)}return n>0&&o(a,n),c},P=(r,e)=>{if(e===void 0)return r;try{return e(r)??void 0}catch{return}},Sr=r=>({...r,...r.fields===void 0?{}:{fields:j(r.fields)},message:j(r.message)}),H=(r,e,o)=>{if(r.kind==="rpc"){const s=P(r.event,e?.rpc);return s===void 0?void 0:{bucket:"spans",encoded:dr(s,r.endMs)}}if(r.kind==="span"){const s=P(r.event,e?.span);return s===void 0?void 0:{bucket:"spans",encoded:ur(s)}}if(r.kind==="log"){const s=P(o?Sr(r.event):r.event,e?.log);return s===void 0?void 0:{bucket:"logs",encoded:pr(s)}}const t=P(r.event,e?.metric);return t===void 0?void 0:{bucket:"metrics",encoded:lr(t)}},Ir=["fuseCloudflareTraces","instrumentDatabase","metricHistory","traceFetch"],Or=(r={})=>{const{onlyErrors:e}=r;return{onLog:o=>{o.level==="error"||o.level==="fatal"?console.error("[lunora:log]",o.functionPath,o.message):console.log("[lunora:log]",o.functionPath,o.message)},onMetric:o=>{console.log("[lunora:metric]",`${o.name}=${String(o.value)}`,o.kind,o.functionPath)},onRpc:o=>{O(o,e)||(o.ok?console.log("[lunora:rpc]",o):console.error("[lunora:rpc]",o))},onSpan:o=>{const t=o.ok?"ok":`error ${o.error?.type??""}`.trim();console.log("[lunora:span]",o.name,`${String(o.durationMs)}ms`,t,o.functionPath)}}},Nr=r=>{const{headers:e,onlyErrors:o,transform:t,transformLog:s,url:c}=r,n=z({"content-type":"application/json"},e),a=(h,m)=>{try{const p=fetch(c,{body:JSON.stringify(h),headers:n,method:"POST"}).catch(()=>{});m?.waitUntil&&m.waitUntil(p)}catch{}};return{onLog:(h,m)=>{const p=P(h,s);p!==void 0&&a(p,m)},onRpc:(h,m)=>{if(O(h,o))return;const p=P(h,t);p!==void 0&&a(p,m)}}},Er=r=>{const{capture:e,captureLog:o}=r;if(typeof e!="function")throw new TypeError("sentrySink requires a `capture` callback — wire your own Sentry client, e.g. `sentrySink({ capture: (event) => Sentry.captureMessage(event.name) })`. There is no `dsn` option; the runtime bundles no Sentry client.");const t=r.onlyErrors??!0;return{onLog:o?s=>{try{o(s)}catch{}}:void 0,onRpc:s=>{if(!O(s,t))try{e(s)}catch{}}}},Lr=r=>{const{dataset:e,onlyErrors:o}=r;return{onRpc:t=>{if(!O(t,o))try{e.writeDataPoint({blobs:[t.functionPath,t.ok?"ok":"error",t.shardKey??"",t.error?.code??"",t.fanOut?.table??""],doubles:[t.durationMs,t.ok?0:1,t.fanOut?.shards??0,t.fanOut?.failed??0],indexes:[t.functionPath]})}catch{}}}},Rr=r=>{const{pipeline:e,serializeFields:o}=r;return{onLog:(t,s)=>{try{const c={functionPath:t.functionPath,level:t.level,message:t.message,ts:t.ts};t.fields&&(c.fields=o===!0?JSON.stringify(t.fields):t.fields);for(const a of["shardKey","userId","traceId","spanId"])t[a]!==void 0&&(c[a]=t[a]);const n=e.send([c]).catch(()=>{});s?.waitUntil&&s.waitUntil(n)}catch{}}}},Ar=r=>{const{batch:e,deploymentEnvironment:o,detectResources:t,endpoint:s,headers:c,onlyErrors:n,postProcessor:a,resourceAttributes:h,serviceNamespace:m,serviceVersion:p,tailSampler:d,token:q}=r,x=r.serviceName??"lunora",U=r.redactLogs??!0;if(e!==!1&&e?.maxItems!==void 0&&(!Number.isInteger(e.maxItems)||e.maxItems<1))throw new Z("ENV_INVALID",`otlpSink: \`batch.maxItems\` must be a positive integer, received ${String(e.maxItems)}.`);const _={...p===void 0?{}:{"service.version":p},...m===void 0?{}:{"service.namespace":m},...o===void 0?{}:{"deployment.environment":o},...h},D=new WeakMap,k=u=>{if(t!==!0||u?.resourceAttributes===void 0)return _;const i=D.get(u);if(i!==void 0)return i;const f=er(u.resourceAttributes(),_);return D.set(u,f),f};let I=s;for(;I.endsWith("/");)I=I.slice(0,-1);const F={logs:{url:`${I}/v1/logs`,wrap:or},metrics:{url:`${I}/v1/metrics`,wrap:tr},spans:{url:`${I}/v1/traces`,wrap:rr}},K=z({"content-type":"application/json"},c,q);let L=0;const G=(u,i)=>{if(L>=C)return;L+=1;const f=L===C?" Further tailSampler failures from this sink are silenced until the isolate restarts.":"";console.error(`[lunora:otlp] tailSampler threw for ${String(i)} trace(s) in this flush window; keeping them (fail-open), so the sampling policy did NOT apply.${f}`,u)},Y=async u=>{const i=kr(u,d,G),f=new Map;for(const g of i){const b=H(g,a,U);if(b===void 0)continue;const E=A(g.resource);let T=f.get(E);T===void 0&&(T={logs:[],metrics:[],resource:g.resource,spans:[]},f.set(E,T)),T[b.bucket].push(b.encoded)}const w=[];for(const[,g]of f)for(const b of["spans","logs","metrics"])if(g[b].length>0){const{url:E,wrap:T}=F[b];w.push(X(E,T(g[b],"@lunora/runtime",x,g.resource),K))}await Promise.all(w)};if(e===!1){const u=(i,f)=>{const w=H(i,a,U);if(w!==void 0){const{url:g,wrap:b}=F[w.bucket];yr(g,b(w.encoded,"@lunora/runtime",x,i.resource),K,f)}};return{onLog:(i,f)=>{u({event:i,kind:"log",resource:k(f)},f)},onMetric:(i,f)=>{u({event:i,kind:"metric",resource:k(f)},f)},onRpc:(i,f)=>{O(i,n)||u({endMs:Date.now(),event:i,kind:"rpc",resource:k(f)},f)},onSpan:(i,f)=>{u({event:i,kind:"span",resource:k(f)},f)}}}const N=ar({export:Y,...e?.maxDelayMs===void 0?{}:{maxDelayMs:e.maxDelayMs},...e?.maxItems===void 0?{}:{maxItems:e.maxItems}});return{flush:u=>{N.flush(u?.waitUntil).catch(()=>{})},onLog:(u,i)=>{N.add({event:u,kind:"log",resource:k(i)},i?.waitUntil)},onMetric:(u,i)=>{N.add({event:u,kind:"metric",resource:k(i)},i?.waitUntil)},onRpc:(u,i)=>{O(u,n)||N.add({endMs:Date.now(),event:u,kind:"rpc",resource:k(i)},i?.waitUntil)},onSpan:(u,i)=>{N.add({event:u,kind:"span",resource:k(i)},i?.waitUntil)}}},Mr=(...r)=>{const e=(t,s)=>{for(const c of r){const n=c[t];if(n)try{n.apply(c,s)}catch{}}},o={};for(const t of r)for(const s of Ir)o[s]===void 0&&t[s]!==void 0&&(o[s]=t[s]);return{...o,flush:t=>{e("flush",[t])},onLog:(t,s)=>{e("onLog",[t,s])},onMetric:(t,s)=>{e("onMetric",[t,s])},onRpc:(t,s)=>{e("onRpc",[t,s])},onSpan:(t,s)=>{e("onSpan",[t,s])}}};export{Lr as analyticsEngineSink,Mr as combineSinks,Or as consoleSink,Ar as otlpSink,Rr as pipelineLogSink,Er as sentrySink,Nr as webhookSink};
@@ -1 +1 @@
1
- import"./rest-cache-D1BlbZb1.mjs";import{a,b as o,c as i,r as m}from"./rest-routes-BbMQwlSV.mjs";import"./method-guard-BG_vJNTl.mjs";export{a as argsFromQuery,o as buildRestRoutes,i as createRestRateLimit,m as restSurfaceFromRegistry};
1
+ import"./rest-cache-D1BlbZb1.mjs";import{a,b as o,c as i,r as m}from"./rest-routes-CyXGd_yB.mjs";import"./method-guard-BG_vJNTl.mjs";export{a as argsFromQuery,o as buildRestRoutes,i as createRestRateLimit,m as restSurfaceFromRegistry};
@@ -0,0 +1,6 @@
1
+ import{isLunoraError as Ln,toErrorBody as Mn}from"@lunora/errors";import{e as Mt}from"./evict-oldest-BNXsKx4s.mjs";import{NOOP_EXECUTION_CONTEXT as jn}from"./NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{t as $n,f as Kn}from"./base64-Bl1_r2k1.mjs";import{e as Fn,a as Gn}from"./identity-header-C4Z5pldl.mjs";import{o as Ie,b as jt,p as Qn,m as zn,d as Wn,a as Vn,r as Jn}from"./otlp-resource-JKBCWf6c.mjs";import{e as ke,d as Ve,a as qn}from"./wire-codec-BLvSm5Mn.mjs";import{d as te,e as he,M as $t,b as Yn,f as Xn,g as Kt,t as Zn,h as Ft}from"./rest-routes-CyXGd_yB.mjs";import{LunoraError as c,toErrorResponse as dt}from"./LunoraError-DksAgIpa.mjs";import{a as j,m as we}from"./method-guard-BG_vJNTl.mjs";import{normalizeBackupPrefix as Xe,BACKUP_KEY_PREFIX as Ze,isBackupManifestKey as er,backupObjectKeyOfManifest as Gt,backupObjectKey as tr,backupManifestKey as nr}from"./BACKUP_KEY_PREFIX-BOtSu-_3.mjs";import{toHex as rr,buildStorageAdminRoutes as or,STORAGE_UPLOAD_MAX_BODY_BYTES as ar,STORAGE_PATH as sr}from"./STORAGE_UPLOAD_MAX_BODY_BYTES-BqyO-1l6.mjs";import{b as ir,e as cr,f as ut,g as dr,h as ur}from"./export-tap-CAyZ2TWC.mjs";import{buildHealthRoutes as lr,durableObjectProbe as hr,d1Probe as fr,presenceProbe as Le}from"./HEALTH_PATH-D0i8LhwT.mjs";import{wrapResolverWithContract as pr}from"./composeIdentityResolvers-BHZ4jH8o.mjs";import{composeIdentityResolvers as Ms,routeIdentityResolvers as js}from"./composeIdentityResolvers-BHZ4jH8o.mjs";import{buildLogArchiveAdminRoutes as mr}from"./LOG_ARCHIVE_PATH-Hmjpz_Ko.mjs";import{r as wr,f as lt,a as ce}from"./observability-B1hLjwgx.mjs";import{resolveShard as ge,applyJurisdiction as ht}from"./applyJurisdiction-C0ddU7Tg.mjs";import{resolveSecurity as ft,handleCorsPreflight as gr,enforceOrigin as yr,decorateResponse as Me,enforceWebSocketOrigin as pt}from"./decorateResponse-Y2sCM0w1.mjs";const br=e=>{const t=e??{};if(typeof t.bucket=="function")return t;const n=t.bucketName,a={...t,bucketName:typeof n=="string"&&n!==""?n:"default"};return a.bucket=()=>a,a},Qt="__lunoraBranch",_r=e=>typeof e=="object"&&e!==null&&Object.hasOwn(e,Qt),Rr=`may not contain the reserved workflow branch-marker key ("${Qt}")`,Er=async e=>{const t=[];let n;for(;;){const r=await e(n);if(t.push(...Array.isArray(r.records)?r.records:[]),r.truncated!==!0||typeof r.cursor!="string"||r.cursor.length===0)return t;if(r.cursor===n)throw new Error("collectPages: the list did not advance its cursor — refusing to page forever");n=r.cursor}},et=(e,t)=>{const n=Math.max(e.length,t.length);let r=e.length^t.length;for(let a=0;a<n;a+=1){const i=a<e.length?e.charCodeAt(a):0,u=a<t.length?t.charCodeAt(a):0;r|=i^u}return r===0},Sr=/already[\s_-]?exists/iu,Ar=e=>Sr.test(e instanceof Error?e.message:String(e)),Tr=(e,t,n,r)=>{const a=e.get(t);if(a!==void 0)return a;Mt(e,r);const i=n().catch(u=>{throw e.get(t)===i&&e.delete(t),u});return e.set(t,i),i},tt=new TextEncoder,Or=Array.from({length:32},(e,t)=>t);new RegExp(`[${Or.map(e=>String.fromCodePoint(e)).join("")}]`,"u");const vr=64,kr=new Map,zt=async e=>Tr(kr,e,async()=>crypto.subtle.importKey("raw",tt.encode(e),{hash:"SHA-256",name:"HMAC"},!1,["sign","verify"]),vr),Wt=async(e,t)=>{const n=await zt(e),r=await crypto.subtle.sign("HMAC",n,tt.encode(t));return $n(new Uint8Array(r))},Ir=async(e,t,n)=>{const r=await zt(e);return crypto.subtle.verify("HMAC",r,n,tt.encode(t))},Pr=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"];new Set(Pr);const Nr=new Set(["AE","BH","IL","IQ","IR","JO","KW","LB","OM","PS","QA","SA","SY","TR","YE"]),Dr=-100,Ur=15,Cr=e=>{const t=Number(e.longitude??Number.NaN);switch(e.continent){case"AF":return"afr";case"AS":return e.country!==void 0&&Nr.has(e.country)?"me":"apac";case"EU":return Number.isFinite(t)&&t>Ur?"eeur":"weur";case"NA":return Number.isFinite(t)&&t<Dr?"wnam":"enam";case"OC":return"oc";case"SA":return"sam";default:return}},mt=e=>{const t=e.cf;return t===void 0?void 0:Cr(t)},Je="::relay::",Br=(e,t)=>`${e}${Je}${String(t)}`,qe="::replica::",xr=(e,t)=>`${e}${qe}${t}`,Hr=e=>{if(e==null||!/^\d+$/.test(e))return;const t=Number.parseInt(e,10);return Number.isSafeInteger(t)&&t>0?t:void 0},Lr=new Set(["1","enabled","on","true","yes"]),Mr=new Set(["0","disabled","false","no","off"]),jr=(e,t)=>{const n=(e??"").trim().toLowerCase();return Lr.has(n)?!0:Mr.has(n)?!1:t},Vt="v1",$r=6e4,Kr=async(e,t={})=>{const n=(t.now??Date.now())+(t.ttlMs??$r),r=`${Vt}.${String(n)}`,a=await Wt(e,r);return{expiresAtMs:n,token:`${r}.${a}`}},Fr=async(e,t,n=Date.now())=>{if(e.length===0||t.length===0)return!1;const r=t.split(".");if(r.length!==3)return!1;const[a,i,u]=r;if(a!==Vt||u.length===0)return!1;const h=Number(i);if(!Number.isFinite(h)||h<=n)return!1;let p;try{p=Kn(u)}catch{return!1}return Ir(e,`${a}.${i}`,p)},P="/_lunora/admin/auth",Gr={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},D=(e,t)=>{const n=e[t];if(typeof n!="string"||n==="")throw new c(`\`${t}\` is required`,{code:"BAD_REQUEST",status:400});return n},le=(e,t)=>{const n=e(t);if(n===void 0)throw new c(`\`${t}\` query parameter is required`,{code:"BAD_REQUEST",status:400});return n},Jt=e=>{if(typeof e=="string"||Array.isArray(e)&&e.every(t=>typeof t=="string"))return e},re=(e,t)=>typeof e[t]=="string"?e[t]:void 0,je=(e,t)=>{const n=e[t];return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:void 0},wt=e=>{const t=Jt(e.role);if(t===void 0||typeof t=="string"&&t.trim()==="")throw new c("`role` is required",{code:"BAD_REQUEST",status:400});return t},gt=e=>{const t=e.permission;if(typeof t!="object"||t===null||Array.isArray(t))throw new c("`permission` object is required",{code:"BAD_REQUEST",status:400});const n={};for(const[r,a]of Object.entries(t))Array.isArray(a)&&a.every(i=>typeof i=="string")&&(n[r]=a);return n},Qr={[`${P}/capabilities`]:{build:()=>({}),http:"GET",method:"capabilities"},[`${P}/users`]:{build:({paging:e,query:t})=>{const n=t("sortDirection");return{...e,filterField:t("filterField"),filterValue:t("filterValue"),search:t("search"),searchField:t("searchField"),sortBy:t("sortBy"),sortDirection:n==="asc"||n==="desc"?n:void 0}},http:"GET",method:"listUsers"},[`${P}/sessions`]:{build:({paging:e,query:t})=>({...e,userId:t("userId")}),http:"GET",method:"listSessions"},[`${P}/accounts`]:{build:({query:e})=>({userId:le(e,"userId")}),http:"GET",method:"listAccounts"},[`${P}/passkeys`]:{build:({query:e})=>({userId:le(e,"userId")}),http:"GET",method:"listPasskeys"},[`${P}/organizations`]:{build:({paging:e})=>({...e}),http:"GET",method:"listOrganizations"},[`${P}/organizations/members`]:{build:({paging:e,query:t})=>({...e,organizationId:le(t,"organizationId")}),http:"GET",method:"listMembers"},[`${P}/organizations/invitations`]:{build:({paging:e,query:t})=>({...e,organizationId:le(t,"organizationId")}),http:"GET",method:"listInvitations"},[`${P}/sign-up-invitations`]:{build:({paging:e})=>({...e}),http:"GET",method:"listSignUpInvitations"},[`${P}/sign-up-invitations/create`]:{build:({body:e})=>({email:D(e,"email"),expiresInSeconds:typeof e.expiresInSeconds=="number"?e.expiresInSeconds:void 0,invitedBy:re(e,"invitedBy")}),http:"POST",method:"createSignUpInvitation"},[`${P}/sign-up-invitations/revoke`]:{build:({body:e})=>({email:D(e,"email")}),http:"POST",method:"revokeSignUpInvitation",returns:"void"},[`${P}/config`]:{build:()=>({}),http:"GET",method:"config"},[`${P}/organizations/teams`]:{build:({paging:e,query:t})=>({...e,organizationId:le(t,"organizationId")}),http:"GET",method:"listTeams"},[`${P}/organizations/teams/members`]:{build:({paging:e,query:t})=>({...e,teamId:le(t,"teamId")}),http:"GET",method:"listTeamMembers"},[`${P}/organizations/roles`]:{build:({paging:e,query:t})=>({...e,organizationId:le(t,"organizationId")}),http:"GET",method:"listOrgRoles"},[`${P}/users/create`]:{build:({body:e})=>({data:je(e,"data"),email:D(e,"email"),name:D(e,"name"),password:re(e,"password"),role:Jt(e.role)}),http:"POST",method:"createUser"},[`${P}/users/update`]:{build:({body:e})=>{const{data:t}=e;if(typeof t!="object"||t===null||Array.isArray(t))throw new c("`data` object is required",{code:"BAD_REQUEST",status:400});return{data:t,userId:D(e,"userId")}},http:"POST",method:"updateUser"},[`${P}/users/role`]:{build:({body:e})=>({role:wt(e),userId:D(e,"userId")}),http:"POST",method:"setRole"},[`${P}/users/ban`]:{build:({body:e})=>({expiresInSeconds:typeof e.expiresInSeconds=="number"?e.expiresInSeconds:void 0,reason:re(e,"reason"),userId:D(e,"userId")}),http:"POST",method:"banUser"},[`${P}/users/unban`]:{build:({body:e})=>({userId:D(e,"userId")}),http:"POST",method:"unbanUser"},[`${P}/users/password`]:{build:({body:e})=>({newPassword:D(e,"newPassword"),userId:D(e,"userId")}),http:"POST",method:"setUserPassword",returns:"void"},[`${P}/users/remove`]:{build:({body:e})=>({userId:D(e,"userId")}),http:"POST",method:"removeUser",returns:"void"},[`${P}/users/impersonate`]:{build:({body:e})=>({userId:D(e,"userId")}),http:"POST",method:"impersonateUser"},[`${P}/sessions/revoke`]:{build:({body:e})=>({sessionId:D(e,"sessionId")}),http:"POST",method:"revokeUserSession",returns:"void"},[`${P}/sessions/revoke-all`]:{build:({body:e})=>({userId:D(e,"userId")}),http:"POST",method:"revokeUserSessions",returns:"void"},[`${P}/accounts/unlink`]:{build:({body:e})=>({accountId:D(e,"accountId"),userId:D(e,"userId")}),http:"POST",method:"unlinkAccount",returns:"void"},[`${P}/two-factor/disable`]:{build:({body:e})=>({userId:D(e,"userId")}),http:"POST",method:"disableTwoFactor",returns:"void"},[`${P}/passkeys/delete`]:{build:({body:e})=>({passkeyId:D(e,"passkeyId")}),http:"POST",method:"deletePasskey",returns:"void"},[`${P}/organizations/members/remove`]:{build:({body:e})=>({memberId:D(e,"memberId")}),http:"POST",method:"removeMember",returns:"void"},[`${P}/organizations/invitations/cancel`]:{build:({body:e})=>({invitationId:D(e,"invitationId")}),http:"POST",method:"cancelInvitation",returns:"void"},[`${P}/organizations/create`]:{build:({body:e})=>({logo:re(e,"logo"),metadata:je(e,"metadata"),name:D(e,"name"),ownerId:re(e,"ownerId"),slug:re(e,"slug")}),http:"POST",method:"createOrganization"},[`${P}/organizations/update`]:{build:({body:e})=>({logo:re(e,"logo"),metadata:je(e,"metadata"),name:re(e,"name"),organizationId:D(e,"organizationId"),slug:re(e,"slug")}),http:"POST",method:"updateOrganization"},[`${P}/organizations/remove`]:{build:({body:e})=>({organizationId:D(e,"organizationId")}),http:"POST",method:"deleteOrganization",returns:"void"},[`${P}/organizations/members/add`]:{build:({body:e})=>({organizationId:D(e,"organizationId"),role:re(e,"role"),userId:D(e,"userId")}),http:"POST",method:"addMember"},[`${P}/organizations/members/invite`]:{build:({body:e})=>({email:D(e,"email"),inviterId:re(e,"inviterId"),organizationId:D(e,"organizationId"),role:re(e,"role")}),http:"POST",method:"inviteMember"},[`${P}/organizations/members/role`]:{build:({body:e})=>({memberId:D(e,"memberId"),role:wt(e)}),http:"POST",method:"updateMemberRole"},[`${P}/organizations/teams/create`]:{build:({body:e})=>({name:D(e,"name"),organizationId:D(e,"organizationId")}),http:"POST",method:"createTeam"},[`${P}/organizations/teams/update`]:{build:({body:e})=>({name:D(e,"name"),teamId:D(e,"teamId")}),http:"POST",method:"updateTeam"},[`${P}/organizations/teams/remove`]:{build:({body:e})=>({teamId:D(e,"teamId")}),http:"POST",method:"removeTeam",returns:"void"},[`${P}/organizations/teams/members/add`]:{build:({body:e})=>({teamId:D(e,"teamId"),userId:D(e,"userId")}),http:"POST",method:"addTeamMember"},[`${P}/organizations/teams/members/remove`]:{build:({body:e})=>({teamMemberId:D(e,"teamMemberId")}),http:"POST",method:"removeTeamMember",returns:"void"},[`${P}/organizations/roles/create`]:{build:({body:e})=>({organizationId:D(e,"organizationId"),permission:gt(e),role:D(e,"role")}),http:"POST",method:"createOrgRole"},[`${P}/organizations/roles/update`]:{build:({body:e})=>({permission:gt(e),roleId:D(e,"roleId")}),http:"POST",method:"updateOrgRole"},[`${P}/organizations/roles/remove`]:{build:({body:e})=>({roleId:D(e,"roleId")}),http:"POST",method:"deleteOrgRole",returns:"void"}},zr=e=>{const t=async a=>{try{return await a()}catch(i){if(i instanceof c)throw i;const u=i,h=typeof u.code=="string"?u.code:"AUTH_ADMIN_ERROR";throw console.error("[lunora] auth admin operation failed:",i),new c("auth admin operation failed",{code:h,status:Gr[h]??500})}},n=async(a,i)=>{if(e.assertAdmin(a),a.method!==i.http)throw new c(`Auth admin endpoint requires ${i.http}`,{code:"METHOD_NOT_ALLOWED",status:405});const u=e.getAuthAdmin();if(u===void 0)throw new c("auth endpoints require an `authAdmin` on the worker",{code:"AUTH_NOT_CONFIGURED",status:400});const h=u[i.method];if(h===void 0)throw new c(`auth admin does not support \`${i.method}\``,{code:"AUTH_OP_NOT_SUPPORTED",status:400});const p=new URL(a.url),w={body:i.http==="POST"?await e.readJsonBody(a):{},paging:e.parsePaging(a),query:T=>e.queryParameter(p,T)},S=i.build(w),A=await t(()=>h(S));return Response.json(i.returns==="void"?{ok:!0}:A,{headers:{"cache-control":"no-store","content-type":"application/json"},status:200})},r={};for(const[a,i]of Object.entries(Qr))r[a]=u=>n(u,i);return r},yt="__lunora_admin__:getAuthAuditLog",bt=e=>typeof e=="string"&&e!==""?e:void 0,_t=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0,Wr=e=>async(n,r)=>{e.assertAdmin(n);const a=e.getReader();if(a===void 0)throw new c("the auth/security audit endpoint requires an `authAuditReader` on the worker",{code:"AUTH_AUDIT_NOT_CONFIGURED",status:400});const i=bt(r.actorId),u=bt(r.event),h=_t(r.sinceSeq),p=_t(r.limit),w={...i===void 0?{}:{actorId:i},...u===void 0?{}:{event:u},...h===void 0?{}:{sinceSeq:h},...p===void 0?{}:{limit:p}};let S;try{S=await a.read(w)}catch(T){throw T instanceof c?T:(console.error("[lunora] auth audit read failed:",T),new c("auth audit read failed",{code:"AUTH_AUDIT_READ_FAILED",status:500}))}const A={entries:S};return Response.json({result:ke(A)},{headers:{"content-type":"application/json"},status:200})},Vr=(e,t)=>{const n=[],r=[];if(t&&t.length>0)for(const a of t)e.resolveTableSharding?.(a)?.mode.kind==="global"?r.push(a):n.push(a);return{globalTables:r,shardLocalTables:n}},Jr=async(e,t,n,r,a,i,u)=>{if(n!==void 0&&r.length===0)return;const h=await e.orchestrateExport(i,{args:{tables:r},defaultShardKey:u,headers:t,tables:r});for(const p of h.shards)if(!p.error)for(const w of p.rows??[])a(w)},qt=async(e,t,n,r,a,i)=>{const u=r??e.listSchemaTables?.();r===void 0&&e.listSchemaTables===void 0&&console.warn("[lunora] export: no table list available (`listSchemaTables` is unset and no `tables` were named), so only the default shard is reachable. A `.shardBy()` deployment's other shards will be missing from this export. Name the tables explicitly, or regenerate the worker so codegen supplies the list.");const{globalTables:h,shardLocalTables:p}=Vr(e,u);await Jr(t,n,u,p,a,i,e.defaultShardKey??"__root__");const w=e.exportGlobals;if((r===void 0||h.length>0)&&w)for await(const A of w({tables:h}))a(A)},qr=new TextEncoder,Yr=1e3,Yt=10,Xr=200,Rt=8,Xt="lunoraBackupCron",Et=24*1048576,St=e=>{const t=e.slice(0,Yt).map(r=>Gt(r)),n=e.length-t.length;return`${t.join(", ")}${n>0?` (+${String(n)} more)`:""}`},Zr=(e,t)=>{const n=new Uint8Array(new ArrayBuffer(t));let r=0;for(const a of e)n.set(a,r),r+=a.byteLength;return n},nt=async(e,t,n,r)=>{if(n===void 0||!Number.isInteger(n)||n<=0)return{eligible:0,stale:[]};const a=[];let i;for(let u=0;u<Yr;u+=1){const h=await e.list({cursor:i,include:["customMetadata"],prefix:t});for(const p of h.objects)er(p.key)&&p.customMetadata?.[Xt]===r&&a.push(p.key);if(!h.truncated||h.cursor===void 0)break;i=h.cursor}return{eligible:a.length,stale:a.toSorted((u,h)=>h.localeCompare(u)).slice(n)}},eo=async(e,t,n,r,a)=>{const{stale:i}=await nt(e,t,n,r),u=new Set(a),h=i.filter(y=>u.has(y)),p=h.slice(0,Xr),w=i.length-p.length,S=a.length-h.length;if(p.length===0)return{deleted:[],failed:[],ignored:S,remaining:w};const A=[],T=[];for(let y=0;y<p.length;y+=Rt){const _=await Promise.allSettled(p.slice(y,y+Rt).map(async R=>(await e.delete(Gt(R)),await e.delete(R),R)));for(const[R,f]of _.entries())f.status==="fulfilled"?A.push(f.value):T.push(p[y+R])}return A.length>0&&console.info(`[lunora] backup prune kept the newest ${String(n)} and deleted ${String(A.length)}: ${St(A)}`),T.length>0&&console.warn(`[lunora] backup prune failed to remove ${String(T.length)}: ${St(T)}`),{deleted:A,failed:T,ignored:S,remaining:w}},to=async e=>{const t=e.backupStore;if(!t)throw new c("backup retention preview requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});const n=Xe(e.backupPrefix??Ze),r=e.backupCron,{eligible:a,stale:i}=r===void 0?{eligible:0,stale:[]}:await nt(t,n,e.backupRetain,r);return{cron:r,eligible:a,keep:e.backupRetain??0,prefix:n,wouldDelete:i}},no=async(e,t,n,r)=>{const a=e.backupStore,i=e.queryCoordinator;if(!a)throw new c("scheduled backup requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});if(!i)throw new c("scheduled backup requires a `queryCoordinator` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});if(!n||n.length===0)throw new c("scheduled backup requires an `adminToken` (or `env.LUNORA_ADMIN_TOKEN`) to authenticate the per-shard export gate",{code:"BACKUP_NOT_CONFIGURED",status:500});const u={authorization:`Bearer ${n}`,"content-type":"application/json"},h=e.backupTables;let p=0,w=0,S=[];await qt(e,i,u,h,U=>{const M=qr.encode(`${JSON.stringify(U)}
2
+ `);if(p+=1,w+=M.byteLength,w>Et)throw new c(`scheduled backup reached ${String(w)} bytes of NDJSON, past the ${String(Et)}-byte limit for a snapshot assembled inside a Worker — nothing was written. Narrow it with \`backupTables\`, or take this snapshot off-platform with \`lunora backup create --bucket\`.`,{code:"BACKUP_TOO_LARGE",status:507});S.push(M)},t);const T=Xe(e.backupPrefix??Ze),y=new Date(r.scheduledTime).toISOString(),_=tr(T,y),R=Zr(S,w);S=[];const f=rr(await crypto.subtle.digest("SHA-256",R));await a.put(_,R,{httpMetadata:{contentType:"application/x-ndjson"},sha256:f});const v={bytes:w,createdAt:y,cron:r.cron,file:_,id:y,rows:p,scheduledTime:r.scheduledTime,sha256:f,...h?{tables:h.join(",")}:{}};await a.put(nr(_),`${JSON.stringify(v,void 0,2)}
3
+ `,{customMetadata:{[Xt]:r.cron},httpMetadata:{contentType:"application/json"}});try{const{stale:U}=await nt(a,T,e.backupRetain,r.cron);if(U.length>0){const M=U.slice(0,Yt),N=U.length-M.length;console.info(`[lunora] backup retention: ${String(U.length)} snapshot(s) past the newest ${String(e.backupRetain)} — run \`lunora backup prune\` to remove them: ${M.join(", ")}${N>0?` (+${String(N)} more)`:""}`)}}catch(U){console.warn(`[lunora] backup ${_} was written, but the retention report failed:`,U)}},ro=async(e,t)=>{const n=e.backupStore;if(!n)throw new c("backup prune requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});const r=e.backupCron,a=e.backupRetain;if(r===void 0||a===void 0||!Number.isInteger(a)||a<=0)throw new c("backup prune needs a retention window: set `backupRetain` (and `backupCron`, which decides whose snapshots retention owns) on the worker. Without one there is nothing past the window to remove.",{code:"BACKUP_RETENTION_NOT_CONFIGURED",status:400});return eo(n,Xe(e.backupPrefix??Ze),a,r,t)},oo="/_lunora/admin/backup/retention",ao="/_lunora/admin/backup/prune",so=e=>{const{options:t,readJsonBody:n,requireAdminOption:r}=e,a=(h,p)=>{r(h,t.backupStore,{code:"BACKUP_NOT_CONFIGURED",message:`backup ${p} requires a \`backupStore\` on the worker`})},i=async h=>(j(h,"GET","Backup-retention"),a(h,"retention preview"),Response.json(await to(t),{headers:{"cache-control":"no-store"}})),u=async h=>{j(h,"POST","Backup-prune"),a(h,"prune");const{confirm:p}=await n(h);if(!Array.isArray(p)||p.some(w=>typeof w!="string"))throw new c("backup prune requires a `confirm` array of the sidecar keys to remove — read them from `GET /_lunora/admin/backup/retention` and pass back the ones you mean to delete",{code:"BAD_REQUEST",status:400});return Response.json(await ro(t,p),{headers:{"cache-control":"no-store"}})};return{[ao]:u,[oo]:i}},At=500,io=(e,t,n)=>{if(typeof e!="object"||e===null||Array.isArray(e))throw new c("each batch call must be an object",{code:"BAD_REQUEST",status:400});const r=e;if(typeof r.functionPath!="string")throw new c("each batch call needs a string `functionPath`",{code:"BAD_REQUEST",status:400});if(r.functionPath.startsWith("__lunora_relation__:")||r.functionPath.startsWith("__lunora_admin__"))throw new c("reserved function path cannot be batched",{code:"FORBIDDEN",status:403});if(r.args!==void 0&&(typeof r.args!="object"||r.args===null||Array.isArray(r.args)))throw new c("each batch call `args` must be an object",{code:"BAD_REQUEST",status:400});return{entry:{args:r.args===void 0?{}:r.args,clientId:typeof r.clientId=="string"?r.clientId:void 0,clientSeq:typeof r.clientSeq=="number"?r.clientSeq:void 0,functionPath:r.functionPath,id:typeof r.id=="number"?r.id:t,mutationId:typeof r.mutationId=="string"?r.mutationId:void 0},shardKey:typeof r.shardKey=="string"?r.shardKey:n}},co=(e,t)=>{if(e.length>At)throw new c(`RPC batch exceeds the ${String(At)}-call limit`,{code:"BAD_REQUEST",status:400});const n=new Map;for(const[r,a]of e.entries()){const{entry:i,shardKey:u}=io(a,r,t),h=n.get(u)??[];h.push(i),n.set(u,h)}return n},uo="/_lunora/admin/export",lo="/_lunora/admin/import",ho="/_lunora/admin/sync",fo="/_lunora/admin/connector/sync",po="/_lunora/admin/apply",mo="/_lunora/admin/export-tap/run",wo=new TextEncoder,go=async e=>{const n=await he(e,"Export")??{};if(n.tables===void 0)return{tables:void 0};if(!Array.isArray(n.tables))throw new c("Export `tables` must be a string array",{code:"BAD_REQUEST",status:400});const r=[];for(const a of n.tables){if(typeof a!="string"||a.length===0)throw new c("Export `tables` entries must be non-empty strings",{code:"BAD_REQUEST",status:400});r.push(a)}return{tables:r}},$e=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):void 0,yo=e=>{const{applyGlobals:t,defaultShardKey:n,exportCursorStore:r,exportSinks:a,knownTables:i,queryCoordinator:u,assertAdmin:h,requireAdminOption:p,resolveForwardContext:w,shardDO:S,streamExportRows:A,streamingImport:T,syncGlobals:y}=e,_=async(N,K)=>{const $=we(N,["POST"]);if($)return $;const V=p(N,u,{code:"BAD_REQUEST",message:"Export endpoint requires a `queryCoordinator` on the worker"}),B=await go(N),{headers:J}=await w(N,K),F=new ReadableStream({async pull(q){const ee=L=>{q.enqueue(wo.encode(`${JSON.stringify(L)}
4
+ `))};try{await A(V,J,B.tables,ee),q.close()}catch(L){q.error(L)}}});return new Response(F,{headers:{"content-type":"application/x-ndjson"},status:200})},R=async(N,K)=>{const $=we(N,["POST"]);if($)return $;const V=p(N,u,{code:"BAD_REQUEST",message:"Sync endpoint requires a `queryCoordinator` on the worker"}),B=await te(N),J=typeof B.cursors=="object"&&B.cursors!==null?B.cursors:{},F=typeof B.limit=="number"?B.limit:void 0,q=typeof B.globalCursor=="number"?B.globalCursor:0,ee=$e(B.tables),{headers:L}=await w(N,K),Y=ee??i(),G=await V.orchestrateCdcSync(S,{cursors:J,defaultShardKey:n,headers:L,limit:F,tables:Y}),fe=y?await y({limit:F,sinceSeq:q}):void 0;return Response.json({global:fe,shards:G.shards},{status:200})},f=async(N,K)=>{const $=we(N,["POST"]);if($)return $;const V=p(N,u,{code:"BAD_REQUEST",message:"Connector sync endpoint requires a `queryCoordinator` on the worker"}),B=await te(N),J=cr(B.cursor),F=typeof B.limit=="number"&&B.limit>0?B.limit:void 0,q=$e(B.tables),{headers:ee}=await w(N,K),L=q??i(),Y=await V.orchestrateCdcSync(S,{cursors:J.s,defaultShardKey:n,headers:ee,limit:F,tables:L}),G=[],fe={...J.s};let ae=!1;for(const se of Y.shards)ae=ut(G,se.changes??[],ur(F))||ae,fe[se.shardKey]=se.cursor;let _e=J.g;if(y){const se=await y({limit:F,sinceSeq:J.g});ae=ut(G,se.changes,F)||ae,_e=se.cursor}const Pe=dr({g:_e,s:fe,v:1}),Ne={changes:G,hasMore:ae,nextCursor:Pe};return Response.json(Ne,{status:200})},v=async(N,K)=>{const $=we(N,["POST"]);if($)return $;const V=p(N,u,{code:"BAD_REQUEST",message:"Apply endpoint requires a `queryCoordinator` on the worker"}),B=await te(N),F=(Array.isArray(B.batches)?B.batches:[]).map(G=>G).filter(G=>G!==null&&typeof G=="object"&&typeof G.shardKey=="string"&&Array.isArray(G.changes)),q=Array.isArray(B.globalChanges)?B.globalChanges:[],{headers:ee}=await w(N,K),L=await V.orchestrateApplyCdc(S,{batches:F,headers:ee}),Y=q.length>0&&t?await t({changes:q}):0;return Response.json({applied:L.applied+Y,failed:L.failed,ok:L.ok},{status:200})},U=async(N,K)=>{const $=we(N,["POST"]);if($)return $;h(N);const{headers:V}=await w(N,K),B=await T(N,V);return Response.json(B,{headers:{"content-type":"application/json"},status:B.failed.length>0?207:200})},M=async(N,K)=>{const $=we(N,["POST"]);if($)return $;const V=p(N,u,{code:"BAD_REQUEST",message:"Export-tap endpoint requires a `queryCoordinator` on the worker"});if(a===void 0||Object.keys(a).length===0||r===void 0)throw new c("Export-tap endpoint requires `exportSinks` + `exportCursorStore` on the worker",{code:"EXPORT_TAP_NOT_CONFIGURED",status:400});const B=await te(N),J=typeof B.sink=="string"?B.sink:void 0,F=typeof B.limit=="number"&&B.limit>0?B.limit:void 0,q=$e(B.tables);if(J===void 0)throw new c("Export-tap `sink` must name a configured sink",{code:"BAD_REQUEST",status:400});const ee=a[J];if(ee===void 0)throw new c(`Export-tap sink "${J}" is not configured`,{code:"NOT_FOUND",status:404});const{headers:L}=await w(N,K),Y=q??i(),G=await ir({coordinator:V,cursorStore:r,defaultShardKey:n,headers:L,limit:F,shardDO:S,sink:ee,tables:Y});return Response.json(G,{headers:{"content-type":"application/json"},status:200})};return{[po]:v,[fo]:f,[uo]:_,[mo]:M,[lo]:U,[ho]:R}},bo=(e,t)=>{let n;try{n=JSON.parse(e)}catch{return{error:{code:"BAD_ROW",line:t,message:"line is not valid JSON",table:""},ok:!1}}if(!n||typeof n!="object"||Array.isArray(n))return{error:{code:"BAD_ROW",line:t,message:"row must be a JSON object",table:""},ok:!1};const r=n;return typeof r.table!="string"||r.table.length===0?{error:{code:"BAD_ROW",line:t,message:"row is missing `table`",table:""},ok:!1}:!r.doc||typeof r.doc!="object"||Array.isArray(r.doc)?{error:{code:"BAD_ROW",line:t,message:"row is missing or malformed `doc`",table:r.table},ok:!1}:{doc:r.doc,ok:!0,table:r.table}},_o=(e,t,n,r,a)=>{if(n?.mode.kind==="shardBy"&&typeof n.mode.field=="string"){const i=e[n.mode.field];return i==null?{error:{code:"BAD_ROW",line:a,message:`row missing shard field "${n.mode.field}" for table "${t}"`,table:t},ok:!1}:{ok:!0,shardKey:typeof i=="string"?i:JSON.stringify(i)}}return{ok:!0,shardKey:r}},Ro=async(e,t,n)=>{if(!e.body)throw new c("Import endpoint requires a request body",{code:"BAD_REQUEST",status:400});const r=[],a=[],i=new Map;let u=0,h=0;const p=e.body.getReader(),w=new TextDecoder;let S="",A=0;const T=y=>{h+=1;const _=y.trim();if(_.length===0)return;u+=1;const R=bo(_,h);if(!R.ok){r.push(R.error);return}const{doc:f,table:v}=R,U=t.resolveTableSharding?.(v);if(U?.mode.kind==="global"){a.push({doc:f,line:h,table:v});return}const M=_o(f,v,U,n,h);if(!M.ok){r.push(M.error);return}const N=i.get(M.shardKey);N?N.rows.push({doc:f,table:v}):i.set(M.shardKey,{rows:[{doc:f,table:v}],shardKey:M.shardKey,startLine:h})};for(;;){const{done:y,value:_}=await p.read();if(y)break;if(_&&(A+=_.byteLength,A>$t))throw await p.cancel().catch(()=>{}),new c("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});S+=w.decode(_,{stream:!0});let R=S.indexOf(`
5
+ `);for(;R!==-1;){const f=S.slice(0,R);S=S.slice(R+1),T(f),R=S.indexOf(`
6
+ `)}}return S.length>0&&T(S),{errors:r,globalRows:a,perShard:i,received:u}},Eo=e=>e.flatMap(t=>t.error?[{message:t.error.message,shardKey:t.shardKey,timedOut:t.error.timedOut}]:[]),Tt=(e,t)=>{for(const[n,r]of Object.entries(t.inserted))e.inserted[n]=(e.inserted[n]??0)+r;for(const n of t.errors)e.errors.push({...n});e.conflicts+=t.conflicts},So=async(e,t,n,r)=>{const a=t.defaultShardKey??"__root__",{errors:i,globalRows:u,perShard:h,received:p}=await Ro(e,t,a),w={conflicts:0,errors:i,failed:[],inserted:{}},S=[];if(t.resolveTableSharding===void 0&&h.size>0&&S.push("no `resolveTableSharding` is configured, so every row was routed to the default shard and no row could be recognised as `.global()` — correct for a single-shard app, silent misplacement for a sharded one"),h.size>0){const A=t.queryCoordinator;if(!A)throw new c("Import endpoint requires a `queryCoordinator` on the worker",{code:"BAD_REQUEST",status:400});const T=await A.orchestrateImport(r,{batches:[...h.values()],headers:n});Tt(w,T),w.failed.push(...Eo(T.shards))}if(u.length>0)if(t.importGlobals){const A=u[0]?.line??1,T=await t.importGlobals({rows:u,startLine:A});Tt(w,T)}else for(const A of u)w.errors.push({code:"GLOBAL_NOT_CONFIGURED",line:A.line,message:`row targets global table "${A.table}" but no \`importGlobals\` is configured`,table:A.table});return{conflicts:w.conflicts,errors:w.errors,failed:w.failed,inserted:w.inserted,received:p,...S.length>0?{warnings:S}:{}}},Ke=e=>typeof e=="object"&&e!==null?e:{},Fe=e=>typeof e.kind=="string"?e.kind:"unknown",Ao=(e,t)=>{let n=Ke(t),r=!1;Fe(n)==="optional"&&(r=!0,n=Ke(n._meta?.inner));const a=Fe(n),i=n._meta??{},u={kind:a,name:e,optional:r};if(a==="id"&&typeof i.tableName=="string"&&(u.table=i.tableName),a==="array"){const h=Fe(Ke(i.inner));h!=="unknown"&&(u.element=h)}return u},To=e=>typeof e!="object"||e===null?[]:Object.entries(e).map(([t,n])=>Ao(t,n)).toSorted((t,n)=>t.name.localeCompare(n.name)),Oo="/_lunora/admin/functions",vo="/_lunora/admin/cron-jobs",ko="/_lunora/admin/openapi",Io="/_lunora/admin/openrpc",Po="/_lunora/admin/global/tables",No="/_lunora/admin/global/table",Do="/_lunora/admin/global/facet",Ot=e=>{if(e===void 0||e==="")return;let t;try{t=Ve(JSON.parse(e))}catch{return}if(!Array.isArray(t))return;const n=t.flatMap(r=>{if(typeof r!="object"||r===null||typeof r.column!="string")return[];const{column:a,value:i}=r;return[{column:a,value:i}]});return n.length===0?void 0:n},Uo=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:{}}),Co=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"}),Bo=e=>{const{assertAdmin:t,options:n,parsePaging:r,queryParameter:a,requireAdminOption:i}=e,u=y=>{j(y,"GET","Functions");const _=i(y,n.functions,{code:"FUNCTIONS_NOT_CONFIGURED",message:"functions endpoint requires a `functions` registry on the worker"}),R=Object.entries(_).flatMap(([f,v])=>v.visibility==="internal"||v.kind==="stream"?[]:[{args:To(v.args),kind:v.kind,path:f}]).toSorted((f,v)=>f.path.localeCompare(v.path));return Response.json({functions:R},{headers:{"content-type":"application/json"},status:200})},h=y=>{j(y,"GET","Cron-jobs");const _=i(y,n.cronJobs,{code:"CRON_JOBS_NOT_CONFIGURED",message:"cron-jobs endpoint requires a `cronJobs` map on the worker"}),R=Object.entries(_).flatMap(([f,v])=>v.map(U=>({args:U.args,cron:f,functionPath:U.functionPath,name:U.name,shardKey:U.shardKey,workflow:U.workflow}))).toSorted((f,v)=>f.name.localeCompare(v.name));return Response.json({jobs:R},{headers:{"content-type":"application/json"},status:200})},p=y=>(j(y,"GET","OpenAPI"),t(y),Response.json(n.openApiSpec??Uo,{headers:{"content-type":"application/json"},status:200})),w=y=>(j(y,"GET","OpenRPC"),t(y),Response.json(n.openRpcSpec??Co,{headers:{"content-type":"application/json"},status:200})),S=async y=>{j(y,"GET","Global-tables");const _=i(y,n.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"});return Response.json(await _.listTables(),{headers:{"content-type":"application/json"},status:200})},A=async y=>{j(y,"GET","Global-table");const _=i(y,n.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),R=new URL(y.url),f=a(R,"table");if(f===void 0)throw new c("Global-table endpoint requires a `table` query param",{code:"BAD_REQUEST",status:400});const v=await _.readTablePage({...r(y),filters:Ot(a(R,"filters")),table:f});return Response.json(v,{headers:{"content-type":"application/json"},status:200})},T=async y=>{j(y,"GET","Global-facet");const _=i(y,n.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),R=new URL(y.url),f=a(R,"table"),v=a(R,"column");if(f===void 0||v===void 0)throw new c("Global-facet endpoint requires `table` and `column` query params",{code:"BAD_REQUEST",status:400});const U=a(R,"limit"),M=U===void 0?void 0:Number(U),N=await _.facetColumn({column:v,filters:Ot(a(R,"filters")),limit:M!==void 0&&Number.isFinite(M)?M:void 0,table:f});return Response.json(N,{headers:{"content-type":"application/json"},status:200})};return{[vo]:h,[Oo]:u,[Do]:T,[No]:A,[Po]:S,[ko]:p,[Io]:w}},xo="/_lunora/admin/kv/namespaces",Ho="/_lunora/admin/kv/keys",Zt="/_lunora/admin/kv/value",en=32*1048576,vt=60,Lo=e=>{const{readJsonBody:t,requireAdminOption:n}=e,r=_=>n(_,e.kvIntrospector,{code:"KV_NOT_CONFIGURED",message:"KV endpoints require a `kvIntrospector` on the worker"}),a=_=>Response.json(_,{headers:{"content-type":"application/json"},status:200}),i=(_,R)=>{const f=new URL(_.url),v=f.searchParams.get("namespace")??"",U=f.searchParams.get("key")??"";if(v==="")throw new c(`KV-value ${R} request requires a \`namespace\` query parameter`,{code:"BAD_REQUEST",status:400});if(U==="")throw new c(`KV-value ${R} request requires a \`key\` query parameter`,{code:"BAD_REQUEST",status:400});return{key:U,namespace:v}},u=async(_,R)=>{if(!(await _.listNamespaces()).some(v=>v.binding===R))throw new c(`Unknown KV namespace binding \`${R}\``,{code:"NOT_FOUND",status:404})},h=async _=>(j(_,"GET","KV-namespaces"),a({namespaces:await r(_).listNamespaces()})),p=async _=>{j(_,"GET","KV-keys");const R=r(_),f=new URL(_.url),v=f.searchParams.get("namespace")??"";if(v==="")throw new c("KV-keys request requires a `namespace` query parameter",{code:"BAD_REQUEST",status:400});const U=f.searchParams.get("prefix")??void 0,M=f.searchParams.get("cursor")??void 0,N=f.searchParams.get("limit"),K=N===null?void 0:Number.parseInt(N,10);if(K!==void 0&&(!Number.isInteger(K)||K<1))throw new c("KV-keys `limit` must be a positive integer",{code:"BAD_REQUEST",status:400});const $=K===void 0?void 0:Math.min(K,1e3);return await u(R,v),a(await R.listKeys({cursor:M,limit:$,namespace:v,prefix:U}))},T={DELETE:async _=>{const R=r(_),f=i(_,"DELETE");return await u(R,f.namespace),await R.deleteKey(f),a({deleted:!0})},GET:async _=>{const R=r(_),f=i(_,"GET");return await u(R,f.namespace),a(await R.getValue(f))},PUT:async _=>{const R=r(_),f=await t(_,en);if(typeof f.namespace!="string"||f.namespace==="")throw new c("KV-value PUT request requires a `namespace` string",{code:"BAD_REQUEST",status:400});if(typeof f.key!="string"||f.key==="")throw new c("KV-value PUT request requires a `key` string",{code:"BAD_REQUEST",status:400});if(typeof f.value!="string")throw new c("KV-value PUT request requires a `value` string",{code:"BAD_REQUEST",status:400});if(f.expirationTtl!==void 0&&(typeof f.expirationTtl!="number"||!Number.isInteger(f.expirationTtl)||f.expirationTtl<vt))throw new c("KV-value PUT `expirationTtl` must be an integer ≥ 60",{code:"BAD_REQUEST",status:400});const v=Math.floor(Date.now()/1e3)+vt;if(f.expiration!==void 0&&(typeof f.expiration!="number"||!Number.isInteger(f.expiration)||f.expiration<v))throw new c("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(R,f.namespace),await R.putValue({expiration:f.expiration,expirationTtl:f.expirationTtl,key:f.key,metadata:f.metadata,namespace:f.namespace,value:f.value}),a({ok:!0})}},y=_=>{const R=T[_.method];if(!R)throw new c("KV-value endpoint requires GET, PUT, or DELETE",{code:"METHOD_NOT_ALLOWED",status:405});return R(_)};return{[xo]:h,[Ho]:p,[Zt]:y}},Mo="/_lunora/migrate",jo="/_lunora/admin/pitr",$o="/_lunora/admin/rank",Ko="/_lunora/admin/rankpage",Fo="/_lunora/admin/shard-traffic",Go=new Set(["__lunora_admin__:migrationStatus","__lunora_admin__:runMigration"]),Qo=new Set(["__lunora_admin__:getPitrBookmark","__lunora_admin__:pitrRestore"]),zo=async e=>{const n=await he(e,"Migration")??{};if(typeof n.table!="string"||n.table.length===0)throw new c("Migration request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof n.functionPath!="string"||!Go.has(n.functionPath))throw new c("Migration request `functionPath` must be a migration admin op",{code:"BAD_REQUEST",status:400});return{args:n.args??{},functionPath:n.functionPath,table:n.table}},Wo=async e=>{const n=await he(e,"Rank")??{};if(typeof n.table!="string"||n.table.length===0)throw new c("Rank request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof n.index!="string"||n.index.length===0)throw new c("Rank request is missing `index`",{code:"BAD_REQUEST",status:400});if(typeof n.partitionKey!="string")throw new c("Rank request `partitionKey` must be a string",{code:"BAD_REQUEST",status:400});if(typeof n.rowId!="string"||n.rowId.length===0)throw new c("Rank request is missing `rowId`",{code:"BAD_REQUEST",status:400});if(!Array.isArray(n.sortValues))throw new c("Rank request `sortValues` must be an array",{code:"BAD_REQUEST",status:400});return{index:n.index,partitionKey:n.partitionKey,rowId:n.rowId,sortValues:n.sortValues,table:n.table}},Vo=e=>{if(e!==void 0){if(!Array.isArray(e)||e.some(t=>t!=="asc"&&t!=="desc"))throw new c('Rank page request `directions` must be an array of "asc"|"desc"',{code:"BAD_REQUEST",status:400});return e}},Jo=e=>{if(typeof e.table!="string"||e.table.length===0)throw new c("Rank page request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof e.index!="string"||e.index.length===0)throw new c("Rank page request is missing `index`",{code:"BAD_REQUEST",status:400});if(e.partitionKey!==void 0&&typeof e.partitionKey!="string")throw new c("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 c("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 c("Rank page request `cursor` must be a string or null",{code:"BAD_REQUEST",status:400})},qo=async e=>{const n=await he(e,"Rank page")??{};Jo(n);const r=Vo(n.directions);return{cursor:typeof n.cursor=="string"?n.cursor:null,directions:r,index:n.index,partitionKey:typeof n.partitionKey=="string"?n.partitionKey:void 0,table:n.table,take:typeof n.take=="number"?n.take:void 0}},Yo=async e=>{const n=await he(e,"Shard-traffic")??{};if(typeof n.table!="string"||n.table.length===0)throw new c("Shard-traffic request is missing `table`",{code:"BAD_REQUEST",status:400});return{table:n.table}},Xo=async e=>{const n=await te(e);if(typeof n.functionPath!="string"||!Qo.has(n.functionPath))throw new c("PITR request `functionPath` must be a PITR admin op",{code:"BAD_REQUEST",status:400});if(n.shardKey!==void 0&&typeof n.shardKey!="string")throw new c("PITR `shardKey` must be a string",{code:"BAD_REQUEST",status:400});return{args:n.args??{},functionPath:n.functionPath,shardKey:n.shardKey}},Zo=e=>{const{defaultShard:t,forwardToShard:n,isAdmin:r,queryCoordinator:a,resolveForwardContext:i,shardDO:u}=e,h=(y,_)=>{if(y.method!=="POST")throw new c(`${_} endpoint requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});if(!r(y))throw new c("Admin auth required",{code:"FORBIDDEN",status:403});if(!a)throw new c(`${_} endpoint requires a \`queryCoordinator\` on the worker`,{code:"BAD_REQUEST",status:400});return a},p=async(y,_)=>{const R=h(y,"Migration"),f=await zo(y),{headers:v}=await i(y,_),U=await R.orchestrateMigration(u,{args:f.args,defaultShardKey:t,functionPath:f.functionPath,headers:v,table:f.table});return Response.json(U,{headers:{"content-type":"application/json"},status:200})},w=async(y,_)=>{const R=h(y,"Rank"),f=await Wo(y),{headers:v}=await i(y,_),U=await R.orchestrateRank(u,{headers:v,index:f.index,partitionKey:f.partitionKey,rowId:f.rowId,sortValues:f.sortValues,table:f.table});return Response.json(U,{headers:{"content-type":"application/json"},status:200})},S=async(y,_)=>{const R=h(y,"Rank page"),f=await qo(y),{headers:v}=await i(y,_),U=await R.orchestrateRankPage(u,{...f,headers:v});return Response.json(U,{headers:{"content-type":"application/json"},status:200})},A=async(y,_)=>{const R=h(y,"Shard-traffic"),f=await Yo(y),{headers:v}=await i(y,_),U=await R.orchestrateShardTraffic(u,{headers:v,table:f.table});return Response.json(U,{headers:{"content-type":"application/json"},status:200})},T=async(y,_)=>{if(j(y,"POST","PITR"),!r(y))throw new c("admin PITR endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403});const R=await Xo(y),{headers:f}=await i(y,_),v=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:R.args,functionPath:R.functionPath}),headers:f,method:"POST"});return n(u,R.shardKey??t,v)};return{[Mo]:p,[jo]:T,[$o]:w,[Ko]:S,[Fo]:A}},ea=1,ta=0,na=32,ra=512,oa=/^[a-z][\d_a-z*/-]{0,255}(?:@[a-z][\d_a-z*/-]{0,13})?=[\u0020-\u002B\u002D-\u003C\u003E-\u007E]{1,256}$/,aa=e=>{if(e==null)return;const t=e.trim();if(t.length===0||t.length>ra)return;const n=t.split(",");if(!(n.length>na)){for(const r of n)if(!oa.test(r.trim()))return;return t}},sa=e=>{const t=Qn(e.headers.get("traceparent"));if(t===void 0)return;const n=aa(e.headers.get("tracestate"));return{parentSpanId:t.parentSpanId,sampled:t.sampled,traceId:t.traceId,...n===void 0?{}:{traceState:n}}},ia=(e,t={})=>{const n=sa(e),r=t.trustInbound===!0?n:void 0,a=Ie(8),i=r?.traceId??Ie(16),u=wr(t.sampling,r===void 0?a:i),h=u.isTraced&&(r===void 0||r.sampled);return{decision:u,ignoredUpstream:n!==void 0&&r===void 0,trace:{sampled:h,spanId:a,traceFlags:h?ea:ta,traceId:i,...r?.parentSpanId===void 0?{}:{parentSpanId:r.parentSpanId},...r?.traceState===void 0?{}:{traceState:r.traceState}}}},ca=(e,t)=>{t.traceparent=jt(e.traceId,e.spanId,e.sampled),e.traceState!==void 0&&(t.tracestate=e.traceState)},da=(e,t)=>{let n;return()=>{if(n===void 0){const r=Jn(e),a=t===void 0?void 0:t.cf;n=zn(Vn(r),Wn(r,a))}return n}},ua="/_lunora/admin/scheduled",la="/_lunora/admin/scheduled/status",ha="/_lunora/admin/scheduled/ws",fa="/_lunora/admin/scheduled/cancel",pa="/_lunora/admin/scheduled/dead",ma="/_lunora/admin/scheduled/dead/retry",wa="/_lunora/admin/scheduled/dead/cancel",ga="/_lunora/admin/scheduled/pool/release",ya=e=>{const{checkWsAdmin:t,requireSchedulerNamespace:n,resolveSchedulerStub:r,schedulerInstanceName:a}=e,i=(w,S)=>A=>{if(A.method!=="GET")throw new c(`${S} endpoint requires GET`,{code:"METHOD_NOT_ALLOWED",status:405});const T=new URL(A.url).searchParams.get("cursor"),y=T===null||T===""?"":`?cursor=${encodeURIComponent(T)}`;return r(A).fetch(new Request(`https://scheduler.internal${w}${y}`,{method:"GET"}))},u=(w,S,A=S)=>async T=>{if(T.method!=="POST")throw new c(`${A} requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});const y=r(T),_=await he(T,S);if(typeof _?.id!="string"||_.id==="")throw new c(`${S} requires a string \`id\``,{code:"BAD_REQUEST",status:400});return y.fetch(new Request(`https://scheduler.internal${w}`,{body:JSON.stringify({id:_.id}),headers:{"content-type":"application/json"},method:"POST"}))},h=async w=>{if(w.method!=="POST")throw new c("Scheduled pool-release endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const S=r(w),A=await he(w,"Scheduled pool-release");if(typeof A?.pool!="string"||A.pool==="")throw new c("Scheduled pool-release requires a string `pool`",{code:"BAD_REQUEST",status:400});const T=typeof A.id=="string"&&A.id!==""?A.id:void 0;return S.fetch(new Request("https://scheduler.internal/complete",{body:JSON.stringify(T===void 0?{pool:A.pool}:{id:T,pool:A.pool}),headers:{"content-type":"application/json"},method:"POST"}))},p=async w=>{if(w.headers.get("Upgrade")!=="websocket")throw new c("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});if(!await t(w))throw new c("admin authorization required",{code:"ADMIN_FORBIDDEN",status:403});const S=n();return ge(S,a).fetch(new Request("https://scheduler.internal/ws",{headers:{Upgrade:"websocket"}}))};return{[fa]:u("/cancel","Scheduled-cancel","Scheduled-cancel endpoint"),[wa]:u("/dead/cancel","Scheduled dead-letter action"),[pa]:i("/dead","Scheduled dead-letter"),[ma]:u("/dead/retry","Scheduled dead-letter action"),[ua]:i("/list","Scheduled-list"),[ga]:h,[la]:i("/status","Scheduler-status"),[ha]:p}},ba=(e,...t)=>{let n=e.cf;for(const r of t){if(typeof n!="object"||n===null)return;n=n[r]}return typeof n=="string"?n:void 0},kt={mtls:e=>ba(e,"tlsClientAuth","certVerified")==="SUCCESS"},_a=e=>e===void 0||e===!1?()=>!1:e===!0?()=>!0:typeof e=="function"?e:(Object.hasOwn(kt,e)?kt[e]:void 0)??(()=>!1),Ra=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.'))}},Ea="/_lunora/admin/vector/indexes",Sa="/_lunora/admin/vector/query",Aa=e=>{const{readJsonBody:t,requireAdminOption:n}=e,r=async i=>{j(i,"GET","Vector-indexes");const u=n(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=>{j(i,"POST","Vector-query");const u=n(i,e.vectorIntrospector,{code:"VECTORS_NOT_CONFIGURED",message:"vector endpoints require a `vectorIntrospector` on the worker"});if(u.queryIndex===void 0)throw new c("vector index querying is not enabled on this worker",{code:"VECTOR_QUERY_UNSUPPORTED",status:400});const p=await t(i);if(typeof p.name!="string"||p.name==="")throw new c("Vector-query request requires a `name` string",{code:"BAD_REQUEST",status:400});if(typeof p.text!="string"||p.text==="")throw new c("Vector-query request requires a `text` string",{code:"BAD_REQUEST",status:400});if(p.topK!==void 0&&(typeof p.topK!="number"||!Number.isInteger(p.topK)||p.topK<1))throw new c("Vector-query `topK` must be a positive integer",{code:"BAD_REQUEST",status:400});const w=await u.queryIndex({name:p.name,text:p.text,topK:p.topK});return Response.json(w,{headers:{"content-type":"application/json"},status:200})};return{[Ea]:r,[Sa]:a}},Ta="/_lunora/admin/workflows/instances",Oa="/_lunora/admin/workflows/instance",va="/_lunora/admin/workflows/status",ka={complete:!0,errored:!0,paused:!0,queued:!0,running:!0,terminated:!0,unknown:!0,waiting:!0,waitingForPause:!0},Ia=e=>e!==null&&Object.hasOwn(ka,e)?e:void 0,It=(e,t)=>{const n=e.searchParams.get(t);if(n===null)return;const r=Number(n);return Number.isInteger(r)&&r>0?r:void 0},Ge=(e,t)=>{const n=e.searchParams.get(t);if(n===null||n==="")throw new c(`Workflows admin endpoint requires a \`${t}\` query parameter`,{code:"BAD_REQUEST",status:400});return n},Pt=()=>{throw new c("Workflow inspection is unconfigured. Set CLOUDFLARE_ACCOUNT_ID + CLOUDFLARE_API_TOKEN in your .dev.vars to enable it.",{code:"WORKFLOWS_NOT_CONFIGURED",status:501})},Pa=e=>{const{assertAdmin:t,resolveWorkflowsClient:n}=e,r=async(u,h,p)=>{j(u,"GET","Workflows instances"),t(u);const w=n(h);if(!w)return Response.json({configured:!1,instances:[],page:1,perPage:0,totalCount:0});const S=Ge(p,"name"),A=Ia(p.searchParams.get("status"));return Response.json(await w.listInstances({page:It(p,"page"),perPage:It(p,"perPage"),status:A,workflowName:S}))},a=async(u,h,p)=>{j(u,"GET","Workflows instance"),t(u);const w=n(h);return w?Response.json(await w.getInstance({instanceId:Ge(p,"id"),workflowName:Ge(p,"name")})):Pt()},i=async(u,h)=>{j(u,"POST","Workflows status"),t(u);const p=n(h);if(!p)return Pt();const w=await u.json().catch(()=>{});if(typeof w?.name!="string"||w.name===""||typeof w.id!="string"||w.id==="")throw new c("Workflows status action requires string `name` and `id`",{code:"BAD_REQUEST",status:400});const{action:S}=w;if(S!=="pause"&&S!=="resume"&&S!=="terminate")throw new c("Workflows status action must be one of: pause, resume, terminate",{code:"BAD_REQUEST",status:400});return Response.json(await p.setInstanceStatus({action:S,instanceId:w.id,workflowName:w.name}))};return{[Oa]:a,[Ta]:r,[va]:i}},Na={[Zt]:en,[sr]:ar},Nt="/_lunora/rpc",Da="/_lunora/rpc-batch",Ua="/_lunora/ws",be=(e,t,n)=>({resourceAttributes:da(e,t),...n===void 0?{}:{waitUntil:n}}),Qe=e=>e?.waitUntil?{waitUntil:t=>e.waitUntil?.(t)}:{},Dt=e=>({spanId:e.spanId,traceFlags:e.traceFlags,traceId:e.traceId,...e.parentSpanId===void 0?{}:{parentSpanId:e.parentSpanId}}),ze=e=>{const{method:t}=e,n=e.headers.get("user-agent")??void 0;let r;try{r=new URL(e.url)}catch{return{method:t,userAgent:n}}const a=r.port===""?void 0:Number(r.port);return{host:r.hostname,method:t,path:r.pathname,port:Number.isNaN(a)?void 0:a,scheme:r.protocol.replace(":",""),userAgent:n}},Ut="/_lunora/voice/",Ca="/_lunora/scheduler/dispatch",Ba="/_lunora/admin/cron-jobs/run",xa="/_lunora/admin/ws-token",Ha="/_lunora/admin/",La="/_lunora/",Ma="/_lunora/migrate",ja="/_lunora/status",$a=e=>e.startsWith(Ha)||e===Ma,Ka="__lunora_relation__:",Se=e=>{if(e.startsWith(Ka))throw new c("`__lunora_relation__:*` is a fan-out-only reserved RPC and cannot be dispatched to a single shard",{code:"FORBIDDEN",status:403})},Ae=async e=>await e===!0,Fa=e=>{const t=e.headers.get("x-lunora-userid"),n=e.headers.get("x-lunora-identity");if(!(t===null&&n===null))return{...n===null?{}:{identity:n},...t===null?{}:{userId:t}}},Ct="/api/auth",Ga="__lunora_admin__:recordAuthEvent",Qa="__lunora_admin__:listPushSubscriptions",za=["/sign-in","/sign-up","/callback"],Wa=(e,t)=>{const n=t.endsWith("/")?t.slice(0,-1):t;if(!e.startsWith(`${n}/`))return!1;const r=e.slice(n.length);return za.some(a=>r===a||r.startsWith(`${a}/`))},Va=(e,t)=>{const n=t.endsWith("/")?t.slice(0,-1):t;return e===n||e.startsWith(`${n}/`)},Te=(e,t,n,r)=>{const a=Ln(n),i=a?n.code:"INTERNAL_SERVER_ERROR",u=a?n.status:500,h=n instanceof Error?n.message:String(n);return{durationMs:t,error:{code:i,message:h,status:u},functionPath:e,ok:!1,...r.fanOut?{fanOut:{failed:0,shards:0,table:r.fanOut.table}}:{},...r.shardKey?{shardKey:r.shardKey}:{}}},Ja=e=>{const{exp:t,expiresAtMs:n}=e;if(typeof n=="number"&&Number.isFinite(n))return n;if(typeof t=="number"&&Number.isFinite(t))return t*1e3},Bt=e=>e.waitUntil?{waitUntil:t=>{e.waitUntil?.(t)}}:void 0,qa=e=>{const t=e?.queue;return typeof t=="string"&&t.length>0?t:"unknown"},Ye=new WeakMap,de=async(e,t,n,r=Ye.get(e))=>{const a={"content-type":"application/json"},i=e.headers.get("authorization"),u=e.headers.get("cookie"),h=e.headers.get("x-d1-bookmark"),p=e.headers.get("x-lunora-mutation-id"),w=e.headers.get("x-lunora-client-id"),S=e.headers.get("x-lunora-client-seq");i&&(a.authorization=i),u&&(a.cookie=u),h&&(a["x-d1-bookmark"]=h),p&&(a["x-lunora-mutation-id"]=p),w&&(a["x-lunora-client-id"]=w),S&&(a["x-lunora-client-seq"]=S);const A=Zn(e.headers);if(A&&(a["x-lunora-client-ip"]=A),!n)return{claims:null,headers:a,identity:null,userId:null};const T=await n(e,t,r);if(!T||typeof T.userId!="string"||T.userId.length===0)return{claims:null,headers:a,identity:null,userId:null};a["x-lunora-userid"]=Fn(T.userId);const y=Ja(T);y!==void 0&&(a["x-lunora-identity-exp"]=String(y));const{userId:_,...R}=T,f=Object.keys(R).length>0?R:null;return f&&(a["x-lunora-identity"]=Gn(f)),{claims:f,headers:a,identity:T,userId:_}},Ya=new Set(["concat","first","groupBy","max","min","rank","sum","topK"]),Xa=e=>{if(e===void 0)return;if(!e||typeof e!="object")throw new c("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 c("RPC `fanOut.table` must be a non-empty string",{code:"BAD_REQUEST",status:400});if(!t.merge||typeof t.merge!="object")throw new c("RPC `fanOut.merge` must be an object",{code:"BAD_REQUEST",status:400});const n=t.merge;if(typeof n.kind!="string"||!Ya.has(n.kind))throw new c("RPC `fanOut.merge.kind` is not a recognized merge strategy",{code:"BAD_REQUEST",status:400});if(n.kind==="topK"){if(typeof n.k!="number"||!Number.isInteger(n.k)||n.k<0)throw new c("RPC `fanOut.merge.k` must be a non-negative integer",{code:"BAD_REQUEST",status:400});if(typeof n.by!="string"||n.by.length===0)throw new c("RPC `fanOut.merge.by` must be a non-empty string",{code:"BAD_REQUEST",status:400})}return t},Za=(e,t)=>{e?.LUNORA_DEBUG_RPC&&console.warn(`[lunora:rpc] ${t.fanOut?"fan-out":`shard=${t.shardKey??"(root)"}`} ${t.functionPath}`)},We=(e,t)=>{if(t.functions===void 0)return;const n=t.functions[e.functionPath]?.x402;if(n){if(e.fanOut)throw new c("a paid (`.x402`) function cannot be fanned out",{code:"BAD_REQUEST",status:400});if(!t.x402Charge)throw new c(`function "${e.functionPath}" is marked paid (.x402) but no x402Charge gate is configured on the worker`,{code:"MISCONFIGURED",status:500});return n}},es=async e=>{const t=await Ft(e);let n;try{n=JSON.parse(t)}catch{throw new c("RPC body must be valid JSON",{code:"BAD_REQUEST",status:400})}if(!n||typeof n!="object"||typeof n.functionPath!="string")throw new c("RPC envelope is missing `functionPath`",{code:"BAD_REQUEST",status:400});const r=n;if(r.args!==void 0&&Kt(r.args,"RPC"),r.shardKey!==void 0&&typeof r.shardKey!="string")throw new c("RPC `shardKey` must be a string",{code:"BAD_REQUEST",status:400});const a=n,i=Xa(a.fanOut),u=a.args??{};if(i&&a.functionPath.startsWith("__lunora_relation__:")){const h=u.table;if(typeof h=="string"&&h!==i.table)throw new c("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=new Map,ts=5e3,ns=4096,rs=async(e,t)=>{const n=Date.now(),r=Oe.get(t);if(r!==void 0&&r.expiresMs>n)return r.relayCount;r!==void 0&&Oe.delete(t);let a=0;try{const i=await ge(e,t).fetch(new Request("https://shard.internal/_lunora/route"));if(i.ok){const h=(await i.json()).relayCount;typeof h=="number"&&h>0&&(a=Math.floor(h))}}catch{a=0}return Mt(Oe,ns),Oe.set(t,{expiresMs:n+ts,relayCount:a}),a},xt=(e,t)=>{if(!(e===null||typeof e!="object"))return Object.entries(e).find(([,n])=>n===t)?.[0]},ve=(e,t,n)=>new Request("https://shard.internal/rpc",{body:JSON.stringify({args:t,functionPath:e}),headers:n,method:"POST"}),os=["x-lunora-userid","x-lunora-identity","x-lunora-identity-exp"],as=(e,t)=>{for(const n of os){e.delete(n);const r=t[n];r!==void 0&&e.set(n,r)}},Ht=(e,t)=>{const n=new Headers(e.headers),r=[...n.keys()];for(const a of r)a.startsWith("x-lunora-")&&n.delete(a);return as(n,t),n},ss=async(e,t,n)=>e.length===0||n.length===0?!1:et(await Wt(e,t),n),Lt=(e,t)=>{if(!t||t.length===0)return!1;const n=e.headers.get("authorization");if(!n)return!1;const[r,...a]=n.split(" ");return r?.toLowerCase()!=="bearer"?!1:et(t,a.join(" ").trim())},is=async(e,t,n)=>{if(!t||t.length===0)return!1;const r=new URL(e.url).searchParams.get("token");return r===null?!1:await Fr(t,r)?!0:n?!1:et(t,r)},cs=(e,t)=>{if(t===null||typeof t!="object"&&typeof t!="function")return;const n=t;if(typeof n.prepare=="function"&&typeof n.batch=="function"&&typeof n.dump=="function")return fr(`d1:${e}`,t);if(typeof n.list=="function"&&typeof n.head=="function"&&typeof n.createMultipartUpload=="function")return Le(`r2:${e}`,!0);if(typeof n.send=="function"&&typeof n.sendBatch=="function"&&typeof n.get!="function")return Le(`queue:${e}`,!0);if(typeof n.connectionString=="string")return Le(`hyperdrive:${e}`,!0)},ds=e=>{if(e.x402Charge!==void 0&&e.functions===void 0)throw new c("`x402Charge` requires `functions`: paid (.x402) procedures are read from the function registry, so without it every paid procedure would dispatch FREE. Build the worker with `defineApp()` (which supplies the registry) or pass `functions` explicitly.",{code:"MISCONFIGURED",status:500})},tn=e=>{ds(e);const t=_a(e.trustInboundTraceContext),n=Ra(e.trustInboundTraceContext),r=e.defaultShardKey??"__root__",a=pr(e.resolveIdentity,e.identity),i=ht(e.shardDO,e.jurisdiction),u=e.schedulerDO===void 0?void 0:ht(e.schedulerDO,e.jurisdiction);let h=!1;const p=o=>{if(o===void 0||e.jurisdiction===void 0)return o;h||(h=!0,console.warn(`[lunora] jurisdiction "${e.jurisdiction}" pins placement, so region hints (\`shardRegion\`, replica and relay placement) are not sent. Residency wins.`))},w=async(o,s,l,d=e.shardRegion?.(s))=>ge(o,s,p(d)).fetch(l);let S;const A=()=>e.adminToken??S;let T;const y=()=>e.requireEphemeralWsToken??T??!0;let _;const R=o=>{const s=o??{};if(_??=xt(o,e.shardDO),T===void 0&&e.requireEphemeralWsToken===void 0){const d=s.LUNORA_REQUIRE_EPHEMERAL_WS_TOKEN;typeof d=="string"&&d.length>0&&(T=jr(d,!0))}if(S!==void 0||e.adminToken!==void 0)return;const l=s.LUNORA_ADMIN_TOKEN;typeof l=="string"&&l.length>0&&(S=l)},f=new WeakSet,v=o=>Lt(o,A())||f.has(o),U=async o=>{if(!(e.adminGate===void 0||f.has(o)))try{await Ae(e.adminGate(o,Ye.get(o)))&&f.add(o)}catch{}},M=async(o,s)=>{const l=await de(o,s,e.resolveIdentity);if(f.has(o)&&l.headers.authorization===void 0){const d=A();d!==void 0&&(l.headers.authorization=`Bearer ${d}`)}return l};let N=!1,K=!1;const $=()=>{K||(K=!0,console.warn("[lunora] `replicaReads: true` has no effect without `functions` — read eligibility is decided from the function registry."))},V=o=>{if(!e.allowUnauthenticatedShardAccess){const s=o==="fan-out"?"authorizeFanOut":"authorizeShard";throw new c(`${o} access is default-denied: configure \`${s}\` 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})}N||(N=!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("")))},B=async(o,s)=>{if(s.includes(Je)||s.includes(qe))throw new c("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403});if(e.authorizeShard){if(!await Ae(e.authorizeShard({identity:o,shardKey:s})))throw new c("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else s!==r&&V("shard")},J=Zo({defaultShard:r,forwardToShard:w,isAdmin:v,queryCoordinator:e.queryCoordinator,resolveForwardContext:M,shardDO:i}),F=async(o,s,l,d,m,b)=>{Se(o);const O={"content-type":"application/json","x-lunora-system":"1"};return m?.userId!==void 0&&m.userId.length>0&&(O["x-lunora-userid"]=m.userId),m?.identity!==void 0&&m.identity.length>0&&(O["x-lunora-identity"]=m.identity),d!==void 0&&d.length>0&&(O["x-lunora-mutation-id"]=d),b!==void 0&&b.length>0&&(O.traceparent=b),w(i,l,ve(o,s,O))},q=async(o,s,l,d,m)=>{const b=l?.[o];if(!b||typeof b.create!="function")throw new c(`${d} targets workflow binding "${o}", which is not bound on env`,{code:"CRON_JOB_FAILED",status:500});if(_r(s))throw new c(`${d} params ${Rr}`,{code:"BAD_REQUEST",status:400});try{await b.create(m===void 0?{params:s}:{id:m,params:s})}catch(O){if(!Ar(O))throw O}},ee=async(o,s,l)=>{if(o.workflow){await q(o.workflow,o.args??{},s,`cron job "${o.name}"`);return}if(o.functionPath===void 0)throw new c(`cron job "${o.name}" has neither a function target nor a workflow target`,{code:"CRON_JOB_FAILED",status:500});const d=await F(o.functionPath,o.args??{},o.shardKey??r,void 0,void 0,l);if(!d.ok)throw new c(`cron job "${o.name}" (${o.functionPath}) failed with shard status ${String(d.status)}`,{code:"CRON_JOB_FAILED",status:500})},L=o=>{if(!v(o))throw new c("admin endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403})},Y=(o,s,l)=>{if(L(o),s===void 0)throw new c(l.message,{code:l.code,status:400});return s},G=async(o,s,l,d,m)=>{const b=e.cronJobs?.[o];if(!b)return 0;for(const O of b)try{await ee(O,s,m)}catch(k){l.push(d(k))}return b.length},fe=async(o,s)=>{if(L(o),j(o,"POST","cron-jobs run"),!e.cronJobs)throw new c("cron-jobs run endpoint requires a `cronJobs` map on the worker",{code:"CRON_JOBS_NOT_CONFIGURED",status:400});const l=await te(o),d=typeof l.name=="string"?l.name:"";if(d==="")throw new c("cron-jobs run endpoint requires a job `name`",{code:"BAD_REQUEST",status:400});const m=Object.values(e.cronJobs).flat().find(b=>b.name===d);if(!m)throw new c(`no cron job named "${d}" is registered`,{code:"CRON_JOB_NOT_FOUND",status:404});return await ee(m,s),Response.json({name:d,ran:!0},{status:200})},ae=async o=>{const s=typeof o.pool=="string"&&o.pool.length>0?o.pool:void 0;if(!s||!u||typeof o.id!="string")return;const l=typeof o.instanceName=="string"&&o.instanceName.length>0?o.instanceName:"default";try{await ge(u,l).fetch(new Request("https://scheduler.internal/complete",{body:JSON.stringify({id:o.id,pool:s}),headers:{"content-type":"application/json"},method:"POST"}))}catch{}},_e=async(o,s)=>{j(o,"POST","Scheduler dispatch");const l=await Ft(o),d=s??{},m=typeof d.LUNORA_SCHEDULER_SECRET=="string"?d.LUNORA_SCHEDULER_SECRET:void 0,b=e.adminToken??(typeof d.LUNORA_ADMIN_TOKEN=="string"?d.LUNORA_ADMIN_TOKEN:void 0),O=o.headers.get("x-lunora-scheduler-signature");let k=!1;if(O&&m?k=await ss(m,l,O):b&&(k=Lt(o,b)),!k)throw new c("Scheduler dispatch requires a valid signature or admin bearer",{code:"DISPATCH_UNAUTHENTICATED",status:403});let I;try{I=JSON.parse(l)}catch{throw new c("Scheduler dispatch body must be valid JSON",{code:"BAD_REQUEST",status:400})}const g=I??{},E=g.args??{},C=typeof g.id=="string"&&g.id.length>0?g.id:void 0;if(typeof g.workflow=="string"&&g.workflow.length>0)return await q(g.workflow,E,s,"scheduled workflow",C),await ae(g),Response.json({ok:!0},{status:200});if(typeof g.functionPath!="string"||g.functionPath.length===0)throw new c("Scheduler dispatch is missing `functionPath`",{code:"BAD_REQUEST",status:400});const x=typeof g.shardKey=="string"&&g.shardKey.length>0?g.shardKey:r,Q=Fa(o),H=await F(g.functionPath,E,x,C,Q,o.headers.get("traceparent")??void 0);return await ae(g),H},Pe=Wr({assertAdmin:L,getReader:()=>e.authAuditReader}),Ne=async(o,s)=>{L(o);const l=e.notifySubscriptionStore;if(l===void 0)return Response.json({result:ke({subscriptions:[]})},{headers:{"content-type":"application/json"},status:200});const d=s?.kind,m=s?.userId,b=s?.limit,O=d==="fcm"||d==="web-push"?d:void 0,k=typeof m=="string"&&m!==""?m:void 0,I=typeof b=="number"&&Number.isFinite(b)?Math.trunc(b):0,g=I>0?Math.min(I,1e3):1e3,C=(await l.list({kind:O,limit:g,userId:k})).filter(x=>O!==void 0&&x.kind!==O?!1:k===void 0||(x.userId??null)===k).map(({keys:x,token:Q,...H})=>H);return Response.json({result:ke({subscriptions:C})},{headers:{"content-type":"application/json"},status:200})},se=async(o,s)=>{if(!s.fanOut&&!(s.functionPath!==yt&&s.functionPath!==Qa))return await U(o),s.functionPath===yt?Pe(o,s.args??{}):Ne(o,s.args)},nn=yo({applyGlobals:e.applyGlobals,assertAdmin:L,exportCursorStore:e.exportCursorStore,exportSinks:e.exportSinks,defaultShardKey:r,knownTables:()=>[...e.listSchemaTables?.()??[]],queryCoordinator:e.queryCoordinator,requireAdminOption:Y,resolveForwardContext:M,shardDO:i,streamExportRows:(o,s,l,d)=>qt(e,o,s,l,d,i),streamingImport:(o,s)=>So(o,e,s,i),syncGlobals:e.syncGlobals}),De=(o,s)=>{const l=o.searchParams.get(s);return l===null||l===""?void 0:l},Ue=o=>{const s=new URL(o.url),l=s.searchParams.get("limit"),d=s.searchParams.get("offset"),m=l===null?void 0:Number.parseInt(l,10),b=d===null?void 0:Number.parseInt(d,10);return{limit:m!==void 0&&Number.isFinite(m)&&m>=0?m:void 0,offset:b!==void 0&&Number.isFinite(b)&&b>=0?b:void 0}},rt=()=>{if(u===void 0)throw new c("scheduled endpoints require a `schedulerDO` namespace on the worker",{code:"SCHEDULER_NOT_CONFIGURED",status:400});return u},rn=ya({checkWsAdmin:async o=>v(o)||is(o,A(),y()),requireSchedulerNamespace:rt,resolveSchedulerStub:o=>(L(o),ge(rt(),e.schedulerInstanceName??"default")),schedulerInstanceName:e.schedulerInstanceName??"default"}),on=Pa({assertAdmin:L,resolveWorkflowsClient:e.workflowsClient??(()=>{})}),an=or({assertAdmin:L,parsePaging:Ue,queryParameter:De,readBodyBytes:Xn,requireAdminOption:Y,storage:{storageBuckets:e.storageBuckets,storageDelete:e.storageDelete,storageDownload:e.storageDownload,storageList:e.storageList,storageSignedUrl:e.storageSignedUrl,storageUpload:e.storageUpload}}),sn=so({options:e,readJsonBody:te,requireAdminOption:Y}),cn=Aa({readJsonBody:te,requireAdminOption:Y,vectorIntrospector:e.vectorIntrospector}),dn=Lo({kvIntrospector:e.kvIntrospector,readJsonBody:te,requireAdminOption:Y}),un=mr({logArchive:e.logArchive,readJsonBody:te,requireAdminOption:Y}),ln=Bo({assertAdmin:L,options:{cronJobs:e.cronJobs,functions:e.functions,globalIntrospector:e.globalIntrospector,openApiSpec:e.openApiSpec,openRpcSpec:e.openRpcSpec},parsePaging:Ue,queryParameter:De,requireAdminOption:Y}),hn=o=>{const s=[],l=i??o?.SHARD;if(l!==void 0&&s.push(hr("durable-object:default",l,r)),e.health?.disableBindingProbes!==!0)for(const[d,m]of Object.entries(o??{})){const b=cs(d,m);b!==void 0&&s.push(b)}for(const d of e.health?.probes??[])s.push(d);return s},fn=lr({appName:e.health?.appName,appVersion:e.health?.appVersion,auth:e.health?.auth??"public",cacheTtlMs:e.health?.cacheTtlMs,isAdmin:v,resolveProbes:hn}),pn=o=>{const s=g=>"args"in g?{...g,args:Ve(g.args)}:g,l=e.schedulerInstanceName??"default",d=()=>ge(o,l),m=async(g,E)=>{const C=await d().fetch(new Request(`https://scheduler.internal${g}`,E));if(!C.ok)throw new c(`ctx.scheduler: SchedulerDO ${g} failed (${String(C.status)}): ${await C.text()}`,{code:"INTERNAL",status:500});return await C.json()},b=async(g,E)=>await m(g,{body:JSON.stringify(E),headers:{"content-type":"application/json"},method:"POST"}),O=g=>{const E=g;if(E==null)throw new c("ctx.scheduler: target is required — pass a reference from the generated `internal` / `workflows` / `agents`",{code:"BAD_REQUEST",status:400});if(typeof E.binding=="string"&&E.binding.length>0)return{workflow:E.binding};if(typeof E.__lunoraRef=="string")return{functionPath:E.__lunoraRef};throw new c("ctx.scheduler: expected a reference from the generated `internal` / `workflows` / `agents` — a bare function-path string is refused here, because an HTTP action can be reached unauthenticated",{code:"BAD_REQUEST",status:400})},k=async()=>(await Er(async E=>m(E===void 0?"/list":`/list?cursor=${encodeURIComponent(E)}`,{method:"GET"}))).map(E=>s(E)),I=async(g,E,C={})=>{const x=O(E),{id:Q}=await b("/schedule",{args:qn("ctx.scheduler",String(x.functionPath??x.workflow),C),scheduledFor:g,...x});return Q};return{cancel:async g=>await b("/cancel",{id:g}),get:async g=>{const E=await m(`/get?id=${encodeURIComponent(g)}`,{method:"GET"});return E.record===void 0?null:s(E.record)},list:k,runAfter:async(g,E,C)=>{if(!Number.isFinite(g)||g<0)throw new c("ctx.scheduler.runAfter: `delayMs` must be a non-negative finite number",{code:"INVALID_INPUT",status:400});return await I(Date.now()+g,E,C)},runAt:async(g,E,C)=>{if(!Number.isFinite(g))throw new c("ctx.scheduler.runAt: `date` must be a non-negative finite number",{code:"INVALID_INPUT",status:400});return await I(g,E,C)}}},mn=async(o,s,l)=>{const{claims:d,headers:m,userId:b}=await de(o,s,a),O=be(s,o,g=>l.waitUntil?.(g)),k=g=>async(E,C={})=>{const x=E.__lunoraRef;if(typeof x!="string")throw new c("ctx.run*: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});Se(x);const Q=await Ee(o,x,ke(C),g,{...m,"x-lunora-system":"1"},O),H=await Q.json();if(H.error)throw new c(H.error.message??"shard RPC failed",{code:H.error.code??"INTERNAL",status:Q.status});return Ve(H.result)},I=k(r);return{auth:{getIdentity:()=>Promise.resolve(d),userId:b},cache:l.cache,fetch:globalThis.fetch.bind(globalThis),forShard:g=>{const E=k(g);return{runAction:E,runMutation:E,runQuery:E}},runAction:I,runMutation:I,runQuery:I,...u===void 0?{}:{scheduler:pn(u)},...l.waitUntil===void 0?{}:{waitUntil:l.waitUntil.bind(l)},...e.storage===void 0?{}:{storage:br(e.storage(s))}}},wn=async(o,s,l)=>{if(!e.httpRouter)return;const d=await mn(o,s,l);try{return await e.httpRouter.fetch(o,{...s,__lunoraCtx:d},l)}catch(m){return console.error("[lunora] httpRouter (SSR) handler threw:",m),new Response("Internal Server Error",{status:500})}},gn=async(o,s,l)=>{if(o.headers.get("Upgrade")!=="websocket")throw new c("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});const d=pt(o,ie);if(d)return d;const m=l.searchParams.get("shard")??r,{headers:b,identity:O}=await de(o,s,a);await B(O,m);const k=Ht(o,b),I=xt(s,e.shardDO);if(I!==void 0){k.set("x-lunora-shard-binding",I);const g=await rs(i,m);if(g>0){const E=Br(m,Math.floor(Math.random()*g));return w(i,E,new Request(o,{headers:k}),mt(o))}}return w(i,m,new Request(o,{headers:k}))},yn=async(o,s,l)=>{const{voiceAgents:d}=e;if(d===void 0)return new Response("Not found",{status:404});if(o.headers.get("Upgrade")!=="websocket")return new Response("Expected a WebSocket upgrade",{headers:{allow:"GET"},status:426});const m=pt(o,ie);if(m)return m;let b;try{b=decodeURIComponent(l.pathname.slice(Ut.length))}catch{return new Response("Unknown voice agent",{status:404})}const O=Object.hasOwn(d,b)?d[b]:void 0;if(O===void 0)return new Response("Unknown voice agent",{status:404});const k=l.searchParams.get("threadKey");if(k===null||k.length===0)return new Response("Missing threadKey",{status:400});const{headers:I,identity:g}=await de(o,s,a);if(e.authorizeShard){if(!await Ae(e.authorizeShard({identity:g,shardKey:k})))throw new c("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else V("shard");const E=Ht(o,I);return w(O,k,new Request(o,{headers:E}))},bn=async(o,s,l)=>{if(e.authorizeFanOut){if(!await Ae(e.authorizeFanOut(l,o.table,s)))throw new c("Forbidden fan-out",{code:"FORBIDDEN_FANOUT",status:403});return}if(s.startsWith("__lunora_relation__:"))throw new c("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 c("Fan-out requires `authorizeFanOut` to be configured on the worker when `authorizeShard` is set",{code:"FORBIDDEN_FANOUT",status:403});V("fan-out")},Re=async(o,s)=>{if(!(!o.fanOut&&o.functionPath.startsWith("__lunora_admin__:"))){if(o.fanOut){await bn(o.fanOut,o.functionPath,s);return}await B(s,o.shardKey??r)}},_n=(o,s,l)=>{if(e.replicaReads!==!0)return;if(e.functions===void 0){$();return}if(e.functions[s]?.kind!=="query"||l.includes(qe)||l.includes(Je))return;const d=mt(o);return d===void 0?void 0:{name:xr(l,d),region:d}},Rn=async(o,s,l,d,m)=>{const b=_n(o,s,d);if(b!==void 0){const O={...m,"x-lunora-replica-read":"1",..._===void 0?{}:{"x-lunora-shard-binding":_}},k=Hr(o.headers.get("x-lunora-min-seq"));k!==void 0&&(O["x-lunora-min-seq"]=String(k));const I=await w(i,b.name,ve(s,l,O),b.region);if(I.status!==421)return I}return w(i,d,ve(s,l,m))},Ee=async(o,s,l,d,m,b)=>{const O=Date.now(),{observability:k,sampling:I}=e,g=ze(o),{decision:E,ignoredUpstream:C,trace:x}=ia(o,{...I===void 0?{}:{sampling:I},trustInbound:t(o)});C&&n();const Q={...m,"x-lunora-sample-errors":E.keepErrors?"1":"0"};ca(x,Q);try{const H=await Rn(o,s,l,d,Q);ce(k,{...g,...Dt(x),durationMs:Date.now()-O,functionPath:s,ok:H.ok,shardKey:d,...H.ok?{}:{error:{code:"SHARD_ERROR",message:`shard returned ${String(H.status)}`,status:H.status}}},b,void 0,{isTraced:x.sampled,keepErrors:E.keepErrors});const ne=new Response(H.body,{headers:H.headers,status:H.status,statusText:H.statusText});return ne.headers.set("x-lunora-shard-key",d),ne}catch(H){throw ce(k,{...g,...Dt(x),...Te(s,Date.now()-O,H,{shardKey:d})},b,void 0,{isTraced:x.sampled,keepErrors:E.keepErrors}),H}},En=o=>{if(o.fanOut&&o.shardKey)throw new c("RPC envelope cannot set both `shardKey` and `fanOut`",{code:"BAD_REQUEST",status:400});if(o.fanOut||Se(o.functionPath),o.fanOut&&!e.queryCoordinator)throw new c("RPC envelope set `fanOut` but no `queryCoordinator` is configured on the worker",{code:"BAD_REQUEST",status:400})},Sn=async(o,s,l)=>{j(o,"POST","RPC");const d=await es(o);Za(s,d),En(d);const m=await se(o,d);if(m!==void 0)return m;const{headers:b,identity:O}=await de(o,s,a);await Re(d,O);const k=We(d,e);{const I=Date.now(),{observability:g}=e,E=ze(o),C=be(s,o,l&&(H=>l.waitUntil?.(H)));if(d.fanOut){const H=e.queryCoordinator;if(!H)throw new c("RPC envelope set `fanOut` but no `queryCoordinator` is configured on the worker",{code:"BAD_REQUEST",status:400});try{const ne=await H.fanOut(i,{args:d.args??{},fanOut:d.fanOut,functionPath:d.functionPath,headers:b});return ce(g,{durationMs:Date.now()-I,fanOut:{failed:ne.failed,shards:ne.ok+ne.failed,table:d.fanOut.table},functionPath:d.functionPath,...E,ok:!0},C),Response.json(ne,{headers:{"content-type":"application/json"},status:200})}catch(ne){throw ce(g,{...Te(d.functionPath,Date.now()-I,ne,{fanOut:{table:d.fanOut.table}}),...E},C),ne}}const x=d.shardKey??r,Q=()=>Ee(o,d.functionPath,d.args??{},x,b,C);return k&&e.x402Charge?e.x402Charge(o,{functionPath:d.functionPath,price:k.price},Q,Qe(l)):Q()}},An=async(o,s,l)=>{j(o,"POST","RPC batch");const d=await te(o),{calls:m}=d;if(!Array.isArray(m))throw new c("RPC batch `calls` must be an array",{code:"BAD_REQUEST",status:400});const{headers:b,identity:O}=await de(o,s,a),k=co(m,r);for(const z of k.values())for(const W of z)if(e.functions?.[W.functionPath]?.x402)throw new c(`paid (\`.x402\`) function "${W.functionPath}" cannot be called in a batch; dispatch it individually over ${Nt}`,{code:"BAD_REQUEST",status:400});await Promise.all([...k.entries()].flatMap(([z,W])=>W.map(oe=>Re({args:oe.args,functionPath:oe.functionPath,shardKey:z},O))));const{observability:I}=e,g=be(s,o,l&&(z=>l.waitUntil?.(z))),E=ze(o),C=[],x=[],Q=(z,W,oe,ue)=>({body:{error:{code:oe,message:ue}},id:z.id,status:W}),H=(z,W,oe,ue,pe)=>{for(const X of z)ce(I,pe(X),g),C.push(Q(X,W,oe,ue))},ne=(z,W,oe,ue,pe)=>{for(const X of z){const me=ue.get(X.id)??pe,ye=me<400;ce(I,{durationMs:oe,functionPath:X.functionPath,...E,ok:ye,shardKey:W,...ye?{}:{error:{code:"SHARD_ERROR",message:`batched call returned ${String(me)}`,status:me}}},g)}};await Promise.all([...k.entries()].map(async([z,W])=>{const oe=new Headers(b);oe.set("content-type","application/json");const ue=new Request("https://shard.internal/rpc-batch",{body:JSON.stringify({calls:W}),headers:oe,method:"POST"}),pe=Date.now();let X;try{X=await w(i,z,ue)}catch(Z){const He=Date.now()-pe,{body:ct}=Mn(Z,{fallbackCode:"SHARD_UNAVAILABLE",redactedMessage:"shard unavailable"});H(W,502,ct.code,ct.message,Hn=>({...Te(Hn.functionPath,He,Z,{shardKey:z}),...E}));return}const me=Date.now()-pe,ye=X.headers.get("x-d1-bookmark");ye&&x.push(ye);let Be;try{Be=await X.json()}catch{const Z=`shard batch returned a non-JSON response (${String(X.status)})`;H(W,X.status,"SHARD_ERROR",Z,He=>({durationMs:me,error:{code:"SHARD_ERROR",message:Z,status:X.status},functionPath:He.functionPath,...E,ok:!1,shardKey:z}));return}const xe=Array.isArray(Be.results)?Be.results:[],Bn=new Map(xe.map(Z=>[Z.id,Z.status??X.status])),xn=new Set(xe.map(Z=>Z.id));ne(W,z,me,Bn,X.status),C.push(...xe);for(const Z of W)xn.has(Z.id)||C.push(Q(Z,X.status,"SHARD_ERROR",`shard batch omitted result for call ${String(Z.id)}`))}));const st={"content-type":"application/json"},[it]=x;return x.length===1&&it!==void 0&&(st["x-d1-bookmark"]=it),Response.json({results:C},{headers:st,status:200})},Tn=async(o,s,l,d={},m={})=>{try{const b=l.__lunoraRef;if(typeof b!="string")throw new c("serverQuery: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});Se(b);const{headers:O,identity:k}=await de(o,s,a,m.context),I={args:d,functionPath:b,shardKey:m.shardKey};await Re(I,k);const g=m.shardKey??r,E=be(s,o,m.waitUntil),C=()=>Ee(o,b,d,g,O,E),x=We(I,e);return x&&e.x402Charge?await e.x402Charge(o,{functionPath:b,price:x.price},C,Qe(m.waitUntil?{waitUntil:m.waitUntil}:m.context)):await C()}catch(b){return dt(b)}},ot=async(o,s,l)=>{const{observability:d}=e,m=Date.now(),b=Ie(16),O=Ie(8),k=Bt(s),I=jt(b,O,!0);try{const g=await l(I);return ce(d,{durationMs:Date.now()-m,functionPath:o,ok:!0,spanId:O,traceId:b},k),g}catch(g){throw ce(d,{...Te(o,Date.now()-m,g,{}),spanId:O,traceId:b},k),g}finally{lt(d,k)}},On=async(o,s,l,d)=>{R(s);const m=[],b=E=>E instanceof Error?E:new Error(String(E)),O=e.crons?.[o.cron];if(O)try{await O(o,s,l)}catch(E){m.push(b(E))}const k=await G(o.cron,s,m,b,d),I=!!e.backupStore&&e.backupCron!==void 0&&e.backupCron===o.cron;if(I)try{await no(e,i,A(),o)}catch(E){m.push(b(E))}if(!O&&k===0&&!I){const E=[...new Set([...Object.keys(e.crons??{}),...Object.keys(e.cronJobs??{})])];console.warn(`[lunora] scheduled("${o.cron}") fired but no cron handler is registered for that expression. Registered: ${E.length===0?"(none)":E.join(", ")}. Check that \`triggers.crons\` in wrangler.jsonc matches the app's cron definitions.`)}const[g]=m;if(m.length===1&&g)throw g;if(m.length>1)throw new AggregateError(m,`scheduled("${o.cron}") had ${String(m.length)} failure(s)`)},vn=async(o,s)=>{try{const l=o??{},d=e.adminToken??(typeof l.LUNORA_ADMIN_TOKEN=="string"?l.LUNORA_ADMIN_TOKEN:void 0);if(!d||d.length===0)return;await w(i,r,ve(Ga,{outcome:s},{authorization:`Bearer ${d}`,"content-type":"application/json"}))}catch{}},kn=async(o,s,l,d)=>{if(!e.authHandler)return;const m=await e.authHandler(o);if(!m)return;const b=e.authBasePath??Ct;return Wa(l.pathname,b)&&d.waitUntil?.(vn(s,m.status>=400?"fail":"ok")),m},In=async({args:o,env:s,functionPath:l,request:d,shardKey:m,waitUntil:b})=>{Kt(o,"REST");const O={functionPath:l,...m===void 0?{}:{shardKey:m}},{headers:k,identity:I}=await de(d,s,a);await Re(O,I);const g=m??r,E=be(s,d,b),C=()=>Ee(d,l,o,g,k,E),x=We(O,e);return x&&e.x402Charge?e.x402Charge(d,{functionPath:l,price:x.price},C,Qe({waitUntil:b})):C()},Pn=Yn({functions:e.functions??{},invoke:In,readJsonBody:te,edgeCache:e.restEdgeCache,...e.restRateLimit?{rateLimit:e.restRateLimit}:{}}),Ce=e.routes!==void 0&&Object.keys(e.routes).length>0?e.routes:void 0,Nn={[ja]: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"}}),[Ua]:(o,s,l)=>gn(o,s,l),[Nt]:(o,s,l,d)=>Sn(o,s,d),[Da]:(o,s,l,d)=>An(o,s,d),[Ca]:(o,s)=>_e(o,s),[Ba]:(o,s)=>fe(o,s),[xa]:async o=>{j(o,"POST","ws-token"),L(o);const s=A();if(s===void 0)throw new c("ws-token minting requires a configured admin token",{code:"ADMIN_TOKEN_NOT_CONFIGURED",status:400});const l=await Kr(s);return Response.json(l,{headers:{"cache-control":"no-store"}})},...J,...nn,...rn,...on,...an,...sn,...cn,...dn,...un,...ln,...fn,...Pn,...zr({assertAdmin:L,getAuthAdmin:()=>e.authAdmin,parsePaging:Ue,queryParameter:De,readJsonBody:te})};let ie=ft(e.security),at=!1;const Dn=o=>{at||(at=!0,ie=ft(e.security,o??{}))},Un=async(o,s)=>{$a(s)&&await U(o)},Cn=async(o,s,l)=>{Ye.set(o,l);const d=new URL(o.url);if((d.pathname.startsWith(La)||e.authHandler!==void 0&&Va(d.pathname,e.authBasePath??Ct))&&(o.method==="POST"||o.method==="PUT")){const I=Number(o.headers.get("content-length")??""),g=Na[d.pathname]??$t;if(Number.isFinite(I)&&I>g)throw new c("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413})}const b=await kn(o,s,d,l);if(b)return b;if(Ce){const I=`${o.method} ${d.pathname}`,g=Ce[I]??Ce[d.pathname];if(g)return g(o,s,l)}const O=Nn[d.pathname];if(O)return await Un(o,d.pathname),O(o,s,d,l);if(e.voiceAgents!==void 0&&d.pathname.startsWith(Ut))return yn(o,s,d);const k=await wn(o,s,l);return k||new Response("Not found",{status:404})};return{async fetch(o,s,l){e.passThroughOnException&&l.passThroughOnException?.(),Dn(s),R(s);const d=gr(o,ie);if(d)return d;const m=yr(o,ie);if(m)return Me(m,o,ie);try{const b=await Cn(o,s,l);return Me(b,o,ie)}catch(b){return Me(dt(b),o,ie)}finally{lt(e.observability,Bt(l))}},async queue(o,s,l){await ot(`queue:${qa(o)}`,l,async d=>{await e.queue?.(o,s,l,{traceparent:d})})},async scheduled(o,s,l){await ot(`cron:${o.cron}`,l,async d=>{await On(o,s,l,d)})},serverQuery:Tn}},us=e=>tn(e),ls=e=>typeof e=="function"?{fetch:e}:e,hs=e=>!!e.backupCron||Object.keys(e.crons??{}).length>0||Object.keys(e.cronJobs??{}).length>0,Cs=(e,t)=>{const n=ls(e),r=typeof e=="object"&&typeof e.scheduled=="function"?e.scheduled:void 0,a=u=>{const h=us({...u,httpRouter:n});return r!==void 0&&!hs(u)?{...h,scheduled:async(p,w,S)=>{await r(p,w,S)}}:h};if(typeof t!="function")return a(t);const i=t;return{fetch:(u,h,p)=>a(i(h)).fetch(u,h,p),queue:(u,h,p)=>a(i(h)).queue?.(u,h,p)??Promise.resolve(),scheduled:(u,h,p)=>a(i(h)).scheduled(u,h,p),serverQuery:(u,h,p,w,S)=>a(i(h)).serverQuery(u,h,p,w,S)}},fs=(e,t)=>{if(typeof e=="function")return e(t);const n=e.shardDO??t?.SHARD;if(!n)throw new c("@lunora/runtime: no shard Durable Object namespace found. Bind `SHARD` in wrangler.jsonc, or pass `createLunoraHandler({ shardDO: env.MY_SHARD })`.");return{...e,shardDO:n}},Bs=(e={})=>(t,n,r)=>tn(fs(e,n)).fetch(t,n,r??jn),xs=e=>e;export{yt as GET_AUTH_AUDIT_LOG_OP,jn as NOOP_EXECUTION_CONTEXT,Ms as composeIdentityResolvers,us as composeWorker,Bs as createLunoraHandler,tn as createWorker,xs as defineRpcEnvelope,rs as probeRelayCount,fs as resolveLunoraOptions,js as routeIdentityResolvers,Cs as withFrameworkWorker};
@@ -1 +1 @@
1
- import{e as c,a as u}from"./identity-header-C4Z5pldl.mjs";import{d as f}from"./wire-codec-BX_-4Tmg.mjs";import{LunoraError as s}from"./LunoraError-DksAgIpa.mjs";const l="/_lunora/rpc",h=e=>{const a={"content-type":"application/json"};return e.userId!==void 0&&e.userId.length>0&&(a["x-lunora-userid"]=c(e.userId)),e.identity!==void 0&&(a["x-lunora-identity"]=u(e.identity)),a},d=async(e,a,o)=>{const t=await(e.fetch??globalThis.fetch)(new Request(`${e.origin}${l}`,{body:JSON.stringify(a),headers:h(e),method:"POST"}));if(!t.ok)throw new s(`cross-shard relation ${o} failed: worker returned ${String(t.status)}`);const r=await t.json();if(typeof r.failed=="number"&&r.failed>0){const i=(typeof r.ok=="number"?r.ok:0)+r.failed;throw new s(`cross-shard relation ${o} failed on ${String(r.failed)} of ${String(i)} shard(s) — refusing to return a partial result`)}return f(r.data)},_=e=>({crossShardCounter:async(n,t)=>{const r=await d(e,{args:{table:n,where:t},fanOut:{merge:{kind:"sum"},table:n},functionPath:"__lunora_relation__:count"},"count");return typeof r=="number"?r:0},crossShardReader:async(n,t)=>{const r=await d(e,{args:{...t,table:n},fanOut:{merge:{kind:"concat"},table:n},functionPath:"__lunora_relation__:read"},"read");return{continueCursor:null,isDone:!0,page:Array.isArray(r)?r:[]}}});export{_ as createCrossShardRelationCapabilities};
1
+ import{e as c,a as u}from"./identity-header-C4Z5pldl.mjs";import{d as f}from"./wire-codec-BLvSm5Mn.mjs";import{LunoraError as s}from"./LunoraError-DksAgIpa.mjs";const l="/_lunora/rpc",h=e=>{const a={"content-type":"application/json"};return e.userId!==void 0&&e.userId.length>0&&(a["x-lunora-userid"]=c(e.userId)),e.identity!==void 0&&(a["x-lunora-identity"]=u(e.identity)),a},d=async(e,a,o)=>{const t=await(e.fetch??globalThis.fetch)(new Request(`${e.origin}${l}`,{body:JSON.stringify(a),headers:h(e),method:"POST"}));if(!t.ok)throw new s(`cross-shard relation ${o} failed: worker returned ${String(t.status)}`);const r=await t.json();if(typeof r.failed=="number"&&r.failed>0){const i=(typeof r.ok=="number"?r.ok:0)+r.failed;throw new s(`cross-shard relation ${o} failed on ${String(r.failed)} of ${String(i)} shard(s) — refusing to return a partial result`)}return f(r.data)},_=e=>({crossShardCounter:async(n,t)=>{const r=await d(e,{args:{table:n,where:t},fanOut:{merge:{kind:"sum"},table:n},functionPath:"__lunora_relation__:count"},"count");return typeof r=="number"?r:0},crossShardReader:async(n,t)=>{const r=await d(e,{args:{...t,table:n},fanOut:{merge:{kind:"concat"},table:n},functionPath:"__lunora_relation__:read"},"read");return{continueCursor:null,isDone:!0,page:Array.isArray(r)?r:[]}}});export{_ as createCrossShardRelationCapabilities};
@@ -1 +1 @@
1
- import{c as o,a as s,d as t,r as i,b as n,s as p,w as S}from"./export-tap-mRfLykiL.mjs";import"./portable-json-DcwKZHQ7.mjs";export{o as createKvCursorStore,s as createMemoryCursorStore,t as defineExportSink,i as r2Sink,n as runExportTap,p as sanitizeChange,S as webhookExportSink};
1
+ import{c as o,a as s,d as t,r as i,b as n,s as p,w as S}from"./export-tap-CAyZ2TWC.mjs";import"./portable-json-BSCiOfqE.mjs";export{o as createKvCursorStore,s as createMemoryCursorStore,t as defineExportSink,i as r2Sink,n as runExportTap,p as sanitizeChange,S as webhookExportSink};
@@ -1 +1 @@
1
- import{LunoraError as n}from"@lunora/errors";import{e as S,a as w}from"./identity-header-C4Z5pldl.mjs";import{e as g,d as f}from"./wire-codec-BX_-4Tmg.mjs";import{applyJurisdiction as p,resolveShard as N}from"./applyJurisdiction-C0ddU7Tg.mjs";const I=e=>{if(typeof e=="string")return e;const t=e?.__lunoraRef;if(typeof t!="string"||t.length===0)throw new n("INTERNAL","createShardClient: expected a generated function reference (api.*/internal.*) or a 'namespace:fn' string");return t},x=e=>{const t=new n(e.code,e.message);return e.data!==void 0&&(t.data=f(e.data)),t},$=(e,t={})=>{const l=p(e,t.jurisdiction),m=t.system??!0,c=r=>$(e,{...t,...r});return{as:r=>c({as:r}),asSystem:()=>c({as:void 0}),call:async(r,y,o)=>{const d=I(r),h=o?.shardKey??t.shardKey;if(h===void 0||h.length===0)throw new n("INTERNAL",`createShardClient: no shard key for "${d}" — pass one to createShardClient({ shardKey }), .forShard(key), or the call's options`);const s={"content-type":"application/json"};m&&(s["x-lunora-system"]="1"),t.as&&(s["x-lunora-userid"]=S(t.as.userId),t.as.claims&&(s["x-lunora-identity"]=w(t.as.claims))),o?.mutationId!==void 0&&o.mutationId.length>0&&(s["x-lunora-mutation-id"]=o.mutationId);const a=await N(l,h).fetch(new Request("https://shard.internal/rpc",{body:JSON.stringify({args:g(y??{}),functionPath:d}),headers:s,method:"POST"})),u=a.statusText?` ${a.statusText}`:"";let i;try{i=await a.json()}catch{throw new n("INTERNAL",`createShardClient: shard response for "${d}" was not JSON (status ${String(a.status)}${u})`)}if("error"in i)throw x(i.error);if(!a.ok)throw new n("INTERNAL",`createShardClient: shard call "${d}" failed (status ${String(a.status)}${u})`);return f(i.result)},forShard:r=>c({shardKey:r})}};export{$ as createShardClient};
1
+ import{LunoraError as n}from"@lunora/errors";import{e as S,a as w}from"./identity-header-C4Z5pldl.mjs";import{e as g,d as f}from"./wire-codec-BLvSm5Mn.mjs";import{applyJurisdiction as p,resolveShard as N}from"./applyJurisdiction-C0ddU7Tg.mjs";const I=e=>{if(typeof e=="string")return e;const t=e?.__lunoraRef;if(typeof t!="string"||t.length===0)throw new n("INTERNAL","createShardClient: expected a generated function reference (api.*/internal.*) or a 'namespace:fn' string");return t},x=e=>{const t=new n(e.code,e.message);return e.data!==void 0&&(t.data=f(e.data)),t},$=(e,t={})=>{const l=p(e,t.jurisdiction),m=t.system??!0,c=r=>$(e,{...t,...r});return{as:r=>c({as:r}),asSystem:()=>c({as:void 0}),call:async(r,y,o)=>{const d=I(r),h=o?.shardKey??t.shardKey;if(h===void 0||h.length===0)throw new n("INTERNAL",`createShardClient: no shard key for "${d}" — pass one to createShardClient({ shardKey }), .forShard(key), or the call's options`);const s={"content-type":"application/json"};m&&(s["x-lunora-system"]="1"),t.as&&(s["x-lunora-userid"]=S(t.as.userId),t.as.claims&&(s["x-lunora-identity"]=w(t.as.claims))),o?.mutationId!==void 0&&o.mutationId.length>0&&(s["x-lunora-mutation-id"]=o.mutationId);const a=await N(l,h).fetch(new Request("https://shard.internal/rpc",{body:JSON.stringify({args:g(y??{}),functionPath:d}),headers:s,method:"POST"})),u=a.statusText?` ${a.statusText}`:"";let i;try{i=await a.json()}catch{throw new n("INTERNAL",`createShardClient: shard response for "${d}" was not JSON (status ${String(a.status)}${u})`)}if("error"in i)throw x(i.error);if(!a.ok)throw new n("INTERNAL",`createShardClient: shard call "${d}" failed (status ${String(a.status)}${u})`);return f(i.result)},forShard:r=>c({shardKey:r})}};export{$ as createShardClient};
@@ -1,3 +1,3 @@
1
- import{f as K,t as j}from"./base64-Bl1_r2k1.mjs";import{t as O}from"./portable-json-DcwKZHQ7.mjs";const N=new TextEncoder,q=e=>j(N.encode(JSON.stringify(e))),B=e=>{const r={g:0,s:{},v:1};if(typeof e!="string"||e.length===0)return r;try{const t=JSON.parse(new TextDecoder().decode(K(e))),o=t.s&&typeof t.s=="object"?t.s:{},s={};for(const[i,n]of Object.entries(o))typeof n=="number"&&Number.isFinite(n)&&(s[i]=n);return{g:typeof t.g=="number"&&Number.isFinite(t.g)?t.g:0,s,v:1}}catch{return r}},P=e=>{const r=typeof e.table=="string"?e.table:"",t=typeof e.op=="string"?e.op:"",o=t==="delete"||t==="insert"||t==="update"?t:"upsert",s=typeof e.id=="string"?e.id:void 0;return{doc:(e.doc&&typeof e.doc=="object"?e.doc:void 0)??(s===void 0?{}:{_id:s}),op:o,table:r}},M=e=>Math.max(1,Math.min(e??1e3,1e4)),D=(e,r,t)=>{for(const o of r)e.push(P(o));return t!==void 0&&r.length>=t},R=e=>new Promise(r=>{setTimeout(r,e)}),$=e=>{const r=typeof e.table=="string"?e.table:"",t=typeof e.op=="string"?e.op:"",o=t==="delete"||t==="insert"||t==="update"?t:"upsert",s=typeof e.id=="string"?e.id:void 0,i=e.doc&&typeof e.doc=="object"?O(e.doc):void 0,n=typeof e.seq=="number"&&Number.isFinite(e.seq)?e.seq:void 0,c=typeof e.ts=="number"&&Number.isFinite(e.ts)?e.ts:void 0;return{op:o,table:r,...i===void 0?{}:{doc:i},...s===void 0?{}:{id:s},...n===void 0?{}:{seq:n},...c===void 0?{}:{ts:c}}},T=async(e,r,t,o,s,i)=>{let n=0;for(;;)try{await e.deliver(r);return}catch(c){if(n>=t)throw c instanceof Error?c:new Error(String(c));const d=Math.min(o*2**n,s);await i(d),n+=1}},I=async e=>{const{coordinator:r,cursorStore:t,defaultShardKey:o,headers:s,initialBackoffMs:i=100,limit:n,maxBackoffMs:c=5e3,maxRetries:d=3,shardDO:S,sink:p,sleep:k=R,tables:C}=e,h=await t.read(p.name),b=await r.orchestrateCdcSync(S,{cursors:h,defaultShardKey:o,headers:s,limit:n,tables:C}),l={...h},m=[];let v=0,f=!1;for(const a of b.shards){if(a.error){m.push({error:a.error.message,shardKey:a.shardKey}),f=!0;continue}const y=a.changes??[];if(y.length===0){l[a.shardKey]=a.cursor;continue}const g=y.map(u=>$(u)),E={changes:g,cursor:a.cursor,shardKey:a.shardKey,sink:p.name};try{await T(p,E,d,i,c,k),l[a.shardKey]=a.cursor,v+=g.length,y.length>=M(n)&&(f=!0)}catch(u){m.push({error:u instanceof Error?u.message:String(u),shardKey:a.shardKey}),f=!0}}return await t.write(p.name,l),{cursors:l,delivered:v,failures:m,hasMore:f,shards:b.shards.length}},x=e=>{if(typeof e.name!="string"||e.name.length===0)throw new Error("defineExportSink: `name` must be a non-empty string");if(typeof e.deliver!="function")throw new TypeError("defineExportSink: `deliver` must be a function");return{deliver:e.deliver,name:e.name}},w=e=>`${e.map(r=>JSON.stringify(r)).join(`
1
+ import{f as K,t as j}from"./base64-Bl1_r2k1.mjs";import{t as O}from"./portable-json-BSCiOfqE.mjs";const N=new TextEncoder,q=e=>j(N.encode(JSON.stringify(e))),B=e=>{const r={g:0,s:{},v:1};if(typeof e!="string"||e.length===0)return r;try{const t=JSON.parse(new TextDecoder().decode(K(e))),o=t.s&&typeof t.s=="object"?t.s:{},s={};for(const[i,n]of Object.entries(o))typeof n=="number"&&Number.isFinite(n)&&(s[i]=n);return{g:typeof t.g=="number"&&Number.isFinite(t.g)?t.g:0,s,v:1}}catch{return r}},P=e=>{const r=typeof e.table=="string"?e.table:"",t=typeof e.op=="string"?e.op:"",o=t==="delete"||t==="insert"||t==="update"?t:"upsert",s=typeof e.id=="string"?e.id:void 0;return{doc:(e.doc&&typeof e.doc=="object"?e.doc:void 0)??(s===void 0?{}:{_id:s}),op:o,table:r}},M=e=>Math.max(1,Math.min(e??1e3,1e4)),D=(e,r,t)=>{for(const o of r)e.push(P(o));return t!==void 0&&r.length>=t},R=e=>new Promise(r=>{setTimeout(r,e)}),$=e=>{const r=typeof e.table=="string"?e.table:"",t=typeof e.op=="string"?e.op:"",o=t==="delete"||t==="insert"||t==="update"?t:"upsert",s=typeof e.id=="string"?e.id:void 0,i=e.doc&&typeof e.doc=="object"?O(e.doc):void 0,n=typeof e.seq=="number"&&Number.isFinite(e.seq)?e.seq:void 0,c=typeof e.ts=="number"&&Number.isFinite(e.ts)?e.ts:void 0;return{op:o,table:r,...i===void 0?{}:{doc:i},...s===void 0?{}:{id:s},...n===void 0?{}:{seq:n},...c===void 0?{}:{ts:c}}},T=async(e,r,t,o,s,i)=>{let n=0;for(;;)try{await e.deliver(r);return}catch(c){if(n>=t)throw c instanceof Error?c:new Error(String(c));const d=Math.min(o*2**n,s);await i(d),n+=1}},I=async e=>{const{coordinator:r,cursorStore:t,defaultShardKey:o,headers:s,initialBackoffMs:i=100,limit:n,maxBackoffMs:c=5e3,maxRetries:d=3,shardDO:S,sink:p,sleep:k=R,tables:C}=e,h=await t.read(p.name),b=await r.orchestrateCdcSync(S,{cursors:h,defaultShardKey:o,headers:s,limit:n,tables:C}),l={...h},m=[];let v=0,f=!1;for(const a of b.shards){if(a.error){m.push({error:a.error.message,shardKey:a.shardKey}),f=!0;continue}const y=a.changes??[];if(y.length===0){l[a.shardKey]=a.cursor;continue}const g=y.map(u=>$(u)),E={changes:g,cursor:a.cursor,shardKey:a.shardKey,sink:p.name};try{await T(p,E,d,i,c,k),l[a.shardKey]=a.cursor,v+=g.length,y.length>=M(n)&&(f=!0)}catch(u){m.push({error:u instanceof Error?u.message:String(u),shardKey:a.shardKey}),f=!0}}return await t.write(p.name,l),{cursors:l,delivered:v,failures:m,hasMore:f,shards:b.shards.length}},x=e=>{if(typeof e.name!="string"||e.name.length===0)throw new Error("defineExportSink: `name` must be a non-empty string");if(typeof e.deliver!="function")throw new TypeError("defineExportSink: `deliver` must be a function");return{deliver:e.deliver,name:e.name}},w=e=>`${e.map(r=>JSON.stringify(r)).join(`
2
2
  `)}
3
3
  `,J=e=>{const r=e.fetchImpl??((t,o)=>fetch(t,o));return x({deliver:async t=>{const o=await r(e.url,{body:w(t.changes),headers:{"content-type":"application/x-ndjson","x-lunora-cursor":String(t.cursor),"x-lunora-shard":t.shardKey,"x-lunora-sink":t.sink,...e.headers},method:"POST"});if(!o.ok)throw new Error(`webhook export sink "${e.name}" returned ${String(o.status)}`)},name:e.name})},U=e=>{let r=e.prefix??"cdc";for(;r.endsWith("/");)r=r.slice(0,-1);return x({deliver:async t=>{const o=`${r}/${t.shardKey}/${String(t.cursor)}.ndjson`;await e.bucket.put(o,w(t.changes),{httpMetadata:{contentType:"application/x-ndjson"}})},name:e.name})},z=()=>{const e={};return{read:r=>Promise.resolve({...e[r]}),snapshot:()=>structuredClone(e),write:(r,t)=>(e[r]={...t},Promise.resolve())}},W=(e,r)=>{const t=r?.keyPrefix??"__lunora_source_cursor:export",o=s=>`${t}:${s}`;return{read:async s=>{const i=await e.get(o(s),"json");if(i===null||typeof i!="object")return{};const n={};for(const[c,d]of Object.entries(i))typeof d=="number"&&Number.isFinite(d)&&(n[c]=d);return n},write:async(s,i)=>{await e.put(o(s),JSON.stringify(i))}}};export{z as a,I as b,W as c,x as d,B as e,D as f,q as g,M as h,U as r,$ as s,J as w};
@@ -0,0 +1 @@
1
+ const R={debug:5,error:17,fatal:21,info:9,log:9,trace:1,warn:13},N=e=>`${String(Math.round(e))}000000`,A=Array.from({length:256},(e,r)=>r.toString(16).padStart(2,"0")),l=512,v=new Uint8Array(l);let a=l;const O=(e,r,t)=>{let o="";for(let n=0;n<t;n+=1)o+=A[e[r+n]];return o},T=e=>{if(e>l){const t=new Uint8Array(e);return crypto.getRandomValues(t),O(t,0,e)}a+e>l&&(crypto.getRandomValues(v),a=0);const r=O(v,a,e);return a+=e,r},u=/^[0-9a-f]+$/,S=(e,r,t=!0)=>`00-${e}-${r}-${t?"01":"00"}`,I=e=>{if(e==null)return;const r=e.trim().toLowerCase().split("-"),[t,o,n,s]=r;if(!(r.length<4||t===void 0||t.length!==2||!u.test(t)||t==="ff"||t==="00"&&r.length!==4||o===void 0||n===void 0||s===void 0||s.length!==2||!u.test(s)||o.length!==32||n.length!==16||!u.test(o)||!u.test(n)||o==="00000000000000000000000000000000"||n==="0000000000000000"))return{parentSpanId:n,sampled:(Number.parseInt(s,16)&1)===1,traceId:o}},_=(e,r)=>typeof r=="boolean"?{key:e,value:{boolValue:r}}:typeof r=="number"?Number.isFinite(r)?Number.isSafeInteger(r)?{key:e,value:{intValue:String(r)}}:{key:e,value:{doubleValue:r}}:{key:e,value:{stringValue:String(r)}}:{key:e,value:{stringValue:r}},b=e=>e===void 0?[]:Object.entries(e).map(([r,t])=>_(r,t)),C=(e,r,t)=>{const o={},n=new Map,s=(c,i)=>{const g=c.toLowerCase(),m=n.get(g);m===void 0?(n.set(g,c),o[c]=i):o[m]=i};for(const[c,i]of Object.entries(e))s(c,i);for(const[c,i]of Object.entries(r??{}))s(c,i);return t!==void 0&&t.length>0&&s("authorization",`Bearer ${t}`),o},f=e=>Array.isArray(e)?e:[e],L={client:3,consumer:5,internal:1,producer:4,server:2},h=Object.freeze({durationMs:"lunora.duration_ms",errorMessage:"error.message",errorType:"error.type",functionPath:"lunora.function_path",ok:"lunora.ok",shardKey:"lunora.shard_key",userId:"lunora.user_id"}),p=(e,r)=>{const t={"service.name":e};for(const[o,n]of Object.entries(r??{}))t[o]=n;return Object.entries(t).map(([o,n])=>_(o,n))},V=(e,r,t,o)=>({resourceSpans:[{resource:{attributes:p(t,o)},scopeSpans:[{scope:{name:r},spans:f(e)}]}]}),M=(e,r,t,o)=>({resourceLogs:[{resource:{attributes:p(t,o)},scopeLogs:[{logRecords:f(e),scope:{name:r}}]}]}),y=(e,r,t,o)=>({resourceMetrics:[{resource:{attributes:p(t,o)},scopeMetrics:[{metrics:f(e),scope:{name:r}}]}]}),E="CF_VERSION_METADATA",d=(e,r)=>{if(typeof e!="object"||e===null)return;const t=e[r];return typeof t=="string"&&t.length>0?t:void 0},w=e=>r=>{const t=e?.[r];if(typeof t=="string")return t.length>0?t:void 0;if(r===E)return d(t,"tag")??d(t,"id")},D=e=>{const r={},t=e("SERVICE_VERSION")??e("CF_VERSION_METADATA")??e("VERCEL_GIT_COMMIT_SHA")??e("GITHUB_SHA")??e("COMMIT_SHA");t!==void 0&&(r["service.version"]=t);const o=e("DEPLOYMENT_ENVIRONMENT")??e("ENVIRONMENT")??e("NODE_ENV");return o!==void 0&&(r["deployment.environment"]=o),r},x=(e,r)=>{if(!(r!==void 0||e("CLOUDFLARE")!==void 0||e("CF_ACCOUNT_ID")!==void 0))return{};const o={"cloud.provider":"cloudflare"},n=d(r,"colo")??e("CF_COLO")??e("CLOUDFLARE_COLO");return n!==void 0&&(o["cloud.region"]=n),o},F=(...e)=>{const r={};for(const t of e)if(t!==void 0)for(const[o,n]of Object.entries(t))r[o]=n;return r};export{h as L,L as O,D as a,S as b,N as c,x as d,_ as e,R as f,b as g,C as h,y as i,M as j,F as m,T as o,I as p,w as r,V as w};
@@ -1 +1 @@
1
- import{a as i}from"./base64-Bl1_r2k1.mjs";import{d as f,i as s}from"./wire-codec-BX_-4Tmg.mjs";const o=r=>{if(typeof r=="bigint")return r.toString();if(r instanceof ArrayBuffer)return i(new Uint8Array(r));if(ArrayBuffer.isView(r))return i(new Uint8Array(r.buffer,r.byteOffset,r.byteLength));if(Array.isArray(r))return r.map(t=>o(t));if(s(r)){const t={};for(const e of Object.keys(r)){const n=o(r[e]);e==="__proto__"?Object.defineProperty(t,e,{configurable:!0,enumerable:!0,value:n,writable:!0}):t[e]=n}return t}return r},y=r=>o(f(r));export{y as t};
1
+ import{a as i}from"./base64-Bl1_r2k1.mjs";import{d as f,i as s}from"./wire-codec-BLvSm5Mn.mjs";const o=r=>{if(typeof r=="bigint")return r.toString();if(r instanceof ArrayBuffer)return i(new Uint8Array(r));if(ArrayBuffer.isView(r))return i(new Uint8Array(r.buffer,r.byteOffset,r.byteLength));if(Array.isArray(r))return r.map(t=>o(t));if(s(r)){const t={};for(const e of Object.keys(r)){const n=o(r[e]);e==="__proto__"?Object.defineProperty(t,e,{configurable:!0,enumerable:!0,value:n,writable:!0}):t[e]=n}return t}return r},y=r=>o(f(r));export{y as t};
@@ -0,0 +1 @@
1
+ import{c as S,d as T,e as O,a as B,f as P}from"./rest-cache-D1BlbZb1.mjs";import{LunoraError as h}from"./LunoraError-DksAgIpa.mjs";import{m as D}from"./method-guard-BG_vJNTl.mjs";const w=1048576,k=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),U=async(e,r=w)=>{if(!e.body)return"";const t=e.body.getReader(),a=new TextDecoder;let i=0,s="";for(;;){const{done:o,value:n}=await t.read();if(o)break;if(n){if(i+=n.byteLength,i>r)throw await t.cancel().catch(()=>{}),new h("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});s+=a.decode(n,{stream:!0})}}return s+=a.decode(),s},z=async(e,r=w)=>{if(!e.body)return new ArrayBuffer(0);const t=e.body.getReader(),a=[];let i=0;for(;;){const{done:n,value:c}=await t.read();if(n)break;if(c){if(i+=c.byteLength,i>r)throw await t.cancel().catch(()=>{}),new h("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});a.push(c)}}const s=new Uint8Array(i);let o=0;for(const n of a)s.set(n,o),o+=n.byteLength;return s.buffer},j=async(e,r,t=w)=>{try{const a=await U(e,t);return a===""?{}:JSON.parse(a)}catch(a){throw a instanceof h?a:new h(`${r} body must be valid JSON`,{code:"BAD_REQUEST",status:400})}},Z=async(e,r=w)=>{const t=await j(e,"Request",r);if(!k(t))throw new h("Request body must be an object",{code:"BAD_REQUEST",status:400});return t},C=(e,r)=>{if(!k(e))throw new h(`${r} \`args\` must be an object`,{code:"BAD_REQUEST",status:400})},b="__lunora_vary",x="x-lunora-edge-cache",G=["x-d1-bookmark","x-lunora-shard-key"],M=()=>{try{return globalThis.caches?.default}catch{return}},_=e=>e.split(",").map(r=>r.trim().toLowerCase()).filter(r=>r!==""),J=(e,r)=>{const t=e.headers.get("vary");return t===null?!0:_(t).every(a=>a!=="*"&&r.includes(a))},K=(e,r)=>{if(e===void 0||r===null||e.scope!=="public"||S(e.maxAge)<=0)return;const t=()=>r??M(),a=_(T(e)??""),i=o=>{const n=new URL(o.url);return n.searchParams.delete(b),a.length>0&&n.searchParams.set(b,a.map(c=>`${c}=${o.headers.get(c)??""}`).join("\0")),new Request(n.toString(),{method:"GET"})},s=(o,n)=>o.method==="GET"&&O(e,o,n)==="public";return{lookup:async(o,n)=>{const c=t();if(c===void 0||!s(o,n))return;let u;try{u=await c.match(i(o))}catch{return}if(u===void 0)return;const l=new Response(u.body,u);return l.headers.set(x,"hit"),l},store:(o,n,c)=>{const u=t();if(u===void 0||!s(n,c)||o.status!==200||o.headers.has("set-cookie")||o.headers.has("x-payment-response")||!J(o,a))return o;try{const l=new Response(o.clone().body,o);for(const R of G)l.headers.delete(R);const d=Promise.resolve(u.put(i(n),l)).catch(()=>{});c?.waitUntil&&c.waitUntil(d)}catch{}return o}}},N=()=>globalThis.navigator?.userAgent==="Cloudflare-Workers",Y=e=>N()?e.get("cf-connecting-ip")??void 0:void 0,F=e=>P(Object.entries(e).map(([r,t])=>({exposure:t.expose,functionPath:r,kind:t.kind}))),H=(e,r)=>{const t=e.searchParams.get("shardKey");if(t!==null&&t!=="")return t;const a=r.headers.get("x-lunora-shard-key");return a===null||a===""?void 0:a},I=e=>{const r=Object.create(null);for(const[t,a]of e.searchParams.entries())if(!(t==="shardKey"||t===b))try{r[t]=JSON.parse(a)}catch{r[t]=a}return r},q=e=>{const{edgeCache:r,functions:t,invoke:a,rateLimit:i,readJsonBody:s}=e,o={};for(const n of F(t)){const c=n.kind==="query"?["GET","POST"]:["POST"],u=t[n.functionPath].expose?.cache,l=K(u,r);o[n.path]=async(d,R,V,f)=>{const g=D(d,c);if(g)return g;const E=new URL(d.url);if(i){const m=await i(d,n.functionPath);if(m)return m}const v=await l?.lookup(d,f);if(v)return v;let y;d.method==="GET"?y=I(E):y=d.body===null?{}:await s(d),C(y,"REST");const p=H(E,d),L=await a({args:y,env:R,functionPath:n.functionPath,request:d,...p===void 0?{}:{shardKey:p},...f?.waitUntil===void 0?{}:{waitUntil:m=>f.waitUntil?.(m)}}),A=B(L,u,d,f);return l?l.store(A,d,f):A}}return o},Q="no-trusted-ip",ee=(e,r)=>async(t,a)=>{const i=(r.key?r.key(t,a):Y(t.headers))??Q,s=await e.limit(r.name,{key:i});if(s.ok)return;if(s.reason==="deny")return Response.json({error:{code:"FORBIDDEN",message:"Request denied"}},{headers:{"content-type":"application/json"},status:403});const o=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(o)},status:429})};export{w as M,I as a,q as b,ee as c,Z as d,j as e,z as f,C as g,U as h,F as r,Y as t};
@@ -1 +1 @@
1
- import{t as b}from"./portable-json-DcwKZHQ7.mjs";const p="_id",f=(t,n=p)=>{const o=Object.create(null),s=Object.create(null),c=Object.create(null),a=Object.create(null),h=e=>typeof n=="string"?n:n[e]??p,l=(e,r)=>{const u=e[r];if(u)return u;const d=[];return e[r]=d,d};for(const e of t.changes){a[e.table]??={primary_key:[h(e.table)]};const r=b(e.doc);e.op==="delete"?l(c,e.table).push(r):e.op==="update"?l(s,e.table).push(r):l(o,e.table).push(r)}return{delete:c,hasMore:t.hasMore,insert:o,schema:a,state:{cursor:t.nextCursor},update:s}},m=(t,n=Date.now())=>{const o=[];for(const s of t.changes){const c=b(s.doc),a=s.op==="delete"?{...c,_lunora_deleted:!0}:c;o.push({record:{data:a,emitted_at:n,stream:s.table},type:"RECORD"})}return o.push({state:{data:{cursor:t.nextCursor}},type:"STATE"}),o};export{m as toAirbyteMessages,f as toFivetranResponse};
1
+ import{t as b}from"./portable-json-BSCiOfqE.mjs";const p="_id",f=(t,n=p)=>{const o=Object.create(null),s=Object.create(null),c=Object.create(null),a=Object.create(null),h=e=>typeof n=="string"?n:n[e]??p,l=(e,r)=>{const u=e[r];if(u)return u;const d=[];return e[r]=d,d};for(const e of t.changes){a[e.table]??={primary_key:[h(e.table)]};const r=b(e.doc);e.op==="delete"?l(c,e.table).push(r):e.op==="update"?l(s,e.table).push(r):l(o,e.table).push(r)}return{delete:c,hasMore:t.hasMore,insert:o,schema:a,state:{cursor:t.nextCursor},update:s}},m=(t,n=Date.now())=>{const o=[];for(const s of t.changes){const c=b(s.doc),a=s.op==="delete"?{...c,_lunora_deleted:!0}:c;o.push({record:{data:a,emitted_at:n,stream:s.table},type:"RECORD"})}return o.push({state:{data:{cursor:t.nextCursor}},type:"STATE"}),o};export{m as toAirbyteMessages,f as toFivetranResponse};
@@ -0,0 +1 @@
1
+ import{a as d,b as E}from"./base64-Bl1_r2k1.mjs";const o="$lunora.wire$",w=64,p=1024,g="__proto__",l={BigInt64Array,BigUint64Array,Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array},A={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError},O=e=>{if(e===null||typeof e!="object")return!1;const n=Object.getPrototypeOf(e);return n===null||n===Object.prototype},u=(e,n=0)=>{if(n>w)throw new RangeError(`wire-codec: value nesting exceeds the ${w}-level limit`);if(e===void 0)return[o,"undefined"];if(e===null)return null;const b=typeof e;if(b==="bigint")return[o,"bigint",e.toString()];if(b==="number"){const r=e;return Number.isNaN(r)?[o,"nan"]:r===1/0?[o,"inf"]:r===-1/0?[o,"-inf"]:r}if(b!=="object")return e;if(e instanceof Date)return[o,"date",u(e.getTime(),n+1)];if(e instanceof Error){const r=e,t={};for(const i of Object.keys(r)){if(r[i]===void 0)continue;const y=u(r[i],n+1);i===g?Object.defineProperty(t,i,{configurable:!0,enumerable:!0,value:y,writable:!0}):t[i]=y}const s=[o,"error",String(r.name),String(r.message),t];return r.cause!==void 0&&s.push(u(r.cause,n+1)),s}if(e instanceof URL)return[o,"url",e.href];if(e instanceof Map)return[o,"map",[...e.entries()].map(([r,t])=>[u(r,n+1),u(t,n+1)])];if(e instanceof Set)return[o,"set",[...e].map(r=>u(r,n+1))];if(e instanceof ArrayBuffer)return[o,"bytes",d(new Uint8Array(e)),"ArrayBuffer"];if(ArrayBuffer.isView(e)){const r=e,t=r.constructor.name,s=new Uint8Array(r.buffer,r.byteOffset,r.byteLength);return t==="Uint8Array"?[o,"bytes",d(s)]:[o,"bytes",d(s),t]}if(Array.isArray(e)){const r=e.map(t=>u(t,n+1));return r.length>0&&r[0]===o?[o,"arr",r]:r}if(!O(e)){const r=e.constructor?.name??"value";throw new TypeError(`wire-codec: cannot encode a ${r} over the Lunora wire — only plain objects, arrays, and the supported built-ins (Date, Error, URL, Map, Set, ArrayBuffer/typed arrays, bigint) round-trip`)}const c=e,a={};for(const r of Object.keys(c)){const t=c[r];if(t===void 0)continue;const s=u(t,n+1);r===g?Object.defineProperty(a,r,{configurable:!0,enumerable:!0,value:s,writable:!0}):a[r]=s}return a},f=(e,n=0)=>{if(n>w)throw new RangeError(`wire-codec: value nesting exceeds the ${w}-level limit`);if(e===null||typeof e!="object")return e;if(Array.isArray(e)){if(e[0]===o)switch(e[1]){case"-inf":return-1/0;case"arr":return e[2].map(r=>f(r,n+1));case"bigint":{const r=e[2];if(typeof r!="string"||r.length>p||!/^-?\d+$/.test(r))throw new RangeError(`wire-codec: invalid or over-long bigint (max ${p} digits)`);return BigInt(r)}case"date":{const r=f(e[2],n+1);if(typeof r!="number")throw new TypeError("wire-codec: malformed date — epoch must be a number");return new Date(r)}case"map":{const r=e[2];return new Map(r.map(t=>{if(!Array.isArray(t)||t.length!==2)throw new TypeError("wire-codec: malformed map entry — expected a [key, value] pair");return[f(t[0],n+1),f(t[1],n+1)]}))}case"set":return new Set(e[2].map(r=>f(r,n+1)));case"url":{const r=e[2];if(typeof r!="string")throw new TypeError("wire-codec: malformed url — href must be a string");return new URL(r)}case"error":{const r=e[2],t=e[3];if(typeof r!="string"||typeof t!="string")throw new TypeError("wire-codec: malformed error — name and message must be strings");const s=(Object.hasOwn(A,r)?A[r]:void 0)??Error,i=new s(t);i.name!==r&&Object.defineProperty(i,"name",{configurable:!0,value:r,writable:!0});const y=f(e[4],n+1);if(y===null||typeof y!="object"||Array.isArray(y))throw new TypeError("wire-codec: malformed error — props must be an object");for(const m of Object.keys(y))m===g?Object.defineProperty(i,m,{configurable:!0,enumerable:!0,value:y[m],writable:!0}):i[m]=y[m];return e.length>5&&Object.defineProperty(i,"cause",{configurable:!0,value:f(e[5],n+1),writable:!0}),i}case"bytes":{const r=e[2];if(typeof r!="string")throw new TypeError("wire-codec: malformed bytes — payload must be a base64 string");const t=E(r);if(d(t)!==r)throw new TypeError("wire-codec: malformed bytes — payload must be canonical padded base64");const s=e[3]??"Uint8Array";if(s==="ArrayBuffer")return t.buffer.byteLength===t.byteLength?t.buffer:t.slice().buffer;const i=Object.hasOwn(l,s)?l[s]:void 0;return i?new i(t.slice().buffer):t}case"inf":return 1/0;case"nan":return Number.NaN;case"undefined":return;default:return e.map(r=>f(r,n+1))}return e.map(a=>f(a,n+1))}const b=e,c={};for(const a of Object.keys(b)){const r=f(b[a],n+1);a===g?Object.defineProperty(c,a,{configurable:!0,enumerable:!0,value:r,writable:!0}):c[a]=r}return c},T=(e,n,b)=>{try{return u(b)}catch(c){throw new TypeError(`${e}: cannot encode args for '${n}' — ${c instanceof Error?c.message:String(c)}`,c instanceof Error?{cause:c}:void 0)}};export{T as a,f as d,u as e,O as i};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/runtime",
3
- "version": "1.0.0-alpha.96",
3
+ "version": "1.0.0-alpha.98",
4
4
  "description": "Lunora Worker runtime: the RPC router, shard resolver, and query coordinator",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -46,9 +46,9 @@
46
46
  "access": "public"
47
47
  },
48
48
  "dependencies": {
49
- "@lunora/bindings": "1.0.0-alpha.51",
50
- "@lunora/errors": "1.0.0-alpha.32",
51
- "@lunora/observability": "1.0.0-alpha.58",
49
+ "@lunora/bindings": "1.0.0-alpha.53",
50
+ "@lunora/errors": "1.0.0-alpha.34",
51
+ "@lunora/observability": "1.0.0-alpha.59",
52
52
  "@lunora/platform": "1.0.0-alpha.27"
53
53
  },
54
54
  "peerDependencies": {
@@ -1,6 +0,0 @@
1
- import{isLunoraError as Hn,toErrorBody as Ln}from"@lunora/errors";import{e as Lt}from"./evict-oldest-BNXsKx4s.mjs";import{NOOP_EXECUTION_CONTEXT as Mn}from"./NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{t as $n,f as jn}from"./base64-Bl1_r2k1.mjs";import{e as Kn,a as Fn}from"./identity-header-C4Z5pldl.mjs";import{o as Ie,b as Gn,p as Qn,m as zn,d as Wn,a as Vn,r as Jn}from"./otlp-resource-DeXhb949.mjs";import{e as ke,d as Mt}from"./wire-codec-BX_-4Tmg.mjs";import{d as te,e as he,M as $t,b as qn,f as Yn,g as jt,h as Kt}from"./rest-routes-BbMQwlSV.mjs";import{LunoraError as d,toErrorResponse as ct}from"./LunoraError-DksAgIpa.mjs";import{a as $,m as we}from"./method-guard-BG_vJNTl.mjs";import{normalizeBackupPrefix as Ye,BACKUP_KEY_PREFIX as Xe,isBackupManifestKey as Xn,backupObjectKeyOfManifest as Ft,backupObjectKey as Zn,backupManifestKey as er}from"./BACKUP_KEY_PREFIX-BOtSu-_3.mjs";import{toHex as tr,buildStorageAdminRoutes as nr,STORAGE_UPLOAD_MAX_BODY_BYTES as rr,STORAGE_PATH as or}from"./STORAGE_UPLOAD_MAX_BODY_BYTES-BqyO-1l6.mjs";import{b as ar,e as sr,f as dt,g as ir,h as cr}from"./export-tap-mRfLykiL.mjs";import{buildHealthRoutes as dr,durableObjectProbe as ur,d1Probe as lr,presenceProbe as Le}from"./HEALTH_PATH-D0i8LhwT.mjs";import{wrapResolverWithContract as hr}from"./composeIdentityResolvers-BHZ4jH8o.mjs";import{composeIdentityResolvers as Hs,routeIdentityResolvers as Ls}from"./composeIdentityResolvers-BHZ4jH8o.mjs";import{buildLogArchiveAdminRoutes as fr}from"./LOG_ARCHIVE_PATH-Hmjpz_Ko.mjs";import{r as pr,f as ut,a as ce}from"./observability-B1hLjwgx.mjs";import{resolveShard as ge,applyJurisdiction as lt}from"./applyJurisdiction-C0ddU7Tg.mjs";import{resolveSecurity as ht,handleCorsPreflight as mr,enforceOrigin as wr,decorateResponse as Me,enforceWebSocketOrigin as ft}from"./decorateResponse-Y2sCM0w1.mjs";const gr=e=>{const t=e??{};if(typeof t.bucket=="function")return t;const n=t.bucketName,a={...t,bucketName:typeof n=="string"&&n!==""?n:"default"};return a.bucket=()=>a,a},Gt="__lunoraBranch",yr=e=>typeof e=="object"&&e!==null&&Object.hasOwn(e,Gt),br=`may not contain the reserved workflow branch-marker key ("${Gt}")`,_r=async e=>{const t=[];let n;for(;;){const r=await e(n);if(t.push(...Array.isArray(r.records)?r.records:[]),r.truncated!==!0||typeof r.cursor!="string"||r.cursor.length===0)return t;if(r.cursor===n)throw new Error("collectPages: the list did not advance its cursor — refusing to page forever");n=r.cursor}},Ze=(e,t)=>{const n=Math.max(e.length,t.length);let r=e.length^t.length;for(let a=0;a<n;a+=1){const i=a<e.length?e.charCodeAt(a):0,u=a<t.length?t.charCodeAt(a):0;r|=i^u}return r===0},Rr=/already[\s_-]?exists/iu,Er=e=>Rr.test(e instanceof Error?e.message:String(e)),Sr=(e,t,n,r)=>{const a=e.get(t);if(a!==void 0)return a;Lt(e,r);const i=n().catch(u=>{throw e.get(t)===i&&e.delete(t),u});return e.set(t,i),i},et=new TextEncoder,Ar=Array.from({length:32},(e,t)=>t);new RegExp(`[${Ar.map(e=>String.fromCodePoint(e)).join("")}]`,"u");const Tr=64,Or=new Map,Qt=async e=>Sr(Or,e,async()=>crypto.subtle.importKey("raw",et.encode(e),{hash:"SHA-256",name:"HMAC"},!1,["sign","verify"]),Tr),zt=async(e,t)=>{const n=await Qt(e),r=await crypto.subtle.sign("HMAC",n,et.encode(t));return $n(new Uint8Array(r))},vr=async(e,t,n)=>{const r=await Qt(e);return crypto.subtle.verify("HMAC",r,n,et.encode(t))},kr=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"];new Set(kr);const Ir=new Set(["AE","BH","IL","IQ","IR","JO","KW","LB","OM","PS","QA","SA","SY","TR","YE"]),Pr=-100,Nr=15,Dr=e=>{const t=Number(e.longitude??Number.NaN);switch(e.continent){case"AF":return"afr";case"AS":return e.country!==void 0&&Ir.has(e.country)?"me":"apac";case"EU":return Number.isFinite(t)&&t>Nr?"eeur":"weur";case"NA":return Number.isFinite(t)&&t<Pr?"wnam":"enam";case"OC":return"oc";case"SA":return"sam";default:return}},pt=e=>{const t=e.cf;return t===void 0?void 0:Dr(t)},Ve="::relay::",Ur=(e,t)=>`${e}${Ve}${String(t)}`,Je="::replica::",Cr=(e,t)=>`${e}${Je}${t}`,Br=e=>{if(e==null||!/^\d+$/.test(e))return;const t=Number.parseInt(e,10);return Number.isSafeInteger(t)&&t>0?t:void 0},xr=new Set(["1","enabled","on","true","yes"]),Hr=new Set(["0","disabled","false","no","off"]),Lr=(e,t)=>{const n=(e??"").trim().toLowerCase();return xr.has(n)?!0:Hr.has(n)?!1:t},Wt="v1",Mr=6e4,$r=async(e,t={})=>{const n=(t.now??Date.now())+(t.ttlMs??Mr),r=`${Wt}.${String(n)}`,a=await zt(e,r);return{expiresAtMs:n,token:`${r}.${a}`}},jr=async(e,t,n=Date.now())=>{if(e.length===0||t.length===0)return!1;const r=t.split(".");if(r.length!==3)return!1;const[a,i,u]=r;if(a!==Wt||u.length===0)return!1;const h=Number(i);if(!Number.isFinite(h)||h<=n)return!1;let p;try{p=jn(u)}catch{return!1}return vr(e,`${a}.${i}`,p)},k="/_lunora/admin/auth",Kr={INVITER_REQUIRED:400,ORG_SLUG_INVALID:400,ORG_SLUG_TAKEN:409,PASSWORD_TOO_LONG:400,PASSWORD_TOO_SHORT:400,USER_ALREADY_EXISTS:409,USER_NOT_FOUND:404},N=(e,t)=>{const n=e[t];if(typeof n!="string"||n==="")throw new d(`\`${t}\` is required`,{code:"BAD_REQUEST",status:400});return n},le=(e,t)=>{const n=e(t);if(n===void 0)throw new d(`\`${t}\` query parameter is required`,{code:"BAD_REQUEST",status:400});return n},Vt=e=>{if(typeof e=="string"||Array.isArray(e)&&e.every(t=>typeof t=="string"))return e},re=(e,t)=>typeof e[t]=="string"?e[t]:void 0,$e=(e,t)=>{const n=e[t];return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:void 0},mt=e=>{const t=Vt(e.role);if(t===void 0||typeof t=="string"&&t.trim()==="")throw new d("`role` is required",{code:"BAD_REQUEST",status:400});return t},wt=e=>{const t=e.permission;if(typeof t!="object"||t===null||Array.isArray(t))throw new d("`permission` object is required",{code:"BAD_REQUEST",status:400});const n={};for(const[r,a]of Object.entries(t))Array.isArray(a)&&a.every(i=>typeof i=="string")&&(n[r]=a);return n},Fr={[`${k}/capabilities`]:{build:()=>({}),http:"GET",method:"capabilities"},[`${k}/users`]:{build:({paging:e,query:t})=>{const n=t("sortDirection");return{...e,filterField:t("filterField"),filterValue:t("filterValue"),search:t("search"),searchField:t("searchField"),sortBy:t("sortBy"),sortDirection:n==="asc"||n==="desc"?n:void 0}},http:"GET",method:"listUsers"},[`${k}/sessions`]:{build:({paging:e,query:t})=>({...e,userId:t("userId")}),http:"GET",method:"listSessions"},[`${k}/accounts`]:{build:({query:e})=>({userId:le(e,"userId")}),http:"GET",method:"listAccounts"},[`${k}/passkeys`]:{build:({query:e})=>({userId:le(e,"userId")}),http:"GET",method:"listPasskeys"},[`${k}/organizations`]:{build:({paging:e})=>({...e}),http:"GET",method:"listOrganizations"},[`${k}/organizations/members`]:{build:({paging:e,query:t})=>({...e,organizationId:le(t,"organizationId")}),http:"GET",method:"listMembers"},[`${k}/organizations/invitations`]:{build:({paging:e,query:t})=>({...e,organizationId:le(t,"organizationId")}),http:"GET",method:"listInvitations"},[`${k}/sign-up-invitations`]:{build:({paging:e})=>({...e}),http:"GET",method:"listSignUpInvitations"},[`${k}/sign-up-invitations/create`]:{build:({body:e})=>({email:N(e,"email"),expiresInSeconds:typeof e.expiresInSeconds=="number"?e.expiresInSeconds:void 0,invitedBy:re(e,"invitedBy")}),http:"POST",method:"createSignUpInvitation"},[`${k}/sign-up-invitations/revoke`]:{build:({body:e})=>({email:N(e,"email")}),http:"POST",method:"revokeSignUpInvitation",returns:"void"},[`${k}/config`]:{build:()=>({}),http:"GET",method:"config"},[`${k}/organizations/teams`]:{build:({paging:e,query:t})=>({...e,organizationId:le(t,"organizationId")}),http:"GET",method:"listTeams"},[`${k}/organizations/teams/members`]:{build:({paging:e,query:t})=>({...e,teamId:le(t,"teamId")}),http:"GET",method:"listTeamMembers"},[`${k}/organizations/roles`]:{build:({paging:e,query:t})=>({...e,organizationId:le(t,"organizationId")}),http:"GET",method:"listOrgRoles"},[`${k}/users/create`]:{build:({body:e})=>({data:$e(e,"data"),email:N(e,"email"),name:N(e,"name"),password:re(e,"password"),role:Vt(e.role)}),http:"POST",method:"createUser"},[`${k}/users/update`]:{build:({body:e})=>{const{data:t}=e;if(typeof t!="object"||t===null||Array.isArray(t))throw new d("`data` object is required",{code:"BAD_REQUEST",status:400});return{data:t,userId:N(e,"userId")}},http:"POST",method:"updateUser"},[`${k}/users/role`]:{build:({body:e})=>({role:mt(e),userId:N(e,"userId")}),http:"POST",method:"setRole"},[`${k}/users/ban`]:{build:({body:e})=>({expiresInSeconds:typeof e.expiresInSeconds=="number"?e.expiresInSeconds:void 0,reason:re(e,"reason"),userId:N(e,"userId")}),http:"POST",method:"banUser"},[`${k}/users/unban`]:{build:({body:e})=>({userId:N(e,"userId")}),http:"POST",method:"unbanUser"},[`${k}/users/password`]:{build:({body:e})=>({newPassword:N(e,"newPassword"),userId:N(e,"userId")}),http:"POST",method:"setUserPassword",returns:"void"},[`${k}/users/remove`]:{build:({body:e})=>({userId:N(e,"userId")}),http:"POST",method:"removeUser",returns:"void"},[`${k}/users/impersonate`]:{build:({body:e})=>({userId:N(e,"userId")}),http:"POST",method:"impersonateUser"},[`${k}/sessions/revoke`]:{build:({body:e})=>({sessionId:N(e,"sessionId")}),http:"POST",method:"revokeUserSession",returns:"void"},[`${k}/sessions/revoke-all`]:{build:({body:e})=>({userId:N(e,"userId")}),http:"POST",method:"revokeUserSessions",returns:"void"},[`${k}/accounts/unlink`]:{build:({body:e})=>({accountId:N(e,"accountId"),userId:N(e,"userId")}),http:"POST",method:"unlinkAccount",returns:"void"},[`${k}/two-factor/disable`]:{build:({body:e})=>({userId:N(e,"userId")}),http:"POST",method:"disableTwoFactor",returns:"void"},[`${k}/passkeys/delete`]:{build:({body:e})=>({passkeyId:N(e,"passkeyId")}),http:"POST",method:"deletePasskey",returns:"void"},[`${k}/organizations/members/remove`]:{build:({body:e})=>({memberId:N(e,"memberId")}),http:"POST",method:"removeMember",returns:"void"},[`${k}/organizations/invitations/cancel`]:{build:({body:e})=>({invitationId:N(e,"invitationId")}),http:"POST",method:"cancelInvitation",returns:"void"},[`${k}/organizations/create`]:{build:({body:e})=>({logo:re(e,"logo"),metadata:$e(e,"metadata"),name:N(e,"name"),ownerId:re(e,"ownerId"),slug:re(e,"slug")}),http:"POST",method:"createOrganization"},[`${k}/organizations/update`]:{build:({body:e})=>({logo:re(e,"logo"),metadata:$e(e,"metadata"),name:re(e,"name"),organizationId:N(e,"organizationId"),slug:re(e,"slug")}),http:"POST",method:"updateOrganization"},[`${k}/organizations/remove`]:{build:({body:e})=>({organizationId:N(e,"organizationId")}),http:"POST",method:"deleteOrganization",returns:"void"},[`${k}/organizations/members/add`]:{build:({body:e})=>({organizationId:N(e,"organizationId"),role:re(e,"role"),userId:N(e,"userId")}),http:"POST",method:"addMember"},[`${k}/organizations/members/invite`]:{build:({body:e})=>({email:N(e,"email"),inviterId:re(e,"inviterId"),organizationId:N(e,"organizationId"),role:re(e,"role")}),http:"POST",method:"inviteMember"},[`${k}/organizations/members/role`]:{build:({body:e})=>({memberId:N(e,"memberId"),role:mt(e)}),http:"POST",method:"updateMemberRole"},[`${k}/organizations/teams/create`]:{build:({body:e})=>({name:N(e,"name"),organizationId:N(e,"organizationId")}),http:"POST",method:"createTeam"},[`${k}/organizations/teams/update`]:{build:({body:e})=>({name:N(e,"name"),teamId:N(e,"teamId")}),http:"POST",method:"updateTeam"},[`${k}/organizations/teams/remove`]:{build:({body:e})=>({teamId:N(e,"teamId")}),http:"POST",method:"removeTeam",returns:"void"},[`${k}/organizations/teams/members/add`]:{build:({body:e})=>({teamId:N(e,"teamId"),userId:N(e,"userId")}),http:"POST",method:"addTeamMember"},[`${k}/organizations/teams/members/remove`]:{build:({body:e})=>({teamMemberId:N(e,"teamMemberId")}),http:"POST",method:"removeTeamMember",returns:"void"},[`${k}/organizations/roles/create`]:{build:({body:e})=>({organizationId:N(e,"organizationId"),permission:wt(e),role:N(e,"role")}),http:"POST",method:"createOrgRole"},[`${k}/organizations/roles/update`]:{build:({body:e})=>({permission:wt(e),roleId:N(e,"roleId")}),http:"POST",method:"updateOrgRole"},[`${k}/organizations/roles/remove`]:{build:({body:e})=>({roleId:N(e,"roleId")}),http:"POST",method:"deleteOrgRole",returns:"void"}},Gr=e=>{const t=async a=>{try{return await a()}catch(i){if(i instanceof d)throw i;const u=i,h=typeof u.code=="string"?u.code:"AUTH_ADMIN_ERROR";throw console.error("[lunora] auth admin operation failed:",i),new d("auth admin operation failed",{code:h,status:Kr[h]??500})}},n=async(a,i)=>{if(e.assertAdmin(a),a.method!==i.http)throw new d(`Auth admin endpoint requires ${i.http}`,{code:"METHOD_NOT_ALLOWED",status:405});const u=e.getAuthAdmin();if(u===void 0)throw new d("auth endpoints require an `authAdmin` on the worker",{code:"AUTH_NOT_CONFIGURED",status:400});const h=u[i.method];if(h===void 0)throw new d(`auth admin does not support \`${i.method}\``,{code:"AUTH_OP_NOT_SUPPORTED",status:400});const p=new URL(a.url),m={body:i.http==="POST"?await e.readJsonBody(a):{},paging:e.parsePaging(a),query:T=>e.queryParameter(p,T)},S=i.build(m),A=await t(()=>h(S));return Response.json(i.returns==="void"?{ok:!0}:A,{headers:{"cache-control":"no-store","content-type":"application/json"},status:200})},r={};for(const[a,i]of Object.entries(Fr))r[a]=u=>n(u,i);return r},gt="__lunora_admin__:getAuthAuditLog",yt=e=>typeof e=="string"&&e!==""?e:void 0,bt=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0,Qr=e=>async(n,r)=>{e.assertAdmin(n);const a=e.getReader();if(a===void 0)throw new d("the auth/security audit endpoint requires an `authAuditReader` on the worker",{code:"AUTH_AUDIT_NOT_CONFIGURED",status:400});const i=yt(r.actorId),u=yt(r.event),h=bt(r.sinceSeq),p=bt(r.limit),m={...i===void 0?{}:{actorId:i},...u===void 0?{}:{event:u},...h===void 0?{}:{sinceSeq:h},...p===void 0?{}:{limit:p}};let S;try{S=await a.read(m)}catch(T){throw T instanceof d?T:(console.error("[lunora] auth audit read failed:",T),new d("auth audit read failed",{code:"AUTH_AUDIT_READ_FAILED",status:500}))}const A={entries:S};return Response.json({result:ke(A)},{headers:{"content-type":"application/json"},status:200})},zr=(e,t)=>{const n=[],r=[];if(t&&t.length>0)for(const a of t)e.resolveTableSharding?.(a)?.mode.kind==="global"?r.push(a):n.push(a);return{globalTables:r,shardLocalTables:n}},Wr=async(e,t,n,r,a,i,u)=>{if(n!==void 0&&r.length===0)return;const h=await e.orchestrateExport(i,{args:{tables:r},defaultShardKey:u,headers:t,tables:r});for(const p of h.shards)if(!p.error)for(const m of p.rows??[])a(m)},Jt=async(e,t,n,r,a,i)=>{const u=r??e.listSchemaTables?.();r===void 0&&e.listSchemaTables===void 0&&console.warn("[lunora] export: no table list available (`listSchemaTables` is unset and no `tables` were named), so only the default shard is reachable. A `.shardBy()` deployment's other shards will be missing from this export. Name the tables explicitly, or regenerate the worker so codegen supplies the list.");const{globalTables:h,shardLocalTables:p}=zr(e,u);await Wr(t,n,u,p,a,i,e.defaultShardKey??"__root__");const m=e.exportGlobals;if((r===void 0||h.length>0)&&m)for await(const A of m({tables:h}))a(A)},Vr=new TextEncoder,Jr=1e3,qt=10,qr=200,_t=8,Yt="lunoraBackupCron",Rt=24*1048576,Et=e=>{const t=e.slice(0,qt).map(r=>Ft(r)),n=e.length-t.length;return`${t.join(", ")}${n>0?` (+${String(n)} more)`:""}`},Yr=(e,t)=>{const n=new Uint8Array(new ArrayBuffer(t));let r=0;for(const a of e)n.set(a,r),r+=a.byteLength;return n},tt=async(e,t,n,r)=>{if(n===void 0||!Number.isInteger(n)||n<=0)return{eligible:0,stale:[]};const a=[];let i;for(let u=0;u<Jr;u+=1){const h=await e.list({cursor:i,include:["customMetadata"],prefix:t});for(const p of h.objects)Xn(p.key)&&p.customMetadata?.[Yt]===r&&a.push(p.key);if(!h.truncated||h.cursor===void 0)break;i=h.cursor}return{eligible:a.length,stale:a.toSorted((u,h)=>h.localeCompare(u)).slice(n)}},Xr=async(e,t,n,r,a)=>{const{stale:i}=await tt(e,t,n,r),u=new Set(a),h=i.filter(g=>u.has(g)),p=h.slice(0,qr),m=i.length-p.length,S=a.length-h.length;if(p.length===0)return{deleted:[],failed:[],ignored:S,remaining:m};const A=[],T=[];for(let g=0;g<p.length;g+=_t){const b=await Promise.allSettled(p.slice(g,g+_t).map(async R=>(await e.delete(Ft(R)),await e.delete(R),R)));for(const[R,f]of b.entries())f.status==="fulfilled"?A.push(f.value):T.push(p[g+R])}return A.length>0&&console.info(`[lunora] backup prune kept the newest ${String(n)} and deleted ${String(A.length)}: ${Et(A)}`),T.length>0&&console.warn(`[lunora] backup prune failed to remove ${String(T.length)}: ${Et(T)}`),{deleted:A,failed:T,ignored:S,remaining:m}},Zr=async e=>{const t=e.backupStore;if(!t)throw new d("backup retention preview requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});const n=Ye(e.backupPrefix??Xe),r=e.backupCron,{eligible:a,stale:i}=r===void 0?{eligible:0,stale:[]}:await tt(t,n,e.backupRetain,r);return{cron:r,eligible:a,keep:e.backupRetain??0,prefix:n,wouldDelete:i}},eo=async(e,t,n,r)=>{const a=e.backupStore,i=e.queryCoordinator;if(!a)throw new d("scheduled backup requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});if(!i)throw new d("scheduled backup requires a `queryCoordinator` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});if(!n||n.length===0)throw new d("scheduled backup requires an `adminToken` (or `env.LUNORA_ADMIN_TOKEN`) to authenticate the per-shard export gate",{code:"BACKUP_NOT_CONFIGURED",status:500});const u={authorization:`Bearer ${n}`,"content-type":"application/json"},h=e.backupTables;let p=0,m=0,S=[];await Jt(e,i,u,h,U=>{const M=Vr.encode(`${JSON.stringify(U)}
2
- `);if(p+=1,m+=M.byteLength,m>Rt)throw new d(`scheduled backup reached ${String(m)} bytes of NDJSON, past the ${String(Rt)}-byte limit for a snapshot assembled inside a Worker — nothing was written. Narrow it with \`backupTables\`, or take this snapshot off-platform with \`lunora backup create --bucket\`.`,{code:"BACKUP_TOO_LARGE",status:507});S.push(M)},t);const T=Ye(e.backupPrefix??Xe),g=new Date(r.scheduledTime).toISOString(),b=Zn(T,g),R=Yr(S,m);S=[];const f=tr(await crypto.subtle.digest("SHA-256",R));await a.put(b,R,{httpMetadata:{contentType:"application/x-ndjson"},sha256:f});const O={bytes:m,createdAt:g,cron:r.cron,file:b,id:g,rows:p,scheduledTime:r.scheduledTime,sha256:f,...h?{tables:h.join(",")}:{}};await a.put(er(b),`${JSON.stringify(O,void 0,2)}
3
- `,{customMetadata:{[Yt]:r.cron},httpMetadata:{contentType:"application/json"}});try{const{stale:U}=await tt(a,T,e.backupRetain,r.cron);if(U.length>0){const M=U.slice(0,qt),I=U.length-M.length;console.info(`[lunora] backup retention: ${String(U.length)} snapshot(s) past the newest ${String(e.backupRetain)} — run \`lunora backup prune\` to remove them: ${M.join(", ")}${I>0?` (+${String(I)} more)`:""}`)}}catch(U){console.warn(`[lunora] backup ${b} was written, but the retention report failed:`,U)}},to=async(e,t)=>{const n=e.backupStore;if(!n)throw new d("backup prune requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});const r=e.backupCron,a=e.backupRetain;if(r===void 0||a===void 0||!Number.isInteger(a)||a<=0)throw new d("backup prune needs a retention window: set `backupRetain` (and `backupCron`, which decides whose snapshots retention owns) on the worker. Without one there is nothing past the window to remove.",{code:"BACKUP_RETENTION_NOT_CONFIGURED",status:400});return Xr(n,Ye(e.backupPrefix??Xe),a,r,t)},no="/_lunora/admin/backup/retention",ro="/_lunora/admin/backup/prune",oo=e=>{const{options:t,readJsonBody:n,requireAdminOption:r}=e,a=(h,p)=>{r(h,t.backupStore,{code:"BACKUP_NOT_CONFIGURED",message:`backup ${p} requires a \`backupStore\` on the worker`})},i=async h=>($(h,"GET","Backup-retention"),a(h,"retention preview"),Response.json(await Zr(t),{headers:{"cache-control":"no-store"}})),u=async h=>{$(h,"POST","Backup-prune"),a(h,"prune");const{confirm:p}=await n(h);if(!Array.isArray(p)||p.some(m=>typeof m!="string"))throw new d("backup prune requires a `confirm` array of the sidecar keys to remove — read them from `GET /_lunora/admin/backup/retention` and pass back the ones you mean to delete",{code:"BAD_REQUEST",status:400});return Response.json(await to(t,p),{headers:{"cache-control":"no-store"}})};return{[ro]:u,[no]:i}},St=500,ao=(e,t,n)=>{if(typeof e!="object"||e===null||Array.isArray(e))throw new d("each batch call must be an object",{code:"BAD_REQUEST",status:400});const r=e;if(typeof r.functionPath!="string")throw new d("each batch call needs a string `functionPath`",{code:"BAD_REQUEST",status:400});if(r.functionPath.startsWith("__lunora_relation__:")||r.functionPath.startsWith("__lunora_admin__"))throw new d("reserved function path cannot be batched",{code:"FORBIDDEN",status:403});if(r.args!==void 0&&(typeof r.args!="object"||r.args===null||Array.isArray(r.args)))throw new d("each batch call `args` must be an object",{code:"BAD_REQUEST",status:400});return{entry:{args:r.args===void 0?{}:r.args,clientId:typeof r.clientId=="string"?r.clientId:void 0,clientSeq:typeof r.clientSeq=="number"?r.clientSeq:void 0,functionPath:r.functionPath,id:typeof r.id=="number"?r.id:t,mutationId:typeof r.mutationId=="string"?r.mutationId:void 0},shardKey:typeof r.shardKey=="string"?r.shardKey:n}},so=(e,t)=>{if(e.length>St)throw new d(`RPC batch exceeds the ${String(St)}-call limit`,{code:"BAD_REQUEST",status:400});const n=new Map;for(const[r,a]of e.entries()){const{entry:i,shardKey:u}=ao(a,r,t),h=n.get(u)??[];h.push(i),n.set(u,h)}return n},io="/_lunora/admin/export",co="/_lunora/admin/import",uo="/_lunora/admin/sync",lo="/_lunora/admin/connector/sync",ho="/_lunora/admin/apply",fo="/_lunora/admin/export-tap/run",po=new TextEncoder,mo=async e=>{const n=await he(e,"Export")??{};if(n.tables===void 0)return{tables:void 0};if(!Array.isArray(n.tables))throw new d("Export `tables` must be a string array",{code:"BAD_REQUEST",status:400});const r=[];for(const a of n.tables){if(typeof a!="string"||a.length===0)throw new d("Export `tables` entries must be non-empty strings",{code:"BAD_REQUEST",status:400});r.push(a)}return{tables:r}},je=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):void 0,wo=e=>{const{applyGlobals:t,defaultShardKey:n,exportCursorStore:r,exportSinks:a,knownTables:i,queryCoordinator:u,assertAdmin:h,requireAdminOption:p,resolveForwardContext:m,shardDO:S,streamExportRows:A,streamingImport:T,syncGlobals:g}=e,b=async(I,K)=>{const j=we(I,["POST"]);if(j)return j;const W=p(I,u,{code:"BAD_REQUEST",message:"Export endpoint requires a `queryCoordinator` on the worker"}),C=await mo(I),{headers:V}=await m(I,K),F=new ReadableStream({async pull(J){const ee=L=>{J.enqueue(po.encode(`${JSON.stringify(L)}
4
- `))};try{await A(W,V,C.tables,ee),J.close()}catch(L){J.error(L)}}});return new Response(F,{headers:{"content-type":"application/x-ndjson"},status:200})},R=async(I,K)=>{const j=we(I,["POST"]);if(j)return j;const W=p(I,u,{code:"BAD_REQUEST",message:"Sync endpoint requires a `queryCoordinator` on the worker"}),C=await te(I),V=typeof C.cursors=="object"&&C.cursors!==null?C.cursors:{},F=typeof C.limit=="number"?C.limit:void 0,J=typeof C.globalCursor=="number"?C.globalCursor:0,ee=je(C.tables),{headers:L}=await m(I,K),q=ee??i(),G=await W.orchestrateCdcSync(S,{cursors:V,defaultShardKey:n,headers:L,limit:F,tables:q}),fe=g?await g({limit:F,sinceSeq:J}):void 0;return Response.json({global:fe,shards:G.shards},{status:200})},f=async(I,K)=>{const j=we(I,["POST"]);if(j)return j;const W=p(I,u,{code:"BAD_REQUEST",message:"Connector sync endpoint requires a `queryCoordinator` on the worker"}),C=await te(I),V=sr(C.cursor),F=typeof C.limit=="number"&&C.limit>0?C.limit:void 0,J=je(C.tables),{headers:ee}=await m(I,K),L=J??i(),q=await W.orchestrateCdcSync(S,{cursors:V.s,defaultShardKey:n,headers:ee,limit:F,tables:L}),G=[],fe={...V.s};let ae=!1;for(const se of q.shards)ae=dt(G,se.changes??[],cr(F))||ae,fe[se.shardKey]=se.cursor;let _e=V.g;if(g){const se=await g({limit:F,sinceSeq:V.g});ae=dt(G,se.changes,F)||ae,_e=se.cursor}const Pe=ir({g:_e,s:fe,v:1}),Ne={changes:G,hasMore:ae,nextCursor:Pe};return Response.json(Ne,{status:200})},O=async(I,K)=>{const j=we(I,["POST"]);if(j)return j;const W=p(I,u,{code:"BAD_REQUEST",message:"Apply endpoint requires a `queryCoordinator` on the worker"}),C=await te(I),F=(Array.isArray(C.batches)?C.batches:[]).map(G=>G).filter(G=>G!==null&&typeof G=="object"&&typeof G.shardKey=="string"&&Array.isArray(G.changes)),J=Array.isArray(C.globalChanges)?C.globalChanges:[],{headers:ee}=await m(I,K),L=await W.orchestrateApplyCdc(S,{batches:F,headers:ee}),q=J.length>0&&t?await t({changes:J}):0;return Response.json({applied:L.applied+q,failed:L.failed,ok:L.ok},{status:200})},U=async(I,K)=>{const j=we(I,["POST"]);if(j)return j;h(I);const{headers:W}=await m(I,K),C=await T(I,W);return Response.json(C,{headers:{"content-type":"application/json"},status:C.failed.length>0?207:200})},M=async(I,K)=>{const j=we(I,["POST"]);if(j)return j;const W=p(I,u,{code:"BAD_REQUEST",message:"Export-tap endpoint requires a `queryCoordinator` on the worker"});if(a===void 0||Object.keys(a).length===0||r===void 0)throw new d("Export-tap endpoint requires `exportSinks` + `exportCursorStore` on the worker",{code:"EXPORT_TAP_NOT_CONFIGURED",status:400});const C=await te(I),V=typeof C.sink=="string"?C.sink:void 0,F=typeof C.limit=="number"&&C.limit>0?C.limit:void 0,J=je(C.tables);if(V===void 0)throw new d("Export-tap `sink` must name a configured sink",{code:"BAD_REQUEST",status:400});const ee=a[V];if(ee===void 0)throw new d(`Export-tap sink "${V}" is not configured`,{code:"NOT_FOUND",status:404});const{headers:L}=await m(I,K),q=J??i(),G=await ar({coordinator:W,cursorStore:r,defaultShardKey:n,headers:L,limit:F,shardDO:S,sink:ee,tables:q});return Response.json(G,{headers:{"content-type":"application/json"},status:200})};return{[ho]:O,[lo]:f,[io]:b,[fo]:M,[co]:U,[uo]:R}},go=(e,t)=>{let n;try{n=JSON.parse(e)}catch{return{error:{code:"BAD_ROW",line:t,message:"line is not valid JSON",table:""},ok:!1}}if(!n||typeof n!="object"||Array.isArray(n))return{error:{code:"BAD_ROW",line:t,message:"row must be a JSON object",table:""},ok:!1};const r=n;return typeof r.table!="string"||r.table.length===0?{error:{code:"BAD_ROW",line:t,message:"row is missing `table`",table:""},ok:!1}:!r.doc||typeof r.doc!="object"||Array.isArray(r.doc)?{error:{code:"BAD_ROW",line:t,message:"row is missing or malformed `doc`",table:r.table},ok:!1}:{doc:r.doc,ok:!0,table:r.table}},yo=(e,t,n,r,a)=>{if(n?.mode.kind==="shardBy"&&typeof n.mode.field=="string"){const i=e[n.mode.field];return i==null?{error:{code:"BAD_ROW",line:a,message:`row missing shard field "${n.mode.field}" for table "${t}"`,table:t},ok:!1}:{ok:!0,shardKey:typeof i=="string"?i:JSON.stringify(i)}}return{ok:!0,shardKey:r}},bo=async(e,t,n)=>{if(!e.body)throw new d("Import endpoint requires a request body",{code:"BAD_REQUEST",status:400});const r=[],a=[],i=new Map;let u=0,h=0;const p=e.body.getReader(),m=new TextDecoder;let S="",A=0;const T=g=>{h+=1;const b=g.trim();if(b.length===0)return;u+=1;const R=go(b,h);if(!R.ok){r.push(R.error);return}const{doc:f,table:O}=R,U=t.resolveTableSharding?.(O);if(U?.mode.kind==="global"){a.push({doc:f,line:h,table:O});return}const M=yo(f,O,U,n,h);if(!M.ok){r.push(M.error);return}const I=i.get(M.shardKey);I?I.rows.push({doc:f,table:O}):i.set(M.shardKey,{rows:[{doc:f,table:O}],shardKey:M.shardKey,startLine:h})};for(;;){const{done:g,value:b}=await p.read();if(g)break;if(b&&(A+=b.byteLength,A>$t))throw await p.cancel().catch(()=>{}),new d("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});S+=m.decode(b,{stream:!0});let R=S.indexOf(`
5
- `);for(;R!==-1;){const f=S.slice(0,R);S=S.slice(R+1),T(f),R=S.indexOf(`
6
- `)}}return S.length>0&&T(S),{errors:r,globalRows:a,perShard:i,received:u}},_o=e=>e.flatMap(t=>t.error?[{message:t.error.message,shardKey:t.shardKey,timedOut:t.error.timedOut}]:[]),At=(e,t)=>{for(const[n,r]of Object.entries(t.inserted))e.inserted[n]=(e.inserted[n]??0)+r;for(const n of t.errors)e.errors.push({...n});e.conflicts+=t.conflicts},Ro=async(e,t,n,r)=>{const a=t.defaultShardKey??"__root__",{errors:i,globalRows:u,perShard:h,received:p}=await bo(e,t,a),m={conflicts:0,errors:i,failed:[],inserted:{}},S=[];if(t.resolveTableSharding===void 0&&h.size>0&&S.push("no `resolveTableSharding` is configured, so every row was routed to the default shard and no row could be recognised as `.global()` — correct for a single-shard app, silent misplacement for a sharded one"),h.size>0){const A=t.queryCoordinator;if(!A)throw new d("Import endpoint requires a `queryCoordinator` on the worker",{code:"BAD_REQUEST",status:400});const T=await A.orchestrateImport(r,{batches:[...h.values()],headers:n});At(m,T),m.failed.push(..._o(T.shards))}if(u.length>0)if(t.importGlobals){const A=u[0]?.line??1,T=await t.importGlobals({rows:u,startLine:A});At(m,T)}else for(const A of u)m.errors.push({code:"GLOBAL_NOT_CONFIGURED",line:A.line,message:`row targets global table "${A.table}" but no \`importGlobals\` is configured`,table:A.table});return{conflicts:m.conflicts,errors:m.errors,failed:m.failed,inserted:m.inserted,received:p,...S.length>0?{warnings:S}:{}}},Ke=e=>typeof e=="object"&&e!==null?e:{},Fe=e=>typeof e.kind=="string"?e.kind:"unknown",Eo=(e,t)=>{let n=Ke(t),r=!1;Fe(n)==="optional"&&(r=!0,n=Ke(n._meta?.inner));const a=Fe(n),i=n._meta??{},u={kind:a,name:e,optional:r};if(a==="id"&&typeof i.tableName=="string"&&(u.table=i.tableName),a==="array"){const h=Fe(Ke(i.inner));h!=="unknown"&&(u.element=h)}return u},So=e=>typeof e!="object"||e===null?[]:Object.entries(e).map(([t,n])=>Eo(t,n)).toSorted((t,n)=>t.name.localeCompare(n.name)),Ao="/_lunora/admin/functions",To="/_lunora/admin/cron-jobs",Oo="/_lunora/admin/openapi",vo="/_lunora/admin/openrpc",ko="/_lunora/admin/global/tables",Io="/_lunora/admin/global/table",Po="/_lunora/admin/global/facet",Tt=e=>{if(e===void 0||e==="")return;let t;try{t=Mt(JSON.parse(e))}catch{return}if(!Array.isArray(t))return;const n=t.flatMap(r=>{if(typeof r!="object"||r===null||typeof r.column!="string")return[];const{column:a,value:i}=r;return[{column:a,value:i}]});return n.length===0?void 0:n},No=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:{}}),Do=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"}),Uo=e=>{const{assertAdmin:t,options:n,parsePaging:r,queryParameter:a,requireAdminOption:i}=e,u=g=>{$(g,"GET","Functions");const b=i(g,n.functions,{code:"FUNCTIONS_NOT_CONFIGURED",message:"functions endpoint requires a `functions` registry on the worker"}),R=Object.entries(b).flatMap(([f,O])=>O.visibility==="internal"||O.kind==="stream"?[]:[{args:So(O.args),kind:O.kind,path:f}]).toSorted((f,O)=>f.path.localeCompare(O.path));return Response.json({functions:R},{headers:{"content-type":"application/json"},status:200})},h=g=>{$(g,"GET","Cron-jobs");const b=i(g,n.cronJobs,{code:"CRON_JOBS_NOT_CONFIGURED",message:"cron-jobs endpoint requires a `cronJobs` map on the worker"}),R=Object.entries(b).flatMap(([f,O])=>O.map(U=>({args:U.args,cron:f,functionPath:U.functionPath,name:U.name,shardKey:U.shardKey,workflow:U.workflow}))).toSorted((f,O)=>f.name.localeCompare(O.name));return Response.json({jobs:R},{headers:{"content-type":"application/json"},status:200})},p=g=>($(g,"GET","OpenAPI"),t(g),Response.json(n.openApiSpec??No,{headers:{"content-type":"application/json"},status:200})),m=g=>($(g,"GET","OpenRPC"),t(g),Response.json(n.openRpcSpec??Do,{headers:{"content-type":"application/json"},status:200})),S=async g=>{$(g,"GET","Global-tables");const b=i(g,n.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"});return Response.json(await b.listTables(),{headers:{"content-type":"application/json"},status:200})},A=async g=>{$(g,"GET","Global-table");const b=i(g,n.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),R=new URL(g.url),f=a(R,"table");if(f===void 0)throw new d("Global-table endpoint requires a `table` query param",{code:"BAD_REQUEST",status:400});const O=await b.readTablePage({...r(g),filters:Tt(a(R,"filters")),table:f});return Response.json(O,{headers:{"content-type":"application/json"},status:200})},T=async g=>{$(g,"GET","Global-facet");const b=i(g,n.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),R=new URL(g.url),f=a(R,"table"),O=a(R,"column");if(f===void 0||O===void 0)throw new d("Global-facet endpoint requires `table` and `column` query params",{code:"BAD_REQUEST",status:400});const U=a(R,"limit"),M=U===void 0?void 0:Number(U),I=await b.facetColumn({column:O,filters:Tt(a(R,"filters")),limit:M!==void 0&&Number.isFinite(M)?M:void 0,table:f});return Response.json(I,{headers:{"content-type":"application/json"},status:200})};return{[To]:h,[Ao]:u,[Po]:T,[Io]:A,[ko]:S,[Oo]:p,[vo]:m}},Co="/_lunora/admin/kv/namespaces",Bo="/_lunora/admin/kv/keys",Xt="/_lunora/admin/kv/value",Zt=32*1048576,Ot=60,xo=e=>{const{readJsonBody:t,requireAdminOption:n}=e,r=b=>n(b,e.kvIntrospector,{code:"KV_NOT_CONFIGURED",message:"KV endpoints require a `kvIntrospector` on the worker"}),a=b=>Response.json(b,{headers:{"content-type":"application/json"},status:200}),i=(b,R)=>{const f=new URL(b.url),O=f.searchParams.get("namespace")??"",U=f.searchParams.get("key")??"";if(O==="")throw new d(`KV-value ${R} request requires a \`namespace\` query parameter`,{code:"BAD_REQUEST",status:400});if(U==="")throw new d(`KV-value ${R} request requires a \`key\` query parameter`,{code:"BAD_REQUEST",status:400});return{key:U,namespace:O}},u=async(b,R)=>{if(!(await b.listNamespaces()).some(O=>O.binding===R))throw new d(`Unknown KV namespace binding \`${R}\``,{code:"NOT_FOUND",status:404})},h=async b=>($(b,"GET","KV-namespaces"),a({namespaces:await r(b).listNamespaces()})),p=async b=>{$(b,"GET","KV-keys");const R=r(b),f=new URL(b.url),O=f.searchParams.get("namespace")??"";if(O==="")throw new d("KV-keys request requires a `namespace` query parameter",{code:"BAD_REQUEST",status:400});const U=f.searchParams.get("prefix")??void 0,M=f.searchParams.get("cursor")??void 0,I=f.searchParams.get("limit"),K=I===null?void 0:Number.parseInt(I,10);if(K!==void 0&&(!Number.isInteger(K)||K<1))throw new d("KV-keys `limit` must be a positive integer",{code:"BAD_REQUEST",status:400});const j=K===void 0?void 0:Math.min(K,1e3);return await u(R,O),a(await R.listKeys({cursor:M,limit:j,namespace:O,prefix:U}))},T={DELETE:async b=>{const R=r(b),f=i(b,"DELETE");return await u(R,f.namespace),await R.deleteKey(f),a({deleted:!0})},GET:async b=>{const R=r(b),f=i(b,"GET");return await u(R,f.namespace),a(await R.getValue(f))},PUT:async b=>{const R=r(b),f=await t(b,Zt);if(typeof f.namespace!="string"||f.namespace==="")throw new d("KV-value PUT request requires a `namespace` string",{code:"BAD_REQUEST",status:400});if(typeof f.key!="string"||f.key==="")throw new d("KV-value PUT request requires a `key` string",{code:"BAD_REQUEST",status:400});if(typeof f.value!="string")throw new d("KV-value PUT request requires a `value` string",{code:"BAD_REQUEST",status:400});if(f.expirationTtl!==void 0&&(typeof f.expirationTtl!="number"||!Number.isInteger(f.expirationTtl)||f.expirationTtl<Ot))throw new d("KV-value PUT `expirationTtl` must be an integer ≥ 60",{code:"BAD_REQUEST",status:400});const O=Math.floor(Date.now()/1e3)+Ot;if(f.expiration!==void 0&&(typeof f.expiration!="number"||!Number.isInteger(f.expiration)||f.expiration<O))throw new d("KV-value PUT `expiration` must be a Unix-seconds timestamp at least 60 seconds in the future",{code:"BAD_REQUEST",status:400});return await u(R,f.namespace),await R.putValue({expiration:f.expiration,expirationTtl:f.expirationTtl,key:f.key,metadata:f.metadata,namespace:f.namespace,value:f.value}),a({ok:!0})}},g=b=>{const R=T[b.method];if(!R)throw new d("KV-value endpoint requires GET, PUT, or DELETE",{code:"METHOD_NOT_ALLOWED",status:405});return R(b)};return{[Co]:h,[Bo]:p,[Xt]:g}},Ho="/_lunora/migrate",Lo="/_lunora/admin/pitr",Mo="/_lunora/admin/rank",$o="/_lunora/admin/rankpage",jo="/_lunora/admin/shard-traffic",Ko=new Set(["__lunora_admin__:migrationStatus","__lunora_admin__:runMigration"]),Fo=new Set(["__lunora_admin__:getPitrBookmark","__lunora_admin__:pitrRestore"]),Go=async e=>{const n=await he(e,"Migration")??{};if(typeof n.table!="string"||n.table.length===0)throw new d("Migration request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof n.functionPath!="string"||!Ko.has(n.functionPath))throw new d("Migration request `functionPath` must be a migration admin op",{code:"BAD_REQUEST",status:400});return{args:n.args??{},functionPath:n.functionPath,table:n.table}},Qo=async e=>{const n=await he(e,"Rank")??{};if(typeof n.table!="string"||n.table.length===0)throw new d("Rank request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof n.index!="string"||n.index.length===0)throw new d("Rank request is missing `index`",{code:"BAD_REQUEST",status:400});if(typeof n.partitionKey!="string")throw new d("Rank request `partitionKey` must be a string",{code:"BAD_REQUEST",status:400});if(typeof n.rowId!="string"||n.rowId.length===0)throw new d("Rank request is missing `rowId`",{code:"BAD_REQUEST",status:400});if(!Array.isArray(n.sortValues))throw new d("Rank request `sortValues` must be an array",{code:"BAD_REQUEST",status:400});return{index:n.index,partitionKey:n.partitionKey,rowId:n.rowId,sortValues:n.sortValues,table:n.table}},zo=e=>{if(e!==void 0){if(!Array.isArray(e)||e.some(t=>t!=="asc"&&t!=="desc"))throw new d('Rank page request `directions` must be an array of "asc"|"desc"',{code:"BAD_REQUEST",status:400});return e}},Wo=e=>{if(typeof e.table!="string"||e.table.length===0)throw new d("Rank page request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof e.index!="string"||e.index.length===0)throw new d("Rank page request is missing `index`",{code:"BAD_REQUEST",status:400});if(e.partitionKey!==void 0&&typeof e.partitionKey!="string")throw new d("Rank page request `partitionKey` must be a string",{code:"BAD_REQUEST",status:400});if(e.take!==void 0&&(typeof e.take!="number"||!Number.isFinite(e.take)))throw new d("Rank page request `take` must be a number",{code:"BAD_REQUEST",status:400});if(e.cursor!==void 0&&e.cursor!==null&&typeof e.cursor!="string")throw new d("Rank page request `cursor` must be a string or null",{code:"BAD_REQUEST",status:400})},Vo=async e=>{const n=await he(e,"Rank page")??{};Wo(n);const r=zo(n.directions);return{cursor:typeof n.cursor=="string"?n.cursor:null,directions:r,index:n.index,partitionKey:typeof n.partitionKey=="string"?n.partitionKey:void 0,table:n.table,take:typeof n.take=="number"?n.take:void 0}},Jo=async e=>{const n=await he(e,"Shard-traffic")??{};if(typeof n.table!="string"||n.table.length===0)throw new d("Shard-traffic request is missing `table`",{code:"BAD_REQUEST",status:400});return{table:n.table}},qo=async e=>{const n=await te(e);if(typeof n.functionPath!="string"||!Fo.has(n.functionPath))throw new d("PITR request `functionPath` must be a PITR admin op",{code:"BAD_REQUEST",status:400});if(n.shardKey!==void 0&&typeof n.shardKey!="string")throw new d("PITR `shardKey` must be a string",{code:"BAD_REQUEST",status:400});return{args:n.args??{},functionPath:n.functionPath,shardKey:n.shardKey}},Yo=e=>{const{defaultShard:t,forwardToShard:n,isAdmin:r,queryCoordinator:a,resolveForwardContext:i,shardDO:u}=e,h=(g,b)=>{if(g.method!=="POST")throw new d(`${b} endpoint requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});if(!r(g))throw new d("Admin auth required",{code:"FORBIDDEN",status:403});if(!a)throw new d(`${b} endpoint requires a \`queryCoordinator\` on the worker`,{code:"BAD_REQUEST",status:400});return a},p=async(g,b)=>{const R=h(g,"Migration"),f=await Go(g),{headers:O}=await i(g,b),U=await R.orchestrateMigration(u,{args:f.args,defaultShardKey:t,functionPath:f.functionPath,headers:O,table:f.table});return Response.json(U,{headers:{"content-type":"application/json"},status:200})},m=async(g,b)=>{const R=h(g,"Rank"),f=await Qo(g),{headers:O}=await i(g,b),U=await R.orchestrateRank(u,{headers:O,index:f.index,partitionKey:f.partitionKey,rowId:f.rowId,sortValues:f.sortValues,table:f.table});return Response.json(U,{headers:{"content-type":"application/json"},status:200})},S=async(g,b)=>{const R=h(g,"Rank page"),f=await Vo(g),{headers:O}=await i(g,b),U=await R.orchestrateRankPage(u,{...f,headers:O});return Response.json(U,{headers:{"content-type":"application/json"},status:200})},A=async(g,b)=>{const R=h(g,"Shard-traffic"),f=await Jo(g),{headers:O}=await i(g,b),U=await R.orchestrateShardTraffic(u,{headers:O,table:f.table});return Response.json(U,{headers:{"content-type":"application/json"},status:200})},T=async(g,b)=>{if($(g,"POST","PITR"),!r(g))throw new d("admin PITR endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403});const R=await qo(g),{headers:f}=await i(g,b),O=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:R.args,functionPath:R.functionPath}),headers:f,method:"POST"});return n(u,R.shardKey??t,O)};return{[Ho]:p,[Lo]:T,[Mo]:m,[$o]:S,[jo]:A}},Xo=1,Zo=0,ea=32,ta=512,na=/^[a-z][\d_a-z*/-]{0,255}(?:@[a-z][\d_a-z*/-]{0,13})?=[\u0020-\u002B\u002D-\u003C\u003E-\u007E]{1,256}$/,ra=e=>{if(e==null)return;const t=e.trim();if(t.length===0||t.length>ta)return;const n=t.split(",");if(!(n.length>ea)){for(const r of n)if(!na.test(r.trim()))return;return t}},oa=e=>{const t=Qn(e.headers.get("traceparent"));if(t===void 0)return;const n=ra(e.headers.get("tracestate"));return{parentSpanId:t.parentSpanId,sampled:t.sampled,traceId:t.traceId,...n===void 0?{}:{traceState:n}}},aa=(e,t={})=>{const n=oa(e),r=t.trustInbound===!0?n:void 0,a=Ie(8),i=r?.traceId??Ie(16),u=pr(t.sampling,r===void 0?a:i),h=u.isTraced&&(r===void 0||r.sampled);return{decision:u,ignoredUpstream:n!==void 0&&r===void 0,trace:{sampled:h,spanId:a,traceFlags:h?Xo:Zo,traceId:i,...r?.parentSpanId===void 0?{}:{parentSpanId:r.parentSpanId},...r?.traceState===void 0?{}:{traceState:r.traceState}}}},sa=(e,t)=>{t.traceparent=Gn(e.traceId,e.spanId,e.sampled),e.traceState!==void 0&&(t.tracestate=e.traceState)},ia=(e,t)=>{let n;return()=>{if(n===void 0){const r=Jn(e),a=t===void 0?void 0:t.cf;n=zn(Vn(r),Wn(r,a))}return n}},ca="/_lunora/admin/scheduled",da="/_lunora/admin/scheduled/status",ua="/_lunora/admin/scheduled/ws",la="/_lunora/admin/scheduled/cancel",ha="/_lunora/admin/scheduled/dead",fa="/_lunora/admin/scheduled/dead/retry",pa="/_lunora/admin/scheduled/dead/cancel",ma="/_lunora/admin/scheduled/pool/release",wa=e=>{const{checkWsAdmin:t,requireSchedulerNamespace:n,resolveSchedulerStub:r,schedulerInstanceName:a}=e,i=(m,S)=>A=>{if(A.method!=="GET")throw new d(`${S} endpoint requires GET`,{code:"METHOD_NOT_ALLOWED",status:405});const T=new URL(A.url).searchParams.get("cursor"),g=T===null||T===""?"":`?cursor=${encodeURIComponent(T)}`;return r(A).fetch(new Request(`https://scheduler.internal${m}${g}`,{method:"GET"}))},u=(m,S,A=S)=>async T=>{if(T.method!=="POST")throw new d(`${A} requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});const g=r(T),b=await he(T,S);if(typeof b?.id!="string"||b.id==="")throw new d(`${S} requires a string \`id\``,{code:"BAD_REQUEST",status:400});return g.fetch(new Request(`https://scheduler.internal${m}`,{body:JSON.stringify({id:b.id}),headers:{"content-type":"application/json"},method:"POST"}))},h=async m=>{if(m.method!=="POST")throw new d("Scheduled pool-release endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const S=r(m),A=await he(m,"Scheduled pool-release");if(typeof A?.pool!="string"||A.pool==="")throw new d("Scheduled pool-release requires a string `pool`",{code:"BAD_REQUEST",status:400});const T=typeof A.id=="string"&&A.id!==""?A.id:void 0;return S.fetch(new Request("https://scheduler.internal/complete",{body:JSON.stringify(T===void 0?{pool:A.pool}:{id:T,pool:A.pool}),headers:{"content-type":"application/json"},method:"POST"}))},p=async m=>{if(m.headers.get("Upgrade")!=="websocket")throw new d("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});if(!await t(m))throw new d("admin authorization required",{code:"ADMIN_FORBIDDEN",status:403});const S=n();return ge(S,a).fetch(new Request("https://scheduler.internal/ws",{headers:{Upgrade:"websocket"}}))};return{[la]:u("/cancel","Scheduled-cancel","Scheduled-cancel endpoint"),[pa]:u("/dead/cancel","Scheduled dead-letter action"),[ha]:i("/dead","Scheduled dead-letter"),[fa]:u("/dead/retry","Scheduled dead-letter action"),[ca]:i("/list","Scheduled-list"),[ma]:h,[da]:i("/status","Scheduler-status"),[ua]:p}},ga=(e,...t)=>{let n=e.cf;for(const r of t){if(typeof n!="object"||n===null)return;n=n[r]}return typeof n=="string"?n:void 0},vt={mtls:e=>ga(e,"tlsClientAuth","certVerified")==="SUCCESS"},ya=e=>e===void 0||e===!1?()=>!1:e===!0?()=>!0:typeof e=="function"?e:(Object.hasOwn(vt,e)?vt[e]:void 0)??(()=>!1),ba=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.'))}},_a="/_lunora/admin/vector/indexes",Ra="/_lunora/admin/vector/query",Ea=e=>{const{readJsonBody:t,requireAdminOption:n}=e,r=async i=>{$(i,"GET","Vector-indexes");const u=n(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=>{$(i,"POST","Vector-query");const u=n(i,e.vectorIntrospector,{code:"VECTORS_NOT_CONFIGURED",message:"vector endpoints require a `vectorIntrospector` on the worker"});if(u.queryIndex===void 0)throw new d("vector index querying is not enabled on this worker",{code:"VECTOR_QUERY_UNSUPPORTED",status:400});const p=await t(i);if(typeof p.name!="string"||p.name==="")throw new d("Vector-query request requires a `name` string",{code:"BAD_REQUEST",status:400});if(typeof p.text!="string"||p.text==="")throw new d("Vector-query request requires a `text` string",{code:"BAD_REQUEST",status:400});if(p.topK!==void 0&&(typeof p.topK!="number"||!Number.isInteger(p.topK)||p.topK<1))throw new d("Vector-query `topK` must be a positive integer",{code:"BAD_REQUEST",status:400});const m=await u.queryIndex({name:p.name,text:p.text,topK:p.topK});return Response.json(m,{headers:{"content-type":"application/json"},status:200})};return{[_a]:r,[Ra]:a}},Sa="/_lunora/admin/workflows/instances",Aa="/_lunora/admin/workflows/instance",Ta="/_lunora/admin/workflows/status",Oa={complete:!0,errored:!0,paused:!0,queued:!0,running:!0,terminated:!0,unknown:!0,waiting:!0,waitingForPause:!0},va=e=>e!==null&&Object.hasOwn(Oa,e)?e:void 0,kt=(e,t)=>{const n=e.searchParams.get(t);if(n===null)return;const r=Number(n);return Number.isInteger(r)&&r>0?r:void 0},Ge=(e,t)=>{const n=e.searchParams.get(t);if(n===null||n==="")throw new d(`Workflows admin endpoint requires a \`${t}\` query parameter`,{code:"BAD_REQUEST",status:400});return n},It=()=>{throw new d("Workflow inspection is unconfigured. Set CLOUDFLARE_ACCOUNT_ID + CLOUDFLARE_API_TOKEN in your .dev.vars to enable it.",{code:"WORKFLOWS_NOT_CONFIGURED",status:501})},ka=e=>{const{assertAdmin:t,resolveWorkflowsClient:n}=e,r=async(u,h,p)=>{$(u,"GET","Workflows instances"),t(u);const m=n(h);if(!m)return Response.json({configured:!1,instances:[],page:1,perPage:0,totalCount:0});const S=Ge(p,"name"),A=va(p.searchParams.get("status"));return Response.json(await m.listInstances({page:kt(p,"page"),perPage:kt(p,"perPage"),status:A,workflowName:S}))},a=async(u,h,p)=>{$(u,"GET","Workflows instance"),t(u);const m=n(h);return m?Response.json(await m.getInstance({instanceId:Ge(p,"id"),workflowName:Ge(p,"name")})):It()},i=async(u,h)=>{$(u,"POST","Workflows status"),t(u);const p=n(h);if(!p)return It();const m=await u.json().catch(()=>{});if(typeof m?.name!="string"||m.name===""||typeof m.id!="string"||m.id==="")throw new d("Workflows status action requires string `name` and `id`",{code:"BAD_REQUEST",status:400});const{action:S}=m;if(S!=="pause"&&S!=="resume"&&S!=="terminate")throw new d("Workflows status action must be one of: pause, resume, terminate",{code:"BAD_REQUEST",status:400});return Response.json(await p.setInstanceStatus({action:S,instanceId:m.id,workflowName:m.name}))};return{[Aa]:a,[Sa]:r,[Ta]:i}},Ia={[Xt]:Zt,[or]:rr},Pt="/_lunora/rpc",Pa="/_lunora/rpc-batch",Na="/_lunora/ws",be=(e,t,n)=>({resourceAttributes:ia(e,t),...n===void 0?{}:{waitUntil:n}}),Qe=e=>e?.waitUntil?{waitUntil:t=>e.waitUntil?.(t)}:{},Nt=e=>({spanId:e.spanId,traceFlags:e.traceFlags,traceId:e.traceId,...e.parentSpanId===void 0?{}:{parentSpanId:e.parentSpanId}}),ze=e=>{const{method:t}=e,n=e.headers.get("user-agent")??void 0;let r;try{r=new URL(e.url)}catch{return{method:t,userAgent:n}}const a=r.port===""?void 0:Number(r.port);return{host:r.hostname,method:t,path:r.pathname,port:Number.isNaN(a)?void 0:a,scheme:r.protocol.replace(":",""),userAgent:n}},Dt="/_lunora/voice/",Da="/_lunora/scheduler/dispatch",Ua="/_lunora/admin/cron-jobs/run",Ca="/_lunora/admin/ws-token",Ba="/_lunora/admin/",xa="/_lunora/",Ha="/_lunora/migrate",La="/_lunora/status",Ma=e=>e.startsWith(Ba)||e===Ha,$a="__lunora_relation__:",Se=e=>{if(e.startsWith($a))throw new d("`__lunora_relation__:*` is a fan-out-only reserved RPC and cannot be dispatched to a single shard",{code:"FORBIDDEN",status:403})},Ae=async e=>await e===!0,ja=e=>{const t=e.headers.get("x-lunora-userid"),n=e.headers.get("x-lunora-identity");if(!(t===null&&n===null))return{...n===null?{}:{identity:n},...t===null?{}:{userId:t}}},Ut="/api/auth",Ka="__lunora_admin__:recordAuthEvent",Fa="__lunora_admin__:listPushSubscriptions",Ga=["/sign-in","/sign-up","/callback"],Qa=(e,t)=>{const n=t.endsWith("/")?t.slice(0,-1):t;if(!e.startsWith(`${n}/`))return!1;const r=e.slice(n.length);return Ga.some(a=>r===a||r.startsWith(`${a}/`))},za=(e,t)=>{const n=t.endsWith("/")?t.slice(0,-1):t;return e===n||e.startsWith(`${n}/`)},Te=(e,t,n,r)=>{const a=Hn(n),i=a?n.code:"INTERNAL_SERVER_ERROR",u=a?n.status:500,h=n instanceof Error?n.message:String(n);return{durationMs:t,error:{code:i,message:h,status:u},functionPath:e,ok:!1,...r.fanOut?{fanOut:{failed:0,shards:0,table:r.fanOut.table}}:{},...r.shardKey?{shardKey:r.shardKey}:{}}},Wa=e=>{const{exp:t,expiresAtMs:n}=e;if(typeof n=="number"&&Number.isFinite(n))return n;if(typeof t=="number"&&Number.isFinite(t))return t*1e3},Ct=e=>e.waitUntil?{waitUntil:t=>{e.waitUntil?.(t)}}:void 0,Va=e=>{const t=e?.queue;return typeof t=="string"&&t.length>0?t:"unknown"},qe=new WeakMap,de=async(e,t,n,r=qe.get(e))=>{const a={"content-type":"application/json"},i=e.headers.get("authorization"),u=e.headers.get("cookie"),h=e.headers.get("x-d1-bookmark"),p=e.headers.get("x-lunora-mutation-id"),m=e.headers.get("x-lunora-client-id"),S=e.headers.get("x-lunora-client-seq");i&&(a.authorization=i),u&&(a.cookie=u),h&&(a["x-d1-bookmark"]=h),p&&(a["x-lunora-mutation-id"]=p),m&&(a["x-lunora-client-id"]=m),S&&(a["x-lunora-client-seq"]=S);const A=e.headers.get("cf-connecting-ip");if(A&&(a["x-lunora-client-ip"]=A),!n)return{claims:null,headers:a,identity:null,userId:null};const T=await n(e,t,r);if(!T||typeof T.userId!="string"||T.userId.length===0)return{claims:null,headers:a,identity:null,userId:null};a["x-lunora-userid"]=Kn(T.userId);const g=Wa(T);g!==void 0&&(a["x-lunora-identity-exp"]=String(g));const{userId:b,...R}=T,f=Object.keys(R).length>0?R:null;return f&&(a["x-lunora-identity"]=Fn(f)),{claims:f,headers:a,identity:T,userId:b}},Ja=new Set(["concat","first","groupBy","max","min","rank","sum","topK"]),qa=e=>{if(e===void 0)return;if(!e||typeof e!="object")throw new d("RPC `fanOut` must be an object",{code:"BAD_REQUEST",status:400});const t=e;if(typeof t.table!="string"||t.table.length===0)throw new d("RPC `fanOut.table` must be a non-empty string",{code:"BAD_REQUEST",status:400});if(!t.merge||typeof t.merge!="object")throw new d("RPC `fanOut.merge` must be an object",{code:"BAD_REQUEST",status:400});const n=t.merge;if(typeof n.kind!="string"||!Ja.has(n.kind))throw new d("RPC `fanOut.merge.kind` is not a recognized merge strategy",{code:"BAD_REQUEST",status:400});if(n.kind==="topK"){if(typeof n.k!="number"||!Number.isInteger(n.k)||n.k<0)throw new d("RPC `fanOut.merge.k` must be a non-negative integer",{code:"BAD_REQUEST",status:400});if(typeof n.by!="string"||n.by.length===0)throw new d("RPC `fanOut.merge.by` must be a non-empty string",{code:"BAD_REQUEST",status:400})}return t},Ya=(e,t)=>{e?.LUNORA_DEBUG_RPC&&console.warn(`[lunora:rpc] ${t.fanOut?"fan-out":`shard=${t.shardKey??"(root)"}`} ${t.functionPath}`)},We=(e,t)=>{if(t.functions===void 0)return;const n=t.functions[e.functionPath]?.x402;if(n){if(e.fanOut)throw new d("a paid (`.x402`) function cannot be fanned out",{code:"BAD_REQUEST",status:400});if(!t.x402Charge)throw new d(`function "${e.functionPath}" is marked paid (.x402) but no x402Charge gate is configured on the worker`,{code:"MISCONFIGURED",status:500});return n}},Xa=async e=>{const t=await Kt(e);let n;try{n=JSON.parse(t)}catch{throw new d("RPC body must be valid JSON",{code:"BAD_REQUEST",status:400})}if(!n||typeof n!="object"||typeof n.functionPath!="string")throw new d("RPC envelope is missing `functionPath`",{code:"BAD_REQUEST",status:400});const r=n;if(r.args!==void 0&&jt(r.args,"RPC"),r.shardKey!==void 0&&typeof r.shardKey!="string")throw new d("RPC `shardKey` must be a string",{code:"BAD_REQUEST",status:400});const a=n,i=qa(a.fanOut),u=a.args??{};if(i&&a.functionPath.startsWith("__lunora_relation__:")){const h=u.table;if(typeof h=="string"&&h!==i.table)throw new d("RPC `args.table` must match the authorized `fanOut.table` for a relation fan-out",{code:"BAD_REQUEST",status:400});u.table=i.table}return{args:u,fanOut:i,functionPath:a.functionPath,shardKey:a.shardKey}},Oe=new Map,Za=5e3,es=4096,ts=async(e,t)=>{const n=Date.now(),r=Oe.get(t);if(r!==void 0&&r.expiresMs>n)return r.relayCount;r!==void 0&&Oe.delete(t);let a=0;try{const i=await ge(e,t).fetch(new Request("https://shard.internal/_lunora/route"));if(i.ok){const h=(await i.json()).relayCount;typeof h=="number"&&h>0&&(a=Math.floor(h))}}catch{a=0}return Lt(Oe,es),Oe.set(t,{expiresMs:n+Za,relayCount:a}),a},Bt=(e,t)=>{if(!(e===null||typeof e!="object"))return Object.entries(e).find(([,n])=>n===t)?.[0]},ve=(e,t,n)=>new Request("https://shard.internal/rpc",{body:JSON.stringify({args:t,functionPath:e}),headers:n,method:"POST"}),ns=["x-lunora-userid","x-lunora-identity","x-lunora-identity-exp"],rs=(e,t)=>{for(const n of ns){e.delete(n);const r=t[n];r!==void 0&&e.set(n,r)}},xt=(e,t)=>{const n=new Headers(e.headers),r=[...n.keys()];for(const a of r)a.startsWith("x-lunora-")&&n.delete(a);return rs(n,t),n},os=async(e,t,n)=>e.length===0||n.length===0?!1:Ze(await zt(e,t),n),Ht=(e,t)=>{if(!t||t.length===0)return!1;const n=e.headers.get("authorization");if(!n)return!1;const[r,...a]=n.split(" ");return r?.toLowerCase()!=="bearer"?!1:Ze(t,a.join(" ").trim())},as=async(e,t,n)=>{if(!t||t.length===0)return!1;const r=new URL(e.url).searchParams.get("token");return r===null?!1:await jr(t,r)?!0:n?!1:Ze(t,r)},ss=(e,t)=>{if(t===null||typeof t!="object"&&typeof t!="function")return;const n=t;if(typeof n.prepare=="function"&&typeof n.batch=="function"&&typeof n.dump=="function")return lr(`d1:${e}`,t);if(typeof n.list=="function"&&typeof n.head=="function"&&typeof n.createMultipartUpload=="function")return Le(`r2:${e}`,!0);if(typeof n.send=="function"&&typeof n.sendBatch=="function"&&typeof n.get!="function")return Le(`queue:${e}`,!0);if(typeof n.connectionString=="string")return Le(`hyperdrive:${e}`,!0)},is=e=>{if(e.x402Charge!==void 0&&e.functions===void 0)throw new d("`x402Charge` requires `functions`: paid (.x402) procedures are read from the function registry, so without it every paid procedure would dispatch FREE. Build the worker with `defineApp()` (which supplies the registry) or pass `functions` explicitly.",{code:"MISCONFIGURED",status:500})},en=e=>{is(e);const t=ya(e.trustInboundTraceContext),n=ba(e.trustInboundTraceContext),r=e.defaultShardKey??"__root__",a=hr(e.resolveIdentity,e.identity),i=lt(e.shardDO,e.jurisdiction),u=e.schedulerDO===void 0?void 0:lt(e.schedulerDO,e.jurisdiction);let h=!1;const p=o=>{if(o===void 0||e.jurisdiction===void 0)return o;h||(h=!0,console.warn(`[lunora] jurisdiction "${e.jurisdiction}" pins placement, so region hints (\`shardRegion\`, replica and relay placement) are not sent. Residency wins.`))},m=async(o,s,l,c=e.shardRegion?.(s))=>ge(o,s,p(c)).fetch(l);let S;const A=()=>e.adminToken??S;let T;const g=()=>e.requireEphemeralWsToken??T??!0;let b;const R=o=>{const s=o??{};if(b??=Bt(o,e.shardDO),T===void 0&&e.requireEphemeralWsToken===void 0){const c=s.LUNORA_REQUIRE_EPHEMERAL_WS_TOKEN;typeof c=="string"&&c.length>0&&(T=Lr(c,!0))}if(S!==void 0||e.adminToken!==void 0)return;const l=s.LUNORA_ADMIN_TOKEN;typeof l=="string"&&l.length>0&&(S=l)},f=new WeakSet,O=o=>Ht(o,A())||f.has(o),U=async o=>{if(!(e.adminGate===void 0||f.has(o)))try{await Ae(e.adminGate(o,qe.get(o)))&&f.add(o)}catch{}},M=async(o,s)=>{const l=await de(o,s,e.resolveIdentity);if(f.has(o)&&l.headers.authorization===void 0){const c=A();c!==void 0&&(l.headers.authorization=`Bearer ${c}`)}return l};let I=!1,K=!1;const j=()=>{K||(K=!0,console.warn("[lunora] `replicaReads: true` has no effect without `functions` — read eligibility is decided from the function registry."))},W=o=>{if(!e.allowUnauthenticatedShardAccess){const s=o==="fan-out"?"authorizeFanOut":"authorizeShard";throw new d(`${o} access is default-denied: configure \`${s}\` 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})}I||(I=!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("")))},C=async(o,s)=>{if(s.includes(Ve)||s.includes(Je))throw new d("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403});if(e.authorizeShard){if(!await Ae(e.authorizeShard({identity:o,shardKey:s})))throw new d("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else s!==r&&W("shard")},V=Yo({defaultShard:r,forwardToShard:m,isAdmin:O,queryCoordinator:e.queryCoordinator,resolveForwardContext:M,shardDO:i}),F=async(o,s,l,c,w)=>{Se(o);const y={"content-type":"application/json","x-lunora-system":"1"};return w?.userId!==void 0&&w.userId.length>0&&(y["x-lunora-userid"]=w.userId),w?.identity!==void 0&&w.identity.length>0&&(y["x-lunora-identity"]=w.identity),c!==void 0&&c.length>0&&(y["x-lunora-mutation-id"]=c),m(i,l,ve(o,s,y))},J=async(o,s,l,c,w)=>{const y=l?.[o];if(!y||typeof y.create!="function")throw new d(`${c} targets workflow binding "${o}", which is not bound on env`,{code:"CRON_JOB_FAILED",status:500});if(yr(s))throw new d(`${c} params ${br}`,{code:"BAD_REQUEST",status:400});try{await y.create(w===void 0?{params:s}:{id:w,params:s})}catch(P){if(!Er(P))throw P}},ee=async(o,s)=>{if(o.workflow){await J(o.workflow,o.args??{},s,`cron job "${o.name}"`);return}if(o.functionPath===void 0)throw new d(`cron job "${o.name}" has neither a function target nor a workflow target`,{code:"CRON_JOB_FAILED",status:500});const l=await F(o.functionPath,o.args??{},o.shardKey??r);if(!l.ok)throw new d(`cron job "${o.name}" (${o.functionPath}) failed with shard status ${String(l.status)}`,{code:"CRON_JOB_FAILED",status:500})},L=o=>{if(!O(o))throw new d("admin endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403})},q=(o,s,l)=>{if(L(o),s===void 0)throw new d(l.message,{code:l.code,status:400});return s},G=async(o,s,l,c)=>{const w=e.cronJobs?.[o];if(!w)return 0;for(const y of w)try{await ee(y,s)}catch(P){l.push(c(P))}return w.length},fe=async(o,s)=>{if(L(o),$(o,"POST","cron-jobs run"),!e.cronJobs)throw new d("cron-jobs run endpoint requires a `cronJobs` map on the worker",{code:"CRON_JOBS_NOT_CONFIGURED",status:400});const l=await te(o),c=typeof l.name=="string"?l.name:"";if(c==="")throw new d("cron-jobs run endpoint requires a job `name`",{code:"BAD_REQUEST",status:400});const w=Object.values(e.cronJobs).flat().find(y=>y.name===c);if(!w)throw new d(`no cron job named "${c}" is registered`,{code:"CRON_JOB_NOT_FOUND",status:404});return await ee(w,s),Response.json({name:c,ran:!0},{status:200})},ae=async o=>{const s=typeof o.pool=="string"&&o.pool.length>0?o.pool:void 0;if(!s||!u||typeof o.id!="string")return;const l=typeof o.instanceName=="string"&&o.instanceName.length>0?o.instanceName:"default";try{await ge(u,l).fetch(new Request("https://scheduler.internal/complete",{body:JSON.stringify({id:o.id,pool:s}),headers:{"content-type":"application/json"},method:"POST"}))}catch{}},_e=async(o,s)=>{$(o,"POST","Scheduler dispatch");const l=await Kt(o),c=s??{},w=typeof c.LUNORA_SCHEDULER_SECRET=="string"?c.LUNORA_SCHEDULER_SECRET:void 0,y=e.adminToken??(typeof c.LUNORA_ADMIN_TOKEN=="string"?c.LUNORA_ADMIN_TOKEN:void 0),P=o.headers.get("x-lunora-scheduler-signature");let v=!1;if(P&&w?v=await os(w,l,P):y&&(v=Ht(o,y)),!v)throw new d("Scheduler dispatch requires a valid signature or admin bearer",{code:"DISPATCH_UNAUTHENTICATED",status:403});let E;try{E=JSON.parse(l)}catch{throw new d("Scheduler dispatch body must be valid JSON",{code:"BAD_REQUEST",status:400})}const _=E??{},D=_.args??{},H=typeof _.id=="string"&&_.id.length>0?_.id:void 0;if(typeof _.workflow=="string"&&_.workflow.length>0)return await J(_.workflow,D,s,"scheduled workflow",H),await ae(_),Response.json({ok:!0},{status:200});if(typeof _.functionPath!="string"||_.functionPath.length===0)throw new d("Scheduler dispatch is missing `functionPath`",{code:"BAD_REQUEST",status:400});const x=typeof _.shardKey=="string"&&_.shardKey.length>0?_.shardKey:r,X=ja(o),B=await F(_.functionPath,D,x,H,X);return await ae(_),B},Pe=Qr({assertAdmin:L,getReader:()=>e.authAuditReader}),Ne=async(o,s)=>{L(o);const l=e.notifySubscriptionStore;if(l===void 0)return Response.json({result:ke({subscriptions:[]})},{headers:{"content-type":"application/json"},status:200});const c=s?.kind,w=s?.userId,y=s?.limit,P=c==="fcm"||c==="web-push"?c:void 0,v=typeof w=="string"&&w!==""?w:void 0,E=typeof y=="number"&&Number.isFinite(y)?Math.trunc(y):0,_=E>0?Math.min(E,1e3):1e3,H=(await l.list({kind:P,limit:_,userId:v})).filter(x=>P!==void 0&&x.kind!==P?!1:v===void 0||(x.userId??null)===v).map(({keys:x,token:X,...B})=>B);return Response.json({result:ke({subscriptions:H})},{headers:{"content-type":"application/json"},status:200})},se=async(o,s)=>{if(!s.fanOut&&!(s.functionPath!==gt&&s.functionPath!==Fa))return await U(o),s.functionPath===gt?Pe(o,s.args??{}):Ne(o,s.args)},tn=wo({applyGlobals:e.applyGlobals,assertAdmin:L,exportCursorStore:e.exportCursorStore,exportSinks:e.exportSinks,defaultShardKey:r,knownTables:()=>[...e.listSchemaTables?.()??[]],queryCoordinator:e.queryCoordinator,requireAdminOption:q,resolveForwardContext:M,shardDO:i,streamExportRows:(o,s,l,c)=>Jt(e,o,s,l,c,i),streamingImport:(o,s)=>Ro(o,e,s,i),syncGlobals:e.syncGlobals}),De=(o,s)=>{const l=o.searchParams.get(s);return l===null||l===""?void 0:l},Ue=o=>{const s=new URL(o.url),l=s.searchParams.get("limit"),c=s.searchParams.get("offset"),w=l===null?void 0:Number.parseInt(l,10),y=c===null?void 0:Number.parseInt(c,10);return{limit:w!==void 0&&Number.isFinite(w)&&w>=0?w:void 0,offset:y!==void 0&&Number.isFinite(y)&&y>=0?y:void 0}},nt=()=>{if(u===void 0)throw new d("scheduled endpoints require a `schedulerDO` namespace on the worker",{code:"SCHEDULER_NOT_CONFIGURED",status:400});return u},nn=wa({checkWsAdmin:async o=>O(o)||as(o,A(),g()),requireSchedulerNamespace:nt,resolveSchedulerStub:o=>(L(o),ge(nt(),e.schedulerInstanceName??"default")),schedulerInstanceName:e.schedulerInstanceName??"default"}),rn=ka({assertAdmin:L,resolveWorkflowsClient:e.workflowsClient??(()=>{})}),on=nr({assertAdmin:L,parsePaging:Ue,queryParameter:De,readBodyBytes:Yn,requireAdminOption:q,storage:{storageBuckets:e.storageBuckets,storageDelete:e.storageDelete,storageDownload:e.storageDownload,storageList:e.storageList,storageSignedUrl:e.storageSignedUrl,storageUpload:e.storageUpload}}),an=oo({options:e,readJsonBody:te,requireAdminOption:q}),sn=Ea({readJsonBody:te,requireAdminOption:q,vectorIntrospector:e.vectorIntrospector}),cn=xo({kvIntrospector:e.kvIntrospector,readJsonBody:te,requireAdminOption:q}),dn=fr({logArchive:e.logArchive,readJsonBody:te,requireAdminOption:q}),un=Uo({assertAdmin:L,options:{cronJobs:e.cronJobs,functions:e.functions,globalIntrospector:e.globalIntrospector,openApiSpec:e.openApiSpec,openRpcSpec:e.openRpcSpec},parsePaging:Ue,queryParameter:De,requireAdminOption:q}),ln=o=>{const s=[],l=i??o?.SHARD;if(l!==void 0&&s.push(ur("durable-object:default",l,r)),e.health?.disableBindingProbes!==!0)for(const[c,w]of Object.entries(o??{})){const y=ss(c,w);y!==void 0&&s.push(y)}for(const c of e.health?.probes??[])s.push(c);return s},hn=dr({appName:e.health?.appName,appVersion:e.health?.appVersion,auth:e.health?.auth??"public",cacheTtlMs:e.health?.cacheTtlMs,isAdmin:O,resolveProbes:ln}),fn=o=>{const s=e.schedulerInstanceName??"default",l=()=>ge(o,s),c=async(E,_)=>{const D=await l().fetch(new Request(`https://scheduler.internal${E}`,_));if(!D.ok)throw new d(`ctx.scheduler: SchedulerDO ${E} failed (${String(D.status)}): ${await D.text()}`,{code:"INTERNAL",status:500});return await D.json()},w=async(E,_)=>await c(E,{body:JSON.stringify(_),headers:{"content-type":"application/json"},method:"POST"}),y=E=>{const _=E;if(_==null)throw new d("ctx.scheduler: target is required — pass a reference from the generated `internal` / `workflows` / `agents`",{code:"BAD_REQUEST",status:400});if(typeof _.binding=="string"&&_.binding.length>0)return{workflow:_.binding};if(typeof _.__lunoraRef=="string")return{functionPath:_.__lunoraRef};throw new d("ctx.scheduler: expected a reference from the generated `internal` / `workflows` / `agents` — a bare function-path string is refused here, because an HTTP action can be reached unauthenticated",{code:"BAD_REQUEST",status:400})},P=async()=>await _r(async E=>c(E===void 0?"/list":`/list?cursor=${encodeURIComponent(E)}`,{method:"GET"})),v=async(E,_,D={})=>{const{id:H}=await w("/schedule",{args:D,scheduledFor:E,...y(_)});return H};return{cancel:async E=>await w("/cancel",{id:E}),get:async E=>await c(`/get?id=${encodeURIComponent(E)}`,{method:"GET"}),list:P,runAfter:async(E,_,D)=>{if(!Number.isFinite(E)||E<0)throw new d("ctx.scheduler.runAfter: `delayMs` must be a non-negative finite number",{code:"INVALID_INPUT",status:400});return await v(Date.now()+E,_,D)},runAt:async(E,_,D)=>{if(!Number.isFinite(E))throw new d("ctx.scheduler.runAt: `date` must be a non-negative finite number",{code:"INVALID_INPUT",status:400});return await v(E,_,D)}}},pn=async(o,s,l)=>{const{claims:c,headers:w,userId:y}=await de(o,s,a),P=be(s,o,_=>l.waitUntil?.(_)),v=_=>async(D,H={})=>{const x=D.__lunoraRef;if(typeof x!="string")throw new d("ctx.run*: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});Se(x);const X=await Ee(o,x,ke(H),_,{...w,"x-lunora-system":"1"},P),B=await X.json();if(B.error)throw new d(B.error.message??"shard RPC failed",{code:B.error.code??"INTERNAL",status:X.status});return Mt(B.result)},E=v(r);return{auth:{getIdentity:()=>Promise.resolve(c),userId:y},cache:l.cache,fetch:globalThis.fetch.bind(globalThis),forShard:_=>{const D=v(_);return{runAction:D,runMutation:D,runQuery:D}},runAction:E,runMutation:E,runQuery:E,...u===void 0?{}:{scheduler:fn(u)},...l.waitUntil===void 0?{}:{waitUntil:l.waitUntil.bind(l)},...e.storage===void 0?{}:{storage:gr(e.storage(s))}}},mn=async(o,s,l)=>{if(!e.httpRouter)return;const c=await pn(o,s,l);try{return await e.httpRouter.fetch(o,{...s,__lunoraCtx:c},l)}catch(w){return console.error("[lunora] httpRouter (SSR) handler threw:",w),new Response("Internal Server Error",{status:500})}},wn=async(o,s,l)=>{if(o.headers.get("Upgrade")!=="websocket")throw new d("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});const c=ft(o,ie);if(c)return c;const w=l.searchParams.get("shard")??r,{headers:y,identity:P}=await de(o,s,a);await C(P,w);const v=xt(o,y),E=Bt(s,e.shardDO);if(E!==void 0){v.set("x-lunora-shard-binding",E);const _=await ts(i,w);if(_>0){const D=Ur(w,Math.floor(Math.random()*_));return m(i,D,new Request(o,{headers:v}),pt(o))}}return m(i,w,new Request(o,{headers:v}))},gn=async(o,s,l)=>{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 w=ft(o,ie);if(w)return w;let y;try{y=decodeURIComponent(l.pathname.slice(Dt.length))}catch{return new Response("Unknown voice agent",{status:404})}const P=Object.hasOwn(c,y)?c[y]:void 0;if(P===void 0)return new Response("Unknown voice agent",{status:404});const v=l.searchParams.get("threadKey");if(v===null||v.length===0)return new Response("Missing threadKey",{status:400});const{headers:E,identity:_}=await de(o,s,a);if(e.authorizeShard){if(!await Ae(e.authorizeShard({identity:_,shardKey:v})))throw new d("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else W("shard");const D=xt(o,E);return m(P,v,new Request(o,{headers:D}))},yn=async(o,s,l)=>{if(e.authorizeFanOut){if(!await Ae(e.authorizeFanOut(l,o.table,s)))throw new d("Forbidden fan-out",{code:"FORBIDDEN_FANOUT",status:403});return}if(s.startsWith("__lunora_relation__:"))throw new d("reverse cross-backend relation reads (`__lunora_relation__:*`) require `authorizeFanOut` to be configured on the worker",{code:"FORBIDDEN_FANOUT",status:403});if(e.authorizeShard)throw new d("Fan-out requires `authorizeFanOut` to be configured on the worker when `authorizeShard` is set",{code:"FORBIDDEN_FANOUT",status:403});W("fan-out")},Re=async(o,s)=>{if(!(!o.fanOut&&o.functionPath.startsWith("__lunora_admin__:"))){if(o.fanOut){await yn(o.fanOut,o.functionPath,s);return}await C(s,o.shardKey??r)}},bn=(o,s,l)=>{if(e.replicaReads!==!0)return;if(e.functions===void 0){j();return}if(e.functions[s]?.kind!=="query"||l.includes(Je)||l.includes(Ve))return;const c=pt(o);return c===void 0?void 0:{name:Cr(l,c),region:c}},_n=async(o,s,l,c,w)=>{const y=bn(o,s,c);if(y!==void 0){const P={...w,"x-lunora-replica-read":"1",...b===void 0?{}:{"x-lunora-shard-binding":b}},v=Br(o.headers.get("x-lunora-min-seq"));v!==void 0&&(P["x-lunora-min-seq"]=String(v));const E=await m(i,y.name,ve(s,l,P),y.region);if(E.status!==421)return E}return m(i,c,ve(s,l,w))},Ee=async(o,s,l,c,w,y)=>{const P=Date.now(),{observability:v,sampling:E}=e,_=ze(o),{decision:D,ignoredUpstream:H,trace:x}=aa(o,{...E===void 0?{}:{sampling:E},trustInbound:t(o)});H&&n();const X={...w,"x-lunora-sample-errors":D.keepErrors?"1":"0"};sa(x,X);try{const B=await _n(o,s,l,c,X);ce(v,{..._,...Nt(x),durationMs:Date.now()-P,functionPath:s,ok:B.ok,shardKey:c,...B.ok?{}:{error:{code:"SHARD_ERROR",message:`shard returned ${String(B.status)}`,status:B.status}}},y,void 0,{isTraced:x.sampled,keepErrors:D.keepErrors});const ne=new Response(B.body,{headers:B.headers,status:B.status,statusText:B.statusText});return ne.headers.set("x-lunora-shard-key",c),ne}catch(B){throw ce(v,{..._,...Nt(x),...Te(s,Date.now()-P,B,{shardKey:c})},y,void 0,{isTraced:x.sampled,keepErrors:D.keepErrors}),B}},Rn=o=>{if(o.fanOut&&o.shardKey)throw new d("RPC envelope cannot set both `shardKey` and `fanOut`",{code:"BAD_REQUEST",status:400});if(o.fanOut||Se(o.functionPath),o.fanOut&&!e.queryCoordinator)throw new d("RPC envelope set `fanOut` but no `queryCoordinator` is configured on the worker",{code:"BAD_REQUEST",status:400})},En=async(o,s,l)=>{$(o,"POST","RPC");const c=await Xa(o);Ya(s,c),Rn(c);const w=await se(o,c);if(w!==void 0)return w;const{headers:y,identity:P}=await de(o,s,a);await Re(c,P);const v=We(c,e);{const E=Date.now(),{observability:_}=e,D=ze(o),H=be(s,o,l&&(B=>l.waitUntil?.(B)));if(c.fanOut){const B=e.queryCoordinator;if(!B)throw new d("RPC envelope set `fanOut` but no `queryCoordinator` is configured on the worker",{code:"BAD_REQUEST",status:400});try{const ne=await B.fanOut(i,{args:c.args??{},fanOut:c.fanOut,functionPath:c.functionPath,headers:y});return ce(_,{durationMs:Date.now()-E,fanOut:{failed:ne.failed,shards:ne.ok+ne.failed,table:c.fanOut.table},functionPath:c.functionPath,...D,ok:!0},H),Response.json(ne,{headers:{"content-type":"application/json"},status:200})}catch(ne){throw ce(_,{...Te(c.functionPath,Date.now()-E,ne,{fanOut:{table:c.fanOut.table}}),...D},H),ne}}const x=c.shardKey??r,X=()=>Ee(o,c.functionPath,c.args??{},x,y,H);return v&&e.x402Charge?e.x402Charge(o,{functionPath:c.functionPath,price:v.price},X,Qe(l)):X()}},Sn=async(o,s,l)=>{$(o,"POST","RPC batch");const c=await te(o),{calls:w}=c;if(!Array.isArray(w))throw new d("RPC batch `calls` must be an array",{code:"BAD_REQUEST",status:400});const{headers:y,identity:P}=await de(o,s,a),v=so(w,r);for(const Q of v.values())for(const z of Q)if(e.functions?.[z.functionPath]?.x402)throw new d(`paid (\`.x402\`) function "${z.functionPath}" cannot be called in a batch; dispatch it individually over ${Pt}`,{code:"BAD_REQUEST",status:400});await Promise.all([...v.entries()].flatMap(([Q,z])=>z.map(oe=>Re({args:oe.args,functionPath:oe.functionPath,shardKey:Q},P))));const{observability:E}=e,_=be(s,o,l&&(Q=>l.waitUntil?.(Q))),D=ze(o),H=[],x=[],X=(Q,z,oe,ue)=>({body:{error:{code:oe,message:ue}},id:Q.id,status:z}),B=(Q,z,oe,ue,pe)=>{for(const Y of Q)ce(E,pe(Y),_),H.push(X(Y,z,oe,ue))},ne=(Q,z,oe,ue,pe)=>{for(const Y of Q){const me=ue.get(Y.id)??pe,ye=me<400;ce(E,{durationMs:oe,functionPath:Y.functionPath,...D,ok:ye,shardKey:z,...ye?{}:{error:{code:"SHARD_ERROR",message:`batched call returned ${String(me)}`,status:me}}},_)}};await Promise.all([...v.entries()].map(async([Q,z])=>{const oe=new Headers(y);oe.set("content-type","application/json");const ue=new Request("https://shard.internal/rpc-batch",{body:JSON.stringify({calls:z}),headers:oe,method:"POST"}),pe=Date.now();let Y;try{Y=await m(i,Q,ue)}catch(Z){const He=Date.now()-pe,{body:it}=Ln(Z,{fallbackCode:"SHARD_UNAVAILABLE",redactedMessage:"shard unavailable"});B(z,502,it.code,it.message,xn=>({...Te(xn.functionPath,He,Z,{shardKey:Q}),...D}));return}const me=Date.now()-pe,ye=Y.headers.get("x-d1-bookmark");ye&&x.push(ye);let Be;try{Be=await Y.json()}catch{const Z=`shard batch returned a non-JSON response (${String(Y.status)})`;B(z,Y.status,"SHARD_ERROR",Z,He=>({durationMs:me,error:{code:"SHARD_ERROR",message:Z,status:Y.status},functionPath:He.functionPath,...D,ok:!1,shardKey:Q}));return}const xe=Array.isArray(Be.results)?Be.results:[],Cn=new Map(xe.map(Z=>[Z.id,Z.status??Y.status])),Bn=new Set(xe.map(Z=>Z.id));ne(z,Q,me,Cn,Y.status),H.push(...xe);for(const Z of z)Bn.has(Z.id)||H.push(X(Z,Y.status,"SHARD_ERROR",`shard batch omitted result for call ${String(Z.id)}`))}));const at={"content-type":"application/json"},[st]=x;return x.length===1&&st!==void 0&&(at["x-d1-bookmark"]=st),Response.json({results:H},{headers:at,status:200})},An=async(o,s,l,c={},w={})=>{try{const y=l.__lunoraRef;if(typeof y!="string")throw new d("serverQuery: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});Se(y);const{headers:P,identity:v}=await de(o,s,a,w.context),E={args:c,functionPath:y,shardKey:w.shardKey};await Re(E,v);const _=w.shardKey??r,D=be(s,o,w.waitUntil),H=()=>Ee(o,y,c,_,P,D),x=We(E,e);return x&&e.x402Charge?await e.x402Charge(o,{functionPath:y,price:x.price},H,Qe(w.waitUntil?{waitUntil:w.waitUntil}:w.context)):await H()}catch(y){return ct(y)}},rt=async(o,s,l)=>{const{observability:c}=e,w=Date.now(),y=Ie(16),P=Ie(8),v=Ct(s);try{const E=await l();return ce(c,{durationMs:Date.now()-w,functionPath:o,ok:!0,spanId:P,traceId:y},v),E}catch(E){throw ce(c,{...Te(o,Date.now()-w,E,{}),spanId:P,traceId:y},v),E}finally{ut(c,v)}},Tn=async(o,s,l)=>{R(s);const c=[],w=_=>_ instanceof Error?_:new Error(String(_)),y=e.crons?.[o.cron];if(y)try{await y(o,s,l)}catch(_){c.push(w(_))}const P=await G(o.cron,s,c,w),v=!!e.backupStore&&e.backupCron!==void 0&&e.backupCron===o.cron;if(v)try{await eo(e,i,A(),o)}catch(_){c.push(w(_))}if(!y&&P===0&&!v){const _=[...new Set([...Object.keys(e.crons??{}),...Object.keys(e.cronJobs??{})])];console.warn(`[lunora] scheduled("${o.cron}") fired but no cron handler is registered for that expression. Registered: ${_.length===0?"(none)":_.join(", ")}. Check that \`triggers.crons\` in wrangler.jsonc matches the app's cron definitions.`)}const[E]=c;if(c.length===1&&E)throw E;if(c.length>1)throw new AggregateError(c,`scheduled("${o.cron}") had ${String(c.length)} failure(s)`)},On=async(o,s)=>{try{const l=o??{},c=e.adminToken??(typeof l.LUNORA_ADMIN_TOKEN=="string"?l.LUNORA_ADMIN_TOKEN:void 0);if(!c||c.length===0)return;await m(i,r,ve(Ka,{outcome:s},{authorization:`Bearer ${c}`,"content-type":"application/json"}))}catch{}},vn=async(o,s,l,c)=>{if(!e.authHandler)return;const w=await e.authHandler(o);if(!w)return;const y=e.authBasePath??Ut;return Qa(l.pathname,y)&&c.waitUntil?.(On(s,w.status>=400?"fail":"ok")),w},kn=async({args:o,env:s,functionPath:l,request:c,shardKey:w,waitUntil:y})=>{jt(o,"REST");const P={functionPath:l,...w===void 0?{}:{shardKey:w}},{headers:v,identity:E}=await de(c,s,a);await Re(P,E);const _=w??r,D=be(s,c,y),H=()=>Ee(c,l,o,_,v,D),x=We(P,e);return x&&e.x402Charge?e.x402Charge(c,{functionPath:l,price:x.price},H,Qe({waitUntil:y})):H()},In=qn({functions:e.functions??{},invoke:kn,readJsonBody:te,edgeCache:e.restEdgeCache,...e.restRateLimit?{rateLimit:e.restRateLimit}:{}}),Ce=e.routes!==void 0&&Object.keys(e.routes).length>0?e.routes:void 0,Pn={[La]: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"}}),[Na]:(o,s,l)=>wn(o,s,l),[Pt]:(o,s,l,c)=>En(o,s,c),[Pa]:(o,s,l,c)=>Sn(o,s,c),[Da]:(o,s)=>_e(o,s),[Ua]:(o,s)=>fe(o,s),[Ca]:async o=>{$(o,"POST","ws-token"),L(o);const s=A();if(s===void 0)throw new d("ws-token minting requires a configured admin token",{code:"ADMIN_TOKEN_NOT_CONFIGURED",status:400});const l=await $r(s);return Response.json(l,{headers:{"cache-control":"no-store"}})},...V,...tn,...nn,...rn,...on,...an,...sn,...cn,...dn,...un,...hn,...In,...Gr({assertAdmin:L,getAuthAdmin:()=>e.authAdmin,parsePaging:Ue,queryParameter:De,readJsonBody:te})};let ie=ht(e.security),ot=!1;const Nn=o=>{ot||(ot=!0,ie=ht(e.security,o??{}))},Dn=async(o,s)=>{Ma(s)&&await U(o)},Un=async(o,s,l)=>{qe.set(o,l);const c=new URL(o.url);if((c.pathname.startsWith(xa)||e.authHandler!==void 0&&za(c.pathname,e.authBasePath??Ut))&&(o.method==="POST"||o.method==="PUT")){const E=Number(o.headers.get("content-length")??""),_=Ia[c.pathname]??$t;if(Number.isFinite(E)&&E>_)throw new d("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413})}const y=await vn(o,s,c,l);if(y)return y;if(Ce){const E=`${o.method} ${c.pathname}`,_=Ce[E]??Ce[c.pathname];if(_)return _(o,s,l)}const P=Pn[c.pathname];if(P)return await Dn(o,c.pathname),P(o,s,c,l);if(e.voiceAgents!==void 0&&c.pathname.startsWith(Dt))return gn(o,s,c);const v=await mn(o,s,l);return v||new Response("Not found",{status:404})};return{async fetch(o,s,l){e.passThroughOnException&&l.passThroughOnException?.(),Nn(s),R(s);const c=mr(o,ie);if(c)return c;const w=wr(o,ie);if(w)return Me(w,o,ie);try{const y=await Un(o,s,l);return Me(y,o,ie)}catch(y){return Me(ct(y),o,ie)}finally{ut(e.observability,Ct(l))}},async queue(o,s,l){await rt(`queue:${Va(o)}`,l,async()=>{await e.queue?.(o,s,l)})},async scheduled(o,s,l){await rt(`cron:${o.cron}`,l,async()=>{await Tn(o,s,l)})},serverQuery:An}},cs=e=>en(e),ds=e=>typeof e=="function"?{fetch:e}:e,us=e=>!!(e.crons??e.cronJobs??e.backupCron),Ds=(e,t)=>{const n=ds(e),r=typeof e=="object"&&typeof e.scheduled=="function"?e.scheduled:void 0,a=u=>{const h=cs({...u,httpRouter:n});return r!==void 0&&!us(u)?{...h,scheduled:async(p,m,S)=>{await r(p,m,S)}}:h};if(typeof t!="function")return a(t);const i=t;return{fetch:(u,h,p)=>a(i(h)).fetch(u,h,p),queue:(u,h,p)=>a(i(h)).queue?.(u,h,p)??Promise.resolve(),scheduled:(u,h,p)=>a(i(h)).scheduled(u,h,p),serverQuery:(u,h,p,m,S)=>a(i(h)).serverQuery(u,h,p,m,S)}},ls=(e,t)=>{if(typeof e=="function")return e(t);const n=e.shardDO??t?.SHARD;if(!n)throw new d("@lunora/runtime: no shard Durable Object namespace found. Bind `SHARD` in wrangler.jsonc, or pass `createLunoraHandler({ shardDO: env.MY_SHARD })`.");return{...e,shardDO:n}},Us=(e={})=>(t,n,r)=>en(ls(e,n)).fetch(t,n,r??Mn),Cs=e=>e;export{gt as GET_AUTH_AUDIT_LOG_OP,Mn as NOOP_EXECUTION_CONTEXT,Hs as composeIdentityResolvers,cs as composeWorker,Us as createLunoraHandler,en as createWorker,Cs as defineRpcEnvelope,ts as probeRelayCount,ls as resolveLunoraOptions,Ls as routeIdentityResolvers,Ds as withFrameworkWorker};
@@ -1 +0,0 @@
1
- const R={debug:5,error:17,fatal:21,info:9,log:9,trace:1,warn:13},A=e=>`${String(Math.round(e))}000000`,_=Array.from({length:256},(e,r)=>r.toString(16).padStart(2,"0")),l=512,m=new Uint8Array(l);let a=l;const v=(e,r,t)=>{let o="";for(let n=0;n<t;n+=1)o+=_[e[r+n]];return o},S=e=>{if(e>l){const t=new Uint8Array(e);return crypto.getRandomValues(t),v(t,0,e)}a+e>l&&(crypto.getRandomValues(m),a=0);const r=v(m,a,e);return a+=e,r},u=/^[0-9a-f]+$/,b=(e,r,t=!0)=>`00-${e}-${r}-${t?"01":"00"}`,N=e=>{if(e==null)return;const r=e.trim().toLowerCase().split("-"),[t,o,n,s]=r;if(!(r.length<4||t===void 0||t.length!==2||!u.test(t)||t==="ff"||t==="00"&&r.length!==4||o===void 0||n===void 0||s===void 0||s.length!==2||!u.test(s)||o.length!==32||n.length!==16||!u.test(o)||!u.test(n)||o==="00000000000000000000000000000000"||n==="0000000000000000"))return{parentSpanId:n,sampled:(Number.parseInt(s,16)&1)===1,traceId:o}},O=(e,r)=>typeof r=="boolean"?{key:e,value:{boolValue:r}}:typeof r=="number"?Number.isFinite(r)?Number.isSafeInteger(r)?{key:e,value:{intValue:String(r)}}:{key:e,value:{doubleValue:r}}:{key:e,value:{stringValue:String(r)}}:{key:e,value:{stringValue:r}},T=e=>e===void 0?[]:Object.entries(e).map(([r,t])=>O(r,t)),L=(e,r,t)=>{const o={},n=new Map,s=(c,i)=>{const p=c.toLowerCase(),g=n.get(p);g===void 0?(n.set(p,c),o[c]=i):o[g]=i};for(const[c,i]of Object.entries(e))s(c,i);for(const[c,i]of Object.entries(r??{}))s(c,i);return t!==void 0&&t.length>0&&s("authorization",`Bearer ${t}`),o},d=e=>Array.isArray(e)?e:[e],h={client:3,consumer:5,internal:1,producer:4,server:2},C=Object.freeze({durationMs:"lunora.duration_ms",errorMessage:"error.message",errorType:"error.type",functionPath:"lunora.function_path",ok:"lunora.ok",shardKey:"lunora.shard_key",userId:"lunora.user_id"}),f=(e,r)=>{const t={"service.name":e};for(const[o,n]of Object.entries(r??{}))t[o]=n;return Object.entries(t).map(([o,n])=>O(o,n))},I=(e,r,t,o)=>({resourceSpans:[{resource:{attributes:f(t,o)},scopeSpans:[{scope:{name:r},spans:d(e)}]}]}),V=(e,r,t,o)=>({resourceLogs:[{resource:{attributes:f(t,o)},scopeLogs:[{logRecords:d(e),scope:{name:r}}]}]}),M=(e,r,t,o)=>({resourceMetrics:[{resource:{attributes:f(t,o)},scopeMetrics:[{metrics:d(e),scope:{name:r}}]}]}),y=e=>r=>{const t=e?.[r];return typeof t=="string"&&t.length>0?t:void 0},E=(e,r)=>{if(typeof e!="object"||e===null)return;const t=e[r];return typeof t=="string"&&t.length>0?t:void 0},w=e=>{const r={},t=e("SERVICE_VERSION")??e("CF_VERSION_METADATA")??e("VERCEL_GIT_COMMIT_SHA")??e("GITHUB_SHA")??e("COMMIT_SHA");t!==void 0&&(r["service.version"]=t);const o=e("DEPLOYMENT_ENVIRONMENT")??e("ENVIRONMENT")??e("NODE_ENV");return o!==void 0&&(r["deployment.environment"]=o),r},x=(e,r)=>{if(!(r!==void 0||e("CLOUDFLARE")!==void 0||e("CF_ACCOUNT_ID")!==void 0))return{};const o={"cloud.provider":"cloudflare"},n=E(r,"colo")??e("CF_COLO")??e("CLOUDFLARE_COLO");return n!==void 0&&(o["cloud.region"]=n),o},H=(...e)=>{const r={};for(const t of e)if(t!==void 0)for(const[o,n]of Object.entries(t))r[o]=n;return r};export{C as L,h as O,w as a,b,A as c,x as d,O as e,R as f,T as g,L as h,M as i,V as j,H as m,S as o,N as p,y as r,I as w};
@@ -1 +0,0 @@
1
- import{c as S,d as T,e as O,a as B,f as P}from"./rest-cache-D1BlbZb1.mjs";import{LunoraError as l}from"./LunoraError-DksAgIpa.mjs";import{m as D}from"./method-guard-BG_vJNTl.mjs";const w=1048576,_=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),U=async(e,r=w)=>{if(!e.body)return"";const t=e.body.getReader(),a=new TextDecoder;let i=0,s="";for(;;){const{done:o,value:n}=await t.read();if(o)break;if(n){if(i+=n.byteLength,i>r)throw await t.cancel().catch(()=>{}),new l("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});s+=a.decode(n,{stream:!0})}}return s+=a.decode(),s},W=async(e,r=w)=>{if(!e.body)return new ArrayBuffer(0);const t=e.body.getReader(),a=[];let i=0;for(;;){const{done:n,value:c}=await t.read();if(n)break;if(c){if(i+=c.byteLength,i>r)throw await t.cancel().catch(()=>{}),new l("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});a.push(c)}}const s=new Uint8Array(i);let o=0;for(const n of a)s.set(n,o),o+=n.byteLength;return s.buffer},j=async(e,r,t=w)=>{try{const a=await U(e,t);return a===""?{}:JSON.parse(a)}catch(a){throw a instanceof l?a:new l(`${r} body must be valid JSON`,{code:"BAD_REQUEST",status:400})}},X=async(e,r=w)=>{const t=await j(e,"Request",r);if(!_(t))throw new l("Request body must be an object",{code:"BAD_REQUEST",status:400});return t},x=(e,r)=>{if(!_(e))throw new l(`${r} \`args\` must be an object`,{code:"BAD_REQUEST",status:400})},b="__lunora_vary",C="x-lunora-edge-cache",G=["x-d1-bookmark","x-lunora-shard-key"],M=()=>{try{return globalThis.caches?.default}catch{return}},k=e=>e.split(",").map(r=>r.trim().toLowerCase()).filter(r=>r!==""),J=(e,r)=>{const t=e.headers.get("vary");return t===null?!0:k(t).every(a=>a!=="*"&&r.includes(a))},K=(e,r)=>{if(e===void 0||r===null||e.scope!=="public"||S(e.maxAge)<=0)return;const t=()=>r??M(),a=k(T(e)??""),i=o=>{const n=new URL(o.url);return n.searchParams.delete(b),a.length>0&&n.searchParams.set(b,a.map(c=>`${c}=${o.headers.get(c)??""}`).join("\0")),new Request(n.toString(),{method:"GET"})},s=(o,n)=>o.method==="GET"&&O(e,o,n)==="public";return{lookup:async(o,n)=>{const c=t();if(c===void 0||!s(o,n))return;let u;try{u=await c.match(i(o))}catch{return}if(u===void 0)return;const h=new Response(u.body,u);return h.headers.set(C,"hit"),h},store:(o,n,c)=>{const u=t();if(u===void 0||!s(n,c)||o.status!==200||o.headers.has("set-cookie")||o.headers.has("x-payment-response")||!J(o,a))return o;try{const h=new Response(o.clone().body,o);for(const R of G)h.headers.delete(R);const d=Promise.resolve(u.put(i(n),h)).catch(()=>{});c?.waitUntil&&c.waitUntil(d)}catch{}return o}}},N=e=>P(Object.entries(e).map(([r,t])=>({exposure:t.expose,functionPath:r,kind:t.kind}))),Y=(e,r)=>{const t=e.searchParams.get("shardKey");if(t!==null&&t!=="")return t;const a=r.headers.get("x-lunora-shard-key");return a===null||a===""?void 0:a},F=e=>{const r=Object.create(null);for(const[t,a]of e.searchParams.entries())if(!(t==="shardKey"||t===b))try{r[t]=JSON.parse(a)}catch{r[t]=a}return r},z=e=>{const{edgeCache:r,functions:t,invoke:a,rateLimit:i,readJsonBody:s}=e,o={};for(const n of N(t)){const c=n.kind==="query"?["GET","POST"]:["POST"],u=t[n.functionPath].expose?.cache,h=K(u,r);o[n.path]=async(d,R,Q,f)=>{const E=D(d,c);if(E)return E;const g=new URL(d.url);if(i){const m=await i(d,n.functionPath);if(m)return m}const v=await h?.lookup(d,f);if(v)return v;let y;d.method==="GET"?y=F(g):y=d.body===null?{}:await s(d),x(y,"REST");const p=Y(g,d),L=await a({args:y,env:R,functionPath:n.functionPath,request:d,...p===void 0?{}:{shardKey:p},...f?.waitUntil===void 0?{}:{waitUntil:m=>f.waitUntil?.(m)}}),A=B(L,u,d,f);return h?h.store(A,d,f):A}}return o},H="no-trusted-ip",Z=(e,r)=>async(t,a)=>{const i=(r.key?r.key(t,a):t.headers.get("cf-connecting-ip"))??H,s=await e.limit(r.name,{key:i});if(s.ok)return;if(s.reason==="deny")return Response.json({error:{code:"FORBIDDEN",message:"Request denied"}},{headers:{"content-type":"application/json"},status:403});const o=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(o)},status:429})};export{w as M,F as a,z as b,Z as c,X as d,j as e,W as f,x as g,U as h,N as r};
@@ -1 +0,0 @@
1
- import{a as p,b as E}from"./base64-Bl1_r2k1.mjs";const o="$lunora.wire$",d=64,g=1024,w="__proto__",A={BigInt64Array,BigUint64Array,Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array},l={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError},O=e=>{if(e===null||typeof e!="object")return!1;const n=Object.getPrototypeOf(e);return n===null||n===Object.prototype},y=(e,n=0)=>{if(n>d)throw new RangeError(`wire-codec: value nesting exceeds the ${d}-level limit`);if(e===void 0)return[o,"undefined"];if(e===null)return null;const u=typeof e;if(u==="bigint")return[o,"bigint",e.toString()];if(u==="number"){const r=e;return Number.isNaN(r)?[o,"nan"]:r===1/0?[o,"inf"]:r===-1/0?[o,"-inf"]:r}if(u!=="object")return e;if(e instanceof Date)return[o,"date",y(e.getTime(),n+1)];if(e instanceof Error){const r=e,t={};for(const i of Object.keys(r)){if(r[i]===void 0)continue;const a=y(r[i],n+1);i===w?Object.defineProperty(t,i,{configurable:!0,enumerable:!0,value:a,writable:!0}):t[i]=a}const c=[o,"error",r.name,r.message,t];return r.cause!==void 0&&c.push(y(r.cause,n+1)),c}if(e instanceof URL)return[o,"url",e.href];if(e instanceof Map)return[o,"map",[...e.entries()].map(([r,t])=>[y(r,n+1),y(t,n+1)])];if(e instanceof Set)return[o,"set",[...e].map(r=>y(r,n+1))];if(e instanceof ArrayBuffer)return[o,"bytes",p(new Uint8Array(e)),"ArrayBuffer"];if(ArrayBuffer.isView(e)){const r=e,t=r.constructor.name,c=new Uint8Array(r.buffer,r.byteOffset,r.byteLength);return t==="Uint8Array"?[o,"bytes",p(c)]:[o,"bytes",p(c),t]}if(Array.isArray(e)){const r=e.map(t=>y(t,n+1));return r.length>0&&r[0]===o?[o,"arr",r]:r}if(!O(e)){const r=e.constructor?.name??"value";throw new TypeError(`wire-codec: cannot encode a ${r} over the Lunora wire — only plain objects, arrays, and the supported built-ins (Date, Error, URL, Map, Set, ArrayBuffer/typed arrays, bigint) round-trip`)}const b=e,s={};for(const r of Object.keys(b)){const t=b[r];if(t===void 0)continue;const c=y(t,n+1);r===w?Object.defineProperty(s,r,{configurable:!0,enumerable:!0,value:c,writable:!0}):s[r]=c}return s},f=(e,n=0)=>{if(n>d)throw new RangeError(`wire-codec: value nesting exceeds the ${d}-level limit`);if(e===null||typeof e!="object")return e;if(Array.isArray(e)){if(e[0]===o)switch(e[1]){case"-inf":return-1/0;case"arr":return e[2].map(r=>f(r,n+1));case"bigint":{const r=e[2];if(typeof r!="string"||r.length>g||!/^-?\d+$/.test(r))throw new RangeError(`wire-codec: invalid or over-long bigint (max ${g} digits)`);return BigInt(r)}case"date":{const r=f(e[2],n+1);if(typeof r!="number")throw new TypeError("wire-codec: malformed date — epoch must be a number");return new Date(r)}case"map":{const r=e[2];return new Map(r.map(t=>{if(!Array.isArray(t)||t.length!==2)throw new TypeError("wire-codec: malformed map entry — expected a [key, value] pair");return[f(t[0],n+1),f(t[1],n+1)]}))}case"set":return new Set(e[2].map(r=>f(r,n+1)));case"url":{const r=e[2];if(typeof r!="string")throw new TypeError("wire-codec: malformed url — href must be a string");return new URL(r)}case"error":{const r=e[2],t=e[3],c=(Object.hasOwn(l,r)?l[r]:void 0)??Error,i=new c(t);i.name!==r&&Object.defineProperty(i,"name",{configurable:!0,value:r,writable:!0});const a=f(e[4],n+1);if(a===null||typeof a!="object"||Array.isArray(a))throw new TypeError("wire-codec: malformed error — props must be an object");for(const m of Object.keys(a))m===w?Object.defineProperty(i,m,{configurable:!0,enumerable:!0,value:a[m],writable:!0}):i[m]=a[m];return e.length>5&&Object.defineProperty(i,"cause",{configurable:!0,value:f(e[5],n+1),writable:!0}),i}case"bytes":{const r=e[2];if(typeof r!="string")throw new TypeError("wire-codec: malformed bytes — payload must be a base64 string");const t=E(r),c=e[3]??"Uint8Array";if(c==="ArrayBuffer")return t.buffer.byteLength===t.byteLength?t.buffer:t.slice().buffer;const i=Object.hasOwn(A,c)?A[c]:void 0;return i?new i(t.slice().buffer):t}case"inf":return 1/0;case"nan":return Number.NaN;case"undefined":return;default:return e.map(r=>f(r,n+1))}return e.map(s=>f(s,n+1))}const u=e,b={};for(const s of Object.keys(u)){const r=f(u[s],n+1);s===w?Object.defineProperty(b,s,{configurable:!0,enumerable:!0,value:r,writable:!0}):b[s]=r}return b};export{f as d,y as e,O as i};