@lunora/codegen 1.0.0-alpha.54 → 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.
- package/dist/index.d.mts +65 -6
- package/dist/index.d.ts +65 -6
- package/dist/index.mjs +1 -38
- package/dist/packem_shared/AGENTS_FILENAME-BesaDYkL.mjs +1 -0
- package/dist/packem_shared/CONTAINERS_FILENAME-CFwdyaCI.mjs +1 -0
- package/dist/packem_shared/CodegenDiagnosticError-DPezpZTz.mjs +1 -0
- package/dist/packem_shared/FLAGS_FILENAME-DW5oGq1q.mjs +1 -0
- package/dist/packem_shared/GENERATED_HEADER-C94PuLpQ.mjs +1 -0
- package/dist/packem_shared/LUNORA_ERROR_CODES-Um9hC1gr.mjs +1 -0
- package/dist/packem_shared/MUTATORS_FILENAME-BKKPROzu.mjs +1 -0
- package/dist/packem_shared/NOTIFY_FILENAME-C-c7Lg-U.mjs +1 -0
- package/dist/packem_shared/OPENRPC_VERSION-DpV3v2W8.mjs +3 -0
- package/dist/packem_shared/QUEUES_FILENAME-CSE6i-ld.mjs +1 -0
- package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-DJsxljOQ.mjs +3 -0
- package/dist/packem_shared/SCHEMA_SNAPSHOT_VERSION-Bpf1FGMG.mjs +15 -0
- package/dist/packem_shared/SHAPES_FILENAME-DTkSJSsg.mjs +1 -0
- package/dist/packem_shared/WORKFLOWS_FILENAME-Bk5upkGM.mjs +1 -0
- package/dist/packem_shared/buildOpenApiDocument-DXX1G3GZ.mjs +3 -0
- package/dist/packem_shared/discover-ast-CezKqEhE.mjs +1 -0
- package/dist/packem_shared/discoverAuthApiCalls-DOfSQqVK.mjs +1 -0
- package/dist/packem_shared/discoverCrons-B09_uEuL.mjs +1 -0
- package/dist/packem_shared/discoverFunctions-BdibLQmc.mjs +1 -0
- package/dist/packem_shared/discoverHttpRoutes-BOWz6y_n.mjs +1 -0
- package/dist/packem_shared/discoverInserts-BtteTyNy.mjs +1 -0
- package/dist/packem_shared/discoverMaskProcedures-COPmwMBm.mjs +1 -0
- package/dist/packem_shared/discoverMigrations-iGMlp9YJ.mjs +1 -0
- package/dist/packem_shared/discoverNondeterministicCalls-Dmgc4QBx.mjs +1 -0
- package/dist/packem_shared/discoverQueries-CcfuGKHh.mjs +1 -0
- package/dist/packem_shared/discoverR2sqlCalls-CjZKvg-N.mjs +1 -0
- package/dist/packem_shared/discoverRlsMetadata-BXmNOgry.mjs +1 -0
- package/dist/packem_shared/discoverSandboxUsage-CDdBqWcM.mjs +1 -0
- package/dist/packem_shared/discoverSchema-m2voTncu.mjs +1 -0
- package/dist/packem_shared/discoverStorageRulesMetadata-b71cJJHz.mjs +1 -0
- package/dist/packem_shared/emit-Dr6XSLfW.mjs +2104 -0
- package/dist/packem_shared/emitApp-B671iU7r.mjs +413 -0
- package/dist/packem_shared/formatAdvisories-DZvv-0MG.mjs +2 -0
- package/dist/packem_shared/parse-validator-CSDlMEvE.mjs +1 -0
- package/dist/packem_shared/paths-BmX5O1sG.mjs +1 -0
- package/dist/packem_shared/redact-CQ8-to6l.mjs +1 -0
- package/dist/packem_shared/schemaFromIr-R1ZFzVyy.mjs +1 -0
- package/package.json +3 -3
- package/dist/packem_shared/AGENTS_FILENAME-Cxx7wiSs.mjs +0 -158
- package/dist/packem_shared/CONTAINERS_FILENAME-DjpXMqhp.mjs +0 -224
- package/dist/packem_shared/CodegenDiagnosticError-DyQ5FwkM.mjs +0 -24
- package/dist/packem_shared/FLAGS_FILENAME-D5igzqwR.mjs +0 -139
- package/dist/packem_shared/GENERATED_HEADER-C8tAvxqP.mjs +0 -4
- package/dist/packem_shared/LUNORA_ERROR_CODES-DvTLozCu.mjs +0 -68
- package/dist/packem_shared/MUTATORS_FILENAME-BZOfUhlY.mjs +0 -81
- package/dist/packem_shared/NOTIFY_FILENAME-CK2IrsrP.mjs +0 -152
- package/dist/packem_shared/OPENRPC_VERSION-DvDChMhC.mjs +0 -60
- package/dist/packem_shared/QUEUES_FILENAME-Xv6Vy-Ku.mjs +0 -145
- package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME--TKFIHmr.mjs +0 -3597
- package/dist/packem_shared/SCHEMA_SNAPSHOT_VERSION-D0ARY6rL.mjs +0 -249
- package/dist/packem_shared/SHAPES_FILENAME-DOhPGi-6.mjs +0 -94
- package/dist/packem_shared/WORKFLOWS_FILENAME-Dtuzvluc.mjs +0 -158
- package/dist/packem_shared/buildOpenApiDocument-DCQSLuFc.mjs +0 -262
- package/dist/packem_shared/discover-ast-CT6BgBr4.mjs +0 -13
- package/dist/packem_shared/discoverAuthApiCalls-Dhwgf4J4.mjs +0 -62
- package/dist/packem_shared/discoverCrons-UbQLLmMS.mjs +0 -286
- package/dist/packem_shared/discoverFunctions-COG_Xkyz.mjs +0 -544
- package/dist/packem_shared/discoverHttpRoutes-CVXWZkzo.mjs +0 -139
- package/dist/packem_shared/discoverInserts-DdWnXmLS.mjs +0 -61
- package/dist/packem_shared/discoverMaskProcedures-BG58_fw3.mjs +0 -273
- package/dist/packem_shared/discoverMigrations-Bw1U01zr.mjs +0 -97
- package/dist/packem_shared/discoverNondeterministicCalls-BbXEFZUT.mjs +0 -122
- package/dist/packem_shared/discoverQueries-CDmxu2ET.mjs +0 -62
- package/dist/packem_shared/discoverR2sqlCalls-Bn7QVv7J.mjs +0 -80
- package/dist/packem_shared/discoverRlsMetadata-D9uN35no.mjs +0 -280
- package/dist/packem_shared/discoverSandboxUsage-B5jDU6Bt.mjs +0 -38
- package/dist/packem_shared/discoverSchema-BJp5_T4o.mjs +0 -906
- package/dist/packem_shared/discoverStorageRulesMetadata-BqMhuEjo.mjs +0 -97
- package/dist/packem_shared/emit-DIbr7U31.mjs +0 -3884
- package/dist/packem_shared/emitApp-DbMM8iHe.mjs +0 -706
- package/dist/packem_shared/formatAdvisories-Cans5TWS.mjs +0 -131
- package/dist/packem_shared/parse-validator-BDGV8iue.mjs +0 -144
- package/dist/packem_shared/paths-BRd6JHuF.mjs +0 -11
- package/dist/packem_shared/redact-oTmsol5A.mjs +0 -33
- package/dist/packem_shared/schemaFromIr-DTYsLBaA.mjs +0 -57
|
@@ -0,0 +1,413 @@
|
|
|
1
|
+
import{c as w,w as E}from"./emit-Dr6XSLfW.mjs";const D=e=>`has${e.charAt(0).toUpperCase()}${e.slice(1)}`,m=w.map(({appMethod:e,key:t})=>[D(t),e.method,e.configKey,e.doc]),g=e=>m.some(([t])=>e[t]),A=e=>e?['import * as lunoraIdentityContract from "../identity.js";']:[],x=(e,t)=>e?['import type { CreateAccessResolverOptions } from "@lunora/cloudflare-access";',`import { createAccessResolver${t?", composeResolvers":""} } from "@lunora/cloudflare-access";`]:[],R=e=>e?['import { createKvIntrospectorFromEnv } from "@lunora/bindings/kv";']:[],O=e=>e?['import notifyConfig from "../notify.js";']:[],k=e=>(e.emailAgents?.length??0)>0,C=e=>k(e)?['import { dispatchAgentEmail } from "@lunora/agent/inbound";']:[],L=e=>k(e)?['import * as lunoraAgentDefinitions from "../agents.js";']:[],T=e=>{const{hasAccess:t,hasAuth:r,hasFramework:a,hasGlobal:n,hasHyperdriveGlobal:o,hasKv:l,hasQueue:s,hasScheduler:u,hasStorage:d,hasWorkflow:h,useUmbrella:c,wantsOpenApi:p,wantsOpenRpc:v}=e,i=c?"lunorash/runtime":"@lunora/runtime",b=["ExecutionContextLike","LunoraWorker","Route","ScheduledControllerLike","ShardNamespaceLike","WorkerOptions"];n&&b.push("GlobalIntrospector"),a&&b.push("FrameworkHostHandler");const f=[...n||o?["createCrossShardRelationCapabilities"]:[],"createWorker","resolveLogArchiveFromEnv",...a?["withFrameworkWorker"]:[]].join(", ");return[...r?['import type { LunoraAuth, LunoraAuthOptions } from "@lunora/auth";','import { createAuth, createAuthAdmin, createAuthAuditReader, d1Executor, ensureMigrated, handleAuthRequest, lunoraD1Adapter } from "@lunora/auth";']:[],...x(t,r),...n?['import type { D1CtxDbOptions, D1DatabaseLike, D1Exec } from "@lunora/d1";','import { createD1CtxDb, facetGlobalColumn, listGlobalTables, readGlobalTablePage } from "@lunora/d1";']:[],...o?['import type { HyperdriveEngine } from "@lunora/hyperdrive/global";','import { createHyperdriveGlobalCtxDb } from "@lunora/hyperdrive/global";','import type { SqlCtxDbOptions, SqlExec } from "@lunora/sql-store";']:[],...R(l),...u?['import type { DurableObjectNamespaceLike } from "@lunora/scheduler";','import { createScheduler } from "@lunora/scheduler";']:[],...d?['import type { R2BucketLike, Storage } from "@lunora/storage";','import { createBucketStorage, createStorage } from "@lunora/storage";']:[],...h?['import { createWorkflowsRestClient } from "@lunora/workflow";']:[],...C(e),`import type { ${[...b].toSorted((S,y)=>S.localeCompare(y)).join(", ")} } from "${i}";`,`import { ${f} } from "${i}";`,"",...A(e.identity),...L(e),...n||o?['import schema from "../schema.js";']:[],...O(e.hasNotify),'import { LUNORA_CRONS } from "./crons.js";','import { LUNORA_FUNCTIONS } from "./functions.js";',...s?['import { createQueueCaptureSink, dispatchQueueBatch, shouldCaptureQueue } from "@lunora/queue";','import { LUNORA_QUEUE_REGISTRY } from "./queues.js";']:[],...p?['import { openApiSpec } from "./openapi.js";']:[],...v?['import { openRpcSpec } from "./openrpc.js";']:[],'import { createShardDO } from "./shard.js";']},$=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. */
|
|
2
|
+
interface StorageDeclaration<Env> {
|
|
3
|
+
/** The default R2 bucket binding (the bare \`ctx.storage\`). */
|
|
4
|
+
bucket: Selector<Env, R2BucketLike>;
|
|
5
|
+
/** Extra named buckets, reached via \`ctx.storage.bucket("name")\` and the studio's bucket picker. */
|
|
6
|
+
buckets?: Record<string, Selector<Env, R2BucketLike>>;
|
|
7
|
+
/** Public base URL signed/public object URLs resolve against. */
|
|
8
|
+
publicBaseUrl?: Selector<Env, string>;
|
|
9
|
+
/** HMAC secret for signed URLs. */
|
|
10
|
+
signingSecret?: Selector<Env, string>;
|
|
11
|
+
}`]:[],...e.hasScheduler?["/** `.scheduler(...)` declaration — the `SchedulerDO` namespace plus the worker origin its callbacks dispatch back to. Backs `ctx.scheduler` AND the studio's scheduled-jobs view. */\ninterface SchedulerDeclaration<Env> {\n /** The `SchedulerDO` namespace binding (typically `env.SCHEDULER`). */\n namespace: Selector<Env, DurableObjectNamespaceLike & ShardNamespaceLike>;\n /** The worker origin the `SchedulerDO` dispatches HTTP job callbacks back to. */\n origin?: Selector<Env, string>;\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 D1 binding its SQL adapter reads. 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`). */\n d1: Selector<Env, unknown>;\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>;"]:[]," private adminToken?: Selector<Env, string>;",...e.hasAuth?[" private authDeclaration?: AuthDeclaration<Env>;"]:[]," private readonly extendFns: ((env: Env, derived: Readonly<WorkerOptions>) => Partial<WorkerOptions>)[] = [];",...e.hasGlobal?[" private globalDeclaration?: GlobalDeclaration<Env>;"]:[],...e.hasHyperdriveGlobal?[" private hyperdriveGlobalDeclaration?: HyperdriveGlobalDeclaration<Env>;"]:[]," 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.hasStorage?[" private storageDeclaration?: StorageDeclaration<Env>;"]:[]],j=e=>m.filter(([t])=>e[t]).map(([,t,r,a])=>` /** ${a} */
|
|
12
|
+
public ${t}(factory: NonNullable<ShardConfig["${r}"]>): this {
|
|
13
|
+
this.shardExtras.${r} = factory;
|
|
14
|
+
|
|
15
|
+
return this;
|
|
16
|
+
}`),I=e=>[...e.hasAccess?[" /** 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). */\n public access(selector: Selector<Env, CreateAccessResolverOptions>): this {\n this.accessSelector = selector;\n\n return this;\n }"]:[],` /** Bearer token gating the \`/_lunora/admin/*\` endpoints the studio calls. */
|
|
17
|
+
public admin(selector: Selector<Env, string>): this {
|
|
18
|
+
this.adminToken = selector;
|
|
19
|
+
|
|
20
|
+
return this;
|
|
21
|
+
}`,...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). */
|
|
22
|
+
public auth(declaration: AuthDeclaration<Env>): this {
|
|
23
|
+
this.authDeclaration = declaration;
|
|
24
|
+
|
|
25
|
+
return this;
|
|
26
|
+
}`]:[]," /** 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. */
|
|
27
|
+
public global(declaration: GlobalDeclaration<Env>): this {
|
|
28
|
+
this.globalDeclaration = declaration;
|
|
29
|
+
|
|
30
|
+
return this;
|
|
31
|
+
}`]:[],...e.hasHyperdriveGlobal?[` /** Back \`.global({ backend: "hyperdrive" })\` tables with a Postgres/MySQL database via Hyperdrive — wires reactive \`ctx.db\` routing through the shared store core. */
|
|
32
|
+
public hyperdriveGlobal(declaration: HyperdriveGlobalDeclaration<Env>): this {
|
|
33
|
+
this.hyperdriveGlobalDeclaration = declaration;
|
|
34
|
+
|
|
35
|
+
return this;
|
|
36
|
+
}`]:[],` /** Cloudflare Email Routing entry — exposes the top-level \`email\` handler. */
|
|
37
|
+
public onEmail(handler: (env: Env) => (message: unknown, env: unknown, context: ExecutionContextLike) => Promise<void>): this {
|
|
38
|
+
this.emailHandler = handler;
|
|
39
|
+
|
|
40
|
+
return this;
|
|
41
|
+
}`,` /** 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. */
|
|
42
|
+
public route(key: string, handler: Route): this {
|
|
43
|
+
this.routeMap[key] = handler;
|
|
44
|
+
|
|
45
|
+
return this;
|
|
46
|
+
}`,...e.hasScheduler?[` /** Wire the \`SchedulerDO\` — backs \`ctx.scheduler\` and the studio's scheduled-jobs view. */
|
|
47
|
+
public scheduler(declaration: SchedulerDeclaration<Env>): this {
|
|
48
|
+
this.schedulerDeclaration = declaration;
|
|
49
|
+
|
|
50
|
+
return this;
|
|
51
|
+
}`]:[],` /** The shard Durable Object namespace (typically \`env.SHARD\`) — required: every app routes RPC + WebSocket traffic through it. */
|
|
52
|
+
public shard(selector: Selector<Env, ShardNamespaceLike>): this {
|
|
53
|
+
this.shardSelector = selector;
|
|
54
|
+
|
|
55
|
+
return this;
|
|
56
|
+
}`,...e.hasStorage?[` /** Wire R2 storage — backs \`ctx.storage\` (incl. multi-bucket) and the studio file browser, from one declaration. */
|
|
57
|
+
public storage(declaration: StorageDeclaration<Env>): this {
|
|
58
|
+
this.storageDeclaration = declaration;
|
|
59
|
+
|
|
60
|
+
return this;
|
|
61
|
+
}`]:[],...j(e)],W=e=>{const t=[...e.hasGlobal?[` ...(this.globalDeclaration
|
|
62
|
+
? {
|
|
63
|
+
d1: (rawEnv: Record<string, unknown>, request?: { identity?: Record<string, unknown>; userId?: string | null }) => {
|
|
64
|
+
const env = rawEnv as Env;
|
|
65
|
+
const database = this.globalDeclaration?.d1(env);
|
|
66
|
+
|
|
67
|
+
if (!database) {
|
|
68
|
+
return undefined;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
const origin = this.globalDeclaration?.origin?.(env);
|
|
72
|
+
const crossShard = origin
|
|
73
|
+
? createCrossShardRelationCapabilities({ identity: request?.identity, origin, userId: request?.userId ?? undefined })
|
|
74
|
+
: undefined;
|
|
75
|
+
|
|
76
|
+
return createD1CtxDb({
|
|
77
|
+
...(crossShard ? { crossShardCounter: crossShard.crossShardCounter, crossShardReader: crossShard.crossShardReader } : {}),
|
|
78
|
+
auth: { identity: request?.identity ?? null, userId: request?.userId ?? null },
|
|
79
|
+
exec: buildExec(database),
|
|
80
|
+
schema: schema as unknown as D1CtxDbOptions["schema"],
|
|
81
|
+
});
|
|
82
|
+
},
|
|
83
|
+
}
|
|
84
|
+
: {}),`]:[],...e.hasHyperdriveGlobal?[` ...(this.hyperdriveGlobalDeclaration
|
|
85
|
+
? {
|
|
86
|
+
hyperdriveGlobal: (rawEnv: Record<string, unknown>, request?: { identity?: Record<string, unknown>; userId?: string | null }) => {
|
|
87
|
+
const env = rawEnv as Env;
|
|
88
|
+
const exec = this.hyperdriveGlobalDeclaration?.exec(env) as SqlExec | undefined;
|
|
89
|
+
|
|
90
|
+
if (!exec) {
|
|
91
|
+
return undefined;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
const origin = this.hyperdriveGlobalDeclaration?.origin?.(env);
|
|
95
|
+
const crossShard = origin
|
|
96
|
+
? createCrossShardRelationCapabilities({ identity: request?.identity, origin, userId: request?.userId ?? undefined })
|
|
97
|
+
: undefined;
|
|
98
|
+
|
|
99
|
+
return createHyperdriveGlobalCtxDb({
|
|
100
|
+
...(crossShard ? { crossShardCounter: crossShard.crossShardCounter, crossShardReader: crossShard.crossShardReader } : {}),
|
|
101
|
+
auth: { identity: request?.identity ?? null, userId: request?.userId ?? null },
|
|
102
|
+
engine: this.hyperdriveGlobalDeclaration?.engine as HyperdriveEngine,
|
|
103
|
+
exec,
|
|
104
|
+
schema: schema as unknown as SqlCtxDbOptions["schema"],
|
|
105
|
+
});
|
|
106
|
+
},
|
|
107
|
+
}
|
|
108
|
+
: {}),`]:[],...e.hasScheduler?[` ...(this.schedulerDeclaration
|
|
109
|
+
? {
|
|
110
|
+
scheduler: (rawEnv: Record<string, unknown>) => {
|
|
111
|
+
const env = rawEnv as Env;
|
|
112
|
+
const namespace = this.schedulerDeclaration?.namespace(env);
|
|
113
|
+
const origin = this.schedulerDeclaration?.origin?.(env);
|
|
114
|
+
|
|
115
|
+
return namespace && origin ? createScheduler({${e.jurisdiction?` jurisdiction: ${JSON.stringify(e.jurisdiction)},`:""} namespace, originUrl: origin }) : undefined;
|
|
116
|
+
},
|
|
117
|
+
}
|
|
118
|
+
: {}),`]:[],...e.hasStorage?[" ...(this.storageDeclaration ? { storage: (rawEnv: Record<string, unknown>) => this.resolveStorage(rawEnv as Env) } : {}),"]:[],...g(e)?[" ...this.shardExtras,"]:[]];return t.length>0?`
|
|
119
|
+
${t.join(`
|
|
120
|
+
`)}
|
|
121
|
+
`:""},N=e=>[...e.hasScheduler?[` if (this.schedulerDeclaration) {
|
|
122
|
+
options.schedulerDO = this.schedulerDeclaration.namespace(env);
|
|
123
|
+
}`]:[],...e.hasWorkflow?[` options.workflowsClient = (workflowEnv) => {
|
|
124
|
+
const source = workflowEnv as Record<string, unknown>;
|
|
125
|
+
const accountId = source["CLOUDFLARE_ACCOUNT_ID"];
|
|
126
|
+
const apiToken = source["CLOUDFLARE_API_TOKEN"];
|
|
127
|
+
|
|
128
|
+
return typeof accountId === "string" && accountId !== "" && typeof apiToken === "string" && apiToken !== ""
|
|
129
|
+
? createWorkflowsRestClient({ accountId, apiToken })
|
|
130
|
+
: undefined;
|
|
131
|
+
};`]:[],...e.hasGlobal?[` if (this.globalDeclaration) {
|
|
132
|
+
const database = this.globalDeclaration.d1(env);
|
|
133
|
+
|
|
134
|
+
if (database) {
|
|
135
|
+
options.d1 = database;
|
|
136
|
+
options.globalIntrospector = buildGlobalIntrospector(database);
|
|
137
|
+
}
|
|
138
|
+
}`]:[],...e.hasStorage?[` if (this.storageDeclaration) {
|
|
139
|
+
Object.assign(options, this.buildStorageAdmin(env));
|
|
140
|
+
}`]:[],...e.hasKv?[" options.kvIntrospector = createKvIntrospectorFromEnv(env);"]:[],...e.hasNotify?[" options.notifySubscriptionStore = notifyConfig.store ? notifyConfig.store(env) : undefined;"]:[]," options.logArchive = resolveLogArchiveFromEnv(env);",...e.hasAuth?[` if (this.authDeclaration) {
|
|
141
|
+
options.authHandler = (request) => {
|
|
142
|
+
const auth = getAuth();
|
|
143
|
+
|
|
144
|
+
return auth ? handleAuthRequest(auth, request) : Promise.resolve(undefined);
|
|
145
|
+
};
|
|
146
|
+
options.resolveIdentity = async (request) => {
|
|
147
|
+
const auth = getAuth();
|
|
148
|
+
|
|
149
|
+
if (!auth) {
|
|
150
|
+
return null;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
const session = await auth.api.getSession({ headers: (request as Request).headers });
|
|
154
|
+
|
|
155
|
+
return session?.user?.id ? { userId: session.user.id } : null;
|
|
156
|
+
};
|
|
157
|
+
const authInstance = getAuth();
|
|
158
|
+
|
|
159
|
+
options.authAdmin = authInstance ? createAuthAdmin(authInstance) : undefined;
|
|
160
|
+
options.authAuditReader = createAuthAuditReader(d1Executor(this.authDeclaration.d1(env) as never));
|
|
161
|
+
}`]:[],...e.hasAccess?[e.hasAuth?` if (this.accessSelector) {
|
|
162
|
+
const accessResolver = createAccessResolver(this.accessSelector(env));
|
|
163
|
+
const fallback = options.resolveIdentity;
|
|
164
|
+
|
|
165
|
+
options.resolveIdentity = fallback ? composeResolvers(accessResolver, fallback) : accessResolver;
|
|
166
|
+
}`:` if (this.accessSelector) {
|
|
167
|
+
options.resolveIdentity = createAccessResolver(this.accessSelector(env));
|
|
168
|
+
}`]:[],...e.voiceAgents&&e.voiceAgents.length>0?[` options.voiceAgents = {
|
|
169
|
+
${e.voiceAgents.map(t=>` ${JSON.stringify(t.exportName)}: (env as Record<string, unknown>)[${JSON.stringify(t.bindingName)}] as ShardNamespaceLike,`).join(`
|
|
170
|
+
`)}
|
|
171
|
+
};`]:[]],G=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): 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>,"," }),"]:[]," routes: this.routeMap,"," shardDO: this.shardSelector?.(env) ?? (undefined as unknown as ShardNamespaceLike),"],B=e=>e?`
|
|
172
|
+
/** Resolve the storage capability (single or multi-bucket) for the DO side. */
|
|
173
|
+
private resolveStorage(env: Env): Storage | undefined {
|
|
174
|
+
const declaration = this.storageDeclaration;
|
|
175
|
+
|
|
176
|
+
if (!declaration) {
|
|
177
|
+
return undefined;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
const defaultBucket = declaration.bucket(env);
|
|
181
|
+
|
|
182
|
+
if (!defaultBucket) {
|
|
183
|
+
return undefined;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
const make = (bucket: R2BucketLike): Storage =>
|
|
187
|
+
createStorage({ bucket, publicBaseUrl: declaration.publicBaseUrl?.(env), signingSecret: declaration.signingSecret?.(env) });
|
|
188
|
+
const extraEntries = Object.entries(declaration.buckets ?? {})
|
|
189
|
+
.map(([name, selector]) => [name, selector(env)] as const)
|
|
190
|
+
.filter((entry): entry is [string, R2BucketLike] => Boolean(entry[1]));
|
|
191
|
+
|
|
192
|
+
if (extraEntries.length === 0) {
|
|
193
|
+
return make(defaultBucket);
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
const map: Record<string, Storage> = { default: make(defaultBucket) };
|
|
197
|
+
|
|
198
|
+
for (const [name, bucket] of extraEntries) {
|
|
199
|
+
map[name] = make(bucket);
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
return createBucketStorage(map, { default: "default" });
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/** Derive the studio file-browser admin functions from the same buckets \`.storage()\` declared. */
|
|
206
|
+
private buildStorageAdmin(env: Env): Partial<WorkerOptions> {
|
|
207
|
+
const declaration = this.storageDeclaration;
|
|
208
|
+
|
|
209
|
+
if (!declaration) {
|
|
210
|
+
return {};
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
const defaultBucket = declaration.bucket(env);
|
|
214
|
+
|
|
215
|
+
if (!defaultBucket) {
|
|
216
|
+
return {};
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
const make = (bucket: R2BucketLike): Storage =>
|
|
220
|
+
createStorage({ bucket, publicBaseUrl: declaration.publicBaseUrl?.(env), signingSecret: declaration.signingSecret?.(env) });
|
|
221
|
+
const buckets: Record<string, Storage> = { default: make(defaultBucket) };
|
|
222
|
+
|
|
223
|
+
for (const [name, selector] of Object.entries(declaration.buckets ?? {})) {
|
|
224
|
+
const bucket = selector(env);
|
|
225
|
+
|
|
226
|
+
if (bucket) {
|
|
227
|
+
buckets[name] = make(bucket);
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
const pick = (name?: string): Storage => buckets[name !== undefined && name !== "" ? name : "default"] ?? buckets.default;
|
|
232
|
+
const hasSigning = Boolean(declaration.publicBaseUrl?.(env) && declaration.signingSecret?.(env));
|
|
233
|
+
|
|
234
|
+
return {
|
|
235
|
+
storageBuckets: Object.keys(buckets),
|
|
236
|
+
storageDelete: (key: string, opts?: { bucket?: string }) => pick(opts?.bucket).delete(key),
|
|
237
|
+
storageList: (prefix?: string, opts?: { bucket?: string; cursor?: string; limit?: number }) => pick(opts?.bucket).list(prefix, opts),
|
|
238
|
+
storageSignedUrl: hasSigning
|
|
239
|
+
? (key: string, opts?: { bucket?: string; expiresInSeconds?: number }) => pick(opts?.bucket).getSignedUrl(key, { expiresInSeconds: opts?.expiresInSeconds })
|
|
240
|
+
: undefined,
|
|
241
|
+
storageUpload: (key: string, body: ArrayBuffer, opts?: { bucket?: string; contentType?: string }) => pick(opts?.bucket).upload(key, body, opts),
|
|
242
|
+
};
|
|
243
|
+
}
|
|
244
|
+
`:"",H=e=>e?`
|
|
245
|
+
/** Adapt the raw D1 binding to \`@lunora/d1\`'s \`D1Exec\` (reads via \`all\`, writes via \`run\`). */
|
|
246
|
+
const buildExec = (database: D1DatabaseLike): D1Exec => ({
|
|
247
|
+
all: async (sql, parameters) => {
|
|
248
|
+
const result = await database
|
|
249
|
+
.prepare(sql)
|
|
250
|
+
.bind(...parameters)
|
|
251
|
+
.all<Record<string, unknown>>();
|
|
252
|
+
|
|
253
|
+
return result.results;
|
|
254
|
+
},
|
|
255
|
+
run: async (sql, parameters) => {
|
|
256
|
+
await database
|
|
257
|
+
.prepare(sql)
|
|
258
|
+
.bind(...parameters)
|
|
259
|
+
.run();
|
|
260
|
+
},
|
|
261
|
+
});
|
|
262
|
+
|
|
263
|
+
/** Introspect \`.global()\` (D1-backed) tables for the studio's global data browser. */
|
|
264
|
+
const buildGlobalIntrospector = (database: D1DatabaseLike): GlobalIntrospector => {
|
|
265
|
+
const exec = buildExec(database);
|
|
266
|
+
|
|
267
|
+
return {
|
|
268
|
+
facetColumn: (options) => facetGlobalColumn(exec, schema as never, options),
|
|
269
|
+
listTables: () => listGlobalTables(exec, schema as never),
|
|
270
|
+
readTablePage: (options) => readGlobalTablePage(exec, schema as never, options),
|
|
271
|
+
};
|
|
272
|
+
};
|
|
273
|
+
`:"",U=e=>[...e.hasAuth?["AuthDeclaration"]:[],"ComposedApp",...e.hasGlobal?["GlobalDeclaration"]:[],...e.hasScheduler?["SchedulerDeclaration"]:[],"Selector",...e.hasStorage?["StorageDeclaration"]:[]].toSorted((t,r)=>t.localeCompare(r)).join(", "),F=e=>{const{hasAuth:t}=e,r=$(e),a=N(e),n=t?` let auth: LunoraAuth | null = null;
|
|
274
|
+
`:"",o=t?`
|
|
275
|
+
const ensureAuth = async (env: Env): Promise<void> => {
|
|
276
|
+
if (!this.authDeclaration || auth) {
|
|
277
|
+
return;
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
auth = createAuth({ ...this.authDeclaration.options(env), database: lunoraD1Adapter(this.authDeclaration.d1(env) as never) });
|
|
281
|
+
// Apply the better-auth schema lazily on first request (raw-D1 Kysely
|
|
282
|
+
// migrator). For production run the migrate command ahead of deploy.
|
|
283
|
+
await ensureMigrated(createAuth({ ...this.authDeclaration.options(env), database: this.authDeclaration.d1(env) as never }));
|
|
284
|
+
};
|
|
285
|
+
`:"",l=t?`
|
|
286
|
+
await ensureAuth(env);`:"",s=t?"() => auth":"() => null",u=t?"getAuth: () => LunoraAuth | null":"_getAuth: () => null",d=e.hasFramework?` const buildWorker = (env: Env): LunoraWorker =>
|
|
287
|
+
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=e.hasFramework?"host?: FrameworkHostHandler":"",c=e.emailAgents??[],p=c.length>0?` composed.email = dispatchAgentEmail([
|
|
288
|
+
${c.map(i=>` { agent: lunoraAgentDefinitions.${i.exportName}, binding: ${JSON.stringify(i.bindingName)} },`).join(`
|
|
289
|
+
`)}
|
|
290
|
+
]);
|
|
291
|
+
|
|
292
|
+
`:"",v=` /** Materialise the standalone Cloudflare worker + \`ShardDO\` class. */
|
|
293
|
+
public build(): ComposedApp {
|
|
294
|
+
return this.assemble();
|
|
295
|
+
}${e.hasFramework?"\n\n /** Compose Lunora's realtime plane INTO a meta-framework's Cloudflare handler (SvelteKit/Astro/Nuxt). The framework `host` serves everything except the reserved `/_lunora/*` endpoints; pass the adapter-emitted worker (e.g. SvelteKit's `_worker.js`, Astro's `handle`). */\n public buildFrameworkWorker(host: FrameworkHostHandler): ComposedApp {\n return this.assemble(host);\n }":""}`;return`${E}${T(e).join(`
|
|
296
|
+
`)}
|
|
297
|
+
|
|
298
|
+
/** Read a value off the per-request \`env\`. Returns \`undefined\` to leave the capability unconfigured (its \`ctx.*\`/admin surface stays a clear-error stub). */
|
|
299
|
+
type Selector<Env, T> = (env: Env) => T | undefined;
|
|
300
|
+
${g(e)?"\n/** The generated `createShardDO` config — the long-tail `.ai()` / `.kv()` / … methods pass straight through to it. */\ntype ShardConfig = NonNullable<Parameters<typeof createShardDO>[0]>;\n":""}
|
|
301
|
+
${r.join(`
|
|
302
|
+
|
|
303
|
+
`)}${r.length>0?`
|
|
304
|
+
|
|
305
|
+
`:""}/** The composed app: a Cloudflare module worker (\`fetch\` / \`scheduled\` / optional \`email\`) plus the \`ShardDO\` class binding. */
|
|
306
|
+
interface ComposedApp extends LunoraWorker {
|
|
307
|
+
/** Cloudflare Email Routing entry — present only when \`.onEmail(...)\` was configured. */
|
|
308
|
+
email?: (message: unknown, env: unknown, context: ExecutionContextLike) => Promise<void>;
|
|
309
|
+
/** The generated shard Durable Object class — re-export it as a named export so wrangler can bind it. */
|
|
310
|
+
ShardDO: ReturnType<typeof createShardDO>;
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
/**
|
|
314
|
+
* Fluent worker-composition builder. Records each capability declaration, then
|
|
315
|
+
* \`.build()\` fans them into the DO-side \`createShardDO\` factory and the
|
|
316
|
+
* worker-side \`createWorker\` options — constructing the worker lazily on the
|
|
317
|
+
* first request so per-isolate singletons are built once.
|
|
318
|
+
*/
|
|
319
|
+
class AppBuilder<Env extends object> {
|
|
320
|
+
${q(e).join(`
|
|
321
|
+
`)}
|
|
322
|
+
|
|
323
|
+
private emailHandler?: (env: Env) => (message: unknown, env: unknown, context: ExecutionContextLike) => Promise<void>;
|
|
324
|
+
|
|
325
|
+
${I(e).join(`
|
|
326
|
+
|
|
327
|
+
`)}
|
|
328
|
+
|
|
329
|
+
${v}
|
|
330
|
+
|
|
331
|
+
/** Build the shard DO + compose the worker (standalone or framework-hosted), wrapping the lazy per-isolate singletons + auth init. */
|
|
332
|
+
private assemble(${h}): ComposedApp {
|
|
333
|
+
const ShardDO = createShardDO({${W(e)}});
|
|
334
|
+
|
|
335
|
+
// Per-isolate singletons: the worker (and auth instance) are expensive to
|
|
336
|
+
// build, so the first request constructs them and every later request on
|
|
337
|
+
// the same isolate reuses them.
|
|
338
|
+
let worker: LunoraWorker | null = null;
|
|
339
|
+
${n}${o}
|
|
340
|
+
${d}
|
|
341
|
+
|
|
342
|
+
const composed: ComposedApp = {
|
|
343
|
+
ShardDO,
|
|
344
|
+
fetch: async (request: Request, rawEnv: unknown, context: ExecutionContextLike): Promise<Response> => {
|
|
345
|
+
const env = rawEnv as Env;${l}
|
|
346
|
+
worker ??= buildWorker(env);
|
|
347
|
+
|
|
348
|
+
return worker.fetch(request, rawEnv, context);
|
|
349
|
+
},
|
|
350
|
+
scheduled: async (controller: ScheduledControllerLike, rawEnv: unknown, context: ExecutionContextLike): Promise<void> => {
|
|
351
|
+
worker ??= buildWorker(rawEnv as Env);
|
|
352
|
+
|
|
353
|
+
return worker.scheduled(controller, rawEnv, context);
|
|
354
|
+
},
|
|
355
|
+
serverQuery: (request, rawEnv, reference, args, options) => {
|
|
356
|
+
worker ??= buildWorker(rawEnv as Env);
|
|
357
|
+
|
|
358
|
+
return worker.serverQuery(request, rawEnv, reference, args, options);
|
|
359
|
+
},${e.hasQueue?`
|
|
360
|
+
queue: async (batch: unknown, rawEnv: unknown, context: ExecutionContextLike): Promise<void> => {
|
|
361
|
+
worker ??= buildWorker(rawEnv as Env);
|
|
362
|
+
|
|
363
|
+
return worker.queue?.(batch, rawEnv, context);
|
|
364
|
+
},`:""}
|
|
365
|
+
};
|
|
366
|
+
|
|
367
|
+
${p} if (this.emailHandler) {
|
|
368
|
+
const handler = this.emailHandler;
|
|
369
|
+
|
|
370
|
+
composed.email = (message, rawEnv, context) => handler(rawEnv as Env)(message, rawEnv, context);
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
return composed;
|
|
374
|
+
}
|
|
375
|
+
${B(e.hasStorage)}
|
|
376
|
+
/** Fan the recorded declarations into the worker-side \`createWorker\` options. */
|
|
377
|
+
private buildWorkerOptions(env: Env, ${u}): WorkerOptions {
|
|
378
|
+
const options: WorkerOptions = {
|
|
379
|
+
${G(e).join(`
|
|
380
|
+
`)}
|
|
381
|
+
};
|
|
382
|
+
|
|
383
|
+
if (this.adminToken) {
|
|
384
|
+
options.adminToken = this.adminToken(env);
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
${a.join(`
|
|
388
|
+
|
|
389
|
+
`)}${a.length>0?`
|
|
390
|
+
|
|
391
|
+
`:""} for (const fn of this.extendFns) {
|
|
392
|
+
Object.assign(options, fn(env, { ...options }));
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
return options;
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
${H(e.hasGlobal)}
|
|
399
|
+
/**
|
|
400
|
+
* Start composing the app. Chain the capability methods, then \`.build()\`.
|
|
401
|
+
*
|
|
402
|
+
* \`Env\` is constrained to \`object\`, not \`Record<string, unknown>\`: an \`interface Env\`
|
|
403
|
+
* — which is what wrangler's generated \`worker-configuration.d.ts\` gives you, and
|
|
404
|
+
* what any app with its own bindings declares — is NOT assignable to an index
|
|
405
|
+
* signature, so the stricter bound forced every real app to write
|
|
406
|
+
* \`type AppEnv = Env & Record<string, unknown>\`. The builder only ever reads \`env\`
|
|
407
|
+
* through the selectors you pass it, so the looser bound costs nothing.
|
|
408
|
+
*/
|
|
409
|
+
const defineApp = <Env extends object>(): AppBuilder<Env> => new AppBuilder<Env>();
|
|
410
|
+
|
|
411
|
+
export { AppBuilder, defineApp };
|
|
412
|
+
export type { ${U(e)} };
|
|
413
|
+
`};export{F as emitApp};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{runAdvisor as i}from"@lunora/advisor";const n=e=>[...e.indexes.map(s=>({fields:s.fields,kind:"index",name:s.name,unique:s.unique})),...e.searchIndexes.map(s=>({fields:[s.field,...s.filterFields??[]],kind:"search",name:s.name})),...e.rankIndexes.map(s=>({fields:[...s.sortBy.map(a=>a.field),...s.partitionBy??[]],kind:"rank",name:s.name})),...e.vectorIndexes.filter(s=>s.field!==void 0).map(s=>({fields:[s.field],kind:"vector",name:s.name})),...(e.geoIndexes??[]).map(s=>({fields:[s.field],kind:"geo",name:s.name}))],r=e=>{const s={};for(const[a,t]of Object.entries(e.shape))s[a]=t.kind==="optional"?t.inner?.kind??"optional":t.kind;return s},l=e=>({rlsMode:e.rlsMode,tables:e.tables.map(s=>({externallyManaged:s.externallyManaged??!1,externalSource:s.externalSource?{hasReconcile:s.externalSource.hasReconcile??!1,hasSoftDelete:s.externalSource.hasSoftDelete??!1,hasTenantBy:s.externalSource.hasTenantBy,mode:s.externalSource.mode,unanalyzable:s.externalSource.unanalyzable}:void 0,columnKinds:r(s),fields:Object.keys(s.shape),indexes:n(s),isPublic:s.isPublic??!1,name:s.name,relations:s.relations.map(a=>({field:a.field,kind:a.kind,name:a.name,onDelete:a.onDelete,references:a.references,table:a.table})),shardKind:typeof s.shardMode=="string"?s.shardMode:"shardBy",softDelete:s.softDelete,ttl:s.ttl}))}),o=e=>e.map(s=>({exportName:s.exportName,file:`lunora/${s.filePath}.ts`,table:s.table})),d=e=>i({adminRoutes:e.adminRoutes,aiRawRuns:e.aiRawRuns,aiToolSideEffects:e.aiToolSideEffects,argumentDerivedFetches:e.argumentDerivedFetches,argValidators:e.argumentValidators,authApiCalls:e.authApiCalls,authConfigs:e.authConfigs,browserUrlAccesses:e.browserUrlAccesses,configCalls:e.configCalls,containerKeyAccesses:e.containerKeyAccesses,containerOverrides:e.containerOverrides,containers:e.containers,exportSinks:e.exportSinks,failOpenGuards:e.failOpenGuards,flagSecurityDefaults:e.flagSecurityDefaults,geoIndexUsages:e.geoIndexUsages,httpActionGuards:e.httpActionGuards,httpHeaderWrites:e.httpHeaderWrites,identityClaimReads:e.identityClaimReads,imageDeliveryUrlAccesses:e.imageDeliveryUrlAccesses,inserts:e.inserts,kvKeyAccesses:e.kvKeyAccesses,mailRecipientAccesses:e.mailRecipientAccesses,maskProcedures:e.maskProcedures,maskStrategies:e.maskStrategies,mutatorWrites:e.mutatorWrites,nondeterministicCalls:e.nondeterministicCalls,normalizeIdAuthorizations:e.normalizeIdAuthorizations,notifyCalls:e.notifyCalls,notifyConfig:e.notifyConfig,ownerFieldWrites:e.ownerFieldWrites,unrestrictedWhereBranches:e.unrestrictedWhereBranches,paymentWebhooks:e.paymentWebhooks,privilegedDispatches:e.privilegedDispatches,procedureProtections:e.procedureProtections,queries:e.queries??[],queues:e.queues,r2sqlCalls:e.r2sqlCalls,ratelimitKeySelectors:e.ratelimitKeySelectors,rawRowReturns:e.rawRowReturns,relationLoads:e.relationLoads,rlsProcedures:e.rlsProcedures,schema:l(e.schema),secretLiterals:e.secretLiterals,shapes:e.shapes===void 0?void 0:o(e.shapes),softDeleteReads:e.softDeleteReads,sqlInterpolations:e.sqlInterpolations,storageKeyAccesses:e.storageKeyAccesses,storageUploads:e.storageUploads,vectorNamespaceAccesses:e.vectorNamespaceAccesses,workflowCalls:e.workflowCalls,workflows:e.workflows,wranglerVariables:e.wranglerVariables},{source:"static"}),m=e=>{if(e.length===0)return"";const s=`@lunora/codegen: ${String(e.length)} schema advisor finding${e.length===1?"":"s"}`,a=e.map(t=>` [${t.level}] ${t.name}: ${t.detail}`);return[s,...a].join(`
|
|
2
|
+
`)};export{m as formatAdvisories,d as lintSchema};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as l}from"@lunora/errors";import{Node as r}from"ts-morph";const c=/^[A-Za-z_$][\w$]*$/u,d=new Set(["$defaultFn","$onUpdateFn","$type","default","defaultNow","nullable","unique"]),p=(n,t)=>{const e={notNull:!0,...n.column};switch(t){case"$defaultFn":case"default":case"defaultNow":{e.hasDefault=!0;break}case"$onUpdateFn":{e.hasOnUpdate=!0;break}case"$type":break;case"nullable":{e.notNull=!1;break}case"unique":{e.unique=!0;break}}return{...n,column:e}},k=new Set(["any","bigint","boolean","bytes","date","geoPoint","null","number","string","timestamp"]),f=new Set(["check","meta"]),o=n=>r.isCallExpression(n)?b(n):{kind:"any",sourceText:n.getText()},g=n=>{const t={};for(const e of n.getProperties()){if(!r.isPropertyAssignment(e))continue;const s=e.getNameNode();if(r.isComputedPropertyName(s))continue;const i=e.getInitializer();if(!i)continue;const a=e.getName();if(!c.test(a))throw new l("INTERNAL",`@lunora/codegen: field name is not a valid JS identifier: ${JSON.stringify(a)}`);t[a]=o(i)}return t},u=(n,t)=>n&&r.isExpression(n)?o(n):t,m=n=>n===void 0?"undefined":r.isStringLiteral(n)||r.isNoSubstitutionTemplateLiteral(n)?JSON.stringify(n.getLiteralValue()):n.getText(),y=(n,t)=>{if(k.has(n))return{kind:n};const[e,s]=t;switch(n){case"array":return{inner:u(e,{kind:"any"}),kind:"array"};case"from":return{kind:"from"};case"id":return{kind:"id",tableName:e&&r.isStringLiteral(e)?e.getLiteralText():"_unknown_"};case"literal":return{kind:"literal",literalValue:m(e)};case"object":return e&&r.isObjectLiteralExpression(e)?{kind:"object",shape:g(e)}:{kind:"object",shape:{}};case"optional":return{inner:u(e,{kind:"any"}),kind:"optional"};case"record":return{keyType:u(e,{kind:"string"}),kind:"record",valueType:u(s,{kind:"any"})};case"storage":return e&&r.isStringLiteral(e)?{bucket:e.getLiteralText(),kind:"storage"}:{kind:"storage"};case"union":return{kind:"union",members:t.filter(i=>r.isExpression(i)).map(i=>o(i))};default:throw new l("INTERNAL",`Unsupported validator kind: ${n}`)}},b=n=>{const t=n.getExpression();if(!r.isPropertyAccessExpression(t))return{kind:"any",sourceText:n.getText()};const e=t.getName(),s=n.getArguments();if(d.has(e)){const i=t.getExpression(),a=r.isExpression(i)?o(i):{kind:"any"};return p(a,e)}if(f.has(e)){const i=t.getExpression(),a=r.isExpression(i)?o(i):{kind:"any"};return e==="check"?{...a,hasRefinement:!0}:a}return y(e,s)};export{g as d,o as s};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const a=/\/index$/u,l=/[^\dA-Za-z]/gu,c=e=>e.replace(a,"").replaceAll(l,"_");export{c as n};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const s=/[\w+/=-]{40,}/u,d=/[a-z]/u,i=/[A-Z]/u,n=/\d/u,k=/\b(?:[\da-f]{32,}|[\dA-F]{32,})\b/u,a=t=>{const e=s.exec(t)?.[0];return e===void 0?!1:d.test(e)&&i.test(e)&&n.test(e)},r=t=>k.test(t),u=/\b(?:sk|rk)_live_[\dA-Za-z]{20,}/u,_=/\bAKIA[\dA-Z]{16}\b/u,c=/\bgh[posru]_[\dA-Za-z]{36,}/u,A=/\bsk-[\dA-Za-z]{32,}/u,b=/\bxox[abprs]-[\dA-Za-z-]{10,}/u,o=/-----BEGIN(?: [A-Z]+)? PRIVATE KEY-----/u,h=[{kind:"stripe_live_key",test:t=>u.test(t)},{kind:"aws_access_key",test:t=>_.test(t)},{kind:"github_token",test:t=>c.test(t)},{kind:"openai_key",test:t=>A.test(t)},{kind:"slack_token",test:t=>b.test(t)},{kind:"private_key",test:t=>o.test(t)},{kind:"high_entropy",test:a},{kind:"hex_secret",test:r}],p=t=>h.find(e=>e.test(t))?.kind,E=t=>`${t.slice(0,4)}…(${String(t.length)} chars)`;export{h as SECRET_RULES,E as redact,p as secretKindOf};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const n=e=>{try{return JSON.parse(e)}catch{const t=e.trim();return t.length>=2&&(t.startsWith("'")||t.startsWith('"'))&&t.at(-1)===t[0]?t.slice(1,-1):t}},a=e=>{const t={};return e.column!==void 0&&(t.column={defaultValue:e.column.hasDefault===!0?null:void 0,notNull:e.column.notNull,unique:e.column.unique}),e.inner!==void 0&&(t.inner=a(e.inner)),e.members!==void 0&&(t.members=e.members.map(r=>a(r))),e.shape!==void 0&&(t.shape=Object.fromEntries(Object.entries(e.shape).map(([r,l])=>[r,a(l)]))),e.tableName!==void 0&&(t.tableName=e.tableName),e.literalValue!==void 0&&(t.value=n(e.literalValue)),e.keyType!==void 0&&(t.keyValidator=a(e.keyType)),e.valueType!==void 0&&(t.valueValidator=a(e.valueType)),{_meta:t,kind:e.kind}},i=e=>({tables:Object.fromEntries(e.tables.map(t=>[t.name,{shape:Object.fromEntries(Object.entries(t.shape).map(([r,l])=>[r,a(l)]))}]))});export{i as schemaFromIr};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/codegen",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.56",
|
|
4
4
|
"description": "Code generator for Lunora: emits _generated/{api,server,dataModel}.ts from your schema",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cloudflare",
|
|
@@ -46,8 +46,8 @@
|
|
|
46
46
|
"access": "public"
|
|
47
47
|
},
|
|
48
48
|
"dependencies": {
|
|
49
|
-
"@lunora/advisor": "1.0.0-alpha.
|
|
50
|
-
"@lunora/agent": "1.0.0-alpha.
|
|
49
|
+
"@lunora/advisor": "1.0.0-alpha.35",
|
|
50
|
+
"@lunora/agent": "1.0.0-alpha.11",
|
|
51
51
|
"@lunora/container": "1.0.0-alpha.16",
|
|
52
52
|
"@lunora/errors": "1.0.0-alpha.8",
|
|
53
53
|
"@lunora/queue": "1.0.0-alpha.10",
|
|
@@ -1,158 +0,0 @@
|
|
|
1
|
-
import { existsSync } from 'node:fs';
|
|
2
|
-
import { join } from 'node:path';
|
|
3
|
-
import { agentDefaultName, agentClassName, agentBindingName, voiceBindingName, voiceClassName } from '@lunora/agent/naming';
|
|
4
|
-
import { LunoraError } from '@lunora/errors';
|
|
5
|
-
import { Node, SyntaxKind } from 'ts-morph';
|
|
6
|
-
import { diagnosticAt } from './CodegenDiagnosticError-DyQ5FwkM.mjs';
|
|
7
|
-
|
|
8
|
-
const AGENTS_FILENAME = "agents.ts";
|
|
9
|
-
const isDefineAgent = (identifier) => {
|
|
10
|
-
const symbol = identifier.getSymbol();
|
|
11
|
-
if (!symbol) {
|
|
12
|
-
return identifier.getText() === "defineAgent";
|
|
13
|
-
}
|
|
14
|
-
for (const declaration of symbol.getDeclarations()) {
|
|
15
|
-
if (!Node.isImportSpecifier(declaration)) {
|
|
16
|
-
continue;
|
|
17
|
-
}
|
|
18
|
-
if (declaration.getImportDeclaration().getModuleSpecifierValue() !== "@lunora/agent") {
|
|
19
|
-
return false;
|
|
20
|
-
}
|
|
21
|
-
return declaration.getNameNode().getText() === "defineAgent";
|
|
22
|
-
}
|
|
23
|
-
return false;
|
|
24
|
-
};
|
|
25
|
-
const stringProperty = (expression, exportName, property) => {
|
|
26
|
-
if (Node.isStringLiteral(expression) || Node.isNoSubstitutionTemplateLiteral(expression)) {
|
|
27
|
-
return expression.getLiteralValue();
|
|
28
|
-
}
|
|
29
|
-
throw diagnosticAt(
|
|
30
|
-
expression,
|
|
31
|
-
`agent "${exportName}": \`${property}\` must be a static string literal — it is deploy configuration codegen writes into wrangler.jsonc`
|
|
32
|
-
);
|
|
33
|
-
};
|
|
34
|
-
const booleanProperty = (expression, exportName, property) => {
|
|
35
|
-
if (expression.getKind() === SyntaxKind.TrueKeyword) {
|
|
36
|
-
return true;
|
|
37
|
-
}
|
|
38
|
-
if (expression.getKind() === SyntaxKind.FalseKeyword) {
|
|
39
|
-
return false;
|
|
40
|
-
}
|
|
41
|
-
throw diagnosticAt(
|
|
42
|
-
expression,
|
|
43
|
-
`agent "${exportName}": \`${property}\` must be a static boolean literal — it is deploy configuration codegen writes into the ctx.agents wiring spec`
|
|
44
|
-
);
|
|
45
|
-
};
|
|
46
|
-
const agentFromCall = (call, exportName) => {
|
|
47
|
-
const argument = call.getArguments()[0];
|
|
48
|
-
if (!argument || !Node.isObjectLiteralExpression(argument)) {
|
|
49
|
-
throw diagnosticAt(call, `agent "${exportName}": defineAgent must be passed an inline object literal`);
|
|
50
|
-
}
|
|
51
|
-
const ir = {
|
|
52
|
-
bindingName: agentBindingName(exportName),
|
|
53
|
-
className: agentClassName(exportName),
|
|
54
|
-
exportName,
|
|
55
|
-
name: agentDefaultName(exportName)
|
|
56
|
-
};
|
|
57
|
-
const nameProperty = argument.getProperty("name");
|
|
58
|
-
if (nameProperty && Node.isPropertyAssignment(nameProperty)) {
|
|
59
|
-
ir.name = stringProperty(nameProperty.getInitializerOrThrow(), exportName, "name");
|
|
60
|
-
}
|
|
61
|
-
const publicRunProperty = argument.getProperty("publicRun");
|
|
62
|
-
if (publicRunProperty && Node.isPropertyAssignment(publicRunProperty) && booleanProperty(publicRunProperty.getInitializerOrThrow(), exportName, "publicRun")) {
|
|
63
|
-
ir.publicRun = true;
|
|
64
|
-
}
|
|
65
|
-
const voiceProperty = argument.getProperty("voice");
|
|
66
|
-
if (voiceProperty && Node.isPropertyAssignment(voiceProperty)) {
|
|
67
|
-
const voiceInitializer = voiceProperty.getInitializerOrThrow();
|
|
68
|
-
if (!Node.isObjectLiteralExpression(voiceInitializer)) {
|
|
69
|
-
throw diagnosticAt(
|
|
70
|
-
voiceInitializer,
|
|
71
|
-
`agent "${exportName}": \`voice\` must be an inline object literal — its presence tells codegen to emit the voice-session Durable Object`
|
|
72
|
-
);
|
|
73
|
-
}
|
|
74
|
-
ir.voice = true;
|
|
75
|
-
ir.voiceBindingName = voiceBindingName(exportName);
|
|
76
|
-
ir.voiceClassName = voiceClassName(exportName);
|
|
77
|
-
}
|
|
78
|
-
if (argument.getProperty("onEmail")) {
|
|
79
|
-
ir.onEmail = true;
|
|
80
|
-
}
|
|
81
|
-
return ir;
|
|
82
|
-
};
|
|
83
|
-
const unwrapToCallExpression = (node) => {
|
|
84
|
-
let current = node;
|
|
85
|
-
while (current && (Node.isAsExpression(current) || Node.isSatisfiesExpression(current) || Node.isParenthesizedExpression(current))) {
|
|
86
|
-
current = current.getExpression();
|
|
87
|
-
}
|
|
88
|
-
return current && Node.isCallExpression(current) ? current : void 0;
|
|
89
|
-
};
|
|
90
|
-
const agentsFromSource = (source) => {
|
|
91
|
-
const agents = [];
|
|
92
|
-
for (const declaration of source.getVariableDeclarations()) {
|
|
93
|
-
if (!declaration.isExported()) {
|
|
94
|
-
continue;
|
|
95
|
-
}
|
|
96
|
-
const call = unwrapToCallExpression(declaration.getInitializer());
|
|
97
|
-
if (!call) {
|
|
98
|
-
continue;
|
|
99
|
-
}
|
|
100
|
-
const callee = call.getExpression();
|
|
101
|
-
if (!Node.isIdentifier(callee) || !isDefineAgent(callee)) {
|
|
102
|
-
continue;
|
|
103
|
-
}
|
|
104
|
-
const nameNode = declaration.getNameNode();
|
|
105
|
-
if (!Node.isIdentifier(nameNode)) {
|
|
106
|
-
throw diagnosticAt(nameNode, "defineAgent exports must be plain named exports (no destructuring)");
|
|
107
|
-
}
|
|
108
|
-
agents.push(agentFromCall(call, nameNode.getText()));
|
|
109
|
-
}
|
|
110
|
-
return agents;
|
|
111
|
-
};
|
|
112
|
-
const assertUniqueNames = (agents) => {
|
|
113
|
-
const seenNames = /* @__PURE__ */ new Map();
|
|
114
|
-
const seenBindings = /* @__PURE__ */ new Map();
|
|
115
|
-
const seenClasses = /* @__PURE__ */ new Map();
|
|
116
|
-
for (const agent of agents) {
|
|
117
|
-
const priorName = seenNames.get(agent.name);
|
|
118
|
-
if (priorName !== void 0) {
|
|
119
|
-
throw new LunoraError(
|
|
120
|
-
"DUPLICATE_AGENT_NAME",
|
|
121
|
-
`Duplicate agent name "${agent.name}": produced by both "${priorName}" and "${agent.exportName}". Deployed agent names must be unique across the project.`,
|
|
122
|
-
{ status: 500 }
|
|
123
|
-
);
|
|
124
|
-
}
|
|
125
|
-
seenNames.set(agent.name, agent.exportName);
|
|
126
|
-
const priorBinding = seenBindings.get(agent.bindingName);
|
|
127
|
-
if (priorBinding !== void 0) {
|
|
128
|
-
throw new LunoraError(
|
|
129
|
-
"DUPLICATE_AGENT_BINDING",
|
|
130
|
-
`Duplicate agent binding "${agent.bindingName}": produced by both "${priorBinding}" and "${agent.exportName}". Agent export names must yield unique binding names.`,
|
|
131
|
-
{ status: 500 }
|
|
132
|
-
);
|
|
133
|
-
}
|
|
134
|
-
seenBindings.set(agent.bindingName, agent.exportName);
|
|
135
|
-
const priorClass = seenClasses.get(agent.className);
|
|
136
|
-
if (priorClass !== void 0) {
|
|
137
|
-
throw new LunoraError(
|
|
138
|
-
"DUPLICATE_AGENT_CLASS",
|
|
139
|
-
`Duplicate agent class "${agent.className}": produced by both "${priorClass}" and "${agent.exportName}". Agent export names must yield unique generated class names.`,
|
|
140
|
-
{ status: 500 }
|
|
141
|
-
);
|
|
142
|
-
}
|
|
143
|
-
seenClasses.set(agent.className, agent.exportName);
|
|
144
|
-
}
|
|
145
|
-
};
|
|
146
|
-
const discoverAgents = (project, lunoraDirectory) => {
|
|
147
|
-
const agentsPath = join(lunoraDirectory, AGENTS_FILENAME);
|
|
148
|
-
if (!existsSync(agentsPath)) {
|
|
149
|
-
return [];
|
|
150
|
-
}
|
|
151
|
-
const source = project.getSourceFile(agentsPath) ?? project.addSourceFileAtPath(agentsPath);
|
|
152
|
-
const agents = agentsFromSource(source);
|
|
153
|
-
agents.sort((a, b) => a.exportName.localeCompare(b.exportName));
|
|
154
|
-
assertUniqueNames(agents);
|
|
155
|
-
return agents;
|
|
156
|
-
};
|
|
157
|
-
|
|
158
|
-
export { AGENTS_FILENAME, discoverAgents };
|