@lunora/runtime 1.0.0-alpha.70 → 1.0.0-alpha.72
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 +27 -21
- package/dist/index.d.ts +27 -21
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/applyRestCache-BiAx6BGW.mjs +1 -0
- package/dist/packem_shared/{argsFromQuery-NAXezjJF.mjs → argsFromQuery-CRa3o4U3.mjs} +1 -1
- package/dist/packem_shared/{composeWorker-DVjmsFp1.mjs → composeWorker-D41ytQme.mjs} +5 -5
- package/dist/packem_shared/createKvCursorStore-kQ8HNv0l.mjs +3 -0
- package/dist/packem_shared/{createShardClient-DnQNYYNU.mjs → createShardClient-CCncsgTs.mjs} +1 -1
- package/dist/packem_shared/{decorateResponse-D3NzOIvB.mjs → decorateResponse-BuqVnrmc.mjs} +1 -1
- package/dist/packem_shared/portable-json-BAMIgqk5.mjs +1 -0
- package/dist/packem_shared/rest-cache-CPSyD1RD.mjs +1 -0
- package/dist/packem_shared/rest-routes-Dq17Zntv.mjs +1 -0
- package/dist/packem_shared/toAirbyteMessages-CZimuevO.mjs +1 -0
- package/dist/packem_shared/{wire-codec-0SQDg-5_.mjs → wire-codec-D_qTfaaH.mjs} +1 -1
- package/package.json +3 -3
- package/dist/packem_shared/applyRestCache-qYyCDFO2.mjs +0 -1
- package/dist/packem_shared/createKvCursorStore-VOd1DFsf.mjs +0 -3
- package/dist/packem_shared/rest-cache-BnMq2hbO.mjs +0 -1
- package/dist/packem_shared/rest-routes-D2b3HXA9.mjs +0 -1
- package/dist/packem_shared/toAirbyteMessages-Cy3uaySU.mjs +0 -1
package/dist/index.d.mts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
+
import { ShardDirectory, HttpCacheLike } from '@lunora/platform';
|
|
1
2
|
import { RankDirection, RankPageRow, DatabaseWriterLike, CrossShardReadArgs, QueryPage } from '@lunora/shard-engine';
|
|
2
3
|
export type { RankDirection as RankPageDirection, RankPageRowKey as RankPageKey, RankPageRow, ShardRankPageResult } from '@lunora/shard-engine';
|
|
3
|
-
import { ShardDirectory } from '@lunora/platform';
|
|
4
4
|
import { R2SqlClient } from '@lunora/bindings/r2sql';
|
|
5
5
|
import { WorkflowsRestClient } from '@lunora/workflow';
|
|
6
6
|
import { LunoraError as LunoraError$1, ErrorBody } from '@lunora/errors';
|
|
@@ -76,24 +76,6 @@ interface BackupManifestEntry {
|
|
|
76
76
|
* without a guard.
|
|
77
77
|
*/
|
|
78
78
|
declare const isBackupManifestEntry: (value: unknown) => value is BackupManifestEntry;
|
|
79
|
-
/**
|
|
80
|
-
* Turn-key incremental-sync source helpers for warehouse connectors
|
|
81
|
-
* (Fivetran custom functions, Airbyte incremental sources).
|
|
82
|
-
*
|
|
83
|
-
* The runtime's admin `/_lunora/admin/connector/sync` endpoint returns a
|
|
84
|
-
* {@link ConnectorSyncPage}: a flat list of change records since an opaque
|
|
85
|
-
* cursor, a `nextCursor` to resume from, and a `hasMore` flag. These helpers
|
|
86
|
-
* reshape that page into the response envelopes the two ecosystems expect, so a
|
|
87
|
-
* connector wrapper stays a few lines.
|
|
88
|
-
*
|
|
89
|
-
* {@link toFivetranResponse} produces the `{ state, insert, update, delete,
|
|
90
|
-
* hasMore, schema }` object a Fivetran connector function returns from its
|
|
91
|
-
* handler. {@link toAirbyteMessages} produces an ordered array of Airbyte
|
|
92
|
-
* protocol messages (a `RECORD` per row, a trailing `STATE` carrying the cursor),
|
|
93
|
-
* the line-delimited stream an Airbyte incremental source emits.
|
|
94
|
-
*
|
|
95
|
-
* Both consume the SAME page, so a single endpoint feeds either ecosystem.
|
|
96
|
-
*/
|
|
97
79
|
/**
|
|
98
80
|
* One change record in a {@link ConnectorSyncPage}. Mirrors a row of the CDC log
|
|
99
81
|
* the shard / D1 change feed produces: an `op` (insert / update / delete), the
|
|
@@ -1436,6 +1418,11 @@ interface RunExportTapOptions {
|
|
|
1436
1418
|
* Project a raw op-log CDC record (`{ id, op, seq, table, ts, doc? }`) into a
|
|
1437
1419
|
* clean {@link ExportChange}. Mirrors `./connector-cdc`'s `flattenCdcChange` but
|
|
1438
1420
|
* PRESERVES `seq` / `id` / `ts` so a downstream warehouse can order and dedupe.
|
|
1421
|
+
*
|
|
1422
|
+
* The raw record arrives in wire form (the shard admin RPC encodes its result),
|
|
1423
|
+
* so `doc` is mapped through {@link toPortableDocument} — every sink NDJSON-encodes
|
|
1424
|
+
* it straight to a third party, where a `["$lunora.wire$","bigint",…]` tag would
|
|
1425
|
+
* land as an array instead of a value.
|
|
1439
1426
|
*/
|
|
1440
1427
|
declare const sanitizeChange: (raw: Record<string, unknown>) => ExportChange;
|
|
1441
1428
|
/**
|
|
@@ -2500,6 +2487,14 @@ type RestRateLimit = (request: Request, functionPath: string) => Promise<Respons
|
|
|
2500
2487
|
*/
|
|
2501
2488
|
type RestRoute = (request: Request, env: unknown, url?: URL, context?: ExecutionContextLike) => Promise<Response>;
|
|
2502
2489
|
interface RestRouteDeps {
|
|
2490
|
+
/**
|
|
2491
|
+
* The shared HTTP cache a declared `cache` policy is stored in. Defaults to
|
|
2492
|
+
* the host's own (`caches.default` on Cloudflare); pass a double in tests, or
|
|
2493
|
+
* `null` to keep the surface headers-only on a host whose cache should not be
|
|
2494
|
+
* used. A host with no cache at all needs no opt-out — `undefined` is what
|
|
2495
|
+
* `rest-edge-cache` already finds there.
|
|
2496
|
+
*/
|
|
2497
|
+
edgeCache?: HttpCacheLike | null;
|
|
2503
2498
|
/** The generated function registry — the source of which procedures are exposed. */
|
|
2504
2499
|
functions: RestRegistryLike;
|
|
2505
2500
|
/** The shared RPC dispatch (bound in `create-worker`). */
|
|
@@ -2521,7 +2516,8 @@ declare const readShardKey: (url: URL, request: Request) => string | undefined;
|
|
|
2521
2516
|
/**
|
|
2522
2517
|
* Decode GET args from the query string. Each value is parsed as JSON when it
|
|
2523
2518
|
* looks like a JSON scalar/array/object (so `?limit=10` → number, `?ids=[1,2]` →
|
|
2524
|
-
* array), else kept as a string. `shardKey`
|
|
2519
|
+
* array), else kept as a string. `shardKey` (routing) and `__lunora_vary` (the
|
|
2520
|
+
* edge cache key) are reserved and excluded.
|
|
2525
2521
|
*/
|
|
2526
2522
|
declare const argsFromQuery: (url: URL) => Record<string, unknown>;
|
|
2527
2523
|
/**
|
|
@@ -3877,6 +3873,16 @@ interface WorkerOptions {
|
|
|
3877
3873
|
* bucket rows; when omitted, every row routes to the default shard.
|
|
3878
3874
|
*/
|
|
3879
3875
|
resolveTableSharding?: AdminTableResolver;
|
|
3876
|
+
/**
|
|
3877
|
+
* The shared HTTP cache a REST `cache` policy is stored in and served from.
|
|
3878
|
+
*
|
|
3879
|
+
* Defaults to the host's own (`caches.default` on Cloudflare), which is what
|
|
3880
|
+
* makes `.expose({ rest: true, cache })` store anything at all. Pass `null` to
|
|
3881
|
+
* keep the surface headers-only — the declared `Cache-Control` still goes out,
|
|
3882
|
+
* but nothing is written to the colo. A host with no cache needs no opt-out:
|
|
3883
|
+
* `rest-edge-cache` finds none and degrades to the same behaviour.
|
|
3884
|
+
*/
|
|
3885
|
+
restEdgeCache?: HttpCacheLike | null;
|
|
3880
3886
|
/**
|
|
3881
3887
|
* Optional per-request rate-limit gate for the opt-in public REST surface
|
|
3882
3888
|
* (plan 167). Invoked with the inbound request + the target `functionPath`
|
|
@@ -4886,7 +4892,7 @@ declare const requestCarriesCredentials: (request: Request, policy: RestCachePol
|
|
|
4886
4892
|
* isn't cacheable at all (non-`GET`, or a non-2xx result — an error body must
|
|
4887
4893
|
* never be stored as if it were the resource).
|
|
4888
4894
|
*
|
|
4889
|
-
* The effective scope is `policy.scope` narrowed by {@link
|
|
4895
|
+
* The effective scope is `policy.scope` narrowed by {@link effectiveRestScope};
|
|
4890
4896
|
* `"public"` survives only for a genuinely anonymous request.
|
|
4891
4897
|
*/
|
|
4892
4898
|
declare const restCacheHeaders: (policy: RestCachePolicy, request: Request, status: number, context?: ExecutionContextLike) => Record<string, string> | undefined;
|
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
+
import { ShardDirectory, HttpCacheLike } from '@lunora/platform';
|
|
1
2
|
import { RankDirection, RankPageRow, DatabaseWriterLike, CrossShardReadArgs, QueryPage } from '@lunora/shard-engine';
|
|
2
3
|
export type { RankDirection as RankPageDirection, RankPageRowKey as RankPageKey, RankPageRow, ShardRankPageResult } from '@lunora/shard-engine';
|
|
3
|
-
import { ShardDirectory } from '@lunora/platform';
|
|
4
4
|
import { R2SqlClient } from '@lunora/bindings/r2sql';
|
|
5
5
|
import { WorkflowsRestClient } from '@lunora/workflow';
|
|
6
6
|
import { LunoraError as LunoraError$1, ErrorBody } from '@lunora/errors';
|
|
@@ -76,24 +76,6 @@ interface BackupManifestEntry {
|
|
|
76
76
|
* without a guard.
|
|
77
77
|
*/
|
|
78
78
|
declare const isBackupManifestEntry: (value: unknown) => value is BackupManifestEntry;
|
|
79
|
-
/**
|
|
80
|
-
* Turn-key incremental-sync source helpers for warehouse connectors
|
|
81
|
-
* (Fivetran custom functions, Airbyte incremental sources).
|
|
82
|
-
*
|
|
83
|
-
* The runtime's admin `/_lunora/admin/connector/sync` endpoint returns a
|
|
84
|
-
* {@link ConnectorSyncPage}: a flat list of change records since an opaque
|
|
85
|
-
* cursor, a `nextCursor` to resume from, and a `hasMore` flag. These helpers
|
|
86
|
-
* reshape that page into the response envelopes the two ecosystems expect, so a
|
|
87
|
-
* connector wrapper stays a few lines.
|
|
88
|
-
*
|
|
89
|
-
* {@link toFivetranResponse} produces the `{ state, insert, update, delete,
|
|
90
|
-
* hasMore, schema }` object a Fivetran connector function returns from its
|
|
91
|
-
* handler. {@link toAirbyteMessages} produces an ordered array of Airbyte
|
|
92
|
-
* protocol messages (a `RECORD` per row, a trailing `STATE` carrying the cursor),
|
|
93
|
-
* the line-delimited stream an Airbyte incremental source emits.
|
|
94
|
-
*
|
|
95
|
-
* Both consume the SAME page, so a single endpoint feeds either ecosystem.
|
|
96
|
-
*/
|
|
97
79
|
/**
|
|
98
80
|
* One change record in a {@link ConnectorSyncPage}. Mirrors a row of the CDC log
|
|
99
81
|
* the shard / D1 change feed produces: an `op` (insert / update / delete), the
|
|
@@ -1436,6 +1418,11 @@ interface RunExportTapOptions {
|
|
|
1436
1418
|
* Project a raw op-log CDC record (`{ id, op, seq, table, ts, doc? }`) into a
|
|
1437
1419
|
* clean {@link ExportChange}. Mirrors `./connector-cdc`'s `flattenCdcChange` but
|
|
1438
1420
|
* PRESERVES `seq` / `id` / `ts` so a downstream warehouse can order and dedupe.
|
|
1421
|
+
*
|
|
1422
|
+
* The raw record arrives in wire form (the shard admin RPC encodes its result),
|
|
1423
|
+
* so `doc` is mapped through {@link toPortableDocument} — every sink NDJSON-encodes
|
|
1424
|
+
* it straight to a third party, where a `["$lunora.wire$","bigint",…]` tag would
|
|
1425
|
+
* land as an array instead of a value.
|
|
1439
1426
|
*/
|
|
1440
1427
|
declare const sanitizeChange: (raw: Record<string, unknown>) => ExportChange;
|
|
1441
1428
|
/**
|
|
@@ -2500,6 +2487,14 @@ type RestRateLimit = (request: Request, functionPath: string) => Promise<Respons
|
|
|
2500
2487
|
*/
|
|
2501
2488
|
type RestRoute = (request: Request, env: unknown, url?: URL, context?: ExecutionContextLike) => Promise<Response>;
|
|
2502
2489
|
interface RestRouteDeps {
|
|
2490
|
+
/**
|
|
2491
|
+
* The shared HTTP cache a declared `cache` policy is stored in. Defaults to
|
|
2492
|
+
* the host's own (`caches.default` on Cloudflare); pass a double in tests, or
|
|
2493
|
+
* `null` to keep the surface headers-only on a host whose cache should not be
|
|
2494
|
+
* used. A host with no cache at all needs no opt-out — `undefined` is what
|
|
2495
|
+
* `rest-edge-cache` already finds there.
|
|
2496
|
+
*/
|
|
2497
|
+
edgeCache?: HttpCacheLike | null;
|
|
2503
2498
|
/** The generated function registry — the source of which procedures are exposed. */
|
|
2504
2499
|
functions: RestRegistryLike;
|
|
2505
2500
|
/** The shared RPC dispatch (bound in `create-worker`). */
|
|
@@ -2521,7 +2516,8 @@ declare const readShardKey: (url: URL, request: Request) => string | undefined;
|
|
|
2521
2516
|
/**
|
|
2522
2517
|
* Decode GET args from the query string. Each value is parsed as JSON when it
|
|
2523
2518
|
* looks like a JSON scalar/array/object (so `?limit=10` → number, `?ids=[1,2]` →
|
|
2524
|
-
* array), else kept as a string. `shardKey`
|
|
2519
|
+
* array), else kept as a string. `shardKey` (routing) and `__lunora_vary` (the
|
|
2520
|
+
* edge cache key) are reserved and excluded.
|
|
2525
2521
|
*/
|
|
2526
2522
|
declare const argsFromQuery: (url: URL) => Record<string, unknown>;
|
|
2527
2523
|
/**
|
|
@@ -3877,6 +3873,16 @@ interface WorkerOptions {
|
|
|
3877
3873
|
* bucket rows; when omitted, every row routes to the default shard.
|
|
3878
3874
|
*/
|
|
3879
3875
|
resolveTableSharding?: AdminTableResolver;
|
|
3876
|
+
/**
|
|
3877
|
+
* The shared HTTP cache a REST `cache` policy is stored in and served from.
|
|
3878
|
+
*
|
|
3879
|
+
* Defaults to the host's own (`caches.default` on Cloudflare), which is what
|
|
3880
|
+
* makes `.expose({ rest: true, cache })` store anything at all. Pass `null` to
|
|
3881
|
+
* keep the surface headers-only — the declared `Cache-Control` still goes out,
|
|
3882
|
+
* but nothing is written to the colo. A host with no cache needs no opt-out:
|
|
3883
|
+
* `rest-edge-cache` finds none and degrades to the same behaviour.
|
|
3884
|
+
*/
|
|
3885
|
+
restEdgeCache?: HttpCacheLike | null;
|
|
3880
3886
|
/**
|
|
3881
3887
|
* Optional per-request rate-limit gate for the opt-in public REST surface
|
|
3882
3888
|
* (plan 167). Invoked with the inbound request + the target `functionPath`
|
|
@@ -4886,7 +4892,7 @@ declare const requestCarriesCredentials: (request: Request, policy: RestCachePol
|
|
|
4886
4892
|
* isn't cacheable at all (non-`GET`, or a non-2xx result — an error body must
|
|
4887
4893
|
* never be stored as if it were the resource).
|
|
4888
4894
|
*
|
|
4889
|
-
* The effective scope is `policy.scope` narrowed by {@link
|
|
4895
|
+
* The effective scope is `policy.scope` narrowed by {@link effectiveRestScope};
|
|
4890
4896
|
* `"public"` survives only for a genuinely anonymous request.
|
|
4891
4897
|
*/
|
|
4892
4898
|
declare const restCacheHeaders: (policy: RestCachePolicy, request: Request, status: number, context?: ExecutionContextLike) => Record<string, string> | undefined;
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{BACKUP_KEY_PREFIX as t,backupManifestKey as a,backupObjectKey as s,backupObjectKeyOfManifest as i,isBackupManifestEntry as n,isBackupManifestKey as p,normalizeBackupPrefix as c}from"./packem_shared/BACKUP_KEY_PREFIX-BOtSu-_3.mjs";import{toAirbyteMessages as f,toFivetranResponse as E}from"./packem_shared/toAirbyteMessages-
|
|
1
|
+
import{BACKUP_KEY_PREFIX as t,backupManifestKey as a,backupObjectKey as s,backupObjectKeyOfManifest as i,isBackupManifestEntry as n,isBackupManifestKey as p,normalizeBackupPrefix as c}from"./packem_shared/BACKUP_KEY_PREFIX-BOtSu-_3.mjs";import{toAirbyteMessages as f,toFivetranResponse as E}from"./packem_shared/toAirbyteMessages-CZimuevO.mjs";import{composeWorker as S,createLunoraHandler as x,createWorker as _,defineRpcEnvelope as d,resolveLunoraOptions as l,withFrameworkWorker as u}from"./packem_shared/composeWorker-D41ytQme.mjs";import{createCrossShardRelationCapabilities as k}from"./packem_shared/createCrossShardRelationCapabilities-DgQYQzd1.mjs";import{DEFAULT_REGISTRY_CACHE_TTL_MS as A,SHARD_REGISTRY_DO_NAME as C,createDynamicShardRegistry as L}from"./packem_shared/DEFAULT_REGISTRY_CACHE_TTL_MS-D5O7elXI.mjs";import{LunoraError as b,toErrorResponse as g}from"./packem_shared/LunoraError-DksAgIpa.mjs";import{createKvCursorStore as H,createMemoryCursorStore as I,defineExportSink as P,r2Sink as v,runExportTap as D,sanitizeChange as F,webhookExportSink as M}from"./packem_shared/createKvCursorStore-kQ8HNv0l.mjs";import{HEALTH_PATH as K,HEALTH_READY_PATH as N,buildHealthRoutes as U,d1Probe as B,durableObjectProbe as Y,presenceProbe as w}from"./packem_shared/HEALTH_PATH-jZsuCmSs.mjs";import{LOG_ARCHIVE_PATH as X,resolveLogArchiveFromEnv as j}from"./packem_shared/LOG_ARCHIVE_PATH-jgHjdsz2.mjs";import{memoizeIdentity as W,memoizeIdentityPerRequest as q}from"./packem_shared/memoizeIdentity-DnOj3QRi.mjs";import{e as J,a as Z}from"./packem_shared/observability-vDK-rMbs.mjs";import{analyticsEngineSink as ee,combineSinks as re,consoleSink as oe,otlpSink as te,pipelineLogSink as ae,sentrySink as se,webhookSink as ie}from"./packem_shared/analyticsEngineSink-BgmqAmTM.mjs";import{D as pe,a as ce,c as me}from"./packem_shared/pipeline-log-reader-BGrl66P5.mjs";import{createQueryCoordinator as Ee,createStaticShardRegistry as Re,mergeStrategyForAggregate as Se}from"./packem_shared/createQueryCoordinator-CnNyazLX.mjs";import{applyJurisdiction as _e,resolveShard as de}from"./packem_shared/applyJurisdiction-C0ddU7Tg.mjs";import{a as ue,r as ye,b as ke}from"./packem_shared/rest-cache-CPSyD1RD.mjs";import{a as Ae,b as Ce,c as Le,r as Te,d as be}from"./packem_shared/rest-routes-Dq17Zntv.mjs";import{decorateResponse as he,enforceOrigin as He,handleCorsPreflight as Ie,resolveSecurity as Pe}from"./packem_shared/decorateResponse-BuqVnrmc.mjs";import{createShardClient as De}from"./packem_shared/createShardClient-CCncsgTs.mjs";import{STORAGE_UPLOAD_MAX_BODY_BYTES as Me}from"./packem_shared/STORAGE_UPLOAD_MAX_BODY_BYTES-BqyO-1l6.mjs";import{LOG_ARCHIVE_NOT_CONFIGURED as Ke}from"./packem_shared/LOG_ARCHIVE_NOT_CONFIGURED-CDpi4yFD.mjs";import{NOOP_EXECUTION_CONTEXT as Ue}from"./packem_shared/NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{composeIdentityResolvers as Ye,routeIdentityResolvers as we}from"./packem_shared/composeIdentityResolvers-BHZ4jH8o.mjs";const e="0.0.0";export{t as BACKUP_KEY_PREFIX,pe as DEFAULT_LOG_COLUMNS,ce as DEFAULT_LOG_LIMIT,A as DEFAULT_REGISTRY_CACHE_TTL_MS,K as HEALTH_PATH,N as HEALTH_READY_PATH,Ke as LOG_ARCHIVE_NOT_CONFIGURED,X as LOG_ARCHIVE_PATH,b as LunoraError,Ue as NOOP_EXECUTION_CONTEXT,C as SHARD_REGISTRY_DO_NAME,Me as STORAGE_UPLOAD_MAX_BODY_BYTES,e as VERSION,ee as analyticsEngineSink,_e as applyJurisdiction,ue as applyRestCache,Ae as argsFromQuery,a as backupManifestKey,s as backupObjectKey,i as backupObjectKeyOfManifest,U as buildHealthRoutes,Ce as buildRestRoutes,re as combineSinks,Ye as composeIdentityResolvers,S as composeWorker,oe as consoleSink,k as createCrossShardRelationCapabilities,L as createDynamicShardRegistry,H as createKvCursorStore,x as createLunoraHandler,I as createMemoryCursorStore,me as createPipelineLogReader,Ee as createQueryCoordinator,Le as createRestRateLimit,De as createShardClient,Re as createStaticShardRegistry,_ as createWorker,B as d1Probe,he as decorateResponse,P as defineExportSink,d as defineRpcEnvelope,Y as durableObjectProbe,J as emitLogEvent,Z as emitRpcEvent,He as enforceOrigin,Ie as handleCorsPreflight,n as isBackupManifestEntry,p as isBackupManifestKey,W as memoizeIdentity,q as memoizeIdentityPerRequest,Se as mergeStrategyForAggregate,c as normalizeBackupPrefix,te as otlpSink,ae as pipelineLogSink,w as presenceProbe,v as r2Sink,Te as readShardKey,ye as requestCarriesCredentials,j as resolveLogArchiveFromEnv,l as resolveLunoraOptions,Pe as resolveSecurity,de as resolveShard,ke as restCacheHeaders,be as restSurfaceFromRegistry,we as routeIdentityResolvers,D as runExportTap,F as sanitizeChange,se as sentrySink,f as toAirbyteMessages,g as toErrorResponse,E as toFivetranResponse,M as webhookExportSink,ie as webhookSink,u as withFrameworkWorker};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as s,e as r,r as t,b as c}from"./rest-cache-CPSyD1RD.mjs";export{s as applyRestCache,r as effectiveRestScope,t as requestCarriesCredentials,c as restCacheHeaders};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import"./rest-cache-
|
|
1
|
+
import"./rest-cache-CPSyD1RD.mjs";import{a as t,b as o,c as i,r as m,d as R}from"./rest-routes-Dq17Zntv.mjs";import"./method-guard-BG_vJNTl.mjs";export{t as argsFromQuery,o as buildRestRoutes,i as createRestRateLimit,m as readShardKey,R as restSurfaceFromRegistry};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{isLunoraError as Nn,toErrorBody as Un}from"@lunora/errors";import{e as Nt}from"./evict-oldest-BNXsKx4s.mjs";import{NOOP_EXECUTION_CONTEXT as Cn}from"./NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{e as Bn,a as xn}from"./identity-header-JF5q3H5w.mjs";import{o as Se,b as Hn,p as Ln,m as Mn,d as jn,a as $n,r as Kn}from"./otlp-resource-B4Yylr0V.mjs";import{e as Fe}from"./wire-codec-0SQDg-5_.mjs";import{e as Z,f as be,M as Ut,b as Fn,g as Gn,h as Ct,i as Bt}from"./rest-routes-D2b3HXA9.mjs";import{LunoraError as d,toErrorResponse as nt}from"./LunoraError-DksAgIpa.mjs";import{a as j,m as me}from"./method-guard-BG_vJNTl.mjs";import{normalizeBackupPrefix as Qe,BACKUP_KEY_PREFIX as ze,isBackupManifestKey as Qn,backupObjectKeyOfManifest as xt,backupObjectKey as zn,backupManifestKey as Wn}from"./BACKUP_KEY_PREFIX-BOtSu-_3.mjs";import{toHex as Vn,buildStorageAdminRoutes as Jn,STORAGE_UPLOAD_MAX_BODY_BYTES as qn,STORAGE_PATH as Yn}from"./STORAGE_UPLOAD_MAX_BODY_BYTES-BqyO-1l6.mjs";import{runExportTap as Xn}from"./createKvCursorStore-VOd1DFsf.mjs";import{buildHealthRoutes as Zn,durableObjectProbe as er,d1Probe as tr,presenceProbe as Ce}from"./HEALTH_PATH-jZsuCmSs.mjs";import{wrapResolverWithContract as nr}from"./composeIdentityResolvers-BHZ4jH8o.mjs";import{composeIdentityResolvers as Es,routeIdentityResolvers as As}from"./composeIdentityResolvers-BHZ4jH8o.mjs";import{buildLogArchiveAdminRoutes as rr}from"./LOG_ARCHIVE_PATH-jgHjdsz2.mjs";import{r as or,f as rt,a as ce}from"./observability-vDK-rMbs.mjs";import{resolveShard as we,applyJurisdiction as ot}from"./applyJurisdiction-C0ddU7Tg.mjs";import{resolveSecurity as at,handleCorsPreflight as ar,enforceOrigin as sr,decorateResponse as Be,enforceWebSocketOrigin as st}from"./decorateResponse-D3NzOIvB.mjs";const ir=e=>{const n=e??{};if(typeof n.bucket=="function")return n;const t={...n,bucketName:"default"};return t.bucket=()=>t,t},Ht="__lunoraBranch",cr=e=>typeof e=="object"&&e!==null&&Object.hasOwn(e,Ht),dr=`may not contain the reserved workflow branch-marker key ("${Ht}")`,We=(e,n)=>{const t=Math.max(e.length,n.length);let r=e.length^n.length;for(let a=0;a<t;a+=1){const s=a<e.length?e.charCodeAt(a):0,l=a<n.length?n.charCodeAt(a):0;r|=s^l}return r===0},Ve=new TextEncoder,ur=Array.from({length:32},(e,n)=>n);new RegExp(`[${ur.map(e=>String.fromCodePoint(e)).join("")}]`,"u");const lr=e=>{const n=String.fromCodePoint(...e);return btoa(n).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")},hr=e=>{const n=e.replaceAll("-","+").replaceAll("_","/")+"===".slice((e.length+3)%4),t=atob(n),r=new Uint8Array(t.length);for(let a=0;a<t.length;a+=1)r[a]=t.codePointAt(a)??0;return r},fr=64,xe=new Map,Lt=async e=>{const n=xe.get(e);if(n)return n;Nt(xe,fr);const t=crypto.subtle.importKey("raw",Ve.encode(e),{hash:"SHA-256",name:"HMAC"},!1,["sign","verify"]);return xe.set(e,t),t},Mt=async(e,n)=>{const t=await Lt(e),r=await crypto.subtle.sign("HMAC",t,Ve.encode(n));return lr(new Uint8Array(r))},pr=async(e,n,t)=>{const r=await Lt(e);return crypto.subtle.verify("HMAC",r,t,Ve.encode(n))},mr=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"];new Set(mr);const wr=new Set(["AE","BH","IL","IQ","IR","JO","KW","LB","OM","PS","QA","SA","SY","TR","YE"]),gr=-100,yr=15,br=e=>{const n=Number(e.longitude??Number.NaN);switch(e.continent){case"AF":return"afr";case"AS":return e.country!==void 0&&wr.has(e.country)?"me":"apac";case"EU":return Number.isFinite(n)&&n>yr?"eeur":"weur";case"NA":return Number.isFinite(n)&&n<gr?"wnam":"enam";case"OC":return"oc";case"SA":return"sam";default:return}},it=e=>{const n=e.cf;return n===void 0?void 0:br(n)},jt="::relay::",_r=(e,n)=>`${e}${jt}${String(n)}`,$t="::replica::",Rr=(e,n)=>`${e}${$t}${n}`,Er=e=>{if(e==null||!/^\d+$/.test(e))return;const n=Number.parseInt(e,10);return Number.isSafeInteger(n)&&n>0?n:void 0},Ar=new Set(["1","enabled","on","true","yes"]),Sr=new Set(["0","disabled","false","no","off"]),Tr=(e,n)=>{const t=(e??"").trim().toLowerCase();return Ar.has(t)?!0:Sr.has(t)?!1:n},Kt="v1",Or=6e4,vr=async(e,n={})=>{const t=(n.now??Date.now())+(n.ttlMs??Or),r=`${Kt}.${String(t)}`,a=await Mt(e,r);return{expiresAtMs:t,token:`${r}.${a}`}},kr=async(e,n,t=Date.now())=>{if(e.length===0||n.length===0)return!1;const r=n.split(".");if(r.length!==3)return!1;const[a,s,l]=r;if(a!==Kt||l.length===0)return!1;const u=Number(s);if(!Number.isFinite(u)||u<=t)return!1;let f;try{f=hr(l)}catch{return!1}return pr(e,`${a}.${s}`,f)},P="/_lunora/admin/auth",Ir={INVITER_REQUIRED:400,ORG_SLUG_INVALID:400,ORG_SLUG_TAKEN:409,PASSWORD_TOO_LONG:400,PASSWORD_TOO_SHORT:400,USER_ALREADY_EXISTS:409,USER_NOT_FOUND:404},N=(e,n)=>{const t=e[n];if(typeof t!="string"||t==="")throw new d(`\`${n}\` is required`,{code:"BAD_REQUEST",status:400});return t},le=(e,n)=>{const t=e(n);if(t===void 0)throw new d(`\`${n}\` query parameter is required`,{code:"BAD_REQUEST",status:400});return t},Ft=e=>{if(typeof e=="string"||Array.isArray(e)&&e.every(n=>typeof n=="string"))return e},re=(e,n)=>typeof e[n]=="string"?e[n]:void 0,He=(e,n)=>{const t=e[n];return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:void 0},ct=e=>{const n=Ft(e.role);if(n===void 0||typeof n=="string"&&n.trim()==="")throw new d("`role` is required",{code:"BAD_REQUEST",status:400});return n},dt=e=>{const n=e.permission;if(typeof n!="object"||n===null||Array.isArray(n))throw new d("`permission` object is required",{code:"BAD_REQUEST",status:400});const t={};for(const[r,a]of Object.entries(n))Array.isArray(a)&&a.every(s=>typeof s=="string")&&(t[r]=a);return t},Pr={[`${P}/capabilities`]:{build:()=>({}),http:"GET",method:"capabilities"},[`${P}/users`]:{build:({paging:e,query:n})=>{const t=n("sortDirection");return{...e,filterField:n("filterField"),filterValue:n("filterValue"),search:n("search"),searchField:n("searchField"),sortBy:n("sortBy"),sortDirection:t==="asc"||t==="desc"?t:void 0}},http:"GET",method:"listUsers"},[`${P}/sessions`]:{build:({paging:e,query:n})=>({...e,userId:n("userId")}),http:"GET",method:"listSessions"},[`${P}/accounts`]:{build:({query:e})=>({userId:le(e,"userId")}),http:"GET",method:"listAccounts"},[`${P}/passkeys`]:{build:({query:e})=>({userId:le(e,"userId")}),http:"GET",method:"listPasskeys"},[`${P}/organizations`]:{build:({paging:e})=>({...e}),http:"GET",method:"listOrganizations"},[`${P}/organizations/members`]:{build:({paging:e,query:n})=>({...e,organizationId:le(n,"organizationId")}),http:"GET",method:"listMembers"},[`${P}/organizations/invitations`]:{build:({paging:e,query:n})=>({...e,organizationId:le(n,"organizationId")}),http:"GET",method:"listInvitations"},[`${P}/config`]:{build:()=>({}),http:"GET",method:"config"},[`${P}/organizations/teams`]:{build:({paging:e,query:n})=>({...e,organizationId:le(n,"organizationId")}),http:"GET",method:"listTeams"},[`${P}/organizations/teams/members`]:{build:({paging:e,query:n})=>({...e,teamId:le(n,"teamId")}),http:"GET",method:"listTeamMembers"},[`${P}/organizations/roles`]:{build:({paging:e,query:n})=>({...e,organizationId:le(n,"organizationId")}),http:"GET",method:"listOrgRoles"},[`${P}/users/create`]:{build:({body:e})=>({data:He(e,"data"),email:N(e,"email"),name:N(e,"name"),password:re(e,"password"),role:Ft(e.role)}),http:"POST",method:"createUser"},[`${P}/users/update`]:{build:({body:e})=>{const{data:n}=e;if(typeof n!="object"||n===null||Array.isArray(n))throw new d("`data` object is required",{code:"BAD_REQUEST",status:400});return{data:n,userId:N(e,"userId")}},http:"POST",method:"updateUser"},[`${P}/users/role`]:{build:({body:e})=>({role:ct(e),userId:N(e,"userId")}),http:"POST",method:"setRole"},[`${P}/users/ban`]:{build:({body:e})=>({expiresInSeconds:typeof e.expiresInSeconds=="number"?e.expiresInSeconds:void 0,reason:re(e,"reason"),userId:N(e,"userId")}),http:"POST",method:"banUser"},[`${P}/users/unban`]:{build:({body:e})=>({userId:N(e,"userId")}),http:"POST",method:"unbanUser"},[`${P}/users/password`]:{build:({body:e})=>({newPassword:N(e,"newPassword"),userId:N(e,"userId")}),http:"POST",method:"setUserPassword",returns:"void"},[`${P}/users/remove`]:{build:({body:e})=>({userId:N(e,"userId")}),http:"POST",method:"removeUser",returns:"void"},[`${P}/users/impersonate`]:{build:({body:e})=>({userId:N(e,"userId")}),http:"POST",method:"impersonateUser"},[`${P}/sessions/revoke`]:{build:({body:e})=>({sessionId:N(e,"sessionId")}),http:"POST",method:"revokeUserSession",returns:"void"},[`${P}/sessions/revoke-all`]:{build:({body:e})=>({userId:N(e,"userId")}),http:"POST",method:"revokeUserSessions",returns:"void"},[`${P}/accounts/unlink`]:{build:({body:e})=>({accountId:N(e,"accountId"),userId:N(e,"userId")}),http:"POST",method:"unlinkAccount",returns:"void"},[`${P}/two-factor/disable`]:{build:({body:e})=>({userId:N(e,"userId")}),http:"POST",method:"disableTwoFactor",returns:"void"},[`${P}/passkeys/delete`]:{build:({body:e})=>({passkeyId:N(e,"passkeyId")}),http:"POST",method:"deletePasskey",returns:"void"},[`${P}/organizations/members/remove`]:{build:({body:e})=>({memberId:N(e,"memberId")}),http:"POST",method:"removeMember",returns:"void"},[`${P}/organizations/invitations/cancel`]:{build:({body:e})=>({invitationId:N(e,"invitationId")}),http:"POST",method:"cancelInvitation",returns:"void"},[`${P}/organizations/create`]:{build:({body:e})=>({logo:re(e,"logo"),metadata:He(e,"metadata"),name:N(e,"name"),ownerId:re(e,"ownerId"),slug:re(e,"slug")}),http:"POST",method:"createOrganization"},[`${P}/organizations/update`]:{build:({body:e})=>({logo:re(e,"logo"),metadata:He(e,"metadata"),name:re(e,"name"),organizationId:N(e,"organizationId"),slug:re(e,"slug")}),http:"POST",method:"updateOrganization"},[`${P}/organizations/remove`]:{build:({body:e})=>({organizationId:N(e,"organizationId")}),http:"POST",method:"deleteOrganization",returns:"void"},[`${P}/organizations/members/add`]:{build:({body:e})=>({organizationId:N(e,"organizationId"),role:re(e,"role"),userId:N(e,"userId")}),http:"POST",method:"addMember"},[`${P}/organizations/members/invite`]:{build:({body:e})=>({email:N(e,"email"),inviterId:re(e,"inviterId"),organizationId:N(e,"organizationId"),role:re(e,"role")}),http:"POST",method:"inviteMember"},[`${P}/organizations/members/role`]:{build:({body:e})=>({memberId:N(e,"memberId"),role:ct(e)}),http:"POST",method:"updateMemberRole"},[`${P}/organizations/teams/create`]:{build:({body:e})=>({name:N(e,"name"),organizationId:N(e,"organizationId")}),http:"POST",method:"createTeam"},[`${P}/organizations/teams/update`]:{build:({body:e})=>({name:N(e,"name"),teamId:N(e,"teamId")}),http:"POST",method:"updateTeam"},[`${P}/organizations/teams/remove`]:{build:({body:e})=>({teamId:N(e,"teamId")}),http:"POST",method:"removeTeam",returns:"void"},[`${P}/organizations/teams/members/add`]:{build:({body:e})=>({teamId:N(e,"teamId"),userId:N(e,"userId")}),http:"POST",method:"addTeamMember"},[`${P}/organizations/teams/members/remove`]:{build:({body:e})=>({teamMemberId:N(e,"teamMemberId")}),http:"POST",method:"removeTeamMember",returns:"void"},[`${P}/organizations/roles/create`]:{build:({body:e})=>({organizationId:N(e,"organizationId"),permission:dt(e),role:N(e,"role")}),http:"POST",method:"createOrgRole"},[`${P}/organizations/roles/update`]:{build:({body:e})=>({permission:dt(e),roleId:N(e,"roleId")}),http:"POST",method:"updateOrgRole"},[`${P}/organizations/roles/remove`]:{build:({body:e})=>({roleId:N(e,"roleId")}),http:"POST",method:"deleteOrgRole",returns:"void"}},Dr=e=>{const n=async a=>{try{return await a()}catch(s){if(s instanceof d)throw s;const l=s,u=typeof l.code=="string"?l.code:"AUTH_ADMIN_ERROR";throw console.error("[lunora] auth admin operation failed:",s),new d("auth admin operation failed",{code:u,status:Ir[u]??500})}},t=async(a,s)=>{if(e.assertAdmin(a),a.method!==s.http)throw new d(`Auth admin endpoint requires ${s.http}`,{code:"METHOD_NOT_ALLOWED",status:405});const l=e.getAuthAdmin();if(l===void 0)throw new d("auth endpoints require an `authAdmin` on the worker",{code:"AUTH_NOT_CONFIGURED",status:400});const u=l[s.method];if(u===void 0)throw new d(`auth admin does not support \`${s.method}\``,{code:"AUTH_OP_NOT_SUPPORTED",status:400});const f=new URL(a.url),g={body:s.http==="POST"?await e.readJsonBody(a):{},paging:e.parsePaging(a),query:v=>e.queryParameter(f,v)},E=s.build(g),k=await n(()=>u(E));return Response.json(s.returns==="void"?{ok:!0}:k,{headers:{"content-type":"application/json"},status:200})},r={};for(const[a,s]of Object.entries(Pr))r[a]=l=>t(l,s);return r},Nr="__lunora_admin__:getAuthAuditLog",ut=e=>typeof e=="string"&&e!==""?e:void 0,lt=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0,Ur=e=>async(t,r)=>{e.assertAdmin(t);const a=e.getReader();if(a===void 0)throw new d("the auth/security audit endpoint requires an `authAuditReader` on the worker",{code:"AUTH_AUDIT_NOT_CONFIGURED",status:400});const s=ut(r.actorId),l=ut(r.event),u=lt(r.sinceSeq),f=lt(r.limit),g={...s===void 0?{}:{actorId:s},...l===void 0?{}:{event:l},...u===void 0?{}:{sinceSeq:u},...f===void 0?{}:{limit:f}};let E;try{E=await a.read(g)}catch(v){throw v instanceof d?v:(console.error("[lunora] auth audit read failed:",v),new d("auth audit read failed",{code:"AUTH_AUDIT_READ_FAILED",status:500}))}const k={entries:E};return Response.json({result:Fe(k)},{headers:{"content-type":"application/json"},status:200})},Cr=(e,n)=>{const t=[],r=[];if(n&&n.length>0)for(const a of n)e.resolveTableSharding?.(a)?.mode.kind==="global"?r.push(a):t.push(a);return{globalTables:r,shardLocalTables:t}},Br=async(e,n,t,r,a,s)=>{if(t!==void 0&&r.length===0)return;const l=await e.orchestrateExport(s,{args:{tables:r},headers:n,tables:r});for(const u of l.shards)if(!u.error)for(const f of u.rows??[])a(f)},Gt=async(e,n,t,r,a,s)=>{const{globalTables:l,shardLocalTables:u}=Cr(e,r);await Br(n,t,r,u,a,s);const f=e.exportGlobals;if((r===void 0||l.length>0)&&f)for await(const E of f({tables:l}))a(E)},xr=new TextEncoder,Hr=1e3,Qt=10,Lr=200,ht=8,zt="lunoraBackupCron",ft=24*1048576,pt=e=>{const n=e.slice(0,Qt).map(r=>xt(r)),t=e.length-n.length;return`${n.join(", ")}${t>0?` (+${String(t)} more)`:""}`},Mr=(e,n)=>{const t=new Uint8Array(new ArrayBuffer(n));let r=0;for(const a of e)t.set(a,r),r+=a.byteLength;return t},Je=async(e,n,t,r)=>{if(t===void 0||!Number.isInteger(t)||t<=0)return{eligible:0,stale:[]};const a=[];let s;for(let l=0;l<Hr;l+=1){const u=await e.list({cursor:s,include:["customMetadata"],prefix:n});for(const f of u.objects)Qn(f.key)&&f.customMetadata?.[zt]===r&&a.push(f.key);if(!u.truncated||u.cursor===void 0)break;s=u.cursor}return{eligible:a.length,stale:a.toSorted((l,u)=>u.localeCompare(l)).slice(t)}},jr=async(e,n,t,r,a)=>{const{stale:s}=await Je(e,n,t,r),l=new Set(a),u=s.filter(w=>l.has(w)),f=u.slice(0,Lr),g=s.length-f.length,E=a.length-u.length;if(f.length===0)return{deleted:[],failed:[],ignored:E,remaining:g};const k=[],v=[];for(let w=0;w<f.length;w+=ht){const b=await Promise.allSettled(f.slice(w,w+ht).map(async _=>(await e.delete(xt(_)),await e.delete(_),_)));for(const[_,p]of b.entries())p.status==="fulfilled"?k.push(p.value):v.push(f[w+_])}return k.length>0&&console.info(`[lunora] backup prune kept the newest ${String(t)} and deleted ${String(k.length)}: ${pt(k)}`),v.length>0&&console.warn(`[lunora] backup prune failed to remove ${String(v.length)}: ${pt(v)}`),{deleted:k,failed:v,ignored:E,remaining:g}},$r=async e=>{const n=e.backupStore;if(!n)throw new d("backup retention preview requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});const t=Qe(e.backupPrefix??ze),r=e.backupCron,{eligible:a,stale:s}=r===void 0?{eligible:0,stale:[]}:await Je(n,t,e.backupRetain,r);return{cron:r,eligible:a,keep:e.backupRetain??0,prefix:t,wouldDelete:s}},Kr=async(e,n,t,r)=>{const a=e.backupStore,s=e.queryCoordinator;if(!a)throw new d("scheduled backup requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});if(!s)throw new d("scheduled backup requires a `queryCoordinator` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});if(!t||t.length===0)throw new d("scheduled backup requires an `adminToken` (or `env.LUNORA_ADMIN_TOKEN`) to authenticate the per-shard export gate",{code:"BACKUP_NOT_CONFIGURED",status:500});const l={authorization:`Bearer ${t}`,"content-type":"application/json"},u=e.backupTables;let f=0,g=0,E=[];await Gt(e,s,l,u,D=>{const T=xr.encode(`${JSON.stringify(D)}
|
|
2
|
-
`);if(f+=1,g+=T.byteLength,g>
|
|
3
|
-
`,{customMetadata:{[
|
|
4
|
-
`))};try{await E($,W,U.tables,X),V.close()}catch(J){V.error(J)}}});return new Response(K,{headers:{"content-type":"application/x-ndjson"},status:200})},b=async(T,x)=>{const H=me(T,["POST"]);if(H)return H;const $=u(T,s,{code:"BAD_REQUEST",message:"Sync endpoint requires a `queryCoordinator` on the worker"}),U=await Z(T),W=typeof U.cursors=="object"&&U.cursors!==null?U.cursors:{},K=typeof U.limit=="number"?U.limit:void 0,V=typeof U.globalCursor=="number"?U.globalCursor:0,X=
|
|
1
|
+
import{isLunoraError as Dn,toErrorBody as Nn}from"@lunora/errors";import{e as Dt}from"./evict-oldest-BNXsKx4s.mjs";import{NOOP_EXECUTION_CONTEXT as Un}from"./NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{e as Cn,a as Bn}from"./identity-header-JF5q3H5w.mjs";import{o as Se,b as xn,p as Hn,m as Ln,d as Mn,a as jn,r as $n}from"./otlp-resource-B4Yylr0V.mjs";import{e as Ke}from"./wire-codec-D_qTfaaH.mjs";import{e as Z,f as be,M as Nt,b as Kn,g as Fn,h as Ut,i as Ct}from"./rest-routes-Dq17Zntv.mjs";import{LunoraError as d,toErrorResponse as tt}from"./LunoraError-DksAgIpa.mjs";import{a as j,m as me}from"./method-guard-BG_vJNTl.mjs";import{normalizeBackupPrefix as Ge,BACKUP_KEY_PREFIX as Qe,isBackupManifestKey as Gn,backupObjectKeyOfManifest as Bt,backupObjectKey as Qn,backupManifestKey as zn}from"./BACKUP_KEY_PREFIX-BOtSu-_3.mjs";import{toHex as Wn,buildStorageAdminRoutes as Vn,STORAGE_UPLOAD_MAX_BODY_BYTES as Jn,STORAGE_PATH as qn}from"./STORAGE_UPLOAD_MAX_BODY_BYTES-BqyO-1l6.mjs";import{runExportTap as Yn}from"./createKvCursorStore-kQ8HNv0l.mjs";import{buildHealthRoutes as Xn,durableObjectProbe as Zn,d1Probe as er,presenceProbe as Ce}from"./HEALTH_PATH-jZsuCmSs.mjs";import{wrapResolverWithContract as tr}from"./composeIdentityResolvers-BHZ4jH8o.mjs";import{composeIdentityResolvers as As,routeIdentityResolvers as Ss}from"./composeIdentityResolvers-BHZ4jH8o.mjs";import{buildLogArchiveAdminRoutes as nr}from"./LOG_ARCHIVE_PATH-jgHjdsz2.mjs";import{r as rr,f as nt,a as ce}from"./observability-vDK-rMbs.mjs";import{resolveShard as we,applyJurisdiction as rt}from"./applyJurisdiction-C0ddU7Tg.mjs";import{resolveSecurity as ot,handleCorsPreflight as or,enforceOrigin as ar,decorateResponse as Be,enforceWebSocketOrigin as at}from"./decorateResponse-BuqVnrmc.mjs";const sr=e=>{const n=e??{};if(typeof n.bucket=="function")return n;const t={...n,bucketName:"default"};return t.bucket=()=>t,t},xt="__lunoraBranch",ir=e=>typeof e=="object"&&e!==null&&Object.hasOwn(e,xt),cr=`may not contain the reserved workflow branch-marker key ("${xt}")`,ze=(e,n)=>{const t=Math.max(e.length,n.length);let r=e.length^n.length;for(let a=0;a<t;a+=1){const s=a<e.length?e.charCodeAt(a):0,l=a<n.length?n.charCodeAt(a):0;r|=s^l}return r===0},dr=(e,n,t,r)=>{const a=e.get(n);if(a!==void 0)return a;Dt(e,r);const s=t().catch(l=>{throw e.get(n)===s&&e.delete(n),l});return e.set(n,s),s},We=new TextEncoder,ur=Array.from({length:32},(e,n)=>n);new RegExp(`[${ur.map(e=>String.fromCodePoint(e)).join("")}]`,"u");const lr=e=>{const n=String.fromCodePoint(...e);return btoa(n).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")},hr=e=>{const n=e.replaceAll("-","+").replaceAll("_","/")+"===".slice((e.length+3)%4),t=atob(n),r=new Uint8Array(t.length);for(let a=0;a<t.length;a+=1)r[a]=t.codePointAt(a)??0;return r},fr=64,pr=new Map,Ht=async e=>dr(pr,e,async()=>crypto.subtle.importKey("raw",We.encode(e),{hash:"SHA-256",name:"HMAC"},!1,["sign","verify"]),fr),Lt=async(e,n)=>{const t=await Ht(e),r=await crypto.subtle.sign("HMAC",t,We.encode(n));return lr(new Uint8Array(r))},mr=async(e,n,t)=>{const r=await Ht(e);return crypto.subtle.verify("HMAC",r,t,We.encode(n))},wr=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"];new Set(wr);const gr=new Set(["AE","BH","IL","IQ","IR","JO","KW","LB","OM","PS","QA","SA","SY","TR","YE"]),yr=-100,br=15,_r=e=>{const n=Number(e.longitude??Number.NaN);switch(e.continent){case"AF":return"afr";case"AS":return e.country!==void 0&&gr.has(e.country)?"me":"apac";case"EU":return Number.isFinite(n)&&n>br?"eeur":"weur";case"NA":return Number.isFinite(n)&&n<yr?"wnam":"enam";case"OC":return"oc";case"SA":return"sam";default:return}},st=e=>{const n=e.cf;return n===void 0?void 0:_r(n)},Mt="::relay::",Rr=(e,n)=>`${e}${Mt}${String(n)}`,jt="::replica::",Er=(e,n)=>`${e}${jt}${n}`,Ar=e=>{if(e==null||!/^\d+$/.test(e))return;const n=Number.parseInt(e,10);return Number.isSafeInteger(n)&&n>0?n:void 0},Sr=new Set(["1","enabled","on","true","yes"]),Tr=new Set(["0","disabled","false","no","off"]),Or=(e,n)=>{const t=(e??"").trim().toLowerCase();return Sr.has(t)?!0:Tr.has(t)?!1:n},$t="v1",vr=6e4,kr=async(e,n={})=>{const t=(n.now??Date.now())+(n.ttlMs??vr),r=`${$t}.${String(t)}`,a=await Lt(e,r);return{expiresAtMs:t,token:`${r}.${a}`}},Ir=async(e,n,t=Date.now())=>{if(e.length===0||n.length===0)return!1;const r=n.split(".");if(r.length!==3)return!1;const[a,s,l]=r;if(a!==$t||l.length===0)return!1;const u=Number(s);if(!Number.isFinite(u)||u<=t)return!1;let f;try{f=hr(l)}catch{return!1}return mr(e,`${a}.${s}`,f)},P="/_lunora/admin/auth",Pr={INVITER_REQUIRED:400,ORG_SLUG_INVALID:400,ORG_SLUG_TAKEN:409,PASSWORD_TOO_LONG:400,PASSWORD_TOO_SHORT:400,USER_ALREADY_EXISTS:409,USER_NOT_FOUND:404},N=(e,n)=>{const t=e[n];if(typeof t!="string"||t==="")throw new d(`\`${n}\` is required`,{code:"BAD_REQUEST",status:400});return t},le=(e,n)=>{const t=e(n);if(t===void 0)throw new d(`\`${n}\` query parameter is required`,{code:"BAD_REQUEST",status:400});return t},Kt=e=>{if(typeof e=="string"||Array.isArray(e)&&e.every(n=>typeof n=="string"))return e},re=(e,n)=>typeof e[n]=="string"?e[n]:void 0,xe=(e,n)=>{const t=e[n];return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:void 0},it=e=>{const n=Kt(e.role);if(n===void 0||typeof n=="string"&&n.trim()==="")throw new d("`role` is required",{code:"BAD_REQUEST",status:400});return n},ct=e=>{const n=e.permission;if(typeof n!="object"||n===null||Array.isArray(n))throw new d("`permission` object is required",{code:"BAD_REQUEST",status:400});const t={};for(const[r,a]of Object.entries(n))Array.isArray(a)&&a.every(s=>typeof s=="string")&&(t[r]=a);return t},Dr={[`${P}/capabilities`]:{build:()=>({}),http:"GET",method:"capabilities"},[`${P}/users`]:{build:({paging:e,query:n})=>{const t=n("sortDirection");return{...e,filterField:n("filterField"),filterValue:n("filterValue"),search:n("search"),searchField:n("searchField"),sortBy:n("sortBy"),sortDirection:t==="asc"||t==="desc"?t:void 0}},http:"GET",method:"listUsers"},[`${P}/sessions`]:{build:({paging:e,query:n})=>({...e,userId:n("userId")}),http:"GET",method:"listSessions"},[`${P}/accounts`]:{build:({query:e})=>({userId:le(e,"userId")}),http:"GET",method:"listAccounts"},[`${P}/passkeys`]:{build:({query:e})=>({userId:le(e,"userId")}),http:"GET",method:"listPasskeys"},[`${P}/organizations`]:{build:({paging:e})=>({...e}),http:"GET",method:"listOrganizations"},[`${P}/organizations/members`]:{build:({paging:e,query:n})=>({...e,organizationId:le(n,"organizationId")}),http:"GET",method:"listMembers"},[`${P}/organizations/invitations`]:{build:({paging:e,query:n})=>({...e,organizationId:le(n,"organizationId")}),http:"GET",method:"listInvitations"},[`${P}/config`]:{build:()=>({}),http:"GET",method:"config"},[`${P}/organizations/teams`]:{build:({paging:e,query:n})=>({...e,organizationId:le(n,"organizationId")}),http:"GET",method:"listTeams"},[`${P}/organizations/teams/members`]:{build:({paging:e,query:n})=>({...e,teamId:le(n,"teamId")}),http:"GET",method:"listTeamMembers"},[`${P}/organizations/roles`]:{build:({paging:e,query:n})=>({...e,organizationId:le(n,"organizationId")}),http:"GET",method:"listOrgRoles"},[`${P}/users/create`]:{build:({body:e})=>({data:xe(e,"data"),email:N(e,"email"),name:N(e,"name"),password:re(e,"password"),role:Kt(e.role)}),http:"POST",method:"createUser"},[`${P}/users/update`]:{build:({body:e})=>{const{data:n}=e;if(typeof n!="object"||n===null||Array.isArray(n))throw new d("`data` object is required",{code:"BAD_REQUEST",status:400});return{data:n,userId:N(e,"userId")}},http:"POST",method:"updateUser"},[`${P}/users/role`]:{build:({body:e})=>({role:it(e),userId:N(e,"userId")}),http:"POST",method:"setRole"},[`${P}/users/ban`]:{build:({body:e})=>({expiresInSeconds:typeof e.expiresInSeconds=="number"?e.expiresInSeconds:void 0,reason:re(e,"reason"),userId:N(e,"userId")}),http:"POST",method:"banUser"},[`${P}/users/unban`]:{build:({body:e})=>({userId:N(e,"userId")}),http:"POST",method:"unbanUser"},[`${P}/users/password`]:{build:({body:e})=>({newPassword:N(e,"newPassword"),userId:N(e,"userId")}),http:"POST",method:"setUserPassword",returns:"void"},[`${P}/users/remove`]:{build:({body:e})=>({userId:N(e,"userId")}),http:"POST",method:"removeUser",returns:"void"},[`${P}/users/impersonate`]:{build:({body:e})=>({userId:N(e,"userId")}),http:"POST",method:"impersonateUser"},[`${P}/sessions/revoke`]:{build:({body:e})=>({sessionId:N(e,"sessionId")}),http:"POST",method:"revokeUserSession",returns:"void"},[`${P}/sessions/revoke-all`]:{build:({body:e})=>({userId:N(e,"userId")}),http:"POST",method:"revokeUserSessions",returns:"void"},[`${P}/accounts/unlink`]:{build:({body:e})=>({accountId:N(e,"accountId"),userId:N(e,"userId")}),http:"POST",method:"unlinkAccount",returns:"void"},[`${P}/two-factor/disable`]:{build:({body:e})=>({userId:N(e,"userId")}),http:"POST",method:"disableTwoFactor",returns:"void"},[`${P}/passkeys/delete`]:{build:({body:e})=>({passkeyId:N(e,"passkeyId")}),http:"POST",method:"deletePasskey",returns:"void"},[`${P}/organizations/members/remove`]:{build:({body:e})=>({memberId:N(e,"memberId")}),http:"POST",method:"removeMember",returns:"void"},[`${P}/organizations/invitations/cancel`]:{build:({body:e})=>({invitationId:N(e,"invitationId")}),http:"POST",method:"cancelInvitation",returns:"void"},[`${P}/organizations/create`]:{build:({body:e})=>({logo:re(e,"logo"),metadata:xe(e,"metadata"),name:N(e,"name"),ownerId:re(e,"ownerId"),slug:re(e,"slug")}),http:"POST",method:"createOrganization"},[`${P}/organizations/update`]:{build:({body:e})=>({logo:re(e,"logo"),metadata:xe(e,"metadata"),name:re(e,"name"),organizationId:N(e,"organizationId"),slug:re(e,"slug")}),http:"POST",method:"updateOrganization"},[`${P}/organizations/remove`]:{build:({body:e})=>({organizationId:N(e,"organizationId")}),http:"POST",method:"deleteOrganization",returns:"void"},[`${P}/organizations/members/add`]:{build:({body:e})=>({organizationId:N(e,"organizationId"),role:re(e,"role"),userId:N(e,"userId")}),http:"POST",method:"addMember"},[`${P}/organizations/members/invite`]:{build:({body:e})=>({email:N(e,"email"),inviterId:re(e,"inviterId"),organizationId:N(e,"organizationId"),role:re(e,"role")}),http:"POST",method:"inviteMember"},[`${P}/organizations/members/role`]:{build:({body:e})=>({memberId:N(e,"memberId"),role:it(e)}),http:"POST",method:"updateMemberRole"},[`${P}/organizations/teams/create`]:{build:({body:e})=>({name:N(e,"name"),organizationId:N(e,"organizationId")}),http:"POST",method:"createTeam"},[`${P}/organizations/teams/update`]:{build:({body:e})=>({name:N(e,"name"),teamId:N(e,"teamId")}),http:"POST",method:"updateTeam"},[`${P}/organizations/teams/remove`]:{build:({body:e})=>({teamId:N(e,"teamId")}),http:"POST",method:"removeTeam",returns:"void"},[`${P}/organizations/teams/members/add`]:{build:({body:e})=>({teamId:N(e,"teamId"),userId:N(e,"userId")}),http:"POST",method:"addTeamMember"},[`${P}/organizations/teams/members/remove`]:{build:({body:e})=>({teamMemberId:N(e,"teamMemberId")}),http:"POST",method:"removeTeamMember",returns:"void"},[`${P}/organizations/roles/create`]:{build:({body:e})=>({organizationId:N(e,"organizationId"),permission:ct(e),role:N(e,"role")}),http:"POST",method:"createOrgRole"},[`${P}/organizations/roles/update`]:{build:({body:e})=>({permission:ct(e),roleId:N(e,"roleId")}),http:"POST",method:"updateOrgRole"},[`${P}/organizations/roles/remove`]:{build:({body:e})=>({roleId:N(e,"roleId")}),http:"POST",method:"deleteOrgRole",returns:"void"}},Nr=e=>{const n=async a=>{try{return await a()}catch(s){if(s instanceof d)throw s;const l=s,u=typeof l.code=="string"?l.code:"AUTH_ADMIN_ERROR";throw console.error("[lunora] auth admin operation failed:",s),new d("auth admin operation failed",{code:u,status:Pr[u]??500})}},t=async(a,s)=>{if(e.assertAdmin(a),a.method!==s.http)throw new d(`Auth admin endpoint requires ${s.http}`,{code:"METHOD_NOT_ALLOWED",status:405});const l=e.getAuthAdmin();if(l===void 0)throw new d("auth endpoints require an `authAdmin` on the worker",{code:"AUTH_NOT_CONFIGURED",status:400});const u=l[s.method];if(u===void 0)throw new d(`auth admin does not support \`${s.method}\``,{code:"AUTH_OP_NOT_SUPPORTED",status:400});const f=new URL(a.url),g={body:s.http==="POST"?await e.readJsonBody(a):{},paging:e.parsePaging(a),query:v=>e.queryParameter(f,v)},E=s.build(g),k=await n(()=>u(E));return Response.json(s.returns==="void"?{ok:!0}:k,{headers:{"content-type":"application/json"},status:200})},r={};for(const[a,s]of Object.entries(Dr))r[a]=l=>t(l,s);return r},Ur="__lunora_admin__:getAuthAuditLog",dt=e=>typeof e=="string"&&e!==""?e:void 0,ut=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0,Cr=e=>async(t,r)=>{e.assertAdmin(t);const a=e.getReader();if(a===void 0)throw new d("the auth/security audit endpoint requires an `authAuditReader` on the worker",{code:"AUTH_AUDIT_NOT_CONFIGURED",status:400});const s=dt(r.actorId),l=dt(r.event),u=ut(r.sinceSeq),f=ut(r.limit),g={...s===void 0?{}:{actorId:s},...l===void 0?{}:{event:l},...u===void 0?{}:{sinceSeq:u},...f===void 0?{}:{limit:f}};let E;try{E=await a.read(g)}catch(v){throw v instanceof d?v:(console.error("[lunora] auth audit read failed:",v),new d("auth audit read failed",{code:"AUTH_AUDIT_READ_FAILED",status:500}))}const k={entries:E};return Response.json({result:Ke(k)},{headers:{"content-type":"application/json"},status:200})},Br=(e,n)=>{const t=[],r=[];if(n&&n.length>0)for(const a of n)e.resolveTableSharding?.(a)?.mode.kind==="global"?r.push(a):t.push(a);return{globalTables:r,shardLocalTables:t}},xr=async(e,n,t,r,a,s)=>{if(t!==void 0&&r.length===0)return;const l=await e.orchestrateExport(s,{args:{tables:r},headers:n,tables:r});for(const u of l.shards)if(!u.error)for(const f of u.rows??[])a(f)},Ft=async(e,n,t,r,a,s)=>{const{globalTables:l,shardLocalTables:u}=Br(e,r);await xr(n,t,r,u,a,s);const f=e.exportGlobals;if((r===void 0||l.length>0)&&f)for await(const E of f({tables:l}))a(E)},Hr=new TextEncoder,Lr=1e3,Gt=10,Mr=200,lt=8,Qt="lunoraBackupCron",ht=24*1048576,ft=e=>{const n=e.slice(0,Gt).map(r=>Bt(r)),t=e.length-n.length;return`${n.join(", ")}${t>0?` (+${String(t)} more)`:""}`},jr=(e,n)=>{const t=new Uint8Array(new ArrayBuffer(n));let r=0;for(const a of e)t.set(a,r),r+=a.byteLength;return t},Ve=async(e,n,t,r)=>{if(t===void 0||!Number.isInteger(t)||t<=0)return{eligible:0,stale:[]};const a=[];let s;for(let l=0;l<Lr;l+=1){const u=await e.list({cursor:s,include:["customMetadata"],prefix:n});for(const f of u.objects)Gn(f.key)&&f.customMetadata?.[Qt]===r&&a.push(f.key);if(!u.truncated||u.cursor===void 0)break;s=u.cursor}return{eligible:a.length,stale:a.toSorted((l,u)=>u.localeCompare(l)).slice(t)}},$r=async(e,n,t,r,a)=>{const{stale:s}=await Ve(e,n,t,r),l=new Set(a),u=s.filter(w=>l.has(w)),f=u.slice(0,Mr),g=s.length-f.length,E=a.length-u.length;if(f.length===0)return{deleted:[],failed:[],ignored:E,remaining:g};const k=[],v=[];for(let w=0;w<f.length;w+=lt){const b=await Promise.allSettled(f.slice(w,w+lt).map(async _=>(await e.delete(Bt(_)),await e.delete(_),_)));for(const[_,p]of b.entries())p.status==="fulfilled"?k.push(p.value):v.push(f[w+_])}return k.length>0&&console.info(`[lunora] backup prune kept the newest ${String(t)} and deleted ${String(k.length)}: ${ft(k)}`),v.length>0&&console.warn(`[lunora] backup prune failed to remove ${String(v.length)}: ${ft(v)}`),{deleted:k,failed:v,ignored:E,remaining:g}},Kr=async e=>{const n=e.backupStore;if(!n)throw new d("backup retention preview requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});const t=Ge(e.backupPrefix??Qe),r=e.backupCron,{eligible:a,stale:s}=r===void 0?{eligible:0,stale:[]}:await Ve(n,t,e.backupRetain,r);return{cron:r,eligible:a,keep:e.backupRetain??0,prefix:t,wouldDelete:s}},Fr=async(e,n,t,r)=>{const a=e.backupStore,s=e.queryCoordinator;if(!a)throw new d("scheduled backup requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});if(!s)throw new d("scheduled backup requires a `queryCoordinator` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});if(!t||t.length===0)throw new d("scheduled backup requires an `adminToken` (or `env.LUNORA_ADMIN_TOKEN`) to authenticate the per-shard export gate",{code:"BACKUP_NOT_CONFIGURED",status:500});const l={authorization:`Bearer ${t}`,"content-type":"application/json"},u=e.backupTables;let f=0,g=0,E=[];await Ft(e,s,l,u,D=>{const T=Hr.encode(`${JSON.stringify(D)}
|
|
2
|
+
`);if(f+=1,g+=T.byteLength,g>ht)throw new d(`scheduled backup reached ${String(g)} bytes of NDJSON, past the ${String(ht)}-byte limit for a snapshot assembled inside a Worker — nothing was written. Narrow it with \`backupTables\`, or take this snapshot off-platform with \`lunora backup create --bucket\`.`,{code:"BACKUP_TOO_LARGE",status:507});E.push(T)},n);const v=Ge(e.backupPrefix??Qe),w=new Date(r.scheduledTime).toISOString(),b=Qn(v,w),_=jr(E,g);E=[];const p=Wn(await crypto.subtle.digest("SHA-256",_));await a.put(b,_,{httpMetadata:{contentType:"application/x-ndjson"},sha256:p});const S={bytes:g,createdAt:w,cron:r.cron,file:b,id:w,rows:f,scheduledTime:r.scheduledTime,sha256:p,...u?{tables:u.join(",")}:{}};await a.put(zn(b),`${JSON.stringify(S,void 0,2)}
|
|
3
|
+
`,{customMetadata:{[Qt]:r.cron},httpMetadata:{contentType:"application/json"}});try{const{stale:D}=await Ve(a,v,e.backupRetain,r.cron);if(D.length>0){const T=D.slice(0,Gt),x=D.length-T.length;console.info(`[lunora] backup retention: ${String(D.length)} snapshot(s) past the newest ${String(e.backupRetain)} — run \`lunora backup prune\` to remove them: ${T.join(", ")}${x>0?` (+${String(x)} more)`:""}`)}}catch(D){console.warn(`[lunora] backup ${b} was written, but the retention report failed:`,D)}},Gr=async(e,n)=>{const t=e.backupStore;if(!t)throw new d("backup prune requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});const r=e.backupCron,a=e.backupRetain;if(r===void 0||a===void 0||!Number.isInteger(a)||a<=0)throw new d("backup prune needs a retention window: set `backupRetain` (and `backupCron`, which decides whose snapshots retention owns) on the worker. Without one there is nothing past the window to remove.",{code:"BACKUP_RETENTION_NOT_CONFIGURED",status:400});return $r(t,Ge(e.backupPrefix??Qe),a,r,n)},Qr="/_lunora/admin/backup/retention",zr="/_lunora/admin/backup/prune",Wr=e=>{const{options:n,readJsonBody:t,requireAdminOption:r}=e,a=(u,f)=>{r(u,n.backupStore,{code:"BACKUP_NOT_CONFIGURED",message:`backup ${f} requires a \`backupStore\` on the worker`})},s=async u=>(j(u,"GET","Backup-retention"),a(u,"retention preview"),Response.json(await Kr(n),{headers:{"cache-control":"no-store"}})),l=async u=>{j(u,"POST","Backup-prune"),a(u,"prune");const{confirm:f}=await t(u);if(!Array.isArray(f)||f.some(g=>typeof g!="string"))throw new d("backup prune requires a `confirm` array of the sidecar keys to remove — read them from `GET /_lunora/admin/backup/retention` and pass back the ones you mean to delete",{code:"BAD_REQUEST",status:400});return Response.json(await Gr(n,f),{headers:{"cache-control":"no-store"}})};return{[zr]:l,[Qr]:s}},pt=500,Vr=(e,n,t)=>{if(typeof e!="object"||e===null||Array.isArray(e))throw new d("each batch call must be an object",{code:"BAD_REQUEST",status:400});const r=e;if(typeof r.functionPath!="string")throw new d("each batch call needs a string `functionPath`",{code:"BAD_REQUEST",status:400});if(r.functionPath.startsWith("__lunora_relation__:")||r.functionPath.startsWith("__lunora_admin__"))throw new d("reserved function path cannot be batched",{code:"FORBIDDEN",status:403});if(r.args!==void 0&&(typeof r.args!="object"||r.args===null||Array.isArray(r.args)))throw new d("each batch call `args` must be an object",{code:"BAD_REQUEST",status:400});return{entry:{args:r.args===void 0?{}:r.args,clientId:typeof r.clientId=="string"?r.clientId:void 0,clientSeq:typeof r.clientSeq=="number"?r.clientSeq:void 0,functionPath:r.functionPath,id:typeof r.id=="number"?r.id:n,mutationId:typeof r.mutationId=="string"?r.mutationId:void 0},shardKey:typeof r.shardKey=="string"?r.shardKey:t}},Jr=(e,n)=>{if(e.length>pt)throw new d(`RPC batch exceeds the ${String(pt)}-call limit`,{code:"BAD_REQUEST",status:400});const t=new Map;for(const[r,a]of e.entries()){const{entry:s,shardKey:l}=Vr(a,r,n),u=t.get(l)??[];u.push(s),t.set(l,u)}return t},qr=new TextEncoder,Yr=e=>{const n=JSON.stringify(e),t=qr.encode(n);let r="";for(const a of t)r+=String.fromCodePoint(a);return btoa(r).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")},Xr=e=>{const n={g:0,s:{},v:1};if(typeof e!="string"||e.length===0)return n;try{const t=atob(e.replaceAll("-","+").replaceAll("_","/")),r=new Uint8Array(t.length);for(let u=0;u<t.length;u+=1)r[u]=t.codePointAt(u)??0;const a=JSON.parse(new TextDecoder().decode(r)),s=a.s&&typeof a.s=="object"?a.s:{},l={};for(const[u,f]of Object.entries(s))typeof f=="number"&&Number.isFinite(f)&&(l[u]=f);return{g:typeof a.g=="number"&&Number.isFinite(a.g)?a.g:0,s:l,v:1}}catch{return n}},Zr=e=>{const n=typeof e.table=="string"?e.table:"",t=typeof e.op=="string"?e.op:"",r=t==="delete"||t==="insert"||t==="update"?t:"upsert",a=typeof e.id=="string"?e.id:void 0;return{doc:(e.doc&&typeof e.doc=="object"?e.doc:void 0)??(a===void 0?{}:{_id:a}),op:r,table:n}},mt=(e,n,t)=>{for(const r of n)e.push(Zr(r));return t!==void 0&&n.length>=t},eo="/_lunora/admin/export",to="/_lunora/admin/import",no="/_lunora/admin/sync",ro="/_lunora/admin/connector/sync",oo="/_lunora/admin/apply",ao="/_lunora/admin/export-tap/run",so=new TextEncoder,io=async e=>{const t=await be(e,"Export")??{};if(t.tables===void 0)return{tables:void 0};if(!Array.isArray(t.tables))throw new d("Export `tables` must be a string array",{code:"BAD_REQUEST",status:400});const r=[];for(const a of t.tables){if(typeof a!="string"||a.length===0)throw new d("Export `tables` entries must be non-empty strings",{code:"BAD_REQUEST",status:400});r.push(a)}return{tables:r}},He=e=>Array.isArray(e)?e.filter(n=>typeof n=="string"):void 0,co=e=>{const{applyGlobals:n,exportCursorStore:t,exportSinks:r,knownTables:a,queryCoordinator:s,assertAdmin:l,requireAdminOption:u,resolveForwardContext:f,shardDO:g,streamExportRows:E,streamingImport:k,syncGlobals:v}=e,w=async(T,x)=>{const H=me(T,["POST"]);if(H)return H;const $=u(T,s,{code:"BAD_REQUEST",message:"Export endpoint requires a `queryCoordinator` on the worker"}),U=await io(T),{headers:W}=await f(T,x),K=new ReadableStream({async pull(V){const X=J=>{V.enqueue(so.encode(`${JSON.stringify(J)}
|
|
4
|
+
`))};try{await E($,W,U.tables,X),V.close()}catch(J){V.error(J)}}});return new Response(K,{headers:{"content-type":"application/x-ndjson"},status:200})},b=async(T,x)=>{const H=me(T,["POST"]);if(H)return H;const $=u(T,s,{code:"BAD_REQUEST",message:"Sync endpoint requires a `queryCoordinator` on the worker"}),U=await Z(T),W=typeof U.cursors=="object"&&U.cursors!==null?U.cursors:{},K=typeof U.limit=="number"?U.limit:void 0,V=typeof U.globalCursor=="number"?U.globalCursor:0,X=He(U.tables),{headers:J}=await f(T,x),ae=X??a(),F=await $.orchestrateCdcSync(g,{cursors:W,headers:J,limit:K,tables:ae}),he=v?await v({limit:K,sinceSeq:V}):void 0;return Response.json({global:he,shards:F.shards},{status:200})},_=async(T,x)=>{const H=me(T,["POST"]);if(H)return H;const $=u(T,s,{code:"BAD_REQUEST",message:"Connector sync endpoint requires a `queryCoordinator` on the worker"}),U=await Z(T),W=Xr(U.cursor),K=typeof U.limit=="number"&&U.limit>0?U.limit:void 0,V=He(U.tables),{headers:X}=await f(T,x),J=V??a(),ae=await $.orchestrateCdcSync(g,{cursors:W.s,headers:X,limit:K,tables:J}),F=[],he={...W.s};let G=!1;for(const se of ae.shards)G=mt(F,se.changes??[],K)||G,he[se.shardKey]=se.cursor;let oe=W.g;if(v){const se=await v({limit:K,sinceSeq:W.g});G=mt(F,se.changes,K)||G,oe=se.cursor}const Te=Yr({g:oe,s:he,v:1}),Oe={changes:F,hasMore:G,nextCursor:Te};return Response.json(Oe,{status:200})},p=async(T,x)=>{const H=me(T,["POST"]);if(H)return H;const $=u(T,s,{code:"BAD_REQUEST",message:"Apply endpoint requires a `queryCoordinator` on the worker"}),U=await Z(T),K=(Array.isArray(U.batches)?U.batches:[]).map(F=>F).filter(F=>F!==null&&typeof F=="object"&&typeof F.shardKey=="string"&&Array.isArray(F.changes)),V=Array.isArray(U.globalChanges)?U.globalChanges:[],{headers:X}=await f(T,x),J=await $.orchestrateApplyCdc(g,{batches:K,headers:X}),ae=V.length>0&&n?await n({changes:V}):0;return Response.json({applied:J.applied+ae,failed:J.failed,ok:J.ok},{status:200})},S=async(T,x)=>{const H=me(T,["POST"]);if(H)return H;l(T);const{headers:$}=await f(T,x),U=await k(T,$);return Response.json(U,{headers:{"content-type":"application/json"},status:200})},D=async(T,x)=>{const H=me(T,["POST"]);if(H)return H;const $=u(T,s,{code:"BAD_REQUEST",message:"Export-tap endpoint requires a `queryCoordinator` on the worker"});if(r===void 0||Object.keys(r).length===0||t===void 0)throw new d("Export-tap endpoint requires `exportSinks` + `exportCursorStore` on the worker",{code:"EXPORT_TAP_NOT_CONFIGURED",status:400});const U=await Z(T),W=typeof U.sink=="string"?U.sink:void 0,K=typeof U.limit=="number"&&U.limit>0?U.limit:void 0,V=He(U.tables);if(W===void 0)throw new d("Export-tap `sink` must name a configured sink",{code:"BAD_REQUEST",status:400});const X=r[W];if(X===void 0)throw new d(`Export-tap sink "${W}" is not configured`,{code:"NOT_FOUND",status:404});const{headers:J}=await f(T,x),ae=V??a(),F=await Yn({coordinator:$,cursorStore:t,headers:J,limit:K,shardDO:g,sink:X,tables:ae});return Response.json(F,{headers:{"content-type":"application/json"},status:200})};return{[oo]:p,[ro]:_,[eo]:w,[ao]:D,[to]:S,[no]:b}},uo=(e,n)=>{let t;try{t=JSON.parse(e)}catch{return{error:{code:"BAD_ROW",line:n,message:"line is not valid JSON",table:""},ok:!1}}if(!t||typeof t!="object"||Array.isArray(t))return{error:{code:"BAD_ROW",line:n,message:"row must be a JSON object",table:""},ok:!1};const r=t;return typeof r.table!="string"||r.table.length===0?{error:{code:"BAD_ROW",line:n,message:"row is missing `table`",table:""},ok:!1}:!r.doc||typeof r.doc!="object"||Array.isArray(r.doc)?{error:{code:"BAD_ROW",line:n,message:"row is missing or malformed `doc`",table:r.table},ok:!1}:{doc:r.doc,ok:!0,table:r.table}},lo=(e,n,t,r,a)=>{if(t?.mode.kind==="shardBy"&&typeof t.mode.field=="string"){const s=e[t.mode.field];return s==null?{error:{code:"BAD_ROW",line:a,message:`row missing shard field "${t.mode.field}" for table "${n}"`,table:n},ok:!1}:{ok:!0,shardKey:typeof s=="string"?s:JSON.stringify(s)}}return{ok:!0,shardKey:r}},ho=async(e,n,t)=>{if(!e.body)throw new d("Import endpoint requires a request body",{code:"BAD_REQUEST",status:400});const r=[],a=[],s=new Map;let l=0,u=0;const f=e.body.getReader(),g=new TextDecoder;let E="",k=0;const v=w=>{u+=1;const b=w.trim();if(b.length===0)return;l+=1;const _=uo(b,u);if(!_.ok){r.push(_.error);return}const{doc:p,table:S}=_,D=n.resolveTableSharding?.(S);if(D?.mode.kind==="global"){a.push({doc:p,line:u,table:S});return}const T=lo(p,S,D,t,u);if(!T.ok){r.push(T.error);return}const x=s.get(T.shardKey);x?x.rows.push({doc:p,table:S}):s.set(T.shardKey,{rows:[{doc:p,table:S}],shardKey:T.shardKey,startLine:u})};for(;;){const{done:w,value:b}=await f.read();if(w)break;if(b&&(k+=b.byteLength,k>Nt))throw await f.cancel().catch(()=>{}),new d("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});E+=g.decode(b,{stream:!0});let _=E.indexOf(`
|
|
5
5
|
`);for(;_!==-1;){const p=E.slice(0,_);E=E.slice(_+1),v(p),_=E.indexOf(`
|
|
6
|
-
`)}}return E.length>0&&v(E),{errors:r,globalRows:a,perShard:s,received:l}},gt=(e,n)=>{for(const[t,r]of Object.entries(n.inserted))e.inserted[t]=(e.inserted[t]??0)+r;for(const t of n.errors)e.errors.push({...t});e.conflicts+=n.conflicts},ho=async(e,n,t,r)=>{const a=n.defaultShardKey??"__root__",{errors:s,globalRows:l,perShard:u,received:f}=await lo(e,n,a),g={conflicts:0,errors:s,inserted:{}},E=[];if(n.resolveTableSharding===void 0&&u.size>0&&E.push("no `resolveTableSharding` is configured, so every row was routed to the default shard and no row could be recognised as `.global()` — correct for a single-shard app, silent misplacement for a sharded one"),u.size>0){const k=n.queryCoordinator;if(!k)throw new d("Import endpoint requires a `queryCoordinator` on the worker",{code:"BAD_REQUEST",status:400});const v=await k.orchestrateImport(r,{batches:[...u.values()],headers:t});gt(g,v)}if(l.length>0)if(n.importGlobals){const k=l[0]?.line??1,v=await n.importGlobals({rows:l,startLine:k});gt(g,v)}else for(const k of l)g.errors.push({code:"GLOBAL_NOT_CONFIGURED",line:k.line,message:`row targets global table "${k.table}" but no \`importGlobals\` is configured`,table:k.table});return{conflicts:g.conflicts,errors:g.errors,inserted:g.inserted,received:f,...E.length>0?{warnings:E}:{}}},Me=e=>typeof e=="object"&&e!==null?e:{},je=e=>typeof e.kind=="string"?e.kind:"unknown",fo=(e,n)=>{let t=Me(n),r=!1;je(t)==="optional"&&(r=!0,t=Me(t._meta?.inner));const a=je(t),s=t._meta??{},l={kind:a,name:e,optional:r};if(a==="id"&&typeof s.tableName=="string"&&(l.table=s.tableName),a==="array"){const u=je(Me(s.inner));u!=="unknown"&&(l.element=u)}return l},po=e=>typeof e!="object"||e===null?[]:Object.entries(e).map(([n,t])=>fo(n,t)).toSorted((n,t)=>n.name.localeCompare(t.name)),mo="/_lunora/admin/functions",wo="/_lunora/admin/cron-jobs",go="/_lunora/admin/openapi",yo="/_lunora/admin/openrpc",bo="/_lunora/admin/global/tables",_o="/_lunora/admin/global/table",Ro="/_lunora/admin/global/facet",yt=e=>{if(e===void 0||e==="")return;let n;try{n=JSON.parse(e)}catch{return}if(!Array.isArray(n))return;const t=n.flatMap(r=>{if(typeof r!="object"||r===null||typeof r.column!="string")return[];const{column:a,value:s}=r;return[{column:a,value:s}]});return t.length===0?void 0:t},Eo=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:{}}),Ao=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"}),So=e=>{const{assertAdmin:n,options:t,parsePaging:r,queryParameter:a,requireAdminOption:s}=e,l=w=>{j(w,"GET","Functions");const b=s(w,t.functions,{code:"FUNCTIONS_NOT_CONFIGURED",message:"functions endpoint requires a `functions` registry on the worker"}),_=Object.entries(b).flatMap(([p,S])=>S.visibility==="internal"||S.kind==="stream"?[]:[{args:po(S.args),kind:S.kind,path:p}]).toSorted((p,S)=>p.path.localeCompare(S.path));return Response.json({functions:_},{headers:{"content-type":"application/json"},status:200})},u=w=>{j(w,"GET","Cron-jobs");const b=s(w,t.cronJobs,{code:"CRON_JOBS_NOT_CONFIGURED",message:"cron-jobs endpoint requires a `cronJobs` map on the worker"}),_=Object.entries(b).flatMap(([p,S])=>S.map(D=>({args:D.args,cron:p,functionPath:D.functionPath,name:D.name,shardKey:D.shardKey,workflow:D.workflow}))).toSorted((p,S)=>p.name.localeCompare(S.name));return Response.json({jobs:_},{headers:{"content-type":"application/json"},status:200})},f=w=>(j(w,"GET","OpenAPI"),n(w),Response.json(t.openApiSpec??Eo,{headers:{"content-type":"application/json"},status:200})),g=w=>(j(w,"GET","OpenRPC"),n(w),Response.json(t.openRpcSpec??Ao,{headers:{"content-type":"application/json"},status:200})),E=async w=>{j(w,"GET","Global-tables");const b=s(w,t.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"});return Response.json(await b.listTables(),{headers:{"content-type":"application/json"},status:200})},k=async w=>{j(w,"GET","Global-table");const b=s(w,t.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),_=new URL(w.url),p=a(_,"table");if(p===void 0)throw new d("Global-table endpoint requires a `table` query param",{code:"BAD_REQUEST",status:400});const S=await b.readTablePage({...r(w),filters:yt(a(_,"filters")),table:p});return Response.json(S,{headers:{"content-type":"application/json"},status:200})},v=async w=>{j(w,"GET","Global-facet");const b=s(w,t.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),_=new URL(w.url),p=a(_,"table"),S=a(_,"column");if(p===void 0||S===void 0)throw new d("Global-facet endpoint requires `table` and `column` query params",{code:"BAD_REQUEST",status:400});const D=a(_,"limit"),T=D===void 0?void 0:Number(D),x=await b.facetColumn({column:S,filters:yt(a(_,"filters")),limit:T!==void 0&&Number.isFinite(T)?T:void 0,table:p});return Response.json(x,{headers:{"content-type":"application/json"},status:200})};return{[wo]:u,[mo]:l,[Ro]:v,[_o]:k,[bo]:E,[go]:f,[yo]:g}},To="/_lunora/admin/kv/namespaces",Oo="/_lunora/admin/kv/keys",Wt="/_lunora/admin/kv/value",Vt=32*1048576,bt=60,vo=e=>{const{readJsonBody:n,requireAdminOption:t}=e,r=b=>t(b,e.kvIntrospector,{code:"KV_NOT_CONFIGURED",message:"KV endpoints require a `kvIntrospector` on the worker"}),a=b=>Response.json(b,{headers:{"content-type":"application/json"},status:200}),s=(b,_)=>{const p=new URL(b.url),S=p.searchParams.get("namespace")??"",D=p.searchParams.get("key")??"";if(S==="")throw new d(`KV-value ${_} request requires a \`namespace\` query parameter`,{code:"BAD_REQUEST",status:400});if(D==="")throw new d(`KV-value ${_} request requires a \`key\` query parameter`,{code:"BAD_REQUEST",status:400});return{key:D,namespace:S}},l=async(b,_)=>{if(!(await b.listNamespaces()).some(S=>S.binding===_))throw new d(`Unknown KV namespace binding \`${_}\``,{code:"NOT_FOUND",status:404})},u=async b=>(j(b,"GET","KV-namespaces"),a({namespaces:await r(b).listNamespaces()})),f=async b=>{j(b,"GET","KV-keys");const _=r(b),p=new URL(b.url),S=p.searchParams.get("namespace")??"";if(S==="")throw new d("KV-keys request requires a `namespace` query parameter",{code:"BAD_REQUEST",status:400});const D=p.searchParams.get("prefix")??void 0,T=p.searchParams.get("cursor")??void 0,x=p.searchParams.get("limit"),H=x===null?void 0:Number.parseInt(x,10);if(H!==void 0&&(!Number.isInteger(H)||H<1))throw new d("KV-keys `limit` must be a positive integer",{code:"BAD_REQUEST",status:400});const $=H===void 0?void 0:Math.min(H,1e3);return await l(_,S),a(await _.listKeys({cursor:T,limit:$,namespace:S,prefix:D}))},v={DELETE:async b=>{const _=r(b),p=s(b,"DELETE");return await l(_,p.namespace),await _.deleteKey(p),a({deleted:!0})},GET:async b=>{const _=r(b),p=s(b,"GET");return await l(_,p.namespace),a(await _.getValue(p))},PUT:async b=>{const _=r(b),p=await n(b,Vt);if(typeof p.namespace!="string"||p.namespace==="")throw new d("KV-value PUT request requires a `namespace` string",{code:"BAD_REQUEST",status:400});if(typeof p.key!="string"||p.key==="")throw new d("KV-value PUT request requires a `key` string",{code:"BAD_REQUEST",status:400});if(typeof p.value!="string")throw new d("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<bt))throw new d("KV-value PUT `expirationTtl` must be an integer ≥ 60",{code:"BAD_REQUEST",status:400});const S=Math.floor(Date.now()/1e3)+bt;if(p.expiration!==void 0&&(typeof p.expiration!="number"||!Number.isInteger(p.expiration)||p.expiration<S))throw new d("KV-value PUT `expiration` must be a Unix-seconds timestamp at least 60 seconds in the future",{code:"BAD_REQUEST",status:400});return await l(_,p.namespace),await _.putValue({expiration:p.expiration,expirationTtl:p.expirationTtl,key:p.key,metadata:p.metadata,namespace:p.namespace,value:p.value}),a({ok:!0})}},w=b=>{const _=v[b.method];if(!_)throw new d("KV-value endpoint requires GET, PUT, or DELETE",{code:"METHOD_NOT_ALLOWED",status:405});return _(b)};return{[To]:u,[Oo]:f,[Wt]:w}},ko="/_lunora/migrate",Io="/_lunora/admin/pitr",Po="/_lunora/admin/rank",Do="/_lunora/admin/rankpage",No="/_lunora/admin/shard-traffic",Uo=new Set(["__lunora_admin__:migrationStatus","__lunora_admin__:runMigration"]),Co=new Set(["__lunora_admin__:getPitrBookmark","__lunora_admin__:pitrRestore"]),Bo=async e=>{const t=await be(e,"Migration")??{};if(typeof t.table!="string"||t.table.length===0)throw new d("Migration request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof t.functionPath!="string"||!Uo.has(t.functionPath))throw new d("Migration request `functionPath` must be a migration admin op",{code:"BAD_REQUEST",status:400});return{args:t.args??{},functionPath:t.functionPath,table:t.table}},xo=async e=>{const t=await be(e,"Rank")??{};if(typeof t.table!="string"||t.table.length===0)throw new d("Rank request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof t.index!="string"||t.index.length===0)throw new d("Rank request is missing `index`",{code:"BAD_REQUEST",status:400});if(typeof t.partitionKey!="string")throw new d("Rank request `partitionKey` must be a string",{code:"BAD_REQUEST",status:400});if(typeof t.rowId!="string"||t.rowId.length===0)throw new d("Rank request is missing `rowId`",{code:"BAD_REQUEST",status:400});if(!Array.isArray(t.sortValues))throw new d("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}},Ho=e=>{if(e!==void 0){if(!Array.isArray(e)||e.some(n=>n!=="asc"&&n!=="desc"))throw new d('Rank page request `directions` must be an array of "asc"|"desc"',{code:"BAD_REQUEST",status:400});return e}},Lo=e=>{if(typeof e.table!="string"||e.table.length===0)throw new d("Rank page request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof e.index!="string"||e.index.length===0)throw new d("Rank page request is missing `index`",{code:"BAD_REQUEST",status:400});if(e.partitionKey!==void 0&&typeof e.partitionKey!="string")throw new d("Rank page request `partitionKey` must be a string",{code:"BAD_REQUEST",status:400});if(e.take!==void 0&&(typeof e.take!="number"||!Number.isFinite(e.take)))throw new d("Rank page request `take` must be a number",{code:"BAD_REQUEST",status:400});if(e.cursor!==void 0&&e.cursor!==null&&typeof e.cursor!="string")throw new d("Rank page request `cursor` must be a string or null",{code:"BAD_REQUEST",status:400})},Mo=async e=>{const t=await be(e,"Rank page")??{};Lo(t);const r=Ho(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}},jo=async e=>{const t=await be(e,"Shard-traffic")??{};if(typeof t.table!="string"||t.table.length===0)throw new d("Shard-traffic request is missing `table`",{code:"BAD_REQUEST",status:400});return{table:t.table}},$o=async e=>{const t=await Z(e);if(typeof t.functionPath!="string"||!Co.has(t.functionPath))throw new d("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 d("PITR `shardKey` must be a string",{code:"BAD_REQUEST",status:400});return{args:t.args??{},functionPath:t.functionPath,shardKey:t.shardKey}},Ko=e=>{const{defaultShard:n,forwardToShard:t,isAdmin:r,queryCoordinator:a,resolveForwardContext:s,shardDO:l}=e,u=(w,b)=>{if(w.method!=="POST")throw new d(`${b} endpoint requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});if(!r(w))throw new d("Admin auth required",{code:"FORBIDDEN",status:403});if(!a)throw new d(`${b} endpoint requires a \`queryCoordinator\` on the worker`,{code:"BAD_REQUEST",status:400});return a},f=async(w,b)=>{const _=u(w,"Migration"),p=await Bo(w),{headers:S}=await s(w,b),D=await _.orchestrateMigration(l,{args:p.args,functionPath:p.functionPath,headers:S,table:p.table});return Response.json(D,{headers:{"content-type":"application/json"},status:200})},g=async(w,b)=>{const _=u(w,"Rank"),p=await xo(w),{headers:S}=await s(w,b),D=await _.orchestrateRank(l,{headers:S,index:p.index,partitionKey:p.partitionKey,rowId:p.rowId,sortValues:p.sortValues,table:p.table});return Response.json(D,{headers:{"content-type":"application/json"},status:200})},E=async(w,b)=>{const _=u(w,"Rank page"),p=await Mo(w),{headers:S}=await s(w,b),D=await _.orchestrateRankPage(l,{...p,headers:S});return Response.json(D,{headers:{"content-type":"application/json"},status:200})},k=async(w,b)=>{const _=u(w,"Shard-traffic"),p=await jo(w),{headers:S}=await s(w,b),D=await _.orchestrateShardTraffic(l,{headers:S,table:p.table});return Response.json(D,{headers:{"content-type":"application/json"},status:200})},v=async(w,b)=>{if(j(w,"POST","PITR"),!r(w))throw new d("admin PITR endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403});const _=await $o(w),{headers:p}=await s(w,b),S=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:_.args,functionPath:_.functionPath}),headers:p,method:"POST"});return t(l,_.shardKey??n,S)};return{[ko]:f,[Io]:v,[Po]:g,[Do]:E,[No]:k}},Fo=1,Go=0,Qo=32,zo=512,Wo=/^[a-z][\d_a-z*/-]{0,255}(?:@[a-z][\d_a-z*/-]{0,13})?=[\u0020-\u002B\u002D-\u003C\u003E-\u007E]{1,256}$/,Vo=e=>{if(e==null)return;const n=e.trim();if(n.length===0||n.length>zo)return;const t=n.split(",");if(!(t.length>Qo)){for(const r of t)if(!Wo.test(r.trim()))return;return n}},Jo=e=>{const n=Ln(e.headers.get("traceparent"));if(n===void 0)return;const t=Vo(e.headers.get("tracestate"));return{parentSpanId:n.parentSpanId,sampled:n.sampled,traceId:n.traceId,...t===void 0?{}:{traceState:t}}},qo=(e,n={})=>{const t=Jo(e),r=n.trustInbound===!0?t:void 0,a=Se(8),s=r?.traceId??Se(16),l=or(n.sampling,r===void 0?a:s),u=l.isTraced&&(r===void 0||r.sampled);return{decision:l,ignoredUpstream:t!==void 0&&r===void 0,trace:{sampled:u,spanId:a,traceFlags:u?Fo:Go,traceId:s,...r?.parentSpanId===void 0?{}:{parentSpanId:r.parentSpanId},...r?.traceState===void 0?{}:{traceState:r.traceState}}}},Yo=(e,n)=>{n.traceparent=Hn(e.traceId,e.spanId,e.sampled),e.traceState!==void 0&&(n.tracestate=e.traceState)},Xo=(e,n)=>{let t;return()=>{if(t===void 0){const r=Kn(e),a=n===void 0?void 0:n.cf;t=Mn($n(r),jn(r,a))}return t}},Zo="/_lunora/admin/scheduled",ea="/_lunora/admin/scheduled/status",ta="/_lunora/admin/scheduled/ws",na="/_lunora/admin/scheduled/cancel",ra="/_lunora/admin/scheduled/dead",oa="/_lunora/admin/scheduled/dead/retry",aa="/_lunora/admin/scheduled/dead/cancel",sa=e=>{const{checkWsAdmin:n,requireSchedulerNamespace:t,resolveSchedulerStub:r,schedulerInstanceName:a}=e,s=(f,g)=>E=>{if(E.method!=="GET")throw new d(`${g} endpoint requires GET`,{code:"METHOD_NOT_ALLOWED",status:405});return r(E).fetch(new Request(`https://scheduler.internal${f}`,{method:"GET"}))},l=(f,g,E=g)=>async k=>{if(k.method!=="POST")throw new d(`${E} requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});const v=r(k),w=await k.json().catch(()=>{});if(typeof w?.id!="string"||w.id==="")throw new d(`${g} requires a string \`id\``,{code:"BAD_REQUEST",status:400});return v.fetch(new Request(`https://scheduler.internal${f}`,{body:JSON.stringify({id:w.id}),headers:{"content-type":"application/json"},method:"POST"}))},u=async f=>{if(f.headers.get("Upgrade")!=="websocket")throw new d("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});if(!await n(f))throw new d("admin authorization required",{code:"ADMIN_FORBIDDEN",status:403});const g=t();return we(g,a).fetch(new Request("https://scheduler.internal/ws",{headers:{Upgrade:"websocket"}}))};return{[na]:l("/cancel","Scheduled-cancel","Scheduled-cancel endpoint"),[aa]:l("/dead/cancel","Scheduled dead-letter action"),[ra]:s("/dead","Scheduled dead-letter"),[oa]:l("/dead/retry","Scheduled dead-letter action"),[Zo]:s("/list","Scheduled-list"),[ea]:s("/status","Scheduler-status"),[ta]:u}},ia=(e,...n)=>{let t=e.cf;for(const r of n){if(typeof t!="object"||t===null)return;t=t[r]}return typeof t=="string"?t:void 0},_t={mtls:e=>ia(e,"tlsClientAuth","certVerified")==="SUCCESS"},ca=e=>e===void 0||e===!1?()=>!1:e===!0?()=>!0:typeof e=="function"?e:(Object.hasOwn(_t,e)?_t[e]:void 0)??(()=>!1),da=e=>{if(e!==void 0)return()=>{};let n=!1;return()=>{n||(n=!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.'))}},ua="/_lunora/admin/vector/indexes",la="/_lunora/admin/vector/query",ha=e=>{const{readJsonBody:n,requireAdminOption:t}=e,r=async s=>{j(s,"GET","Vector-indexes");const l=t(s,e.vectorIntrospector,{code:"VECTORS_NOT_CONFIGURED",message:"vector endpoints require a `vectorIntrospector` on the worker"});return Response.json({indexes:await l.listIndexes()},{headers:{"content-type":"application/json"},status:200})},a=async s=>{j(s,"POST","Vector-query");const l=t(s,e.vectorIntrospector,{code:"VECTORS_NOT_CONFIGURED",message:"vector endpoints require a `vectorIntrospector` on the worker"});if(l.queryIndex===void 0)throw new d("vector index querying is not enabled on this worker",{code:"VECTOR_QUERY_UNSUPPORTED",status:400});const f=await n(s);if(typeof f.name!="string"||f.name==="")throw new d("Vector-query request requires a `name` string",{code:"BAD_REQUEST",status:400});if(typeof f.text!="string"||f.text==="")throw new d("Vector-query request requires a `text` string",{code:"BAD_REQUEST",status:400});if(f.topK!==void 0&&(typeof f.topK!="number"||!Number.isInteger(f.topK)||f.topK<1))throw new d("Vector-query `topK` must be a positive integer",{code:"BAD_REQUEST",status:400});const g=await l.queryIndex({name:f.name,text:f.text,topK:f.topK});return Response.json(g,{headers:{"content-type":"application/json"},status:200})};return{[ua]:r,[la]:a}},fa="/_lunora/admin/workflows/instances",pa="/_lunora/admin/workflows/instance",ma="/_lunora/admin/workflows/status",wa={complete:!0,errored:!0,paused:!0,queued:!0,running:!0,terminated:!0,unknown:!0,waiting:!0,waitingForPause:!0},ga=e=>e!==null&&Object.hasOwn(wa,e)?e:void 0,Rt=(e,n)=>{const t=e.searchParams.get(n);if(t===null)return;const r=Number(t);return Number.isInteger(r)&&r>0?r:void 0},$e=(e,n)=>{const t=e.searchParams.get(n);if(t===null||t==="")throw new d(`Workflows admin endpoint requires a \`${n}\` query parameter`,{code:"BAD_REQUEST",status:400});return t},Et=()=>{throw new d("Workflow inspection is unconfigured. Set CLOUDFLARE_ACCOUNT_ID + CLOUDFLARE_API_TOKEN in your .dev.vars to enable it.",{code:"WORKFLOWS_NOT_CONFIGURED",status:501})},ya=e=>{const{assertAdmin:n,resolveWorkflowsClient:t}=e,r=async(l,u,f)=>{j(l,"GET","Workflows instances"),n(l);const g=t(u);if(!g)return Response.json({configured:!1,instances:[],page:1,perPage:0,totalCount:0});const E=$e(f,"name"),k=ga(f.searchParams.get("status"));return Response.json(await g.listInstances({page:Rt(f,"page"),perPage:Rt(f,"perPage"),status:k,workflowName:E}))},a=async(l,u,f)=>{j(l,"GET","Workflows instance"),n(l);const g=t(u);return g?Response.json(await g.getInstance({instanceId:$e(f,"id"),workflowName:$e(f,"name")})):Et()},s=async(l,u)=>{j(l,"POST","Workflows status"),n(l);const f=t(u);if(!f)return Et();const g=await l.json().catch(()=>{});if(typeof g?.name!="string"||g.name===""||typeof g.id!="string"||g.id==="")throw new d("Workflows status action requires string `name` and `id`",{code:"BAD_REQUEST",status:400});const{action:E}=g;if(E!=="pause"&&E!=="resume"&&E!=="terminate")throw new d("Workflows status action must be one of: pause, resume, terminate",{code:"BAD_REQUEST",status:400});return Response.json(await f.setInstanceStatus({action:E,instanceId:g.id,workflowName:g.name}))};return{[pa]:a,[fa]:r,[ma]:s}},ba={[Wt]:Vt,[Yn]:qn},At="/_lunora/rpc",_a="/_lunora/rpc-batch",Ra="/_lunora/ws",Re=(e,n,t)=>({resourceAttributes:Xo(e,n),...t===void 0?{}:{waitUntil:t}}),St=e=>e?.waitUntil?{waitUntil:n=>e.waitUntil?.(n)}:{},Tt=e=>({spanId:e.spanId,traceFlags:e.traceFlags,traceId:e.traceId,...e.parentSpanId===void 0?{}:{parentSpanId:e.parentSpanId}}),Ke=e=>{const{method:n}=e,t=e.headers.get("user-agent")??void 0;let r;try{r=new URL(e.url)}catch{return{method:n,userAgent:t}}const a=r.port===""?void 0:Number(r.port);return{host:r.hostname,method:n,path:r.pathname,port:Number.isNaN(a)?void 0:a,scheme:r.protocol.replace(":",""),userAgent:t}},Ot="/_lunora/voice/",Ea="/_lunora/scheduler/dispatch",Aa="/_lunora/admin/cron-jobs/run",Sa="/_lunora/admin/ws-token",Ta="/_lunora/admin/",Oa="/_lunora/migrate",va="/_lunora/status",ka=e=>e.startsWith(Ta)||e===Oa,Ia=e=>{const n=e.headers.get("x-lunora-userid"),t=e.headers.get("x-lunora-identity");if(!(n===null&&t===null))return{...t===null?{}:{identity:t},...n===null?{}:{userId:n}}},Pa="/api/auth",Da="__lunora_admin__:recordAuthEvent",Na="__lunora_admin__:listPushSubscriptions",Ua=["/sign-in","/sign-up","/callback"],Ca=(e,n)=>{const t=n.endsWith("/")?n.slice(0,-1):n;if(!e.startsWith(`${t}/`))return!1;const r=e.slice(t.length);return Ua.some(a=>r===a||r.startsWith(`${a}/`))},Ee=(e,n,t,r)=>{const a=Nn(t),s=a?t.code:"INTERNAL_SERVER_ERROR",l=a?t.status:500,u=t instanceof Error?t.message:String(t);return{durationMs:n,error:{code:s,message:u,status:l},functionPath:e,ok:!1,...r.fanOut?{fanOut:{failed:0,shards:0,table:r.fanOut.table}}:{},...r.shardKey?{shardKey:r.shardKey}:{}}},Ba=e=>{const{exp:n,expiresAtMs:t}=e;if(typeof t=="number"&&Number.isFinite(t))return t;if(typeof n=="number"&&Number.isFinite(n))return n*1e3},vt=e=>e.waitUntil?{waitUntil:n=>{e.waitUntil?.(n)}}:void 0,xa=e=>{const n=e?.queue;return typeof n=="string"&&n.length>0?n:"unknown"},Ge=new WeakMap,de=async(e,n,t,r=Ge.get(e))=>{const a={"content-type":"application/json"},s=e.headers.get("authorization"),l=e.headers.get("cookie"),u=e.headers.get("x-d1-bookmark"),f=e.headers.get("x-lunora-mutation-id"),g=e.headers.get("x-lunora-client-id"),E=e.headers.get("x-lunora-client-seq");s&&(a.authorization=s),l&&(a.cookie=l),u&&(a["x-d1-bookmark"]=u),f&&(a["x-lunora-mutation-id"]=f),g&&(a["x-lunora-client-id"]=g),E&&(a["x-lunora-client-seq"]=E);const k=e.headers.get("cf-connecting-ip");if(k&&(a["x-lunora-client-ip"]=k),!t)return{claims:null,headers:a,identity:null,userId:null};const v=await t(e,n,r);if(!v||typeof v.userId!="string"||v.userId.length===0)return{claims:null,headers:a,identity:null,userId:null};a["x-lunora-userid"]=Bn(v.userId);const w=Ba(v);w!==void 0&&(a["x-lunora-identity-exp"]=String(w));const{userId:b,..._}=v,p=Object.keys(_).length>0?_:null;return p&&(a["x-lunora-identity"]=xn(p)),{claims:p,headers:a,identity:v,userId:b}},Ha=new Set(["concat","first","groupBy","max","min","rank","sum","topK"]),La=e=>{if(e===void 0)return;if(!e||typeof e!="object")throw new d("RPC `fanOut` must be an object",{code:"BAD_REQUEST",status:400});const n=e;if(typeof n.table!="string"||n.table.length===0)throw new d("RPC `fanOut.table` must be a non-empty string",{code:"BAD_REQUEST",status:400});if(!n.merge||typeof n.merge!="object")throw new d("RPC `fanOut.merge` must be an object",{code:"BAD_REQUEST",status:400});const t=n.merge;if(typeof t.kind!="string"||!Ha.has(t.kind))throw new d("RPC `fanOut.merge.kind` is not a recognized merge strategy",{code:"BAD_REQUEST",status:400});if(t.kind==="topK"){if(typeof t.k!="number"||!Number.isInteger(t.k)||t.k<0)throw new d("RPC `fanOut.merge.k` must be a non-negative integer",{code:"BAD_REQUEST",status:400});if(typeof t.by!="string"||t.by.length===0)throw new d("RPC `fanOut.merge.by` must be a non-empty string",{code:"BAD_REQUEST",status:400})}return n},Ma=(e,n)=>{e?.LUNORA_DEBUG_RPC&&console.warn(`[lunora:rpc] ${n.fanOut?"fan-out":`shard=${n.shardKey??"(root)"}`} ${n.functionPath}`)},kt=(e,n)=>{const t=n.functions?.[e.functionPath]?.x402;if(t){if(e.fanOut)throw new d("a paid (`.x402`) function cannot be fanned out",{code:"BAD_REQUEST",status:400});if(!n.x402Charge)throw new d(`function "${e.functionPath}" is marked paid (.x402) but no x402Charge gate is configured on the worker`,{code:"MISCONFIGURED",status:500});return t}},ja=async e=>{const n=await Bt(e);let t;try{t=JSON.parse(n)}catch{throw new d("RPC body must be valid JSON",{code:"BAD_REQUEST",status:400})}if(!t||typeof t!="object"||typeof t.functionPath!="string")throw new d("RPC envelope is missing `functionPath`",{code:"BAD_REQUEST",status:400});const r=t;if(r.args!==void 0&&Ct(r.args,"RPC"),r.shardKey!==void 0&&typeof r.shardKey!="string")throw new d("RPC `shardKey` must be a string",{code:"BAD_REQUEST",status:400});const a=t,s=La(a.fanOut),l=a.args??{};if(s&&a.functionPath.startsWith("__lunora_relation__:")){const u=l.table;if(typeof u=="string"&&u!==s.table)throw new d("RPC `args.table` must match the authorized `fanOut.table` for a relation fan-out",{code:"BAD_REQUEST",status:400});l.table=s.table}return{args:l,fanOut:s,functionPath:a.functionPath,shardKey:a.shardKey}},Ae=new Map,$a=5e3,Ka=4096,Fa=async(e,n)=>{const t=Date.now(),r=Ae.get(n);if(r!==void 0&&r.expiresMs>t)return r.relayCount;r!==void 0&&Ae.delete(n);let a=0;try{const s=await we(e,n).fetch(new Request("https://shard.internal/_lunora/route"));if(s.ok){const u=(await s.json()).relayCount;typeof u=="number"&&u>0&&(a=Math.floor(u))}}catch{a=0}return Nt(Ae,Ka),Ae.set(n,{expiresMs:t+$a,relayCount:a}),a},It=(e,n)=>{if(!(e===null||typeof e!="object"))return Object.entries(e).find(([,t])=>t===n)?.[0]},ye=(e,n,t)=>new Request("https://shard.internal/rpc",{body:JSON.stringify({args:n,functionPath:e}),headers:t,method:"POST"}),Ga=["x-lunora-userid","x-lunora-identity","x-lunora-identity-exp"],Pt=(e,n)=>{for(const t of Ga){e.delete(t);const r=n[t];r!==void 0&&e.set(t,r)}},Qa=async(e,n,t)=>e.length===0||t.length===0?!1:We(await Mt(e,n),t),Dt=(e,n)=>{if(!n||n.length===0)return!1;const t=e.headers.get("authorization");if(!t)return!1;const[r,...a]=t.split(" ");return r?.toLowerCase()!=="bearer"?!1:We(n,a.join(" ").trim())},za=async(e,n,t)=>{if(!n||n.length===0)return!1;const r=new URL(e.url).searchParams.get("token");return r===null?!1:await kr(n,r)?!0:t?!1:We(n,r)},Wa=(e,n)=>{if(n===null||typeof n!="object"&&typeof n!="function")return;const t=n;if(typeof t.prepare=="function"&&typeof t.batch=="function"&&typeof t.dump=="function")return tr(`d1:${e}`,n);if(typeof t.list=="function"&&typeof t.head=="function"&&typeof t.createMultipartUpload=="function")return Ce(`r2:${e}`,!0);if(typeof t.send=="function"&&typeof t.sendBatch=="function"&&typeof t.get!="function")return Ce(`queue:${e}`,!0);if(typeof t.connectionString=="string")return Ce(`hyperdrive:${e}`,!0)},Jt=e=>{const n=ca(e.trustInboundTraceContext),t=da(e.trustInboundTraceContext),r=e.defaultShardKey??"__root__",a=nr(e.resolveIdentity,e.identity),s=ot(e.shardDO,e.jurisdiction),l=e.schedulerDO===void 0?void 0:ot(e.schedulerDO,e.jurisdiction);let u=!1;const f=o=>{if(o===void 0||e.jurisdiction===void 0)return o;u||(u=!0,console.warn(`[lunora] jurisdiction "${e.jurisdiction}" pins placement, so region hints (\`shardRegion\`, replica and relay placement) are not sent. Residency wins.`))},g=async(o,i,h,c=e.shardRegion?.(i))=>we(o,i,f(c)).fetch(h);let E;const k=()=>e.adminToken??E;let v;const w=()=>e.requireEphemeralWsToken??v??!0;let b;const _=o=>{const i=o??{};if(b??=It(o,e.shardDO),v===void 0&&e.requireEphemeralWsToken===void 0){const c=i.LUNORA_REQUIRE_EPHEMERAL_WS_TOKEN;typeof c=="string"&&c.length>0&&(v=Tr(c,!0))}if(E!==void 0||e.adminToken!==void 0)return;const h=i.LUNORA_ADMIN_TOKEN;typeof h=="string"&&h.length>0&&(E=h)},p=new WeakSet,S=o=>Dt(o,k())||p.has(o),D=async(o,i)=>{const h=await de(o,i,e.resolveIdentity);if(p.has(o)&&h.headers.authorization===void 0){const c=k();c!==void 0&&(h.headers.authorization=`Bearer ${c}`)}return h};let T=!1,x=!1;const H=()=>{x||(x=!0,console.warn("[lunora] `replicaReads: true` has no effect without `functions` — read eligibility is decided from the function registry."))},$=o=>{if(!e.allowUnauthenticatedShardAccess){const i=o==="fan-out"?"authorizeFanOut":"authorizeShard";throw new d(`${o} access is default-denied: configure \`${i}\` on the worker, or set \`allowUnauthenticatedShardAccess: true\` to explicitly allow unauthenticated ${o} access (relying solely on per-row RLS).`,{code:o==="fan-out"?"FORBIDDEN_FANOUT":"FORBIDDEN_SHARD",status:403})}T||(T=!0,console.warn([`[lunora] SECURITY: serving ${o} access with \`allowUnauthenticatedShardAccess: true\` and no \`authorizeShard\`/\`authorizeFanOut\` — `,"any caller (including unauthenticated ones) can target any shard / fan out across the table. ","This is safe only if every table is protected by per-row RLS. Configure `authorizeShard`/`authorizeFanOut` to gate it."].join("")))},U=async(o,i,h=!0)=>{if(e.authorizeShard){if(!await e.authorizeShard(o,i))throw new d("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else h&&i!==r&&$("shard")},W=Ko({defaultShard:r,forwardToShard:g,isAdmin:S,queryCoordinator:e.queryCoordinator,resolveForwardContext:D,shardDO:s}),K=async(o,i,h,c,m)=>{await U(null,h,!1);const R={"content-type":"application/json","x-lunora-system":"1"};return m?.userId!==void 0&&m.userId.length>0&&(R["x-lunora-userid"]=m.userId),m?.identity!==void 0&&m.identity.length>0&&(R["x-lunora-identity"]=m.identity),c!==void 0&&c.length>0&&(R["x-lunora-mutation-id"]=c),g(s,h,ye(o,i,R))},V=async(o,i,h,c)=>{const m=h?.[o];if(!m||typeof m.create!="function")throw new d(`${c} targets workflow binding "${o}", which is not bound on env`,{code:"CRON_JOB_FAILED",status:500});if(cr(i))throw new d(`${c} params ${dr}`,{code:"BAD_REQUEST",status:400});await m.create({params:i})},X=async(o,i)=>{if(o.workflow){await V(o.workflow,o.args??{},i,`cron job "${o.name}"`);return}if(o.functionPath===void 0)throw new d(`cron job "${o.name}" has neither a function target nor a workflow target`,{code:"CRON_JOB_FAILED",status:500});const h=await K(o.functionPath,o.args??{},o.shardKey??r);if(!h.ok)throw new d(`cron job "${o.name}" (${o.functionPath}) failed with shard status ${String(h.status)}`,{code:"CRON_JOB_FAILED",status:500})},J=async(o,i,h,c)=>{const m=e.cronJobs?.[o];if(m)for(const R of m)try{await X(R,i)}catch(I){h.push(c(I))}},ae=async(o,i)=>{if(!S(o))throw new d("admin endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403});if(j(o,"POST","cron-jobs run"),!e.cronJobs)throw new d("cron-jobs run endpoint requires a `cronJobs` map on the worker",{code:"CRON_JOBS_NOT_CONFIGURED",status:400});const h=await Z(o),c=typeof h.name=="string"?h.name:"";if(c==="")throw new d("cron-jobs run endpoint requires a job `name`",{code:"BAD_REQUEST",status:400});const m=Object.values(e.cronJobs).flat().find(R=>R.name===c);if(!m)throw new d(`no cron job named "${c}" is registered`,{code:"CRON_JOB_NOT_FOUND",status:404});return await X(m,i),Response.json({name:c,ran:!0},{status:200})},F=async o=>{const i=typeof o.pool=="string"&&o.pool.length>0?o.pool:void 0;if(!i||!l||typeof o.id!="string")return;const h=typeof o.instanceName=="string"&&o.instanceName.length>0?o.instanceName:"default";try{await we(l,h).fetch(new Request("https://scheduler.internal/complete",{body:JSON.stringify({id:o.id,pool:i}),headers:{"content-type":"application/json"},method:"POST"}))}catch{}},he=async(o,i)=>{j(o,"POST","Scheduler dispatch");const h=await Bt(o),c=i??{},m=typeof c.LUNORA_SCHEDULER_SECRET=="string"?c.LUNORA_SCHEDULER_SECRET:void 0,R=e.adminToken??(typeof c.LUNORA_ADMIN_TOKEN=="string"?c.LUNORA_ADMIN_TOKEN:void 0),I=o.headers.get("x-lunora-scheduler-signature");let y=!1;if(I&&m?y=await Qa(m,h,I):R&&(y=Dt(o,R)),!y)throw new d("Scheduler dispatch requires a valid signature or admin bearer",{code:"FORBIDDEN",status:403});let A;try{A=JSON.parse(h)}catch{throw new d("Scheduler dispatch body must be valid JSON",{code:"BAD_REQUEST",status:400})}const O=A??{},C=O.args??{};if(typeof O.workflow=="string"&&O.workflow.length>0)return await V(O.workflow,C,i,"scheduled workflow"),Response.json({ok:!0},{status:200});if(typeof O.functionPath!="string"||O.functionPath.length===0)throw new d("Scheduler dispatch is missing `functionPath`",{code:"BAD_REQUEST",status:400});const B=typeof O.shardKey=="string"&&O.shardKey.length>0?O.shardKey:r,L=typeof O.id=="string"&&O.id.length>0?O.id:void 0,te=Ia(o),M=await K(O.functionPath,C,B,L,te);return await F(O),M},G=o=>{if(!S(o))throw new d("admin endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403})},oe=(o,i,h)=>{if(G(o),i===void 0)throw new d(h.message,{code:h.code,status:400});return i},Te=Ur({assertAdmin:G,getReader:()=>e.authAuditReader}),Oe=async(o,i)=>{G(o);const h=e.notifySubscriptionStore;if(h===void 0)return Response.json({result:Fe({subscriptions:[]})},{headers:{"content-type":"application/json"},status:200});const c=i?.kind,m=i?.userId,R=i?.limit,I=c==="fcm"||c==="web-push"?c:void 0,y=typeof m=="string"&&m!==""?m:void 0,A=typeof R=="number"&&Number.isFinite(R)?Math.trunc(R):0,O=A>0?Math.min(A,1e3):1e3,B=(await h.list({kind:I,limit:O,userId:y})).filter(L=>I!==void 0&&L.kind!==I?!1:y===void 0||(L.userId??null)===y).map(({keys:L,token:te,...M})=>M);return Response.json({result:Fe({subscriptions:B})},{headers:{"content-type":"application/json"},status:200})},se=async(o,i)=>{if(!i.fanOut){if(i.functionPath===Nr)return Te(o,i.args??{});if(i.functionPath===Na)return Oe(o,i.args)}},qt=io({applyGlobals:e.applyGlobals,assertAdmin:G,exportCursorStore:e.exportCursorStore,exportSinks:e.exportSinks,knownTables:()=>[],queryCoordinator:e.queryCoordinator,requireAdminOption:oe,resolveForwardContext:D,shardDO:s,streamExportRows:(o,i,h,c)=>Gt(e,o,i,h,c,s),streamingImport:(o,i)=>ho(o,e,i,s),syncGlobals:e.syncGlobals}),ve=(o,i)=>{const h=o.searchParams.get(i);return h===null||h===""?void 0:h},ke=o=>{const i=new URL(o.url),h=i.searchParams.get("limit"),c=i.searchParams.get("offset"),m=h===null?void 0:Number.parseInt(h,10),R=c===null?void 0:Number.parseInt(c,10);return{limit:m!==void 0&&Number.isFinite(m)&&m>=0?m:void 0,offset:R!==void 0&&Number.isFinite(R)&&R>=0?R:void 0}},qe=()=>{if(l===void 0)throw new d("scheduled endpoints require a `schedulerDO` namespace on the worker",{code:"SCHEDULER_NOT_CONFIGURED",status:400});return l},Yt=sa({checkWsAdmin:async o=>S(o)||za(o,k(),w()),requireSchedulerNamespace:qe,resolveSchedulerStub:o=>(G(o),we(qe(),e.schedulerInstanceName??"default")),schedulerInstanceName:e.schedulerInstanceName??"default"}),Xt=ya({assertAdmin:G,resolveWorkflowsClient:e.workflowsClient??(()=>{})}),Zt=Jn({assertAdmin:G,parsePaging:ke,queryParameter:ve,readBodyBytes:Gn,requireAdminOption:oe,storage:{storageBuckets:e.storageBuckets,storageDelete:e.storageDelete,storageDownload:e.storageDownload,storageList:e.storageList,storageSignedUrl:e.storageSignedUrl,storageUpload:e.storageUpload}}),en=zr({options:e,readJsonBody:Z,requireAdminOption:oe}),tn=ha({readJsonBody:Z,requireAdminOption:oe,vectorIntrospector:e.vectorIntrospector}),nn=vo({kvIntrospector:e.kvIntrospector,readJsonBody:Z,requireAdminOption:oe}),rn=rr({logArchive:e.logArchive,readJsonBody:Z,requireAdminOption:oe}),on=So({assertAdmin:G,options:{cronJobs:e.cronJobs,functions:e.functions,globalIntrospector:e.globalIntrospector,openApiSpec:e.openApiSpec,openRpcSpec:e.openRpcSpec},parsePaging:ke,queryParameter:ve,requireAdminOption:oe}),an=o=>{const i=[],h=s??o?.SHARD;if(h!==void 0&&i.push(er("durable-object:default",h,r)),e.health?.disableBindingProbes!==!0)for(const[c,m]of Object.entries(o??{})){const R=Wa(c,m);R!==void 0&&i.push(R)}for(const c of e.health?.probes??[])i.push(c);return i},sn=Zn({appName:e.health?.appName,appVersion:e.health?.appVersion,auth:e.health?.auth??"public",cacheTtlMs:e.health?.cacheTtlMs,isAdmin:S,resolveProbes:an}),cn=o=>{const i=e.schedulerInstanceName??"default",h=()=>we(o,i),c=async(y,A)=>{const O=await h().fetch(new Request(`https://scheduler.internal${y}`,A));if(!O.ok)throw new d(`ctx.scheduler: SchedulerDO ${y} failed (${String(O.status)}): ${await O.text()}`,{code:"INTERNAL",status:500});return await O.json()},m=async(y,A)=>await c(y,{body:JSON.stringify(A),headers:{"content-type":"application/json"},method:"POST"}),R=y=>{const A=y;if(A==null)throw new d("ctx.scheduler: target is required — pass a reference from the generated `internal` / `workflows` / `agents`",{code:"BAD_REQUEST",status:400});if(typeof A.binding=="string"&&A.binding.length>0)return{workflow:A.binding};if(typeof A.__lunoraRef=="string")return{functionPath:A.__lunoraRef};throw new d("ctx.scheduler: expected a reference from the generated `internal` / `workflows` / `agents` — a bare function-path string is refused here, because an HTTP action can be reached unauthenticated",{code:"BAD_REQUEST",status:400})},I=async(y,A,O={})=>{const{id:C}=await m("/schedule",{args:O,scheduledFor:y,...R(A)});return C};return{cancel:async y=>await m("/cancel",{id:y}),get:async y=>await c(`/get?id=${encodeURIComponent(y)}`,{method:"GET"}),list:async()=>await c("/list",{method:"GET"}),runAfter:async(y,A,O)=>{if(!Number.isFinite(y)||y<0)throw new d("ctx.scheduler.runAfter: `delayMs` must be a non-negative finite number",{code:"BAD_REQUEST",status:400});return await I(Date.now()+y,A,O)},runAt:async(y,A,O)=>{if(!Number.isFinite(y))throw new d("ctx.scheduler.runAt: `timestampMs` must be a finite epoch-millisecond number",{code:"BAD_REQUEST",status:400});return await I(y,A,O)}}},dn=async(o,i,h)=>{const{claims:c,headers:m,userId:R}=await de(o,i,a),I=async(y,A={})=>{const O=y.__lunoraRef;if(typeof O!="string")throw new d("ctx.run*: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});const C=ye(O,A,{...m,"x-lunora-system":"1"}),B=await g(s,r,C),L=await B.json();if(L.error)throw new d(L.error.message??"shard RPC failed",{code:L.error.code??"INTERNAL",status:B.status});return L.result};return{auth:{getIdentity:()=>Promise.resolve(c),userId:R},cache:h.cache,fetch:globalThis.fetch.bind(globalThis),runAction:I,runMutation:I,runQuery:I,...l===void 0?{}:{scheduler:cn(l)},...e.storage===void 0?{}:{storage:ir(e.storage(i))}}},un=async(o,i,h)=>{if(!e.httpRouter)return;const c=await dn(o,i,h);try{return await e.httpRouter.fetch(o,{...i,__lunoraCtx:c},h)}catch(m){return console.error("[lunora] httpRouter (SSR) handler threw:",m),new Response("Internal Server Error",{status:500})}},ln=async(o,i,h)=>{if(o.headers.get("Upgrade")!=="websocket")throw new d("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});const c=st(o,ie);if(c)return c;const m=h.searchParams.get("shard")??r,{headers:R,identity:I}=await de(o,i,a);await U(I,m);const y=new Headers(o.headers),A=[...y.keys()];for(const C of A)C.startsWith("x-lunora-")&&y.delete(C);Pt(y,R);const O=It(i,e.shardDO);if(O!==void 0){y.set("x-lunora-shard-binding",O);const C=await Fa(s,m);if(C>0){const B=_r(m,Math.floor(Math.random()*C));return g(s,B,new Request(o,{headers:y}),it(o))}}return g(s,m,new Request(o,{headers:y}))},hn=async(o,i,h)=>{const{voiceAgents:c}=e;if(c===void 0)return new Response("Not found",{status:404});if(o.headers.get("Upgrade")!=="websocket")return new Response("Expected a WebSocket upgrade",{headers:{allow:"GET"},status:426});const m=st(o,ie);if(m)return m;let R;try{R=decodeURIComponent(h.pathname.slice(Ot.length))}catch{return new Response("Unknown voice agent",{status:404})}const I=Object.hasOwn(c,R)?c[R]:void 0;if(I===void 0)return new Response("Unknown voice agent",{status:404});const y=h.searchParams.get("threadKey");if(y===null||y.length===0)return new Response("Missing threadKey",{status:400});const{headers:A,identity:O}=await de(o,i,a);if(e.authorizeShard){if(!await e.authorizeShard(O,y))return new Response("Forbidden",{status:403})}else $("shard");const C=new Headers(o.headers);for(const B of C.keys())B.startsWith("x-lunora-")&&C.delete(B);return Pt(C,A),g(I,y,new Request(o,{headers:C}))},fn=async(o,i,h)=>{if(e.authorizeFanOut){if(!await e.authorizeFanOut(h,o.table,i))throw new d("Forbidden fan-out",{code:"FORBIDDEN_FANOUT",status:403});return}if(i.startsWith("__lunora_relation__:"))throw new d("reverse cross-backend relation reads (`__lunora_relation__:*`) require `authorizeFanOut` to be configured on the worker",{code:"FORBIDDEN_FANOUT",status:403});if(e.authorizeShard)throw new d("Fan-out requires `authorizeFanOut` to be configured on the worker when `authorizeShard` is set",{code:"FORBIDDEN_FANOUT",status:403});$("fan-out")},_e=async(o,i)=>{if(!(!o.fanOut&&o.functionPath.startsWith("__lunora_admin__:"))){if(o.fanOut){await fn(o.fanOut,o.functionPath,i);return}await U(i,o.shardKey??r)}},pn=(o,i,h)=>{if(e.replicaReads!==!0)return;if(e.functions===void 0){H();return}if(e.functions[i]?.kind!=="query"||h.includes($t)||h.includes(jt))return;const c=it(o);return c===void 0?void 0:{name:Rr(h,c),region:c}},mn=async(o,i,h,c,m)=>{const R=pn(o,i,c);if(R!==void 0){const I={...m,"x-lunora-replica-read":"1",...b===void 0?{}:{"x-lunora-shard-binding":b}},y=Er(o.headers.get("x-lunora-min-seq"));y!==void 0&&(I["x-lunora-min-seq"]=String(y));const A=await g(s,R.name,ye(i,h,I),R.region);if(A.status!==421)return A}return g(s,c,ye(i,h,m))},Ie=async(o,i,h,c,m,R)=>{const I=Date.now(),{observability:y,sampling:A}=e,O=Ke(o),{decision:C,ignoredUpstream:B,trace:L}=qo(o,{...A===void 0?{}:{sampling:A},trustInbound:n(o)});B&&t();const te={...m,"x-lunora-sample-errors":C.keepErrors?"1":"0"};Yo(L,te);try{const M=await mn(o,i,h,c,te);ce(y,{...O,...Tt(L),durationMs:Date.now()-I,functionPath:i,ok:M.ok,shardKey:c,...M.ok?{}:{error:{code:"SHARD_ERROR",message:`shard returned ${String(M.status)}`,status:M.status}}},R,void 0,{isTraced:L.sampled,keepErrors:C.keepErrors});const ee=new Response(M.body,{headers:M.headers,status:M.status,statusText:M.statusText});return ee.headers.set("x-lunora-shard-key",c),ee}catch(M){throw ce(y,{...O,...Tt(L),...Ee(i,Date.now()-I,M,{shardKey:c})},R,void 0,{isTraced:L.sampled,keepErrors:C.keepErrors}),M}},wn=o=>{if(o.fanOut&&o.shardKey)throw new d("RPC envelope cannot set both `shardKey` and `fanOut`",{code:"BAD_REQUEST",status:400});if(!o.fanOut&&o.functionPath.startsWith("__lunora_relation__:"))throw new d("`__lunora_relation__:*` is a fan-out-only reserved RPC and cannot be dispatched to a single shard",{code:"FORBIDDEN",status:403});if(o.fanOut&&!e.queryCoordinator)throw new d("RPC envelope set `fanOut` but no `queryCoordinator` is configured on the worker",{code:"BAD_REQUEST",status:400})},gn=async(o,i,h)=>{j(o,"POST","RPC");const c=await ja(o);Ma(i,c),wn(c);const m=await se(o,c);if(m!==void 0)return m;const{headers:R,identity:I}=await de(o,i,a);await _e(c,I);const y=kt(c,e);{const A=Date.now(),{observability:O}=e,C=Ke(o),B=Re(i,o,h&&(M=>h.waitUntil?.(M)));if(c.fanOut){const M=e.queryCoordinator;if(!M)throw new d("RPC envelope set `fanOut` but no `queryCoordinator` is configured on the worker",{code:"BAD_REQUEST",status:400});try{const ee=await M.fanOut(s,{args:c.args??{},fanOut:c.fanOut,functionPath:c.functionPath,headers:R});return ce(O,{durationMs:Date.now()-A,fanOut:{failed:ee.failed,shards:ee.ok+ee.failed,table:c.fanOut.table},functionPath:c.functionPath,...C,ok:!0},B),Response.json(ee,{headers:{"content-type":"application/json"},status:200})}catch(ee){throw ce(O,{...Ee(c.functionPath,Date.now()-A,ee,{fanOut:{table:c.fanOut.table}}),...C},B),ee}}const L=c.shardKey??r,te=()=>Ie(o,c.functionPath,c.args??{},L,R,B);return y&&e.x402Charge?e.x402Charge(o,{functionPath:c.functionPath,price:y.price},te,St(h)):te()}},yn=async(o,i,h)=>{j(o,"POST","RPC batch");const c=await Z(o),{calls:m}=c;if(!Array.isArray(m))throw new d("RPC batch `calls` must be an array",{code:"BAD_REQUEST",status:400});const{headers:R,identity:I}=await de(o,i,a),y=Vr(m,r);for(const Q of y.values())for(const z of Q)if(e.functions?.[z.functionPath]?.x402)throw new d(`paid (\`.x402\`) function "${z.functionPath}" cannot be called in a batch; dispatch it individually over ${At}`,{code:"BAD_REQUEST",status:400});await Promise.all([...y.entries()].flatMap(([Q,z])=>z.map(ne=>_e({args:ne.args,functionPath:ne.functionPath,shardKey:Q},I))));const{observability:A}=e,O=Re(i,o,h&&(Q=>h.waitUntil?.(Q))),C=Ke(o),B=[],L=[],te=(Q,z,ne,ue)=>({body:{error:{code:ne,message:ue}},id:Q.id,status:z}),M=(Q,z,ne,ue,fe)=>{for(const q of Q)ce(A,fe(q),O),B.push(te(q,z,ne,ue))},ee=(Q,z,ne,ue,fe)=>{for(const q of Q){const pe=ue.get(q.id)??fe,ge=pe<400;ce(A,{durationMs:ne,functionPath:q.functionPath,...C,ok:ge,shardKey:z,...ge?{}:{error:{code:"SHARD_ERROR",message:`batched call returned ${String(pe)}`,status:pe}}},O)}};await Promise.all([...y.entries()].map(async([Q,z])=>{const ne=new Headers(R);ne.set("content-type","application/json");const ue=new Request("https://shard.internal/rpc-batch",{body:JSON.stringify({calls:z}),headers:ne,method:"POST"}),fe=Date.now();let q;try{q=await g(s,Q,ue)}catch(Y){const Ue=Date.now()-fe,{body:tt}=Un(Y,{fallbackCode:"SHARD_UNAVAILABLE",redactedMessage:"shard unavailable"});M(z,502,tt.code,tt.message,Dn=>({...Ee(Dn.functionPath,Ue,Y,{shardKey:Q}),...C}));return}const pe=Date.now()-fe,ge=q.headers.get("x-d1-bookmark");ge&&L.push(ge);let De;try{De=await q.json()}catch{const Y=`shard batch returned a non-JSON response (${String(q.status)})`;M(z,q.status,"SHARD_ERROR",Y,Ue=>({durationMs:pe,error:{code:"SHARD_ERROR",message:Y,status:q.status},functionPath:Ue.functionPath,...C,ok:!1,shardKey:Q}));return}const Ne=Array.isArray(De.results)?De.results:[],In=new Map(Ne.map(Y=>[Y.id,Y.status??q.status])),Pn=new Set(Ne.map(Y=>Y.id));ee(z,Q,pe,In,q.status),B.push(...Ne);for(const Y of z)Pn.has(Y.id)||B.push(te(Y,q.status,"SHARD_ERROR",`shard batch omitted result for call ${String(Y.id)}`))}));const Ze={"content-type":"application/json"},[et]=L;return L.length===1&&et!==void 0&&(Ze["x-d1-bookmark"]=et),Response.json({results:B},{headers:Ze,status:200})},bn=async(o,i,h,c={},m={})=>{try{const R=h.__lunoraRef;if(typeof R!="string")throw new d("serverQuery: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});const{headers:I,identity:y}=await de(o,i,a,m.context);await _e({args:c,functionPath:R,shardKey:m.shardKey},y);const A=m.shardKey??r,O=Re(i,o,m.waitUntil);return await Ie(o,R,c,A,I,O)}catch(R){return nt(R)}},Ye=async(o,i,h)=>{const{observability:c}=e,m=Date.now(),R=Se(16),I=Se(8),y=vt(i);try{const A=await h();return ce(c,{durationMs:Date.now()-m,functionPath:o,ok:!0,spanId:I,traceId:R},y),A}catch(A){throw ce(c,{...Ee(o,Date.now()-m,A,{}),spanId:I,traceId:R},y),A}finally{rt(c,y)}},_n=async(o,i,h)=>{_(i);const c=[],m=y=>y instanceof Error?y:new Error(String(y)),R=e.crons?.[o.cron];if(R)try{await R(o,i,h)}catch(y){c.push(m(y))}if(await J(o.cron,i,c,m),e.backupStore&&e.backupCron!==void 0&&e.backupCron===o.cron)try{await Kr(e,s,k(),o)}catch(y){c.push(m(y))}const[I]=c;if(c.length===1&&I)throw I;if(c.length>1)throw new AggregateError(c,`scheduled("${o.cron}") had ${String(c.length)} failure(s)`)},Rn=async(o,i)=>{try{const h=o??{},c=e.adminToken??(typeof h.LUNORA_ADMIN_TOKEN=="string"?h.LUNORA_ADMIN_TOKEN:void 0);if(!c||c.length===0)return;await g(s,r,ye(Da,{outcome:i},{authorization:`Bearer ${c}`,"content-type":"application/json"}))}catch{}},En=async(o,i,h,c)=>{if(!e.authHandler)return;const m=await e.authHandler(o);if(!m)return;const R=e.authBasePath??Pa;return Ca(h.pathname,R)&&c.waitUntil?.(Rn(i,m.status>=400?"fail":"ok")),m},An=async({args:o,env:i,functionPath:h,request:c,shardKey:m,waitUntil:R})=>{Ct(o,"REST");const I={functionPath:h,...m===void 0?{}:{shardKey:m}},{headers:y,identity:A}=await de(c,i,a);await _e(I,A);const O=m??r,C=Re(i,c,R),B=()=>Ie(c,h,o,O,y,C),L=kt(I,e);return L&&e.x402Charge?e.x402Charge(c,{functionPath:h,price:L.price},B,St({waitUntil:R})):B()},Sn=Fn({functions:e.functions??{},invoke:An,readJsonBody:Z,...e.restRateLimit?{rateLimit:e.restRateLimit}:{}}),Pe=e.routes!==void 0&&Object.keys(e.routes).length>0?e.routes:void 0,Tn={[va]:o=>o.method!=="GET"&&o.method!=="HEAD"?new Response(void 0,{headers:{allow:"GET, HEAD"},status:405}):Response.json({ok:!0},{headers:{"cache-control":"no-store"}}),[Ra]:(o,i,h)=>ln(o,i,h),[At]:(o,i,h,c)=>gn(o,i,c),[_a]:(o,i,h,c)=>yn(o,i,c),[Ea]:(o,i)=>he(o,i),[Aa]:(o,i)=>ae(o,i),[Sa]:async o=>{j(o,"POST","ws-token"),G(o);const i=k();if(i===void 0)throw new d("ws-token minting requires a configured admin token",{code:"ADMIN_TOKEN_NOT_CONFIGURED",status:400});const h=await vr(i);return Response.json(h,{headers:{"cache-control":"no-store"}})},...W,...qt,...Yt,...Xt,...Zt,...en,...tn,...nn,...rn,...on,...sn,...Sn,...Dr({assertAdmin:G,getAuthAdmin:()=>e.authAdmin,parsePaging:ke,queryParameter:ve,readJsonBody:Z})};let ie=at(e.security),Xe=!1;const On=o=>{Xe||(Xe=!0,ie=at(e.security,o??{}))},vn=async(o,i)=>{if(!(e.adminGate===void 0||!ka(i)))try{await e.adminGate(o,Ge.get(o))&&p.add(o)}catch{}},kn=async(o,i,h)=>{Ge.set(o,h);const c=new URL(o.url);if(o.method==="POST"||o.method==="PUT"){const y=Number(o.headers.get("content-length")??""),A=ba[c.pathname]??Ut;if(Number.isFinite(y)&&y>A)throw new d("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413})}const m=await En(o,i,c,h);if(m)return m;if(Pe){const y=`${o.method} ${c.pathname}`,A=Pe[y]??Pe[c.pathname];if(A)return A(o,i,h)}const R=Tn[c.pathname];if(R)return await vn(o,c.pathname),R(o,i,c,h);if(e.voiceAgents!==void 0&&c.pathname.startsWith(Ot))return hn(o,i,c);const I=await un(o,i,h);return I||new Response("Not found",{status:404})};return{async fetch(o,i,h){e.passThroughOnException&&h.passThroughOnException?.(),On(i),_(i);const c=ar(o,ie);if(c)return c;const m=sr(o,ie);if(m)return Be(m,o,ie);try{const R=await kn(o,i,h);return Be(R,o,ie)}catch(R){return Be(nt(R),o,ie)}finally{rt(e.observability,vt(h))}},async queue(o,i,h){await Ye(`queue:${xa(o)}`,h,async()=>{await e.queue?.(o,i,h)})},async scheduled(o,i,h){await Ye(`cron:${o.cron}`,h,async()=>{await _n(o,i,h)})},serverQuery:bn}},Va=e=>Jt(e),Ja=e=>typeof e=="function"?{fetch:e}:e,qa=e=>!!(e.crons??e.cronJobs??e.backupCron),gs=(e,n)=>{const t=Ja(e),r=typeof e=="object"&&typeof e.scheduled=="function"?e.scheduled:void 0,a=l=>{const u=Va({...l,httpRouter:t});return r!==void 0&&!qa(l)?{...u,scheduled:async(f,g,E)=>{await r(f,g,E)}}:u};if(typeof n!="function")return a(n);const s=n;return{fetch:(l,u,f)=>a(s(u)).fetch(l,u,f),queue:(l,u,f)=>a(s(u)).queue?.(l,u,f)??Promise.resolve(),scheduled:(l,u,f)=>a(s(u)).scheduled(l,u,f),serverQuery:(l,u,f,g,E)=>a(s(u)).serverQuery(l,u,f,g,E)}},Ya=(e,n)=>{if(typeof e=="function")return e(n);const t=e.shardDO??n?.SHARD;if(!t)throw new d("@lunora/runtime: no shard Durable Object namespace found. Bind `SHARD` in wrangler.jsonc, or pass `createLunoraHandler({ shardDO: env.MY_SHARD })`.");return{...e,shardDO:t}},ys=(e={})=>(n,t,r)=>Jt(Ya(e,t)).fetch(n,t,r??Cn),bs=e=>e;export{Nr as GET_AUTH_AUDIT_LOG_OP,Cn as NOOP_EXECUTION_CONTEXT,Es as composeIdentityResolvers,Va as composeWorker,ys as createLunoraHandler,Jt as createWorker,bs as defineRpcEnvelope,Fa as probeRelayCount,Ya as resolveLunoraOptions,As as routeIdentityResolvers,gs as withFrameworkWorker};
|
|
6
|
+
`)}}return E.length>0&&v(E),{errors:r,globalRows:a,perShard:s,received:l}},wt=(e,n)=>{for(const[t,r]of Object.entries(n.inserted))e.inserted[t]=(e.inserted[t]??0)+r;for(const t of n.errors)e.errors.push({...t});e.conflicts+=n.conflicts},fo=async(e,n,t,r)=>{const a=n.defaultShardKey??"__root__",{errors:s,globalRows:l,perShard:u,received:f}=await ho(e,n,a),g={conflicts:0,errors:s,inserted:{}},E=[];if(n.resolveTableSharding===void 0&&u.size>0&&E.push("no `resolveTableSharding` is configured, so every row was routed to the default shard and no row could be recognised as `.global()` — correct for a single-shard app, silent misplacement for a sharded one"),u.size>0){const k=n.queryCoordinator;if(!k)throw new d("Import endpoint requires a `queryCoordinator` on the worker",{code:"BAD_REQUEST",status:400});const v=await k.orchestrateImport(r,{batches:[...u.values()],headers:t});wt(g,v)}if(l.length>0)if(n.importGlobals){const k=l[0]?.line??1,v=await n.importGlobals({rows:l,startLine:k});wt(g,v)}else for(const k of l)g.errors.push({code:"GLOBAL_NOT_CONFIGURED",line:k.line,message:`row targets global table "${k.table}" but no \`importGlobals\` is configured`,table:k.table});return{conflicts:g.conflicts,errors:g.errors,inserted:g.inserted,received:f,...E.length>0?{warnings:E}:{}}},Le=e=>typeof e=="object"&&e!==null?e:{},Me=e=>typeof e.kind=="string"?e.kind:"unknown",po=(e,n)=>{let t=Le(n),r=!1;Me(t)==="optional"&&(r=!0,t=Le(t._meta?.inner));const a=Me(t),s=t._meta??{},l={kind:a,name:e,optional:r};if(a==="id"&&typeof s.tableName=="string"&&(l.table=s.tableName),a==="array"){const u=Me(Le(s.inner));u!=="unknown"&&(l.element=u)}return l},mo=e=>typeof e!="object"||e===null?[]:Object.entries(e).map(([n,t])=>po(n,t)).toSorted((n,t)=>n.name.localeCompare(t.name)),wo="/_lunora/admin/functions",go="/_lunora/admin/cron-jobs",yo="/_lunora/admin/openapi",bo="/_lunora/admin/openrpc",_o="/_lunora/admin/global/tables",Ro="/_lunora/admin/global/table",Eo="/_lunora/admin/global/facet",gt=e=>{if(e===void 0||e==="")return;let n;try{n=JSON.parse(e)}catch{return}if(!Array.isArray(n))return;const t=n.flatMap(r=>{if(typeof r!="object"||r===null||typeof r.column!="string")return[];const{column:a,value:s}=r;return[{column:a,value:s}]});return t.length===0?void 0:t},Ao=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:{}}),So=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"}),To=e=>{const{assertAdmin:n,options:t,parsePaging:r,queryParameter:a,requireAdminOption:s}=e,l=w=>{j(w,"GET","Functions");const b=s(w,t.functions,{code:"FUNCTIONS_NOT_CONFIGURED",message:"functions endpoint requires a `functions` registry on the worker"}),_=Object.entries(b).flatMap(([p,S])=>S.visibility==="internal"||S.kind==="stream"?[]:[{args:mo(S.args),kind:S.kind,path:p}]).toSorted((p,S)=>p.path.localeCompare(S.path));return Response.json({functions:_},{headers:{"content-type":"application/json"},status:200})},u=w=>{j(w,"GET","Cron-jobs");const b=s(w,t.cronJobs,{code:"CRON_JOBS_NOT_CONFIGURED",message:"cron-jobs endpoint requires a `cronJobs` map on the worker"}),_=Object.entries(b).flatMap(([p,S])=>S.map(D=>({args:D.args,cron:p,functionPath:D.functionPath,name:D.name,shardKey:D.shardKey,workflow:D.workflow}))).toSorted((p,S)=>p.name.localeCompare(S.name));return Response.json({jobs:_},{headers:{"content-type":"application/json"},status:200})},f=w=>(j(w,"GET","OpenAPI"),n(w),Response.json(t.openApiSpec??Ao,{headers:{"content-type":"application/json"},status:200})),g=w=>(j(w,"GET","OpenRPC"),n(w),Response.json(t.openRpcSpec??So,{headers:{"content-type":"application/json"},status:200})),E=async w=>{j(w,"GET","Global-tables");const b=s(w,t.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"});return Response.json(await b.listTables(),{headers:{"content-type":"application/json"},status:200})},k=async w=>{j(w,"GET","Global-table");const b=s(w,t.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),_=new URL(w.url),p=a(_,"table");if(p===void 0)throw new d("Global-table endpoint requires a `table` query param",{code:"BAD_REQUEST",status:400});const S=await b.readTablePage({...r(w),filters:gt(a(_,"filters")),table:p});return Response.json(S,{headers:{"content-type":"application/json"},status:200})},v=async w=>{j(w,"GET","Global-facet");const b=s(w,t.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),_=new URL(w.url),p=a(_,"table"),S=a(_,"column");if(p===void 0||S===void 0)throw new d("Global-facet endpoint requires `table` and `column` query params",{code:"BAD_REQUEST",status:400});const D=a(_,"limit"),T=D===void 0?void 0:Number(D),x=await b.facetColumn({column:S,filters:gt(a(_,"filters")),limit:T!==void 0&&Number.isFinite(T)?T:void 0,table:p});return Response.json(x,{headers:{"content-type":"application/json"},status:200})};return{[go]:u,[wo]:l,[Eo]:v,[Ro]:k,[_o]:E,[yo]:f,[bo]:g}},Oo="/_lunora/admin/kv/namespaces",vo="/_lunora/admin/kv/keys",zt="/_lunora/admin/kv/value",Wt=32*1048576,yt=60,ko=e=>{const{readJsonBody:n,requireAdminOption:t}=e,r=b=>t(b,e.kvIntrospector,{code:"KV_NOT_CONFIGURED",message:"KV endpoints require a `kvIntrospector` on the worker"}),a=b=>Response.json(b,{headers:{"content-type":"application/json"},status:200}),s=(b,_)=>{const p=new URL(b.url),S=p.searchParams.get("namespace")??"",D=p.searchParams.get("key")??"";if(S==="")throw new d(`KV-value ${_} request requires a \`namespace\` query parameter`,{code:"BAD_REQUEST",status:400});if(D==="")throw new d(`KV-value ${_} request requires a \`key\` query parameter`,{code:"BAD_REQUEST",status:400});return{key:D,namespace:S}},l=async(b,_)=>{if(!(await b.listNamespaces()).some(S=>S.binding===_))throw new d(`Unknown KV namespace binding \`${_}\``,{code:"NOT_FOUND",status:404})},u=async b=>(j(b,"GET","KV-namespaces"),a({namespaces:await r(b).listNamespaces()})),f=async b=>{j(b,"GET","KV-keys");const _=r(b),p=new URL(b.url),S=p.searchParams.get("namespace")??"";if(S==="")throw new d("KV-keys request requires a `namespace` query parameter",{code:"BAD_REQUEST",status:400});const D=p.searchParams.get("prefix")??void 0,T=p.searchParams.get("cursor")??void 0,x=p.searchParams.get("limit"),H=x===null?void 0:Number.parseInt(x,10);if(H!==void 0&&(!Number.isInteger(H)||H<1))throw new d("KV-keys `limit` must be a positive integer",{code:"BAD_REQUEST",status:400});const $=H===void 0?void 0:Math.min(H,1e3);return await l(_,S),a(await _.listKeys({cursor:T,limit:$,namespace:S,prefix:D}))},v={DELETE:async b=>{const _=r(b),p=s(b,"DELETE");return await l(_,p.namespace),await _.deleteKey(p),a({deleted:!0})},GET:async b=>{const _=r(b),p=s(b,"GET");return await l(_,p.namespace),a(await _.getValue(p))},PUT:async b=>{const _=r(b),p=await n(b,Wt);if(typeof p.namespace!="string"||p.namespace==="")throw new d("KV-value PUT request requires a `namespace` string",{code:"BAD_REQUEST",status:400});if(typeof p.key!="string"||p.key==="")throw new d("KV-value PUT request requires a `key` string",{code:"BAD_REQUEST",status:400});if(typeof p.value!="string")throw new d("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<yt))throw new d("KV-value PUT `expirationTtl` must be an integer ≥ 60",{code:"BAD_REQUEST",status:400});const S=Math.floor(Date.now()/1e3)+yt;if(p.expiration!==void 0&&(typeof p.expiration!="number"||!Number.isInteger(p.expiration)||p.expiration<S))throw new d("KV-value PUT `expiration` must be a Unix-seconds timestamp at least 60 seconds in the future",{code:"BAD_REQUEST",status:400});return await l(_,p.namespace),await _.putValue({expiration:p.expiration,expirationTtl:p.expirationTtl,key:p.key,metadata:p.metadata,namespace:p.namespace,value:p.value}),a({ok:!0})}},w=b=>{const _=v[b.method];if(!_)throw new d("KV-value endpoint requires GET, PUT, or DELETE",{code:"METHOD_NOT_ALLOWED",status:405});return _(b)};return{[Oo]:u,[vo]:f,[zt]:w}},Io="/_lunora/migrate",Po="/_lunora/admin/pitr",Do="/_lunora/admin/rank",No="/_lunora/admin/rankpage",Uo="/_lunora/admin/shard-traffic",Co=new Set(["__lunora_admin__:migrationStatus","__lunora_admin__:runMigration"]),Bo=new Set(["__lunora_admin__:getPitrBookmark","__lunora_admin__:pitrRestore"]),xo=async e=>{const t=await be(e,"Migration")??{};if(typeof t.table!="string"||t.table.length===0)throw new d("Migration request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof t.functionPath!="string"||!Co.has(t.functionPath))throw new d("Migration request `functionPath` must be a migration admin op",{code:"BAD_REQUEST",status:400});return{args:t.args??{},functionPath:t.functionPath,table:t.table}},Ho=async e=>{const t=await be(e,"Rank")??{};if(typeof t.table!="string"||t.table.length===0)throw new d("Rank request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof t.index!="string"||t.index.length===0)throw new d("Rank request is missing `index`",{code:"BAD_REQUEST",status:400});if(typeof t.partitionKey!="string")throw new d("Rank request `partitionKey` must be a string",{code:"BAD_REQUEST",status:400});if(typeof t.rowId!="string"||t.rowId.length===0)throw new d("Rank request is missing `rowId`",{code:"BAD_REQUEST",status:400});if(!Array.isArray(t.sortValues))throw new d("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}},Lo=e=>{if(e!==void 0){if(!Array.isArray(e)||e.some(n=>n!=="asc"&&n!=="desc"))throw new d('Rank page request `directions` must be an array of "asc"|"desc"',{code:"BAD_REQUEST",status:400});return e}},Mo=e=>{if(typeof e.table!="string"||e.table.length===0)throw new d("Rank page request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof e.index!="string"||e.index.length===0)throw new d("Rank page request is missing `index`",{code:"BAD_REQUEST",status:400});if(e.partitionKey!==void 0&&typeof e.partitionKey!="string")throw new d("Rank page request `partitionKey` must be a string",{code:"BAD_REQUEST",status:400});if(e.take!==void 0&&(typeof e.take!="number"||!Number.isFinite(e.take)))throw new d("Rank page request `take` must be a number",{code:"BAD_REQUEST",status:400});if(e.cursor!==void 0&&e.cursor!==null&&typeof e.cursor!="string")throw new d("Rank page request `cursor` must be a string or null",{code:"BAD_REQUEST",status:400})},jo=async e=>{const t=await be(e,"Rank page")??{};Mo(t);const r=Lo(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}},$o=async e=>{const t=await be(e,"Shard-traffic")??{};if(typeof t.table!="string"||t.table.length===0)throw new d("Shard-traffic request is missing `table`",{code:"BAD_REQUEST",status:400});return{table:t.table}},Ko=async e=>{const t=await Z(e);if(typeof t.functionPath!="string"||!Bo.has(t.functionPath))throw new d("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 d("PITR `shardKey` must be a string",{code:"BAD_REQUEST",status:400});return{args:t.args??{},functionPath:t.functionPath,shardKey:t.shardKey}},Fo=e=>{const{defaultShard:n,forwardToShard:t,isAdmin:r,queryCoordinator:a,resolveForwardContext:s,shardDO:l}=e,u=(w,b)=>{if(w.method!=="POST")throw new d(`${b} endpoint requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});if(!r(w))throw new d("Admin auth required",{code:"FORBIDDEN",status:403});if(!a)throw new d(`${b} endpoint requires a \`queryCoordinator\` on the worker`,{code:"BAD_REQUEST",status:400});return a},f=async(w,b)=>{const _=u(w,"Migration"),p=await xo(w),{headers:S}=await s(w,b),D=await _.orchestrateMigration(l,{args:p.args,functionPath:p.functionPath,headers:S,table:p.table});return Response.json(D,{headers:{"content-type":"application/json"},status:200})},g=async(w,b)=>{const _=u(w,"Rank"),p=await Ho(w),{headers:S}=await s(w,b),D=await _.orchestrateRank(l,{headers:S,index:p.index,partitionKey:p.partitionKey,rowId:p.rowId,sortValues:p.sortValues,table:p.table});return Response.json(D,{headers:{"content-type":"application/json"},status:200})},E=async(w,b)=>{const _=u(w,"Rank page"),p=await jo(w),{headers:S}=await s(w,b),D=await _.orchestrateRankPage(l,{...p,headers:S});return Response.json(D,{headers:{"content-type":"application/json"},status:200})},k=async(w,b)=>{const _=u(w,"Shard-traffic"),p=await $o(w),{headers:S}=await s(w,b),D=await _.orchestrateShardTraffic(l,{headers:S,table:p.table});return Response.json(D,{headers:{"content-type":"application/json"},status:200})},v=async(w,b)=>{if(j(w,"POST","PITR"),!r(w))throw new d("admin PITR endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403});const _=await Ko(w),{headers:p}=await s(w,b),S=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:_.args,functionPath:_.functionPath}),headers:p,method:"POST"});return t(l,_.shardKey??n,S)};return{[Io]:f,[Po]:v,[Do]:g,[No]:E,[Uo]:k}},Go=1,Qo=0,zo=32,Wo=512,Vo=/^[a-z][\d_a-z*/-]{0,255}(?:@[a-z][\d_a-z*/-]{0,13})?=[\u0020-\u002B\u002D-\u003C\u003E-\u007E]{1,256}$/,Jo=e=>{if(e==null)return;const n=e.trim();if(n.length===0||n.length>Wo)return;const t=n.split(",");if(!(t.length>zo)){for(const r of t)if(!Vo.test(r.trim()))return;return n}},qo=e=>{const n=Hn(e.headers.get("traceparent"));if(n===void 0)return;const t=Jo(e.headers.get("tracestate"));return{parentSpanId:n.parentSpanId,sampled:n.sampled,traceId:n.traceId,...t===void 0?{}:{traceState:t}}},Yo=(e,n={})=>{const t=qo(e),r=n.trustInbound===!0?t:void 0,a=Se(8),s=r?.traceId??Se(16),l=rr(n.sampling,r===void 0?a:s),u=l.isTraced&&(r===void 0||r.sampled);return{decision:l,ignoredUpstream:t!==void 0&&r===void 0,trace:{sampled:u,spanId:a,traceFlags:u?Go:Qo,traceId:s,...r?.parentSpanId===void 0?{}:{parentSpanId:r.parentSpanId},...r?.traceState===void 0?{}:{traceState:r.traceState}}}},Xo=(e,n)=>{n.traceparent=xn(e.traceId,e.spanId,e.sampled),e.traceState!==void 0&&(n.tracestate=e.traceState)},Zo=(e,n)=>{let t;return()=>{if(t===void 0){const r=$n(e),a=n===void 0?void 0:n.cf;t=Ln(jn(r),Mn(r,a))}return t}},ea="/_lunora/admin/scheduled",ta="/_lunora/admin/scheduled/status",na="/_lunora/admin/scheduled/ws",ra="/_lunora/admin/scheduled/cancel",oa="/_lunora/admin/scheduled/dead",aa="/_lunora/admin/scheduled/dead/retry",sa="/_lunora/admin/scheduled/dead/cancel",ia=e=>{const{checkWsAdmin:n,requireSchedulerNamespace:t,resolveSchedulerStub:r,schedulerInstanceName:a}=e,s=(f,g)=>E=>{if(E.method!=="GET")throw new d(`${g} endpoint requires GET`,{code:"METHOD_NOT_ALLOWED",status:405});return r(E).fetch(new Request(`https://scheduler.internal${f}`,{method:"GET"}))},l=(f,g,E=g)=>async k=>{if(k.method!=="POST")throw new d(`${E} requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});const v=r(k),w=await k.json().catch(()=>{});if(typeof w?.id!="string"||w.id==="")throw new d(`${g} requires a string \`id\``,{code:"BAD_REQUEST",status:400});return v.fetch(new Request(`https://scheduler.internal${f}`,{body:JSON.stringify({id:w.id}),headers:{"content-type":"application/json"},method:"POST"}))},u=async f=>{if(f.headers.get("Upgrade")!=="websocket")throw new d("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});if(!await n(f))throw new d("admin authorization required",{code:"ADMIN_FORBIDDEN",status:403});const g=t();return we(g,a).fetch(new Request("https://scheduler.internal/ws",{headers:{Upgrade:"websocket"}}))};return{[ra]:l("/cancel","Scheduled-cancel","Scheduled-cancel endpoint"),[sa]:l("/dead/cancel","Scheduled dead-letter action"),[oa]:s("/dead","Scheduled dead-letter"),[aa]:l("/dead/retry","Scheduled dead-letter action"),[ea]:s("/list","Scheduled-list"),[ta]:s("/status","Scheduler-status"),[na]:u}},ca=(e,...n)=>{let t=e.cf;for(const r of n){if(typeof t!="object"||t===null)return;t=t[r]}return typeof t=="string"?t:void 0},bt={mtls:e=>ca(e,"tlsClientAuth","certVerified")==="SUCCESS"},da=e=>e===void 0||e===!1?()=>!1:e===!0?()=>!0:typeof e=="function"?e:(Object.hasOwn(bt,e)?bt[e]:void 0)??(()=>!1),ua=e=>{if(e!==void 0)return()=>{};let n=!1;return()=>{n||(n=!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.'))}},la="/_lunora/admin/vector/indexes",ha="/_lunora/admin/vector/query",fa=e=>{const{readJsonBody:n,requireAdminOption:t}=e,r=async s=>{j(s,"GET","Vector-indexes");const l=t(s,e.vectorIntrospector,{code:"VECTORS_NOT_CONFIGURED",message:"vector endpoints require a `vectorIntrospector` on the worker"});return Response.json({indexes:await l.listIndexes()},{headers:{"content-type":"application/json"},status:200})},a=async s=>{j(s,"POST","Vector-query");const l=t(s,e.vectorIntrospector,{code:"VECTORS_NOT_CONFIGURED",message:"vector endpoints require a `vectorIntrospector` on the worker"});if(l.queryIndex===void 0)throw new d("vector index querying is not enabled on this worker",{code:"VECTOR_QUERY_UNSUPPORTED",status:400});const f=await n(s);if(typeof f.name!="string"||f.name==="")throw new d("Vector-query request requires a `name` string",{code:"BAD_REQUEST",status:400});if(typeof f.text!="string"||f.text==="")throw new d("Vector-query request requires a `text` string",{code:"BAD_REQUEST",status:400});if(f.topK!==void 0&&(typeof f.topK!="number"||!Number.isInteger(f.topK)||f.topK<1))throw new d("Vector-query `topK` must be a positive integer",{code:"BAD_REQUEST",status:400});const g=await l.queryIndex({name:f.name,text:f.text,topK:f.topK});return Response.json(g,{headers:{"content-type":"application/json"},status:200})};return{[la]:r,[ha]:a}},pa="/_lunora/admin/workflows/instances",ma="/_lunora/admin/workflows/instance",wa="/_lunora/admin/workflows/status",ga={complete:!0,errored:!0,paused:!0,queued:!0,running:!0,terminated:!0,unknown:!0,waiting:!0,waitingForPause:!0},ya=e=>e!==null&&Object.hasOwn(ga,e)?e:void 0,_t=(e,n)=>{const t=e.searchParams.get(n);if(t===null)return;const r=Number(t);return Number.isInteger(r)&&r>0?r:void 0},je=(e,n)=>{const t=e.searchParams.get(n);if(t===null||t==="")throw new d(`Workflows admin endpoint requires a \`${n}\` query parameter`,{code:"BAD_REQUEST",status:400});return t},Rt=()=>{throw new d("Workflow inspection is unconfigured. Set CLOUDFLARE_ACCOUNT_ID + CLOUDFLARE_API_TOKEN in your .dev.vars to enable it.",{code:"WORKFLOWS_NOT_CONFIGURED",status:501})},ba=e=>{const{assertAdmin:n,resolveWorkflowsClient:t}=e,r=async(l,u,f)=>{j(l,"GET","Workflows instances"),n(l);const g=t(u);if(!g)return Response.json({configured:!1,instances:[],page:1,perPage:0,totalCount:0});const E=je(f,"name"),k=ya(f.searchParams.get("status"));return Response.json(await g.listInstances({page:_t(f,"page"),perPage:_t(f,"perPage"),status:k,workflowName:E}))},a=async(l,u,f)=>{j(l,"GET","Workflows instance"),n(l);const g=t(u);return g?Response.json(await g.getInstance({instanceId:je(f,"id"),workflowName:je(f,"name")})):Rt()},s=async(l,u)=>{j(l,"POST","Workflows status"),n(l);const f=t(u);if(!f)return Rt();const g=await l.json().catch(()=>{});if(typeof g?.name!="string"||g.name===""||typeof g.id!="string"||g.id==="")throw new d("Workflows status action requires string `name` and `id`",{code:"BAD_REQUEST",status:400});const{action:E}=g;if(E!=="pause"&&E!=="resume"&&E!=="terminate")throw new d("Workflows status action must be one of: pause, resume, terminate",{code:"BAD_REQUEST",status:400});return Response.json(await f.setInstanceStatus({action:E,instanceId:g.id,workflowName:g.name}))};return{[ma]:a,[pa]:r,[wa]:s}},_a={[zt]:Wt,[qn]:Jn},Et="/_lunora/rpc",Ra="/_lunora/rpc-batch",Ea="/_lunora/ws",Re=(e,n,t)=>({resourceAttributes:Zo(e,n),...t===void 0?{}:{waitUntil:t}}),At=e=>e?.waitUntil?{waitUntil:n=>e.waitUntil?.(n)}:{},St=e=>({spanId:e.spanId,traceFlags:e.traceFlags,traceId:e.traceId,...e.parentSpanId===void 0?{}:{parentSpanId:e.parentSpanId}}),$e=e=>{const{method:n}=e,t=e.headers.get("user-agent")??void 0;let r;try{r=new URL(e.url)}catch{return{method:n,userAgent:t}}const a=r.port===""?void 0:Number(r.port);return{host:r.hostname,method:n,path:r.pathname,port:Number.isNaN(a)?void 0:a,scheme:r.protocol.replace(":",""),userAgent:t}},Tt="/_lunora/voice/",Aa="/_lunora/scheduler/dispatch",Sa="/_lunora/admin/cron-jobs/run",Ta="/_lunora/admin/ws-token",Oa="/_lunora/admin/",va="/_lunora/migrate",ka="/_lunora/status",Ia=e=>e.startsWith(Oa)||e===va,Pa=e=>{const n=e.headers.get("x-lunora-userid"),t=e.headers.get("x-lunora-identity");if(!(n===null&&t===null))return{...t===null?{}:{identity:t},...n===null?{}:{userId:n}}},Da="/api/auth",Na="__lunora_admin__:recordAuthEvent",Ua="__lunora_admin__:listPushSubscriptions",Ca=["/sign-in","/sign-up","/callback"],Ba=(e,n)=>{const t=n.endsWith("/")?n.slice(0,-1):n;if(!e.startsWith(`${t}/`))return!1;const r=e.slice(t.length);return Ca.some(a=>r===a||r.startsWith(`${a}/`))},Ee=(e,n,t,r)=>{const a=Dn(t),s=a?t.code:"INTERNAL_SERVER_ERROR",l=a?t.status:500,u=t instanceof Error?t.message:String(t);return{durationMs:n,error:{code:s,message:u,status:l},functionPath:e,ok:!1,...r.fanOut?{fanOut:{failed:0,shards:0,table:r.fanOut.table}}:{},...r.shardKey?{shardKey:r.shardKey}:{}}},xa=e=>{const{exp:n,expiresAtMs:t}=e;if(typeof t=="number"&&Number.isFinite(t))return t;if(typeof n=="number"&&Number.isFinite(n))return n*1e3},Ot=e=>e.waitUntil?{waitUntil:n=>{e.waitUntil?.(n)}}:void 0,Ha=e=>{const n=e?.queue;return typeof n=="string"&&n.length>0?n:"unknown"},Fe=new WeakMap,de=async(e,n,t,r=Fe.get(e))=>{const a={"content-type":"application/json"},s=e.headers.get("authorization"),l=e.headers.get("cookie"),u=e.headers.get("x-d1-bookmark"),f=e.headers.get("x-lunora-mutation-id"),g=e.headers.get("x-lunora-client-id"),E=e.headers.get("x-lunora-client-seq");s&&(a.authorization=s),l&&(a.cookie=l),u&&(a["x-d1-bookmark"]=u),f&&(a["x-lunora-mutation-id"]=f),g&&(a["x-lunora-client-id"]=g),E&&(a["x-lunora-client-seq"]=E);const k=e.headers.get("cf-connecting-ip");if(k&&(a["x-lunora-client-ip"]=k),!t)return{claims:null,headers:a,identity:null,userId:null};const v=await t(e,n,r);if(!v||typeof v.userId!="string"||v.userId.length===0)return{claims:null,headers:a,identity:null,userId:null};a["x-lunora-userid"]=Cn(v.userId);const w=xa(v);w!==void 0&&(a["x-lunora-identity-exp"]=String(w));const{userId:b,..._}=v,p=Object.keys(_).length>0?_:null;return p&&(a["x-lunora-identity"]=Bn(p)),{claims:p,headers:a,identity:v,userId:b}},La=new Set(["concat","first","groupBy","max","min","rank","sum","topK"]),Ma=e=>{if(e===void 0)return;if(!e||typeof e!="object")throw new d("RPC `fanOut` must be an object",{code:"BAD_REQUEST",status:400});const n=e;if(typeof n.table!="string"||n.table.length===0)throw new d("RPC `fanOut.table` must be a non-empty string",{code:"BAD_REQUEST",status:400});if(!n.merge||typeof n.merge!="object")throw new d("RPC `fanOut.merge` must be an object",{code:"BAD_REQUEST",status:400});const t=n.merge;if(typeof t.kind!="string"||!La.has(t.kind))throw new d("RPC `fanOut.merge.kind` is not a recognized merge strategy",{code:"BAD_REQUEST",status:400});if(t.kind==="topK"){if(typeof t.k!="number"||!Number.isInteger(t.k)||t.k<0)throw new d("RPC `fanOut.merge.k` must be a non-negative integer",{code:"BAD_REQUEST",status:400});if(typeof t.by!="string"||t.by.length===0)throw new d("RPC `fanOut.merge.by` must be a non-empty string",{code:"BAD_REQUEST",status:400})}return n},ja=(e,n)=>{e?.LUNORA_DEBUG_RPC&&console.warn(`[lunora:rpc] ${n.fanOut?"fan-out":`shard=${n.shardKey??"(root)"}`} ${n.functionPath}`)},vt=(e,n)=>{const t=n.functions?.[e.functionPath]?.x402;if(t){if(e.fanOut)throw new d("a paid (`.x402`) function cannot be fanned out",{code:"BAD_REQUEST",status:400});if(!n.x402Charge)throw new d(`function "${e.functionPath}" is marked paid (.x402) but no x402Charge gate is configured on the worker`,{code:"MISCONFIGURED",status:500});return t}},$a=async e=>{const n=await Ct(e);let t;try{t=JSON.parse(n)}catch{throw new d("RPC body must be valid JSON",{code:"BAD_REQUEST",status:400})}if(!t||typeof t!="object"||typeof t.functionPath!="string")throw new d("RPC envelope is missing `functionPath`",{code:"BAD_REQUEST",status:400});const r=t;if(r.args!==void 0&&Ut(r.args,"RPC"),r.shardKey!==void 0&&typeof r.shardKey!="string")throw new d("RPC `shardKey` must be a string",{code:"BAD_REQUEST",status:400});const a=t,s=Ma(a.fanOut),l=a.args??{};if(s&&a.functionPath.startsWith("__lunora_relation__:")){const u=l.table;if(typeof u=="string"&&u!==s.table)throw new d("RPC `args.table` must match the authorized `fanOut.table` for a relation fan-out",{code:"BAD_REQUEST",status:400});l.table=s.table}return{args:l,fanOut:s,functionPath:a.functionPath,shardKey:a.shardKey}},Ae=new Map,Ka=5e3,Fa=4096,Ga=async(e,n)=>{const t=Date.now(),r=Ae.get(n);if(r!==void 0&&r.expiresMs>t)return r.relayCount;r!==void 0&&Ae.delete(n);let a=0;try{const s=await we(e,n).fetch(new Request("https://shard.internal/_lunora/route"));if(s.ok){const u=(await s.json()).relayCount;typeof u=="number"&&u>0&&(a=Math.floor(u))}}catch{a=0}return Dt(Ae,Fa),Ae.set(n,{expiresMs:t+Ka,relayCount:a}),a},kt=(e,n)=>{if(!(e===null||typeof e!="object"))return Object.entries(e).find(([,t])=>t===n)?.[0]},ye=(e,n,t)=>new Request("https://shard.internal/rpc",{body:JSON.stringify({args:n,functionPath:e}),headers:t,method:"POST"}),Qa=["x-lunora-userid","x-lunora-identity","x-lunora-identity-exp"],It=(e,n)=>{for(const t of Qa){e.delete(t);const r=n[t];r!==void 0&&e.set(t,r)}},za=async(e,n,t)=>e.length===0||t.length===0?!1:ze(await Lt(e,n),t),Pt=(e,n)=>{if(!n||n.length===0)return!1;const t=e.headers.get("authorization");if(!t)return!1;const[r,...a]=t.split(" ");return r?.toLowerCase()!=="bearer"?!1:ze(n,a.join(" ").trim())},Wa=async(e,n,t)=>{if(!n||n.length===0)return!1;const r=new URL(e.url).searchParams.get("token");return r===null?!1:await Ir(n,r)?!0:t?!1:ze(n,r)},Va=(e,n)=>{if(n===null||typeof n!="object"&&typeof n!="function")return;const t=n;if(typeof t.prepare=="function"&&typeof t.batch=="function"&&typeof t.dump=="function")return er(`d1:${e}`,n);if(typeof t.list=="function"&&typeof t.head=="function"&&typeof t.createMultipartUpload=="function")return Ce(`r2:${e}`,!0);if(typeof t.send=="function"&&typeof t.sendBatch=="function"&&typeof t.get!="function")return Ce(`queue:${e}`,!0);if(typeof t.connectionString=="string")return Ce(`hyperdrive:${e}`,!0)},Vt=e=>{const n=da(e.trustInboundTraceContext),t=ua(e.trustInboundTraceContext),r=e.defaultShardKey??"__root__",a=tr(e.resolveIdentity,e.identity),s=rt(e.shardDO,e.jurisdiction),l=e.schedulerDO===void 0?void 0:rt(e.schedulerDO,e.jurisdiction);let u=!1;const f=o=>{if(o===void 0||e.jurisdiction===void 0)return o;u||(u=!0,console.warn(`[lunora] jurisdiction "${e.jurisdiction}" pins placement, so region hints (\`shardRegion\`, replica and relay placement) are not sent. Residency wins.`))},g=async(o,i,h,c=e.shardRegion?.(i))=>we(o,i,f(c)).fetch(h);let E;const k=()=>e.adminToken??E;let v;const w=()=>e.requireEphemeralWsToken??v??!0;let b;const _=o=>{const i=o??{};if(b??=kt(o,e.shardDO),v===void 0&&e.requireEphemeralWsToken===void 0){const c=i.LUNORA_REQUIRE_EPHEMERAL_WS_TOKEN;typeof c=="string"&&c.length>0&&(v=Or(c,!0))}if(E!==void 0||e.adminToken!==void 0)return;const h=i.LUNORA_ADMIN_TOKEN;typeof h=="string"&&h.length>0&&(E=h)},p=new WeakSet,S=o=>Pt(o,k())||p.has(o),D=async(o,i)=>{const h=await de(o,i,e.resolveIdentity);if(p.has(o)&&h.headers.authorization===void 0){const c=k();c!==void 0&&(h.headers.authorization=`Bearer ${c}`)}return h};let T=!1,x=!1;const H=()=>{x||(x=!0,console.warn("[lunora] `replicaReads: true` has no effect without `functions` — read eligibility is decided from the function registry."))},$=o=>{if(!e.allowUnauthenticatedShardAccess){const i=o==="fan-out"?"authorizeFanOut":"authorizeShard";throw new d(`${o} access is default-denied: configure \`${i}\` on the worker, or set \`allowUnauthenticatedShardAccess: true\` to explicitly allow unauthenticated ${o} access (relying solely on per-row RLS).`,{code:o==="fan-out"?"FORBIDDEN_FANOUT":"FORBIDDEN_SHARD",status:403})}T||(T=!0,console.warn([`[lunora] SECURITY: serving ${o} access with \`allowUnauthenticatedShardAccess: true\` and no \`authorizeShard\`/\`authorizeFanOut\` — `,"any caller (including unauthenticated ones) can target any shard / fan out across the table. ","This is safe only if every table is protected by per-row RLS. Configure `authorizeShard`/`authorizeFanOut` to gate it."].join("")))},U=async(o,i,h=!0)=>{if(e.authorizeShard){if(!await e.authorizeShard(o,i))throw new d("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else h&&i!==r&&$("shard")},W=Fo({defaultShard:r,forwardToShard:g,isAdmin:S,queryCoordinator:e.queryCoordinator,resolveForwardContext:D,shardDO:s}),K=async(o,i,h,c,m)=>{await U(null,h,!1);const R={"content-type":"application/json","x-lunora-system":"1"};return m?.userId!==void 0&&m.userId.length>0&&(R["x-lunora-userid"]=m.userId),m?.identity!==void 0&&m.identity.length>0&&(R["x-lunora-identity"]=m.identity),c!==void 0&&c.length>0&&(R["x-lunora-mutation-id"]=c),g(s,h,ye(o,i,R))},V=async(o,i,h,c)=>{const m=h?.[o];if(!m||typeof m.create!="function")throw new d(`${c} targets workflow binding "${o}", which is not bound on env`,{code:"CRON_JOB_FAILED",status:500});if(ir(i))throw new d(`${c} params ${cr}`,{code:"BAD_REQUEST",status:400});await m.create({params:i})},X=async(o,i)=>{if(o.workflow){await V(o.workflow,o.args??{},i,`cron job "${o.name}"`);return}if(o.functionPath===void 0)throw new d(`cron job "${o.name}" has neither a function target nor a workflow target`,{code:"CRON_JOB_FAILED",status:500});const h=await K(o.functionPath,o.args??{},o.shardKey??r);if(!h.ok)throw new d(`cron job "${o.name}" (${o.functionPath}) failed with shard status ${String(h.status)}`,{code:"CRON_JOB_FAILED",status:500})},J=async(o,i,h,c)=>{const m=e.cronJobs?.[o];if(m)for(const R of m)try{await X(R,i)}catch(I){h.push(c(I))}},ae=async(o,i)=>{if(!S(o))throw new d("admin endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403});if(j(o,"POST","cron-jobs run"),!e.cronJobs)throw new d("cron-jobs run endpoint requires a `cronJobs` map on the worker",{code:"CRON_JOBS_NOT_CONFIGURED",status:400});const h=await Z(o),c=typeof h.name=="string"?h.name:"";if(c==="")throw new d("cron-jobs run endpoint requires a job `name`",{code:"BAD_REQUEST",status:400});const m=Object.values(e.cronJobs).flat().find(R=>R.name===c);if(!m)throw new d(`no cron job named "${c}" is registered`,{code:"CRON_JOB_NOT_FOUND",status:404});return await X(m,i),Response.json({name:c,ran:!0},{status:200})},F=async o=>{const i=typeof o.pool=="string"&&o.pool.length>0?o.pool:void 0;if(!i||!l||typeof o.id!="string")return;const h=typeof o.instanceName=="string"&&o.instanceName.length>0?o.instanceName:"default";try{await we(l,h).fetch(new Request("https://scheduler.internal/complete",{body:JSON.stringify({id:o.id,pool:i}),headers:{"content-type":"application/json"},method:"POST"}))}catch{}},he=async(o,i)=>{j(o,"POST","Scheduler dispatch");const h=await Ct(o),c=i??{},m=typeof c.LUNORA_SCHEDULER_SECRET=="string"?c.LUNORA_SCHEDULER_SECRET:void 0,R=e.adminToken??(typeof c.LUNORA_ADMIN_TOKEN=="string"?c.LUNORA_ADMIN_TOKEN:void 0),I=o.headers.get("x-lunora-scheduler-signature");let y=!1;if(I&&m?y=await za(m,h,I):R&&(y=Pt(o,R)),!y)throw new d("Scheduler dispatch requires a valid signature or admin bearer",{code:"FORBIDDEN",status:403});let A;try{A=JSON.parse(h)}catch{throw new d("Scheduler dispatch body must be valid JSON",{code:"BAD_REQUEST",status:400})}const O=A??{},C=O.args??{};if(typeof O.workflow=="string"&&O.workflow.length>0)return await V(O.workflow,C,i,"scheduled workflow"),Response.json({ok:!0},{status:200});if(typeof O.functionPath!="string"||O.functionPath.length===0)throw new d("Scheduler dispatch is missing `functionPath`",{code:"BAD_REQUEST",status:400});const B=typeof O.shardKey=="string"&&O.shardKey.length>0?O.shardKey:r,L=typeof O.id=="string"&&O.id.length>0?O.id:void 0,te=Pa(o),M=await K(O.functionPath,C,B,L,te);return await F(O),M},G=o=>{if(!S(o))throw new d("admin endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403})},oe=(o,i,h)=>{if(G(o),i===void 0)throw new d(h.message,{code:h.code,status:400});return i},Te=Cr({assertAdmin:G,getReader:()=>e.authAuditReader}),Oe=async(o,i)=>{G(o);const h=e.notifySubscriptionStore;if(h===void 0)return Response.json({result:Ke({subscriptions:[]})},{headers:{"content-type":"application/json"},status:200});const c=i?.kind,m=i?.userId,R=i?.limit,I=c==="fcm"||c==="web-push"?c:void 0,y=typeof m=="string"&&m!==""?m:void 0,A=typeof R=="number"&&Number.isFinite(R)?Math.trunc(R):0,O=A>0?Math.min(A,1e3):1e3,B=(await h.list({kind:I,limit:O,userId:y})).filter(L=>I!==void 0&&L.kind!==I?!1:y===void 0||(L.userId??null)===y).map(({keys:L,token:te,...M})=>M);return Response.json({result:Ke({subscriptions:B})},{headers:{"content-type":"application/json"},status:200})},se=async(o,i)=>{if(!i.fanOut){if(i.functionPath===Ur)return Te(o,i.args??{});if(i.functionPath===Ua)return Oe(o,i.args)}},Jt=co({applyGlobals:e.applyGlobals,assertAdmin:G,exportCursorStore:e.exportCursorStore,exportSinks:e.exportSinks,knownTables:()=>[],queryCoordinator:e.queryCoordinator,requireAdminOption:oe,resolveForwardContext:D,shardDO:s,streamExportRows:(o,i,h,c)=>Ft(e,o,i,h,c,s),streamingImport:(o,i)=>fo(o,e,i,s),syncGlobals:e.syncGlobals}),ve=(o,i)=>{const h=o.searchParams.get(i);return h===null||h===""?void 0:h},ke=o=>{const i=new URL(o.url),h=i.searchParams.get("limit"),c=i.searchParams.get("offset"),m=h===null?void 0:Number.parseInt(h,10),R=c===null?void 0:Number.parseInt(c,10);return{limit:m!==void 0&&Number.isFinite(m)&&m>=0?m:void 0,offset:R!==void 0&&Number.isFinite(R)&&R>=0?R:void 0}},Je=()=>{if(l===void 0)throw new d("scheduled endpoints require a `schedulerDO` namespace on the worker",{code:"SCHEDULER_NOT_CONFIGURED",status:400});return l},qt=ia({checkWsAdmin:async o=>S(o)||Wa(o,k(),w()),requireSchedulerNamespace:Je,resolveSchedulerStub:o=>(G(o),we(Je(),e.schedulerInstanceName??"default")),schedulerInstanceName:e.schedulerInstanceName??"default"}),Yt=ba({assertAdmin:G,resolveWorkflowsClient:e.workflowsClient??(()=>{})}),Xt=Vn({assertAdmin:G,parsePaging:ke,queryParameter:ve,readBodyBytes:Fn,requireAdminOption:oe,storage:{storageBuckets:e.storageBuckets,storageDelete:e.storageDelete,storageDownload:e.storageDownload,storageList:e.storageList,storageSignedUrl:e.storageSignedUrl,storageUpload:e.storageUpload}}),Zt=Wr({options:e,readJsonBody:Z,requireAdminOption:oe}),en=fa({readJsonBody:Z,requireAdminOption:oe,vectorIntrospector:e.vectorIntrospector}),tn=ko({kvIntrospector:e.kvIntrospector,readJsonBody:Z,requireAdminOption:oe}),nn=nr({logArchive:e.logArchive,readJsonBody:Z,requireAdminOption:oe}),rn=To({assertAdmin:G,options:{cronJobs:e.cronJobs,functions:e.functions,globalIntrospector:e.globalIntrospector,openApiSpec:e.openApiSpec,openRpcSpec:e.openRpcSpec},parsePaging:ke,queryParameter:ve,requireAdminOption:oe}),on=o=>{const i=[],h=s??o?.SHARD;if(h!==void 0&&i.push(Zn("durable-object:default",h,r)),e.health?.disableBindingProbes!==!0)for(const[c,m]of Object.entries(o??{})){const R=Va(c,m);R!==void 0&&i.push(R)}for(const c of e.health?.probes??[])i.push(c);return i},an=Xn({appName:e.health?.appName,appVersion:e.health?.appVersion,auth:e.health?.auth??"public",cacheTtlMs:e.health?.cacheTtlMs,isAdmin:S,resolveProbes:on}),sn=o=>{const i=e.schedulerInstanceName??"default",h=()=>we(o,i),c=async(y,A)=>{const O=await h().fetch(new Request(`https://scheduler.internal${y}`,A));if(!O.ok)throw new d(`ctx.scheduler: SchedulerDO ${y} failed (${String(O.status)}): ${await O.text()}`,{code:"INTERNAL",status:500});return await O.json()},m=async(y,A)=>await c(y,{body:JSON.stringify(A),headers:{"content-type":"application/json"},method:"POST"}),R=y=>{const A=y;if(A==null)throw new d("ctx.scheduler: target is required — pass a reference from the generated `internal` / `workflows` / `agents`",{code:"BAD_REQUEST",status:400});if(typeof A.binding=="string"&&A.binding.length>0)return{workflow:A.binding};if(typeof A.__lunoraRef=="string")return{functionPath:A.__lunoraRef};throw new d("ctx.scheduler: expected a reference from the generated `internal` / `workflows` / `agents` — a bare function-path string is refused here, because an HTTP action can be reached unauthenticated",{code:"BAD_REQUEST",status:400})},I=async(y,A,O={})=>{const{id:C}=await m("/schedule",{args:O,scheduledFor:y,...R(A)});return C};return{cancel:async y=>await m("/cancel",{id:y}),get:async y=>await c(`/get?id=${encodeURIComponent(y)}`,{method:"GET"}),list:async()=>await c("/list",{method:"GET"}),runAfter:async(y,A,O)=>{if(!Number.isFinite(y)||y<0)throw new d("ctx.scheduler.runAfter: `delayMs` must be a non-negative finite number",{code:"BAD_REQUEST",status:400});return await I(Date.now()+y,A,O)},runAt:async(y,A,O)=>{if(!Number.isFinite(y))throw new d("ctx.scheduler.runAt: `timestampMs` must be a finite epoch-millisecond number",{code:"BAD_REQUEST",status:400});return await I(y,A,O)}}},cn=async(o,i,h)=>{const{claims:c,headers:m,userId:R}=await de(o,i,a),I=async(y,A={})=>{const O=y.__lunoraRef;if(typeof O!="string")throw new d("ctx.run*: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});const C=ye(O,A,{...m,"x-lunora-system":"1"}),B=await g(s,r,C),L=await B.json();if(L.error)throw new d(L.error.message??"shard RPC failed",{code:L.error.code??"INTERNAL",status:B.status});return L.result};return{auth:{getIdentity:()=>Promise.resolve(c),userId:R},cache:h.cache,fetch:globalThis.fetch.bind(globalThis),runAction:I,runMutation:I,runQuery:I,...l===void 0?{}:{scheduler:sn(l)},...e.storage===void 0?{}:{storage:sr(e.storage(i))}}},dn=async(o,i,h)=>{if(!e.httpRouter)return;const c=await cn(o,i,h);try{return await e.httpRouter.fetch(o,{...i,__lunoraCtx:c},h)}catch(m){return console.error("[lunora] httpRouter (SSR) handler threw:",m),new Response("Internal Server Error",{status:500})}},un=async(o,i,h)=>{if(o.headers.get("Upgrade")!=="websocket")throw new d("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});const c=at(o,ie);if(c)return c;const m=h.searchParams.get("shard")??r,{headers:R,identity:I}=await de(o,i,a);await U(I,m);const y=new Headers(o.headers),A=[...y.keys()];for(const C of A)C.startsWith("x-lunora-")&&y.delete(C);It(y,R);const O=kt(i,e.shardDO);if(O!==void 0){y.set("x-lunora-shard-binding",O);const C=await Ga(s,m);if(C>0){const B=Rr(m,Math.floor(Math.random()*C));return g(s,B,new Request(o,{headers:y}),st(o))}}return g(s,m,new Request(o,{headers:y}))},ln=async(o,i,h)=>{const{voiceAgents:c}=e;if(c===void 0)return new Response("Not found",{status:404});if(o.headers.get("Upgrade")!=="websocket")return new Response("Expected a WebSocket upgrade",{headers:{allow:"GET"},status:426});const m=at(o,ie);if(m)return m;let R;try{R=decodeURIComponent(h.pathname.slice(Tt.length))}catch{return new Response("Unknown voice agent",{status:404})}const I=Object.hasOwn(c,R)?c[R]:void 0;if(I===void 0)return new Response("Unknown voice agent",{status:404});const y=h.searchParams.get("threadKey");if(y===null||y.length===0)return new Response("Missing threadKey",{status:400});const{headers:A,identity:O}=await de(o,i,a);if(e.authorizeShard){if(!await e.authorizeShard(O,y))return new Response("Forbidden",{status:403})}else $("shard");const C=new Headers(o.headers);for(const B of C.keys())B.startsWith("x-lunora-")&&C.delete(B);return It(C,A),g(I,y,new Request(o,{headers:C}))},hn=async(o,i,h)=>{if(e.authorizeFanOut){if(!await e.authorizeFanOut(h,o.table,i))throw new d("Forbidden fan-out",{code:"FORBIDDEN_FANOUT",status:403});return}if(i.startsWith("__lunora_relation__:"))throw new d("reverse cross-backend relation reads (`__lunora_relation__:*`) require `authorizeFanOut` to be configured on the worker",{code:"FORBIDDEN_FANOUT",status:403});if(e.authorizeShard)throw new d("Fan-out requires `authorizeFanOut` to be configured on the worker when `authorizeShard` is set",{code:"FORBIDDEN_FANOUT",status:403});$("fan-out")},_e=async(o,i)=>{if(!(!o.fanOut&&o.functionPath.startsWith("__lunora_admin__:"))){if(o.fanOut){await hn(o.fanOut,o.functionPath,i);return}await U(i,o.shardKey??r)}},fn=(o,i,h)=>{if(e.replicaReads!==!0)return;if(e.functions===void 0){H();return}if(e.functions[i]?.kind!=="query"||h.includes(jt)||h.includes(Mt))return;const c=st(o);return c===void 0?void 0:{name:Er(h,c),region:c}},pn=async(o,i,h,c,m)=>{const R=fn(o,i,c);if(R!==void 0){const I={...m,"x-lunora-replica-read":"1",...b===void 0?{}:{"x-lunora-shard-binding":b}},y=Ar(o.headers.get("x-lunora-min-seq"));y!==void 0&&(I["x-lunora-min-seq"]=String(y));const A=await g(s,R.name,ye(i,h,I),R.region);if(A.status!==421)return A}return g(s,c,ye(i,h,m))},Ie=async(o,i,h,c,m,R)=>{const I=Date.now(),{observability:y,sampling:A}=e,O=$e(o),{decision:C,ignoredUpstream:B,trace:L}=Yo(o,{...A===void 0?{}:{sampling:A},trustInbound:n(o)});B&&t();const te={...m,"x-lunora-sample-errors":C.keepErrors?"1":"0"};Xo(L,te);try{const M=await pn(o,i,h,c,te);ce(y,{...O,...St(L),durationMs:Date.now()-I,functionPath:i,ok:M.ok,shardKey:c,...M.ok?{}:{error:{code:"SHARD_ERROR",message:`shard returned ${String(M.status)}`,status:M.status}}},R,void 0,{isTraced:L.sampled,keepErrors:C.keepErrors});const ee=new Response(M.body,{headers:M.headers,status:M.status,statusText:M.statusText});return ee.headers.set("x-lunora-shard-key",c),ee}catch(M){throw ce(y,{...O,...St(L),...Ee(i,Date.now()-I,M,{shardKey:c})},R,void 0,{isTraced:L.sampled,keepErrors:C.keepErrors}),M}},mn=o=>{if(o.fanOut&&o.shardKey)throw new d("RPC envelope cannot set both `shardKey` and `fanOut`",{code:"BAD_REQUEST",status:400});if(!o.fanOut&&o.functionPath.startsWith("__lunora_relation__:"))throw new d("`__lunora_relation__:*` is a fan-out-only reserved RPC and cannot be dispatched to a single shard",{code:"FORBIDDEN",status:403});if(o.fanOut&&!e.queryCoordinator)throw new d("RPC envelope set `fanOut` but no `queryCoordinator` is configured on the worker",{code:"BAD_REQUEST",status:400})},wn=async(o,i,h)=>{j(o,"POST","RPC");const c=await $a(o);ja(i,c),mn(c);const m=await se(o,c);if(m!==void 0)return m;const{headers:R,identity:I}=await de(o,i,a);await _e(c,I);const y=vt(c,e);{const A=Date.now(),{observability:O}=e,C=$e(o),B=Re(i,o,h&&(M=>h.waitUntil?.(M)));if(c.fanOut){const M=e.queryCoordinator;if(!M)throw new d("RPC envelope set `fanOut` but no `queryCoordinator` is configured on the worker",{code:"BAD_REQUEST",status:400});try{const ee=await M.fanOut(s,{args:c.args??{},fanOut:c.fanOut,functionPath:c.functionPath,headers:R});return ce(O,{durationMs:Date.now()-A,fanOut:{failed:ee.failed,shards:ee.ok+ee.failed,table:c.fanOut.table},functionPath:c.functionPath,...C,ok:!0},B),Response.json(ee,{headers:{"content-type":"application/json"},status:200})}catch(ee){throw ce(O,{...Ee(c.functionPath,Date.now()-A,ee,{fanOut:{table:c.fanOut.table}}),...C},B),ee}}const L=c.shardKey??r,te=()=>Ie(o,c.functionPath,c.args??{},L,R,B);return y&&e.x402Charge?e.x402Charge(o,{functionPath:c.functionPath,price:y.price},te,At(h)):te()}},gn=async(o,i,h)=>{j(o,"POST","RPC batch");const c=await Z(o),{calls:m}=c;if(!Array.isArray(m))throw new d("RPC batch `calls` must be an array",{code:"BAD_REQUEST",status:400});const{headers:R,identity:I}=await de(o,i,a),y=Jr(m,r);for(const Q of y.values())for(const z of Q)if(e.functions?.[z.functionPath]?.x402)throw new d(`paid (\`.x402\`) function "${z.functionPath}" cannot be called in a batch; dispatch it individually over ${Et}`,{code:"BAD_REQUEST",status:400});await Promise.all([...y.entries()].flatMap(([Q,z])=>z.map(ne=>_e({args:ne.args,functionPath:ne.functionPath,shardKey:Q},I))));const{observability:A}=e,O=Re(i,o,h&&(Q=>h.waitUntil?.(Q))),C=$e(o),B=[],L=[],te=(Q,z,ne,ue)=>({body:{error:{code:ne,message:ue}},id:Q.id,status:z}),M=(Q,z,ne,ue,fe)=>{for(const q of Q)ce(A,fe(q),O),B.push(te(q,z,ne,ue))},ee=(Q,z,ne,ue,fe)=>{for(const q of Q){const pe=ue.get(q.id)??fe,ge=pe<400;ce(A,{durationMs:ne,functionPath:q.functionPath,...C,ok:ge,shardKey:z,...ge?{}:{error:{code:"SHARD_ERROR",message:`batched call returned ${String(pe)}`,status:pe}}},O)}};await Promise.all([...y.entries()].map(async([Q,z])=>{const ne=new Headers(R);ne.set("content-type","application/json");const ue=new Request("https://shard.internal/rpc-batch",{body:JSON.stringify({calls:z}),headers:ne,method:"POST"}),fe=Date.now();let q;try{q=await g(s,Q,ue)}catch(Y){const Ue=Date.now()-fe,{body:et}=Nn(Y,{fallbackCode:"SHARD_UNAVAILABLE",redactedMessage:"shard unavailable"});M(z,502,et.code,et.message,Pn=>({...Ee(Pn.functionPath,Ue,Y,{shardKey:Q}),...C}));return}const pe=Date.now()-fe,ge=q.headers.get("x-d1-bookmark");ge&&L.push(ge);let De;try{De=await q.json()}catch{const Y=`shard batch returned a non-JSON response (${String(q.status)})`;M(z,q.status,"SHARD_ERROR",Y,Ue=>({durationMs:pe,error:{code:"SHARD_ERROR",message:Y,status:q.status},functionPath:Ue.functionPath,...C,ok:!1,shardKey:Q}));return}const Ne=Array.isArray(De.results)?De.results:[],kn=new Map(Ne.map(Y=>[Y.id,Y.status??q.status])),In=new Set(Ne.map(Y=>Y.id));ee(z,Q,pe,kn,q.status),B.push(...Ne);for(const Y of z)In.has(Y.id)||B.push(te(Y,q.status,"SHARD_ERROR",`shard batch omitted result for call ${String(Y.id)}`))}));const Xe={"content-type":"application/json"},[Ze]=L;return L.length===1&&Ze!==void 0&&(Xe["x-d1-bookmark"]=Ze),Response.json({results:B},{headers:Xe,status:200})},yn=async(o,i,h,c={},m={})=>{try{const R=h.__lunoraRef;if(typeof R!="string")throw new d("serverQuery: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});const{headers:I,identity:y}=await de(o,i,a,m.context);await _e({args:c,functionPath:R,shardKey:m.shardKey},y);const A=m.shardKey??r,O=Re(i,o,m.waitUntil);return await Ie(o,R,c,A,I,O)}catch(R){return tt(R)}},qe=async(o,i,h)=>{const{observability:c}=e,m=Date.now(),R=Se(16),I=Se(8),y=Ot(i);try{const A=await h();return ce(c,{durationMs:Date.now()-m,functionPath:o,ok:!0,spanId:I,traceId:R},y),A}catch(A){throw ce(c,{...Ee(o,Date.now()-m,A,{}),spanId:I,traceId:R},y),A}finally{nt(c,y)}},bn=async(o,i,h)=>{_(i);const c=[],m=y=>y instanceof Error?y:new Error(String(y)),R=e.crons?.[o.cron];if(R)try{await R(o,i,h)}catch(y){c.push(m(y))}if(await J(o.cron,i,c,m),e.backupStore&&e.backupCron!==void 0&&e.backupCron===o.cron)try{await Fr(e,s,k(),o)}catch(y){c.push(m(y))}const[I]=c;if(c.length===1&&I)throw I;if(c.length>1)throw new AggregateError(c,`scheduled("${o.cron}") had ${String(c.length)} failure(s)`)},_n=async(o,i)=>{try{const h=o??{},c=e.adminToken??(typeof h.LUNORA_ADMIN_TOKEN=="string"?h.LUNORA_ADMIN_TOKEN:void 0);if(!c||c.length===0)return;await g(s,r,ye(Na,{outcome:i},{authorization:`Bearer ${c}`,"content-type":"application/json"}))}catch{}},Rn=async(o,i,h,c)=>{if(!e.authHandler)return;const m=await e.authHandler(o);if(!m)return;const R=e.authBasePath??Da;return Ba(h.pathname,R)&&c.waitUntil?.(_n(i,m.status>=400?"fail":"ok")),m},En=async({args:o,env:i,functionPath:h,request:c,shardKey:m,waitUntil:R})=>{Ut(o,"REST");const I={functionPath:h,...m===void 0?{}:{shardKey:m}},{headers:y,identity:A}=await de(c,i,a);await _e(I,A);const O=m??r,C=Re(i,c,R),B=()=>Ie(c,h,o,O,y,C),L=vt(I,e);return L&&e.x402Charge?e.x402Charge(c,{functionPath:h,price:L.price},B,At({waitUntil:R})):B()},An=Kn({functions:e.functions??{},invoke:En,readJsonBody:Z,edgeCache:e.restEdgeCache,...e.restRateLimit?{rateLimit:e.restRateLimit}:{}}),Pe=e.routes!==void 0&&Object.keys(e.routes).length>0?e.routes:void 0,Sn={[ka]:o=>o.method!=="GET"&&o.method!=="HEAD"?new Response(void 0,{headers:{allow:"GET, HEAD"},status:405}):Response.json({ok:!0},{headers:{"cache-control":"no-store"}}),[Ea]:(o,i,h)=>un(o,i,h),[Et]:(o,i,h,c)=>wn(o,i,c),[Ra]:(o,i,h,c)=>gn(o,i,c),[Aa]:(o,i)=>he(o,i),[Sa]:(o,i)=>ae(o,i),[Ta]:async o=>{j(o,"POST","ws-token"),G(o);const i=k();if(i===void 0)throw new d("ws-token minting requires a configured admin token",{code:"ADMIN_TOKEN_NOT_CONFIGURED",status:400});const h=await kr(i);return Response.json(h,{headers:{"cache-control":"no-store"}})},...W,...Jt,...qt,...Yt,...Xt,...Zt,...en,...tn,...nn,...rn,...an,...An,...Nr({assertAdmin:G,getAuthAdmin:()=>e.authAdmin,parsePaging:ke,queryParameter:ve,readJsonBody:Z})};let ie=ot(e.security),Ye=!1;const Tn=o=>{Ye||(Ye=!0,ie=ot(e.security,o??{}))},On=async(o,i)=>{if(!(e.adminGate===void 0||!Ia(i)))try{await e.adminGate(o,Fe.get(o))&&p.add(o)}catch{}},vn=async(o,i,h)=>{Fe.set(o,h);const c=new URL(o.url);if(o.method==="POST"||o.method==="PUT"){const y=Number(o.headers.get("content-length")??""),A=_a[c.pathname]??Nt;if(Number.isFinite(y)&&y>A)throw new d("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413})}const m=await Rn(o,i,c,h);if(m)return m;if(Pe){const y=`${o.method} ${c.pathname}`,A=Pe[y]??Pe[c.pathname];if(A)return A(o,i,h)}const R=Sn[c.pathname];if(R)return await On(o,c.pathname),R(o,i,c,h);if(e.voiceAgents!==void 0&&c.pathname.startsWith(Tt))return ln(o,i,c);const I=await dn(o,i,h);return I||new Response("Not found",{status:404})};return{async fetch(o,i,h){e.passThroughOnException&&h.passThroughOnException?.(),Tn(i),_(i);const c=or(o,ie);if(c)return c;const m=ar(o,ie);if(m)return Be(m,o,ie);try{const R=await vn(o,i,h);return Be(R,o,ie)}catch(R){return Be(tt(R),o,ie)}finally{nt(e.observability,Ot(h))}},async queue(o,i,h){await qe(`queue:${Ha(o)}`,h,async()=>{await e.queue?.(o,i,h)})},async scheduled(o,i,h){await qe(`cron:${o.cron}`,h,async()=>{await bn(o,i,h)})},serverQuery:yn}},Ja=e=>Vt(e),qa=e=>typeof e=="function"?{fetch:e}:e,Ya=e=>!!(e.crons??e.cronJobs??e.backupCron),ys=(e,n)=>{const t=qa(e),r=typeof e=="object"&&typeof e.scheduled=="function"?e.scheduled:void 0,a=l=>{const u=Ja({...l,httpRouter:t});return r!==void 0&&!Ya(l)?{...u,scheduled:async(f,g,E)=>{await r(f,g,E)}}:u};if(typeof n!="function")return a(n);const s=n;return{fetch:(l,u,f)=>a(s(u)).fetch(l,u,f),queue:(l,u,f)=>a(s(u)).queue?.(l,u,f)??Promise.resolve(),scheduled:(l,u,f)=>a(s(u)).scheduled(l,u,f),serverQuery:(l,u,f,g,E)=>a(s(u)).serverQuery(l,u,f,g,E)}},Xa=(e,n)=>{if(typeof e=="function")return e(n);const t=e.shardDO??n?.SHARD;if(!t)throw new d("@lunora/runtime: no shard Durable Object namespace found. Bind `SHARD` in wrangler.jsonc, or pass `createLunoraHandler({ shardDO: env.MY_SHARD })`.");return{...e,shardDO:t}},bs=(e={})=>(n,t,r)=>Vt(Xa(e,t)).fetch(n,t,r??Un),_s=e=>e;export{Ur as GET_AUTH_AUDIT_LOG_OP,Un as NOOP_EXECUTION_CONTEXT,As as composeIdentityResolvers,Ja as composeWorker,bs as createLunoraHandler,Vt as createWorker,_s as defineRpcEnvelope,Ga as probeRelayCount,Xa as resolveLunoraOptions,Ss as routeIdentityResolvers,ys as withFrameworkWorker};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{t as E}from"./portable-json-BAMIgqk5.mjs";const j=e=>new Promise(t=>{setTimeout(t,e)}),C=e=>{const t=typeof e.table=="string"?e.table:"",r=typeof e.op=="string"?e.op:"",s=r==="delete"||r==="insert"||r==="update"?r:"upsert",n=typeof e.id=="string"?e.id:void 0,o=e.doc&&typeof e.doc=="object"?E(e.doc):void 0,i=typeof e.seq=="number"&&Number.isFinite(e.seq)?e.seq:void 0,c=typeof e.ts=="number"&&Number.isFinite(e.ts)?e.ts:void 0;return{op:s,table:t,...o===void 0?{}:{doc:o},...n===void 0?{}:{id:n},...i===void 0?{}:{seq:i},...c===void 0?{}:{ts:c}}},$=async(e,t,r,s,n,o)=>{let i=0;for(;;)try{await e.deliver(t);return}catch(c){if(i>=r)throw c instanceof Error?c:new Error(String(c));const d=Math.min(s*2**i,n);await o(d),i+=1}},M=async e=>{const{coordinator:t,cursorStore:r,headers:s,initialBackoffMs:n=100,limit:o,maxBackoffMs:i=5e3,maxRetries:c=3,shardDO:d,sink:p,sleep:g=j,tables:w}=e,f=await r.read(p.name),v=await t.orchestrateCdcSync(d,{cursors:f,headers:s,limit:o,tables:w}),h={...f},y=[];let x=0,l=!1;for(const a of v.shards){if(a.error){y.push({error:a.error.message,shardKey:a.shardKey}),l=!0;continue}const m=a.changes??[];if(m.length===0){h[a.shardKey]=a.cursor;continue}const k=m.map(u=>C(u)),K={changes:k,cursor:a.cursor,shardKey:a.shardKey,sink:p.name};try{await $(p,K,c,n,i,g),h[a.shardKey]=a.cursor,x+=k.length,o!==void 0&&m.length>=o&&(l=!0)}catch(u){y.push({error:u instanceof Error?u.message:String(u),shardKey:a.shardKey}),l=!0}}return await r.write(p.name,h),{cursors:h,delivered:x,failures:y,hasMore:l,shards:v.shards.length}},S=e=>{if(typeof e.name!="string"||e.name.length===0)throw new Error("defineExportSink: `name` must be a non-empty string");if(typeof e.deliver!="function")throw new TypeError("defineExportSink: `deliver` must be a function");return{deliver:e.deliver,name:e.name}},b=e=>`${e.map(t=>JSON.stringify(t)).join(`
|
|
2
|
+
`)}
|
|
3
|
+
`,N=e=>{const t=e.fetchImpl??((r,s)=>fetch(r,s));return S({deliver:async r=>{const s=await t(e.url,{body:b(r.changes),headers:{"content-type":"application/x-ndjson","x-lunora-cursor":String(r.cursor),"x-lunora-shard":r.shardKey,"x-lunora-sink":r.sink,...e.headers},method:"POST"});if(!s.ok)throw new Error(`webhook export sink "${e.name}" returned ${String(s.status)}`)},name:e.name})},O=e=>{let t=e.prefix??"cdc";for(;t.endsWith("/");)t=t.slice(0,-1);return S({deliver:async r=>{const s=`${t}/${r.shardKey}/${String(r.cursor)}.ndjson`;await e.bucket.put(s,b(r.changes),{httpMetadata:{contentType:"application/x-ndjson"}})},name:e.name})},T=()=>{const e={};return{read:t=>Promise.resolve({...e[t]}),snapshot:()=>structuredClone(e),write:(t,r)=>(e[t]={...r},Promise.resolve())}},q=(e,t)=>{const r=t?.keyPrefix??"__lunora_source_cursor:export",s=n=>`${r}:${n}`;return{read:async n=>{const o=await e.get(s(n),"json");if(o===null||typeof o!="object")return{};const i={};for(const[c,d]of Object.entries(o))typeof d=="number"&&Number.isFinite(d)&&(i[c]=d);return i},write:async(n,o)=>{await e.put(s(n),JSON.stringify(o))}}};export{q as createKvCursorStore,T as createMemoryCursorStore,S as defineExportSink,O as r2Sink,M as runExportTap,C as sanitizeChange,N as webhookExportSink};
|
package/dist/packem_shared/{createShardClient-DnQNYYNU.mjs → createShardClient-CCncsgTs.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as n}from"@lunora/errors";import{e as S,a as w}from"./identity-header-JF5q3H5w.mjs";import{e as g,d as f}from"./wire-codec-
|
|
1
|
+
import{LunoraError as n}from"@lunora/errors";import{e as S,a as w}from"./identity-header-JF5q3H5w.mjs";import{e as g,d as f}from"./wire-codec-D_qTfaaH.mjs";import{applyJurisdiction as p,resolveShard as N}from"./applyJurisdiction-C0ddU7Tg.mjs";const I=e=>{if(typeof e=="string")return e;const t=e?.__lunoraRef;if(typeof t!="string"||t.length===0)throw new n("INTERNAL","createShardClient: expected a generated function reference (api.*/internal.*) or a 'namespace:fn' string");return t},x=e=>{const t=new n(e.code,e.message);return e.data!==void 0&&(t.data=f(e.data)),t},$=(e,t={})=>{const l=p(e,t.jurisdiction),m=t.system??!0,c=r=>$(e,{...t,...r});return{as:r=>c({as:r}),asSystem:()=>c({as:void 0}),call:async(r,y,o)=>{const d=I(r),h=o?.shardKey??t.shardKey;if(h===void 0||h.length===0)throw new n("INTERNAL",`createShardClient: no shard key for "${d}" — pass one to createShardClient({ shardKey }), .forShard(key), or the call's options`);const s={"content-type":"application/json"};m&&(s["x-lunora-system"]="1"),t.as&&(s["x-lunora-userid"]=S(t.as.userId),t.as.claims&&(s["x-lunora-identity"]=w(t.as.claims))),o?.mutationId!==void 0&&o.mutationId.length>0&&(s["x-lunora-mutation-id"]=o.mutationId);const a=await N(l,h).fetch(new Request("https://shard.internal/rpc",{body:JSON.stringify({args:g(y??{}),functionPath:d}),headers:s,method:"POST"})),u=a.statusText?` ${a.statusText}`:"";let i;try{i=await a.json()}catch{throw new n("INTERNAL",`createShardClient: shard response for "${d}" was not JSON (status ${String(a.status)}${u})`)}if("error"in i)throw x(i.error);if(!a.ok)throw new n("INTERNAL",`createShardClient: shard call "${d}" failed (status ${String(a.status)}${u})`);return f(i.result)},forShard:r=>c({shardKey:r})}};export{$ as createShardClient};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as
|
|
1
|
+
import{LunoraError as m}from"./LunoraError-DksAgIpa.mjs";const O="default-src 'none'; frame-ancestors 'none'; base-uri 'none'; form-action 'none'",E=e=>{const o=["base-uri 'none'","object-src 'none'"];return e==="DENY"?o.push("frame-ancestors 'none'"):e==="SAMEORIGIN"&&o.push("frame-ancestors 'self'"),o.join("; ")},y="accelerometer=(), autoplay=(), camera=(), display-capture=(), geolocation=(), gyroscope=(), magnetometer=(), microphone=(), payment=(), usb=()",d=["Authorization","Content-Type","X-D1-Bookmark","X-Lunora-Client-Id","X-Lunora-Client-Seq","X-Lunora-Min-Seq","X-Lunora-Mutation-Id"],u=["DELETE","GET","HEAD","PATCH","POST","PUT"],S=31536e3,L=new Set(["GET","HEAD","OPTIONS"]),A=e=>{if(e===!1)return;const o=e===void 0||e===!0?{}:e,s=o.maxAge??S,r=o.includeSubDomains??!0;return`max-age=${String(s)}${r?"; includeSubDomains":""}${o.preload?"; preload":""}`},b=(e,o)=>{if(e!==!1)return typeof e=="string"?{htmlValue:e,value:e}:{htmlValue:o,value:O}},C=e=>{if(e===!1)return{coop:void 0,csp:void 0,enabled:!1,frameOptions:void 0,hsts:void 0,permissionsPolicy:void 0,referrerPolicy:void 0};const o=e===void 0||e===!0?{}:e,s=o.frameOptions===!1?void 0:o.frameOptions??"SAMEORIGIN";return{coop:"same-origin",csp:b(o.csp,E(s)),enabled:!0,frameOptions:s,hsts:A(o.hsts),permissionsPolicy:o.permissionsPolicy===!1?void 0:o.permissionsPolicy??y,referrerPolicy:o.referrerPolicy===!1?void 0:o.referrerPolicy??"strict-origin-when-cross-origin"}},v=e=>{const o={allowCredentials:!1,allowedHeaders:d,allowedMethods:u,enabled:!1,isAllowed:()=>!1,isExplicitlyAllowed:()=>!1,maxAge:600};if(e===void 0||e===!1)return o;const s=e.allowCredentials??!1,r=e.allowedOrigins;let t,n;if(typeof r=="function")t=r,n=r,console.warn(`@lunora/runtime: security.cors uses a custom \`allowedOrigins\` predicate. It is trusted by the CSRF and WebSocket origin checks${s?" AND reflects matching origins with credentials (`allowCredentials: true`)":""} — ensure it matches ONLY trusted origins by exact equality; an over-broad predicate (e.g. \`() => true\`, or \`endsWith\`/\`includes\` checks) defeats the allowlist.`);else{const l=r;if(l.includes("*")&&s)throw new m('@lunora/runtime: security.cors cannot combine a wildcard origin ("*") with allowCredentials: true — browsers reject it and it defeats the allowlist.');t=i=>l.includes("*")||l.includes(i),n=i=>l.includes(i)}return{allowCredentials:s,allowedHeaders:e.allowedHeaders??d,allowedMethods:e.allowedMethods??u,enabled:!0,isAllowed:t,isExplicitlyAllowed:n,maxAge:e.maxAge??600}},R=e=>{if(e===!1)return{allowLoopback:!1,enabled:!1,trustedOrigins:[]};const o=e===void 0||e===!0?{}:e;return{allowLoopback:o.allowLoopback??!0,enabled:!0,trustedOrigins:o.trustedOrigins??[]}},D=new Set(["0","disabled","false","no","off"]),_=new Set(["1","enabled","on","true","yes"]),f=e=>typeof e=="string"&&D.has(e.trim().toLowerCase()),N=e=>typeof e=="string"&&_.has(e.trim().toLowerCase()),H=e=>{const o=e?.LUNORA_ALLOWED_ORIGINS;if(typeof o!="string")return;const s=o.split(",").map(n=>n.trim()).filter(n=>n.length>0);return s.length===0?void 0:{allowCredentials:!s.includes("*")&&N(e?.LUNORA_CORS_ALLOW_CREDENTIALS),allowedOrigins:s}},M=(e,o)=>{const s=e?.headers??(f(o?.LUNORA_SECURITY_HEADERS)?!1:void 0),r=e?.csrf??(f(o?.LUNORA_SECURITY_CSRF)?!1:void 0),t=e?.cors??H(o);return{cors:v(t),csrf:R(r),headers:C(s)}},I=new Set(["127.0.0.1","::1","[::1]","localhost"]),p=e=>{try{return I.has(new URL(e).hostname)}catch{return!1}},c=e=>{if(e)try{return new URL(e).origin}catch{return}},h=(e,o,s)=>e===o||s.csrf.trustedOrigins.includes(e)||s.csrf.allowLoopback&&p(o)&&p(e)?!0:s.cors.enabled&&s.cors.isExplicitlyAllowed(e),w=(e,o,s)=>Response.json({error:{code:"FORBIDDEN_ORIGIN",expectedOrigin:s,message:`${e} rejected: Origin ${o===void 0?"was missing":`"${o}"`} is not trusted (this worker serves "${s}"). Add it to \`security.csrf.trustedOrigins\` (or LUNORA_ALLOWED_ORIGINS) if it is yours. Behind a dev proxy this usually means the proxy rewrote the host: keep both ends on loopback, or list the dev-server origin.`,receivedOrigin:o}},{headers:{"content-type":"application/json"},status:403}),j=(e,o)=>{if(!o.csrf.enabled||L.has(e.method)||!e.headers.get("cookie"))return;const s=new URL(e.url).origin,r=c(e.headers.get("origin"))??c(e.headers.get("referer"));if(!(r!==void 0&&h(r,s,o)))return w("cross-origin state-changing request",r,s)},F=(e,o)=>{if(!o.csrf.enabled||!e.headers.get("cookie"))return;const s=new URL(e.url).origin,r=c(e.headers.get("origin"));if(!(r!==void 0&&h(r,s,o)))return w("cross-origin websocket upgrade",r,s)},P=["X-D1-Bookmark","X-Lunora-Edge-Cache","X-Lunora-Shard-Key"],g=(e,o)=>{const s=new Headers;return s.set("access-control-allow-origin",e),s.set("access-control-expose-headers",P.join(", ")),s.append("vary","Origin"),o.allowCredentials&&s.set("access-control-allow-credentials","true"),s},X=(e,o)=>{if(!o.cors.enabled||e.method!=="OPTIONS")return;const s=e.headers.get("origin");if(!s||!e.headers.get("access-control-request-method")||!o.cors.isAllowed(s))return;const r=g(s,o.cors),t=e.headers.get("access-control-request-headers");r.set("access-control-allow-methods",o.cors.allowedMethods.join(", "));let n;if(t===null)n=o.cors.allowedHeaders.join(", ");else{const l=new Set(o.cors.allowedHeaders.map(i=>i.toLowerCase()));n=t.split(",").map(i=>i.trim()).filter(i=>i.length>0&&l.has(i.toLowerCase())).join(", ")}return r.set("access-control-allow-headers",n),r.set("access-control-max-age",String(o.cors.maxAge)),new Response(null,{headers:r,status:204})},T=e=>(e.headers.get("content-type")??"").toLowerCase().includes("text/html"),a=(e,o,s)=>{e.has(o)||e.set(o,s)},x=(e,o,s,r)=>{if(r.hsts!==void 0&&new URL(o.url).protocol==="https:"&&a(e,"strict-transport-security",r.hsts),a(e,"x-content-type-options","nosniff"),r.frameOptions!==void 0&&a(e,"x-frame-options",r.frameOptions),r.referrerPolicy!==void 0&&a(e,"referrer-policy",r.referrerPolicy),r.permissionsPolicy!==void 0&&a(e,"permissions-policy",r.permissionsPolicy),r.coop!==void 0&&a(e,"cross-origin-opener-policy",r.coop),r.csp!==void 0){const t=T(s)?r.csp.htmlValue:r.csp.value;t!==void 0&&a(e,"content-security-policy",t)}},k=(e,o,s)=>{const r=o.headers.get("origin");if(!(!r||!s.isAllowed(r)))for(const[t,n]of g(r,s).entries())t==="vary"?e.append("vary",n):a(e,t,n)},B=(e,o,s)=>{if(e.status===101||e.webSocket)return e;const r=new Headers(e.headers);return s.headers.enabled&&x(r,o,e,s.headers),s.cors.enabled&&k(r,o,s.cors),new Response(e.body,{headers:r,status:e.status,statusText:e.statusText})};export{B as decorateResponse,j as enforceOrigin,F as enforceWebSocketOrigin,X as handleCorsPreflight,M as resolveSecurity};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{t as i}from"./base64-CMlwEPti.mjs";import{d as f,i as s}from"./wire-codec-D_qTfaaH.mjs";const o=r=>{if(typeof r=="bigint")return r.toString();if(r instanceof ArrayBuffer)return i(new Uint8Array(r));if(ArrayBuffer.isView(r))return i(new Uint8Array(r.buffer,r.byteOffset,r.byteLength));if(Array.isArray(r))return r.map(t=>o(t));if(s(r)){const t={};for(const e of Object.keys(r)){const n=o(r[e]);e==="__proto__"?Object.defineProperty(t,e,{configurable:!0,enumerable:!0,value:n,writable:!0}):t[e]=n}return t}return r},y=r=>o(f(r));export{y as t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const v="/_lunora/rest",m=["authorization","cf-access-jwt-assertion","cookie","x-payment"],d=["x-d1-bookmark","x-lunora-shard-key"],h=e=>[...m,...(e.credentialHeaders??[]).map(t=>t.toLowerCase())],u=e=>Number.isFinite(e)?Math.max(0,Math.floor(e)):0,c=(...e)=>{const t=[];for(const a of e)for(const s of a?.split(",")??[]){const n=s.trim().toLowerCase();n!==""&&!t.includes(n)&&t.push(n)}return t.length===0?void 0:t.join(", ")},l=(e,t)=>{const a=[t,`max-age=${String(u(e.maxAge))}`];return e.staleWhileRevalidate!==void 0&&a.push(`stale-while-revalidate=${String(u(e.staleWhileRevalidate))}`),a.join(", ")},p=e=>e.scope==="public"?c(e.vary,...h(e),...d):c(e.vary,...d),f=e=>{const t=e.indexOf(":");if(!(t<=0||t>=e.length-1||e.indexOf(":",t+1)!==-1))return{name:e.slice(t+1),namespace:e.slice(0,t)}},g=e=>{const t=f(e);if(t!==void 0)return`${v}/${t.namespace}/${t.name}`},E=e=>e==="query"?"GET":"POST",S=e=>{const t=[];for(const a of e){if(a.exposure?.rest!==!0||a.kind==="stream")continue;const s=f(a.functionPath),n=g(a.functionPath);s===void 0||n===void 0||t.push({functionPath:a.functionPath,kind:a.kind,method:E(a.kind),name:s.name,namespace:s.namespace,path:n})}return t.sort((a,s)=>a.path.localeCompare(s.path)),t},R=(e,t,a)=>a?.access!==void 0||h(t).some(s=>e.headers.has(s)),x=(e,t,a)=>e.scope==="public"&&!R(t,e,a)?"public":"private",C=(e,t,a,s)=>{if(t.method!=="GET"||a<200||a>299)return;const n={"cache-control":l(e,x(e,t,s))};e.tag!==void 0&&e.tag!==""&&(n["cache-tag"]=e.tag);const r=p(e);return r!==void 0&&(n.vary=r),n},b=(e,t,a,s)=>{if(t===void 0)return e;const n=C(t,a,e.status,s);if(n===void 0)return e;const r=new Response(e.body,e);for(const[i,o]of Object.entries(n))r.headers.set(i,i==="vary"?c(r.headers.get("vary")??void 0,o)??o:o);return r};export{b as a,C as b,u as c,p as d,x as e,S as f,R as r};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{c as S,d as T,e as O,a as P,f as B}from"./rest-cache-CPSyD1RD.mjs";import{LunoraError as l}from"./LunoraError-DksAgIpa.mjs";import{m as D}from"./method-guard-BG_vJNTl.mjs";const w=1048576,p=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),U=async(t,r=w)=>{if(!t.body)return"";const e=t.body.getReader(),a=new TextDecoder;let s=0,i="";for(;;){const{done:o,value:n}=await e.read();if(o)break;if(n){if(s+=n.byteLength,s>r)throw await e.cancel().catch(()=>{}),new l("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});i+=a.decode(n,{stream:!0})}}return i+=a.decode(),i},W=async(t,r=w)=>{if(!t.body)return new ArrayBuffer(0);const e=t.body.getReader(),a=[];let s=0;for(;;){const{done:n,value:c}=await e.read();if(n)break;if(c){if(s+=c.byteLength,s>r)throw await e.cancel().catch(()=>{}),new l("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});a.push(c)}}const i=new Uint8Array(s);let o=0;for(const n of a)i.set(n,o),o+=n.byteLength;return i.buffer},j=async(t,r,e=w)=>{try{const a=await U(t,e);return a===""?{}:JSON.parse(a)}catch(a){throw a instanceof l?a:new l(`${r} body must be valid JSON`,{code:"BAD_REQUEST",status:400})}},I=async(t,r=w)=>{const e=await j(t,"Request",r);if(!p(e))throw new l("Request body must be an object",{code:"BAD_REQUEST",status:400});return e},x=(t,r)=>{if(!p(t))throw new l(`${r} \`args\` must be an object`,{code:"BAD_REQUEST",status:400})},R="__lunora_vary",G="x-lunora-edge-cache",C=["x-d1-bookmark","x-lunora-shard-key"],M=()=>{try{return globalThis.caches?.default}catch{return}},L=t=>t.split(",").map(r=>r.trim().toLowerCase()).filter(r=>r!==""),J=(t,r)=>{const e=t.headers.get("vary");return e===null?!0:L(e).every(a=>a!=="*"&&r.includes(a))},Y=(t,r)=>{if(t===void 0||r===null||t.scope!=="public"||S(t.maxAge)<=0)return;const e=()=>r??M(),a=L(T(t)??""),s=o=>{const n=new URL(o.url);return n.searchParams.delete(R),a.length>0&&n.searchParams.set(R,a.map(c=>`${c}=${o.headers.get(c)??""}`).join("\0")),new Request(n.toString(),{method:"GET"})},i=(o,n)=>o.method==="GET"&&O(t,o,n)==="public";return{lookup:async(o,n)=>{const c=e();if(c===void 0||!i(o,n))return;let u;try{u=await c.match(s(o))}catch{return}if(u===void 0)return;const h=new Response(u.body,u);return h.headers.set(G,"hit"),h},store:(o,n,c)=>{const u=e();if(u===void 0||!i(n,c)||o.status!==200||o.headers.has("set-cookie")||o.headers.has("x-payment-response")||!J(o,a))return o;try{const h=new Response(o.clone().body,o);for(const b of C)h.headers.delete(b);const d=Promise.resolve(u.put(s(n),h)).catch(()=>{});c?.waitUntil&&c.waitUntil(d)}catch{}return o}}},H=t=>B(Object.entries(t).map(([r,e])=>({exposure:e.expose,functionPath:r,kind:e.kind}))),K=(t,r)=>{const e=t.searchParams.get("shardKey");if(e!==null&&e!=="")return e;const a=r.headers.get("x-lunora-shard-key");return a===null||a===""?void 0:a},Q=t=>{const r=Object.create(null);for(const[e,a]of t.searchParams.entries())if(!(e==="shardKey"||e===R))try{r[e]=JSON.parse(a)}catch{r[e]=a}return r},X=t=>{const{edgeCache:r,functions:e,invoke:a,rateLimit:s,readJsonBody:i}=t,o={};for(const n of H(e)){const c=n.kind==="query"?["GET","POST"]:["POST"],u=e[n.functionPath].expose?.cache,h=Y(u,r);o[n.path]=async(d,b,F,f)=>{const g=D(d,c);if(g)return g;const v=new URL(d.url);if(s){const m=await s(d,n.functionPath);if(m)return m}const E=await h?.lookup(d,f);if(E)return E;let y;d.method==="GET"?y=Q(v):y=d.body===null?{}:await i(d),x(y,"REST");const A=K(v,d),_=await a({args:y,env:b,functionPath:n.functionPath,request:d,...A===void 0?{}:{shardKey:A},...f?.waitUntil===void 0?{}:{waitUntil:m=>f.waitUntil?.(m)}}),k=P(_,u,d,f);return h?h.store(k,d,f):k}}return o},z=(t,r)=>async(e,a)=>{const s=r.key?r.key(e,a):e.headers.get("cf-connecting-ip")??void 0,i=await t.limit(r.name,s===void 0?{}:{key:s});if(i.ok)return;const o=Math.max(1,Math.ceil(i.retryAfter/1e3));return Response.json({error:{code:"RATE_LIMITED",message:"Rate limit exceeded"}},{headers:{"content-type":"application/json","retry-after":String(o)},status:429})};export{w as M,Q as a,X as b,z as c,H as d,I as e,j as f,W as g,x as h,U as i,K as r};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{t as b}from"./portable-json-BAMIgqk5.mjs";const p="_id",f=(t,n=p)=>{const o=Object.create(null),s=Object.create(null),c=Object.create(null),a=Object.create(null),h=e=>typeof n=="string"?n:n[e]??p,l=(e,r)=>{const u=e[r];if(u)return u;const d=[];return e[r]=d,d};for(const e of t.changes){a[e.table]??={primary_key:[h(e.table)]};const r=b(e.doc);e.op==="delete"?l(c,e.table).push(r):e.op==="update"?l(s,e.table).push(r):l(o,e.table).push(r)}return{delete:c,hasMore:t.hasMore,insert:o,schema:a,state:{cursor:t.nextCursor},update:s}},m=(t,n=Date.now())=>{const o=[];for(const s of t.changes){const c=b(s.doc),a=s.op==="delete"?{...c,_lunora_deleted:!0}:c;o.push({record:{data:a,emitted_at:n,stream:s.table},type:"RECORD"})}return o.push({state:{data:{cursor:t.nextCursor}},type:"STATE"}),o};export{m as toAirbyteMessages,f as toFivetranResponse};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{t as w,f as O}from"./base64-CMlwEPti.mjs";const o="$lunora.wire$",m=64,A=1024,d="__proto__",p={BigInt64Array,BigUint64Array,Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array},E={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError},j=e=>{if(e===null||typeof e!="object")return!1;const t=Object.getPrototypeOf(e);return t===null||t===Object.prototype},a=(e,t=0)=>{if(t>m)throw new RangeError(`wire-codec: value nesting exceeds the ${m}-level limit`);if(e===void 0)return[o,"undefined"];if(e===null)return null;const y=typeof e;if(y==="bigint")return[o,"bigint",e.toString()];if(y==="number"){const r=e;return Number.isNaN(r)?[o,"nan"]:r===1/0?[o,"inf"]:r===-1/0?[o,"-inf"]:r}if(y!=="object")return e;if(e instanceof Date)return[o,"date",a(e.getTime(),t+1)];if(e instanceof Error){const r=e,n={};for(const c of Object.keys(r))r[c]!==void 0&&(n[c]=a(r[c],t+1));const i=[o,"error",r.name,r.message,n];return r.cause!==void 0&&i.push(a(r.cause,t+1)),i}if(e instanceof URL)return[o,"url",e.href];if(e instanceof Map)return[o,"map",[...e.entries()].map(([r,n])=>[a(r,t+1),a(n,t+1)])];if(e instanceof Set)return[o,"set",[...e].map(r=>a(r,t+1))];if(e instanceof ArrayBuffer)return[o,"bytes",w(new Uint8Array(e)),"ArrayBuffer"];if(ArrayBuffer.isView(e)){const r=e,n=r.constructor.name,i=new Uint8Array(r.buffer,r.byteOffset,r.byteLength);return n==="Uint8Array"?[o,"bytes",w(i)]:[o,"bytes",w(i),n]}if(Array.isArray(e)){const r=e.map(n=>a(n,t+1));return r.length>0&&r[0]===o?[o,"arr",r]:r}if(!j(e)){const r=e.constructor?.name??"value";throw new TypeError(`wire-codec: cannot encode a ${r} over the Lunora wire — only plain objects, arrays, and the supported built-ins (Date, Error, URL, Map, Set, ArrayBuffer/typed arrays, bigint) round-trip`)}const u=e,s={};for(const r of Object.keys(u)){const n=u[r];if(n===void 0)continue;const i=a(n,t+1);r===d?Object.defineProperty(s,r,{configurable:!0,enumerable:!0,value:i,writable:!0}):s[r]=i}return s},f=(e,t=0)=>{if(t>m)throw new RangeError(`wire-codec: value nesting exceeds the ${m}-level limit`);if(e===null||typeof e!="object")return e;if(Array.isArray(e)){if(e[0]===o)switch(e[1]){case"-inf":return-1/0;case"arr":return e[2].map(r=>f(r,t+1));case"bigint":{const r=e[2];if(typeof r!="string"||r.length>A||!/^-?\d+$/.test(r))throw new RangeError(`wire-codec: invalid or over-long bigint (max ${A} digits)`);return BigInt(r)}case"date":return new Date(f(e[2],t+1));case"map":return new Map(e[2].map(([r,n])=>[f(r,t+1),f(n,t+1)]));case"set":return new Set(e[2].map(r=>f(r,t+1)));case"url":return new URL(e[2]);case"error":{const r=e[2],n=e[3],i=(Object.hasOwn(E,r)?E[r]:void 0)??Error,c=new i(n);c.name!==r&&Object.defineProperty(c,"name",{configurable:!0,value:r,writable:!0});const g=f(e[4],t+1);for(const b of Object.keys(g))b===d?Object.defineProperty(c,b,{configurable:!0,enumerable:!0,value:g[b],writable:!0}):c[b]=g[b];return e.length>5&&Object.defineProperty(c,"cause",{configurable:!0,value:f(e[5],t+1),writable:!0}),c}case"bytes":{const r=O(e[2]),n=e[3]??"Uint8Array";if(n==="ArrayBuffer")return r.buffer.byteLength===r.byteLength?r.buffer:r.slice().buffer;const i=Object.hasOwn(p,n)?p[n]:void 0;return i?new i(r.slice().buffer):r}case"inf":return 1/0;case"nan":return Number.NaN;case"undefined":return;default:return e.map(r=>f(r,t+1))}return e.map(s=>f(s,t+1))}const y=e,u={};for(const s of Object.keys(y)){const r=f(y[s],t+1);s===d?Object.defineProperty(u,s,{configurable:!0,enumerable:!0,value:r,writable:!0}):u[s]=r}return u};export{f as d,a as e};
|
|
1
|
+
import{t as w,f as O}from"./base64-CMlwEPti.mjs";const o="$lunora.wire$",m=64,A=1024,d="__proto__",p={BigInt64Array,BigUint64Array,Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array},E={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError},j=e=>{if(e===null||typeof e!="object")return!1;const t=Object.getPrototypeOf(e);return t===null||t===Object.prototype},a=(e,t=0)=>{if(t>m)throw new RangeError(`wire-codec: value nesting exceeds the ${m}-level limit`);if(e===void 0)return[o,"undefined"];if(e===null)return null;const y=typeof e;if(y==="bigint")return[o,"bigint",e.toString()];if(y==="number"){const r=e;return Number.isNaN(r)?[o,"nan"]:r===1/0?[o,"inf"]:r===-1/0?[o,"-inf"]:r}if(y!=="object")return e;if(e instanceof Date)return[o,"date",a(e.getTime(),t+1)];if(e instanceof Error){const r=e,n={};for(const c of Object.keys(r))r[c]!==void 0&&(n[c]=a(r[c],t+1));const i=[o,"error",r.name,r.message,n];return r.cause!==void 0&&i.push(a(r.cause,t+1)),i}if(e instanceof URL)return[o,"url",e.href];if(e instanceof Map)return[o,"map",[...e.entries()].map(([r,n])=>[a(r,t+1),a(n,t+1)])];if(e instanceof Set)return[o,"set",[...e].map(r=>a(r,t+1))];if(e instanceof ArrayBuffer)return[o,"bytes",w(new Uint8Array(e)),"ArrayBuffer"];if(ArrayBuffer.isView(e)){const r=e,n=r.constructor.name,i=new Uint8Array(r.buffer,r.byteOffset,r.byteLength);return n==="Uint8Array"?[o,"bytes",w(i)]:[o,"bytes",w(i),n]}if(Array.isArray(e)){const r=e.map(n=>a(n,t+1));return r.length>0&&r[0]===o?[o,"arr",r]:r}if(!j(e)){const r=e.constructor?.name??"value";throw new TypeError(`wire-codec: cannot encode a ${r} over the Lunora wire — only plain objects, arrays, and the supported built-ins (Date, Error, URL, Map, Set, ArrayBuffer/typed arrays, bigint) round-trip`)}const u=e,s={};for(const r of Object.keys(u)){const n=u[r];if(n===void 0)continue;const i=a(n,t+1);r===d?Object.defineProperty(s,r,{configurable:!0,enumerable:!0,value:i,writable:!0}):s[r]=i}return s},f=(e,t=0)=>{if(t>m)throw new RangeError(`wire-codec: value nesting exceeds the ${m}-level limit`);if(e===null||typeof e!="object")return e;if(Array.isArray(e)){if(e[0]===o)switch(e[1]){case"-inf":return-1/0;case"arr":return e[2].map(r=>f(r,t+1));case"bigint":{const r=e[2];if(typeof r!="string"||r.length>A||!/^-?\d+$/.test(r))throw new RangeError(`wire-codec: invalid or over-long bigint (max ${A} digits)`);return BigInt(r)}case"date":return new Date(f(e[2],t+1));case"map":return new Map(e[2].map(([r,n])=>[f(r,t+1),f(n,t+1)]));case"set":return new Set(e[2].map(r=>f(r,t+1)));case"url":return new URL(e[2]);case"error":{const r=e[2],n=e[3],i=(Object.hasOwn(E,r)?E[r]:void 0)??Error,c=new i(n);c.name!==r&&Object.defineProperty(c,"name",{configurable:!0,value:r,writable:!0});const g=f(e[4],t+1);for(const b of Object.keys(g))b===d?Object.defineProperty(c,b,{configurable:!0,enumerable:!0,value:g[b],writable:!0}):c[b]=g[b];return e.length>5&&Object.defineProperty(c,"cause",{configurable:!0,value:f(e[5],t+1),writable:!0}),c}case"bytes":{const r=O(e[2]),n=e[3]??"Uint8Array";if(n==="ArrayBuffer")return r.buffer.byteLength===r.byteLength?r.buffer:r.slice().buffer;const i=Object.hasOwn(p,n)?p[n]:void 0;return i?new i(r.slice().buffer):r}case"inf":return 1/0;case"nan":return Number.NaN;case"undefined":return;default:return e.map(r=>f(r,t+1))}return e.map(s=>f(s,t+1))}const y=e,u={};for(const s of Object.keys(y)){const r=f(y[s],t+1);s===d?Object.defineProperty(u,s,{configurable:!0,enumerable:!0,value:r,writable:!0}):u[s]=r}return u};export{f as d,a as e,j as i};
|
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.72",
|
|
4
4
|
"description": "Lunora Worker runtime: the RPC router, shard resolver, and query coordinator",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cloudflare",
|
|
@@ -46,9 +46,9 @@
|
|
|
46
46
|
"access": "public"
|
|
47
47
|
},
|
|
48
48
|
"dependencies": {
|
|
49
|
-
"@lunora/bindings": "1.0.0-alpha.
|
|
49
|
+
"@lunora/bindings": "1.0.0-alpha.36",
|
|
50
50
|
"@lunora/errors": "1.0.0-alpha.22",
|
|
51
|
-
"@lunora/platform": "1.0.0-alpha.
|
|
51
|
+
"@lunora/platform": "1.0.0-alpha.17"
|
|
52
52
|
},
|
|
53
53
|
"engines": {
|
|
54
54
|
"node": "^22.15.0 || >=24.11.0"
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a as r,r as s,b as t}from"./rest-cache-BnMq2hbO.mjs";export{r as applyRestCache,s as requestCarriesCredentials,t as restCacheHeaders};
|
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
const E=e=>new Promise(t=>{setTimeout(t,e)}),j=e=>{const t=typeof e.table=="string"?e.table:"",r=typeof e.op=="string"?e.op:"",s=r==="delete"||r==="insert"||r==="update"?r:"upsert",o=typeof e.id=="string"?e.id:void 0,n=e.doc&&typeof e.doc=="object"?e.doc:void 0,i=typeof e.seq=="number"&&Number.isFinite(e.seq)?e.seq:void 0,c=typeof e.ts=="number"&&Number.isFinite(e.ts)?e.ts:void 0;return{op:s,table:t,...n===void 0?{}:{doc:n},...o===void 0?{}:{id:o},...i===void 0?{}:{seq:i},...c===void 0?{}:{ts:c}}},C=async(e,t,r,s,o,n)=>{let i=0;for(;;)try{await e.deliver(t);return}catch(c){if(i>=r)throw c instanceof Error?c:new Error(String(c));const d=Math.min(s*2**i,o);await n(d),i+=1}},$=async e=>{const{coordinator:t,cursorStore:r,headers:s,initialBackoffMs:o=100,limit:n,maxBackoffMs:i=5e3,maxRetries:c=3,shardDO:d,sink:h,sleep:w=E,tables:b}=e,f=await r.read(h.name),v=await t.orchestrateCdcSync(d,{cursors:f,headers:s,limit:n,tables:b}),p={...f},y=[];let x=0,l=!1;for(const a of v.shards){if(a.error){y.push({error:a.error.message,shardKey:a.shardKey}),l=!0;continue}const m=a.changes??[];if(m.length===0){p[a.shardKey]=a.cursor;continue}const k=m.map(u=>j(u)),K={changes:k,cursor:a.cursor,shardKey:a.shardKey,sink:h.name};try{await C(h,K,c,o,i,w),p[a.shardKey]=a.cursor,x+=k.length,n!==void 0&&m.length>=n&&(l=!0)}catch(u){y.push({error:u instanceof Error?u.message:String(u),shardKey:a.shardKey}),l=!0}}return await r.write(h.name,p),{cursors:p,delivered:x,failures:y,hasMore:l,shards:v.shards.length}},S=e=>{if(typeof e.name!="string"||e.name.length===0)throw new Error("defineExportSink: `name` must be a non-empty string");if(typeof e.deliver!="function")throw new TypeError("defineExportSink: `deliver` must be a function");return{deliver:e.deliver,name:e.name}},g=e=>`${e.map(t=>JSON.stringify(t)).join(`
|
|
2
|
-
`)}
|
|
3
|
-
`,M=e=>{const t=e.fetchImpl??((r,s)=>fetch(r,s));return S({deliver:async r=>{const s=await t(e.url,{body:g(r.changes),headers:{"content-type":"application/x-ndjson","x-lunora-cursor":String(r.cursor),"x-lunora-shard":r.shardKey,"x-lunora-sink":r.sink,...e.headers},method:"POST"});if(!s.ok)throw new Error(`webhook export sink "${e.name}" returned ${String(s.status)}`)},name:e.name})},N=e=>{let t=e.prefix??"cdc";for(;t.endsWith("/");)t=t.slice(0,-1);return S({deliver:async r=>{const s=`${t}/${r.shardKey}/${String(r.cursor)}.ndjson`;await e.bucket.put(s,g(r.changes),{httpMetadata:{contentType:"application/x-ndjson"}})},name:e.name})},O=()=>{const e={};return{read:t=>Promise.resolve({...e[t]}),snapshot:()=>structuredClone(e),write:(t,r)=>(e[t]={...r},Promise.resolve())}},P=(e,t)=>{const r=t?.keyPrefix??"__lunora_source_cursor:export",s=o=>`${r}:${o}`;return{read:async o=>{const n=await e.get(s(o),"json");if(n===null||typeof n!="object")return{};const i={};for(const[c,d]of Object.entries(n))typeof d=="number"&&Number.isFinite(d)&&(i[c]=d);return i},write:async(o,n)=>{await e.put(s(o),JSON.stringify(n))}}};export{P as createKvCursorStore,O as createMemoryCursorStore,S as defineExportSink,N as r2Sink,$ as runExportTap,j as sanitizeChange,M as webhookExportSink};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
const v="/_lunora/rest",m=["authorization","cf-access-jwt-assertion","cookie"],d=["x-d1-bookmark","x-lunora-shard-key"],h=e=>[...m,...(e.credentialHeaders??[]).map(t=>t.toLowerCase())],u=e=>Number.isFinite(e)?Math.max(0,Math.floor(e)):0,i=(...e)=>{const t=[];for(const a of e)for(const r of a?.split(",")??[]){const n=r.trim().toLowerCase();n!==""&&!t.includes(n)&&t.push(n)}return t.length===0?void 0:t.join(", ")},l=(e,t)=>{const a=[t,`max-age=${String(u(e.maxAge))}`];return e.staleWhileRevalidate!==void 0&&a.push(`stale-while-revalidate=${String(u(e.staleWhileRevalidate))}`),a.join(", ")},p=e=>e.scope==="public"?i(e.vary,...h(e),...d):i(e.vary,...d),f=e=>{const t=e.indexOf(":");if(!(t<=0||t>=e.length-1||e.indexOf(":",t+1)!==-1))return{name:e.slice(t+1),namespace:e.slice(0,t)}},g=e=>{const t=f(e);if(t!==void 0)return`${v}/${t.namespace}/${t.name}`},E=e=>e==="query"?"GET":"POST",S=e=>{const t=[];for(const a of e){if(a.exposure?.rest!==!0||a.kind==="stream")continue;const r=f(a.functionPath),n=g(a.functionPath);r===void 0||n===void 0||t.push({functionPath:a.functionPath,kind:a.kind,method:E(a.kind),name:r.name,namespace:r.namespace,path:n})}return t.sort((a,r)=>a.path.localeCompare(r.path)),t},C=(e,t,a)=>a?.access!==void 0||h(t).some(r=>e.headers.has(r)),R=(e,t,a,r)=>{if(t.method!=="GET"||a<200||a>299)return;const n=e.scope==="public"&&!C(t,e,r)?"public":"private",s={"cache-control":l(e,n)};e.tag!==void 0&&e.tag!==""&&(s["cache-tag"]=e.tag);const o=p(e);return o!==void 0&&(s.vary=o),s},b=(e,t,a,r)=>{if(t===void 0)return e;const n=R(t,a,e.status,r);if(n===void 0)return e;const s=new Response(e.body,e);for(const[o,c]of Object.entries(n))s.headers.set(o,o==="vary"?i(s.headers.get("vary")??void 0,c)??c:c);return s};export{b as a,R as b,S as d,C as r};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a as A,d as L}from"./rest-cache-BnMq2hbO.mjs";import{LunoraError as d}from"./LunoraError-DksAgIpa.mjs";import{m as O}from"./method-guard-BG_vJNTl.mjs";const h=1048576,g=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),E=async(e,r=h)=>{if(!e.body)return"";const t=e.body.getReader(),a=new TextDecoder;let s=0,o="";for(;;){const{done:n,value:c}=await t.read();if(n)break;if(c){if(s+=c.byteLength,s>r)throw await t.cancel().catch(()=>{}),new d("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});o+=a.decode(c,{stream:!0})}}return o+=a.decode(),o},U=async(e,r=h)=>{if(!e.body)return new ArrayBuffer(0);const t=e.body.getReader(),a=[];let s=0;for(;;){const{done:c,value:u}=await t.read();if(c)break;if(u){if(s+=u.byteLength,s>r)throw await t.cancel().catch(()=>{}),new d("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});a.push(u)}}const o=new Uint8Array(s);let n=0;for(const c of a)o.set(c,n),n+=c.byteLength;return o.buffer},S=async(e,r,t=h)=>{try{const a=await E(e,t);return a===""?{}:JSON.parse(a)}catch(a){throw a instanceof d?a:new d(`${r} body must be valid JSON`,{code:"BAD_REQUEST",status:400})}},x=async(e,r=h)=>{const t=await S(e,"Request",r);if(!g(t))throw new d("Request body must be an object",{code:"BAD_REQUEST",status:400});return t},T=(e,r)=>{if(!g(e))throw new d(`${r} \`args\` must be an object`,{code:"BAD_REQUEST",status:400})},k=e=>L(Object.entries(e).map(([r,t])=>({exposure:t.expose,functionPath:r,kind:t.kind}))),B=(e,r)=>{const t=e.searchParams.get("shardKey");if(t!==null&&t!=="")return t;const a=r.headers.get("x-lunora-shard-key");return a===null||a===""?void 0:a},v=e=>{const r=Object.create(null);for(const[t,a]of e.searchParams.entries())if(t!=="shardKey")try{r[t]=JSON.parse(a)}catch{r[t]=a}return r},J=e=>{const{functions:r,invoke:t,rateLimit:a,readJsonBody:s}=e,o={};for(const n of k(r)){const c=n.kind==="query"?["GET","POST"]:["POST"],u=r[n.functionPath].expose?.cache;o[n.path]=async(i,R,P,l)=>{const w=O(i,c);if(w)return w;const m=new URL(i.url);if(a){const f=await a(i,n.functionPath);if(f)return f}let y;i.method==="GET"?y=v(m):y=i.body===null?{}:await s(i),T(y,"REST");const b=B(m,i),p=await t({args:y,env:R,functionPath:n.functionPath,request:i,...b===void 0?{}:{shardKey:b},...l?.waitUntil===void 0?{}:{waitUntil:f=>l.waitUntil?.(f)}});return A(p,u,i,l)}}return o},M=(e,r)=>async(t,a)=>{const s=r.key?r.key(t,a):t.headers.get("cf-connecting-ip")??void 0,o=await e.limit(r.name,s===void 0?{}:{key:s});if(o.ok)return;const n=Math.max(1,Math.ceil(o.retryAfter/1e3));return Response.json({error:{code:"RATE_LIMITED",message:"Rate limit exceeded"}},{headers:{"content-type":"application/json","retry-after":String(n)},status:429})};export{h as M,v as a,J as b,M as c,k as d,x as e,S as f,U as g,T as h,E as i,B as r};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
const p=(s,c="_id")=>{const o=Object.create(null),t=Object.create(null),n=Object.create(null),a=Object.create(null),h=e=>typeof c=="string"?c:c[e]??"_id",r=(e,u)=>{const l=e[u];if(l)return l;const d=[];return e[u]=d,d};for(const e of s.changes)a[e.table]??={primary_key:[h(e.table)]},e.op==="delete"?r(n,e.table).push(e.doc):e.op==="update"?r(t,e.table).push(e.doc):r(o,e.table).push(e.doc);return{delete:n,hasMore:s.hasMore,insert:o,schema:a,state:{cursor:s.nextCursor},update:t}},b=(s,c=Date.now())=>{const o=[];for(const t of s.changes){const n=t.op==="delete"?{...t.doc,_lunora_deleted:!0}:t.doc;o.push({record:{data:n,emitted_at:c,stream:t.table},type:"RECORD"})}return o.push({state:{data:{cursor:s.nextCursor}},type:"STATE"}),o};export{b as toAirbyteMessages,p as toFivetranResponse};
|