@lunora/codegen 1.0.0-alpha.253 → 1.0.0-alpha.255

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.
@@ -1,407 +1,102 @@
1
- import{APP_METHOD_CAPABILITIES as k}from"./CAPABILITY_PROBES-BPeV994T.mjs";import{i as S}from"./ir-DBSvhNa-.mjs";import{G as E}from"./shared-DjUziztz.mjs";const D=e=>k.filter(({key:r})=>e.capabilities.has(r)),R={configKey:"vectors",doc:"Wire the Vectorize index map backing `ctx.vectors`.",method:"vectors"},g=e=>[...D(e).map(({appMethod:r})=>r),...e.hasVectors===!0?[R]:[]],m=e=>g(e).length>0,x=e=>e?['import * as lunoraIdentityContract from "../identity.js";']:[],A=(e,r)=>e?['import type { CreateAccessResolverOptions } from "@lunora/cloudflare-access";',`import { createAccessResolver${r?", composeResolvers":""} } from "@lunora/cloudflare-access";`]:[],C=e=>e?['import { createKvIntrospectorFromEnv } from "@lunora/bindings/kv";']:[],O=e=>e?['import { createVectorAdminIntrospector } from "@lunora/bindings/vectors";']:[],T=e=>e?['import type { D1CtxDbOptions, D1DatabaseLike, D1Exec } from "@lunora/d1";','import { applyCdcChanges, createD1CtxDb, emitD1QueryCost, exportGlobalRows, facetGlobalColumn, importGlobalRows, listGlobalTables, readD1CdcChanges, readGlobalTablePage, retryingExec } from "@lunora/d1";']:[],N=e=>e?['import notifyConfig from "../notify.js";']:[],v=e=>(e.emailAgents?.length??0)>0,q=e=>v(e)?['import { dispatchAgentEmail } from "@lunora/agent/inbound";']:[],I=e=>v(e)?['import * as lunoraAgentDefinitions from "../agents.js";']:[],d=e=>e.tables.some(r=>S(r)),L=e=>{const{hasFramework:r,hasGlobal:t,hasHyperdriveGlobal:a,hasQueue:n,useUmbrella:o}=e,i=o?"lunorash/runtime":"@lunora/runtime",l=["ExecutionContextLike","HttpRouterLike","LunoraWorker","Route","ScheduledControllerLike","ShardNamespaceLike","WorkerOptions",...n?["TriggerTrace"]:[],...t?["GlobalIntrospector"]:[],...e.tables.length>0?["ShardingInfo"]:[],...r?["FrameworkHostHandler"]:[]],c=[...t||a?["createCrossShardRelationCapabilities"]:[],...d(e)?["createDynamicShardRegistry","createQueryCoordinator"]:[],"createWorker",...e.jurisdiction?["declareAppJurisdiction"]:[],"resolveLogArchiveFromEnv",...r?["withFrameworkWorker"]:[]].join(", ");return[`import type { ${[...l].toSorted((s,h)=>s.localeCompare(h)).join(", ")} } from "${i}";`,`import { ${c} } from "${i}";`]},j=e=>{const{hasAccess:r,hasAuth:t,hasGlobal:a,hasHyperdriveGlobal:n,hasKvIntrospector:o,hasQueue:i,hasScheduler:l,hasStorage:c,hasWorkflow:s,wantsOpenApi:h,wantsOpenRpc:u}=e;return[...t?['import type { AuthNamespaceLike, LunoraAuth, LunoraAuthOptions } from "@lunora/auth";','import { authDiscoveryPathsFor, createAuth, createAuthAdmin, createAuthAuditReader, createDoAuthWiring, d1Executor, ensureMigrated, handleAuthDiscoveryRequest, handleAuthRequest, lunoraD1Adapter } from "@lunora/auth";']:[],...A(r,t),...T(a),...n?['import type { HyperdriveEngine } from "@lunora/hyperdrive/global";','import { createHyperdriveGlobalCtxDb } from "@lunora/hyperdrive/global";','import type { SqlCtxDbOptions, SqlExec } from "@lunora/sql-store";']:[],...C(o),...O(e.hasVectors===!0),...l?['import type { DurableObjectNamespaceLike } from "@lunora/scheduler";','import { createScheduler } from "@lunora/scheduler";']:[],...c?['import type { R2BucketLike, R2S3Credentials, Storage } from "@lunora/storage";','import { createBucketStorage, createStorage } from "@lunora/storage";']:[],...s?['import { createWorkflowsRestClient } from "@lunora/workflow";']:[],...q(e),...L(e),"",...x(e.identity),...I(e),...a||n?['import schema from "../schema.js";']:[],...N(e.hasNotify),'import { LUNORA_CRONS } from "./crons.js";','import { LUNORA_FUNCTIONS } from "./functions.js";',...i?['import { createQueueCaptureSink, dispatchQueueBatch, shouldCaptureQueue } from "@lunora/queue";','import { LUNORA_QUEUE_REGISTRY } from "./queues.js";']:[],...e.wantsArchitecture?['import { architecture } from "./architecture.js";']:[],...h?['import { openApiSpec } from "./openapi.js";']:[],...u?['import { openRpcSpec } from "./openrpc.js";']:[],'import { createShardDO } from "./shard.js";',...e.hasVectors===!0?['import { LUNORA_VECTOR_INDEXES } from "./vectors.js";']:[]]},G=e=>[...e.hasStorage?["/** `.storage(...)` declaration — one bucket (required) plus optional extra named buckets and signed-URL config. Backs `ctx.storage` AND the studio file browser. */\ninterface StorageDeclaration<Env> {\n /** The default R2 bucket binding (the bare `ctx.storage`). */\n bucket: Selector<Env, R2BucketLike>;\n /** Extra named buckets, reached via `ctx.storage.bucket(\"name\")` and the studio's bucket picker. */\n buckets?: Record<string, Selector<Env, R2BucketLike>>;\n /** Public base URL signed/public object URLs resolve against. Omit it and `ctx.storage` in a mutation, action or HTTP handler (and the studio's copy-URL) signs against the origin the request reached the worker on — no per-environment value to ship. Queries get no such fallback (a live query re-runs with no request behind it), so a query that signs URLs needs this set. */\n publicBaseUrl?: Selector<Env, string>;\n /** R2 S3-API credentials (`{ accountId, accessKeyId, secretAccessKey, bucket, jurisdiction? }`) enabling `ctx.storage.getPresignedUrl` — native S3 presigned URLs that hit R2 directly, bypassing the worker. Omit to use only the worker-signed `getSignedUrl` path. */\n s3?: Selector<Env, R2S3Credentials>;\n /** HMAC secret for signed URLs. */\n signingSecret?: Selector<Env, string>;\n}"]:[],...e.hasScheduler?["/** `.scheduler(...)` declaration — the `SchedulerDO` namespace. Backs `ctx.scheduler` AND the studio's scheduled-jobs view. The origin its callbacks dispatch back to is not declared here: the DO reads `env.LUNORA_ORIGIN_URL` at fire time, because a caller-supplied dispatch target would be an SSRF vector. */\ninterface SchedulerDeclaration<Env> {\n /** The `SchedulerDO` namespace binding (typically `env.SCHEDULER`). */\n namespace: Selector<Env, DurableObjectNamespaceLike & ShardNamespaceLike>;\n}"]:[],...e.hasGlobal?["/** `.global(...)` declaration — the D1 binding backing `.global()` tables. Backs cross-tenant `ctx.db` reads/writes AND the studio's global data browser. */\ninterface GlobalDeclaration<Env> {\n /** The D1 binding (typically `env.DB`). */\n d1: Selector<Env, D1DatabaseLike>;\n /** The worker origin used to fan reverse cross-backend relations across shards. Without it, such a relation throws a clear error. */\n origin?: Selector<Env, string>;\n}"]:[],...e.hasHyperdriveGlobal?['/** `.hyperdriveGlobal(...)` declaration — backs `.global({ backend: "hyperdrive" })` tables on a Postgres/MySQL database via Hyperdrive. Stays reactive: the writer is injected as `globalDb` and the broadcast hook drives live queries. */\ninterface HyperdriveGlobalDeclaration<Env> {\n /** The Hyperdrive engine — selects the Postgres or MySQL dialect. */\n engine: HyperdriveEngine;\n /** Build the `SqlExec` from `env` — e.g. `buildPgExec(fromPostgresJs(postgres(env.HYPERDRIVE.connectionString)))`. Cache the driver on the DO instance; rebuild lazily after hibernation. */\n exec: (env: Env) => SqlExec;\n /** The worker origin used to fan reverse cross-backend relations across shards. Without it, such a relation throws a clear error. */\n origin?: Selector<Env, string>;\n}']:[],...e.hasAuth?['/** `.auth(...)` declaration — better-auth options plus the storage the adapter reads. Give it `d1` (the default) or `namespace` (a Durable Object that hosts the auth tables), never both. The builder owns the lazy build + `ensureMigrated` dance and wires `authHandler` / `resolveIdentity` / `authAdmin`. */\ninterface AuthDeclaration<Env> {\n /** The D1 binding the auth SQL adapter is wired over (via `lunoraD1Adapter`). Omit only when using `namespace`. */\n d1?: Selector<Env, unknown>;\n /** Shared secret the worker presents on the object\'s internal session route. REQUIRED with `namespace`: the binding is reachable from any worker bound to it, so the secret — not the binding — is the authorization boundary. Without it identity resolution fails closed. */\n internalSecret?: Selector<Env, string>;\n /** Name of the Durable Object instance holding the auth tables. Defaults to `"auth"`. Set it to run separate auth objects (per deployment, per tenant) off one namespace. */\n objectName?: Selector<Env, string>;\n /** The auth Durable Object namespace — the DO-backed mode. Needed for `@better-auth/scim`, which requires native transactions that D1 has none of. The object owns the auth tables, so `/api/auth/*` and identity resolution both go through it. Typed as `AuthNamespaceLike` because `createDoAuthWiring` resolves through `idFromName` + `get` and has no `getByName` fallback — both members are load-bearing here, and `ShardNamespaceLike` leaves both optional. */\n namespace?: Selector<Env, AuthNamespaceLike>;\n /** Build the better-auth options from `env` (secret, plugins, email/password, …). */\n options: (env: Env) => LunoraAuthOptions;\n}']:[]],B=e=>[...e.hasAccess?[" private accessSelector?: Selector<Env, CreateAccessResolverOptions | undefined>;"]:[]," private adminToken?: Selector<Env, string>;",...e.hasAuth?[" private authDeclaration?: AuthDeclaration<Env>;"]:[]," private cdcEnabled = false;"," private reactiveCacheConfig: boolean | { maxBytes?: number; maxEntries?: number } = false;",' private maxRelationKeysLimit?: ShardConfig["maxRelationKeys"];',' private observabilitySink?: ShardConfig["observability"];',' private relationExistsPushDownMode?: ShardConfig["relationExistsPushDown"];'," private readonly extendFns: ((env: Env, derived: Readonly<WorkerOptions>) => Partial<WorkerOptions>)[] = [];",...e.hasGlobal?[" private globalDeclaration?: GlobalDeclaration<Env>;"]:[],...e.hasHyperdriveGlobal?[" private hyperdriveGlobalDeclaration?: HyperdriveGlobalDeclaration<Env>;"]:[]," private httpRouterApp?: HttpRouterLike;"," private readonly routeMap: Record<string, Route> = {};",...e.hasScheduler?[" private schedulerDeclaration?: SchedulerDeclaration<Env>;"]:[],...m(e)?[" private readonly shardExtras: Partial<ShardConfig> = {};"]:[],...d(e)?[" private shardRegistrySelector?: Selector<Env, ShardNamespaceLike>;"]:[]," private shardSelector?: Selector<Env, ShardNamespaceLike>;",...e.hasSourcedTables?[' private sourceClientFactory?: NonNullable<ShardConfig["sourceClient"]>;']:[],...e.hasStorage?[" private storageDeclaration?: StorageDeclaration<Env>;"]:[]],P=e=>g(e).map(({configKey:r,doc:t,method:a})=>` /** ${t} */
2
- public ${a}(factory: (env: Env) => ReturnType<NonNullable<ShardConfig["${r}"]>>): this {
3
- this.shardExtras.${r} = factory as NonNullable<ShardConfig["${r}"]>;
4
-
5
- return this;
6
- }`),W=e=>[...e.hasAccess?[" /** Wire Cloudflare Access (Zero Trust) — feeds the verified Access identity into `ctx.auth` / RLS via `resolveIdentity`. Call it with no argument when the Access policy is attached to the Worker (the identity arrives on the execution context; nothing to configure); pass `teamDomain` + `aud` for a hostname-scoped Access application, whose `Cf-Access-Jwt-Assertion` JWT is verified against your team JWKS. When `.auth(...)` is also configured, Access is composed ahead of it (Access wins when it authenticated the caller; everyone else falls through to the app session). */\n public access(selector?: Selector<Env, CreateAccessResolverOptions>): this {\n this.accessSelector = selector ?? (() => undefined);\n\n return this;\n }"]:[],` /** Bearer token gating the \`/_lunora/admin/*\` endpoints the studio calls. */
7
- public admin(selector: Selector<Env, string>): this {
8
- this.adminToken = selector;
1
+ import{APP_METHOD_CAPABILITIES as k}from"./CAPABILITY_PROBES-DFsutD7g.mjs";import{i as S}from"./ir-DBSvhNa-.mjs";import{G as E}from"./shared-DjUziztz.mjs";const D={configKey:"vectors",doc:"Wire the Vectorize index map backing `ctx.vectors`.",method:"vectors"},g=e=>[...k.filter(({key:r})=>e.capabilities.has(r)).map(({appMethod:r})=>r),...e.hasVectors?[D]:[]],m=e=>g(e).length>0,v=e=>(e.emailAgents?.length??0)>0,d=e=>e.tables.some(r=>S(r)),R=e=>e.hasScheduler?`
2
+ /** Resolve the \`SchedulerDO\`-backed scheduler for this env; \`undefined\` until the namespace is wired. */
3
+ private resolveScheduler(env: Env): ReturnType<typeof createScheduler> | undefined {
4
+ const namespace = this.schedulerDeclaration?.namespace(env);
9
5
 
10
- return this;
11
- }`," /**\n * Opt into change-data-capture: every write records a post-image to `__cdc_log` — on this shard AND, when the app has `.global()` tables, on the global backend. Backs streaming export, replay-PITR, and the `.global()` half of `defineShape` replication (whose poll tick asks the global changelog which tables moved). Off by default: it costs a changelog row per write, which an app using none of the above should not pay.\n *\n * REQUIRED for a shard-local `defineShape`: those replicate out of `__cdc_log`, and a `shape_subscribe` is refused with `SHAPE_REQUIRES_CDC` without it.\n *\n * It also changes how fresh a `.global()` shape is against writes made OUTSIDE `ctx.db` — an admin import, a PITR replay, an external ETL job, or a predicate over wall clock. With CDC off the poll re-reads every shape every 2s. With it on the poll asks the global changelog which tables moved and skips the rest, so a change the changelog never saw waits for the 30s unconditional resync instead. Writes through `ctx.db` are unaffected: they append, so the poll sees them on the next tick either way.\n */\n public cdc(enabled = true): this {\n this.cdcEnabled = enabled;\n\n return this;\n }",` /**
12
- * Enable the per-shard reactive query cache: query results are memoized by \`(functionPath, args, identity)\` and invalidated by the ctx-db write hooks BEFORE the subscription broadcast, so a subscriber re-running its query always observes the post-write state.
6
+ return namespace ? createScheduler({${e.jurisdiction?` jurisdiction: ${JSON.stringify(e.jurisdiction)},`:""} namespace }) : undefined;
7
+ }
8
+ `:"",x=e=>e?`
9
+ /**
10
+ * One bucket's \`Storage\`, signing under the name it is registered as.
13
11
  *
14
- * Off by default (every dispatch re-runs its handler). Pass an options object to tune the caps: \`maxEntries\` (default 1000) and \`maxBytes\` (default 4 MiB); either accepts \`Number.POSITIVE_INFINITY\` to disable that cap.
12
+ * \`bucketName\` is bound into every signed URL's HMAC canonical, so a bucket
13
+ * that signs as the default's name lets a URL minted for one bucket verify
14
+ * against another sharing the secret — and multi-bucket verification fails
15
+ * outright. Hence \`"default"\` for the bare \`ctx.storage\` bucket and the
16
+ * \`buckets\` key for every other.
17
+ *
18
+ * \`origin\` is the request's own origin, the base when no \`publicBaseUrl\` is
19
+ * declared.
15
20
  */
16
- public reactiveCache(config: boolean | { maxBytes?: number; maxEntries?: number } = true): this {
17
- this.reactiveCacheConfig = config;
18
-
19
- return this;
20
- }`,` /** Ceiling on the join keys ONE relation-crossing \`where\` predicate may pre-resolve via semijoin before failing closed. Omit for the engine default. */
21
- public maxRelationKeys(limit: NonNullable<ShardConfig["maxRelationKeys"]>): this {
22
- this.maxRelationKeysLimit = limit;
23
-
24
- return this;
25
- }`," /**\n * Route the shard's `ctx.log` lines, `ctx.trace` spans and `ctx.metrics` measurements to a telemetry sink.\n *\n * The DO half of observability: without it every in-handler signal stays in the shard's local ring buffer (the studio Logs panel) and reaches no collector. The worker half — one `onRpc` event per dispatched RPC — is a `createWorker` option; pass the SAME sink to both via `.extend((env) => ({ observability: sink(env) }))` to correlate them.\n */\n public observability(selector: NonNullable<ShardConfig[\"observability\"]>): this {\n this.observabilitySink = selector;\n\n return this;\n }",' /** Resolution policy for a relation-crossing `where` whose child is co-located in this shard: `"auto"` (cost-based, the engine default), `"always"` (inline correlated EXISTS) or `"never"` (universal semijoin). All three return identical rows. */\n public relationExistsPushDown(mode: NonNullable<ShardConfig["relationExistsPushDown"]>): this {\n this.relationExistsPushDownMode = mode;\n\n return this;\n }',...e.hasAuth?[' /** Wire better-auth — the builder lazily builds the instance, runs `ensureMigrated`, and dispatches `/api/auth/*` inside the worker (instrumented for the auth-failure SLO). Pass `d1` for the D1-backed default, or `namespace` + `internalSecret` to host the auth tables in a Durable Object (what `@better-auth/scim` needs). */\n public auth(declaration: AuthDeclaration<Env>): this {\n // Reject the ambiguous and the empty shapes here rather than at the first\n // request: with neither storage set, auth would silently never answer, and\n // with both it is unclear which one owns the tables.\n if (declaration.d1 && declaration.namespace) {\n throw new Error(".auth(): pass either `d1` or `namespace`, not both — they are two different homes for the same tables.");\n }\n\n if (!declaration.d1 && !declaration.namespace) {\n throw new Error(".auth(): needs `d1` (D1-backed) or `namespace` (Durable-Object-backed) to know where the auth tables live.");\n }\n\n if (declaration.namespace && !declaration.internalSecret) {\n throw new Error(\n ".auth(): `namespace` requires `internalSecret` — the auth DO binding is reachable from any worker bound to it, so identity resolution is gated on a shared secret and would otherwise fail closed on every request.",\n );\n }\n\n this.authDeclaration = declaration;\n\n return this;\n }']:[]," /** Escape hatch — merge raw `WorkerOptions` (anything not yet sugared) over the derived options at build time. The second `derived` argument is a snapshot of the options assembled so far (after `.auth(...)` etc.), so you can compose rather than clobber — e.g. wrap `derived.resolveIdentity` instead of replacing it. */\n public extend(fn: (env: Env, derived: Readonly<WorkerOptions>) => Partial<WorkerOptions>): this {\n this.extendFns.push(fn);\n\n return this;\n }",...e.hasGlobal?[` /** Back \`.global()\` (cross-tenant) tables with D1 — wires \`ctx.db\` routing, the studio global browser, and reverse cross-shard relations. */
26
- public global(declaration: GlobalDeclaration<Env>): this {
27
- this.globalDeclaration = declaration;
21
+ private makeStorage(env: Env, declaration: StorageDeclaration<Env>, bucket: R2BucketLike, bucketName: string, origin?: string): Storage {
22
+ return createStorage({
23
+ bucket,
24
+ bucketName,
25
+ publicBaseUrl: declaration.publicBaseUrl?.(env) ?? origin,
26
+ s3: declaration.s3?.(env),
27
+ signingSecret: declaration.signingSecret?.(env),
28
+ });
29
+ }
28
30
 
29
- return this;
30
- }`]:[],...e.hasHyperdriveGlobal?[` /** Back \`.global({ backend: "hyperdrive" })\` tables with a Postgres/MySQL database via Hyperdrive — wires reactive \`ctx.db\` routing through the shared store core. */
31
- public hyperdriveGlobal(declaration: HyperdriveGlobalDeclaration<Env>): this {
32
- this.hyperdriveGlobalDeclaration = declaration;
31
+ /** Resolve the storage capability (single or multi-bucket) for the DO side. */
32
+ private resolveStorage(env: Env, origin?: string): Storage | undefined {
33
+ const declaration = this.storageDeclaration;
33
34
 
34
- return this;
35
- }`]:[],` /** Cloudflare Email Routing entry — exposes the top-level \`email\` handler. */
36
- public onEmail(handler: (env: Env) => (message: unknown, env: unknown, context: ExecutionContextLike) => Promise<void>): this {
37
- this.emailHandler = handler;
35
+ if (!declaration) {
36
+ return undefined;
37
+ }
38
38
 
39
- return this;
40
- }`," /** Mount a whole HTTP app (`httpRouter()` from `@lunora/server`, or anything with a `fetch`) ahead of Lunora's own routes. Use this for a multi-endpoint hono app with its own CORS + error handling; `.route()` is for one-off endpoints. */\n public httpRouter(app: HttpRouterLike): this {\n this.httpRouterApp = app;\n\n return this;\n }",` /** Mount a custom HTTP route (e.g. an asset-serving or test endpoint). Key is \`"METHOD path"\`, \`"path"\`, or a path prefix matched by the runtime. */
41
- public route(key: string, handler: Route): this {
42
- this.routeMap[key] = handler;
39
+ const defaultBucket = declaration.bucket(env);
43
40
 
44
- return this;
45
- }`,...e.hasScheduler?[` /** Wire the \`SchedulerDO\` — backs \`ctx.scheduler\` and the studio's scheduled-jobs view. */
46
- public scheduler(declaration: SchedulerDeclaration<Env>): this {
47
- this.schedulerDeclaration = declaration;
41
+ if (!defaultBucket) {
42
+ return undefined;
43
+ }
48
44
 
49
- return this;
50
- }`]:[],` /** The shard Durable Object namespace (typically \`env.SHARD\`) — required: every app routes RPC + WebSocket traffic through it. */
51
- public shard(selector: Selector<Env, ShardNamespaceLike>): this {
52
- this.shardSelector = selector;
45
+ const extraEntries = Object.entries(declaration.buckets ?? {})
46
+ .map(([name, selector]) => [name, selector(env)] as const)
47
+ .filter((entry): entry is [string, R2BucketLike] => Boolean(entry[1]));
53
48
 
54
- return this;
55
- }`,...d(e)?[" /** The `ShardRegistryDO` namespace (typically `env.SHARD_REGISTRY`). Each shard registers itself for the `.shardBy()` tables it writes, and cross-shard export, CDC sync and migrations fan out to the shards it lists. Without it they refuse a `.shardBy()` table. */\n public shardRegistry(selector: Selector<Env, ShardNamespaceLike>): this {\n this.shardRegistrySelector = selector;\n\n return this;\n }"]:[],...e.hasSourcedTables?[` /** Resolve the SQL client a \`.source(...)\` table's ingest poll reads from, given the wrangler Hyperdrive binding it named. Build it with \`@lunora/hyperdrive\`'s \`createHyperdrive\` plus your driver adapter. REQUIRED for a sourced table: without it every poll tick records "no sourceClient resolved for binding" and the table stays empty. */
56
- public sourceClient(factory: (env: Env, binding: string) => ReturnType<NonNullable<ShardConfig["sourceClient"]>>): this {
57
- this.sourceClientFactory = factory as NonNullable<ShardConfig["sourceClient"]>;
49
+ if (extraEntries.length === 0) {
50
+ return this.makeStorage(env, declaration, defaultBucket, "default", origin);
51
+ }
58
52
 
59
- return this;
60
- }`]:[],...e.hasStorage?[` /** Wire R2 storage — backs \`ctx.storage\` (incl. multi-bucket) and the studio file browser, from one declaration. */
61
- public storage(declaration: StorageDeclaration<Env>): this {
62
- this.storageDeclaration = declaration;
53
+ const map: Record<string, Storage> = { default: this.makeStorage(env, declaration, defaultBucket, "default", origin) };
63
54
 
64
- return this;
65
- }`]:[],...P(e)],_=e=>{const r=a=>e.hasScheduler?`
66
- ...(this.schedulerDeclaration ? { scheduler: this.resolveScheduler(env) as unknown as ${a}["scheduler"] } : {}),`:"",t=[" cdc: this.cdcEnabled,"," reactiveCache: this.reactiveCacheConfig,"," ...(this.maxRelationKeysLimit === undefined ? {} : { maxRelationKeys: this.maxRelationKeysLimit }),"," ...(this.observabilitySink === undefined ? {} : { observability: this.observabilitySink }),"," ...(this.relationExistsPushDownMode === undefined ? {} : { relationExistsPushDown: this.relationExistsPushDownMode }),",...e.hasGlobal?[` ...(this.globalDeclaration
67
- ? {
68
- d1: (rawEnv: Record<string, unknown>, request?: { bookmark?: string; cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown>; onBookmark?: (bookmark: string | undefined) => void; userId?: string | null }) => {
69
- const env = rawEnv as Env;
70
- const database = this.globalDeclaration?.d1(env);
55
+ for (const [name, bucket] of extraEntries) {
56
+ map[name] = this.makeStorage(env, declaration, bucket, name, origin);
57
+ }
71
58
 
72
- if (!database) {
73
- return undefined;
74
- }
59
+ return createBucketStorage(map, { default: "default" });
60
+ }
75
61
 
76
- const origin = this.globalDeclaration?.origin?.(env);
77
- const crossShard = origin
78
- ? createCrossShardRelationCapabilities({ identity: request?.identity, origin, userId: request?.userId ?? undefined })
79
- : undefined;
62
+ /** Derive the studio file-browser admin functions from the same buckets \`.storage()\` declared. */
63
+ private buildStorageAdmin(env: Env): Partial<WorkerOptions> {
64
+ const declaration = this.storageDeclaration;
80
65
 
81
- return createD1CtxDb({
82
- ...(crossShard ? { crossShardCounter: crossShard.crossShardCounter, crossShardReader: crossShard.crossShardReader } : {}),${r("D1CtxDbOptions")}
83
- ...(request?.cdcRetentionMs === undefined ? {} : { cdcRetentionMs: request.cdcRetentionMs }),
84
- auth: { identity: request?.identity ?? null, userId: request?.userId ?? null },
85
- // Forwarded from the shard's own \`cdc\` config, so ONE
86
- // switch governs both changelogs. Built without it, the
87
- // global \`__cdc_log\` is never written and the shape
88
- // poll's changed-tables fast path is unreachable.
89
- cdc: request?.cdc ?? false,
90
- exec: buildExec(database, request?.bookmark, request?.onBookmark),
91
- // The binding outlives this per-request writer, so the
92
- // provisioning sweep runs once per isolate rather than
93
- // once per request. See \`SqlCtxDbOptions.provisionScope\`.
94
- provisionScope: database,
95
- schema: schema as unknown as D1CtxDbOptions["schema"],
96
- });
97
- },
98
- }
99
- : {}),`]:[],...e.hasHyperdriveGlobal?[` ...(this.hyperdriveGlobalDeclaration
100
- ? {
101
- hyperdriveGlobal: (rawEnv: Record<string, unknown>, request?: { cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown>; userId?: string | null }) => {
102
- const env = rawEnv as Env;
103
- const declaration = this.hyperdriveGlobalDeclaration;
104
- const exec = declaration?.exec(env) as SqlExec | undefined;
66
+ if (!declaration) {
67
+ return {};
68
+ }
105
69
 
106
- if (!declaration || !exec) {
107
- return undefined;
108
- }
70
+ const defaultBucket = declaration.bucket(env);
109
71
 
110
- const origin = declaration.origin?.(env);
111
- const crossShard = origin
112
- ? createCrossShardRelationCapabilities({ identity: request?.identity, origin, userId: request?.userId ?? undefined })
113
- : undefined;
72
+ if (!defaultBucket) {
73
+ return {};
74
+ }
114
75
 
115
- return createHyperdriveGlobalCtxDb({
116
- ...(crossShard ? { crossShardCounter: crossShard.crossShardCounter, crossShardReader: crossShard.crossShardReader } : {}),${r("SqlCtxDbOptions")}
117
- ...(request?.cdcRetentionMs === undefined ? {} : { cdcRetentionMs: request.cdcRetentionMs }),
118
- auth: { identity: request?.identity ?? null, userId: request?.userId ?? null },
119
- // See the D1 twin: one \`cdc\` switch, both changelogs.
120
- cdc: request?.cdc ?? false,
121
- engine: declaration.engine as HyperdriveEngine,
122
- exec,
123
- // The DECLARATION, not \`exec\` — \`exec(env)\` is a user
124
- // callback that builds a fresh client per call, so scoping
125
- // to its result would key the memo on a new object every
126
- // request and never share anything. The declaration is
127
- // built once and names one database.
128
- provisionScope: declaration,
129
- schema: schema as unknown as SqlCtxDbOptions["schema"],
130
- });
131
- },
132
- }
133
- : {}),`]:[],...e.hasScheduler?[` ...(this.schedulerDeclaration
134
- ? {
135
- scheduler: (rawEnv: Record<string, unknown>) => this.resolveScheduler(rawEnv as Env),
136
- }
137
- : {}),`]:[],...d(e)?[" ...(this.shardRegistrySelector ? { shardRegistry: (rawEnv: Record<string, unknown>) => this.shardRegistrySelector?.(rawEnv as Env) } : {}),"]:[],...e.hasSourcedTables?[" ...(this.sourceClientFactory === undefined ? {} : { sourceClient: this.sourceClientFactory }),"]:[],...e.hasStorage?[" ...(this.storageDeclaration ? { storage: (rawEnv: Record<string, unknown>, origin?: string) => this.resolveStorage(rawEnv as Env, origin) } : {}),"]:[],...m(e)?[" ...this.shardExtras,"]:[]];return t.length>0?`
138
- ${t.join(`
139
- `)}
140
- `:""},$=e=>e.jurisdiction&&e.jurisdictionPinsAuth===!0?`
141
- // The schema's jurisdiction pins the auth object like every other DO.
142
- jurisdiction: ${JSON.stringify(e.jurisdiction)},`:"",H=e=>typeof e=="string"?`{ mode: { kind: ${JSON.stringify(e)} } }`:`{ mode: { field: ${JSON.stringify(e.field)}, kind: "shardBy" } }`,U=e=>[...e.tables.length>0?[` const tableSharding = new Map<string, ShardingInfo>([
143
- ${e.tables.map(r=>` [${JSON.stringify(r.name)}, ${H(r.shardMode)}],`).join(`
144
- `)}
145
- ]);
76
+ const bindings: Record<string, R2BucketLike> = { default: defaultBucket };
146
77
 
147
- options.listSchemaTables = () => [...tableSharding.keys()];
148
- options.resolveTableSharding = (table) => tableSharding.get(table);`]:[],...d(e)?[` const shardRegistry = this.shardRegistrySelector?.(env);
78
+ for (const [name, selector] of Object.entries(declaration.buckets ?? {})) {
79
+ const bucket = selector(env);
149
80
 
150
- if (shardRegistry) {
151
- options.queryCoordinator = createQueryCoordinator({ registry: createDynamicShardRegistry({ ${e.jurisdiction?`jurisdiction: ${JSON.stringify(e.jurisdiction)}, `:""}namespace: shardRegistry }) });
152
- }`]:[]],F=e=>[...U(e),...e.hasScheduler?[` if (this.schedulerDeclaration) {
153
- options.schedulerDO = this.schedulerDeclaration.namespace(env);
154
- }`]:[],...e.hasWorkflow?[` options.workflowsClient = (workflowEnv) => {
155
- const source = workflowEnv as Record<string, unknown>;
156
- const accountId = source["CLOUDFLARE_ACCOUNT_ID"];
157
- const apiToken = source["CLOUDFLARE_API_TOKEN"];
81
+ if (bucket) {
82
+ bindings[name] = bucket;
83
+ }
84
+ }
158
85
 
159
- return typeof accountId === "string" && accountId !== "" && typeof apiToken === "string" && apiToken !== ""
160
- ? createWorkflowsRestClient({ accountId, apiToken })
161
- : undefined;
162
- };`]:[],...e.hasGlobal?[` if (this.globalDeclaration) {
163
- const database = this.globalDeclaration.d1(env);
86
+ // \`Object.hasOwn\`, not a bare lookup: \`bindings\` is a plain object, so a
87
+ // prototype key (\`?bucket=constructor\`, \`__proto__\`, \`toString\`) resolves
88
+ // to an inherited Object.prototype member instead of the default bucket.
89
+ //
90
+ // \`origin\` is the base when no \`publicBaseUrl\` is declared: the origin the
91
+ // admin request reached the worker on, which the signed-URL route hands
92
+ // over and then verifies. Only the secret gates signing.
93
+ const pick = (name?: string, origin?: string): Storage => {
94
+ const wanted = name !== undefined && name !== "" ? name : "default";
95
+ const bucketName = Object.hasOwn(bindings, wanted) ? wanted : "default";
164
96
 
165
- if (database) {
166
- options.globalIntrospector = buildGlobalIntrospector(database);
167
- // \`importGlobals\` wires the admin bulk-import endpoint's global
168
- // plane: the rows \`resolveTableSharding\` classifies as \`.global()\`
169
- // land here, and without it they are reported, not written.
170
- options.importGlobals = buildGlobalImporter(database, this.cdcEnabled);
171
- // The read/replay half of the same admin plane. Each one is the
172
- // only reason its endpoint can see the global storage plane at
173
- // all, and every one of them fails SILENTLY when unset — export
174
- // and \`lunora backup create\` answer 200 having written only
175
- // shard-local rows (an export→import round trip then restores
176
- // cleanly minus every global row), CDC sync answers with only
177
- // shard changes, and point-in-time apply reports
178
- // \`globalApplied: 0\`. Nothing here is project-specific either.
179
- options.exportGlobals = buildGlobalExporter(database);
180
- options.syncGlobals = buildGlobalCdcSync(database);
181
- options.applyGlobals = buildGlobalCdcApplier(database, this.cdcEnabled);
182
- }
183
- }`]:[],...e.hasStorage?[` if (this.storageDeclaration) {
184
- Object.assign(options, this.buildStorageAdmin(env));
185
- options.storage = (rawEnv: unknown, origin?: string) => this.resolveStorage(rawEnv as Env, origin);
186
- }`]:[],...e.hasKvIntrospector?[" options.kvIntrospector = createKvIntrospectorFromEnv(env);"]:[],...e.hasVectors===!0?[` if (this.shardExtras.vectors) {
187
- options.vectorIntrospector = createVectorAdminIntrospector({
188
- indexes: this.shardExtras.vectors(env as unknown as Record<string, unknown>),
189
- registry: LUNORA_VECTOR_INDEXES,
190
- });
191
- } else {
192
- // Emitted only when the schema declares an index, so reaching here
193
- // means the app declared one and never bound it. The studio's
194
- // Vectors tab is on (its flag is the same index count) and every
195
- // request to it would answer VECTORS_NOT_CONFIGURED, while
196
- // \`ctx.vectors\` is the throwing stub — so this is already broken,
197
- // just later and less legibly. Same shape as \`.auth()\`'s guards.
198
- throw new Error(
199
- ".vectors(): the schema declares vector index(es) but no binding map was chained. Pass \`.vectors((env) => ({ <indexName>: env.<BINDING> }))\` so \`ctx.vectors\` resolves and the studio's Vectors tab can list them.",
200
- );
201
- }`]:[],...e.hasNotify?[" options.notifySubscriptionStore = notifyConfig.store ? notifyConfig.store(env as Record<string, unknown>) : undefined;"]:[]," options.logArchive = resolveLogArchiveFromEnv(env);",...e.hasAuth?[` // Captured before the branch so the narrowing survives — reading
202
- // \`this.authDeclaration.namespace\` again below would be optional all over again.
203
- const authDeclaration = this.authDeclaration;
204
- const authNamespace = authDeclaration?.namespace;
205
- const authD1 = authDeclaration?.d1;
206
-
207
- if (authDeclaration && authNamespace) {
208
- // DO-backed mode. The auth tables live inside the object and DO storage is
209
- // unreachable from here, so better-auth runs in there and this worker talks
210
- // to it. \`createDoAuthWiring\` is a tested function in \`@lunora/auth\` rather
211
- // than more emitted code: request-path logic in generated output can only be
212
- // typechecked, never unit-tested.
213
- const authWiring = createDoAuthWiring({
214
- // The OAuth discovery documents (an \`mcp()\` resource's metadata, the
215
- // issuer's) are derived here from the declared options, so the worker
216
- // forwards only those exact paths and no other probe reaches the object.
217
- // Memoised on the declaration: a framework-hosted worker rebuilds these
218
- // options per request, and \`options(env)\` rebuilds every plugin.
219
- discoveryPaths: authDiscoveryPathsFor(authDeclaration, env),
220
- internalSecret: authDeclaration.internalSecret?.(env),${$(e)}
221
- namespace: authNamespace(env),
222
- objectName: authDeclaration.objectName?.(env),
223
- });
224
-
225
- options.authHandler = authWiring.authHandler;
226
- options.authDiscoveryHandler = authWiring.discoveryHandler;
227
- options.resolveIdentity = authWiring.resolveIdentity;
228
- // The audit log lives in the object like every other auth table, so the feed
229
- // reads through it rather than querying D1.
230
- options.authAuditReader = authWiring.auditReader;
231
- // Set only once auth is pinned to a jurisdiction: copies the users left in the
232
- // un-pinned object across (\`__lunora_admin__:copyAuthToJurisdiction\`).
233
- options.authJurisdictionMove = authWiring.jurisdictionMove;
234
- // \`authAdmin\` stays D1-only: its ~30 methods read the auth tables directly
235
- // from the worker, which DO storage does not allow. The studio's auth pages
236
- // therefore report "not configured" in this mode rather than silently
237
- // returning empty data.
238
- } else if (authDeclaration && authD1) {
239
- options.authHandler = (request) => {
240
- const auth = getAuth();
241
-
242
- return auth ? handleAuthRequest(auth, request) : Promise.resolve(undefined);
243
- };
244
- // The OAuth discovery documents outside \`/api/auth\` (served only with an
245
- // \`mcp()\` or \`oauthProvider()\` plugin, and only after the app's own routes).
246
- options.authDiscoveryHandler = (request) => {
247
- const auth = getAuth();
248
-
249
- return auth ? handleAuthDiscoveryRequest(auth, request) : Promise.resolve(undefined);
250
- };
251
- options.resolveIdentity = async (request) => {
252
- const auth = getAuth();
253
-
254
- if (!auth) {
255
- return null;
256
- }
257
-
258
- const session = await auth.api.getSession({ headers: (request as Request).headers });
259
-
260
- if (!session?.user?.id) {
261
- return null;
262
- }
263
-
264
- // \`role\` rides along so \`rls(policies, { roles })\` and \`auth.can(...)\`
265
- // work on this wiring without a hand-written resolver. better-auth's
266
- // \`admin()\` plugin owns that column (comma-joined for multiple roles)
267
- // and only an administrator can write it; it is absent when the plugin
268
- // is off, which reads as no roles.
269
- //
270
- // \`expiresAtMs\` is the socket credential expiry the runtime forwards
271
- // as \`x-lunora-identity-exp\`. Without it the DO's expiry check never
272
- // fires, so a signed-out, banned or lapsed user keeps streaming their
273
- // RLS-scoped rows over an already-open WebSocket while every HTTP call
274
- // is anonymous. better-auth hands back a \`Date\`; anything else means
275
- // the adapter did not hydrate it, and omitting beats guessing.
276
- const expiresAt = session.session.expiresAt;
277
- // \`email\` and \`name\` are the claims \`ctx.auth.getIdentity()\` is
278
- // documented to carry ("email, name, roles, custom claims"). Without
279
- // them the documented \`me\` query — \`identity?.email\` — resolves
280
- // \`undefined\` on the built-in wiring. Empty strings are dropped so an
281
- // absent claim reads as absent rather than as "".
282
- const user = session.user as { email?: unknown; name?: unknown; role?: unknown };
283
-
284
- return {
285
- ...(typeof user.email === "string" && user.email.length > 0 ? { email: user.email } : {}),
286
- ...(expiresAt instanceof Date ? { expiresAtMs: expiresAt.getTime() } : {}),
287
- ...(typeof user.name === "string" && user.name.length > 0 ? { name: user.name } : {}),
288
- role: user.role,
289
- userId: session.user.id,
290
- };
291
- };
292
- const authInstance = getAuth();
293
-
294
- options.authAdmin = authInstance ? createAuthAdmin(authInstance) : undefined;
295
- options.authAuditReader = createAuthAuditReader(d1Executor(authD1(env) as never));
296
- }`]:[],...e.hasAccess?[e.hasAuth?` if (this.accessSelector) {
297
- const accessResolver = createAccessResolver(this.accessSelector(env));
298
- const fallback = options.resolveIdentity;
299
-
300
- options.resolveIdentity = fallback ? composeResolvers(accessResolver, fallback) : accessResolver;
301
- }`:` if (this.accessSelector) {
302
- options.resolveIdentity = createAccessResolver(this.accessSelector(env));
303
- }`]:[],...e.voiceAgents&&e.voiceAgents.length>0?[` options.voiceAgents = {
304
- ${e.voiceAgents.map(r=>` ${JSON.stringify(r.exportName)}: (env as Record<string, unknown>)[${JSON.stringify(r.bindingName)}] as ShardNamespaceLike,`).join(`
305
- `)}
306
- };`]:[]],M=e=>[" cronJobs: LUNORA_CRONS,"," functions: LUNORA_FUNCTIONS,",...e.identity?[` identity: lunoraIdentityContract.${e.identity.exportName},`]:[],...e.jurisdiction?[` jurisdiction: ${JSON.stringify(e.jurisdiction)},`]:[],...e.wantsArchitecture?[" architecture,"]:[],...e.wantsOpenApi?[" openApiSpec,"]:[],...e.wantsOpenRpc?[" openRpcSpec,"]:[],...e.hasQueue?[" queue: (batch: unknown, queueEnv: unknown, _context: ExecutionContextLike, trigger: TriggerTrace): Promise<void> =>"," dispatchQueueBatch(batch as Parameters<typeof dispatchQueueBatch>[0], LUNORA_QUEUE_REGISTRY, {"," capture: shouldCaptureQueue(queueEnv as Record<string, unknown>)",` ? createQueueCaptureSink(queueEnv as Record<string, unknown>${e.jurisdiction?`, { jurisdiction: ${JSON.stringify(e.jurisdiction)} }`:""})`," : undefined,"," env: queueEnv as Record<string, unknown>,"," traceparent: trigger.traceparent,"," }),"]:[]," ...(this.httpRouterApp ? { httpRouter: this.httpRouterApp } : {}),"," routes: this.routeMap,"," shardDO: this.shardSelector?.(env) ?? (undefined as unknown as ShardNamespaceLike),"],Q=e=>e.hasScheduler?`
307
- /** Resolve the \`SchedulerDO\`-backed scheduler for this env; \`undefined\` until the namespace is wired. */
308
- private resolveScheduler(env: Env): ReturnType<typeof createScheduler> | undefined {
309
- const namespace = this.schedulerDeclaration?.namespace(env);
310
-
311
- return namespace ? createScheduler({${e.jurisdiction?` jurisdiction: ${JSON.stringify(e.jurisdiction)},`:""} namespace }) : undefined;
312
- }
313
- `:"",J=e=>e?`
314
- /**
315
- * One bucket's \`Storage\`, signing under the name it is registered as.
316
- *
317
- * \`bucketName\` is bound into every signed URL's HMAC canonical, so a bucket
318
- * that signs as the default's name lets a URL minted for one bucket verify
319
- * against another sharing the secret — and multi-bucket verification fails
320
- * outright. Hence \`"default"\` for the bare \`ctx.storage\` bucket and the
321
- * \`buckets\` key for every other.
322
- *
323
- * \`origin\` is the request's own origin, the base when no \`publicBaseUrl\` is
324
- * declared.
325
- */
326
- private makeStorage(env: Env, declaration: StorageDeclaration<Env>, bucket: R2BucketLike, bucketName: string, origin?: string): Storage {
327
- return createStorage({
328
- bucket,
329
- bucketName,
330
- publicBaseUrl: declaration.publicBaseUrl?.(env) ?? origin,
331
- s3: declaration.s3?.(env),
332
- signingSecret: declaration.signingSecret?.(env),
333
- });
334
- }
335
-
336
- /** Resolve the storage capability (single or multi-bucket) for the DO side. */
337
- private resolveStorage(env: Env, origin?: string): Storage | undefined {
338
- const declaration = this.storageDeclaration;
339
-
340
- if (!declaration) {
341
- return undefined;
342
- }
343
-
344
- const defaultBucket = declaration.bucket(env);
345
-
346
- if (!defaultBucket) {
347
- return undefined;
348
- }
349
-
350
- const extraEntries = Object.entries(declaration.buckets ?? {})
351
- .map(([name, selector]) => [name, selector(env)] as const)
352
- .filter((entry): entry is [string, R2BucketLike] => Boolean(entry[1]));
353
-
354
- if (extraEntries.length === 0) {
355
- return this.makeStorage(env, declaration, defaultBucket, "default", origin);
356
- }
357
-
358
- const map: Record<string, Storage> = { default: this.makeStorage(env, declaration, defaultBucket, "default", origin) };
359
-
360
- for (const [name, bucket] of extraEntries) {
361
- map[name] = this.makeStorage(env, declaration, bucket, name, origin);
362
- }
363
-
364
- return createBucketStorage(map, { default: "default" });
365
- }
366
-
367
- /** Derive the studio file-browser admin functions from the same buckets \`.storage()\` declared. */
368
- private buildStorageAdmin(env: Env): Partial<WorkerOptions> {
369
- const declaration = this.storageDeclaration;
370
-
371
- if (!declaration) {
372
- return {};
373
- }
374
-
375
- const defaultBucket = declaration.bucket(env);
376
-
377
- if (!defaultBucket) {
378
- return {};
379
- }
380
-
381
- const bindings: Record<string, R2BucketLike> = { default: defaultBucket };
382
-
383
- for (const [name, selector] of Object.entries(declaration.buckets ?? {})) {
384
- const bucket = selector(env);
385
-
386
- if (bucket) {
387
- bindings[name] = bucket;
388
- }
389
- }
390
-
391
- // \`Object.hasOwn\`, not a bare lookup: \`bindings\` is a plain object, so a
392
- // prototype key (\`?bucket=constructor\`, \`__proto__\`, \`toString\`) resolves
393
- // to an inherited Object.prototype member instead of the default bucket.
394
- //
395
- // \`origin\` is the base when no \`publicBaseUrl\` is declared: the origin the
396
- // admin request reached the worker on, which the signed-URL route hands
397
- // over and then verifies. Only the secret gates signing.
398
- const pick = (name?: string, origin?: string): Storage => {
399
- const wanted = name !== undefined && name !== "" ? name : "default";
400
- const bucketName = Object.hasOwn(bindings, wanted) ? wanted : "default";
401
-
402
- return this.makeStorage(env, declaration, bindings[bucketName] ?? defaultBucket, bucketName, origin);
403
- };
404
- const hasSigning = Boolean(declaration.signingSecret?.(env));
97
+ return this.makeStorage(env, declaration, bindings[bucketName] ?? defaultBucket, bucketName, origin);
98
+ };
99
+ const hasSigning = Boolean(declaration.signingSecret?.(env));
405
100
 
406
101
  return {
407
102
  storageBuckets: Object.keys(bindings),
@@ -415,7 +110,7 @@ ${e.voiceAgents.map(r=>` ${JSON.stringify(r.exportName)}: (env as Rec
415
110
  storageUpload: (key: string, body: ArrayBuffer, opts?: { bucket?: string; contentType?: string; sha256?: string }) => pick(opts?.bucket).upload(key, body, opts),
416
111
  };
417
112
  }
418
- `:"",K=e=>e?`
113
+ `:"",A=e=>e?`
419
114
  /**
420
115
  * Adapt the raw D1 binding to \`@lunora/d1\`'s \`D1Exec\` (reads via \`all\`, writes via \`run\`, and — when the binding exposes it — several writes in one round trip via \`batch\`).
421
116
  *
@@ -637,7 +332,312 @@ const buildGlobalCdcApplier =
637
332
 
638
333
  return request.changes.length;
639
334
  };
640
- `:"",V=e=>[...e.hasAuth?["AuthDeclaration"]:[],"ComposedApp",...e.hasGlobal?["GlobalDeclaration"]:[],"LunoraConfig",...e.hasScheduler?["SchedulerDeclaration"]:[],"Selector",...e.hasStorage?["StorageDeclaration"]:[]].toSorted((r,t)=>r.localeCompare(t)).join(", "),Z=e=>{const r=(e.hasVectors??!0)&&(e.vectorIndexCount??0)>0,t={...e,hasVectors:r},{hasAuth:a}=t,n=G(t),o=F(t),i=a?` let auth: LunoraAuth | null = null;
335
+ `:"",C=e=>[...e.hasStorage?["/** `.storage(...)` declaration — one bucket (required) plus optional extra named buckets and signed-URL config. Backs `ctx.storage` AND the studio file browser. */\ninterface StorageDeclaration<Env> {\n /** The default R2 bucket binding (the bare `ctx.storage`). */\n bucket: Selector<Env, R2BucketLike>;\n /** Extra named buckets, reached via `ctx.storage.bucket(\"name\")` and the studio's bucket picker. */\n buckets?: Record<string, Selector<Env, R2BucketLike>>;\n /** Public base URL signed/public object URLs resolve against. Omit it and `ctx.storage` in a mutation, action or HTTP handler (and the studio's copy-URL) signs against the origin the request reached the worker on — no per-environment value to ship. Queries get no such fallback (a live query re-runs with no request behind it), so a query that signs URLs needs this set. */\n publicBaseUrl?: Selector<Env, string>;\n /** R2 S3-API credentials (`{ accountId, accessKeyId, secretAccessKey, bucket, jurisdiction? }`) enabling `ctx.storage.getPresignedUrl` — native S3 presigned URLs that hit R2 directly, bypassing the worker. Omit to use only the worker-signed `getSignedUrl` path. */\n s3?: Selector<Env, R2S3Credentials>;\n /** HMAC secret for signed URLs. */\n signingSecret?: Selector<Env, string>;\n}"]:[],...e.hasScheduler?["/** `.scheduler(...)` declaration — the `SchedulerDO` namespace. Backs `ctx.scheduler` AND the studio's scheduled-jobs view. The origin its callbacks dispatch back to is not declared here: the DO reads `env.LUNORA_ORIGIN_URL` at fire time, because a caller-supplied dispatch target would be an SSRF vector. */\ninterface SchedulerDeclaration<Env> {\n /** The `SchedulerDO` namespace binding (typically `env.SCHEDULER`). */\n namespace: Selector<Env, DurableObjectNamespaceLike & ShardNamespaceLike>;\n}"]:[],...e.hasGlobal?["/** `.global(...)` declaration — the D1 binding backing `.global()` tables. Backs cross-tenant `ctx.db` reads/writes AND the studio's global data browser. */\ninterface GlobalDeclaration<Env> {\n /** The D1 binding (typically `env.DB`). */\n d1: Selector<Env, D1DatabaseLike>;\n /** The worker origin used to fan reverse cross-backend relations across shards. Without it, such a relation throws a clear error. */\n origin?: Selector<Env, string>;\n}"]:[],...e.hasHyperdriveGlobal?['/** `.hyperdriveGlobal(...)` declaration — backs `.global({ backend: "hyperdrive" })` tables on a Postgres/MySQL database via Hyperdrive. Stays reactive: the writer is injected as `globalDb` and the broadcast hook drives live queries. */\ninterface HyperdriveGlobalDeclaration<Env> {\n /** The Hyperdrive engine — selects the Postgres or MySQL dialect. */\n engine: HyperdriveEngine;\n /** Build the `SqlExec` from `env` — e.g. `buildPgExec(fromPostgresJs(postgres(env.HYPERDRIVE.connectionString)))`. Cache the driver on the DO instance; rebuild lazily after hibernation. */\n exec: (env: Env) => SqlExec;\n /** The worker origin used to fan reverse cross-backend relations across shards. Without it, such a relation throws a clear error. */\n origin?: Selector<Env, string>;\n}']:[],...e.hasAuth?['/** `.auth(...)` declaration — better-auth options plus the storage the adapter reads. Give it `d1` (the default) or `namespace` (a Durable Object that hosts the auth tables), never both. The builder owns the lazy build + `ensureMigrated` dance and wires `authHandler` / `resolveIdentity` / `authAdmin`. */\ninterface AuthDeclaration<Env> {\n /** The D1 binding the auth SQL adapter is wired over (via `lunoraD1Adapter`). Omit only when using `namespace`. */\n d1?: Selector<Env, unknown>;\n /** Shared secret the worker presents on the object\'s internal session route. REQUIRED with `namespace`: the binding is reachable from any worker bound to it, so the secret — not the binding — is the authorization boundary. Without it identity resolution fails closed. */\n internalSecret?: Selector<Env, string>;\n /** Name of the Durable Object instance holding the auth tables. Defaults to `"auth"`. Set it to run separate auth objects (per deployment, per tenant) off one namespace. */\n objectName?: Selector<Env, string>;\n /** The auth Durable Object namespace — the DO-backed mode. Needed for `@better-auth/scim`, which requires native transactions that D1 has none of. The object owns the auth tables, so `/api/auth/*` and identity resolution both go through it. Typed as `AuthNamespaceLike` because `createDoAuthWiring` resolves through `idFromName` + `get` and has no `getByName` fallback — both members are load-bearing here, and `ShardNamespaceLike` leaves both optional. */\n namespace?: Selector<Env, AuthNamespaceLike>;\n /** Build the better-auth options from `env` (secret, plugins, email/password, …). */\n options: (env: Env) => LunoraAuthOptions;\n}']:[]],O=e=>[...e.hasAccess?[" private accessSelector?: Selector<Env, CreateAccessResolverOptions | undefined>;"]:[]," private adminToken?: Selector<Env, string>;",...e.hasAuth?[" private authDeclaration?: AuthDeclaration<Env>;"]:[]," private cdcEnabled = false;"," private reactiveCacheConfig: boolean | { maxBytes?: number; maxEntries?: number } = false;",' private maxRelationKeysLimit?: ShardConfig["maxRelationKeys"];',' private observabilitySink?: ShardConfig["observability"];',' private relationExistsPushDownMode?: ShardConfig["relationExistsPushDown"];'," private readonly extendFns: ((env: Env, derived: Readonly<WorkerOptions>) => Partial<WorkerOptions>)[] = [];",...e.hasGlobal?[" private globalDeclaration?: GlobalDeclaration<Env>;"]:[],...e.hasHyperdriveGlobal?[" private hyperdriveGlobalDeclaration?: HyperdriveGlobalDeclaration<Env>;"]:[]," private httpRouterApp?: HttpRouterLike;"," private readonly routeMap: Record<string, Route> = {};",...e.hasScheduler?[" private schedulerDeclaration?: SchedulerDeclaration<Env>;"]:[],...m(e)?[" private readonly shardExtras: Partial<ShardConfig> = {};"]:[],...d(e)?[" private shardRegistrySelector?: Selector<Env, ShardNamespaceLike>;"]:[]," private shardSelector?: Selector<Env, ShardNamespaceLike>;",...e.hasSourcedTables?[' private sourceClientFactory?: NonNullable<ShardConfig["sourceClient"]>;']:[],...e.hasStorage?[" private storageDeclaration?: StorageDeclaration<Env>;"]:[]],T=e=>g(e).map(({configKey:r,doc:t,method:a})=>` /** ${t} */
336
+ public ${a}(factory: (env: Env) => ReturnType<NonNullable<ShardConfig["${r}"]>>): this {
337
+ this.shardExtras.${r} = factory as NonNullable<ShardConfig["${r}"]>;
338
+
339
+ return this;
340
+ }`),N=e=>[...e.hasAccess?[" /** Wire Cloudflare Access (Zero Trust) — feeds the verified Access identity into `ctx.auth` / RLS via `resolveIdentity`. Call it with no argument when the Access policy is attached to the Worker (the identity arrives on the execution context; nothing to configure); pass `teamDomain` + `aud` for a hostname-scoped Access application, whose `Cf-Access-Jwt-Assertion` JWT is verified against your team JWKS. When `.auth(...)` is also configured, Access is composed ahead of it (Access wins when it authenticated the caller; everyone else falls through to the app session). */\n public access(selector?: Selector<Env, CreateAccessResolverOptions>): this {\n this.accessSelector = selector ?? (() => undefined);\n\n return this;\n }"]:[],` /** Bearer token gating the \`/_lunora/admin/*\` endpoints the studio calls. */
341
+ public admin(selector: Selector<Env, string>): this {
342
+ this.adminToken = selector;
343
+
344
+ return this;
345
+ }`," /**\n * Opt into change-data-capture: every write records a post-image to `__cdc_log` — on this shard AND, when the app has `.global()` tables, on the global backend. Backs streaming export, replay-PITR, and the `.global()` half of `defineShape` replication (whose poll tick asks the global changelog which tables moved). Off by default: it costs a changelog row per write, which an app using none of the above should not pay.\n *\n * REQUIRED for a shard-local `defineShape`: those replicate out of `__cdc_log`, and a `shape_subscribe` is refused with `SHAPE_REQUIRES_CDC` without it.\n *\n * It also changes how fresh a `.global()` shape is against writes made OUTSIDE `ctx.db` — an admin import, a PITR replay, an external ETL job, or a predicate over wall clock. With CDC off the poll re-reads every shape every 2s. With it on the poll asks the global changelog which tables moved and skips the rest, so a change the changelog never saw waits for the 30s unconditional resync instead. Writes through `ctx.db` are unaffected: they append, so the poll sees them on the next tick either way.\n */\n public cdc(enabled = true): this {\n this.cdcEnabled = enabled;\n\n return this;\n }",` /**
346
+ * Enable the per-shard reactive query cache: query results are memoized by \`(functionPath, args, identity)\` and invalidated by the ctx-db write hooks BEFORE the subscription broadcast, so a subscriber re-running its query always observes the post-write state.
347
+ *
348
+ * Off by default (every dispatch re-runs its handler). Pass an options object to tune the caps: \`maxEntries\` (default 1000) and \`maxBytes\` (default 4 MiB); either accepts \`Number.POSITIVE_INFINITY\` to disable that cap.
349
+ */
350
+ public reactiveCache(config: boolean | { maxBytes?: number; maxEntries?: number } = true): this {
351
+ this.reactiveCacheConfig = config;
352
+
353
+ return this;
354
+ }`,` /** Ceiling on the join keys ONE relation-crossing \`where\` predicate may pre-resolve via semijoin before failing closed. Omit for the engine default. */
355
+ public maxRelationKeys(limit: NonNullable<ShardConfig["maxRelationKeys"]>): this {
356
+ this.maxRelationKeysLimit = limit;
357
+
358
+ return this;
359
+ }`," /**\n * Route the shard's `ctx.log` lines, `ctx.trace` spans and `ctx.metrics` measurements to a telemetry sink.\n *\n * The DO half of observability: without it every in-handler signal stays in the shard's local ring buffer (the studio Logs panel) and reaches no collector. The worker half — one `onRpc` event per dispatched RPC — is a `createWorker` option; pass the SAME sink to both via `.extend((env) => ({ observability: sink(env) }))` to correlate them.\n */\n public observability(selector: NonNullable<ShardConfig[\"observability\"]>): this {\n this.observabilitySink = selector;\n\n return this;\n }",' /** Resolution policy for a relation-crossing `where` whose child is co-located in this shard: `"auto"` (cost-based, the engine default), `"always"` (inline correlated EXISTS) or `"never"` (universal semijoin). All three return identical rows. */\n public relationExistsPushDown(mode: NonNullable<ShardConfig["relationExistsPushDown"]>): this {\n this.relationExistsPushDownMode = mode;\n\n return this;\n }',...e.hasAuth?[' /** Wire better-auth — the builder lazily builds the instance, runs `ensureMigrated`, and dispatches `/api/auth/*` inside the worker (instrumented for the auth-failure SLO). Pass `d1` for the D1-backed default, or `namespace` + `internalSecret` to host the auth tables in a Durable Object (what `@better-auth/scim` needs). */\n public auth(declaration: AuthDeclaration<Env>): this {\n // Reject the ambiguous and the empty shapes here rather than at the first\n // request: with neither storage set, auth would silently never answer, and\n // with both it is unclear which one owns the tables.\n if (declaration.d1 && declaration.namespace) {\n throw new Error(".auth(): pass either `d1` or `namespace`, not both — they are two different homes for the same tables.");\n }\n\n if (!declaration.d1 && !declaration.namespace) {\n throw new Error(".auth(): needs `d1` (D1-backed) or `namespace` (Durable-Object-backed) to know where the auth tables live.");\n }\n\n if (declaration.namespace && !declaration.internalSecret) {\n throw new Error(\n ".auth(): `namespace` requires `internalSecret` — the auth DO binding is reachable from any worker bound to it, so identity resolution is gated on a shared secret and would otherwise fail closed on every request.",\n );\n }\n\n this.authDeclaration = declaration;\n\n return this;\n }']:[]," /** Escape hatch — merge raw `WorkerOptions` (anything not yet sugared) over the derived options at build time. The second `derived` argument is a snapshot of the options assembled so far (after `.auth(...)` etc.), so you can compose rather than clobber — e.g. wrap `derived.resolveIdentity` instead of replacing it. */\n public extend(fn: (env: Env, derived: Readonly<WorkerOptions>) => Partial<WorkerOptions>): this {\n this.extendFns.push(fn);\n\n return this;\n }",...e.hasGlobal?[` /** Back \`.global()\` (cross-tenant) tables with D1 — wires \`ctx.db\` routing, the studio global browser, and reverse cross-shard relations. */
360
+ public global(declaration: GlobalDeclaration<Env>): this {
361
+ this.globalDeclaration = declaration;
362
+
363
+ return this;
364
+ }`]:[],...e.hasHyperdriveGlobal?[` /** Back \`.global({ backend: "hyperdrive" })\` tables with a Postgres/MySQL database via Hyperdrive — wires reactive \`ctx.db\` routing through the shared store core. */
365
+ public hyperdriveGlobal(declaration: HyperdriveGlobalDeclaration<Env>): this {
366
+ this.hyperdriveGlobalDeclaration = declaration;
367
+
368
+ return this;
369
+ }`]:[],` /** Cloudflare Email Routing entry — exposes the top-level \`email\` handler. */
370
+ public onEmail(handler: (env: Env) => (message: unknown, env: unknown, context: ExecutionContextLike) => Promise<void>): this {
371
+ this.emailHandler = handler;
372
+
373
+ return this;
374
+ }`," /** Mount a whole HTTP app (`httpRouter()` from `@lunora/server`, or anything with a `fetch`) ahead of Lunora's own routes. Use this for a multi-endpoint hono app with its own CORS + error handling; `.route()` is for one-off endpoints. */\n public httpRouter(app: HttpRouterLike): this {\n this.httpRouterApp = app;\n\n return this;\n }",` /** Mount a custom HTTP route (e.g. an asset-serving or test endpoint). Key is \`"METHOD path"\`, \`"path"\`, or a path prefix matched by the runtime. */
375
+ public route(key: string, handler: Route): this {
376
+ this.routeMap[key] = handler;
377
+
378
+ return this;
379
+ }`,...e.hasScheduler?[` /** Wire the \`SchedulerDO\` — backs \`ctx.scheduler\` and the studio's scheduled-jobs view. */
380
+ public scheduler(declaration: SchedulerDeclaration<Env>): this {
381
+ this.schedulerDeclaration = declaration;
382
+
383
+ return this;
384
+ }`]:[],` /** The shard Durable Object namespace (typically \`env.SHARD\`) — required: every app routes RPC + WebSocket traffic through it. */
385
+ public shard(selector: Selector<Env, ShardNamespaceLike>): this {
386
+ this.shardSelector = selector;
387
+
388
+ return this;
389
+ }`,...d(e)?[" /** The `ShardRegistryDO` namespace (typically `env.SHARD_REGISTRY`). Each shard registers itself for the `.shardBy()` tables it writes, and cross-shard export, CDC sync and migrations fan out to the shards it lists. Without it they refuse a `.shardBy()` table. */\n public shardRegistry(selector: Selector<Env, ShardNamespaceLike>): this {\n this.shardRegistrySelector = selector;\n\n return this;\n }"]:[],...e.hasSourcedTables?[` /** Resolve the SQL client a \`.source(...)\` table's ingest poll reads from, given the wrangler Hyperdrive binding it named. Build it with \`@lunora/hyperdrive\`'s \`createHyperdrive\` plus your driver adapter. REQUIRED for a sourced table: without it every poll tick records "no sourceClient resolved for binding" and the table stays empty. */
390
+ public sourceClient(factory: (env: Env, binding: string) => ReturnType<NonNullable<ShardConfig["sourceClient"]>>): this {
391
+ this.sourceClientFactory = factory as NonNullable<ShardConfig["sourceClient"]>;
392
+
393
+ return this;
394
+ }`]:[],...e.hasStorage?[` /** Wire R2 storage — backs \`ctx.storage\` (incl. multi-bucket) and the studio file browser, from one declaration. */
395
+ public storage(declaration: StorageDeclaration<Env>): this {
396
+ this.storageDeclaration = declaration;
397
+
398
+ return this;
399
+ }`]:[],...T(e)],q=e=>{const r=a=>e.hasScheduler?`
400
+ ...(this.schedulerDeclaration ? { scheduler: this.resolveScheduler(env) as unknown as ${a}["scheduler"] } : {}),`:"",t=[" cdc: this.cdcEnabled,"," reactiveCache: this.reactiveCacheConfig,"," ...(this.maxRelationKeysLimit === undefined ? {} : { maxRelationKeys: this.maxRelationKeysLimit }),"," ...(this.observabilitySink === undefined ? {} : { observability: this.observabilitySink }),"," ...(this.relationExistsPushDownMode === undefined ? {} : { relationExistsPushDown: this.relationExistsPushDownMode }),",...e.hasGlobal?[` ...(this.globalDeclaration
401
+ ? {
402
+ d1: (rawEnv: Record<string, unknown>, request?: { bookmark?: string; cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown>; onBookmark?: (bookmark: string | undefined) => void; userId?: string | null }) => {
403
+ const env = rawEnv as Env;
404
+ const database = this.globalDeclaration?.d1(env);
405
+
406
+ if (!database) {
407
+ return undefined;
408
+ }
409
+
410
+ const origin = this.globalDeclaration?.origin?.(env);
411
+ const crossShard = origin
412
+ ? createCrossShardRelationCapabilities({ identity: request?.identity, origin, userId: request?.userId ?? undefined })
413
+ : undefined;
414
+
415
+ return createD1CtxDb({
416
+ ...(crossShard ? { crossShardCounter: crossShard.crossShardCounter, crossShardReader: crossShard.crossShardReader } : {}),${r("D1CtxDbOptions")}
417
+ ...(request?.cdcRetentionMs === undefined ? {} : { cdcRetentionMs: request.cdcRetentionMs }),
418
+ auth: { identity: request?.identity ?? null, userId: request?.userId ?? null },
419
+ // Forwarded from the shard's own \`cdc\` config, so ONE
420
+ // switch governs both changelogs. Built without it, the
421
+ // global \`__cdc_log\` is never written and the shape
422
+ // poll's changed-tables fast path is unreachable.
423
+ cdc: request?.cdc ?? false,
424
+ exec: buildExec(database, request?.bookmark, request?.onBookmark),
425
+ // The binding outlives this per-request writer, so the
426
+ // provisioning sweep runs once per isolate rather than
427
+ // once per request. See \`SqlCtxDbOptions.provisionScope\`.
428
+ provisionScope: database,
429
+ schema: schema as unknown as D1CtxDbOptions["schema"],
430
+ });
431
+ },
432
+ }
433
+ : {}),`]:[],...e.hasHyperdriveGlobal?[` ...(this.hyperdriveGlobalDeclaration
434
+ ? {
435
+ hyperdriveGlobal: (rawEnv: Record<string, unknown>, request?: { cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown>; userId?: string | null }) => {
436
+ const env = rawEnv as Env;
437
+ const declaration = this.hyperdriveGlobalDeclaration;
438
+ const exec = declaration?.exec(env) as SqlExec | undefined;
439
+
440
+ if (!declaration || !exec) {
441
+ return undefined;
442
+ }
443
+
444
+ const origin = declaration.origin?.(env);
445
+ const crossShard = origin
446
+ ? createCrossShardRelationCapabilities({ identity: request?.identity, origin, userId: request?.userId ?? undefined })
447
+ : undefined;
448
+
449
+ return createHyperdriveGlobalCtxDb({
450
+ ...(crossShard ? { crossShardCounter: crossShard.crossShardCounter, crossShardReader: crossShard.crossShardReader } : {}),${r("SqlCtxDbOptions")}
451
+ ...(request?.cdcRetentionMs === undefined ? {} : { cdcRetentionMs: request.cdcRetentionMs }),
452
+ auth: { identity: request?.identity ?? null, userId: request?.userId ?? null },
453
+ // See the D1 twin: one \`cdc\` switch, both changelogs.
454
+ cdc: request?.cdc ?? false,
455
+ engine: declaration.engine as HyperdriveEngine,
456
+ exec,
457
+ // The DECLARATION, not \`exec\` — \`exec(env)\` is a user
458
+ // callback that builds a fresh client per call, so scoping
459
+ // to its result would key the memo on a new object every
460
+ // request and never share anything. The declaration is
461
+ // built once and names one database.
462
+ provisionScope: declaration,
463
+ schema: schema as unknown as SqlCtxDbOptions["schema"],
464
+ });
465
+ },
466
+ }
467
+ : {}),`]:[],...e.hasScheduler?[` ...(this.schedulerDeclaration
468
+ ? {
469
+ scheduler: (rawEnv: Record<string, unknown>) => this.resolveScheduler(rawEnv as Env),
470
+ }
471
+ : {}),`]:[],...d(e)?[" ...(this.shardRegistrySelector ? { shardRegistry: (rawEnv: Record<string, unknown>) => this.shardRegistrySelector?.(rawEnv as Env) } : {}),"]:[],...e.hasSourcedTables?[" ...(this.sourceClientFactory === undefined ? {} : { sourceClient: this.sourceClientFactory }),"]:[],...e.hasStorage?[" ...(this.storageDeclaration ? { storage: (rawEnv: Record<string, unknown>, origin?: string) => this.resolveStorage(rawEnv as Env, origin) } : {}),"]:[],...m(e)?[" ...this.shardExtras,"]:[]];return t.length>0?`
472
+ ${t.join(`
473
+ `)}
474
+ `:""},I=e=>e?['import * as lunoraIdentityContract from "../identity.js";']:[],L=(e,r)=>e?['import type { CreateAccessResolverOptions } from "@lunora/cloudflare-access";',`import { createAccessResolver${r?", composeResolvers":""} } from "@lunora/cloudflare-access";`]:[],j=e=>e?['import { createKvIntrospectorFromEnv } from "@lunora/bindings/kv";']:[],G=e=>e?['import { createVectorAdminIntrospector } from "@lunora/bindings/vectors";']:[],B=e=>e?['import type { D1CtxDbOptions, D1DatabaseLike, D1Exec } from "@lunora/d1";','import { applyCdcChanges, createD1CtxDb, emitD1QueryCost, exportGlobalRows, facetGlobalColumn, importGlobalRows, listGlobalTables, readD1CdcChanges, readGlobalTablePage, retryingExec } from "@lunora/d1";']:[],P=e=>e?['import notifyConfig from "../notify.js";']:[],W=e=>v(e)?['import { dispatchAgentEmail } from "@lunora/agent/inbound";']:[],_=e=>v(e)?['import * as lunoraAgentDefinitions from "../agents.js";']:[],$=e=>{const{hasFramework:r,hasGlobal:t,hasHyperdriveGlobal:a,hasQueue:n,useUmbrella:o}=e,i=o?"lunorash/runtime":"@lunora/runtime",l=["ExecutionContextLike","HttpRouterLike","LunoraWorker","Route","ScheduledControllerLike","ShardNamespaceLike","WorkerOptions",...n?["TriggerTrace"]:[],...t?["GlobalIntrospector"]:[],...e.tables.length>0?["ShardingInfo"]:[],...r?["FrameworkHostHandler"]:[]],c=[...t||a?["createCrossShardRelationCapabilities"]:[],...d(e)?["createDynamicShardRegistry","createQueryCoordinator"]:[],"createWorker",...e.jurisdiction?["declareAppJurisdiction"]:[],"resolveLogArchiveFromEnv",...r?["withFrameworkWorker"]:[]].join(", ");return[`import type { ${[...l].toSorted((s,h)=>s.localeCompare(h)).join(", ")} } from "${i}";`,`import { ${c} } from "${i}";`]},H=e=>{const{hasAccess:r,hasAuth:t,hasGlobal:a,hasHyperdriveGlobal:n,hasKvIntrospector:o,hasQueue:i,hasScheduler:l,hasStorage:c,hasWorkflow:s,wantsOpenApi:h,wantsOpenRpc:u}=e;return[...t?['import type { AuthNamespaceLike, LunoraAuth, LunoraAuthOptions } from "@lunora/auth";','import { authDiscoveryPathsFor, createAuth, createAuthAdmin, createAuthAuditReader, createDoAuthWiring, d1Executor, ensureMigrated, handleAuthDiscoveryRequest, handleAuthRequest, lunoraD1Adapter } from "@lunora/auth";']:[],...L(r,t),...B(a),...n?['import type { HyperdriveEngine } from "@lunora/hyperdrive/global";','import { createHyperdriveGlobalCtxDb } from "@lunora/hyperdrive/global";','import type { SqlCtxDbOptions, SqlExec } from "@lunora/sql-store";']:[],...j(o),...G(e.hasVectors),...l?['import type { DurableObjectNamespaceLike } from "@lunora/scheduler";','import { createScheduler } from "@lunora/scheduler";']:[],...c?['import type { R2BucketLike, R2S3Credentials, Storage } from "@lunora/storage";','import { createBucketStorage, createStorage } from "@lunora/storage";']:[],...s?['import { createWorkflowsRestClient } from "@lunora/workflow";']:[],...W(e),...$(e),"",...I(e.identity),..._(e),...a||n?['import schema from "../schema.js";']:[],...P(e.hasNotify),'import { LUNORA_CRONS } from "./crons.js";','import { LUNORA_FUNCTIONS } from "./functions.js";',...i?['import { createQueueCaptureSink, dispatchQueueBatch, shouldCaptureQueue } from "@lunora/queue";','import { LUNORA_QUEUE_REGISTRY } from "./queues.js";']:[],...e.wantsArchitecture?['import { architecture } from "./architecture.js";']:[],...h?['import { openApiSpec } from "./openapi.js";']:[],...u?['import { openRpcSpec } from "./openrpc.js";']:[],'import { createShardDO } from "./shard.js";',...e.hasVectors?['import { LUNORA_VECTOR_INDEXES } from "./vectors.js";']:[]]},U=e=>e.jurisdiction&&e.jurisdictionPinsAuth===!0?`
475
+ // The schema's jurisdiction pins the auth object like every other DO.
476
+ jurisdiction: ${JSON.stringify(e.jurisdiction)},`:"",F=e=>typeof e=="string"?`{ mode: { kind: ${JSON.stringify(e)} } }`:`{ mode: { field: ${JSON.stringify(e.field)}, kind: "shardBy" } }`,M=e=>[...e.tables.length>0?[` const tableSharding = new Map<string, ShardingInfo>([
477
+ ${e.tables.map(r=>` [${JSON.stringify(r.name)}, ${F(r.shardMode)}],`).join(`
478
+ `)}
479
+ ]);
480
+
481
+ options.listSchemaTables = () => [...tableSharding.keys()];
482
+ options.resolveTableSharding = (table) => tableSharding.get(table);`]:[],...d(e)?[` const shardRegistry = this.shardRegistrySelector?.(env);
483
+
484
+ if (shardRegistry) {
485
+ options.queryCoordinator = createQueryCoordinator({ registry: createDynamicShardRegistry({ ${e.jurisdiction?`jurisdiction: ${JSON.stringify(e.jurisdiction)}, `:""}namespace: shardRegistry }) });
486
+ }`]:[]],Q=e=>[...M(e),...e.hasScheduler?[` if (this.schedulerDeclaration) {
487
+ options.schedulerDO = this.schedulerDeclaration.namespace(env);
488
+ }`]:[],...e.hasWorkflow?[` options.workflowsClient = (workflowEnv) => {
489
+ const source = workflowEnv as Record<string, unknown>;
490
+ const accountId = source["CLOUDFLARE_ACCOUNT_ID"];
491
+ const apiToken = source["CLOUDFLARE_API_TOKEN"];
492
+
493
+ return typeof accountId === "string" && accountId !== "" && typeof apiToken === "string" && apiToken !== ""
494
+ ? createWorkflowsRestClient({ accountId, apiToken })
495
+ : undefined;
496
+ };`]:[],...e.hasGlobal?[` if (this.globalDeclaration) {
497
+ const database = this.globalDeclaration.d1(env);
498
+
499
+ if (database) {
500
+ options.globalIntrospector = buildGlobalIntrospector(database);
501
+ // \`importGlobals\` wires the admin bulk-import endpoint's global
502
+ // plane: the rows \`resolveTableSharding\` classifies as \`.global()\`
503
+ // land here, and without it they are reported, not written.
504
+ options.importGlobals = buildGlobalImporter(database, this.cdcEnabled);
505
+ // The read/replay half of the same admin plane. Each one is the
506
+ // only reason its endpoint can see the global storage plane at
507
+ // all, and every one of them fails SILENTLY when unset — export
508
+ // and \`lunora backup create\` answer 200 having written only
509
+ // shard-local rows (an export→import round trip then restores
510
+ // cleanly minus every global row), CDC sync answers with only
511
+ // shard changes, and point-in-time apply reports
512
+ // \`globalApplied: 0\`. Nothing here is project-specific either.
513
+ options.exportGlobals = buildGlobalExporter(database);
514
+ options.syncGlobals = buildGlobalCdcSync(database);
515
+ options.applyGlobals = buildGlobalCdcApplier(database, this.cdcEnabled);
516
+ }
517
+ }`]:[],...e.hasStorage?[` if (this.storageDeclaration) {
518
+ Object.assign(options, this.buildStorageAdmin(env));
519
+ options.storage = (rawEnv: unknown, origin?: string) => this.resolveStorage(rawEnv as Env, origin);
520
+ }`]:[],...e.hasKvIntrospector?[" options.kvIntrospector = createKvIntrospectorFromEnv(env);"]:[],...e.hasVectors?[` if (this.shardExtras.vectors) {
521
+ options.vectorIntrospector = createVectorAdminIntrospector({
522
+ indexes: this.shardExtras.vectors(env as unknown as Record<string, unknown>),
523
+ registry: LUNORA_VECTOR_INDEXES,
524
+ });
525
+ } else {
526
+ // Emitted only when the schema declares an index, so reaching here
527
+ // means the app declared one and never bound it. The studio's
528
+ // Vectors tab is on (its flag is the same index count) and every
529
+ // request to it would answer VECTORS_NOT_CONFIGURED, while
530
+ // \`ctx.vectors\` is the throwing stub — so this is already broken,
531
+ // just later and less legibly. Same shape as \`.auth()\`'s guards.
532
+ throw new Error(
533
+ ".vectors(): the schema declares vector index(es) but no binding map was chained. Pass \`.vectors((env) => ({ <indexName>: env.<BINDING> }))\` so \`ctx.vectors\` resolves and the studio's Vectors tab can list them.",
534
+ );
535
+ }`]:[],...e.hasNotify?[" options.notifySubscriptionStore = notifyConfig.store ? notifyConfig.store(env as Record<string, unknown>) : undefined;"]:[]," options.logArchive = resolveLogArchiveFromEnv(env);",...e.hasAuth?[` // Captured before the branch so the narrowing survives — reading
536
+ // \`this.authDeclaration.namespace\` again below would be optional all over again.
537
+ const authDeclaration = this.authDeclaration;
538
+ const authNamespace = authDeclaration?.namespace;
539
+ const authD1 = authDeclaration?.d1;
540
+
541
+ if (authDeclaration && authNamespace) {
542
+ // DO-backed mode. The auth tables live inside the object and DO storage is
543
+ // unreachable from here, so better-auth runs in there and this worker talks
544
+ // to it. \`createDoAuthWiring\` is a tested function in \`@lunora/auth\` rather
545
+ // than more emitted code: request-path logic in generated output can only be
546
+ // typechecked, never unit-tested.
547
+ const authWiring = createDoAuthWiring({
548
+ // The OAuth discovery documents (an \`mcp()\` resource's metadata, the
549
+ // issuer's) are derived here from the declared options, so the worker
550
+ // forwards only those exact paths and no other probe reaches the object.
551
+ // Memoised on the declaration: a framework-hosted worker rebuilds these
552
+ // options per request, and \`options(env)\` rebuilds every plugin.
553
+ discoveryPaths: authDiscoveryPathsFor(authDeclaration, env),
554
+ internalSecret: authDeclaration.internalSecret?.(env),${U(e)}
555
+ namespace: authNamespace(env),
556
+ objectName: authDeclaration.objectName?.(env),
557
+ });
558
+
559
+ options.authHandler = authWiring.authHandler;
560
+ options.authDiscoveryHandler = authWiring.discoveryHandler;
561
+ options.resolveIdentity = authWiring.resolveIdentity;
562
+ // The audit log lives in the object like every other auth table, so the feed
563
+ // reads through it rather than querying D1.
564
+ options.authAuditReader = authWiring.auditReader;
565
+ // Set only once auth is pinned to a jurisdiction: copies the users left in the
566
+ // un-pinned object across (\`__lunora_admin__:copyAuthToJurisdiction\`).
567
+ options.authJurisdictionMove = authWiring.jurisdictionMove;
568
+ // \`authAdmin\` stays D1-only: its ~30 methods read the auth tables directly
569
+ // from the worker, which DO storage does not allow. The studio's auth pages
570
+ // therefore report "not configured" in this mode rather than silently
571
+ // returning empty data.
572
+ } else if (authDeclaration && authD1) {
573
+ options.authHandler = (request) => {
574
+ const auth = getAuth();
575
+
576
+ return auth ? handleAuthRequest(auth, request) : Promise.resolve(undefined);
577
+ };
578
+ // The OAuth discovery documents outside \`/api/auth\` (served only with an
579
+ // \`mcp()\` or \`oauthProvider()\` plugin, and only after the app's own routes).
580
+ options.authDiscoveryHandler = (request) => {
581
+ const auth = getAuth();
582
+
583
+ return auth ? handleAuthDiscoveryRequest(auth, request) : Promise.resolve(undefined);
584
+ };
585
+ options.resolveIdentity = async (request) => {
586
+ const auth = getAuth();
587
+
588
+ if (!auth) {
589
+ return null;
590
+ }
591
+
592
+ const session = await auth.api.getSession({ headers: (request as Request).headers });
593
+
594
+ if (!session?.user?.id) {
595
+ return null;
596
+ }
597
+
598
+ // \`role\` rides along so \`rls(policies, { roles })\` and \`auth.can(...)\`
599
+ // work on this wiring without a hand-written resolver. better-auth's
600
+ // \`admin()\` plugin owns that column (comma-joined for multiple roles)
601
+ // and only an administrator can write it; it is absent when the plugin
602
+ // is off, which reads as no roles.
603
+ //
604
+ // \`expiresAtMs\` is the socket credential expiry the runtime forwards
605
+ // as \`x-lunora-identity-exp\`. Without it the DO's expiry check never
606
+ // fires, so a signed-out, banned or lapsed user keeps streaming their
607
+ // RLS-scoped rows over an already-open WebSocket while every HTTP call
608
+ // is anonymous. better-auth hands back a \`Date\`; anything else means
609
+ // the adapter did not hydrate it, and omitting beats guessing.
610
+ const expiresAt = session.session.expiresAt;
611
+ // \`email\` and \`name\` are the claims \`ctx.auth.getIdentity()\` is
612
+ // documented to carry ("email, name, roles, custom claims"). Without
613
+ // them the documented \`me\` query — \`identity?.email\` — resolves
614
+ // \`undefined\` on the built-in wiring. Empty strings are dropped so an
615
+ // absent claim reads as absent rather than as "".
616
+ const user = session.user as { email?: unknown; name?: unknown; role?: unknown };
617
+
618
+ return {
619
+ ...(typeof user.email === "string" && user.email.length > 0 ? { email: user.email } : {}),
620
+ ...(expiresAt instanceof Date ? { expiresAtMs: expiresAt.getTime() } : {}),
621
+ ...(typeof user.name === "string" && user.name.length > 0 ? { name: user.name } : {}),
622
+ role: user.role,
623
+ userId: session.user.id,
624
+ };
625
+ };
626
+ const authInstance = getAuth();
627
+
628
+ options.authAdmin = authInstance ? createAuthAdmin(authInstance) : undefined;
629
+ options.authAuditReader = createAuthAuditReader(d1Executor(authD1(env) as never));
630
+ }`]:[],...e.hasAccess?[e.hasAuth?` if (this.accessSelector) {
631
+ const accessResolver = createAccessResolver(this.accessSelector(env));
632
+ const fallback = options.resolveIdentity;
633
+
634
+ options.resolveIdentity = fallback ? composeResolvers(accessResolver, fallback) : accessResolver;
635
+ }`:` if (this.accessSelector) {
636
+ options.resolveIdentity = createAccessResolver(this.accessSelector(env));
637
+ }`]:[],...e.voiceAgents&&e.voiceAgents.length>0?[` options.voiceAgents = {
638
+ ${e.voiceAgents.map(r=>` ${JSON.stringify(r.exportName)}: (env as Record<string, unknown>)[${JSON.stringify(r.bindingName)}] as ShardNamespaceLike,`).join(`
639
+ `)}
640
+ };`]:[]],J=e=>[" cronJobs: LUNORA_CRONS,"," functions: LUNORA_FUNCTIONS,",...e.identity?[` identity: lunoraIdentityContract.${e.identity.exportName},`]:[],...e.jurisdiction?[` jurisdiction: ${JSON.stringify(e.jurisdiction)},`]:[],...e.wantsArchitecture?[" architecture,"]:[],...e.wantsOpenApi?[" openApiSpec,"]:[],...e.wantsOpenRpc?[" openRpcSpec,"]:[],...e.hasQueue?[" queue: (batch: unknown, queueEnv: unknown, _context: ExecutionContextLike, trigger: TriggerTrace): Promise<void> =>"," dispatchQueueBatch(batch as Parameters<typeof dispatchQueueBatch>[0], LUNORA_QUEUE_REGISTRY, {"," capture: shouldCaptureQueue(queueEnv as Record<string, unknown>)",` ? createQueueCaptureSink(queueEnv as Record<string, unknown>${e.jurisdiction?`, { jurisdiction: ${JSON.stringify(e.jurisdiction)} }`:""})`," : undefined,"," env: queueEnv as Record<string, unknown>,"," traceparent: trigger.traceparent,"," }),"]:[]," ...(this.httpRouterApp ? { httpRouter: this.httpRouterApp } : {}),"," routes: this.routeMap,"," shardDO: this.shardSelector?.(env) ?? (undefined as unknown as ShardNamespaceLike),"],K=e=>[...e.hasAuth?["AuthDeclaration"]:[],"ComposedApp",...e.hasGlobal?["GlobalDeclaration"]:[],"LunoraConfig",...e.hasScheduler?["SchedulerDeclaration"]:[],"Selector",...e.hasStorage?["StorageDeclaration"]:[]].toSorted((r,t)=>r.localeCompare(t)).join(", "),X=e=>{const r=(e.hasVectors??!0)&&(e.vectorIndexCount??0)>0,t={...e,hasVectors:r},{hasAuth:a}=t,n=C(t),o=Q(t),i=a?` let auth: LunoraAuth | null = null;
641
641
  let authInit: Promise<void> | null = null;
642
642
  `:"",l=a?`
643
643
  const initAuth = async (env: Env): Promise<void> => {
@@ -698,7 +698,7 @@ ${p.map(b=>` { agent: lunoraAgentDefinitions.${b.exportName}, classNa
698
698
  `:"",w=` /** Materialise the standalone Cloudflare worker + \`ShardDO\` class. */
699
699
  public build(): ComposedApp {
700
700
  return this.assemble();
701
- }${t.hasFramework?"\n\n /** Compose Lunora's realtime plane INTO a meta-framework's Cloudflare handler (SvelteKit/Astro/Nuxt). The framework `host` serves everything except the reserved `/_lunora/*` endpoints; pass the adapter-emitted worker (e.g. SvelteKit's `_worker.js`, Astro's `handle`). */\n public buildFrameworkWorker(host: FrameworkHostHandler): ComposedApp {\n return this.assemble(host);\n }":""}`;return`${E}${j(t).join(`
701
+ }${t.hasFramework?"\n\n /** Compose Lunora's realtime plane INTO a meta-framework's Cloudflare handler (SvelteKit/Astro/Nuxt). The framework `host` serves everything except the reserved `/_lunora/*` endpoints; pass the adapter-emitted worker (e.g. SvelteKit's `_worker.js`, Astro's `handle`). */\n public buildFrameworkWorker(host: FrameworkHostHandler): ComposedApp {\n return this.assemble(host);\n }":""}`;return`${E}${H(t).join(`
702
702
  `)}
703
703
 
704
704
  /** Read a value off the per-request \`env\`. Returns \`undefined\` to leave the capability unconfigured (its \`ctx.*\`/admin surface stays a clear-error stub). */
@@ -731,12 +731,12 @@ interface ComposedApp extends LunoraWorker {
731
731
  * first request so per-isolate singletons are built once.
732
732
  */
733
733
  class AppBuilder<Env extends object> {
734
- ${B(t).join(`
734
+ ${O(t).join(`
735
735
  `)}
736
736
 
737
737
  private emailHandler?: (env: Env) => (message: unknown, env: unknown, context: ExecutionContextLike) => Promise<void>;
738
738
 
739
- ${W(t).join(`
739
+ ${N(t).join(`
740
740
 
741
741
  `)}
742
742
 
@@ -744,7 +744,7 @@ ${w}
744
744
 
745
745
  /** Build the shard DO + compose the worker (standalone or framework-hosted), wrapping the lazy per-isolate singletons + auth init. */
746
746
  private assemble(${y}): ComposedApp {
747
- const ShardDO = createShardDO({${_(t)}});
747
+ const ShardDO = createShardDO({${q(t)}});
748
748
 
749
749
  // Per-isolate singletons: the worker (and auth instance) are expensive to
750
750
  // build, so the first request constructs them and every later request on
@@ -798,11 +798,11 @@ ${t.hasFramework?`
798
798
  `:""}
799
799
  return composed;
800
800
  }
801
- ${Q(t)}${J(t.hasStorage)}
801
+ ${R(t)}${x(t.hasStorage)}
802
802
  /** Fan the recorded declarations into the worker-side \`createWorker\` options. */
803
803
  private buildWorkerOptions(env: Env, ${h}): WorkerOptions {
804
804
  const options: WorkerOptions = {
805
- ${M(t).join(`
805
+ ${J(t).join(`
806
806
  `)}
807
807
  };
808
808
 
@@ -821,7 +821,7 @@ ${o.join(`
821
821
  return options;
822
822
  }
823
823
  }
824
- ${K(t.hasGlobal)}
824
+ ${A(t.hasGlobal)}
825
825
  /**
826
826
  * Shape of the project's root \`lunora.config.*\`.
827
827
  *
@@ -856,5 +856,5 @@ interface LunoraConfig<Env extends object = object> {
856
856
  const defineApp = <Env extends object>(): AppBuilder<Env> => new AppBuilder<Env>();
857
857
 
858
858
  export { AppBuilder, defineApp };
859
- export type { ${V(t)} };
860
- `};export{Z as emitApp};
859
+ export type { ${K(t)} };
860
+ `};export{X as emitApp};