@lunora/codegen 1.0.0-alpha.24 → 1.0.0-alpha.240

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.
Files changed (110) hide show
  1. package/LICENSE.md +6 -0
  2. package/README.md +1 -1
  3. package/dist/index.d.mts +3388 -1179
  4. package/dist/index.d.ts +3388 -1179
  5. package/dist/index.mjs +1 -34
  6. package/dist/packem_shared/AGENTS_FILENAME-DoPI92Wu.mjs +1 -0
  7. package/dist/packem_shared/CONTAINERS_FILENAME-B6TFs82W.mjs +1 -0
  8. package/dist/packem_shared/CodegenDiagnosticError-BUXlG3P-.mjs +1 -0
  9. package/dist/packem_shared/DEFAULT_TARGET-DCpDuuUM.mjs +1 -0
  10. package/dist/packem_shared/FLAGS_FILENAME-BedPDCsR.mjs +1 -0
  11. package/dist/packem_shared/GENERATED_HEADER-DSXl0YM2.mjs +1 -0
  12. package/dist/packem_shared/LUNORA_ERROR_CODES-C2s0xWQD.mjs +1 -0
  13. package/dist/packem_shared/MUTATORS_FILENAME-B6cKrN_m.mjs +1 -0
  14. package/dist/packem_shared/NOTIFY_FILENAME-Cri3NT5U.mjs +1 -0
  15. package/dist/packem_shared/OPENRPC_VERSION-Cl6P9WGv.mjs +3 -0
  16. package/dist/packem_shared/PROJECT_CONFIG_FILENAMES-DzOu-lSc.mjs +1 -0
  17. package/dist/packem_shared/QUEUES_FILENAME-CxkPcMH1.mjs +1 -0
  18. package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-IOiezeVr.mjs +9 -0
  19. package/dist/packem_shared/SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs +2 -0
  20. package/dist/packem_shared/SDK_LANGUAGES-Df_CnJx5.mjs +372 -0
  21. package/dist/packem_shared/SHAPES_FILENAME-zJgzynXR.mjs +1 -0
  22. package/dist/packem_shared/SchemaSnapshotParseError-CPOXlFhI.mjs +18 -0
  23. package/dist/packem_shared/WORKFLOWS_FILENAME-B_ZJxRSx.mjs +1 -0
  24. package/dist/packem_shared/buildOpenApiDocument-nYvBhjxu.mjs +3 -0
  25. package/dist/packem_shared/capabilities-DJJWVEtk.mjs +18 -0
  26. package/dist/packem_shared/chain-H2N_uKgj.mjs +1 -0
  27. package/dist/packem_shared/classify-procedure-call-BztLe76A.mjs +1 -0
  28. package/dist/packem_shared/context-property-calls-CjDzLU8p.mjs +1 -0
  29. package/dist/packem_shared/declared-output-Iaar469J.mjs +1 -0
  30. package/dist/packem_shared/describeErrorLevelFindings-vzaGS9KL.mjs +1 -0
  31. package/dist/packem_shared/discoverAuthApiCalls-FxrdBeVt.mjs +1 -0
  32. package/dist/packem_shared/discoverCrons-MfKw7IFf.mjs +1 -0
  33. package/dist/packem_shared/discoverFunctions-BsmX-sEq.mjs +1 -0
  34. package/dist/packem_shared/discoverHttpRoutes-BcXI9CNt.mjs +1 -0
  35. package/dist/packem_shared/discoverHyperdriveCalls-D9qXqTq3.mjs +1 -0
  36. package/dist/packem_shared/discoverInserts-CFJ3IVeI.mjs +1 -0
  37. package/dist/packem_shared/discoverMaskProcedures-CV_Cc2_g.mjs +1 -0
  38. package/dist/packem_shared/discoverMigrations-DbrHwcGE.mjs +1 -0
  39. package/dist/packem_shared/discoverNondeterministicCalls-CSQ_GDcA.mjs +1 -0
  40. package/dist/packem_shared/discoverQueries-C7y8i_Ga.mjs +1 -0
  41. package/dist/packem_shared/discoverR2sqlCalls-fu7fC0i_.mjs +1 -0
  42. package/dist/packem_shared/discoverRlsMetadata-CPmAGL0W.mjs +1 -0
  43. package/dist/packem_shared/discoverRlsProcedures-BO4qC77y.mjs +1 -0
  44. package/dist/packem_shared/discoverSandboxUsage-CrjZ6yNg.mjs +1 -0
  45. package/dist/packem_shared/discoverSchema-D8DBDHEg.mjs +1 -0
  46. package/dist/packem_shared/discoverStorageRulesMetadata-D8VYflWt.mjs +1 -0
  47. package/dist/packem_shared/emitAgents-Cy7QGO1t.mjs +1 -0
  48. package/dist/packem_shared/emitApi-CJ9ziZnP.mjs +154 -0
  49. package/dist/packem_shared/emitApp-BGhO5bhT.mjs +852 -0
  50. package/dist/packem_shared/emitCrons-mkwWkn0R.mjs +69 -0
  51. package/dist/packem_shared/emitDataModel-D3WuEZ4b.mjs +113 -0
  52. package/dist/packem_shared/emitDrizzleSchema-Cv0HtLR3.mjs +15 -0
  53. package/dist/packem_shared/emitFunctions-BqAz1ssY.mjs +249 -0
  54. package/dist/packem_shared/emitServer-BEo_fCY8.mjs +365 -0
  55. package/dist/packem_shared/emitShard-CsWK2K91.mjs +1 -0
  56. package/dist/packem_shared/exported-procedure-chains-CmCDiPBV.mjs +1 -0
  57. package/dist/packem_shared/fingerprintSchemaSources-L3nGKDQt.mjs +1 -0
  58. package/dist/packem_shared/formatAdvisories-DwmUKYuc.mjs +2 -0
  59. package/dist/packem_shared/index-BoaHhVtM.mjs +1 -0
  60. package/dist/packem_shared/isD1GlobalTable-udvHAAzD.mjs +1 -0
  61. package/dist/packem_shared/isTypedSchema-CKzc3ioR.mjs +4 -0
  62. package/dist/packem_shared/json-data-Chfs2Cz5.mjs +1 -0
  63. package/dist/packem_shared/listLunoraSourceFiles-DP-5e-RE.mjs +1 -0
  64. package/dist/packem_shared/loadProjectConfig-CKsFNgn3.mjs +1 -0
  65. package/dist/packem_shared/module-specifiers-WF8iAydP.mjs +1 -0
  66. package/dist/packem_shared/parse-validator-C94Yiabo.mjs +1 -0
  67. package/dist/packem_shared/paths-C-9fwEgQ.mjs +1 -0
  68. package/dist/packem_shared/qualifiers-BhOL15WZ.mjs +1 -0
  69. package/dist/packem_shared/queries-B-f4jO-x.mjs +1 -0
  70. package/dist/packem_shared/readPackageDependencies-C6h6FZuP.mjs +1 -0
  71. package/dist/packem_shared/redact-Cy14LEnc.mjs +1 -0
  72. package/dist/packem_shared/schemaFromIr-BWFnvCVg.mjs +1 -0
  73. package/dist/packem_shared/shard-BBv6VBmX.mjs +1435 -0
  74. package/dist/packem_shared/shard-runtime-CM5qthZc.mjs +309 -0
  75. package/dist/packem_shared/shared-DjUziztz.mjs +9 -0
  76. package/dist/packem_shared/unwrap-handler-return-CoV_GK33.mjs +1 -0
  77. package/package.json +16 -7
  78. package/dist/packem_shared/CONTAINERS_FILENAME-DlP6YM_Q.mjs +0 -224
  79. package/dist/packem_shared/CodegenDiagnosticError-DeblMkzO.mjs +0 -23
  80. package/dist/packem_shared/FLAGS_FILENAME-B1vE0LIo.mjs +0 -139
  81. package/dist/packem_shared/GENERATED_HEADER-DUkXYD5R.mjs +0 -3260
  82. package/dist/packem_shared/LUNORA_ERROR_CODES-CySpQPD3.mjs +0 -61
  83. package/dist/packem_shared/LUNORA_SOLUTION_RULES-BTejmZp-.mjs +0 -131
  84. package/dist/packem_shared/MUTATORS_FILENAME-BhqdPtKp.mjs +0 -81
  85. package/dist/packem_shared/OPENRPC_VERSION-CjBUaolx.mjs +0 -60
  86. package/dist/packem_shared/QUEUES_FILENAME-B5_eWCRe.mjs +0 -119
  87. package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-BUcGCXi3.mjs +0 -1130
  88. package/dist/packem_shared/SCHEMA_SNAPSHOT_VERSION-wWGP2_5E.mjs +0 -245
  89. package/dist/packem_shared/SHAPES_FILENAME-ChV7MqgE.mjs +0 -94
  90. package/dist/packem_shared/WORKFLOWS_FILENAME-CCisG0Vy.mjs +0 -124
  91. package/dist/packem_shared/buildOpenApiDocument-WxYTLh11.mjs +0 -183
  92. package/dist/packem_shared/discover-ast-CT6BgBr4.mjs +0 -13
  93. package/dist/packem_shared/discoverAuthApiCalls-CoirYbg6.mjs +0 -62
  94. package/dist/packem_shared/discoverCrons-Cev7RRAf.mjs +0 -257
  95. package/dist/packem_shared/discoverFunctions-BWMczzBx.mjs +0 -465
  96. package/dist/packem_shared/discoverHttpRoutes-CfP6cMzt.mjs +0 -131
  97. package/dist/packem_shared/discoverInserts-C7zxXkUf.mjs +0 -61
  98. package/dist/packem_shared/discoverMaskProcedures-Cm81kwrb.mjs +0 -217
  99. package/dist/packem_shared/discoverMigrations-Bi5nJ0mJ.mjs +0 -97
  100. package/dist/packem_shared/discoverNondeterministicCalls-C4M8AXmQ.mjs +0 -122
  101. package/dist/packem_shared/discoverQueries-B0wGT-xe.mjs +0 -62
  102. package/dist/packem_shared/discoverR2sqlCalls-BVNMd428.mjs +0 -80
  103. package/dist/packem_shared/discoverRlsMetadata-BS9GOGC5.mjs +0 -280
  104. package/dist/packem_shared/discoverSchema-KYq55qu3.mjs +0 -864
  105. package/dist/packem_shared/discoverStorageRulesMetadata-Da8BKXcI.mjs +0 -97
  106. package/dist/packem_shared/emitApp-DD0i1ks0.mjs +0 -666
  107. package/dist/packem_shared/formatAdvisories-DdjK7sgh.mjs +0 -81
  108. package/dist/packem_shared/parse-validator-Cabb60UV.mjs +0 -133
  109. package/dist/packem_shared/paths-BRd6JHuF.mjs +0 -11
  110. package/dist/packem_shared/schemaFromIr-DTYsLBaA.mjs +0 -57
@@ -0,0 +1,852 @@
1
+ import{A as w}from"./capabilities-DJJWVEtk.mjs";import{G as y}from"./shared-DjUziztz.mjs";const k=e=>`has${e.charAt(0).toUpperCase()}${e.slice(1)}`,b=w.map(({appMethod:e,key:t})=>[k(t),e.method,e.configKey,e.doc]),g=e=>b.some(([t])=>e[t]),S=e=>e?['import * as lunoraIdentityContract from "../identity.js";']:[],E=(e,t)=>e?['import type { CreateAccessResolverOptions } from "@lunora/cloudflare-access";',`import { createAccessResolver${t?", composeResolvers":""} } from "@lunora/cloudflare-access";`]:[],D=e=>e?['import { createKvIntrospectorFromEnv } from "@lunora/bindings/kv";']:[],x=e=>e?['import { createVectorAdminIntrospector } from "@lunora/bindings/vectors";']:[],R=e=>e?['import type { D1CtxDbOptions, D1DatabaseLike, D1Exec } from "@lunora/d1";','import { applyCdcChanges, createD1CtxDb, emitD1QueryCost, exportGlobalRows, facetGlobalColumn, importGlobalRows, listGlobalTables, readD1CdcChanges, readGlobalTablePage, retryingExec } from "@lunora/d1";']:[],A=e=>e?['import notifyConfig from "../notify.js";']:[],m=e=>(e.emailAgents?.length??0)>0,C=e=>m(e)?['import { dispatchAgentEmail } from "@lunora/agent/inbound";']:[],O=e=>m(e)?['import * as lunoraAgentDefinitions from "../agents.js";']:[],T=e=>{const{hasFramework:t,hasGlobal:a,hasHyperdriveGlobal:r,hasQueue:n,useUmbrella:i}=e,o=i?"lunorash/runtime":"@lunora/runtime",l=["ExecutionContextLike","HttpRouterLike","LunoraWorker","Route","ScheduledControllerLike","ShardNamespaceLike","WorkerOptions",...n?["TriggerTrace"]:[],...a?["GlobalIntrospector","AdminTableResolver"]:[],...t?["FrameworkHostHandler"]:[]],s=[...a||r?["createCrossShardRelationCapabilities"]:[],"createWorker",...e.jurisdiction?["declareAppJurisdiction"]:[],"resolveLogArchiveFromEnv",...t?["withFrameworkWorker"]:[]].join(", ");return[`import type { ${[...l].toSorted((c,d)=>c.localeCompare(d)).join(", ")} } from "${o}";`,`import { ${s} } from "${o}";`]},N=e=>{const{hasAccess:t,hasAuth:a,hasGlobal:r,hasHyperdriveGlobal:n,hasKvIntrospector:i,hasQueue:o,hasScheduler:l,hasStorage:s,hasWorkflow:c,wantsOpenApi:d,wantsOpenRpc:h}=e;return[...a?['import type { AuthNamespaceLike, LunoraAuth, LunoraAuthOptions } from "@lunora/auth";','import { createAuth, createAuthAdmin, createAuthAuditReader, createDoAuthWiring, d1Executor, ensureMigrated, handleAuthRequest, lunoraD1Adapter } from "@lunora/auth";']:[],...E(t,a),...R(r),...n?['import type { HyperdriveEngine } from "@lunora/hyperdrive/global";','import { createHyperdriveGlobalCtxDb } from "@lunora/hyperdrive/global";','import type { SqlCtxDbOptions, SqlExec } from "@lunora/sql-store";']:[],...D(i),...x(e.hasVectors===!0),...l?['import type { DurableObjectNamespaceLike } from "@lunora/scheduler";','import { createScheduler } from "@lunora/scheduler";']:[],...s?['import type { R2BucketLike, R2S3Credentials, Storage } from "@lunora/storage";','import { createBucketStorage, createStorage } from "@lunora/storage";']:[],...c?['import { createWorkflowsRestClient } from "@lunora/workflow";']:[],...C(e),...T(e),"",...S(e.identity),...O(e),...r||n?['import schema from "../schema.js";']:[],...A(e.hasNotify),'import { LUNORA_CRONS } from "./crons.js";','import { LUNORA_FUNCTIONS } from "./functions.js";',...o?['import { createQueueCaptureSink, dispatchQueueBatch, shouldCaptureQueue } from "@lunora/queue";','import { LUNORA_QUEUE_REGISTRY } from "./queues.js";']:[],...d?['import { openApiSpec } from "./openapi.js";']:[],...h?['import { openRpcSpec } from "./openrpc.js";']:[],'import { createShardDO } from "./shard.js";',...e.hasVectors===!0?['import { LUNORA_VECTOR_INDEXES } from "./vectors.js";']:[]]},I=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}']:[]],L=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>;"]:[],...g(e)?[" private readonly shardExtras: Partial<ShardConfig> = {};"]:[]," private shardSelector?: Selector<Env, ShardNamespaceLike>;",...e.hasSourcedTables?[' private sourceClientFactory?: NonNullable<ShardConfig["sourceClient"]>;']:[],...e.hasStorage?[" private storageDeclaration?: StorageDeclaration<Env>;"]:[]],q=e=>b.filter(([t])=>e[t]).map(([,t,a,r])=>` /** ${r} */
2
+ public ${t}(factory: (env: Env) => ReturnType<NonNullable<ShardConfig["${a}"]>>): this {
3
+ this.shardExtras.${a} = factory as NonNullable<ShardConfig["${a}"]>;
4
+
5
+ return this;
6
+ }`),j=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;
9
+
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.
13
+ *
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.
15
+ */
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;
28
+
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;
33
+
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;
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;
43
+
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;
48
+
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;
53
+
54
+ return this;
55
+ }`,...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"]>;
58
+
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;
63
+
64
+ return this;
65
+ }`]:[],...q(e)],G=e=>{const t=r=>e.hasScheduler?`
66
+ ...(this.schedulerDeclaration ? { scheduler: this.resolveScheduler(env) as unknown as ${r}["scheduler"] } : {}),`:"",a=[" 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);
71
+
72
+ if (!database) {
73
+ return undefined;
74
+ }
75
+
76
+ const origin = this.globalDeclaration?.origin?.(env);
77
+ const crossShard = origin
78
+ ? createCrossShardRelationCapabilities({ identity: request?.identity, origin, userId: request?.userId ?? undefined })
79
+ : undefined;
80
+
81
+ return createD1CtxDb({
82
+ ...(crossShard ? { crossShardCounter: crossShard.crossShardCounter, crossShardReader: crossShard.crossShardReader } : {}),${t("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;
105
+
106
+ if (!declaration || !exec) {
107
+ return undefined;
108
+ }
109
+
110
+ const origin = declaration.origin?.(env);
111
+ const crossShard = origin
112
+ ? createCrossShardRelationCapabilities({ identity: request?.identity, origin, userId: request?.userId ?? undefined })
113
+ : undefined;
114
+
115
+ return createHyperdriveGlobalCtxDb({
116
+ ...(crossShard ? { crossShardCounter: crossShard.crossShardCounter, crossShardReader: crossShard.crossShardReader } : {}),${t("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
+ : {}),`]:[],...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) } : {}),"]:[],...g(e)?[" ...this.shardExtras,"]:[]];return a.length>0?`
138
+ ${a.join(`
139
+ `)}
140
+ `:""},B=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)},`:"",P=e=>[...e.tableNames.length>0?[` options.listSchemaTables = () => [${e.tableNames.map(t=>JSON.stringify(t)).join(", ")}];`]:[],...e.hasScheduler?[` if (this.schedulerDeclaration) {
143
+ options.schedulerDO = this.schedulerDeclaration.namespace(env);
144
+ }`]:[],...e.hasWorkflow?[` options.workflowsClient = (workflowEnv) => {
145
+ const source = workflowEnv as Record<string, unknown>;
146
+ const accountId = source["CLOUDFLARE_ACCOUNT_ID"];
147
+ const apiToken = source["CLOUDFLARE_API_TOKEN"];
148
+
149
+ return typeof accountId === "string" && accountId !== "" && typeof apiToken === "string" && apiToken !== ""
150
+ ? createWorkflowsRestClient({ accountId, apiToken })
151
+ : undefined;
152
+ };`]:[],...e.hasGlobal?[` if (this.globalDeclaration) {
153
+ const database = this.globalDeclaration.d1(env);
154
+
155
+ if (database) {
156
+ options.globalIntrospector = buildGlobalIntrospector(database);
157
+ // \`resolveTableSharding\`/\`importGlobals\` wire the admin bulk-import
158
+ // endpoint: without the former, EVERY row (including a \`.global()\`
159
+ // table's) routes to the default shard, so a global table is never
160
+ // recognised as global and the latter is never reached — the
161
+ // endpoint answers 200 with \`inserted: {}\` for a write that never
162
+ // happened. Both are mechanical over the schema this file already
163
+ // imports, so there is nothing project-specific to configure.
164
+ options.resolveTableSharding = buildTableShardingResolver();
165
+ options.importGlobals = buildGlobalImporter(database, this.cdcEnabled);
166
+ // The read/replay half of the same admin plane. Each one is the
167
+ // only reason its endpoint can see the global storage plane at
168
+ // all, and every one of them fails SILENTLY when unset — export
169
+ // and \`lunora backup create\` answer 200 having written only
170
+ // shard-local rows (an export→import round trip then restores
171
+ // cleanly minus every global row), CDC sync answers with only
172
+ // shard changes, and point-in-time apply reports
173
+ // \`globalApplied: 0\`. Nothing here is project-specific either.
174
+ options.exportGlobals = buildGlobalExporter(database);
175
+ options.syncGlobals = buildGlobalCdcSync(database);
176
+ options.applyGlobals = buildGlobalCdcApplier(database, this.cdcEnabled);
177
+ }
178
+ }`]:[],...e.hasStorage?[` if (this.storageDeclaration) {
179
+ Object.assign(options, this.buildStorageAdmin(env));
180
+ options.storage = (rawEnv: unknown, origin?: string) => this.resolveStorage(rawEnv as Env, origin);
181
+ }`]:[],...e.hasKvIntrospector?[" options.kvIntrospector = createKvIntrospectorFromEnv(env);"]:[],...e.hasVectors===!0?[` if (this.shardExtras.vectors) {
182
+ options.vectorIntrospector = createVectorAdminIntrospector({
183
+ indexes: this.shardExtras.vectors(env as unknown as Record<string, unknown>),
184
+ registry: LUNORA_VECTOR_INDEXES,
185
+ });
186
+ } else {
187
+ // Emitted only when the schema declares an index, so reaching here
188
+ // means the app declared one and never bound it. The studio's
189
+ // Vectors tab is on (its flag is the same index count) and every
190
+ // request to it would answer VECTORS_NOT_CONFIGURED, while
191
+ // \`ctx.vectors\` is the throwing stub — so this is already broken,
192
+ // just later and less legibly. Same shape as \`.auth()\`'s guards.
193
+ throw new Error(
194
+ ".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.",
195
+ );
196
+ }`]:[],...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
197
+ // \`this.authDeclaration.namespace\` again below would be optional all over again.
198
+ const authDeclaration = this.authDeclaration;
199
+ const authNamespace = authDeclaration?.namespace;
200
+ const authD1 = authDeclaration?.d1;
201
+
202
+ if (authDeclaration && authNamespace) {
203
+ // DO-backed mode. The auth tables live inside the object and DO storage is
204
+ // unreachable from here, so better-auth runs in there and this worker talks
205
+ // to it. \`createDoAuthWiring\` is a tested function in \`@lunora/auth\` rather
206
+ // than more emitted code: request-path logic in generated output can only be
207
+ // typechecked, never unit-tested.
208
+ const authWiring = createDoAuthWiring({
209
+ internalSecret: authDeclaration.internalSecret?.(env),${B(e)}
210
+ namespace: authNamespace(env),
211
+ objectName: authDeclaration.objectName?.(env),
212
+ });
213
+
214
+ options.authHandler = authWiring.authHandler;
215
+ options.resolveIdentity = authWiring.resolveIdentity;
216
+ // The audit log lives in the object like every other auth table, so the feed
217
+ // reads through it rather than querying D1.
218
+ options.authAuditReader = authWiring.auditReader;
219
+ // Set only once auth is pinned to a jurisdiction: copies the users left in the
220
+ // un-pinned object across (\`__lunora_admin__:copyAuthToJurisdiction\`).
221
+ options.authJurisdictionMove = authWiring.jurisdictionMove;
222
+ // \`authAdmin\` stays D1-only: its ~30 methods read the auth tables directly
223
+ // from the worker, which DO storage does not allow. The studio's auth pages
224
+ // therefore report "not configured" in this mode rather than silently
225
+ // returning empty data.
226
+ } else if (authDeclaration && authD1) {
227
+ options.authHandler = (request) => {
228
+ const auth = getAuth();
229
+
230
+ return auth ? handleAuthRequest(auth, request) : Promise.resolve(undefined);
231
+ };
232
+ options.resolveIdentity = async (request) => {
233
+ const auth = getAuth();
234
+
235
+ if (!auth) {
236
+ return null;
237
+ }
238
+
239
+ const session = await auth.api.getSession({ headers: (request as Request).headers });
240
+
241
+ if (!session?.user?.id) {
242
+ return null;
243
+ }
244
+
245
+ // \`role\` rides along so \`rls(policies, { roles })\` and \`auth.can(...)\`
246
+ // work on this wiring without a hand-written resolver. better-auth's
247
+ // \`admin()\` plugin owns that column (comma-joined for multiple roles)
248
+ // and only an administrator can write it; it is absent when the plugin
249
+ // is off, which reads as no roles.
250
+ //
251
+ // \`expiresAtMs\` is the socket credential expiry the runtime forwards
252
+ // as \`x-lunora-identity-exp\`. Without it the DO's expiry check never
253
+ // fires, so a signed-out, banned or lapsed user keeps streaming their
254
+ // RLS-scoped rows over an already-open WebSocket while every HTTP call
255
+ // is anonymous. better-auth hands back a \`Date\`; anything else means
256
+ // the adapter did not hydrate it, and omitting beats guessing.
257
+ const expiresAt = session.session.expiresAt;
258
+ // \`email\` and \`name\` are the claims \`ctx.auth.getIdentity()\` is
259
+ // documented to carry ("email, name, roles, custom claims"). Without
260
+ // them the documented \`me\` query — \`identity?.email\` — resolves
261
+ // \`undefined\` on the built-in wiring. Empty strings are dropped so an
262
+ // absent claim reads as absent rather than as "".
263
+ const user = session.user as { email?: unknown; name?: unknown; role?: unknown };
264
+
265
+ return {
266
+ ...(typeof user.email === "string" && user.email.length > 0 ? { email: user.email } : {}),
267
+ ...(expiresAt instanceof Date ? { expiresAtMs: expiresAt.getTime() } : {}),
268
+ ...(typeof user.name === "string" && user.name.length > 0 ? { name: user.name } : {}),
269
+ role: user.role,
270
+ userId: session.user.id,
271
+ };
272
+ };
273
+ const authInstance = getAuth();
274
+
275
+ options.authAdmin = authInstance ? createAuthAdmin(authInstance) : undefined;
276
+ options.authAuditReader = createAuthAuditReader(d1Executor(authD1(env) as never));
277
+ }`]:[],...e.hasAccess?[e.hasAuth?` if (this.accessSelector) {
278
+ const accessResolver = createAccessResolver(this.accessSelector(env));
279
+ const fallback = options.resolveIdentity;
280
+
281
+ options.resolveIdentity = fallback ? composeResolvers(accessResolver, fallback) : accessResolver;
282
+ }`:` if (this.accessSelector) {
283
+ options.resolveIdentity = createAccessResolver(this.accessSelector(env));
284
+ }`]:[],...e.voiceAgents&&e.voiceAgents.length>0?[` options.voiceAgents = {
285
+ ${e.voiceAgents.map(t=>` ${JSON.stringify(t.exportName)}: (env as Record<string, unknown>)[${JSON.stringify(t.bindingName)}] as ShardNamespaceLike,`).join(`
286
+ `)}
287
+ };`]:[]],W=e=>[" cronJobs: LUNORA_CRONS,"," functions: LUNORA_FUNCTIONS,",...e.identity?[` identity: lunoraIdentityContract.${e.identity.exportName},`]:[],...e.jurisdiction?[` jurisdiction: ${JSON.stringify(e.jurisdiction)},`]:[],...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),"],_=e=>e.hasScheduler?`
288
+ /** Resolve the \`SchedulerDO\`-backed scheduler for this env; \`undefined\` until the namespace is wired. */
289
+ private resolveScheduler(env: Env): ReturnType<typeof createScheduler> | undefined {
290
+ const namespace = this.schedulerDeclaration?.namespace(env);
291
+
292
+ return namespace ? createScheduler({${e.jurisdiction?` jurisdiction: ${JSON.stringify(e.jurisdiction)},`:""} namespace }) : undefined;
293
+ }
294
+ `:"",$=e=>e?`
295
+ /**
296
+ * One bucket's \`Storage\`, signing under the name it is registered as.
297
+ *
298
+ * \`bucketName\` is bound into every signed URL's HMAC canonical, so a bucket
299
+ * that signs as the default's name lets a URL minted for one bucket verify
300
+ * against another sharing the secret — and multi-bucket verification fails
301
+ * outright. Hence \`"default"\` for the bare \`ctx.storage\` bucket and the
302
+ * \`buckets\` key for every other.
303
+ *
304
+ * \`origin\` is the request's own origin, the base when no \`publicBaseUrl\` is
305
+ * declared.
306
+ */
307
+ private makeStorage(env: Env, declaration: StorageDeclaration<Env>, bucket: R2BucketLike, bucketName: string, origin?: string): Storage {
308
+ return createStorage({
309
+ bucket,
310
+ bucketName,
311
+ publicBaseUrl: declaration.publicBaseUrl?.(env) ?? origin,
312
+ s3: declaration.s3?.(env),
313
+ signingSecret: declaration.signingSecret?.(env),
314
+ });
315
+ }
316
+
317
+ /** Resolve the storage capability (single or multi-bucket) for the DO side. */
318
+ private resolveStorage(env: Env, origin?: string): Storage | undefined {
319
+ const declaration = this.storageDeclaration;
320
+
321
+ if (!declaration) {
322
+ return undefined;
323
+ }
324
+
325
+ const defaultBucket = declaration.bucket(env);
326
+
327
+ if (!defaultBucket) {
328
+ return undefined;
329
+ }
330
+
331
+ const extraEntries = Object.entries(declaration.buckets ?? {})
332
+ .map(([name, selector]) => [name, selector(env)] as const)
333
+ .filter((entry): entry is [string, R2BucketLike] => Boolean(entry[1]));
334
+
335
+ if (extraEntries.length === 0) {
336
+ return this.makeStorage(env, declaration, defaultBucket, "default", origin);
337
+ }
338
+
339
+ const map: Record<string, Storage> = { default: this.makeStorage(env, declaration, defaultBucket, "default", origin) };
340
+
341
+ for (const [name, bucket] of extraEntries) {
342
+ map[name] = this.makeStorage(env, declaration, bucket, name, origin);
343
+ }
344
+
345
+ return createBucketStorage(map, { default: "default" });
346
+ }
347
+
348
+ /** Derive the studio file-browser admin functions from the same buckets \`.storage()\` declared. */
349
+ private buildStorageAdmin(env: Env): Partial<WorkerOptions> {
350
+ const declaration = this.storageDeclaration;
351
+
352
+ if (!declaration) {
353
+ return {};
354
+ }
355
+
356
+ const defaultBucket = declaration.bucket(env);
357
+
358
+ if (!defaultBucket) {
359
+ return {};
360
+ }
361
+
362
+ const bindings: Record<string, R2BucketLike> = { default: defaultBucket };
363
+
364
+ for (const [name, selector] of Object.entries(declaration.buckets ?? {})) {
365
+ const bucket = selector(env);
366
+
367
+ if (bucket) {
368
+ bindings[name] = bucket;
369
+ }
370
+ }
371
+
372
+ // \`Object.hasOwn\`, not a bare lookup: \`bindings\` is a plain object, so a
373
+ // prototype key (\`?bucket=constructor\`, \`__proto__\`, \`toString\`) resolves
374
+ // to an inherited Object.prototype member instead of the default bucket.
375
+ //
376
+ // \`origin\` is the base when no \`publicBaseUrl\` is declared: the origin the
377
+ // admin request reached the worker on, which the signed-URL route hands
378
+ // over and then verifies. Only the secret gates signing.
379
+ const pick = (name?: string, origin?: string): Storage => {
380
+ const wanted = name !== undefined && name !== "" ? name : "default";
381
+ const bucketName = Object.hasOwn(bindings, wanted) ? wanted : "default";
382
+
383
+ return this.makeStorage(env, declaration, bindings[bucketName] ?? defaultBucket, bucketName, origin);
384
+ };
385
+ const hasSigning = Boolean(declaration.signingSecret?.(env));
386
+
387
+ return {
388
+ storageBuckets: Object.keys(bindings),
389
+ storageDelete: (key: string, opts?: { bucket?: string }) => pick(opts?.bucket).delete(key),
390
+ storageDownload: (key: string, opts?: { bucket?: string }) => pick(opts?.bucket).download(key),
391
+ storageList: (prefix?: string, opts?: { bucket?: string; cursor?: string; limit?: number }) => pick(opts?.bucket).list(prefix, opts),
392
+ storageSignedUrl: hasSigning
393
+ ? (key: string, opts?: { bucket?: string; contentType?: string; expiresInSeconds?: number; method?: "GET" | "PUT"; origin?: string }) =>
394
+ pick(opts?.bucket, opts?.origin).getSignedUrl(key, { contentType: opts?.contentType, expiresInSeconds: opts?.expiresInSeconds, method: opts?.method })
395
+ : undefined,
396
+ storageUpload: (key: string, body: ArrayBuffer, opts?: { bucket?: string; contentType?: string; sha256?: string }) => pick(opts?.bucket).upload(key, body, opts),
397
+ };
398
+ }
399
+ `:"",H=e=>e?`
400
+ /**
401
+ * 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\`).
402
+ *
403
+ * Opens a D1 Sessions API session pinned to \`bookmark\` (the caller's own
404
+ * last-known write, when supplied) so reads observe it — read-your-writes
405
+ * across replicas. \`onBookmark\`, when supplied, is invoked with the bookmark
406
+ * produced by each write so the caller (the generated DO) can record it on the
407
+ * dispatch's bookmark sink and echo \`x-d1-bookmark\` on the response.
408
+ *
409
+ * Wrapped in \`retryingExec\` so D1's documented baseline of transient failures
410
+ * (storage-object resets, isolate memory evictions, dropped connections) does
411
+ * not surface on every \`.global()\` read. Only statements that are provably
412
+ * read-only retry; writes — including the \`UPDATE … RETURNING\` the store's
413
+ * optimistic-concurrency check issues through \`all\` — pass straight through,
414
+ * because a transient error never says whether the write applied.
415
+ *
416
+ * Every read and write also records D1's own \`meta\` accounting (\`rows_read\` /
417
+ * \`rows_written\` / \`duration\`) against a low-cardinality \`verb:table\` tag.
418
+ * Rows READ is rows SCANNED, not returned, so this is the number that explains
419
+ * a D1 bill and the one a missing index inflates without anything being
420
+ * deployed; the dashboard's own metric is per-database and can't name the query.
421
+ * The emit is best-effort — instrumentation must never fail a served query.
422
+ */
423
+ const buildExec = (database: D1DatabaseLike, bookmark?: string, onBookmark?: (bookmark: string | undefined) => void): D1Exec => {
424
+ // Real D1 always exposes \`withSession\`; guarded the same way as \`batch\`
425
+ // below so a hand-rolled test double that omits it keeps working via
426
+ // \`prepare()\` straight on the raw binding — today's behaviour. With no
427
+ // inbound bookmark, \`"first-unconstrained"\` is the documented no-op
428
+ // equivalent (lowest latency, may read any replica) — see \`D1Client.withSession\`.
429
+ const session = typeof database.withSession === "function" ? database.withSession(bookmark ?? "first-unconstrained") : undefined;
430
+ const target = session ?? database;
431
+ const batchFn = target.batch;
432
+ const meter = (sql: string, meta: Record<string, unknown> | undefined): void => {
433
+ try {
434
+ emitD1QueryCost(sql, meta);
435
+ } catch {
436
+ // Best-effort: never let cost accounting fail the query it measures.
437
+ }
438
+ };
439
+
440
+ return retryingExec({
441
+ all: async (sql, parameters) => {
442
+ const result = await target
443
+ .prepare(sql)
444
+ .bind(...parameters)
445
+ .all<Record<string, unknown>>();
446
+
447
+ // \`all\` carries writes, not just reads: D1 runs
448
+ // \`UPDATE/DELETE … RETURNING\` through it exactly like \`.run()\`, and
449
+ // that is precisely what \`@lunora/sql-store\` issues for its
450
+ // optimistic-concurrency compare-and-swap — so \`patch\`, \`replace\`
451
+ // and \`delete\` all land here and nowhere else. Without this the
452
+ // bookmark those writes produced was never reported, and the next
453
+ // read could pin a replica that has not seen them: read-your-writes
454
+ // lost on the exact path the bookmark exists for. Reporting it after
455
+ // a plain \`SELECT\` too is harmless and correct — the session's
456
+ // bookmark only ever moves forward, and the sink takes the last
457
+ // value.
458
+ onBookmark?.(session?.getBookmark() ?? undefined);
459
+ meter(sql, result.meta);
460
+
461
+ return result.results;
462
+ },
463
+ // D1's own \`batch\` runs the whole array as one atomic SQLite
464
+ // transaction. Guarded because \`batch\` is optional in the structural
465
+ // type (test doubles may omit it) — real D1 always has it; a double
466
+ // without it still works through the store's sequential fallback.
467
+ // Invoked via \`.call(target, ...)\` rather than \`target.batch(...)\`
468
+ // directly so TS can narrow the captured \`batchFn\` across the closure
469
+ // boundary (a property-access narrowing like
470
+ // \`hasBatch = typeof target.batch === "function"\` does not survive
471
+ // into a nested arrow function); \`.call\` still binds \`this\` to
472
+ // \`target\`, so the real workerd \`D1Database\`/session doesn't throw
473
+ // \`TypeError: Illegal invocation\` the way a detached
474
+ // \`const fn = target.batch; fn(...)\` capture would.
475
+ batch: batchFn
476
+ ? async (statements) => {
477
+ const results = await batchFn.call(
478
+ target,
479
+ statements.map(({ params, sql }) => target.prepare(sql).bind(...params)),
480
+ );
481
+
482
+ // Meter each leg. D1 returns one result per statement, in
483
+ // order, each with its own \`meta\` — and a batch is where the
484
+ // expensive writes live (\`@lunora/sql-store\` runs its
485
+ // backfills through here), so discarding it left exactly the
486
+ // statements worth costing unaccounted. Guarded on the array
487
+ // because \`batch\` is optional in the structural type and a
488
+ // test double may resolve to anything.
489
+ if (Array.isArray(results)) {
490
+ for (const [index, statement] of statements.entries()) {
491
+ meter(statement.sql, (results[index] as { meta?: Record<string, unknown> } | undefined)?.meta);
492
+ }
493
+ }
494
+
495
+ onBookmark?.(session?.getBookmark() ?? undefined);
496
+ }
497
+ : undefined,
498
+ run: async (sql, parameters) => {
499
+ const result = await target
500
+ .prepare(sql)
501
+ .bind(...parameters)
502
+ .run();
503
+
504
+ meter(sql, result.meta);
505
+ onBookmark?.(session?.getBookmark() ?? undefined);
506
+ },
507
+ });
508
+ };
509
+
510
+ /** Introspect \`.global()\` (D1-backed) tables for the studio's global data browser. */
511
+ const buildGlobalIntrospector = (database: D1DatabaseLike): GlobalIntrospector => {
512
+ const exec = buildExec(database);
513
+
514
+ return {
515
+ facetColumn: (options) => facetGlobalColumn(exec, schema as never, options),
516
+ listTables: () => listGlobalTables(exec, schema as never),
517
+ readTablePage: (options) => readGlobalTablePage(exec, schema as never, options),
518
+ };
519
+ };
520
+
521
+ /**
522
+ * \`resolveTableSharding\` for the admin bulk-import endpoint: a lookup over each
523
+ * table's declared \`shardMode\` (\`defineTable(...).global()\` / \`.shardBy(field)\`
524
+ * already record exactly this shape on the table) — mechanical, nothing to
525
+ * configure per project. \`undefined\` for a table the schema doesn't declare, so
526
+ * the import endpoint's own unknown-table handling still applies.
527
+ */
528
+ const buildTableShardingResolver = (): AdminTableResolver => (table) => {
529
+ const declared = (schema as unknown as D1CtxDbOptions["schema"]).tables[table];
530
+
531
+ return declared?.shardMode ? { mode: declared.shardMode } : undefined;
532
+ };
533
+
534
+ /**
535
+ * \`importGlobals\` for the admin bulk-import endpoint: routes \`.global()\` rows
536
+ * through the same D1 writer \`.global()\` reads/writes already use, via
537
+ * \`@lunora/d1\`'s \`importGlobalRows\`. Mirrors \`runShardImport\`'s shard-local
538
+ * twin (\`createShardCtxDb\` + \`importShardRows\`) — same \`{ rows, startLine }\`
539
+ * shape, same trusted-import \`allowExplicitId\` semantics, forwarded as-is.
540
+ *
541
+ * Passes each row's own \`line\` through rather than dropping it: the caller
542
+ * (\`@lunora/runtime\`'s NDJSON import stream) already carries the row's true
543
+ * physical source line, and global rows are typically interspersed with
544
+ * shard-local ones it filtered out before calling here — a single
545
+ * \`startLine\` plus positional counting would mis-attribute every row after
546
+ * the first gap. \`importGlobalRows\` prefers \`row.line\` when present and
547
+ * falls back to the position-derived count otherwise.
548
+ */
549
+ const buildGlobalImporter =
550
+ (database: D1DatabaseLike, cdc: boolean) =>
551
+ (request: { rows: ReadonlyArray<{ doc: Record<string, unknown>; line: number; table: string }>; startLine?: number }) => {
552
+ const exec = buildExec(database);
553
+ // Same reason the PITR applier carries it: a bulk import that skips the
554
+ // changelog restores rows no downstream consumer is ever told about.
555
+ const writer = createD1CtxDb({ cdc, exec, schema: schema as unknown as D1CtxDbOptions["schema"] });
556
+
557
+ return importGlobalRows(writer, schema as unknown as D1CtxDbOptions["schema"], {
558
+ exec,
559
+ rows: request.rows.map((row) => ({ doc: row.doc, line: row.line, table: row.table })),
560
+ startLine: request.startLine,
561
+ });
562
+ };
563
+
564
+ /**
565
+ * \`exportGlobals\` for the admin export endpoint (and the scheduled R2 backup,
566
+ * which drains the same stream): the read twin of {@link buildGlobalImporter},
567
+ * over the same D1 handle. \`@lunora/d1\`'s \`exportGlobalRows\` keyset-paginates
568
+ * each table and provisions the schema's global tables first, so a table that
569
+ * was never written exports as empty instead of throwing \`no such table\`.
570
+ *
571
+ * \`tables\` is forwarded as-is: the runtime passes an empty array for "every
572
+ * table" (its \`tables === undefined\` case), which is exactly what
573
+ * \`selectGlobalTables\` reads an empty allowlist as.
574
+ */
575
+ const buildGlobalExporter =
576
+ (database: D1DatabaseLike) =>
577
+ (request: { tables: ReadonlyArray<string> }) =>
578
+ exportGlobalRows(buildExec(database), schema as unknown as D1CtxDbOptions["schema"], { tables: request.tables });
579
+
580
+ /**
581
+ * \`syncGlobals\` for the admin CDC sync + warehouse-connector endpoints: pages
582
+ * the global \`__cdc_log\` past \`sinceSeq\`, the global-plane twin of the shard's
583
+ * \`runShardCdcSync\`.
584
+ *
585
+ * Probes \`sqlite_master\` first, exactly as the shard twin does. The changelog
586
+ * table is only created when the global writer runs with CDC enabled, so on
587
+ * every other app a straight read would throw \`no such table: __cdc_log\` and
588
+ * turn "nothing has changed yet" into a 500. Absent log ⇒ an empty page that
589
+ * leaves the caller's cursor where it was.
590
+ */
591
+ const buildGlobalCdcSync =
592
+ (database: D1DatabaseLike) =>
593
+ async (request: { limit?: number; sinceSeq: number }): Promise<{ changes: ReadonlyArray<Record<string, unknown>>; cursor: number }> => {
594
+ const exec = buildExec(database);
595
+ const present = await exec.all(\`SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?\`, ["__cdc_log"]);
596
+
597
+ if (present.length === 0) {
598
+ return { changes: [], cursor: request.sinceSeq };
599
+ }
600
+
601
+ const page = await readD1CdcChanges(exec, { limit: request.limit, sinceSeq: request.sinceSeq });
602
+
603
+ // \`as unknown as\`, because \`CdcChange\` is an interface and interfaces carry
604
+ // no implicit index signature — the shapes are otherwise identical.
605
+ return { changes: page.changes as unknown as ReadonlyArray<Record<string, unknown>>, cursor: page.cursor };
606
+ };
607
+
608
+ /**
609
+ * \`applyGlobals\` for the admin point-in-time-recovery apply endpoint: replays a
610
+ * batch of global CDC changes through the same D1 writer \`.global()\` writes go
611
+ * through, and reports how many were replayed.
612
+ *
613
+ * \`applyCdcChanges\` is order-sensitive and idempotent per row (insert, falling
614
+ * back to replace on conflict), so the batch is handed over untouched — the
615
+ * caller already emits it in commit order. The changes arrive as plain parsed
616
+ * JSON off the wire, hence the cast to the replayer's own change shape.
617
+ *
618
+ * The writer carries the app's own \`cdc\` setting, so a replay APPENDS to the
619
+ * global changelog like any other write. Built without it the restored rows
620
+ * reach the tables and nothing else: a warehouse connector's cursor walks past a
621
+ * range that has no entries and its mirror silently diverges from the database,
622
+ * with nothing on either side able to notice — and every live \`.global()\` shape
623
+ * misses the restore until the next unconditional resync.
624
+ */
625
+ const buildGlobalCdcApplier =
626
+ (database: D1DatabaseLike, cdc: boolean) =>
627
+ async (request: { changes: ReadonlyArray<Record<string, unknown>> }): Promise<number> => {
628
+ const writer = createD1CtxDb({ cdc, exec: buildExec(database), schema: schema as unknown as D1CtxDbOptions["schema"] });
629
+
630
+ await applyCdcChanges(writer, request.changes as unknown as Parameters<typeof applyCdcChanges>[1]);
631
+
632
+ return request.changes.length;
633
+ };
634
+ `:"",U=e=>[...e.hasAuth?["AuthDeclaration"]:[],"ComposedApp",...e.hasGlobal?["GlobalDeclaration"]:[],"LunoraConfig",...e.hasScheduler?["SchedulerDeclaration"]:[],"Selector",...e.hasStorage?["StorageDeclaration"]:[]].toSorted((t,a)=>t.localeCompare(a)).join(", "),Q=e=>{const t={...e,hasVectors:(e.hasVectors??!0)&&(e.vectorIndexCount??0)>0},{hasAuth:a}=t,r=I(t),n=P(t),i=a?` let auth: LunoraAuth | null = null;
635
+ let authInit: Promise<void> | null = null;
636
+ `:"",o=a?`
637
+ const initAuth = async (env: Env): Promise<void> => {
638
+ if (!this.authDeclaration) {
639
+ return;
640
+ }
641
+
642
+ const d1 = this.authDeclaration.d1;
643
+
644
+ // DO-backed mode builds no instance here: better-auth runs inside the
645
+ // object, which materialises its own schema (the Kysely migrator below is
646
+ // dialect-bound and cannot target DO storage).
647
+ if (!d1) {
648
+ return;
649
+ }
650
+
651
+ // Apply the better-auth schema lazily on first request (raw-D1 Kysely
652
+ // migrator). For production run the migrate command ahead of deploy.
653
+ // The migration instance takes the RAW binding: better-auth migrates
654
+ // only through Kysely and rejects the adapter the request instance uses.
655
+ //
656
+ // CONSTRUCTED BEFORE THE MIGRATION, ASSIGNED AFTER IT. Both halves matter:
657
+ // building it first gives \`ensureMigrated\`'s schema-check invalidation a
658
+ // registered check to invalidate, and assigning it only afterwards keeps a
659
+ // concurrent request from serving \`/api/auth/*\` against tables the
660
+ // migrator has not created yet. See \`emit-app.ts\` in @lunora/codegen for
661
+ // the full reasoning.
662
+ //
663
+ // On a first boot against an unmigrated database this means better-auth's
664
+ // eager schema check runs BEFORE the migration, so one
665
+ // "the auth tables do not match…" line on a cold start is expected.
666
+ const requestAuth = createAuth({ ...this.authDeclaration.options(env), database: lunoraD1Adapter(d1(env) as never) });
667
+
668
+ await ensureMigrated(createAuth({ ...this.authDeclaration.options(env), database: d1(env) as never }));
669
+
670
+ auth = requestAuth;
671
+ };
672
+
673
+ // Single-flighted on the PROMISE, not on \`auth\`. Every \`fetch\` awaits this
674
+ // and the body above is async, so a per-isolate cold start runs it once
675
+ // rather than once per concurrent request — better-auth's migrator emits a
676
+ // bare \`CREATE TABLE\` (no IF NOT EXISTS), so a second concurrent run on a
677
+ // fresh database fails with \`table user already exists\` and, because this is
678
+ // awaited ahead of the router, 500s every route. Evicted on failure so a
679
+ // transient error retries instead of being replayed forever.
680
+ const ensureAuth = (env: Env): Promise<void> =>
681
+ (authInit ??= initAuth(env).catch((error: unknown) => {
682
+ authInit = null;
683
+ throw error;
684
+ }));
685
+ `:"",l=a?`
686
+ await ensureAuth(env);`:"",s=a?"() => auth":"() => null",c=a?"getAuth: () => LunoraAuth | null":"_getAuth: () => null",d=t.hasFramework?` const buildWorker = (env: Env): LunoraWorker =>
687
+ host ? withFrameworkWorker(host, (hostEnv) => this.buildWorkerOptions(hostEnv as Env, ${s})) : createWorker(this.buildWorkerOptions(env, ${s}));`:` const buildWorker = (env: Env): LunoraWorker => createWorker(this.buildWorkerOptions(env, ${s}));`,h=t.hasFramework?"host?: FrameworkHostHandler":"",u=t.emailAgents??[],v=u.length>0?` composed.email = dispatchAgentEmail([
688
+ ${u.map(p=>` { agent: lunoraAgentDefinitions.${p.exportName}, binding: ${JSON.stringify(p.bindingName)} },`).join(`
689
+ `)}
690
+ ]);
691
+
692
+ `:"",f=` /** Materialise the standalone Cloudflare worker + \`ShardDO\` class. */
693
+ public build(): ComposedApp {
694
+ return this.assemble();
695
+ }${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`${y}${N(t).join(`
696
+ `)}
697
+
698
+ /** Read a value off the per-request \`env\`. Returns \`undefined\` to leave the capability unconfigured (its \`ctx.*\`/admin surface stays a clear-error stub). */
699
+ type Selector<Env, T> = (env: Env) => T | undefined;
700
+
701
+ /** The generated \`createShardDO\` config — \`.observability()\`, \`.maxRelationKeys()\` and the long-tail \`.ai()\` / \`.kv()\` / … methods pass straight through to it. */
702
+ type ShardConfig = NonNullable<Parameters<typeof createShardDO>[0]>;
703
+ ${t.jurisdiction?`
704
+ // Module scope, so every isolate loading this script (the worker and each Durable
705
+ // Object class it exports) knows the schema's jurisdiction before a request runs.
706
+ // \`@lunora/mail\` reads it to pin its shard RPC like every other DO path.
707
+ declareAppJurisdiction(${JSON.stringify(t.jurisdiction)});
708
+ `:""}
709
+ ${r.join(`
710
+
711
+ `)}${r.length>0?`
712
+
713
+ `:""}/** The composed app: a Cloudflare module worker (\`fetch\` / \`scheduled\` / optional \`email\`) plus the \`ShardDO\` class binding. */
714
+ interface ComposedApp extends LunoraWorker {
715
+ /** Cloudflare Email Routing entry — present only when \`.onEmail(...)\` was configured. */
716
+ email?: (message: unknown, env: unknown, context: ExecutionContextLike) => Promise<void>;
717
+ /** The generated shard Durable Object class — re-export it as a named export so wrangler can bind it. */
718
+ ShardDO: ReturnType<typeof createShardDO>;
719
+ }
720
+
721
+ /**
722
+ * Fluent worker-composition builder. Records each capability declaration, then
723
+ * \`.build()\` fans them into the DO-side \`createShardDO\` factory and the
724
+ * worker-side \`createWorker\` options — constructing the worker lazily on the
725
+ * first request so per-isolate singletons are built once.
726
+ */
727
+ class AppBuilder<Env extends object> {
728
+ ${L(t).join(`
729
+ `)}
730
+
731
+ private emailHandler?: (env: Env) => (message: unknown, env: unknown, context: ExecutionContextLike) => Promise<void>;
732
+
733
+ ${j(t).join(`
734
+
735
+ `)}
736
+
737
+ ${f}
738
+
739
+ /** Build the shard DO + compose the worker (standalone or framework-hosted), wrapping the lazy per-isolate singletons + auth init. */
740
+ private assemble(${h}): ComposedApp {
741
+ const ShardDO = createShardDO({${G(t)}});
742
+
743
+ // Per-isolate singletons: the worker (and auth instance) are expensive to
744
+ // build, so the first request constructs them and every later request on
745
+ // the same isolate reuses them.
746
+ let worker: LunoraWorker | null = null;
747
+ ${i}${o}
748
+ ${d}
749
+
750
+ const composed: ComposedApp = {
751
+ ShardDO,
752
+ fetch: async (request: Request, rawEnv: unknown, context: ExecutionContextLike): Promise<Response> => {
753
+ const env = rawEnv as Env;${l}
754
+ worker ??= buildWorker(env);
755
+
756
+ return worker.fetch(request, rawEnv, context);
757
+ },
758
+ scheduled: async (controller: ScheduledControllerLike, rawEnv: unknown, context: ExecutionContextLike): Promise<void> => {
759
+ worker ??= buildWorker(rawEnv as Env);
760
+
761
+ return worker.scheduled(controller, rawEnv, context);
762
+ },
763
+ serverQuery: (request, rawEnv, reference, args, options) => {
764
+ worker ??= buildWorker(rawEnv as Env);
765
+
766
+ return worker.serverQuery(request, rawEnv, reference, args, options);
767
+ },${t.hasQueue||t.hasFramework?`
768
+ queue: async (batch: unknown, rawEnv: unknown, context: ExecutionContextLike): Promise<void> => {
769
+ worker ??= buildWorker(rawEnv as Env);
770
+
771
+ return worker.queue?.(batch, rawEnv, context);
772
+ },`:""}
773
+ };
774
+
775
+ ${v} if (this.emailHandler) {
776
+ const handler = this.emailHandler;
777
+
778
+ composed.email = (message, rawEnv, context) => handler(rawEnv as Env)(message, rawEnv, context);
779
+ }
780
+ ${t.hasFramework?`
781
+ // A framework host may export its own \`email\` (Nitro's \`cloudflare-module\`
782
+ // does). Nothing in Lunora serves one, so when the app registered no handler
783
+ // of its own the host's is the only one there is — forward to it rather than
784
+ // dropping the entry.
785
+ if (!composed.email && host && typeof host === "object" && typeof host.email === "function") {
786
+ composed.email = (message, rawEnv, context) => {
787
+ worker ??= buildWorker(rawEnv as Env);
788
+
789
+ return worker.email?.(message, rawEnv, context) ?? Promise.resolve();
790
+ };
791
+ }
792
+ `:""}
793
+ return composed;
794
+ }
795
+ ${_(t)}${$(t.hasStorage)}
796
+ /** Fan the recorded declarations into the worker-side \`createWorker\` options. */
797
+ private buildWorkerOptions(env: Env, ${c}): WorkerOptions {
798
+ const options: WorkerOptions = {
799
+ ${W(t).join(`
800
+ `)}
801
+ };
802
+
803
+ if (this.adminToken) {
804
+ options.adminToken = this.adminToken(env);
805
+ }
806
+
807
+ ${n.join(`
808
+
809
+ `)}${n.length>0?`
810
+
811
+ `:""} for (const fn of this.extendFns) {
812
+ Object.assign(options, fn(env, { ...options }));
813
+ }
814
+
815
+ return options;
816
+ }
817
+ }
818
+ ${H(t.hasGlobal)}
819
+ /**
820
+ * Shape of the project's root \`lunora.config.*\`.
821
+ *
822
+ * Declared HERE, not in a package, so the \`app\` hook is typed against THIS
823
+ * project's builder with no annotation to keep in step — and so the config file
824
+ * needs only a type-only import, which is erased. That matters: the hook is
825
+ * bundled into the worker, and a runtime import in that file ships with it.
826
+ */
827
+ interface LunoraConfig<Env extends object = object> {
828
+ /** Codegen's static advisor. \`minSeverity\` is the lowest level it reports and writes into \`_generated/shard.ts\`; an \`"error"\` is never dropped, so the gate that fails codegen stays on. A literal, for the same reason as \`target\`. */
829
+ advisor?: { minSeverity?: "error" | "info" | "warn" };
830
+ /** Receives this project's \`defineApp()\` builder and returns it — where a Vite-first app makes the builder calls its generated entry cannot derive. */
831
+ app?: (app: AppBuilder<Env>) => AppBuilder<Env>;
832
+ /** Opt into remote-binding dev without \`--remote\` or \`LUNORA_REMOTE\` on every run. A literal, for the same reason as \`target\`. */
833
+ remote?: boolean;
834
+ /** Deploy target id — \`lunora deploy\`/\`verify\` read it when no \`--target\` is passed. Must be a literal: \`runCodegen\` resolves it synchronously by PARSING this file, so a computed value is not seen — \`lunora verify\` reports \`platform_unreadable_target\` rather than defaulting in silence. */
835
+ target?: string;
836
+ }
837
+
838
+ /**
839
+ * Start composing the app. Chain the capability methods, then \`.build()\`.
840
+ *
841
+ * \`Env\` is constrained to \`object\`, not \`Record<string, unknown>\`: an \`interface Env\`
842
+ * — which is what wrangler's generated \`worker-configuration.d.ts\` gives you, and
843
+ * what any app with its own bindings declares — is NOT assignable to an index
844
+ * signature, so the stricter bound forced every real app to write
845
+ * \`type AppEnv = Env & Record<string, unknown>\`. The builder only ever reads \`env\`
846
+ * through the selectors you pass it, so the looser bound costs nothing.
847
+ */
848
+ const defineApp = <Env extends object>(): AppBuilder<Env> => new AppBuilder<Env>();
849
+
850
+ export { AppBuilder, defineApp };
851
+ export type { ${U(t)} };
852
+ `};export{Q as emitApp};