@lunora/runtime 1.0.0-alpha.54 → 1.0.0-alpha.56
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 +42 -19
- package/dist/index.d.ts +42 -19
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/composeWorker-MnGFIJTe.mjs +6 -0
- package/dist/packem_shared/createCrossShardRelationCapabilities-CQfrCIWR.mjs +1 -0
- package/package.json +3 -3
- package/dist/packem_shared/composeWorker--WeDfW17.mjs +0 -6
- package/dist/packem_shared/createCrossShardRelationCapabilities-CdYCKy9v.mjs +0 -1
package/dist/index.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { RankDirection, RankPageRow, DatabaseWriterLike } from '@lunora/shard-engine';
|
|
1
|
+
import { RankDirection, RankPageRow, DatabaseWriterLike, CrossShardReadArgs, QueryPage } from '@lunora/shard-engine';
|
|
2
2
|
export type { RankDirection as RankPageDirection, RankPageRowKey as RankPageKey, RankPageRow, ShardRankPageResult } from '@lunora/shard-engine';
|
|
3
3
|
import { R2SqlClient } from '@lunora/bindings/r2sql';
|
|
4
4
|
import { WorkflowsRestClient } from '@lunora/workflow';
|
|
@@ -2769,6 +2769,13 @@ interface StorageObject {
|
|
|
2769
2769
|
contentType?: string;
|
|
2770
2770
|
};
|
|
2771
2771
|
key: string;
|
|
2772
|
+
/**
|
|
2773
|
+
* Lowercase-hex SHA-256, when the object was written with one. R2 reports a
|
|
2774
|
+
* checksum only if the writer supplied it, so this is absent for objects
|
|
2775
|
+
* uploaded before that was wired up — consumers must treat "absent" as "not
|
|
2776
|
+
* reported", never as "does not match".
|
|
2777
|
+
*/
|
|
2778
|
+
sha256?: string;
|
|
2772
2779
|
size: number;
|
|
2773
2780
|
}
|
|
2774
2781
|
/**
|
|
@@ -2881,6 +2888,7 @@ type StorageDeleteFunction = (key: string, options?: {
|
|
|
2881
2888
|
type StorageUploadFunction = (key: string, body: ArrayBuffer, options?: {
|
|
2882
2889
|
bucket?: string;
|
|
2883
2890
|
contentType?: string;
|
|
2891
|
+
sha256?: string;
|
|
2884
2892
|
}) => Promise<{
|
|
2885
2893
|
etag?: string;
|
|
2886
2894
|
key: string;
|
|
@@ -3298,6 +3306,13 @@ interface WorkerOptions {
|
|
|
3298
3306
|
* every live shard for the table) and a per-shard gate is not
|
|
3299
3307
|
* sufficient to authorize it. Apps that need client-driven fan-out
|
|
3300
3308
|
* must opt in explicitly via this callback.
|
|
3309
|
+
*
|
|
3310
|
+
* SCOPE: this gate is TABLE-granular — it decides whether the caller may fan
|
|
3311
|
+
* this function out over this table at all, never which ROWS come back. Row
|
|
3312
|
+
* filtering is RLS's job and stays RLS's job on the fan-out path too: the
|
|
3313
|
+
* reserved `__lunora_relation__:read` hop carries the child's read policy as
|
|
3314
|
+
* data (`where` + `relationPolicies`) so each shard applies it. Do not read
|
|
3315
|
+
* an `authorizeFanOut: () => true` as "this caller may see every row".
|
|
3301
3316
|
*/
|
|
3302
3317
|
authorizeFanOut?: (identity: ResolvedIdentity | null, table: string, functionPath: string) => boolean | Promise<boolean>;
|
|
3303
3318
|
/**
|
|
@@ -3559,17 +3574,24 @@ interface WorkerOptions {
|
|
|
3559
3574
|
*/
|
|
3560
3575
|
queue?: QueueConsumerHandler;
|
|
3561
3576
|
/**
|
|
3562
|
-
* Enforce the ephemeral WS admin token:
|
|
3563
|
-
* the
|
|
3564
|
-
*
|
|
3565
|
-
*
|
|
3566
|
-
*
|
|
3567
|
-
*
|
|
3568
|
-
*
|
|
3569
|
-
*
|
|
3570
|
-
*
|
|
3571
|
-
*
|
|
3572
|
-
*
|
|
3577
|
+
* Enforce the ephemeral WS admin token: the worker's WS admin gate rejects
|
|
3578
|
+
* the raw master admin token in the `?token=` query parameter — only a
|
|
3579
|
+
* short-lived sub-token minted by `POST /_lunora/admin/ws-token` (or the
|
|
3580
|
+
* master token in the `Authorization` HEADER, which never leaks via URLs)
|
|
3581
|
+
* authorizes.
|
|
3582
|
+
*
|
|
3583
|
+
* **On by default**: a query string lands in access logs, browser history and
|
|
3584
|
+
* `Referer`, so the master admin credential must not ride one. The studio
|
|
3585
|
+
* mints and sends the ephemeral token already.
|
|
3586
|
+
*
|
|
3587
|
+
* To opt back out for a legacy client that still puts the master token in a
|
|
3588
|
+
* URL, set **`env.LUNORA_REQUIRE_EPHEMERAL_WS_TOKEN`** to
|
|
3589
|
+
* `0`/`false`/`off`/`no`/`disabled`. That is the knob to use: it is read
|
|
3590
|
+
* independently by the worker AND by the shard/relay Durable Objects, so the
|
|
3591
|
+
* whole deployment agrees. This code-level option only governs the WORKER's
|
|
3592
|
+
* gate — a DO stamps its own socket from `env` alone, so setting `false` here
|
|
3593
|
+
* without the env var yields a socket the worker admits and the DO marks
|
|
3594
|
+
* non-admin (admin subscriptions then return nothing).
|
|
3573
3595
|
*/
|
|
3574
3596
|
requireEphemeralWsToken?: boolean;
|
|
3575
3597
|
/**
|
|
@@ -3959,15 +3981,16 @@ declare const createLunoraHandler: (options?: LunoraHandlerOptions) => ((request
|
|
|
3959
3981
|
/** Re-exported helper so callers can roundtrip envelopes in tests. */
|
|
3960
3982
|
declare const defineRpcEnvelope: (envelope: RpcEnvelope) => RpcEnvelope;
|
|
3961
3983
|
/**
|
|
3962
|
-
* Reader / counter capabilities, typed against the SAME canonical
|
|
3963
|
-
*
|
|
3964
|
-
* `crossShardCounter` options from
|
|
3965
|
-
* `
|
|
3966
|
-
*
|
|
3967
|
-
*
|
|
3984
|
+
* Reader / counter capabilities, typed against the SAME canonical shard-engine
|
|
3985
|
+
* types the `@lunora/d1` ctx-db derives its `crossShardReader` /
|
|
3986
|
+
* `crossShardCounter` options from — so the pair drops straight into
|
|
3987
|
+
* `createD1CtxDb` with no cast and no structural drift. The reader takes
|
|
3988
|
+
* {@link CrossShardReadArgs} (not `QueryArgs`) because the hop is a JSON envelope
|
|
3989
|
+
* and the RLS filters must travel as data. The import is type-only:
|
|
3990
|
+
* `@lunora/runtime` keeps no hard (value) dependency on `@lunora/do`.
|
|
3968
3991
|
*/
|
|
3969
3992
|
type CrossShardCounter = DatabaseWriterLike["count"];
|
|
3970
|
-
type CrossShardReader =
|
|
3993
|
+
type CrossShardReader = (table: string, args: CrossShardReadArgs) => Promise<QueryPage>;
|
|
3971
3994
|
interface CrossShardRelationOptions {
|
|
3972
3995
|
/**
|
|
3973
3996
|
* `fetch` used for the worker subrequest. Defaults to `globalThis.fetch`.
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { RankDirection, RankPageRow, DatabaseWriterLike } from '@lunora/shard-engine';
|
|
1
|
+
import { RankDirection, RankPageRow, DatabaseWriterLike, CrossShardReadArgs, QueryPage } from '@lunora/shard-engine';
|
|
2
2
|
export type { RankDirection as RankPageDirection, RankPageRowKey as RankPageKey, RankPageRow, ShardRankPageResult } from '@lunora/shard-engine';
|
|
3
3
|
import { R2SqlClient } from '@lunora/bindings/r2sql';
|
|
4
4
|
import { WorkflowsRestClient } from '@lunora/workflow';
|
|
@@ -2769,6 +2769,13 @@ interface StorageObject {
|
|
|
2769
2769
|
contentType?: string;
|
|
2770
2770
|
};
|
|
2771
2771
|
key: string;
|
|
2772
|
+
/**
|
|
2773
|
+
* Lowercase-hex SHA-256, when the object was written with one. R2 reports a
|
|
2774
|
+
* checksum only if the writer supplied it, so this is absent for objects
|
|
2775
|
+
* uploaded before that was wired up — consumers must treat "absent" as "not
|
|
2776
|
+
* reported", never as "does not match".
|
|
2777
|
+
*/
|
|
2778
|
+
sha256?: string;
|
|
2772
2779
|
size: number;
|
|
2773
2780
|
}
|
|
2774
2781
|
/**
|
|
@@ -2881,6 +2888,7 @@ type StorageDeleteFunction = (key: string, options?: {
|
|
|
2881
2888
|
type StorageUploadFunction = (key: string, body: ArrayBuffer, options?: {
|
|
2882
2889
|
bucket?: string;
|
|
2883
2890
|
contentType?: string;
|
|
2891
|
+
sha256?: string;
|
|
2884
2892
|
}) => Promise<{
|
|
2885
2893
|
etag?: string;
|
|
2886
2894
|
key: string;
|
|
@@ -3298,6 +3306,13 @@ interface WorkerOptions {
|
|
|
3298
3306
|
* every live shard for the table) and a per-shard gate is not
|
|
3299
3307
|
* sufficient to authorize it. Apps that need client-driven fan-out
|
|
3300
3308
|
* must opt in explicitly via this callback.
|
|
3309
|
+
*
|
|
3310
|
+
* SCOPE: this gate is TABLE-granular — it decides whether the caller may fan
|
|
3311
|
+
* this function out over this table at all, never which ROWS come back. Row
|
|
3312
|
+
* filtering is RLS's job and stays RLS's job on the fan-out path too: the
|
|
3313
|
+
* reserved `__lunora_relation__:read` hop carries the child's read policy as
|
|
3314
|
+
* data (`where` + `relationPolicies`) so each shard applies it. Do not read
|
|
3315
|
+
* an `authorizeFanOut: () => true` as "this caller may see every row".
|
|
3301
3316
|
*/
|
|
3302
3317
|
authorizeFanOut?: (identity: ResolvedIdentity | null, table: string, functionPath: string) => boolean | Promise<boolean>;
|
|
3303
3318
|
/**
|
|
@@ -3559,17 +3574,24 @@ interface WorkerOptions {
|
|
|
3559
3574
|
*/
|
|
3560
3575
|
queue?: QueueConsumerHandler;
|
|
3561
3576
|
/**
|
|
3562
|
-
* Enforce the ephemeral WS admin token:
|
|
3563
|
-
* the
|
|
3564
|
-
*
|
|
3565
|
-
*
|
|
3566
|
-
*
|
|
3567
|
-
*
|
|
3568
|
-
*
|
|
3569
|
-
*
|
|
3570
|
-
*
|
|
3571
|
-
*
|
|
3572
|
-
*
|
|
3577
|
+
* Enforce the ephemeral WS admin token: the worker's WS admin gate rejects
|
|
3578
|
+
* the raw master admin token in the `?token=` query parameter — only a
|
|
3579
|
+
* short-lived sub-token minted by `POST /_lunora/admin/ws-token` (or the
|
|
3580
|
+
* master token in the `Authorization` HEADER, which never leaks via URLs)
|
|
3581
|
+
* authorizes.
|
|
3582
|
+
*
|
|
3583
|
+
* **On by default**: a query string lands in access logs, browser history and
|
|
3584
|
+
* `Referer`, so the master admin credential must not ride one. The studio
|
|
3585
|
+
* mints and sends the ephemeral token already.
|
|
3586
|
+
*
|
|
3587
|
+
* To opt back out for a legacy client that still puts the master token in a
|
|
3588
|
+
* URL, set **`env.LUNORA_REQUIRE_EPHEMERAL_WS_TOKEN`** to
|
|
3589
|
+
* `0`/`false`/`off`/`no`/`disabled`. That is the knob to use: it is read
|
|
3590
|
+
* independently by the worker AND by the shard/relay Durable Objects, so the
|
|
3591
|
+
* whole deployment agrees. This code-level option only governs the WORKER's
|
|
3592
|
+
* gate — a DO stamps its own socket from `env` alone, so setting `false` here
|
|
3593
|
+
* without the env var yields a socket the worker admits and the DO marks
|
|
3594
|
+
* non-admin (admin subscriptions then return nothing).
|
|
3573
3595
|
*/
|
|
3574
3596
|
requireEphemeralWsToken?: boolean;
|
|
3575
3597
|
/**
|
|
@@ -3959,15 +3981,16 @@ declare const createLunoraHandler: (options?: LunoraHandlerOptions) => ((request
|
|
|
3959
3981
|
/** Re-exported helper so callers can roundtrip envelopes in tests. */
|
|
3960
3982
|
declare const defineRpcEnvelope: (envelope: RpcEnvelope) => RpcEnvelope;
|
|
3961
3983
|
/**
|
|
3962
|
-
* Reader / counter capabilities, typed against the SAME canonical
|
|
3963
|
-
*
|
|
3964
|
-
* `crossShardCounter` options from
|
|
3965
|
-
* `
|
|
3966
|
-
*
|
|
3967
|
-
*
|
|
3984
|
+
* Reader / counter capabilities, typed against the SAME canonical shard-engine
|
|
3985
|
+
* types the `@lunora/d1` ctx-db derives its `crossShardReader` /
|
|
3986
|
+
* `crossShardCounter` options from — so the pair drops straight into
|
|
3987
|
+
* `createD1CtxDb` with no cast and no structural drift. The reader takes
|
|
3988
|
+
* {@link CrossShardReadArgs} (not `QueryArgs`) because the hop is a JSON envelope
|
|
3989
|
+
* and the RLS filters must travel as data. The import is type-only:
|
|
3990
|
+
* `@lunora/runtime` keeps no hard (value) dependency on `@lunora/do`.
|
|
3968
3991
|
*/
|
|
3969
3992
|
type CrossShardCounter = DatabaseWriterLike["count"];
|
|
3970
|
-
type CrossShardReader =
|
|
3993
|
+
type CrossShardReader = (table: string, args: CrossShardReadArgs) => Promise<QueryPage>;
|
|
3971
3994
|
interface CrossShardRelationOptions {
|
|
3972
3995
|
/**
|
|
3973
3996
|
* `fetch` used for the worker subrequest. Defaults to `globalThis.fetch`.
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{toAirbyteMessages as t,toFivetranResponse as a}from"./packem_shared/toAirbyteMessages-DTk8e2f9.mjs";import{composeWorker as i,createLunoraHandler as n,createWorker as p,defineRpcEnvelope as m,resolveLunoraOptions as c,withFrameworkWorker as R}from"./packem_shared/composeWorker
|
|
1
|
+
import{toAirbyteMessages as t,toFivetranResponse as a}from"./packem_shared/toAirbyteMessages-DTk8e2f9.mjs";import{composeWorker as i,createLunoraHandler as n,createWorker as p,defineRpcEnvelope as m,resolveLunoraOptions as c,withFrameworkWorker as R}from"./packem_shared/composeWorker-MnGFIJTe.mjs";import{createCrossShardRelationCapabilities as S}from"./packem_shared/createCrossShardRelationCapabilities-CQfrCIWR.mjs";import{DEFAULT_REGISTRY_CACHE_TTL_MS as f,SHARD_REGISTRY_DO_NAME as l,createDynamicShardRegistry as x}from"./packem_shared/DEFAULT_REGISTRY_CACHE_TTL_MS-BclNO0yc.mjs";import{LunoraError as y,toErrorResponse as C}from"./packem_shared/LunoraError-ByasbDmd.mjs";import{createKvCursorStore as g,createMemoryCursorStore as u,defineExportSink as T,r2Sink as A,runExportTap as h,sanitizeChange as k,webhookExportSink as O}from"./packem_shared/createKvCursorStore-C24tEuYk.mjs";import{HEALTH_PATH as v,HEALTH_READY_PATH as I,buildHealthRoutes as b,d1Probe as F,durableObjectProbe as P,presenceProbe as D}from"./packem_shared/HEALTH_PATH-Cqrg0Dq3.mjs";import{LOG_ARCHIVE_PATH as G,resolveLogArchiveFromEnv as U}from"./packem_shared/LOG_ARCHIVE_PATH-CuHKuDCS.mjs";import{memoizeIdentity as w,memoizeIdentityPerRequest as z}from"./packem_shared/memoizeIdentity-CX3xEPYw.mjs";import{e as W,a as Y}from"./packem_shared/observability-DWlkDJJw.mjs";import{analyticsEngineSink as K,combineSinks as Q,consoleSink as X,otlpSink as j,pipelineLogSink as J,sentrySink as B,webhookSink as Z}from"./packem_shared/analyticsEngineSink-iIRy11I9.mjs";import{D as ee,a as re,c as oe}from"./packem_shared/pipeline-log-reader-FF1V32O2.mjs";import{createQueryCoordinator as ae,createStaticShardRegistry as se,mergeStrategyForAggregate as ie}from"./packem_shared/createQueryCoordinator-D7NpIHuQ.mjs";import{applyJurisdiction as pe,resolveShard as me}from"./packem_shared/applyJurisdiction-8bzZjAPR.mjs";import{R as Re,d as Ee,o as Se}from"./packem_shared/rest-cache-5unAzdFN.mjs";import{g as fe,E as le,U as xe,p as _e,y as ye}from"./packem_shared/rest-routes-BqldHiaH.mjs";import{decorateResponse as Le,enforceOrigin as ge,handleCorsPreflight as ue,resolveSecurity as Te}from"./packem_shared/decorateResponse-DBIWsRSZ.mjs";import{createShardClient as he}from"./packem_shared/createShardClient-D4mXb3vL.mjs";import{LOG_ARCHIVE_NOT_CONFIGURED as Oe}from"./packem_shared/LOG_ARCHIVE_NOT_CONFIGURED-CDpi4yFD.mjs";import{NOOP_EXECUTION_CONTEXT as ve}from"./packem_shared/NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{composeIdentityResolvers as be,routeIdentityResolvers as Fe}from"./packem_shared/composeIdentityResolvers-DwE0Jbww.mjs";const e="0.0.0";export{ee as DEFAULT_LOG_COLUMNS,re as DEFAULT_LOG_LIMIT,f as DEFAULT_REGISTRY_CACHE_TTL_MS,v as HEALTH_PATH,I as HEALTH_READY_PATH,Oe as LOG_ARCHIVE_NOT_CONFIGURED,G as LOG_ARCHIVE_PATH,y as LunoraError,ve as NOOP_EXECUTION_CONTEXT,l as SHARD_REGISTRY_DO_NAME,e as VERSION,K as analyticsEngineSink,pe as applyJurisdiction,Re as applyRestCache,fe as argsFromQuery,b as buildHealthRoutes,le as buildRestRoutes,Q as combineSinks,be as composeIdentityResolvers,i as composeWorker,X as consoleSink,S as createCrossShardRelationCapabilities,x as createDynamicShardRegistry,g as createKvCursorStore,n as createLunoraHandler,u as createMemoryCursorStore,oe as createPipelineLogReader,ae as createQueryCoordinator,xe as createRestRateLimit,he as createShardClient,se as createStaticShardRegistry,p as createWorker,F as d1Probe,Le as decorateResponse,T as defineExportSink,m as defineRpcEnvelope,P as durableObjectProbe,W as emitLogEvent,Y as emitRpcEvent,ge as enforceOrigin,ue as handleCorsPreflight,w as memoizeIdentity,z as memoizeIdentityPerRequest,ie as mergeStrategyForAggregate,j as otlpSink,J as pipelineLogSink,D as presenceProbe,A as r2Sink,_e as readShardKey,Ee as requestCarriesCredentials,U as resolveLogArchiveFromEnv,c as resolveLunoraOptions,Te as resolveSecurity,me as resolveShard,Se as restCacheHeaders,ye as restSurfaceFromRegistry,Fe as routeIdentityResolvers,h as runExportTap,k as sanitizeChange,B as sentrySink,t as toAirbyteMessages,C as toErrorResponse,a as toFivetranResponse,O as webhookExportSink,Z as webhookSink,R as withFrameworkWorker};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import{isLunoraError as pr,toErrorBody as fr}from"@lunora/errors";import{d as Rt}from"./evict-oldest-C2XU6HBR.mjs";import{NOOP_EXECUTION_CONTEXT as mr}from"./NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{f as wr,u as gr}from"./identity-header-pdXOyDU4.mjs";import{O as Oe,m as yr,A as br,R as _r,d as Rr,i as Er,s as Sr}from"./otlp-resource-B-ByO9qo.mjs";import{h as ee,f as ye,i as Et,E as Tr,w as St,e as Tt,b as Or}from"./rest-routes-BqldHiaH.mjs";import{LunoraError as i,toErrorResponse as Je}from"./LunoraError-ByasbDmd.mjs";import{runExportTap as Ar}from"./createKvCursorStore-C24tEuYk.mjs";import{t as we,r as L}from"./method-guard-rzvo19pa.mjs";import{buildHealthRoutes as vr,durableObjectProbe as kr,d1Probe as Ir,presenceProbe as Ne}from"./HEALTH_PATH-Cqrg0Dq3.mjs";import{wrapResolverWithContract as Dr}from"./composeIdentityResolvers-DwE0Jbww.mjs";import{composeIdentityResolvers as Bo,routeIdentityResolvers as $o}from"./composeIdentityResolvers-DwE0Jbww.mjs";import{buildLogArchiveAdminRoutes as Pr}from"./LOG_ARCHIVE_PATH-CuHKuDCS.mjs";import{o as Ur,f as Ve,a as ce}from"./observability-DWlkDJJw.mjs";import{resolveShard as Ae,applyJurisdiction as Ye}from"./applyJurisdiction-8bzZjAPR.mjs";import{resolveSecurity as Xe,handleCorsPreflight as Nr,enforceOrigin as qr,decorateResponse as qe,enforceWebSocketOrigin as Ze}from"./decorateResponse-DBIWsRSZ.mjs";const Cr=e=>{const t=e??{};if(typeof t.bucket=="function")return t;const r={...t,bucketName:"default"};return r.bucket=()=>r,r},Ot="__lunoraBranch",xr=e=>typeof e=="object"&&e!==null&&Object.hasOwn(e,Ot),jr=`may not contain the reserved workflow branch-marker key ("${Ot}")`,Ge=(e,t)=>{const r=Math.max(e.length,t.length);let n=e.length^t.length;for(let o=0;o<r;o+=1){const d=o<e.length?e.charCodeAt(o):0,u=o<t.length?t.charCodeAt(o):0;n|=d^u}return n===0},Fe=new TextEncoder,Br=Array.from({length:32},(e,t)=>t);new RegExp(`[${Br.map(e=>String.fromCodePoint(e)).join("")}]`,"u");const $r=e=>{const t=String.fromCodePoint(...e);return btoa(t).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")},Lr=e=>{const t=e.replaceAll("-","+").replaceAll("_","/")+"===".slice((e.length+3)%4),r=atob(t),n=new Uint8Array(r.length);for(let o=0;o<r.length;o+=1)n[o]=r.codePointAt(o)??0;return n},Kr=64,Ce=new Map,At=async e=>{const t=Ce.get(e);if(t)return t;Rt(Ce,Kr);const r=crypto.subtle.importKey("raw",Fe.encode(e),{hash:"SHA-256",name:"HMAC"},!1,["sign","verify"]);return Ce.set(e,r),r},vt=async(e,t)=>{const r=await At(e),n=await crypto.subtle.sign("HMAC",r,Fe.encode(t));return $r(new Uint8Array(n))},Gr=async(e,t,r)=>{const n=await At(e);return crypto.subtle.verify("HMAC",n,r,Fe.encode(t))},Fr="::relay::",Qr=(e,t)=>`${e}${Fr}${String(t)}`,Mr=new Set(["1","enabled","on","true","yes"]),zr=new Set(["0","disabled","false","no","off"]),Wr=(e,t)=>{const r=(e??"").trim().toLowerCase();return Mr.has(r)?!0:zr.has(r)?!1:t},kt="v1",Hr=6e4,Jr=async(e,t={})=>{const r=(t.now??Date.now())+(t.ttlMs??Hr),n=`${kt}.${String(r)}`,o=await vt(e,n);return{expiresAtMs:r,token:`${n}.${o}`}},Vr=async(e,t,r=Date.now())=>{if(e.length===0||t.length===0)return!1;const n=t.split(".");if(n.length!==3)return!1;const[o,d,u]=n;if(o!==kt||u.length===0)return!1;const h=Number(d);if(!Number.isFinite(h)||h<=r)return!1;let w;try{w=Lr(u)}catch{return!1}return Gr(e,`${o}.${d}`,w)},D="/_lunora/admin/auth",Yr={INVITER_REQUIRED:400,ORG_SLUG_INVALID:400,ORG_SLUG_TAKEN:409,PASSWORD_TOO_LONG:400,PASSWORD_TOO_SHORT:400,USER_ALREADY_EXISTS:409,USER_NOT_FOUND:404},U=(e,t)=>{const r=e[t];if(typeof r!="string"||r==="")throw new i(`\`${t}\` is required`,{code:"BAD_REQUEST",status:400});return r},le=(e,t)=>{const r=e(t);if(r===void 0)throw new i(`\`${t}\` query parameter is required`,{code:"BAD_REQUEST",status:400});return r},It=e=>{if(typeof e=="string"||Array.isArray(e)&&e.every(t=>typeof t=="string"))return e},te=(e,t)=>typeof e[t]=="string"?e[t]:void 0,xe=(e,t)=>{const r=e[t];return typeof r=="object"&&r!==null&&!Array.isArray(r)?r:void 0},et=e=>{const t=It(e.role);if(t===void 0||typeof t=="string"&&t.trim()==="")throw new i("`role` is required",{code:"BAD_REQUEST",status:400});return t},tt=e=>{const t=e.permission;if(typeof t!="object"||t===null||Array.isArray(t))throw new i("`permission` object is required",{code:"BAD_REQUEST",status:400});const r={};for(const[n,o]of Object.entries(t))Array.isArray(o)&&o.every(d=>typeof d=="string")&&(r[n]=o);return r},Xr={[`${D}/capabilities`]:{build:()=>({}),http:"GET",method:"capabilities"},[`${D}/users`]:{build:({paging:e,query:t})=>{const r=t("sortDirection");return{...e,filterField:t("filterField"),filterValue:t("filterValue"),search:t("search"),searchField:t("searchField"),sortBy:t("sortBy"),sortDirection:r==="asc"||r==="desc"?r:void 0}},http:"GET",method:"listUsers"},[`${D}/sessions`]:{build:({paging:e,query:t})=>({...e,userId:t("userId")}),http:"GET",method:"listSessions"},[`${D}/accounts`]:{build:({query:e})=>({userId:le(e,"userId")}),http:"GET",method:"listAccounts"},[`${D}/passkeys`]:{build:({query:e})=>({userId:le(e,"userId")}),http:"GET",method:"listPasskeys"},[`${D}/organizations`]:{build:({paging:e})=>({...e}),http:"GET",method:"listOrganizations"},[`${D}/organizations/members`]:{build:({paging:e,query:t})=>({...e,organizationId:le(t,"organizationId")}),http:"GET",method:"listMembers"},[`${D}/organizations/invitations`]:{build:({paging:e,query:t})=>({...e,organizationId:le(t,"organizationId")}),http:"GET",method:"listInvitations"},[`${D}/config`]:{build:()=>({}),http:"GET",method:"config"},[`${D}/organizations/teams`]:{build:({paging:e,query:t})=>({...e,organizationId:le(t,"organizationId")}),http:"GET",method:"listTeams"},[`${D}/organizations/teams/members`]:{build:({paging:e,query:t})=>({...e,teamId:le(t,"teamId")}),http:"GET",method:"listTeamMembers"},[`${D}/organizations/roles`]:{build:({paging:e,query:t})=>({...e,organizationId:le(t,"organizationId")}),http:"GET",method:"listOrgRoles"},[`${D}/users/create`]:{build:({body:e})=>({data:xe(e,"data"),email:U(e,"email"),name:U(e,"name"),password:te(e,"password"),role:It(e.role)}),http:"POST",method:"createUser"},[`${D}/users/update`]:{build:({body:e})=>{const{data:t}=e;if(typeof t!="object"||t===null||Array.isArray(t))throw new i("`data` object is required",{code:"BAD_REQUEST",status:400});return{data:t,userId:U(e,"userId")}},http:"POST",method:"updateUser"},[`${D}/users/role`]:{build:({body:e})=>({role:et(e),userId:U(e,"userId")}),http:"POST",method:"setRole"},[`${D}/users/ban`]:{build:({body:e})=>({expiresInSeconds:typeof e.expiresInSeconds=="number"?e.expiresInSeconds:void 0,reason:te(e,"reason"),userId:U(e,"userId")}),http:"POST",method:"banUser"},[`${D}/users/unban`]:{build:({body:e})=>({userId:U(e,"userId")}),http:"POST",method:"unbanUser"},[`${D}/users/password`]:{build:({body:e})=>({newPassword:U(e,"newPassword"),userId:U(e,"userId")}),http:"POST",method:"setUserPassword",returns:"void"},[`${D}/users/remove`]:{build:({body:e})=>({userId:U(e,"userId")}),http:"POST",method:"removeUser",returns:"void"},[`${D}/users/impersonate`]:{build:({body:e})=>({userId:U(e,"userId")}),http:"POST",method:"impersonateUser"},[`${D}/sessions/revoke`]:{build:({body:e})=>({sessionId:U(e,"sessionId")}),http:"POST",method:"revokeUserSession",returns:"void"},[`${D}/sessions/revoke-all`]:{build:({body:e})=>({userId:U(e,"userId")}),http:"POST",method:"revokeUserSessions",returns:"void"},[`${D}/accounts/unlink`]:{build:({body:e})=>({accountId:U(e,"accountId"),userId:U(e,"userId")}),http:"POST",method:"unlinkAccount",returns:"void"},[`${D}/two-factor/disable`]:{build:({body:e})=>({userId:U(e,"userId")}),http:"POST",method:"disableTwoFactor",returns:"void"},[`${D}/passkeys/delete`]:{build:({body:e})=>({passkeyId:U(e,"passkeyId")}),http:"POST",method:"deletePasskey",returns:"void"},[`${D}/organizations/members/remove`]:{build:({body:e})=>({memberId:U(e,"memberId")}),http:"POST",method:"removeMember",returns:"void"},[`${D}/organizations/invitations/cancel`]:{build:({body:e})=>({invitationId:U(e,"invitationId")}),http:"POST",method:"cancelInvitation",returns:"void"},[`${D}/organizations/create`]:{build:({body:e})=>({logo:te(e,"logo"),metadata:xe(e,"metadata"),name:U(e,"name"),ownerId:te(e,"ownerId"),slug:te(e,"slug")}),http:"POST",method:"createOrganization"},[`${D}/organizations/update`]:{build:({body:e})=>({logo:te(e,"logo"),metadata:xe(e,"metadata"),name:te(e,"name"),organizationId:U(e,"organizationId"),slug:te(e,"slug")}),http:"POST",method:"updateOrganization"},[`${D}/organizations/remove`]:{build:({body:e})=>({organizationId:U(e,"organizationId")}),http:"POST",method:"deleteOrganization",returns:"void"},[`${D}/organizations/members/add`]:{build:({body:e})=>({organizationId:U(e,"organizationId"),role:te(e,"role"),userId:U(e,"userId")}),http:"POST",method:"addMember"},[`${D}/organizations/members/invite`]:{build:({body:e})=>({email:U(e,"email"),inviterId:te(e,"inviterId"),organizationId:U(e,"organizationId"),role:te(e,"role")}),http:"POST",method:"inviteMember"},[`${D}/organizations/members/role`]:{build:({body:e})=>({memberId:U(e,"memberId"),role:et(e)}),http:"POST",method:"updateMemberRole"},[`${D}/organizations/teams/create`]:{build:({body:e})=>({name:U(e,"name"),organizationId:U(e,"organizationId")}),http:"POST",method:"createTeam"},[`${D}/organizations/teams/update`]:{build:({body:e})=>({name:U(e,"name"),teamId:U(e,"teamId")}),http:"POST",method:"updateTeam"},[`${D}/organizations/teams/remove`]:{build:({body:e})=>({teamId:U(e,"teamId")}),http:"POST",method:"removeTeam",returns:"void"},[`${D}/organizations/teams/members/add`]:{build:({body:e})=>({teamId:U(e,"teamId"),userId:U(e,"userId")}),http:"POST",method:"addTeamMember"},[`${D}/organizations/teams/members/remove`]:{build:({body:e})=>({teamMemberId:U(e,"teamMemberId")}),http:"POST",method:"removeTeamMember",returns:"void"},[`${D}/organizations/roles/create`]:{build:({body:e})=>({organizationId:U(e,"organizationId"),permission:tt(e),role:U(e,"role")}),http:"POST",method:"createOrgRole"},[`${D}/organizations/roles/update`]:{build:({body:e})=>({permission:tt(e),roleId:U(e,"roleId")}),http:"POST",method:"updateOrgRole"},[`${D}/organizations/roles/remove`]:{build:({body:e})=>({roleId:U(e,"roleId")}),http:"POST",method:"deleteOrgRole",returns:"void"}},Zr=e=>{const t=async o=>{try{return await o()}catch(d){if(d instanceof i)throw d;const u=d,h=typeof u.code=="string"?u.code:"AUTH_ADMIN_ERROR";throw console.error("[lunora] auth admin operation failed:",d),new i("auth admin operation failed",{code:h,status:Yr[h]??500})}},r=async(o,d)=>{if(e.assertAdmin(o),o.method!==d.http)throw new i(`Auth admin endpoint requires ${d.http}`,{code:"METHOD_NOT_ALLOWED",status:405});const u=e.getAuthAdmin();if(u===void 0)throw new i("auth endpoints require an `authAdmin` on the worker",{code:"AUTH_NOT_CONFIGURED",status:400});const h=u[d.method];if(h===void 0)throw new i(`auth admin does not support \`${d.method}\``,{code:"AUTH_OP_NOT_SUPPORTED",status:400});const w=new URL(o.url),R={body:d.http==="POST"?await e.readJsonBody(o):{},paging:e.parsePaging(o),query:k=>e.queryParameter(w,k)},I=d.build(R),b=await t(()=>h(I));return Response.json(d.returns==="void"?{ok:!0}:b,{headers:{"content-type":"application/json"},status:200})},n={};for(const[o,d]of Object.entries(Xr))n[o]=u=>r(u,d);return n},en="__lunora_admin__:getAuthAuditLog",rt=e=>typeof e=="string"&&e!==""?e:void 0,nt=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0,tn=e=>async(t,r)=>{e.assertAdmin(t);const n=e.getReader();if(n===void 0)throw new i("the auth/security audit endpoint requires an `authAuditReader` on the worker",{code:"AUTH_AUDIT_NOT_CONFIGURED",status:400});const o=rt(r.actorId),d=rt(r.event),u=nt(r.sinceSeq),h=nt(r.limit),w={...o===void 0?{}:{actorId:o},...d===void 0?{}:{event:d},...u===void 0?{}:{sinceSeq:u},...h===void 0?{}:{limit:h}};let R;try{R=await n.read(w)}catch(b){throw b instanceof i?b:(console.error("[lunora] auth audit read failed:",b),new i("auth audit read failed",{code:"AUTH_AUDIT_READ_FAILED",status:500}))}const I={entries:R};return Response.json(I,{headers:{"content-type":"application/json"},status:200})},at=500,rn=(e,t,r)=>{if(typeof e!="object"||e===null||Array.isArray(e))throw new i("each batch call must be an object",{code:"BAD_REQUEST",status:400});const n=e;if(typeof n.functionPath!="string")throw new i("each batch call needs a string `functionPath`",{code:"BAD_REQUEST",status:400});if(n.functionPath.startsWith("__lunora_relation__:")||n.functionPath.startsWith("__lunora_admin__"))throw new i("reserved function path cannot be batched",{code:"FORBIDDEN",status:403});if(n.args!==void 0&&(typeof n.args!="object"||n.args===null||Array.isArray(n.args)))throw new i("each batch call `args` must be an object",{code:"BAD_REQUEST",status:400});return{entry:{args:n.args===void 0?{}:n.args,clientId:typeof n.clientId=="string"?n.clientId:void 0,clientSeq:typeof n.clientSeq=="number"?n.clientSeq:void 0,functionPath:n.functionPath,id:typeof n.id=="number"?n.id:t,mutationId:typeof n.mutationId=="string"?n.mutationId:void 0},shardKey:typeof n.shardKey=="string"?n.shardKey:r}},nn=(e,t)=>{if(e.length>at)throw new i(`RPC batch exceeds the ${String(at)}-call limit`,{code:"BAD_REQUEST",status:400});const r=new Map;for(const[n,o]of e.entries()){const{entry:d,shardKey:u}=rn(o,n,t),h=r.get(u)??[];h.push(d),r.set(u,h)}return r},an=new TextEncoder,on=e=>{const t=JSON.stringify(e),r=an.encode(t);let n="";for(const o of r)n+=String.fromCodePoint(o);return btoa(n).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")},sn=e=>{const t={g:0,s:{},v:1};if(typeof e!="string"||e.length===0)return t;try{const r=atob(e.replaceAll("-","+").replaceAll("_","/")),n=new Uint8Array(r.length);for(let h=0;h<r.length;h+=1)n[h]=r.codePointAt(h)??0;const o=JSON.parse(new TextDecoder().decode(n)),d=o.s&&typeof o.s=="object"?o.s:{},u={};for(const[h,w]of Object.entries(d))typeof w=="number"&&Number.isFinite(w)&&(u[h]=w);return{g:typeof o.g=="number"&&Number.isFinite(o.g)?o.g:0,s:u,v:1}}catch{return t}},cn=e=>{const t=typeof e.table=="string"?e.table:"",r=typeof e.op=="string"?e.op:"",n=r==="delete"||r==="insert"||r==="update"?r:"upsert",o=typeof e.id=="string"?e.id:void 0;return{doc:(e.doc&&typeof e.doc=="object"?e.doc:void 0)??(o===void 0?{}:{_id:o}),op:n,table:t}},ot=(e,t,r)=>{for(const n of t)e.push(cn(n));return r!==void 0&&t.length>=r},dn="/_lunora/admin/export",un="/_lunora/admin/import",ln="/_lunora/admin/sync",hn="/_lunora/admin/connector/sync",pn="/_lunora/admin/apply",fn="/_lunora/admin/export-tap/run",mn=new TextEncoder,wn=async e=>{const t=await ye(e,"Export")??{};if(t.tables===void 0)return{tables:void 0};if(!Array.isArray(t.tables))throw new i("Export `tables` must be a string array",{code:"BAD_REQUEST",status:400});const r=[];for(const n of t.tables){if(typeof n!="string"||n.length===0)throw new i("Export `tables` entries must be non-empty strings",{code:"BAD_REQUEST",status:400});r.push(n)}return{tables:r}},je=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):void 0,gn=e=>{const{applyGlobals:t,exportCursorStore:r,exportSinks:n,knownTables:o,queryCoordinator:d,assertAdmin:u,requireAdminOption:h,resolveForwardContext:w,shardDO:R,streamExportRows:I,streamingImport:b,syncGlobals:k}=e,p=async(A,j)=>{const x=we(A,["POST"]);if(x)return x;const F=h(A,d,{code:"BAD_REQUEST",message:"Export endpoint requires a `queryCoordinator` on the worker"}),P=await wn(A),{headers:Q}=await w(A,j),M=new ReadableStream({async pull(B){const K=X=>{B.enqueue(mn.encode(`${JSON.stringify(X)}
|
|
2
|
+
`))};try{await I(F,Q,P.tables,K),B.close()}catch(X){B.error(X)}}});return new Response(M,{headers:{"content-type":"application/x-ndjson"},status:200})},g=async(A,j)=>{const x=we(A,["POST"]);if(x)return x;const F=h(A,d,{code:"BAD_REQUEST",message:"Sync endpoint requires a `queryCoordinator` on the worker"}),P=await ee(A),Q=typeof P.cursors=="object"&&P.cursors!==null?P.cursors:{},M=typeof P.limit=="number"?P.limit:void 0,B=typeof P.globalCursor=="number"?P.globalCursor:0,K=je(P.tables),{headers:X}=await w(A,j),J=K??o(),ne=await F.orchestrateCdcSync(R,{cursors:Q,headers:X,limit:M,tables:J}),he=k?await k({limit:M,sinceSeq:B}):void 0;return Response.json({global:he,shards:ne.shards},{status:200})},E=async(A,j)=>{const x=we(A,["POST"]);if(x)return x;const F=h(A,d,{code:"BAD_REQUEST",message:"Connector sync endpoint requires a `queryCoordinator` on the worker"}),P=await ee(A),Q=sn(P.cursor),M=typeof P.limit=="number"&&P.limit>0?P.limit:void 0,B=je(P.tables),{headers:K}=await w(A,j),X=B??o(),J=await F.orchestrateCdcSync(R,{cursors:Q.s,headers:K,limit:M,tables:X}),ne=[],he={...Q.s};let ae=!1;for(const se of J.shards)ae=ot(ne,se.changes??[],M)||ae,he[se.shardKey]=se.cursor;let pe=Q.g;if(k){const se=await k({limit:M,sinceSeq:Q.g});ae=ot(ne,se.changes,M)||ae,pe=se.cursor}const be=on({g:pe,s:he,v:1}),ve={changes:ne,hasMore:ae,nextCursor:be};return Response.json(ve,{status:200})},_=async(A,j)=>{const x=we(A,["POST"]);if(x)return x;const F=h(A,d,{code:"BAD_REQUEST",message:"Apply endpoint requires a `queryCoordinator` on the worker"}),P=await ee(A),Q=(Array.isArray(P.batches)?P.batches:[]).map(J=>J).filter(J=>J!==null&&typeof J=="object"&&typeof J.shardKey=="string"&&Array.isArray(J.changes)),M=Array.isArray(P.globalChanges)?P.globalChanges:[],{headers:B}=await w(A,j),K=await F.orchestrateApplyCdc(R,{batches:Q,headers:B}),X=M.length>0&&t?await t({changes:M}):0;return Response.json({applied:K.applied+X,failed:K.failed,ok:K.ok},{status:200})},O=async(A,j)=>{const x=we(A,["POST"]);if(x)return x;u(A);const{headers:F}=await w(A,j),P=await b(A,F);return Response.json(P,{headers:{"content-type":"application/json"},status:200})},N=async(A,j)=>{const x=we(A,["POST"]);if(x)return x;const F=h(A,d,{code:"BAD_REQUEST",message:"Export-tap endpoint requires a `queryCoordinator` on the worker"});if(n===void 0||Object.keys(n).length===0||r===void 0)throw new i("Export-tap endpoint requires `exportSinks` + `exportCursorStore` on the worker",{code:"EXPORT_TAP_NOT_CONFIGURED",status:400});const P=await ee(A),Q=typeof P.sink=="string"?P.sink:void 0,M=typeof P.limit=="number"&&P.limit>0?P.limit:void 0,B=je(P.tables);if(Q===void 0)throw new i("Export-tap `sink` must name a configured sink",{code:"BAD_REQUEST",status:400});const K=n[Q];if(K===void 0)throw new i(`Export-tap sink "${Q}" is not configured`,{code:"NOT_FOUND",status:404});const{headers:X}=await w(A,j),J=B??o(),ne=await Ar({coordinator:F,cursorStore:r,headers:X,limit:M,shardDO:R,sink:K,tables:J});return Response.json(ne,{headers:{"content-type":"application/json"},status:200})};return{[pn]:_,[hn]:E,[dn]:p,[fn]:N,[un]:O,[ln]:g}},yn=(e,t)=>{const r=[],n=[];if(t&&t.length>0)for(const o of t)e.resolveTableSharding?.(o)?.mode.kind==="global"?n.push(o):r.push(o);return{globalTables:n,shardLocalTables:r}},bn=async(e,t,r,n,o,d)=>{if(r!==void 0&&n.length===0)return;const u=await e.orchestrateExport(d,{args:{tables:n},headers:t,tables:n});for(const h of u.shards)if(!h.error)for(const w of h.rows??[])o(w)},st=async(e,t,r,n,o,d)=>{const{globalTables:u,shardLocalTables:h}=yn(e,n);await bn(t,r,n,h,o,d);const w=e.exportGlobals;if((n===void 0||u.length>0)&&w)for await(const R of w({tables:u}))o(R)},_n=(e,t)=>{let r;try{r=JSON.parse(e)}catch{return{error:{code:"BAD_ROW",line:t,message:"line is not valid JSON",table:""},ok:!1}}if(!r||typeof r!="object"||Array.isArray(r))return{error:{code:"BAD_ROW",line:t,message:"row must be a JSON object",table:""},ok:!1};const n=r;return typeof n.table!="string"||n.table.length===0?{error:{code:"BAD_ROW",line:t,message:"row is missing `table`",table:""},ok:!1}:!n.doc||typeof n.doc!="object"||Array.isArray(n.doc)?{error:{code:"BAD_ROW",line:t,message:"row is missing or malformed `doc`",table:n.table},ok:!1}:{doc:n.doc,ok:!0,table:n.table}},Rn=(e,t,r,n,o)=>{if(r?.mode.kind==="shardBy"&&typeof r.mode.field=="string"){const d=e[r.mode.field];return d==null?{error:{code:"BAD_ROW",line:o,message:`row missing shard field "${r.mode.field}" for table "${t}"`,table:t},ok:!1}:{ok:!0,shardKey:typeof d=="string"?d:JSON.stringify(d)}}return{ok:!0,shardKey:n}},En=async(e,t,r)=>{if(!e.body)throw new i("Import endpoint requires a request body",{code:"BAD_REQUEST",status:400});const n=[],o=[],d=new Map;let u=0,h=0;const w=e.body.getReader(),R=new TextDecoder;let I="",b=0;const k=p=>{h+=1;const g=p.trim();if(g.length===0)return;u+=1;const E=_n(g,h);if(!E.ok){n.push(E.error);return}const{doc:_,table:O}=E,N=t.resolveTableSharding?.(O);if(N?.mode.kind==="global"){o.push({doc:_,line:h,table:O});return}const A=Rn(_,O,N,r,h);if(!A.ok){n.push(A.error);return}const j=d.get(A.shardKey);j?j.rows.push({doc:_,table:O}):d.set(A.shardKey,{rows:[{doc:_,table:O}],shardKey:A.shardKey,startLine:h})};for(;;){const{done:p,value:g}=await w.read();if(p)break;if(g&&(b+=g.byteLength,b>Et))throw await w.cancel().catch(()=>{}),new i("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});I+=R.decode(g,{stream:!0});let E=I.indexOf(`
|
|
3
|
+
`);for(;E!==-1;){const _=I.slice(0,E);I=I.slice(E+1),k(_),E=I.indexOf(`
|
|
4
|
+
`)}}return I.length>0&&k(I),{errors:n,globalRows:o,perShard:d,received:u}},it=(e,t)=>{for(const[r,n]of Object.entries(t.inserted))e.inserted[r]=(e.inserted[r]??0)+n;for(const r of t.errors)e.errors.push({...r});e.conflicts+=t.conflicts},Sn=async(e,t,r,n)=>{const o=t.defaultShardKey??"__root__",{errors:d,globalRows:u,perShard:h,received:w}=await En(e,t,o),R={conflicts:0,errors:d,inserted:{}},I=[];if(t.resolveTableSharding===void 0&&h.size>0&&I.push("no `resolveTableSharding` is configured, so every row was routed to the default shard and no row could be recognised as `.global()` — correct for a single-shard app, silent misplacement for a sharded one"),h.size>0){const b=t.queryCoordinator;if(!b)throw new i("Import endpoint requires a `queryCoordinator` on the worker",{code:"BAD_REQUEST",status:400});const k=await b.orchestrateImport(n,{batches:[...h.values()],headers:r});it(R,k)}if(u.length>0)if(t.importGlobals){const b=u[0]?.line??1,k=await t.importGlobals({rows:u,startLine:b});it(R,k)}else for(const b of u)R.errors.push({code:"GLOBAL_NOT_CONFIGURED",line:b.line,message:`row targets global table "${b.table}" but no \`importGlobals\` is configured`,table:b.table});return{conflicts:R.conflicts,errors:R.errors,inserted:R.inserted,received:w,...I.length>0?{warnings:I}:{}}},Be=e=>typeof e=="object"&&e!==null?e:{},$e=e=>typeof e.kind=="string"?e.kind:"unknown",Tn=(e,t)=>{let r=Be(t),n=!1;$e(r)==="optional"&&(n=!0,r=Be(r._meta?.inner));const o=$e(r),d=r._meta??{},u={kind:o,name:e,optional:n};if(o==="id"&&typeof d.tableName=="string"&&(u.table=d.tableName),o==="array"){const h=$e(Be(d.inner));h!=="unknown"&&(u.element=h)}return u},On=e=>typeof e!="object"||e===null?[]:Object.entries(e).map(([t,r])=>Tn(t,r)).toSorted((t,r)=>t.name.localeCompare(r.name)),An="/_lunora/admin/functions",vn="/_lunora/admin/cron-jobs",kn="/_lunora/admin/openapi",In="/_lunora/admin/openrpc",Dn="/_lunora/admin/global/tables",Pn="/_lunora/admin/global/table",Un="/_lunora/admin/global/facet",ct=e=>{if(e===void 0||e==="")return;let t;try{t=JSON.parse(e)}catch{return}if(!Array.isArray(t))return;const r=t.flatMap(n=>{if(typeof n!="object"||n===null||typeof n.column!="string")return[];const{column:o,value:d}=n;return[{column:o,value:d}]});return r.length===0?void 0:r},Nn=Object.freeze({info:{description:'No OpenAPI spec is configured on this worker. Run `lunora codegen`, then wire the generated module to `createWorker`: `import { openApiSpec } from "./lunora/_generated/openapi"`.',title:"Lunora API",version:"0.0.0"},openapi:"3.1.0",paths:{}}),qn=Object.freeze({info:{description:'No OpenRPC spec is configured on this worker. Run `lunora codegen --api-spec openrpc` (or `both`), then wire the generated module to `createWorker`: `import { openRpcSpec } from "./lunora/_generated/openrpc"`.',title:"Lunora RPC",version:"0.0.0"},methods:[],openrpc:"1.3.2"}),Cn=e=>{const{assertAdmin:t,options:r,parsePaging:n,queryParameter:o,requireAdminOption:d}=e,u=p=>{L(p,"GET","Functions");const g=d(p,r.functions,{code:"FUNCTIONS_NOT_CONFIGURED",message:"functions endpoint requires a `functions` registry on the worker"}),E=Object.entries(g).flatMap(([_,O])=>O.visibility==="internal"||O.kind==="stream"?[]:[{args:On(O.args),kind:O.kind,path:_}]).toSorted((_,O)=>_.path.localeCompare(O.path));return Response.json({functions:E},{headers:{"content-type":"application/json"},status:200})},h=p=>{L(p,"GET","Cron-jobs");const g=d(p,r.cronJobs,{code:"CRON_JOBS_NOT_CONFIGURED",message:"cron-jobs endpoint requires a `cronJobs` map on the worker"}),E=Object.entries(g).flatMap(([_,O])=>O.map(N=>({args:N.args,cron:_,functionPath:N.functionPath,name:N.name,shardKey:N.shardKey,workflow:N.workflow}))).toSorted((_,O)=>_.name.localeCompare(O.name));return Response.json({jobs:E},{headers:{"content-type":"application/json"},status:200})},w=p=>(L(p,"GET","OpenAPI"),t(p),Response.json(r.openApiSpec??Nn,{headers:{"content-type":"application/json"},status:200})),R=p=>(L(p,"GET","OpenRPC"),t(p),Response.json(r.openRpcSpec??qn,{headers:{"content-type":"application/json"},status:200})),I=async p=>{L(p,"GET","Global-tables");const g=d(p,r.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"});return Response.json(await g.listTables(),{headers:{"content-type":"application/json"},status:200})},b=async p=>{L(p,"GET","Global-table");const g=d(p,r.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),E=new URL(p.url),_=o(E,"table");if(_===void 0)throw new i("Global-table endpoint requires a `table` query param",{code:"BAD_REQUEST",status:400});const O=await g.readTablePage({...n(p),filters:ct(o(E,"filters")),table:_});return Response.json(O,{headers:{"content-type":"application/json"},status:200})},k=async p=>{L(p,"GET","Global-facet");const g=d(p,r.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),E=new URL(p.url),_=o(E,"table"),O=o(E,"column");if(_===void 0||O===void 0)throw new i("Global-facet endpoint requires `table` and `column` query params",{code:"BAD_REQUEST",status:400});const N=o(E,"limit"),A=N===void 0?void 0:Number(N),j=await g.facetColumn({column:O,filters:ct(o(E,"filters")),limit:A!==void 0&&Number.isFinite(A)?A:void 0,table:_});return Response.json(j,{headers:{"content-type":"application/json"},status:200})};return{[vn]:h,[An]:u,[Un]:k,[Pn]:b,[Dn]:I,[kn]:w,[In]:R}},xn="/_lunora/admin/kv/namespaces",jn="/_lunora/admin/kv/keys",Dt="/_lunora/admin/kv/value",Pt=32*1048576,dt=60,Bn=e=>{const{readJsonBody:t,requireAdminOption:r}=e,n=b=>r(b,e.kvIntrospector,{code:"KV_NOT_CONFIGURED",message:"KV endpoints require a `kvIntrospector` on the worker"}),o=b=>Response.json(b,{headers:{"content-type":"application/json"},status:200}),d=(b,k)=>{const p=new URL(b.url),g=p.searchParams.get("namespace")??"",E=p.searchParams.get("key")??"";if(g==="")throw new i(`KV-value ${k} request requires a \`namespace\` query parameter`,{code:"BAD_REQUEST",status:400});if(E==="")throw new i(`KV-value ${k} request requires a \`key\` query parameter`,{code:"BAD_REQUEST",status:400});return{key:E,namespace:g}},u=async(b,k)=>{if(!(await b.listNamespaces()).some(p=>p.binding===k))throw new i(`Unknown KV namespace binding \`${k}\``,{code:"NOT_FOUND",status:404})},h=async b=>(L(b,"GET","KV-namespaces"),o({namespaces:await n(b).listNamespaces()})),w=async b=>{L(b,"GET","KV-keys");const k=n(b),p=new URL(b.url),g=p.searchParams.get("namespace")??"";if(g==="")throw new i("KV-keys request requires a `namespace` query parameter",{code:"BAD_REQUEST",status:400});const E=p.searchParams.get("prefix")??void 0,_=p.searchParams.get("cursor")??void 0,O=p.searchParams.get("limit"),N=O===null?void 0:Number.parseInt(O,10);if(N!==void 0&&(!Number.isInteger(N)||N<1))throw new i("KV-keys `limit` must be a positive integer",{code:"BAD_REQUEST",status:400});const A=N===void 0?void 0:Math.min(N,1e3);return await u(k,g),o(await k.listKeys({cursor:_,limit:A,namespace:g,prefix:E}))},R={DELETE:async b=>{const k=n(b),p=d(b,"DELETE");return await u(k,p.namespace),await k.deleteKey(p),o({deleted:!0})},GET:async b=>{const k=n(b),p=d(b,"GET");return await u(k,p.namespace),o(await k.getValue(p))},PUT:async b=>{const k=n(b),p=await t(b,Pt);if(typeof p.namespace!="string"||p.namespace==="")throw new i("KV-value PUT request requires a `namespace` string",{code:"BAD_REQUEST",status:400});if(typeof p.key!="string"||p.key==="")throw new i("KV-value PUT request requires a `key` string",{code:"BAD_REQUEST",status:400});if(typeof p.value!="string")throw new i("KV-value PUT request requires a `value` string",{code:"BAD_REQUEST",status:400});if(p.expirationTtl!==void 0&&(typeof p.expirationTtl!="number"||!Number.isInteger(p.expirationTtl)||p.expirationTtl<dt))throw new i("KV-value PUT `expirationTtl` must be an integer ≥ 60",{code:"BAD_REQUEST",status:400});const g=Math.floor(Date.now()/1e3)+dt;if(p.expiration!==void 0&&(typeof p.expiration!="number"||!Number.isInteger(p.expiration)||p.expiration<g))throw new i("KV-value PUT `expiration` must be a Unix-seconds timestamp at least 60 seconds in the future",{code:"BAD_REQUEST",status:400});return await u(k,p.namespace),await k.putValue({expiration:p.expiration,expirationTtl:p.expirationTtl,key:p.key,metadata:p.metadata,namespace:p.namespace,value:p.value}),o({ok:!0})}},I=b=>{const k=R[b.method];if(!k)throw new i("KV-value endpoint requires GET, PUT, or DELETE",{code:"METHOD_NOT_ALLOWED",status:405});return k(b)};return{[xn]:h,[jn]:w,[Dt]:I}},$n="/_lunora/migrate",Ln="/_lunora/admin/pitr",Kn="/_lunora/admin/rank",Gn="/_lunora/admin/rankpage",Fn="/_lunora/admin/shard-traffic",Qn=new Set(["__lunora_admin__:migrationStatus","__lunora_admin__:runMigration"]),Mn=new Set(["__lunora_admin__:getPitrBookmark","__lunora_admin__:pitrRestore"]),zn=async e=>{const t=await ye(e,"Migration")??{};if(typeof t.table!="string"||t.table.length===0)throw new i("Migration request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof t.functionPath!="string"||!Qn.has(t.functionPath))throw new i("Migration request `functionPath` must be a migration admin op",{code:"BAD_REQUEST",status:400});return{args:t.args??{},functionPath:t.functionPath,table:t.table}},Wn=async e=>{const t=await ye(e,"Rank")??{};if(typeof t.table!="string"||t.table.length===0)throw new i("Rank request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof t.index!="string"||t.index.length===0)throw new i("Rank request is missing `index`",{code:"BAD_REQUEST",status:400});if(typeof t.partitionKey!="string")throw new i("Rank request `partitionKey` must be a string",{code:"BAD_REQUEST",status:400});if(typeof t.rowId!="string"||t.rowId.length===0)throw new i("Rank request is missing `rowId`",{code:"BAD_REQUEST",status:400});if(!Array.isArray(t.sortValues))throw new i("Rank request `sortValues` must be an array",{code:"BAD_REQUEST",status:400});return{index:t.index,partitionKey:t.partitionKey,rowId:t.rowId,sortValues:t.sortValues,table:t.table}},Hn=e=>{if(e!==void 0){if(!Array.isArray(e)||e.some(t=>t!=="asc"&&t!=="desc"))throw new i('Rank page request `directions` must be an array of "asc"|"desc"',{code:"BAD_REQUEST",status:400});return e}},Jn=e=>{if(typeof e.table!="string"||e.table.length===0)throw new i("Rank page request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof e.index!="string"||e.index.length===0)throw new i("Rank page request is missing `index`",{code:"BAD_REQUEST",status:400});if(e.partitionKey!==void 0&&typeof e.partitionKey!="string")throw new i("Rank page request `partitionKey` must be a string",{code:"BAD_REQUEST",status:400});if(e.take!==void 0&&(typeof e.take!="number"||!Number.isFinite(e.take)))throw new i("Rank page request `take` must be a number",{code:"BAD_REQUEST",status:400});if(e.cursor!==void 0&&e.cursor!==null&&typeof e.cursor!="string")throw new i("Rank page request `cursor` must be a string or null",{code:"BAD_REQUEST",status:400})},Vn=async e=>{const t=await ye(e,"Rank page")??{};Jn(t);const r=Hn(t.directions);return{cursor:typeof t.cursor=="string"?t.cursor:null,directions:r,index:t.index,partitionKey:typeof t.partitionKey=="string"?t.partitionKey:void 0,table:t.table,take:typeof t.take=="number"?t.take:void 0}},Yn=async e=>{const t=await ye(e,"Shard-traffic")??{};if(typeof t.table!="string"||t.table.length===0)throw new i("Shard-traffic request is missing `table`",{code:"BAD_REQUEST",status:400});return{table:t.table}},Xn=async e=>{const t=await ee(e);if(typeof t.functionPath!="string"||!Mn.has(t.functionPath))throw new i("PITR request `functionPath` must be a PITR admin op",{code:"BAD_REQUEST",status:400});if(t.shardKey!==void 0&&typeof t.shardKey!="string")throw new i("PITR `shardKey` must be a string",{code:"BAD_REQUEST",status:400});return{args:t.args??{},functionPath:t.functionPath,shardKey:t.shardKey}},Zn=e=>{const{defaultShard:t,forwardToShard:r,isAdmin:n,queryCoordinator:o,resolveForwardContext:d,shardDO:u}=e,h=(p,g)=>{if(p.method!=="POST")throw new i(`${g} endpoint requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});if(!n(p))throw new i("Admin auth required",{code:"FORBIDDEN",status:403});if(!o)throw new i(`${g} endpoint requires a \`queryCoordinator\` on the worker`,{code:"BAD_REQUEST",status:400});return o},w=async(p,g)=>{const E=h(p,"Migration"),_=await zn(p),{headers:O}=await d(p,g),N=await E.orchestrateMigration(u,{args:_.args,functionPath:_.functionPath,headers:O,table:_.table});return Response.json(N,{headers:{"content-type":"application/json"},status:200})},R=async(p,g)=>{const E=h(p,"Rank"),_=await Wn(p),{headers:O}=await d(p,g),N=await E.orchestrateRank(u,{headers:O,index:_.index,partitionKey:_.partitionKey,rowId:_.rowId,sortValues:_.sortValues,table:_.table});return Response.json(N,{headers:{"content-type":"application/json"},status:200})},I=async(p,g)=>{const E=h(p,"Rank page"),_=await Vn(p),{headers:O}=await d(p,g),N=await E.orchestrateRankPage(u,{..._,headers:O});return Response.json(N,{headers:{"content-type":"application/json"},status:200})},b=async(p,g)=>{const E=h(p,"Shard-traffic"),_=await Yn(p),{headers:O}=await d(p,g),N=await E.orchestrateShardTraffic(u,{headers:O,table:_.table});return Response.json(N,{headers:{"content-type":"application/json"},status:200})},k=async(p,g)=>{if(L(p,"POST","PITR"),!n(p))throw new i("admin PITR endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403});const E=await Xn(p),{headers:_}=await d(p,g),O=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:E.args,functionPath:E.functionPath}),headers:_,method:"POST"});return r(u,E.shardKey??t,O)};return{[$n]:w,[Ln]:k,[Kn]:R,[Gn]:I,[Fn]:b}},ea=1,ta=0,ra=32,na=512,aa=/^[a-z][\d_a-z*/-]{0,255}(?:@[a-z][\d_a-z*/-]{0,13})?=[\u0020-\u002B\u002D-\u003C\u003E-\u007E]{1,256}$/,oa=e=>{if(e==null)return;const t=e.trim();if(t.length===0||t.length>na)return;const r=t.split(",");if(!(r.length>ra)){for(const n of r)if(!aa.test(n.trim()))return;return t}},sa=e=>{const t=br(e.headers.get("traceparent"));if(t===void 0)return;const r=oa(e.headers.get("tracestate"));return{parentSpanId:t.parentSpanId,sampled:t.sampled,traceId:t.traceId,...r===void 0?{}:{traceState:r}}},ia=(e,t={})=>{const r=sa(e),n=t.trustInbound===!0?r:void 0,o=Oe(8),d=n?.traceId??Oe(16),u=Ur(t.sampling,n===void 0?o:d),h=u.isTraced&&(n===void 0||n.sampled);return{decision:u,ignoredUpstream:r!==void 0&&n===void 0,trace:{sampled:h,spanId:o,traceFlags:h?ea:ta,traceId:d,...n?.parentSpanId===void 0?{}:{parentSpanId:n.parentSpanId},...n?.traceState===void 0?{}:{traceState:n.traceState}}}},ca=(e,t)=>{t.traceparent=yr(e.traceId,e.spanId,e.sampled),e.traceState!==void 0&&(t.tracestate=e.traceState)},da=(e,t)=>{let r;return()=>{if(r===void 0){const n=Sr(e),o=t===void 0?void 0:t.cf;r=_r(Er(n),Rr(n,o))}return r}},ua="/_lunora/admin/scheduled",la="/_lunora/admin/scheduled/status",ha="/_lunora/admin/scheduled/ws",pa="/_lunora/admin/scheduled/cancel",fa="/_lunora/admin/scheduled/dead",ma="/_lunora/admin/scheduled/dead/retry",wa="/_lunora/admin/scheduled/dead/cancel",ga=e=>{const{checkWsAdmin:t,requireSchedulerNamespace:r,resolveSchedulerStub:n,schedulerInstanceName:o}=e,d=(w,R)=>I=>{if(I.method!=="GET")throw new i(`${R} endpoint requires GET`,{code:"METHOD_NOT_ALLOWED",status:405});return n(I).fetch(new Request(`https://scheduler.internal${w}`,{method:"GET"}))},u=(w,R,I=R)=>async b=>{if(b.method!=="POST")throw new i(`${I} requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});const k=n(b),p=await b.json().catch(()=>{});if(typeof p?.id!="string"||p.id==="")throw new i(`${R} requires a string \`id\``,{code:"BAD_REQUEST",status:400});return k.fetch(new Request(`https://scheduler.internal${w}`,{body:JSON.stringify({id:p.id}),headers:{"content-type":"application/json"},method:"POST"}))},h=async w=>{if(w.headers.get("Upgrade")!=="websocket")throw new i("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});if(!await t(w))throw new i("admin authorization required",{code:"ADMIN_FORBIDDEN",status:403});const R=r();return Ae(R,o).fetch(new Request("https://scheduler.internal/ws",{headers:{Upgrade:"websocket"}}))};return{[pa]:u("/cancel","Scheduled-cancel","Scheduled-cancel endpoint"),[wa]:u("/dead/cancel","Scheduled dead-letter action"),[fa]:d("/dead","Scheduled dead-letter"),[ma]:u("/dead/retry","Scheduled dead-letter action"),[ua]:d("/list","Scheduled-list"),[la]:d("/status","Scheduler-status"),[ha]:h}},Ut="/_lunora/admin/storage",ya="/_lunora/admin/storage/url",ba="/_lunora/admin/storage/buckets",_a=10080*60,Nt=32*1048576,Ra=new Set(["GET","PUT"]),Ea=e=>{const t=new Uint8Array(e);let r="";for(const n of t)r+=n.toString(16).padStart(2,"0");return r},Sa=e=>{const{assertAdmin:t,parsePaging:r,queryParameter:n,readBodyBytes:o,requireAdminOption:d,storage:u}=e,h=g=>{const E=n(g,"key");if(E===void 0)throw new i("Storage endpoint requires a `key` query parameter",{code:"BAD_REQUEST",status:400});return E},w=async g=>{const E=d(g,u.storageList,{code:"STORAGE_NOT_CONFIGURED",message:"storage endpoint requires a `storageList` function on the worker"}),_=new URL(g.url),O=await E(n(_,"prefix"),{bucket:n(_,"bucket"),cursor:n(_,"cursor"),...r(g)});return Response.json(O,{headers:{"content-type":"application/json"},status:200})},R=g=>(L(g,"GET","Storage-buckets"),t(g),Response.json({buckets:u.storageBuckets??[]},{headers:{"content-type":"application/json"},status:200})),I=async g=>{const E=d(g,u.storageDelete,{code:"STORAGE_DELETE_NOT_CONFIGURED",message:"storage delete requires a `storageDelete` function on the worker"}),_=new URL(g.url),O=h(_);return await E(O,{bucket:n(_,"bucket")}),Response.json({deleted:!0,key:O},{headers:{"content-type":"application/json"},status:200})},b=async g=>{const E=d(g,u.storageUpload,{code:"STORAGE_UPLOAD_NOT_CONFIGURED",message:"storage upload requires a `storageUpload` function on the worker"}),_=new URL(g.url),O=h(_),N=await o(g,Nt),A=g.headers.get("content-type"),j=A===null||A===""?void 0:A,x=n(_,"expectedSha256"),F=n(_,"expectedSize");let P;if(x!==void 0||F!==void 0){const M=await crypto.subtle.digest("SHA-256",N);P=Ea(M);const B=F!==void 0&&N.byteLength!==Number(F),K=x!==void 0&&P!==x.toLowerCase();if(B||K)throw new i("Upload failed verification — the body did not match the declared size or SHA-256 checksum, so nothing was written",{code:"STORAGE_CHECKSUM_MISMATCH",status:400})}const Q=await E(O,N,{bucket:n(_,"bucket"),contentType:j,sha256:P});return Response.json(P===void 0?Q:{...Q,sha256:P},{headers:{"content-type":"application/json"},status:200})},k=async g=>{switch(g.method){case"DELETE":return I(g);case"GET":return w(g);case"POST":case"PUT":return b(g);default:throw new i("Storage endpoint requires GET, PUT, POST, or DELETE",{code:"METHOD_NOT_ALLOWED",status:405})}},p=async g=>{L(g,"GET","Storage URL");const E=d(g,u.storageSignedUrl,{code:"STORAGE_URL_NOT_CONFIGURED",message:"storage URL endpoint requires a `storageSignedUrl` function on the worker"}),_=new URL(g.url),O=h(_),N=Number(n(_,"expiresIn")??""),A=Number.isFinite(N)&&N>0?Math.min(N,_a):void 0,j=n(_,"method");if(j!==void 0&&!Ra.has(j))throw new i("Storage URL `method` must be GET or PUT",{code:"BAD_REQUEST",status:400});const x=j,F=n(_,"contentType"),P=await E(O,{bucket:n(_,"bucket"),contentType:F,expiresInSeconds:A,method:x});return Response.json({key:O,url:P},{headers:{"content-type":"application/json"},status:200})};return{[ba]:R,[Ut]:k,[ya]:p}},Ta=(e,...t)=>{let r=e.cf;for(const n of t){if(typeof r!="object"||r===null)return;r=r[n]}return typeof r=="string"?r:void 0},ut={mtls:e=>Ta(e,"tlsClientAuth","certVerified")==="SUCCESS"},Oa=e=>e===void 0||e===!1?()=>!1:e===!0?()=>!0:typeof e=="function"?e:(Object.hasOwn(ut,e)?ut[e]:void 0)??(()=>!1),Aa=e=>{if(e!==void 0)return()=>{};let t=!1;return()=>{t||(t=!0,console.warn('[lunora] Ignored an inbound `traceparent`, so this request starts a new trace instead of joining the caller\'s. That is the safe default: the header is caller-supplied, and trusting it lets any client choose which trace its spans and logs join. If this worker sits behind a gateway, service mesh, or Cloudflare Access that sets `traceparent` itself, set `trustInboundTraceContext: true` on createWorker() (or `"mtls"` to trust only edge-verified client certificates). Set it to `false` to keep this behaviour and silence this message.'))}},va="/_lunora/admin/vector/indexes",ka="/_lunora/admin/vector/query",Ia=e=>{const{readJsonBody:t,requireAdminOption:r}=e,n=async d=>{L(d,"GET","Vector-indexes");const u=r(d,e.vectorIntrospector,{code:"VECTORS_NOT_CONFIGURED",message:"vector endpoints require a `vectorIntrospector` on the worker"});return Response.json({indexes:await u.listIndexes()},{headers:{"content-type":"application/json"},status:200})},o=async d=>{L(d,"POST","Vector-query");const u=r(d,e.vectorIntrospector,{code:"VECTORS_NOT_CONFIGURED",message:"vector endpoints require a `vectorIntrospector` on the worker"});if(u.queryIndex===void 0)throw new i("vector index querying is not enabled on this worker",{code:"VECTOR_QUERY_UNSUPPORTED",status:400});const h=await t(d);if(typeof h.name!="string"||h.name==="")throw new i("Vector-query request requires a `name` string",{code:"BAD_REQUEST",status:400});if(typeof h.text!="string"||h.text==="")throw new i("Vector-query request requires a `text` string",{code:"BAD_REQUEST",status:400});if(h.topK!==void 0&&(typeof h.topK!="number"||!Number.isInteger(h.topK)||h.topK<1))throw new i("Vector-query `topK` must be a positive integer",{code:"BAD_REQUEST",status:400});const w=await u.queryIndex({name:h.name,text:h.text,topK:h.topK});return Response.json(w,{headers:{"content-type":"application/json"},status:200})};return{[va]:n,[ka]:o}},Da="/_lunora/admin/workflows/instances",Pa="/_lunora/admin/workflows/instance",Ua="/_lunora/admin/workflows/status",Na={complete:!0,errored:!0,paused:!0,queued:!0,running:!0,terminated:!0,unknown:!0,waiting:!0,waitingForPause:!0},qa=e=>e!==null&&Object.hasOwn(Na,e)?e:void 0,lt=(e,t)=>{const r=e.searchParams.get(t);if(r===null)return;const n=Number(r);return Number.isInteger(n)&&n>0?n:void 0},Le=(e,t)=>{const r=e.searchParams.get(t);if(r===null||r==="")throw new i(`Workflows admin endpoint requires a \`${t}\` query parameter`,{code:"BAD_REQUEST",status:400});return r},ht=()=>{throw new i("Workflow inspection is unconfigured. Set CLOUDFLARE_ACCOUNT_ID + CLOUDFLARE_API_TOKEN in your .dev.vars to enable it.",{code:"WORKFLOWS_NOT_CONFIGURED",status:501})},Ca=e=>{const{assertAdmin:t,resolveWorkflowsClient:r}=e,n=async(u,h,w)=>{L(u,"GET","Workflows instances"),t(u);const R=r(h);if(!R)return Response.json({configured:!1,instances:[],page:1,perPage:0,totalCount:0});const I=Le(w,"name"),b=qa(w.searchParams.get("status"));return Response.json(await R.listInstances({page:lt(w,"page"),perPage:lt(w,"perPage"),status:b,workflowName:I}))},o=async(u,h,w)=>{L(u,"GET","Workflows instance"),t(u);const R=r(h);return R?Response.json(await R.getInstance({instanceId:Le(w,"id"),workflowName:Le(w,"name")})):ht()},d=async(u,h)=>{L(u,"POST","Workflows status"),t(u);const w=r(h);if(!w)return ht();const R=await u.json().catch(()=>{});if(typeof R?.name!="string"||R.name===""||typeof R.id!="string"||R.id==="")throw new i("Workflows status action requires string `name` and `id`",{code:"BAD_REQUEST",status:400});const{action:I}=R;if(I!=="pause"&&I!=="resume"&&I!=="terminate")throw new i("Workflows status action must be one of: pause, resume, terminate",{code:"BAD_REQUEST",status:400});return Response.json(await w.setInstanceStatus({action:I,instanceId:R.id,workflowName:R.name}))};return{[Pa]:o,[Da]:n,[Ua]:d}},xa={[Dt]:Pt,[Ut]:Nt},ja=new TextEncoder,pt="/_lunora/rpc",Ba="/_lunora/rpc-batch",$a="/_lunora/ws",Re=(e,t,r)=>({resourceAttributes:da(e,t),...r===void 0?{}:{waitUntil:r}}),ft=e=>e?.waitUntil?{waitUntil:t=>e.waitUntil?.(t)}:{},mt=e=>({spanId:e.spanId,traceFlags:e.traceFlags,traceId:e.traceId,...e.parentSpanId===void 0?{}:{parentSpanId:e.parentSpanId}}),Ke=e=>{const{method:t}=e,r=e.headers.get("user-agent")??void 0;let n;try{n=new URL(e.url)}catch{return{method:t,userAgent:r}}const o=n.port===""?void 0:Number(n.port);return{host:n.hostname,method:t,path:n.pathname,port:Number.isNaN(o)?void 0:o,scheme:n.protocol.replace(":",""),userAgent:r}},wt="/_lunora/voice/",La="/_lunora/scheduler/dispatch",Ka="/_lunora/admin/cron-jobs/run",Ga="/_lunora/admin/ws-token",Fa="/_lunora/admin/",Qa="/_lunora/migrate",Ma="/_lunora/status",za=e=>e.startsWith(Fa)||e===Qa,Wa=e=>{const t=e.headers.get("x-lunora-userid"),r=e.headers.get("x-lunora-identity");if(!(t===null&&r===null))return{...r===null?{}:{identity:r},...t===null?{}:{userId:t}}},Ha="/api/auth",Ja="__lunora_admin__:recordAuthEvent",Va="__lunora_admin__:listPushSubscriptions",Ya=["/sign-in","/sign-up","/callback"],Xa=(e,t)=>{const r=t.endsWith("/")?t.slice(0,-1):t;if(!e.startsWith(`${r}/`))return!1;const n=e.slice(r.length);return Ya.some(o=>n===o||n.startsWith(`${o}/`))},Ee=(e,t,r,n)=>{const o=pr(r),d=o?r.code:"INTERNAL_SERVER_ERROR",u=o?r.status:500,h=r instanceof Error?r.message:String(r);return{durationMs:t,error:{code:d,message:h,status:u},functionPath:e,ok:!1,...n.fanOut?{fanOut:{failed:0,shards:0,table:n.fanOut.table}}:{},...n.shardKey?{shardKey:n.shardKey}:{}}},Za=e=>{const{exp:t,expiresAtMs:r}=e;if(typeof r=="number"&&Number.isFinite(r))return r;if(typeof t=="number"&&Number.isFinite(t))return t*1e3},gt=e=>e.waitUntil?{waitUntil:t=>{e.waitUntil?.(t)}}:void 0,eo=e=>{const t=e?.queue;return typeof t=="string"&&t.length>0?t:"unknown"},de=async(e,t,r)=>{const n={"content-type":"application/json"},o=e.headers.get("authorization"),d=e.headers.get("cookie"),u=e.headers.get("x-d1-bookmark"),h=e.headers.get("x-lunora-mutation-id"),w=e.headers.get("x-lunora-client-id"),R=e.headers.get("x-lunora-client-seq");o&&(n.authorization=o),d&&(n.cookie=d),u&&(n["x-d1-bookmark"]=u),h&&(n["x-lunora-mutation-id"]=h),w&&(n["x-lunora-client-id"]=w),R&&(n["x-lunora-client-seq"]=R);const I=e.headers.get("cf-connecting-ip");if(I&&(n["x-lunora-client-ip"]=I),!r)return{claims:null,headers:n,identity:null,userId:null};const b=await r(e,t);if(!b||typeof b.userId!="string"||b.userId.length===0)return{claims:null,headers:n,identity:null,userId:null};n["x-lunora-userid"]=wr(b.userId);const k=Za(b);k!==void 0&&(n["x-lunora-identity-exp"]=String(k));const{userId:p,...g}=b,E=Object.keys(g).length>0?g:null;return E&&(n["x-lunora-identity"]=gr(E)),{claims:E,headers:n,identity:b,userId:p}},to=new Set(["concat","first","groupBy","max","min","rank","sum","topK"]),ro=e=>{if(e===void 0)return;if(!e||typeof e!="object")throw new i("RPC `fanOut` must be an object",{code:"BAD_REQUEST",status:400});const t=e;if(typeof t.table!="string"||t.table.length===0)throw new i("RPC `fanOut.table` must be a non-empty string",{code:"BAD_REQUEST",status:400});if(!t.merge||typeof t.merge!="object")throw new i("RPC `fanOut.merge` must be an object",{code:"BAD_REQUEST",status:400});const r=t.merge;if(typeof r.kind!="string"||!to.has(r.kind))throw new i("RPC `fanOut.merge.kind` is not a recognized merge strategy",{code:"BAD_REQUEST",status:400});if(r.kind==="topK"){if(typeof r.k!="number"||!Number.isInteger(r.k)||r.k<0)throw new i("RPC `fanOut.merge.k` must be a non-negative integer",{code:"BAD_REQUEST",status:400});if(typeof r.by!="string"||r.by.length===0)throw new i("RPC `fanOut.merge.by` must be a non-empty string",{code:"BAD_REQUEST",status:400})}return t},no=(e,t)=>{e?.LUNORA_DEBUG_RPC&&console.warn(`[lunora:rpc] ${t.fanOut?"fan-out":`shard=${t.shardKey??"(root)"}`} ${t.functionPath}`)},yt=(e,t)=>{const r=t.functions?.[e.functionPath]?.x402;if(r){if(e.fanOut)throw new i("a paid (`.x402`) function cannot be fanned out",{code:"BAD_REQUEST",status:400});if(!t.x402Charge)throw new i(`function "${e.functionPath}" is marked paid (.x402) but no x402Charge gate is configured on the worker`,{code:"MISCONFIGURED",status:500});return r}},ao=async e=>{const t=await St(e);let r;try{r=JSON.parse(t)}catch{throw new i("RPC body must be valid JSON",{code:"BAD_REQUEST",status:400})}if(!r||typeof r!="object"||typeof r.functionPath!="string")throw new i("RPC envelope is missing `functionPath`",{code:"BAD_REQUEST",status:400});const n=r;if(n.args!==void 0&&Tt(n.args,"RPC"),n.shardKey!==void 0&&typeof n.shardKey!="string")throw new i("RPC `shardKey` must be a string",{code:"BAD_REQUEST",status:400});const o=r,d=ro(o.fanOut),u=o.args??{};if(d&&o.functionPath.startsWith("__lunora_relation__:")){const h=u.table;if(typeof h=="string"&&h!==d.table)throw new i("RPC `args.table` must match the authorized `fanOut.table` for a relation fan-out",{code:"BAD_REQUEST",status:400});u.table=d.table}return{args:u,fanOut:d,functionPath:o.functionPath,shardKey:o.shardKey}},oe=async(e,t,r)=>Ae(e,t).fetch(r),Se=new Map,oo=5e3,so=4096,io=async(e,t)=>{const r=Date.now(),n=Se.get(t);if(n!==void 0&&n.expiresMs>r)return n.relayCount;n!==void 0&&Se.delete(t);let o=0;try{const d=await Ae(e,t).fetch(new Request("https://shard.internal/_lunora/route"));if(d.ok){const u=(await d.json()).relayCount;typeof u=="number"&&u>0&&(o=Math.floor(u))}}catch{o=0}return Rt(Se,so),Se.set(t,{expiresMs:r+oo,relayCount:o}),o},co=(e,t)=>{if(!(e===null||typeof e!="object"))return Object.entries(e).find(([,r])=>r===t)?.[0]},Te=(e,t,r)=>new Request("https://shard.internal/rpc",{body:JSON.stringify({args:t,functionPath:e}),headers:r,method:"POST"}),uo=["x-lunora-userid","x-lunora-identity","x-lunora-identity-exp"],bt=(e,t)=>{for(const r of uo){e.delete(r);const n=t[r];n!==void 0&&e.set(r,n)}},lo=async(e,t,r)=>e.length===0||r.length===0?!1:Ge(await vt(e,t),r),_t=(e,t)=>{if(!t||t.length===0)return!1;const r=e.headers.get("authorization");if(!r)return!1;const[n,...o]=r.split(" ");return n?.toLowerCase()!=="bearer"?!1:Ge(t,o.join(" ").trim())},ho=async(e,t,r)=>{if(!t||t.length===0)return!1;const n=new URL(e.url).searchParams.get("token");return n===null?!1:await Vr(t,n)?!0:r?!1:Ge(t,n)},po=(e,t)=>{if(t===null||typeof t!="object"&&typeof t!="function")return;const r=t;if(typeof r.prepare=="function"&&typeof r.batch=="function"&&typeof r.dump=="function")return Ir(`d1:${e}`,t);if(typeof r.list=="function"&&typeof r.head=="function"&&typeof r.createMultipartUpload=="function")return Ne(`r2:${e}`,!0);if(typeof r.send=="function"&&typeof r.sendBatch=="function"&&typeof r.get!="function")return Ne(`queue:${e}`,!0);if(typeof r.connectionString=="string")return Ne(`hyperdrive:${e}`,!0)},qt=e=>{const t=Oa(e.trustInboundTraceContext),r=Aa(e.trustInboundTraceContext),n=e.defaultShardKey??"__root__",o=Dr(e.resolveIdentity,e.identity),d=Ye(e.shardDO,e.jurisdiction),u=e.schedulerDO===void 0?void 0:Ye(e.schedulerDO,e.jurisdiction);let h;const w=()=>e.adminToken??h;let R;const I=()=>e.requireEphemeralWsToken??R??!0,b=a=>{const s=a??{};if(R===void 0&&e.requireEphemeralWsToken===void 0){const c=s.LUNORA_REQUIRE_EPHEMERAL_WS_TOKEN;typeof c=="string"&&c.length>0&&(R=Wr(c,!0))}if(h!==void 0||e.adminToken!==void 0)return;const l=s.LUNORA_ADMIN_TOKEN;typeof l=="string"&&l.length>0&&(h=l)},k=new WeakSet,p=a=>_t(a,w())||k.has(a),g=async(a,s)=>{const l=await de(a,s,e.resolveIdentity);if(k.has(a)&&l.headers.authorization===void 0){const c=w();c!==void 0&&(l.headers.authorization=`Bearer ${c}`)}return l};let E=!1;const _=a=>{if(!e.allowUnauthenticatedShardAccess){const s=a==="fan-out"?"authorizeFanOut":"authorizeShard";throw new i(`${a} access is default-denied: configure \`${s}\` on the worker, or set \`allowUnauthenticatedShardAccess: true\` to explicitly allow unauthenticated ${a} access (relying solely on per-row RLS).`,{code:a==="fan-out"?"FORBIDDEN_FANOUT":"FORBIDDEN_SHARD",status:403})}E||(E=!0,console.warn([`[lunora] SECURITY: serving ${a} access with \`allowUnauthenticatedShardAccess: true\` and no \`authorizeShard\`/\`authorizeFanOut\` — `,"any caller (including unauthenticated ones) can target any shard / fan out across the table. ","This is safe only if every table is protected by per-row RLS. Configure `authorizeShard`/`authorizeFanOut` to gate it."].join("")))},O=async(a,s,l=!0)=>{if(e.authorizeShard){if(!await e.authorizeShard(a,s))throw new i("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else l&&s!==n&&_("shard")},N=Zn({defaultShard:n,forwardToShard:oe,isAdmin:p,queryCoordinator:e.queryCoordinator,resolveForwardContext:g,shardDO:d}),A=async(a,s,l,c,m)=>{await O(null,l,!1);const y={"content-type":"application/json","x-lunora-system":"1"};return m?.userId!==void 0&&m.userId.length>0&&(y["x-lunora-userid"]=m.userId),m?.identity!==void 0&&m.identity.length>0&&(y["x-lunora-identity"]=m.identity),c!==void 0&&c.length>0&&(y["x-lunora-mutation-id"]=c),oe(d,l,Te(a,s,y))},j=async(a,s,l,c)=>{const m=l?.[a];if(!m||typeof m.create!="function")throw new i(`${c} targets workflow binding "${a}", which is not bound on env`,{code:"CRON_JOB_FAILED",status:500});if(xr(s))throw new i(`${c} params ${jr}`,{code:"BAD_REQUEST",status:400});await m.create({params:s})},x=async(a,s)=>{if(a.workflow){await j(a.workflow,a.args??{},s,`cron job "${a.name}"`);return}if(a.functionPath===void 0)throw new i(`cron job "${a.name}" has neither a function target nor a workflow target`,{code:"CRON_JOB_FAILED",status:500});const l=await A(a.functionPath,a.args??{},a.shardKey??n);if(!l.ok)throw new i(`cron job "${a.name}" (${a.functionPath}) failed with shard status ${String(l.status)}`,{code:"CRON_JOB_FAILED",status:500})},F=async(a,s,l,c)=>{const m=e.cronJobs?.[a];if(m)for(const y of m)try{await x(y,s)}catch(v){l.push(c(v))}},P=async(a,s)=>{if(!p(a))throw new i("admin endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403});if(L(a,"POST","cron-jobs run"),!e.cronJobs)throw new i("cron-jobs run endpoint requires a `cronJobs` map on the worker",{code:"CRON_JOBS_NOT_CONFIGURED",status:400});const l=await ee(a),c=typeof l.name=="string"?l.name:"";if(c==="")throw new i("cron-jobs run endpoint requires a job `name`",{code:"BAD_REQUEST",status:400});const m=Object.values(e.cronJobs).flat().find(y=>y.name===c);if(!m)throw new i(`no cron job named "${c}" is registered`,{code:"CRON_JOB_NOT_FOUND",status:404});return await x(m,s),Response.json({name:c,ran:!0},{status:200})},Q=async a=>{const s=typeof a.pool=="string"&&a.pool.length>0?a.pool:void 0;if(!s||!u||typeof a.id!="string")return;const l=typeof a.instanceName=="string"&&a.instanceName.length>0?a.instanceName:"default";try{await u.get(u.idFromName(l)).fetch(new Request("https://scheduler.internal/complete",{body:JSON.stringify({id:a.id,pool:s}),headers:{"content-type":"application/json"},method:"POST"}))}catch{}},M=async(a,s)=>{L(a,"POST","Scheduler dispatch");const l=await St(a),c=s??{},m=typeof c.LUNORA_SCHEDULER_SECRET=="string"?c.LUNORA_SCHEDULER_SECRET:void 0,y=e.adminToken??(typeof c.LUNORA_ADMIN_TOKEN=="string"?c.LUNORA_ADMIN_TOKEN:void 0),v=a.headers.get("x-lunora-scheduler-signature");let f=!1;if(v&&m?f=await lo(m,l,v):y&&(f=_t(a,y)),!f)throw new i("Scheduler dispatch requires a valid signature or admin bearer",{code:"FORBIDDEN",status:403});let S;try{S=JSON.parse(l)}catch{throw new i("Scheduler dispatch body must be valid JSON",{code:"BAD_REQUEST",status:400})}const T=S??{},q=T.args??{};if(typeof T.workflow=="string"&&T.workflow.length>0)return await j(T.workflow,q,s,"scheduled workflow"),Response.json({ok:!0},{status:200});if(typeof T.functionPath!="string"||T.functionPath.length===0)throw new i("Scheduler dispatch is missing `functionPath`",{code:"BAD_REQUEST",status:400});const C=typeof T.shardKey=="string"&&T.shardKey.length>0?T.shardKey:n,$=typeof T.id=="string"&&T.id.length>0?T.id:void 0,V=Wa(a),Z=await A(T.functionPath,q,C,$,V);return await Q(T),Z},B=a=>{if(!p(a))throw new i("admin endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403})},K=(a,s,l)=>{if(B(a),s===void 0)throw new i(l.message,{code:l.code,status:400});return s},X=tn({assertAdmin:B,getReader:()=>e.authAuditReader}),J=async(a,s)=>{B(a);const l=e.notifySubscriptionStore;if(l===void 0)return Response.json({subscriptions:[]},{headers:{"content-type":"application/json"},status:200});const c=s?.kind,m=s?.userId,y=s?.limit,v=c==="fcm"||c==="web-push"?c:void 0,f=typeof m=="string"&&m!==""?m:void 0,S=typeof y=="number"&&Number.isFinite(y)?Math.trunc(y):0,T=S>0?Math.min(S,1e3):1e3,q=(await l.list({kind:v,limit:T,userId:f})).filter(C=>v!==void 0&&C.kind!==v?!1:f===void 0||(C.userId??null)===f).map(({keys:C,token:$,...V})=>V);return Response.json({subscriptions:q},{headers:{"content-type":"application/json"},status:200})},ne=async(a,s)=>{if(!s.fanOut){if(s.functionPath===en)return X(a,s.args??{});if(s.functionPath===Va)return J(a,s.args)}},he=gn({applyGlobals:e.applyGlobals,assertAdmin:B,exportCursorStore:e.exportCursorStore,exportSinks:e.exportSinks,knownTables:()=>[],queryCoordinator:e.queryCoordinator,requireAdminOption:K,resolveForwardContext:g,shardDO:d,streamExportRows:(a,s,l,c)=>st(e,a,s,l,c,d),streamingImport:(a,s)=>Sn(a,e,s,d),syncGlobals:e.syncGlobals}),ae=(a,s)=>{const l=a.searchParams.get(s);return l===null||l===""?void 0:l},pe=a=>{const s=new URL(a.url),l=s.searchParams.get("limit"),c=s.searchParams.get("offset"),m=l===null?void 0:Number.parseInt(l,10),y=c===null?void 0:Number.parseInt(c,10);return{limit:m!==void 0&&Number.isFinite(m)&&m>=0?m:void 0,offset:y!==void 0&&Number.isFinite(y)&&y>=0?y:void 0}},be=()=>{if(u===void 0)throw new i("scheduled endpoints require a `schedulerDO` namespace on the worker",{code:"SCHEDULER_NOT_CONFIGURED",status:400});return u},ve=ga({checkWsAdmin:async a=>p(a)||ho(a,w(),I()),requireSchedulerNamespace:be,resolveSchedulerStub:a=>(B(a),Ae(be(),e.schedulerInstanceName??"default")),schedulerInstanceName:e.schedulerInstanceName??"default"}),se=Ca({assertAdmin:B,resolveWorkflowsClient:e.workflowsClient??(()=>{})}),Ct=Sa({assertAdmin:B,parsePaging:pe,queryParameter:ae,readBodyBytes:Or,requireAdminOption:K,storage:{storageBuckets:e.storageBuckets,storageDelete:e.storageDelete,storageList:e.storageList,storageSignedUrl:e.storageSignedUrl,storageUpload:e.storageUpload}}),xt=Ia({readJsonBody:ee,requireAdminOption:K,vectorIntrospector:e.vectorIntrospector}),jt=Bn({kvIntrospector:e.kvIntrospector,readJsonBody:ee,requireAdminOption:K}),Bt=Pr({logArchive:e.logArchive,readJsonBody:ee,requireAdminOption:K}),$t=Cn({assertAdmin:B,options:{cronJobs:e.cronJobs,functions:e.functions,globalIntrospector:e.globalIntrospector,openApiSpec:e.openApiSpec,openRpcSpec:e.openRpcSpec},parsePaging:pe,queryParameter:ae,requireAdminOption:K}),Lt=a=>{const s=[],l=d??a?.SHARD;if(l!==void 0&&s.push(kr("durable-object:default",l,n)),e.health?.disableBindingProbes!==!0)for(const[c,m]of Object.entries(a??{})){const y=po(c,m);y!==void 0&&s.push(y)}for(const c of e.health?.probes??[])s.push(c);return s},Kt=vr({appName:e.health?.appName,appVersion:e.health?.appVersion,auth:e.health?.auth??"public",cacheTtlMs:e.health?.cacheTtlMs,isAdmin:p,resolveProbes:Lt}),Gt=a=>{const s=e.schedulerInstanceName??"default",l=()=>a.get(a.idFromName(s)),c=async(f,S)=>{const T=await l().fetch(new Request(`https://scheduler.internal${f}`,S));if(!T.ok)throw new i(`ctx.scheduler: SchedulerDO ${f} failed (${String(T.status)}): ${await T.text()}`,{code:"INTERNAL",status:500});return await T.json()},m=async(f,S)=>await c(f,{body:JSON.stringify(S),headers:{"content-type":"application/json"},method:"POST"}),y=f=>{const S=f;if(S==null)throw new i("ctx.scheduler: target is required — pass a reference from the generated `internal` / `workflows` / `agents`",{code:"BAD_REQUEST",status:400});if(typeof S.binding=="string"&&S.binding.length>0)return{workflow:S.binding};if(typeof S.__lunoraRef=="string")return{functionPath:S.__lunoraRef};throw new i("ctx.scheduler: expected a reference from the generated `internal` / `workflows` / `agents` — a bare function-path string is refused here, because an HTTP action can be reached unauthenticated",{code:"BAD_REQUEST",status:400})},v=async(f,S,T={})=>{const{id:q}=await m("/schedule",{args:T,scheduledFor:f,...y(S)});return q};return{cancel:async f=>await m("/cancel",{id:f}),get:async f=>await c(`/get?id=${encodeURIComponent(f)}`,{method:"GET"}),list:async()=>await c("/list",{method:"GET"}),runAfter:async(f,S,T)=>{if(!Number.isFinite(f)||f<0)throw new i("ctx.scheduler.runAfter: `delayMs` must be a non-negative finite number",{code:"BAD_REQUEST",status:400});return await v(Date.now()+f,S,T)},runAt:async(f,S,T)=>{if(!Number.isFinite(f))throw new i("ctx.scheduler.runAt: `timestampMs` must be a finite epoch-millisecond number",{code:"BAD_REQUEST",status:400});return await v(f,S,T)}}},Ft=async(a,s,l)=>{const{claims:c,headers:m,userId:y}=await de(a,s,o),v=async(f,S={})=>{const T=f.__lunoraRef;if(typeof T!="string")throw new i("ctx.run*: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});const q=Te(T,S,{...m,"x-lunora-system":"1"}),C=await oe(d,n,q),$=await C.json();if($.error)throw new i($.error.message??"shard RPC failed",{code:$.error.code??"INTERNAL",status:C.status});return $.result};return{auth:{getIdentity:()=>Promise.resolve(c),userId:y},cache:l.cache,fetch:globalThis.fetch.bind(globalThis),runAction:v,runMutation:v,runQuery:v,...u===void 0?{}:{scheduler:Gt(u)},...e.storage===void 0?{}:{storage:Cr(e.storage(s))}}},Qt=async(a,s,l)=>{if(!e.httpRouter)return;const c=await Ft(a,s,l);try{return await e.httpRouter.fetch(a,{...s,__lunoraCtx:c},l)}catch(m){return console.error("[lunora] httpRouter (SSR) handler threw:",m),new Response("Internal Server Error",{status:500})}},Mt=async(a,s,l)=>{if(a.headers.get("Upgrade")!=="websocket")throw new i("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});const c=Ze(a,ie);if(c)return c;const m=l.searchParams.get("shard")??n,{headers:y,identity:v}=await de(a,s,o);await O(v,m);const f=new Headers(a.headers),S=[...f.keys()];for(const q of S)q.startsWith("x-lunora-")&&f.delete(q);bt(f,y);const T=co(s,e.shardDO);if(T!==void 0){f.set("x-lunora-shard-binding",T);const q=await io(d,m);if(q>0){const C=Qr(m,Math.floor(Math.random()*q));return oe(d,C,new Request(a,{headers:f}))}}return oe(d,m,new Request(a,{headers:f}))},zt=async(a,s,l)=>{const{voiceAgents:c}=e;if(c===void 0)return new Response("Not found",{status:404});if(a.headers.get("Upgrade")!=="websocket")return new Response("Expected a WebSocket upgrade",{headers:{allow:"GET"},status:426});const m=Ze(a,ie);if(m)return m;let y;try{y=decodeURIComponent(l.pathname.slice(wt.length))}catch{return new Response("Unknown voice agent",{status:404})}const v=Object.hasOwn(c,y)?c[y]:void 0;if(v===void 0)return new Response("Unknown voice agent",{status:404});const f=l.searchParams.get("threadKey");if(f===null||f.length===0)return new Response("Missing threadKey",{status:400});const{headers:S,identity:T}=await de(a,s,o);if(e.authorizeShard){if(!await e.authorizeShard(T,f))return new Response("Forbidden",{status:403})}else _("shard");const q=new Headers(a.headers);for(const C of q.keys())C.startsWith("x-lunora-")&&q.delete(C);return bt(q,S),oe(v,f,new Request(a,{headers:q}))},Wt=async(a,s,l)=>{if(e.authorizeFanOut){if(!await e.authorizeFanOut(l,a.table,s))throw new i("Forbidden fan-out",{code:"FORBIDDEN_FANOUT",status:403});return}if(s.startsWith("__lunora_relation__:"))throw new i("reverse cross-backend relation reads (`__lunora_relation__:*`) require `authorizeFanOut` to be configured on the worker",{code:"FORBIDDEN_FANOUT",status:403});if(e.authorizeShard)throw new i("Fan-out requires `authorizeFanOut` to be configured on the worker when `authorizeShard` is set",{code:"FORBIDDEN_FANOUT",status:403});_("fan-out")},_e=async(a,s)=>{if(!(!a.fanOut&&a.functionPath.startsWith("__lunora_admin__:"))){if(a.fanOut){await Wt(a.fanOut,a.functionPath,s);return}await O(s,a.shardKey??n)}},ke=async(a,s,l,c,m,y)=>{const v=Date.now(),{observability:f,sampling:S}=e,T=Ke(a),{decision:q,ignoredUpstream:C,trace:$}=ia(a,{...S===void 0?{}:{sampling:S},trustInbound:t(a)});C&&r();const V={...m,"x-lunora-sample-errors":q.keepErrors?"1":"0"};ca($,V);const Z=Te(s,l,V);try{const G=await oe(d,c,Z);return ce(f,{...T,...mt($),durationMs:Date.now()-v,functionPath:s,ok:G.ok,shardKey:c,...G.ok?{}:{error:{code:"SHARD_ERROR",message:`shard returned ${String(G.status)}`,status:G.status}}},y,void 0,{isTraced:$.sampled,keepErrors:q.keepErrors}),G}catch(G){throw ce(f,{...T,...mt($),...Ee(s,Date.now()-v,G,{shardKey:c})},y,void 0,{isTraced:$.sampled,keepErrors:q.keepErrors}),G}},Ht=a=>{if(a.fanOut&&a.shardKey)throw new i("RPC envelope cannot set both `shardKey` and `fanOut`",{code:"BAD_REQUEST",status:400});if(!a.fanOut&&a.functionPath.startsWith("__lunora_relation__:"))throw new i("`__lunora_relation__:*` is a fan-out-only reserved RPC and cannot be dispatched to a single shard",{code:"FORBIDDEN",status:403});if(a.fanOut&&!e.queryCoordinator)throw new i("RPC envelope set `fanOut` but no `queryCoordinator` is configured on the worker",{code:"BAD_REQUEST",status:400})},Jt=async(a,s,l)=>{L(a,"POST","RPC");const c=await ao(a);no(s,c),Ht(c);const m=await ne(a,c);if(m!==void 0)return m;const{headers:y,identity:v}=await de(a,s,o);await _e(c,v);const f=yt(c,e);{const S=Date.now(),{observability:T}=e,q=Ke(a),C=Re(s,a,l&&(Z=>l.waitUntil?.(Z)));if(c.fanOut){const Z=e.queryCoordinator;if(!Z)throw new i("RPC envelope set `fanOut` but no `queryCoordinator` is configured on the worker",{code:"BAD_REQUEST",status:400});try{const G=await Z.fanOut(d,{args:c.args??{},fanOut:c.fanOut,functionPath:c.functionPath,headers:y});return ce(T,{durationMs:Date.now()-S,fanOut:{failed:G.failed,shards:G.ok+G.failed,table:c.fanOut.table},functionPath:c.functionPath,...q,ok:!0},C),Response.json(G,{headers:{"content-type":"application/json"},status:200})}catch(G){throw ce(T,{...Ee(c.functionPath,Date.now()-S,G,{fanOut:{table:c.fanOut.table}}),...q},C),G}}const $=c.shardKey??n,V=()=>ke(a,c.functionPath,c.args??{},$,y,C);return f&&e.x402Charge?e.x402Charge(a,{functionPath:c.functionPath,price:f.price},V,ft(l)):V()}},Vt=async(a,s,l)=>{L(a,"POST","RPC batch");const c=await ee(a),{calls:m}=c;if(!Array.isArray(m))throw new i("RPC batch `calls` must be an array",{code:"BAD_REQUEST",status:400});const{headers:y,identity:v}=await de(a,s,o),f=nn(m,n);for(const z of f.values())for(const W of z)if(e.functions?.[W.functionPath]?.x402)throw new i(`paid (\`.x402\`) function "${W.functionPath}" cannot be called in a batch; dispatch it individually over ${pt}`,{code:"BAD_REQUEST",status:400});await Promise.all([...f.entries()].flatMap(([z,W])=>W.map(re=>_e({functionPath:re.functionPath,shardKey:z},v))));const{observability:S}=e,T=Re(s,a,l&&(z=>l.waitUntil?.(z))),q=Ke(a),C=[],$=[],V=(z,W,re,ue)=>({body:{error:{code:re,message:ue}},id:z.id,status:W}),Z=(z,W,re,ue,fe)=>{for(const H of z)ce(S,fe(H),T),C.push(V(H,W,re,ue))},G=(z,W,re,ue,fe)=>{for(const H of z){const me=ue.get(H.id)??fe,ge=me<400;ce(S,{durationMs:re,functionPath:H.functionPath,...q,ok:ge,shardKey:W,...ge?{}:{error:{code:"SHARD_ERROR",message:`batched call returned ${String(me)}`,status:me}}},T)}};await Promise.all([...f.entries()].map(async([z,W])=>{const re=new Headers(y);re.set("content-type","application/json");const ue=new Request("https://shard.internal/rpc-batch",{body:JSON.stringify({calls:W}),headers:re,method:"POST"}),fe=Date.now();let H;try{H=await oe(d,z,ue)}catch(Y){const Ue=Date.now()-fe,{body:He}=fr(Y,{fallbackCode:"SHARD_UNAVAILABLE",redactedMessage:"shard unavailable"});Z(W,502,He.code,He.message,hr=>({...Ee(hr.functionPath,Ue,Y,{shardKey:z}),...q}));return}const me=Date.now()-fe,ge=H.headers.get("x-d1-bookmark");ge&&$.push(ge);let De;try{De=await H.json()}catch{const Y=`shard batch returned a non-JSON response (${String(H.status)})`;Z(W,H.status,"SHARD_ERROR",Y,Ue=>({durationMs:me,error:{code:"SHARD_ERROR",message:Y,status:H.status},functionPath:Ue.functionPath,...q,ok:!1,shardKey:z}));return}const Pe=Array.isArray(De.results)?De.results:[],ur=new Map(Pe.map(Y=>[Y.id,Y.status??H.status])),lr=new Set(Pe.map(Y=>Y.id));G(W,z,me,ur,H.status),C.push(...Pe);for(const Y of W)lr.has(Y.id)||C.push(V(Y,H.status,"SHARD_ERROR",`shard batch omitted result for call ${String(Y.id)}`))}));const ze={"content-type":"application/json"},[We]=$;return $.length===1&&We!==void 0&&(ze["x-d1-bookmark"]=We),Response.json({results:C},{headers:ze,status:200})},Yt=async(a,s,l,c={},m={})=>{try{const y=l.__lunoraRef;if(typeof y!="string")throw new i("serverQuery: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});const{headers:v,identity:f}=await de(a,s,o);await _e({functionPath:y,shardKey:m.shardKey},f);const S=m.shardKey??n,T=Re(s,a,m.waitUntil);return await ke(a,y,c,S,v,T)}catch(y){return Je(y)}},Xt=1e3,Zt=async(a,s)=>{const l=e.backupRetain;if(l===void 0||l<=0)return;const c=[];let m;for(let v=0;v<Xt;v+=1){const f=await a.list({cursor:m,prefix:s});for(const S of f.objects)S.key.endsWith(".manifest.json")&&c.push(S.key);if(!f.truncated||f.cursor===void 0)break;m=f.cursor}const y=c.toSorted((v,f)=>f.localeCompare(v)).slice(l);await Promise.all(y.flatMap(v=>{const f=v.slice(0,-14);return[a.delete(v),a.delete(f)]}))},er=async a=>{const s=e.backupStore,l=e.queryCoordinator;if(!s)throw new i("scheduled backup requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});if(!l)throw new i("scheduled backup requires a `queryCoordinator` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});const c=w();if(!c||c.length===0)throw new i("scheduled backup requires an `adminToken` (or `env.LUNORA_ADMIN_TOKEN`) to authenticate the per-shard export gate",{code:"BACKUP_NOT_CONFIGURED",status:500});const m={authorization:`Bearer ${c}`,"content-type":"application/json"},y=e.backupTables;let v=0,f=0;const S=[];await st(e,l,m,y,Z=>{const G=`${JSON.stringify(Z)}
|
|
5
|
+
`;v+=1,f+=ja.encode(G).byteLength,S.push(G)},d);const T=e.backupPrefix??"backups/",q=new Date(a.scheduledTime).toISOString(),C=`${T}lunora-backup-${q.replaceAll(/[.:]/gu,"-")}.ndjson`,$=`${C}.manifest.json`;await s.put(C,new Blob(S,{type:"application/x-ndjson"}),{httpMetadata:{contentType:"application/x-ndjson"}});const V={bytes:f,createdAt:q,cron:a.cron,file:C,id:q,rows:v,scheduledTime:a.scheduledTime,...y?{tables:y.join(",")}:{}};await s.put($,`${JSON.stringify(V,void 0,2)}
|
|
6
|
+
`,{httpMetadata:{contentType:"application/json"}}),await Zt(s,T)},Qe=async(a,s,l)=>{const{observability:c}=e,m=Date.now(),y=Oe(16),v=Oe(8),f=gt(s);try{const S=await l();return ce(c,{durationMs:Date.now()-m,functionPath:a,ok:!0,spanId:v,traceId:y},f),S}catch(S){throw ce(c,{...Ee(a,Date.now()-m,S,{}),spanId:v,traceId:y},f),S}finally{Ve(c,f)}},tr=async(a,s,l)=>{b(s);const c=[],m=f=>f instanceof Error?f:new Error(String(f)),y=e.crons?.[a.cron];if(y)try{await y(a,s,l)}catch(f){c.push(m(f))}if(await F(a.cron,s,c,m),e.backupStore&&e.backupCron!==void 0&&e.backupCron===a.cron)try{await er(a)}catch(f){c.push(m(f))}const[v]=c;if(c.length===1&&v)throw v;if(c.length>1)throw new AggregateError(c,`scheduled("${a.cron}") had ${String(c.length)} failure(s)`)},rr=async(a,s)=>{try{const l=a??{},c=e.adminToken??(typeof l.LUNORA_ADMIN_TOKEN=="string"?l.LUNORA_ADMIN_TOKEN:void 0);if(!c||c.length===0)return;await oe(d,n,Te(Ja,{outcome:s},{authorization:`Bearer ${c}`,"content-type":"application/json"}))}catch{}},nr=async(a,s,l,c)=>{if(!e.authHandler)return;const m=await e.authHandler(a);if(!m)return;const y=e.authBasePath??Ha;return Xa(l.pathname,y)&&c.waitUntil?.(rr(s,m.status>=400?"fail":"ok")),m},ar=async({args:a,env:s,functionPath:l,request:c,shardKey:m,waitUntil:y})=>{Tt(a,"REST");const v={functionPath:l,...m===void 0?{}:{shardKey:m}},{headers:f,identity:S}=await de(c,s,o);await _e(v,S);const T=m??n,q=Re(s,c,y),C=()=>ke(c,l,a,T,f,q),$=yt(v,e);return $&&e.x402Charge?e.x402Charge(c,{functionPath:l,price:$.price},C,ft({waitUntil:y})):C()},or=Tr({functions:e.functions??{},invoke:ar,readJsonBody:ee,...e.restRateLimit?{rateLimit:e.restRateLimit}:{}}),Ie=e.routes!==void 0&&Object.keys(e.routes).length>0?e.routes:void 0,sr={[Ma]:a=>a.method!=="GET"&&a.method!=="HEAD"?new Response(void 0,{headers:{allow:"GET, HEAD"},status:405}):Response.json({ok:!0},{headers:{"cache-control":"no-store"}}),[$a]:(a,s,l)=>Mt(a,s,l),[pt]:(a,s,l,c)=>Jt(a,s,c),[Ba]:(a,s,l,c)=>Vt(a,s,c),[La]:(a,s)=>M(a,s),[Ka]:(a,s)=>P(a,s),[Ga]:async a=>{L(a,"POST","ws-token"),B(a);const s=w();if(s===void 0)throw new i("ws-token minting requires a configured admin token",{code:"ADMIN_TOKEN_NOT_CONFIGURED",status:400});const l=await Jr(s);return Response.json(l,{headers:{"cache-control":"no-store"}})},...N,...he,...ve,...se,...Ct,...xt,...jt,...Bt,...$t,...Kt,...or,...Zr({assertAdmin:B,getAuthAdmin:()=>e.authAdmin,parsePaging:pe,queryParameter:ae,readJsonBody:ee})};let ie=Xe(e.security),Me=!1;const ir=a=>{Me||(Me=!0,ie=Xe(e.security,a??{}))},cr=async(a,s)=>{if(!(e.adminGate===void 0||!za(s)))try{await e.adminGate(a)&&k.add(a)}catch{}},dr=async(a,s,l)=>{const c=new URL(a.url);if(a.method==="POST"||a.method==="PUT"){const f=Number(a.headers.get("content-length")??""),S=xa[c.pathname]??Et;if(Number.isFinite(f)&&f>S)throw new i("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413})}const m=await nr(a,s,c,l);if(m)return m;if(Ie){const f=`${a.method} ${c.pathname}`,S=Ie[f]??Ie[c.pathname];if(S)return S(a,s,l)}const y=sr[c.pathname];return y?(await cr(a,c.pathname),y(a,s,c,l)):e.voiceAgents!==void 0&&c.pathname.startsWith(wt)?zt(a,s,c):await Qt(a,s,l)||new Response("Not found",{status:404})};return{async fetch(a,s,l){e.passThroughOnException&&l.passThroughOnException?.(),ir(s),b(s);const c=Nr(a,ie);if(c)return c;const m=qr(a,ie);if(m)return qe(m,a,ie);try{const y=await dr(a,s,l);return qe(y,a,ie)}catch(y){return qe(Je(y),a,ie)}finally{Ve(e.observability,gt(l))}},async queue(a,s,l){await Qe(`queue:${eo(a)}`,l,async()=>{await e.queue?.(a,s,l)})},async scheduled(a,s,l){await Qe(`cron:${a.cron}`,l,async()=>{await tr(a,s,l)})},serverQuery:Yt}},fo=e=>qt(e),mo=e=>typeof e=="function"?{fetch:e}:e,wo=e=>!!(e.crons??e.cronJobs??e.backupCron),No=(e,t)=>{const r=mo(e),n=typeof e=="object"&&typeof e.scheduled=="function"?e.scheduled:void 0,o=u=>{const h=fo({...u,httpRouter:r});return n!==void 0&&!wo(u)?{...h,scheduled:async(w,R,I)=>{await n(w,R,I)}}:h};if(typeof t!="function")return o(t);const d=t;return{fetch:(u,h,w)=>o(d(h)).fetch(u,h,w),queue:(u,h,w)=>o(d(h)).queue?.(u,h,w)??Promise.resolve(),scheduled:(u,h,w)=>o(d(h)).scheduled(u,h,w),serverQuery:(u,h,w,R,I)=>o(d(h)).serverQuery(u,h,w,R,I)}},go=(e,t)=>{if(typeof e=="function")return e(t);const r=e.shardDO??t?.SHARD;if(!r)throw new i("@lunora/runtime: no shard Durable Object namespace found. Bind `SHARD` in wrangler.jsonc, or pass `createLunoraHandler({ shardDO: env.MY_SHARD })`.");return{...e,shardDO:r}},qo=(e={})=>(t,r,n)=>qt(go(e,r)).fetch(t,r,n??mr),Co=e=>e;export{en as GET_AUTH_AUDIT_LOG_OP,mr as NOOP_EXECUTION_CONTEXT,Bo as composeIdentityResolvers,fo as composeWorker,qo as createLunoraHandler,qt as createWorker,Co as defineRpcEnvelope,io as probeRelayCount,go as resolveLunoraOptions,$o as routeIdentityResolvers,No as withFrameworkWorker};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{f as u,u as d}from"./identity-header-pdXOyDU4.mjs";import{LunoraError as o}from"./LunoraError-ByasbDmd.mjs";const l="/_lunora/rpc",c=r=>{const t={"content-type":"application/json"};return r.userId!==void 0&&r.userId.length>0&&(t["x-lunora-userid"]=u(r.userId)),r.identity!==void 0&&(t["x-lunora-identity"]=d(r.identity)),t},i=async(r,t,e)=>{const a=await(r.fetch??globalThis.fetch)(new Request(`${r.origin}${l}`,{body:JSON.stringify(t),headers:c(r),method:"POST"}));if(!a.ok)throw new o(`cross-shard relation ${e} failed: worker returned ${String(a.status)}`);const n=await a.json();if(typeof n.failed=="number"&&n.failed>0){const s=(typeof n.ok=="number"?n.ok:0)+n.failed;throw new o(`cross-shard relation ${e} failed on ${String(n.failed)} of ${String(s)} shard(s) — refusing to return a partial result`)}return n.data},y=r=>({crossShardCounter:async(t,e)=>{const a=await i(r,{args:{table:t,where:e},fanOut:{merge:{kind:"sum"},table:t},functionPath:"__lunora_relation__:count"},"count");return typeof a=="number"?a:0},crossShardReader:async(t,e)=>{const a=await i(r,{args:{...e,table:t},fanOut:{merge:{kind:"concat"},table:t},functionPath:"__lunora_relation__:read"},"read");return{continueCursor:null,isDone:!0,page:Array.isArray(a)?a:[]}}});export{y as createCrossShardRelationCapabilities};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/runtime",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.56",
|
|
4
4
|
"description": "Lunora Worker runtime: the RPC router, shard resolver, and query coordinator",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cloudflare",
|
|
@@ -46,8 +46,8 @@
|
|
|
46
46
|
"access": "public"
|
|
47
47
|
},
|
|
48
48
|
"dependencies": {
|
|
49
|
-
"@lunora/bindings": "1.0.0-alpha.
|
|
50
|
-
"@lunora/errors": "1.0.0-alpha.
|
|
49
|
+
"@lunora/bindings": "1.0.0-alpha.22",
|
|
50
|
+
"@lunora/errors": "1.0.0-alpha.16",
|
|
51
51
|
"@lunora/platform": "1.0.0-alpha.6"
|
|
52
52
|
},
|
|
53
53
|
"engines": {
|
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
import{isLunoraError as pr,toErrorBody as fr}from"@lunora/errors";import{d as Rt}from"./evict-oldest-C2XU6HBR.mjs";import{NOOP_EXECUTION_CONTEXT as mr}from"./NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{f as wr,u as gr}from"./identity-header-pdXOyDU4.mjs";import{O as Te,m as yr,A as br,R as _r,d as Rr,i as Er,s as Sr}from"./otlp-resource-B-ByO9qo.mjs";import{h as ee,f as ye,i as Et,E as Or,w as St,e as Ot,b as Tr}from"./rest-routes-BqldHiaH.mjs";import{LunoraError as i,toErrorResponse as Je}from"./LunoraError-ByasbDmd.mjs";import{runExportTap as vr}from"./createKvCursorStore-C24tEuYk.mjs";import{t as we,r as L}from"./method-guard-rzvo19pa.mjs";import{buildHealthRoutes as Ar,durableObjectProbe as kr,d1Probe as Ir,presenceProbe as Ne}from"./HEALTH_PATH-Cqrg0Dq3.mjs";import{wrapResolverWithContract as Dr}from"./composeIdentityResolvers-DwE0Jbww.mjs";import{composeIdentityResolvers as jo,routeIdentityResolvers as xo}from"./composeIdentityResolvers-DwE0Jbww.mjs";import{buildLogArchiveAdminRoutes as Pr}from"./LOG_ARCHIVE_PATH-CuHKuDCS.mjs";import{o as Ur,f as Ve,a as ce}from"./observability-DWlkDJJw.mjs";import{resolveShard as ve,applyJurisdiction as Ye}from"./applyJurisdiction-8bzZjAPR.mjs";import{resolveSecurity as Xe,handleCorsPreflight as Nr,enforceOrigin as qr,decorateResponse as qe,enforceWebSocketOrigin as Ze}from"./decorateResponse-DBIWsRSZ.mjs";const Cr=e=>{const t=e??{};if(typeof t.bucket=="function")return t;const r={...t,bucketName:"default"};return r.bucket=()=>r,r},Tt="__lunoraBranch",jr=e=>typeof e=="object"&&e!==null&&Object.hasOwn(e,Tt),xr=`may not contain the reserved workflow branch-marker key ("${Tt}")`,Fe=(e,t)=>{const r=Math.max(e.length,t.length);let n=e.length^t.length;for(let o=0;o<r;o+=1){const d=o<e.length?e.charCodeAt(o):0,u=o<t.length?t.charCodeAt(o):0;n|=d^u}return n===0},Ge=new TextEncoder,Br=Array.from({length:32},(e,t)=>t);new RegExp(`[${Br.map(e=>String.fromCodePoint(e)).join("")}]`,"u");const $r=e=>{const t=String.fromCodePoint(...e);return btoa(t).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")},Lr=e=>{const t=e.replaceAll("-","+").replaceAll("_","/")+"===".slice((e.length+3)%4),r=atob(t),n=new Uint8Array(r.length);for(let o=0;o<r.length;o+=1)n[o]=r.codePointAt(o)??0;return n},Kr=64,Ce=new Map,vt=async e=>{const t=Ce.get(e);if(t)return t;Rt(Ce,Kr);const r=crypto.subtle.importKey("raw",Ge.encode(e),{hash:"SHA-256",name:"HMAC"},!1,["sign","verify"]);return Ce.set(e,r),r},At=async(e,t)=>{const r=await vt(e),n=await crypto.subtle.sign("HMAC",r,Ge.encode(t));return $r(new Uint8Array(n))},Fr=async(e,t,r)=>{const n=await vt(e);return crypto.subtle.verify("HMAC",n,r,Ge.encode(t))},Gr="::relay::",Qr=(e,t)=>`${e}${Gr}${String(t)}`,kt="v1",Mr=6e4,zr=async(e,t={})=>{const r=(t.now??Date.now())+(t.ttlMs??Mr),n=`${kt}.${String(r)}`,o=await At(e,n);return{expiresAtMs:r,token:`${n}.${o}`}},Wr=async(e,t,r=Date.now())=>{if(e.length===0||t.length===0)return!1;const n=t.split(".");if(n.length!==3)return!1;const[o,d,u]=n;if(o!==kt||u.length===0)return!1;const h=Number(d);if(!Number.isFinite(h)||h<=r)return!1;let w;try{w=Lr(u)}catch{return!1}return Fr(e,`${o}.${d}`,w)},D="/_lunora/admin/auth",Hr={INVITER_REQUIRED:400,ORG_SLUG_INVALID:400,ORG_SLUG_TAKEN:409,PASSWORD_TOO_LONG:400,PASSWORD_TOO_SHORT:400,USER_ALREADY_EXISTS:409,USER_NOT_FOUND:404},U=(e,t)=>{const r=e[t];if(typeof r!="string"||r==="")throw new i(`\`${t}\` is required`,{code:"BAD_REQUEST",status:400});return r},le=(e,t)=>{const r=e(t);if(r===void 0)throw new i(`\`${t}\` query parameter is required`,{code:"BAD_REQUEST",status:400});return r},It=e=>{if(typeof e=="string"||Array.isArray(e)&&e.every(t=>typeof t=="string"))return e},te=(e,t)=>typeof e[t]=="string"?e[t]:void 0,je=(e,t)=>{const r=e[t];return typeof r=="object"&&r!==null&&!Array.isArray(r)?r:void 0},et=e=>{const t=It(e.role);if(t===void 0||typeof t=="string"&&t.trim()==="")throw new i("`role` is required",{code:"BAD_REQUEST",status:400});return t},tt=e=>{const t=e.permission;if(typeof t!="object"||t===null||Array.isArray(t))throw new i("`permission` object is required",{code:"BAD_REQUEST",status:400});const r={};for(const[n,o]of Object.entries(t))Array.isArray(o)&&o.every(d=>typeof d=="string")&&(r[n]=o);return r},Jr={[`${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:je(e,"data"),email:U(e,"email"),name:U(e,"name"),password:te(e,"password"),role:It(e.role)}),http:"POST",method:"createUser"},[`${D}/users/update`]:{build:({body:e})=>{const{data:t}=e;if(typeof t!="object"||t===null||Array.isArray(t))throw new i("`data` object is required",{code:"BAD_REQUEST",status:400});return{data:t,userId:U(e,"userId")}},http:"POST",method:"updateUser"},[`${D}/users/role`]:{build:({body:e})=>({role:et(e),userId:U(e,"userId")}),http:"POST",method:"setRole"},[`${D}/users/ban`]:{build:({body:e})=>({expiresInSeconds:typeof e.expiresInSeconds=="number"?e.expiresInSeconds:void 0,reason:te(e,"reason"),userId:U(e,"userId")}),http:"POST",method:"banUser"},[`${D}/users/unban`]:{build:({body:e})=>({userId:U(e,"userId")}),http:"POST",method:"unbanUser"},[`${D}/users/password`]:{build:({body:e})=>({newPassword:U(e,"newPassword"),userId:U(e,"userId")}),http:"POST",method:"setUserPassword",returns:"void"},[`${D}/users/remove`]:{build:({body:e})=>({userId:U(e,"userId")}),http:"POST",method:"removeUser",returns:"void"},[`${D}/users/impersonate`]:{build:({body:e})=>({userId:U(e,"userId")}),http:"POST",method:"impersonateUser"},[`${D}/sessions/revoke`]:{build:({body:e})=>({sessionId:U(e,"sessionId")}),http:"POST",method:"revokeUserSession",returns:"void"},[`${D}/sessions/revoke-all`]:{build:({body:e})=>({userId:U(e,"userId")}),http:"POST",method:"revokeUserSessions",returns:"void"},[`${D}/accounts/unlink`]:{build:({body:e})=>({accountId:U(e,"accountId"),userId:U(e,"userId")}),http:"POST",method:"unlinkAccount",returns:"void"},[`${D}/two-factor/disable`]:{build:({body:e})=>({userId:U(e,"userId")}),http:"POST",method:"disableTwoFactor",returns:"void"},[`${D}/passkeys/delete`]:{build:({body:e})=>({passkeyId:U(e,"passkeyId")}),http:"POST",method:"deletePasskey",returns:"void"},[`${D}/organizations/members/remove`]:{build:({body:e})=>({memberId:U(e,"memberId")}),http:"POST",method:"removeMember",returns:"void"},[`${D}/organizations/invitations/cancel`]:{build:({body:e})=>({invitationId:U(e,"invitationId")}),http:"POST",method:"cancelInvitation",returns:"void"},[`${D}/organizations/create`]:{build:({body:e})=>({logo:te(e,"logo"),metadata:je(e,"metadata"),name:U(e,"name"),ownerId:te(e,"ownerId"),slug:te(e,"slug")}),http:"POST",method:"createOrganization"},[`${D}/organizations/update`]:{build:({body:e})=>({logo:te(e,"logo"),metadata:je(e,"metadata"),name:te(e,"name"),organizationId:U(e,"organizationId"),slug:te(e,"slug")}),http:"POST",method:"updateOrganization"},[`${D}/organizations/remove`]:{build:({body:e})=>({organizationId:U(e,"organizationId")}),http:"POST",method:"deleteOrganization",returns:"void"},[`${D}/organizations/members/add`]:{build:({body:e})=>({organizationId:U(e,"organizationId"),role:te(e,"role"),userId:U(e,"userId")}),http:"POST",method:"addMember"},[`${D}/organizations/members/invite`]:{build:({body:e})=>({email:U(e,"email"),inviterId:te(e,"inviterId"),organizationId:U(e,"organizationId"),role:te(e,"role")}),http:"POST",method:"inviteMember"},[`${D}/organizations/members/role`]:{build:({body:e})=>({memberId:U(e,"memberId"),role:et(e)}),http:"POST",method:"updateMemberRole"},[`${D}/organizations/teams/create`]:{build:({body:e})=>({name:U(e,"name"),organizationId:U(e,"organizationId")}),http:"POST",method:"createTeam"},[`${D}/organizations/teams/update`]:{build:({body:e})=>({name:U(e,"name"),teamId:U(e,"teamId")}),http:"POST",method:"updateTeam"},[`${D}/organizations/teams/remove`]:{build:({body:e})=>({teamId:U(e,"teamId")}),http:"POST",method:"removeTeam",returns:"void"},[`${D}/organizations/teams/members/add`]:{build:({body:e})=>({teamId:U(e,"teamId"),userId:U(e,"userId")}),http:"POST",method:"addTeamMember"},[`${D}/organizations/teams/members/remove`]:{build:({body:e})=>({teamMemberId:U(e,"teamMemberId")}),http:"POST",method:"removeTeamMember",returns:"void"},[`${D}/organizations/roles/create`]:{build:({body:e})=>({organizationId:U(e,"organizationId"),permission:tt(e),role:U(e,"role")}),http:"POST",method:"createOrgRole"},[`${D}/organizations/roles/update`]:{build:({body:e})=>({permission:tt(e),roleId:U(e,"roleId")}),http:"POST",method:"updateOrgRole"},[`${D}/organizations/roles/remove`]:{build:({body:e})=>({roleId:U(e,"roleId")}),http:"POST",method:"deleteOrgRole",returns:"void"}},Vr=e=>{const t=async o=>{try{return await o()}catch(d){if(d instanceof i)throw d;const u=d,h=typeof u.code=="string"?u.code:"AUTH_ADMIN_ERROR";throw console.error("[lunora] auth admin operation failed:",d),new i("auth admin operation failed",{code:h,status:Hr[h]??500})}},r=async(o,d)=>{if(e.assertAdmin(o),o.method!==d.http)throw new i(`Auth admin endpoint requires ${d.http}`,{code:"METHOD_NOT_ALLOWED",status:405});const u=e.getAuthAdmin();if(u===void 0)throw new i("auth endpoints require an `authAdmin` on the worker",{code:"AUTH_NOT_CONFIGURED",status:400});const h=u[d.method];if(h===void 0)throw new i(`auth admin does not support \`${d.method}\``,{code:"AUTH_OP_NOT_SUPPORTED",status:400});const w=new URL(o.url),R={body:d.http==="POST"?await e.readJsonBody(o):{},paging:e.parsePaging(o),query:k=>e.queryParameter(w,k)},I=d.build(R),b=await t(()=>h(I));return Response.json(d.returns==="void"?{ok:!0}:b,{headers:{"content-type":"application/json"},status:200})},n={};for(const[o,d]of Object.entries(Jr))n[o]=u=>r(u,d);return n},Yr="__lunora_admin__:getAuthAuditLog",rt=e=>typeof e=="string"&&e!==""?e:void 0,nt=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0,Xr=e=>async(t,r)=>{e.assertAdmin(t);const n=e.getReader();if(n===void 0)throw new i("the auth/security audit endpoint requires an `authAuditReader` on the worker",{code:"AUTH_AUDIT_NOT_CONFIGURED",status:400});const o=rt(r.actorId),d=rt(r.event),u=nt(r.sinceSeq),h=nt(r.limit),w={...o===void 0?{}:{actorId:o},...d===void 0?{}:{event:d},...u===void 0?{}:{sinceSeq:u},...h===void 0?{}:{limit:h}};let R;try{R=await n.read(w)}catch(b){throw b instanceof i?b:(console.error("[lunora] auth audit read failed:",b),new i("auth audit read failed",{code:"AUTH_AUDIT_READ_FAILED",status:500}))}const I={entries:R};return Response.json(I,{headers:{"content-type":"application/json"},status:200})},at=500,Zr=(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}},en=(e,t)=>{if(e.length>at)throw new i(`RPC batch exceeds the ${String(at)}-call limit`,{code:"BAD_REQUEST",status:400});const r=new Map;for(const[n,o]of e.entries()){const{entry:d,shardKey:u}=Zr(o,n,t),h=r.get(u)??[];h.push(d),r.set(u,h)}return r},tn=new TextEncoder,rn=e=>{const t=JSON.stringify(e),r=tn.encode(t);let n="";for(const o of r)n+=String.fromCodePoint(o);return btoa(n).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")},nn=e=>{const t={g:0,s:{},v:1};if(typeof e!="string"||e.length===0)return t;try{const r=atob(e.replaceAll("-","+").replaceAll("_","/")),n=new Uint8Array(r.length);for(let h=0;h<r.length;h+=1)n[h]=r.codePointAt(h)??0;const o=JSON.parse(new TextDecoder().decode(n)),d=o.s&&typeof o.s=="object"?o.s:{},u={};for(const[h,w]of Object.entries(d))typeof w=="number"&&Number.isFinite(w)&&(u[h]=w);return{g:typeof o.g=="number"&&Number.isFinite(o.g)?o.g:0,s:u,v:1}}catch{return t}},an=e=>{const t=typeof e.table=="string"?e.table:"",r=typeof e.op=="string"?e.op:"",n=r==="delete"||r==="insert"||r==="update"?r:"upsert",o=typeof e.id=="string"?e.id:void 0;return{doc:(e.doc&&typeof e.doc=="object"?e.doc:void 0)??(o===void 0?{}:{_id:o}),op:n,table:t}},ot=(e,t,r)=>{for(const n of t)e.push(an(n));return r!==void 0&&t.length>=r},on="/_lunora/admin/export",sn="/_lunora/admin/import",cn="/_lunora/admin/sync",dn="/_lunora/admin/connector/sync",un="/_lunora/admin/apply",ln="/_lunora/admin/export-tap/run",hn=new TextEncoder,pn=async e=>{const t=await ye(e,"Export")??{};if(t.tables===void 0)return{tables:void 0};if(!Array.isArray(t.tables))throw new i("Export `tables` must be a string array",{code:"BAD_REQUEST",status:400});const r=[];for(const n of t.tables){if(typeof n!="string"||n.length===0)throw new i("Export `tables` entries must be non-empty strings",{code:"BAD_REQUEST",status:400});r.push(n)}return{tables:r}},xe=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):void 0,fn=e=>{const{applyGlobals:t,exportCursorStore:r,exportSinks:n,knownTables:o,queryCoordinator:d,assertAdmin:u,requireAdminOption:h,resolveForwardContext:w,shardDO:R,streamExportRows:I,streamingImport:b,syncGlobals:k}=e,p=async(v,x)=>{const j=we(v,["POST"]);if(j)return j;const G=h(v,d,{code:"BAD_REQUEST",message:"Export endpoint requires a `queryCoordinator` on the worker"}),P=await pn(v),{headers:Q}=await w(v,x),M=new ReadableStream({async pull(B){const K=X=>{B.enqueue(hn.encode(`${JSON.stringify(X)}
|
|
2
|
-
`))};try{await I(G,Q,P.tables,K),B.close()}catch(X){B.error(X)}}});return new Response(M,{headers:{"content-type":"application/x-ndjson"},status:200})},g=async(v,x)=>{const j=we(v,["POST"]);if(j)return j;const G=h(v,d,{code:"BAD_REQUEST",message:"Sync endpoint requires a `queryCoordinator` on the worker"}),P=await ee(v),Q=typeof P.cursors=="object"&&P.cursors!==null?P.cursors:{},M=typeof P.limit=="number"?P.limit:void 0,B=typeof P.globalCursor=="number"?P.globalCursor:0,K=xe(P.tables),{headers:X}=await w(v,x),J=K??o(),ne=await G.orchestrateCdcSync(R,{cursors:Q,headers:X,limit:M,tables:J}),he=k?await k({limit:M,sinceSeq:B}):void 0;return Response.json({global:he,shards:ne.shards},{status:200})},E=async(v,x)=>{const j=we(v,["POST"]);if(j)return j;const G=h(v,d,{code:"BAD_REQUEST",message:"Connector sync endpoint requires a `queryCoordinator` on the worker"}),P=await ee(v),Q=nn(P.cursor),M=typeof P.limit=="number"&&P.limit>0?P.limit:void 0,B=xe(P.tables),{headers:K}=await w(v,x),X=B??o(),J=await G.orchestrateCdcSync(R,{cursors:Q.s,headers:K,limit:M,tables:X}),ne=[],he={...Q.s};let ae=!1;for(const se of J.shards)ae=ot(ne,se.changes??[],M)||ae,he[se.shardKey]=se.cursor;let pe=Q.g;if(k){const se=await k({limit:M,sinceSeq:Q.g});ae=ot(ne,se.changes,M)||ae,pe=se.cursor}const be=rn({g:pe,s:he,v:1}),Ae={changes:ne,hasMore:ae,nextCursor:be};return Response.json(Ae,{status:200})},_=async(v,x)=>{const j=we(v,["POST"]);if(j)return j;const G=h(v,d,{code:"BAD_REQUEST",message:"Apply endpoint requires a `queryCoordinator` on the worker"}),P=await ee(v),Q=(Array.isArray(P.batches)?P.batches:[]).map(J=>J).filter(J=>J!==null&&typeof J=="object"&&typeof J.shardKey=="string"&&Array.isArray(J.changes)),M=Array.isArray(P.globalChanges)?P.globalChanges:[],{headers:B}=await w(v,x),K=await G.orchestrateApplyCdc(R,{batches:Q,headers:B}),X=M.length>0&&t?await t({changes:M}):0;return Response.json({applied:K.applied+X,failed:K.failed,ok:K.ok},{status:200})},T=async(v,x)=>{const j=we(v,["POST"]);if(j)return j;u(v);const{headers:G}=await w(v,x),P=await b(v,G);return Response.json(P,{headers:{"content-type":"application/json"},status:200})},N=async(v,x)=>{const j=we(v,["POST"]);if(j)return j;const G=h(v,d,{code:"BAD_REQUEST",message:"Export-tap endpoint requires a `queryCoordinator` on the worker"});if(n===void 0||Object.keys(n).length===0||r===void 0)throw new i("Export-tap endpoint requires `exportSinks` + `exportCursorStore` on the worker",{code:"EXPORT_TAP_NOT_CONFIGURED",status:400});const P=await ee(v),Q=typeof P.sink=="string"?P.sink:void 0,M=typeof P.limit=="number"&&P.limit>0?P.limit:void 0,B=xe(P.tables);if(Q===void 0)throw new i("Export-tap `sink` must name a configured sink",{code:"BAD_REQUEST",status:400});const K=n[Q];if(K===void 0)throw new i(`Export-tap sink "${Q}" is not configured`,{code:"NOT_FOUND",status:404});const{headers:X}=await w(v,x),J=B??o(),ne=await vr({coordinator:G,cursorStore:r,headers:X,limit:M,shardDO:R,sink:K,tables:J});return Response.json(ne,{headers:{"content-type":"application/json"},status:200})};return{[un]:_,[dn]:E,[on]:p,[ln]:N,[sn]:T,[cn]:g}},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,d)=>{if(r!==void 0&&n.length===0)return;const u=await e.orchestrateExport(d,{args:{tables:n},headers:t,tables:n});for(const h of u.shards)if(!h.error)for(const w of h.rows??[])o(w)},st=async(e,t,r,n,o,d)=>{const{globalTables:u,shardLocalTables:h}=mn(e,n);await wn(t,r,n,h,o,d);const w=e.exportGlobals;if((n===void 0||u.length>0)&&w)for await(const R of w({tables:u}))o(R)},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}},yn=(e,t,r,n,o)=>{if(r?.mode.kind==="shardBy"&&typeof r.mode.field=="string"){const d=e[r.mode.field];return d==null?{error:{code:"BAD_ROW",line:o,message:`row missing shard field "${r.mode.field}" for table "${t}"`,table:t},ok:!1}:{ok:!0,shardKey:typeof d=="string"?d:JSON.stringify(d)}}return{ok:!0,shardKey:n}},bn=async(e,t,r)=>{if(!e.body)throw new i("Import endpoint requires a request body",{code:"BAD_REQUEST",status:400});const n=[],o=[],d=new Map;let u=0,h=0;const w=e.body.getReader(),R=new TextDecoder;let I="",b=0;const k=p=>{h+=1;const g=p.trim();if(g.length===0)return;u+=1;const E=gn(g,h);if(!E.ok){n.push(E.error);return}const{doc:_,table:T}=E,N=t.resolveTableSharding?.(T);if(N?.mode.kind==="global"){o.push({doc:_,line:h,table:T});return}const v=yn(_,T,N,r,h);if(!v.ok){n.push(v.error);return}const x=d.get(v.shardKey);x?x.rows.push({doc:_,table:T}):d.set(v.shardKey,{rows:[{doc:_,table:T}],shardKey:v.shardKey,startLine:h})};for(;;){const{done:p,value:g}=await w.read();if(p)break;if(g&&(b+=g.byteLength,b>Et))throw await w.cancel().catch(()=>{}),new i("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});I+=R.decode(g,{stream:!0});let E=I.indexOf(`
|
|
3
|
-
`);for(;E!==-1;){const _=I.slice(0,E);I=I.slice(E+1),k(_),E=I.indexOf(`
|
|
4
|
-
`)}}return I.length>0&&k(I),{errors:n,globalRows:o,perShard:d,received:u}},it=(e,t)=>{for(const[r,n]of Object.entries(t.inserted))e.inserted[r]=(e.inserted[r]??0)+n;for(const r of t.errors)e.errors.push({...r});e.conflicts+=t.conflicts},_n=async(e,t,r,n)=>{const o=t.defaultShardKey??"__root__",{errors:d,globalRows:u,perShard:h,received:w}=await bn(e,t,o),R={conflicts:0,errors:d,inserted:{}},I=[];if(t.resolveTableSharding===void 0&&h.size>0&&I.push("no `resolveTableSharding` is configured, so every row was routed to the default shard and no row could be recognised as `.global()` — correct for a single-shard app, silent misplacement for a sharded one"),h.size>0){const b=t.queryCoordinator;if(!b)throw new i("Import endpoint requires a `queryCoordinator` on the worker",{code:"BAD_REQUEST",status:400});const k=await b.orchestrateImport(n,{batches:[...h.values()],headers:r});it(R,k)}if(u.length>0)if(t.importGlobals){const b=u[0]?.line??1,k=await t.importGlobals({rows:u,startLine:b});it(R,k)}else for(const b of u)R.errors.push({code:"GLOBAL_NOT_CONFIGURED",line:b.line,message:`row targets global table "${b.table}" but no \`importGlobals\` is configured`,table:b.table});return{conflicts:R.conflicts,errors:R.errors,inserted:R.inserted,received:w,...I.length>0?{warnings:I}:{}}},Be=e=>typeof e=="object"&&e!==null?e:{},$e=e=>typeof e.kind=="string"?e.kind:"unknown",Rn=(e,t)=>{let r=Be(t),n=!1;$e(r)==="optional"&&(n=!0,r=Be(r._meta?.inner));const o=$e(r),d=r._meta??{},u={kind:o,name:e,optional:n};if(o==="id"&&typeof d.tableName=="string"&&(u.table=d.tableName),o==="array"){const h=$e(Be(d.inner));h!=="unknown"&&(u.element=h)}return u},En=e=>typeof e!="object"||e===null?[]:Object.entries(e).map(([t,r])=>Rn(t,r)).toSorted((t,r)=>t.name.localeCompare(r.name)),Sn="/_lunora/admin/functions",On="/_lunora/admin/cron-jobs",Tn="/_lunora/admin/openapi",vn="/_lunora/admin/openrpc",An="/_lunora/admin/global/tables",kn="/_lunora/admin/global/table",In="/_lunora/admin/global/facet",ct=e=>{if(e===void 0||e==="")return;let t;try{t=JSON.parse(e)}catch{return}if(!Array.isArray(t))return;const r=t.flatMap(n=>{if(typeof n!="object"||n===null||typeof n.column!="string")return[];const{column:o,value:d}=n;return[{column:o,value:d}]});return r.length===0?void 0:r},Dn=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:{}}),Pn=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"}),Un=e=>{const{assertAdmin:t,options:r,parsePaging:n,queryParameter:o,requireAdminOption:d}=e,u=p=>{L(p,"GET","Functions");const g=d(p,r.functions,{code:"FUNCTIONS_NOT_CONFIGURED",message:"functions endpoint requires a `functions` registry on the worker"}),E=Object.entries(g).flatMap(([_,T])=>T.visibility==="internal"||T.kind==="stream"?[]:[{args:En(T.args),kind:T.kind,path:_}]).toSorted((_,T)=>_.path.localeCompare(T.path));return Response.json({functions:E},{headers:{"content-type":"application/json"},status:200})},h=p=>{L(p,"GET","Cron-jobs");const g=d(p,r.cronJobs,{code:"CRON_JOBS_NOT_CONFIGURED",message:"cron-jobs endpoint requires a `cronJobs` map on the worker"}),E=Object.entries(g).flatMap(([_,T])=>T.map(N=>({args:N.args,cron:_,functionPath:N.functionPath,name:N.name,shardKey:N.shardKey,workflow:N.workflow}))).toSorted((_,T)=>_.name.localeCompare(T.name));return Response.json({jobs:E},{headers:{"content-type":"application/json"},status:200})},w=p=>(L(p,"GET","OpenAPI"),t(p),Response.json(r.openApiSpec??Dn,{headers:{"content-type":"application/json"},status:200})),R=p=>(L(p,"GET","OpenRPC"),t(p),Response.json(r.openRpcSpec??Pn,{headers:{"content-type":"application/json"},status:200})),I=async p=>{L(p,"GET","Global-tables");const g=d(p,r.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"});return Response.json(await g.listTables(),{headers:{"content-type":"application/json"},status:200})},b=async p=>{L(p,"GET","Global-table");const g=d(p,r.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),E=new URL(p.url),_=o(E,"table");if(_===void 0)throw new i("Global-table endpoint requires a `table` query param",{code:"BAD_REQUEST",status:400});const T=await g.readTablePage({...n(p),filters:ct(o(E,"filters")),table:_});return Response.json(T,{headers:{"content-type":"application/json"},status:200})},k=async p=>{L(p,"GET","Global-facet");const g=d(p,r.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),E=new URL(p.url),_=o(E,"table"),T=o(E,"column");if(_===void 0||T===void 0)throw new i("Global-facet endpoint requires `table` and `column` query params",{code:"BAD_REQUEST",status:400});const N=o(E,"limit"),v=N===void 0?void 0:Number(N),x=await g.facetColumn({column:T,filters:ct(o(E,"filters")),limit:v!==void 0&&Number.isFinite(v)?v:void 0,table:_});return Response.json(x,{headers:{"content-type":"application/json"},status:200})};return{[On]:h,[Sn]:u,[In]:k,[kn]:b,[An]:I,[Tn]:w,[vn]:R}},Nn="/_lunora/admin/kv/namespaces",qn="/_lunora/admin/kv/keys",Dt="/_lunora/admin/kv/value",Pt=32*1048576,dt=60,Cn=e=>{const{readJsonBody:t,requireAdminOption:r}=e,n=b=>r(b,e.kvIntrospector,{code:"KV_NOT_CONFIGURED",message:"KV endpoints require a `kvIntrospector` on the worker"}),o=b=>Response.json(b,{headers:{"content-type":"application/json"},status:200}),d=(b,k)=>{const p=new URL(b.url),g=p.searchParams.get("namespace")??"",E=p.searchParams.get("key")??"";if(g==="")throw new i(`KV-value ${k} request requires a \`namespace\` query parameter`,{code:"BAD_REQUEST",status:400});if(E==="")throw new i(`KV-value ${k} request requires a \`key\` query parameter`,{code:"BAD_REQUEST",status:400});return{key:E,namespace:g}},u=async(b,k)=>{if(!(await b.listNamespaces()).some(p=>p.binding===k))throw new i(`Unknown KV namespace binding \`${k}\``,{code:"NOT_FOUND",status:404})},h=async b=>(L(b,"GET","KV-namespaces"),o({namespaces:await n(b).listNamespaces()})),w=async b=>{L(b,"GET","KV-keys");const k=n(b),p=new URL(b.url),g=p.searchParams.get("namespace")??"";if(g==="")throw new i("KV-keys request requires a `namespace` query parameter",{code:"BAD_REQUEST",status:400});const E=p.searchParams.get("prefix")??void 0,_=p.searchParams.get("cursor")??void 0,T=p.searchParams.get("limit"),N=T===null?void 0:Number.parseInt(T,10);if(N!==void 0&&(!Number.isInteger(N)||N<1))throw new i("KV-keys `limit` must be a positive integer",{code:"BAD_REQUEST",status:400});const v=N===void 0?void 0:Math.min(N,1e3);return await u(k,g),o(await k.listKeys({cursor:_,limit:v,namespace:g,prefix:E}))},R={DELETE:async b=>{const k=n(b),p=d(b,"DELETE");return await u(k,p.namespace),await k.deleteKey(p),o({deleted:!0})},GET:async b=>{const k=n(b),p=d(b,"GET");return await u(k,p.namespace),o(await k.getValue(p))},PUT:async b=>{const k=n(b),p=await t(b,Pt);if(typeof p.namespace!="string"||p.namespace==="")throw new i("KV-value PUT request requires a `namespace` string",{code:"BAD_REQUEST",status:400});if(typeof p.key!="string"||p.key==="")throw new i("KV-value PUT request requires a `key` string",{code:"BAD_REQUEST",status:400});if(typeof p.value!="string")throw new i("KV-value PUT request requires a `value` string",{code:"BAD_REQUEST",status:400});if(p.expirationTtl!==void 0&&(typeof p.expirationTtl!="number"||!Number.isInteger(p.expirationTtl)||p.expirationTtl<dt))throw new i("KV-value PUT `expirationTtl` must be an integer ≥ 60",{code:"BAD_REQUEST",status:400});const g=Math.floor(Date.now()/1e3)+dt;if(p.expiration!==void 0&&(typeof p.expiration!="number"||!Number.isInteger(p.expiration)||p.expiration<g))throw new i("KV-value PUT `expiration` must be a Unix-seconds timestamp at least 60 seconds in the future",{code:"BAD_REQUEST",status:400});return await u(k,p.namespace),await k.putValue({expiration:p.expiration,expirationTtl:p.expirationTtl,key:p.key,metadata:p.metadata,namespace:p.namespace,value:p.value}),o({ok:!0})}},I=b=>{const k=R[b.method];if(!k)throw new i("KV-value endpoint requires GET, PUT, or DELETE",{code:"METHOD_NOT_ALLOWED",status:405});return k(b)};return{[Nn]:h,[qn]:w,[Dt]:I}},jn="/_lunora/migrate",xn="/_lunora/admin/pitr",Bn="/_lunora/admin/rank",$n="/_lunora/admin/rankpage",Ln="/_lunora/admin/shard-traffic",Kn=new Set(["__lunora_admin__:migrationStatus","__lunora_admin__:runMigration"]),Fn=new Set(["__lunora_admin__:getPitrBookmark","__lunora_admin__:pitrRestore"]),Gn=async e=>{const t=await ye(e,"Migration")??{};if(typeof t.table!="string"||t.table.length===0)throw new i("Migration request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof t.functionPath!="string"||!Kn.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}},Qn=async e=>{const t=await ye(e,"Rank")??{};if(typeof t.table!="string"||t.table.length===0)throw new i("Rank request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof t.index!="string"||t.index.length===0)throw new i("Rank request is missing `index`",{code:"BAD_REQUEST",status:400});if(typeof t.partitionKey!="string")throw new i("Rank request `partitionKey` must be a string",{code:"BAD_REQUEST",status:400});if(typeof t.rowId!="string"||t.rowId.length===0)throw new i("Rank request is missing `rowId`",{code:"BAD_REQUEST",status:400});if(!Array.isArray(t.sortValues))throw new i("Rank request `sortValues` must be an array",{code:"BAD_REQUEST",status:400});return{index:t.index,partitionKey:t.partitionKey,rowId:t.rowId,sortValues:t.sortValues,table:t.table}},Mn=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}},zn=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})},Wn=async e=>{const t=await ye(e,"Rank page")??{};zn(t);const r=Mn(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}},Hn=async e=>{const t=await ye(e,"Shard-traffic")??{};if(typeof t.table!="string"||t.table.length===0)throw new i("Shard-traffic request is missing `table`",{code:"BAD_REQUEST",status:400});return{table:t.table}},Jn=async e=>{const t=await ee(e);if(typeof t.functionPath!="string"||!Fn.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}},Vn=e=>{const{defaultShard:t,forwardToShard:r,isAdmin:n,queryCoordinator:o,resolveForwardContext:d,shardDO:u}=e,h=(p,g)=>{if(p.method!=="POST")throw new i(`${g} endpoint requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});if(!n(p))throw new i("Admin auth required",{code:"FORBIDDEN",status:403});if(!o)throw new i(`${g} endpoint requires a \`queryCoordinator\` on the worker`,{code:"BAD_REQUEST",status:400});return o},w=async(p,g)=>{const E=h(p,"Migration"),_=await Gn(p),{headers:T}=await d(p,g),N=await E.orchestrateMigration(u,{args:_.args,functionPath:_.functionPath,headers:T,table:_.table});return Response.json(N,{headers:{"content-type":"application/json"},status:200})},R=async(p,g)=>{const E=h(p,"Rank"),_=await Qn(p),{headers:T}=await d(p,g),N=await E.orchestrateRank(u,{headers:T,index:_.index,partitionKey:_.partitionKey,rowId:_.rowId,sortValues:_.sortValues,table:_.table});return Response.json(N,{headers:{"content-type":"application/json"},status:200})},I=async(p,g)=>{const E=h(p,"Rank page"),_=await Wn(p),{headers:T}=await d(p,g),N=await E.orchestrateRankPage(u,{..._,headers:T});return Response.json(N,{headers:{"content-type":"application/json"},status:200})},b=async(p,g)=>{const E=h(p,"Shard-traffic"),_=await Hn(p),{headers:T}=await d(p,g),N=await E.orchestrateShardTraffic(u,{headers:T,table:_.table});return Response.json(N,{headers:{"content-type":"application/json"},status:200})},k=async(p,g)=>{if(L(p,"POST","PITR"),!n(p))throw new i("admin PITR endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403});const E=await Jn(p),{headers:_}=await d(p,g),T=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:E.args,functionPath:E.functionPath}),headers:_,method:"POST"});return r(u,E.shardKey??t,T)};return{[jn]:w,[xn]:k,[Bn]:R,[$n]:I,[Ln]:b}},Yn=1,Xn=0,Zn=32,ea=512,ta=/^[a-z][\d_a-z*/-]{0,255}(?:@[a-z][\d_a-z*/-]{0,13})?=[\u0020-\u002B\u002D-\u003C\u003E-\u007E]{1,256}$/,ra=e=>{if(e==null)return;const t=e.trim();if(t.length===0||t.length>ea)return;const r=t.split(",");if(!(r.length>Zn)){for(const n of r)if(!ta.test(n.trim()))return;return t}},na=e=>{const t=br(e.headers.get("traceparent"));if(t===void 0)return;const r=ra(e.headers.get("tracestate"));return{parentSpanId:t.parentSpanId,sampled:t.sampled,traceId:t.traceId,...r===void 0?{}:{traceState:r}}},aa=(e,t={})=>{const r=na(e),n=t.trustInbound===!0?r:void 0,o=Te(8),d=n?.traceId??Te(16),u=Ur(t.sampling,n===void 0?o:d),h=u.isTraced&&(n===void 0||n.sampled);return{decision:u,ignoredUpstream:r!==void 0&&n===void 0,trace:{sampled:h,spanId:o,traceFlags:h?Yn:Xn,traceId:d,...n?.parentSpanId===void 0?{}:{parentSpanId:n.parentSpanId},...n?.traceState===void 0?{}:{traceState:n.traceState}}}},oa=(e,t)=>{t.traceparent=yr(e.traceId,e.spanId,e.sampled),e.traceState!==void 0&&(t.tracestate=e.traceState)},sa=(e,t)=>{let r;return()=>{if(r===void 0){const n=Sr(e),o=t===void 0?void 0:t.cf;r=_r(Er(n),Rr(n,o))}return r}},ia="/_lunora/admin/scheduled",ca="/_lunora/admin/scheduled/status",da="/_lunora/admin/scheduled/ws",ua="/_lunora/admin/scheduled/cancel",la="/_lunora/admin/scheduled/dead",ha="/_lunora/admin/scheduled/dead/retry",pa="/_lunora/admin/scheduled/dead/cancel",fa=e=>{const{checkWsAdmin:t,requireSchedulerNamespace:r,resolveSchedulerStub:n,schedulerInstanceName:o}=e,d=(w,R)=>I=>{if(I.method!=="GET")throw new i(`${R} endpoint requires GET`,{code:"METHOD_NOT_ALLOWED",status:405});return n(I).fetch(new Request(`https://scheduler.internal${w}`,{method:"GET"}))},u=(w,R,I=R)=>async b=>{if(b.method!=="POST")throw new i(`${I} requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});const k=n(b),p=await b.json().catch(()=>{});if(typeof p?.id!="string"||p.id==="")throw new i(`${R} requires a string \`id\``,{code:"BAD_REQUEST",status:400});return k.fetch(new Request(`https://scheduler.internal${w}`,{body:JSON.stringify({id:p.id}),headers:{"content-type":"application/json"},method:"POST"}))},h=async w=>{if(w.headers.get("Upgrade")!=="websocket")throw new i("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});if(!await t(w))throw new i("admin authorization required",{code:"ADMIN_FORBIDDEN",status:403});const R=r();return ve(R,o).fetch(new Request("https://scheduler.internal/ws",{headers:{Upgrade:"websocket"}}))};return{[ua]:u("/cancel","Scheduled-cancel","Scheduled-cancel endpoint"),[pa]:u("/dead/cancel","Scheduled dead-letter action"),[la]:d("/dead","Scheduled dead-letter"),[ha]:u("/dead/retry","Scheduled dead-letter action"),[ia]:d("/list","Scheduled-list"),[ca]:d("/status","Scheduler-status"),[da]:h}},Ut="/_lunora/admin/storage",ma="/_lunora/admin/storage/url",wa="/_lunora/admin/storage/buckets",ga=10080*60,Nt=32*1048576,ya=new Set(["GET","PUT"]),ba=e=>{const t=new Uint8Array(e);let r="";for(const n of t)r+=n.toString(16).padStart(2,"0");return r},_a=e=>{const{assertAdmin:t,parsePaging:r,queryParameter:n,readBodyBytes:o,requireAdminOption:d,storage:u}=e,h=g=>{const E=n(g,"key");if(E===void 0)throw new i("Storage endpoint requires a `key` query parameter",{code:"BAD_REQUEST",status:400});return E},w=async g=>{const E=d(g,u.storageList,{code:"STORAGE_NOT_CONFIGURED",message:"storage endpoint requires a `storageList` function on the worker"}),_=new URL(g.url),T=await E(n(_,"prefix"),{bucket:n(_,"bucket"),cursor:n(_,"cursor"),...r(g)});return Response.json(T,{headers:{"content-type":"application/json"},status:200})},R=g=>(L(g,"GET","Storage-buckets"),t(g),Response.json({buckets:u.storageBuckets??[]},{headers:{"content-type":"application/json"},status:200})),I=async g=>{const E=d(g,u.storageDelete,{code:"STORAGE_DELETE_NOT_CONFIGURED",message:"storage delete requires a `storageDelete` function on the worker"}),_=new URL(g.url),T=h(_);return await E(T,{bucket:n(_,"bucket")}),Response.json({deleted:!0,key:T},{headers:{"content-type":"application/json"},status:200})},b=async g=>{const E=d(g,u.storageUpload,{code:"STORAGE_UPLOAD_NOT_CONFIGURED",message:"storage upload requires a `storageUpload` function on the worker"}),_=new URL(g.url),T=h(_),N=await o(g,Nt),v=g.headers.get("content-type"),x=v===null||v===""?void 0:v,j=n(_,"expectedSha256"),G=n(_,"expectedSize");let P;if(j!==void 0||G!==void 0){const M=await crypto.subtle.digest("SHA-256",N);P=ba(M);const B=G!==void 0&&N.byteLength!==Number(G),K=j!==void 0&&P!==j.toLowerCase();if(B||K)throw new i("Upload failed verification — the body did not match the declared size or SHA-256 checksum, so nothing was written",{code:"STORAGE_CHECKSUM_MISMATCH",status:400})}const Q=await E(T,N,{bucket:n(_,"bucket"),contentType:x});return Response.json(P===void 0?Q:{...Q,sha256:P},{headers:{"content-type":"application/json"},status:200})},k=async g=>{switch(g.method){case"DELETE":return I(g);case"GET":return w(g);case"POST":case"PUT":return b(g);default:throw new i("Storage endpoint requires GET, PUT, POST, or DELETE",{code:"METHOD_NOT_ALLOWED",status:405})}},p=async g=>{L(g,"GET","Storage URL");const E=d(g,u.storageSignedUrl,{code:"STORAGE_URL_NOT_CONFIGURED",message:"storage URL endpoint requires a `storageSignedUrl` function on the worker"}),_=new URL(g.url),T=h(_),N=Number(n(_,"expiresIn")??""),v=Number.isFinite(N)&&N>0?Math.min(N,ga):void 0,x=n(_,"method");if(x!==void 0&&!ya.has(x))throw new i("Storage URL `method` must be GET or PUT",{code:"BAD_REQUEST",status:400});const j=x,G=n(_,"contentType"),P=await E(T,{bucket:n(_,"bucket"),contentType:G,expiresInSeconds:v,method:j});return Response.json({key:T,url:P},{headers:{"content-type":"application/json"},status:200})};return{[wa]:R,[Ut]:k,[ma]:p}},Ra=(e,...t)=>{let r=e.cf;for(const n of t){if(typeof r!="object"||r===null)return;r=r[n]}return typeof r=="string"?r:void 0},ut={mtls:e=>Ra(e,"tlsClientAuth","certVerified")==="SUCCESS"},Ea=e=>e===void 0||e===!1?()=>!1:e===!0?()=>!0:typeof e=="function"?e:(Object.hasOwn(ut,e)?ut[e]:void 0)??(()=>!1),Sa=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.'))}},Oa="/_lunora/admin/vector/indexes",Ta="/_lunora/admin/vector/query",va=e=>{const{readJsonBody:t,requireAdminOption:r}=e,n=async d=>{L(d,"GET","Vector-indexes");const u=r(d,e.vectorIntrospector,{code:"VECTORS_NOT_CONFIGURED",message:"vector endpoints require a `vectorIntrospector` on the worker"});return Response.json({indexes:await u.listIndexes()},{headers:{"content-type":"application/json"},status:200})},o=async d=>{L(d,"POST","Vector-query");const u=r(d,e.vectorIntrospector,{code:"VECTORS_NOT_CONFIGURED",message:"vector endpoints require a `vectorIntrospector` on the worker"});if(u.queryIndex===void 0)throw new i("vector index querying is not enabled on this worker",{code:"VECTOR_QUERY_UNSUPPORTED",status:400});const h=await t(d);if(typeof h.name!="string"||h.name==="")throw new i("Vector-query request requires a `name` string",{code:"BAD_REQUEST",status:400});if(typeof h.text!="string"||h.text==="")throw new i("Vector-query request requires a `text` string",{code:"BAD_REQUEST",status:400});if(h.topK!==void 0&&(typeof h.topK!="number"||!Number.isInteger(h.topK)||h.topK<1))throw new i("Vector-query `topK` must be a positive integer",{code:"BAD_REQUEST",status:400});const w=await u.queryIndex({name:h.name,text:h.text,topK:h.topK});return Response.json(w,{headers:{"content-type":"application/json"},status:200})};return{[Oa]:n,[Ta]:o}},Aa="/_lunora/admin/workflows/instances",ka="/_lunora/admin/workflows/instance",Ia="/_lunora/admin/workflows/status",Da={complete:!0,errored:!0,paused:!0,queued:!0,running:!0,terminated:!0,unknown:!0,waiting:!0,waitingForPause:!0},Pa=e=>e!==null&&Object.hasOwn(Da,e)?e:void 0,lt=(e,t)=>{const r=e.searchParams.get(t);if(r===null)return;const n=Number(r);return Number.isInteger(n)&&n>0?n:void 0},Le=(e,t)=>{const r=e.searchParams.get(t);if(r===null||r==="")throw new i(`Workflows admin endpoint requires a \`${t}\` query parameter`,{code:"BAD_REQUEST",status:400});return r},ht=()=>{throw new i("Workflow inspection is unconfigured. Set CLOUDFLARE_ACCOUNT_ID + CLOUDFLARE_API_TOKEN in your .dev.vars to enable it.",{code:"WORKFLOWS_NOT_CONFIGURED",status:501})},Ua=e=>{const{assertAdmin:t,resolveWorkflowsClient:r}=e,n=async(u,h,w)=>{L(u,"GET","Workflows instances"),t(u);const R=r(h);if(!R)return Response.json({configured:!1,instances:[],page:1,perPage:0,totalCount:0});const I=Le(w,"name"),b=Pa(w.searchParams.get("status"));return Response.json(await R.listInstances({page:lt(w,"page"),perPage:lt(w,"perPage"),status:b,workflowName:I}))},o=async(u,h,w)=>{L(u,"GET","Workflows instance"),t(u);const R=r(h);return R?Response.json(await R.getInstance({instanceId:Le(w,"id"),workflowName:Le(w,"name")})):ht()},d=async(u,h)=>{L(u,"POST","Workflows status"),t(u);const w=r(h);if(!w)return ht();const R=await u.json().catch(()=>{});if(typeof R?.name!="string"||R.name===""||typeof R.id!="string"||R.id==="")throw new i("Workflows status action requires string `name` and `id`",{code:"BAD_REQUEST",status:400});const{action:I}=R;if(I!=="pause"&&I!=="resume"&&I!=="terminate")throw new i("Workflows status action must be one of: pause, resume, terminate",{code:"BAD_REQUEST",status:400});return Response.json(await w.setInstanceStatus({action:I,instanceId:R.id,workflowName:R.name}))};return{[ka]:o,[Aa]:n,[Ia]:d}},Na={[Dt]:Pt,[Ut]:Nt},qa=new TextEncoder,pt="/_lunora/rpc",Ca="/_lunora/rpc-batch",ja="/_lunora/ws",Re=(e,t,r)=>({resourceAttributes:sa(e,t),...r===void 0?{}:{waitUntil:r}}),ft=e=>e?.waitUntil?{waitUntil:t=>e.waitUntil?.(t)}:{},mt=e=>({spanId:e.spanId,traceFlags:e.traceFlags,traceId:e.traceId,...e.parentSpanId===void 0?{}:{parentSpanId:e.parentSpanId}}),Ke=e=>{const{method:t}=e,r=e.headers.get("user-agent")??void 0;let n;try{n=new URL(e.url)}catch{return{method:t,userAgent:r}}const o=n.port===""?void 0:Number(n.port);return{host:n.hostname,method:t,path:n.pathname,port:Number.isNaN(o)?void 0:o,scheme:n.protocol.replace(":",""),userAgent:r}},wt="/_lunora/voice/",xa="/_lunora/scheduler/dispatch",Ba="/_lunora/admin/cron-jobs/run",$a="/_lunora/admin/ws-token",La="/_lunora/admin/",Ka="/_lunora/migrate",Fa="/_lunora/status",Ga=e=>e.startsWith(La)||e===Ka,Qa=new Set(["1","enabled","on","true","yes"]),Ma=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}}},za="/api/auth",Wa="__lunora_admin__:recordAuthEvent",Ha="__lunora_admin__:listPushSubscriptions",Ja=["/sign-in","/sign-up","/callback"],Va=(e,t)=>{const r=t.endsWith("/")?t.slice(0,-1):t;if(!e.startsWith(`${r}/`))return!1;const n=e.slice(r.length);return Ja.some(o=>n===o||n.startsWith(`${o}/`))},Ee=(e,t,r,n)=>{const o=pr(r),d=o?r.code:"INTERNAL_SERVER_ERROR",u=o?r.status:500,h=r instanceof Error?r.message:String(r);return{durationMs:t,error:{code:d,message:h,status:u},functionPath:e,ok:!1,...n.fanOut?{fanOut:{failed:0,shards:0,table:n.fanOut.table}}:{},...n.shardKey?{shardKey:n.shardKey}:{}}},Ya=e=>{const{exp:t,expiresAtMs:r}=e;if(typeof r=="number"&&Number.isFinite(r))return r;if(typeof t=="number"&&Number.isFinite(t))return t*1e3},gt=e=>e.waitUntil?{waitUntil:t=>{e.waitUntil?.(t)}}:void 0,Xa=e=>{const t=e?.queue;return typeof t=="string"&&t.length>0?t:"unknown"},de=async(e,t,r)=>{const n={"content-type":"application/json"},o=e.headers.get("authorization"),d=e.headers.get("cookie"),u=e.headers.get("x-d1-bookmark"),h=e.headers.get("x-lunora-mutation-id"),w=e.headers.get("x-lunora-client-id"),R=e.headers.get("x-lunora-client-seq");o&&(n.authorization=o),d&&(n.cookie=d),u&&(n["x-d1-bookmark"]=u),h&&(n["x-lunora-mutation-id"]=h),w&&(n["x-lunora-client-id"]=w),R&&(n["x-lunora-client-seq"]=R);const I=e.headers.get("cf-connecting-ip");if(I&&(n["x-lunora-client-ip"]=I),!r)return{claims:null,headers:n,identity:null,userId:null};const b=await r(e,t);if(!b||typeof b.userId!="string"||b.userId.length===0)return{claims:null,headers:n,identity:null,userId:null};n["x-lunora-userid"]=wr(b.userId);const k=Ya(b);k!==void 0&&(n["x-lunora-identity-exp"]=String(k));const{userId:p,...g}=b,E=Object.keys(g).length>0?g:null;return E&&(n["x-lunora-identity"]=gr(E)),{claims:E,headers:n,identity:b,userId:p}},Za=new Set(["concat","first","groupBy","max","min","rank","sum","topK"]),eo=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"||!Za.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},to=(e,t)=>{e?.LUNORA_DEBUG_RPC&&console.warn(`[lunora:rpc] ${t.fanOut?"fan-out":`shard=${t.shardKey??"(root)"}`} ${t.functionPath}`)},yt=(e,t)=>{const r=t.functions?.[e.functionPath]?.x402;if(r){if(e.fanOut)throw new i("a paid (`.x402`) function cannot be fanned out",{code:"BAD_REQUEST",status:400});if(!t.x402Charge)throw new i(`function "${e.functionPath}" is marked paid (.x402) but no x402Charge gate is configured on the worker`,{code:"MISCONFIGURED",status:500});return r}},ro=async e=>{const t=await St(e);let r;try{r=JSON.parse(t)}catch{throw new i("RPC body must be valid JSON",{code:"BAD_REQUEST",status:400})}if(!r||typeof r!="object"||typeof r.functionPath!="string")throw new i("RPC envelope is missing `functionPath`",{code:"BAD_REQUEST",status:400});const n=r;if(n.args!==void 0&&Ot(n.args,"RPC"),n.shardKey!==void 0&&typeof n.shardKey!="string")throw new i("RPC `shardKey` must be a string",{code:"BAD_REQUEST",status:400});const o=r,d=eo(o.fanOut),u=o.args??{};if(d&&o.functionPath.startsWith("__lunora_relation__:")){const h=u.table;if(typeof h=="string"&&h!==d.table)throw new i("RPC `args.table` must match the authorized `fanOut.table` for a relation fan-out",{code:"BAD_REQUEST",status:400});u.table=d.table}return{args:u,fanOut:d,functionPath:o.functionPath,shardKey:o.shardKey}},oe=async(e,t,r)=>ve(e,t).fetch(r),Se=new Map,no=5e3,ao=4096,oo=async(e,t)=>{const r=Date.now(),n=Se.get(t);if(n!==void 0&&n.expiresMs>r)return n.relayCount;n!==void 0&&Se.delete(t);let o=0;try{const d=await ve(e,t).fetch(new Request("https://shard.internal/_lunora/route"));if(d.ok){const u=(await d.json()).relayCount;typeof u=="number"&&u>0&&(o=Math.floor(u))}}catch{o=0}return Rt(Se,ao),Se.set(t,{expiresMs:r+no,relayCount:o}),o},so=(e,t)=>{if(!(e===null||typeof e!="object"))return Object.entries(e).find(([,r])=>r===t)?.[0]},Oe=(e,t,r)=>new Request("https://shard.internal/rpc",{body:JSON.stringify({args:t,functionPath:e}),headers:r,method:"POST"}),io=["x-lunora-userid","x-lunora-identity","x-lunora-identity-exp"],bt=(e,t)=>{for(const r of io){e.delete(r);const n=t[r];n!==void 0&&e.set(r,n)}},co=async(e,t,r)=>e.length===0||r.length===0?!1:Fe(await At(e,t),r),_t=(e,t)=>{if(!t||t.length===0)return!1;const r=e.headers.get("authorization");if(!r)return!1;const[n,...o]=r.split(" ");return n?.toLowerCase()!=="bearer"?!1:Fe(t,o.join(" ").trim())},uo=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 Wr(t,n)?!0:r?!1:Fe(t,n)},lo=(e,t)=>{if(t===null||typeof t!="object"&&typeof t!="function")return;const r=t;if(typeof r.prepare=="function"&&typeof r.batch=="function"&&typeof r.dump=="function")return Ir(`d1:${e}`,t);if(typeof r.list=="function"&&typeof r.head=="function"&&typeof r.createMultipartUpload=="function")return Ne(`r2:${e}`,!0);if(typeof r.send=="function"&&typeof r.sendBatch=="function"&&typeof r.get!="function")return Ne(`queue:${e}`,!0);if(typeof r.connectionString=="string")return Ne(`hyperdrive:${e}`,!0)},qt=e=>{const t=Ea(e.trustInboundTraceContext),r=Sa(e.trustInboundTraceContext),n=e.defaultShardKey??"__root__",o=Dr(e.resolveIdentity,e.identity),d=Ye(e.shardDO,e.jurisdiction),u=e.schedulerDO===void 0?void 0:Ye(e.schedulerDO,e.jurisdiction);let h;const w=()=>e.adminToken??h;let R;const I=()=>e.requireEphemeralWsToken??R??!1,b=a=>{const s=a??{};if(R===void 0&&e.requireEphemeralWsToken===void 0){const c=s.LUNORA_REQUIRE_EPHEMERAL_WS_TOKEN;typeof c=="string"&&c.length>0&&(R=Qa.has(c.trim().toLowerCase()))}if(h!==void 0||e.adminToken!==void 0)return;const l=s.LUNORA_ADMIN_TOKEN;typeof l=="string"&&l.length>0&&(h=l)},k=new WeakSet,p=a=>_t(a,w())||k.has(a),g=async(a,s)=>{const l=await de(a,s,e.resolveIdentity);if(k.has(a)&&l.headers.authorization===void 0){const c=w();c!==void 0&&(l.headers.authorization=`Bearer ${c}`)}return l};let E=!1;const _=a=>{if(!e.allowUnauthenticatedShardAccess){const s=a==="fan-out"?"authorizeFanOut":"authorizeShard";throw new i(`${a} access is default-denied: configure \`${s}\` on the worker, or set \`allowUnauthenticatedShardAccess: true\` to explicitly allow unauthenticated ${a} access (relying solely on per-row RLS).`,{code:a==="fan-out"?"FORBIDDEN_FANOUT":"FORBIDDEN_SHARD",status:403})}E||(E=!0,console.warn([`[lunora] SECURITY: serving ${a} access with \`allowUnauthenticatedShardAccess: true\` and no \`authorizeShard\`/\`authorizeFanOut\` — `,"any caller (including unauthenticated ones) can target any shard / fan out across the table. ","This is safe only if every table is protected by per-row RLS. Configure `authorizeShard`/`authorizeFanOut` to gate it."].join("")))},T=async(a,s,l=!0)=>{if(e.authorizeShard){if(!await e.authorizeShard(a,s))throw new i("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else l&&s!==n&&_("shard")},N=Vn({defaultShard:n,forwardToShard:oe,isAdmin:p,queryCoordinator:e.queryCoordinator,resolveForwardContext:g,shardDO:d}),v=async(a,s,l,c,m)=>{await T(null,l,!1);const y={"content-type":"application/json","x-lunora-system":"1"};return m?.userId!==void 0&&m.userId.length>0&&(y["x-lunora-userid"]=m.userId),m?.identity!==void 0&&m.identity.length>0&&(y["x-lunora-identity"]=m.identity),c!==void 0&&c.length>0&&(y["x-lunora-mutation-id"]=c),oe(d,l,Oe(a,s,y))},x=async(a,s,l,c)=>{const m=l?.[a];if(!m||typeof m.create!="function")throw new i(`${c} targets workflow binding "${a}", which is not bound on env`,{code:"CRON_JOB_FAILED",status:500});if(jr(s))throw new i(`${c} params ${xr}`,{code:"BAD_REQUEST",status:400});await m.create({params:s})},j=async(a,s)=>{if(a.workflow){await x(a.workflow,a.args??{},s,`cron job "${a.name}"`);return}if(a.functionPath===void 0)throw new i(`cron job "${a.name}" has neither a function target nor a workflow target`,{code:"CRON_JOB_FAILED",status:500});const l=await v(a.functionPath,a.args??{},a.shardKey??n);if(!l.ok)throw new i(`cron job "${a.name}" (${a.functionPath}) failed with shard status ${String(l.status)}`,{code:"CRON_JOB_FAILED",status:500})},G=async(a,s,l,c)=>{const m=e.cronJobs?.[a];if(m)for(const y of m)try{await j(y,s)}catch(A){l.push(c(A))}},P=async(a,s)=>{if(!p(a))throw new i("admin endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403});if(L(a,"POST","cron-jobs run"),!e.cronJobs)throw new i("cron-jobs run endpoint requires a `cronJobs` map on the worker",{code:"CRON_JOBS_NOT_CONFIGURED",status:400});const l=await ee(a),c=typeof l.name=="string"?l.name:"";if(c==="")throw new i("cron-jobs run endpoint requires a job `name`",{code:"BAD_REQUEST",status:400});const m=Object.values(e.cronJobs).flat().find(y=>y.name===c);if(!m)throw new i(`no cron job named "${c}" is registered`,{code:"CRON_JOB_NOT_FOUND",status:404});return await j(m,s),Response.json({name:c,ran:!0},{status:200})},Q=async a=>{const s=typeof a.pool=="string"&&a.pool.length>0?a.pool:void 0;if(!s||!u||typeof a.id!="string")return;const l=typeof a.instanceName=="string"&&a.instanceName.length>0?a.instanceName:"default";try{await u.get(u.idFromName(l)).fetch(new Request("https://scheduler.internal/complete",{body:JSON.stringify({id:a.id,pool:s}),headers:{"content-type":"application/json"},method:"POST"}))}catch{}},M=async(a,s)=>{L(a,"POST","Scheduler dispatch");const l=await St(a),c=s??{},m=typeof c.LUNORA_SCHEDULER_SECRET=="string"?c.LUNORA_SCHEDULER_SECRET:void 0,y=e.adminToken??(typeof c.LUNORA_ADMIN_TOKEN=="string"?c.LUNORA_ADMIN_TOKEN:void 0),A=a.headers.get("x-lunora-scheduler-signature");let f=!1;if(A&&m?f=await co(m,l,A):y&&(f=_t(a,y)),!f)throw new i("Scheduler dispatch requires a valid signature or admin bearer",{code:"FORBIDDEN",status:403});let S;try{S=JSON.parse(l)}catch{throw new i("Scheduler dispatch body must be valid JSON",{code:"BAD_REQUEST",status:400})}const O=S??{},q=O.args??{};if(typeof O.workflow=="string"&&O.workflow.length>0)return await x(O.workflow,q,s,"scheduled workflow"),Response.json({ok:!0},{status:200});if(typeof O.functionPath!="string"||O.functionPath.length===0)throw new i("Scheduler dispatch is missing `functionPath`",{code:"BAD_REQUEST",status:400});const C=typeof O.shardKey=="string"&&O.shardKey.length>0?O.shardKey:n,$=typeof O.id=="string"&&O.id.length>0?O.id:void 0,V=Ma(a),Z=await v(O.functionPath,q,C,$,V);return await Q(O),Z},B=a=>{if(!p(a))throw new i("admin endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403})},K=(a,s,l)=>{if(B(a),s===void 0)throw new i(l.message,{code:l.code,status:400});return s},X=Xr({assertAdmin:B,getReader:()=>e.authAuditReader}),J=async(a,s)=>{B(a);const l=e.notifySubscriptionStore;if(l===void 0)return Response.json({subscriptions:[]},{headers:{"content-type":"application/json"},status:200});const c=s?.kind,m=s?.userId,y=s?.limit,A=c==="fcm"||c==="web-push"?c:void 0,f=typeof m=="string"&&m!==""?m:void 0,S=typeof y=="number"&&Number.isFinite(y)?Math.trunc(y):0,O=S>0?Math.min(S,1e3):1e3,q=(await l.list({kind:A,limit:O,userId:f})).filter(C=>A!==void 0&&C.kind!==A?!1:f===void 0||(C.userId??null)===f).map(({keys:C,token:$,...V})=>V);return Response.json({subscriptions:q},{headers:{"content-type":"application/json"},status:200})},ne=async(a,s)=>{if(!s.fanOut){if(s.functionPath===Yr)return X(a,s.args??{});if(s.functionPath===Ha)return J(a,s.args)}},he=fn({applyGlobals:e.applyGlobals,assertAdmin:B,exportCursorStore:e.exportCursorStore,exportSinks:e.exportSinks,knownTables:()=>[],queryCoordinator:e.queryCoordinator,requireAdminOption:K,resolveForwardContext:g,shardDO:d,streamExportRows:(a,s,l,c)=>st(e,a,s,l,c,d),streamingImport:(a,s)=>_n(a,e,s,d),syncGlobals:e.syncGlobals}),ae=(a,s)=>{const l=a.searchParams.get(s);return l===null||l===""?void 0:l},pe=a=>{const s=new URL(a.url),l=s.searchParams.get("limit"),c=s.searchParams.get("offset"),m=l===null?void 0:Number.parseInt(l,10),y=c===null?void 0:Number.parseInt(c,10);return{limit:m!==void 0&&Number.isFinite(m)&&m>=0?m:void 0,offset:y!==void 0&&Number.isFinite(y)&&y>=0?y:void 0}},be=()=>{if(u===void 0)throw new i("scheduled endpoints require a `schedulerDO` namespace on the worker",{code:"SCHEDULER_NOT_CONFIGURED",status:400});return u},Ae=fa({checkWsAdmin:async a=>p(a)||uo(a,w(),I()),requireSchedulerNamespace:be,resolveSchedulerStub:a=>(B(a),ve(be(),e.schedulerInstanceName??"default")),schedulerInstanceName:e.schedulerInstanceName??"default"}),se=Ua({assertAdmin:B,resolveWorkflowsClient:e.workflowsClient??(()=>{})}),Ct=_a({assertAdmin:B,parsePaging:pe,queryParameter:ae,readBodyBytes:Tr,requireAdminOption:K,storage:{storageBuckets:e.storageBuckets,storageDelete:e.storageDelete,storageList:e.storageList,storageSignedUrl:e.storageSignedUrl,storageUpload:e.storageUpload}}),jt=va({readJsonBody:ee,requireAdminOption:K,vectorIntrospector:e.vectorIntrospector}),xt=Cn({kvIntrospector:e.kvIntrospector,readJsonBody:ee,requireAdminOption:K}),Bt=Pr({logArchive:e.logArchive,readJsonBody:ee,requireAdminOption:K}),$t=Un({assertAdmin:B,options:{cronJobs:e.cronJobs,functions:e.functions,globalIntrospector:e.globalIntrospector,openApiSpec:e.openApiSpec,openRpcSpec:e.openRpcSpec},parsePaging:pe,queryParameter:ae,requireAdminOption:K}),Lt=a=>{const s=[],l=d??a?.SHARD;if(l!==void 0&&s.push(kr("durable-object:default",l,n)),e.health?.disableBindingProbes!==!0)for(const[c,m]of Object.entries(a??{})){const y=lo(c,m);y!==void 0&&s.push(y)}for(const c of e.health?.probes??[])s.push(c);return s},Kt=Ar({appName:e.health?.appName,appVersion:e.health?.appVersion,auth:e.health?.auth??"public",cacheTtlMs:e.health?.cacheTtlMs,isAdmin:p,resolveProbes:Lt}),Ft=a=>{const s=e.schedulerInstanceName??"default",l=()=>a.get(a.idFromName(s)),c=async(f,S)=>{const O=await l().fetch(new Request(`https://scheduler.internal${f}`,S));if(!O.ok)throw new i(`ctx.scheduler: SchedulerDO ${f} failed (${String(O.status)}): ${await O.text()}`,{code:"INTERNAL",status:500});return await O.json()},m=async(f,S)=>await c(f,{body:JSON.stringify(S),headers:{"content-type":"application/json"},method:"POST"}),y=f=>{const S=f;if(S==null)throw new i("ctx.scheduler: target is required — pass a reference from the generated `internal` / `workflows` / `agents`",{code:"BAD_REQUEST",status:400});if(typeof S.binding=="string"&&S.binding.length>0)return{workflow:S.binding};if(typeof S.__lunoraRef=="string")return{functionPath:S.__lunoraRef};throw new i("ctx.scheduler: expected a reference from the generated `internal` / `workflows` / `agents` — a bare function-path string is refused here, because an HTTP action can be reached unauthenticated",{code:"BAD_REQUEST",status:400})},A=async(f,S,O={})=>{const{id:q}=await m("/schedule",{args:O,scheduledFor:f,...y(S)});return q};return{cancel:async f=>await m("/cancel",{id:f}),get:async f=>await c(`/get?id=${encodeURIComponent(f)}`,{method:"GET"}),list:async()=>await c("/list",{method:"GET"}),runAfter:async(f,S,O)=>{if(!Number.isFinite(f)||f<0)throw new i("ctx.scheduler.runAfter: `delayMs` must be a non-negative finite number",{code:"BAD_REQUEST",status:400});return await A(Date.now()+f,S,O)},runAt:async(f,S,O)=>{if(!Number.isFinite(f))throw new i("ctx.scheduler.runAt: `timestampMs` must be a finite epoch-millisecond number",{code:"BAD_REQUEST",status:400});return await A(f,S,O)}}},Gt=async(a,s,l)=>{const{claims:c,headers:m,userId:y}=await de(a,s,o),A=async(f,S={})=>{const O=f.__lunoraRef;if(typeof O!="string")throw new i("ctx.run*: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});const q=Oe(O,S,{...m,"x-lunora-system":"1"}),C=await oe(d,n,q),$=await C.json();if($.error)throw new i($.error.message??"shard RPC failed",{code:$.error.code??"INTERNAL",status:C.status});return $.result};return{auth:{getIdentity:()=>Promise.resolve(c),userId:y},cache:l.cache,fetch:globalThis.fetch.bind(globalThis),runAction:A,runMutation:A,runQuery:A,...u===void 0?{}:{scheduler:Ft(u)},...e.storage===void 0?{}:{storage:Cr(e.storage(s))}}},Qt=async(a,s,l)=>{if(!e.httpRouter)return;const c=await Gt(a,s,l);try{return await e.httpRouter.fetch(a,{...s,__lunoraCtx:c},l)}catch(m){return console.error("[lunora] httpRouter (SSR) handler threw:",m),new Response("Internal Server Error",{status:500})}},Mt=async(a,s,l)=>{if(a.headers.get("Upgrade")!=="websocket")throw new i("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});const c=Ze(a,ie);if(c)return c;const m=l.searchParams.get("shard")??n,{headers:y,identity:A}=await de(a,s,o);await T(A,m);const f=new Headers(a.headers),S=[...f.keys()];for(const q of S)q.startsWith("x-lunora-")&&f.delete(q);bt(f,y);const O=so(s,e.shardDO);if(O!==void 0){f.set("x-lunora-shard-binding",O);const q=await oo(d,m);if(q>0){const C=Qr(m,Math.floor(Math.random()*q));return oe(d,C,new Request(a,{headers:f}))}}return oe(d,m,new Request(a,{headers:f}))},zt=async(a,s,l)=>{const{voiceAgents:c}=e;if(c===void 0)return new Response("Not found",{status:404});if(a.headers.get("Upgrade")!=="websocket")return new Response("Expected a WebSocket upgrade",{headers:{allow:"GET"},status:426});const m=Ze(a,ie);if(m)return m;let y;try{y=decodeURIComponent(l.pathname.slice(wt.length))}catch{return new Response("Unknown voice agent",{status:404})}const A=Object.hasOwn(c,y)?c[y]:void 0;if(A===void 0)return new Response("Unknown voice agent",{status:404});const f=l.searchParams.get("threadKey");if(f===null||f.length===0)return new Response("Missing threadKey",{status:400});const{headers:S,identity:O}=await de(a,s,o);if(e.authorizeShard){if(!await e.authorizeShard(O,f))return new Response("Forbidden",{status:403})}else _("shard");const q=new Headers(a.headers);return bt(q,S),oe(A,f,new Request(a,{headers:q}))},Wt=async(a,s,l)=>{if(e.authorizeFanOut){if(!await e.authorizeFanOut(l,a.table,s))throw new i("Forbidden fan-out",{code:"FORBIDDEN_FANOUT",status:403});return}if(s.startsWith("__lunora_relation__:"))throw new i("reverse cross-backend relation reads (`__lunora_relation__:*`) require `authorizeFanOut` to be configured on the worker",{code:"FORBIDDEN_FANOUT",status:403});if(e.authorizeShard)throw new i("Fan-out requires `authorizeFanOut` to be configured on the worker when `authorizeShard` is set",{code:"FORBIDDEN_FANOUT",status:403});_("fan-out")},_e=async(a,s)=>{if(!(!a.fanOut&&a.functionPath.startsWith("__lunora_admin__:"))){if(a.fanOut){await Wt(a.fanOut,a.functionPath,s);return}await T(s,a.shardKey??n)}},ke=async(a,s,l,c,m,y)=>{const A=Date.now(),{observability:f,sampling:S}=e,O=Ke(a),{decision:q,ignoredUpstream:C,trace:$}=aa(a,{...S===void 0?{}:{sampling:S},trustInbound:t(a)});C&&r();const V={...m,"x-lunora-sample-errors":q.keepErrors?"1":"0"};oa($,V);const Z=Oe(s,l,V);try{const F=await oe(d,c,Z);return ce(f,{...O,...mt($),durationMs:Date.now()-A,functionPath:s,ok:F.ok,shardKey:c,...F.ok?{}:{error:{code:"SHARD_ERROR",message:`shard returned ${String(F.status)}`,status:F.status}}},y,void 0,{isTraced:$.sampled,keepErrors:q.keepErrors}),F}catch(F){throw ce(f,{...O,...mt($),...Ee(s,Date.now()-A,F,{shardKey:c})},y,void 0,{isTraced:$.sampled,keepErrors:q.keepErrors}),F}},Ht=a=>{if(a.fanOut&&a.shardKey)throw new i("RPC envelope cannot set both `shardKey` and `fanOut`",{code:"BAD_REQUEST",status:400});if(!a.fanOut&&a.functionPath.startsWith("__lunora_relation__:"))throw new i("`__lunora_relation__:*` is a fan-out-only reserved RPC and cannot be dispatched to a single shard",{code:"FORBIDDEN",status:403});if(a.fanOut&&!e.queryCoordinator)throw new i("RPC envelope set `fanOut` but no `queryCoordinator` is configured on the worker",{code:"BAD_REQUEST",status:400})},Jt=async(a,s,l)=>{L(a,"POST","RPC");const c=await ro(a);to(s,c),Ht(c);const m=await ne(a,c);if(m!==void 0)return m;const{headers:y,identity:A}=await de(a,s,o);await _e(c,A);const f=yt(c,e);{const S=Date.now(),{observability:O}=e,q=Ke(a),C=Re(s,a,l&&(Z=>l.waitUntil?.(Z)));if(c.fanOut){const Z=e.queryCoordinator;if(!Z)throw new i("RPC envelope set `fanOut` but no `queryCoordinator` is configured on the worker",{code:"BAD_REQUEST",status:400});try{const F=await Z.fanOut(d,{args:c.args??{},fanOut:c.fanOut,functionPath:c.functionPath,headers:y});return ce(O,{durationMs:Date.now()-S,fanOut:{failed:F.failed,shards:F.ok+F.failed,table:c.fanOut.table},functionPath:c.functionPath,...q,ok:!0},C),Response.json(F,{headers:{"content-type":"application/json"},status:200})}catch(F){throw ce(O,{...Ee(c.functionPath,Date.now()-S,F,{fanOut:{table:c.fanOut.table}}),...q},C),F}}const $=c.shardKey??n,V=()=>ke(a,c.functionPath,c.args??{},$,y,C);return f&&e.x402Charge?e.x402Charge(a,{functionPath:c.functionPath,price:f.price},V,ft(l)):V()}},Vt=async(a,s,l)=>{L(a,"POST","RPC batch");const c=await ee(a),{calls:m}=c;if(!Array.isArray(m))throw new i("RPC batch `calls` must be an array",{code:"BAD_REQUEST",status:400});const{headers:y,identity:A}=await de(a,s,o),f=en(m,n);for(const z of f.values())for(const W of z)if(e.functions?.[W.functionPath]?.x402)throw new i(`paid (\`.x402\`) function "${W.functionPath}" cannot be called in a batch; dispatch it individually over ${pt}`,{code:"BAD_REQUEST",status:400});await Promise.all([...f.entries()].flatMap(([z,W])=>W.map(re=>_e({functionPath:re.functionPath,shardKey:z},A))));const{observability:S}=e,O=Re(s,a,l&&(z=>l.waitUntil?.(z))),q=Ke(a),C=[],$=[],V=(z,W,re,ue)=>({body:{error:{code:re,message:ue}},id:z.id,status:W}),Z=(z,W,re,ue,fe)=>{for(const H of z)ce(S,fe(H),O),C.push(V(H,W,re,ue))},F=(z,W,re,ue,fe)=>{for(const H of z){const me=ue.get(H.id)??fe,ge=me<400;ce(S,{durationMs:re,functionPath:H.functionPath,...q,ok:ge,shardKey:W,...ge?{}:{error:{code:"SHARD_ERROR",message:`batched call returned ${String(me)}`,status:me}}},O)}};await Promise.all([...f.entries()].map(async([z,W])=>{const re=new Headers(y);re.set("content-type","application/json");const ue=new Request("https://shard.internal/rpc-batch",{body:JSON.stringify({calls:W}),headers:re,method:"POST"}),fe=Date.now();let H;try{H=await oe(d,z,ue)}catch(Y){const Ue=Date.now()-fe,{body:He}=fr(Y,{fallbackCode:"SHARD_UNAVAILABLE",redactedMessage:"shard unavailable"});Z(W,502,He.code,He.message,hr=>({...Ee(hr.functionPath,Ue,Y,{shardKey:z}),...q}));return}const me=Date.now()-fe,ge=H.headers.get("x-d1-bookmark");ge&&$.push(ge);let De;try{De=await H.json()}catch{const Y=`shard batch returned a non-JSON response (${String(H.status)})`;Z(W,H.status,"SHARD_ERROR",Y,Ue=>({durationMs:me,error:{code:"SHARD_ERROR",message:Y,status:H.status},functionPath:Ue.functionPath,...q,ok:!1,shardKey:z}));return}const Pe=Array.isArray(De.results)?De.results:[],ur=new Map(Pe.map(Y=>[Y.id,Y.status??H.status])),lr=new Set(Pe.map(Y=>Y.id));F(W,z,me,ur,H.status),C.push(...Pe);for(const Y of W)lr.has(Y.id)||C.push(V(Y,H.status,"SHARD_ERROR",`shard batch omitted result for call ${String(Y.id)}`))}));const ze={"content-type":"application/json"},[We]=$;return $.length===1&&We!==void 0&&(ze["x-d1-bookmark"]=We),Response.json({results:C},{headers:ze,status:200})},Yt=async(a,s,l,c={},m={})=>{try{const y=l.__lunoraRef;if(typeof y!="string")throw new i("serverQuery: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});const{headers:A,identity:f}=await de(a,s,o);await _e({functionPath:y,shardKey:m.shardKey},f);const S=m.shardKey??n,O=Re(s,a,m.waitUntil);return await ke(a,y,c,S,A,O)}catch(y){return Je(y)}},Xt=1e3,Zt=async(a,s)=>{const l=e.backupRetain;if(l===void 0||l<=0)return;const c=[];let m;for(let A=0;A<Xt;A+=1){const f=await a.list({cursor:m,prefix:s});for(const S of f.objects)S.key.endsWith(".manifest.json")&&c.push(S.key);if(!f.truncated||f.cursor===void 0)break;m=f.cursor}const y=c.toSorted((A,f)=>f.localeCompare(A)).slice(l);await Promise.all(y.flatMap(A=>{const f=A.slice(0,-14);return[a.delete(A),a.delete(f)]}))},er=async a=>{const s=e.backupStore,l=e.queryCoordinator;if(!s)throw new i("scheduled backup requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});if(!l)throw new i("scheduled backup requires a `queryCoordinator` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});const c=w();if(!c||c.length===0)throw new i("scheduled backup requires an `adminToken` (or `env.LUNORA_ADMIN_TOKEN`) to authenticate the per-shard export gate",{code:"BACKUP_NOT_CONFIGURED",status:500});const m={authorization:`Bearer ${c}`,"content-type":"application/json"},y=e.backupTables;let A=0,f=0;const S=[];await st(e,l,m,y,Z=>{const F=`${JSON.stringify(Z)}
|
|
5
|
-
`;A+=1,f+=qa.encode(F).byteLength,S.push(F)},d);const O=e.backupPrefix??"backups/",q=new Date(a.scheduledTime).toISOString(),C=`${O}lunora-backup-${q.replaceAll(/[.:]/gu,"-")}.ndjson`,$=`${C}.manifest.json`;await s.put(C,new Blob(S,{type:"application/x-ndjson"}),{httpMetadata:{contentType:"application/x-ndjson"}});const V={bytes:f,createdAt:q,cron:a.cron,file:C,id:q,rows:A,scheduledTime:a.scheduledTime,...y?{tables:y.join(",")}:{}};await s.put($,`${JSON.stringify(V,void 0,2)}
|
|
6
|
-
`,{httpMetadata:{contentType:"application/json"}}),await Zt(s,O)},Qe=async(a,s,l)=>{const{observability:c}=e,m=Date.now(),y=Te(16),A=Te(8),f=gt(s);try{const S=await l();return ce(c,{durationMs:Date.now()-m,functionPath:a,ok:!0,spanId:A,traceId:y},f),S}catch(S){throw ce(c,{...Ee(a,Date.now()-m,S,{}),spanId:A,traceId:y},f),S}finally{Ve(c,f)}},tr=async(a,s,l)=>{b(s);const c=[],m=f=>f instanceof Error?f:new Error(String(f)),y=e.crons?.[a.cron];if(y)try{await y(a,s,l)}catch(f){c.push(m(f))}if(await G(a.cron,s,c,m),e.backupStore&&e.backupCron!==void 0&&e.backupCron===a.cron)try{await er(a)}catch(f){c.push(m(f))}const[A]=c;if(c.length===1&&A)throw A;if(c.length>1)throw new AggregateError(c,`scheduled("${a.cron}") had ${String(c.length)} failure(s)`)},rr=async(a,s)=>{try{const l=a??{},c=e.adminToken??(typeof l.LUNORA_ADMIN_TOKEN=="string"?l.LUNORA_ADMIN_TOKEN:void 0);if(!c||c.length===0)return;await oe(d,n,Oe(Wa,{outcome:s},{authorization:`Bearer ${c}`,"content-type":"application/json"}))}catch{}},nr=async(a,s,l,c)=>{if(!e.authHandler)return;const m=await e.authHandler(a);if(!m)return;const y=e.authBasePath??za;return Va(l.pathname,y)&&c.waitUntil?.(rr(s,m.status>=400?"fail":"ok")),m},ar=async({args:a,env:s,functionPath:l,request:c,shardKey:m,waitUntil:y})=>{Ot(a,"REST");const A={functionPath:l,...m===void 0?{}:{shardKey:m}},{headers:f,identity:S}=await de(c,s,o);await _e(A,S);const O=m??n,q=Re(s,c,y),C=()=>ke(c,l,a,O,f,q),$=yt(A,e);return $&&e.x402Charge?e.x402Charge(c,{functionPath:l,price:$.price},C,ft({waitUntil:y})):C()},or=Or({functions:e.functions??{},invoke:ar,readJsonBody:ee,...e.restRateLimit?{rateLimit:e.restRateLimit}:{}}),Ie=e.routes!==void 0&&Object.keys(e.routes).length>0?e.routes:void 0,sr={[Fa]: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"}}),[ja]:(a,s,l)=>Mt(a,s,l),[pt]:(a,s,l,c)=>Jt(a,s,c),[Ca]:(a,s,l,c)=>Vt(a,s,c),[xa]:(a,s)=>M(a,s),[Ba]:(a,s)=>P(a,s),[$a]:async a=>{L(a,"POST","ws-token"),B(a);const s=w();if(s===void 0)throw new i("ws-token minting requires a configured admin token",{code:"ADMIN_TOKEN_NOT_CONFIGURED",status:400});const l=await zr(s);return Response.json(l,{headers:{"cache-control":"no-store"}})},...N,...he,...Ae,...se,...Ct,...jt,...xt,...Bt,...$t,...Kt,...or,...Vr({assertAdmin:B,getAuthAdmin:()=>e.authAdmin,parsePaging:pe,queryParameter:ae,readJsonBody:ee})};let ie=Xe(e.security),Me=!1;const ir=a=>{Me||(Me=!0,ie=Xe(e.security,a??{}))},cr=async(a,s)=>{if(!(e.adminGate===void 0||!Ga(s)))try{await e.adminGate(a)&&k.add(a)}catch{}},dr=async(a,s,l)=>{const c=new URL(a.url);if(a.method==="POST"||a.method==="PUT"){const f=Number(a.headers.get("content-length")??""),S=Na[c.pathname]??Et;if(Number.isFinite(f)&&f>S)throw new i("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413})}const m=await nr(a,s,c,l);if(m)return m;if(Ie){const f=`${a.method} ${c.pathname}`,S=Ie[f]??Ie[c.pathname];if(S)return S(a,s,l)}const y=sr[c.pathname];return y?(await cr(a,c.pathname),y(a,s,c,l)):e.voiceAgents!==void 0&&c.pathname.startsWith(wt)?zt(a,s,c):await Qt(a,s,l)||new Response("Not found",{status:404})};return{async fetch(a,s,l){e.passThroughOnException&&l.passThroughOnException?.(),ir(s),b(s);const c=Nr(a,ie);if(c)return c;const m=qr(a,ie);if(m)return qe(m,a,ie);try{const y=await dr(a,s,l);return qe(y,a,ie)}catch(y){return qe(Je(y),a,ie)}finally{Ve(e.observability,gt(l))}},async queue(a,s,l){await Qe(`queue:${Xa(a)}`,l,async()=>{await e.queue?.(a,s,l)})},async scheduled(a,s,l){await Qe(`cron:${a.cron}`,l,async()=>{await tr(a,s,l)})},serverQuery:Yt}},ho=e=>qt(e),po=e=>typeof e=="function"?{fetch:e}:e,fo=e=>!!(e.crons??e.cronJobs??e.backupCron),Po=(e,t)=>{const r=po(e),n=typeof e=="object"&&typeof e.scheduled=="function"?e.scheduled:void 0,o=u=>{const h=ho({...u,httpRouter:r});return n!==void 0&&!fo(u)?{...h,scheduled:async(w,R,I)=>{await n(w,R,I)}}:h};if(typeof t!="function")return o(t);const d=t;return{fetch:(u,h,w)=>o(d(h)).fetch(u,h,w),queue:(u,h,w)=>o(d(h)).queue?.(u,h,w)??Promise.resolve(),scheduled:(u,h,w)=>o(d(h)).scheduled(u,h,w),serverQuery:(u,h,w,R,I)=>o(d(h)).serverQuery(u,h,w,R,I)}},mo=(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}},Uo=(e={})=>(t,r,n)=>qt(mo(e,r)).fetch(t,r,n??mr),No=e=>e;export{Yr as GET_AUTH_AUDIT_LOG_OP,mr as NOOP_EXECUTION_CONTEXT,jo as composeIdentityResolvers,ho as composeWorker,Uo as createLunoraHandler,qt as createWorker,No as defineRpcEnvelope,oo as probeRelayCount,mo as resolveLunoraOptions,xo as routeIdentityResolvers,Po as withFrameworkWorker};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{f as u,u as d}from"./identity-header-pdXOyDU4.mjs";import{LunoraError as o}from"./LunoraError-ByasbDmd.mjs";const l="/_lunora/rpc",c=r=>{const t={"content-type":"application/json"};return r.userId!==void 0&&r.userId.length>0&&(t["x-lunora-userid"]=u(r.userId)),r.identity!==void 0&&(t["x-lunora-identity"]=d(r.identity)),t},i=async(r,t,a)=>{const e=await(r.fetch??globalThis.fetch)(new Request(`${r.origin}${l}`,{body:JSON.stringify(t),headers:c(r),method:"POST"}));if(!e.ok)throw new o(`cross-shard relation ${a} failed: worker returned ${String(e.status)}`);const n=await e.json();if(typeof n.failed=="number"&&n.failed>0){const s=(typeof n.ok=="number"?n.ok:0)+n.failed;throw new o(`cross-shard relation ${a} failed on ${String(n.failed)} of ${String(s)} shard(s) — refusing to return a partial result`)}return n.data},y=r=>({crossShardCounter:async(t,a)=>{const e=await i(r,{args:{table:t,where:a},fanOut:{merge:{kind:"sum"},table:t},functionPath:"__lunora_relation__:count"},"count");return typeof e=="number"?e:0},crossShardReader:async(t,a)=>{const e=await i(r,{args:{orderBy:a?.orderBy,table:t,where:a?.where,with:a?.with},fanOut:{merge:{kind:"concat"},table:t},functionPath:"__lunora_relation__:read"},"read");return{continueCursor:null,isDone:!0,page:Array.isArray(e)?e:[]}}});export{y as createCrossShardRelationCapabilities};
|