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

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
@@ -223,6 +223,33 @@ interface ExecutionContextLike {
223
223
  * receives a valid third argument.
224
224
  */
225
225
  declare const NOOP_EXECUTION_CONTEXT: ExecutionContextLike;
226
+ /**
227
+ * Edge geography → placement region, shared by `@lunora/runtime` (which reads
228
+ * `request.cf` to pick where a shard, replica, or region-local socket should
229
+ * live) and `@lunora/do` (which parses a region out of its own DO name). Kept
230
+ * here — inlined into each consumer's bundle — so the two sides can never drift
231
+ * on the region vocabulary without creating a runtime dependency edge between
232
+ * the packages.
233
+ *
234
+ * The values are Cloudflare's Durable Object location hints, which is also the
235
+ * only vocabulary a Lunora deployment needs today: a region is *only* ever used
236
+ * as a placement hint and as a name segment, never as data. Wrong-but-close is
237
+ * fine by construction — a misrouted read is one longer hop, never a wrong
238
+ * answer — so this maps coarsely and returns `undefined` rather than guessing
239
+ * when the request carries no usable geography.
240
+ *
241
+ * Zero-dependency by design (see the repo's `shared/` rules): only relative /
242
+ * builtin imports, named exports, no `.js` extensions.
243
+ */
244
+ /**
245
+ * The placement regions a name may carry and a hint may request — Cloudflare's
246
+ * `DurableObjectLocationHint` values, listed so the set can be validated at a
247
+ * trust boundary (a region parsed out of a DO name is attacker-influenced input
248
+ * on any route that mints names from a client-supplied shard key).
249
+ */
250
+ declare const REGION_HINTS: readonly ["wnam", "enam", "sam", "weur", "eeur", "apac", "apac-ne", "apac-se", "oc", "afr", "me"];
251
+ /** One placement region. Structurally identical to Cloudflare's `DurableObjectLocationHint`. */
252
+ type RegionHint = (typeof REGION_HINTS)[number];
226
253
  /** Procedure kinds that can be exposed over REST (`stream` cannot — it is a WebSocket surface). */
227
254
  type RestFunctionKind = "action" | "mutation" | "query";
228
255
  /**
@@ -674,14 +701,23 @@ interface FunctionArgumentDescriptor {
674
701
  * @see https://developers.cloudflare.com/durable-objects/reference/data-location/
675
702
  */
676
703
  type DurableObjectJurisdiction = "eu" | "fedramp" | "us";
704
+ /**
705
+ * The options bag Cloudflare's `DurableObjectNamespace.get` / `getByName`
706
+ * accept. Only `locationHint` is modelled: it is the one member the runtime
707
+ * sets, and it is honoured **only by the call that creates the object** — every
708
+ * later resolution of the same name reaches the object where it already lives.
709
+ */
710
+ interface ShardGetOptions {
711
+ locationHint?: RegionHint;
712
+ }
677
713
  /**
678
714
  * Structural projection of the bits of `DurableObjectNamespace` the runtime
679
715
  * needs. Real workers-types defines a much wider surface; this lets us pass
680
716
  * unit-test doubles without coupling to `@cloudflare/workers-types`.
681
717
  */
682
718
  interface ShardNamespaceLike {
683
- /** Materialize a stub from an opaque id. */
684
- get: (id: unknown) => {
719
+ /** Materialize a stub from an opaque id, optionally hinting where to create it. */
720
+ get: (id: unknown, options?: ShardGetOptions) => {
685
721
  fetch: (request: Request) => Promise<Response>;
686
722
  };
687
723
  /**
@@ -689,7 +725,7 @@ interface ShardNamespaceLike {
689
725
  * release yet. We prefer it when available and fall back to
690
726
  * `idFromName` + `get` for compatibility.
691
727
  */
692
- getByName?: (name: string) => {
728
+ getByName?: (name: string, options?: ShardGetOptions) => {
693
729
  fetch: (request: Request) => Promise<Response>;
694
730
  };
695
731
  /** Cloudflare's `DurableObjectNamespace` spelling of `idForName`. */
@@ -740,8 +776,13 @@ declare const applyJurisdiction: (namespace: ShardNamespaceLike, jurisdiction?:
740
776
  * contract. Preserves the historical preference — `getByName` when present,
741
777
  * else `idFromName` + `get` — but the preference now lives in one place (the
742
778
  * contract's `resolveShard`) rather than being restated per resolution path.
779
+ *
780
+ * `locationHint` asks the platform to create the object in that region. It is
781
+ * advisory and only the *creating* resolution can honour it, so it is safe to
782
+ * pass on every call and never safe to depend on: callers must behave
783
+ * identically when the shard turns out to live somewhere else entirely.
743
784
  */
744
- declare const resolveShard: (namespace: ShardNamespaceInput, shardKey: string) => ResolvedShard;
785
+ declare const resolveShard: (namespace: ShardNamespaceInput, shardKey: string, locationHint?: RegionHint) => ResolvedShard;
745
786
  /**
746
787
  * Source of "which shard keys exist for a given table right now". Returning
747
788
  * an empty array is valid — the coordinator will respond with the merge
@@ -3714,6 +3755,26 @@ interface WorkerOptions {
3714
3755
  * stays decoupled from the queue package. Omitted when no push queues exist.
3715
3756
  */
3716
3757
  queue?: QueueConsumerHandler;
3758
+ /**
3759
+ * Serve one-shot **queries** from a read replica placed in the caller's
3760
+ * region instead of from the shard owner. Off by default.
3761
+ *
3762
+ * What it buys: a query answered near the reader rather than across an
3763
+ * ocean. What it costs: a query that names no bookmark may be up to
3764
+ * `LUNORA_REPLICA_MAX_STALENESS_MS` (default 1000) behind the owner, and
3765
+ * every replica is a second Durable Object holding a copy of the shard.
3766
+ *
3767
+ * Read-your-writes is preserved for callers that pass the `commitCursor`
3768
+ * their last write returned back as `x-lunora-min-seq`: the replica catches
3769
+ * up to at least that cursor or the read falls back to the owner. Mutations,
3770
+ * actions, streams, subscriptions, and fan-outs are never replica-routed.
3771
+ *
3772
+ * Requires CDC to be enabled on the schema — the changelog IS the
3773
+ * replication feed. Without it a replica has nothing to follow, reports
3774
+ * itself unavailable, and every read falls back to the owner (correct, and
3775
+ * one wasted hop per read).
3776
+ */
3777
+ replicaReads?: boolean;
3717
3778
  /**
3718
3779
  * Enforce the ephemeral WS admin token: the worker's WS admin gate rejects
3719
3780
  * the raw master admin token in the `?token=` query parameter — only a
@@ -3809,6 +3870,23 @@ interface WorkerOptions {
3809
3870
  security?: SecurityOptions;
3810
3871
  /** Namespace binding for the shard Durable Object (typically `env.SHARD`). */
3811
3872
  shardDO: ShardNamespaceLike;
3873
+ /**
3874
+ * Where a shard should be created, by shard key — a per-tenant placement
3875
+ * policy (`(key) => "weur"` for a European tenant, say).
3876
+ *
3877
+ * The platform already creates a shard near whichever request first touches
3878
+ * it, so this exists for the cases where that request is the wrong signal:
3879
+ * a shard first materialized by a cron fire, a migration fan-out, a seeding
3880
+ * run, or the Studio lands wherever that ran, and stays there for life. A
3881
+ * key whose region is not known yet returns `undefined`, which restores the
3882
+ * default (place near the first request).
3883
+ *
3884
+ * Advisory in both directions: the hint is honoured only by the resolution
3885
+ * that CREATES the object — changing this callback later does not move a
3886
+ * shard that already exists — and even then the platform places near the
3887
+ * hinted region rather than exactly in it.
3888
+ */
3889
+ shardRegion?: (shardKey: string) => RegionHint | undefined;
3812
3890
  /**
3813
3891
  * Resolve the app-facing storage capability from the worker `env` — the same
3814
3892
  * `createStorage(...)` / `createBucketStorage(...)` result the shard DO
package/dist/index.d.ts CHANGED
@@ -223,6 +223,33 @@ interface ExecutionContextLike {
223
223
  * receives a valid third argument.
224
224
  */
225
225
  declare const NOOP_EXECUTION_CONTEXT: ExecutionContextLike;
226
+ /**
227
+ * Edge geography → placement region, shared by `@lunora/runtime` (which reads
228
+ * `request.cf` to pick where a shard, replica, or region-local socket should
229
+ * live) and `@lunora/do` (which parses a region out of its own DO name). Kept
230
+ * here — inlined into each consumer's bundle — so the two sides can never drift
231
+ * on the region vocabulary without creating a runtime dependency edge between
232
+ * the packages.
233
+ *
234
+ * The values are Cloudflare's Durable Object location hints, which is also the
235
+ * only vocabulary a Lunora deployment needs today: a region is *only* ever used
236
+ * as a placement hint and as a name segment, never as data. Wrong-but-close is
237
+ * fine by construction — a misrouted read is one longer hop, never a wrong
238
+ * answer — so this maps coarsely and returns `undefined` rather than guessing
239
+ * when the request carries no usable geography.
240
+ *
241
+ * Zero-dependency by design (see the repo's `shared/` rules): only relative /
242
+ * builtin imports, named exports, no `.js` extensions.
243
+ */
244
+ /**
245
+ * The placement regions a name may carry and a hint may request — Cloudflare's
246
+ * `DurableObjectLocationHint` values, listed so the set can be validated at a
247
+ * trust boundary (a region parsed out of a DO name is attacker-influenced input
248
+ * on any route that mints names from a client-supplied shard key).
249
+ */
250
+ declare const REGION_HINTS: readonly ["wnam", "enam", "sam", "weur", "eeur", "apac", "apac-ne", "apac-se", "oc", "afr", "me"];
251
+ /** One placement region. Structurally identical to Cloudflare's `DurableObjectLocationHint`. */
252
+ type RegionHint = (typeof REGION_HINTS)[number];
226
253
  /** Procedure kinds that can be exposed over REST (`stream` cannot — it is a WebSocket surface). */
227
254
  type RestFunctionKind = "action" | "mutation" | "query";
228
255
  /**
@@ -674,14 +701,23 @@ interface FunctionArgumentDescriptor {
674
701
  * @see https://developers.cloudflare.com/durable-objects/reference/data-location/
675
702
  */
676
703
  type DurableObjectJurisdiction = "eu" | "fedramp" | "us";
704
+ /**
705
+ * The options bag Cloudflare's `DurableObjectNamespace.get` / `getByName`
706
+ * accept. Only `locationHint` is modelled: it is the one member the runtime
707
+ * sets, and it is honoured **only by the call that creates the object** — every
708
+ * later resolution of the same name reaches the object where it already lives.
709
+ */
710
+ interface ShardGetOptions {
711
+ locationHint?: RegionHint;
712
+ }
677
713
  /**
678
714
  * Structural projection of the bits of `DurableObjectNamespace` the runtime
679
715
  * needs. Real workers-types defines a much wider surface; this lets us pass
680
716
  * unit-test doubles without coupling to `@cloudflare/workers-types`.
681
717
  */
682
718
  interface ShardNamespaceLike {
683
- /** Materialize a stub from an opaque id. */
684
- get: (id: unknown) => {
719
+ /** Materialize a stub from an opaque id, optionally hinting where to create it. */
720
+ get: (id: unknown, options?: ShardGetOptions) => {
685
721
  fetch: (request: Request) => Promise<Response>;
686
722
  };
687
723
  /**
@@ -689,7 +725,7 @@ interface ShardNamespaceLike {
689
725
  * release yet. We prefer it when available and fall back to
690
726
  * `idFromName` + `get` for compatibility.
691
727
  */
692
- getByName?: (name: string) => {
728
+ getByName?: (name: string, options?: ShardGetOptions) => {
693
729
  fetch: (request: Request) => Promise<Response>;
694
730
  };
695
731
  /** Cloudflare's `DurableObjectNamespace` spelling of `idForName`. */
@@ -740,8 +776,13 @@ declare const applyJurisdiction: (namespace: ShardNamespaceLike, jurisdiction?:
740
776
  * contract. Preserves the historical preference — `getByName` when present,
741
777
  * else `idFromName` + `get` — but the preference now lives in one place (the
742
778
  * contract's `resolveShard`) rather than being restated per resolution path.
779
+ *
780
+ * `locationHint` asks the platform to create the object in that region. It is
781
+ * advisory and only the *creating* resolution can honour it, so it is safe to
782
+ * pass on every call and never safe to depend on: callers must behave
783
+ * identically when the shard turns out to live somewhere else entirely.
743
784
  */
744
- declare const resolveShard: (namespace: ShardNamespaceInput, shardKey: string) => ResolvedShard;
785
+ declare const resolveShard: (namespace: ShardNamespaceInput, shardKey: string, locationHint?: RegionHint) => ResolvedShard;
745
786
  /**
746
787
  * Source of "which shard keys exist for a given table right now". Returning
747
788
  * an empty array is valid — the coordinator will respond with the merge
@@ -3714,6 +3755,26 @@ interface WorkerOptions {
3714
3755
  * stays decoupled from the queue package. Omitted when no push queues exist.
3715
3756
  */
3716
3757
  queue?: QueueConsumerHandler;
3758
+ /**
3759
+ * Serve one-shot **queries** from a read replica placed in the caller's
3760
+ * region instead of from the shard owner. Off by default.
3761
+ *
3762
+ * What it buys: a query answered near the reader rather than across an
3763
+ * ocean. What it costs: a query that names no bookmark may be up to
3764
+ * `LUNORA_REPLICA_MAX_STALENESS_MS` (default 1000) behind the owner, and
3765
+ * every replica is a second Durable Object holding a copy of the shard.
3766
+ *
3767
+ * Read-your-writes is preserved for callers that pass the `commitCursor`
3768
+ * their last write returned back as `x-lunora-min-seq`: the replica catches
3769
+ * up to at least that cursor or the read falls back to the owner. Mutations,
3770
+ * actions, streams, subscriptions, and fan-outs are never replica-routed.
3771
+ *
3772
+ * Requires CDC to be enabled on the schema — the changelog IS the
3773
+ * replication feed. Without it a replica has nothing to follow, reports
3774
+ * itself unavailable, and every read falls back to the owner (correct, and
3775
+ * one wasted hop per read).
3776
+ */
3777
+ replicaReads?: boolean;
3717
3778
  /**
3718
3779
  * Enforce the ephemeral WS admin token: the worker's WS admin gate rejects
3719
3780
  * the raw master admin token in the `?token=` query parameter — only a
@@ -3809,6 +3870,23 @@ interface WorkerOptions {
3809
3870
  security?: SecurityOptions;
3810
3871
  /** Namespace binding for the shard Durable Object (typically `env.SHARD`). */
3811
3872
  shardDO: ShardNamespaceLike;
3873
+ /**
3874
+ * Where a shard should be created, by shard key — a per-tenant placement
3875
+ * policy (`(key) => "weur"` for a European tenant, say).
3876
+ *
3877
+ * The platform already creates a shard near whichever request first touches
3878
+ * it, so this exists for the cases where that request is the wrong signal:
3879
+ * a shard first materialized by a cron fire, a migration fan-out, a seeding
3880
+ * run, or the Studio lands wherever that ran, and stays there for life. A
3881
+ * key whose region is not known yet returns `undefined`, which restores the
3882
+ * default (place near the first request).
3883
+ *
3884
+ * Advisory in both directions: the hint is honoured only by the resolution
3885
+ * that CREATES the object — changing this callback later does not move a
3886
+ * shard that already exists — and even then the platform places near the
3887
+ * hinted region rather than exactly in it.
3888
+ */
3889
+ shardRegion?: (shardKey: string) => RegionHint | undefined;
3812
3890
  /**
3813
3891
  * Resolve the app-facing storage capability from the worker `env` — the same
3814
3892
  * `createStorage(...)` / `createBucketStorage(...)` result the shard DO
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 m}from"./packem_shared/BACKUP_KEY_PREFIX-DhFUE3VL.mjs";import{toAirbyteMessages as f,toFivetranResponse as E}from"./packem_shared/toAirbyteMessages-DTk8e2f9.mjs";import{composeWorker as S,createLunoraHandler as x,createWorker as _,defineRpcEnvelope as d,resolveLunoraOptions as l,withFrameworkWorker as u}from"./packem_shared/composeWorker-y5QruLqo.mjs";import{createCrossShardRelationCapabilities as k}from"./packem_shared/createCrossShardRelationCapabilities-CQfrCIWR.mjs";import{DEFAULT_REGISTRY_CACHE_TTL_MS as A,SHARD_REGISTRY_DO_NAME as C,createDynamicShardRegistry as L}from"./packem_shared/DEFAULT_REGISTRY_CACHE_TTL_MS-CCDyswsf.mjs";import{LunoraError as g,toErrorResponse as b}from"./packem_shared/LunoraError-ByasbDmd.mjs";import{createKvCursorStore as H,createMemoryCursorStore as I,defineExportSink as P,r2Sink as v,runExportTap as D,sanitizeChange as F,webhookExportSink as M}from"./packem_shared/createKvCursorStore-C24tEuYk.mjs";import{HEALTH_PATH as G,HEALTH_READY_PATH as K,buildHealthRoutes as N,d1Probe as B,durableObjectProbe as Y,presenceProbe as w}from"./packem_shared/HEALTH_PATH-BuLCcWNS.mjs";import{LOG_ARCHIVE_PATH as X,resolveLogArchiveFromEnv as j}from"./packem_shared/LOG_ARCHIVE_PATH-CuHKuDCS.mjs";import{memoizeIdentity as W,memoizeIdentityPerRequest as q}from"./packem_shared/memoizeIdentity-CX3xEPYw.mjs";import{e as J,a as Z}from"./packem_shared/observability-DWlkDJJw.mjs";import{analyticsEngineSink as ee,combineSinks as re,consoleSink as oe,otlpSink as te,pipelineLogSink as ae,sentrySink as se,webhookSink as ie}from"./packem_shared/analyticsEngineSink-iIRy11I9.mjs";import{D as pe,a as me,c as ce}from"./packem_shared/pipeline-log-reader-FF1V32O2.mjs";import{createQueryCoordinator as Ee,createStaticShardRegistry as Re,mergeStrategyForAggregate as Se}from"./packem_shared/createQueryCoordinator-BkPfcxUG.mjs";import{applyJurisdiction as _e,resolveShard as de}from"./packem_shared/applyJurisdiction-Dsm_m5zW.mjs";import{R as ue,d as ye,o as ke}from"./packem_shared/rest-cache-5unAzdFN.mjs";import{g as Ae,E as Ce,U as Le,p as Te,y as ge}from"./packem_shared/rest-routes-BqldHiaH.mjs";import{decorateResponse as he,enforceOrigin as He,handleCorsPreflight as Ie,resolveSecurity as Pe}from"./packem_shared/decorateResponse-DBIWsRSZ.mjs";import{createShardClient as De}from"./packem_shared/createShardClient-BYYzDbMc.mjs";import{STORAGE_UPLOAD_MAX_BODY_BYTES as Me}from"./packem_shared/STORAGE_UPLOAD_MAX_BODY_BYTES-K0uZPIUj.mjs";import{LOG_ARCHIVE_NOT_CONFIGURED as Ge}from"./packem_shared/LOG_ARCHIVE_NOT_CONFIGURED-CDpi4yFD.mjs";import{NOOP_EXECUTION_CONTEXT as Ne}from"./packem_shared/NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{composeIdentityResolvers as Ye,routeIdentityResolvers as we}from"./packem_shared/composeIdentityResolvers-DwE0Jbww.mjs";const e="0.0.0";export{t as BACKUP_KEY_PREFIX,pe as DEFAULT_LOG_COLUMNS,me as DEFAULT_LOG_LIMIT,A as DEFAULT_REGISTRY_CACHE_TTL_MS,G as HEALTH_PATH,K as HEALTH_READY_PATH,Ge as LOG_ARCHIVE_NOT_CONFIGURED,X as LOG_ARCHIVE_PATH,g as LunoraError,Ne as NOOP_EXECUTION_CONTEXT,C as SHARD_REGISTRY_DO_NAME,Me as STORAGE_UPLOAD_MAX_BODY_BYTES,e as VERSION,ee as analyticsEngineSink,_e as applyJurisdiction,ue as applyRestCache,Ae as argsFromQuery,a as backupManifestKey,s as backupObjectKey,i as backupObjectKeyOfManifest,N as buildHealthRoutes,Ce as buildRestRoutes,re as combineSinks,Ye as composeIdentityResolvers,S as composeWorker,oe as consoleSink,k as createCrossShardRelationCapabilities,L as createDynamicShardRegistry,H as createKvCursorStore,x as createLunoraHandler,I as createMemoryCursorStore,ce as createPipelineLogReader,Ee as createQueryCoordinator,Le as createRestRateLimit,De as createShardClient,Re as createStaticShardRegistry,_ as createWorker,B as d1Probe,he as decorateResponse,P as defineExportSink,d as defineRpcEnvelope,Y as durableObjectProbe,J as emitLogEvent,Z as emitRpcEvent,He as enforceOrigin,Ie as handleCorsPreflight,n as isBackupManifestEntry,p as isBackupManifestKey,W as memoizeIdentity,q as memoizeIdentityPerRequest,Se as mergeStrategyForAggregate,m as normalizeBackupPrefix,te as otlpSink,ae as pipelineLogSink,w as presenceProbe,v as r2Sink,Te as readShardKey,ye as requestCarriesCredentials,j as resolveLogArchiveFromEnv,l as resolveLunoraOptions,Pe as resolveSecurity,de as resolveShard,ke as restCacheHeaders,ge as restSurfaceFromRegistry,we as routeIdentityResolvers,D as runExportTap,F as sanitizeChange,se as sentrySink,f as toAirbyteMessages,b as toErrorResponse,E as toFivetranResponse,M as webhookExportSink,ie as webhookSink,u as withFrameworkWorker};
1
+ import{BACKUP_KEY_PREFIX as t,backupManifestKey as a,backupObjectKey as s,backupObjectKeyOfManifest as i,isBackupManifestEntry as n,isBackupManifestKey as p,normalizeBackupPrefix as m}from"./packem_shared/BACKUP_KEY_PREFIX-DhFUE3VL.mjs";import{toAirbyteMessages as f,toFivetranResponse as E}from"./packem_shared/toAirbyteMessages-DTk8e2f9.mjs";import{composeWorker as S,createLunoraHandler as x,createWorker as _,defineRpcEnvelope as d,resolveLunoraOptions as l,withFrameworkWorker as u}from"./packem_shared/composeWorker-rVokGnPq.mjs";import{createCrossShardRelationCapabilities as k}from"./packem_shared/createCrossShardRelationCapabilities-CQfrCIWR.mjs";import{DEFAULT_REGISTRY_CACHE_TTL_MS as A,SHARD_REGISTRY_DO_NAME as C,createDynamicShardRegistry as L}from"./packem_shared/DEFAULT_REGISTRY_CACHE_TTL_MS-DqWtiFAk.mjs";import{LunoraError as g,toErrorResponse as b}from"./packem_shared/LunoraError-ByasbDmd.mjs";import{createKvCursorStore as H,createMemoryCursorStore as I,defineExportSink as P,r2Sink as v,runExportTap as D,sanitizeChange as F,webhookExportSink as M}from"./packem_shared/createKvCursorStore-C24tEuYk.mjs";import{HEALTH_PATH as G,HEALTH_READY_PATH as K,buildHealthRoutes as N,d1Probe as B,durableObjectProbe as Y,presenceProbe as w}from"./packem_shared/HEALTH_PATH-BwWsxoqV.mjs";import{LOG_ARCHIVE_PATH as X,resolveLogArchiveFromEnv as j}from"./packem_shared/LOG_ARCHIVE_PATH-CuHKuDCS.mjs";import{memoizeIdentity as W,memoizeIdentityPerRequest as q}from"./packem_shared/memoizeIdentity-CX3xEPYw.mjs";import{e as J,a as Z}from"./packem_shared/observability-DWlkDJJw.mjs";import{analyticsEngineSink as ee,combineSinks as re,consoleSink as oe,otlpSink as te,pipelineLogSink as ae,sentrySink as se,webhookSink as ie}from"./packem_shared/analyticsEngineSink-iIRy11I9.mjs";import{D as pe,a as me,c as ce}from"./packem_shared/pipeline-log-reader-FF1V32O2.mjs";import{createQueryCoordinator as Ee,createStaticShardRegistry as Re,mergeStrategyForAggregate as Se}from"./packem_shared/createQueryCoordinator-D8GY_boW.mjs";import{applyJurisdiction as _e,resolveShard as de}from"./packem_shared/applyJurisdiction-DX_lQ6fY.mjs";import{R as ue,d as ye,o as ke}from"./packem_shared/rest-cache-5unAzdFN.mjs";import{g as Ae,E as Ce,U as Le,p as Te,y as ge}from"./packem_shared/rest-routes-BqldHiaH.mjs";import{decorateResponse as he,enforceOrigin as He,handleCorsPreflight as Ie,resolveSecurity as Pe}from"./packem_shared/decorateResponse-BeLVRQuJ.mjs";import{createShardClient as De}from"./packem_shared/createShardClient-DoSOeXwx.mjs";import{STORAGE_UPLOAD_MAX_BODY_BYTES as Me}from"./packem_shared/STORAGE_UPLOAD_MAX_BODY_BYTES-K0uZPIUj.mjs";import{LOG_ARCHIVE_NOT_CONFIGURED as Ge}from"./packem_shared/LOG_ARCHIVE_NOT_CONFIGURED-CDpi4yFD.mjs";import{NOOP_EXECUTION_CONTEXT as Ne}from"./packem_shared/NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{composeIdentityResolvers as Ye,routeIdentityResolvers as we}from"./packem_shared/composeIdentityResolvers-DwE0Jbww.mjs";const e="0.0.0";export{t as BACKUP_KEY_PREFIX,pe as DEFAULT_LOG_COLUMNS,me as DEFAULT_LOG_LIMIT,A as DEFAULT_REGISTRY_CACHE_TTL_MS,G as HEALTH_PATH,K as HEALTH_READY_PATH,Ge as LOG_ARCHIVE_NOT_CONFIGURED,X as LOG_ARCHIVE_PATH,g as LunoraError,Ne as NOOP_EXECUTION_CONTEXT,C as SHARD_REGISTRY_DO_NAME,Me as STORAGE_UPLOAD_MAX_BODY_BYTES,e as VERSION,ee as analyticsEngineSink,_e as applyJurisdiction,ue as applyRestCache,Ae as argsFromQuery,a as backupManifestKey,s as backupObjectKey,i as backupObjectKeyOfManifest,N as buildHealthRoutes,Ce as buildRestRoutes,re as combineSinks,Ye as composeIdentityResolvers,S as composeWorker,oe as consoleSink,k as createCrossShardRelationCapabilities,L as createDynamicShardRegistry,H as createKvCursorStore,x as createLunoraHandler,I as createMemoryCursorStore,ce as createPipelineLogReader,Ee as createQueryCoordinator,Le as createRestRateLimit,De as createShardClient,Re as createStaticShardRegistry,_ as createWorker,B as d1Probe,he as decorateResponse,P as defineExportSink,d as defineRpcEnvelope,Y as durableObjectProbe,J as emitLogEvent,Z as emitRpcEvent,He as enforceOrigin,Ie as handleCorsPreflight,n as isBackupManifestEntry,p as isBackupManifestKey,W as memoizeIdentity,q as memoizeIdentityPerRequest,Se as mergeStrategyForAggregate,m as normalizeBackupPrefix,te as otlpSink,ae as pipelineLogSink,w as presenceProbe,v as r2Sink,Te as readShardKey,ye as requestCarriesCredentials,j as resolveLogArchiveFromEnv,l as resolveLunoraOptions,Pe as resolveSecurity,de as resolveShard,ke as restCacheHeaders,ge as restSurfaceFromRegistry,we as routeIdentityResolvers,D as runExportTap,F as sanitizeChange,se as sentrySink,f as toAirbyteMessages,b as toErrorResponse,E as toFivetranResponse,M as webhookExportSink,ie as webhookSink,u as withFrameworkWorker};
@@ -1 +1 @@
1
- import{LunoraError as n}from"./LunoraError-ByasbDmd.mjs";import{applyJurisdiction as S,resolveShard as _}from"./applyJurisdiction-Dsm_m5zW.mjs";const m="__lunora_shard_registry__",f=3e4,g="https://shard-registry.internal",l=async r=>await r.json(),T=r=>{const w=r.instanceName??m,o=r.cacheTtlMs??f,a=new Map,p=S(r.namespace,r.jurisdiction);let c;const d=()=>(c??=_(p,w),c),h=async(t,e)=>d().fetch(new Request(`${g}${t}`,{body:JSON.stringify(e),headers:{"content-type":"application/json"},method:"POST"})),y=async t=>d().fetch(new Request(`${g}${t}`,{method:"GET"}));return{invalidate(t){t===void 0?a.clear():a.delete(t)},async listShardKeys(t){const e=Date.now(),s=a.get(t);if(s&&s.expiresAt>e)return s.shardKeys;const i=await y(`/list?table=${encodeURIComponent(t)}`);if(!i.ok)throw new n(`shard registry /list returned ${String(i.status)}`);const{shardKeys:u}=await l(i);return o>0&&a.set(t,{expiresAt:e+o,shardKeys:u}),u},async register(t,e){const s=await h("/register",{shardKey:e,table:t});if(!s.ok)throw new n(`shard registry /register returned ${String(s.status)}`);a.delete(t)},async snapshot(){const t=await y("/snapshot");if(!t.ok)throw new n(`shard registry /snapshot returned ${String(t.status)}`);const{tables:e}=await l(t);return e},async unregister(t,e){const s=await h("/unregister",{shardKey:e,table:t});if(!s.ok)throw new n(`shard registry /unregister returned ${String(s.status)}`);a.delete(t)}}};export{f as DEFAULT_REGISTRY_CACHE_TTL_MS,m as SHARD_REGISTRY_DO_NAME,T as createDynamicShardRegistry};
1
+ import{LunoraError as n}from"./LunoraError-ByasbDmd.mjs";import{applyJurisdiction as S,resolveShard as _}from"./applyJurisdiction-DX_lQ6fY.mjs";const m="__lunora_shard_registry__",f=3e4,g="https://shard-registry.internal",l=async r=>await r.json(),T=r=>{const w=r.instanceName??m,o=r.cacheTtlMs??f,a=new Map,p=S(r.namespace,r.jurisdiction);let c;const d=()=>(c??=_(p,w),c),h=async(t,e)=>d().fetch(new Request(`${g}${t}`,{body:JSON.stringify(e),headers:{"content-type":"application/json"},method:"POST"})),y=async t=>d().fetch(new Request(`${g}${t}`,{method:"GET"}));return{invalidate(t){t===void 0?a.clear():a.delete(t)},async listShardKeys(t){const e=Date.now(),s=a.get(t);if(s&&s.expiresAt>e)return s.shardKeys;const i=await y(`/list?table=${encodeURIComponent(t)}`);if(!i.ok)throw new n(`shard registry /list returned ${String(i.status)}`);const{shardKeys:u}=await l(i);return o>0&&a.set(t,{expiresAt:e+o,shardKeys:u}),u},async register(t,e){const s=await h("/register",{shardKey:e,table:t});if(!s.ok)throw new n(`shard registry /register returned ${String(s.status)}`);a.delete(t)},async snapshot(){const t=await y("/snapshot");if(!t.ok)throw new n(`shard registry /snapshot returned ${String(t.status)}`);const{tables:e}=await l(t);return e},async unregister(t,e){const s=await h("/unregister",{shardKey:e,table:t});if(!s.ok)throw new n(`shard registry /unregister returned ${String(s.status)}`);a.delete(t)}}};export{f as DEFAULT_REGISTRY_CACHE_TTL_MS,m as SHARD_REGISTRY_DO_NAME,T as createDynamicShardRegistry};
@@ -1 +1 @@
1
- import{LunoraError as k}from"./LunoraError-ByasbDmd.mjs";import{t as H}from"./method-guard-rzvo19pa.mjs";import{resolveShard as R}from"./applyJurisdiction-Dsm_m5zW.mjs";const T="/_lunora/health",P="/_lunora/health/ready",_=a=>a==="liveness"?["liveness"]:a==="readiness"?["readiness"]:["liveness","readiness"];class j{#e=new Map;addChecker(e,s,t){this.#e.set(e,{run:s,types:t.type})}async getReport(e){const s=[...this.#e].filter(([,r])=>e===void 0||r.types.includes(e)),t=await Promise.all(s.map(async([r,o])=>[r,await o.run()]));return{healthy:t.every(([,r])=>r.health.healthy),report:Object.fromEntries(t)}}}const N=a=>{const e=new j,s=new Set;for(const t of a)t.critical&&s.add(t.name),e.addChecker(t.name,async()=>{let r;try{r=await t.check()}catch(o){r={healthy:!1,message:o instanceof Error?o.message:"probe failed"}}return{health:{healthy:r.healthy,...r.message===void 0?{}:{message:r.message}}}},{type:_(t.kind)});return{criticalNames:s,registry:e}},S=(a,e)=>{const s=a.includes(":")?a.slice(0,a.indexOf(":")):"probe",t=(e.get(s)??0)+1;return e.set(s,t),t===1?s:`${s}#${String(t)}`},C=(a,e)=>a?"unhealthy":e?"degraded":"healthy",O=(a,e,s,t,r)=>{const o=[];let d=!1,u=!1;const m=new Map;for(const[h,c]of Object.entries(a)){const n=e.has(h),i=c.health.healthy;u=u||!i,d=d||!i&&n;const l=s==="admin"?h:S(h,m);o.push({critical:n,...s==="admin"&&c.health.message!==void 0?{message:c.health.message}:{},name:l,status:i?"up":"down"})}return o.sort((h,c)=>h.name.localeCompare(c.name)),{anyCriticalDown:d,body:{appName:t,appVersion:r,checks:o,status:C(d,u),timestamp:new Date().toISOString()}}},q=a=>{const{appName:e="lunora",appVersion:s="0.0.0",auth:t="public",cacheTtlMs:r,isAdmin:o,resolveProbes:d}=a,u=n=>r!==void 0?r:n==="readiness"?0:t==="public"?5e3:0,m={},h=n=>{if(t==="admin"&&!o(n))throw new k("health endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403})},c=async(n,i,l)=>{const f=H(n,["GET","HEAD"]);if(f)return f;h(n);const y=u(l);if(y>0){const p=m[l];if(p!==void 0&&Date.now()<p.expiresAt)return Response.json(p.body,{headers:{"cache-control":"no-store"},status:p.down?503:200})}const{criticalNames:w,registry:v}=N(d(i)),{healthy:E,report:A}=await v.getReport(l==="readiness"?"readiness":void 0),{anyCriticalDown:D,body:g}=O(A,w,t,e,s),b=l==="readiness"?!E:D;return y>0&&(m[l]={body:g,down:b,expiresAt:Date.now()+y}),Response.json(g,{headers:{"cache-control":"no-store"},status:b?503:200})};return{[T]:(n,i)=>c(n,i,"aggregate"),[P]:(n,i)=>c(n,i,"readiness")}},I=(a,e,s)=>({check:async()=>{try{return await R(e,s).fetch(new Request("https://shard.internal/_lunora/status",{method:"GET"})),{healthy:!0}}catch{return{healthy:!1,message:"durable object unreachable"}}},critical:!0,name:a}),$=(a,e)=>({check:async()=>{try{return await e.prepare("SELECT 1").first(),{healthy:!0}}catch{return{healthy:!1,message:"d1 query failed"}}},critical:!0,name:a}),B=(a,e)=>({check:()=>e?{healthy:!0}:{healthy:!1,message:"binding not configured"},critical:!1,name:a});export{T as HEALTH_PATH,P as HEALTH_READY_PATH,q as buildHealthRoutes,$ as d1Probe,I as durableObjectProbe,B as presenceProbe};
1
+ import{LunoraError as k}from"./LunoraError-ByasbDmd.mjs";import{t as H}from"./method-guard-rzvo19pa.mjs";import{resolveShard as R}from"./applyJurisdiction-DX_lQ6fY.mjs";const T="/_lunora/health",P="/_lunora/health/ready",_=a=>a==="liveness"?["liveness"]:a==="readiness"?["readiness"]:["liveness","readiness"];class j{#e=new Map;addChecker(e,s,t){this.#e.set(e,{run:s,types:t.type})}async getReport(e){const s=[...this.#e].filter(([,r])=>e===void 0||r.types.includes(e)),t=await Promise.all(s.map(async([r,o])=>[r,await o.run()]));return{healthy:t.every(([,r])=>r.health.healthy),report:Object.fromEntries(t)}}}const N=a=>{const e=new j,s=new Set;for(const t of a)t.critical&&s.add(t.name),e.addChecker(t.name,async()=>{let r;try{r=await t.check()}catch(o){r={healthy:!1,message:o instanceof Error?o.message:"probe failed"}}return{health:{healthy:r.healthy,...r.message===void 0?{}:{message:r.message}}}},{type:_(t.kind)});return{criticalNames:s,registry:e}},S=(a,e)=>{const s=a.includes(":")?a.slice(0,a.indexOf(":")):"probe",t=(e.get(s)??0)+1;return e.set(s,t),t===1?s:`${s}#${String(t)}`},C=(a,e)=>a?"unhealthy":e?"degraded":"healthy",O=(a,e,s,t,r)=>{const o=[];let d=!1,u=!1;const m=new Map;for(const[h,c]of Object.entries(a)){const n=e.has(h),i=c.health.healthy;u=u||!i,d=d||!i&&n;const l=s==="admin"?h:S(h,m);o.push({critical:n,...s==="admin"&&c.health.message!==void 0?{message:c.health.message}:{},name:l,status:i?"up":"down"})}return o.sort((h,c)=>h.name.localeCompare(c.name)),{anyCriticalDown:d,body:{appName:t,appVersion:r,checks:o,status:C(d,u),timestamp:new Date().toISOString()}}},q=a=>{const{appName:e="lunora",appVersion:s="0.0.0",auth:t="public",cacheTtlMs:r,isAdmin:o,resolveProbes:d}=a,u=n=>r!==void 0?r:n==="readiness"?0:t==="public"?5e3:0,m={},h=n=>{if(t==="admin"&&!o(n))throw new k("health endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403})},c=async(n,i,l)=>{const f=H(n,["GET","HEAD"]);if(f)return f;h(n);const y=u(l);if(y>0){const p=m[l];if(p!==void 0&&Date.now()<p.expiresAt)return Response.json(p.body,{headers:{"cache-control":"no-store"},status:p.down?503:200})}const{criticalNames:w,registry:v}=N(d(i)),{healthy:E,report:A}=await v.getReport(l==="readiness"?"readiness":void 0),{anyCriticalDown:D,body:g}=O(A,w,t,e,s),b=l==="readiness"?!E:D;return y>0&&(m[l]={body:g,down:b,expiresAt:Date.now()+y}),Response.json(g,{headers:{"cache-control":"no-store"},status:b?503:200})};return{[T]:(n,i)=>c(n,i,"aggregate"),[P]:(n,i)=>c(n,i,"readiness")}},I=(a,e,s)=>({check:async()=>{try{return await R(e,s).fetch(new Request("https://shard.internal/_lunora/status",{method:"GET"})),{healthy:!0}}catch{return{healthy:!1,message:"durable object unreachable"}}},critical:!0,name:a}),$=(a,e)=>({check:async()=>{try{return await e.prepare("SELECT 1").first(),{healthy:!0}}catch{return{healthy:!1,message:"d1 query failed"}}},critical:!0,name:a}),B=(a,e)=>({check:()=>e?{healthy:!0}:{healthy:!1,message:"binding not configured"},critical:!1,name:a});export{T as HEALTH_PATH,P as HEALTH_READY_PATH,q as buildHealthRoutes,$ as d1Probe,I as durableObjectProbe,B as presenceProbe};
@@ -0,0 +1 @@
1
+ import{resolveShard as c}from"@lunora/platform";const u=new WeakMap,n=o=>o===void 0?void 0:{locationHint:o},p=o=>typeof o.idFromName=="function",a=o=>{if(!p(o))return o;const i=o,e=u.get(o);if(e!==void 0)return e;const d=typeof i.jurisdiction=="function"?t=>a(i.jurisdiction(t)):void 0,s=typeof i.getByName=="function"?{get:(t,r)=>i.get(t,n(r)),getByName:(t,r)=>i.getByName(t,n(r)),idForName:t=>i.idFromName(t),jurisdiction:d}:{get:(t,r)=>i.get(t,n(r)),idForName:t=>i.idFromName(t),jurisdiction:d};return u.set(o,s),s},f=(o,i)=>{if(i===void 0)return o;if(typeof o.jurisdiction!="function")throw new TypeError(`@lunora/runtime: Durable Object namespace does not support jurisdiction("${i}") — update @cloudflare/workers-types or remove the jurisdiction option`);return o.jurisdiction(i)},y=(o,i,e)=>c(a(o),i,e);export{f as applyJurisdiction,y as resolveShard};
@@ -0,0 +1,6 @@
1
+ import{isLunoraError as Ir,toErrorBody as Dr}from"@lunora/errors";import{d as Dt}from"./evict-oldest-C2XU6HBR.mjs";import{NOOP_EXECUTION_CONTEXT as Pr}from"./NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{f as Ur,u as Nr}from"./identity-header-pdXOyDU4.mjs";import{O as Oe,m as qr,A as $r,R as Cr,d as xr,i as Br,s as jr}from"./otlp-resource-B-ByO9qo.mjs";import{h as Z,f as be,i as Pt,E as Kr,w as Ut,e as Nt,b as Fr}from"./rest-routes-BqldHiaH.mjs";import{LunoraError as u,toErrorResponse as et}from"./LunoraError-ByasbDmd.mjs";import{r as x,t as me}from"./method-guard-rzvo19pa.mjs";import{normalizeBackupPrefix as Ge,BACKUP_KEY_PREFIX as Qe,isBackupManifestKey as Lr,backupObjectKeyOfManifest as qt,backupObjectKey as Gr,backupManifestKey as Qr}from"./BACKUP_KEY_PREFIX-DhFUE3VL.mjs";import{toHex as Mr,STORAGE_UPLOAD_MAX_BODY_BYTES as zr,STORAGE_PATH as Wr,buildStorageAdminRoutes as Hr}from"./STORAGE_UPLOAD_MAX_BODY_BYTES-K0uZPIUj.mjs";import{runExportTap as Jr}from"./createKvCursorStore-C24tEuYk.mjs";import{buildHealthRoutes as Vr,durableObjectProbe as Yr,d1Probe as Xr,presenceProbe as qe}from"./HEALTH_PATH-BwWsxoqV.mjs";import{wrapResolverWithContract as Zr}from"./composeIdentityResolvers-DwE0Jbww.mjs";import{composeIdentityResolvers as ys,routeIdentityResolvers as bs}from"./composeIdentityResolvers-DwE0Jbww.mjs";import{buildLogArchiveAdminRoutes as en}from"./LOG_ARCHIVE_PATH-CuHKuDCS.mjs";import{o as tn,f as tt,a as ce}from"./observability-DWlkDJJw.mjs";import{resolveShard as we,applyJurisdiction as rt}from"./applyJurisdiction-DX_lQ6fY.mjs";import{resolveSecurity as nt,handleCorsPreflight as rn,enforceOrigin as nn,decorateResponse as $e,enforceWebSocketOrigin as at}from"./decorateResponse-BeLVRQuJ.mjs";const an=e=>{const t=e??{};if(typeof t.bucket=="function")return t;const r={...t,bucketName:"default"};return r.bucket=()=>r,r},$t="__lunoraBranch",on=e=>typeof e=="object"&&e!==null&&Object.hasOwn(e,$t),sn=`may not contain the reserved workflow branch-marker key ("${$t}")`,Me=(e,t)=>{const r=Math.max(e.length,t.length);let n=e.length^t.length;for(let o=0;o<r;o+=1){const i=o<e.length?e.charCodeAt(o):0,l=o<t.length?t.charCodeAt(o):0;n|=i^l}return n===0},ze=new TextEncoder,cn=Array.from({length:32},(e,t)=>t);new RegExp(`[${cn.map(e=>String.fromCodePoint(e)).join("")}]`,"u");const un=e=>{const t=String.fromCodePoint(...e);return btoa(t).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")},dn=e=>{const t=e.replaceAll("-","+").replaceAll("_","/")+"===".slice((e.length+3)%4),r=atob(t),n=new Uint8Array(r.length);for(let o=0;o<r.length;o+=1)n[o]=r.codePointAt(o)??0;return n},ln=64,Ce=new Map,Ct=async e=>{const t=Ce.get(e);if(t)return t;Dt(Ce,ln);const r=crypto.subtle.importKey("raw",ze.encode(e),{hash:"SHA-256",name:"HMAC"},!1,["sign","verify"]);return Ce.set(e,r),r},xt=async(e,t)=>{const r=await Ct(e),n=await crypto.subtle.sign("HMAC",r,ze.encode(t));return un(new Uint8Array(n))},hn=async(e,t,r)=>{const n=await Ct(e);return crypto.subtle.verify("HMAC",n,r,ze.encode(t))},pn=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"];new Set(pn);const fn=new Set(["AE","BH","IL","IQ","IR","JO","KW","LB","OM","PS","QA","SA","SY","TR","YE"]),mn=-100,wn=15,gn=e=>{const t=Number(e.longitude??Number.NaN);switch(e.continent){case"AF":return"afr";case"AS":return e.country!==void 0&&fn.has(e.country)?"me":"apac";case"EU":return Number.isFinite(t)&&t>wn?"eeur":"weur";case"NA":return Number.isFinite(t)&&t<mn?"wnam":"enam";case"OC":return"oc";case"SA":return"sam";default:return}},ot=e=>{const t=e.cf;return t===void 0?void 0:gn(t)},Bt="::relay::",yn=(e,t)=>`${e}${Bt}${String(t)}`,jt="::replica::",bn=(e,t)=>`${e}${jt}${t}`,Rn=e=>{if(e==null||!/^\d+$/.test(e))return;const t=Number.parseInt(e,10);return Number.isSafeInteger(t)&&t>0?t:void 0},_n=new Set(["1","enabled","on","true","yes"]),Sn=new Set(["0","disabled","false","no","off"]),En=(e,t)=>{const r=(e??"").trim().toLowerCase();return _n.has(r)?!0:Sn.has(r)?!1:t},Kt="v1",On=6e4,Tn=async(e,t={})=>{const r=(t.now??Date.now())+(t.ttlMs??On),n=`${Kt}.${String(r)}`,o=await xt(e,n);return{expiresAtMs:r,token:`${n}.${o}`}},An=async(e,t,r=Date.now())=>{if(e.length===0||t.length===0)return!1;const n=t.split(".");if(n.length!==3)return!1;const[o,i,l]=n;if(o!==Kt||l.length===0)return!1;const d=Number(i);if(!Number.isFinite(d)||d<=r)return!1;let f;try{f=dn(l)}catch{return!1}return hn(e,`${o}.${i}`,f)},D="/_lunora/admin/auth",vn={INVITER_REQUIRED:400,ORG_SLUG_INVALID:400,ORG_SLUG_TAKEN:409,PASSWORD_TOO_LONG:400,PASSWORD_TOO_SHORT:400,USER_ALREADY_EXISTS:409,USER_NOT_FOUND:404},P=(e,t)=>{const r=e[t];if(typeof r!="string"||r==="")throw new u(`\`${t}\` is required`,{code:"BAD_REQUEST",status:400});return r},le=(e,t)=>{const r=e(t);if(r===void 0)throw new u(`\`${t}\` query parameter is required`,{code:"BAD_REQUEST",status:400});return r},Ft=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,xe=(e,t)=>{const r=e[t];return typeof r=="object"&&r!==null&&!Array.isArray(r)?r:void 0},st=e=>{const t=Ft(e.role);if(t===void 0||typeof t=="string"&&t.trim()==="")throw new u("`role` is required",{code:"BAD_REQUEST",status:400});return t},it=e=>{const t=e.permission;if(typeof t!="object"||t===null||Array.isArray(t))throw new u("`permission` object is required",{code:"BAD_REQUEST",status:400});const r={};for(const[n,o]of Object.entries(t))Array.isArray(o)&&o.every(i=>typeof i=="string")&&(r[n]=o);return r},kn={[`${D}/capabilities`]:{build:()=>({}),http:"GET",method:"capabilities"},[`${D}/users`]:{build:({paging:e,query:t})=>{const r=t("sortDirection");return{...e,filterField:t("filterField"),filterValue:t("filterValue"),search:t("search"),searchField:t("searchField"),sortBy:t("sortBy"),sortDirection:r==="asc"||r==="desc"?r:void 0}},http:"GET",method:"listUsers"},[`${D}/sessions`]:{build:({paging:e,query:t})=>({...e,userId:t("userId")}),http:"GET",method:"listSessions"},[`${D}/accounts`]:{build:({query:e})=>({userId:le(e,"userId")}),http:"GET",method:"listAccounts"},[`${D}/passkeys`]:{build:({query:e})=>({userId:le(e,"userId")}),http:"GET",method:"listPasskeys"},[`${D}/organizations`]:{build:({paging:e})=>({...e}),http:"GET",method:"listOrganizations"},[`${D}/organizations/members`]:{build:({paging:e,query:t})=>({...e,organizationId:le(t,"organizationId")}),http:"GET",method:"listMembers"},[`${D}/organizations/invitations`]:{build:({paging:e,query:t})=>({...e,organizationId:le(t,"organizationId")}),http:"GET",method:"listInvitations"},[`${D}/config`]:{build:()=>({}),http:"GET",method:"config"},[`${D}/organizations/teams`]:{build:({paging:e,query:t})=>({...e,organizationId:le(t,"organizationId")}),http:"GET",method:"listTeams"},[`${D}/organizations/teams/members`]:{build:({paging:e,query:t})=>({...e,teamId:le(t,"teamId")}),http:"GET",method:"listTeamMembers"},[`${D}/organizations/roles`]:{build:({paging:e,query:t})=>({...e,organizationId:le(t,"organizationId")}),http:"GET",method:"listOrgRoles"},[`${D}/users/create`]:{build:({body:e})=>({data:xe(e,"data"),email:P(e,"email"),name:P(e,"name"),password:re(e,"password"),role:Ft(e.role)}),http:"POST",method:"createUser"},[`${D}/users/update`]:{build:({body:e})=>{const{data:t}=e;if(typeof t!="object"||t===null||Array.isArray(t))throw new u("`data` object is required",{code:"BAD_REQUEST",status:400});return{data:t,userId:P(e,"userId")}},http:"POST",method:"updateUser"},[`${D}/users/role`]:{build:({body:e})=>({role:st(e),userId:P(e,"userId")}),http:"POST",method:"setRole"},[`${D}/users/ban`]:{build:({body:e})=>({expiresInSeconds:typeof e.expiresInSeconds=="number"?e.expiresInSeconds:void 0,reason:re(e,"reason"),userId:P(e,"userId")}),http:"POST",method:"banUser"},[`${D}/users/unban`]:{build:({body:e})=>({userId:P(e,"userId")}),http:"POST",method:"unbanUser"},[`${D}/users/password`]:{build:({body:e})=>({newPassword:P(e,"newPassword"),userId:P(e,"userId")}),http:"POST",method:"setUserPassword",returns:"void"},[`${D}/users/remove`]:{build:({body:e})=>({userId:P(e,"userId")}),http:"POST",method:"removeUser",returns:"void"},[`${D}/users/impersonate`]:{build:({body:e})=>({userId:P(e,"userId")}),http:"POST",method:"impersonateUser"},[`${D}/sessions/revoke`]:{build:({body:e})=>({sessionId:P(e,"sessionId")}),http:"POST",method:"revokeUserSession",returns:"void"},[`${D}/sessions/revoke-all`]:{build:({body:e})=>({userId:P(e,"userId")}),http:"POST",method:"revokeUserSessions",returns:"void"},[`${D}/accounts/unlink`]:{build:({body:e})=>({accountId:P(e,"accountId"),userId:P(e,"userId")}),http:"POST",method:"unlinkAccount",returns:"void"},[`${D}/two-factor/disable`]:{build:({body:e})=>({userId:P(e,"userId")}),http:"POST",method:"disableTwoFactor",returns:"void"},[`${D}/passkeys/delete`]:{build:({body:e})=>({passkeyId:P(e,"passkeyId")}),http:"POST",method:"deletePasskey",returns:"void"},[`${D}/organizations/members/remove`]:{build:({body:e})=>({memberId:P(e,"memberId")}),http:"POST",method:"removeMember",returns:"void"},[`${D}/organizations/invitations/cancel`]:{build:({body:e})=>({invitationId:P(e,"invitationId")}),http:"POST",method:"cancelInvitation",returns:"void"},[`${D}/organizations/create`]:{build:({body:e})=>({logo:re(e,"logo"),metadata:xe(e,"metadata"),name:P(e,"name"),ownerId:re(e,"ownerId"),slug:re(e,"slug")}),http:"POST",method:"createOrganization"},[`${D}/organizations/update`]:{build:({body:e})=>({logo:re(e,"logo"),metadata:xe(e,"metadata"),name:re(e,"name"),organizationId:P(e,"organizationId"),slug:re(e,"slug")}),http:"POST",method:"updateOrganization"},[`${D}/organizations/remove`]:{build:({body:e})=>({organizationId:P(e,"organizationId")}),http:"POST",method:"deleteOrganization",returns:"void"},[`${D}/organizations/members/add`]:{build:({body:e})=>({organizationId:P(e,"organizationId"),role:re(e,"role"),userId:P(e,"userId")}),http:"POST",method:"addMember"},[`${D}/organizations/members/invite`]:{build:({body:e})=>({email:P(e,"email"),inviterId:re(e,"inviterId"),organizationId:P(e,"organizationId"),role:re(e,"role")}),http:"POST",method:"inviteMember"},[`${D}/organizations/members/role`]:{build:({body:e})=>({memberId:P(e,"memberId"),role:st(e)}),http:"POST",method:"updateMemberRole"},[`${D}/organizations/teams/create`]:{build:({body:e})=>({name:P(e,"name"),organizationId:P(e,"organizationId")}),http:"POST",method:"createTeam"},[`${D}/organizations/teams/update`]:{build:({body:e})=>({name:P(e,"name"),teamId:P(e,"teamId")}),http:"POST",method:"updateTeam"},[`${D}/organizations/teams/remove`]:{build:({body:e})=>({teamId:P(e,"teamId")}),http:"POST",method:"removeTeam",returns:"void"},[`${D}/organizations/teams/members/add`]:{build:({body:e})=>({teamId:P(e,"teamId"),userId:P(e,"userId")}),http:"POST",method:"addTeamMember"},[`${D}/organizations/teams/members/remove`]:{build:({body:e})=>({teamMemberId:P(e,"teamMemberId")}),http:"POST",method:"removeTeamMember",returns:"void"},[`${D}/organizations/roles/create`]:{build:({body:e})=>({organizationId:P(e,"organizationId"),permission:it(e),role:P(e,"role")}),http:"POST",method:"createOrgRole"},[`${D}/organizations/roles/update`]:{build:({body:e})=>({permission:it(e),roleId:P(e,"roleId")}),http:"POST",method:"updateOrgRole"},[`${D}/organizations/roles/remove`]:{build:({body:e})=>({roleId:P(e,"roleId")}),http:"POST",method:"deleteOrgRole",returns:"void"}},In=e=>{const t=async o=>{try{return await o()}catch(i){if(i instanceof u)throw i;const l=i,d=typeof l.code=="string"?l.code:"AUTH_ADMIN_ERROR";throw console.error("[lunora] auth admin operation failed:",i),new u("auth admin operation failed",{code:d,status:vn[d]??500})}},r=async(o,i)=>{if(e.assertAdmin(o),o.method!==i.http)throw new u(`Auth admin endpoint requires ${i.http}`,{code:"METHOD_NOT_ALLOWED",status:405});const l=e.getAuthAdmin();if(l===void 0)throw new u("auth endpoints require an `authAdmin` on the worker",{code:"AUTH_NOT_CONFIGURED",status:400});const d=l[i.method];if(d===void 0)throw new u(`auth admin does not support \`${i.method}\``,{code:"AUTH_OP_NOT_SUPPORTED",status:400});const f=new URL(o.url),g={body:i.http==="POST"?await e.readJsonBody(o):{},paging:e.parsePaging(o),query:R=>e.queryParameter(f,R)},S=i.build(g),w=await t(()=>d(S));return Response.json(i.returns==="void"?{ok:!0}:w,{headers:{"content-type":"application/json"},status:200})},n={};for(const[o,i]of Object.entries(kn))n[o]=l=>r(l,i);return n},Dn="__lunora_admin__:getAuthAuditLog",ct=e=>typeof e=="string"&&e!==""?e:void 0,ut=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0,Pn=e=>async(t,r)=>{e.assertAdmin(t);const n=e.getReader();if(n===void 0)throw new u("the auth/security audit endpoint requires an `authAuditReader` on the worker",{code:"AUTH_AUDIT_NOT_CONFIGURED",status:400});const o=ct(r.actorId),i=ct(r.event),l=ut(r.sinceSeq),d=ut(r.limit),f={...o===void 0?{}:{actorId:o},...i===void 0?{}:{event:i},...l===void 0?{}:{sinceSeq:l},...d===void 0?{}:{limit:d}};let g;try{g=await n.read(f)}catch(w){throw w instanceof u?w:(console.error("[lunora] auth audit read failed:",w),new u("auth audit read failed",{code:"AUTH_AUDIT_READ_FAILED",status:500}))}const S={entries:g};return Response.json(S,{headers:{"content-type":"application/json"},status:200})},Un=(e,t)=>{const r=[],n=[];if(t&&t.length>0)for(const o of t)e.resolveTableSharding?.(o)?.mode.kind==="global"?n.push(o):r.push(o);return{globalTables:n,shardLocalTables:r}},Nn=async(e,t,r,n,o,i)=>{if(r!==void 0&&n.length===0)return;const l=await e.orchestrateExport(i,{args:{tables:n},headers:t,tables:n});for(const d of l.shards)if(!d.error)for(const f of d.rows??[])o(f)},Lt=async(e,t,r,n,o,i)=>{const{globalTables:l,shardLocalTables:d}=Un(e,n);await Nn(t,r,n,d,o,i);const f=e.exportGlobals;if((n===void 0||l.length>0)&&f)for await(const g of f({tables:l}))o(g)},qn=new TextEncoder,$n=1e3,Gt=10,Cn=200,dt=8,Qt="lunoraBackupCron",lt=24*1048576,ht=e=>{const t=e.slice(0,Gt).map(n=>qt(n)),r=e.length-t.length;return`${t.join(", ")}${r>0?` (+${String(r)} more)`:""}`},xn=(e,t)=>{const r=new Uint8Array(new ArrayBuffer(t));let n=0;for(const o of e)r.set(o,n),n+=o.byteLength;return r},We=async(e,t,r,n)=>{if(r===void 0||!Number.isInteger(r)||r<=0)return{eligible:0,stale:[]};const o=[];let i;for(let l=0;l<$n;l+=1){const d=await e.list({cursor:i,include:["customMetadata"],prefix:t});for(const f of d.objects)Lr(f.key)&&f.customMetadata?.[Qt]===n&&o.push(f.key);if(!d.truncated||d.cursor===void 0)break;i=d.cursor}return{eligible:o.length,stale:o.toSorted((l,d)=>d.localeCompare(l)).slice(r)}},Bn=async(e,t,r,n,o)=>{const{stale:i}=await We(e,t,r,n),l=new Set(o),d=i.filter(p=>l.has(p)),f=d.slice(0,Cn),g=i.length-f.length,S=o.length-d.length;if(f.length===0)return{deleted:[],failed:[],ignored:S,remaining:g};const w=[],R=[];for(let p=0;p<f.length;p+=dt){const O=await Promise.allSettled(f.slice(p,p+dt).map(async _=>(await e.delete(qt(_)),await e.delete(_),_)));for(const[_,A]of O.entries())A.status==="fulfilled"?w.push(A.value):R.push(f[p+_])}return w.length>0&&console.info(`[lunora] backup prune kept the newest ${String(r)} and deleted ${String(w.length)}: ${ht(w)}`),R.length>0&&console.warn(`[lunora] backup prune failed to remove ${String(R.length)}: ${ht(R)}`),{deleted:w,failed:R,ignored:S,remaining:g}},jn=async e=>{const t=e.backupStore;if(!t)throw new u("backup retention preview requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});const r=Ge(e.backupPrefix??Qe),n=e.backupCron,{eligible:o,stale:i}=n===void 0?{eligible:0,stale:[]}:await We(t,r,e.backupRetain,n);return{cron:n,eligible:o,keep:e.backupRetain??0,prefix:r,wouldDelete:i}},Kn=async(e,t,r,n)=>{const o=e.backupStore,i=e.queryCoordinator;if(!o)throw new u("scheduled backup requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});if(!i)throw new u("scheduled backup requires a `queryCoordinator` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});if(!r||r.length===0)throw new u("scheduled backup requires an `adminToken` (or `env.LUNORA_ADMIN_TOKEN`) to authenticate the per-shard export gate",{code:"BACKUP_NOT_CONFIGURED",status:500});const l={authorization:`Bearer ${r}`,"content-type":"application/json"},d=e.backupTables;let f=0,g=0,S=[];await Lt(e,i,l,d,T=>{const U=qn.encode(`${JSON.stringify(T)}
2
+ `);if(f+=1,g+=U.byteLength,g>lt)throw new u(`scheduled backup reached ${String(g)} bytes of NDJSON, past the ${String(lt)}-byte limit for a snapshot assembled inside a Worker — nothing was written. Narrow it with \`backupTables\`, or take this snapshot off-platform with \`lunora backup create --bucket\`.`,{code:"BACKUP_TOO_LARGE",status:507});S.push(U)},t);const w=Ge(e.backupPrefix??Qe),R=new Date(n.scheduledTime).toISOString(),p=Gr(w,R),O=xn(S,g);S=[];const _=Mr(await crypto.subtle.digest("SHA-256",O));await o.put(p,O,{httpMetadata:{contentType:"application/x-ndjson"},sha256:_});const A={bytes:g,createdAt:R,cron:n.cron,file:p,id:R,rows:f,scheduledTime:n.scheduledTime,sha256:_,...d?{tables:d.join(",")}:{}};await o.put(Qr(p),`${JSON.stringify(A,void 0,2)}
3
+ `,{customMetadata:{[Qt]:n.cron},httpMetadata:{contentType:"application/json"}});try{const{stale:T}=await We(o,w,e.backupRetain,n.cron);if(T.length>0){const U=T.slice(0,Gt),k=T.length-U.length;console.info(`[lunora] backup retention: ${String(T.length)} snapshot(s) past the newest ${String(e.backupRetain)} — run \`lunora backup prune\` to remove them: ${U.join(", ")}${k>0?` (+${String(k)} more)`:""}`)}}catch(T){console.warn(`[lunora] backup ${p} was written, but the retention report failed:`,T)}},Fn=async(e,t)=>{const r=e.backupStore;if(!r)throw new u("backup prune requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});const n=e.backupCron,o=e.backupRetain;if(n===void 0||o===void 0||!Number.isInteger(o)||o<=0)throw new u("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 Bn(r,Ge(e.backupPrefix??Qe),o,n,t)},Ln="/_lunora/admin/backup/retention",Gn="/_lunora/admin/backup/prune",Qn=e=>{const{options:t,readJsonBody:r,requireAdminOption:n}=e,o=(d,f)=>{n(d,t.backupStore,{code:"BACKUP_NOT_CONFIGURED",message:`backup ${f} requires a \`backupStore\` on the worker`})},i=async d=>(x(d,"GET","Backup-retention"),o(d,"retention preview"),Response.json(await jn(t),{headers:{"cache-control":"no-store"}})),l=async d=>{x(d,"POST","Backup-prune"),o(d,"prune");const{confirm:f}=await r(d);if(!Array.isArray(f)||f.some(g=>typeof g!="string"))throw new u("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 Fn(t,f),{headers:{"cache-control":"no-store"}})};return{[Gn]:l,[Ln]:i}},pt=500,Mn=(e,t,r)=>{if(typeof e!="object"||e===null||Array.isArray(e))throw new u("each batch call must be an object",{code:"BAD_REQUEST",status:400});const n=e;if(typeof n.functionPath!="string")throw new u("each batch call needs a string `functionPath`",{code:"BAD_REQUEST",status:400});if(n.functionPath.startsWith("__lunora_relation__:")||n.functionPath.startsWith("__lunora_admin__"))throw new u("reserved function path cannot be batched",{code:"FORBIDDEN",status:403});if(n.args!==void 0&&(typeof n.args!="object"||n.args===null||Array.isArray(n.args)))throw new u("each batch call `args` must be an object",{code:"BAD_REQUEST",status:400});return{entry:{args:n.args===void 0?{}:n.args,clientId:typeof n.clientId=="string"?n.clientId:void 0,clientSeq:typeof n.clientSeq=="number"?n.clientSeq:void 0,functionPath:n.functionPath,id:typeof n.id=="number"?n.id:t,mutationId:typeof n.mutationId=="string"?n.mutationId:void 0},shardKey:typeof n.shardKey=="string"?n.shardKey:r}},zn=(e,t)=>{if(e.length>pt)throw new u(`RPC batch exceeds the ${String(pt)}-call limit`,{code:"BAD_REQUEST",status:400});const r=new Map;for(const[n,o]of e.entries()){const{entry:i,shardKey:l}=Mn(o,n,t),d=r.get(l)??[];d.push(i),r.set(l,d)}return r},Wn=new TextEncoder,Hn=e=>{const t=JSON.stringify(e),r=Wn.encode(t);let n="";for(const o of r)n+=String.fromCodePoint(o);return btoa(n).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")},Jn=e=>{const t={g:0,s:{},v:1};if(typeof e!="string"||e.length===0)return t;try{const r=atob(e.replaceAll("-","+").replaceAll("_","/")),n=new Uint8Array(r.length);for(let d=0;d<r.length;d+=1)n[d]=r.codePointAt(d)??0;const o=JSON.parse(new TextDecoder().decode(n)),i=o.s&&typeof o.s=="object"?o.s:{},l={};for(const[d,f]of Object.entries(i))typeof f=="number"&&Number.isFinite(f)&&(l[d]=f);return{g:typeof o.g=="number"&&Number.isFinite(o.g)?o.g:0,s:l,v:1}}catch{return t}},Vn=e=>{const t=typeof e.table=="string"?e.table:"",r=typeof e.op=="string"?e.op:"",n=r==="delete"||r==="insert"||r==="update"?r:"upsert",o=typeof e.id=="string"?e.id:void 0;return{doc:(e.doc&&typeof e.doc=="object"?e.doc:void 0)??(o===void 0?{}:{_id:o}),op:n,table:t}},ft=(e,t,r)=>{for(const n of t)e.push(Vn(n));return r!==void 0&&t.length>=r},Yn="/_lunora/admin/export",Xn="/_lunora/admin/import",Zn="/_lunora/admin/sync",ea="/_lunora/admin/connector/sync",ta="/_lunora/admin/apply",ra="/_lunora/admin/export-tap/run",na=new TextEncoder,aa=async e=>{const t=await be(e,"Export")??{};if(t.tables===void 0)return{tables:void 0};if(!Array.isArray(t.tables))throw new u("Export `tables` must be a string array",{code:"BAD_REQUEST",status:400});const r=[];for(const n of t.tables){if(typeof n!="string"||n.length===0)throw new u("Export `tables` entries must be non-empty strings",{code:"BAD_REQUEST",status:400});r.push(n)}return{tables:r}},Be=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):void 0,oa=e=>{const{applyGlobals:t,exportCursorStore:r,exportSinks:n,knownTables:o,queryCoordinator:i,assertAdmin:l,requireAdminOption:d,resolveForwardContext:f,shardDO:g,streamExportRows:S,streamingImport:w,syncGlobals:R}=e,p=async(k,j)=>{const K=me(k,["POST"]);if(K)return K;const z=d(k,i,{code:"BAD_REQUEST",message:"Export endpoint requires a `queryCoordinator` on the worker"}),N=await aa(k),{headers:L}=await f(k,j),F=new ReadableStream({async pull(J){const W=X=>{J.enqueue(na.encode(`${JSON.stringify(X)}
4
+ `))};try{await S(z,L,N.tables,W),J.close()}catch(X){J.error(X)}}});return new Response(F,{headers:{"content-type":"application/x-ndjson"},status:200})},O=async(k,j)=>{const K=me(k,["POST"]);if(K)return K;const z=d(k,i,{code:"BAD_REQUEST",message:"Sync endpoint requires a `queryCoordinator` on the worker"}),N=await Z(k),L=typeof N.cursors=="object"&&N.cursors!==null?N.cursors:{},F=typeof N.limit=="number"?N.limit:void 0,J=typeof N.globalCursor=="number"?N.globalCursor:0,W=Be(N.tables),{headers:X}=await f(k,j),V=W??o(),oe=await z.orchestrateCdcSync(g,{cursors:L,headers:X,limit:F,tables:V}),he=R?await R({limit:F,sinceSeq:J}):void 0;return Response.json({global:he,shards:oe.shards},{status:200})},_=async(k,j)=>{const K=me(k,["POST"]);if(K)return K;const z=d(k,i,{code:"BAD_REQUEST",message:"Connector sync endpoint requires a `queryCoordinator` on the worker"}),N=await Z(k),L=Jn(N.cursor),F=typeof N.limit=="number"&&N.limit>0?N.limit:void 0,J=Be(N.tables),{headers:W}=await f(k,j),X=J??o(),V=await z.orchestrateCdcSync(g,{cursors:L.s,headers:W,limit:F,tables:X}),oe=[],he={...L.s};let G=!1;for(const se of V.shards)G=ft(oe,se.changes??[],F)||G,he[se.shardKey]=se.cursor;let ne=L.g;if(R){const se=await R({limit:F,sinceSeq:L.g});G=ft(oe,se.changes,F)||G,ne=se.cursor}const Te=Hn({g:ne,s:he,v:1}),Ae={changes:oe,hasMore:G,nextCursor:Te};return Response.json(Ae,{status:200})},A=async(k,j)=>{const K=me(k,["POST"]);if(K)return K;const z=d(k,i,{code:"BAD_REQUEST",message:"Apply endpoint requires a `queryCoordinator` on the worker"}),N=await Z(k),L=(Array.isArray(N.batches)?N.batches:[]).map(V=>V).filter(V=>V!==null&&typeof V=="object"&&typeof V.shardKey=="string"&&Array.isArray(V.changes)),F=Array.isArray(N.globalChanges)?N.globalChanges:[],{headers:J}=await f(k,j),W=await z.orchestrateApplyCdc(g,{batches:L,headers:J}),X=F.length>0&&t?await t({changes:F}):0;return Response.json({applied:W.applied+X,failed:W.failed,ok:W.ok},{status:200})},T=async(k,j)=>{const K=me(k,["POST"]);if(K)return K;l(k);const{headers:z}=await f(k,j),N=await w(k,z);return Response.json(N,{headers:{"content-type":"application/json"},status:200})},U=async(k,j)=>{const K=me(k,["POST"]);if(K)return K;const z=d(k,i,{code:"BAD_REQUEST",message:"Export-tap endpoint requires a `queryCoordinator` on the worker"});if(n===void 0||Object.keys(n).length===0||r===void 0)throw new u("Export-tap endpoint requires `exportSinks` + `exportCursorStore` on the worker",{code:"EXPORT_TAP_NOT_CONFIGURED",status:400});const N=await Z(k),L=typeof N.sink=="string"?N.sink:void 0,F=typeof N.limit=="number"&&N.limit>0?N.limit:void 0,J=Be(N.tables);if(L===void 0)throw new u("Export-tap `sink` must name a configured sink",{code:"BAD_REQUEST",status:400});const W=n[L];if(W===void 0)throw new u(`Export-tap sink "${L}" is not configured`,{code:"NOT_FOUND",status:404});const{headers:X}=await f(k,j),V=J??o(),oe=await Jr({coordinator:z,cursorStore:r,headers:X,limit:F,shardDO:g,sink:W,tables:V});return Response.json(oe,{headers:{"content-type":"application/json"},status:200})};return{[ta]:A,[ea]:_,[Yn]:p,[ra]:U,[Xn]:T,[Zn]:O}},sa=(e,t)=>{let r;try{r=JSON.parse(e)}catch{return{error:{code:"BAD_ROW",line:t,message:"line is not valid JSON",table:""},ok:!1}}if(!r||typeof r!="object"||Array.isArray(r))return{error:{code:"BAD_ROW",line:t,message:"row must be a JSON object",table:""},ok:!1};const n=r;return typeof n.table!="string"||n.table.length===0?{error:{code:"BAD_ROW",line:t,message:"row is missing `table`",table:""},ok:!1}:!n.doc||typeof n.doc!="object"||Array.isArray(n.doc)?{error:{code:"BAD_ROW",line:t,message:"row is missing or malformed `doc`",table:n.table},ok:!1}:{doc:n.doc,ok:!0,table:n.table}},ia=(e,t,r,n,o)=>{if(r?.mode.kind==="shardBy"&&typeof r.mode.field=="string"){const i=e[r.mode.field];return i==null?{error:{code:"BAD_ROW",line:o,message:`row missing shard field "${r.mode.field}" for table "${t}"`,table:t},ok:!1}:{ok:!0,shardKey:typeof i=="string"?i:JSON.stringify(i)}}return{ok:!0,shardKey:n}},ca=async(e,t,r)=>{if(!e.body)throw new u("Import endpoint requires a request body",{code:"BAD_REQUEST",status:400});const n=[],o=[],i=new Map;let l=0,d=0;const f=e.body.getReader(),g=new TextDecoder;let S="",w=0;const R=p=>{d+=1;const O=p.trim();if(O.length===0)return;l+=1;const _=sa(O,d);if(!_.ok){n.push(_.error);return}const{doc:A,table:T}=_,U=t.resolveTableSharding?.(T);if(U?.mode.kind==="global"){o.push({doc:A,line:d,table:T});return}const k=ia(A,T,U,r,d);if(!k.ok){n.push(k.error);return}const j=i.get(k.shardKey);j?j.rows.push({doc:A,table:T}):i.set(k.shardKey,{rows:[{doc:A,table:T}],shardKey:k.shardKey,startLine:d})};for(;;){const{done:p,value:O}=await f.read();if(p)break;if(O&&(w+=O.byteLength,w>Pt))throw await f.cancel().catch(()=>{}),new u("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});S+=g.decode(O,{stream:!0});let _=S.indexOf(`
5
+ `);for(;_!==-1;){const A=S.slice(0,_);S=S.slice(_+1),R(A),_=S.indexOf(`
6
+ `)}}return S.length>0&&R(S),{errors:n,globalRows:o,perShard:i,received:l}},mt=(e,t)=>{for(const[r,n]of Object.entries(t.inserted))e.inserted[r]=(e.inserted[r]??0)+n;for(const r of t.errors)e.errors.push({...r});e.conflicts+=t.conflicts},ua=async(e,t,r,n)=>{const o=t.defaultShardKey??"__root__",{errors:i,globalRows:l,perShard:d,received:f}=await ca(e,t,o),g={conflicts:0,errors:i,inserted:{}},S=[];if(t.resolveTableSharding===void 0&&d.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"),d.size>0){const w=t.queryCoordinator;if(!w)throw new u("Import endpoint requires a `queryCoordinator` on the worker",{code:"BAD_REQUEST",status:400});const R=await w.orchestrateImport(n,{batches:[...d.values()],headers:r});mt(g,R)}if(l.length>0)if(t.importGlobals){const w=l[0]?.line??1,R=await t.importGlobals({rows:l,startLine:w});mt(g,R)}else for(const w of l)g.errors.push({code:"GLOBAL_NOT_CONFIGURED",line:w.line,message:`row targets global table "${w.table}" but no \`importGlobals\` is configured`,table:w.table});return{conflicts:g.conflicts,errors:g.errors,inserted:g.inserted,received:f,...S.length>0?{warnings:S}:{}}},je=e=>typeof e=="object"&&e!==null?e:{},Ke=e=>typeof e.kind=="string"?e.kind:"unknown",da=(e,t)=>{let r=je(t),n=!1;Ke(r)==="optional"&&(n=!0,r=je(r._meta?.inner));const o=Ke(r),i=r._meta??{},l={kind:o,name:e,optional:n};if(o==="id"&&typeof i.tableName=="string"&&(l.table=i.tableName),o==="array"){const d=Ke(je(i.inner));d!=="unknown"&&(l.element=d)}return l},la=e=>typeof e!="object"||e===null?[]:Object.entries(e).map(([t,r])=>da(t,r)).toSorted((t,r)=>t.name.localeCompare(r.name)),ha="/_lunora/admin/functions",pa="/_lunora/admin/cron-jobs",fa="/_lunora/admin/openapi",ma="/_lunora/admin/openrpc",wa="/_lunora/admin/global/tables",ga="/_lunora/admin/global/table",ya="/_lunora/admin/global/facet",wt=e=>{if(e===void 0||e==="")return;let t;try{t=JSON.parse(e)}catch{return}if(!Array.isArray(t))return;const r=t.flatMap(n=>{if(typeof n!="object"||n===null||typeof n.column!="string")return[];const{column:o,value:i}=n;return[{column:o,value:i}]});return r.length===0?void 0:r},ba=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:{}}),Ra=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"}),_a=e=>{const{assertAdmin:t,options:r,parsePaging:n,queryParameter:o,requireAdminOption:i}=e,l=p=>{x(p,"GET","Functions");const O=i(p,r.functions,{code:"FUNCTIONS_NOT_CONFIGURED",message:"functions endpoint requires a `functions` registry on the worker"}),_=Object.entries(O).flatMap(([A,T])=>T.visibility==="internal"||T.kind==="stream"?[]:[{args:la(T.args),kind:T.kind,path:A}]).toSorted((A,T)=>A.path.localeCompare(T.path));return Response.json({functions:_},{headers:{"content-type":"application/json"},status:200})},d=p=>{x(p,"GET","Cron-jobs");const O=i(p,r.cronJobs,{code:"CRON_JOBS_NOT_CONFIGURED",message:"cron-jobs endpoint requires a `cronJobs` map on the worker"}),_=Object.entries(O).flatMap(([A,T])=>T.map(U=>({args:U.args,cron:A,functionPath:U.functionPath,name:U.name,shardKey:U.shardKey,workflow:U.workflow}))).toSorted((A,T)=>A.name.localeCompare(T.name));return Response.json({jobs:_},{headers:{"content-type":"application/json"},status:200})},f=p=>(x(p,"GET","OpenAPI"),t(p),Response.json(r.openApiSpec??ba,{headers:{"content-type":"application/json"},status:200})),g=p=>(x(p,"GET","OpenRPC"),t(p),Response.json(r.openRpcSpec??Ra,{headers:{"content-type":"application/json"},status:200})),S=async p=>{x(p,"GET","Global-tables");const O=i(p,r.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"});return Response.json(await O.listTables(),{headers:{"content-type":"application/json"},status:200})},w=async p=>{x(p,"GET","Global-table");const O=i(p,r.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),_=new URL(p.url),A=o(_,"table");if(A===void 0)throw new u("Global-table endpoint requires a `table` query param",{code:"BAD_REQUEST",status:400});const T=await O.readTablePage({...n(p),filters:wt(o(_,"filters")),table:A});return Response.json(T,{headers:{"content-type":"application/json"},status:200})},R=async p=>{x(p,"GET","Global-facet");const O=i(p,r.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),_=new URL(p.url),A=o(_,"table"),T=o(_,"column");if(A===void 0||T===void 0)throw new u("Global-facet endpoint requires `table` and `column` query params",{code:"BAD_REQUEST",status:400});const U=o(_,"limit"),k=U===void 0?void 0:Number(U),j=await O.facetColumn({column:T,filters:wt(o(_,"filters")),limit:k!==void 0&&Number.isFinite(k)?k:void 0,table:A});return Response.json(j,{headers:{"content-type":"application/json"},status:200})};return{[pa]:d,[ha]:l,[ya]:R,[ga]:w,[wa]:S,[fa]:f,[ma]:g}},Sa="/_lunora/admin/kv/namespaces",Ea="/_lunora/admin/kv/keys",Mt="/_lunora/admin/kv/value",zt=32*1048576,gt=60,Oa=e=>{const{readJsonBody:t,requireAdminOption:r}=e,n=w=>r(w,e.kvIntrospector,{code:"KV_NOT_CONFIGURED",message:"KV endpoints require a `kvIntrospector` on the worker"}),o=w=>Response.json(w,{headers:{"content-type":"application/json"},status:200}),i=(w,R)=>{const p=new URL(w.url),O=p.searchParams.get("namespace")??"",_=p.searchParams.get("key")??"";if(O==="")throw new u(`KV-value ${R} request requires a \`namespace\` query parameter`,{code:"BAD_REQUEST",status:400});if(_==="")throw new u(`KV-value ${R} request requires a \`key\` query parameter`,{code:"BAD_REQUEST",status:400});return{key:_,namespace:O}},l=async(w,R)=>{if(!(await w.listNamespaces()).some(p=>p.binding===R))throw new u(`Unknown KV namespace binding \`${R}\``,{code:"NOT_FOUND",status:404})},d=async w=>(x(w,"GET","KV-namespaces"),o({namespaces:await n(w).listNamespaces()})),f=async w=>{x(w,"GET","KV-keys");const R=n(w),p=new URL(w.url),O=p.searchParams.get("namespace")??"";if(O==="")throw new u("KV-keys request requires a `namespace` query parameter",{code:"BAD_REQUEST",status:400});const _=p.searchParams.get("prefix")??void 0,A=p.searchParams.get("cursor")??void 0,T=p.searchParams.get("limit"),U=T===null?void 0:Number.parseInt(T,10);if(U!==void 0&&(!Number.isInteger(U)||U<1))throw new u("KV-keys `limit` must be a positive integer",{code:"BAD_REQUEST",status:400});const k=U===void 0?void 0:Math.min(U,1e3);return await l(R,O),o(await R.listKeys({cursor:A,limit:k,namespace:O,prefix:_}))},g={DELETE:async w=>{const R=n(w),p=i(w,"DELETE");return await l(R,p.namespace),await R.deleteKey(p),o({deleted:!0})},GET:async w=>{const R=n(w),p=i(w,"GET");return await l(R,p.namespace),o(await R.getValue(p))},PUT:async w=>{const R=n(w),p=await t(w,zt);if(typeof p.namespace!="string"||p.namespace==="")throw new u("KV-value PUT request requires a `namespace` string",{code:"BAD_REQUEST",status:400});if(typeof p.key!="string"||p.key==="")throw new u("KV-value PUT request requires a `key` string",{code:"BAD_REQUEST",status:400});if(typeof p.value!="string")throw new u("KV-value PUT request requires a `value` string",{code:"BAD_REQUEST",status:400});if(p.expirationTtl!==void 0&&(typeof p.expirationTtl!="number"||!Number.isInteger(p.expirationTtl)||p.expirationTtl<gt))throw new u("KV-value PUT `expirationTtl` must be an integer ≥ 60",{code:"BAD_REQUEST",status:400});const O=Math.floor(Date.now()/1e3)+gt;if(p.expiration!==void 0&&(typeof p.expiration!="number"||!Number.isInteger(p.expiration)||p.expiration<O))throw new u("KV-value PUT `expiration` must be a Unix-seconds timestamp at least 60 seconds in the future",{code:"BAD_REQUEST",status:400});return await l(R,p.namespace),await R.putValue({expiration:p.expiration,expirationTtl:p.expirationTtl,key:p.key,metadata:p.metadata,namespace:p.namespace,value:p.value}),o({ok:!0})}},S=w=>{const R=g[w.method];if(!R)throw new u("KV-value endpoint requires GET, PUT, or DELETE",{code:"METHOD_NOT_ALLOWED",status:405});return R(w)};return{[Sa]:d,[Ea]:f,[Mt]:S}},Ta="/_lunora/migrate",Aa="/_lunora/admin/pitr",va="/_lunora/admin/rank",ka="/_lunora/admin/rankpage",Ia="/_lunora/admin/shard-traffic",Da=new Set(["__lunora_admin__:migrationStatus","__lunora_admin__:runMigration"]),Pa=new Set(["__lunora_admin__:getPitrBookmark","__lunora_admin__:pitrRestore"]),Ua=async e=>{const t=await be(e,"Migration")??{};if(typeof t.table!="string"||t.table.length===0)throw new u("Migration request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof t.functionPath!="string"||!Da.has(t.functionPath))throw new u("Migration request `functionPath` must be a migration admin op",{code:"BAD_REQUEST",status:400});return{args:t.args??{},functionPath:t.functionPath,table:t.table}},Na=async e=>{const t=await be(e,"Rank")??{};if(typeof t.table!="string"||t.table.length===0)throw new u("Rank request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof t.index!="string"||t.index.length===0)throw new u("Rank request is missing `index`",{code:"BAD_REQUEST",status:400});if(typeof t.partitionKey!="string")throw new u("Rank request `partitionKey` must be a string",{code:"BAD_REQUEST",status:400});if(typeof t.rowId!="string"||t.rowId.length===0)throw new u("Rank request is missing `rowId`",{code:"BAD_REQUEST",status:400});if(!Array.isArray(t.sortValues))throw new u("Rank request `sortValues` must be an array",{code:"BAD_REQUEST",status:400});return{index:t.index,partitionKey:t.partitionKey,rowId:t.rowId,sortValues:t.sortValues,table:t.table}},qa=e=>{if(e!==void 0){if(!Array.isArray(e)||e.some(t=>t!=="asc"&&t!=="desc"))throw new u('Rank page request `directions` must be an array of "asc"|"desc"',{code:"BAD_REQUEST",status:400});return e}},$a=e=>{if(typeof e.table!="string"||e.table.length===0)throw new u("Rank page request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof e.index!="string"||e.index.length===0)throw new u("Rank page request is missing `index`",{code:"BAD_REQUEST",status:400});if(e.partitionKey!==void 0&&typeof e.partitionKey!="string")throw new u("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 u("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 u("Rank page request `cursor` must be a string or null",{code:"BAD_REQUEST",status:400})},Ca=async e=>{const t=await be(e,"Rank page")??{};$a(t);const r=qa(t.directions);return{cursor:typeof t.cursor=="string"?t.cursor:null,directions:r,index:t.index,partitionKey:typeof t.partitionKey=="string"?t.partitionKey:void 0,table:t.table,take:typeof t.take=="number"?t.take:void 0}},xa=async e=>{const t=await be(e,"Shard-traffic")??{};if(typeof t.table!="string"||t.table.length===0)throw new u("Shard-traffic request is missing `table`",{code:"BAD_REQUEST",status:400});return{table:t.table}},Ba=async e=>{const t=await Z(e);if(typeof t.functionPath!="string"||!Pa.has(t.functionPath))throw new u("PITR request `functionPath` must be a PITR admin op",{code:"BAD_REQUEST",status:400});if(t.shardKey!==void 0&&typeof t.shardKey!="string")throw new u("PITR `shardKey` must be a string",{code:"BAD_REQUEST",status:400});return{args:t.args??{},functionPath:t.functionPath,shardKey:t.shardKey}},ja=e=>{const{defaultShard:t,forwardToShard:r,isAdmin:n,queryCoordinator:o,resolveForwardContext:i,shardDO:l}=e,d=(p,O)=>{if(p.method!=="POST")throw new u(`${O} endpoint requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});if(!n(p))throw new u("Admin auth required",{code:"FORBIDDEN",status:403});if(!o)throw new u(`${O} endpoint requires a \`queryCoordinator\` on the worker`,{code:"BAD_REQUEST",status:400});return o},f=async(p,O)=>{const _=d(p,"Migration"),A=await Ua(p),{headers:T}=await i(p,O),U=await _.orchestrateMigration(l,{args:A.args,functionPath:A.functionPath,headers:T,table:A.table});return Response.json(U,{headers:{"content-type":"application/json"},status:200})},g=async(p,O)=>{const _=d(p,"Rank"),A=await Na(p),{headers:T}=await i(p,O),U=await _.orchestrateRank(l,{headers:T,index:A.index,partitionKey:A.partitionKey,rowId:A.rowId,sortValues:A.sortValues,table:A.table});return Response.json(U,{headers:{"content-type":"application/json"},status:200})},S=async(p,O)=>{const _=d(p,"Rank page"),A=await Ca(p),{headers:T}=await i(p,O),U=await _.orchestrateRankPage(l,{...A,headers:T});return Response.json(U,{headers:{"content-type":"application/json"},status:200})},w=async(p,O)=>{const _=d(p,"Shard-traffic"),A=await xa(p),{headers:T}=await i(p,O),U=await _.orchestrateShardTraffic(l,{headers:T,table:A.table});return Response.json(U,{headers:{"content-type":"application/json"},status:200})},R=async(p,O)=>{if(x(p,"POST","PITR"),!n(p))throw new u("admin PITR endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403});const _=await Ba(p),{headers:A}=await i(p,O),T=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:_.args,functionPath:_.functionPath}),headers:A,method:"POST"});return r(l,_.shardKey??t,T)};return{[Ta]:f,[Aa]:R,[va]:g,[ka]:S,[Ia]:w}},Ka=1,Fa=0,La=32,Ga=512,Qa=/^[a-z][\d_a-z*/-]{0,255}(?:@[a-z][\d_a-z*/-]{0,13})?=[\u0020-\u002B\u002D-\u003C\u003E-\u007E]{1,256}$/,Ma=e=>{if(e==null)return;const t=e.trim();if(t.length===0||t.length>Ga)return;const r=t.split(",");if(!(r.length>La)){for(const n of r)if(!Qa.test(n.trim()))return;return t}},za=e=>{const t=$r(e.headers.get("traceparent"));if(t===void 0)return;const r=Ma(e.headers.get("tracestate"));return{parentSpanId:t.parentSpanId,sampled:t.sampled,traceId:t.traceId,...r===void 0?{}:{traceState:r}}},Wa=(e,t={})=>{const r=za(e),n=t.trustInbound===!0?r:void 0,o=Oe(8),i=n?.traceId??Oe(16),l=tn(t.sampling,n===void 0?o:i),d=l.isTraced&&(n===void 0||n.sampled);return{decision:l,ignoredUpstream:r!==void 0&&n===void 0,trace:{sampled:d,spanId:o,traceFlags:d?Ka:Fa,traceId:i,...n?.parentSpanId===void 0?{}:{parentSpanId:n.parentSpanId},...n?.traceState===void 0?{}:{traceState:n.traceState}}}},Ha=(e,t)=>{t.traceparent=qr(e.traceId,e.spanId,e.sampled),e.traceState!==void 0&&(t.tracestate=e.traceState)},Ja=(e,t)=>{let r;return()=>{if(r===void 0){const n=jr(e),o=t===void 0?void 0:t.cf;r=Cr(Br(n),xr(n,o))}return r}},Va="/_lunora/admin/scheduled",Ya="/_lunora/admin/scheduled/status",Xa="/_lunora/admin/scheduled/ws",Za="/_lunora/admin/scheduled/cancel",eo="/_lunora/admin/scheduled/dead",to="/_lunora/admin/scheduled/dead/retry",ro="/_lunora/admin/scheduled/dead/cancel",no=e=>{const{checkWsAdmin:t,requireSchedulerNamespace:r,resolveSchedulerStub:n,schedulerInstanceName:o}=e,i=(f,g)=>S=>{if(S.method!=="GET")throw new u(`${g} endpoint requires GET`,{code:"METHOD_NOT_ALLOWED",status:405});return n(S).fetch(new Request(`https://scheduler.internal${f}`,{method:"GET"}))},l=(f,g,S=g)=>async w=>{if(w.method!=="POST")throw new u(`${S} requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});const R=n(w),p=await w.json().catch(()=>{});if(typeof p?.id!="string"||p.id==="")throw new u(`${g} requires a string \`id\``,{code:"BAD_REQUEST",status:400});return R.fetch(new Request(`https://scheduler.internal${f}`,{body:JSON.stringify({id:p.id}),headers:{"content-type":"application/json"},method:"POST"}))},d=async f=>{if(f.headers.get("Upgrade")!=="websocket")throw new u("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});if(!await t(f))throw new u("admin authorization required",{code:"ADMIN_FORBIDDEN",status:403});const g=r();return we(g,o).fetch(new Request("https://scheduler.internal/ws",{headers:{Upgrade:"websocket"}}))};return{[Za]:l("/cancel","Scheduled-cancel","Scheduled-cancel endpoint"),[ro]:l("/dead/cancel","Scheduled dead-letter action"),[eo]:i("/dead","Scheduled dead-letter"),[to]:l("/dead/retry","Scheduled dead-letter action"),[Va]:i("/list","Scheduled-list"),[Ya]:i("/status","Scheduler-status"),[Xa]:d}},ao=(e,...t)=>{let r=e.cf;for(const n of t){if(typeof r!="object"||r===null)return;r=r[n]}return typeof r=="string"?r:void 0},yt={mtls:e=>ao(e,"tlsClientAuth","certVerified")==="SUCCESS"},oo=e=>e===void 0||e===!1?()=>!1:e===!0?()=>!0:typeof e=="function"?e:(Object.hasOwn(yt,e)?yt[e]:void 0)??(()=>!1),so=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.'))}},io="/_lunora/admin/vector/indexes",co="/_lunora/admin/vector/query",uo=e=>{const{readJsonBody:t,requireAdminOption:r}=e,n=async i=>{x(i,"GET","Vector-indexes");const l=r(i,e.vectorIntrospector,{code:"VECTORS_NOT_CONFIGURED",message:"vector endpoints require a `vectorIntrospector` on the worker"});return Response.json({indexes:await l.listIndexes()},{headers:{"content-type":"application/json"},status:200})},o=async i=>{x(i,"POST","Vector-query");const l=r(i,e.vectorIntrospector,{code:"VECTORS_NOT_CONFIGURED",message:"vector endpoints require a `vectorIntrospector` on the worker"});if(l.queryIndex===void 0)throw new u("vector index querying is not enabled on this worker",{code:"VECTOR_QUERY_UNSUPPORTED",status:400});const d=await t(i);if(typeof d.name!="string"||d.name==="")throw new u("Vector-query request requires a `name` string",{code:"BAD_REQUEST",status:400});if(typeof d.text!="string"||d.text==="")throw new u("Vector-query request requires a `text` string",{code:"BAD_REQUEST",status:400});if(d.topK!==void 0&&(typeof d.topK!="number"||!Number.isInteger(d.topK)||d.topK<1))throw new u("Vector-query `topK` must be a positive integer",{code:"BAD_REQUEST",status:400});const f=await l.queryIndex({name:d.name,text:d.text,topK:d.topK});return Response.json(f,{headers:{"content-type":"application/json"},status:200})};return{[io]:n,[co]:o}},lo="/_lunora/admin/workflows/instances",ho="/_lunora/admin/workflows/instance",po="/_lunora/admin/workflows/status",fo={complete:!0,errored:!0,paused:!0,queued:!0,running:!0,terminated:!0,unknown:!0,waiting:!0,waitingForPause:!0},mo=e=>e!==null&&Object.hasOwn(fo,e)?e:void 0,bt=(e,t)=>{const r=e.searchParams.get(t);if(r===null)return;const n=Number(r);return Number.isInteger(n)&&n>0?n:void 0},Fe=(e,t)=>{const r=e.searchParams.get(t);if(r===null||r==="")throw new u(`Workflows admin endpoint requires a \`${t}\` query parameter`,{code:"BAD_REQUEST",status:400});return r},Rt=()=>{throw new u("Workflow inspection is unconfigured. Set CLOUDFLARE_ACCOUNT_ID + CLOUDFLARE_API_TOKEN in your .dev.vars to enable it.",{code:"WORKFLOWS_NOT_CONFIGURED",status:501})},wo=e=>{const{assertAdmin:t,resolveWorkflowsClient:r}=e,n=async(l,d,f)=>{x(l,"GET","Workflows instances"),t(l);const g=r(d);if(!g)return Response.json({configured:!1,instances:[],page:1,perPage:0,totalCount:0});const S=Fe(f,"name"),w=mo(f.searchParams.get("status"));return Response.json(await g.listInstances({page:bt(f,"page"),perPage:bt(f,"perPage"),status:w,workflowName:S}))},o=async(l,d,f)=>{x(l,"GET","Workflows instance"),t(l);const g=r(d);return g?Response.json(await g.getInstance({instanceId:Fe(f,"id"),workflowName:Fe(f,"name")})):Rt()},i=async(l,d)=>{x(l,"POST","Workflows status"),t(l);const f=r(d);if(!f)return Rt();const g=await l.json().catch(()=>{});if(typeof g?.name!="string"||g.name===""||typeof g.id!="string"||g.id==="")throw new u("Workflows status action requires string `name` and `id`",{code:"BAD_REQUEST",status:400});const{action:S}=g;if(S!=="pause"&&S!=="resume"&&S!=="terminate")throw new u("Workflows status action must be one of: pause, resume, terminate",{code:"BAD_REQUEST",status:400});return Response.json(await f.setInstanceStatus({action:S,instanceId:g.id,workflowName:g.name}))};return{[ho]:o,[lo]:n,[po]:i}},go={[Mt]:zt,[Wr]:zr},_t="/_lunora/rpc",yo="/_lunora/rpc-batch",bo="/_lunora/ws",_e=(e,t,r)=>({resourceAttributes:Ja(e,t),...r===void 0?{}:{waitUntil:r}}),St=e=>e?.waitUntil?{waitUntil:t=>e.waitUntil?.(t)}:{},Et=e=>({spanId:e.spanId,traceFlags:e.traceFlags,traceId:e.traceId,...e.parentSpanId===void 0?{}:{parentSpanId:e.parentSpanId}}),Le=e=>{const{method:t}=e,r=e.headers.get("user-agent")??void 0;let n;try{n=new URL(e.url)}catch{return{method:t,userAgent:r}}const o=n.port===""?void 0:Number(n.port);return{host:n.hostname,method:t,path:n.pathname,port:Number.isNaN(o)?void 0:o,scheme:n.protocol.replace(":",""),userAgent:r}},Ot="/_lunora/voice/",Ro="/_lunora/scheduler/dispatch",_o="/_lunora/admin/cron-jobs/run",So="/_lunora/admin/ws-token",Eo="/_lunora/admin/",Oo="/_lunora/migrate",To="/_lunora/status",Ao=e=>e.startsWith(Eo)||e===Oo,vo=e=>{const t=e.headers.get("x-lunora-userid"),r=e.headers.get("x-lunora-identity");if(!(t===null&&r===null))return{...r===null?{}:{identity:r},...t===null?{}:{userId:t}}},ko="/api/auth",Io="__lunora_admin__:recordAuthEvent",Do="__lunora_admin__:listPushSubscriptions",Po=["/sign-in","/sign-up","/callback"],Uo=(e,t)=>{const r=t.endsWith("/")?t.slice(0,-1):t;if(!e.startsWith(`${r}/`))return!1;const n=e.slice(r.length);return Po.some(o=>n===o||n.startsWith(`${o}/`))},Se=(e,t,r,n)=>{const o=Ir(r),i=o?r.code:"INTERNAL_SERVER_ERROR",l=o?r.status:500,d=r instanceof Error?r.message:String(r);return{durationMs:t,error:{code:i,message:d,status:l},functionPath:e,ok:!1,...n.fanOut?{fanOut:{failed:0,shards:0,table:n.fanOut.table}}:{},...n.shardKey?{shardKey:n.shardKey}:{}}},No=e=>{const{exp:t,expiresAtMs:r}=e;if(typeof r=="number"&&Number.isFinite(r))return r;if(typeof t=="number"&&Number.isFinite(t))return t*1e3},Tt=e=>e.waitUntil?{waitUntil:t=>{e.waitUntil?.(t)}}:void 0,qo=e=>{const t=e?.queue;return typeof t=="string"&&t.length>0?t:"unknown"},ue=async(e,t,r)=>{const n={"content-type":"application/json"},o=e.headers.get("authorization"),i=e.headers.get("cookie"),l=e.headers.get("x-d1-bookmark"),d=e.headers.get("x-lunora-mutation-id"),f=e.headers.get("x-lunora-client-id"),g=e.headers.get("x-lunora-client-seq");o&&(n.authorization=o),i&&(n.cookie=i),l&&(n["x-d1-bookmark"]=l),d&&(n["x-lunora-mutation-id"]=d),f&&(n["x-lunora-client-id"]=f),g&&(n["x-lunora-client-seq"]=g);const S=e.headers.get("cf-connecting-ip");if(S&&(n["x-lunora-client-ip"]=S),!r)return{claims:null,headers:n,identity:null,userId:null};const w=await r(e,t);if(!w||typeof w.userId!="string"||w.userId.length===0)return{claims:null,headers:n,identity:null,userId:null};n["x-lunora-userid"]=Ur(w.userId);const R=No(w);R!==void 0&&(n["x-lunora-identity-exp"]=String(R));const{userId:p,...O}=w,_=Object.keys(O).length>0?O:null;return _&&(n["x-lunora-identity"]=Nr(_)),{claims:_,headers:n,identity:w,userId:p}},$o=new Set(["concat","first","groupBy","max","min","rank","sum","topK"]),Co=e=>{if(e===void 0)return;if(!e||typeof e!="object")throw new u("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 u("RPC `fanOut.table` must be a non-empty string",{code:"BAD_REQUEST",status:400});if(!t.merge||typeof t.merge!="object")throw new u("RPC `fanOut.merge` must be an object",{code:"BAD_REQUEST",status:400});const r=t.merge;if(typeof r.kind!="string"||!$o.has(r.kind))throw new u("RPC `fanOut.merge.kind` is not a recognized merge strategy",{code:"BAD_REQUEST",status:400});if(r.kind==="topK"){if(typeof r.k!="number"||!Number.isInteger(r.k)||r.k<0)throw new u("RPC `fanOut.merge.k` must be a non-negative integer",{code:"BAD_REQUEST",status:400});if(typeof r.by!="string"||r.by.length===0)throw new u("RPC `fanOut.merge.by` must be a non-empty string",{code:"BAD_REQUEST",status:400})}return t},xo=(e,t)=>{e?.LUNORA_DEBUG_RPC&&console.warn(`[lunora:rpc] ${t.fanOut?"fan-out":`shard=${t.shardKey??"(root)"}`} ${t.functionPath}`)},At=(e,t)=>{const r=t.functions?.[e.functionPath]?.x402;if(r){if(e.fanOut)throw new u("a paid (`.x402`) function cannot be fanned out",{code:"BAD_REQUEST",status:400});if(!t.x402Charge)throw new u(`function "${e.functionPath}" is marked paid (.x402) but no x402Charge gate is configured on the worker`,{code:"MISCONFIGURED",status:500});return r}},Bo=async e=>{const t=await Ut(e);let r;try{r=JSON.parse(t)}catch{throw new u("RPC body must be valid JSON",{code:"BAD_REQUEST",status:400})}if(!r||typeof r!="object"||typeof r.functionPath!="string")throw new u("RPC envelope is missing `functionPath`",{code:"BAD_REQUEST",status:400});const n=r;if(n.args!==void 0&&Nt(n.args,"RPC"),n.shardKey!==void 0&&typeof n.shardKey!="string")throw new u("RPC `shardKey` must be a string",{code:"BAD_REQUEST",status:400});const o=r,i=Co(o.fanOut),l=o.args??{};if(i&&o.functionPath.startsWith("__lunora_relation__:")){const d=l.table;if(typeof d=="string"&&d!==i.table)throw new u("RPC `args.table` must match the authorized `fanOut.table` for a relation fan-out",{code:"BAD_REQUEST",status:400});l.table=i.table}return{args:l,fanOut:i,functionPath:o.functionPath,shardKey:o.shardKey}},Ee=new Map,jo=5e3,Ko=4096,Fo=async(e,t)=>{const r=Date.now(),n=Ee.get(t);if(n!==void 0&&n.expiresMs>r)return n.relayCount;n!==void 0&&Ee.delete(t);let o=0;try{const i=await we(e,t).fetch(new Request("https://shard.internal/_lunora/route"));if(i.ok){const l=(await i.json()).relayCount;typeof l=="number"&&l>0&&(o=Math.floor(l))}}catch{o=0}return Dt(Ee,Ko),Ee.set(t,{expiresMs:r+jo,relayCount:o}),o},vt=(e,t)=>{if(!(e===null||typeof e!="object"))return Object.entries(e).find(([,r])=>r===t)?.[0]},ye=(e,t,r)=>new Request("https://shard.internal/rpc",{body:JSON.stringify({args:t,functionPath:e}),headers:r,method:"POST"}),Lo=["x-lunora-userid","x-lunora-identity","x-lunora-identity-exp"],kt=(e,t)=>{for(const r of Lo){e.delete(r);const n=t[r];n!==void 0&&e.set(r,n)}},Go=async(e,t,r)=>e.length===0||r.length===0?!1:Me(await xt(e,t),r),It=(e,t)=>{if(!t||t.length===0)return!1;const r=e.headers.get("authorization");if(!r)return!1;const[n,...o]=r.split(" ");return n?.toLowerCase()!=="bearer"?!1:Me(t,o.join(" ").trim())},Qo=async(e,t,r)=>{if(!t||t.length===0)return!1;const n=new URL(e.url).searchParams.get("token");return n===null?!1:await An(t,n)?!0:r?!1:Me(t,n)},Mo=(e,t)=>{if(t===null||typeof t!="object"&&typeof t!="function")return;const r=t;if(typeof r.prepare=="function"&&typeof r.batch=="function"&&typeof r.dump=="function")return Xr(`d1:${e}`,t);if(typeof r.list=="function"&&typeof r.head=="function"&&typeof r.createMultipartUpload=="function")return qe(`r2:${e}`,!0);if(typeof r.send=="function"&&typeof r.sendBatch=="function"&&typeof r.get!="function")return qe(`queue:${e}`,!0);if(typeof r.connectionString=="string")return qe(`hyperdrive:${e}`,!0)},Wt=e=>{const t=oo(e.trustInboundTraceContext),r=so(e.trustInboundTraceContext),n=e.defaultShardKey??"__root__",o=Zr(e.resolveIdentity,e.identity),i=rt(e.shardDO,e.jurisdiction),l=e.schedulerDO===void 0?void 0:rt(e.schedulerDO,e.jurisdiction);let d=!1;const f=a=>{if(a===void 0||e.jurisdiction===void 0)return a;d||(d=!0,console.warn(`[lunora] jurisdiction "${e.jurisdiction}" pins placement, so region hints (\`shardRegion\`, replica and relay placement) are not sent. Residency wins.`))},g=async(a,s,h,c=e.shardRegion?.(s))=>we(a,s,f(c)).fetch(h);let S;const w=()=>e.adminToken??S;let R;const p=()=>e.requireEphemeralWsToken??R??!0;let O;const _=a=>{const s=a??{};if(O??=vt(a,e.shardDO),R===void 0&&e.requireEphemeralWsToken===void 0){const c=s.LUNORA_REQUIRE_EPHEMERAL_WS_TOKEN;typeof c=="string"&&c.length>0&&(R=En(c,!0))}if(S!==void 0||e.adminToken!==void 0)return;const h=s.LUNORA_ADMIN_TOKEN;typeof h=="string"&&h.length>0&&(S=h)},A=new WeakSet,T=a=>It(a,w())||A.has(a),U=async(a,s)=>{const h=await ue(a,s,e.resolveIdentity);if(A.has(a)&&h.headers.authorization===void 0){const c=w();c!==void 0&&(h.headers.authorization=`Bearer ${c}`)}return h};let k=!1,j=!1;const K=()=>{j||(j=!0,console.warn("[lunora] `replicaReads: true` has no effect without `functions` — read eligibility is decided from the function registry."))},z=a=>{if(!e.allowUnauthenticatedShardAccess){const s=a==="fan-out"?"authorizeFanOut":"authorizeShard";throw new u(`${a} access is default-denied: configure \`${s}\` on the worker, or set \`allowUnauthenticatedShardAccess: true\` to explicitly allow unauthenticated ${a} access (relying solely on per-row RLS).`,{code:a==="fan-out"?"FORBIDDEN_FANOUT":"FORBIDDEN_SHARD",status:403})}k||(k=!0,console.warn([`[lunora] SECURITY: serving ${a} access with \`allowUnauthenticatedShardAccess: true\` and no \`authorizeShard\`/\`authorizeFanOut\` — `,"any caller (including unauthenticated ones) can target any shard / fan out across the table. ","This is safe only if every table is protected by per-row RLS. Configure `authorizeShard`/`authorizeFanOut` to gate it."].join("")))},N=async(a,s,h=!0)=>{if(e.authorizeShard){if(!await e.authorizeShard(a,s))throw new u("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else h&&s!==n&&z("shard")},L=ja({defaultShard:n,forwardToShard:g,isAdmin:T,queryCoordinator:e.queryCoordinator,resolveForwardContext:U,shardDO:i}),F=async(a,s,h,c,m)=>{await N(null,h,!1);const b={"content-type":"application/json","x-lunora-system":"1"};return m?.userId!==void 0&&m.userId.length>0&&(b["x-lunora-userid"]=m.userId),m?.identity!==void 0&&m.identity.length>0&&(b["x-lunora-identity"]=m.identity),c!==void 0&&c.length>0&&(b["x-lunora-mutation-id"]=c),g(i,h,ye(a,s,b))},J=async(a,s,h,c)=>{const m=h?.[a];if(!m||typeof m.create!="function")throw new u(`${c} targets workflow binding "${a}", which is not bound on env`,{code:"CRON_JOB_FAILED",status:500});if(on(s))throw new u(`${c} params ${sn}`,{code:"BAD_REQUEST",status:400});await m.create({params:s})},W=async(a,s)=>{if(a.workflow){await J(a.workflow,a.args??{},s,`cron job "${a.name}"`);return}if(a.functionPath===void 0)throw new u(`cron job "${a.name}" has neither a function target nor a workflow target`,{code:"CRON_JOB_FAILED",status:500});const h=await F(a.functionPath,a.args??{},a.shardKey??n);if(!h.ok)throw new u(`cron job "${a.name}" (${a.functionPath}) failed with shard status ${String(h.status)}`,{code:"CRON_JOB_FAILED",status:500})},X=async(a,s,h,c)=>{const m=e.cronJobs?.[a];if(m)for(const b of m)try{await W(b,s)}catch(I){h.push(c(I))}},V=async(a,s)=>{if(!T(a))throw new u("admin endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403});if(x(a,"POST","cron-jobs run"),!e.cronJobs)throw new u("cron-jobs run endpoint requires a `cronJobs` map on the worker",{code:"CRON_JOBS_NOT_CONFIGURED",status:400});const h=await Z(a),c=typeof h.name=="string"?h.name:"";if(c==="")throw new u("cron-jobs run endpoint requires a job `name`",{code:"BAD_REQUEST",status:400});const m=Object.values(e.cronJobs).flat().find(b=>b.name===c);if(!m)throw new u(`no cron job named "${c}" is registered`,{code:"CRON_JOB_NOT_FOUND",status:404});return await W(m,s),Response.json({name:c,ran:!0},{status:200})},oe=async a=>{const s=typeof a.pool=="string"&&a.pool.length>0?a.pool:void 0;if(!s||!l||typeof a.id!="string")return;const h=typeof a.instanceName=="string"&&a.instanceName.length>0?a.instanceName:"default";try{await we(l,h).fetch(new Request("https://scheduler.internal/complete",{body:JSON.stringify({id:a.id,pool:s}),headers:{"content-type":"application/json"},method:"POST"}))}catch{}},he=async(a,s)=>{x(a,"POST","Scheduler dispatch");const h=await Ut(a),c=s??{},m=typeof c.LUNORA_SCHEDULER_SECRET=="string"?c.LUNORA_SCHEDULER_SECRET:void 0,b=e.adminToken??(typeof c.LUNORA_ADMIN_TOKEN=="string"?c.LUNORA_ADMIN_TOKEN:void 0),I=a.headers.get("x-lunora-scheduler-signature");let y=!1;if(I&&m?y=await Go(m,h,I):b&&(y=It(a,b)),!y)throw new u("Scheduler dispatch requires a valid signature or admin bearer",{code:"FORBIDDEN",status:403});let E;try{E=JSON.parse(h)}catch{throw new u("Scheduler dispatch body must be valid JSON",{code:"BAD_REQUEST",status:400})}const v=E??{},q=v.args??{};if(typeof v.workflow=="string"&&v.workflow.length>0)return await J(v.workflow,q,s,"scheduled workflow"),Response.json({ok:!0},{status:200});if(typeof v.functionPath!="string"||v.functionPath.length===0)throw new u("Scheduler dispatch is missing `functionPath`",{code:"BAD_REQUEST",status:400});const $=typeof v.shardKey=="string"&&v.shardKey.length>0?v.shardKey:n,C=typeof v.id=="string"&&v.id.length>0?v.id:void 0,ee=vo(a),B=await F(v.functionPath,q,$,C,ee);return await oe(v),B},G=a=>{if(!T(a))throw new u("admin endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403})},ne=(a,s,h)=>{if(G(a),s===void 0)throw new u(h.message,{code:h.code,status:400});return s},Te=Pn({assertAdmin:G,getReader:()=>e.authAuditReader}),Ae=async(a,s)=>{G(a);const h=e.notifySubscriptionStore;if(h===void 0)return Response.json({subscriptions:[]},{headers:{"content-type":"application/json"},status:200});const c=s?.kind,m=s?.userId,b=s?.limit,I=c==="fcm"||c==="web-push"?c:void 0,y=typeof m=="string"&&m!==""?m:void 0,E=typeof b=="number"&&Number.isFinite(b)?Math.trunc(b):0,v=E>0?Math.min(E,1e3):1e3,q=(await h.list({kind:I,limit:v,userId:y})).filter($=>I!==void 0&&$.kind!==I?!1:y===void 0||($.userId??null)===y).map(({keys:$,token:C,...ee})=>ee);return Response.json({subscriptions:q},{headers:{"content-type":"application/json"},status:200})},se=async(a,s)=>{if(!s.fanOut){if(s.functionPath===Dn)return Te(a,s.args??{});if(s.functionPath===Do)return Ae(a,s.args)}},Ht=oa({applyGlobals:e.applyGlobals,assertAdmin:G,exportCursorStore:e.exportCursorStore,exportSinks:e.exportSinks,knownTables:()=>[],queryCoordinator:e.queryCoordinator,requireAdminOption:ne,resolveForwardContext:U,shardDO:i,streamExportRows:(a,s,h,c)=>Lt(e,a,s,h,c,i),streamingImport:(a,s)=>ua(a,e,s,i),syncGlobals:e.syncGlobals}),ve=(a,s)=>{const h=a.searchParams.get(s);return h===null||h===""?void 0:h},ke=a=>{const s=new URL(a.url),h=s.searchParams.get("limit"),c=s.searchParams.get("offset"),m=h===null?void 0:Number.parseInt(h,10),b=c===null?void 0:Number.parseInt(c,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}},He=()=>{if(l===void 0)throw new u("scheduled endpoints require a `schedulerDO` namespace on the worker",{code:"SCHEDULER_NOT_CONFIGURED",status:400});return l},Jt=no({checkWsAdmin:async a=>T(a)||Qo(a,w(),p()),requireSchedulerNamespace:He,resolveSchedulerStub:a=>(G(a),we(He(),e.schedulerInstanceName??"default")),schedulerInstanceName:e.schedulerInstanceName??"default"}),Vt=wo({assertAdmin:G,resolveWorkflowsClient:e.workflowsClient??(()=>{})}),Yt=Hr({assertAdmin:G,parsePaging:ke,queryParameter:ve,readBodyBytes:Fr,requireAdminOption:ne,storage:{storageBuckets:e.storageBuckets,storageDelete:e.storageDelete,storageDownload:e.storageDownload,storageList:e.storageList,storageSignedUrl:e.storageSignedUrl,storageUpload:e.storageUpload}}),Xt=Qn({options:e,readJsonBody:Z,requireAdminOption:ne}),Zt=uo({readJsonBody:Z,requireAdminOption:ne,vectorIntrospector:e.vectorIntrospector}),er=Oa({kvIntrospector:e.kvIntrospector,readJsonBody:Z,requireAdminOption:ne}),tr=en({logArchive:e.logArchive,readJsonBody:Z,requireAdminOption:ne}),rr=_a({assertAdmin:G,options:{cronJobs:e.cronJobs,functions:e.functions,globalIntrospector:e.globalIntrospector,openApiSpec:e.openApiSpec,openRpcSpec:e.openRpcSpec},parsePaging:ke,queryParameter:ve,requireAdminOption:ne}),nr=a=>{const s=[],h=i??a?.SHARD;if(h!==void 0&&s.push(Yr("durable-object:default",h,n)),e.health?.disableBindingProbes!==!0)for(const[c,m]of Object.entries(a??{})){const b=Mo(c,m);b!==void 0&&s.push(b)}for(const c of e.health?.probes??[])s.push(c);return s},ar=Vr({appName:e.health?.appName,appVersion:e.health?.appVersion,auth:e.health?.auth??"public",cacheTtlMs:e.health?.cacheTtlMs,isAdmin:T,resolveProbes:nr}),or=a=>{const s=e.schedulerInstanceName??"default",h=()=>we(a,s),c=async(y,E)=>{const v=await h().fetch(new Request(`https://scheduler.internal${y}`,E));if(!v.ok)throw new u(`ctx.scheduler: SchedulerDO ${y} failed (${String(v.status)}): ${await v.text()}`,{code:"INTERNAL",status:500});return await v.json()},m=async(y,E)=>await c(y,{body:JSON.stringify(E),headers:{"content-type":"application/json"},method:"POST"}),b=y=>{const E=y;if(E==null)throw new u("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 u("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})},I=async(y,E,v={})=>{const{id:q}=await m("/schedule",{args:v,scheduledFor:y,...b(E)});return q};return{cancel:async y=>await m("/cancel",{id:y}),get:async y=>await c(`/get?id=${encodeURIComponent(y)}`,{method:"GET"}),list:async()=>await c("/list",{method:"GET"}),runAfter:async(y,E,v)=>{if(!Number.isFinite(y)||y<0)throw new u("ctx.scheduler.runAfter: `delayMs` must be a non-negative finite number",{code:"BAD_REQUEST",status:400});return await I(Date.now()+y,E,v)},runAt:async(y,E,v)=>{if(!Number.isFinite(y))throw new u("ctx.scheduler.runAt: `timestampMs` must be a finite epoch-millisecond number",{code:"BAD_REQUEST",status:400});return await I(y,E,v)}}},sr=async(a,s,h)=>{const{claims:c,headers:m,userId:b}=await ue(a,s,o),I=async(y,E={})=>{const v=y.__lunoraRef;if(typeof v!="string")throw new u("ctx.run*: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});const q=ye(v,E,{...m,"x-lunora-system":"1"}),$=await g(i,n,q),C=await $.json();if(C.error)throw new u(C.error.message??"shard RPC failed",{code:C.error.code??"INTERNAL",status:$.status});return C.result};return{auth:{getIdentity:()=>Promise.resolve(c),userId:b},cache:h.cache,fetch:globalThis.fetch.bind(globalThis),runAction:I,runMutation:I,runQuery:I,...l===void 0?{}:{scheduler:or(l)},...e.storage===void 0?{}:{storage:an(e.storage(s))}}},ir=async(a,s,h)=>{if(!e.httpRouter)return;const c=await sr(a,s,h);try{return await e.httpRouter.fetch(a,{...s,__lunoraCtx:c},h)}catch(m){return console.error("[lunora] httpRouter (SSR) handler threw:",m),new Response("Internal Server Error",{status:500})}},cr=async(a,s,h)=>{if(a.headers.get("Upgrade")!=="websocket")throw new u("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});const c=at(a,ie);if(c)return c;const m=h.searchParams.get("shard")??n,{headers:b,identity:I}=await ue(a,s,o);await N(I,m);const y=new Headers(a.headers),E=[...y.keys()];for(const q of E)q.startsWith("x-lunora-")&&y.delete(q);kt(y,b);const v=vt(s,e.shardDO);if(v!==void 0){y.set("x-lunora-shard-binding",v);const q=await Fo(i,m);if(q>0){const $=yn(m,Math.floor(Math.random()*q));return g(i,$,new Request(a,{headers:y}),ot(a))}}return g(i,m,new Request(a,{headers:y}))},ur=async(a,s,h)=>{const{voiceAgents:c}=e;if(c===void 0)return new Response("Not found",{status:404});if(a.headers.get("Upgrade")!=="websocket")return new Response("Expected a WebSocket upgrade",{headers:{allow:"GET"},status:426});const m=at(a,ie);if(m)return m;let b;try{b=decodeURIComponent(h.pathname.slice(Ot.length))}catch{return new Response("Unknown voice agent",{status:404})}const I=Object.hasOwn(c,b)?c[b]:void 0;if(I===void 0)return new Response("Unknown voice agent",{status:404});const y=h.searchParams.get("threadKey");if(y===null||y.length===0)return new Response("Missing threadKey",{status:400});const{headers:E,identity:v}=await ue(a,s,o);if(e.authorizeShard){if(!await e.authorizeShard(v,y))return new Response("Forbidden",{status:403})}else z("shard");const q=new Headers(a.headers);for(const $ of q.keys())$.startsWith("x-lunora-")&&q.delete($);return kt(q,E),g(I,y,new Request(a,{headers:q}))},dr=async(a,s,h)=>{if(e.authorizeFanOut){if(!await e.authorizeFanOut(h,a.table,s))throw new u("Forbidden fan-out",{code:"FORBIDDEN_FANOUT",status:403});return}if(s.startsWith("__lunora_relation__:"))throw new u("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 u("Fan-out requires `authorizeFanOut` to be configured on the worker when `authorizeShard` is set",{code:"FORBIDDEN_FANOUT",status:403});z("fan-out")},Re=async(a,s)=>{if(!(!a.fanOut&&a.functionPath.startsWith("__lunora_admin__:"))){if(a.fanOut){await dr(a.fanOut,a.functionPath,s);return}await N(s,a.shardKey??n)}},lr=(a,s,h)=>{if(e.replicaReads!==!0)return;if(e.functions===void 0){K();return}if(e.functions[s]?.kind!=="query"||h.includes(jt)||h.includes(Bt))return;const c=ot(a);return c===void 0?void 0:{name:bn(h,c),region:c}},hr=async(a,s,h,c,m)=>{const b=lr(a,s,c);if(b!==void 0){const I={...m,"x-lunora-replica-read":"1",...O===void 0?{}:{"x-lunora-shard-binding":O}},y=Rn(a.headers.get("x-lunora-min-seq"));y!==void 0&&(I["x-lunora-min-seq"]=String(y));const E=await g(i,b.name,ye(s,h,I),b.region);if(E.status!==421)return E}return g(i,c,ye(s,h,m))},Ie=async(a,s,h,c,m,b)=>{const I=Date.now(),{observability:y,sampling:E}=e,v=Le(a),{decision:q,ignoredUpstream:$,trace:C}=Wa(a,{...E===void 0?{}:{sampling:E},trustInbound:t(a)});$&&r();const ee={...m,"x-lunora-sample-errors":q.keepErrors?"1":"0"};Ha(C,ee);try{const B=await hr(a,s,h,c,ee);ce(y,{...v,...Et(C),durationMs:Date.now()-I,functionPath:s,ok:B.ok,shardKey:c,...B.ok?{}:{error:{code:"SHARD_ERROR",message:`shard returned ${String(B.status)}`,status:B.status}}},b,void 0,{isTraced:C.sampled,keepErrors:q.keepErrors});const te=new Response(B.body,{headers:B.headers,status:B.status,statusText:B.statusText});return te.headers.set("x-lunora-shard-key",c),te}catch(B){throw ce(y,{...v,...Et(C),...Se(s,Date.now()-I,B,{shardKey:c})},b,void 0,{isTraced:C.sampled,keepErrors:q.keepErrors}),B}},pr=a=>{if(a.fanOut&&a.shardKey)throw new u("RPC envelope cannot set both `shardKey` and `fanOut`",{code:"BAD_REQUEST",status:400});if(!a.fanOut&&a.functionPath.startsWith("__lunora_relation__:"))throw new u("`__lunora_relation__:*` is a fan-out-only reserved RPC and cannot be dispatched to a single shard",{code:"FORBIDDEN",status:403});if(a.fanOut&&!e.queryCoordinator)throw new u("RPC envelope set `fanOut` but no `queryCoordinator` is configured on the worker",{code:"BAD_REQUEST",status:400})},fr=async(a,s,h)=>{x(a,"POST","RPC");const c=await Bo(a);xo(s,c),pr(c);const m=await se(a,c);if(m!==void 0)return m;const{headers:b,identity:I}=await ue(a,s,o);await Re(c,I);const y=At(c,e);{const E=Date.now(),{observability:v}=e,q=Le(a),$=_e(s,a,h&&(B=>h.waitUntil?.(B)));if(c.fanOut){const B=e.queryCoordinator;if(!B)throw new u("RPC envelope set `fanOut` but no `queryCoordinator` is configured on the worker",{code:"BAD_REQUEST",status:400});try{const te=await B.fanOut(i,{args:c.args??{},fanOut:c.fanOut,functionPath:c.functionPath,headers:b});return ce(v,{durationMs:Date.now()-E,fanOut:{failed:te.failed,shards:te.ok+te.failed,table:c.fanOut.table},functionPath:c.functionPath,...q,ok:!0},$),Response.json(te,{headers:{"content-type":"application/json"},status:200})}catch(te){throw ce(v,{...Se(c.functionPath,Date.now()-E,te,{fanOut:{table:c.fanOut.table}}),...q},$),te}}const C=c.shardKey??n,ee=()=>Ie(a,c.functionPath,c.args??{},C,b,$);return y&&e.x402Charge?e.x402Charge(a,{functionPath:c.functionPath,price:y.price},ee,St(h)):ee()}},mr=async(a,s,h)=>{x(a,"POST","RPC batch");const c=await Z(a),{calls:m}=c;if(!Array.isArray(m))throw new u("RPC batch `calls` must be an array",{code:"BAD_REQUEST",status:400});const{headers:b,identity:I}=await ue(a,s,o),y=zn(m,n);for(const Q of y.values())for(const M of Q)if(e.functions?.[M.functionPath]?.x402)throw new u(`paid (\`.x402\`) function "${M.functionPath}" cannot be called in a batch; dispatch it individually over ${_t}`,{code:"BAD_REQUEST",status:400});await Promise.all([...y.entries()].flatMap(([Q,M])=>M.map(ae=>Re({functionPath:ae.functionPath,shardKey:Q},I))));const{observability:E}=e,v=_e(s,a,h&&(Q=>h.waitUntil?.(Q))),q=Le(a),$=[],C=[],ee=(Q,M,ae,de)=>({body:{error:{code:ae,message:de}},id:Q.id,status:M}),B=(Q,M,ae,de,pe)=>{for(const H of Q)ce(E,pe(H),v),$.push(ee(H,M,ae,de))},te=(Q,M,ae,de,pe)=>{for(const H of Q){const fe=de.get(H.id)??pe,ge=fe<400;ce(E,{durationMs:ae,functionPath:H.functionPath,...q,ok:ge,shardKey:M,...ge?{}:{error:{code:"SHARD_ERROR",message:`batched call returned ${String(fe)}`,status:fe}}},v)}};await Promise.all([...y.entries()].map(async([Q,M])=>{const ae=new Headers(b);ae.set("content-type","application/json");const de=new Request("https://shard.internal/rpc-batch",{body:JSON.stringify({calls:M}),headers:ae,method:"POST"}),pe=Date.now();let H;try{H=await g(i,Q,de)}catch(Y){const Ne=Date.now()-pe,{body:Ze}=Dr(Y,{fallbackCode:"SHARD_UNAVAILABLE",redactedMessage:"shard unavailable"});B(M,502,Ze.code,Ze.message,kr=>({...Se(kr.functionPath,Ne,Y,{shardKey:Q}),...q}));return}const fe=Date.now()-pe,ge=H.headers.get("x-d1-bookmark");ge&&C.push(ge);let Pe;try{Pe=await H.json()}catch{const Y=`shard batch returned a non-JSON response (${String(H.status)})`;B(M,H.status,"SHARD_ERROR",Y,Ne=>({durationMs:fe,error:{code:"SHARD_ERROR",message:Y,status:H.status},functionPath:Ne.functionPath,...q,ok:!1,shardKey:Q}));return}const Ue=Array.isArray(Pe.results)?Pe.results:[],Ar=new Map(Ue.map(Y=>[Y.id,Y.status??H.status])),vr=new Set(Ue.map(Y=>Y.id));te(M,Q,fe,Ar,H.status),$.push(...Ue);for(const Y of M)vr.has(Y.id)||$.push(ee(Y,H.status,"SHARD_ERROR",`shard batch omitted result for call ${String(Y.id)}`))}));const Ye={"content-type":"application/json"},[Xe]=C;return C.length===1&&Xe!==void 0&&(Ye["x-d1-bookmark"]=Xe),Response.json({results:$},{headers:Ye,status:200})},wr=async(a,s,h,c={},m={})=>{try{const b=h.__lunoraRef;if(typeof b!="string")throw new u("serverQuery: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});const{headers:I,identity:y}=await ue(a,s,o);await Re({functionPath:b,shardKey:m.shardKey},y);const E=m.shardKey??n,v=_e(s,a,m.waitUntil);return await Ie(a,b,c,E,I,v)}catch(b){return et(b)}},Je=async(a,s,h)=>{const{observability:c}=e,m=Date.now(),b=Oe(16),I=Oe(8),y=Tt(s);try{const E=await h();return ce(c,{durationMs:Date.now()-m,functionPath:a,ok:!0,spanId:I,traceId:b},y),E}catch(E){throw ce(c,{...Se(a,Date.now()-m,E,{}),spanId:I,traceId:b},y),E}finally{tt(c,y)}},gr=async(a,s,h)=>{_(s);const c=[],m=y=>y instanceof Error?y:new Error(String(y)),b=e.crons?.[a.cron];if(b)try{await b(a,s,h)}catch(y){c.push(m(y))}if(await X(a.cron,s,c,m),e.backupStore&&e.backupCron!==void 0&&e.backupCron===a.cron)try{await Kn(e,i,w(),a)}catch(y){c.push(m(y))}const[I]=c;if(c.length===1&&I)throw I;if(c.length>1)throw new AggregateError(c,`scheduled("${a.cron}") had ${String(c.length)} failure(s)`)},yr=async(a,s)=>{try{const h=a??{},c=e.adminToken??(typeof h.LUNORA_ADMIN_TOKEN=="string"?h.LUNORA_ADMIN_TOKEN:void 0);if(!c||c.length===0)return;await g(i,n,ye(Io,{outcome:s},{authorization:`Bearer ${c}`,"content-type":"application/json"}))}catch{}},br=async(a,s,h,c)=>{if(!e.authHandler)return;const m=await e.authHandler(a);if(!m)return;const b=e.authBasePath??ko;return Uo(h.pathname,b)&&c.waitUntil?.(yr(s,m.status>=400?"fail":"ok")),m},Rr=async({args:a,env:s,functionPath:h,request:c,shardKey:m,waitUntil:b})=>{Nt(a,"REST");const I={functionPath:h,...m===void 0?{}:{shardKey:m}},{headers:y,identity:E}=await ue(c,s,o);await Re(I,E);const v=m??n,q=_e(s,c,b),$=()=>Ie(c,h,a,v,y,q),C=At(I,e);return C&&e.x402Charge?e.x402Charge(c,{functionPath:h,price:C.price},$,St({waitUntil:b})):$()},_r=Kr({functions:e.functions??{},invoke:Rr,readJsonBody:Z,...e.restRateLimit?{rateLimit:e.restRateLimit}:{}}),De=e.routes!==void 0&&Object.keys(e.routes).length>0?e.routes:void 0,Sr={[To]:a=>a.method!=="GET"&&a.method!=="HEAD"?new Response(void 0,{headers:{allow:"GET, HEAD"},status:405}):Response.json({ok:!0},{headers:{"cache-control":"no-store"}}),[bo]:(a,s,h)=>cr(a,s,h),[_t]:(a,s,h,c)=>fr(a,s,c),[yo]:(a,s,h,c)=>mr(a,s,c),[Ro]:(a,s)=>he(a,s),[_o]:(a,s)=>V(a,s),[So]:async a=>{x(a,"POST","ws-token"),G(a);const s=w();if(s===void 0)throw new u("ws-token minting requires a configured admin token",{code:"ADMIN_TOKEN_NOT_CONFIGURED",status:400});const h=await Tn(s);return Response.json(h,{headers:{"cache-control":"no-store"}})},...L,...Ht,...Jt,...Vt,...Yt,...Xt,...Zt,...er,...tr,...rr,...ar,..._r,...In({assertAdmin:G,getAuthAdmin:()=>e.authAdmin,parsePaging:ke,queryParameter:ve,readJsonBody:Z})};let ie=nt(e.security),Ve=!1;const Er=a=>{Ve||(Ve=!0,ie=nt(e.security,a??{}))},Or=async(a,s)=>{if(!(e.adminGate===void 0||!Ao(s)))try{await e.adminGate(a)&&A.add(a)}catch{}},Tr=async(a,s,h)=>{const c=new URL(a.url);if(a.method==="POST"||a.method==="PUT"){const y=Number(a.headers.get("content-length")??""),E=go[c.pathname]??Pt;if(Number.isFinite(y)&&y>E)throw new u("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413})}const m=await br(a,s,c,h);if(m)return m;if(De){const y=`${a.method} ${c.pathname}`,E=De[y]??De[c.pathname];if(E)return E(a,s,h)}const b=Sr[c.pathname];return b?(await Or(a,c.pathname),b(a,s,c,h)):e.voiceAgents!==void 0&&c.pathname.startsWith(Ot)?ur(a,s,c):await ir(a,s,h)||new Response("Not found",{status:404})};return{async fetch(a,s,h){e.passThroughOnException&&h.passThroughOnException?.(),Er(s),_(s);const c=rn(a,ie);if(c)return c;const m=nn(a,ie);if(m)return $e(m,a,ie);try{const b=await Tr(a,s,h);return $e(b,a,ie)}catch(b){return $e(et(b),a,ie)}finally{tt(e.observability,Tt(h))}},async queue(a,s,h){await Je(`queue:${qo(a)}`,h,async()=>{await e.queue?.(a,s,h)})},async scheduled(a,s,h){await Je(`cron:${a.cron}`,h,async()=>{await gr(a,s,h)})},serverQuery:wr}},zo=e=>Wt(e),Wo=e=>typeof e=="function"?{fetch:e}:e,Ho=e=>!!(e.crons??e.cronJobs??e.backupCron),ps=(e,t)=>{const r=Wo(e),n=typeof e=="object"&&typeof e.scheduled=="function"?e.scheduled:void 0,o=l=>{const d=zo({...l,httpRouter:r});return n!==void 0&&!Ho(l)?{...d,scheduled:async(f,g,S)=>{await n(f,g,S)}}:d};if(typeof t!="function")return o(t);const i=t;return{fetch:(l,d,f)=>o(i(d)).fetch(l,d,f),queue:(l,d,f)=>o(i(d)).queue?.(l,d,f)??Promise.resolve(),scheduled:(l,d,f)=>o(i(d)).scheduled(l,d,f),serverQuery:(l,d,f,g,S)=>o(i(d)).serverQuery(l,d,f,g,S)}},Jo=(e,t)=>{if(typeof e=="function")return e(t);const r=e.shardDO??t?.SHARD;if(!r)throw new u("@lunora/runtime: no shard Durable Object namespace found. Bind `SHARD` in wrangler.jsonc, or pass `createLunoraHandler({ shardDO: env.MY_SHARD })`.");return{...e,shardDO:r}},fs=(e={})=>(t,r,n)=>Wt(Jo(e,r)).fetch(t,r,n??Pr),ms=e=>e;export{Dn as GET_AUTH_AUDIT_LOG_OP,Pr as NOOP_EXECUTION_CONTEXT,ys as composeIdentityResolvers,zo as composeWorker,fs as createLunoraHandler,Wt as createWorker,ms as defineRpcEnvelope,Fo as probeRelayCount,Jo as resolveLunoraOptions,bs as routeIdentityResolvers,ps as withFrameworkWorker};
@@ -1 +1 @@
1
- import{o as T,a as q}from"./base64-DPPVK6s_.mjs";import{LunoraError as A}from"./LunoraError-ByasbDmd.mjs";import{resolveShard as C}from"./applyJurisdiction-Dsm_m5zW.mjs";const me=r=>({listShardKeys(e){return r[e]??[]}}),pe=r=>{if(r.kind==="count")return{kind:"sum"};if(r.kind==="scalar"){if(r.op==="count"||r.op==="sum")return{kind:"sum"};if(r.op==="max")return{kind:"max"};if(r.op==="min")return{kind:"min"};throw new A('aggregate({ op: "avg" }) is not supported across shards in v1 — fan out sum + count separately',{code:"BAD_REQUEST",status:400})}const e=r.agg?.op??"count";if(e==="count"||e==="sum")return{kind:"groupBy",op:"sum"};if(e==="max")return{kind:"groupBy",op:"max"};if(e==="min")return{kind:"groupBy",op:"min"};throw new A('groupBy({ agg: { op: "avg" } }) is not supported across shards in v1 — fan out sum + count separately',{code:"BAD_REQUEST",status:400})},B=16,F=5e3,f=r=>r!==null&&typeof r=="object"&&"result"in r?r.result:r,I=r=>{const e=r??{};return{changed:typeof e.changed=="number"?e.changed:0,processed:typeof e.processed=="number"?e.processed:0,status:typeof e.status=="string"?e.status:void 0}},D=(r,e)=>r?"failed":e?"in_progress":"completed",R=r=>{const e=[];let s=0,a=0,t=0,o=0,n=!1,i=!1;for(const u of r){if(u.kind==="err"){a+=1,e.push({error:{message:u.message,timedOut:u.timedOut},shardKey:u.shardKey});continue}s+=1;const d=f(u.value),c=I(d);t+=c.changed,o+=c.processed,n||=c.status==="in_progress",i||=c.status==="failed",e.push({result:d,shardKey:u.shardKey})}return{changed:t,failed:a,ok:s,processed:o,shards:e,status:D(i,n||a>0)}},V=r=>{const e=r??{};return{before:typeof e.before=="number"&&Number.isFinite(e.before)?e.before:0,total:typeof e.total=="number"&&Number.isFinite(e.total)?e.total:0}},$=r=>{const e=[];let s=0,a=0,t=0,o=0;for(const n of r){if(n.kind==="err"){a+=1,e.push({error:{message:n.message,timedOut:n.timedOut},shardKey:n.shardKey});continue}s+=1;const i=V(f(n.value));t+=i.before,o+=i.total,e.push({result:i,shardKey:n.shardKey})}return{failed:a,ok:s,partial:a>0,position:t+1,shards:e,total:o}},j=0,E=1,J=2,b=(r,e)=>r<e?-1:r>e?1:0,M=r=>r==null?j:typeof r=="number"?E:J,O=(r,e)=>{const s=M(r),a=M(e);return s!==a?s<a?-1:1:s===j?0:s===E?b(r,e):b(String(r),String(e))},Q=(r,e,s)=>{const a=O(r.partitionKey,e.partitionKey);if(a!==0)return a;const t=Math.max(r.sortValues.length,e.sortValues.length);for(let o=0;o<t;o+=1){const n=O(r.sortValues[o],e.sortValues[o]);if(n!==0)return s[o]==="desc"?-n:n}return O(r.rowId,e.rowId)},L=r=>q(new TextEncoder().encode(JSON.stringify(r))),U=r=>{try{const e=JSON.parse(new TextDecoder().decode(T(r)));if(e!==null&&typeof e=="object"&&"perShard"in e){const{perShard:s}=e;if(s!==null&&typeof s=="object")return{perShard:s}}}catch{}return{perShard:{}}},G=r=>{const e=r??{},s=Array.isArray(e.rows)?e.rows:[];return{directions:Array.isArray(e.directions)?e.directions:[],hasMore:e.hasMore===!0,rows:s}},Y=(r,e)=>{let s;for(const a of r){const t=a.rows[a.head];t!==void 0&&(s===void 0||Q(t.key,s.row.key,e)<0)&&(s={row:t,slice:a})}return s},z=(r,e)=>{let s=!1;const a=new Set;for(const o of r)a.add(o.shardKey),(o.head<o.rows.length||o.hasMore)&&(s=!0);const t={...e};for(const o of Object.keys(e))a.has(o)||(s=!0);return s?L({perShard:t}):null},H=(r,e,s,a)=>{const t=[],o={...a};for(;t.length<e;){const i=Y(r,s);if(i===void 0)break;t.push(i.row.doc),o[i.slice.shardKey]=i.row.key,i.slice.head+=1}const n=z(r,o);return{isDone:n===null,nextCursor:n,page:t}},W=r=>{const e=[];let s=0,a=0;for(const t of r){if(t.kind==="err"){a+=1,e.push({error:{message:t.message,timedOut:t.timedOut},shardKey:t.shardKey});continue}s+=1;const o=f(t.value),n=Array.isArray(o?.rows)?o.rows:[];e.push({rows:n,shardKey:t.shardKey})}return{failed:a,ok:s,shards:e}},X=r=>{const e=[];let s=0,a=0;for(const{outcome:t,sinceSeq:o}of r){if(t.kind==="err"){a+=1,e.push({cursor:o,error:{message:t.message,timedOut:t.timedOut},shardKey:t.shardKey});continue}s+=1;const n=f(t.value),i=Array.isArray(n?.changes)?n.changes:[],u=typeof n?.cursor=="number"?n.cursor:o;e.push({changes:i,cursor:u,shardKey:t.shardKey})}return{failed:a,ok:s,shards:e}},Z=r=>{let e=0,s=0,a=0;for(const t of r){if(t.kind==="err"){s+=1;continue}e+=1;const o=f(t.value);a+=typeof o?.applied=="number"?o.applied:0}return{applied:a,failed:s,ok:e}},ee=r=>{const e=r??{};return typeof e.requests=="number"&&Number.isFinite(e.requests)&&e.requests>=0?e.requests:0},re=r=>{const e=[];let s=0,a=0;for(const t of r){if(t.kind==="err"){a+=1,e.push({requests:0,shardKey:t.shardKey});continue}s+=1,e.push({requests:ee(f(t.value)),shardKey:t.shardKey})}return{failed:a,ok:s,shards:e}},te=r=>{const e=[],s={},a=[];let t=0,o=0,n=0;for(const i of r){if(i.kind==="err"){n+=1,e.push({error:{message:i.message,timedOut:i.timedOut},shardKey:i.shardKey});continue}o+=1;const u=f(i.value),d=u?.inserted??{};for(const[l,y]of Object.entries(d))s[l]=(s[l]??0)+y;const c=u?.errors;Array.isArray(c)&&a.push(...c),t+=u?.conflicts??0,e.push({result:{conflicts:u?.conflicts??0,errors:u?.errors??[],inserted:d},shardKey:i.shardKey})}return{conflicts:t,errors:a,failed:n,inserted:s,ok:o,shards:e}},p=r=>({body:JSON.stringify({args:r.args??{},functionPath:r.functionPath}),headers:{"content-type":"application/json",...r.headers}}),g=async(r,e,s,a)=>{const t=C(r,e),o=new AbortController,n=new Request("https://shard.internal/rpc",{body:s.body,headers:s.headers,method:"POST",signal:o.signal});let i;const u=new Promise(c=>{i=setTimeout(()=>{try{o.abort()}catch{}c({kind:"err",message:`shard "${e}" timed out after ${String(a)}ms`,shardKey:e,timedOut:!0})},a)}),d=(async()=>{try{const c=await t.fetch(n);if(!c.ok)return{kind:"err",message:`shard "${e}" returned ${String(c.status)}`,shardKey:e,timedOut:!1};const l=await c.json();return{kind:"ok",shardKey:e,value:l}}catch(c){const l=c instanceof Error?c.message:String(c);return{kind:"err",message:`shard "${e}" threw: ${l}`,shardKey:e,timedOut:!1}}})();try{return await Promise.race([d,u])}finally{i!==void 0&&clearTimeout(i)}},w=async(r,e,s)=>{if(r.length===0)return[];const a=Array.from({length:r.length});let t=0;const o=async()=>{for(;;){const i=t;t+=1;const u=r[i];if(i>=r.length||u===void 0)return;a[i]=await s(u,i)}},n=Math.min(e,r.length);return await Promise.all(Array.from({length:n},()=>o())),a},P=async(r,e)=>{const s=await Promise.all(e.map(async a=>r.listShardKeys(a)));return[...new Set(s.flat())]},m=async(r,e,s,a,t)=>{const o=p(s);return w(e,a,async n=>g(r,n,o,t))},se=r=>{const e={};for(const s of Object.keys(r).toSorted(b))e[s]=r[s]??null;return JSON.stringify(e)},ae=r=>r.flatMap(e=>Array.isArray(e)?e:[]),oe=(r,e,s)=>{switch(s){case"max":return Math.max(r,e);case"min":return Math.min(r,e);case"sum":return r+e;default:return r}},ne=(r,e,s)=>{if(e===null||typeof e!="object")return;const a=e.key??{},t=e.value??null,o=se(a),n=r.get(o);if(!n){r.set(o,{key:a,value:t});return}if(n.value===null){n.value=t;return}t!==null&&(n.value=oe(n.value,t,s))},ie=(r,e)=>{const s=new Map;for(const a of r)if(Array.isArray(a))for(const t of a)ne(s,t,e);return[...s.values()]},N=(r,e)=>{let s=null;for(const a of r)typeof a=="number"&&Number.isFinite(a)&&(s=s===null?a:e(s,a));return s},ue=r=>{let e=0;for(const s of r)typeof s=="number"&&Number.isFinite(s)&&(e+=s);return e},ce=r=>{let e=0,s=0;for(const a of r){if(a===null||typeof a!="object")continue;const t=a;typeof t.before=="number"&&Number.isFinite(t.before)&&(e+=t.before),typeof t.total=="number"&&Number.isFinite(t.total)&&(s+=t.total)}return{position:e+1,total:s}},de=(r,e)=>{const s=[];for(const t of r)if(Array.isArray(t))for(const o of t){if(o===null||typeof o!="object")continue;const n=o[e.by],i=typeof n=="number"&&Number.isFinite(n)?n:Number.NEGATIVE_INFINITY;s.push({row:o,score:i})}const a=e.direction??"desc";return s.sort((t,o)=>a==="asc"?b(t.score,o.score):b(o.score,t.score)),s.slice(0,e.k).map(t=>t.row)},he=(r,e)=>{switch(e.kind){case"concat":return ae(r);case"first":return r[0];case"groupBy":return ie(r,e.op??"sum");case"max":return N(r,Math.max);case"min":return N(r,Math.min);case"rank":return ce(r);case"sum":return ue(r);case"topK":return de(r,e);default:return r}},ge=r=>{const e=r.maxConcurrency??B,s=r.perShardTimeoutMs??F;if(e<1)throw new A("maxConcurrency must be >= 1",{code:"BAD_REQUEST",status:400});return{async fanOut(a,t){const o=await r.registry.listShardKeys(t.fanOut.table),n=await m(a,o,t,e,s),i=[],u=[];for(const d of n)d.kind==="ok"?i.push(d.value):u.push({message:d.message,shardKey:d.shardKey,timedOut:d.timedOut});return{data:he(i,t.fanOut.merge),errors:u,failed:u.length,ok:i.length}},async orchestrateExport(a,t){const o=await P(r.registry,t.tables),n={args:{...t.args,tables:[...t.tables]},functionPath:"__lunora_admin__:exportShard",headers:t.headers},i=await m(a,o,n,e,s);return W(i)},async orchestrateCdcSync(a,t){const o=await P(r.registry,t.tables),n=t.cursors??{},i=await w(o,e,async u=>{const d=n[u]??0;return{outcome:await g(a,u,p({args:{limit:t.limit,sinceSeq:d},functionPath:"__lunora_admin__:cdcSync",headers:t.headers}),s),sinceSeq:d}});return X(i)},async orchestrateImport(a,t){const{batches:o}=t,n=await w(o,e,async i=>g(a,i.shardKey,p({args:{rows:[...i.rows],startLine:i.startLine??1},functionPath:"__lunora_admin__:importShard",headers:t.headers}),s));return te(n)},async orchestrateApplyCdc(a,t){const{batches:o}=t,n=await w(o,e,async i=>g(a,i.shardKey,p({args:{changes:[...i.changes]},functionPath:"__lunora_admin__:applyCdc",headers:t.headers}),s));return Z(n)},async orchestrateMigration(a,t){const o=await r.registry.listShardKeys(t.table),n=await m(a,o,t,e,s);return R(n)},async orchestrateRank(a,t){const o=await r.registry.listShardKeys(t.table),n={args:{index:t.index,partitionKey:t.partitionKey,rowId:t.rowId,sortValues:[...t.sortValues],table:t.table},functionPath:"__lunora_admin__:rankBefore",headers:t.headers},i=await m(a,o,n,e,s);return $(i)},async orchestrateRankPage(a,t){const o=await r.registry.listShardKeys(t.table),n=Math.max(1,Math.min(1e3,Math.floor(t.take??100))),i=t.directions??[],u=t.cursor?U(t.cursor):{perShard:{}},d=await w(o,e,async h=>{const x=u.perShard[h],_={index:t.index,table:t.table,take:n};t.partitionKey!==void 0&&(_.partitionKey=t.partitionKey),x!==void 0&&(_.after=x);const K=await g(a,h,p({args:_,functionPath:"__lunora_admin__:rankPage",headers:t.headers}),s);if(K.kind==="err")return{error:{message:K.message,timedOut:K.timedOut},shardKey:h};const v=G(f(K.value));return{directions:v.directions,hasMore:v.hasMore,rows:v.rows,shardKey:h}}),c=[];let l=0,y=0,k;for(const h of d){if(h.error){y+=1;continue}l+=1,k===void 0&&h.directions&&h.directions.length>0&&(k=h.directions),c.push({hasMore:h.hasMore??!1,head:0,rows:h.rows??[],shardKey:h.shardKey})}const S=H(c,n,k??i,u.perShard);return{continueCursor:S.nextCursor,failed:y,isDone:S.isDone,ok:l,page:S.page,partial:y>0,shards:d}},async orchestrateShardTraffic(a,t){const o=await r.registry.listShardKeys(t.table),n={functionPath:"__lunora_admin__:getMetrics",headers:t.headers},i=await m(a,o,n,e,s);return re(i)},registry:r.registry}};export{ge as createQueryCoordinator,me as createStaticShardRegistry,pe as mergeStrategyForAggregate};
1
+ import{o as T,a as q}from"./base64-DPPVK6s_.mjs";import{LunoraError as A}from"./LunoraError-ByasbDmd.mjs";import{resolveShard as C}from"./applyJurisdiction-DX_lQ6fY.mjs";const me=r=>({listShardKeys(e){return r[e]??[]}}),pe=r=>{if(r.kind==="count")return{kind:"sum"};if(r.kind==="scalar"){if(r.op==="count"||r.op==="sum")return{kind:"sum"};if(r.op==="max")return{kind:"max"};if(r.op==="min")return{kind:"min"};throw new A('aggregate({ op: "avg" }) is not supported across shards in v1 — fan out sum + count separately',{code:"BAD_REQUEST",status:400})}const e=r.agg?.op??"count";if(e==="count"||e==="sum")return{kind:"groupBy",op:"sum"};if(e==="max")return{kind:"groupBy",op:"max"};if(e==="min")return{kind:"groupBy",op:"min"};throw new A('groupBy({ agg: { op: "avg" } }) is not supported across shards in v1 — fan out sum + count separately',{code:"BAD_REQUEST",status:400})},B=16,F=5e3,f=r=>r!==null&&typeof r=="object"&&"result"in r?r.result:r,I=r=>{const e=r??{};return{changed:typeof e.changed=="number"?e.changed:0,processed:typeof e.processed=="number"?e.processed:0,status:typeof e.status=="string"?e.status:void 0}},D=(r,e)=>r?"failed":e?"in_progress":"completed",R=r=>{const e=[];let s=0,a=0,t=0,o=0,n=!1,i=!1;for(const u of r){if(u.kind==="err"){a+=1,e.push({error:{message:u.message,timedOut:u.timedOut},shardKey:u.shardKey});continue}s+=1;const d=f(u.value),c=I(d);t+=c.changed,o+=c.processed,n||=c.status==="in_progress",i||=c.status==="failed",e.push({result:d,shardKey:u.shardKey})}return{changed:t,failed:a,ok:s,processed:o,shards:e,status:D(i,n||a>0)}},V=r=>{const e=r??{};return{before:typeof e.before=="number"&&Number.isFinite(e.before)?e.before:0,total:typeof e.total=="number"&&Number.isFinite(e.total)?e.total:0}},$=r=>{const e=[];let s=0,a=0,t=0,o=0;for(const n of r){if(n.kind==="err"){a+=1,e.push({error:{message:n.message,timedOut:n.timedOut},shardKey:n.shardKey});continue}s+=1;const i=V(f(n.value));t+=i.before,o+=i.total,e.push({result:i,shardKey:n.shardKey})}return{failed:a,ok:s,partial:a>0,position:t+1,shards:e,total:o}},j=0,E=1,J=2,b=(r,e)=>r<e?-1:r>e?1:0,M=r=>r==null?j:typeof r=="number"?E:J,O=(r,e)=>{const s=M(r),a=M(e);return s!==a?s<a?-1:1:s===j?0:s===E?b(r,e):b(String(r),String(e))},Q=(r,e,s)=>{const a=O(r.partitionKey,e.partitionKey);if(a!==0)return a;const t=Math.max(r.sortValues.length,e.sortValues.length);for(let o=0;o<t;o+=1){const n=O(r.sortValues[o],e.sortValues[o]);if(n!==0)return s[o]==="desc"?-n:n}return O(r.rowId,e.rowId)},L=r=>q(new TextEncoder().encode(JSON.stringify(r))),U=r=>{try{const e=JSON.parse(new TextDecoder().decode(T(r)));if(e!==null&&typeof e=="object"&&"perShard"in e){const{perShard:s}=e;if(s!==null&&typeof s=="object")return{perShard:s}}}catch{}return{perShard:{}}},G=r=>{const e=r??{},s=Array.isArray(e.rows)?e.rows:[];return{directions:Array.isArray(e.directions)?e.directions:[],hasMore:e.hasMore===!0,rows:s}},Y=(r,e)=>{let s;for(const a of r){const t=a.rows[a.head];t!==void 0&&(s===void 0||Q(t.key,s.row.key,e)<0)&&(s={row:t,slice:a})}return s},z=(r,e)=>{let s=!1;const a=new Set;for(const o of r)a.add(o.shardKey),(o.head<o.rows.length||o.hasMore)&&(s=!0);const t={...e};for(const o of Object.keys(e))a.has(o)||(s=!0);return s?L({perShard:t}):null},H=(r,e,s,a)=>{const t=[],o={...a};for(;t.length<e;){const i=Y(r,s);if(i===void 0)break;t.push(i.row.doc),o[i.slice.shardKey]=i.row.key,i.slice.head+=1}const n=z(r,o);return{isDone:n===null,nextCursor:n,page:t}},W=r=>{const e=[];let s=0,a=0;for(const t of r){if(t.kind==="err"){a+=1,e.push({error:{message:t.message,timedOut:t.timedOut},shardKey:t.shardKey});continue}s+=1;const o=f(t.value),n=Array.isArray(o?.rows)?o.rows:[];e.push({rows:n,shardKey:t.shardKey})}return{failed:a,ok:s,shards:e}},X=r=>{const e=[];let s=0,a=0;for(const{outcome:t,sinceSeq:o}of r){if(t.kind==="err"){a+=1,e.push({cursor:o,error:{message:t.message,timedOut:t.timedOut},shardKey:t.shardKey});continue}s+=1;const n=f(t.value),i=Array.isArray(n?.changes)?n.changes:[],u=typeof n?.cursor=="number"?n.cursor:o;e.push({changes:i,cursor:u,shardKey:t.shardKey})}return{failed:a,ok:s,shards:e}},Z=r=>{let e=0,s=0,a=0;for(const t of r){if(t.kind==="err"){s+=1;continue}e+=1;const o=f(t.value);a+=typeof o?.applied=="number"?o.applied:0}return{applied:a,failed:s,ok:e}},ee=r=>{const e=r??{};return typeof e.requests=="number"&&Number.isFinite(e.requests)&&e.requests>=0?e.requests:0},re=r=>{const e=[];let s=0,a=0;for(const t of r){if(t.kind==="err"){a+=1,e.push({requests:0,shardKey:t.shardKey});continue}s+=1,e.push({requests:ee(f(t.value)),shardKey:t.shardKey})}return{failed:a,ok:s,shards:e}},te=r=>{const e=[],s={},a=[];let t=0,o=0,n=0;for(const i of r){if(i.kind==="err"){n+=1,e.push({error:{message:i.message,timedOut:i.timedOut},shardKey:i.shardKey});continue}o+=1;const u=f(i.value),d=u?.inserted??{};for(const[l,y]of Object.entries(d))s[l]=(s[l]??0)+y;const c=u?.errors;Array.isArray(c)&&a.push(...c),t+=u?.conflicts??0,e.push({result:{conflicts:u?.conflicts??0,errors:u?.errors??[],inserted:d},shardKey:i.shardKey})}return{conflicts:t,errors:a,failed:n,inserted:s,ok:o,shards:e}},p=r=>({body:JSON.stringify({args:r.args??{},functionPath:r.functionPath}),headers:{"content-type":"application/json",...r.headers}}),g=async(r,e,s,a)=>{const t=C(r,e),o=new AbortController,n=new Request("https://shard.internal/rpc",{body:s.body,headers:s.headers,method:"POST",signal:o.signal});let i;const u=new Promise(c=>{i=setTimeout(()=>{try{o.abort()}catch{}c({kind:"err",message:`shard "${e}" timed out after ${String(a)}ms`,shardKey:e,timedOut:!0})},a)}),d=(async()=>{try{const c=await t.fetch(n);if(!c.ok)return{kind:"err",message:`shard "${e}" returned ${String(c.status)}`,shardKey:e,timedOut:!1};const l=await c.json();return{kind:"ok",shardKey:e,value:l}}catch(c){const l=c instanceof Error?c.message:String(c);return{kind:"err",message:`shard "${e}" threw: ${l}`,shardKey:e,timedOut:!1}}})();try{return await Promise.race([d,u])}finally{i!==void 0&&clearTimeout(i)}},w=async(r,e,s)=>{if(r.length===0)return[];const a=Array.from({length:r.length});let t=0;const o=async()=>{for(;;){const i=t;t+=1;const u=r[i];if(i>=r.length||u===void 0)return;a[i]=await s(u,i)}},n=Math.min(e,r.length);return await Promise.all(Array.from({length:n},()=>o())),a},P=async(r,e)=>{const s=await Promise.all(e.map(async a=>r.listShardKeys(a)));return[...new Set(s.flat())]},m=async(r,e,s,a,t)=>{const o=p(s);return w(e,a,async n=>g(r,n,o,t))},se=r=>{const e={};for(const s of Object.keys(r).toSorted(b))e[s]=r[s]??null;return JSON.stringify(e)},ae=r=>r.flatMap(e=>Array.isArray(e)?e:[]),oe=(r,e,s)=>{switch(s){case"max":return Math.max(r,e);case"min":return Math.min(r,e);case"sum":return r+e;default:return r}},ne=(r,e,s)=>{if(e===null||typeof e!="object")return;const a=e.key??{},t=e.value??null,o=se(a),n=r.get(o);if(!n){r.set(o,{key:a,value:t});return}if(n.value===null){n.value=t;return}t!==null&&(n.value=oe(n.value,t,s))},ie=(r,e)=>{const s=new Map;for(const a of r)if(Array.isArray(a))for(const t of a)ne(s,t,e);return[...s.values()]},N=(r,e)=>{let s=null;for(const a of r)typeof a=="number"&&Number.isFinite(a)&&(s=s===null?a:e(s,a));return s},ue=r=>{let e=0;for(const s of r)typeof s=="number"&&Number.isFinite(s)&&(e+=s);return e},ce=r=>{let e=0,s=0;for(const a of r){if(a===null||typeof a!="object")continue;const t=a;typeof t.before=="number"&&Number.isFinite(t.before)&&(e+=t.before),typeof t.total=="number"&&Number.isFinite(t.total)&&(s+=t.total)}return{position:e+1,total:s}},de=(r,e)=>{const s=[];for(const t of r)if(Array.isArray(t))for(const o of t){if(o===null||typeof o!="object")continue;const n=o[e.by],i=typeof n=="number"&&Number.isFinite(n)?n:Number.NEGATIVE_INFINITY;s.push({row:o,score:i})}const a=e.direction??"desc";return s.sort((t,o)=>a==="asc"?b(t.score,o.score):b(o.score,t.score)),s.slice(0,e.k).map(t=>t.row)},he=(r,e)=>{switch(e.kind){case"concat":return ae(r);case"first":return r[0];case"groupBy":return ie(r,e.op??"sum");case"max":return N(r,Math.max);case"min":return N(r,Math.min);case"rank":return ce(r);case"sum":return ue(r);case"topK":return de(r,e);default:return r}},ge=r=>{const e=r.maxConcurrency??B,s=r.perShardTimeoutMs??F;if(e<1)throw new A("maxConcurrency must be >= 1",{code:"BAD_REQUEST",status:400});return{async fanOut(a,t){const o=await r.registry.listShardKeys(t.fanOut.table),n=await m(a,o,t,e,s),i=[],u=[];for(const d of n)d.kind==="ok"?i.push(d.value):u.push({message:d.message,shardKey:d.shardKey,timedOut:d.timedOut});return{data:he(i,t.fanOut.merge),errors:u,failed:u.length,ok:i.length}},async orchestrateExport(a,t){const o=await P(r.registry,t.tables),n={args:{...t.args,tables:[...t.tables]},functionPath:"__lunora_admin__:exportShard",headers:t.headers},i=await m(a,o,n,e,s);return W(i)},async orchestrateCdcSync(a,t){const o=await P(r.registry,t.tables),n=t.cursors??{},i=await w(o,e,async u=>{const d=n[u]??0;return{outcome:await g(a,u,p({args:{limit:t.limit,sinceSeq:d},functionPath:"__lunora_admin__:cdcSync",headers:t.headers}),s),sinceSeq:d}});return X(i)},async orchestrateImport(a,t){const{batches:o}=t,n=await w(o,e,async i=>g(a,i.shardKey,p({args:{rows:[...i.rows],startLine:i.startLine??1},functionPath:"__lunora_admin__:importShard",headers:t.headers}),s));return te(n)},async orchestrateApplyCdc(a,t){const{batches:o}=t,n=await w(o,e,async i=>g(a,i.shardKey,p({args:{changes:[...i.changes]},functionPath:"__lunora_admin__:applyCdc",headers:t.headers}),s));return Z(n)},async orchestrateMigration(a,t){const o=await r.registry.listShardKeys(t.table),n=await m(a,o,t,e,s);return R(n)},async orchestrateRank(a,t){const o=await r.registry.listShardKeys(t.table),n={args:{index:t.index,partitionKey:t.partitionKey,rowId:t.rowId,sortValues:[...t.sortValues],table:t.table},functionPath:"__lunora_admin__:rankBefore",headers:t.headers},i=await m(a,o,n,e,s);return $(i)},async orchestrateRankPage(a,t){const o=await r.registry.listShardKeys(t.table),n=Math.max(1,Math.min(1e3,Math.floor(t.take??100))),i=t.directions??[],u=t.cursor?U(t.cursor):{perShard:{}},d=await w(o,e,async h=>{const x=u.perShard[h],_={index:t.index,table:t.table,take:n};t.partitionKey!==void 0&&(_.partitionKey=t.partitionKey),x!==void 0&&(_.after=x);const K=await g(a,h,p({args:_,functionPath:"__lunora_admin__:rankPage",headers:t.headers}),s);if(K.kind==="err")return{error:{message:K.message,timedOut:K.timedOut},shardKey:h};const v=G(f(K.value));return{directions:v.directions,hasMore:v.hasMore,rows:v.rows,shardKey:h}}),c=[];let l=0,y=0,k;for(const h of d){if(h.error){y+=1;continue}l+=1,k===void 0&&h.directions&&h.directions.length>0&&(k=h.directions),c.push({hasMore:h.hasMore??!1,head:0,rows:h.rows??[],shardKey:h.shardKey})}const S=H(c,n,k??i,u.perShard);return{continueCursor:S.nextCursor,failed:y,isDone:S.isDone,ok:l,page:S.page,partial:y>0,shards:d}},async orchestrateShardTraffic(a,t){const o=await r.registry.listShardKeys(t.table),n={functionPath:"__lunora_admin__:getMetrics",headers:t.headers},i=await m(a,o,n,e,s);return re(i)},registry:r.registry}};export{ge as createQueryCoordinator,me as createStaticShardRegistry,pe as mergeStrategyForAggregate};
@@ -1 +1 @@
1
- import{LunoraError as b}from"@lunora/errors";import{f as j,u as E}from"./identity-header-pdXOyDU4.mjs";import{a as w,o as O}from"./base64-DPPVK6s_.mjs";import{applyJurisdiction as N,resolveShard as R}from"./applyJurisdiction-Dsm_m5zW.mjs";const i="$lunora.wire$",m=64,v=1024,g="__proto__",S={BigInt64Array,BigUint64Array,Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array},$={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError},I=r=>{if(r===null||typeof r!="object")return!1;const t=Object.getPrototypeOf(r);return t===null||t===Object.prototype},f=(r,t=0)=>{if(t>m)throw new RangeError(`wire-codec: value nesting exceeds the ${m}-level limit`);if(r===void 0)return[i,"undefined"];if(r===null)return null;const l=typeof r;if(l==="bigint")return[i,"bigint",r.toString()];if(l==="number"){const e=r;return Number.isNaN(e)?[i,"nan"]:e===1/0?[i,"inf"]:e===-1/0?[i,"-inf"]:e}if(l!=="object")return r;if(r instanceof Date)return[i,"date",f(r.getTime(),t+1)];if(r instanceof Error){const e=r,o={};for(const s of Object.keys(e))e[s]!==void 0&&(o[s]=f(e[s],t+1));const n=[i,"error",e.name,e.message,o];return e.cause!==void 0&&n.push(f(e.cause,t+1)),n}if(r instanceof URL)return[i,"url",r.href];if(r instanceof Map)return[i,"map",[...r.entries()].map(([e,o])=>[f(e,t+1),f(o,t+1)])];if(r instanceof Set)return[i,"set",[...r].map(e=>f(e,t+1))];if(r instanceof ArrayBuffer)return[i,"bytes",w(new Uint8Array(r)),"ArrayBuffer"];if(ArrayBuffer.isView(r)){const e=r,o=e.constructor.name,n=new Uint8Array(e.buffer,e.byteOffset,e.byteLength);return o==="Uint8Array"?[i,"bytes",w(n)]:[i,"bytes",w(n),o]}if(Array.isArray(r)){const e=r.map(o=>f(o,t+1));return e.length>0&&e[0]===i?[i,"arr",e]:e}if(!I(r)){const e=r.constructor?.name??"value";throw new TypeError(`wire-codec: cannot encode a ${e} over the Lunora wire — only plain objects, arrays, and the supported built-ins (Date, Error, URL, Map, Set, ArrayBuffer/typed arrays, bigint) round-trip`)}const d=r,a={};for(const e of Object.keys(d)){const o=d[e];if(o===void 0)continue;const n=f(o,t+1);e===g?Object.defineProperty(a,e,{configurable:!0,enumerable:!0,value:n,writable:!0}):a[e]=n}return a},u=(r,t=0)=>{if(t>m)throw new RangeError(`wire-codec: value nesting exceeds the ${m}-level limit`);if(r===null||typeof r!="object")return r;if(Array.isArray(r)){if(r[0]===i)switch(r[1]){case"-inf":return-1/0;case"arr":return r[2].map(a=>u(a,t+1));case"bigint":{const a=r[2];if(typeof a!="string"||a.length>v||!/^-?\d+$/.test(a))throw new RangeError(`wire-codec: invalid or over-long bigint (max ${v} digits)`);return BigInt(a)}case"date":return new Date(u(r[2],t+1));case"map":return new Map(r[2].map(([a,e])=>[u(a,t+1),u(e,t+1)]));case"set":return new Set(r[2].map(a=>u(a,t+1)));case"url":return new URL(r[2]);case"error":{const a=r[2],e=r[3],o=(Object.hasOwn($,a)?$[a]:void 0)??Error,n=new o(e);n.name!==a&&Object.defineProperty(n,"name",{configurable:!0,value:a,writable:!0});const s=u(r[4],t+1);for(const c of Object.keys(s))c===g?Object.defineProperty(n,c,{configurable:!0,enumerable:!0,value:s[c],writable:!0}):n[c]=s[c];return r.length>5&&Object.defineProperty(n,"cause",{configurable:!0,value:u(r[5],t+1),writable:!0}),n}case"bytes":{const a=O(r[2]),e=r[3]??"Uint8Array";if(e==="ArrayBuffer")return a.buffer.byteLength===a.byteLength?a.buffer:a.slice().buffer;const o=Object.hasOwn(S,e)?S[e]:void 0;return o?new o(a.slice().buffer):a}case"inf":return 1/0;case"nan":return Number.NaN;case"undefined":return;default:return r.map(a=>u(a,t+1))}return r.map(a=>u(a,t+1))}const l=r,d={};for(const a of Object.keys(l)){const e=u(l[a],t+1);a===g?Object.defineProperty(d,a,{configurable:!0,enumerable:!0,value:e,writable:!0}):d[a]=e}return d},U=r=>{if(typeof r=="string")return r;const t=r?.__lunoraRef;if(typeof t!="string"||t.length===0)throw new b("INTERNAL","createShardClient: expected a generated function reference (api.*/internal.*) or a 'namespace:fn' string");return t},x=r=>{const t=new b(r.code,r.message);return r.data!==void 0&&(t.data=u(r.data)),t},L=(r,t={})=>{const l=N(r,t.jurisdiction),d=t.system??!0,a=e=>L(r,{...t,...e});return{as:e=>a({as:e}),asSystem:()=>a({as:void 0}),call:async(e,o,n)=>{const s=U(e),c=n?.shardKey??t.shardKey;if(c===void 0||c.length===0)throw new b("INTERNAL",`createShardClient: no shard key for "${s}" — pass one to createShardClient({ shardKey }), .forShard(key), or the call's options`);const p={"content-type":"application/json"};d&&(p["x-lunora-system"]="1"),t.as&&(p["x-lunora-userid"]=j(t.as.userId),t.as.claims&&(p["x-lunora-identity"]=E(t.as.claims))),n?.mutationId!==void 0&&n.mutationId.length>0&&(p["x-lunora-mutation-id"]=n.mutationId);const y=await R(l,c).fetch(new Request("https://shard.internal/rpc",{body:JSON.stringify({args:f(o??{}),functionPath:s}),headers:p,method:"POST"})),A=y.statusText?` ${y.statusText}`:"";let h;try{h=await y.json()}catch{throw new b("INTERNAL",`createShardClient: shard response for "${s}" was not JSON (status ${String(y.status)}${A})`)}if("error"in h)throw x(h.error);if(!y.ok)throw new b("INTERNAL",`createShardClient: shard call "${s}" failed (status ${String(y.status)}${A})`);return u(h.result)},forShard:e=>a({shardKey:e})}};export{L as createShardClient};
1
+ import{LunoraError as b}from"@lunora/errors";import{f as j,u as E}from"./identity-header-pdXOyDU4.mjs";import{a as w,o as O}from"./base64-DPPVK6s_.mjs";import{applyJurisdiction as N,resolveShard as R}from"./applyJurisdiction-DX_lQ6fY.mjs";const i="$lunora.wire$",m=64,v=1024,g="__proto__",S={BigInt64Array,BigUint64Array,Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array},$={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError},I=r=>{if(r===null||typeof r!="object")return!1;const t=Object.getPrototypeOf(r);return t===null||t===Object.prototype},f=(r,t=0)=>{if(t>m)throw new RangeError(`wire-codec: value nesting exceeds the ${m}-level limit`);if(r===void 0)return[i,"undefined"];if(r===null)return null;const l=typeof r;if(l==="bigint")return[i,"bigint",r.toString()];if(l==="number"){const e=r;return Number.isNaN(e)?[i,"nan"]:e===1/0?[i,"inf"]:e===-1/0?[i,"-inf"]:e}if(l!=="object")return r;if(r instanceof Date)return[i,"date",f(r.getTime(),t+1)];if(r instanceof Error){const e=r,o={};for(const s of Object.keys(e))e[s]!==void 0&&(o[s]=f(e[s],t+1));const n=[i,"error",e.name,e.message,o];return e.cause!==void 0&&n.push(f(e.cause,t+1)),n}if(r instanceof URL)return[i,"url",r.href];if(r instanceof Map)return[i,"map",[...r.entries()].map(([e,o])=>[f(e,t+1),f(o,t+1)])];if(r instanceof Set)return[i,"set",[...r].map(e=>f(e,t+1))];if(r instanceof ArrayBuffer)return[i,"bytes",w(new Uint8Array(r)),"ArrayBuffer"];if(ArrayBuffer.isView(r)){const e=r,o=e.constructor.name,n=new Uint8Array(e.buffer,e.byteOffset,e.byteLength);return o==="Uint8Array"?[i,"bytes",w(n)]:[i,"bytes",w(n),o]}if(Array.isArray(r)){const e=r.map(o=>f(o,t+1));return e.length>0&&e[0]===i?[i,"arr",e]:e}if(!I(r)){const e=r.constructor?.name??"value";throw new TypeError(`wire-codec: cannot encode a ${e} over the Lunora wire — only plain objects, arrays, and the supported built-ins (Date, Error, URL, Map, Set, ArrayBuffer/typed arrays, bigint) round-trip`)}const d=r,a={};for(const e of Object.keys(d)){const o=d[e];if(o===void 0)continue;const n=f(o,t+1);e===g?Object.defineProperty(a,e,{configurable:!0,enumerable:!0,value:n,writable:!0}):a[e]=n}return a},u=(r,t=0)=>{if(t>m)throw new RangeError(`wire-codec: value nesting exceeds the ${m}-level limit`);if(r===null||typeof r!="object")return r;if(Array.isArray(r)){if(r[0]===i)switch(r[1]){case"-inf":return-1/0;case"arr":return r[2].map(a=>u(a,t+1));case"bigint":{const a=r[2];if(typeof a!="string"||a.length>v||!/^-?\d+$/.test(a))throw new RangeError(`wire-codec: invalid or over-long bigint (max ${v} digits)`);return BigInt(a)}case"date":return new Date(u(r[2],t+1));case"map":return new Map(r[2].map(([a,e])=>[u(a,t+1),u(e,t+1)]));case"set":return new Set(r[2].map(a=>u(a,t+1)));case"url":return new URL(r[2]);case"error":{const a=r[2],e=r[3],o=(Object.hasOwn($,a)?$[a]:void 0)??Error,n=new o(e);n.name!==a&&Object.defineProperty(n,"name",{configurable:!0,value:a,writable:!0});const s=u(r[4],t+1);for(const c of Object.keys(s))c===g?Object.defineProperty(n,c,{configurable:!0,enumerable:!0,value:s[c],writable:!0}):n[c]=s[c];return r.length>5&&Object.defineProperty(n,"cause",{configurable:!0,value:u(r[5],t+1),writable:!0}),n}case"bytes":{const a=O(r[2]),e=r[3]??"Uint8Array";if(e==="ArrayBuffer")return a.buffer.byteLength===a.byteLength?a.buffer:a.slice().buffer;const o=Object.hasOwn(S,e)?S[e]:void 0;return o?new o(a.slice().buffer):a}case"inf":return 1/0;case"nan":return Number.NaN;case"undefined":return;default:return r.map(a=>u(a,t+1))}return r.map(a=>u(a,t+1))}const l=r,d={};for(const a of Object.keys(l)){const e=u(l[a],t+1);a===g?Object.defineProperty(d,a,{configurable:!0,enumerable:!0,value:e,writable:!0}):d[a]=e}return d},U=r=>{if(typeof r=="string")return r;const t=r?.__lunoraRef;if(typeof t!="string"||t.length===0)throw new b("INTERNAL","createShardClient: expected a generated function reference (api.*/internal.*) or a 'namespace:fn' string");return t},x=r=>{const t=new b(r.code,r.message);return r.data!==void 0&&(t.data=u(r.data)),t},L=(r,t={})=>{const l=N(r,t.jurisdiction),d=t.system??!0,a=e=>L(r,{...t,...e});return{as:e=>a({as:e}),asSystem:()=>a({as:void 0}),call:async(e,o,n)=>{const s=U(e),c=n?.shardKey??t.shardKey;if(c===void 0||c.length===0)throw new b("INTERNAL",`createShardClient: no shard key for "${s}" — pass one to createShardClient({ shardKey }), .forShard(key), or the call's options`);const p={"content-type":"application/json"};d&&(p["x-lunora-system"]="1"),t.as&&(p["x-lunora-userid"]=j(t.as.userId),t.as.claims&&(p["x-lunora-identity"]=E(t.as.claims))),n?.mutationId!==void 0&&n.mutationId.length>0&&(p["x-lunora-mutation-id"]=n.mutationId);const y=await R(l,c).fetch(new Request("https://shard.internal/rpc",{body:JSON.stringify({args:f(o??{}),functionPath:s}),headers:p,method:"POST"})),A=y.statusText?` ${y.statusText}`:"";let h;try{h=await y.json()}catch{throw new b("INTERNAL",`createShardClient: shard response for "${s}" was not JSON (status ${String(y.status)}${A})`)}if("error"in h)throw x(h.error);if(!y.ok)throw new b("INTERNAL",`createShardClient: shard call "${s}" failed (status ${String(y.status)}${A})`);return u(h.result)},forShard:e=>a({shardKey:e})}};export{L as createShardClient};
@@ -0,0 +1 @@
1
+ import{LunoraError as m}from"./LunoraError-ByasbDmd.mjs";const y="default-src 'none'; frame-ancestors 'none'; base-uri 'none'; form-action 'none'",O=e=>{const r=["base-uri 'none'","object-src 'none'"];return e==="DENY"?r.push("frame-ancestors 'none'"):e==="SAMEORIGIN"&&r.push("frame-ancestors 'self'"),r.join("; ")},v="accelerometer=(), autoplay=(), camera=(), display-capture=(), geolocation=(), gyroscope=(), magnetometer=(), microphone=(), payment=(), usb=()",d=["Authorization","Content-Type","X-D1-Bookmark","X-Lunora-Client-Id","X-Lunora-Client-Seq","X-Lunora-Min-Seq","X-Lunora-Mutation-Id"],u=["DELETE","GET","HEAD","PATCH","POST","PUT"],b=31536e3,L=new Set(["GET","HEAD","OPTIONS"]),A=e=>{if(e===!1)return;const r=e===void 0||e===!0?{}:e,o=r.maxAge??b,s=r.includeSubDomains??!0;return`max-age=${String(o)}${s?"; includeSubDomains":""}${r.preload?"; preload":""}`},S=(e,r)=>{if(e!==!1)return typeof e=="string"?{htmlValue:e,value:e}:{htmlValue:r,value:y}},R=e=>{if(e===!1)return{coop:void 0,csp:void 0,enabled:!1,frameOptions:void 0,hsts:void 0,permissionsPolicy:void 0,referrerPolicy:void 0};const r=e===void 0||e===!0?{}:e,o=r.frameOptions===!1?void 0:r.frameOptions??"SAMEORIGIN";return{coop:"same-origin",csp:S(r.csp,O(o)),enabled:!0,frameOptions:o,hsts:A(r.hsts),permissionsPolicy:r.permissionsPolicy===!1?void 0:r.permissionsPolicy??v,referrerPolicy:r.referrerPolicy===!1?void 0:r.referrerPolicy??"strict-origin-when-cross-origin"}},C=e=>{const r={allowCredentials:!1,allowedHeaders:d,allowedMethods:u,enabled:!1,isAllowed:()=>!1,isExplicitlyAllowed:()=>!1,maxAge:600};if(e===void 0||e===!1)return r;const o=e.allowCredentials??!1,s=e.allowedOrigins;let t,i;if(typeof s=="function")t=s,i=s,console.warn(`@lunora/runtime: security.cors uses a custom \`allowedOrigins\` predicate. It is trusted by the CSRF and WebSocket origin checks${o?" AND reflects matching origins with credentials (`allowCredentials: true`)":""} — ensure it matches ONLY trusted origins by exact equality; an over-broad predicate (e.g. \`() => true\`, or \`endsWith\`/\`includes\` checks) defeats the allowlist.`);else{const l=s;if(l.includes("*")&&o)throw new m('@lunora/runtime: security.cors cannot combine a wildcard origin ("*") with allowCredentials: true — browsers reject it and it defeats the allowlist.');t=n=>l.includes("*")||l.includes(n),i=n=>l.includes(n)}return{allowCredentials:o,allowedHeaders:e.allowedHeaders??d,allowedMethods:e.allowedMethods??u,enabled:!0,isAllowed:t,isExplicitlyAllowed:i,maxAge:e.maxAge??600}},E=e=>{if(e===!1)return{allowLoopback:!1,enabled:!1,trustedOrigins:[]};const r=e===void 0||e===!0?{}:e;return{allowLoopback:r.allowLoopback??!0,enabled:!0,trustedOrigins:r.trustedOrigins??[]}},x=new Set(["0","disabled","false","no","off"]),k=new Set(["1","enabled","on","true","yes"]),f=e=>typeof e=="string"&&x.has(e.trim().toLowerCase()),I=e=>typeof e=="string"&&k.has(e.trim().toLowerCase()),P=e=>{const r=e?.LUNORA_ALLOWED_ORIGINS;if(typeof r!="string")return;const o=r.split(",").map(s=>s.trim()).filter(s=>s.length>0);return o.length===0?void 0:{allowCredentials:!o.includes("*")&&I(e?.LUNORA_CORS_ALLOW_CREDENTIALS),allowedOrigins:o}},j=(e,r)=>{const o=e?.headers??(f(r?.LUNORA_SECURITY_HEADERS)?!1:void 0),s=e?.csrf??(f(r?.LUNORA_SECURITY_CSRF)?!1:void 0),t=e?.cors??P(r);return{cors:C(t),csrf:E(s),headers:R(o)}},N=new Set(["127.0.0.1","::1","[::1]","localhost"]),p=e=>{try{return N.has(new URL(e).hostname)}catch{return!1}},c=e=>{if(e)try{return new URL(e).origin}catch{return}},h=(e,r,o)=>e===r||o.csrf.trustedOrigins.includes(e)||o.csrf.allowLoopback&&p(r)&&p(e)?!0:o.cors.enabled&&o.cors.isExplicitlyAllowed(e),g=(e,r,o)=>Response.json({error:{code:"FORBIDDEN_ORIGIN",expectedOrigin:o,message:`${e} rejected: Origin ${r===void 0?"was missing":`"${r}"`} is not trusted (this worker serves "${o}"). Add it to \`security.csrf.trustedOrigins\` (or LUNORA_ALLOWED_ORIGINS) if it is yours. Behind a dev proxy this usually means the proxy rewrote the host: keep both ends on loopback, or list the dev-server origin.`,receivedOrigin:r}},{headers:{"content-type":"application/json"},status:403}),M=(e,r)=>{if(!r.csrf.enabled||L.has(e.method)||!e.headers.get("cookie"))return;const o=new URL(e.url).origin,s=c(e.headers.get("origin"))??c(e.headers.get("referer"));if(!(s!==void 0&&h(s,o,r)))return g("cross-origin state-changing request",s,o)},$=(e,r)=>{if(!r.csrf.enabled||!e.headers.get("cookie"))return;const o=new URL(e.url).origin,s=c(e.headers.get("origin"));if(!(s!==void 0&&h(s,o,r)))return g("cross-origin websocket upgrade",s,o)},D=["X-D1-Bookmark","X-Lunora-Shard-Key"],w=(e,r)=>{const o=new Headers;return o.set("access-control-allow-origin",e),o.set("access-control-expose-headers",D.join(", ")),o.append("vary","Origin"),r.allowCredentials&&o.set("access-control-allow-credentials","true"),o},G=(e,r)=>{if(!r.cors.enabled||e.method!=="OPTIONS")return;const o=e.headers.get("origin");if(!o||!e.headers.get("access-control-request-method")||!r.cors.isAllowed(o))return;const s=w(o,r.cors),t=e.headers.get("access-control-request-headers");s.set("access-control-allow-methods",r.cors.allowedMethods.join(", "));let i;if(t===null)i=r.cors.allowedHeaders.join(", ");else{const l=new Set(r.cors.allowedHeaders.map(n=>n.toLowerCase()));i=t.split(",").map(n=>n.trim()).filter(n=>n.length>0&&l.has(n.toLowerCase())).join(", ")}return s.set("access-control-allow-headers",i),s.set("access-control-max-age",String(r.cors.maxAge)),new Response(null,{headers:s,status:204})},T=e=>(e.headers.get("content-type")??"").toLowerCase().includes("text/html"),a=(e,r,o)=>{e.has(r)||e.set(r,o)},U=(e,r,o,s)=>{if(s.hsts!==void 0&&new URL(r.url).protocol==="https:"&&a(e,"strict-transport-security",s.hsts),a(e,"x-content-type-options","nosniff"),s.frameOptions!==void 0&&a(e,"x-frame-options",s.frameOptions),s.referrerPolicy!==void 0&&a(e,"referrer-policy",s.referrerPolicy),s.permissionsPolicy!==void 0&&a(e,"permissions-policy",s.permissionsPolicy),s.coop!==void 0&&a(e,"cross-origin-opener-policy",s.coop),s.csp!==void 0){const t=T(o)?s.csp.htmlValue:s.csp.value;t!==void 0&&a(e,"content-security-policy",t)}},_=(e,r,o)=>{const s=r.headers.get("origin");if(!(!s||!o.isAllowed(s)))for(const[t,i]of w(s,o).entries())t==="vary"?e.append("vary",i):a(e,t,i)},X=(e,r,o)=>{if(e.status===101||e.webSocket)return e;const s=new Headers(e.headers);return o.headers.enabled&&U(s,r,e,o.headers),o.cors.enabled&&_(s,r,o.cors),new Response(e.body,{headers:s,status:e.status,statusText:e.statusText})};export{X as decorateResponse,M as enforceOrigin,$ as enforceWebSocketOrigin,G as handleCorsPreflight,j as resolveSecurity};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/runtime",
3
- "version": "1.0.0-alpha.59",
3
+ "version": "1.0.0-alpha.60",
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.25",
50
- "@lunora/errors": "1.0.0-alpha.18",
51
- "@lunora/platform": "1.0.0-alpha.8"
49
+ "@lunora/bindings": "1.0.0-alpha.27",
50
+ "@lunora/errors": "1.0.0-alpha.20",
51
+ "@lunora/platform": "1.0.0-alpha.9"
52
52
  },
53
53
  "engines": {
54
54
  "node": "^22.15.0 || >=24.11.0"
@@ -1 +0,0 @@
1
- import{resolveShard as u}from"@lunora/platform";const d=new WeakMap,a=o=>typeof o.idFromName=="function",s=o=>{if(!a(o))return o;const e=o,t=d.get(o);if(t!==void 0)return t;const r=typeof e.jurisdiction=="function"?i=>s(e.jurisdiction(i)):void 0,n=typeof e.getByName=="function"?{get:i=>e.get(i),getByName:i=>e.getByName(i),idForName:i=>e.idFromName(i),jurisdiction:r}:{get:i=>e.get(i),idForName:i=>e.idFromName(i),jurisdiction:r};return d.set(o,n),n},m=(o,e)=>{if(e===void 0)return o;if(typeof o.jurisdiction!="function")throw new TypeError(`@lunora/runtime: Durable Object namespace does not support jurisdiction("${e}") — update @cloudflare/workers-types or remove the jurisdiction option`);return o.jurisdiction(e)},p=(o,e)=>u(s(o),e);export{m as applyJurisdiction,p as resolveShard};
@@ -1,6 +0,0 @@
1
- import{isLunoraError as yr,toErrorBody as br}from"@lunora/errors";import{d as At}from"./evict-oldest-C2XU6HBR.mjs";import{NOOP_EXECUTION_CONTEXT as _r}from"./NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{f as Rr,u as Er}from"./identity-header-pdXOyDU4.mjs";import{O as Ae,m as Sr,A as Or,R as Tr,d as Ar,i as kr,s as vr}from"./otlp-resource-B-ByO9qo.mjs";import{h as X,f as be,i as kt,E as Ir,w as vt,e as It,b as Dr}from"./rest-routes-BqldHiaH.mjs";import{LunoraError as i,toErrorResponse as Xe}from"./LunoraError-ByasbDmd.mjs";import{r as x,t as we}from"./method-guard-rzvo19pa.mjs";import{normalizeBackupPrefix as Fe,BACKUP_KEY_PREFIX as Ge,isBackupManifestKey as Pr,backupObjectKeyOfManifest as Dt,backupObjectKey as Ur,backupManifestKey as Nr}from"./BACKUP_KEY_PREFIX-DhFUE3VL.mjs";import{toHex as qr,STORAGE_UPLOAD_MAX_BODY_BYTES as Cr,STORAGE_PATH as $r,buildStorageAdminRoutes as Br}from"./STORAGE_UPLOAD_MAX_BODY_BYTES-K0uZPIUj.mjs";import{runExportTap as xr}from"./createKvCursorStore-C24tEuYk.mjs";import{buildHealthRoutes as jr,durableObjectProbe as Kr,d1Probe as Lr,presenceProbe as Ne}from"./HEALTH_PATH-BuLCcWNS.mjs";import{wrapResolverWithContract as Fr}from"./composeIdentityResolvers-DwE0Jbww.mjs";import{composeIdentityResolvers as rs,routeIdentityResolvers as ns}from"./composeIdentityResolvers-DwE0Jbww.mjs";import{buildLogArchiveAdminRoutes as Gr}from"./LOG_ARCHIVE_PATH-CuHKuDCS.mjs";import{o as Qr,f as Ze,a as ce}from"./observability-DWlkDJJw.mjs";import{resolveShard as ge,applyJurisdiction as et}from"./applyJurisdiction-Dsm_m5zW.mjs";import{resolveSecurity as tt,handleCorsPreflight as Mr,enforceOrigin as zr,decorateResponse as qe,enforceWebSocketOrigin as rt}from"./decorateResponse-DBIWsRSZ.mjs";const Wr=e=>{const t=e??{};if(typeof t.bucket=="function")return t;const r={...t,bucketName:"default"};return r.bucket=()=>r,r},Pt="__lunoraBranch",Jr=e=>typeof e=="object"&&e!==null&&Object.hasOwn(e,Pt),Hr=`may not contain the reserved workflow branch-marker key ("${Pt}")`,Qe=(e,t)=>{const r=Math.max(e.length,t.length);let n=e.length^t.length;for(let o=0;o<r;o+=1){const s=o<e.length?e.charCodeAt(o):0,l=o<t.length?t.charCodeAt(o):0;n|=s^l}return n===0},Me=new TextEncoder,Vr=Array.from({length:32},(e,t)=>t);new RegExp(`[${Vr.map(e=>String.fromCodePoint(e)).join("")}]`,"u");const Yr=e=>{const t=String.fromCodePoint(...e);return btoa(t).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")},Xr=e=>{const t=e.replaceAll("-","+").replaceAll("_","/")+"===".slice((e.length+3)%4),r=atob(t),n=new Uint8Array(r.length);for(let o=0;o<r.length;o+=1)n[o]=r.codePointAt(o)??0;return n},Zr=64,Ce=new Map,Ut=async e=>{const t=Ce.get(e);if(t)return t;At(Ce,Zr);const r=crypto.subtle.importKey("raw",Me.encode(e),{hash:"SHA-256",name:"HMAC"},!1,["sign","verify"]);return Ce.set(e,r),r},Nt=async(e,t)=>{const r=await Ut(e),n=await crypto.subtle.sign("HMAC",r,Me.encode(t));return Yr(new Uint8Array(n))},en=async(e,t,r)=>{const n=await Ut(e);return crypto.subtle.verify("HMAC",n,r,Me.encode(t))},tn="::relay::",rn=(e,t)=>`${e}${tn}${String(t)}`,nn=new Set(["1","enabled","on","true","yes"]),an=new Set(["0","disabled","false","no","off"]),on=(e,t)=>{const r=(e??"").trim().toLowerCase();return nn.has(r)?!0:an.has(r)?!1:t},qt="v1",sn=6e4,cn=async(e,t={})=>{const r=(t.now??Date.now())+(t.ttlMs??sn),n=`${qt}.${String(r)}`,o=await Nt(e,n);return{expiresAtMs:r,token:`${n}.${o}`}},un=async(e,t,r=Date.now())=>{if(e.length===0||t.length===0)return!1;const n=t.split(".");if(n.length!==3)return!1;const[o,s,l]=n;if(o!==qt||l.length===0)return!1;const u=Number(s);if(!Number.isFinite(u)||u<=r)return!1;let f;try{f=Xr(l)}catch{return!1}return en(e,`${o}.${s}`,f)},I="/_lunora/admin/auth",dn={INVITER_REQUIRED:400,ORG_SLUG_INVALID:400,ORG_SLUG_TAKEN:409,PASSWORD_TOO_LONG:400,PASSWORD_TOO_SHORT:400,USER_ALREADY_EXISTS:409,USER_NOT_FOUND:404},P=(e,t)=>{const r=e[t];if(typeof r!="string"||r==="")throw new i(`\`${t}\` is required`,{code:"BAD_REQUEST",status:400});return r},le=(e,t)=>{const r=e(t);if(r===void 0)throw new i(`\`${t}\` query parameter is required`,{code:"BAD_REQUEST",status:400});return r},Ct=e=>{if(typeof e=="string"||Array.isArray(e)&&e.every(t=>typeof t=="string"))return e},te=(e,t)=>typeof e[t]=="string"?e[t]:void 0,$e=(e,t)=>{const r=e[t];return typeof r=="object"&&r!==null&&!Array.isArray(r)?r:void 0},nt=e=>{const t=Ct(e.role);if(t===void 0||typeof t=="string"&&t.trim()==="")throw new i("`role` is required",{code:"BAD_REQUEST",status:400});return t},at=e=>{const t=e.permission;if(typeof t!="object"||t===null||Array.isArray(t))throw new i("`permission` object is required",{code:"BAD_REQUEST",status:400});const r={};for(const[n,o]of Object.entries(t))Array.isArray(o)&&o.every(s=>typeof s=="string")&&(r[n]=o);return r},ln={[`${I}/capabilities`]:{build:()=>({}),http:"GET",method:"capabilities"},[`${I}/users`]:{build:({paging:e,query:t})=>{const r=t("sortDirection");return{...e,filterField:t("filterField"),filterValue:t("filterValue"),search:t("search"),searchField:t("searchField"),sortBy:t("sortBy"),sortDirection:r==="asc"||r==="desc"?r:void 0}},http:"GET",method:"listUsers"},[`${I}/sessions`]:{build:({paging:e,query:t})=>({...e,userId:t("userId")}),http:"GET",method:"listSessions"},[`${I}/accounts`]:{build:({query:e})=>({userId:le(e,"userId")}),http:"GET",method:"listAccounts"},[`${I}/passkeys`]:{build:({query:e})=>({userId:le(e,"userId")}),http:"GET",method:"listPasskeys"},[`${I}/organizations`]:{build:({paging:e})=>({...e}),http:"GET",method:"listOrganizations"},[`${I}/organizations/members`]:{build:({paging:e,query:t})=>({...e,organizationId:le(t,"organizationId")}),http:"GET",method:"listMembers"},[`${I}/organizations/invitations`]:{build:({paging:e,query:t})=>({...e,organizationId:le(t,"organizationId")}),http:"GET",method:"listInvitations"},[`${I}/config`]:{build:()=>({}),http:"GET",method:"config"},[`${I}/organizations/teams`]:{build:({paging:e,query:t})=>({...e,organizationId:le(t,"organizationId")}),http:"GET",method:"listTeams"},[`${I}/organizations/teams/members`]:{build:({paging:e,query:t})=>({...e,teamId:le(t,"teamId")}),http:"GET",method:"listTeamMembers"},[`${I}/organizations/roles`]:{build:({paging:e,query:t})=>({...e,organizationId:le(t,"organizationId")}),http:"GET",method:"listOrgRoles"},[`${I}/users/create`]:{build:({body:e})=>({data:$e(e,"data"),email:P(e,"email"),name:P(e,"name"),password:te(e,"password"),role:Ct(e.role)}),http:"POST",method:"createUser"},[`${I}/users/update`]:{build:({body:e})=>{const{data:t}=e;if(typeof t!="object"||t===null||Array.isArray(t))throw new i("`data` object is required",{code:"BAD_REQUEST",status:400});return{data:t,userId:P(e,"userId")}},http:"POST",method:"updateUser"},[`${I}/users/role`]:{build:({body:e})=>({role:nt(e),userId:P(e,"userId")}),http:"POST",method:"setRole"},[`${I}/users/ban`]:{build:({body:e})=>({expiresInSeconds:typeof e.expiresInSeconds=="number"?e.expiresInSeconds:void 0,reason:te(e,"reason"),userId:P(e,"userId")}),http:"POST",method:"banUser"},[`${I}/users/unban`]:{build:({body:e})=>({userId:P(e,"userId")}),http:"POST",method:"unbanUser"},[`${I}/users/password`]:{build:({body:e})=>({newPassword:P(e,"newPassword"),userId:P(e,"userId")}),http:"POST",method:"setUserPassword",returns:"void"},[`${I}/users/remove`]:{build:({body:e})=>({userId:P(e,"userId")}),http:"POST",method:"removeUser",returns:"void"},[`${I}/users/impersonate`]:{build:({body:e})=>({userId:P(e,"userId")}),http:"POST",method:"impersonateUser"},[`${I}/sessions/revoke`]:{build:({body:e})=>({sessionId:P(e,"sessionId")}),http:"POST",method:"revokeUserSession",returns:"void"},[`${I}/sessions/revoke-all`]:{build:({body:e})=>({userId:P(e,"userId")}),http:"POST",method:"revokeUserSessions",returns:"void"},[`${I}/accounts/unlink`]:{build:({body:e})=>({accountId:P(e,"accountId"),userId:P(e,"userId")}),http:"POST",method:"unlinkAccount",returns:"void"},[`${I}/two-factor/disable`]:{build:({body:e})=>({userId:P(e,"userId")}),http:"POST",method:"disableTwoFactor",returns:"void"},[`${I}/passkeys/delete`]:{build:({body:e})=>({passkeyId:P(e,"passkeyId")}),http:"POST",method:"deletePasskey",returns:"void"},[`${I}/organizations/members/remove`]:{build:({body:e})=>({memberId:P(e,"memberId")}),http:"POST",method:"removeMember",returns:"void"},[`${I}/organizations/invitations/cancel`]:{build:({body:e})=>({invitationId:P(e,"invitationId")}),http:"POST",method:"cancelInvitation",returns:"void"},[`${I}/organizations/create`]:{build:({body:e})=>({logo:te(e,"logo"),metadata:$e(e,"metadata"),name:P(e,"name"),ownerId:te(e,"ownerId"),slug:te(e,"slug")}),http:"POST",method:"createOrganization"},[`${I}/organizations/update`]:{build:({body:e})=>({logo:te(e,"logo"),metadata:$e(e,"metadata"),name:te(e,"name"),organizationId:P(e,"organizationId"),slug:te(e,"slug")}),http:"POST",method:"updateOrganization"},[`${I}/organizations/remove`]:{build:({body:e})=>({organizationId:P(e,"organizationId")}),http:"POST",method:"deleteOrganization",returns:"void"},[`${I}/organizations/members/add`]:{build:({body:e})=>({organizationId:P(e,"organizationId"),role:te(e,"role"),userId:P(e,"userId")}),http:"POST",method:"addMember"},[`${I}/organizations/members/invite`]:{build:({body:e})=>({email:P(e,"email"),inviterId:te(e,"inviterId"),organizationId:P(e,"organizationId"),role:te(e,"role")}),http:"POST",method:"inviteMember"},[`${I}/organizations/members/role`]:{build:({body:e})=>({memberId:P(e,"memberId"),role:nt(e)}),http:"POST",method:"updateMemberRole"},[`${I}/organizations/teams/create`]:{build:({body:e})=>({name:P(e,"name"),organizationId:P(e,"organizationId")}),http:"POST",method:"createTeam"},[`${I}/organizations/teams/update`]:{build:({body:e})=>({name:P(e,"name"),teamId:P(e,"teamId")}),http:"POST",method:"updateTeam"},[`${I}/organizations/teams/remove`]:{build:({body:e})=>({teamId:P(e,"teamId")}),http:"POST",method:"removeTeam",returns:"void"},[`${I}/organizations/teams/members/add`]:{build:({body:e})=>({teamId:P(e,"teamId"),userId:P(e,"userId")}),http:"POST",method:"addTeamMember"},[`${I}/organizations/teams/members/remove`]:{build:({body:e})=>({teamMemberId:P(e,"teamMemberId")}),http:"POST",method:"removeTeamMember",returns:"void"},[`${I}/organizations/roles/create`]:{build:({body:e})=>({organizationId:P(e,"organizationId"),permission:at(e),role:P(e,"role")}),http:"POST",method:"createOrgRole"},[`${I}/organizations/roles/update`]:{build:({body:e})=>({permission:at(e),roleId:P(e,"roleId")}),http:"POST",method:"updateOrgRole"},[`${I}/organizations/roles/remove`]:{build:({body:e})=>({roleId:P(e,"roleId")}),http:"POST",method:"deleteOrgRole",returns:"void"}},hn=e=>{const t=async o=>{try{return await o()}catch(s){if(s instanceof i)throw s;const l=s,u=typeof l.code=="string"?l.code:"AUTH_ADMIN_ERROR";throw console.error("[lunora] auth admin operation failed:",s),new i("auth admin operation failed",{code:u,status:dn[u]??500})}},r=async(o,s)=>{if(e.assertAdmin(o),o.method!==s.http)throw new i(`Auth admin endpoint requires ${s.http}`,{code:"METHOD_NOT_ALLOWED",status:405});const l=e.getAuthAdmin();if(l===void 0)throw new i("auth endpoints require an `authAdmin` on the worker",{code:"AUTH_NOT_CONFIGURED",status:400});const u=l[s.method];if(u===void 0)throw new i(`auth admin does not support \`${s.method}\``,{code:"AUTH_OP_NOT_SUPPORTED",status:400});const f=new URL(o.url),y={body:s.http==="POST"?await e.readJsonBody(o):{},paging:e.parsePaging(o),query:_=>e.queryParameter(f,_)},E=s.build(y),w=await t(()=>u(E));return Response.json(s.returns==="void"?{ok:!0}:w,{headers:{"content-type":"application/json"},status:200})},n={};for(const[o,s]of Object.entries(ln))n[o]=l=>r(l,s);return n},pn="__lunora_admin__:getAuthAuditLog",ot=e=>typeof e=="string"&&e!==""?e:void 0,st=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0,fn=e=>async(t,r)=>{e.assertAdmin(t);const n=e.getReader();if(n===void 0)throw new i("the auth/security audit endpoint requires an `authAuditReader` on the worker",{code:"AUTH_AUDIT_NOT_CONFIGURED",status:400});const o=ot(r.actorId),s=ot(r.event),l=st(r.sinceSeq),u=st(r.limit),f={...o===void 0?{}:{actorId:o},...s===void 0?{}:{event:s},...l===void 0?{}:{sinceSeq:l},...u===void 0?{}:{limit:u}};let y;try{y=await n.read(f)}catch(w){throw w instanceof i?w:(console.error("[lunora] auth audit read failed:",w),new i("auth audit read failed",{code:"AUTH_AUDIT_READ_FAILED",status:500}))}const E={entries:y};return Response.json(E,{headers:{"content-type":"application/json"},status:200})},mn=(e,t)=>{const r=[],n=[];if(t&&t.length>0)for(const o of t)e.resolveTableSharding?.(o)?.mode.kind==="global"?n.push(o):r.push(o);return{globalTables:n,shardLocalTables:r}},wn=async(e,t,r,n,o,s)=>{if(r!==void 0&&n.length===0)return;const l=await e.orchestrateExport(s,{args:{tables:n},headers:t,tables:n});for(const u of l.shards)if(!u.error)for(const f of u.rows??[])o(f)},$t=async(e,t,r,n,o,s)=>{const{globalTables:l,shardLocalTables:u}=mn(e,n);await wn(t,r,n,u,o,s);const f=e.exportGlobals;if((n===void 0||l.length>0)&&f)for await(const y of f({tables:l}))o(y)},gn=new TextEncoder,yn=1e3,Bt=10,bn=200,it=8,xt="lunoraBackupCron",ct=24*1048576,ut=e=>{const t=e.slice(0,Bt).map(n=>Dt(n)),r=e.length-t.length;return`${t.join(", ")}${r>0?` (+${String(r)} more)`:""}`},_n=(e,t)=>{const r=new Uint8Array(new ArrayBuffer(t));let n=0;for(const o of e)r.set(o,n),n+=o.byteLength;return r},ze=async(e,t,r,n)=>{if(r===void 0||!Number.isInteger(r)||r<=0)return{eligible:0,stale:[]};const o=[];let s;for(let l=0;l<yn;l+=1){const u=await e.list({cursor:s,include:["customMetadata"],prefix:t});for(const f of u.objects)Pr(f.key)&&f.customMetadata?.[xt]===n&&o.push(f.key);if(!u.truncated||u.cursor===void 0)break;s=u.cursor}return{eligible:o.length,stale:o.toSorted((l,u)=>u.localeCompare(l)).slice(r)}},Rn=async(e,t,r,n,o)=>{const{stale:s}=await ze(e,t,r,n),l=new Set(o),u=s.filter(h=>l.has(h)),f=u.slice(0,bn),y=s.length-f.length,E=o.length-u.length;if(f.length===0)return{deleted:[],failed:[],ignored:E,remaining:y};const w=[],_=[];for(let h=0;h<f.length;h+=it){const S=await Promise.allSettled(f.slice(h,h+it).map(async R=>(await e.delete(Dt(R)),await e.delete(R),R)));for(const[R,T]of S.entries())T.status==="fulfilled"?w.push(T.value):_.push(f[h+R])}return w.length>0&&console.info(`[lunora] backup prune kept the newest ${String(r)} and deleted ${String(w.length)}: ${ut(w)}`),_.length>0&&console.warn(`[lunora] backup prune failed to remove ${String(_.length)}: ${ut(_)}`),{deleted:w,failed:_,ignored:E,remaining:y}},En=async e=>{const t=e.backupStore;if(!t)throw new i("backup retention preview requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});const r=Fe(e.backupPrefix??Ge),n=e.backupCron,{eligible:o,stale:s}=n===void 0?{eligible:0,stale:[]}:await ze(t,r,e.backupRetain,n);return{cron:n,eligible:o,keep:e.backupRetain??0,prefix:r,wouldDelete:s}},Sn=async(e,t,r,n)=>{const o=e.backupStore,s=e.queryCoordinator;if(!o)throw new i("scheduled backup requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});if(!s)throw new i("scheduled backup requires a `queryCoordinator` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});if(!r||r.length===0)throw new i("scheduled backup requires an `adminToken` (or `env.LUNORA_ADMIN_TOKEN`) to authenticate the per-shard export gate",{code:"BACKUP_NOT_CONFIGURED",status:500});const l={authorization:`Bearer ${r}`,"content-type":"application/json"},u=e.backupTables;let f=0,y=0,E=[];await $t(e,s,l,u,A=>{const U=gn.encode(`${JSON.stringify(A)}
2
- `);if(f+=1,y+=U.byteLength,y>ct)throw new i(`scheduled backup reached ${String(y)} bytes of NDJSON, past the ${String(ct)}-byte limit for a snapshot assembled inside a Worker — nothing was written. Narrow it with \`backupTables\`, or take this snapshot off-platform with \`lunora backup create --bucket\`.`,{code:"BACKUP_TOO_LARGE",status:507});E.push(U)},t);const w=Fe(e.backupPrefix??Ge),_=new Date(n.scheduledTime).toISOString(),h=Ur(w,_),S=_n(E,y);E=[];const R=qr(await crypto.subtle.digest("SHA-256",S));await o.put(h,S,{httpMetadata:{contentType:"application/x-ndjson"},sha256:R});const T={bytes:y,createdAt:_,cron:n.cron,file:h,id:_,rows:f,scheduledTime:n.scheduledTime,sha256:R,...u?{tables:u.join(",")}:{}};await o.put(Nr(h),`${JSON.stringify(T,void 0,2)}
3
- `,{customMetadata:{[xt]:n.cron},httpMetadata:{contentType:"application/json"}});try{const{stale:A}=await ze(o,w,e.backupRetain,n.cron);if(A.length>0){const U=A.slice(0,Bt),v=A.length-U.length;console.info(`[lunora] backup retention: ${String(A.length)} snapshot(s) past the newest ${String(e.backupRetain)} — run \`lunora backup prune\` to remove them: ${U.join(", ")}${v>0?` (+${String(v)} more)`:""}`)}}catch(A){console.warn(`[lunora] backup ${h} was written, but the retention report failed:`,A)}},On=async(e,t)=>{const r=e.backupStore;if(!r)throw new i("backup prune requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});const n=e.backupCron,o=e.backupRetain;if(n===void 0||o===void 0||!Number.isInteger(o)||o<=0)throw new i("backup prune needs a retention window: set `backupRetain` (and `backupCron`, which decides whose snapshots retention owns) on the worker. Without one there is nothing past the window to remove.",{code:"BACKUP_RETENTION_NOT_CONFIGURED",status:400});return Rn(r,Fe(e.backupPrefix??Ge),o,n,t)},Tn="/_lunora/admin/backup/retention",An="/_lunora/admin/backup/prune",kn=e=>{const{options:t,readJsonBody:r,requireAdminOption:n}=e,o=(u,f)=>{n(u,t.backupStore,{code:"BACKUP_NOT_CONFIGURED",message:`backup ${f} requires a \`backupStore\` on the worker`})},s=async u=>(x(u,"GET","Backup-retention"),o(u,"retention preview"),Response.json(await En(t),{headers:{"cache-control":"no-store"}})),l=async u=>{x(u,"POST","Backup-prune"),o(u,"prune");const{confirm:f}=await r(u);if(!Array.isArray(f)||f.some(y=>typeof y!="string"))throw new i("backup prune requires a `confirm` array of the sidecar keys to remove — read them from `GET /_lunora/admin/backup/retention` and pass back the ones you mean to delete",{code:"BAD_REQUEST",status:400});return Response.json(await On(t,f),{headers:{"cache-control":"no-store"}})};return{[An]:l,[Tn]:s}},dt=500,vn=(e,t,r)=>{if(typeof e!="object"||e===null||Array.isArray(e))throw new i("each batch call must be an object",{code:"BAD_REQUEST",status:400});const n=e;if(typeof n.functionPath!="string")throw new i("each batch call needs a string `functionPath`",{code:"BAD_REQUEST",status:400});if(n.functionPath.startsWith("__lunora_relation__:")||n.functionPath.startsWith("__lunora_admin__"))throw new i("reserved function path cannot be batched",{code:"FORBIDDEN",status:403});if(n.args!==void 0&&(typeof n.args!="object"||n.args===null||Array.isArray(n.args)))throw new i("each batch call `args` must be an object",{code:"BAD_REQUEST",status:400});return{entry:{args:n.args===void 0?{}:n.args,clientId:typeof n.clientId=="string"?n.clientId:void 0,clientSeq:typeof n.clientSeq=="number"?n.clientSeq:void 0,functionPath:n.functionPath,id:typeof n.id=="number"?n.id:t,mutationId:typeof n.mutationId=="string"?n.mutationId:void 0},shardKey:typeof n.shardKey=="string"?n.shardKey:r}},In=(e,t)=>{if(e.length>dt)throw new i(`RPC batch exceeds the ${String(dt)}-call limit`,{code:"BAD_REQUEST",status:400});const r=new Map;for(const[n,o]of e.entries()){const{entry:s,shardKey:l}=vn(o,n,t),u=r.get(l)??[];u.push(s),r.set(l,u)}return r},Dn=new TextEncoder,Pn=e=>{const t=JSON.stringify(e),r=Dn.encode(t);let n="";for(const o of r)n+=String.fromCodePoint(o);return btoa(n).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")},Un=e=>{const t={g:0,s:{},v:1};if(typeof e!="string"||e.length===0)return t;try{const r=atob(e.replaceAll("-","+").replaceAll("_","/")),n=new Uint8Array(r.length);for(let u=0;u<r.length;u+=1)n[u]=r.codePointAt(u)??0;const o=JSON.parse(new TextDecoder().decode(n)),s=o.s&&typeof o.s=="object"?o.s:{},l={};for(const[u,f]of Object.entries(s))typeof f=="number"&&Number.isFinite(f)&&(l[u]=f);return{g:typeof o.g=="number"&&Number.isFinite(o.g)?o.g:0,s:l,v:1}}catch{return t}},Nn=e=>{const t=typeof e.table=="string"?e.table:"",r=typeof e.op=="string"?e.op:"",n=r==="delete"||r==="insert"||r==="update"?r:"upsert",o=typeof e.id=="string"?e.id:void 0;return{doc:(e.doc&&typeof e.doc=="object"?e.doc:void 0)??(o===void 0?{}:{_id:o}),op:n,table:t}},lt=(e,t,r)=>{for(const n of t)e.push(Nn(n));return r!==void 0&&t.length>=r},qn="/_lunora/admin/export",Cn="/_lunora/admin/import",$n="/_lunora/admin/sync",Bn="/_lunora/admin/connector/sync",xn="/_lunora/admin/apply",jn="/_lunora/admin/export-tap/run",Kn=new TextEncoder,Ln=async e=>{const t=await be(e,"Export")??{};if(t.tables===void 0)return{tables:void 0};if(!Array.isArray(t.tables))throw new i("Export `tables` must be a string array",{code:"BAD_REQUEST",status:400});const r=[];for(const n of t.tables){if(typeof n!="string"||n.length===0)throw new i("Export `tables` entries must be non-empty strings",{code:"BAD_REQUEST",status:400});r.push(n)}return{tables:r}},Be=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):void 0,Fn=e=>{const{applyGlobals:t,exportCursorStore:r,exportSinks:n,knownTables:o,queryCoordinator:s,assertAdmin:l,requireAdminOption:u,resolveForwardContext:f,shardDO:y,streamExportRows:E,streamingImport:w,syncGlobals:_}=e,h=async(v,L)=>{const j=we(v,["POST"]);if(j)return j;const V=u(v,s,{code:"BAD_REQUEST",message:"Export endpoint requires a `queryCoordinator` on the worker"}),N=await Ln(v),{headers:G}=await f(v,L),Q=new ReadableStream({async pull($){const K=Y=>{$.enqueue(Kn.encode(`${JSON.stringify(Y)}
4
- `))};try{await E(V,G,N.tables,K),$.close()}catch(Y){$.error(Y)}}});return new Response(Q,{headers:{"content-type":"application/x-ndjson"},status:200})},S=async(v,L)=>{const j=we(v,["POST"]);if(j)return j;const V=u(v,s,{code:"BAD_REQUEST",message:"Sync endpoint requires a `queryCoordinator` on the worker"}),N=await X(v),G=typeof N.cursors=="object"&&N.cursors!==null?N.cursors:{},Q=typeof N.limit=="number"?N.limit:void 0,$=typeof N.globalCursor=="number"?N.globalCursor:0,K=Be(N.tables),{headers:Y}=await f(v,L),J=K??o(),ne=await V.orchestrateCdcSync(y,{cursors:G,headers:Y,limit:Q,tables:J}),he=_?await _({limit:Q,sinceSeq:$}):void 0;return Response.json({global:he,shards:ne.shards},{status:200})},R=async(v,L)=>{const j=we(v,["POST"]);if(j)return j;const V=u(v,s,{code:"BAD_REQUEST",message:"Connector sync endpoint requires a `queryCoordinator` on the worker"}),N=await X(v),G=Un(N.cursor),Q=typeof N.limit=="number"&&N.limit>0?N.limit:void 0,$=Be(N.tables),{headers:K}=await f(v,L),Y=$??o(),J=await V.orchestrateCdcSync(y,{cursors:G.s,headers:K,limit:Q,tables:Y}),ne=[],he={...G.s};let ae=!1;for(const se of J.shards)ae=lt(ne,se.changes??[],Q)||ae,he[se.shardKey]=se.cursor;let pe=G.g;if(_){const se=await _({limit:Q,sinceSeq:G.g});ae=lt(ne,se.changes,Q)||ae,pe=se.cursor}const _e=Pn({g:pe,s:he,v:1}),ke={changes:ne,hasMore:ae,nextCursor:_e};return Response.json(ke,{status:200})},T=async(v,L)=>{const j=we(v,["POST"]);if(j)return j;const V=u(v,s,{code:"BAD_REQUEST",message:"Apply endpoint requires a `queryCoordinator` on the worker"}),N=await X(v),G=(Array.isArray(N.batches)?N.batches:[]).map(J=>J).filter(J=>J!==null&&typeof J=="object"&&typeof J.shardKey=="string"&&Array.isArray(J.changes)),Q=Array.isArray(N.globalChanges)?N.globalChanges:[],{headers:$}=await f(v,L),K=await V.orchestrateApplyCdc(y,{batches:G,headers:$}),Y=Q.length>0&&t?await t({changes:Q}):0;return Response.json({applied:K.applied+Y,failed:K.failed,ok:K.ok},{status:200})},A=async(v,L)=>{const j=we(v,["POST"]);if(j)return j;l(v);const{headers:V}=await f(v,L),N=await w(v,V);return Response.json(N,{headers:{"content-type":"application/json"},status:200})},U=async(v,L)=>{const j=we(v,["POST"]);if(j)return j;const V=u(v,s,{code:"BAD_REQUEST",message:"Export-tap endpoint requires a `queryCoordinator` on the worker"});if(n===void 0||Object.keys(n).length===0||r===void 0)throw new i("Export-tap endpoint requires `exportSinks` + `exportCursorStore` on the worker",{code:"EXPORT_TAP_NOT_CONFIGURED",status:400});const N=await X(v),G=typeof N.sink=="string"?N.sink:void 0,Q=typeof N.limit=="number"&&N.limit>0?N.limit:void 0,$=Be(N.tables);if(G===void 0)throw new i("Export-tap `sink` must name a configured sink",{code:"BAD_REQUEST",status:400});const K=n[G];if(K===void 0)throw new i(`Export-tap sink "${G}" is not configured`,{code:"NOT_FOUND",status:404});const{headers:Y}=await f(v,L),J=$??o(),ne=await xr({coordinator:V,cursorStore:r,headers:Y,limit:Q,shardDO:y,sink:K,tables:J});return Response.json(ne,{headers:{"content-type":"application/json"},status:200})};return{[xn]:T,[Bn]:R,[qn]:h,[jn]:U,[Cn]:A,[$n]:S}},Gn=(e,t)=>{let r;try{r=JSON.parse(e)}catch{return{error:{code:"BAD_ROW",line:t,message:"line is not valid JSON",table:""},ok:!1}}if(!r||typeof r!="object"||Array.isArray(r))return{error:{code:"BAD_ROW",line:t,message:"row must be a JSON object",table:""},ok:!1};const n=r;return typeof n.table!="string"||n.table.length===0?{error:{code:"BAD_ROW",line:t,message:"row is missing `table`",table:""},ok:!1}:!n.doc||typeof n.doc!="object"||Array.isArray(n.doc)?{error:{code:"BAD_ROW",line:t,message:"row is missing or malformed `doc`",table:n.table},ok:!1}:{doc:n.doc,ok:!0,table:n.table}},Qn=(e,t,r,n,o)=>{if(r?.mode.kind==="shardBy"&&typeof r.mode.field=="string"){const s=e[r.mode.field];return s==null?{error:{code:"BAD_ROW",line:o,message:`row missing shard field "${r.mode.field}" for table "${t}"`,table:t},ok:!1}:{ok:!0,shardKey:typeof s=="string"?s:JSON.stringify(s)}}return{ok:!0,shardKey:n}},Mn=async(e,t,r)=>{if(!e.body)throw new i("Import endpoint requires a request body",{code:"BAD_REQUEST",status:400});const n=[],o=[],s=new Map;let l=0,u=0;const f=e.body.getReader(),y=new TextDecoder;let E="",w=0;const _=h=>{u+=1;const S=h.trim();if(S.length===0)return;l+=1;const R=Gn(S,u);if(!R.ok){n.push(R.error);return}const{doc:T,table:A}=R,U=t.resolveTableSharding?.(A);if(U?.mode.kind==="global"){o.push({doc:T,line:u,table:A});return}const v=Qn(T,A,U,r,u);if(!v.ok){n.push(v.error);return}const L=s.get(v.shardKey);L?L.rows.push({doc:T,table:A}):s.set(v.shardKey,{rows:[{doc:T,table:A}],shardKey:v.shardKey,startLine:u})};for(;;){const{done:h,value:S}=await f.read();if(h)break;if(S&&(w+=S.byteLength,w>kt))throw await f.cancel().catch(()=>{}),new i("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});E+=y.decode(S,{stream:!0});let R=E.indexOf(`
5
- `);for(;R!==-1;){const T=E.slice(0,R);E=E.slice(R+1),_(T),R=E.indexOf(`
6
- `)}}return E.length>0&&_(E),{errors:n,globalRows:o,perShard:s,received:l}},ht=(e,t)=>{for(const[r,n]of Object.entries(t.inserted))e.inserted[r]=(e.inserted[r]??0)+n;for(const r of t.errors)e.errors.push({...r});e.conflicts+=t.conflicts},zn=async(e,t,r,n)=>{const o=t.defaultShardKey??"__root__",{errors:s,globalRows:l,perShard:u,received:f}=await Mn(e,t,o),y={conflicts:0,errors:s,inserted:{}},E=[];if(t.resolveTableSharding===void 0&&u.size>0&&E.push("no `resolveTableSharding` is configured, so every row was routed to the default shard and no row could be recognised as `.global()` — correct for a single-shard app, silent misplacement for a sharded one"),u.size>0){const w=t.queryCoordinator;if(!w)throw new i("Import endpoint requires a `queryCoordinator` on the worker",{code:"BAD_REQUEST",status:400});const _=await w.orchestrateImport(n,{batches:[...u.values()],headers:r});ht(y,_)}if(l.length>0)if(t.importGlobals){const w=l[0]?.line??1,_=await t.importGlobals({rows:l,startLine:w});ht(y,_)}else for(const w of l)y.errors.push({code:"GLOBAL_NOT_CONFIGURED",line:w.line,message:`row targets global table "${w.table}" but no \`importGlobals\` is configured`,table:w.table});return{conflicts:y.conflicts,errors:y.errors,inserted:y.inserted,received:f,...E.length>0?{warnings:E}:{}}},xe=e=>typeof e=="object"&&e!==null?e:{},je=e=>typeof e.kind=="string"?e.kind:"unknown",Wn=(e,t)=>{let r=xe(t),n=!1;je(r)==="optional"&&(n=!0,r=xe(r._meta?.inner));const o=je(r),s=r._meta??{},l={kind:o,name:e,optional:n};if(o==="id"&&typeof s.tableName=="string"&&(l.table=s.tableName),o==="array"){const u=je(xe(s.inner));u!=="unknown"&&(l.element=u)}return l},Jn=e=>typeof e!="object"||e===null?[]:Object.entries(e).map(([t,r])=>Wn(t,r)).toSorted((t,r)=>t.name.localeCompare(r.name)),Hn="/_lunora/admin/functions",Vn="/_lunora/admin/cron-jobs",Yn="/_lunora/admin/openapi",Xn="/_lunora/admin/openrpc",Zn="/_lunora/admin/global/tables",ea="/_lunora/admin/global/table",ta="/_lunora/admin/global/facet",pt=e=>{if(e===void 0||e==="")return;let t;try{t=JSON.parse(e)}catch{return}if(!Array.isArray(t))return;const r=t.flatMap(n=>{if(typeof n!="object"||n===null||typeof n.column!="string")return[];const{column:o,value:s}=n;return[{column:o,value:s}]});return r.length===0?void 0:r},ra=Object.freeze({info:{description:'No OpenAPI spec is configured on this worker. Run `lunora codegen`, then wire the generated module to `createWorker`: `import { openApiSpec } from "./lunora/_generated/openapi"`.',title:"Lunora API",version:"0.0.0"},openapi:"3.1.0",paths:{}}),na=Object.freeze({info:{description:'No OpenRPC spec is configured on this worker. Run `lunora codegen --api-spec openrpc` (or `both`), then wire the generated module to `createWorker`: `import { openRpcSpec } from "./lunora/_generated/openrpc"`.',title:"Lunora RPC",version:"0.0.0"},methods:[],openrpc:"1.3.2"}),aa=e=>{const{assertAdmin:t,options:r,parsePaging:n,queryParameter:o,requireAdminOption:s}=e,l=h=>{x(h,"GET","Functions");const S=s(h,r.functions,{code:"FUNCTIONS_NOT_CONFIGURED",message:"functions endpoint requires a `functions` registry on the worker"}),R=Object.entries(S).flatMap(([T,A])=>A.visibility==="internal"||A.kind==="stream"?[]:[{args:Jn(A.args),kind:A.kind,path:T}]).toSorted((T,A)=>T.path.localeCompare(A.path));return Response.json({functions:R},{headers:{"content-type":"application/json"},status:200})},u=h=>{x(h,"GET","Cron-jobs");const S=s(h,r.cronJobs,{code:"CRON_JOBS_NOT_CONFIGURED",message:"cron-jobs endpoint requires a `cronJobs` map on the worker"}),R=Object.entries(S).flatMap(([T,A])=>A.map(U=>({args:U.args,cron:T,functionPath:U.functionPath,name:U.name,shardKey:U.shardKey,workflow:U.workflow}))).toSorted((T,A)=>T.name.localeCompare(A.name));return Response.json({jobs:R},{headers:{"content-type":"application/json"},status:200})},f=h=>(x(h,"GET","OpenAPI"),t(h),Response.json(r.openApiSpec??ra,{headers:{"content-type":"application/json"},status:200})),y=h=>(x(h,"GET","OpenRPC"),t(h),Response.json(r.openRpcSpec??na,{headers:{"content-type":"application/json"},status:200})),E=async h=>{x(h,"GET","Global-tables");const S=s(h,r.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"});return Response.json(await S.listTables(),{headers:{"content-type":"application/json"},status:200})},w=async h=>{x(h,"GET","Global-table");const S=s(h,r.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),R=new URL(h.url),T=o(R,"table");if(T===void 0)throw new i("Global-table endpoint requires a `table` query param",{code:"BAD_REQUEST",status:400});const A=await S.readTablePage({...n(h),filters:pt(o(R,"filters")),table:T});return Response.json(A,{headers:{"content-type":"application/json"},status:200})},_=async h=>{x(h,"GET","Global-facet");const S=s(h,r.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),R=new URL(h.url),T=o(R,"table"),A=o(R,"column");if(T===void 0||A===void 0)throw new i("Global-facet endpoint requires `table` and `column` query params",{code:"BAD_REQUEST",status:400});const U=o(R,"limit"),v=U===void 0?void 0:Number(U),L=await S.facetColumn({column:A,filters:pt(o(R,"filters")),limit:v!==void 0&&Number.isFinite(v)?v:void 0,table:T});return Response.json(L,{headers:{"content-type":"application/json"},status:200})};return{[Vn]:u,[Hn]:l,[ta]:_,[ea]:w,[Zn]:E,[Yn]:f,[Xn]:y}},oa="/_lunora/admin/kv/namespaces",sa="/_lunora/admin/kv/keys",jt="/_lunora/admin/kv/value",Kt=32*1048576,ft=60,ia=e=>{const{readJsonBody:t,requireAdminOption:r}=e,n=w=>r(w,e.kvIntrospector,{code:"KV_NOT_CONFIGURED",message:"KV endpoints require a `kvIntrospector` on the worker"}),o=w=>Response.json(w,{headers:{"content-type":"application/json"},status:200}),s=(w,_)=>{const h=new URL(w.url),S=h.searchParams.get("namespace")??"",R=h.searchParams.get("key")??"";if(S==="")throw new i(`KV-value ${_} request requires a \`namespace\` query parameter`,{code:"BAD_REQUEST",status:400});if(R==="")throw new i(`KV-value ${_} request requires a \`key\` query parameter`,{code:"BAD_REQUEST",status:400});return{key:R,namespace:S}},l=async(w,_)=>{if(!(await w.listNamespaces()).some(h=>h.binding===_))throw new i(`Unknown KV namespace binding \`${_}\``,{code:"NOT_FOUND",status:404})},u=async w=>(x(w,"GET","KV-namespaces"),o({namespaces:await n(w).listNamespaces()})),f=async w=>{x(w,"GET","KV-keys");const _=n(w),h=new URL(w.url),S=h.searchParams.get("namespace")??"";if(S==="")throw new i("KV-keys request requires a `namespace` query parameter",{code:"BAD_REQUEST",status:400});const R=h.searchParams.get("prefix")??void 0,T=h.searchParams.get("cursor")??void 0,A=h.searchParams.get("limit"),U=A===null?void 0:Number.parseInt(A,10);if(U!==void 0&&(!Number.isInteger(U)||U<1))throw new i("KV-keys `limit` must be a positive integer",{code:"BAD_REQUEST",status:400});const v=U===void 0?void 0:Math.min(U,1e3);return await l(_,S),o(await _.listKeys({cursor:T,limit:v,namespace:S,prefix:R}))},y={DELETE:async w=>{const _=n(w),h=s(w,"DELETE");return await l(_,h.namespace),await _.deleteKey(h),o({deleted:!0})},GET:async w=>{const _=n(w),h=s(w,"GET");return await l(_,h.namespace),o(await _.getValue(h))},PUT:async w=>{const _=n(w),h=await t(w,Kt);if(typeof h.namespace!="string"||h.namespace==="")throw new i("KV-value PUT request requires a `namespace` string",{code:"BAD_REQUEST",status:400});if(typeof h.key!="string"||h.key==="")throw new i("KV-value PUT request requires a `key` string",{code:"BAD_REQUEST",status:400});if(typeof h.value!="string")throw new i("KV-value PUT request requires a `value` string",{code:"BAD_REQUEST",status:400});if(h.expirationTtl!==void 0&&(typeof h.expirationTtl!="number"||!Number.isInteger(h.expirationTtl)||h.expirationTtl<ft))throw new i("KV-value PUT `expirationTtl` must be an integer ≥ 60",{code:"BAD_REQUEST",status:400});const S=Math.floor(Date.now()/1e3)+ft;if(h.expiration!==void 0&&(typeof h.expiration!="number"||!Number.isInteger(h.expiration)||h.expiration<S))throw new i("KV-value PUT `expiration` must be a Unix-seconds timestamp at least 60 seconds in the future",{code:"BAD_REQUEST",status:400});return await l(_,h.namespace),await _.putValue({expiration:h.expiration,expirationTtl:h.expirationTtl,key:h.key,metadata:h.metadata,namespace:h.namespace,value:h.value}),o({ok:!0})}},E=w=>{const _=y[w.method];if(!_)throw new i("KV-value endpoint requires GET, PUT, or DELETE",{code:"METHOD_NOT_ALLOWED",status:405});return _(w)};return{[oa]:u,[sa]:f,[jt]:E}},ca="/_lunora/migrate",ua="/_lunora/admin/pitr",da="/_lunora/admin/rank",la="/_lunora/admin/rankpage",ha="/_lunora/admin/shard-traffic",pa=new Set(["__lunora_admin__:migrationStatus","__lunora_admin__:runMigration"]),fa=new Set(["__lunora_admin__:getPitrBookmark","__lunora_admin__:pitrRestore"]),ma=async e=>{const t=await be(e,"Migration")??{};if(typeof t.table!="string"||t.table.length===0)throw new i("Migration request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof t.functionPath!="string"||!pa.has(t.functionPath))throw new i("Migration request `functionPath` must be a migration admin op",{code:"BAD_REQUEST",status:400});return{args:t.args??{},functionPath:t.functionPath,table:t.table}},wa=async e=>{const t=await be(e,"Rank")??{};if(typeof t.table!="string"||t.table.length===0)throw new i("Rank request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof t.index!="string"||t.index.length===0)throw new i("Rank request is missing `index`",{code:"BAD_REQUEST",status:400});if(typeof t.partitionKey!="string")throw new i("Rank request `partitionKey` must be a string",{code:"BAD_REQUEST",status:400});if(typeof t.rowId!="string"||t.rowId.length===0)throw new i("Rank request is missing `rowId`",{code:"BAD_REQUEST",status:400});if(!Array.isArray(t.sortValues))throw new i("Rank request `sortValues` must be an array",{code:"BAD_REQUEST",status:400});return{index:t.index,partitionKey:t.partitionKey,rowId:t.rowId,sortValues:t.sortValues,table:t.table}},ga=e=>{if(e!==void 0){if(!Array.isArray(e)||e.some(t=>t!=="asc"&&t!=="desc"))throw new i('Rank page request `directions` must be an array of "asc"|"desc"',{code:"BAD_REQUEST",status:400});return e}},ya=e=>{if(typeof e.table!="string"||e.table.length===0)throw new i("Rank page request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof e.index!="string"||e.index.length===0)throw new i("Rank page request is missing `index`",{code:"BAD_REQUEST",status:400});if(e.partitionKey!==void 0&&typeof e.partitionKey!="string")throw new i("Rank page request `partitionKey` must be a string",{code:"BAD_REQUEST",status:400});if(e.take!==void 0&&(typeof e.take!="number"||!Number.isFinite(e.take)))throw new i("Rank page request `take` must be a number",{code:"BAD_REQUEST",status:400});if(e.cursor!==void 0&&e.cursor!==null&&typeof e.cursor!="string")throw new i("Rank page request `cursor` must be a string or null",{code:"BAD_REQUEST",status:400})},ba=async e=>{const t=await be(e,"Rank page")??{};ya(t);const r=ga(t.directions);return{cursor:typeof t.cursor=="string"?t.cursor:null,directions:r,index:t.index,partitionKey:typeof t.partitionKey=="string"?t.partitionKey:void 0,table:t.table,take:typeof t.take=="number"?t.take:void 0}},_a=async e=>{const t=await be(e,"Shard-traffic")??{};if(typeof t.table!="string"||t.table.length===0)throw new i("Shard-traffic request is missing `table`",{code:"BAD_REQUEST",status:400});return{table:t.table}},Ra=async e=>{const t=await X(e);if(typeof t.functionPath!="string"||!fa.has(t.functionPath))throw new i("PITR request `functionPath` must be a PITR admin op",{code:"BAD_REQUEST",status:400});if(t.shardKey!==void 0&&typeof t.shardKey!="string")throw new i("PITR `shardKey` must be a string",{code:"BAD_REQUEST",status:400});return{args:t.args??{},functionPath:t.functionPath,shardKey:t.shardKey}},Ea=e=>{const{defaultShard:t,forwardToShard:r,isAdmin:n,queryCoordinator:o,resolveForwardContext:s,shardDO:l}=e,u=(h,S)=>{if(h.method!=="POST")throw new i(`${S} endpoint requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});if(!n(h))throw new i("Admin auth required",{code:"FORBIDDEN",status:403});if(!o)throw new i(`${S} endpoint requires a \`queryCoordinator\` on the worker`,{code:"BAD_REQUEST",status:400});return o},f=async(h,S)=>{const R=u(h,"Migration"),T=await ma(h),{headers:A}=await s(h,S),U=await R.orchestrateMigration(l,{args:T.args,functionPath:T.functionPath,headers:A,table:T.table});return Response.json(U,{headers:{"content-type":"application/json"},status:200})},y=async(h,S)=>{const R=u(h,"Rank"),T=await wa(h),{headers:A}=await s(h,S),U=await R.orchestrateRank(l,{headers:A,index:T.index,partitionKey:T.partitionKey,rowId:T.rowId,sortValues:T.sortValues,table:T.table});return Response.json(U,{headers:{"content-type":"application/json"},status:200})},E=async(h,S)=>{const R=u(h,"Rank page"),T=await ba(h),{headers:A}=await s(h,S),U=await R.orchestrateRankPage(l,{...T,headers:A});return Response.json(U,{headers:{"content-type":"application/json"},status:200})},w=async(h,S)=>{const R=u(h,"Shard-traffic"),T=await _a(h),{headers:A}=await s(h,S),U=await R.orchestrateShardTraffic(l,{headers:A,table:T.table});return Response.json(U,{headers:{"content-type":"application/json"},status:200})},_=async(h,S)=>{if(x(h,"POST","PITR"),!n(h))throw new i("admin PITR endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403});const R=await Ra(h),{headers:T}=await s(h,S),A=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:R.args,functionPath:R.functionPath}),headers:T,method:"POST"});return r(l,R.shardKey??t,A)};return{[ca]:f,[ua]:_,[da]:y,[la]:E,[ha]:w}},Sa=1,Oa=0,Ta=32,Aa=512,ka=/^[a-z][\d_a-z*/-]{0,255}(?:@[a-z][\d_a-z*/-]{0,13})?=[\u0020-\u002B\u002D-\u003C\u003E-\u007E]{1,256}$/,va=e=>{if(e==null)return;const t=e.trim();if(t.length===0||t.length>Aa)return;const r=t.split(",");if(!(r.length>Ta)){for(const n of r)if(!ka.test(n.trim()))return;return t}},Ia=e=>{const t=Or(e.headers.get("traceparent"));if(t===void 0)return;const r=va(e.headers.get("tracestate"));return{parentSpanId:t.parentSpanId,sampled:t.sampled,traceId:t.traceId,...r===void 0?{}:{traceState:r}}},Da=(e,t={})=>{const r=Ia(e),n=t.trustInbound===!0?r:void 0,o=Ae(8),s=n?.traceId??Ae(16),l=Qr(t.sampling,n===void 0?o:s),u=l.isTraced&&(n===void 0||n.sampled);return{decision:l,ignoredUpstream:r!==void 0&&n===void 0,trace:{sampled:u,spanId:o,traceFlags:u?Sa:Oa,traceId:s,...n?.parentSpanId===void 0?{}:{parentSpanId:n.parentSpanId},...n?.traceState===void 0?{}:{traceState:n.traceState}}}},Pa=(e,t)=>{t.traceparent=Sr(e.traceId,e.spanId,e.sampled),e.traceState!==void 0&&(t.tracestate=e.traceState)},Ua=(e,t)=>{let r;return()=>{if(r===void 0){const n=vr(e),o=t===void 0?void 0:t.cf;r=Tr(kr(n),Ar(n,o))}return r}},Na="/_lunora/admin/scheduled",qa="/_lunora/admin/scheduled/status",Ca="/_lunora/admin/scheduled/ws",$a="/_lunora/admin/scheduled/cancel",Ba="/_lunora/admin/scheduled/dead",xa="/_lunora/admin/scheduled/dead/retry",ja="/_lunora/admin/scheduled/dead/cancel",Ka=e=>{const{checkWsAdmin:t,requireSchedulerNamespace:r,resolveSchedulerStub:n,schedulerInstanceName:o}=e,s=(f,y)=>E=>{if(E.method!=="GET")throw new i(`${y} endpoint requires GET`,{code:"METHOD_NOT_ALLOWED",status:405});return n(E).fetch(new Request(`https://scheduler.internal${f}`,{method:"GET"}))},l=(f,y,E=y)=>async w=>{if(w.method!=="POST")throw new i(`${E} requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});const _=n(w),h=await w.json().catch(()=>{});if(typeof h?.id!="string"||h.id==="")throw new i(`${y} requires a string \`id\``,{code:"BAD_REQUEST",status:400});return _.fetch(new Request(`https://scheduler.internal${f}`,{body:JSON.stringify({id:h.id}),headers:{"content-type":"application/json"},method:"POST"}))},u=async f=>{if(f.headers.get("Upgrade")!=="websocket")throw new i("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});if(!await t(f))throw new i("admin authorization required",{code:"ADMIN_FORBIDDEN",status:403});const y=r();return ge(y,o).fetch(new Request("https://scheduler.internal/ws",{headers:{Upgrade:"websocket"}}))};return{[$a]:l("/cancel","Scheduled-cancel","Scheduled-cancel endpoint"),[ja]:l("/dead/cancel","Scheduled dead-letter action"),[Ba]:s("/dead","Scheduled dead-letter"),[xa]:l("/dead/retry","Scheduled dead-letter action"),[Na]:s("/list","Scheduled-list"),[qa]:s("/status","Scheduler-status"),[Ca]:u}},La=(e,...t)=>{let r=e.cf;for(const n of t){if(typeof r!="object"||r===null)return;r=r[n]}return typeof r=="string"?r:void 0},mt={mtls:e=>La(e,"tlsClientAuth","certVerified")==="SUCCESS"},Fa=e=>e===void 0||e===!1?()=>!1:e===!0?()=>!0:typeof e=="function"?e:(Object.hasOwn(mt,e)?mt[e]:void 0)??(()=>!1),Ga=e=>{if(e!==void 0)return()=>{};let t=!1;return()=>{t||(t=!0,console.warn('[lunora] Ignored an inbound `traceparent`, so this request starts a new trace instead of joining the caller\'s. That is the safe default: the header is caller-supplied, and trusting it lets any client choose which trace its spans and logs join. If this worker sits behind a gateway, service mesh, or Cloudflare Access that sets `traceparent` itself, set `trustInboundTraceContext: true` on createWorker() (or `"mtls"` to trust only edge-verified client certificates). Set it to `false` to keep this behaviour and silence this message.'))}},Qa="/_lunora/admin/vector/indexes",Ma="/_lunora/admin/vector/query",za=e=>{const{readJsonBody:t,requireAdminOption:r}=e,n=async s=>{x(s,"GET","Vector-indexes");const l=r(s,e.vectorIntrospector,{code:"VECTORS_NOT_CONFIGURED",message:"vector endpoints require a `vectorIntrospector` on the worker"});return Response.json({indexes:await l.listIndexes()},{headers:{"content-type":"application/json"},status:200})},o=async s=>{x(s,"POST","Vector-query");const l=r(s,e.vectorIntrospector,{code:"VECTORS_NOT_CONFIGURED",message:"vector endpoints require a `vectorIntrospector` on the worker"});if(l.queryIndex===void 0)throw new i("vector index querying is not enabled on this worker",{code:"VECTOR_QUERY_UNSUPPORTED",status:400});const u=await t(s);if(typeof u.name!="string"||u.name==="")throw new i("Vector-query request requires a `name` string",{code:"BAD_REQUEST",status:400});if(typeof u.text!="string"||u.text==="")throw new i("Vector-query request requires a `text` string",{code:"BAD_REQUEST",status:400});if(u.topK!==void 0&&(typeof u.topK!="number"||!Number.isInteger(u.topK)||u.topK<1))throw new i("Vector-query `topK` must be a positive integer",{code:"BAD_REQUEST",status:400});const f=await l.queryIndex({name:u.name,text:u.text,topK:u.topK});return Response.json(f,{headers:{"content-type":"application/json"},status:200})};return{[Qa]:n,[Ma]:o}},Wa="/_lunora/admin/workflows/instances",Ja="/_lunora/admin/workflows/instance",Ha="/_lunora/admin/workflows/status",Va={complete:!0,errored:!0,paused:!0,queued:!0,running:!0,terminated:!0,unknown:!0,waiting:!0,waitingForPause:!0},Ya=e=>e!==null&&Object.hasOwn(Va,e)?e:void 0,wt=(e,t)=>{const r=e.searchParams.get(t);if(r===null)return;const n=Number(r);return Number.isInteger(n)&&n>0?n:void 0},Ke=(e,t)=>{const r=e.searchParams.get(t);if(r===null||r==="")throw new i(`Workflows admin endpoint requires a \`${t}\` query parameter`,{code:"BAD_REQUEST",status:400});return r},gt=()=>{throw new i("Workflow inspection is unconfigured. Set CLOUDFLARE_ACCOUNT_ID + CLOUDFLARE_API_TOKEN in your .dev.vars to enable it.",{code:"WORKFLOWS_NOT_CONFIGURED",status:501})},Xa=e=>{const{assertAdmin:t,resolveWorkflowsClient:r}=e,n=async(l,u,f)=>{x(l,"GET","Workflows instances"),t(l);const y=r(u);if(!y)return Response.json({configured:!1,instances:[],page:1,perPage:0,totalCount:0});const E=Ke(f,"name"),w=Ya(f.searchParams.get("status"));return Response.json(await y.listInstances({page:wt(f,"page"),perPage:wt(f,"perPage"),status:w,workflowName:E}))},o=async(l,u,f)=>{x(l,"GET","Workflows instance"),t(l);const y=r(u);return y?Response.json(await y.getInstance({instanceId:Ke(f,"id"),workflowName:Ke(f,"name")})):gt()},s=async(l,u)=>{x(l,"POST","Workflows status"),t(l);const f=r(u);if(!f)return gt();const y=await l.json().catch(()=>{});if(typeof y?.name!="string"||y.name===""||typeof y.id!="string"||y.id==="")throw new i("Workflows status action requires string `name` and `id`",{code:"BAD_REQUEST",status:400});const{action:E}=y;if(E!=="pause"&&E!=="resume"&&E!=="terminate")throw new i("Workflows status action must be one of: pause, resume, terminate",{code:"BAD_REQUEST",status:400});return Response.json(await f.setInstanceStatus({action:E,instanceId:y.id,workflowName:y.name}))};return{[Ja]:o,[Wa]:n,[Ha]:s}},Za={[jt]:Kt,[$r]:Cr},yt="/_lunora/rpc",eo="/_lunora/rpc-batch",to="/_lunora/ws",Ee=(e,t,r)=>({resourceAttributes:Ua(e,t),...r===void 0?{}:{waitUntil:r}}),bt=e=>e?.waitUntil?{waitUntil:t=>e.waitUntil?.(t)}:{},_t=e=>({spanId:e.spanId,traceFlags:e.traceFlags,traceId:e.traceId,...e.parentSpanId===void 0?{}:{parentSpanId:e.parentSpanId}}),Le=e=>{const{method:t}=e,r=e.headers.get("user-agent")??void 0;let n;try{n=new URL(e.url)}catch{return{method:t,userAgent:r}}const o=n.port===""?void 0:Number(n.port);return{host:n.hostname,method:t,path:n.pathname,port:Number.isNaN(o)?void 0:o,scheme:n.protocol.replace(":",""),userAgent:r}},Rt="/_lunora/voice/",ro="/_lunora/scheduler/dispatch",no="/_lunora/admin/cron-jobs/run",ao="/_lunora/admin/ws-token",oo="/_lunora/admin/",so="/_lunora/migrate",io="/_lunora/status",co=e=>e.startsWith(oo)||e===so,uo=e=>{const t=e.headers.get("x-lunora-userid"),r=e.headers.get("x-lunora-identity");if(!(t===null&&r===null))return{...r===null?{}:{identity:r},...t===null?{}:{userId:t}}},lo="/api/auth",ho="__lunora_admin__:recordAuthEvent",po="__lunora_admin__:listPushSubscriptions",fo=["/sign-in","/sign-up","/callback"],mo=(e,t)=>{const r=t.endsWith("/")?t.slice(0,-1):t;if(!e.startsWith(`${r}/`))return!1;const n=e.slice(r.length);return fo.some(o=>n===o||n.startsWith(`${o}/`))},Se=(e,t,r,n)=>{const o=yr(r),s=o?r.code:"INTERNAL_SERVER_ERROR",l=o?r.status:500,u=r instanceof Error?r.message:String(r);return{durationMs:t,error:{code:s,message:u,status:l},functionPath:e,ok:!1,...n.fanOut?{fanOut:{failed:0,shards:0,table:n.fanOut.table}}:{},...n.shardKey?{shardKey:n.shardKey}:{}}},wo=e=>{const{exp:t,expiresAtMs:r}=e;if(typeof r=="number"&&Number.isFinite(r))return r;if(typeof t=="number"&&Number.isFinite(t))return t*1e3},Et=e=>e.waitUntil?{waitUntil:t=>{e.waitUntil?.(t)}}:void 0,go=e=>{const t=e?.queue;return typeof t=="string"&&t.length>0?t:"unknown"},ue=async(e,t,r)=>{const n={"content-type":"application/json"},o=e.headers.get("authorization"),s=e.headers.get("cookie"),l=e.headers.get("x-d1-bookmark"),u=e.headers.get("x-lunora-mutation-id"),f=e.headers.get("x-lunora-client-id"),y=e.headers.get("x-lunora-client-seq");o&&(n.authorization=o),s&&(n.cookie=s),l&&(n["x-d1-bookmark"]=l),u&&(n["x-lunora-mutation-id"]=u),f&&(n["x-lunora-client-id"]=f),y&&(n["x-lunora-client-seq"]=y);const E=e.headers.get("cf-connecting-ip");if(E&&(n["x-lunora-client-ip"]=E),!r)return{claims:null,headers:n,identity:null,userId:null};const w=await r(e,t);if(!w||typeof w.userId!="string"||w.userId.length===0)return{claims:null,headers:n,identity:null,userId:null};n["x-lunora-userid"]=Rr(w.userId);const _=wo(w);_!==void 0&&(n["x-lunora-identity-exp"]=String(_));const{userId:h,...S}=w,R=Object.keys(S).length>0?S:null;return R&&(n["x-lunora-identity"]=Er(R)),{claims:R,headers:n,identity:w,userId:h}},yo=new Set(["concat","first","groupBy","max","min","rank","sum","topK"]),bo=e=>{if(e===void 0)return;if(!e||typeof e!="object")throw new i("RPC `fanOut` must be an object",{code:"BAD_REQUEST",status:400});const t=e;if(typeof t.table!="string"||t.table.length===0)throw new i("RPC `fanOut.table` must be a non-empty string",{code:"BAD_REQUEST",status:400});if(!t.merge||typeof t.merge!="object")throw new i("RPC `fanOut.merge` must be an object",{code:"BAD_REQUEST",status:400});const r=t.merge;if(typeof r.kind!="string"||!yo.has(r.kind))throw new i("RPC `fanOut.merge.kind` is not a recognized merge strategy",{code:"BAD_REQUEST",status:400});if(r.kind==="topK"){if(typeof r.k!="number"||!Number.isInteger(r.k)||r.k<0)throw new i("RPC `fanOut.merge.k` must be a non-negative integer",{code:"BAD_REQUEST",status:400});if(typeof r.by!="string"||r.by.length===0)throw new i("RPC `fanOut.merge.by` must be a non-empty string",{code:"BAD_REQUEST",status:400})}return t},_o=(e,t)=>{e?.LUNORA_DEBUG_RPC&&console.warn(`[lunora:rpc] ${t.fanOut?"fan-out":`shard=${t.shardKey??"(root)"}`} ${t.functionPath}`)},St=(e,t)=>{const r=t.functions?.[e.functionPath]?.x402;if(r){if(e.fanOut)throw new i("a paid (`.x402`) function cannot be fanned out",{code:"BAD_REQUEST",status:400});if(!t.x402Charge)throw new i(`function "${e.functionPath}" is marked paid (.x402) but no x402Charge gate is configured on the worker`,{code:"MISCONFIGURED",status:500});return r}},Ro=async e=>{const t=await vt(e);let r;try{r=JSON.parse(t)}catch{throw new i("RPC body must be valid JSON",{code:"BAD_REQUEST",status:400})}if(!r||typeof r!="object"||typeof r.functionPath!="string")throw new i("RPC envelope is missing `functionPath`",{code:"BAD_REQUEST",status:400});const n=r;if(n.args!==void 0&&It(n.args,"RPC"),n.shardKey!==void 0&&typeof n.shardKey!="string")throw new i("RPC `shardKey` must be a string",{code:"BAD_REQUEST",status:400});const o=r,s=bo(o.fanOut),l=o.args??{};if(s&&o.functionPath.startsWith("__lunora_relation__:")){const u=l.table;if(typeof u=="string"&&u!==s.table)throw new i("RPC `args.table` must match the authorized `fanOut.table` for a relation fan-out",{code:"BAD_REQUEST",status:400});l.table=s.table}return{args:l,fanOut:s,functionPath:o.functionPath,shardKey:o.shardKey}},oe=async(e,t,r)=>ge(e,t).fetch(r),Oe=new Map,Eo=5e3,So=4096,Oo=async(e,t)=>{const r=Date.now(),n=Oe.get(t);if(n!==void 0&&n.expiresMs>r)return n.relayCount;n!==void 0&&Oe.delete(t);let o=0;try{const s=await ge(e,t).fetch(new Request("https://shard.internal/_lunora/route"));if(s.ok){const l=(await s.json()).relayCount;typeof l=="number"&&l>0&&(o=Math.floor(l))}}catch{o=0}return At(Oe,So),Oe.set(t,{expiresMs:r+Eo,relayCount:o}),o},To=(e,t)=>{if(!(e===null||typeof e!="object"))return Object.entries(e).find(([,r])=>r===t)?.[0]},Te=(e,t,r)=>new Request("https://shard.internal/rpc",{body:JSON.stringify({args:t,functionPath:e}),headers:r,method:"POST"}),Ao=["x-lunora-userid","x-lunora-identity","x-lunora-identity-exp"],Ot=(e,t)=>{for(const r of Ao){e.delete(r);const n=t[r];n!==void 0&&e.set(r,n)}},ko=async(e,t,r)=>e.length===0||r.length===0?!1:Qe(await Nt(e,t),r),Tt=(e,t)=>{if(!t||t.length===0)return!1;const r=e.headers.get("authorization");if(!r)return!1;const[n,...o]=r.split(" ");return n?.toLowerCase()!=="bearer"?!1:Qe(t,o.join(" ").trim())},vo=async(e,t,r)=>{if(!t||t.length===0)return!1;const n=new URL(e.url).searchParams.get("token");return n===null?!1:await un(t,n)?!0:r?!1:Qe(t,n)},Io=(e,t)=>{if(t===null||typeof t!="object"&&typeof t!="function")return;const r=t;if(typeof r.prepare=="function"&&typeof r.batch=="function"&&typeof r.dump=="function")return Lr(`d1:${e}`,t);if(typeof r.list=="function"&&typeof r.head=="function"&&typeof r.createMultipartUpload=="function")return Ne(`r2:${e}`,!0);if(typeof r.send=="function"&&typeof r.sendBatch=="function"&&typeof r.get!="function")return Ne(`queue:${e}`,!0);if(typeof r.connectionString=="string")return Ne(`hyperdrive:${e}`,!0)},Lt=e=>{const t=Fa(e.trustInboundTraceContext),r=Ga(e.trustInboundTraceContext),n=e.defaultShardKey??"__root__",o=Fr(e.resolveIdentity,e.identity),s=et(e.shardDO,e.jurisdiction),l=e.schedulerDO===void 0?void 0:et(e.schedulerDO,e.jurisdiction);let u;const f=()=>e.adminToken??u;let y;const E=()=>e.requireEphemeralWsToken??y??!0,w=a=>{const c=a??{};if(y===void 0&&e.requireEphemeralWsToken===void 0){const d=c.LUNORA_REQUIRE_EPHEMERAL_WS_TOKEN;typeof d=="string"&&d.length>0&&(y=on(d,!0))}if(u!==void 0||e.adminToken!==void 0)return;const p=c.LUNORA_ADMIN_TOKEN;typeof p=="string"&&p.length>0&&(u=p)},_=new WeakSet,h=a=>Tt(a,f())||_.has(a),S=async(a,c)=>{const p=await ue(a,c,e.resolveIdentity);if(_.has(a)&&p.headers.authorization===void 0){const d=f();d!==void 0&&(p.headers.authorization=`Bearer ${d}`)}return p};let R=!1;const T=a=>{if(!e.allowUnauthenticatedShardAccess){const c=a==="fan-out"?"authorizeFanOut":"authorizeShard";throw new i(`${a} access is default-denied: configure \`${c}\` on the worker, or set \`allowUnauthenticatedShardAccess: true\` to explicitly allow unauthenticated ${a} access (relying solely on per-row RLS).`,{code:a==="fan-out"?"FORBIDDEN_FANOUT":"FORBIDDEN_SHARD",status:403})}R||(R=!0,console.warn([`[lunora] SECURITY: serving ${a} access with \`allowUnauthenticatedShardAccess: true\` and no \`authorizeShard\`/\`authorizeFanOut\` — `,"any caller (including unauthenticated ones) can target any shard / fan out across the table. ","This is safe only if every table is protected by per-row RLS. Configure `authorizeShard`/`authorizeFanOut` to gate it."].join("")))},A=async(a,c,p=!0)=>{if(e.authorizeShard){if(!await e.authorizeShard(a,c))throw new i("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else p&&c!==n&&T("shard")},U=Ea({defaultShard:n,forwardToShard:oe,isAdmin:h,queryCoordinator:e.queryCoordinator,resolveForwardContext:S,shardDO:s}),v=async(a,c,p,d,m)=>{await A(null,p,!1);const b={"content-type":"application/json","x-lunora-system":"1"};return m?.userId!==void 0&&m.userId.length>0&&(b["x-lunora-userid"]=m.userId),m?.identity!==void 0&&m.identity.length>0&&(b["x-lunora-identity"]=m.identity),d!==void 0&&d.length>0&&(b["x-lunora-mutation-id"]=d),oe(s,p,Te(a,c,b))},L=async(a,c,p,d)=>{const m=p?.[a];if(!m||typeof m.create!="function")throw new i(`${d} targets workflow binding "${a}", which is not bound on env`,{code:"CRON_JOB_FAILED",status:500});if(Jr(c))throw new i(`${d} params ${Hr}`,{code:"BAD_REQUEST",status:400});await m.create({params:c})},j=async(a,c)=>{if(a.workflow){await L(a.workflow,a.args??{},c,`cron job "${a.name}"`);return}if(a.functionPath===void 0)throw new i(`cron job "${a.name}" has neither a function target nor a workflow target`,{code:"CRON_JOB_FAILED",status:500});const p=await v(a.functionPath,a.args??{},a.shardKey??n);if(!p.ok)throw new i(`cron job "${a.name}" (${a.functionPath}) failed with shard status ${String(p.status)}`,{code:"CRON_JOB_FAILED",status:500})},V=async(a,c,p,d)=>{const m=e.cronJobs?.[a];if(m)for(const b of m)try{await j(b,c)}catch(D){p.push(d(D))}},N=async(a,c)=>{if(!h(a))throw new i("admin endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403});if(x(a,"POST","cron-jobs run"),!e.cronJobs)throw new i("cron-jobs run endpoint requires a `cronJobs` map on the worker",{code:"CRON_JOBS_NOT_CONFIGURED",status:400});const p=await X(a),d=typeof p.name=="string"?p.name:"";if(d==="")throw new i("cron-jobs run endpoint requires a job `name`",{code:"BAD_REQUEST",status:400});const m=Object.values(e.cronJobs).flat().find(b=>b.name===d);if(!m)throw new i(`no cron job named "${d}" is registered`,{code:"CRON_JOB_NOT_FOUND",status:404});return await j(m,c),Response.json({name:d,ran:!0},{status:200})},G=async a=>{const c=typeof a.pool=="string"&&a.pool.length>0?a.pool:void 0;if(!c||!l||typeof a.id!="string")return;const p=typeof a.instanceName=="string"&&a.instanceName.length>0?a.instanceName:"default";try{await ge(l,p).fetch(new Request("https://scheduler.internal/complete",{body:JSON.stringify({id:a.id,pool:c}),headers:{"content-type":"application/json"},method:"POST"}))}catch{}},Q=async(a,c)=>{x(a,"POST","Scheduler dispatch");const p=await vt(a),d=c??{},m=typeof d.LUNORA_SCHEDULER_SECRET=="string"?d.LUNORA_SCHEDULER_SECRET:void 0,b=e.adminToken??(typeof d.LUNORA_ADMIN_TOKEN=="string"?d.LUNORA_ADMIN_TOKEN:void 0),D=a.headers.get("x-lunora-scheduler-signature");let g=!1;if(D&&m?g=await ko(m,p,D):b&&(g=Tt(a,b)),!g)throw new i("Scheduler dispatch requires a valid signature or admin bearer",{code:"FORBIDDEN",status:403});let O;try{O=JSON.parse(p)}catch{throw new i("Scheduler dispatch body must be valid JSON",{code:"BAD_REQUEST",status:400})}const k=O??{},q=k.args??{};if(typeof k.workflow=="string"&&k.workflow.length>0)return await L(k.workflow,q,c,"scheduled workflow"),Response.json({ok:!0},{status:200});if(typeof k.functionPath!="string"||k.functionPath.length===0)throw new i("Scheduler dispatch is missing `functionPath`",{code:"BAD_REQUEST",status:400});const C=typeof k.shardKey=="string"&&k.shardKey.length>0?k.shardKey:n,B=typeof k.id=="string"&&k.id.length>0?k.id:void 0,Z=uo(a),ee=await v(k.functionPath,q,C,B,Z);return await G(k),ee},$=a=>{if(!h(a))throw new i("admin endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403})},K=(a,c,p)=>{if($(a),c===void 0)throw new i(p.message,{code:p.code,status:400});return c},Y=fn({assertAdmin:$,getReader:()=>e.authAuditReader}),J=async(a,c)=>{$(a);const p=e.notifySubscriptionStore;if(p===void 0)return Response.json({subscriptions:[]},{headers:{"content-type":"application/json"},status:200});const d=c?.kind,m=c?.userId,b=c?.limit,D=d==="fcm"||d==="web-push"?d:void 0,g=typeof m=="string"&&m!==""?m:void 0,O=typeof b=="number"&&Number.isFinite(b)?Math.trunc(b):0,k=O>0?Math.min(O,1e3):1e3,q=(await p.list({kind:D,limit:k,userId:g})).filter(C=>D!==void 0&&C.kind!==D?!1:g===void 0||(C.userId??null)===g).map(({keys:C,token:B,...Z})=>Z);return Response.json({subscriptions:q},{headers:{"content-type":"application/json"},status:200})},ne=async(a,c)=>{if(!c.fanOut){if(c.functionPath===pn)return Y(a,c.args??{});if(c.functionPath===po)return J(a,c.args)}},he=Fn({applyGlobals:e.applyGlobals,assertAdmin:$,exportCursorStore:e.exportCursorStore,exportSinks:e.exportSinks,knownTables:()=>[],queryCoordinator:e.queryCoordinator,requireAdminOption:K,resolveForwardContext:S,shardDO:s,streamExportRows:(a,c,p,d)=>$t(e,a,c,p,d,s),streamingImport:(a,c)=>zn(a,e,c,s),syncGlobals:e.syncGlobals}),ae=(a,c)=>{const p=a.searchParams.get(c);return p===null||p===""?void 0:p},pe=a=>{const c=new URL(a.url),p=c.searchParams.get("limit"),d=c.searchParams.get("offset"),m=p===null?void 0:Number.parseInt(p,10),b=d===null?void 0:Number.parseInt(d,10);return{limit:m!==void 0&&Number.isFinite(m)&&m>=0?m:void 0,offset:b!==void 0&&Number.isFinite(b)&&b>=0?b:void 0}},_e=()=>{if(l===void 0)throw new i("scheduled endpoints require a `schedulerDO` namespace on the worker",{code:"SCHEDULER_NOT_CONFIGURED",status:400});return l},ke=Ka({checkWsAdmin:async a=>h(a)||vo(a,f(),E()),requireSchedulerNamespace:_e,resolveSchedulerStub:a=>($(a),ge(_e(),e.schedulerInstanceName??"default")),schedulerInstanceName:e.schedulerInstanceName??"default"}),se=Xa({assertAdmin:$,resolveWorkflowsClient:e.workflowsClient??(()=>{})}),Ft=Br({assertAdmin:$,parsePaging:pe,queryParameter:ae,readBodyBytes:Dr,requireAdminOption:K,storage:{storageBuckets:e.storageBuckets,storageDelete:e.storageDelete,storageDownload:e.storageDownload,storageList:e.storageList,storageSignedUrl:e.storageSignedUrl,storageUpload:e.storageUpload}}),Gt=kn({options:e,readJsonBody:X,requireAdminOption:K}),Qt=za({readJsonBody:X,requireAdminOption:K,vectorIntrospector:e.vectorIntrospector}),Mt=ia({kvIntrospector:e.kvIntrospector,readJsonBody:X,requireAdminOption:K}),zt=Gr({logArchive:e.logArchive,readJsonBody:X,requireAdminOption:K}),Wt=aa({assertAdmin:$,options:{cronJobs:e.cronJobs,functions:e.functions,globalIntrospector:e.globalIntrospector,openApiSpec:e.openApiSpec,openRpcSpec:e.openRpcSpec},parsePaging:pe,queryParameter:ae,requireAdminOption:K}),Jt=a=>{const c=[],p=s??a?.SHARD;if(p!==void 0&&c.push(Kr("durable-object:default",p,n)),e.health?.disableBindingProbes!==!0)for(const[d,m]of Object.entries(a??{})){const b=Io(d,m);b!==void 0&&c.push(b)}for(const d of e.health?.probes??[])c.push(d);return c},Ht=jr({appName:e.health?.appName,appVersion:e.health?.appVersion,auth:e.health?.auth??"public",cacheTtlMs:e.health?.cacheTtlMs,isAdmin:h,resolveProbes:Jt}),Vt=a=>{const c=e.schedulerInstanceName??"default",p=()=>ge(a,c),d=async(g,O)=>{const k=await p().fetch(new Request(`https://scheduler.internal${g}`,O));if(!k.ok)throw new i(`ctx.scheduler: SchedulerDO ${g} failed (${String(k.status)}): ${await k.text()}`,{code:"INTERNAL",status:500});return await k.json()},m=async(g,O)=>await d(g,{body:JSON.stringify(O),headers:{"content-type":"application/json"},method:"POST"}),b=g=>{const O=g;if(O==null)throw new i("ctx.scheduler: target is required — pass a reference from the generated `internal` / `workflows` / `agents`",{code:"BAD_REQUEST",status:400});if(typeof O.binding=="string"&&O.binding.length>0)return{workflow:O.binding};if(typeof O.__lunoraRef=="string")return{functionPath:O.__lunoraRef};throw new i("ctx.scheduler: expected a reference from the generated `internal` / `workflows` / `agents` — a bare function-path string is refused here, because an HTTP action can be reached unauthenticated",{code:"BAD_REQUEST",status:400})},D=async(g,O,k={})=>{const{id:q}=await m("/schedule",{args:k,scheduledFor:g,...b(O)});return q};return{cancel:async g=>await m("/cancel",{id:g}),get:async g=>await d(`/get?id=${encodeURIComponent(g)}`,{method:"GET"}),list:async()=>await d("/list",{method:"GET"}),runAfter:async(g,O,k)=>{if(!Number.isFinite(g)||g<0)throw new i("ctx.scheduler.runAfter: `delayMs` must be a non-negative finite number",{code:"BAD_REQUEST",status:400});return await D(Date.now()+g,O,k)},runAt:async(g,O,k)=>{if(!Number.isFinite(g))throw new i("ctx.scheduler.runAt: `timestampMs` must be a finite epoch-millisecond number",{code:"BAD_REQUEST",status:400});return await D(g,O,k)}}},Yt=async(a,c,p)=>{const{claims:d,headers:m,userId:b}=await ue(a,c,o),D=async(g,O={})=>{const k=g.__lunoraRef;if(typeof k!="string")throw new i("ctx.run*: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});const q=Te(k,O,{...m,"x-lunora-system":"1"}),C=await oe(s,n,q),B=await C.json();if(B.error)throw new i(B.error.message??"shard RPC failed",{code:B.error.code??"INTERNAL",status:C.status});return B.result};return{auth:{getIdentity:()=>Promise.resolve(d),userId:b},cache:p.cache,fetch:globalThis.fetch.bind(globalThis),runAction:D,runMutation:D,runQuery:D,...l===void 0?{}:{scheduler:Vt(l)},...e.storage===void 0?{}:{storage:Wr(e.storage(c))}}},Xt=async(a,c,p)=>{if(!e.httpRouter)return;const d=await Yt(a,c,p);try{return await e.httpRouter.fetch(a,{...c,__lunoraCtx:d},p)}catch(m){return console.error("[lunora] httpRouter (SSR) handler threw:",m),new Response("Internal Server Error",{status:500})}},Zt=async(a,c,p)=>{if(a.headers.get("Upgrade")!=="websocket")throw new i("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});const d=rt(a,ie);if(d)return d;const m=p.searchParams.get("shard")??n,{headers:b,identity:D}=await ue(a,c,o);await A(D,m);const g=new Headers(a.headers),O=[...g.keys()];for(const q of O)q.startsWith("x-lunora-")&&g.delete(q);Ot(g,b);const k=To(c,e.shardDO);if(k!==void 0){g.set("x-lunora-shard-binding",k);const q=await Oo(s,m);if(q>0){const C=rn(m,Math.floor(Math.random()*q));return oe(s,C,new Request(a,{headers:g}))}}return oe(s,m,new Request(a,{headers:g}))},er=async(a,c,p)=>{const{voiceAgents:d}=e;if(d===void 0)return new Response("Not found",{status:404});if(a.headers.get("Upgrade")!=="websocket")return new Response("Expected a WebSocket upgrade",{headers:{allow:"GET"},status:426});const m=rt(a,ie);if(m)return m;let b;try{b=decodeURIComponent(p.pathname.slice(Rt.length))}catch{return new Response("Unknown voice agent",{status:404})}const D=Object.hasOwn(d,b)?d[b]:void 0;if(D===void 0)return new Response("Unknown voice agent",{status:404});const g=p.searchParams.get("threadKey");if(g===null||g.length===0)return new Response("Missing threadKey",{status:400});const{headers:O,identity:k}=await ue(a,c,o);if(e.authorizeShard){if(!await e.authorizeShard(k,g))return new Response("Forbidden",{status:403})}else T("shard");const q=new Headers(a.headers);for(const C of q.keys())C.startsWith("x-lunora-")&&q.delete(C);return Ot(q,O),oe(D,g,new Request(a,{headers:q}))},tr=async(a,c,p)=>{if(e.authorizeFanOut){if(!await e.authorizeFanOut(p,a.table,c))throw new i("Forbidden fan-out",{code:"FORBIDDEN_FANOUT",status:403});return}if(c.startsWith("__lunora_relation__:"))throw new i("reverse cross-backend relation reads (`__lunora_relation__:*`) require `authorizeFanOut` to be configured on the worker",{code:"FORBIDDEN_FANOUT",status:403});if(e.authorizeShard)throw new i("Fan-out requires `authorizeFanOut` to be configured on the worker when `authorizeShard` is set",{code:"FORBIDDEN_FANOUT",status:403});T("fan-out")},Re=async(a,c)=>{if(!(!a.fanOut&&a.functionPath.startsWith("__lunora_admin__:"))){if(a.fanOut){await tr(a.fanOut,a.functionPath,c);return}await A(c,a.shardKey??n)}},ve=async(a,c,p,d,m,b)=>{const D=Date.now(),{observability:g,sampling:O}=e,k=Le(a),{decision:q,ignoredUpstream:C,trace:B}=Da(a,{...O===void 0?{}:{sampling:O},trustInbound:t(a)});C&&r();const Z={...m,"x-lunora-sample-errors":q.keepErrors?"1":"0"};Pa(B,Z);const ee=Te(c,p,Z);try{const F=await oe(s,d,ee);return ce(g,{...k,..._t(B),durationMs:Date.now()-D,functionPath:c,ok:F.ok,shardKey:d,...F.ok?{}:{error:{code:"SHARD_ERROR",message:`shard returned ${String(F.status)}`,status:F.status}}},b,void 0,{isTraced:B.sampled,keepErrors:q.keepErrors}),F}catch(F){throw ce(g,{...k,..._t(B),...Se(c,Date.now()-D,F,{shardKey:d})},b,void 0,{isTraced:B.sampled,keepErrors:q.keepErrors}),F}},rr=a=>{if(a.fanOut&&a.shardKey)throw new i("RPC envelope cannot set both `shardKey` and `fanOut`",{code:"BAD_REQUEST",status:400});if(!a.fanOut&&a.functionPath.startsWith("__lunora_relation__:"))throw new i("`__lunora_relation__:*` is a fan-out-only reserved RPC and cannot be dispatched to a single shard",{code:"FORBIDDEN",status:403});if(a.fanOut&&!e.queryCoordinator)throw new i("RPC envelope set `fanOut` but no `queryCoordinator` is configured on the worker",{code:"BAD_REQUEST",status:400})},nr=async(a,c,p)=>{x(a,"POST","RPC");const d=await Ro(a);_o(c,d),rr(d);const m=await ne(a,d);if(m!==void 0)return m;const{headers:b,identity:D}=await ue(a,c,o);await Re(d,D);const g=St(d,e);{const O=Date.now(),{observability:k}=e,q=Le(a),C=Ee(c,a,p&&(ee=>p.waitUntil?.(ee)));if(d.fanOut){const ee=e.queryCoordinator;if(!ee)throw new i("RPC envelope set `fanOut` but no `queryCoordinator` is configured on the worker",{code:"BAD_REQUEST",status:400});try{const F=await ee.fanOut(s,{args:d.args??{},fanOut:d.fanOut,functionPath:d.functionPath,headers:b});return ce(k,{durationMs:Date.now()-O,fanOut:{failed:F.failed,shards:F.ok+F.failed,table:d.fanOut.table},functionPath:d.functionPath,...q,ok:!0},C),Response.json(F,{headers:{"content-type":"application/json"},status:200})}catch(F){throw ce(k,{...Se(d.functionPath,Date.now()-O,F,{fanOut:{table:d.fanOut.table}}),...q},C),F}}const B=d.shardKey??n,Z=()=>ve(a,d.functionPath,d.args??{},B,b,C);return g&&e.x402Charge?e.x402Charge(a,{functionPath:d.functionPath,price:g.price},Z,bt(p)):Z()}},ar=async(a,c,p)=>{x(a,"POST","RPC batch");const d=await X(a),{calls:m}=d;if(!Array.isArray(m))throw new i("RPC batch `calls` must be an array",{code:"BAD_REQUEST",status:400});const{headers:b,identity:D}=await ue(a,c,o),g=In(m,n);for(const M of g.values())for(const z of M)if(e.functions?.[z.functionPath]?.x402)throw new i(`paid (\`.x402\`) function "${z.functionPath}" cannot be called in a batch; dispatch it individually over ${yt}`,{code:"BAD_REQUEST",status:400});await Promise.all([...g.entries()].flatMap(([M,z])=>z.map(re=>Re({functionPath:re.functionPath,shardKey:M},D))));const{observability:O}=e,k=Ee(c,a,p&&(M=>p.waitUntil?.(M))),q=Le(a),C=[],B=[],Z=(M,z,re,de)=>({body:{error:{code:re,message:de}},id:M.id,status:z}),ee=(M,z,re,de,fe)=>{for(const W of M)ce(O,fe(W),k),C.push(Z(W,z,re,de))},F=(M,z,re,de,fe)=>{for(const W of M){const me=de.get(W.id)??fe,ye=me<400;ce(O,{durationMs:re,functionPath:W.functionPath,...q,ok:ye,shardKey:z,...ye?{}:{error:{code:"SHARD_ERROR",message:`batched call returned ${String(me)}`,status:me}}},k)}};await Promise.all([...g.entries()].map(async([M,z])=>{const re=new Headers(b);re.set("content-type","application/json");const de=new Request("https://shard.internal/rpc-batch",{body:JSON.stringify({calls:z}),headers:re,method:"POST"}),fe=Date.now();let W;try{W=await oe(s,M,de)}catch(H){const Ue=Date.now()-fe,{body:Ye}=br(H,{fallbackCode:"SHARD_UNAVAILABLE",redactedMessage:"shard unavailable"});ee(z,502,Ye.code,Ye.message,gr=>({...Se(gr.functionPath,Ue,H,{shardKey:M}),...q}));return}const me=Date.now()-fe,ye=W.headers.get("x-d1-bookmark");ye&&B.push(ye);let De;try{De=await W.json()}catch{const H=`shard batch returned a non-JSON response (${String(W.status)})`;ee(z,W.status,"SHARD_ERROR",H,Ue=>({durationMs:me,error:{code:"SHARD_ERROR",message:H,status:W.status},functionPath:Ue.functionPath,...q,ok:!1,shardKey:M}));return}const Pe=Array.isArray(De.results)?De.results:[],mr=new Map(Pe.map(H=>[H.id,H.status??W.status])),wr=new Set(Pe.map(H=>H.id));F(z,M,me,mr,W.status),C.push(...Pe);for(const H of z)wr.has(H.id)||C.push(Z(H,W.status,"SHARD_ERROR",`shard batch omitted result for call ${String(H.id)}`))}));const He={"content-type":"application/json"},[Ve]=B;return B.length===1&&Ve!==void 0&&(He["x-d1-bookmark"]=Ve),Response.json({results:C},{headers:He,status:200})},or=async(a,c,p,d={},m={})=>{try{const b=p.__lunoraRef;if(typeof b!="string")throw new i("serverQuery: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});const{headers:D,identity:g}=await ue(a,c,o);await Re({functionPath:b,shardKey:m.shardKey},g);const O=m.shardKey??n,k=Ee(c,a,m.waitUntil);return await ve(a,b,d,O,D,k)}catch(b){return Xe(b)}},We=async(a,c,p)=>{const{observability:d}=e,m=Date.now(),b=Ae(16),D=Ae(8),g=Et(c);try{const O=await p();return ce(d,{durationMs:Date.now()-m,functionPath:a,ok:!0,spanId:D,traceId:b},g),O}catch(O){throw ce(d,{...Se(a,Date.now()-m,O,{}),spanId:D,traceId:b},g),O}finally{Ze(d,g)}},sr=async(a,c,p)=>{w(c);const d=[],m=g=>g instanceof Error?g:new Error(String(g)),b=e.crons?.[a.cron];if(b)try{await b(a,c,p)}catch(g){d.push(m(g))}if(await V(a.cron,c,d,m),e.backupStore&&e.backupCron!==void 0&&e.backupCron===a.cron)try{await Sn(e,s,f(),a)}catch(g){d.push(m(g))}const[D]=d;if(d.length===1&&D)throw D;if(d.length>1)throw new AggregateError(d,`scheduled("${a.cron}") had ${String(d.length)} failure(s)`)},ir=async(a,c)=>{try{const p=a??{},d=e.adminToken??(typeof p.LUNORA_ADMIN_TOKEN=="string"?p.LUNORA_ADMIN_TOKEN:void 0);if(!d||d.length===0)return;await oe(s,n,Te(ho,{outcome:c},{authorization:`Bearer ${d}`,"content-type":"application/json"}))}catch{}},cr=async(a,c,p,d)=>{if(!e.authHandler)return;const m=await e.authHandler(a);if(!m)return;const b=e.authBasePath??lo;return mo(p.pathname,b)&&d.waitUntil?.(ir(c,m.status>=400?"fail":"ok")),m},ur=async({args:a,env:c,functionPath:p,request:d,shardKey:m,waitUntil:b})=>{It(a,"REST");const D={functionPath:p,...m===void 0?{}:{shardKey:m}},{headers:g,identity:O}=await ue(d,c,o);await Re(D,O);const k=m??n,q=Ee(c,d,b),C=()=>ve(d,p,a,k,g,q),B=St(D,e);return B&&e.x402Charge?e.x402Charge(d,{functionPath:p,price:B.price},C,bt({waitUntil:b})):C()},dr=Ir({functions:e.functions??{},invoke:ur,readJsonBody:X,...e.restRateLimit?{rateLimit:e.restRateLimit}:{}}),Ie=e.routes!==void 0&&Object.keys(e.routes).length>0?e.routes:void 0,lr={[io]:a=>a.method!=="GET"&&a.method!=="HEAD"?new Response(void 0,{headers:{allow:"GET, HEAD"},status:405}):Response.json({ok:!0},{headers:{"cache-control":"no-store"}}),[to]:(a,c,p)=>Zt(a,c,p),[yt]:(a,c,p,d)=>nr(a,c,d),[eo]:(a,c,p,d)=>ar(a,c,d),[ro]:(a,c)=>Q(a,c),[no]:(a,c)=>N(a,c),[ao]:async a=>{x(a,"POST","ws-token"),$(a);const c=f();if(c===void 0)throw new i("ws-token minting requires a configured admin token",{code:"ADMIN_TOKEN_NOT_CONFIGURED",status:400});const p=await cn(c);return Response.json(p,{headers:{"cache-control":"no-store"}})},...U,...he,...ke,...se,...Ft,...Gt,...Qt,...Mt,...zt,...Wt,...Ht,...dr,...hn({assertAdmin:$,getAuthAdmin:()=>e.authAdmin,parsePaging:pe,queryParameter:ae,readJsonBody:X})};let ie=tt(e.security),Je=!1;const hr=a=>{Je||(Je=!0,ie=tt(e.security,a??{}))},pr=async(a,c)=>{if(!(e.adminGate===void 0||!co(c)))try{await e.adminGate(a)&&_.add(a)}catch{}},fr=async(a,c,p)=>{const d=new URL(a.url);if(a.method==="POST"||a.method==="PUT"){const g=Number(a.headers.get("content-length")??""),O=Za[d.pathname]??kt;if(Number.isFinite(g)&&g>O)throw new i("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413})}const m=await cr(a,c,d,p);if(m)return m;if(Ie){const g=`${a.method} ${d.pathname}`,O=Ie[g]??Ie[d.pathname];if(O)return O(a,c,p)}const b=lr[d.pathname];return b?(await pr(a,d.pathname),b(a,c,d,p)):e.voiceAgents!==void 0&&d.pathname.startsWith(Rt)?er(a,c,d):await Xt(a,c,p)||new Response("Not found",{status:404})};return{async fetch(a,c,p){e.passThroughOnException&&p.passThroughOnException?.(),hr(c),w(c);const d=Mr(a,ie);if(d)return d;const m=zr(a,ie);if(m)return qe(m,a,ie);try{const b=await fr(a,c,p);return qe(b,a,ie)}catch(b){return qe(Xe(b),a,ie)}finally{Ze(e.observability,Et(p))}},async queue(a,c,p){await We(`queue:${go(a)}`,p,async()=>{await e.queue?.(a,c,p)})},async scheduled(a,c,p){await We(`cron:${a.cron}`,p,async()=>{await sr(a,c,p)})},serverQuery:or}},Do=e=>Lt(e),Po=e=>typeof e=="function"?{fetch:e}:e,Uo=e=>!!(e.crons??e.cronJobs??e.backupCron),Yo=(e,t)=>{const r=Po(e),n=typeof e=="object"&&typeof e.scheduled=="function"?e.scheduled:void 0,o=l=>{const u=Do({...l,httpRouter:r});return n!==void 0&&!Uo(l)?{...u,scheduled:async(f,y,E)=>{await n(f,y,E)}}:u};if(typeof t!="function")return o(t);const s=t;return{fetch:(l,u,f)=>o(s(u)).fetch(l,u,f),queue:(l,u,f)=>o(s(u)).queue?.(l,u,f)??Promise.resolve(),scheduled:(l,u,f)=>o(s(u)).scheduled(l,u,f),serverQuery:(l,u,f,y,E)=>o(s(u)).serverQuery(l,u,f,y,E)}},No=(e,t)=>{if(typeof e=="function")return e(t);const r=e.shardDO??t?.SHARD;if(!r)throw new i("@lunora/runtime: no shard Durable Object namespace found. Bind `SHARD` in wrangler.jsonc, or pass `createLunoraHandler({ shardDO: env.MY_SHARD })`.");return{...e,shardDO:r}},Xo=(e={})=>(t,r,n)=>Lt(No(e,r)).fetch(t,r,n??_r),Zo=e=>e;export{pn as GET_AUTH_AUDIT_LOG_OP,_r as NOOP_EXECUTION_CONTEXT,rs as composeIdentityResolvers,Do as composeWorker,Xo as createLunoraHandler,Lt as createWorker,Zo as defineRpcEnvelope,Oo as probeRelayCount,No as resolveLunoraOptions,ns as routeIdentityResolvers,Yo as withFrameworkWorker};
@@ -1 +0,0 @@
1
- import{LunoraError as m}from"./LunoraError-ByasbDmd.mjs";const y="default-src 'none'; frame-ancestors 'none'; base-uri 'none'; form-action 'none'",O=e=>{const r=["base-uri 'none'","object-src 'none'"];return e==="DENY"?r.push("frame-ancestors 'none'"):e==="SAMEORIGIN"&&r.push("frame-ancestors 'self'"),r.join("; ")},v="accelerometer=(), autoplay=(), camera=(), display-capture=(), geolocation=(), gyroscope=(), magnetometer=(), microphone=(), payment=(), usb=()",d=["Authorization","Content-Type","X-D1-Bookmark","X-Lunora-Mutation-Id"],u=["DELETE","GET","HEAD","PATCH","POST","PUT"],b=31536e3,A=new Set(["GET","HEAD","OPTIONS"]),L=e=>{if(e===!1)return;const r=e===void 0||e===!0?{}:e,s=r.maxAge??b,o=r.includeSubDomains??!0;return`max-age=${String(s)}${o?"; includeSubDomains":""}${r.preload?"; preload":""}`},R=(e,r)=>{if(e!==!1)return typeof e=="string"?{htmlValue:e,value:e}:{htmlValue:r,value:y}},S=e=>{if(e===!1)return{coop:void 0,csp:void 0,enabled:!1,frameOptions:void 0,hsts:void 0,permissionsPolicy:void 0,referrerPolicy:void 0};const r=e===void 0||e===!0?{}:e,s=r.frameOptions===!1?void 0:r.frameOptions??"SAMEORIGIN";return{coop:"same-origin",csp:R(r.csp,O(s)),enabled:!0,frameOptions:s,hsts:L(r.hsts),permissionsPolicy:r.permissionsPolicy===!1?void 0:r.permissionsPolicy??v,referrerPolicy:r.referrerPolicy===!1?void 0:r.referrerPolicy??"strict-origin-when-cross-origin"}},E=e=>{const r={allowCredentials:!1,allowedHeaders:d,allowedMethods:u,enabled:!1,isAllowed:()=>!1,isExplicitlyAllowed:()=>!1,maxAge:600};if(e===void 0||e===!1)return r;const s=e.allowCredentials??!1,o=e.allowedOrigins;let t,i;if(typeof o=="function")t=o,i=o,console.warn(`@lunora/runtime: security.cors uses a custom \`allowedOrigins\` predicate. It is trusted by the CSRF and WebSocket origin checks${s?" AND reflects matching origins with credentials (`allowCredentials: true`)":""} — ensure it matches ONLY trusted origins by exact equality; an over-broad predicate (e.g. \`() => true\`, or \`endsWith\`/\`includes\` checks) defeats the allowlist.`);else{const l=o;if(l.includes("*")&&s)throw new m('@lunora/runtime: security.cors cannot combine a wildcard origin ("*") with allowCredentials: true — browsers reject it and it defeats the allowlist.');t=n=>l.includes("*")||l.includes(n),i=n=>l.includes(n)}return{allowCredentials:s,allowedHeaders:e.allowedHeaders??d,allowedMethods:e.allowedMethods??u,enabled:!0,isAllowed:t,isExplicitlyAllowed:i,maxAge:e.maxAge??600}},C=e=>{if(e===!1)return{allowLoopback:!1,enabled:!1,trustedOrigins:[]};const r=e===void 0||e===!0?{}:e;return{allowLoopback:r.allowLoopback??!0,enabled:!0,trustedOrigins:r.trustedOrigins??[]}},x=new Set(["0","disabled","false","no","off"]),I=new Set(["1","enabled","on","true","yes"]),f=e=>typeof e=="string"&&x.has(e.trim().toLowerCase()),P=e=>typeof e=="string"&&I.has(e.trim().toLowerCase()),k=e=>{const r=e?.LUNORA_ALLOWED_ORIGINS;if(typeof r!="string")return;const s=r.split(",").map(o=>o.trim()).filter(o=>o.length>0);return s.length===0?void 0:{allowCredentials:!s.includes("*")&&P(e?.LUNORA_CORS_ALLOW_CREDENTIALS),allowedOrigins:s}},H=(e,r)=>{const s=e?.headers??(f(r?.LUNORA_SECURITY_HEADERS)?!1:void 0),o=e?.csrf??(f(r?.LUNORA_SECURITY_CSRF)?!1:void 0),t=e?.cors??k(r);return{cors:E(t),csrf:C(o),headers:S(s)}},N=new Set(["127.0.0.1","::1","[::1]","localhost"]),p=e=>{try{return N.has(new URL(e).hostname)}catch{return!1}},c=e=>{if(e)try{return new URL(e).origin}catch{return}},h=(e,r,s)=>e===r||s.csrf.trustedOrigins.includes(e)||s.csrf.allowLoopback&&p(r)&&p(e)?!0:s.cors.enabled&&s.cors.isExplicitlyAllowed(e),g=(e,r,s)=>Response.json({error:{code:"FORBIDDEN_ORIGIN",expectedOrigin:s,message:`${e} rejected: Origin ${r===void 0?"was missing":`"${r}"`} is not trusted (this worker serves "${s}"). Add it to \`security.csrf.trustedOrigins\` (or LUNORA_ALLOWED_ORIGINS) if it is yours. Behind a dev proxy this usually means the proxy rewrote the host: keep both ends on loopback, or list the dev-server origin.`,receivedOrigin:r}},{headers:{"content-type":"application/json"},status:403}),j=(e,r)=>{if(!r.csrf.enabled||A.has(e.method)||!e.headers.get("cookie"))return;const s=new URL(e.url).origin,o=c(e.headers.get("origin"))??c(e.headers.get("referer"));if(!(o!==void 0&&h(o,s,r)))return g("cross-origin state-changing request",o,s)},$=(e,r)=>{if(!r.csrf.enabled||!e.headers.get("cookie"))return;const s=new URL(e.url).origin,o=c(e.headers.get("origin"));if(!(o!==void 0&&h(o,s,r)))return g("cross-origin websocket upgrade",o,s)},w=(e,r)=>{const s=new Headers;return s.set("access-control-allow-origin",e),s.append("vary","Origin"),r.allowCredentials&&s.set("access-control-allow-credentials","true"),s},M=(e,r)=>{if(!r.cors.enabled||e.method!=="OPTIONS")return;const s=e.headers.get("origin");if(!s||!e.headers.get("access-control-request-method")||!r.cors.isAllowed(s))return;const o=w(s,r.cors),t=e.headers.get("access-control-request-headers");o.set("access-control-allow-methods",r.cors.allowedMethods.join(", "));let i;if(t===null)i=r.cors.allowedHeaders.join(", ");else{const l=new Set(r.cors.allowedHeaders.map(n=>n.toLowerCase()));i=t.split(",").map(n=>n.trim()).filter(n=>n.length>0&&l.has(n.toLowerCase())).join(", ")}return o.set("access-control-allow-headers",i),o.set("access-control-max-age",String(r.cors.maxAge)),new Response(null,{headers:o,status:204})},D=e=>(e.headers.get("content-type")??"").toLowerCase().includes("text/html"),a=(e,r,s)=>{e.has(r)||e.set(r,s)},T=(e,r,s,o)=>{if(o.hsts!==void 0&&new URL(r.url).protocol==="https:"&&a(e,"strict-transport-security",o.hsts),a(e,"x-content-type-options","nosniff"),o.frameOptions!==void 0&&a(e,"x-frame-options",o.frameOptions),o.referrerPolicy!==void 0&&a(e,"referrer-policy",o.referrerPolicy),o.permissionsPolicy!==void 0&&a(e,"permissions-policy",o.permissionsPolicy),o.coop!==void 0&&a(e,"cross-origin-opener-policy",o.coop),o.csp!==void 0){const t=D(s)?o.csp.htmlValue:o.csp.value;t!==void 0&&a(e,"content-security-policy",t)}},U=(e,r,s)=>{const o=r.headers.get("origin");if(!(!o||!s.isAllowed(o)))for(const[t,i]of w(o,s).entries())t==="vary"?e.append("vary",i):a(e,t,i)},G=(e,r,s)=>{if(e.status===101||e.webSocket)return e;const o=new Headers(e.headers);return s.headers.enabled&&T(o,r,e,s.headers),s.cors.enabled&&U(o,r,s.cors),new Response(e.body,{headers:o,status:e.status,statusText:e.statusText})};export{G as decorateResponse,j as enforceOrigin,$ as enforceWebSocketOrigin,M as handleCorsPreflight,H as resolveSecurity};