@lunora/codegen 1.0.0-alpha.157 → 1.0.0-alpha.159
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.mjs +1 -1
- package/dist/packem_shared/{GENERATED_HEADER-_apO4IVc.mjs → GENERATED_HEADER-zxE5ds4T.mjs} +1 -1
- package/dist/packem_shared/{OPENRPC_VERSION-DWdTwXvO.mjs → OPENRPC_VERSION-BoFdEr0g.mjs} +1 -1
- package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-Lyu1_yTq.mjs +9 -0
- package/dist/packem_shared/{buildOpenApiDocument-DIboMAh6.mjs → buildOpenApiDocument-aQrg7YwH.mjs} +1 -1
- package/dist/packem_shared/{emit-B6ud4F_z.mjs → emit-BNdsZPcd.mjs} +67 -61
- package/dist/packem_shared/{emitApp-BSxrIa6e.mjs → emitApp-Dg93w6dv.mjs} +53 -22
- package/package.json +10 -10
- package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-B9OxLwqq.mjs +0 -9
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{A as S,G as
|
|
1
|
+
import{A as S,G as E}from"./emit-BNdsZPcd.mjs";const D=e=>`has${e.charAt(0).toUpperCase()}${e.slice(1)}`,v=S.map(({appMethod:e,key:t})=>[D(t),e.method,e.configKey,e.doc]),m=e=>v.some(([t])=>e[t]),x=e=>e?['import * as lunoraIdentityContract from "../identity.js";']:[],A=(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";']:[],C=e=>e?['import type { D1CtxDbOptions, D1DatabaseLike, D1Exec } from "@lunora/d1";','import { applyCdcChanges, createD1CtxDb, exportGlobalRows, facetGlobalColumn, importGlobalRows, listGlobalTables, readD1CdcChanges, readGlobalTablePage, retryingExec } from "@lunora/d1";']:[],O=e=>e?['import notifyConfig from "../notify.js";']:[],k=e=>(e.emailAgents?.length??0)>0,T=e=>k(e)?['import { dispatchAgentEmail } from "@lunora/agent/inbound";']:[],I=e=>k(e)?['import * as lunoraAgentDefinitions from "../agents.js";']:[],L=e=>{const{hasAccess:t,hasAuth:a,hasFramework:r,hasGlobal:n,hasHyperdriveGlobal:o,hasKvIntrospector:d,hasQueue:h,hasScheduler:i,hasStorage:u,hasWorkflow:p,useUmbrella:b,wantsOpenApi:l,wantsOpenRpc:g}=e,c=b?"lunorash/runtime":"@lunora/runtime",s=["ExecutionContextLike","HttpRouterLike","LunoraWorker","Route","ScheduledControllerLike","ShardNamespaceLike","WorkerOptions"];n&&s.push("GlobalIntrospector","AdminTableResolver"),r&&s.push("FrameworkHostHandler");const f=[...n||o?["createCrossShardRelationCapabilities"]:[],"createWorker","resolveLogArchiveFromEnv",...r?["withFrameworkWorker"]:[]].join(", ");return[...a?['import type { AuthNamespaceLike, LunoraAuth, LunoraAuthOptions } from "@lunora/auth";','import { createAuth, createAuthAdmin, createAuthAuditReader, createDoAuthWiring, d1Executor, ensureMigrated, handleAuthRequest, lunoraD1Adapter } from "@lunora/auth";']:[],...A(t,a),...C(n),...o?['import type { HyperdriveEngine } from "@lunora/hyperdrive/global";','import { createHyperdriveGlobalCtxDb } from "@lunora/hyperdrive/global";','import type { SqlCtxDbOptions, SqlExec } from "@lunora/sql-store";']:[],...R(d),...i?['import type { DurableObjectNamespaceLike } from "@lunora/scheduler";','import { createScheduler } from "@lunora/scheduler";']:[],...u?['import type { R2BucketLike, R2S3Credentials, Storage } from "@lunora/storage";','import { createBucketStorage, createStorage } from "@lunora/storage";']:[],...p?['import { createWorkflowsRestClient } from "@lunora/workflow";']:[],...T(e),`import type { ${[...s].toSorted((w,y)=>w.localeCompare(y)).join(", ")} } from "${c}";`,`import { ${f} } from "${c}";`,"",...x(e.identity),...I(e),...n||o?['import schema from "../schema.js";']:[],...O(e.hasNotify),'import { LUNORA_CRONS } from "./crons.js";','import { LUNORA_FUNCTIONS } from "./functions.js";',...h?['import { createQueueCaptureSink, dispatchQueueBatch, shouldCaptureQueue } from "@lunora/queue";','import { LUNORA_QUEUE_REGISTRY } from "./queues.js";']:[],...l?['import { openApiSpec } from "./openapi.js";']:[],...g?['import { openRpcSpec } from "./openrpc.js";']:[],'import { createShardDO } from "./shard.js";']},q=e=>[...e.hasStorage?['/** `.storage(...)` declaration — one bucket (required) plus optional extra named buckets and signed-URL config. Backs `ctx.storage` AND the studio file browser. */\ninterface StorageDeclaration<Env> {\n /** The default R2 bucket binding (the bare `ctx.storage`). */\n bucket: Selector<Env, R2BucketLike>;\n /** Extra named buckets, reached via `ctx.storage.bucket("name")` and the studio\'s bucket picker. */\n buckets?: Record<string, Selector<Env, R2BucketLike>>;\n /** Public base URL signed/public object URLs resolve against. */\n publicBaseUrl?: Selector<Env, string>;\n /** R2 S3-API credentials (`{ accountId, accessKeyId, secretAccessKey, bucket, jurisdiction? }`) enabling `ctx.storage.getPresignedUrl` — native S3 presigned URLs that hit R2 directly, bypassing the worker. Omit to use only the worker-signed `getSignedUrl` path. */\n s3?: Selector<Env, R2S3Credentials>;\n /** HMAC secret for signed URLs. */\n signingSecret?: Selector<Env, string>;\n}']:[],...e.hasScheduler?["/** `.scheduler(...)` declaration — the `SchedulerDO` namespace 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 storage the adapter reads. Give it `d1` (the default) or `namespace` (a Durable Object that hosts the auth tables), never both. The builder owns the lazy build + `ensureMigrated` dance and wires `authHandler` / `resolveIdentity` / `authAdmin`. */\ninterface AuthDeclaration<Env> {\n /** The D1 binding the auth SQL adapter is wired over (via `lunoraD1Adapter`). Omit only when using `namespace`. */\n d1?: Selector<Env, unknown>;\n /** Shared secret the worker presents on the object\'s internal session route. REQUIRED with `namespace`: the binding is reachable from any worker bound to it, so the secret — not the binding — is the authorization boundary. Without it identity resolution fails closed. */\n internalSecret?: Selector<Env, string>;\n /** Name of the Durable Object instance holding the auth tables. Defaults to `"auth"`. Set it to run separate auth objects (per deployment, per tenant) off one namespace. */\n objectName?: Selector<Env, string>;\n /** The auth Durable Object namespace — the DO-backed mode. Needed for `@better-auth/scim`, which requires native transactions that D1 has none of. The object owns the auth tables, so `/api/auth/*` and identity resolution both go through it. Typed as `AuthNamespaceLike` because `createDoAuthWiring` resolves through `idFromName` + `get` and has no `getByName` fallback — both members are load-bearing here, and `ShardNamespaceLike` leaves both optional. */\n namespace?: Selector<Env, AuthNamespaceLike>;\n /** Build the better-auth options from `env` (secret, plugins, email/password, …). */\n options: (env: Env) => LunoraAuthOptions;\n}']:[]],N=e=>[...e.hasAccess?[" private accessSelector?: Selector<Env, CreateAccessResolverOptions | undefined>;"]:[]," private adminToken?: Selector<Env, string>;",...e.hasAuth?[" private authDeclaration?: AuthDeclaration<Env>;"]:[]," private cdcEnabled = false;"," private reactiveCacheConfig: boolean | { maxBytes?: number; maxEntries?: number } = false;"," private readonly extendFns: ((env: Env, derived: Readonly<WorkerOptions>) => Partial<WorkerOptions>)[] = [];",...e.hasGlobal?[" private globalDeclaration?: GlobalDeclaration<Env>;"]:[],...e.hasHyperdriveGlobal?[" private hyperdriveGlobalDeclaration?: HyperdriveGlobalDeclaration<Env>;"]:[]," private httpRouterApp?: HttpRouterLike;"," private readonly routeMap: Record<string, Route> = {};",...e.hasScheduler?[" private schedulerDeclaration?: SchedulerDeclaration<Env>;"]:[],...m(e)?[" private readonly shardExtras: Partial<ShardConfig> = {};"]:[]," private shardSelector?: Selector<Env, ShardNamespaceLike>;",...e.hasStorage?[" private storageDeclaration?: StorageDeclaration<Env>;"]:[]],j=e=>v.filter(([t])=>e[t]).map(([,t,a,r])=>` /** ${r} */
|
|
2
2
|
public ${t}(factory: NonNullable<ShardConfig["${a}"]>): this {
|
|
3
3
|
this.shardExtras.${a} = factory;
|
|
4
4
|
|
|
@@ -52,7 +52,7 @@ import{A as S,G as D}from"./emit-B6ud4F_z.mjs";const E=e=>`has${e.charAt(0).toUp
|
|
|
52
52
|
this.storageDeclaration = declaration;
|
|
53
53
|
|
|
54
54
|
return this;
|
|
55
|
-
}`]:[],...
|
|
55
|
+
}`]:[],...j(e)],B=e=>{const t=r=>e.hasScheduler?`
|
|
56
56
|
...(this.schedulerDeclaration ? { scheduler: this.resolveScheduler(env) as unknown as ${r}["scheduler"] } : {}),`:"",a=[" cdc: this.cdcEnabled,"," reactiveCache: this.reactiveCacheConfig,",...e.hasGlobal?[` ...(this.globalDeclaration
|
|
57
57
|
? {
|
|
58
58
|
d1: (rawEnv: Record<string, unknown>, request?: { bookmark?: string; cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown>; onBookmark?: (bookmark: string | undefined) => void; userId?: string | null }) => {
|
|
@@ -78,6 +78,10 @@ import{A as S,G as D}from"./emit-B6ud4F_z.mjs";const E=e=>`has${e.charAt(0).toUp
|
|
|
78
78
|
// poll's changed-tables fast path is unreachable.
|
|
79
79
|
cdc: request?.cdc ?? false,
|
|
80
80
|
exec: buildExec(database, request?.bookmark, request?.onBookmark),
|
|
81
|
+
// The binding outlives this per-request writer, so the
|
|
82
|
+
// provisioning sweep runs once per isolate rather than
|
|
83
|
+
// once per request. See \`SqlCtxDbOptions.provisionScope\`.
|
|
84
|
+
provisionScope: database,
|
|
81
85
|
schema: schema as unknown as D1CtxDbOptions["schema"],
|
|
82
86
|
});
|
|
83
87
|
},
|
|
@@ -86,13 +90,14 @@ import{A as S,G as D}from"./emit-B6ud4F_z.mjs";const E=e=>`has${e.charAt(0).toUp
|
|
|
86
90
|
? {
|
|
87
91
|
hyperdriveGlobal: (rawEnv: Record<string, unknown>, request?: { cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown>; userId?: string | null }) => {
|
|
88
92
|
const env = rawEnv as Env;
|
|
89
|
-
const
|
|
93
|
+
const declaration = this.hyperdriveGlobalDeclaration;
|
|
94
|
+
const exec = declaration?.exec(env) as SqlExec | undefined;
|
|
90
95
|
|
|
91
|
-
if (!exec) {
|
|
96
|
+
if (!declaration || !exec) {
|
|
92
97
|
return undefined;
|
|
93
98
|
}
|
|
94
99
|
|
|
95
|
-
const origin =
|
|
100
|
+
const origin = declaration.origin?.(env);
|
|
96
101
|
const crossShard = origin
|
|
97
102
|
? createCrossShardRelationCapabilities({ identity: request?.identity, origin, userId: request?.userId ?? undefined })
|
|
98
103
|
: undefined;
|
|
@@ -103,8 +108,14 @@ import{A as S,G as D}from"./emit-B6ud4F_z.mjs";const E=e=>`has${e.charAt(0).toUp
|
|
|
103
108
|
auth: { identity: request?.identity ?? null, userId: request?.userId ?? null },
|
|
104
109
|
// See the D1 twin: one \`cdc\` switch, both changelogs.
|
|
105
110
|
cdc: request?.cdc ?? false,
|
|
106
|
-
engine:
|
|
111
|
+
engine: declaration.engine as HyperdriveEngine,
|
|
107
112
|
exec,
|
|
113
|
+
// The DECLARATION, not \`exec\` — \`exec(env)\` is a user
|
|
114
|
+
// callback that builds a fresh client per call, so scoping
|
|
115
|
+
// to its result would key the memo on a new object every
|
|
116
|
+
// request and never share anything. The declaration is
|
|
117
|
+
// built once and names one database.
|
|
118
|
+
provisionScope: declaration,
|
|
108
119
|
schema: schema as unknown as SqlCtxDbOptions["schema"],
|
|
109
120
|
});
|
|
110
121
|
},
|
|
@@ -116,7 +127,7 @@ import{A as S,G as D}from"./emit-B6ud4F_z.mjs";const E=e=>`has${e.charAt(0).toUp
|
|
|
116
127
|
: {}),`]:[],...e.hasStorage?[" ...(this.storageDeclaration ? { storage: (rawEnv: Record<string, unknown>) => this.resolveStorage(rawEnv as Env) } : {}),"]:[],...m(e)?[" ...this.shardExtras,"]:[]];return a.length>0?`
|
|
117
128
|
${a.join(`
|
|
118
129
|
`)}
|
|
119
|
-
`:""},
|
|
130
|
+
`:""},W=e=>[...e.tableNames.length>0?[` options.listSchemaTables = () => [${e.tableNames.map(t=>JSON.stringify(t)).join(", ")}];`]:[],...e.hasScheduler?[` if (this.schedulerDeclaration) {
|
|
120
131
|
options.schedulerDO = this.schedulerDeclaration.namespace(env);
|
|
121
132
|
}`]:[],...e.hasWorkflow?[` options.workflowsClient = (workflowEnv) => {
|
|
122
133
|
const source = workflowEnv as Record<string, unknown>;
|
|
@@ -243,7 +254,7 @@ ${a.join(`
|
|
|
243
254
|
}`]:[],...e.voiceAgents&&e.voiceAgents.length>0?[` options.voiceAgents = {
|
|
244
255
|
${e.voiceAgents.map(t=>` ${JSON.stringify(t.exportName)}: (env as Record<string, unknown>)[${JSON.stringify(t.bindingName)}] as ShardNamespaceLike,`).join(`
|
|
245
256
|
`)}
|
|
246
|
-
};`]:[]],
|
|
257
|
+
};`]:[]],P=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>,"," }),"]:[]," ...(this.httpRouterApp ? { httpRouter: this.httpRouterApp } : {}),"," routes: this.routeMap,"," shardDO: this.shardSelector?.(env) ?? (undefined as unknown as ShardNamespaceLike),"],$=e=>e.hasScheduler?`
|
|
247
258
|
/** Resolve the \`SchedulerDO\`-backed scheduler for this env; \`undefined\` until both the namespace and origin are wired. */
|
|
248
259
|
private resolveScheduler(env: Env): ReturnType<typeof createScheduler> | undefined {
|
|
249
260
|
const namespace = this.schedulerDeclaration?.namespace(env);
|
|
@@ -251,7 +262,7 @@ ${e.voiceAgents.map(t=>` ${JSON.stringify(t.exportName)}: (env as Rec
|
|
|
251
262
|
|
|
252
263
|
return namespace && origin ? createScheduler({${e.jurisdiction?` jurisdiction: ${JSON.stringify(e.jurisdiction)},`:""} namespace, originUrl: origin }) : undefined;
|
|
253
264
|
}
|
|
254
|
-
`:""
|
|
265
|
+
`:"",H=e=>e?`
|
|
255
266
|
/**
|
|
256
267
|
* One bucket's \`Storage\`, signing under the name it is registered as.
|
|
257
268
|
*
|
|
@@ -346,7 +357,7 @@ ${e.voiceAgents.map(t=>` ${JSON.stringify(t.exportName)}: (env as Rec
|
|
|
346
357
|
storageUpload: (key: string, body: ArrayBuffer, opts?: { bucket?: string; contentType?: string; sha256?: string }) => pick(opts?.bucket).upload(key, body, opts),
|
|
347
358
|
};
|
|
348
359
|
}
|
|
349
|
-
`:"",
|
|
360
|
+
`:"",U=e=>e?`
|
|
350
361
|
/**
|
|
351
362
|
* Adapt the raw D1 binding to \`@lunora/d1\`'s \`D1Exec\` (reads via \`all\`, writes via \`run\`, and — when the binding exposes it — several writes in one round trip via \`batch\`).
|
|
352
363
|
*
|
|
@@ -550,10 +561,11 @@ const buildGlobalCdcApplier =
|
|
|
550
561
|
|
|
551
562
|
return request.changes.length;
|
|
552
563
|
};
|
|
553
|
-
`:"",
|
|
564
|
+
`:"",_=e=>[...e.hasAuth?["AuthDeclaration"]:[],"ComposedApp",...e.hasGlobal?["GlobalDeclaration"]:[],...e.hasScheduler?["SchedulerDeclaration"]:[],"Selector",...e.hasStorage?["StorageDeclaration"]:[]].toSorted((t,a)=>t.localeCompare(a)).join(", "),M=e=>{const t={...e,hasVectors:(e.hasVectors??!0)&&(e.vectorIndexCount??0)>0},{hasAuth:a}=t,r=q(t),n=W(t),o=a?` let auth: LunoraAuth | null = null;
|
|
565
|
+
let authInit: Promise<void> | null = null;
|
|
554
566
|
`:"",d=a?`
|
|
555
|
-
const
|
|
556
|
-
if (!this.authDeclaration
|
|
567
|
+
const initAuth = async (env: Env): Promise<void> => {
|
|
568
|
+
if (!this.authDeclaration) {
|
|
557
569
|
return;
|
|
558
570
|
}
|
|
559
571
|
|
|
@@ -566,11 +578,30 @@ const buildGlobalCdcApplier =
|
|
|
566
578
|
return;
|
|
567
579
|
}
|
|
568
580
|
|
|
569
|
-
auth = createAuth({ ...this.authDeclaration.options(env), database: lunoraD1Adapter(d1(env) as never) });
|
|
570
581
|
// Apply the better-auth schema lazily on first request (raw-D1 Kysely
|
|
571
582
|
// migrator). For production run the migrate command ahead of deploy.
|
|
583
|
+
// The migration instance takes the RAW binding: better-auth migrates
|
|
584
|
+
// only through Kysely and rejects the adapter the request instance uses.
|
|
572
585
|
await ensureMigrated(createAuth({ ...this.authDeclaration.options(env), database: d1(env) as never }));
|
|
586
|
+
// Assigned after the schema exists, never before. Assigning first is
|
|
587
|
+
// what let a concurrent request see a non-null \`auth\` and serve
|
|
588
|
+
// \`/api/auth/*\` against tables the migrator had not created yet —
|
|
589
|
+
// \`no such table: rateLimit\`, from the isolate that was mid-migration.
|
|
590
|
+
auth = createAuth({ ...this.authDeclaration.options(env), database: lunoraD1Adapter(d1(env) as never) });
|
|
573
591
|
};
|
|
592
|
+
|
|
593
|
+
// Single-flighted on the PROMISE, not on \`auth\`. Every \`fetch\` awaits this
|
|
594
|
+
// and the body above is async, so a per-isolate cold start runs it once
|
|
595
|
+
// rather than once per concurrent request — better-auth's migrator emits a
|
|
596
|
+
// bare \`CREATE TABLE\` (no IF NOT EXISTS), so a second concurrent run on a
|
|
597
|
+
// fresh database fails with \`table user already exists\` and, because this is
|
|
598
|
+
// awaited ahead of the router, 500s every route. Evicted on failure so a
|
|
599
|
+
// transient error retries instead of being replayed forever.
|
|
600
|
+
const ensureAuth = (env: Env): Promise<void> =>
|
|
601
|
+
(authInit ??= initAuth(env).catch((error: unknown) => {
|
|
602
|
+
authInit = null;
|
|
603
|
+
throw error;
|
|
604
|
+
}));
|
|
574
605
|
`:"",h=a?`
|
|
575
606
|
await ensureAuth(env);`:"",i=a?"() => auth":"() => null",u=a?"getAuth: () => LunoraAuth | null":"_getAuth: () => null",p=t.hasFramework?` const buildWorker = (env: Env): LunoraWorker =>
|
|
576
607
|
host ? withFrameworkWorker(host, (hostEnv) => this.buildWorkerOptions(hostEnv as Env, ${i})) : createWorker(this.buildWorkerOptions(env, ${i}));`:` const buildWorker = (env: Env): LunoraWorker => createWorker(this.buildWorkerOptions(env, ${i}));`,b=t.hasFramework?"host?: FrameworkHostHandler":"",l=t.emailAgents??[],g=l.length>0?` composed.email = dispatchAgentEmail([
|
|
@@ -581,7 +612,7 @@ ${l.map(s=>` { agent: lunoraAgentDefinitions.${s.exportName}, binding
|
|
|
581
612
|
`:"",c=` /** Materialise the standalone Cloudflare worker + \`ShardDO\` class. */
|
|
582
613
|
public build(): ComposedApp {
|
|
583
614
|
return this.assemble();
|
|
584
|
-
}${t.hasFramework?"\n\n /** Compose Lunora's realtime plane INTO a meta-framework's Cloudflare handler (SvelteKit/Astro/Nuxt). The framework `host` serves everything except the reserved `/_lunora/*` endpoints; pass the adapter-emitted worker (e.g. SvelteKit's `_worker.js`, Astro's `handle`). */\n public buildFrameworkWorker(host: FrameworkHostHandler): ComposedApp {\n return this.assemble(host);\n }":""}`;return`${
|
|
615
|
+
}${t.hasFramework?"\n\n /** Compose Lunora's realtime plane INTO a meta-framework's Cloudflare handler (SvelteKit/Astro/Nuxt). The framework `host` serves everything except the reserved `/_lunora/*` endpoints; pass the adapter-emitted worker (e.g. SvelteKit's `_worker.js`, Astro's `handle`). */\n public buildFrameworkWorker(host: FrameworkHostHandler): ComposedApp {\n return this.assemble(host);\n }":""}`;return`${E}${L(t).join(`
|
|
585
616
|
`)}
|
|
586
617
|
|
|
587
618
|
/** Read a value off the per-request \`env\`. Returns \`undefined\` to leave the capability unconfigured (its \`ctx.*\`/admin surface stays a clear-error stub). */
|
|
@@ -606,7 +637,7 @@ interface ComposedApp extends LunoraWorker {
|
|
|
606
637
|
* first request so per-isolate singletons are built once.
|
|
607
638
|
*/
|
|
608
639
|
class AppBuilder<Env extends object> {
|
|
609
|
-
${
|
|
640
|
+
${N(t).join(`
|
|
610
641
|
`)}
|
|
611
642
|
|
|
612
643
|
private emailHandler?: (env: Env) => (message: unknown, env: unknown, context: ExecutionContextLike) => Promise<void>;
|
|
@@ -619,7 +650,7 @@ ${c}
|
|
|
619
650
|
|
|
620
651
|
/** Build the shard DO + compose the worker (standalone or framework-hosted), wrapping the lazy per-isolate singletons + auth init. */
|
|
621
652
|
private assemble(${b}): ComposedApp {
|
|
622
|
-
const ShardDO = createShardDO({${
|
|
653
|
+
const ShardDO = createShardDO({${B(t)}});
|
|
623
654
|
|
|
624
655
|
// Per-isolate singletons: the worker (and auth instance) are expensive to
|
|
625
656
|
// build, so the first request constructs them and every later request on
|
|
@@ -661,11 +692,11 @@ ${g} if (this.emailHandler) {
|
|
|
661
692
|
|
|
662
693
|
return composed;
|
|
663
694
|
}
|
|
664
|
-
${
|
|
695
|
+
${$(t)}${H(t.hasStorage)}
|
|
665
696
|
/** Fan the recorded declarations into the worker-side \`createWorker\` options. */
|
|
666
697
|
private buildWorkerOptions(env: Env, ${u}): WorkerOptions {
|
|
667
698
|
const options: WorkerOptions = {
|
|
668
|
-
${
|
|
699
|
+
${P(t).join(`
|
|
669
700
|
`)}
|
|
670
701
|
};
|
|
671
702
|
|
|
@@ -684,7 +715,7 @@ ${n.join(`
|
|
|
684
715
|
return options;
|
|
685
716
|
}
|
|
686
717
|
}
|
|
687
|
-
${
|
|
718
|
+
${U(t.hasGlobal)}
|
|
688
719
|
/**
|
|
689
720
|
* Start composing the app. Chain the capability methods, then \`.build()\`.
|
|
690
721
|
*
|
|
@@ -698,5 +729,5 @@ ${H(t.hasGlobal)}
|
|
|
698
729
|
const defineApp = <Env extends object>(): AppBuilder<Env> => new AppBuilder<Env>();
|
|
699
730
|
|
|
700
731
|
export { AppBuilder, defineApp };
|
|
701
|
-
export type { ${
|
|
702
|
-
`};export{
|
|
732
|
+
export type { ${_(t)} };
|
|
733
|
+
`};export{M as emitApp};
|
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.159",
|
|
4
4
|
"description": "Code generator for Lunora: emits _generated/{api,server,dataModel}.ts from your schema",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cloudflare",
|
|
@@ -46,15 +46,15 @@
|
|
|
46
46
|
"access": "public"
|
|
47
47
|
},
|
|
48
48
|
"dependencies": {
|
|
49
|
-
"@lunora/advisor": "1.0.0-alpha.
|
|
50
|
-
"@lunora/agent": "1.0.0-alpha.
|
|
51
|
-
"@lunora/container": "1.0.0-alpha.
|
|
52
|
-
"@lunora/errors": "1.0.0-alpha.
|
|
53
|
-
"@lunora/platform": "1.0.0-alpha.
|
|
54
|
-
"@lunora/queue": "1.0.0-alpha.
|
|
55
|
-
"@lunora/scheduler": "1.0.0-alpha.
|
|
56
|
-
"@lunora/values": "1.0.0-alpha.
|
|
57
|
-
"@lunora/workflow": "1.0.0-alpha.
|
|
49
|
+
"@lunora/advisor": "1.0.0-alpha.111",
|
|
50
|
+
"@lunora/agent": "1.0.0-alpha.90",
|
|
51
|
+
"@lunora/container": "1.0.0-alpha.45",
|
|
52
|
+
"@lunora/errors": "1.0.0-alpha.32",
|
|
53
|
+
"@lunora/platform": "1.0.0-alpha.27",
|
|
54
|
+
"@lunora/queue": "1.0.0-alpha.47",
|
|
55
|
+
"@lunora/scheduler": "1.0.0-alpha.53",
|
|
56
|
+
"@lunora/values": "1.0.0-alpha.40",
|
|
57
|
+
"@lunora/workflow": "1.0.0-alpha.46",
|
|
58
58
|
"jsonc-parser": "^3.3.1",
|
|
59
59
|
"quicktype-core": "^26.0.0",
|
|
60
60
|
"ts-morph": "^28.0.0"
|
|
@@ -1,9 +0,0 @@
|
|
|
1
|
-
import{existsSync as P,mkdirSync as cs,readFileSync as bt,writeFileSync as ls,rmSync as us}from"node:fs";import{join as f,dirname as X}from"node:path";import{performance as ge}from"node:perf_hooks";import{runAdvisor as ds}from"@lunora/advisor";import{LunoraError as k}from"@lunora/errors";import{SyntaxKind as l,Node as o,Project as Je}from"ts-morph";import{serializeSchemaSnapshot as fs}from"./SCHEMA_SNAPSHOT_VERSION-CWESEYLi.mjs";import{toAdvisorContext as ps}from"./formatAdvisories-CkEu1eye.mjs";import{s as gs}from"./paths-C-9fwEgQ.mjs";import{discoverAgents as ms}from"./AGENTS_FILENAME-CRdh_pOr.mjs";import{discoverContainers as hs}from"./CONTAINERS_FILENAME-BssQL6eI.mjs";import xs from"./discoverCrons-c0ig327z.mjs";import{diagnosticAt as re}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{b as ie}from"./module-specifiers-WF8iAydP.mjs";import{C as me,i as Es,f as vs,n as Ss,j as ys,b as As,c as Ns,l as bs,e as Ps,o as Is,d as ws,k as Ts,g as Cs,p as Fs,m as Os,a as Rs,h as Ls}from"./emit-B6ud4F_z.mjs";import{listLunoraSourceFiles as m,lunoraRelativePath as v,collectCallRows as w,collectSecurityCallRows as Ds,propertyInitializer as N,listSecurityScanFiles as Pt,limitNameOf as It,isContextIdentifier as ve,handlerOf as ks,isDatabaseAccessor as M,unwrapExpression as et,readTargetOf as wt,enclosingExportName as Ms}from"./listLunoraSourceFiles-BvqYMy81.mjs";import Ks from"./readPackageDependencies-C6h6FZuP.mjs";import{discoverQueues as _s}from"./QUEUES_FILENAME-CIfuMMG3.mjs";import{discoverSandboxUsage as zs}from"./discoverSandboxUsage-BJHLHZR_.mjs";import Us from"./discoverStorageRulesMetadata-CUa2Dtb4.mjs";import{discoverWorkflows as Bs}from"./WORKFLOWS_FILENAME-CSqONfHS.mjs";import{gatePlatformFeatures as $s,resolveCodegenTarget as qs}from"./DEFAULT_TARGET-lPq34YeN.mjs";import{i as R,a as _,e as E,r as js,b as Vs,s as oe,c as Ws,f as Hs,d as Gs}from"./queries-D8DheHbi.mjs";import{a as y,c as z,d as Tt,e as Ys}from"./classify-procedure-call-CRm5Etni.mjs";import Qs from"./discoverAuthApiCalls-B5Qmjmyk.mjs";import tt from"./discoverFunctions-DeuEs6Ce.mjs";import{i as Xs,r as Zs,e as Js}from"./unwrap-handler-return-CmIWbykC.mjs";import st from"./discoverHttpRoutes-zWSSyyOj.mjs";import en from"./discoverHyperdriveCalls-C6kV2CPz.mjs";import tn from"./discoverInserts-BB7o_8pU.mjs";import{m as be,a as J,s as Ct,d as sn}from"./index-BsVoa-4F.mjs";import{e as Ft}from"./exported-procedure-chains-Cmt3Pr92.mjs";import nn from"./discoverMigrations-CQjGLKW-.mjs";import{MUTATORS_FILENAME as rn,isDefineMutatorCallee as on,discoverMutators as nt}from"./MUTATORS_FILENAME-DHX1qUP5.mjs";import an from"./discoverNondeterministicCalls-B07wjsd2.mjs";import{discoverNotifyConfig as cn,discoverNotifyCalls as ln}from"./NOTIFY_FILENAME-BH0djo6F.mjs";import un from"./discoverR2sqlCalls-CuHe5smg.mjs";import dn from"./discoverRlsProcedures-DXdr9YHi.mjs";import fn from"./discoverRlsMetadata-CXWVNLk4.mjs";import pn from"./discoverSchema-C4znXEB-.mjs";import{secretKindOf as gn,redact as mn,isHeuristicSecretKind as hn,isSecretishName as xn}from"./redact-Cy14LEnc.mjs";import{discoverShapes as En}from"./SHAPES_FILENAME-DhZ3JkkH.mjs";import{emitApp as vn}from"./emitApp-BSxrIa6e.mjs";import{buildOpenApiDocument as Sn,emitOpenApiModule as yn}from"./buildOpenApiDocument-DIboMAh6.mjs";import{buildOpenRpcDocument as An,emitOpenRpcModule as Nn}from"./OPENRPC_VERSION-DWdTwXvO.mjs";import{s as bn}from"./parse-validator-CMV0eq2a.mjs";import{buildSchemaSnapshot as Pn}from"./SchemaSnapshotParseError-yrVM8bTa.mjs";const rt=(e,t="api")=>{const s=new Map;for(const n of e){const i=gs(n),r=s.get(i);if(r===void 0){s.set(i,n);continue}if(r!==n){const a=t==="api"?`the generated api.ts would declare "${i}" twice and the dispatch key "${i}:<fn>" would be ambiguous`:`the generated api.ts would declare "${i}" twice in HttpStreamsRef and again in the httpStreams object literal`;throw new k("INTERNAL",`@lunora/codegen: "${r}" and "${n}" both map to the ${t} namespace "${i}" — ${a}. Rename one file so the two differ by more than a non-identifier character (\`-\`, \`.\`, \`/\` and \`_\` all sanitize to \`_\`).`,{status:500})}}},In=(e,t=!0)=>{const s=[],n=e.tables.filter(i=>i.shardMode==="global");return n.some(i=>i.globalBackend!=="hyperdrive")&&s.push({name:"@lunora/d1",reason:"`.global()` tables are D1-backed, so `_generated/app.ts` imports the D1 `ctx.db` adapter"}),n.some(i=>i.globalBackend==="hyperdrive")&&s.push({name:"@lunora/hyperdrive",reason:'`.global({ backend: "hyperdrive" })` tables route through `@lunora/hyperdrive/global`'}),e.vectorIndexes.length>0&&t&&s.push({name:"@lunora/bindings",reason:"`.vectorize()` indexes make `_generated/shard.ts` import `@lunora/bindings/vectors`"}),s},wn=(e,t,s=!0)=>{if(t===void 0)return;const n=In(e,s).filter(r=>!t.has(r.name));if(n.length===0)return;const i=n.map(r=>` - ${r.name} — ${r.reason}`).join(`
|
|
2
|
-
`);throw new k("INTERNAL",`@lunora/codegen: this schema's generated code imports packages the project does not declare:
|
|
3
|
-
${i}
|
|
4
|
-
|
|
5
|
-
Install them with your package manager, then re-run codegen.`)},Tn="env.ts",Cn=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineEnv";for(const s of t.getDeclarations())if(o.isImportSpecifier(s))return ie(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineEnv":!1;return!1},Fn=e=>{const t=e.getSymbol();if(!t)return!1;for(const s of t.getDeclarations()){if(!o.isNamespaceImport(s))continue;const n=s.getFirstAncestorByKind(l.ImportDeclaration);return n!==void 0&&ie(n.getModuleSpecifierValue())}return!1},On=e=>{if(o.isIdentifier(e))return Cn(e);if(o.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineEnv"&&o.isIdentifier(t)&&Fn(t)}return!1},Rn=e=>{const t=[];for(const s of e.getVariableDeclarations()){if(!s.isExported())continue;const n=s.getInitializer();if(n?.getKind()!==l.CallExpression||!On(n.getExpression()))continue;const r=s.getNameNode();if(!o.isIdentifier(r))throw re(r,"defineEnv exports must be plain named exports (no destructuring)");t.push({exportName:r.getText()})}return t},Ln=(e,t)=>{const s=f(t,Tn);if(!P(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s),i=Rn(n);if(i.length!==0){if(i.length>1)throw re(n,`lunora/env.ts declares ${i.length.toString()} defineEnv() contracts (${i.map(r=>r.exportName).join(", ")}); exactly one is allowed`);return i[0]}},Ot=e=>{const t=n=>o.isIdentifier(n)&&n.getText()==="ctx",s=new Set;for(const n of e.getDescendantsOfKind(l.PropertyAccessExpression))t(n.getExpression())&&s.add(n.getName());for(const n of e.getDescendantsOfKind(l.VariableDeclaration)){const i=n.getInitializer(),r=n.getNameNode();if(!(i===void 0||!t(i)||!o.isObjectBindingPattern(r)))for(const a of r.getElements()){const c=a.getPropertyNameNode()?.getText()??a.getName();c&&s.add(c)}}return s},Dn=(e,t)=>{const s=Object.fromEntries(me.map(n=>[n.key,!1]));for(const n of m(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=new Set(i.getImportDeclarations().map(c=>c.getModuleSpecifierValue())),a=Ot(i);for(const c of me)if(!s[c.key]){if(r.has(c.moduleSpecifier)){s[c.key]=!0;continue}c.contextProperty!==void 0&&a.has(c.contextProperty)&&(s[c.key]=!0)}if(me.every(c=>s[c.key]))break}return s},Rt="identity.ts",kn=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineIdentity";for(const s of t.getDeclarations())if(o.isImportSpecifier(s))return ie(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineIdentity":!1;return!1},Mn=e=>{const t=e.getSymbol();if(!t)return!1;for(const s of t.getDeclarations()){if(!o.isNamespaceImport(s))continue;const n=s.getFirstAncestorByKind(l.ImportDeclaration);return n!==void 0&&ie(n.getModuleSpecifierValue())}return!1},Kn=e=>{if(o.isIdentifier(e))return kn(e);if(o.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineIdentity"&&o.isIdentifier(t)&&Mn(t)}return!1},_n=e=>{const t=[];for(const s of e.getVariableDeclarations()){if(!s.isExported())continue;const n=s.getInitializer();if(n?.getKind()!==l.CallExpression||!Kn(n.getExpression()))continue;const r=s.getNameNode();if(!o.isIdentifier(r))throw re(r,"defineIdentity exports must be plain named exports (no destructuring)");t.push({exportName:r.getText()})}return t},zn=(e,t)=>{const s=f(t,Rt);if(!P(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s),i=_n(n);if(i.length!==0){if(i.length>1)throw re(n,`lunora/identity.ts declares ${i.length.toString()} defineIdentity() contracts (${i.map(r=>r.exportName).join(", ")}); exactly one is allowed`);return i[0]}},Lt=e=>o.isParenthesizedExpression(e)?Lt(e.getExpression()):e,Un=e=>o.isObjectLiteralExpression(e)&&e.getProperties().some(t=>{if(o.isShorthandPropertyAssignment(t))return t.getName()==="durable";if(!o.isPropertyAssignment(t)||t.getName()!=="durable")return!1;const s=t.getInitializer();return s===void 0||Lt(s).getText()!=="false"}),Bn=(e,t)=>{const s={durableStreams:!1,secrets:!1};for(const n of m(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);if(s.secrets||(s.secrets=Ot(i).has("secrets")),s.durableStreams||(s.durableStreams=i.getDescendantsOfKind(l.CallExpression).some(r=>{const a=r.getExpression();return(o.isPropertyAccessExpression(a)?a.getName():a.getText())==="stream"&&r.getArguments().some(u=>Un(u))})),s.durableStreams&&s.secrets)break}return s},$n=(e,t)=>{const s=new Map,n=new Map,i=new Map;for(const r of e)s.set(r.name,`workflow "${r.exportName}"`),n.set(r.bindingName,`workflow "${r.exportName}"`),i.set(r.className,`workflow "${r.exportName}"`);for(const r of t){const a=s.get(r.name);if(a!==void 0)throw new k("DUPLICATE_WORKFLOW_NAME",`Duplicate deployed name "${r.name}": produced by both ${a} and agent "${r.exportName}". Workflow and agent names share the same wrangler workflows[] array and must be unique together.`,{status:500});const c=n.get(r.bindingName);if(c!==void 0)throw new k("DUPLICATE_WORKFLOW_BINDING",`Duplicate binding "${r.bindingName}": produced by both ${c} and agent "${r.exportName}". Workflow and agent bindings share the same wrangler workflows[] array and must be unique together.`,{status:500});const u=i.get(r.className);if(u!==void 0)throw new k("DUPLICATE_WORKFLOW_CLASS",`Duplicate generated class "${r.className}": produced by both ${u} and agent "${r.exportName}". Workflow and agent export names must yield unique generated class names.`,{status:500})}},qn=e=>{const{lunoraDirectory:t,project:s,projectRoot:n,schema:i}=e,r=zn(s,t),a=Ln(s,t),c=Bs(s,t),u=_s(s,t),d=ms(s,t);$n(c,d);const S=hs(s,t),x=Us(s,t),I=xs(s,t,c,d),g=Bn(s,t),A=zs(s,t),C=Dn(s,t);C.browser=C.browser||A.usesSandboxBrowser;const L=$s(C,qs(n,e.target),{agents:d.length>0,commitOrderedTables:i.tables.some(p=>p.commitOrdered===!0),cronTriggers:I.length>0,crossShardFanout:i.tables.some(p=>typeof p.shardMode=="object"),durableStreams:g.durableStreams,globalTables:i.tables.some(p=>p.shardMode==="global"),queues:u.length>0,secrets:g.secrets,vectorStore:i.vectorIndexes.length>0}),b=L.usage,D=L.signals.vectorStore!==!1,U=Ks(n),$=U??new Set,W=$.has("lunorash");wn(i,U,D);const K=P(f(t,"flags.ts")),F=P(f(t,"notify.ts"));return{agents:d,containers:S,crons:I,dataModelContent:vs(i),declaredDependencies:U,dependencies:$,env:a,featureUsage:b,hasFlags:K,hasNotify:F,identity:r,platformGate:L,queues:u,serverContent:Es({agents:d,containers:S,env:a,hasAccessFacade:b.access,hasAi:b.ai,hasAnalytics:b.analytics,hasBrowser:b.browser,hasVectors:D,hasFlags:K,hasHyperdrive:b.hyperdrive,hasImages:b.images,hasKv:b.kv,hasNotify:F,hasPayments:b.payments,hasPipelines:b.pipelines,hasR2sql:b.r2sql,hasX402:b.x402,identity:r,queues:u,schema:i,storageRuleBuckets:x.rules.map(p=>p.bucket),useUmbrella:W,workflows:c}),storageRulesMetadata:x,usesSandbox:A.usesSandboxBrowser||A.usesSandboxContainer||A.usesSandboxFs,useUmbrella:W,workflows:c}},Dt=new Set(["delete","get","head","options","patch","post","put"]),jn=new Set(["handler","stream"]),Vn=/\/(?:_|admin|internal|superuser|sudo|root|debug)/iu,it=new Set(["ADMIN_TOKEN","adminToken","assertAdmin","assertAuth","auth","Authorization","getSession","identity","isAdmin","requireAdmin","requireAuth","requireRole","verifyAdmin"]),Wn=e=>{if(!o.isCallExpression(e))return;const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||!Dt.has(t.getName()))return;const s=t.getExpression();if(!o.isIdentifier(s)||s.getText()!=="httpRoute")return;const n=e.getArguments()[0];if(!(!n||!o.isStringLiteral(n)))return{method:t.getName().toUpperCase(),path:n.getLiteralValue()}},Hn=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t))return;let s=t.getExpression();for(;o.isCallExpression(s);){const n=s.getExpression();if(!o.isPropertyAccessExpression(n)||Dt.has(n.getName()))break;s=n.getExpression()}return Wn(s)},Gn=e=>{for(const t of e.getDescendantsOfKind(l.PropertyAccessExpression))if(it.has(t.getName()))return!0;for(const t of e.getDescendantsOfKind(l.CallExpression)){const s=t.getExpression();if(o.isIdentifier(s)&&it.has(s.getText()))return!0}return!1},Yn=(e,t)=>{const s=e.getInitializer();if(!s||!o.isCallExpression(s))return;const n=s.getExpression();if(!o.isPropertyAccessExpression(n)||!jn.has(n.getName()))return;const i=Hn(s);if(!i||!Vn.test(i.path))return;const r=s.getArguments()[0],a=r!==void 0&&(o.isArrowFunction(r)||o.isFunctionExpression(r))&&Gn(r);return{exportName:e.getName(),file:t,method:i.method,path:i.path,usesGuard:a}},Qn=(e,t)=>{const s=[];for(const n of e.getVariableStatements())if(n.isExported())for(const i of n.getDeclarations()){const r=Yn(i,t);r&&s.push(r)}return s},Xn=(e,t)=>{const s=[];for(const n of m(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Qn(i,v(t,n)))}return s},Zn=e=>!o.isPropertyAccessExpression(e)||e.getName()!=="run"?!1:e.getExpression().getText()==="ctx.ai",Jn=(e,t)=>{if(!Zn(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!R(s)||_(s)))return{exportName:E(e),file:t,line:e.getStartLineNumber()}},er=(e,t)=>w(e,t,Jn),tr=new Set(["generateText","streamText"]),sr=new Set(["messages","prompt","system"]),nr=[{methods:new Set(["delete","insert","insertManyUnsafe","patch","replace"]),prefixes:["context.db","ctx.db"]},{methods:new Set(["run","runAction","runMutation"]),prefixes:["context","ctx"]},{methods:new Set(["fetch"]),prefixes:["context","ctx"]},{methods:new Set(["queue","send"]),prefixes:["context.email","context.mail","ctx.email","ctx.mail"]}],rr=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t))return;const s=t.getName(),n=t.getExpression().getText();for(const i of nr)if(i.methods.has(s)&&i.prefixes.some(r=>n===r||n.startsWith(`${r}.`)))return`${n}.${s}`},ir=e=>{for(const t of e.getDescendantsOfKind(l.CallExpression)){const s=rr(t);if(s!==void 0)return s}},or=e=>{const t=new Set,s=e.getFirstAncestor(r=>o.isArrowFunction(r)||o.isFunctionExpression(r)||o.isFunctionDeclaration(r)),[n]=s?.getParameters()??[],i=n?.getNameNode();if(i===void 0||!o.isObjectBindingPattern(i))return t;for(const r of i.getElements()){const a=r.getPropertyNameNode()?.getText()??r.getName(),c=r.getNameNode();if(a==="args"&&o.isObjectBindingPattern(c))for(const u of c.getElements())t.add(u.getName())}return t},ar=e=>{if(js(e))return!0;const t=or(e);return t.size===0?!1:e.getDescendantsOfKind(l.Identifier).some(s=>t.has(s.getText()))},cr=e=>{for(const t of e.getProperties()){if(!o.isPropertyAssignment(t)||!sr.has(t.getName()))continue;const s=t.getInitializer();if(s!==void 0&&ar(s))return!0}return!1},lr=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression)){const i=y(n.getExpression());if(i===void 0||!tr.has(i))continue;const[r]=n.getArguments();if(r===void 0||!o.isObjectLiteralExpression(r))continue;let a;for(const c of r.getDescendantsOfKind(l.CallExpression))if(y(c.getExpression())==="tool"&&(a=ir(c),a!==void 0))break;a!==void 0&&s.push({exportName:E(n),file:t,line:n.getStartLineNumber(),method:i,sideEffect:a,userInputDerived:cr(r)})}return s},ur=(e,t)=>{const s=[];for(const n of m(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...lr(i,v(t,n)))}return s},dr=e=>{if(!o.isPropertyAccessExpression(e)||e.getName()!=="fetch")return!1;const t=e.getExpression();return o.isIdentifier(t)&&t.getText()==="ctx"},fr=(e,t)=>{if(!dr(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!R(s)))return{exportName:E(e),file:t,line:e.getStartLineNumber()}},pr=(e,t)=>w(e,t,fr),kt=e=>e.getProperties().some(t=>o.isSpreadAssignment(t)),gr=e=>{const t=e.getArguments()[0];if(!t||!o.isObjectLiteralExpression(t))return{objects:[],opaque:!0};const s=t.getProperty("args");if(!s)return{objects:[],opaque:!1};if(!o.isPropertyAssignment(s))return{objects:[],opaque:!0};const n=s.getInitializer();return!n||!o.isObjectLiteralExpression(n)?{objects:[],opaque:!0}:{objects:[n],opaque:kt(n)}},mr=e=>{const t=[];let s=!1,n=e;for(;o.isCallExpression(n);){const i=n.getExpression();if(!o.isPropertyAccessExpression(i))break;if(i.getName()==="input"){const r=n.getArguments()[0];r&&o.isObjectLiteralExpression(r)?(t.push(r),s||=kt(r)):s=!0}n=i.getExpression()}return{objects:t,opaque:s}},Mt=(e,t)=>t?mr(t):gr(e),hr=e=>e.flatMap(t=>t.getProperties().filter(s=>o.isPropertyAssignment(s)||o.isShorthandPropertyAssignment(s)).map(s=>s.getName())),xr=new Set(["check","length","max"]),Se=e=>{if(!o.isCallExpression(e))return;const t=e.getExpression();if(!(!o.isPropertyAccessExpression(t)||t.getExpression().getText()!=="v"))return t.getName()},Er=e=>[e,...e.getDescendants()].filter(t=>Se(t)!==void 0),vr=e=>{let t=e;for(;;){const s=t.getParent();if(!s||!o.isPropertyAccessExpression(s)||s.getExpression()!==t)return!1;const n=s.getParent();if(!n||!o.isCallExpression(n)||n.getExpression()!==s)return!1;if(xr.has(s.getName()))return!0;t=n}},Sr=e=>{const t=[],s=[];for(const n of e)for(const i of n.getProperties()){if(!o.isPropertyAssignment(i))continue;const r=i.getInitializer();if(!r)continue;const a=Er(r),c=i.getName();a.some(u=>Se(u)==="any")?t.push(c):a.some(u=>Se(u)==="string"&&!vr(u))&&s.push(c)}return{anyArgs:t,unboundedStringArgs:s}},yr=(e,t)=>{const s=e.getInitializer();if(!s||!o.isCallExpression(s))return;const n=z(s);if(n?.visibility!=="public")return;const{objects:i}=Mt(s,n.receiver),{anyArgs:r,unboundedStringArgs:a}=Sr(i);if(!(r.length===0&&a.length===0))return{anyArgs:r,exportName:e.getName(),file:t,line:s.getStartLineNumber(),unboundedStringArgs:a}},Ar=(e,t)=>{const s=[];for(const n of e.getVariableStatements())if(n.isExported())for(const i of n.getDeclarations()){const r=yr(i,t);r&&s.push(r)}return s},Nr=(e,t)=>{const s=[];for(const n of m(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Ar(i,v(t,n)))}return s},he=e=>e?.getKind()===l.TrueKeyword,br=e=>e?.getKind()===l.FalseKeyword,Pr=e=>e!==void 0&&o.isNumericLiteral(e)&&e.getLiteralValue()===0,Ir=new Set(["lunoraAuthAdapter","lunoraD1Adapter"]),wr=e=>!e||!o.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>o.isCallExpression(t)&&y(t.getExpression())==="scim"),Tr=e=>e!==void 0&&o.isCallExpression(e)&&Ir.has(y(e.getExpression())??""),Cr=e=>!e||!o.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>o.isStringLiteral(t)&&t.getLiteralText()==="*"),Fr=e=>{const t=N(e,"advanced"),s=N(e,"emailAndPassword"),n=N(e,"session");return{analyzable:!0,disableCsrfCheck:he(N(t,"disableCSRFCheck")),emailPasswordEnabled:he(N(s,"enabled")),requireEmailVerification:he(N(s,"requireEmailVerification")),scimOnNonTransactionalAdapter:wr(N(e,"plugins"))&&Tr(N(e,"database")),secureCookiesDisabled:br(N(t,"useSecureCookies")),sessionFreshAgeZero:Pr(N(n,"freshAge")),trustedOriginsWildcard:Cr(N(e,"trustedOrigins"))}},Or=()=>({analyzable:!1,disableCsrfCheck:!1,emailPasswordEnabled:!1,requireEmailVerification:!1,scimOnNonTransactionalAdapter:!1,secureCookiesDisabled:!1,sessionFreshAgeZero:!1,trustedOriginsWildcard:!1}),Rr=(e,t)=>{if(y(e.getExpression())!=="createAuth")return;const s=e.getArguments()[0],n=s!==void 0&&o.isObjectLiteralExpression(s)&&s.getProperties().some(r=>o.isSpreadAssignment(r)),i=s!==void 0&&o.isObjectLiteralExpression(s)&&!n?Fr(s):Or();return{exportName:E(e),file:t,line:e.getStartLineNumber(),...i}},Lr=(e,t)=>Ds(e,t,Rr),Dr=(e,t)=>{if(!o.isPropertyAccessExpression(e))return;const s=e.getName();if(t.methods.has(s))return t.matchReceiver(e.getExpression().getText())?s:void 0},kr=(e,t,s)=>{const n=Dr(e.getExpression(),s);if(n===void 0)return;const i=e.getArguments()[s.argIndex];if(!(!i||!R(i)||_(i))&&!(s.requireUnmodifiedReach===!0&&!Vs(i)))return{exportName:E(e),file:t,line:e.getStartLineNumber(),method:n}},Mr=(e,t,s)=>{const n=[];for(const i of e.getDescendantsOfKind(l.CallExpression)){const r=kr(i,t,s);r&&n.push(r)}return n},ae=(e,t,s)=>{const n=[];for(const i of m(t)){const r=e.getSourceFile(i)??e.addSourceFileAtPath(i);n.push(...Mr(r,v(t,i),s))}return n},Kr=new Set(["content","pdf","scrape","screenshot"]),_r=(e,t)=>ae(e,t,{argIndex:0,matchReceiver:s=>s==="ctx.browser",methods:Kr}),zr=new Set(["createBrowser","createInboundEmailHandler","createPayment"]),Ur=new Set(["RateLimiter"]),Br=new Set(["extend"]),ot="lunora",$r=["vite.config.ts","vite.config.mts","vite.config.js","vite.config.mjs"],Kt=e=>{const t=[],s=[];let n=!1;for(const i of e.getProperties()){if(o.isSpreadAssignment(i)){n=!0;continue}if(o.isPropertyAssignment(i)){const r=i.getName();t.push(r),i.getInitializer()?.getKind()===l.TrueKeyword&&s.push(r);continue}(o.isShorthandPropertyAssignment(i)||o.isMethodDeclaration(i))&&t.push(i.getName())}return{analyzable:!n,presentKeys:t,trueKeys:s}},ye=e=>e&&o.isObjectLiteralExpression(e)?Kt(e):{analyzable:!1,presentKeys:[],trueKeys:[]},qr=e=>{const t=e.getStatements(),[s]=t;if(t.length!==1||s===void 0||!o.isReturnStatement(s))return;const n=s.getExpression();return n!==void 0&&o.isObjectLiteralExpression(n)?n:void 0},jr=e=>{if(o.isObjectLiteralExpression(e))return e;if(o.isParenthesizedExpression(e)){const t=e.getExpression();return o.isObjectLiteralExpression(t)?t:void 0}return o.isBlock(e)?qr(e):void 0},Vr=e=>{const t=e&&(o.isArrowFunction(e)||o.isFunctionExpression(e))?e:void 0,s=t&&jr(t.getBody());return s?Kt(s):{analyzable:!1,presentKeys:[],trueKeys:[]}},Wr=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression)){const i=y(n.getExpression());i!==void 0&&(zr.has(i)?s.push({callee:i,file:t,line:n.getStartLineNumber(),...ye(n.getArguments()[0])}):Br.has(i)&&s.push({callee:i,file:t,line:n.getStartLineNumber(),...Vr(n.getArguments()[0])}))}for(const n of e.getDescendantsOfKind(l.NewExpression)){const i=y(n.getExpression());i===void 0||!Ur.has(i)||s.push({callee:i,file:t,line:n.getStartLineNumber(),...ye(n.getArguments()[0])})}return s},Hr=(e,t)=>{for(const s of $r){const n=f(t,s);if(!P(n))continue;const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=[];for(const a of i.getDescendantsOfKind(l.CallExpression))y(a.getExpression())===ot&&r.push({callee:ot,file:s,line:a.getStartLineNumber(),...ye(a.getArguments()[0])});return r}return[]},Gr=(e,t)=>{const s=[];for(const{displayPath:n,filePath:i}of Pt(t)){const r=e.getSourceFile(i)??e.addSourceFileAtPath(i);s.push(...Wr(r,n))}return s.push(...Hr(e,X(t))),s},at="ctx.containers.",Yr=e=>{if(!e.startsWith(at))return!1;const t=e.slice(at.length);return t.length>0&&!t.includes(".")},Qr=(e,t)=>ae(e,t,{argIndex:0,matchReceiver:Yr,methods:new Set(["get"])}),Xr=new Set(["allow","deny","setAllowed"]),Zr=e=>{const t=e.getArguments()[0];if(!t||!o.isObjectLiteralExpression(t))return!1;const s=t.getProperty("enableInternet");return s!==void 0&&o.isPropertyAssignment(s)&&o.isTrueLiteral(s.getInitializerOrThrow())},Jr=(e,t)=>{const s=e.getExpression();if(!(!o.isPropertyAccessExpression(s)||s.getName()!=="start"||!Zr(e)))return{detail:"enableInternet: true",exportName:E(e),file:t,kind:"enable_internet",line:e.getStartLineNumber()}},ei=(e,t)=>{const s=e.getExpression();if(!o.isPropertyAccessExpression(s)||!Xr.has(s.getName()))return;const n=s.getExpression();if(!(!o.isPropertyAccessExpression(n)||n.getName()!=="egress"))return{detail:s.getName(),exportName:E(e),file:t,kind:"egress_relaxation",line:e.getStartLineNumber()}},ti=(e,t)=>Jr(e,t)??ei(e,t),si=(e,t)=>w(e,t,ti),ni=new Set(["defineExportSink","r2Sink","webhookExportSink"]),ri=e=>{const t=e.getExpression();if(!o.isIdentifier(t))return;const s=t.getText();return ni.has(s)?s:void 0},ii=e=>{const t=[],s=[];for(const n of e.getProperties()){if(o.isSpreadAssignment(n))return{analyzable:!1,emptyKeys:[],presentKeys:[]};if(o.isPropertyAssignment(n)){const i=n.getName();t.push(i);const r=n.getInitializer();r&&o.isStringLiteral(r)&&r.getLiteralText()===""&&s.push(i);continue}(o.isShorthandPropertyAssignment(n)||o.isMethodDeclaration(n)||o.isGetAccessorDeclaration(n))&&t.push(n.getName())}return{analyzable:!0,emptyKeys:s,presentKeys:t}},oi=(e,t)=>{const s=[];for(const{displayPath:n,filePath:i}of Pt(t)){const r=e.getSourceFile(i)??e.addSourceFileAtPath(i);for(const a of r.getDescendantsOfKind(l.CallExpression)){const c=ri(a);if(c===void 0)continue;const u=a.getArguments()[0],d=u&&o.isObjectLiteralExpression(u)?ii(u):{analyzable:!1,emptyKeys:[],presentKeys:[]};s.push({analyzable:d.analyzable,emptyKeys:d.emptyKeys,factory:c,file:n,line:a.getStartLineNumber(),presentKeys:d.presentKeys})}}return s},ai=new Map([["dbRateLimit",2],["rateLimit",2],["verifyTurnstileMiddleware",0]]),ci=new Set(["dbRateLimit","rateLimit"]),li=e=>{if(!e||!o.isObjectLiteralExpression(e))return!1;const t=e.getProperty("failOpen");return t!==void 0&&o.isPropertyAssignment(t)&&t.getInitializer()?.getKind()===l.TrueKeyword},ui=(e,t)=>{const s=y(e.getExpression());if(s===void 0)return;const n=ai.get(s);if(n!==void 0)return{callee:s,exportName:E(e),failOpen:li(e.getArguments()[n]),file:t,limitName:ci.has(s)?It(e):"",line:e.getStartLineNumber()}},di=(e,t)=>w(e,t,ui),fi=new Set(["boolean","number","object","string"]),pi=e=>{const t=e.getName();if(!fi.has(t))return;const s=e.getExpression();if(!o.isPropertyAccessExpression(s))return;if(s.getName()==="flags"&&ve(s.getExpression()))return t;const n=s.getExpression();if(s.getName()==="details"&&o.isPropertyAccessExpression(n)&&n.getName()==="flags"&&ve(n.getExpression()))return t},gi=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t))return;const s=pi(t);if(s===void 0)return;const n=e.getArguments()[0];if(!n||!(o.isStringLiteral(n)||o.isNoSubstitutionTemplateLiteral(n)))return;const i=n.getLiteralValue();return i.length>0?{key:i,type:s}:void 0},mi=(e,t)=>{const s=new Map;for(const n of m(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const r of i.getDescendantsOfKind(l.CallExpression)){const a=gi(r);a&&!s.has(a.key)&&s.set(a.key,a.type)}}return[...s.entries()].map(([n,i])=>({key:n,type:i})).toSorted((n,i)=>n.key.localeCompare(i.key))},hi=e=>{const t=e.getInitializer();if(!t||!o.isCallExpression(t))return;const s=z(t);if(s?.kind!=="query")return;const n=ks(t,s.receiver);return n?{exportName:e.getName(),handler:n}:void 0},ct=e=>{const t=e.getParent();return t&&o.isPropertyAccessExpression(t)&&t.getExpression()===e?t:void 0},xi=e=>{if(!o.isPropertyAccessExpression(e)||e.getName()!=="flags")return;const t=e.getExpression();if(!o.isIdentifier(t)||t.getText()!=="ctx")return;const s=ct(e);if(!s)return"ctx.flags";if(s.getName()==="details"){const n=ct(s);return n?`ctx.flags.details.${n.getName()}`:"ctx.flags.details"}return`ctx.flags.${s.getName()}`},Ei=(e,t)=>{const s=[];for(const n of e.handler.getDescendantsOfKind(l.PropertyAccessExpression)){const i=xi(n);i!==void 0&&s.push({callee:i,exportName:e.exportName,file:t,line:n.getStartLineNumber()})}return s},vi=(e,t)=>{const s=[];for(const n of e.getVariableStatements())if(n.isExported())for(const i of n.getDeclarations()){const r=hi(i);r&&s.push(...Ei(r,t))}return s},Si=(e,t)=>{const s=[];for(const n of m(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...vi(i,v(t,n)))}return s},yi=e=>{if(!o.isPropertyAccessExpression(e)||e.getName()!=="boolean")return!1;const t=e.getExpression();return o.isPropertyAccessExpression(t)&&t.getName()==="flags"&&ve(t.getExpression())},Ai=e=>{if(e?.getKind()===l.TrueKeyword)return!0;if(e?.getKind()===l.FalseKeyword)return!1},Ni=(e,t)=>{if(!yi(e.getExpression()))return;const[s,n]=e.getArguments();if(!s||!(o.isStringLiteral(s)||o.isNoSubstitutionTemplateLiteral(s)))return;const i=s.getLiteralValue(),r=Ai(n);if(!(i.length===0||r===void 0))return{defaultValue:r,exportName:E(e),file:t,key:i,line:e.getStartLineNumber()}},bi=(e,t)=>w(e,t,Ni),Pi=e=>{const t=e.getType().getProperty("~standard");if(!t)return;const s=t.getTypeAtLocation(e).getProperty("types");if(!s)return;const n=s.getTypeAtLocation(e).getNonNullableType().getProperty("output");if(!n)return;const i=n.getTypeAtLocation(e),r=i.getText(e);if(!r||r==="any"||r==="never"||Xs(r))return;const a=e.getSourceFile().getFilePath();return Zs(i,e,a)?Js(i,e,a,0,new Set):r},Ii=e=>{const t=e.getExpression();return o.isPropertyAccessExpression(t)&&t.getName()==="withGeoIndex"},wi=e=>{const t=e.getArguments()[0];return t&&o.isStringLiteral(t)?t.getLiteralText():""},Ti=(e,t)=>{const s=[];for(const n of m(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=v(t,n);for(const a of i.getDescendantsOfKind(l.CallExpression))Ii(a)&&s.push({file:r,indexName:wi(a),line:a.getStartLineNumber()})}return s},V=e=>e!==void 0&&(o.isArrowFunction(e)||o.isFunctionExpression(e))?e:void 0,_t=e=>{const t=e.getArguments()[0],s=V(t);if(s!==void 0)return s;if(t===void 0||!o.isObjectLiteralExpression(t))return;const n=t.getProperty("handler");return n!==void 0&&o.isPropertyAssignment(n)?V(n.getInitializer()):void 0},Ci=new Set(["delete","get","head","options","patch","post","put"]),Fi=new Set(["handler","stream"]),Oi=new Set(["runAction","runMutation"]),Ri=new Set(["delete","insert","insertManyUnsafe","patch","replace"]),ee=(e,t)=>e!==void 0&&o.isIdentifier(e)&&e.getText()===t,lt=(e,t)=>{const s=e.getParameters()[0];if(s===void 0)return;const n=s.getNameNode();if(t)return o.isIdentifier(n)?n.getText():void 0;if(o.isObjectBindingPattern(n)){for(const i of n.getElements())if((i.getPropertyNameNode()?.getText()??i.getNameNode().getText())==="ctx"){const a=i.getNameNode();return o.isIdentifier(a)?a.getText():void 0}}},ut=(e,t)=>{const s=e.getBody(),n=s.getDescendantsOfKind(l.CallExpression);o.isCallExpression(s)&&n.unshift(s);for(const i of n){const r=i.getExpression();if(!o.isPropertyAccessExpression(r))continue;const a=r.getName(),c=r.getExpression();if(Oi.has(a)&&ee(c,t))return a;if(Ri.has(a)&&o.isPropertyAccessExpression(c)&&c.getName()==="db"&&ee(c.getExpression(),t))return`db.${a}`}},dt=(e,t)=>{const s=e.getBody();for(const n of s.getDescendantsOfKind(l.PropertyAccessExpression))if(n.getName()==="auth"&&ee(n.getExpression(),t))return!0;for(const n of s.getDescendantsOfKind(l.VariableDeclaration)){const i=n.getNameNode();if(!(!o.isObjectBindingPattern(i)||!ee(n.getInitializer(),t))){for(const r of i.getElements())if((r.getPropertyNameNode()?.getText()??r.getNameNode().getText())==="auth")return!0}}return!1},Li=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||!Fi.has(t.getName()))return;let s=t.getExpression();for(;o.isCallExpression(s);){const n=s.getExpression();if(!o.isPropertyAccessExpression(n))return;const i=n.getName();if(Ci.has(i)){const r=n.getExpression();return o.isIdentifier(r)&&r.getText()==="httpRoute"?i.toUpperCase():void 0}s=n.getExpression()}},Di=(e,t)=>{const s=e.getExpression();if(o.isIdentifier(s)&&s.getText()==="httpAction"){const c=V(e.getArguments()[0]),u=c&<(c,!0);if(!c||u===void 0)return;const d=ut(c,u);return d===void 0?void 0:{exportName:E(e),file:t,kind:"httpAction",line:e.getStartLineNumber(),readsAuth:dt(c,u),sideEffect:d}}const n=Li(e);if(n===void 0)return;const i=V(e.getArguments()[0]),r=i&<(i,!1);if(!i||r===void 0)return;const a=ut(i,r);return a===void 0?void 0:{exportName:E(e),file:t,kind:"httpRoute",line:e.getStartLineNumber(),method:n,readsAuth:dt(i,r),sideEffect:a}},ki=(e,t)=>w(e,t,Di),Mi=new Set(["btoa","encodeURI","encodeURIComponent","isSafeHeaderValue","Number","parseFloat","parseInt"]),Ki=new Set(["append","set"]),zt=e=>e!==void 0&&(o.isStringLiteral(e)||o.isNoSubstitutionTemplateLiteral(e))?e.getLiteralText():"",ft=(e,t)=>(o.isCallExpression(e)?[e,...e.getDescendantsOfKind(l.CallExpression)]:e.getDescendantsOfKind(l.CallExpression)).some(n=>Mi.has(y(n.getExpression())??"")&&Hs(n,t)),_i=(e,t)=>{if(ft(e,t))return!0;const s=oe(e);return s!==void 0&&ft(s,t)},Ae=(e,t)=>Ws(e,t)&&!_i(e,t),zi=e=>{if(o.isPropertyAccessExpression(e)&&e.getName()==="headers")return!0;const t=oe(e);return t!==void 0&&o.isNewExpression(t)&&y(t.getExpression())==="Headers"},te=e=>{if(e===void 0)return;if(o.isObjectLiteralExpression(e))return e;const t=oe(e);return t!==void 0&&o.isObjectLiteralExpression(t)?t:void 0},Pe=(e,t,s)=>{for(const n of e.getProperties())if(o.isPropertyAssignment(n)){const i=n.getInitializer();i!==void 0&&Ae(i,s.requestName)&&s.rows.push({exportName:s.exportName,file:s.relativePath,headerName:zt(n.getNameNode()),line:i.getStartLineNumber(),via:t})}else if(o.isShorthandPropertyAssignment(n)){const i=n.getNameNode();Ae(i,s.requestName)&&s.rows.push({exportName:s.exportName,file:s.relativePath,headerName:n.getName(),line:i.getStartLineNumber(),via:t})}else if(o.isSpreadAssignment(n)){const i=te(n.getExpression());i!==void 0&&Pe(i,t,s)}},Ut=(e,t)=>{const s=te(e);if(s===void 0)return;const n=s.getProperty("headers");if(n===void 0||!o.isPropertyAssignment(n))return;const i=te(n.getInitializer());i!==void 0&&Pe(i,"response-init",t)},Ui=(e,t)=>{const s=y(e.getExpression());if(s==="Response")Ut(e.getArguments()[1],t);else if(s==="Headers"){const n=te(e.getArguments()[0]);n!==void 0&&Pe(n,"headers-ctor",t)}},Bi=(e,t)=>{const s=e.getExpression();if(!o.isPropertyAccessExpression(s))return;const n=s.getName(),i=s.getExpression();if(n==="json"&&o.isIdentifier(i)&&i.getText()==="Response"){Ut(e.getArguments()[1],t);return}if(Ki.has(n)&&zi(i)){const r=e.getArguments()[1];r!==void 0&&Ae(r,t.requestName)&&t.rows.push({exportName:t.exportName,file:t.relativePath,headerName:zt(e.getArguments()[0]),line:r.getStartLineNumber(),via:n==="set"?"headers-set":"headers-append"})}},$i=(e,t)=>{for(const s of e.getDescendantsOfKind(l.NewExpression))Ui(s,t);for(const s of e.getDescendantsOfKind(l.CallExpression))Bi(s,t)},qi=(e,t)=>{const s=e.getExpression();if(!o.isIdentifier(s)||s.getText()!=="httpAction")return[];const n=V(e.getArguments()[0]);if(n===void 0)return[];const i=n.getParameters()[1];if(i===void 0)return[];const r=i.getNameNode();if(!o.isIdentifier(r))return[];const a=[];return $i(n,{exportName:E(e),relativePath:t,requestName:r.getText(),rows:a}),a},ji=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression))s.push(...qi(n,t));return s},Vi=(e,t)=>{const s=[];for(const n of m(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...ji(i,v(t,n)))}return s},Wi=new Set(["auth","context.auth","ctx.auth"]),Hi="userId",Gi=e=>{const t=new Set;for(const s of e.getProperties()){if(o.isSpreadAssignment(s))return;(o.isPropertyAssignment(s)||o.isShorthandPropertyAssignment(s)||o.isMethodDeclaration(s))&&t.add(s.getName())}return t},Yi=(e,t)=>{const s=f(t,Rt);if(!P(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const i of n.getDescendantsOfKind(l.CallExpression)){if(y(i.getExpression())!=="defineIdentity")continue;const[r]=i.getArguments();return r&&o.isObjectLiteralExpression(r)?Gi(r):void 0}},pt=e=>{if(!(e===void 0||!o.isPropertyAccessExpression(e)||e.getName()!=="identity"))return Wi.has(e.getExpression().getText())?e:void 0},Qi=e=>{if(o.isPropertyAccessExpression(e)&&pt(e.getExpression())!==void 0)return e.getName();if(o.isElementAccessExpression(e)&&pt(e.getExpression())!==void 0){const t=e.getArgumentExpression();return t&&o.isStringLiteral(t)?t.getLiteralValue():void 0}},Xi=(e,t,s)=>{const n=[];for(const i of e.getDescendants()){const r=Qi(i);r!==void 0&&n.push({declared:r===Hi||s.has(r),exportName:E(i),file:t,key:r,line:i.getStartLineNumber()})}return n},Zi=(e,t)=>{const s=Yi(e,t);if(s===void 0)return[];const n=[];for(const i of m(t)){const r=e.getSourceFile(i)??e.addSourceFileAtPath(i);n.push(...Xi(r,v(t,i),s))}return n},Ji=(e,t)=>{if(y(e.getExpression())!=="buildImageDeliveryUrl")return;const s=e.getArguments()[0];if(!s)return;const n=N(s,"key");if(!(!n||!R(n)||_(n)))return{exportName:E(e),file:t,line:e.getStartLineNumber()}},eo=(e,t)=>w(e,t,Ji),to=new Set(["delete","get","getRaw","getWithMetadata","put"]),so=(e,t,s=[])=>{const n=new Map(s.map(r=>[`${r.filePath}:${r.exportName}`,r.visibility]));return ae(e,t,{argIndex:0,matchReceiver:r=>r==="ctx.kv"||r.startsWith("ctx.kv."),methods:to}).map(r=>{const a=n.get(`${r.file}:${r.exportName}`);return a===void 0?r:{...r,visibility:a}})},no=new Set(["queue","send"]),gt=new Set(["bcc","cc","to"]),ro=e=>{if(!o.isPropertyAccessExpression(e))return;const t=e.getName();if(!no.has(t))return;const s=e.getExpression().getText();return s==="ctx.mail"||s==="ctx.email"?t:void 0},io=e=>o.isObjectLiteralExpression(e)?e.getProperties().some(t=>{if(o.isShorthandPropertyAssignment(t)){const n=t.getNameNode();return gt.has(t.getName())&&R(n)&&!_(n)}if(!o.isPropertyAssignment(t)||!gt.has(t.getName()))return!1;const s=t.getInitializer();return s!==void 0&&R(s)&&!_(s)}):!1,oo=(e,t)=>{const s=ro(e.getExpression());if(s===void 0)return;const n=e.getArguments()[0];if(!(!n||!io(n)))return{exportName:E(e),file:t,line:e.getStartLineNumber(),method:s}},ao=(e,t)=>w(e,t,oo),co=e=>o.isPropertyAssignment(e)||o.isMethodDeclaration(e)||o.isGetAccessorDeclaration(e)?o.isComputedPropertyName(e.getNameNode()):!1,lo=e=>o.isPropertyAssignment(e)||o.isShorthandPropertyAssignment(e)||o.isMethodDeclaration(e)||o.isGetAccessorDeclaration(e)?co(e):!0,Bt=(e,t=!1)=>{for(const s of e.getProperties()){if(lo(s))return!0;if(t)continue;if(!o.isPropertyAssignment(s))return!0;const n=s.getInitializer();if(!n||!o.isObjectLiteralExpression(n)||Bt(n,!0))return!0}return!1},uo=(e,t)=>{for(const s of m(t)){const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const{receiver:i}of Ft(n))for(const r of be(i)){const a=r.getArguments()[0];if(a!==void 0&&(!o.isObjectLiteralExpression(a)||Bt(a)))return!0}}return!1},fo=e=>{const t=e.getArguments()[0];if(!t||!o.isObjectLiteralExpression(t))return[];const s=[];for(const n of t.getProperties()){const i=J(n);if(i===void 0||!o.isPropertyAssignment(n))continue;const r=n.getInitializer();if(!(!r||!o.isObjectLiteralExpression(r)))for(const a of r.getProperties()){const c=J(a);c!==void 0&&s.push({column:c,strategy:Ct(a),table:i})}}return s},po=(e,t)=>{const s=new Map;for(const n of m(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const{receiver:r}of Ft(i))for(const a of be(r))for(const c of fo(a)){const u=`${c.table}\0${c.column}`;s.has(u)||s.set(u,c)}}return{columns:[...s.values()]}},go=(e,t,s)=>{const n=e.getArguments()[0];if(!n||!o.isObjectLiteralExpression(n))return[];const i=[];for(const r of n.getProperties()){const a=J(r);if(a===void 0||!o.isPropertyAssignment(r))continue;const c=r.getInitializer();if(!(!c||!o.isObjectLiteralExpression(c)))for(const u of c.getProperties()){const d=J(u);if(d===void 0)continue;const S=Ct(u);S!=="custom"&&i.push({column:d,exportName:t,file:s,line:u.getStartLineNumber(),strategy:S,table:a})}}return i},mo=(e,t)=>{if(!o.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&o.isCallExpression(s)?z(s):void 0;return n?.receiver?be(n.receiver).flatMap(i=>go(i,e.getName(),t)):[]},ho=(e,t)=>{const s=[];for(const n of m(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=v(t,n);for(const a of i.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...mo(c,r))}return s},xo=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||t.getName()!=="replace")return!1;const s=t.getExpression();return M(s)},Eo=e=>{const t=e.getArguments()[0];if(t===void 0||!o.isObjectLiteralExpression(t))return;const s=t.getProperty("server");if(s!==void 0)return o.isPropertyAssignment(s)?s.getInitializer():s},vo=e=>{if(!e.isExported())return;const t=e.getInitializer();if(t?.getKind()!==l.CallExpression)return;const s=t;return on(s.getExpression())?s:void 0},So=e=>{const t=vo(e),s=t===void 0?void 0:Eo(t);if(s===void 0)return[];const n=e.getNameNode(),i=o.isIdentifier(n)?n.getText():"";return s.getDescendantsOfKind(l.CallExpression).filter(r=>xo(r)).map(r=>({exportName:i,file:"lunora/mutators.ts",line:r.getStartLineNumber()}))},yo=e=>e.getVariableDeclarations().flatMap(t=>So(t)),Ao=(e,t)=>{const s=f(t,rn);if(!P(s))return[];const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);return yo(n)},No=new Set(["delete","get","patch"]),bo=new Set(["accountId","authorId","companyId","createdBy","createdById","customerId","groupId","memberId","organizationId","orgId","ownerId","projectId","teamId","tenantId","userId","workspaceId"]),Po=new Set(["auth","identity","session","user"]),Io=new Set([l.EqualsEqualsEqualsToken,l.EqualsEqualsToken,l.ExclamationEqualsEqualsToken,l.ExclamationEqualsToken]),wo=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||t.getName()!=="normalizeId"||!M(t.getExpression()))return;const s=e.getArguments()[0];return s&&o.isStringLiteral(s)?s.getLiteralText():""},To=e=>{let t=e,s=t.getParent();for(;s!==void 0&&(o.isAsExpression(s)||o.isParenthesizedExpression(s)||o.isNonNullExpression(s));)t=s,s=t.getParent();if(s===void 0||!o.isVariableDeclaration(s))return;const n=s.getNameNode();return o.isIdentifier(n)?n.getText():void 0},Co=(e,t)=>e.getDescendantsOfKind(l.Identifier).some(s=>s.getText()===t),Fo=e=>o.isThrowStatement(e)||o.isReturnStatement(e)||e.getDescendantsOfKind(l.ThrowStatement).length>0||e.getDescendantsOfKind(l.ReturnStatement).length>0,Oo=(e,t)=>e.getDescendantsOfKind(l.IfStatement).some(s=>Co(s.getExpression(),t)&&Fo(s.getThenStatement())),Ro=(e,t)=>{for(const s of e.getDescendantsOfKind(l.CallExpression)){const n=s.getExpression();if(!o.isPropertyAccessExpression(n))continue;const i=n.getName();if(!No.has(i))continue;const r=n.getExpression();if(!(M(r)||o.isPropertyAccessExpression(r)&&M(r.getExpression())))continue;const c=s.getArguments()[0];if(c!==void 0&&o.isIdentifier(c)&&c.getText()===t)return i}},Lo=e=>{let t=e;for(;o.isPropertyAccessExpression(t)||o.isElementAccessExpression(t)||o.isNonNullExpression(t)||o.isParenthesizedExpression(t)||o.isAsExpression(t)||o.isAwaitExpression(t);)t=t.getExpression();return o.isIdentifier(t)?t.getText():void 0},Do=e=>e.getDescendantsOfKind(l.CallExpression).some(t=>t.getArguments().some(s=>Lo(s)==="ctx")),ko=e=>e.getDescendantsOfKind(l.BinaryExpression).some(t=>Io.has(t.getOperatorToken().getKind())?o.isPropertyAccessExpression(t.getLeft())||o.isPropertyAccessExpression(t.getRight()):!1),Mo=e=>{for(const t of e.getDescendantsOfKind(l.Identifier))if(bo.has(t.getText()))return!0;for(const t of e.getDescendantsOfKind(l.PropertyAccessExpression)){const s=t.getExpression();if(o.isIdentifier(s)&&s.getText()==="ctx"&&Po.has(t.getName()))return!0}return Do(e)||ko(e)},Ko=(e,t)=>{if(!o.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!o.isCallExpression(s))return[];const n=z(s);if(n?.kind!=="query"&&n?.kind!=="mutation")return[];const i=_t(s);if(i===void 0)return[];const r=n.receiver!==void 0&&Tt(n.receiver,"use","rls"),a=Mo(i),c=new Set,u=[];for(const d of i.getDescendantsOfKind(l.CallExpression)){const S=wo(d);if(S===void 0)continue;const x=To(d);if(x===void 0||c.has(x)||!Oo(i,x))continue;const I=Ro(i,x);I!==void 0&&(c.add(x),u.push({exportName:e.getName(),file:t,line:d.getStartLineNumber(),mentionsOwnership:a,sinkMethod:I,table:S,usesRls:r,visibility:n.visibility}))}return u},_o=(e,t)=>{const s=[];for(const n of m(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=v(t,n);for(const a of i.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...Ko(c,r))}return s},zo=new Set(["accountId","authorId","createdBy","createdById","organizationId","orgId","ownerId","tenantId","updatedBy","userId","workspaceId"]),Uo=new Set(["insert","insertManyUnsafe","patch","replace"]),Bo=e=>{if(!o.isPropertyAccessExpression(e))return;const t=e.getName();if(!Uo.has(t))return;const s=e.getExpression();if(!o.isPropertyAccessExpression(s)||s.getName()!=="db")return;const n=s.getExpression();return o.isIdentifier(n)&&n.getText()==="ctx"?t:void 0},$o=(e,t)=>{if(t!=="insertManyUnsafe")return o.isObjectLiteralExpression(e)?[e]:[];if(!o.isArrayLiteralExpression(e))return[];const s=[];for(const n of e.getElements())o.isObjectLiteralExpression(n)&&s.push(n);return s},qo=(e,t,s,n)=>{const i=[];for(const r of e.getProperties()){let a,c;o.isPropertyAssignment(r)?(a=r.getName(),c=r.getInitializer()):o.isShorthandPropertyAssignment(r)&&(a=r.getName(),c=r.getNameNode()),!(a===void 0||c===void 0||!zo.has(a))&&R(c)&&!_(c)&&i.push({exportName:E(s),field:a,file:n,line:s.getStartLineNumber(),method:t})}return i},jo=(e,t)=>{const s=Bo(e.getExpression());if(s===void 0)return[];const n=e.getArguments()[1];return n?$o(n,s).flatMap(i=>qo(i,s,e,t)):[]},Vo=(e,t,s)=>{const n=[];for(const i of e.getDescendantsOfKind(l.CallExpression))for(const r of jo(i,t)){const a=s(r.exportName);n.push(a===void 0?r:{...r,visibility:a})}return n},Wo=(e,t,s=[])=>{const n=[],i=new Map(s.map(r=>[`${r.filePath}:${r.exportName}`,r.visibility]));for(const r of m(t)){const a=e.getSourceFile(r)??e.addSourceFileAtPath(r),c=v(t,r);n.push(...Vo(a,c,u=>i.get(`${c}:${u}`)))}return n},Ho=["providerSubscriptionId","state"],Go=["providerEventId","processedAt"],mt=(e,t)=>t.every(s=>s in e.shape),Yo=e=>{const t=e.find(n=>n.name==="subscriptions"),s=e.find(n=>n.name==="events");return t!==void 0&&s!==void 0&&mt(t,Ho)&&mt(s,Go)},Qo=new Set(["createAutumnAdapter","createDodoPaymentsAdapter","createPolarAdapter","createStripeAdapter"]),Xo=e=>e&&o.isNumericLiteral(e)?Number(e.getText()):void 0,Zo=e=>{const t=e.getProperty("webhookToleranceSeconds");return t&&o.isPropertyAssignment(t)?Xo(t.getInitializer()):void 0},Jo=(e,t)=>{const s=y(e.getExpression());if(s===void 0||!Qo.has(s))return;const[n]=e.getArguments(),i=n&&o.isObjectLiteralExpression(n)?Zo(n):void 0;return{callee:s,exportName:E(e),file:t,line:e.getStartLineNumber(),...i===void 0?{}:{toleranceSeconds:i}}},ea=(e,t)=>w(e,t,Jo),ta=new Set(["defineQueue","defineWorkflow"]),sa=new Set(["run","runAction","runMutation","runQuery"]),na=new Set(["api","internal"]),ra=e=>{const t=e.getExpression();return o.isIdentifier(t)?t.getText():void 0},ia=e=>{const t=e.getArguments()[0];if(!t||!o.isObjectLiteralExpression(t))return;const s=t.getProperty("handler");if(s===void 0||!o.isPropertyAssignment(s))return;const n=s.getInitializer();if(n&&(o.isArrowFunction(n)||o.isFunctionExpression(n)))return n},$t=(e,t)=>{const s=e.getParameters()[t]?.getNameNode();return s&&o.isIdentifier(s)?s.getText():void 0},qt=(e,t)=>e===t||e.startsWith(`${t}.`),jt=e=>{const t=e.getDescendantsOfKind(l.PropertyAccessExpression);return o.isPropertyAccessExpression(e)&&t.push(e),t},ht=e=>{const t=e.getParent();return o.isPropertyAccessExpression(t)&&t.getNameNode()===e||o.isPropertyAssignment(t)&&t.getNameNode()===e?!1:!(o.isBindingElement(t)&&t.getNameNode()===e)},Vt=e=>{const t=e.getDescendantsOfKind(l.Identifier).filter(s=>ht(s));return o.isIdentifier(e)&&ht(e)&&t.push(e),t},oa=e=>{if(!o.isVariableDeclaration(e))return[];const t=e.getNameNode();return o.isIdentifier(t)?[t.getText()]:t.getDescendantsOfKind(l.BindingElement).map(s=>s.getName())},aa=e=>{const t=$t(e,1);if(t===void 0)return[];const s=[`${t}.messages`];for(const n of e.getDescendantsOfKind(l.ForOfStatement)){if(n.getExpression().getText()!==`${t}.messages`)continue;const i=n.getInitializer(),r=o.isVariableDeclarationList(i)?i.getDeclarations()[0]?.getNameNode():void 0;r&&o.isIdentifier(r)&&s.push(`${r.getText()}.body`)}return s},ca=(e,t,s)=>{const n=t==="workflow"?[`${s}.params`]:aa(e),i=new Set,r=a=>jt(a).some(c=>n.some(u=>qt(c.getText(),u)))?!0:Vt(a).some(c=>i.has(c.getText()));for(const a of e.getDescendantsOfKind(l.VariableDeclaration)){const c=a.getInitializer();if(c&&r(c))for(const u of oa(a))i.add(u)}return{names:i,prefixes:n}},la=(e,t)=>jt(e).some(s=>t.prefixes.some(n=>qt(s.getText(),n)))?!0:Vt(e).some(s=>t.names.has(s.getText())),ua=e=>{if(e===void 0||!o.isPropertyAccessExpression(e))return;const t=[];let s=e;for(;o.isPropertyAccessExpression(s);)t.unshift(s.getName()),s=s.getExpression();const n=t.at(-1);if(!(n===void 0||!o.isIdentifier(s)||!na.has(s.getText())||t.length<2))return{exportName:n,file:t.slice(0,-1).join("/")}},da=(e,t,s)=>{const n=$t(e,0);if(n===void 0)return[];const i=ca(e,t,n),r=[];for(const a of e.getDescendantsOfKind(l.CallExpression)){const c=a.getExpression();if(!o.isPropertyAccessExpression(c)||!sa.has(c.getName())||c.getExpression().getText()!==n)continue;const u=a.getArguments()[1];if(!u||!la(u,i))continue;const d=ua(a.getArguments()[0]);d!==void 0&&r.push({dispatchKind:t,file:s,handlerExport:E(a),line:a.getStartLineNumber(),targetExport:d.exportName,targetFile:d.file})}return r},fa=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression)){const i=ra(n);if(i===void 0||!ta.has(i))continue;const r=ia(n);r!==void 0&&s.push(...da(r,i==="defineQueue"?"queue":"workflow",t))}return s},pa=(e,t)=>{const s=[];for(const n of m(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...fa(i,v(t,n)))}return s},xt={dbRateLimit:"usesRateLimit",emailGateMiddleware:"usesEmailGate",mask:"usesMask",rateLimit:"usesRateLimit",rls:"usesRls",verifyTurnstileMiddleware:"usesCaptcha"},Et=new Set(["account","credential","member","passkey","session","user"]),ga=e=>e.replaceAll(/[-_]/gu," ").replaceAll(/([a-z0-9])([A-Z])/gu,"$1 $2").split(" ").filter(Boolean).map(t=>t.toLowerCase()),ma=e=>{const s=ga(e).at(-1);if(!s)return!1;const n=s.endsWith("s")?s.slice(0,-1):s;return Et.has(s)||Et.has(n)},ha=e=>{const t=e.replaceAll(/[^a-z0-9]/giu,"").toLowerCase();return t.endsWith("email")||t.endsWith("emailaddress")},xa=(e,t)=>{const{objects:s,opaque:n}=Mt(e,t);return hr(s).some(i=>ha(i))?!0:n?void 0:!1},Ea=e=>{const t=e.getArguments()[0];return!t||!o.isObjectLiteralExpression(t)?{usesCaptcha:!1,usesRateLimit:!1}:{usesCaptcha:!!t.getProperty("captcha"),usesRateLimit:!!t.getProperty("rateLimit")}},va=e=>{if(o.isCallExpression(e))return e;if(!o.isIdentifier(e))return;const s=e.getSourceFile().getVariableDeclaration(e.getText())?.getInitializer();return s&&o.isCallExpression(s)?s:void 0},Z={usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},Sa=e=>{const t=va(e),s=t?y(t.getExpression()):void 0;if(t&&s==="protectPublic"){const n=Ea(t);return{...Z,usesCaptcha:n.usesCaptcha,usesRateLimit:n.usesRateLimit}}return s!==void 0&&s in xt?{...Z,[xt[s]]:!0}:Z},ya=e=>{const t={...Z};let s=e;for(;o.isCallExpression(s);){const n=s.getExpression();if(!o.isPropertyAccessExpression(n))break;const i=n.getName()==="use"?s.getArguments()[0]:void 0;if(i){const r=Sa(i);t.usesCaptcha||=r.usesCaptcha,t.usesEmailGate||=r.usesEmailGate,t.usesMask||=r.usesMask,t.usesRateLimit||=r.usesRateLimit,t.usesRls||=r.usesRls}s=n.getExpression()}return t},Aa=new Set(["insert","insertMany","insertManyUnsafe","replace"]),Na=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||!Aa.has(t.getName()))return!1;const s=t.getExpression();if(!M(s))return!1;const i=e.getArguments()[0];return!i||!(o.isStringLiteral(i)||o.isNoSubstitutionTemplateLiteral(i))?!1:ma(i.getLiteralText())},ba=new Set(["create","runAfter","runAt","send","sendBatch"]),Pa=new Set(["queues","scheduler","workflows"]),Ia=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||!ba.has(t.getName()))return!1;let s=t.getExpression();for(;o.isCallExpression(s)||o.isElementAccessExpression(s)||o.isPropertyAccessExpression(s);){if(o.isPropertyAccessExpression(s)&&Pa.has(s.getName())){const n=s.getExpression();if(o.isIdentifier(n)&&n.getText()==="ctx")return!0}s=s.getExpression()}return!1},wa=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||t.getName()!=="insertManyUnsafe")return!1;const s=t.getExpression();return M(s)},Wt=new Set(["generateObject","generateText","streamObject","streamText"]),Ta=e=>{const t=y(e.getExpression());return t!==void 0&&Wt.has(t)},Ca=e=>{const t=y(e.getExpression());if(t===void 0||!Wt.has(t))return!1;const s=e.getArguments()[0];return!s||!o.isObjectLiteralExpression(s)||s.getProperties().some(n=>o.isSpreadAssignment(n))?!1:!s.getProperty("maxOutputTokens")},Fa=new Set(["log","span","trace"]),Oa=new Set(["ai"]),Ra=new Set(["email","mail"]),La=new Set(["ai","browser","fetch","mail","notify","queues","sql","storage","workflows"]),xe=(e,t)=>e.getDescendantsOfKind(l.PropertyAccessExpression).some(s=>{if(!t.has(s.getName()))return!1;const n=s.getExpression();return o.isIdentifier(n)&&n.getText()==="ctx"}),Da=new Set([l.ArrowFunction,l.FunctionDeclaration,l.FunctionExpression,l.GetAccessor,l.MethodDeclaration,l.SetAccessor]),ka=new Set(["every","filter","flatMap","forEach","map","some"]),Ma=new Set(["all","allSettled","race"]),Ka=e=>{const t=e.getParent();if(!t||!o.isCallExpression(t)||!t.getArguments().includes(e))return;const s=t.getExpression();if(!o.isPropertyAccessExpression(s))return;const n=s.getName();if(ka.has(n))return t;const i=s.getExpression();if(o.isIdentifier(i)&&i.getText()==="Promise"&&Ma.has(n))return t},_a=e=>{let t=e.getParent();for(;t;){if(o.isTryStatement(t)){const s=t.getTryBlock();if(e.getPos()>=s.getPos()&&e.getEnd()<=s.getEnd())return!0}if(Da.has(t.getKind())){const s=Ka(t);if(!s)return!1;t=s;continue}t=t.getParent()}return!1},za=e=>{let t=e;for(;;){const s=t.getParent();if(!o.isPropertyAccessExpression(s)||s.getExpression()!==t)return!1;if(s.getName()==="catch")return!0;if(s.getName()!=="then"&&s.getName()!=="finally")return!1;const n=s.getParent();if(!o.isCallExpression(n)||n.getExpression()!==s)return!1;t=n}},Ua=e=>{let t=e;for(;;){const s=t.getParent();if(o.isPropertyAccessExpression(s)&&s.getExpression()===t){t=s;continue}return o.isCallExpression(s)&&s.getExpression()===t?s:void 0}},Ba=e=>{let t=!1,s=!0;for(const n of e.getDescendantsOfKind(l.PropertyAccessExpression)){if(!La.has(n.getName()))continue;const i=n.getExpression();if(!o.isIdentifier(i)||i.getText()!=="ctx")continue;const r=Ua(n);r&&(t=!0,!_a(r)&&!za(r)&&(s=!1))}return{handlesErrors:t&&s,reachesOutbound:t}},$a=e=>e.getDescendantsOfKind(l.ThrowStatement).some(t=>{const s=t.getExpression();if(!o.isNewExpression(s))return!1;const n=s.getExpression();return o.isIdentifier(n)&&n.getText()==="Error"}),vt="lunora-advisor-exempt",qa=/^[\s*/]+/u,ja=/[\w-]/u,Va=e=>{const s=(e.getFirstAncestorByKind(l.VariableStatement)??e).getLeadingCommentRanges().map(n=>n.getText()).join(`
|
|
6
|
-
`);for(const n of s.split(`
|
|
7
|
-
`)){const i=n.replace(qa,"");if(!i.startsWith(vt))continue;const r=i.slice(vt.length);if(ja.test(r.charAt(0)))continue;const a=r.indexOf("--");return{exempt:!0,exemptReason:(a===-1?"":r.slice(a+2).split("*")[0]??"").trim()}}return{exempt:!1,exemptReason:""}},Wa=e=>{const[t]=e.getArguments();if(t){if(o.isObjectLiteralExpression(t)){const s=t.getProperty("handler");return s?o.isPropertyAssignment(s)?s.getInitializer():o.isShorthandPropertyAssignment(s)?s.getNameNode():o.isMethodDeclaration(s)?s:void 0:void 0}return t}},Ha=(e,t)=>{const s=Wa(t);if(!s)return;if(o.isArrowFunction(s)||o.isFunctionExpression(s)||o.isMethodDeclaration(s))return e;if(!o.isIdentifier(s))return;const n=s.getSourceFile(),i=s.getText(),r=n.getVariableDeclaration(i)?.getInitializer();return r&&(o.isArrowFunction(r)||o.isFunctionExpression(r))?r:n.getFunction(i)},Ga=e=>{let t=!1,s=!1,n=!1,i=!1,r=!1;for(const u of e.getDescendantsOfKind(l.CallExpression))if(Na(u)&&(r=!0),Ia(u)&&(t=!0),wa(u)&&(i=!0),Ta(u)&&(s=!0),Ca(u)&&(n=!0),r&&t&&i&&n)break;const{handlesErrors:a,reachesOutbound:c}=Ba(e);return{callsMail:xe(e,Ra),emitsEvent:xe(e,Fa),fanOut:t,handlesErrors:a,reachesOutbound:c,runsAiGeneration:s||xe(e,Oa),throwsBareError:$a(e),unboundedAiGeneration:n,usesInsertManyUnsafe:i,writesUserTable:r}},Ya=(e,t)=>{const s=e.getInitializer();if(!s||!o.isCallExpression(s))return;const n=z(s);if(!n||n.kind!=="query"&&n.kind!=="mutation"&&n.kind!=="action")return;const i=n.receiver?ya(n.receiver):{usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},r=Ha(e,s);return{...r?Ga(r):{},...Va(e),...i,analyzableBody:r!==void 0,exportName:e.getName(),file:t,hasEmailArg:xa(s,n.receiver),kind:n.kind,visibility:n.visibility}},Qa=(e,t)=>{const s=[];for(const n of e.getVariableStatements())if(n.isExported())for(const i of n.getDeclarations()){const r=Ya(i,t);r&&s.push(r)}return s},Xa=(e,t)=>{const s=[];for(const n of m(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Qa(i,v(t,n)))}return s},Za=new Set(["dbRateLimit","rateLimit"]),Ja=e=>o.isArrowFunction(e)?e.getBody():e,ec=(e,t)=>{const s=y(e.getExpression());if(s===void 0||!Za.has(s))return;const n=e.getArguments()[2];if(!n)return;const i=N(n,"key");if(!i)return;const r=Ja(i);if(!(!R(r)||_(r)))return{callee:s,exportName:E(e),file:t,limitName:It(e),line:e.getStartLineNumber()}},tc=(e,t)=>w(e,t,ec),sc=new Set(["findFirst","findFirstOrThrow","findMany","get"]),nc=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||!sc.has(t.getName()))return;const s=t.getExpression();if(M(s)){const n=e.getArguments()[0];return n&&o.isStringLiteral(n)?n.getLiteralText():""}if(o.isPropertyAccessExpression(s)&&M(s.getExpression()))return s.getName()},rc=e=>{let t=e;for(;o.isCallExpression(t);){const s=t.getExpression();if(!o.isPropertyAccessExpression(s))return;if(s.getName()==="query"&&M(s.getExpression())){const n=t.getArguments()[0];return n&&o.isStringLiteral(n)?n.getLiteralText():""}t=s.getExpression()}},ic=e=>{let t=et(e)??e;for(;o.isAwaitExpression(t);)t=et(t.getExpression())??t.getExpression();return t},Ht=(e,t=!1)=>{const s=ic(e);if(o.isIdentifier(s)){if(t)return;const n=oe(s);return n===void 0?void 0:Ht(n,!0)}if(o.isCallExpression(s))return nc(s)??rc(s)},oc=e=>{const t=e.getBody();if(!o.isBlock(t))return[t];const s=[];for(const n of e.getDescendantsOfKind(l.ReturnStatement)){const i=n.getFirstAncestor(a=>o.isArrowFunction(a)||o.isFunctionExpression(a)||o.isFunctionDeclaration(a)),r=n.getExpression();i===e&&r!==void 0&&s.push(r)}return s},ac=(e,t)=>{if(!o.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!o.isCallExpression(s))return[];const n=z(s);if(n?.kind!=="query")return[];const i=_t(s);if(i===void 0)return[];const r=n.receiver!==void 0&&Ys(n.receiver,"output"),a=n.receiver!==void 0&&Tt(n.receiver,"use","mask"),c=new Set,u=[];for(const d of oc(i)){const S=Ht(d);S===void 0||c.has(S)||(c.add(S),u.push({exportName:e.getName(),file:t,line:d.getStartLineNumber(),table:S,usesMask:a,usesOutput:r,visibility:n.visibility}))}return u},cc=(e,t)=>{const s=[];for(const n of m(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=v(t,n);for(const a of i.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...ac(c,r))}return s},lc=e=>{if(!e||!o.isObjectLiteralExpression(e))return[];const t=[];for(const s of e.getProperties())(o.isPropertyAssignment(s)||o.isShorthandPropertyAssignment(s)||o.isMethodDeclaration(s)||o.isGetAccessorDeclaration(s))&&t.push(s.getName());return t},uc=(e,t)=>{if(!o.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&o.isCallExpression(s)?z(s):void 0;if(!n)return[];const i=[];for(const r of e.getDescendantsOfKind(l.CallExpression)){const a=wt(r);if(a===void 0)continue;const c=lc(N(a.options,"with"));c.length!==0&&i.push({exportName:e.getName(),file:t,line:r.getStartLineNumber(),parentTable:a.table,relations:c,visibility:n.visibility})}return i},dc=(e,t)=>{const s=[];for(const n of m(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=v(t,n);for(const a of i.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...uc(c,r))}return s},se=e=>{if(o.isStringLiteral(e)||o.isNoSubstitutionTemplateLiteral(e))return e.getLiteralText();if(o.isBinaryExpression(e)&&e.getOperatorToken().getKind()===l.PlusToken){const t=se(e.getLeft()),s=se(e.getRight());return t!==void 0&&s!==void 0?t+s:void 0}},fc=e=>{let t=e,s=t.getParent();for(;s!==void 0&&o.isBinaryExpression(s)&&s.getOperatorToken().getKind()===l.PlusToken;)t=s,s=t.getParent();return t!==e&&se(t)!==void 0},pc=/(?:^|\/)__tests__\//u,gc=/\.(?:spec|test)$/u,mc=e=>pc.test(e)||gc.test(e),hc=e=>{const t=e.getParent();if(t!==void 0){if(o.isVariableDeclaration(t)||o.isPropertyAssignment(t)||o.isPropertySignature(t))return t.getName();if(o.isBinaryExpression(t)&&t.getOperatorToken().getKind()===l.EqualsToken)return t.getLeft().getText()}},xc=(e,t,s)=>hn(e)?!mc(s)&&xn(hc(t)):!0,Ec=(e,t)=>{const s=[],n=[...e.getDescendantsOfKind(l.BinaryExpression),...e.getDescendantsOfKind(l.StringLiteral),...e.getDescendantsOfKind(l.NoSubstitutionTemplateLiteral)],i=new Set;for(const r of n){if(fc(r))continue;const a=se(r);if(a===void 0)continue;const c=gn(a);if(c===void 0||!xc(c,r,t))continue;const u=r.getStartLineNumber(),d=`${String(u)}:${c}`;i.has(d)||(i.add(d),s.push({file:t,kind:c,line:u,preview:mn(a)}))}return s},vc=(e,t)=>{const s=[];for(const n of m(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Ec(i,v(t,n)))}return s},Sc=(e,t)=>{if(!o.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&o.isCallExpression(s)?z(s):void 0;if(!n)return[];const i=[];for(const r of e.getDescendantsOfKind(l.CallExpression)){const a=wt(r);if(a===void 0)continue;const c=N(a.options,"includeDeleted");if(c===void 0)continue;const u=o.isTrueLiteral(c),d=!u&&R(c);!u&&!d||i.push({exportName:e.getName(),file:t,fromArgs:d,hardcodedTrue:u,line:r.getStartLineNumber(),table:a.table,visibility:n.visibility})}return i},yc=(e,t)=>{const s=[];for(const n of m(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=v(t,n);for(const a of i.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...Sc(c,r))}return s},Ac=new Set(["query","unsafe"]),Nc=e=>{if(!o.isPropertyAccessExpression(e)||!Ac.has(e.getName()))return!1;const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||t.getName()!=="sql")return!1;const s=t.getExpression();return o.isIdentifier(s)&&s.getText()==="ctx"},bc=e=>o.isBinaryExpression(e)||o.isTemplateExpression(e),Pc=e=>e.getFirstAncestorByKind(l.VariableDeclaration)?.getName()??"<module>",Ic=(e,t)=>{if(!Nc(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!bc(s)))return{exportName:Pc(e),file:t,line:s.getStartLineNumber()}},wc=(e,t)=>w(e,t,Ic),Tc=[["convex",["convex","@convex-dev/"]],["supabase",["@supabase/"]],["firebase",["firebase","@firebase/","firebase-admin"]]],Cc=e=>{for(const[t,s]of Tc)for(const n of s)if(e===n||e.startsWith(n.endsWith("/")?n:`${n}/`))return t},Fc=(e,t)=>{const s=[];for(const n of m(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const r of i.getImportDeclarations()){const a=r.getModuleSpecifierValue(),c=Cc(a);c!==void 0&&s.push({file:v(t,n),line:r.getStartLineNumber(),moduleSpecifier:a,platform:c})}}return s},Oc=new Set(["createMultipartUpload","delete","download","generateUploadUrl","get","getMetadata","getPresignedUrl","getSignedUrl","getUrl","head","put","resumeMultipartUpload","store","upload"]),Rc=(e,t,s=[])=>{const n=new Map(s.map(r=>[`${r.filePath}:${r.exportName}`,r.visibility]));return ae(e,t,{argIndex:0,matchReceiver:r=>r==="ctx.storage"||r.startsWith("ctx.storage."),methods:Oc,requireUnmodifiedReach:!0}).map(r=>{const a=n.get(`${r.file}:${r.exportName}`);return a===void 0?r:{...r,visibility:a}})},Lc=new Map([["generateUploadUrl",1],["getPresignedUrl",1],["getSignedUrl",1],["store",2],["upload",2]]),Dc=e=>e&&o.isNumericLiteral(e)?Number(e.getText()):void 0,kc=e=>{if(e===void 0)return{analyzable:!0,presentKeys:[]};if(!o.isObjectLiteralExpression(e))return{analyzable:!1,presentKeys:[]};const t=[];let s,n=!1;for(const i of e.getProperties()){if(o.isSpreadAssignment(i)){n=!0;continue}if(o.isPropertyAssignment(i)){const r=i.getName();t.push(r),r==="expiresInSeconds"&&(s=Dc(i.getInitializer()));continue}(o.isShorthandPropertyAssignment(i)||o.isMethodDeclaration(i))&&t.push(i.getName())}return{analyzable:!n,expiresInSeconds:s,presentKeys:t}},Mc=e=>{if(!o.isPropertyAccessExpression(e))return;const t=e.getName(),s=Lc.get(t);if(s===void 0)return;const n=e.getExpression().getText();return n==="ctx.storage"||n.startsWith("ctx.storage.")?{method:t,optionsIndex:s}:void 0},Kc=(e,t)=>{const s=Mc(e.getExpression());if(s!==void 0)return{exportName:E(e),file:t,line:e.getStartLineNumber(),method:s.method,...kc(e.getArguments()[s.optionsIndex])}},_c=(e,t)=>w(e,t,Kc),zc=(e,t)=>({analytics:e.analytics||t.dependencies.has("@lunora/bindings"),auth:t.dependencies.has("@lunora/auth"),containers:e.container||t.containerCount>0||t.dependencies.has("@lunora/container"),flags:e.flags||t.dependencies.has("@lunora/flags"),kv:e.kv||t.dependencies.has("@lunora/bindings"),mail:e.mail||t.dependencies.has("@lunora/mail"),notifications:e.notify||t.dependencies.has("@lunora/notify"),payments:e.payments||t.hasPaymentTables,queues:t.queueCount>0||t.dependencies.has("@lunora/queue"),scheduler:e.scheduler||t.cronCount>0||t.dependencies.has("@lunora/scheduler"),storage:e.storage||t.storageRuleCount>0||t.storageColumnCount>0||t.dependencies.has("@lunora/storage"),vectors:t.vectorStoreSupported&&(e.vectors||t.vectorIndexCount>0||t.dependencies.has("@lunora/bindings")),workflows:e.workflows||t.workflowCount>0||t.dependencies.has("@lunora/workflow")}),Uc=new Set(["RegisteredAction","RegisteredMutation","RegisteredQuery"]),Ie=e=>{const t=e.getType(),s=t.getAliasSymbol()?.getName()??t.getSymbol()?.getName();return s!==void 0&&Uc.has(s)?s:void 0},Gt=e=>{const t=e.getInitializer();return t===void 0?!1:o.isCallExpression(t)||o.isIdentifier(t)||o.isPropertyAccessExpression(t)},Yt={cause:"codegen recognises a procedure only when the initializer is a builder chain, and this one is produced by a call or an alias",remediation:"A factory that returns a procedure cannot be read statically — inline it, or export the chain the factory builds."},Bc={cause:"the binding is exported by a separate `export { … }` statement, and codegen reads the `export` keyword on the declaration itself",remediation:"Move the keyword onto the declaration and drop the separate export statement."},we=(e,t,s,n,i)=>({cacheKey:`procedure_not_registered:${e}:${t}`,categories:["SCHEMA"],description:"Codegen registers an export only when the declaration carries `export` and its initializer is literally a builder chain. A procedure written any other way exists at runtime but never reaches `_generated/api.ts`, so no caller can address it.",detail:`\`${t}\` in \`${e}\` (line ${n.toString()}) has type \`${s}\` but was not registered — ${i.cause}.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:t,filePath:e,line:n,typeName:s},name:"procedure_not_registered",remediation:`Assign the builder chain directly: \`export const ${t} = query.input({ … }).query(handler);\`. ${i.remediation}`,title:"Procedure exists at runtime but is missing from the generated API"}),$c=(e,t,s)=>{const n=[];for(const i of e.getVariableStatements().filter(r=>r.isExported()))for(const r of i.getDeclarations()){const a=r.getName();if(s.has(`${t}:${a}`)||!Gt(r))continue;const c=Ie(r);c!==void 0&&n.push(we(t,a,c,r.getStartLineNumber(),Yt))}return n},qc=(e,t,s)=>{if(s.has(`${t}:default`))return[];const n=[];for(const i of e.getExportAssignments().filter(r=>!r.isExportEquals())){const r=Ie(i.getExpression());r!==void 0&&n.push(we(t,"default",r,i.getStartLineNumber(),Yt))}return n},jc=(e,t,s)=>{const n=[];for(const i of e.getExportDeclarations().filter(r=>r.getModuleSpecifier()===void 0))for(const r of i.getNamedExports()){const a=r.getAliasNode()?.getText()??r.getName();if(s.has(`${t}:${a}`))continue;const c=r.getLocalTargetDeclarations().find(d=>o.isVariableDeclaration(d));if(c===void 0||!Gt(c))continue;const u=Ie(c);u!==void 0&&n.push(we(t,a,u,r.getStartLineNumber(),Bc))}return n},Vc=(e,t,s)=>[...$c(e,t,s),...qc(e,t,s),...jc(e,t,s)],Wc=(e,t,s)=>{const n=new Set(s.map(r=>`${r.filePath}:${r.exportName}`)),i=[];for(const r of m(t)){const a=e.getSourceFile(r);a!==void 0&&i.push(...Vc(a,v(t,r),n))}return i.toSorted((r,a)=>r.cacheKey.localeCompare(a.cacheKey))},Hc=new Set(["when","where"]),Ee=new Set(["definePolicy","defineShape"]),Gc=e=>{if(!o.isCallExpression(e))return;const t=e.getExpression();if(o.isPropertyAccessExpression(t)){const n=t.getName();return Ee.has(n)?n:void 0}if(!o.isIdentifier(t))return;for(const n of t.getSymbol()?.getDeclarations()??[])if(o.isImportSpecifier(n)){const i=n.getNameNode().getText();return Ee.has(i)?i:void 0}const s=t.getText();return Ee.has(s)?s:void 0},Yc=e=>o.isObjectLiteralExpression(e)&&e.getProperties().length===0,Qt=e=>{if(e!==void 0){if(o.isReturnStatement(e)&&e.getExpression()===void 0||e.getKind()===l.UndefinedKeyword||e.getText()==="undefined")return"undefined";if(Yc(e))return"empty-object";if(o.isParenthesizedExpression(e))return Qt(e.getExpression())}},Te=e=>e.getAncestors().find(t=>o.isArrowFunction(t)||o.isFunctionExpression(t)||o.isFunctionDeclaration(t)),Qc=e=>e.getDescendantsOfKind(l.ReturnStatement).filter(t=>Te(t)===e),Xt=e=>e.getDescendantsOfKind(l.ConditionalExpression).filter(t=>Te(t)===e),Xc=e=>{const t=Qc(e);return t.length>1?!0:t.some(s=>s.getFirstAncestorByKind(l.IfStatement)!==void 0)||Xt(e).length>0},Zc=e=>e.getDescendantsOfKind(l.IfStatement).filter(t=>Te(t)===e),Ne=e=>e.getKind()===l.NullKeyword||e.getKind()===l.FalseKeyword||o.isIdentifier(e)&&e.getText()==="undefined"?!0:o.isNumericLiteral(e)?e.getLiteralValue()===0:o.isStringLiteral(e)&&e.getLiteralValue()==="",Jc=(e,t)=>Ne(e)||Ne(t),el=new Map([[l.EqualsEqualsEqualsToken,"positive"],[l.EqualsEqualsToken,"positive"],[l.ExclamationEqualsEqualsToken,"negative"],[l.ExclamationEqualsToken,"negative"]]),St=e=>!Ne(e)&&(o.isLiteralExpression(e)||e.getKind()===l.TrueKeyword),tl=(e,t,s)=>{const n=el.get(e);if(n!==void 0)return Jc(t,s)?n==="positive"?"negative":"positive":St(t)||St(s)?void 0:n},j=e=>{if(o.isParenthesizedExpression(e))return j(e.getExpression());if(o.isPrefixUnaryExpression(e)&&e.getOperatorToken()===l.ExclamationToken)return"negative";if(o.isBinaryExpression(e)){const t=e.getOperatorToken().getKind(),s=tl(t,e.getLeft(),e.getRight());if(s!==void 0)return s;if(t===l.AmpersandAmpersandToken||t===l.BarBarToken){const n=j(e.getLeft()),i=j(e.getRight());return n===i?n:"indeterminate"}}return o.isIdentifier(e)||o.isPropertyAccessExpression(e)||o.isElementAccessExpression(e)||o.isCallExpression(e)?"positive":"indeterminate"},yt=e=>{if(e!==void 0){if(o.isReturnStatement(e))return e;if(o.isBlock(e)){const t=e.getStatements().at(-1);return t!==void 0&&o.isReturnStatement(t)?t:void 0}}},sl=e=>{if(e.getElseStatement()!==void 0)return;const t=e.getNextSiblingIfKind(l.ReturnStatement);return t!==void 0&&t.getNextSibling()===void 0?t:void 0},nl=e=>o.isReturnStatement(e)?e.getExpression()??e:e,rl=e=>{const t=[];for(const s of Xt(e)){const n=j(s.getCondition());n==="positive"?t.push(s.getWhenFalse()):n==="negative"&&t.push(s.getWhenTrue())}for(const s of Zc(e)){const n=j(s.getExpression());if(n==="indeterminate")continue;const i=n==="negative"?yt(s.getThenStatement()):yt(s.getElseStatement())??sl(s);i!==void 0&&t.push(nl(i))}return t},il=e=>{for(const t of e.getAncestors())if(o.isVariableDeclaration(t)){const s=t.getNameNode();if(o.isIdentifier(s))return s.getText()}return"<anonymous>"},ol=(e,t,s)=>{if(!o.isCallExpression(e))return[];const[n]=e.getArguments();if(!n||!o.isObjectLiteralExpression(n))return[];const i=[];for(const r of n.getProperties()){if(!o.isPropertyAssignment(r)||!Hc.has(r.getName()))continue;const a=r.getInitializer();if(!(!a||!(o.isArrowFunction(a)||o.isFunctionExpression(a)))&&Xc(a))for(const c of rl(a)){const u=Qt(c);u!==void 0&&i.push({exportName:il(e),file:s,form:u,key:r.getName(),line:c.getStartLineNumber(),owner:t})}}return i},al=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression)){const i=Gc(n);i!==void 0&&s.push(...ol(n,i,t))}return s},cl=(e,t)=>{const s=[];for(const n of m(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...al(i,v(t,n)))}return s},ll=new Set(["query","upsert","upsertMany"]),ul=e=>{if(!o.isPropertyAccessExpression(e))return;const t=e.getName();if(ll.has(t))return e.getExpression().getText()==="ctx.vectors"?t:void 0},dl=(e,t)=>{const s=ul(e.getExpression());if(s===void 0)return;const n=e.getArguments()[1];if(!n)return;const i=N(n,"namespace");if(!(!i||!R(i)||_(i)))return{exportName:E(e),file:t,line:e.getStartLineNumber(),method:s}},fl=(e,t)=>w(e,t,dl),pl=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||t.getName()!=="get")return!1;const s=t.getExpression();return o.isPropertyAccessExpression(s)?s.getName()==="workflows":o.isIdentifier(s)&&s.getText()==="workflows"},gl=e=>{const t=e.getArguments()[0];return t&&o.isStringLiteral(t)?t.getLiteralText():""},ml=(e,t)=>{const s=[];for(const n of m(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=v(t,n);for(const a of i.getDescendantsOfKind(l.CallExpression)){if(!pl(a))continue;const c=Ms(a);c!==""&&s.push({exportName:c,file:r,line:a.getStartLineNumber(),workflow:gl(a)})}}return s},hl=".lunora-schema.json",T=(e,t)=>{P(e)&&bt(e,"utf8")===t||ls(e,t,"utf8")},O=(e,t)=>{if(t===""){us(e,{force:!0});return}T(e,t)},xl=e=>{const t=f(e,"package.json");if(P(t))try{const s=JSON.parse(bt(t,"utf8"));return typeof s.version=="string"&&s.version!==""?s.version:void 0}catch{return}},El=()=>{const e=process.env.LUNORA_CODEGEN_TIMING;return e!==void 0&&e!==""},vl=e=>{let t=P(e)?e:X(e);for(;t&&t!==X(t);){const s=f(t,"tsconfig.json");if(P(s))return s;t=X(t)}},At=e=>e.replaceAll("\\","/"),Sl=(e,t,s)=>{if(s&&e.length>0){const r=e.map(a=>`"${a.exportName}"`).join(", ");throw new k("MASK_UNSUPPORTED",`This project declares a \`mask(...)\` policy whose argument isn't a plain object literal (e.g. \`mask(sharedPolicies)\` referencing a hoisted variable), or contains a spread (\`...shared\`) or computed key (\`[name]:\`) codegen can't enumerate, so codegen can't tell which columns it masks. Because the project also declares replication shape(s) (${r}), codegen can't verify none of them replicate a table that policy masks — inline every table and column as literal keys so codegen can verify it, or remove the affected shape(s).`,{status:422})}const n=new Map;for(const r of t.columns){const a=n.get(r.table)??[];a.push(r.column),n.set(r.table,a)}const i=t.columns.length>0;for(const r of e){if(r.table===void 0){if(i)throw new k("MASK_UNSUPPORTED",`defineShape "${r.exportName}" has a non-literal \`table\` (a variable or expression, not a string literal), so codegen can't statically verify it doesn't replicate a table that masks a column. This project masks at least one column elsewhere, so the combination can't be proven safe — change "${r.exportName}"'s \`table\` to a plain string literal so codegen can verify it, or remove the mask(s) on the table it targets.`,{status:422});continue}const a=n.get(r.table);if(a===void 0)continue;const c=a.map(u=>`"${u}"`).join(", ");throw new k("MASK_UNSUPPORTED",`defineShape "${r.exportName}" replicates table "${r.table}", which masks column(s) ${c} on at least one procedure. A shape runs no procedure, so \`.use(mask(...))\` never applies to its replicated rows — remove the shape, unmask the table, or wait for shape-masking support.`,{status:422})}},ne=(e,t,s)=>{const n=e.getSourceFile(t);if(n===void 0){e.createSourceFile(t,s,{overwrite:!0});return}n.getFullText()!==s&&n.replaceWithText(s)},Nt=(e,t,s)=>e.getSourceFile(t)?.getFullText()===s,yl=8,Al=e=>{const{agents:t,apiPath:s,generatedFunctionsPath:n,lunoraDirectory:i,migrations:r,project:a,shapes:c,usesSandbox:u,useUmbrella:d,workflows:S}=e;let x=tt(a,i),I=nt(a,i),g=st(a,i);rt([...x,...I].map(A=>A.filePath)),rt(g.filter(A=>A.stream).map(A=>A.filePath),"http-stream");for(let A=1;;A+=1){const C=Rs({agents:t,functions:x,httpRoutes:g,mutators:I,useUmbrella:d,workflows:S}),L=Ls({agents:t,functions:x,migrations:r,mutators:I,shapes:c,useUmbrella:d,usesSandbox:u});if(A>=yl||Nt(a,s,C)&&Nt(a,n,L))return{apiContent:C,functions:x,functionsContent:L,httpRoutes:g,mutators:I};ne(a,s,C),ne(a,n,L),x=tt(a,i),I=nt(a,i),g=st(a,i)}},Nl=e=>{const t=vl(e);return t?new Je({skipAddingFilesFromTsConfig:!1,tsConfigFilePath:t,useInMemoryFileSystem:!1}):new Je({skipAddingFilesFromTsConfig:!0,useInMemoryFileSystem:!1})},xu=(e,t)=>{const s=m(t),n=f(t,"schema.ts");P(n)&&s.push(n);for(const c of s){const u=e.getSourceFile(c);u===void 0?e.addSourceFileAtPath(c):u.refreshFromFileSystemSync()}const i=new Set(s.map(c=>At(c))),r=At(t),a=`${r}/`;for(const c of e.getSourceFiles()){const u=c.getFilePath();(u===r||u.startsWith(a))&&!i.has(u)&&e.removeSourceFile(c)}for(const c of e.getSourceFiles()){const u=c.getFilePath();if(!(u===r||u.startsWith(a)||u.includes("/node_modules/")))try{c.refreshFromFileSystemSync()}catch{e.removeSourceFile(c)}}},Eu=e=>{const t=El(),s=t?ge.now():0,n=f(e.projectRoot,e.lunoraDirectory??"lunora"),i=f(n,"schema.ts");if(!P(i))throw new k("INTERNAL",`schema.ts not found at ${i}`);const r=e.project??Nl(n);bn(Pi);const a=pn(r,i,e.projectRoot),{agents:c,containers:u,crons:d,dataModelContent:S,dependencies:x,env:I,featureUsage:g,hasFlags:A,hasNotify:C,identity:L,platformGate:b,queues:D,serverContent:U,storageRulesMetadata:$,usesSandbox:W,useUmbrella:K,workflows:F}=qn({lunoraDirectory:n,project:r,projectRoot:e.projectRoot,schema:a,target:e.target}),p=f(n,"_generated"),Ce=f(p,"dataModel.ts"),Fe=f(p,"server.ts"),Zt=f(p,"api.ts"),Jt=f(p,"functions.ts");ne(r,Ce,S),ne(r,Fe,U);const ce=nn(r,n),q=En(r,n),{apiContent:Oe,functions:B,functionsContent:Re,httpRoutes:es,mutators:ts}=Al({agents:c,apiPath:Zt,generatedFunctionsPath:Jt,lunoraDirectory:n,migrations:ce,project:r,shapes:q,useUmbrella:K,usesSandbox:W,workflows:F}),H=e.lint===!1?void 0:ps({adminRoutes:Xn(r,n),aiRawRuns:er(r,n),aiToolSideEffects:ur(r,n),argumentDerivedFetches:pr(r,n),argumentValidators:Nr(r,n),authApiCalls:Qs(r,n),authConfigs:Lr(r,n),browserUrlAccesses:_r(r,n),configCalls:Gr(r,n),containerKeyAccesses:Qr(r,n),containerOverrides:si(r,n),containers:u,exportSinks:oi(r,n),staleMigrationImports:Fc(r,n),failOpenGuards:di(r,n),flagReads:Si(r,n),flagSecurityDefaults:bi(r,n),geoIndexUsages:Ti(r,n),httpActionGuards:ki(r,n),httpHeaderWrites:Vi(r,n),hyperdriveCalls:en(r,n),identityClaimReads:Zi(r,n),imageDeliveryUrlAccesses:eo(r,n),inserts:tn(r,n),kvKeyAccesses:so(r,n,B),mailRecipientAccesses:ao(r,n),maskProcedures:sn(r,n),maskStrategies:ho(r,n),mutatorWrites:Ao(r,n),nondeterministicCalls:an(r,n),normalizeIdAuthorizations:_o(r,n),notifyCalls:ln(r,n),notifyConfig:cn(r,n),ownerFieldWrites:Wo(r,n,B),unrestrictedWhereBranches:cl(r,n),paymentWebhooks:ea(r,n),privilegedDispatches:pa(r,n),procedureProtections:Xa(r,n),queries:Gs(r,n),queues:D,r2sqlCalls:un(r,n),ratelimitKeySelectors:tc(r,n),rawRowReturns:cc(r,n),relationLoads:dc(r,n),rlsProcedures:dn(r,n),schema:a,secretLiterals:vc(r,n),shapes:q,softDeleteReads:yc(r,n),sqlInterpolations:wc(r,n),storageKeyAccesses:Rc(r,n,B),storageUploads:_c(r,n),vectorNamespaceAccesses:fl(r,n),workflowCalls:ml(r,n),workflows:F,wranglerVariables:e.wranglerVariables}),Le=H===void 0?[]:[...ds(H,{source:"static"}),...Wc(r,n,B)],ss=fn(r,n),De=po(r,n);Sl(q,De,uo(r,n));const ns=A?mi(r,n):[],le=b.signals.vectorStore!==!1,G=zc(g,{containerCount:u.length,cronCount:d.length,dependencies:x,hasPaymentTables:Yo(a.tables),queueCount:D.length,storageColumnCount:Object.keys(Ss(a)).length,storageRuleCount:$.rules.length,vectorIndexCount:a.vectorIndexes.length,vectorStoreSupported:le,workflowCount:F.length}),ke=t?ge.now():0,ue=Pn(a,ce.map(h=>h.id)),Me=ys({advisories:Le,advisorProcedures:H?.procedureProtections??[],agents:c,containers:u,env:I,flagKeys:ns,hasAccessFacade:g.access,hasAi:g.ai,hasAnalytics:g.analytics,hasBrowser:g.browser,hasFlags:A,hasHyperdrive:g.hyperdrive,hasImages:g.images,hasKv:g.kv,hasNotify:C,hasPayments:g.payments,hasPipelines:g.pipelines,hasR2sql:g.r2sql,hasVectors:le,hasX402:g.x402,maskMetadata:De,mutators:ts,queues:D,rlsMetadata:ss,schema:a,schemaSnapshot:ue,shapes:q,storageRules:$,studioFeatures:G,useUmbrella:K,workflows:F}),Ke=As(q,x.has("@lunora/db"),K),_e=Ns(u,a.jurisdiction),ze=bs(F),Ue=Ps(c),Be=Is(D),$e=ws(d),qe=Ts(a.vectorIndexes),Y=Cs(a,K),je=Fs(x.has("@lunora/seed")),Q=e.apiSpec??"openapi",de=Q==="openapi"||Q==="both",fe=Q==="openrpc"||Q==="both",Ve=vn({emailAgents:c.filter(h=>h.onEmail===!0).map(h=>({bindingName:h.bindingName,exportName:h.exportName})),hasAccess:x.has("@lunora/cloudflare-access"),hasAi:g.ai,hasAnalytics:g.analytics,hasAuth:x.has("@lunora/auth"),hasBrowser:g.browser,hasFramework:x.has("@lunora/astro")||x.has("@lunora/svelte")||x.has("@lunora/vue"),hasGlobal:a.tables.some(h=>h.shardMode==="global"&&h.globalBackend!=="hyperdrive"),hasHyperdrive:g.hyperdrive,hasHyperdriveGlobal:a.tables.some(h=>h.shardMode==="global"&&h.globalBackend==="hyperdrive"),hasImages:g.images,hasKv:g.kv,hasKvIntrospector:G.kv,hasNotify:C,hasPayments:g.payments,hasR2sql:g.r2sql,hasQueue:D.some(h=>h.mode==="push"),hasScheduler:G.scheduler,hasStorage:G.storage,hasVectors:le,hasWorkflow:F.length>0,hasX402:g.x402,identity:L,jurisdiction:a.jurisdiction,tableNames:a.tables.map(h=>h.name),useUmbrella:K,vectorIndexCount:a.vectorIndexes.length,voiceAgents:c.filter(h=>h.voice===!0&&h.voiceBindingName!==void 0).map(h=>({bindingName:h.voiceBindingName,exportName:h.exportName})),wantsOpenApi:de,wantsOpenRpc:fe}),We=xl(e.projectRoot),He=Sn({functions:B,httpRoutes:es,version:We}),Ge=An({functions:B,version:We}),Ye=`${JSON.stringify(He,void 0,2)}
|
|
8
|
-
`,Qe=`${JSON.stringify(Ge,void 0,2)}
|
|
9
|
-
`,Xe=yn(He),Ze=Nn(Ge),pe=f(n,hl),rs=P(pe);if(e.dryRun||(P(p)||cs(p,{recursive:!0}),T(f(p,"app.ts"),Ve),T(Ce,S),T(f(p,"api.ts"),Oe),T(Fe,U),T(f(p,"functions.ts"),Re),T(f(p,"shard.ts"),Me),T(f(p,"crons.ts"),$e),T(f(p,"vectors.ts"),qe),T(f(p,"drizzle.global.ts"),Y.global),T(f(p,"drizzle.shard.ts"),Y.shard),O(f(p,"containers.ts"),_e),O(f(p,"workflows.ts"),ze),O(f(p,"agents.ts"),Ue),O(f(p,"queues.ts"),Be),O(f(p,"seed.ts"),je),O(f(p,"collections.ts"),Ke),O(f(p,"openapi.json"),de?Ye:""),O(f(p,"openapi.ts"),de?Xe:""),O(f(p,"openrpc.json"),fe?Qe:""),O(f(p,"openrpc.ts"),fe?Ze:""),(!rs||e.updateSchemaBaseline===!0)&&T(pe,fs(ue))),t){const h=ge.now(),is=Math.round(h-s),os=Math.round(ke-s),as=Math.round(h-ke);console.error(`@lunora/codegen: codegen took ${is.toString()}ms (discovery ${os.toString()}ms, emit ${as.toString()}ms)`)}return{advisories:Le,advisorContext:H,agents:c,containers:u,cronTriggers:Os(d),generated:{agents:Ue,api:Oe,app:Ve,collections:Ke,containers:_e,crons:$e,dataModel:S,drizzleGlobal:Y.global,drizzleShard:Y.shard,functions:Re,openApi:Ye,openApiModule:Xe,openRpc:Qe,openRpcModule:Ze,queues:Be,seed:je,server:U,shard:Me,vectors:qe,workflows:ze},migrations:ce,outputDirectory:p,platformDiagnostics:b.diagnostics,queues:D,schemaSnapshot:ue,schemaSnapshotPath:pe,workflows:F}};export{hl as SCHEMA_SNAPSHOT_FILENAME,Nl as createCodegenProject,vl as findTsconfig,xu as refreshCodegenProject,Eu as runCodegen};
|