@lunora/codegen 1.0.0-alpha.55 → 1.0.0-alpha.56

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/dist/index.d.mts +59 -5
  2. package/dist/index.d.ts +59 -5
  3. package/dist/index.mjs +1 -38
  4. package/dist/packem_shared/AGENTS_FILENAME-BesaDYkL.mjs +1 -0
  5. package/dist/packem_shared/CONTAINERS_FILENAME-CFwdyaCI.mjs +1 -0
  6. package/dist/packem_shared/CodegenDiagnosticError-DPezpZTz.mjs +1 -0
  7. package/dist/packem_shared/FLAGS_FILENAME-DW5oGq1q.mjs +1 -0
  8. package/dist/packem_shared/GENERATED_HEADER-C94PuLpQ.mjs +1 -0
  9. package/dist/packem_shared/LUNORA_ERROR_CODES-Um9hC1gr.mjs +1 -0
  10. package/dist/packem_shared/MUTATORS_FILENAME-BKKPROzu.mjs +1 -0
  11. package/dist/packem_shared/NOTIFY_FILENAME-C-c7Lg-U.mjs +1 -0
  12. package/dist/packem_shared/OPENRPC_VERSION-DpV3v2W8.mjs +3 -0
  13. package/dist/packem_shared/QUEUES_FILENAME-CSE6i-ld.mjs +1 -0
  14. package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-DJsxljOQ.mjs +3 -0
  15. package/dist/packem_shared/SCHEMA_SNAPSHOT_VERSION-Bpf1FGMG.mjs +15 -0
  16. package/dist/packem_shared/SHAPES_FILENAME-DTkSJSsg.mjs +1 -0
  17. package/dist/packem_shared/WORKFLOWS_FILENAME-Bk5upkGM.mjs +1 -0
  18. package/dist/packem_shared/buildOpenApiDocument-DXX1G3GZ.mjs +3 -0
  19. package/dist/packem_shared/discover-ast-CezKqEhE.mjs +1 -0
  20. package/dist/packem_shared/discoverAuthApiCalls-DOfSQqVK.mjs +1 -0
  21. package/dist/packem_shared/discoverCrons-B09_uEuL.mjs +1 -0
  22. package/dist/packem_shared/discoverFunctions-BdibLQmc.mjs +1 -0
  23. package/dist/packem_shared/discoverHttpRoutes-BOWz6y_n.mjs +1 -0
  24. package/dist/packem_shared/discoverInserts-BtteTyNy.mjs +1 -0
  25. package/dist/packem_shared/discoverMaskProcedures-COPmwMBm.mjs +1 -0
  26. package/dist/packem_shared/discoverMigrations-iGMlp9YJ.mjs +1 -0
  27. package/dist/packem_shared/discoverNondeterministicCalls-Dmgc4QBx.mjs +1 -0
  28. package/dist/packem_shared/discoverQueries-CcfuGKHh.mjs +1 -0
  29. package/dist/packem_shared/discoverR2sqlCalls-CjZKvg-N.mjs +1 -0
  30. package/dist/packem_shared/discoverRlsMetadata-BXmNOgry.mjs +1 -0
  31. package/dist/packem_shared/discoverSandboxUsage-CDdBqWcM.mjs +1 -0
  32. package/dist/packem_shared/discoverSchema-m2voTncu.mjs +1 -0
  33. package/dist/packem_shared/discoverStorageRulesMetadata-b71cJJHz.mjs +1 -0
  34. package/dist/packem_shared/emit-Dr6XSLfW.mjs +2104 -0
  35. package/dist/packem_shared/emitApp-B671iU7r.mjs +413 -0
  36. package/dist/packem_shared/formatAdvisories-DZvv-0MG.mjs +2 -0
  37. package/dist/packem_shared/parse-validator-CSDlMEvE.mjs +1 -0
  38. package/dist/packem_shared/paths-BmX5O1sG.mjs +1 -0
  39. package/dist/packem_shared/redact-CQ8-to6l.mjs +1 -0
  40. package/dist/packem_shared/schemaFromIr-R1ZFzVyy.mjs +1 -0
  41. package/package.json +3 -3
  42. package/dist/packem_shared/AGENTS_FILENAME-Cxx7wiSs.mjs +0 -158
  43. package/dist/packem_shared/CONTAINERS_FILENAME-DjpXMqhp.mjs +0 -224
  44. package/dist/packem_shared/CodegenDiagnosticError-DyQ5FwkM.mjs +0 -24
  45. package/dist/packem_shared/FLAGS_FILENAME-D5igzqwR.mjs +0 -139
  46. package/dist/packem_shared/GENERATED_HEADER-C8tAvxqP.mjs +0 -4
  47. package/dist/packem_shared/LUNORA_ERROR_CODES-DvTLozCu.mjs +0 -68
  48. package/dist/packem_shared/MUTATORS_FILENAME-BZOfUhlY.mjs +0 -81
  49. package/dist/packem_shared/NOTIFY_FILENAME-CK2IrsrP.mjs +0 -152
  50. package/dist/packem_shared/OPENRPC_VERSION-DvDChMhC.mjs +0 -60
  51. package/dist/packem_shared/QUEUES_FILENAME-Xv6Vy-Ku.mjs +0 -145
  52. package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-YAL6GrxI.mjs +0 -3597
  53. package/dist/packem_shared/SCHEMA_SNAPSHOT_VERSION-DGD73E_n.mjs +0 -252
  54. package/dist/packem_shared/SHAPES_FILENAME-DOhPGi-6.mjs +0 -94
  55. package/dist/packem_shared/WORKFLOWS_FILENAME-Dtuzvluc.mjs +0 -158
  56. package/dist/packem_shared/buildOpenApiDocument-DCQSLuFc.mjs +0 -262
  57. package/dist/packem_shared/discover-ast-CT6BgBr4.mjs +0 -13
  58. package/dist/packem_shared/discoverAuthApiCalls-Dhwgf4J4.mjs +0 -62
  59. package/dist/packem_shared/discoverCrons-UbQLLmMS.mjs +0 -286
  60. package/dist/packem_shared/discoverFunctions-COG_Xkyz.mjs +0 -544
  61. package/dist/packem_shared/discoverHttpRoutes-CVXWZkzo.mjs +0 -139
  62. package/dist/packem_shared/discoverInserts-DdWnXmLS.mjs +0 -61
  63. package/dist/packem_shared/discoverMaskProcedures-BG58_fw3.mjs +0 -273
  64. package/dist/packem_shared/discoverMigrations-Bw1U01zr.mjs +0 -97
  65. package/dist/packem_shared/discoverNondeterministicCalls-BbXEFZUT.mjs +0 -122
  66. package/dist/packem_shared/discoverQueries-CDmxu2ET.mjs +0 -62
  67. package/dist/packem_shared/discoverR2sqlCalls-Bn7QVv7J.mjs +0 -80
  68. package/dist/packem_shared/discoverRlsMetadata-D9uN35no.mjs +0 -280
  69. package/dist/packem_shared/discoverSandboxUsage-B5jDU6Bt.mjs +0 -38
  70. package/dist/packem_shared/discoverSchema-BJp5_T4o.mjs +0 -906
  71. package/dist/packem_shared/discoverStorageRulesMetadata-BqMhuEjo.mjs +0 -97
  72. package/dist/packem_shared/emit-DIbr7U31.mjs +0 -3884
  73. package/dist/packem_shared/emitApp-DbMM8iHe.mjs +0 -706
  74. package/dist/packem_shared/formatAdvisories-Cans5TWS.mjs +0 -131
  75. package/dist/packem_shared/parse-validator-BDGV8iue.mjs +0 -144
  76. package/dist/packem_shared/paths-BRd6JHuF.mjs +0 -11
  77. package/dist/packem_shared/redact-oTmsol5A.mjs +0 -33
  78. package/dist/packem_shared/schemaFromIr-DTYsLBaA.mjs +0 -57
@@ -1,706 +0,0 @@
1
- import { A as APP_METHOD_CAPABILITIES, G as GENERATED_HEADER } from './emit-DIbr7U31.mjs';
2
-
3
- const hasFlagKey = (key) => `has${key.charAt(0).toUpperCase()}${key.slice(1)}`;
4
- const LONG_TAIL = APP_METHOD_CAPABILITIES.map(
5
- ({ appMethod, key }) => [hasFlagKey(key), appMethod.method, appMethod.configKey, appMethod.doc]
6
- );
7
- const hasAnyLongTail = (options) => LONG_TAIL.some(([flag]) => options[flag]);
8
- const buildIdentityImports = (identity) => identity ? [`import * as lunoraIdentityContract from "../identity.js";`] : [];
9
- const buildAccessImports = (hasAccess, hasAuth) => hasAccess ? [
10
- `import type { CreateAccessResolverOptions } from "@lunora/cloudflare-access";`,
11
- `import { createAccessResolver${hasAuth ? ", composeResolvers" : ""} } from "@lunora/cloudflare-access";`
12
- ] : [];
13
- const buildKvImports = (hasKv) => hasKv ? [`import { createKvIntrospectorFromEnv } from "@lunora/bindings/kv";`] : [];
14
- const buildNotifyImports = (hasNotify) => hasNotify ? [`import notifyConfig from "../notify.js";`] : [];
15
- const hasEmailAgents = (options) => (options.emailAgents?.length ?? 0) > 0;
16
- const buildInboundImports = (options) => hasEmailAgents(options) ? [`import { dispatchAgentEmail } from "@lunora/agent/inbound";`] : [];
17
- const buildAgentDefinitionsImport = (options) => hasEmailAgents(options) ? [`import * as lunoraAgentDefinitions from "../agents.js";`] : [];
18
- const buildImportLines = (options) => {
19
- const {
20
- hasAccess,
21
- hasAuth,
22
- hasFramework,
23
- hasGlobal,
24
- hasHyperdriveGlobal,
25
- hasKv,
26
- hasQueue,
27
- hasScheduler,
28
- hasStorage,
29
- hasWorkflow,
30
- useUmbrella,
31
- wantsOpenApi,
32
- wantsOpenRpc
33
- } = options;
34
- const runtimeModule = useUmbrella ? "lunorash/runtime" : "@lunora/runtime";
35
- const runtimeTypeImports = ["ExecutionContextLike", "LunoraWorker", "Route", "ScheduledControllerLike", "ShardNamespaceLike", "WorkerOptions"];
36
- if (hasGlobal) {
37
- runtimeTypeImports.push("GlobalIntrospector");
38
- }
39
- if (hasFramework) {
40
- runtimeTypeImports.push("FrameworkHostHandler");
41
- }
42
- const runtimeValueImports = [
43
- ...hasGlobal || hasHyperdriveGlobal ? ["createCrossShardRelationCapabilities"] : [],
44
- "createWorker",
45
- "resolveLogArchiveFromEnv",
46
- ...hasFramework ? ["withFrameworkWorker"] : []
47
- ].join(", ");
48
- return [
49
- ...hasAuth ? [
50
- `import type { LunoraAuth, LunoraAuthOptions } from "@lunora/auth";`,
51
- `import { createAuth, createAuthAdmin, createAuthAuditReader, d1Executor, ensureMigrated, handleAuthRequest, lunoraD1Adapter } from "@lunora/auth";`
52
- ] : [],
53
- ...buildAccessImports(hasAccess, hasAuth),
54
- ...hasGlobal ? [
55
- `import type { D1CtxDbOptions, D1DatabaseLike, D1Exec } from "@lunora/d1";`,
56
- `import { createD1CtxDb, facetGlobalColumn, listGlobalTables, readGlobalTablePage } from "@lunora/d1";`
57
- ] : [],
58
- ...hasHyperdriveGlobal ? [
59
- `import type { HyperdriveEngine } from "@lunora/hyperdrive/global";`,
60
- `import { createHyperdriveGlobalCtxDb } from "@lunora/hyperdrive/global";`,
61
- `import type { SqlCtxDbOptions, SqlExec } from "@lunora/sql-store";`
62
- ] : [],
63
- ...buildKvImports(hasKv),
64
- ...hasScheduler ? [`import type { DurableObjectNamespaceLike } from "@lunora/scheduler";`, `import { createScheduler } from "@lunora/scheduler";`] : [],
65
- ...hasStorage ? [`import type { R2BucketLike, Storage } from "@lunora/storage";`, `import { createBucketStorage, createStorage } from "@lunora/storage";`] : [],
66
- ...hasWorkflow ? [`import { createWorkflowsRestClient } from "@lunora/workflow";`] : [],
67
- ...buildInboundImports(options),
68
- `import type { ${[...runtimeTypeImports].toSorted((a, b) => a.localeCompare(b)).join(", ")} } from "${runtimeModule}";`,
69
- `import { ${runtimeValueImports} } from "${runtimeModule}";`,
70
- ``,
71
- ...buildIdentityImports(options.identity),
72
- ...buildAgentDefinitionsImport(options),
73
- ...hasGlobal || hasHyperdriveGlobal ? [`import schema from "../schema.js";`] : [],
74
- ...buildNotifyImports(options.hasNotify),
75
- `import { LUNORA_CRONS } from "./crons.js";`,
76
- `import { LUNORA_FUNCTIONS } from "./functions.js";`,
77
- ...hasQueue ? [
78
- `import { createQueueCaptureSink, dispatchQueueBatch, shouldCaptureQueue } from "@lunora/queue";`,
79
- `import { LUNORA_QUEUE_REGISTRY } from "./queues.js";`
80
- ] : [],
81
- ...wantsOpenApi ? [`import { openApiSpec } from "./openapi.js";`] : [],
82
- ...wantsOpenRpc ? [`import { openRpcSpec } from "./openrpc.js";`] : [],
83
- `import { createShardDO } from "./shard.js";`
84
- ];
85
- };
86
- const buildDeclarationBlocks = (options) => [
87
- ...options.hasStorage ? [
88
- `/** \`.storage(...)\` declaration — one bucket (required) plus optional extra named buckets and signed-URL config. Backs \`ctx.storage\` AND the studio file browser. */
89
- interface StorageDeclaration<Env> {
90
- /** The default R2 bucket binding (the bare \`ctx.storage\`). */
91
- bucket: Selector<Env, R2BucketLike>;
92
- /** Extra named buckets, reached via \`ctx.storage.bucket("name")\` and the studio's bucket picker. */
93
- buckets?: Record<string, Selector<Env, R2BucketLike>>;
94
- /** Public base URL signed/public object URLs resolve against. */
95
- publicBaseUrl?: Selector<Env, string>;
96
- /** HMAC secret for signed URLs. */
97
- signingSecret?: Selector<Env, string>;
98
- }`
99
- ] : [],
100
- ...options.hasScheduler ? [
101
- `/** \`.scheduler(...)\` declaration — the \`SchedulerDO\` namespace plus the worker origin its callbacks dispatch back to. Backs \`ctx.scheduler\` AND the studio's scheduled-jobs view. */
102
- interface SchedulerDeclaration<Env> {
103
- /** The \`SchedulerDO\` namespace binding (typically \`env.SCHEDULER\`). */
104
- namespace: Selector<Env, DurableObjectNamespaceLike & ShardNamespaceLike>;
105
- /** The worker origin the \`SchedulerDO\` dispatches HTTP job callbacks back to. */
106
- origin?: Selector<Env, string>;
107
- }`
108
- ] : [],
109
- ...options.hasGlobal ? [
110
- `/** \`.global(...)\` declaration — the D1 binding backing \`.global()\` tables. Backs cross-tenant \`ctx.db\` reads/writes AND the studio's global data browser. */
111
- interface GlobalDeclaration<Env> {
112
- /** The D1 binding (typically \`env.DB\`). */
113
- d1: Selector<Env, D1DatabaseLike>;
114
- /** The worker origin used to fan reverse cross-backend relations across shards. Without it, such a relation throws a clear error. */
115
- origin?: Selector<Env, string>;
116
- }`
117
- ] : [],
118
- ...options.hasHyperdriveGlobal ? [
119
- `/** \`.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. */
120
- interface HyperdriveGlobalDeclaration<Env> {
121
- /** The Hyperdrive engine — selects the Postgres or MySQL dialect. */
122
- engine: HyperdriveEngine;
123
- /** Build the \`SqlExec\` from \`env\` — e.g. \`buildPgExec(fromPostgresJs(postgres(env.HYPERDRIVE.connectionString)))\`. Cache the driver on the DO instance; rebuild lazily after hibernation. */
124
- exec: (env: Env) => SqlExec;
125
- /** The worker origin used to fan reverse cross-backend relations across shards. Without it, such a relation throws a clear error. */
126
- origin?: Selector<Env, string>;
127
- }`
128
- ] : [],
129
- ...options.hasAuth ? [
130
- `/** \`.auth(...)\` declaration — better-auth options plus the D1 binding its SQL adapter reads. The builder owns the lazy build + \`ensureMigrated\` dance and wires \`authHandler\` / \`resolveIdentity\` / \`authAdmin\`. */
131
- interface AuthDeclaration<Env> {
132
- /** The D1 binding the auth SQL adapter is wired over (via \`lunoraD1Adapter\`). */
133
- d1: Selector<Env, unknown>;
134
- /** Build the better-auth options from \`env\` (secret, plugins, email/password, …). */
135
- options: (env: Env) => LunoraAuthOptions;
136
- }`
137
- ] : []
138
- ];
139
- const buildFieldLines = (options) => [
140
- ...options.hasAccess ? [` private accessSelector?: Selector<Env, CreateAccessResolverOptions>;`] : [],
141
- ` private adminToken?: Selector<Env, string>;`,
142
- ...options.hasAuth ? [` private authDeclaration?: AuthDeclaration<Env>;`] : [],
143
- ` private readonly extendFns: ((env: Env, derived: Readonly<WorkerOptions>) => Partial<WorkerOptions>)[] = [];`,
144
- ...options.hasGlobal ? [` private globalDeclaration?: GlobalDeclaration<Env>;`] : [],
145
- ...options.hasHyperdriveGlobal ? [` private hyperdriveGlobalDeclaration?: HyperdriveGlobalDeclaration<Env>;`] : [],
146
- ` private readonly routeMap: Record<string, Route> = {};`,
147
- ...options.hasScheduler ? [` private schedulerDeclaration?: SchedulerDeclaration<Env>;`] : [],
148
- ...hasAnyLongTail(options) ? [` private readonly shardExtras: Partial<ShardConfig> = {};`] : [],
149
- ` private shardSelector?: Selector<Env, ShardNamespaceLike>;`,
150
- ...options.hasStorage ? [` private storageDeclaration?: StorageDeclaration<Env>;`] : []
151
- ];
152
- const buildLongTailMethods = (options) => LONG_TAIL.filter(([flag]) => options[flag]).map(
153
- ([, name, key, document_]) => ` /** ${document_} */
154
- public ${name}(factory: NonNullable<ShardConfig["${key}"]>): this {
155
- this.shardExtras.${key} = factory;
156
-
157
- return this;
158
- }`
159
- );
160
- const buildMethodBlocks = (options) => [
161
- ...options.hasAccess ? [
162
- ` /** Wire Cloudflare Access (Zero Trust) — verifies the \`Cf-Access-Jwt-Assertion\` JWT and feeds the identity into \`ctx.auth\` / RLS via \`resolveIdentity\`. When \`.auth(...)\` is also configured, Access is composed ahead of it (Access wins when its JWT is present; everyone else falls through to the app session). */
163
- public access(selector: Selector<Env, CreateAccessResolverOptions>): this {
164
- this.accessSelector = selector;
165
-
166
- return this;
167
- }`
168
- ] : [],
169
- ` /** Bearer token gating the \`/_lunora/admin/*\` endpoints the studio calls. */
170
- public admin(selector: Selector<Env, string>): this {
171
- this.adminToken = selector;
172
-
173
- return this;
174
- }`,
175
- ...options.hasAuth ? [
176
- ` /** Wire better-auth — the builder lazily builds the instance, runs \`ensureMigrated\`, and dispatches \`/api/auth/*\` inside the worker (instrumented for the auth-failure SLO). */
177
- public auth(declaration: AuthDeclaration<Env>): this {
178
- this.authDeclaration = declaration;
179
-
180
- return this;
181
- }`
182
- ] : [],
183
- ` /** 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. */
184
- public extend(fn: (env: Env, derived: Readonly<WorkerOptions>) => Partial<WorkerOptions>): this {
185
- this.extendFns.push(fn);
186
-
187
- return this;
188
- }`,
189
- ...options.hasGlobal ? [
190
- ` /** Back \`.global()\` (cross-tenant) tables with D1 — wires \`ctx.db\` routing, the studio global browser, and reverse cross-shard relations. */
191
- public global(declaration: GlobalDeclaration<Env>): this {
192
- this.globalDeclaration = declaration;
193
-
194
- return this;
195
- }`
196
- ] : [],
197
- ...options.hasHyperdriveGlobal ? [
198
- ` /** Back \`.global({ backend: "hyperdrive" })\` tables with a Postgres/MySQL database via Hyperdrive — wires reactive \`ctx.db\` routing through the shared store core. */
199
- public hyperdriveGlobal(declaration: HyperdriveGlobalDeclaration<Env>): this {
200
- this.hyperdriveGlobalDeclaration = declaration;
201
-
202
- return this;
203
- }`
204
- ] : [],
205
- ` /** Cloudflare Email Routing entry — exposes the top-level \`email\` handler. */
206
- public onEmail(handler: (env: Env) => (message: unknown, env: unknown, context: ExecutionContextLike) => Promise<void>): this {
207
- this.emailHandler = handler;
208
-
209
- return this;
210
- }`,
211
- ` /** 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. */
212
- public route(key: string, handler: Route): this {
213
- this.routeMap[key] = handler;
214
-
215
- return this;
216
- }`,
217
- ...options.hasScheduler ? [
218
- ` /** Wire the \`SchedulerDO\` — backs \`ctx.scheduler\` and the studio's scheduled-jobs view. */
219
- public scheduler(declaration: SchedulerDeclaration<Env>): this {
220
- this.schedulerDeclaration = declaration;
221
-
222
- return this;
223
- }`
224
- ] : [],
225
- ` /** The shard Durable Object namespace (typically \`env.SHARD\`) — required: every app routes RPC + WebSocket traffic through it. */
226
- public shard(selector: Selector<Env, ShardNamespaceLike>): this {
227
- this.shardSelector = selector;
228
-
229
- return this;
230
- }`,
231
- ...options.hasStorage ? [
232
- ` /** Wire R2 storage — backs \`ctx.storage\` (incl. multi-bucket) and the studio file browser, from one declaration. */
233
- public storage(declaration: StorageDeclaration<Env>): this {
234
- this.storageDeclaration = declaration;
235
-
236
- return this;
237
- }`
238
- ] : [],
239
- ...buildLongTailMethods(options)
240
- ];
241
- const buildShardFactoryBody = (options) => {
242
- const entries = [
243
- ...options.hasGlobal ? [
244
- ` ...(this.globalDeclaration
245
- ? {
246
- d1: (rawEnv: Record<string, unknown>, request?: { identity?: Record<string, unknown>; userId?: string | null }) => {
247
- const env = rawEnv as Env;
248
- const database = this.globalDeclaration?.d1(env);
249
-
250
- if (!database) {
251
- return undefined;
252
- }
253
-
254
- const origin = this.globalDeclaration?.origin?.(env);
255
- const crossShard = origin
256
- ? createCrossShardRelationCapabilities({ identity: request?.identity, origin, userId: request?.userId ?? undefined })
257
- : undefined;
258
-
259
- return createD1CtxDb({
260
- ...(crossShard ? { crossShardCounter: crossShard.crossShardCounter, crossShardReader: crossShard.crossShardReader } : {}),
261
- auth: { identity: request?.identity ?? null, userId: request?.userId ?? null },
262
- exec: buildExec(database),
263
- schema: schema as unknown as D1CtxDbOptions["schema"],
264
- });
265
- },
266
- }
267
- : {}),`
268
- ] : [],
269
- ...options.hasHyperdriveGlobal ? [
270
- ` ...(this.hyperdriveGlobalDeclaration
271
- ? {
272
- hyperdriveGlobal: (rawEnv: Record<string, unknown>, request?: { identity?: Record<string, unknown>; userId?: string | null }) => {
273
- const env = rawEnv as Env;
274
- const exec = this.hyperdriveGlobalDeclaration?.exec(env) as SqlExec | undefined;
275
-
276
- if (!exec) {
277
- return undefined;
278
- }
279
-
280
- const origin = this.hyperdriveGlobalDeclaration?.origin?.(env);
281
- const crossShard = origin
282
- ? createCrossShardRelationCapabilities({ identity: request?.identity, origin, userId: request?.userId ?? undefined })
283
- : undefined;
284
-
285
- return createHyperdriveGlobalCtxDb({
286
- ...(crossShard ? { crossShardCounter: crossShard.crossShardCounter, crossShardReader: crossShard.crossShardReader } : {}),
287
- auth: { identity: request?.identity ?? null, userId: request?.userId ?? null },
288
- engine: this.hyperdriveGlobalDeclaration?.engine as HyperdriveEngine,
289
- exec,
290
- schema: schema as unknown as SqlCtxDbOptions["schema"],
291
- });
292
- },
293
- }
294
- : {}),`
295
- ] : [],
296
- ...options.hasScheduler ? [
297
- ` ...(this.schedulerDeclaration
298
- ? {
299
- scheduler: (rawEnv: Record<string, unknown>) => {
300
- const env = rawEnv as Env;
301
- const namespace = this.schedulerDeclaration?.namespace(env);
302
- const origin = this.schedulerDeclaration?.origin?.(env);
303
-
304
- return namespace && origin ? createScheduler({${options.jurisdiction ? ` jurisdiction: ${JSON.stringify(options.jurisdiction)},` : ""} namespace, originUrl: origin }) : undefined;
305
- },
306
- }
307
- : {}),`
308
- ] : [],
309
- ...options.hasStorage ? [` ...(this.storageDeclaration ? { storage: (rawEnv: Record<string, unknown>) => this.resolveStorage(rawEnv as Env) } : {}),`] : [],
310
- ...hasAnyLongTail(options) ? [` ...this.shardExtras,`] : []
311
- ];
312
- return entries.length > 0 ? `
313
- ${entries.join("\n")}
314
- ` : "";
315
- };
316
- const buildWorkerOptionLines = (options) => [
317
- ...options.hasScheduler ? [
318
- ` if (this.schedulerDeclaration) {
319
- options.schedulerDO = this.schedulerDeclaration.namespace(env);
320
- }`
321
- ] : [],
322
- ...options.hasWorkflow ? [
323
- // Resolve the Workflows REST client from the request env so the studio's
324
- // \`/_lunora/admin/workflows*\` proxy can read instance/step state; returns
325
- // undefined (→ "not configured") until the CF account id + API token are set.
326
- ` options.workflowsClient = (workflowEnv) => {
327
- const source = workflowEnv as Record<string, unknown>;
328
- const accountId = source["CLOUDFLARE_ACCOUNT_ID"];
329
- const apiToken = source["CLOUDFLARE_API_TOKEN"];
330
-
331
- return typeof accountId === "string" && accountId !== "" && typeof apiToken === "string" && apiToken !== ""
332
- ? createWorkflowsRestClient({ accountId, apiToken })
333
- : undefined;
334
- };`
335
- ] : [],
336
- ...options.hasGlobal ? [
337
- ` if (this.globalDeclaration) {
338
- const database = this.globalDeclaration.d1(env);
339
-
340
- if (database) {
341
- options.d1 = database;
342
- options.globalIntrospector = buildGlobalIntrospector(database);
343
- }
344
- }`
345
- ] : [],
346
- ...options.hasStorage ? [
347
- ` if (this.storageDeclaration) {
348
- Object.assign(options, this.buildStorageAdmin(env));
349
- }`
350
- ] : [],
351
- // The studio's KV browser is wired zero-config: `createKvIntrospectorFromEnv`
352
- // scans `env` for every bound Workers KV namespace, so each `kv_namespaces`
353
- // entry in wrangler.jsonc appears under its binding name (any name, any count)
354
- // with no manual `createKvIntrospector` call. A deployment with no KV binding
355
- // yields an empty namespace list rather than crashing.
356
- ...options.hasKv ? [` options.kvIntrospector = createKvIntrospectorFromEnv(env);`] : [],
357
- // The studio's Notifications page reads the app's registered `@lunora/notify`
358
- // device subscriptions through the SAME store the handlers register into. The
359
- // store is built from `env` via `lunora/notify.ts`'s `defineNotify({ store })`;
360
- // when no `store` is configured (the in-memory default), the gated
361
- // `__lunora_admin__:listPushSubscriptions` RPC returns an empty device list.
362
- ...options.hasNotify ? [` options.notifySubscriptionStore = notifyConfig.store ? notifyConfig.store(env) : undefined;`] : [],
363
- // The studio's Logs → Archive feed is wired zero-config: when the operator sets
364
- // `LUNORA_LOG_ARCHIVE_TABLE` (the R2 Data Catalog table `pipelineLogSink` writes
365
- // to), the durable archive becomes readable; unset ⇒ `undefined` ⇒ the feed
366
- // reports "not configured". The R2 SQL credentials come from `R2_SQL_*` env vars.
367
- ` options.logArchive = resolveLogArchiveFromEnv(env);`,
368
- ...options.hasAuth ? [
369
- ` if (this.authDeclaration) {
370
- options.authHandler = (request) => {
371
- const auth = getAuth();
372
-
373
- return auth ? handleAuthRequest(auth, request) : Promise.resolve(undefined);
374
- };
375
- options.resolveIdentity = async (request) => {
376
- const auth = getAuth();
377
-
378
- if (!auth) {
379
- return null;
380
- }
381
-
382
- const session = await auth.api.getSession({ headers: (request as Request).headers });
383
-
384
- return session?.user?.id ? { userId: session.user.id } : null;
385
- };
386
- const authInstance = getAuth();
387
-
388
- options.authAdmin = authInstance ? createAuthAdmin(authInstance) : undefined;
389
- options.authAuditReader = createAuthAuditReader(d1Executor(this.authDeclaration.d1(env) as never));
390
- }`
391
- ] : [],
392
- // Cloudflare Access — runs AFTER the auth block so it can compose ahead of
393
- // the better-auth resolver rather than clobber it. With `.auth()` present,
394
- // a request carrying a verified Access JWT is authenticated by Access and
395
- // everyone else falls through to the app session; without it, Access is the
396
- // sole resolver.
397
- ...options.hasAccess ? [
398
- options.hasAuth ? ` if (this.accessSelector) {
399
- const accessResolver = createAccessResolver(this.accessSelector(env));
400
- const fallback = options.resolveIdentity;
401
-
402
- options.resolveIdentity = fallback ? composeResolvers(accessResolver, fallback) : accessResolver;
403
- }` : ` if (this.accessSelector) {
404
- options.resolveIdentity = createAccessResolver(this.accessSelector(env));
405
- }`
406
- ] : [],
407
- // Voice-enabled agents: map each export name to its `VOICE_*` Durable Object
408
- // namespace so the runtime serves `/_lunora/voice/<exportName>`. Read off
409
- // `env` structurally (the binding is provisioned by the config layer's
410
- // reconcile step, so it may not be on the generated `Env` type). Emitted only
411
- // when at least one agent opted into voice — voice-free output is unchanged.
412
- ...options.voiceAgents && options.voiceAgents.length > 0 ? [
413
- ` options.voiceAgents = {
414
- ${options.voiceAgents.map(
415
- (agent) => ` ${JSON.stringify(agent.exportName)}: (env as Record<string, unknown>)[${JSON.stringify(agent.bindingName)}] as ShardNamespaceLike,`
416
- ).join("\n")}
417
- };`
418
- ] : []
419
- ];
420
- const buildBaseWorkerOptions = (options) => [
421
- ` cronJobs: LUNORA_CRONS,`,
422
- ` functions: LUNORA_FUNCTIONS,`,
423
- // The declared `defineIdentity(...)` contract — wires the runtime trust
424
- // boundary so `wrapResolverWithContract` validates every resolved identity
425
- // against it before it becomes `ctx.auth`. Emitted only when the app declares
426
- // a contract, so apps without one keep unchanged output.
427
- ...options.identity ? [` identity: lunoraIdentityContract.${options.identity.exportName},`] : [],
428
- // Schema `.jurisdiction("…")` pins every DO the worker reaches to the
429
- // Cloudflare data-residency region. Emitted only when declared, so apps
430
- // without it keep the un-pinned global namespace (and unchanged output).
431
- ...options.jurisdiction ? [` jurisdiction: ${JSON.stringify(options.jurisdiction)},`] : [],
432
- ...options.wantsOpenApi ? [` openApiSpec,`] : [],
433
- ...options.wantsOpenRpc ? [` openRpcSpec,`] : [],
434
- // The push-consumer handler backing the worker's `queue(batch, …)` entry:
435
- // routes each delivered batch to its `defineQueue` handler. Built from
436
- // `@lunora/queue` here (keeping the runtime decoupled) and wired only when the
437
- // app declares push queues in `lunora/queues.ts`. In a dev environment (or with
438
- // `LUNORA_QUEUE_CAPTURE`), every consumed message is recorded into the studio's
439
- // Queues log via the root shard's `recordQueueMessage` admin RPC.
440
- ...options.hasQueue ? [
441
- ` queue: (batch: unknown, queueEnv: unknown, _context: ExecutionContextLike): Promise<void> =>`,
442
- ` dispatchQueueBatch(batch as Parameters<typeof dispatchQueueBatch>[0], LUNORA_QUEUE_REGISTRY, {`,
443
- ` capture: shouldCaptureQueue(queueEnv as Record<string, unknown>)`,
444
- ` ? createQueueCaptureSink(queueEnv as Record<string, unknown>${options.jurisdiction ? `, { jurisdiction: ${JSON.stringify(options.jurisdiction)} }` : ""})`,
445
- ` : undefined,`,
446
- ` env: queueEnv as Record<string, unknown>,`,
447
- ` }),`
448
- ] : [],
449
- ` routes: this.routeMap,`,
450
- ` shardDO: this.shardSelector?.(env) ?? (undefined as unknown as ShardNamespaceLike),`
451
- ];
452
- const buildStorageHelpers = (hasStorage) => hasStorage ? `
453
- /** Resolve the storage capability (single or multi-bucket) for the DO side. */
454
- private resolveStorage(env: Env): Storage | undefined {
455
- const declaration = this.storageDeclaration;
456
-
457
- if (!declaration) {
458
- return undefined;
459
- }
460
-
461
- const defaultBucket = declaration.bucket(env);
462
-
463
- if (!defaultBucket) {
464
- return undefined;
465
- }
466
-
467
- const make = (bucket: R2BucketLike): Storage =>
468
- createStorage({ bucket, publicBaseUrl: declaration.publicBaseUrl?.(env), signingSecret: declaration.signingSecret?.(env) });
469
- const extraEntries = Object.entries(declaration.buckets ?? {})
470
- .map(([name, selector]) => [name, selector(env)] as const)
471
- .filter((entry): entry is [string, R2BucketLike] => Boolean(entry[1]));
472
-
473
- if (extraEntries.length === 0) {
474
- return make(defaultBucket);
475
- }
476
-
477
- const map: Record<string, Storage> = { default: make(defaultBucket) };
478
-
479
- for (const [name, bucket] of extraEntries) {
480
- map[name] = make(bucket);
481
- }
482
-
483
- return createBucketStorage(map, { default: "default" });
484
- }
485
-
486
- /** Derive the studio file-browser admin functions from the same buckets \`.storage()\` declared. */
487
- private buildStorageAdmin(env: Env): Partial<WorkerOptions> {
488
- const declaration = this.storageDeclaration;
489
-
490
- if (!declaration) {
491
- return {};
492
- }
493
-
494
- const defaultBucket = declaration.bucket(env);
495
-
496
- if (!defaultBucket) {
497
- return {};
498
- }
499
-
500
- const make = (bucket: R2BucketLike): Storage =>
501
- createStorage({ bucket, publicBaseUrl: declaration.publicBaseUrl?.(env), signingSecret: declaration.signingSecret?.(env) });
502
- const buckets: Record<string, Storage> = { default: make(defaultBucket) };
503
-
504
- for (const [name, selector] of Object.entries(declaration.buckets ?? {})) {
505
- const bucket = selector(env);
506
-
507
- if (bucket) {
508
- buckets[name] = make(bucket);
509
- }
510
- }
511
-
512
- const pick = (name?: string): Storage => buckets[name !== undefined && name !== "" ? name : "default"] ?? buckets.default;
513
- const hasSigning = Boolean(declaration.publicBaseUrl?.(env) && declaration.signingSecret?.(env));
514
-
515
- return {
516
- storageBuckets: Object.keys(buckets),
517
- storageDelete: (key: string, opts?: { bucket?: string }) => pick(opts?.bucket).delete(key),
518
- storageList: (prefix?: string, opts?: { bucket?: string; cursor?: string; limit?: number }) => pick(opts?.bucket).list(prefix, opts),
519
- storageSignedUrl: hasSigning
520
- ? (key: string, opts?: { bucket?: string; expiresInSeconds?: number }) => pick(opts?.bucket).getSignedUrl(key, { expiresInSeconds: opts?.expiresInSeconds })
521
- : undefined,
522
- storageUpload: (key: string, body: ArrayBuffer, opts?: { bucket?: string; contentType?: string }) => pick(opts?.bucket).upload(key, body, opts),
523
- };
524
- }
525
- ` : "";
526
- const buildGlobalHelpers = (hasGlobal) => hasGlobal ? `
527
- /** Adapt the raw D1 binding to \`@lunora/d1\`'s \`D1Exec\` (reads via \`all\`, writes via \`run\`). */
528
- const buildExec = (database: D1DatabaseLike): D1Exec => ({
529
- all: async (sql, parameters) => {
530
- const result = await database
531
- .prepare(sql)
532
- .bind(...parameters)
533
- .all<Record<string, unknown>>();
534
-
535
- return result.results;
536
- },
537
- run: async (sql, parameters) => {
538
- await database
539
- .prepare(sql)
540
- .bind(...parameters)
541
- .run();
542
- },
543
- });
544
-
545
- /** Introspect \`.global()\` (D1-backed) tables for the studio's global data browser. */
546
- const buildGlobalIntrospector = (database: D1DatabaseLike): GlobalIntrospector => {
547
- const exec = buildExec(database);
548
-
549
- return {
550
- facetColumn: (options) => facetGlobalColumn(exec, schema as never, options),
551
- listTables: () => listGlobalTables(exec, schema as never),
552
- readTablePage: (options) => readGlobalTablePage(exec, schema as never, options),
553
- };
554
- };
555
- ` : "";
556
- const buildExportedTypes = (options) => [
557
- ...options.hasAuth ? ["AuthDeclaration"] : [],
558
- "ComposedApp",
559
- ...options.hasGlobal ? ["GlobalDeclaration"] : [],
560
- ...options.hasScheduler ? ["SchedulerDeclaration"] : [],
561
- "Selector",
562
- ...options.hasStorage ? ["StorageDeclaration"] : []
563
- ].toSorted((a, b) => a.localeCompare(b)).join(", ");
564
- const emitApp = (options) => {
565
- const { hasAuth } = options;
566
- const declarationBlocks = buildDeclarationBlocks(options);
567
- const workerOptionLines = buildWorkerOptionLines(options);
568
- const authState = hasAuth ? ` let auth: LunoraAuth | null = null;
569
- ` : "";
570
- const ensureAuthBlock = hasAuth ? `
571
- const ensureAuth = async (env: Env): Promise<void> => {
572
- if (!this.authDeclaration || auth) {
573
- return;
574
- }
575
-
576
- auth = createAuth({ ...this.authDeclaration.options(env), database: lunoraD1Adapter(this.authDeclaration.d1(env) as never) });
577
- // Apply the better-auth schema lazily on first request (raw-D1 Kysely
578
- // migrator). For production run the migrate command ahead of deploy.
579
- await ensureMigrated(createAuth({ ...this.authDeclaration.options(env), database: this.authDeclaration.d1(env) as never }));
580
- };
581
- ` : "";
582
- const ensureAuthCall = hasAuth ? `
583
- await ensureAuth(env);` : "";
584
- const getAuthArgument = hasAuth ? `() => auth` : `() => null`;
585
- const getAuthParameter = hasAuth ? `getAuth: () => LunoraAuth | null` : `_getAuth: () => null`;
586
- const buildWorkerLine = options.hasFramework ? ` const buildWorker = (env: Env): LunoraWorker =>
587
- host ? withFrameworkWorker(host, (hostEnv) => this.buildWorkerOptions(hostEnv as Env, ${getAuthArgument})) : createWorker(this.buildWorkerOptions(env, ${getAuthArgument}));` : ` const buildWorker = (env: Env): LunoraWorker => createWorker(this.buildWorkerOptions(env, ${getAuthArgument}));`;
588
- const assembleParameter = options.hasFramework ? `host?: FrameworkHostHandler` : ``;
589
- const emailAgents = options.emailAgents ?? [];
590
- const emailAgentsBlock = emailAgents.length > 0 ? ` composed.email = dispatchAgentEmail([
591
- ${emailAgents.map((agent) => ` { agent: lunoraAgentDefinitions.${agent.exportName}, binding: ${JSON.stringify(agent.bindingName)} },`).join("\n")}
592
- ]);
593
-
594
- ` : "";
595
- const buildTerminals = ` /** Materialise the standalone Cloudflare worker + \`ShardDO\` class. */
596
- public build(): ComposedApp {
597
- return this.assemble();
598
- }${options.hasFramework ? `
599
-
600
- /** 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\`). */
601
- public buildFrameworkWorker(host: FrameworkHostHandler): ComposedApp {
602
- return this.assemble(host);
603
- }` : ``}`;
604
- return `${GENERATED_HEADER}${buildImportLines(options).join("\n")}
605
-
606
- /** Read a value off the per-request \`env\`. Returns \`undefined\` to leave the capability unconfigured (its \`ctx.*\`/admin surface stays a clear-error stub). */
607
- type Selector<Env, T> = (env: Env) => T | undefined;
608
- ${hasAnyLongTail(options) ? `
609
- /** The generated \`createShardDO\` config — the long-tail \`.ai()\` / \`.kv()\` / … methods pass straight through to it. */
610
- type ShardConfig = NonNullable<Parameters<typeof createShardDO>[0]>;
611
- ` : ""}
612
- ${declarationBlocks.join("\n\n")}${declarationBlocks.length > 0 ? "\n\n" : ""}/** The composed app: a Cloudflare module worker (\`fetch\` / \`scheduled\` / optional \`email\`) plus the \`ShardDO\` class binding. */
613
- interface ComposedApp extends LunoraWorker {
614
- /** Cloudflare Email Routing entry — present only when \`.onEmail(...)\` was configured. */
615
- email?: (message: unknown, env: unknown, context: ExecutionContextLike) => Promise<void>;
616
- /** The generated shard Durable Object class — re-export it as a named export so wrangler can bind it. */
617
- ShardDO: ReturnType<typeof createShardDO>;
618
- }
619
-
620
- /**
621
- * Fluent worker-composition builder. Records each capability declaration, then
622
- * \`.build()\` fans them into the DO-side \`createShardDO\` factory and the
623
- * worker-side \`createWorker\` options — constructing the worker lazily on the
624
- * first request so per-isolate singletons are built once.
625
- */
626
- class AppBuilder<Env extends Record<string, unknown>> {
627
- ${buildFieldLines(options).join("\n")}
628
-
629
- private emailHandler?: (env: Env) => (message: unknown, env: unknown, context: ExecutionContextLike) => Promise<void>;
630
-
631
- ${buildMethodBlocks(options).join("\n\n")}
632
-
633
- ${buildTerminals}
634
-
635
- /** Build the shard DO + compose the worker (standalone or framework-hosted), wrapping the lazy per-isolate singletons + auth init. */
636
- private assemble(${assembleParameter}): ComposedApp {
637
- const ShardDO = createShardDO({${buildShardFactoryBody(options)}});
638
-
639
- // Per-isolate singletons: the worker (and auth instance) are expensive to
640
- // build, so the first request constructs them and every later request on
641
- // the same isolate reuses them.
642
- let worker: LunoraWorker | null = null;
643
- ${authState}${ensureAuthBlock}
644
- ${buildWorkerLine}
645
-
646
- const composed: ComposedApp = {
647
- ShardDO,
648
- fetch: async (request: Request, rawEnv: unknown, context: ExecutionContextLike): Promise<Response> => {
649
- const env = rawEnv as Env;${ensureAuthCall}
650
- worker ??= buildWorker(env);
651
-
652
- return worker.fetch(request, rawEnv, context);
653
- },
654
- scheduled: async (controller: ScheduledControllerLike, rawEnv: unknown, context: ExecutionContextLike): Promise<void> => {
655
- worker ??= buildWorker(rawEnv as Env);
656
-
657
- return worker.scheduled(controller, rawEnv, context);
658
- },
659
- serverQuery: (request, rawEnv, reference, args, options) => {
660
- worker ??= buildWorker(rawEnv as Env);
661
-
662
- return worker.serverQuery(request, rawEnv, reference, args, options);
663
- },${options.hasQueue ? `
664
- queue: async (batch: unknown, rawEnv: unknown, context: ExecutionContextLike): Promise<void> => {
665
- worker ??= buildWorker(rawEnv as Env);
666
-
667
- return worker.queue?.(batch, rawEnv, context);
668
- },` : ""}
669
- };
670
-
671
- ${emailAgentsBlock} if (this.emailHandler) {
672
- const handler = this.emailHandler;
673
-
674
- composed.email = (message, rawEnv, context) => handler(rawEnv as Env)(message, rawEnv, context);
675
- }
676
-
677
- return composed;
678
- }
679
- ${buildStorageHelpers(options.hasStorage)}
680
- /** Fan the recorded declarations into the worker-side \`createWorker\` options. */
681
- private buildWorkerOptions(env: Env, ${getAuthParameter}): WorkerOptions {
682
- const options: WorkerOptions = {
683
- ${buildBaseWorkerOptions(options).join("\n")}
684
- };
685
-
686
- if (this.adminToken) {
687
- options.adminToken = this.adminToken(env);
688
- }
689
-
690
- ${workerOptionLines.join("\n\n")}${workerOptionLines.length > 0 ? "\n\n" : ""} for (const fn of this.extendFns) {
691
- Object.assign(options, fn(env, { ...options }));
692
- }
693
-
694
- return options;
695
- }
696
- }
697
- ${buildGlobalHelpers(options.hasGlobal)}
698
- /** Start composing the app. Chain the capability methods, then \`.build()\`. */
699
- const defineApp = <Env extends Record<string, unknown>>(): AppBuilder<Env> => new AppBuilder<Env>();
700
-
701
- export { AppBuilder, defineApp };
702
- export type { ${buildExportedTypes(options)} };
703
- `;
704
- };
705
-
706
- export { emitApp };