@lunora/codegen 1.0.0-alpha.23 → 1.0.0-alpha.230
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE.md +6 -0
- package/README.md +1 -1
- package/dist/index.d.mts +3344 -1166
- package/dist/index.d.ts +3344 -1166
- package/dist/index.mjs +1 -34
- package/dist/packem_shared/AGENTS_FILENAME-DoPI92Wu.mjs +1 -0
- package/dist/packem_shared/CONTAINERS_FILENAME-B6TFs82W.mjs +1 -0
- package/dist/packem_shared/CodegenDiagnosticError-BUXlG3P-.mjs +1 -0
- package/dist/packem_shared/DEFAULT_TARGET-kmm2i4Fw.mjs +1 -0
- package/dist/packem_shared/FLAGS_FILENAME-BedPDCsR.mjs +1 -0
- package/dist/packem_shared/GENERATED_HEADER-Cfw75xC4.mjs +1 -0
- package/dist/packem_shared/LUNORA_ERROR_CODES-C2s0xWQD.mjs +1 -0
- package/dist/packem_shared/MUTATORS_FILENAME-B6cKrN_m.mjs +1 -0
- package/dist/packem_shared/NOTIFY_FILENAME-Cri3NT5U.mjs +1 -0
- package/dist/packem_shared/OPENRPC_VERSION-DDd0VJyT.mjs +3 -0
- package/dist/packem_shared/PROJECT_CONFIG_FILENAMES-DzOu-lSc.mjs +1 -0
- package/dist/packem_shared/QUEUES_FILENAME-CxkPcMH1.mjs +1 -0
- package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-Cssrg7G6.mjs +9 -0
- package/dist/packem_shared/SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs +2 -0
- package/dist/packem_shared/SDK_LANGUAGES-Df_CnJx5.mjs +372 -0
- package/dist/packem_shared/SHAPES_FILENAME-zJgzynXR.mjs +1 -0
- package/dist/packem_shared/SchemaSnapshotParseError-lUWe6lPo.mjs +18 -0
- package/dist/packem_shared/WORKFLOWS_FILENAME-B_ZJxRSx.mjs +1 -0
- package/dist/packem_shared/buildOpenApiDocument-D6SBl-tk.mjs +3 -0
- package/dist/packem_shared/chain-H2N_uKgj.mjs +1 -0
- package/dist/packem_shared/classify-procedure-call-BztLe76A.mjs +1 -0
- package/dist/packem_shared/context-property-calls-CjDzLU8p.mjs +1 -0
- package/dist/packem_shared/declared-output-Iaar469J.mjs +1 -0
- package/dist/packem_shared/describeErrorLevelFindings-D23VSkFP.mjs +1 -0
- package/dist/packem_shared/discoverAuthApiCalls-FxrdBeVt.mjs +1 -0
- package/dist/packem_shared/discoverCrons-MfKw7IFf.mjs +1 -0
- package/dist/packem_shared/discoverFunctions-BsmX-sEq.mjs +1 -0
- package/dist/packem_shared/discoverHttpRoutes-BcXI9CNt.mjs +1 -0
- package/dist/packem_shared/discoverHyperdriveCalls-D9qXqTq3.mjs +1 -0
- package/dist/packem_shared/discoverInserts-CFJ3IVeI.mjs +1 -0
- package/dist/packem_shared/discoverMaskProcedures-CV_Cc2_g.mjs +1 -0
- package/dist/packem_shared/discoverMigrations-DbrHwcGE.mjs +1 -0
- package/dist/packem_shared/discoverNondeterministicCalls-CSQ_GDcA.mjs +1 -0
- package/dist/packem_shared/discoverQueries-C7y8i_Ga.mjs +1 -0
- package/dist/packem_shared/discoverR2sqlCalls-fu7fC0i_.mjs +1 -0
- package/dist/packem_shared/discoverRlsMetadata-CPmAGL0W.mjs +1 -0
- package/dist/packem_shared/discoverRlsProcedures-BO4qC77y.mjs +1 -0
- package/dist/packem_shared/discoverSandboxUsage-CgmfgDTS.mjs +1 -0
- package/dist/packem_shared/discoverSchema-D8DBDHEg.mjs +1 -0
- package/dist/packem_shared/discoverStorageRulesMetadata-D8VYflWt.mjs +1 -0
- package/dist/packem_shared/emit-D_prE7y6.mjs +2691 -0
- package/dist/packem_shared/emitApp-rCWsXXGd.mjs +853 -0
- package/dist/packem_shared/exported-procedure-chains-CmCDiPBV.mjs +1 -0
- package/dist/packem_shared/formatAdvisories-DwmUKYuc.mjs +2 -0
- package/dist/packem_shared/index-BoaHhVtM.mjs +1 -0
- package/dist/packem_shared/isD1GlobalTable-udvHAAzD.mjs +1 -0
- package/dist/packem_shared/isTypedSchema-CKzc3ioR.mjs +4 -0
- package/dist/packem_shared/listLunoraSourceFiles-DP-5e-RE.mjs +1 -0
- package/dist/packem_shared/loadProjectConfig-CKsFNgn3.mjs +1 -0
- package/dist/packem_shared/module-specifiers-WF8iAydP.mjs +1 -0
- package/dist/packem_shared/parse-validator-C94Yiabo.mjs +1 -0
- package/dist/packem_shared/paths-C-9fwEgQ.mjs +1 -0
- package/dist/packem_shared/queries-B-f4jO-x.mjs +1 -0
- package/dist/packem_shared/readPackageDependencies-C6h6FZuP.mjs +1 -0
- package/dist/packem_shared/redact-Cy14LEnc.mjs +1 -0
- package/dist/packem_shared/schemaFromIr-BWFnvCVg.mjs +1 -0
- package/dist/packem_shared/unwrap-handler-return-CoV_GK33.mjs +1 -0
- package/package.json +16 -7
- package/dist/packem_shared/CONTAINERS_FILENAME-DlP6YM_Q.mjs +0 -224
- package/dist/packem_shared/CodegenDiagnosticError-DeblMkzO.mjs +0 -23
- package/dist/packem_shared/FLAGS_FILENAME-B1vE0LIo.mjs +0 -139
- package/dist/packem_shared/GENERATED_HEADER-DUkXYD5R.mjs +0 -3260
- package/dist/packem_shared/LUNORA_ERROR_CODES-CySpQPD3.mjs +0 -61
- package/dist/packem_shared/LUNORA_SOLUTION_RULES-BTejmZp-.mjs +0 -131
- package/dist/packem_shared/MUTATORS_FILENAME-BhqdPtKp.mjs +0 -81
- package/dist/packem_shared/OPENRPC_VERSION-CjBUaolx.mjs +0 -60
- package/dist/packem_shared/QUEUES_FILENAME-B5_eWCRe.mjs +0 -119
- package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-BUcGCXi3.mjs +0 -1130
- package/dist/packem_shared/SCHEMA_SNAPSHOT_VERSION-wWGP2_5E.mjs +0 -245
- package/dist/packem_shared/SHAPES_FILENAME-ChV7MqgE.mjs +0 -94
- package/dist/packem_shared/WORKFLOWS_FILENAME-CCisG0Vy.mjs +0 -124
- package/dist/packem_shared/buildOpenApiDocument-WxYTLh11.mjs +0 -183
- package/dist/packem_shared/discover-ast-CT6BgBr4.mjs +0 -13
- package/dist/packem_shared/discoverAuthApiCalls-CoirYbg6.mjs +0 -62
- package/dist/packem_shared/discoverCrons-Cev7RRAf.mjs +0 -257
- package/dist/packem_shared/discoverFunctions-BWMczzBx.mjs +0 -465
- package/dist/packem_shared/discoverHttpRoutes-CfP6cMzt.mjs +0 -131
- package/dist/packem_shared/discoverInserts-C7zxXkUf.mjs +0 -61
- package/dist/packem_shared/discoverMaskProcedures-Cm81kwrb.mjs +0 -217
- package/dist/packem_shared/discoverMigrations-Bi5nJ0mJ.mjs +0 -97
- package/dist/packem_shared/discoverNondeterministicCalls-C4M8AXmQ.mjs +0 -122
- package/dist/packem_shared/discoverQueries-B0wGT-xe.mjs +0 -62
- package/dist/packem_shared/discoverR2sqlCalls-BVNMd428.mjs +0 -80
- package/dist/packem_shared/discoverRlsMetadata-BS9GOGC5.mjs +0 -280
- package/dist/packem_shared/discoverSchema-KYq55qu3.mjs +0 -864
- package/dist/packem_shared/discoverStorageRulesMetadata-Da8BKXcI.mjs +0 -97
- package/dist/packem_shared/emitApp-DD0i1ks0.mjs +0 -666
- package/dist/packem_shared/formatAdvisories-DdjK7sgh.mjs +0 -81
- package/dist/packem_shared/parse-validator-Cabb60UV.mjs +0 -133
- package/dist/packem_shared/paths-BRd6JHuF.mjs +0 -11
- package/dist/packem_shared/schemaFromIr-DTYsLBaA.mjs +0 -57
|
@@ -0,0 +1,853 @@
|
|
|
1
|
+
import{A as w,G as y}from"./emit-D_prE7y6.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}";`]},I=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";']:[]]},N=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 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}']:[]],q=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>;"]:[]],L=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
|
+
}`]:[],...L(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. The studio admin ops pass none, and sign only when one is.
|
|
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
|
+
// Held separately from the map so \`pick\`'s fallback is a plain binding:
|
|
363
|
+
// under \`noUncheckedIndexedAccess\` a \`Record<string, Storage>\` lookup —
|
|
364
|
+
// including \`buckets.default\` — widens to \`Storage | undefined\`, which
|
|
365
|
+
// would not satisfy \`pick\`'s declared \`Storage\` return.
|
|
366
|
+
const fallbackStorage = this.makeStorage(env, declaration, defaultBucket, "default");
|
|
367
|
+
const buckets: Record<string, Storage> = { default: fallbackStorage };
|
|
368
|
+
|
|
369
|
+
for (const [name, selector] of Object.entries(declaration.buckets ?? {})) {
|
|
370
|
+
const bucket = selector(env);
|
|
371
|
+
|
|
372
|
+
if (bucket) {
|
|
373
|
+
buckets[name] = this.makeStorage(env, declaration, bucket, name);
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
// \`Object.hasOwn\`, not a bare lookup: \`buckets\` is a plain object, so a
|
|
378
|
+
// prototype key (\`?bucket=constructor\`, \`__proto__\`, \`toString\`) resolves
|
|
379
|
+
// to an inherited Object.prototype member, \`??\` never engages, and the
|
|
380
|
+
// caller gets a method-less value instead of the default bucket.
|
|
381
|
+
const pick = (name?: string): Storage => {
|
|
382
|
+
const wanted = name !== undefined && name !== "" ? name : "default";
|
|
383
|
+
|
|
384
|
+
return (Object.hasOwn(buckets, wanted) ? buckets[wanted] : undefined) ?? fallbackStorage;
|
|
385
|
+
};
|
|
386
|
+
const hasSigning = Boolean(declaration.publicBaseUrl?.(env) && declaration.signingSecret?.(env));
|
|
387
|
+
|
|
388
|
+
return {
|
|
389
|
+
storageBuckets: Object.keys(buckets),
|
|
390
|
+
storageDelete: (key: string, opts?: { bucket?: string }) => pick(opts?.bucket).delete(key),
|
|
391
|
+
storageDownload: (key: string, opts?: { bucket?: string }) => pick(opts?.bucket).download(key),
|
|
392
|
+
storageList: (prefix?: string, opts?: { bucket?: string; cursor?: string; limit?: number }) => pick(opts?.bucket).list(prefix, opts),
|
|
393
|
+
storageSignedUrl: hasSigning
|
|
394
|
+
? (key: string, opts?: { bucket?: string; contentType?: string; expiresInSeconds?: number; method?: "GET" | "PUT" }) =>
|
|
395
|
+
pick(opts?.bucket).getSignedUrl(key, { contentType: opts?.contentType, expiresInSeconds: opts?.expiresInSeconds, method: opts?.method })
|
|
396
|
+
: undefined,
|
|
397
|
+
storageUpload: (key: string, body: ArrayBuffer, opts?: { bucket?: string; contentType?: string; sha256?: string }) => pick(opts?.bucket).upload(key, body, opts),
|
|
398
|
+
};
|
|
399
|
+
}
|
|
400
|
+
`:"",H=e=>e?`
|
|
401
|
+
/**
|
|
402
|
+
* 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\`).
|
|
403
|
+
*
|
|
404
|
+
* Opens a D1 Sessions API session pinned to \`bookmark\` (the caller's own
|
|
405
|
+
* last-known write, when supplied) so reads observe it — read-your-writes
|
|
406
|
+
* across replicas. \`onBookmark\`, when supplied, is invoked with the bookmark
|
|
407
|
+
* produced by each write so the caller (the generated DO) can record it on the
|
|
408
|
+
* dispatch's bookmark sink and echo \`x-d1-bookmark\` on the response.
|
|
409
|
+
*
|
|
410
|
+
* Wrapped in \`retryingExec\` so D1's documented baseline of transient failures
|
|
411
|
+
* (storage-object resets, isolate memory evictions, dropped connections) does
|
|
412
|
+
* not surface on every \`.global()\` read. Only statements that are provably
|
|
413
|
+
* read-only retry; writes — including the \`UPDATE … RETURNING\` the store's
|
|
414
|
+
* optimistic-concurrency check issues through \`all\` — pass straight through,
|
|
415
|
+
* because a transient error never says whether the write applied.
|
|
416
|
+
*
|
|
417
|
+
* Every read and write also records D1's own \`meta\` accounting (\`rows_read\` /
|
|
418
|
+
* \`rows_written\` / \`duration\`) against a low-cardinality \`verb:table\` tag.
|
|
419
|
+
* Rows READ is rows SCANNED, not returned, so this is the number that explains
|
|
420
|
+
* a D1 bill and the one a missing index inflates without anything being
|
|
421
|
+
* deployed; the dashboard's own metric is per-database and can't name the query.
|
|
422
|
+
* The emit is best-effort — instrumentation must never fail a served query.
|
|
423
|
+
*/
|
|
424
|
+
const buildExec = (database: D1DatabaseLike, bookmark?: string, onBookmark?: (bookmark: string | undefined) => void): D1Exec => {
|
|
425
|
+
// Real D1 always exposes \`withSession\`; guarded the same way as \`batch\`
|
|
426
|
+
// below so a hand-rolled test double that omits it keeps working via
|
|
427
|
+
// \`prepare()\` straight on the raw binding — today's behaviour. With no
|
|
428
|
+
// inbound bookmark, \`"first-unconstrained"\` is the documented no-op
|
|
429
|
+
// equivalent (lowest latency, may read any replica) — see \`D1Client.withSession\`.
|
|
430
|
+
const session = typeof database.withSession === "function" ? database.withSession(bookmark ?? "first-unconstrained") : undefined;
|
|
431
|
+
const target = session ?? database;
|
|
432
|
+
const batchFn = target.batch;
|
|
433
|
+
const meter = (sql: string, meta: Record<string, unknown> | undefined): void => {
|
|
434
|
+
try {
|
|
435
|
+
emitD1QueryCost(sql, meta);
|
|
436
|
+
} catch {
|
|
437
|
+
// Best-effort: never let cost accounting fail the query it measures.
|
|
438
|
+
}
|
|
439
|
+
};
|
|
440
|
+
|
|
441
|
+
return retryingExec({
|
|
442
|
+
all: async (sql, parameters) => {
|
|
443
|
+
const result = await target
|
|
444
|
+
.prepare(sql)
|
|
445
|
+
.bind(...parameters)
|
|
446
|
+
.all<Record<string, unknown>>();
|
|
447
|
+
|
|
448
|
+
// \`all\` carries writes, not just reads: D1 runs
|
|
449
|
+
// \`UPDATE/DELETE … RETURNING\` through it exactly like \`.run()\`, and
|
|
450
|
+
// that is precisely what \`@lunora/sql-store\` issues for its
|
|
451
|
+
// optimistic-concurrency compare-and-swap — so \`patch\`, \`replace\`
|
|
452
|
+
// and \`delete\` all land here and nowhere else. Without this the
|
|
453
|
+
// bookmark those writes produced was never reported, and the next
|
|
454
|
+
// read could pin a replica that has not seen them: read-your-writes
|
|
455
|
+
// lost on the exact path the bookmark exists for. Reporting it after
|
|
456
|
+
// a plain \`SELECT\` too is harmless and correct — the session's
|
|
457
|
+
// bookmark only ever moves forward, and the sink takes the last
|
|
458
|
+
// value.
|
|
459
|
+
onBookmark?.(session?.getBookmark() ?? undefined);
|
|
460
|
+
meter(sql, result.meta);
|
|
461
|
+
|
|
462
|
+
return result.results;
|
|
463
|
+
},
|
|
464
|
+
// D1's own \`batch\` runs the whole array as one atomic SQLite
|
|
465
|
+
// transaction. Guarded because \`batch\` is optional in the structural
|
|
466
|
+
// type (test doubles may omit it) — real D1 always has it; a double
|
|
467
|
+
// without it still works through the store's sequential fallback.
|
|
468
|
+
// Invoked via \`.call(target, ...)\` rather than \`target.batch(...)\`
|
|
469
|
+
// directly so TS can narrow the captured \`batchFn\` across the closure
|
|
470
|
+
// boundary (a property-access narrowing like
|
|
471
|
+
// \`hasBatch = typeof target.batch === "function"\` does not survive
|
|
472
|
+
// into a nested arrow function); \`.call\` still binds \`this\` to
|
|
473
|
+
// \`target\`, so the real workerd \`D1Database\`/session doesn't throw
|
|
474
|
+
// \`TypeError: Illegal invocation\` the way a detached
|
|
475
|
+
// \`const fn = target.batch; fn(...)\` capture would.
|
|
476
|
+
batch: batchFn
|
|
477
|
+
? async (statements) => {
|
|
478
|
+
const results = await batchFn.call(
|
|
479
|
+
target,
|
|
480
|
+
statements.map(({ params, sql }) => target.prepare(sql).bind(...params)),
|
|
481
|
+
);
|
|
482
|
+
|
|
483
|
+
// Meter each leg. D1 returns one result per statement, in
|
|
484
|
+
// order, each with its own \`meta\` — and a batch is where the
|
|
485
|
+
// expensive writes live (\`@lunora/sql-store\` runs its
|
|
486
|
+
// backfills through here), so discarding it left exactly the
|
|
487
|
+
// statements worth costing unaccounted. Guarded on the array
|
|
488
|
+
// because \`batch\` is optional in the structural type and a
|
|
489
|
+
// test double may resolve to anything.
|
|
490
|
+
if (Array.isArray(results)) {
|
|
491
|
+
for (const [index, statement] of statements.entries()) {
|
|
492
|
+
meter(statement.sql, (results[index] as { meta?: Record<string, unknown> } | undefined)?.meta);
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
onBookmark?.(session?.getBookmark() ?? undefined);
|
|
497
|
+
}
|
|
498
|
+
: undefined,
|
|
499
|
+
run: async (sql, parameters) => {
|
|
500
|
+
const result = await target
|
|
501
|
+
.prepare(sql)
|
|
502
|
+
.bind(...parameters)
|
|
503
|
+
.run();
|
|
504
|
+
|
|
505
|
+
meter(sql, result.meta);
|
|
506
|
+
onBookmark?.(session?.getBookmark() ?? undefined);
|
|
507
|
+
},
|
|
508
|
+
});
|
|
509
|
+
};
|
|
510
|
+
|
|
511
|
+
/** Introspect \`.global()\` (D1-backed) tables for the studio's global data browser. */
|
|
512
|
+
const buildGlobalIntrospector = (database: D1DatabaseLike): GlobalIntrospector => {
|
|
513
|
+
const exec = buildExec(database);
|
|
514
|
+
|
|
515
|
+
return {
|
|
516
|
+
facetColumn: (options) => facetGlobalColumn(exec, schema as never, options),
|
|
517
|
+
listTables: () => listGlobalTables(exec, schema as never),
|
|
518
|
+
readTablePage: (options) => readGlobalTablePage(exec, schema as never, options),
|
|
519
|
+
};
|
|
520
|
+
};
|
|
521
|
+
|
|
522
|
+
/**
|
|
523
|
+
* \`resolveTableSharding\` for the admin bulk-import endpoint: a lookup over each
|
|
524
|
+
* table's declared \`shardMode\` (\`defineTable(...).global()\` / \`.shardBy(field)\`
|
|
525
|
+
* already record exactly this shape on the table) — mechanical, nothing to
|
|
526
|
+
* configure per project. \`undefined\` for a table the schema doesn't declare, so
|
|
527
|
+
* the import endpoint's own unknown-table handling still applies.
|
|
528
|
+
*/
|
|
529
|
+
const buildTableShardingResolver = (): AdminTableResolver => (table) => {
|
|
530
|
+
const declared = (schema as unknown as D1CtxDbOptions["schema"]).tables[table];
|
|
531
|
+
|
|
532
|
+
return declared?.shardMode ? { mode: declared.shardMode } : undefined;
|
|
533
|
+
};
|
|
534
|
+
|
|
535
|
+
/**
|
|
536
|
+
* \`importGlobals\` for the admin bulk-import endpoint: routes \`.global()\` rows
|
|
537
|
+
* through the same D1 writer \`.global()\` reads/writes already use, via
|
|
538
|
+
* \`@lunora/d1\`'s \`importGlobalRows\`. Mirrors \`runShardImport\`'s shard-local
|
|
539
|
+
* twin (\`createShardCtxDb\` + \`importShardRows\`) — same \`{ rows, startLine }\`
|
|
540
|
+
* shape, same trusted-import \`allowExplicitId\` semantics, forwarded as-is.
|
|
541
|
+
*
|
|
542
|
+
* Passes each row's own \`line\` through rather than dropping it: the caller
|
|
543
|
+
* (\`@lunora/runtime\`'s NDJSON import stream) already carries the row's true
|
|
544
|
+
* physical source line, and global rows are typically interspersed with
|
|
545
|
+
* shard-local ones it filtered out before calling here — a single
|
|
546
|
+
* \`startLine\` plus positional counting would mis-attribute every row after
|
|
547
|
+
* the first gap. \`importGlobalRows\` prefers \`row.line\` when present and
|
|
548
|
+
* falls back to the position-derived count otherwise.
|
|
549
|
+
*/
|
|
550
|
+
const buildGlobalImporter =
|
|
551
|
+
(database: D1DatabaseLike, cdc: boolean) =>
|
|
552
|
+
(request: { rows: ReadonlyArray<{ doc: Record<string, unknown>; line: number; table: string }>; startLine?: number }) => {
|
|
553
|
+
const exec = buildExec(database);
|
|
554
|
+
// Same reason the PITR applier carries it: a bulk import that skips the
|
|
555
|
+
// changelog restores rows no downstream consumer is ever told about.
|
|
556
|
+
const writer = createD1CtxDb({ cdc, exec, schema: schema as unknown as D1CtxDbOptions["schema"] });
|
|
557
|
+
|
|
558
|
+
return importGlobalRows(writer, schema as unknown as D1CtxDbOptions["schema"], {
|
|
559
|
+
exec,
|
|
560
|
+
rows: request.rows.map((row) => ({ doc: row.doc, line: row.line, table: row.table })),
|
|
561
|
+
startLine: request.startLine,
|
|
562
|
+
});
|
|
563
|
+
};
|
|
564
|
+
|
|
565
|
+
/**
|
|
566
|
+
* \`exportGlobals\` for the admin export endpoint (and the scheduled R2 backup,
|
|
567
|
+
* which drains the same stream): the read twin of {@link buildGlobalImporter},
|
|
568
|
+
* over the same D1 handle. \`@lunora/d1\`'s \`exportGlobalRows\` keyset-paginates
|
|
569
|
+
* each table and provisions the schema's global tables first, so a table that
|
|
570
|
+
* was never written exports as empty instead of throwing \`no such table\`.
|
|
571
|
+
*
|
|
572
|
+
* \`tables\` is forwarded as-is: the runtime passes an empty array for "every
|
|
573
|
+
* table" (its \`tables === undefined\` case), which is exactly what
|
|
574
|
+
* \`selectGlobalTables\` reads an empty allowlist as.
|
|
575
|
+
*/
|
|
576
|
+
const buildGlobalExporter =
|
|
577
|
+
(database: D1DatabaseLike) =>
|
|
578
|
+
(request: { tables: ReadonlyArray<string> }) =>
|
|
579
|
+
exportGlobalRows(buildExec(database), schema as unknown as D1CtxDbOptions["schema"], { tables: request.tables });
|
|
580
|
+
|
|
581
|
+
/**
|
|
582
|
+
* \`syncGlobals\` for the admin CDC sync + warehouse-connector endpoints: pages
|
|
583
|
+
* the global \`__cdc_log\` past \`sinceSeq\`, the global-plane twin of the shard's
|
|
584
|
+
* \`runShardCdcSync\`.
|
|
585
|
+
*
|
|
586
|
+
* Probes \`sqlite_master\` first, exactly as the shard twin does. The changelog
|
|
587
|
+
* table is only created when the global writer runs with CDC enabled, so on
|
|
588
|
+
* every other app a straight read would throw \`no such table: __cdc_log\` and
|
|
589
|
+
* turn "nothing has changed yet" into a 500. Absent log ⇒ an empty page that
|
|
590
|
+
* leaves the caller's cursor where it was.
|
|
591
|
+
*/
|
|
592
|
+
const buildGlobalCdcSync =
|
|
593
|
+
(database: D1DatabaseLike) =>
|
|
594
|
+
async (request: { limit?: number; sinceSeq: number }): Promise<{ changes: ReadonlyArray<Record<string, unknown>>; cursor: number }> => {
|
|
595
|
+
const exec = buildExec(database);
|
|
596
|
+
const present = await exec.all(\`SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?\`, ["__cdc_log"]);
|
|
597
|
+
|
|
598
|
+
if (present.length === 0) {
|
|
599
|
+
return { changes: [], cursor: request.sinceSeq };
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
const page = await readD1CdcChanges(exec, { limit: request.limit, sinceSeq: request.sinceSeq });
|
|
603
|
+
|
|
604
|
+
// \`as unknown as\`, because \`CdcChange\` is an interface and interfaces carry
|
|
605
|
+
// no implicit index signature — the shapes are otherwise identical.
|
|
606
|
+
return { changes: page.changes as unknown as ReadonlyArray<Record<string, unknown>>, cursor: page.cursor };
|
|
607
|
+
};
|
|
608
|
+
|
|
609
|
+
/**
|
|
610
|
+
* \`applyGlobals\` for the admin point-in-time-recovery apply endpoint: replays a
|
|
611
|
+
* batch of global CDC changes through the same D1 writer \`.global()\` writes go
|
|
612
|
+
* through, and reports how many were replayed.
|
|
613
|
+
*
|
|
614
|
+
* \`applyCdcChanges\` is order-sensitive and idempotent per row (insert, falling
|
|
615
|
+
* back to replace on conflict), so the batch is handed over untouched — the
|
|
616
|
+
* caller already emits it in commit order. The changes arrive as plain parsed
|
|
617
|
+
* JSON off the wire, hence the cast to the replayer's own change shape.
|
|
618
|
+
*
|
|
619
|
+
* The writer carries the app's own \`cdc\` setting, so a replay APPENDS to the
|
|
620
|
+
* global changelog like any other write. Built without it the restored rows
|
|
621
|
+
* reach the tables and nothing else: a warehouse connector's cursor walks past a
|
|
622
|
+
* range that has no entries and its mirror silently diverges from the database,
|
|
623
|
+
* with nothing on either side able to notice — and every live \`.global()\` shape
|
|
624
|
+
* misses the restore until the next unconditional resync.
|
|
625
|
+
*/
|
|
626
|
+
const buildGlobalCdcApplier =
|
|
627
|
+
(database: D1DatabaseLike, cdc: boolean) =>
|
|
628
|
+
async (request: { changes: ReadonlyArray<Record<string, unknown>> }): Promise<number> => {
|
|
629
|
+
const writer = createD1CtxDb({ cdc, exec: buildExec(database), schema: schema as unknown as D1CtxDbOptions["schema"] });
|
|
630
|
+
|
|
631
|
+
await applyCdcChanges(writer, request.changes as unknown as Parameters<typeof applyCdcChanges>[1]);
|
|
632
|
+
|
|
633
|
+
return request.changes.length;
|
|
634
|
+
};
|
|
635
|
+
`:"",U=e=>[...e.hasAuth?["AuthDeclaration"]:[],"ComposedApp",...e.hasGlobal?["GlobalDeclaration"]:[],"LunoraConfig",...e.hasScheduler?["SchedulerDeclaration"]:[],"Selector",...e.hasStorage?["StorageDeclaration"]:[]].toSorted((t,a)=>t.localeCompare(a)).join(", "),M=e=>{const t={...e,hasVectors:(e.hasVectors??!0)&&(e.vectorIndexCount??0)>0},{hasAuth:a}=t,r=N(t),n=P(t),i=a?` let auth: LunoraAuth | null = null;
|
|
636
|
+
let authInit: Promise<void> | null = null;
|
|
637
|
+
`:"",o=a?`
|
|
638
|
+
const initAuth = async (env: Env): Promise<void> => {
|
|
639
|
+
if (!this.authDeclaration) {
|
|
640
|
+
return;
|
|
641
|
+
}
|
|
642
|
+
|
|
643
|
+
const d1 = this.authDeclaration.d1;
|
|
644
|
+
|
|
645
|
+
// DO-backed mode builds no instance here: better-auth runs inside the
|
|
646
|
+
// object, which materialises its own schema (the Kysely migrator below is
|
|
647
|
+
// dialect-bound and cannot target DO storage).
|
|
648
|
+
if (!d1) {
|
|
649
|
+
return;
|
|
650
|
+
}
|
|
651
|
+
|
|
652
|
+
// Apply the better-auth schema lazily on first request (raw-D1 Kysely
|
|
653
|
+
// migrator). For production run the migrate command ahead of deploy.
|
|
654
|
+
// The migration instance takes the RAW binding: better-auth migrates
|
|
655
|
+
// only through Kysely and rejects the adapter the request instance uses.
|
|
656
|
+
//
|
|
657
|
+
// CONSTRUCTED BEFORE THE MIGRATION, ASSIGNED AFTER IT. Both halves matter:
|
|
658
|
+
// building it first gives \`ensureMigrated\`'s schema-check invalidation a
|
|
659
|
+
// registered check to invalidate, and assigning it only afterwards keeps a
|
|
660
|
+
// concurrent request from serving \`/api/auth/*\` against tables the
|
|
661
|
+
// migrator has not created yet. See \`emit-app.ts\` in @lunora/codegen for
|
|
662
|
+
// the full reasoning.
|
|
663
|
+
//
|
|
664
|
+
// On a first boot against an unmigrated database this means better-auth's
|
|
665
|
+
// eager schema check runs BEFORE the migration, so one
|
|
666
|
+
// "the auth tables do not match…" line on a cold start is expected.
|
|
667
|
+
const requestAuth = createAuth({ ...this.authDeclaration.options(env), database: lunoraD1Adapter(d1(env) as never) });
|
|
668
|
+
|
|
669
|
+
await ensureMigrated(createAuth({ ...this.authDeclaration.options(env), database: d1(env) as never }));
|
|
670
|
+
|
|
671
|
+
auth = requestAuth;
|
|
672
|
+
};
|
|
673
|
+
|
|
674
|
+
// Single-flighted on the PROMISE, not on \`auth\`. Every \`fetch\` awaits this
|
|
675
|
+
// and the body above is async, so a per-isolate cold start runs it once
|
|
676
|
+
// rather than once per concurrent request — better-auth's migrator emits a
|
|
677
|
+
// bare \`CREATE TABLE\` (no IF NOT EXISTS), so a second concurrent run on a
|
|
678
|
+
// fresh database fails with \`table user already exists\` and, because this is
|
|
679
|
+
// awaited ahead of the router, 500s every route. Evicted on failure so a
|
|
680
|
+
// transient error retries instead of being replayed forever.
|
|
681
|
+
const ensureAuth = (env: Env): Promise<void> =>
|
|
682
|
+
(authInit ??= initAuth(env).catch((error: unknown) => {
|
|
683
|
+
authInit = null;
|
|
684
|
+
throw error;
|
|
685
|
+
}));
|
|
686
|
+
`:"",l=a?`
|
|
687
|
+
await ensureAuth(env);`:"",s=a?"() => auth":"() => null",c=a?"getAuth: () => LunoraAuth | null":"_getAuth: () => null",d=t.hasFramework?` const buildWorker = (env: Env): LunoraWorker =>
|
|
688
|
+
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([
|
|
689
|
+
${u.map(p=>` { agent: lunoraAgentDefinitions.${p.exportName}, binding: ${JSON.stringify(p.bindingName)} },`).join(`
|
|
690
|
+
`)}
|
|
691
|
+
]);
|
|
692
|
+
|
|
693
|
+
`:"",f=` /** Materialise the standalone Cloudflare worker + \`ShardDO\` class. */
|
|
694
|
+
public build(): ComposedApp {
|
|
695
|
+
return this.assemble();
|
|
696
|
+
}${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}${I(t).join(`
|
|
697
|
+
`)}
|
|
698
|
+
|
|
699
|
+
/** Read a value off the per-request \`env\`. Returns \`undefined\` to leave the capability unconfigured (its \`ctx.*\`/admin surface stays a clear-error stub). */
|
|
700
|
+
type Selector<Env, T> = (env: Env) => T | undefined;
|
|
701
|
+
|
|
702
|
+
/** The generated \`createShardDO\` config — \`.observability()\`, \`.maxRelationKeys()\` and the long-tail \`.ai()\` / \`.kv()\` / … methods pass straight through to it. */
|
|
703
|
+
type ShardConfig = NonNullable<Parameters<typeof createShardDO>[0]>;
|
|
704
|
+
${t.jurisdiction?`
|
|
705
|
+
// Module scope, so every isolate loading this script (the worker and each Durable
|
|
706
|
+
// Object class it exports) knows the schema's jurisdiction before a request runs.
|
|
707
|
+
// \`@lunora/mail\` reads it to pin its shard RPC like every other DO path.
|
|
708
|
+
declareAppJurisdiction(${JSON.stringify(t.jurisdiction)});
|
|
709
|
+
`:""}
|
|
710
|
+
${r.join(`
|
|
711
|
+
|
|
712
|
+
`)}${r.length>0?`
|
|
713
|
+
|
|
714
|
+
`:""}/** The composed app: a Cloudflare module worker (\`fetch\` / \`scheduled\` / optional \`email\`) plus the \`ShardDO\` class binding. */
|
|
715
|
+
interface ComposedApp extends LunoraWorker {
|
|
716
|
+
/** Cloudflare Email Routing entry — present only when \`.onEmail(...)\` was configured. */
|
|
717
|
+
email?: (message: unknown, env: unknown, context: ExecutionContextLike) => Promise<void>;
|
|
718
|
+
/** The generated shard Durable Object class — re-export it as a named export so wrangler can bind it. */
|
|
719
|
+
ShardDO: ReturnType<typeof createShardDO>;
|
|
720
|
+
}
|
|
721
|
+
|
|
722
|
+
/**
|
|
723
|
+
* Fluent worker-composition builder. Records each capability declaration, then
|
|
724
|
+
* \`.build()\` fans them into the DO-side \`createShardDO\` factory and the
|
|
725
|
+
* worker-side \`createWorker\` options — constructing the worker lazily on the
|
|
726
|
+
* first request so per-isolate singletons are built once.
|
|
727
|
+
*/
|
|
728
|
+
class AppBuilder<Env extends object> {
|
|
729
|
+
${q(t).join(`
|
|
730
|
+
`)}
|
|
731
|
+
|
|
732
|
+
private emailHandler?: (env: Env) => (message: unknown, env: unknown, context: ExecutionContextLike) => Promise<void>;
|
|
733
|
+
|
|
734
|
+
${j(t).join(`
|
|
735
|
+
|
|
736
|
+
`)}
|
|
737
|
+
|
|
738
|
+
${f}
|
|
739
|
+
|
|
740
|
+
/** Build the shard DO + compose the worker (standalone or framework-hosted), wrapping the lazy per-isolate singletons + auth init. */
|
|
741
|
+
private assemble(${h}): ComposedApp {
|
|
742
|
+
const ShardDO = createShardDO({${G(t)}});
|
|
743
|
+
|
|
744
|
+
// Per-isolate singletons: the worker (and auth instance) are expensive to
|
|
745
|
+
// build, so the first request constructs them and every later request on
|
|
746
|
+
// the same isolate reuses them.
|
|
747
|
+
let worker: LunoraWorker | null = null;
|
|
748
|
+
${i}${o}
|
|
749
|
+
${d}
|
|
750
|
+
|
|
751
|
+
const composed: ComposedApp = {
|
|
752
|
+
ShardDO,
|
|
753
|
+
fetch: async (request: Request, rawEnv: unknown, context: ExecutionContextLike): Promise<Response> => {
|
|
754
|
+
const env = rawEnv as Env;${l}
|
|
755
|
+
worker ??= buildWorker(env);
|
|
756
|
+
|
|
757
|
+
return worker.fetch(request, rawEnv, context);
|
|
758
|
+
},
|
|
759
|
+
scheduled: async (controller: ScheduledControllerLike, rawEnv: unknown, context: ExecutionContextLike): Promise<void> => {
|
|
760
|
+
worker ??= buildWorker(rawEnv as Env);
|
|
761
|
+
|
|
762
|
+
return worker.scheduled(controller, rawEnv, context);
|
|
763
|
+
},
|
|
764
|
+
serverQuery: (request, rawEnv, reference, args, options) => {
|
|
765
|
+
worker ??= buildWorker(rawEnv as Env);
|
|
766
|
+
|
|
767
|
+
return worker.serverQuery(request, rawEnv, reference, args, options);
|
|
768
|
+
},${t.hasQueue||t.hasFramework?`
|
|
769
|
+
queue: async (batch: unknown, rawEnv: unknown, context: ExecutionContextLike): Promise<void> => {
|
|
770
|
+
worker ??= buildWorker(rawEnv as Env);
|
|
771
|
+
|
|
772
|
+
return worker.queue?.(batch, rawEnv, context);
|
|
773
|
+
},`:""}
|
|
774
|
+
};
|
|
775
|
+
|
|
776
|
+
${v} if (this.emailHandler) {
|
|
777
|
+
const handler = this.emailHandler;
|
|
778
|
+
|
|
779
|
+
composed.email = (message, rawEnv, context) => handler(rawEnv as Env)(message, rawEnv, context);
|
|
780
|
+
}
|
|
781
|
+
${t.hasFramework?`
|
|
782
|
+
// A framework host may export its own \`email\` (Nitro's \`cloudflare-module\`
|
|
783
|
+
// does). Nothing in Lunora serves one, so when the app registered no handler
|
|
784
|
+
// of its own the host's is the only one there is — forward to it rather than
|
|
785
|
+
// dropping the entry.
|
|
786
|
+
if (!composed.email && host && typeof host === "object" && typeof host.email === "function") {
|
|
787
|
+
composed.email = (message, rawEnv, context) => {
|
|
788
|
+
worker ??= buildWorker(rawEnv as Env);
|
|
789
|
+
|
|
790
|
+
return worker.email?.(message, rawEnv, context) ?? Promise.resolve();
|
|
791
|
+
};
|
|
792
|
+
}
|
|
793
|
+
`:""}
|
|
794
|
+
return composed;
|
|
795
|
+
}
|
|
796
|
+
${_(t)}${$(t.hasStorage)}
|
|
797
|
+
/** Fan the recorded declarations into the worker-side \`createWorker\` options. */
|
|
798
|
+
private buildWorkerOptions(env: Env, ${c}): WorkerOptions {
|
|
799
|
+
const options: WorkerOptions = {
|
|
800
|
+
${W(t).join(`
|
|
801
|
+
`)}
|
|
802
|
+
};
|
|
803
|
+
|
|
804
|
+
if (this.adminToken) {
|
|
805
|
+
options.adminToken = this.adminToken(env);
|
|
806
|
+
}
|
|
807
|
+
|
|
808
|
+
${n.join(`
|
|
809
|
+
|
|
810
|
+
`)}${n.length>0?`
|
|
811
|
+
|
|
812
|
+
`:""} for (const fn of this.extendFns) {
|
|
813
|
+
Object.assign(options, fn(env, { ...options }));
|
|
814
|
+
}
|
|
815
|
+
|
|
816
|
+
return options;
|
|
817
|
+
}
|
|
818
|
+
}
|
|
819
|
+
${H(t.hasGlobal)}
|
|
820
|
+
/**
|
|
821
|
+
* Shape of the project's root \`lunora.config.*\`.
|
|
822
|
+
*
|
|
823
|
+
* Declared HERE, not in a package, so the \`app\` hook is typed against THIS
|
|
824
|
+
* project's builder with no annotation to keep in step — and so the config file
|
|
825
|
+
* needs only a type-only import, which is erased. That matters: the hook is
|
|
826
|
+
* bundled into the worker, and a runtime import in that file ships with it.
|
|
827
|
+
*/
|
|
828
|
+
interface LunoraConfig<Env extends object = object> {
|
|
829
|
+
/** 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\`. */
|
|
830
|
+
advisor?: { minSeverity?: "error" | "info" | "warn" };
|
|
831
|
+
/** Receives this project's \`defineApp()\` builder and returns it — where a Vite-first app makes the builder calls its generated entry cannot derive. */
|
|
832
|
+
app?: (app: AppBuilder<Env>) => AppBuilder<Env>;
|
|
833
|
+
/** Opt into remote-binding dev without \`--remote\` or \`LUNORA_REMOTE\` on every run. A literal, for the same reason as \`target\`. */
|
|
834
|
+
remote?: boolean;
|
|
835
|
+
/** 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. */
|
|
836
|
+
target?: string;
|
|
837
|
+
}
|
|
838
|
+
|
|
839
|
+
/**
|
|
840
|
+
* Start composing the app. Chain the capability methods, then \`.build()\`.
|
|
841
|
+
*
|
|
842
|
+
* \`Env\` is constrained to \`object\`, not \`Record<string, unknown>\`: an \`interface Env\`
|
|
843
|
+
* — which is what wrangler's generated \`worker-configuration.d.ts\` gives you, and
|
|
844
|
+
* what any app with its own bindings declares — is NOT assignable to an index
|
|
845
|
+
* signature, so the stricter bound forced every real app to write
|
|
846
|
+
* \`type AppEnv = Env & Record<string, unknown>\`. The builder only ever reads \`env\`
|
|
847
|
+
* through the selectors you pass it, so the looser bound costs nothing.
|
|
848
|
+
*/
|
|
849
|
+
const defineApp = <Env extends object>(): AppBuilder<Env> => new AppBuilder<Env>();
|
|
850
|
+
|
|
851
|
+
export { AppBuilder, defineApp };
|
|
852
|
+
export type { ${U(t)} };
|
|
853
|
+
`};export{M as emitApp};
|