@lunora/codegen 0.0.0 → 1.0.0-alpha.2
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 +105 -0
- package/README.md +117 -9
- package/__assets__/package-og.svg +14 -0
- package/dist/index.d.mts +1473 -0
- package/dist/index.d.ts +1473 -0
- package/dist/index.mjs +28 -0
- package/dist/packem_shared/CONTAINERS_FILENAME-0K-pjNb8.mjs +224 -0
- package/dist/packem_shared/CodegenDiagnosticError-54jWDxA9.mjs +22 -0
- package/dist/packem_shared/LUNORA_ERROR_CODES-CySpQPD3.mjs +61 -0
- package/dist/packem_shared/buildOpenApiDocument-yHVN66Xd.mjs +183 -0
- package/dist/packem_shared/buildOpenRpcDocument-BZGY1-jT.mjs +60 -0
- package/dist/packem_shared/buildSchemaSnapshot-DzLDbWk3.mjs +233 -0
- package/dist/packem_shared/createCodegenProject-DGJm0_Pk.mjs +895 -0
- package/dist/packem_shared/discover-ast-CT6BgBr4.mjs +13 -0
- package/dist/packem_shared/discoverAuthApiCalls-C35R6z0T.mjs +62 -0
- package/dist/packem_shared/discoverCrons-BL6iGuJ3.mjs +254 -0
- package/dist/packem_shared/discoverFunctions-DEgAcRuD.mjs +460 -0
- package/dist/packem_shared/discoverHttpRoutes-C978pBiG.mjs +131 -0
- package/dist/packem_shared/discoverInserts-CRQdXvHO.mjs +39 -0
- package/dist/packem_shared/discoverMaskProcedures-B64zA740.mjs +217 -0
- package/dist/packem_shared/discoverMigrations-Doj_-BAA.mjs +91 -0
- package/dist/packem_shared/discoverNondeterministicCalls-4KiPQxQU.mjs +122 -0
- package/dist/packem_shared/discoverQueries-BkIi0dBD.mjs +62 -0
- package/dist/packem_shared/discoverRlsMetadata-DpRB1HMe.mjs +280 -0
- package/dist/packem_shared/discoverSchema-BBulgGbH.mjs +542 -0
- package/dist/packem_shared/discoverStorageRulesMetadata-DAqJUxUv.mjs +97 -0
- package/dist/packem_shared/discoverWorkflows-DRDQdhfq.mjs +84 -0
- package/dist/packem_shared/emitApi-hRVC-kE7.mjs +2426 -0
- package/dist/packem_shared/emitApp-CzZ6GbrD.mjs +593 -0
- package/dist/packem_shared/lintSchema-DicbOHvH.mjs +68 -0
- package/dist/packem_shared/parse-validator-tuQtHrsr.mjs +132 -0
- package/dist/packem_shared/paths-BRd6JHuF.mjs +11 -0
- package/dist/packem_shared/schemaFromIr-DTYsLBaA.mjs +57 -0
- package/package.json +45 -17
|
@@ -0,0 +1,593 @@
|
|
|
1
|
+
import { GENERATED_HEADER } from './emitApi-hRVC-kE7.mjs';
|
|
2
|
+
|
|
3
|
+
const LONG_TAIL = [
|
|
4
|
+
["hasAi", "ai", "ai", "Override the Workers AI binding backing `ctx.ai` (defaults to `env.AI`)."],
|
|
5
|
+
["hasAnalytics", "analytics", "analytics", "Override the Analytics Engine dataset backing `ctx.analytics` (defaults to `env.ANALYTICS`)."],
|
|
6
|
+
["hasBrowser", "browser", "browser", "Override the Browser Rendering binding backing `ctx.browser` (defaults to `env.BROWSER`)."],
|
|
7
|
+
[
|
|
8
|
+
"hasHyperdrive",
|
|
9
|
+
"hyperdrive",
|
|
10
|
+
"sql",
|
|
11
|
+
"Wire the Hyperdrive SQL client backing `ctx.sql` — build it with `createHyperdrive` + `fromPostgresJs`/`fromNodePg`/`fromMysql2`."
|
|
12
|
+
],
|
|
13
|
+
["hasImages", "images", "images", "Override the Images binding backing `ctx.images` (defaults to `env.IMAGES`)."],
|
|
14
|
+
["hasKv", "kv", "kv", "Override the Workers KV binding backing `ctx.kv` (defaults to `env.KV`)."],
|
|
15
|
+
["hasPayments", "payment", "payment", "Wire the payment options backing `ctx.payments`."],
|
|
16
|
+
["hasVectors", "vectors", "vectors", "Wire the Vectorize index map backing `ctx.vectors`."]
|
|
17
|
+
];
|
|
18
|
+
const hasAnyLongTail = (options) => LONG_TAIL.some(([flag]) => options[flag]);
|
|
19
|
+
const buildImportLines = (options) => {
|
|
20
|
+
const { hasAuth, hasFramework, hasGlobal, hasHyperdriveGlobal, hasScheduler, hasStorage, hasWorkflow, useUmbrella, wantsOpenApi, wantsOpenRpc } = options;
|
|
21
|
+
const runtimeModule = useUmbrella ? "lunorash/runtime" : "@lunora/runtime";
|
|
22
|
+
const runtimeTypeImports = ["ExecutionContextLike", "LunoraWorker", "Route", "ScheduledControllerLike", "ShardNamespaceLike", "WorkerOptions"];
|
|
23
|
+
if (hasGlobal) {
|
|
24
|
+
runtimeTypeImports.push("GlobalIntrospector");
|
|
25
|
+
}
|
|
26
|
+
if (hasFramework) {
|
|
27
|
+
runtimeTypeImports.push("FrameworkHostHandler");
|
|
28
|
+
}
|
|
29
|
+
const runtimeValueImports = [
|
|
30
|
+
...hasGlobal || hasHyperdriveGlobal ? ["createCrossShardRelationCapabilities"] : [],
|
|
31
|
+
"createWorker",
|
|
32
|
+
...hasFramework ? ["withFrameworkWorker"] : []
|
|
33
|
+
].join(", ");
|
|
34
|
+
return [
|
|
35
|
+
...hasAuth ? [
|
|
36
|
+
`import type { LunoraAuth, LunoraAuthOptions } from "@lunora/auth";`,
|
|
37
|
+
`import { createAuth, createAuthAdmin, ensureMigrated, handleAuthRequest, lunoraD1Adapter } from "@lunora/auth";`
|
|
38
|
+
] : [],
|
|
39
|
+
...hasGlobal ? [
|
|
40
|
+
`import type { D1CtxDbOptions, D1DatabaseLike, D1Exec } from "@lunora/d1";`,
|
|
41
|
+
`import { createD1CtxDb, facetGlobalColumn, listGlobalTables, readGlobalTablePage } from "@lunora/d1";`
|
|
42
|
+
] : [],
|
|
43
|
+
...hasHyperdriveGlobal ? [
|
|
44
|
+
`import type { HyperdriveEngine } from "@lunora/hyperdrive/global";`,
|
|
45
|
+
`import { createHyperdriveGlobalCtxDb } from "@lunora/hyperdrive/global";`,
|
|
46
|
+
`import type { SqlCtxDbOptions, SqlExec } from "@lunora/sql-store";`
|
|
47
|
+
] : [],
|
|
48
|
+
...hasScheduler ? [`import type { DurableObjectNamespaceLike } from "@lunora/scheduler";`, `import { createScheduler } from "@lunora/scheduler";`] : [],
|
|
49
|
+
...hasStorage ? [`import type { R2BucketLike, Storage } from "@lunora/storage";`, `import { createBucketStorage, createStorage } from "@lunora/storage";`] : [],
|
|
50
|
+
...hasWorkflow ? [`import { createWorkflowsRestClient } from "@lunora/workflow";`] : [],
|
|
51
|
+
`import type { ${[...runtimeTypeImports].toSorted((a, b) => a.localeCompare(b)).join(", ")} } from "${runtimeModule}";`,
|
|
52
|
+
`import { ${runtimeValueImports} } from "${runtimeModule}";`,
|
|
53
|
+
``,
|
|
54
|
+
...hasGlobal || hasHyperdriveGlobal ? [`import schema from "../schema.js";`] : [],
|
|
55
|
+
`import { LUNORA_CRONS } from "./crons.js";`,
|
|
56
|
+
`import { LUNORA_FUNCTIONS } from "./functions.js";`,
|
|
57
|
+
...wantsOpenApi ? [`import { openApiSpec } from "./openapi.js";`] : [],
|
|
58
|
+
...wantsOpenRpc ? [`import { openRpcSpec } from "./openrpc.js";`] : [],
|
|
59
|
+
`import { createShardDO } from "./shard.js";`
|
|
60
|
+
];
|
|
61
|
+
};
|
|
62
|
+
const buildDeclarationBlocks = (options) => [
|
|
63
|
+
...options.hasStorage ? [
|
|
64
|
+
`/** \`.storage(...)\` declaration — one bucket (required) plus optional extra named buckets and signed-URL config. Backs \`ctx.storage\` AND the studio file browser. */
|
|
65
|
+
interface StorageDeclaration<Env> {
|
|
66
|
+
/** The default R2 bucket binding (the bare \`ctx.storage\`). */
|
|
67
|
+
bucket: Selector<Env, R2BucketLike>;
|
|
68
|
+
/** Extra named buckets, reached via \`ctx.storage.bucket("name")\` and the studio's bucket picker. */
|
|
69
|
+
buckets?: Record<string, Selector<Env, R2BucketLike>>;
|
|
70
|
+
/** Public base URL signed/public object URLs resolve against. */
|
|
71
|
+
publicBaseUrl?: Selector<Env, string>;
|
|
72
|
+
/** HMAC secret for signed URLs. */
|
|
73
|
+
signingSecret?: Selector<Env, string>;
|
|
74
|
+
}`
|
|
75
|
+
] : [],
|
|
76
|
+
...options.hasScheduler ? [
|
|
77
|
+
`/** \`.scheduler(...)\` declaration — the \`SchedulerDO\` namespace plus the worker origin its callbacks dispatch back to. Backs \`ctx.scheduler\` AND the studio's scheduled-jobs view. */
|
|
78
|
+
interface SchedulerDeclaration<Env> {
|
|
79
|
+
/** The \`SchedulerDO\` namespace binding (typically \`env.SCHEDULER\`). */
|
|
80
|
+
namespace: Selector<Env, DurableObjectNamespaceLike & ShardNamespaceLike>;
|
|
81
|
+
/** The worker origin the \`SchedulerDO\` dispatches HTTP job callbacks back to. */
|
|
82
|
+
origin?: Selector<Env, string>;
|
|
83
|
+
}`
|
|
84
|
+
] : [],
|
|
85
|
+
...options.hasGlobal ? [
|
|
86
|
+
`/** \`.global(...)\` declaration — the D1 binding backing \`.global()\` tables. Backs cross-tenant \`ctx.db\` reads/writes AND the studio's global data browser. */
|
|
87
|
+
interface GlobalDeclaration<Env> {
|
|
88
|
+
/** The D1 binding (typically \`env.DB\`). */
|
|
89
|
+
d1: Selector<Env, D1DatabaseLike>;
|
|
90
|
+
/** The worker origin used to fan reverse cross-backend relations across shards. Without it, such a relation throws a clear error. */
|
|
91
|
+
origin?: Selector<Env, string>;
|
|
92
|
+
}`
|
|
93
|
+
] : [],
|
|
94
|
+
...options.hasHyperdriveGlobal ? [
|
|
95
|
+
`/** \`.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. */
|
|
96
|
+
interface HyperdriveGlobalDeclaration<Env> {
|
|
97
|
+
/** The Hyperdrive engine — selects the Postgres or MySQL dialect. */
|
|
98
|
+
engine: HyperdriveEngine;
|
|
99
|
+
/** Build the \`SqlExec\` from \`env\` — e.g. \`buildPgExec(fromPostgresJs(postgres(env.HYPERDRIVE.connectionString)))\`. Cache the driver on the DO instance; rebuild lazily after hibernation. */
|
|
100
|
+
exec: (env: Env) => SqlExec;
|
|
101
|
+
/** The worker origin used to fan reverse cross-backend relations across shards. Without it, such a relation throws a clear error. */
|
|
102
|
+
origin?: Selector<Env, string>;
|
|
103
|
+
}`
|
|
104
|
+
] : [],
|
|
105
|
+
...options.hasAuth ? [
|
|
106
|
+
`/** \`.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\`. */
|
|
107
|
+
interface AuthDeclaration<Env> {
|
|
108
|
+
/** The D1 binding the auth SQL adapter is wired over (via \`lunoraD1Adapter\`). */
|
|
109
|
+
d1: Selector<Env, unknown>;
|
|
110
|
+
/** Build the better-auth options from \`env\` (secret, plugins, email/password, …). */
|
|
111
|
+
options: (env: Env) => LunoraAuthOptions;
|
|
112
|
+
}`
|
|
113
|
+
] : []
|
|
114
|
+
];
|
|
115
|
+
const buildFieldLines = (options) => [
|
|
116
|
+
` private adminToken?: Selector<Env, string>;`,
|
|
117
|
+
...options.hasAuth ? [` private authDeclaration?: AuthDeclaration<Env>;`] : [],
|
|
118
|
+
` private readonly extendFns: ((env: Env) => Partial<WorkerOptions>)[] = [];`,
|
|
119
|
+
...options.hasGlobal ? [` private globalDeclaration?: GlobalDeclaration<Env>;`] : [],
|
|
120
|
+
...options.hasHyperdriveGlobal ? [` private hyperdriveGlobalDeclaration?: HyperdriveGlobalDeclaration<Env>;`] : [],
|
|
121
|
+
` private readonly routeMap: Record<string, Route> = {};`,
|
|
122
|
+
...options.hasScheduler ? [` private schedulerDeclaration?: SchedulerDeclaration<Env>;`] : [],
|
|
123
|
+
...hasAnyLongTail(options) ? [` private readonly shardExtras: Partial<ShardConfig> = {};`] : [],
|
|
124
|
+
` private shardSelector?: Selector<Env, ShardNamespaceLike>;`,
|
|
125
|
+
...options.hasStorage ? [` private storageDeclaration?: StorageDeclaration<Env>;`] : []
|
|
126
|
+
];
|
|
127
|
+
const buildLongTailMethods = (options) => LONG_TAIL.filter(([flag]) => options[flag]).map(
|
|
128
|
+
([, name, key, document_]) => ` /** ${document_} */
|
|
129
|
+
public ${name}(factory: NonNullable<ShardConfig["${key}"]>): this {
|
|
130
|
+
this.shardExtras.${key} = factory;
|
|
131
|
+
|
|
132
|
+
return this;
|
|
133
|
+
}`
|
|
134
|
+
);
|
|
135
|
+
const buildMethodBlocks = (options) => [
|
|
136
|
+
` /** Bearer token gating the \`/_lunora/admin/*\` endpoints the studio calls. */
|
|
137
|
+
public admin(selector: Selector<Env, string>): this {
|
|
138
|
+
this.adminToken = selector;
|
|
139
|
+
|
|
140
|
+
return this;
|
|
141
|
+
}`,
|
|
142
|
+
...options.hasAuth ? [
|
|
143
|
+
` /** Wire better-auth — the builder lazily builds the instance, runs \`ensureMigrated\`, and dispatches \`/api/auth/*\` inside the worker (instrumented for the auth-failure SLO). */
|
|
144
|
+
public auth(declaration: AuthDeclaration<Env>): this {
|
|
145
|
+
this.authDeclaration = declaration;
|
|
146
|
+
|
|
147
|
+
return this;
|
|
148
|
+
}`
|
|
149
|
+
] : [],
|
|
150
|
+
` /** Escape hatch — merge raw \`WorkerOptions\` (anything not yet sugared) over the derived options at build time. */
|
|
151
|
+
public extend(fn: (env: Env) => Partial<WorkerOptions>): this {
|
|
152
|
+
this.extendFns.push(fn);
|
|
153
|
+
|
|
154
|
+
return this;
|
|
155
|
+
}`,
|
|
156
|
+
...options.hasGlobal ? [
|
|
157
|
+
` /** Back \`.global()\` (cross-tenant) tables with D1 — wires \`ctx.db\` routing, the studio global browser, and reverse cross-shard relations. */
|
|
158
|
+
public global(declaration: GlobalDeclaration<Env>): this {
|
|
159
|
+
this.globalDeclaration = declaration;
|
|
160
|
+
|
|
161
|
+
return this;
|
|
162
|
+
}`
|
|
163
|
+
] : [],
|
|
164
|
+
...options.hasHyperdriveGlobal ? [
|
|
165
|
+
` /** Back \`.global({ backend: "hyperdrive" })\` tables with a Postgres/MySQL database via Hyperdrive — wires reactive \`ctx.db\` routing through the shared store core. */
|
|
166
|
+
public hyperdriveGlobal(declaration: HyperdriveGlobalDeclaration<Env>): this {
|
|
167
|
+
this.hyperdriveGlobalDeclaration = declaration;
|
|
168
|
+
|
|
169
|
+
return this;
|
|
170
|
+
}`
|
|
171
|
+
] : [],
|
|
172
|
+
` /** Cloudflare Email Routing entry — exposes the top-level \`email\` handler. */
|
|
173
|
+
public onEmail(handler: (env: Env) => (message: unknown, env: unknown, context: ExecutionContextLike) => Promise<void>): this {
|
|
174
|
+
this.emailHandler = handler;
|
|
175
|
+
|
|
176
|
+
return this;
|
|
177
|
+
}`,
|
|
178
|
+
` /** 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. */
|
|
179
|
+
public route(key: string, handler: Route): this {
|
|
180
|
+
this.routeMap[key] = handler;
|
|
181
|
+
|
|
182
|
+
return this;
|
|
183
|
+
}`,
|
|
184
|
+
...options.hasScheduler ? [
|
|
185
|
+
` /** Wire the \`SchedulerDO\` — backs \`ctx.scheduler\` and the studio's scheduled-jobs view. */
|
|
186
|
+
public scheduler(declaration: SchedulerDeclaration<Env>): this {
|
|
187
|
+
this.schedulerDeclaration = declaration;
|
|
188
|
+
|
|
189
|
+
return this;
|
|
190
|
+
}`
|
|
191
|
+
] : [],
|
|
192
|
+
` /** The shard Durable Object namespace (typically \`env.SHARD\`) — required: every app routes RPC + WebSocket traffic through it. */
|
|
193
|
+
public shard(selector: Selector<Env, ShardNamespaceLike>): this {
|
|
194
|
+
this.shardSelector = selector;
|
|
195
|
+
|
|
196
|
+
return this;
|
|
197
|
+
}`,
|
|
198
|
+
...options.hasStorage ? [
|
|
199
|
+
` /** Wire R2 storage — backs \`ctx.storage\` (incl. multi-bucket) and the studio file browser, from one declaration. */
|
|
200
|
+
public storage(declaration: StorageDeclaration<Env>): this {
|
|
201
|
+
this.storageDeclaration = declaration;
|
|
202
|
+
|
|
203
|
+
return this;
|
|
204
|
+
}`
|
|
205
|
+
] : [],
|
|
206
|
+
...buildLongTailMethods(options)
|
|
207
|
+
];
|
|
208
|
+
const buildShardFactoryBody = (options) => {
|
|
209
|
+
const entries = [
|
|
210
|
+
...options.hasGlobal ? [
|
|
211
|
+
` ...(this.globalDeclaration
|
|
212
|
+
? {
|
|
213
|
+
d1: (rawEnv: Record<string, unknown>, request?: { identity?: Record<string, unknown>; userId?: string | null }) => {
|
|
214
|
+
const env = rawEnv as Env;
|
|
215
|
+
const database = this.globalDeclaration?.d1(env);
|
|
216
|
+
|
|
217
|
+
if (!database) {
|
|
218
|
+
return undefined;
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
const origin = this.globalDeclaration?.origin?.(env);
|
|
222
|
+
const crossShard = origin
|
|
223
|
+
? createCrossShardRelationCapabilities({ identity: request?.identity, origin, userId: request?.userId ?? undefined })
|
|
224
|
+
: undefined;
|
|
225
|
+
|
|
226
|
+
return createD1CtxDb({
|
|
227
|
+
...(crossShard ? { crossShardCounter: crossShard.crossShardCounter, crossShardReader: crossShard.crossShardReader } : {}),
|
|
228
|
+
auth: { identity: request?.identity ?? null, userId: request?.userId ?? null },
|
|
229
|
+
exec: buildExec(database),
|
|
230
|
+
schema: schema as unknown as D1CtxDbOptions["schema"],
|
|
231
|
+
});
|
|
232
|
+
},
|
|
233
|
+
}
|
|
234
|
+
: {}),`
|
|
235
|
+
] : [],
|
|
236
|
+
...options.hasHyperdriveGlobal ? [
|
|
237
|
+
` ...(this.hyperdriveGlobalDeclaration
|
|
238
|
+
? {
|
|
239
|
+
hyperdriveGlobal: (rawEnv: Record<string, unknown>, request?: { identity?: Record<string, unknown>; userId?: string | null }) => {
|
|
240
|
+
const env = rawEnv as Env;
|
|
241
|
+
const exec = this.hyperdriveGlobalDeclaration?.exec(env) as SqlExec | undefined;
|
|
242
|
+
|
|
243
|
+
if (!exec) {
|
|
244
|
+
return undefined;
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
const origin = this.hyperdriveGlobalDeclaration?.origin?.(env);
|
|
248
|
+
const crossShard = origin
|
|
249
|
+
? createCrossShardRelationCapabilities({ identity: request?.identity, origin, userId: request?.userId ?? undefined })
|
|
250
|
+
: undefined;
|
|
251
|
+
|
|
252
|
+
return createHyperdriveGlobalCtxDb({
|
|
253
|
+
...(crossShard ? { crossShardCounter: crossShard.crossShardCounter, crossShardReader: crossShard.crossShardReader } : {}),
|
|
254
|
+
auth: { identity: request?.identity ?? null, userId: request?.userId ?? null },
|
|
255
|
+
engine: this.hyperdriveGlobalDeclaration?.engine as HyperdriveEngine,
|
|
256
|
+
exec,
|
|
257
|
+
schema: schema as unknown as SqlCtxDbOptions["schema"],
|
|
258
|
+
});
|
|
259
|
+
},
|
|
260
|
+
}
|
|
261
|
+
: {}),`
|
|
262
|
+
] : [],
|
|
263
|
+
...options.hasScheduler ? [
|
|
264
|
+
` ...(this.schedulerDeclaration
|
|
265
|
+
? {
|
|
266
|
+
scheduler: (rawEnv: Record<string, unknown>) => {
|
|
267
|
+
const env = rawEnv as Env;
|
|
268
|
+
const namespace = this.schedulerDeclaration?.namespace(env);
|
|
269
|
+
const origin = this.schedulerDeclaration?.origin?.(env);
|
|
270
|
+
|
|
271
|
+
return namespace && origin ? createScheduler({ namespace, originUrl: origin }) : undefined;
|
|
272
|
+
},
|
|
273
|
+
}
|
|
274
|
+
: {}),`
|
|
275
|
+
] : [],
|
|
276
|
+
...options.hasStorage ? [` ...(this.storageDeclaration ? { storage: (rawEnv: Record<string, unknown>) => this.resolveStorage(rawEnv as Env) } : {}),`] : [],
|
|
277
|
+
...hasAnyLongTail(options) ? [` ...this.shardExtras,`] : []
|
|
278
|
+
];
|
|
279
|
+
return entries.length > 0 ? `
|
|
280
|
+
${entries.join("\n")}
|
|
281
|
+
` : "";
|
|
282
|
+
};
|
|
283
|
+
const buildWorkerOptionLines = (options) => [
|
|
284
|
+
...options.hasScheduler ? [
|
|
285
|
+
` if (this.schedulerDeclaration) {
|
|
286
|
+
options.schedulerDO = this.schedulerDeclaration.namespace(env);
|
|
287
|
+
}`
|
|
288
|
+
] : [],
|
|
289
|
+
...options.hasWorkflow ? [
|
|
290
|
+
// Resolve the Workflows REST client from the request env so the studio's
|
|
291
|
+
// \`/_lunora/admin/workflows*\` proxy can read instance/step state; returns
|
|
292
|
+
// undefined (→ "not configured") until the CF account id + API token are set.
|
|
293
|
+
` options.workflowsClient = (workflowEnv) => {
|
|
294
|
+
const source = workflowEnv as Record<string, unknown>;
|
|
295
|
+
const accountId = source["CLOUDFLARE_ACCOUNT_ID"];
|
|
296
|
+
const apiToken = source["CLOUDFLARE_API_TOKEN"];
|
|
297
|
+
|
|
298
|
+
return typeof accountId === "string" && accountId !== "" && typeof apiToken === "string" && apiToken !== ""
|
|
299
|
+
? createWorkflowsRestClient({ accountId, apiToken })
|
|
300
|
+
: undefined;
|
|
301
|
+
};`
|
|
302
|
+
] : [],
|
|
303
|
+
...options.hasGlobal ? [
|
|
304
|
+
` if (this.globalDeclaration) {
|
|
305
|
+
const database = this.globalDeclaration.d1(env);
|
|
306
|
+
|
|
307
|
+
if (database) {
|
|
308
|
+
options.d1 = database;
|
|
309
|
+
options.globalIntrospector = buildGlobalIntrospector(database);
|
|
310
|
+
}
|
|
311
|
+
}`
|
|
312
|
+
] : [],
|
|
313
|
+
...options.hasStorage ? [
|
|
314
|
+
` if (this.storageDeclaration) {
|
|
315
|
+
Object.assign(options, this.buildStorageAdmin(env));
|
|
316
|
+
}`
|
|
317
|
+
] : [],
|
|
318
|
+
...options.hasAuth ? [
|
|
319
|
+
` if (this.authDeclaration) {
|
|
320
|
+
options.authHandler = (request) => {
|
|
321
|
+
const auth = getAuth();
|
|
322
|
+
|
|
323
|
+
return auth ? handleAuthRequest(auth, request) : Promise.resolve(undefined);
|
|
324
|
+
};
|
|
325
|
+
options.resolveIdentity = async (request) => {
|
|
326
|
+
const auth = getAuth();
|
|
327
|
+
|
|
328
|
+
if (!auth) {
|
|
329
|
+
return null;
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
const session = await auth.api.getSession({ headers: (request as Request).headers });
|
|
333
|
+
|
|
334
|
+
return session?.user?.id ? { userId: session.user.id } : null;
|
|
335
|
+
};
|
|
336
|
+
const authInstance = getAuth();
|
|
337
|
+
|
|
338
|
+
options.authAdmin = authInstance ? createAuthAdmin(authInstance) : undefined;
|
|
339
|
+
}`
|
|
340
|
+
] : []
|
|
341
|
+
];
|
|
342
|
+
const buildBaseWorkerOptions = (options) => [
|
|
343
|
+
` cronJobs: LUNORA_CRONS,`,
|
|
344
|
+
` functions: LUNORA_FUNCTIONS,`,
|
|
345
|
+
...options.wantsOpenApi ? [` openApiSpec,`] : [],
|
|
346
|
+
...options.wantsOpenRpc ? [` openRpcSpec,`] : [],
|
|
347
|
+
` routes: this.routeMap,`,
|
|
348
|
+
` shardDO: this.shardSelector?.(env) ?? (undefined as unknown as ShardNamespaceLike),`
|
|
349
|
+
];
|
|
350
|
+
const buildStorageHelpers = (hasStorage) => hasStorage ? `
|
|
351
|
+
/** Resolve the storage capability (single or multi-bucket) for the DO side. */
|
|
352
|
+
private resolveStorage(env: Env): Storage | undefined {
|
|
353
|
+
const declaration = this.storageDeclaration;
|
|
354
|
+
|
|
355
|
+
if (!declaration) {
|
|
356
|
+
return undefined;
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
const defaultBucket = declaration.bucket(env);
|
|
360
|
+
|
|
361
|
+
if (!defaultBucket) {
|
|
362
|
+
return undefined;
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
const make = (bucket: R2BucketLike): Storage =>
|
|
366
|
+
createStorage({ bucket, publicBaseUrl: declaration.publicBaseUrl?.(env), signingSecret: declaration.signingSecret?.(env) });
|
|
367
|
+
const extraEntries = Object.entries(declaration.buckets ?? {})
|
|
368
|
+
.map(([name, selector]) => [name, selector(env)] as const)
|
|
369
|
+
.filter((entry): entry is [string, R2BucketLike] => Boolean(entry[1]));
|
|
370
|
+
|
|
371
|
+
if (extraEntries.length === 0) {
|
|
372
|
+
return make(defaultBucket);
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
const map: Record<string, Storage> = { default: make(defaultBucket) };
|
|
376
|
+
|
|
377
|
+
for (const [name, bucket] of extraEntries) {
|
|
378
|
+
map[name] = make(bucket);
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
return createBucketStorage(map, { default: "default" });
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
/** Derive the studio file-browser admin functions from the same buckets \`.storage()\` declared. */
|
|
385
|
+
private buildStorageAdmin(env: Env): Partial<WorkerOptions> {
|
|
386
|
+
const declaration = this.storageDeclaration;
|
|
387
|
+
|
|
388
|
+
if (!declaration) {
|
|
389
|
+
return {};
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
const defaultBucket = declaration.bucket(env);
|
|
393
|
+
|
|
394
|
+
if (!defaultBucket) {
|
|
395
|
+
return {};
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
const make = (bucket: R2BucketLike): Storage =>
|
|
399
|
+
createStorage({ bucket, publicBaseUrl: declaration.publicBaseUrl?.(env), signingSecret: declaration.signingSecret?.(env) });
|
|
400
|
+
const buckets: Record<string, Storage> = { default: make(defaultBucket) };
|
|
401
|
+
|
|
402
|
+
for (const [name, selector] of Object.entries(declaration.buckets ?? {})) {
|
|
403
|
+
const bucket = selector(env);
|
|
404
|
+
|
|
405
|
+
if (bucket) {
|
|
406
|
+
buckets[name] = make(bucket);
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
const pick = (name?: string): Storage => buckets[name !== undefined && name !== "" ? name : "default"] ?? buckets.default;
|
|
411
|
+
const hasSigning = Boolean(declaration.publicBaseUrl?.(env) && declaration.signingSecret?.(env));
|
|
412
|
+
|
|
413
|
+
return {
|
|
414
|
+
storageBuckets: Object.keys(buckets),
|
|
415
|
+
storageDelete: (key: string, opts?: { bucket?: string }) => pick(opts?.bucket).delete(key),
|
|
416
|
+
storageList: (prefix?: string, opts?: { bucket?: string; cursor?: string; limit?: number }) => pick(opts?.bucket).list(prefix, opts),
|
|
417
|
+
storageSignedUrl: hasSigning
|
|
418
|
+
? (key: string, opts?: { bucket?: string; expiresInSeconds?: number }) => pick(opts?.bucket).getSignedUrl(key, { expiresInSeconds: opts?.expiresInSeconds })
|
|
419
|
+
: undefined,
|
|
420
|
+
storageUpload: (key: string, body: ArrayBuffer, opts?: { bucket?: string; contentType?: string }) => pick(opts?.bucket).upload(key, body, opts),
|
|
421
|
+
};
|
|
422
|
+
}
|
|
423
|
+
` : "";
|
|
424
|
+
const buildGlobalHelpers = (hasGlobal) => hasGlobal ? `
|
|
425
|
+
/** Adapt the raw D1 binding to \`@lunora/d1\`'s \`D1Exec\` (reads via \`all\`, writes via \`run\`). */
|
|
426
|
+
const buildExec = (database: D1DatabaseLike): D1Exec => ({
|
|
427
|
+
all: async (sql, parameters) => {
|
|
428
|
+
const result = await database
|
|
429
|
+
.prepare(sql)
|
|
430
|
+
.bind(...parameters)
|
|
431
|
+
.all<Record<string, unknown>>();
|
|
432
|
+
|
|
433
|
+
return result.results;
|
|
434
|
+
},
|
|
435
|
+
run: async (sql, parameters) => {
|
|
436
|
+
await database
|
|
437
|
+
.prepare(sql)
|
|
438
|
+
.bind(...parameters)
|
|
439
|
+
.run();
|
|
440
|
+
},
|
|
441
|
+
});
|
|
442
|
+
|
|
443
|
+
/** Introspect \`.global()\` (D1-backed) tables for the studio's global data browser. */
|
|
444
|
+
const buildGlobalIntrospector = (database: D1DatabaseLike): GlobalIntrospector => {
|
|
445
|
+
const exec = buildExec(database);
|
|
446
|
+
|
|
447
|
+
return {
|
|
448
|
+
facetColumn: (options) => facetGlobalColumn(exec, schema as never, options),
|
|
449
|
+
listTables: () => listGlobalTables(exec, schema as never),
|
|
450
|
+
readTablePage: (options) => readGlobalTablePage(exec, schema as never, options),
|
|
451
|
+
};
|
|
452
|
+
};
|
|
453
|
+
` : "";
|
|
454
|
+
const buildExportedTypes = (options) => [
|
|
455
|
+
...options.hasAuth ? ["AuthDeclaration"] : [],
|
|
456
|
+
"ComposedApp",
|
|
457
|
+
...options.hasGlobal ? ["GlobalDeclaration"] : [],
|
|
458
|
+
...options.hasScheduler ? ["SchedulerDeclaration"] : [],
|
|
459
|
+
"Selector",
|
|
460
|
+
...options.hasStorage ? ["StorageDeclaration"] : []
|
|
461
|
+
].toSorted((a, b) => a.localeCompare(b)).join(", ");
|
|
462
|
+
const emitApp = (options) => {
|
|
463
|
+
const { hasAuth } = options;
|
|
464
|
+
const declarationBlocks = buildDeclarationBlocks(options);
|
|
465
|
+
const workerOptionLines = buildWorkerOptionLines(options);
|
|
466
|
+
const authState = hasAuth ? ` let auth: LunoraAuth | null = null;
|
|
467
|
+
` : "";
|
|
468
|
+
const ensureAuthBlock = hasAuth ? `
|
|
469
|
+
const ensureAuth = async (env: Env): Promise<void> => {
|
|
470
|
+
if (!this.authDeclaration || auth) {
|
|
471
|
+
return;
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
auth = createAuth({ ...this.authDeclaration.options(env), database: lunoraD1Adapter(this.authDeclaration.d1(env) as never) });
|
|
475
|
+
// Apply the better-auth schema lazily on first request (raw-D1 Kysely
|
|
476
|
+
// migrator). For production run the migrate command ahead of deploy.
|
|
477
|
+
await ensureMigrated(createAuth({ ...this.authDeclaration.options(env), database: this.authDeclaration.d1(env) as never }));
|
|
478
|
+
};
|
|
479
|
+
` : "";
|
|
480
|
+
const ensureAuthCall = hasAuth ? `
|
|
481
|
+
await ensureAuth(env);` : "";
|
|
482
|
+
const getAuthArgument = hasAuth ? `() => auth` : `() => null`;
|
|
483
|
+
const getAuthParameter = hasAuth ? `getAuth: () => LunoraAuth | null` : `_getAuth: () => null`;
|
|
484
|
+
const buildWorkerLine = options.hasFramework ? ` const buildWorker = (env: Env): LunoraWorker =>
|
|
485
|
+
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}));`;
|
|
486
|
+
const assembleParameter = options.hasFramework ? `host?: FrameworkHostHandler` : ``;
|
|
487
|
+
const buildTerminals = ` /** Materialise the standalone Cloudflare worker + \`ShardDO\` class. */
|
|
488
|
+
public build(): ComposedApp {
|
|
489
|
+
return this.assemble();
|
|
490
|
+
}${options.hasFramework ? `
|
|
491
|
+
|
|
492
|
+
/** 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\`). */
|
|
493
|
+
public buildFrameworkWorker(host: FrameworkHostHandler): ComposedApp {
|
|
494
|
+
return this.assemble(host);
|
|
495
|
+
}` : ``}`;
|
|
496
|
+
return `${GENERATED_HEADER}${buildImportLines(options).join("\n")}
|
|
497
|
+
|
|
498
|
+
/** Read a value off the per-request \`env\`. Returns \`undefined\` to leave the capability unconfigured (its \`ctx.*\`/admin surface stays a clear-error stub). */
|
|
499
|
+
type Selector<Env, T> = (env: Env) => T | undefined;
|
|
500
|
+
${hasAnyLongTail(options) ? `
|
|
501
|
+
/** The generated \`createShardDO\` config — the long-tail \`.ai()\` / \`.kv()\` / … methods pass straight through to it. */
|
|
502
|
+
type ShardConfig = NonNullable<Parameters<typeof createShardDO>[0]>;
|
|
503
|
+
` : ""}
|
|
504
|
+
${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. */
|
|
505
|
+
interface ComposedApp extends LunoraWorker {
|
|
506
|
+
/** Cloudflare Email Routing entry — present only when \`.onEmail(...)\` was configured. */
|
|
507
|
+
email?: (message: unknown, env: unknown, context: ExecutionContextLike) => Promise<void>;
|
|
508
|
+
/** The generated shard Durable Object class — re-export it as a named export so wrangler can bind it. */
|
|
509
|
+
ShardDO: ReturnType<typeof createShardDO>;
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
/**
|
|
513
|
+
* Fluent worker-composition builder. Records each capability declaration, then
|
|
514
|
+
* \`.build()\` fans them into the DO-side \`createShardDO\` factory and the
|
|
515
|
+
* worker-side \`createWorker\` options — constructing the worker lazily on the
|
|
516
|
+
* first request so per-isolate singletons are built once.
|
|
517
|
+
*/
|
|
518
|
+
class AppBuilder<Env extends Record<string, unknown>> {
|
|
519
|
+
${buildFieldLines(options).join("\n")}
|
|
520
|
+
|
|
521
|
+
private emailHandler?: (env: Env) => (message: unknown, env: unknown, context: ExecutionContextLike) => Promise<void>;
|
|
522
|
+
|
|
523
|
+
${buildMethodBlocks(options).join("\n\n")}
|
|
524
|
+
|
|
525
|
+
${buildTerminals}
|
|
526
|
+
|
|
527
|
+
/** Build the shard DO + compose the worker (standalone or framework-hosted), wrapping the lazy per-isolate singletons + auth init. */
|
|
528
|
+
private assemble(${assembleParameter}): ComposedApp {
|
|
529
|
+
const ShardDO = createShardDO({${buildShardFactoryBody(options)}});
|
|
530
|
+
|
|
531
|
+
// Per-isolate singletons: the worker (and auth instance) are expensive to
|
|
532
|
+
// build, so the first request constructs them and every later request on
|
|
533
|
+
// the same isolate reuses them.
|
|
534
|
+
let worker: LunoraWorker | null = null;
|
|
535
|
+
${authState}${ensureAuthBlock}
|
|
536
|
+
${buildWorkerLine}
|
|
537
|
+
|
|
538
|
+
const composed: ComposedApp = {
|
|
539
|
+
ShardDO,
|
|
540
|
+
fetch: async (request: Request, rawEnv: unknown, context: ExecutionContextLike): Promise<Response> => {
|
|
541
|
+
const env = rawEnv as Env;${ensureAuthCall}
|
|
542
|
+
worker ??= buildWorker(env);
|
|
543
|
+
|
|
544
|
+
return worker.fetch(request, rawEnv, context);
|
|
545
|
+
},
|
|
546
|
+
scheduled: async (controller: ScheduledControllerLike, rawEnv: unknown, context: ExecutionContextLike): Promise<void> => {
|
|
547
|
+
worker ??= buildWorker(rawEnv as Env);
|
|
548
|
+
|
|
549
|
+
return worker.scheduled(controller, rawEnv, context);
|
|
550
|
+
},
|
|
551
|
+
serverQuery: (request, rawEnv, reference, args, options) => {
|
|
552
|
+
worker ??= buildWorker(rawEnv as Env);
|
|
553
|
+
|
|
554
|
+
return worker.serverQuery(request, rawEnv, reference, args, options);
|
|
555
|
+
},
|
|
556
|
+
};
|
|
557
|
+
|
|
558
|
+
if (this.emailHandler) {
|
|
559
|
+
const handler = this.emailHandler;
|
|
560
|
+
|
|
561
|
+
composed.email = (message, rawEnv, context) => handler(rawEnv as Env)(message, rawEnv, context);
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
return composed;
|
|
565
|
+
}
|
|
566
|
+
${buildStorageHelpers(options.hasStorage)}
|
|
567
|
+
/** Fan the recorded declarations into the worker-side \`createWorker\` options. */
|
|
568
|
+
private buildWorkerOptions(env: Env, ${getAuthParameter}): WorkerOptions {
|
|
569
|
+
const options: WorkerOptions = {
|
|
570
|
+
${buildBaseWorkerOptions(options).join("\n")}
|
|
571
|
+
};
|
|
572
|
+
|
|
573
|
+
if (this.adminToken) {
|
|
574
|
+
options.adminToken = this.adminToken(env);
|
|
575
|
+
}
|
|
576
|
+
|
|
577
|
+
${workerOptionLines.join("\n\n")}${workerOptionLines.length > 0 ? "\n\n" : ""} for (const fn of this.extendFns) {
|
|
578
|
+
Object.assign(options, fn(env));
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
return options;
|
|
582
|
+
}
|
|
583
|
+
}
|
|
584
|
+
${buildGlobalHelpers(options.hasGlobal)}
|
|
585
|
+
/** Start composing the app. Chain the capability methods, then \`.build()\`. */
|
|
586
|
+
const defineApp = <Env extends Record<string, unknown>>(): AppBuilder<Env> => new AppBuilder<Env>();
|
|
587
|
+
|
|
588
|
+
export { AppBuilder, defineApp };
|
|
589
|
+
export type { ${buildExportedTypes(options)} };
|
|
590
|
+
`;
|
|
591
|
+
};
|
|
592
|
+
|
|
593
|
+
export { emitApp };
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { runAdvisor } from '@lunora/advisor';
|
|
2
|
+
|
|
3
|
+
const flattenIndexes = (table) => [
|
|
4
|
+
...table.indexes.map((index) => {
|
|
5
|
+
return { fields: index.fields, kind: "index", name: index.name, unique: index.unique };
|
|
6
|
+
}),
|
|
7
|
+
...table.searchIndexes.map((index) => {
|
|
8
|
+
return { fields: [index.field, ...index.filterFields ?? []], kind: "search", name: index.name };
|
|
9
|
+
}),
|
|
10
|
+
...table.rankIndexes.map((index) => {
|
|
11
|
+
return { fields: [...index.sortBy.map((key) => key.field), ...index.partitionBy ?? []], kind: "rank", name: index.name };
|
|
12
|
+
}),
|
|
13
|
+
...table.vectorIndexes.filter((index) => index.field !== void 0).map((index) => {
|
|
14
|
+
return { fields: [index.field], kind: "vector", name: index.name };
|
|
15
|
+
})
|
|
16
|
+
];
|
|
17
|
+
const toAdvisorSchema = (schema) => {
|
|
18
|
+
return {
|
|
19
|
+
tables: schema.tables.map((table) => {
|
|
20
|
+
return {
|
|
21
|
+
externallyManaged: table.externallyManaged ?? false,
|
|
22
|
+
fields: Object.keys(table.shape),
|
|
23
|
+
indexes: flattenIndexes(table),
|
|
24
|
+
name: table.name,
|
|
25
|
+
relations: table.relations.map((relation) => {
|
|
26
|
+
return {
|
|
27
|
+
field: relation.field,
|
|
28
|
+
kind: relation.kind,
|
|
29
|
+
name: relation.name,
|
|
30
|
+
onDelete: relation.onDelete,
|
|
31
|
+
references: relation.references,
|
|
32
|
+
table: relation.table
|
|
33
|
+
};
|
|
34
|
+
})
|
|
35
|
+
};
|
|
36
|
+
})
|
|
37
|
+
};
|
|
38
|
+
};
|
|
39
|
+
const lintSchema = (schema, queries = [], inserts, authApiCalls, rlsProcedures, containers, workflows, workflowCalls, maskProcedures, nondeterministicCalls, procedureProtections, argumentValidators, secretLiterals, sqlInterpolations, adminRoutes) => runAdvisor(
|
|
40
|
+
{
|
|
41
|
+
adminRoutes,
|
|
42
|
+
argValidators: argumentValidators,
|
|
43
|
+
authApiCalls,
|
|
44
|
+
containers,
|
|
45
|
+
inserts,
|
|
46
|
+
maskProcedures,
|
|
47
|
+
nondeterministicCalls,
|
|
48
|
+
procedureProtections,
|
|
49
|
+
queries,
|
|
50
|
+
rlsProcedures,
|
|
51
|
+
schema: toAdvisorSchema(schema),
|
|
52
|
+
secretLiterals,
|
|
53
|
+
sqlInterpolations,
|
|
54
|
+
workflowCalls,
|
|
55
|
+
workflows
|
|
56
|
+
},
|
|
57
|
+
{ source: "static" }
|
|
58
|
+
);
|
|
59
|
+
const formatAdvisories = (findings) => {
|
|
60
|
+
if (findings.length === 0) {
|
|
61
|
+
return "";
|
|
62
|
+
}
|
|
63
|
+
const header = `@lunora/codegen: ${String(findings.length)} schema advisor finding${findings.length === 1 ? "" : "s"}`;
|
|
64
|
+
const lines = findings.map((finding) => ` [${finding.level}] ${finding.name}: ${finding.detail}`);
|
|
65
|
+
return [header, ...lines].join("\n");
|
|
66
|
+
};
|
|
67
|
+
|
|
68
|
+
export { formatAdvisories, lintSchema };
|