@lunora/codegen 1.0.0-alpha.108 → 1.0.0-alpha.109
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +0 -1
- package/dist/index.d.ts +0 -1
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/AGENTS_FILENAME-CPHo8Se5.mjs +1 -0
- package/dist/packem_shared/{CONTAINERS_FILENAME-DQpyhY6c.mjs → CONTAINERS_FILENAME-Bvn6LZP6.mjs} +1 -1
- package/dist/packem_shared/CodegenDiagnosticError-BUXlG3P-.mjs +1 -0
- package/dist/packem_shared/DEFAULT_TARGET-CIH5PRk1.mjs +1 -0
- package/dist/packem_shared/FLAGS_FILENAME-DtBWyUKq.mjs +1 -0
- package/dist/packem_shared/GENERATED_HEADER-GSCh67g3.mjs +1 -0
- package/dist/packem_shared/{LUNORA_ERROR_CODES-zfAI2OFs.mjs → LUNORA_ERROR_CODES-BYg8Lpgb.mjs} +1 -1
- package/dist/packem_shared/MUTATORS_FILENAME-CRmTpN4y.mjs +1 -0
- package/dist/packem_shared/NOTIFY_FILENAME-BybR3Xbd.mjs +1 -0
- package/dist/packem_shared/OPENRPC_VERSION-DB1PSt8W.mjs +3 -0
- package/dist/packem_shared/QUEUES_FILENAME-BnGLtAIu.mjs +1 -0
- package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-D9rvsQ0t.mjs +9 -0
- package/dist/packem_shared/SCHEMA_SNAPSHOT_VERSION-DIqnj_32.mjs +2 -0
- package/dist/packem_shared/SDK_LANGUAGES-p7vq4x7B.mjs +320 -0
- package/dist/packem_shared/SHAPES_FILENAME-DxoIrQhA.mjs +1 -0
- package/dist/packem_shared/SchemaSnapshotParseError-Dc1aZAph.mjs +16 -0
- package/dist/packem_shared/WORKFLOWS_FILENAME-B8y51Frf.mjs +1 -0
- package/dist/packem_shared/buildOpenApiDocument-B2mW3f5a.mjs +3 -0
- package/dist/packem_shared/describeErrorLevelFindings-D23VSkFP.mjs +1 -0
- package/dist/packem_shared/discover-ast-D33zP-NZ.mjs +1 -0
- package/dist/packem_shared/discover-queries-Dfj_0WJG.mjs +1 -0
- package/dist/packem_shared/discoverAuthApiCalls-DUjcl0SB.mjs +1 -0
- package/dist/packem_shared/discoverCrons-BUJO2ipU.mjs +1 -0
- package/dist/packem_shared/discoverFunctions-h8i51Mec.mjs +1 -0
- package/dist/packem_shared/discoverHttpRoutes-MX6y-iVE.mjs +1 -0
- package/dist/packem_shared/discoverInserts-YX8AmrzL.mjs +1 -0
- package/dist/packem_shared/discoverMaskProcedures-DhcK-YMG.mjs +1 -0
- package/dist/packem_shared/discoverMigrations-4Jjf5DJE.mjs +1 -0
- package/dist/packem_shared/discoverNondeterministicCalls-CjS2Mznw.mjs +1 -0
- package/dist/packem_shared/discoverQueries-C5S9tFoD.mjs +1 -0
- package/dist/packem_shared/discoverR2sqlCalls-DuTuaSMM.mjs +1 -0
- package/dist/packem_shared/discoverRlsMetadata-BYVq6cVp.mjs +1 -0
- package/dist/packem_shared/{discoverSandboxUsage-DBM98vVh.mjs → discoverSandboxUsage-L0lV17de.mjs} +1 -1
- package/dist/packem_shared/discoverSchema-BtlNz9b_.mjs +1 -0
- package/dist/packem_shared/discoverStorageRulesMetadata-CKPFWHT5.mjs +1 -0
- package/dist/packem_shared/{emit-BbLyaTLJ.mjs → emit-Ba3NiOwK.mjs} +326 -326
- package/dist/packem_shared/{emitApp-DkO-Qvoo.mjs → emitApp-hKEej7rj.mjs} +18 -18
- package/dist/packem_shared/formatAdvisories-BjTV22uR.mjs +2 -0
- package/dist/packem_shared/isTypedSchema-CU-O5qSH.mjs +2 -0
- package/dist/packem_shared/module-specifiers-WF8iAydP.mjs +1 -0
- package/dist/packem_shared/parse-validator-DtALyvid.mjs +1 -0
- package/dist/packem_shared/paths-C-9fwEgQ.mjs +1 -0
- package/dist/packem_shared/readPackageDependencies-C6h6FZuP.mjs +1 -0
- package/dist/packem_shared/redact-Cy14LEnc.mjs +1 -0
- package/dist/packem_shared/schemaFromIr-BWFnvCVg.mjs +1 -0
- package/package.json +3 -3
- package/dist/packem_shared/AGENTS_FILENAME-Dk-k250h.mjs +0 -1
- package/dist/packem_shared/CodegenDiagnosticError-DPezpZTz.mjs +0 -1
- package/dist/packem_shared/DEFAULT_TARGET-CH5disA3.mjs +0 -1
- package/dist/packem_shared/FLAGS_FILENAME-Boqm0YCP.mjs +0 -1
- package/dist/packem_shared/GENERATED_HEADER-CtitJsDk.mjs +0 -1
- package/dist/packem_shared/MUTATORS_FILENAME-Cp_JxLSz.mjs +0 -1
- package/dist/packem_shared/NOTIFY_FILENAME-DwyJ5I4Q.mjs +0 -1
- package/dist/packem_shared/OPENRPC_VERSION-Bzh1vxcl.mjs +0 -3
- package/dist/packem_shared/QUEUES_FILENAME-QpMZsde0.mjs +0 -1
- package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-lAJi8U-X.mjs +0 -9
- package/dist/packem_shared/SCHEMA_SNAPSHOT_VERSION-CFhF_hmg.mjs +0 -2
- package/dist/packem_shared/SDK_LANGUAGES-fIqQtE14.mjs +0 -320
- package/dist/packem_shared/SHAPES_FILENAME-WxXOsYfe.mjs +0 -1
- package/dist/packem_shared/SchemaSnapshotParseError-BkgxjBPQ.mjs +0 -16
- package/dist/packem_shared/WORKFLOWS_FILENAME-Dz80zqeT.mjs +0 -1
- package/dist/packem_shared/buildOpenApiDocument-B8-PH9af.mjs +0 -3
- package/dist/packem_shared/describeErrorLevelFindings-IhNx9gPr.mjs +0 -1
- package/dist/packem_shared/discover-ast-7ABwvTVn.mjs +0 -1
- package/dist/packem_shared/discover-queries-CU9o_j87.mjs +0 -1
- package/dist/packem_shared/discoverAuthApiCalls-XfNbxqlq.mjs +0 -1
- package/dist/packem_shared/discoverCrons-RlATa0_t.mjs +0 -1
- package/dist/packem_shared/discoverFunctions-4TNKUv7P.mjs +0 -1
- package/dist/packem_shared/discoverHttpRoutes-DQivLBqT.mjs +0 -1
- package/dist/packem_shared/discoverInserts-D6szWzrV.mjs +0 -1
- package/dist/packem_shared/discoverMaskProcedures-BBPqLXA5.mjs +0 -1
- package/dist/packem_shared/discoverMigrations-rbjxflR8.mjs +0 -1
- package/dist/packem_shared/discoverNondeterministicCalls-Bxr652Rz.mjs +0 -1
- package/dist/packem_shared/discoverQueries-CIU5dc0u.mjs +0 -1
- package/dist/packem_shared/discoverR2sqlCalls-DMxG6gHr.mjs +0 -1
- package/dist/packem_shared/discoverRlsMetadata-B63ARnKG.mjs +0 -1
- package/dist/packem_shared/discoverSchema-BNr7PVcZ.mjs +0 -1
- package/dist/packem_shared/discoverStorageRulesMetadata-_40MGqRX.mjs +0 -1
- package/dist/packem_shared/formatAdvisories-CQvIhQ04.mjs +0 -2
- package/dist/packem_shared/isTypedSchema-9wiKtXr2.mjs +0 -2
- package/dist/packem_shared/module-specifiers-8FEEiUcv.mjs +0 -1
- package/dist/packem_shared/parse-validator-CusS8QwU.mjs +0 -1
- package/dist/packem_shared/paths-BmX5O1sG.mjs +0 -1
- package/dist/packem_shared/readPackageDependencies-CogJX1Ia.mjs +0 -1
- package/dist/packem_shared/redact-6jD4lAhq.mjs +0 -1
- package/dist/packem_shared/schemaFromIr-R1ZFzVyy.mjs +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{A as S,G as D}from"./emit-Ba3NiOwK.mjs";const E=e=>`has${e.charAt(0).toUpperCase()}${e.slice(1)}`,v=S.map(({appMethod:e,key:t})=>[E(t),e.method,e.configKey,e.doc]),g=e=>v.some(([t])=>e[t]),A=e=>e?['import * as lunoraIdentityContract from "../identity.js";']:[],R=(e,t)=>e?['import type { CreateAccessResolverOptions } from "@lunora/cloudflare-access";',`import { createAccessResolver${t?", composeResolvers":""} } from "@lunora/cloudflare-access";`]:[],x=e=>e?['import { createKvIntrospectorFromEnv } from "@lunora/bindings/kv";']:[],O=e=>e?['import notifyConfig from "../notify.js";']:[],k=e=>(e.emailAgents?.length??0)>0,L=e=>k(e)?['import { dispatchAgentEmail } from "@lunora/agent/inbound";']:[],C=e=>k(e)?['import * as lunoraAgentDefinitions from "../agents.js";']:[],T=e=>{const{hasAccess:t,hasAuth:r,hasFramework:a,hasGlobal:n,hasHyperdriveGlobal:o,hasKv:c,hasQueue:s,hasScheduler:d,hasStorage:u,hasWorkflow:h,useUmbrella:l,wantsOpenApi:p,wantsOpenRpc:b}=e,i=l?"lunorash/runtime":"@lunora/runtime",m=["ExecutionContextLike","HttpRouterLike","LunoraWorker","Route","ScheduledControllerLike","ShardNamespaceLike","WorkerOptions"];n&&m.push("GlobalIntrospector","AdminTableResolver"),a&&m.push("FrameworkHostHandler");const f=[...n||o?["createCrossShardRelationCapabilities"]:[],"createWorker","resolveLogArchiveFromEnv",...a?["withFrameworkWorker"]:[]].join(", ");return[...r?['import type { AuthNamespaceLike, LunoraAuth, LunoraAuthOptions } from "@lunora/auth";','import { createAuth, createAuthAdmin, createAuthAuditReader, createDoAuthWiring, d1Executor, ensureMigrated, handleAuthRequest, lunoraD1Adapter } from "@lunora/auth";']:[],...R(t,r),...n?['import type { D1CtxDbOptions, D1DatabaseLike, D1Exec } from "@lunora/d1";','import { createD1CtxDb, facetGlobalColumn, importGlobalRows, listGlobalTables, readGlobalTablePage } from "@lunora/d1";']:[],...o?['import type { HyperdriveEngine } from "@lunora/hyperdrive/global";','import { createHyperdriveGlobalCtxDb } from "@lunora/hyperdrive/global";','import type { SqlCtxDbOptions, SqlExec } from "@lunora/sql-store";']:[],...x(c),...d?['import type { DurableObjectNamespaceLike } from "@lunora/scheduler";','import { createScheduler } from "@lunora/scheduler";']:[],...u?['import type { R2BucketLike, Storage } from "@lunora/storage";','import { createBucketStorage, createStorage } from "@lunora/storage";']:[],...h?['import { createWorkflowsRestClient } from "@lunora/workflow";']:[],...L(e),`import type { ${[...m].toSorted((w,y)=>w.localeCompare(y)).join(", ")} } from "${i}";`,`import { ${f} } from "${i}";`,"",...A(e.identity),...C(e),...n||o?['import schema from "../schema.js";']:[],...O(e.hasNotify),'import { LUNORA_CRONS } from "./crons.js";','import { LUNORA_FUNCTIONS } from "./functions.js";',...s?['import { createQueueCaptureSink, dispatchQueueBatch, shouldCaptureQueue } from "@lunora/queue";','import { LUNORA_QUEUE_REGISTRY } from "./queues.js";']:[],...p?['import { openApiSpec } from "./openapi.js";']:[],...b?['import { openRpcSpec } from "./openrpc.js";']:[],'import { createShardDO } from "./shard.js";']},I=e=>[...e.hasStorage?[`/** \`.storage(...)\` declaration — one bucket (required) plus optional extra named buckets and signed-URL config. Backs \`ctx.storage\` AND the studio file browser. */
|
|
2
2
|
interface StorageDeclaration<Env> {
|
|
3
3
|
/** The default R2 bucket binding (the bare \`ctx.storage\`). */
|
|
4
4
|
bucket: Selector<Env, R2BucketLike>;
|
|
@@ -8,12 +8,12 @@ interface StorageDeclaration<Env> {
|
|
|
8
8
|
publicBaseUrl?: Selector<Env, string>;
|
|
9
9
|
/** HMAC secret for signed URLs. */
|
|
10
10
|
signingSecret?: Selector<Env, string>;
|
|
11
|
-
}`]:[],...e.hasScheduler?["/** `.scheduler(...)` declaration — the `SchedulerDO` namespace plus the worker origin its callbacks dispatch back to. Backs `ctx.scheduler` AND the studio's scheduled-jobs view. */\ninterface SchedulerDeclaration<Env> {\n /** The `SchedulerDO` namespace binding (typically `env.SCHEDULER`). */\n namespace: Selector<Env, DurableObjectNamespaceLike & ShardNamespaceLike>;\n /** The worker origin the `SchedulerDO` dispatches HTTP job callbacks back to. */\n origin?: Selector<Env, string>;\n}"]:[],...e.hasGlobal?["/** `.global(...)` declaration — the D1 binding backing `.global()` tables. Backs cross-tenant `ctx.db` reads/writes AND the studio's global data browser. */\ninterface GlobalDeclaration<Env> {\n /** The D1 binding (typically `env.DB`). */\n d1: Selector<Env, D1DatabaseLike>;\n /** The worker origin used to fan reverse cross-backend relations across shards. Without it, such a relation throws a clear error. */\n origin?: Selector<Env, string>;\n}"]:[],...e.hasHyperdriveGlobal?['/** `.hyperdriveGlobal(...)` declaration — backs `.global({ backend: "hyperdrive" })` tables on a Postgres/MySQL database via Hyperdrive. Stays reactive: the writer is injected as `globalDb` and the broadcast hook drives live queries. */\ninterface HyperdriveGlobalDeclaration<Env> {\n /** The Hyperdrive engine — selects the Postgres or MySQL dialect. */\n engine: HyperdriveEngine;\n /** Build the `SqlExec` from `env` — e.g. `buildPgExec(fromPostgresJs(postgres(env.HYPERDRIVE.connectionString)))`. Cache the driver on the DO instance; rebuild lazily after hibernation. */\n exec: (env: Env) => SqlExec;\n /** The worker origin used to fan reverse cross-backend relations across shards. Without it, such a relation throws a clear error. */\n origin?: Selector<Env, string>;\n}']:[],...e.hasAuth?['/** `.auth(...)` declaration — better-auth options plus the 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}']:[]],
|
|
12
|
-
public ${t}(factory: NonNullable<ShardConfig["${
|
|
13
|
-
this.shardExtras.${
|
|
11
|
+
}`]:[],...e.hasScheduler?["/** `.scheduler(...)` declaration — the `SchedulerDO` namespace plus the worker origin its callbacks dispatch back to. Backs `ctx.scheduler` AND the studio's scheduled-jobs view. */\ninterface SchedulerDeclaration<Env> {\n /** The `SchedulerDO` namespace binding (typically `env.SCHEDULER`). */\n namespace: Selector<Env, DurableObjectNamespaceLike & ShardNamespaceLike>;\n /** The worker origin the `SchedulerDO` dispatches HTTP job callbacks back to. */\n origin?: Selector<Env, string>;\n}"]:[],...e.hasGlobal?["/** `.global(...)` declaration — the D1 binding backing `.global()` tables. Backs cross-tenant `ctx.db` reads/writes AND the studio's global data browser. */\ninterface GlobalDeclaration<Env> {\n /** The D1 binding (typically `env.DB`). */\n d1: Selector<Env, D1DatabaseLike>;\n /** The worker origin used to fan reverse cross-backend relations across shards. Without it, such a relation throws a clear error. */\n origin?: Selector<Env, string>;\n}"]:[],...e.hasHyperdriveGlobal?['/** `.hyperdriveGlobal(...)` declaration — backs `.global({ backend: "hyperdrive" })` tables on a Postgres/MySQL database via Hyperdrive. Stays reactive: the writer is injected as `globalDb` and the broadcast hook drives live queries. */\ninterface HyperdriveGlobalDeclaration<Env> {\n /** The Hyperdrive engine — selects the Postgres or MySQL dialect. */\n engine: HyperdriveEngine;\n /** Build the `SqlExec` from `env` — e.g. `buildPgExec(fromPostgresJs(postgres(env.HYPERDRIVE.connectionString)))`. Cache the driver on the DO instance; rebuild lazily after hibernation. */\n exec: (env: Env) => SqlExec;\n /** The worker origin used to fan reverse cross-backend relations across shards. Without it, such a relation throws a clear error. */\n origin?: Selector<Env, string>;\n}']:[],...e.hasAuth?['/** `.auth(...)` declaration — better-auth options plus the 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}']:[]],j=e=>[...e.hasAccess?[" private accessSelector?: Selector<Env, CreateAccessResolverOptions>;"]:[]," private adminToken?: Selector<Env, string>;",...e.hasAuth?[" private authDeclaration?: AuthDeclaration<Env>;"]:[]," private readonly extendFns: ((env: Env, derived: Readonly<WorkerOptions>) => Partial<WorkerOptions>)[] = [];",...e.hasGlobal?[" private globalDeclaration?: GlobalDeclaration<Env>;"]:[],...e.hasHyperdriveGlobal?[" private hyperdriveGlobalDeclaration?: HyperdriveGlobalDeclaration<Env>;"]:[]," private httpRouterApp?: HttpRouterLike;"," private readonly routeMap: Record<string, Route> = {};",...e.hasScheduler?[" private schedulerDeclaration?: SchedulerDeclaration<Env>;"]:[],...g(e)?[" private readonly shardExtras: Partial<ShardConfig> = {};"]:[]," private shardSelector?: Selector<Env, ShardNamespaceLike>;",...e.hasStorage?[" private storageDeclaration?: StorageDeclaration<Env>;"]:[]],N=e=>v.filter(([t])=>e[t]).map(([,t,r,a])=>` /** ${a} */
|
|
12
|
+
public ${t}(factory: NonNullable<ShardConfig["${r}"]>): this {
|
|
13
|
+
this.shardExtras.${r} = factory;
|
|
14
14
|
|
|
15
15
|
return this;
|
|
16
|
-
}`),
|
|
16
|
+
}`),q=e=>[...e.hasAccess?[" /** Wire Cloudflare Access (Zero Trust) — verifies the `Cf-Access-Jwt-Assertion` JWT and feeds the identity into `ctx.auth` / RLS via `resolveIdentity`. When `.auth(...)` is also configured, Access is composed ahead of it (Access wins when its JWT is present; everyone else falls through to the app session). */\n public access(selector: Selector<Env, CreateAccessResolverOptions>): this {\n this.accessSelector = selector;\n\n return this;\n }"]:[],` /** Bearer token gating the \`/_lunora/admin/*\` endpoints the studio calls. */
|
|
17
17
|
public admin(selector: Selector<Env, string>): this {
|
|
18
18
|
this.adminToken = selector;
|
|
19
19
|
|
|
@@ -110,7 +110,7 @@ interface StorageDeclaration<Env> {
|
|
|
110
110
|
return namespace && origin ? createScheduler({${e.jurisdiction?` jurisdiction: ${JSON.stringify(e.jurisdiction)},`:""} namespace, originUrl: origin }) : undefined;
|
|
111
111
|
},
|
|
112
112
|
}
|
|
113
|
-
: {}),`]:[],...e.hasStorage?[" ...(this.storageDeclaration ? { storage: (rawEnv: Record<string, unknown>) => this.resolveStorage(rawEnv as Env) } : {}),"]:[],...
|
|
113
|
+
: {}),`]:[],...e.hasStorage?[" ...(this.storageDeclaration ? { storage: (rawEnv: Record<string, unknown>) => this.resolveStorage(rawEnv as Env) } : {}),"]:[],...g(e)?[" ...this.shardExtras,"]:[]];return t.length>0?`
|
|
114
114
|
${t.join(`
|
|
115
115
|
`)}
|
|
116
116
|
`:""},W=e=>[...e.hasScheduler?[` if (this.schedulerDeclaration) {
|
|
@@ -200,7 +200,7 @@ ${t.join(`
|
|
|
200
200
|
}`]:[],...e.voiceAgents&&e.voiceAgents.length>0?[` options.voiceAgents = {
|
|
201
201
|
${e.voiceAgents.map(t=>` ${JSON.stringify(t.exportName)}: (env as Record<string, unknown>)[${JSON.stringify(t.bindingName)}] as ShardNamespaceLike,`).join(`
|
|
202
202
|
`)}
|
|
203
|
-
};`]:[]]
|
|
203
|
+
};`]:[]],B=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?`
|
|
204
204
|
/** Resolve the storage capability (single or multi-bucket) for the DO side. */
|
|
205
205
|
private resolveStorage(env: Env): Storage | undefined {
|
|
206
206
|
const declaration = this.storageDeclaration;
|
|
@@ -374,7 +374,7 @@ const buildGlobalImporter =
|
|
|
374
374
|
startLine: request.startLine,
|
|
375
375
|
});
|
|
376
376
|
};
|
|
377
|
-
`:"",
|
|
377
|
+
`:"",P=e=>[...e.hasAuth?["AuthDeclaration"]:[],"ComposedApp",...e.hasGlobal?["GlobalDeclaration"]:[],...e.hasScheduler?["SchedulerDeclaration"]:[],"Selector",...e.hasStorage?["StorageDeclaration"]:[]].toSorted((t,r)=>t.localeCompare(r)).join(", "),F=e=>{const{hasAuth:t}=e,r=I(e),a=W(e),n=t?` let auth: LunoraAuth | null = null;
|
|
378
378
|
`:"",o=t?`
|
|
379
379
|
const ensureAuth = async (env: Env): Promise<void> => {
|
|
380
380
|
if (!this.authDeclaration || auth) {
|
|
@@ -410,10 +410,10 @@ ${l.map(i=>` { agent: lunoraAgentDefinitions.${i.exportName}, binding
|
|
|
410
410
|
|
|
411
411
|
/** Read a value off the per-request \`env\`. Returns \`undefined\` to leave the capability unconfigured (its \`ctx.*\`/admin surface stays a clear-error stub). */
|
|
412
412
|
type Selector<Env, T> = (env: Env) => T | undefined;
|
|
413
|
-
${
|
|
414
|
-
${
|
|
413
|
+
${g(e)?"\n/** The generated `createShardDO` config — the long-tail `.ai()` / `.kv()` / … methods pass straight through to it. */\ntype ShardConfig = NonNullable<Parameters<typeof createShardDO>[0]>;\n":""}
|
|
414
|
+
${r.join(`
|
|
415
415
|
|
|
416
|
-
`)}${
|
|
416
|
+
`)}${r.length>0?`
|
|
417
417
|
|
|
418
418
|
`:""}/** The composed app: a Cloudflare module worker (\`fetch\` / \`scheduled\` / optional \`email\`) plus the \`ShardDO\` class binding. */
|
|
419
419
|
interface ComposedApp extends LunoraWorker {
|
|
@@ -430,12 +430,12 @@ interface ComposedApp extends LunoraWorker {
|
|
|
430
430
|
* first request so per-isolate singletons are built once.
|
|
431
431
|
*/
|
|
432
432
|
class AppBuilder<Env extends object> {
|
|
433
|
-
${
|
|
433
|
+
${j(e).join(`
|
|
434
434
|
`)}
|
|
435
435
|
|
|
436
436
|
private emailHandler?: (env: Env) => (message: unknown, env: unknown, context: ExecutionContextLike) => Promise<void>;
|
|
437
437
|
|
|
438
|
-
${
|
|
438
|
+
${q(e).join(`
|
|
439
439
|
|
|
440
440
|
`)}
|
|
441
441
|
|
|
@@ -485,11 +485,11 @@ ${p} if (this.emailHandler) {
|
|
|
485
485
|
|
|
486
486
|
return composed;
|
|
487
487
|
}
|
|
488
|
-
${
|
|
488
|
+
${$(e.hasStorage)}
|
|
489
489
|
/** Fan the recorded declarations into the worker-side \`createWorker\` options. */
|
|
490
490
|
private buildWorkerOptions(env: Env, ${d}): WorkerOptions {
|
|
491
491
|
const options: WorkerOptions = {
|
|
492
|
-
${
|
|
492
|
+
${B(e).join(`
|
|
493
493
|
`)}
|
|
494
494
|
};
|
|
495
495
|
|
|
@@ -497,9 +497,9 @@ ${$(e).join(`
|
|
|
497
497
|
options.adminToken = this.adminToken(env);
|
|
498
498
|
}
|
|
499
499
|
|
|
500
|
-
${
|
|
500
|
+
${a.join(`
|
|
501
501
|
|
|
502
|
-
`)}${
|
|
502
|
+
`)}${a.length>0?`
|
|
503
503
|
|
|
504
504
|
`:""} for (const fn of this.extendFns) {
|
|
505
505
|
Object.assign(options, fn(env, { ...options }));
|
|
@@ -522,5 +522,5 @@ ${H(e.hasGlobal)}
|
|
|
522
522
|
const defineApp = <Env extends object>(): AppBuilder<Env> => new AppBuilder<Env>();
|
|
523
523
|
|
|
524
524
|
export { AppBuilder, defineApp };
|
|
525
|
-
export type { ${
|
|
525
|
+
export type { ${P(e)} };
|
|
526
526
|
`};export{F as emitApp};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{runAdvisor as o}from"@lunora/advisor";const i=n=>[...n.indexes.map(e=>({fields:e.fields,kind:"index",name:e.name,unique:e.unique})),...n.searchIndexes.map(e=>({fields:[e.field,...e.filterFields??[]],kind:"search",name:e.name})),...n.rankIndexes.map(e=>({fields:[...e.sortBy.map(r=>r.field),...e.partitionBy??[]],kind:"rank",name:e.name})),...n.vectorIndexes.filter(e=>e.field!==void 0).map(e=>({fields:[e.field],kind:"vector",name:e.name})),...(n.geoIndexes??[]).map(e=>({fields:[e.field],kind:"geo",name:e.name}))],d=n=>{const e={};for(const[r,s]of Object.entries(n.shape))e[r]=s.kind==="optional"?s.inner?.kind??"optional":s.kind;return e},l=n=>({rlsMode:n.rlsMode,tables:n.tables.map(e=>({externallyManaged:e.externallyManaged??!1,externalSource:e.externalSource?{hasReconcile:e.externalSource.hasReconcile??!1,hasSoftDelete:e.externalSource.hasSoftDelete??!1,hasTenantBy:e.externalSource.hasTenantBy,mode:e.externalSource.mode,unanalyzable:e.externalSource.unanalyzable}:void 0,columnKinds:d(e),fields:Object.keys(e.shape),indexes:i(e),isPublic:e.isPublic??!1,name:e.name,relations:e.relations.map(r=>({field:r.field,kind:r.kind,name:r.name,onDelete:r.onDelete,references:r.references,table:r.table})),shardKind:typeof e.shardMode=="string"?e.shardMode:"shardBy",softDelete:e.softDelete,ttl:e.ttl}))}),c=n=>n.map(e=>({exportName:e.exportName,file:`lunora/${e.filePath}.ts`,table:e.table})),m=n=>{const{argumentValidators:e,queries:r,schema:s,shapes:a,...t}=n;return{...t,argValidators:e,queries:r??[],schema:l(s),shapes:a===void 0?void 0:c(a)}},f=n=>o(m(n),{source:"static"}),h=n=>{if(n.length===0)return"";const e=`@lunora/codegen: ${String(n.length)} schema advisor finding${n.length===1?"":"s"}`,r=n.map(s=>` [${s.level}] ${s.name}: ${s.detail}`);return[e,...r].join(`
|
|
2
|
+
`)};export{h as formatAdvisories,f as lintSchema,m as toAdvisorContext};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const p=/[^a-zA-Z0-9]+/gu,f=/([a-z0-9])([A-Z])/gu,c=t=>t.split(p).filter(e=>e.length>0).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(""),b=t=>t.replaceAll(f,"$1_$2").replaceAll(p,"_").toLowerCase(),i=t=>t===void 0?!1:["$ref","allOf","anyOf","enum","items","oneOf","properties","type"].some(e=>e in t),g=t=>t==="query"?"query":t==="action"?"action":"mutation",o=(t,e=0)=>{if(e>32||t===null||typeof t!="object")return!1;if(Array.isArray(t))return t.some(a=>o(a,e+1));const n=t;if(n.type==="integer"&&n.format==="int64"||n.type==="string"&&n.contentEncoding==="base64")return!0;const{properties:r}=n;return r!==null&&typeof r=="object"&&Object.values(r).some(a=>o(a,e+1))?!0:["additionalProperties","allOf","anyOf","items","oneOf"].some(a=>o(n[a],e+1))},w=t=>t.replaceAll(/[\n\r\u2028\u2029]+/gu," ").replaceAll("*/","* /").replaceAll('"""','" ""'),y=t=>t.replaceAll("\\","\\\\").replaceAll('"','\\"').replaceAll(`
|
|
2
|
+
`,"\\n").replaceAll("\r","\\r"),h=["$","{","'","$","'","}"].join(""),v=t=>y(t).split("$").join(h),T=(t,e)=>t.argsType!==void 0?e.typed(t.argsType):t.takesArgs?e.untyped:e.none,u=t=>{const[e="",n=""]=t.name.split(":"),r=`${c(e)}${c(n)}`,a=t.params?.[0]?.schema,s=t.result?.schema;return{argsType:i(a)&&!o(a)?`${r}Args`:void 0,takesArgs:i(a),functionName:n,functionPath:t.name,namespace:e,resultType:i(s)&&!o(s)?`${r}Result`:void 0,summary:t.summary??t.name,verb:g(t["x-lunora-function-kind"])}},S=t=>{const e=new Map;for(const n of t.methods){const r=u(n),a=e.get(r.namespace);a===void 0?e.set(r.namespace,[r]):a.push(r)}return[...e.entries()].toSorted(([n],[r])=>n.localeCompare(r)).map(([n,r])=>({methods:r.toSorted((a,s)=>a.functionName.localeCompare(s.functionName)),name:n}))},E=t=>t.methods.flatMap(e=>{const n=u(e);return[{name:n.argsType,schema:e.params?.[0]?.schema},{name:n.resultType,schema:e.result?.schema}]}).filter(e=>e.name!==void 0&&e.schema!==void 0).toSorted((e,n)=>e.name.localeCompare(n.name)),A=/^[A-Za-z][A-Za-z0-9]*$/u,m=t=>A.test(t),$=t=>{const e=new Map;for(const n of t.methods){const r=c(n.functionName);if(!m(r))throw new Error(`sdk: function "${n.functionPath}" produces the invalid identifier "${r}" — rename the export so it starts with a letter.`);const a=n.verb==="query"?[r,`Subscribe${r}`]:[r];for(const s of a){const l=e.get(s);if(l!==void 0)throw new Error(`sdk: functions "${l}" and "${n.functionPath}" both generate "${s}" — rename one so the generated methods stay distinct.`);e.set(s,n.functionPath)}}},M=t=>{const e=new Map;for(const n of t){const r=c(n.name);if(!m(r))throw new Error(`sdk: namespace "${n.name}" produces the invalid identifier "${r}" — rename the file so it starts with a letter.`);const a=e.get(r);if(a!==void 0)throw new Error(`sdk: namespaces "${a}" and "${n.name}" both generate "${r}" — rename one so the generated types stay distinct.`);e.set(r,n.name),$(n)}},d=t=>t.flatMap(e=>e.methods),C=t=>[`GENERATED by \`lunora sdk generate --lang ${t}\` — do not edit.`,"Run the command again to regenerate."],N=(t,e)=>{const n=r=>r!==void 0&&new RegExp(String.raw`\b${r}\b`,"u").test(e)?r:void 0;return t.map(r=>({methods:r.methods.map(a=>({...a,argsType:n(a.argsType),resultType:n(a.resultType)})),name:r.name}))},O=t=>t.methods.filter(e=>o(e.params?.[0]?.schema)||o(e.result?.schema)).map(e=>e.name).toSorted((e,n)=>e.localeCompare(n)),k=(t,e)=>[...new Set(d(t).flatMap(n=>[n.argsType,n.resultType]).filter(n=>n!==void 0&&!new RegExp(String.raw`\b${n}\b`,"u").test(e)))].toSorted((n,r)=>n.localeCompare(r)),L=t=>[...new Set(d(t).flatMap(e=>[e.argsType,e.resultType]).filter(e=>e!==void 0))].toSorted((e,n)=>e.localeCompare(n));export{d as allMethods,T as argsChoice,M as assertGeneratable,w as commentText,C as generatedHeaderLines,o as hasUnrepresentableWireType,i as isTypedSchema,v as kotlinLiteral,E as modelSources,u as parseMethod,S as parseSpec,L as referencedModels,y as stringLiteral,c as toPascalCase,b as toSnakeCase,k as undeclaredModels,O as unrepresentableFunctions,g as verbForKind,N as withDeclaredModels};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const r=/(?:^|\/)_generated\/server(?:\.js)?$/u,s=new Set(["@lunora/server","lunorash/server"]),o=e=>s.has(e),n=e=>r.test(e),t=e=>o(e)||n(e),a=new Set(["@lunora/scheduler",...s]),E=e=>a.has(e);export{t as a,o as b,E as i};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as p}from"@lunora/errors";import{Node as n}from"ts-morph";let d;const I=e=>{d=e},g=/^[A-Za-z_$][\w$]*$/u,f=new Set(["$defaultFn","$onUpdateFn","$type","default","defaultNow","nullable","unique"]),y=(e,r)=>{const t={notNull:!0,...e.column};switch(r){case"$defaultFn":case"default":case"defaultNow":{t.hasDefault=!0;break}case"$onUpdateFn":{t.hasOnUpdate=!0;break}case"$type":break;case"nullable":{t.notNull=!1;break}case"unique":{t.unique=!0;break}}return{...e,column:t}},k=new Set(["any","bigint","boolean","bytes","date","geoPoint","null","number","string","timestamp"]),m=new Set(["check","meta"]),u=new Set,N=e=>{const r=e.getSymbol(),t=(r?.getAliasedSymbol()??r)?.getValueDeclaration();if(!(t===void 0||!n.isVariableDeclaration(t)))return t.getInitializer()},b="v",E=e=>{if(n.isIdentifier(e))return!0;let r=e;for(;n.isCallExpression(r);){const t=r.getExpression();if(!n.isPropertyAccessExpression(t))return!1;r=t.getExpression()}return n.isIdentifier(r)&&r.getText()===b},o=e=>{if(n.isIdentifier(e)&&!u.has(e)){const r=N(e);if(r!==void 0&&E(r)){u.add(e);try{return o(r)}finally{u.delete(e)}}}return n.isCallExpression(e)?L(e):{kind:"any",sourceText:e.getText()}},S=e=>{const r={};for(const t of e.getProperties()){const a=n.isShorthandPropertyAssignment(t);if(!a&&!n.isPropertyAssignment(t))continue;const i=t.getNameNode();if(n.isComputedPropertyName(i))continue;const s=a?t.getNameNode():t.getInitializer();if(!s)continue;const c=t.getName();if(!g.test(c))throw new p("INTERNAL",`@lunora/codegen: field name is not a valid JS identifier: ${JSON.stringify(c)}`);r[c]=o(s)}return r},l=(e,r)=>e&&n.isExpression(e)?o(e):r,h=e=>e===void 0?"undefined":n.isStringLiteral(e)||n.isNoSubstitutionTemplateLiteral(e)?JSON.stringify(e.getLiteralValue()):e.getText(),A=e=>{const r=e&&d?d(e):void 0;return r===void 0?{kind:"from"}:{kind:"from",tsType:r}},T=(e,r)=>{if(k.has(e))return{kind:e};const[t,a]=r;switch(e){case"array":return{inner:l(t,{kind:"any"}),kind:"array"};case"from":return A(t);case"id":return{kind:"id",tableName:t&&n.isStringLiteral(t)?t.getLiteralText():"_unknown_"};case"literal":return{kind:"literal",literalValue:h(t)};case"object":return t&&n.isObjectLiteralExpression(t)?{kind:"object",shape:S(t)}:{kind:"object",shape:{}};case"optional":return{inner:l(t,{kind:"any"}),kind:"optional"};case"record":return{keyType:l(t,{kind:"string"}),kind:"record",valueType:l(a,{kind:"any"})};case"storage":return t&&n.isStringLiteral(t)?{bucket:t.getLiteralText(),kind:"storage"}:{kind:"storage"};case"union":return{kind:"union",members:r.filter(i=>n.isExpression(i)).map(i=>o(i))};default:throw new p("INTERNAL",`Unsupported validator kind: ${e}`)}},L=e=>{const r=e.getExpression();if(!n.isPropertyAccessExpression(r))return{kind:"any",sourceText:e.getText()};const t=r.getName(),a=e.getArguments();if(f.has(t)||m.has(t)){const i=r.getExpression(),s=n.isExpression(i)?o(i):{kind:"any"};return f.has(t)?y(s,t):t==="check"?{...s,hasRefinement:!0}:s}return T(t,a)};export{S as a,o as p,I as s};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const a=/\/index$/u,s=/[^\dA-Za-z]/gu,c=e=>e.replace(a,"").replaceAll(s,"_");export{c as s};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{existsSync as r,readFileSync as a}from"node:fs";import{join as d}from"node:path";const m=o=>{const n=d(o,"package.json");if(r(n))try{const s=JSON.parse(a(n,"utf8")),t=new Set;for(const c of["dependencies","devDependencies","peerDependencies","optionalDependencies"]){const e=s[c];if(e!==null&&typeof e=="object")for(const i of Object.keys(e))t.add(i)}return t}catch{return}};export{m as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const s=/[\w+/=-]{40,}/u,n=/[a-z]/u,E=/[A-Z]/u,_=/\d/u,c=/\b(?:[\da-f]{32,}|[\dA-F]{32,})\b/u,o=t=>{const e=s.exec(t)?.[0];return e===void 0?!1:n.test(e)&&E.test(e)&&_.test(e)},i=t=>c.test(t),r=/\b(?:sk|rk)_live_[\dA-Za-z]{20,}/u,a=/\bAKIA[\dA-Z]{16}\b/u,R=/\bgh[posru]_[\dA-Za-z]{36,}/u,d=/\bsk-[\dA-Za-z]{32,}/u,A=/\bxox[abprs]-[\dA-Za-z-]{10,}/u,k=/-----BEGIN(?: [A-Z]+)? PRIVATE KEY-----/u,S=[{kind:"stripe_live_key",test:t=>r.test(t)},{kind:"aws_access_key",test:t=>a.test(t)},{kind:"github_token",test:t=>R.test(t)},{kind:"openai_key",test:t=>d.test(t)},{kind:"slack_token",test:t=>A.test(t)},{kind:"private_key",test:t=>k.test(t)},{kind:"high_entropy",test:o},{kind:"hex_secret",test:i}],u=new Set(["hex_secret","high_entropy"]),h=new Set(["auth","bearer","credential","credentials","hmac","key","keys","passphrase","password","private","secret","secrets","signature","signing","token"]),p=/([a-z\d])([A-Z])/gu,T=/[^A-Za-z\d]+/u,I=t=>t.replaceAll(p,"$1 $2").split(T).filter(Boolean).map(e=>e.toLowerCase()),l=t=>t!==void 0&&I(t).some(e=>h.has(e)),K=t=>S.find(e=>e.test(t))?.kind,b=t=>u.has(t),g=t=>`${t.slice(0,4)}…(${String(t.length)} chars)`;export{S as SECRET_RULES,b as isHeuristicSecretKind,l as isSecretishName,g as redact,K as secretKindOf};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const s=e=>{try{return JSON.parse(e)}catch{const t=e.trim();return t.length>=2&&(t.startsWith("'")||t.startsWith('"'))&&t.at(-1)===t[0]?t.slice(1,-1):t}},n=e=>{const t={};return e.column!==void 0&&(t.column={defaultValue:e.column.hasDefault===!0?null:void 0,notNull:e.column.notNull,unique:e.column.unique}),e.inner!==void 0&&(t.inner=n(e.inner)),e.members!==void 0&&(t.members=e.members.map(a=>n(a))),e.shape!==void 0&&(t.shape=Object.fromEntries(Object.entries(e.shape).map(([a,l])=>[a,n(l)]))),e.tableName!==void 0&&(t.tableName=e.tableName),e.literalValue!==void 0&&(t.value=s(e.literalValue)),e.keyType!==void 0&&(t.keyValidator=n(e.keyType)),e.valueType!==void 0&&(t.valueValidator=n(e.valueType)),{_meta:t,kind:e.kind}},m=e=>({tables:Object.fromEntries(e.tables.map(a=>[a.name,{shape:Object.fromEntries(Object.entries(a.shape).map(([l,o])=>[l,n(o)]))}]))});export{m as schemaFromIr};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/codegen",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.109",
|
|
4
4
|
"description": "Code generator for Lunora: emits _generated/{api,server,dataModel}.ts from your schema",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cloudflare",
|
|
@@ -46,8 +46,8 @@
|
|
|
46
46
|
"access": "public"
|
|
47
47
|
},
|
|
48
48
|
"dependencies": {
|
|
49
|
-
"@lunora/advisor": "1.0.0-alpha.
|
|
50
|
-
"@lunora/agent": "1.0.0-alpha.
|
|
49
|
+
"@lunora/advisor": "1.0.0-alpha.79",
|
|
50
|
+
"@lunora/agent": "1.0.0-alpha.54",
|
|
51
51
|
"@lunora/container": "1.0.0-alpha.30",
|
|
52
52
|
"@lunora/errors": "1.0.0-alpha.21",
|
|
53
53
|
"@lunora/platform": "1.0.0-alpha.10",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{existsSync as l}from"node:fs";import{join as p}from"node:path";import{agentDefaultName as d,agentClassName as f,agentBindingName as N,voiceBindingName as b,voiceClassName as x}from"@lunora/agent/naming";import{LunoraError as g}from"@lunora/errors";import{Node as s,SyntaxKind as u}from"ts-morph";import{diagnosticAt as m}from"./CodegenDiagnosticError-DPezpZTz.mjs";import{T as A,v as w}from"./discover-ast-7ABwvTVn.mjs";const h="agents.ts",y=o=>{const t=o.getSymbol();if(!t)return o.getText()==="defineAgent";for(const n of t.getDeclarations())if(s.isImportSpecifier(n))return n.getImportDeclaration().getModuleSpecifierValue()!=="@lunora/agent"?!1:n.getNameNode().getText()==="defineAgent";return!1},E=w("agent"),T=(o,t,n)=>{if(o.getKind()===u.TrueKeyword)return!0;if(o.getKind()===u.FalseKeyword)return!1;throw m(o,`agent "${t}": \`${n}\` must be a static boolean literal — it is deploy configuration codegen writes into the ctx.agents wiring spec`)},D=(o,t)=>{const n=o.getArguments()[0];if(!n||!s.isObjectLiteralExpression(n))throw m(o,`agent "${t}": defineAgent must be passed an inline object literal`);const i={bindingName:N(t),className:f(t),exportName:t,name:d(t)},e=n.getProperty("name");e&&s.isPropertyAssignment(e)&&(i.name=E(e.getInitializerOrThrow(),t,"name"));const r=n.getProperty("publicRun");r&&s.isPropertyAssignment(r)&&T(r.getInitializerOrThrow(),t,"publicRun")&&(i.publicRun=!0);const a=n.getProperty("voice");if(a&&s.isPropertyAssignment(a)){const c=a.getInitializerOrThrow();if(!s.isObjectLiteralExpression(c))throw m(c,`agent "${t}": \`voice\` must be an inline object literal — its presence tells codegen to emit the voice-session Durable Object`);i.voice=!0,i.voiceBindingName=b(t),i.voiceClassName=x(t)}return n.getProperty("onEmail")&&(i.onEmail=!0),i},I=o=>{const t=[];for(const n of o.getVariableDeclarations()){if(!n.isExported())continue;const i=A(n.getInitializer());if(!i)continue;const e=i.getExpression();if(!s.isIdentifier(e)||!y(e))continue;const r=n.getNameNode();if(!s.isIdentifier(r))throw m(r,"defineAgent exports must be plain named exports (no destructuring)");t.push(D(i,r.getText()))}return t},$=o=>{const t=new Map,n=new Map,i=new Map;for(const e of o){const r=t.get(e.name);if(r!==void 0)throw new g("DUPLICATE_AGENT_NAME",`Duplicate agent name "${e.name}": produced by both "${r}" and "${e.exportName}". Deployed agent names must be unique across the project.`,{status:500});t.set(e.name,e.exportName);const a=n.get(e.bindingName);if(a!==void 0)throw new g("DUPLICATE_AGENT_BINDING",`Duplicate agent binding "${e.bindingName}": produced by both "${a}" and "${e.exportName}". Agent export names must yield unique binding names.`,{status:500});n.set(e.bindingName,e.exportName);const c=i.get(e.className);if(c!==void 0)throw new g("DUPLICATE_AGENT_CLASS",`Duplicate agent class "${e.className}": produced by both "${c}" and "${e.exportName}". Agent export names must yield unique generated class names.`,{status:500});i.set(e.className,e.exportName)}},M=(o,t)=>{const n=p(t,h);if(!l(n))return[];const i=o.getSourceFile(n)??o.addSourceFileAtPath(n),e=I(i);return e.sort((r,a)=>r.exportName.localeCompare(a.exportName)),$(e),e};export{h as AGENTS_FILENAME,M as discoverAgents};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as g}from"@lunora/errors";class a extends g{column;file;line;constructor(i,e,n,t){super("CODEGEN_DIAGNOSTIC",i,{location:{column:t,file:e,line:n},name:"CodegenDiagnosticError"}),this.file=e,this.line=n,this.column=t}}const m=(o,i,e)=>{const n=o.getSourceFile(),t=n.getFilePath(),r=o.getStartLineNumber(),{column:c}=n.getLineAndColumnAtPos(o.getStart()),l=`@lunora/codegen: ${i} (${t}:${r.toString()}:${c.toString()})`,s=new a(l,t,r,c);return e?Object.assign(s,e):s};export{a as CodegenDiagnosticError,m as diagnosticAt};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{existsSync as u,readFileSync as c}from"node:fs";import{join as d}from"node:path";import{NODE_CAPABILITIES as p,CLOUDFLARE_CAPABILITIES as m}from"@lunora/platform";import{parse as f}from"jsonc-parser";const g="cloudflare",h="lunora.json",y=r=>{const e=d(r,h);if(!u(e))return;let a;try{a=c(e,"utf8")}catch{return}const s=[],o=f(a,s,{allowTrailingComma:!0});if(s.length>0||o===null||typeof o!="object")return;const{target:t}=o;return typeof t=="string"&&t.length>0?t:void 0},C=(r,e)=>e??y(r)??g,i={cloudflare:m,node:p},k=()=>Object.keys(i).toSorted((r,e)=>r.localeCompare(e)),v={ai:"ai",analytics:"analytics",browser:"browser",container:"containers",hyperdrive:"hyperdrive",kv:"keyValueStore",mail:"mail",pipelines:"pipelines",scheduler:"scheduler",storage:"objectStorage",vectors:"vectorStore",workflows:"workflows"},$=(r,e,a)=>{const s={...r},o=[];for(const[t,n]of Object.entries(v)){if(!r[t])continue;const l=e.features[n]?.level;l==="unsupported"?(s[t]=!1,o.push({feature:t,level:"error",message:`${e.name} does not support "${t}" (ctx.${t}). Its surface was omitted from the generated types.`,name:"platform_unsupported_feature",remediation:`Remove the ctx.${t} usage, or deploy to a target whose capability matrix marks "${n}" as native or emulated.`,target:a})):l===void 0&&(s[t]=!1,o.push({feature:t,level:"error",message:`${e.name}'s capability matrix does not declare a support level for "${t}" (ctx.${t}). Treated as unsupported and its surface was omitted from the generated types.`,name:"platform_undeclared_feature",remediation:`Rate "${n}" in the ${e.name} capability matrix as "native", "emulated", or "unsupported" — an undeclared feature fails closed rather than shipping a surface the host may not provide.`,target:a}))}return{diagnostics:o,usage:s}},I=(r,e)=>{const a=i[e];return a===void 0?{diagnostics:[{level:"error",message:`Unknown deploy target "${e}" — no capability matrix is registered for it. Codegen emitted the full Cloudflare surface un-gated.`,name:"platform_unknown_target",remediation:`Use a registered target (${Object.keys(i).join(", ")}) or install the target's @lunora/platform-${e} package.`,target:e}],usage:{...r}}:$(r,a,e)};export{g as DEFAULT_TARGET,h as PROJECT_CONFIG_FILE,$ as gateAgainstMatrix,I as gatePlatformFeatures,k as platformMatrixIds,y as readProjectTarget,C as resolveCodegenTarget};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{existsSync as l}from"node:fs";import{join as p}from"node:path";import{SyntaxKind as c,Node as i}from"ts-morph";import{g as f,I as u,C as d,z as g}from"./discover-ast-7ABwvTVn.mjs";const m="flags.ts",x=new Set(["boolean","number","object","string"]),y="@lunora/flags/providers/flagship",S=t=>{const s=t.getSymbol();if(!s)return t.getText()==="flagshipProvider";for(const e of s.getDeclarations())if(i.isImportSpecifier(e))return e.getImportDeclaration().getModuleSpecifierValue()!==y?!1:e.getNameNode().getText()==="flagshipProvider";return!1},E=(t,s)=>{const e=t.getProperty(s);if(!e||!i.isPropertyAssignment(e))return;const r=e.getInitializerOrThrow();if(i.isStringLiteral(r)||i.isNoSubstitutionTemplateLiteral(r))return r.getLiteralValue()},h=t=>{const s=t.getArguments()[0];if(s&&i.isObjectLiteralExpression(s)){const e=E(s,"binding");if(e!==void 0&&e.length>0)return{bindingName:e,mode:"binding",provider:"flagship"}}return{mode:"http",provider:"flagship"}},v=t=>d(t.getArguments()[0],"provider"),I=(t,s)=>{const e=p(s,m);if(!l(e))return;const r=t.getSourceFile(e)??t.addSourceFileAtPath(e),o=u(r);if(!o||!i.isCallExpression(o))return{provider:"custom"};const a=v(o);if(a&&i.isCallExpression(a)){const n=a.getExpression();if(i.isIdentifier(n)&&S(n))return h(a)}return{provider:"custom"}},A=t=>{const s=t.getName();if(!x.has(s))return;const e=t.getExpression();if(!i.isPropertyAccessExpression(e))return;if(e.getName()==="flags"&&g(e.getExpression()))return s;const r=e.getExpression();if(e.getName()==="details"&&i.isPropertyAccessExpression(r)&&r.getName()==="flags"&&g(r.getExpression()))return s},b=t=>{const s=t.getExpression();if(!i.isPropertyAccessExpression(s))return;const e=A(s);if(e===void 0)return;const r=t.getArguments()[0];if(!r||!(i.isStringLiteral(r)||i.isNoSubstitutionTemplateLiteral(r)))return;const o=r.getLiteralValue();return o.length>0?{key:o,type:e}:void 0},k=(t,s)=>{const e=new Map;for(const r of f(s)){const o=t.getSourceFile(r)??t.addSourceFileAtPath(r);for(const a of o.getDescendantsOfKind(c.CallExpression)){const n=b(a);n&&!e.has(n.key)&&e.set(n.key,n.type)}}return[...e.entries()].map(([r,o])=>({key:r,type:o})).toSorted((r,o)=>r.key.localeCompare(o.key))};export{m as FLAGS_FILENAME,k as discoverFlagKeys,I as discoverFlags};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import"@lunora/agent/component";import"@lunora/errors";import"./SCHEMA_SNAPSHOT_VERSION-CFhF_hmg.mjs";import{S as r,d as o,a as n,h as E,M as l,B as A,p as S,L as p,R as C,C as d,V as g,f as u,P as c,Q as D,$ as R,E as f,m as h,F as B}from"./emit-BbLyaTLJ.mjs";import"./paths-BmX5O1sG.mjs";export{r as GENERATED_HEADER,o as UMBRELLA_BASE_PACKAGES,n as buildStorageColumns,E as emitAgents,l as emitApi,A as emitCollections,S as emitContainers,p as emitCrons,C as emitDataModel,d as emitDrizzleSchema,g as emitFunctions,u as emitQueues,c as emitSeed,D as emitServer,R as emitShard,f as emitVectors,h as emitWorkflows,B as emitWranglerCronTriggers};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{existsSync as p}from"node:fs";import{join as m}from"node:path";import{Node as o,SyntaxKind as c}from"ts-morph";import{diagnosticAt as l}from"./CodegenDiagnosticError-DPezpZTz.mjs";import{unwrapHandlerReturn as g}from"./discoverFunctions-4TNKUv7P.mjs";import{t as d}from"./module-specifiers-8FEEiUcv.mjs";import{g as x}from"./parse-validator-CusS8QwU.mjs";const y="mutators.ts",f=d,E=r=>{const e=r.getSymbol();if(!e)return r.getText()==="defineMutator";for(const t of e.getDeclarations())if(o.isImportSpecifier(t))return f(t.getImportDeclaration().getModuleSpecifierValue())?t.getNameNode().getText()==="defineMutator":!1;return!1},N=r=>{const e=r.getSymbol();if(!e)return!1;for(const t of e.getDeclarations()){if(!o.isNamespaceImport(t))continue;const i=t.getFirstAncestorByKind(c.ImportDeclaration);return i!==void 0&&f(i.getModuleSpecifierValue())}return!1},I=r=>{if(o.isIdentifier(r))return E(r);if(o.isPropertyAccessExpression(r)){const e=r.getExpression();return r.getName()==="defineMutator"&&o.isIdentifier(e)&&N(e)}return!1},S=r=>{const e=r.getArguments()[0];return e&&o.isObjectLiteralExpression(e)?e:void 0},A=r=>{const e=r?.getProperty("args");if(!e||!o.isPropertyAssignment(e))return{};const t=e.getInitializer();return t&&o.isObjectLiteralExpression(t)?x(t):{}},M=r=>{const e=r?.getProperty("server");if(!e||!o.isPropertyAssignment(e))return"unknown";const t=e.getInitializer();return!t||!(o.isArrowFunction(t)||o.isFunctionExpression(t))?"unknown":g(t)},P=r=>{const e=[];for(const t of r.getVariableDeclarations()){if(!t.isExported())continue;const i=t.getInitializer();if(i?.getKind()!==c.CallExpression)continue;const n=i,a=n.getExpression();if(!I(a))continue;const s=t.getNameNode();if(!o.isIdentifier(s))throw l(s,"defineMutator exports must be plain named exports (no destructuring)");const u=S(n);e.push({args:A(u),exportName:s.getText(),filePath:"mutators",returnType:M(u)})}return e},j=(r,e)=>{const t=m(e,y);if(!p(t))return[];const i=r.getSourceFile(t)??r.addSourceFileAtPath(t),n=P(i);return n.sort((a,s)=>a.exportName.localeCompare(s.exportName)),n};export{y as MUTATORS_FILENAME,j as discoverMutators,I as isDefineMutatorCallee};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{existsSync as m}from"node:fs";import{join as g}from"node:path";import{SyntaxKind as u,Node as c}from"ts-morph";import{g as d,p as x,I as y,w as E}from"./discover-ast-7ABwvTVn.mjs";import{classifyProcedureCall as P}from"./discoverFunctions-4TNKUv7P.mjs";const N="notify.ts",A=new Set(["chat","inApp","send","webhook"]),l=new Set(["broadcast","send"]),S=e=>{const t=e.getInitializer();if(!t||!c.isCallExpression(t))return;const s=P(t);if(!s)return;const r=E(t,s.receiver);return r?{exportName:e.getName(),handler:r,kind:s.kind}:void 0},h=e=>{const t=[];for(const s of e.getVariableStatements())if(s.isExported())for(const r of s.getDeclarations()){const o=S(r);o&&t.push(o)}return t},a=e=>{if(!c.isPropertyAccessExpression(e))return;const t=e.getName(),s=e.getExpression();if((t==="notify"||t==="push")&&c.isIdentifier(s)&&s.getText()==="ctx")return t;if(t==="push"&&a(s)==="notify")return"push"},F=e=>{if(!c.isPropertyAccessExpression(e))return;const t=e.getName(),s=a(e.getExpression());if(s==="notify"&&A.has(t))return`ctx.notify.${t}`;if(s==="push"&&l.has(t))return`ctx.push.${t}`},b=e=>c.isPropertyAccessExpression(e)?a(e.getExpression())==="push"&&l.has(e.getName()):!1,D=(e,t)=>{const s=[];for(const r of d(t)){const o=e.getSourceFile(r)??e.addSourceFileAtPath(r),f=x(t,r);for(const n of h(o))if(!(n.kind!=="query"&&n.kind!=="mutation"))for(const i of n.handler.getDescendantsOfKind(u.PropertyAccessExpression)){const p=F(i);p!==void 0&&s.push({callee:p,exportName:n.exportName,file:f,kind:n.kind,line:i.getStartLineNumber()})}}return s},v=(e,t)=>{for(const s of d(t)){const r=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const o of h(r))for(const f of o.handler.getDescendantsOfKind(u.PropertyAccessExpression))if(b(f))return!0}return!1},K=(e,t)=>{const s=g(t,N);if(!m(s))return;const r=e.getSourceFile(s)??e.addSourceFileAtPath(s),o=y(r);let f=!1,n=!1;if(o&&c.isCallExpression(o)){const i=o.getArguments()[0];i&&c.isObjectLiteralExpression(i)&&(f=i.getProperty("webPush")!==void 0,n=i.getProperty("fcm")!==void 0)}return{hasFcm:n,hasWebPush:f,usesPush:v(e,t)}};export{N as NOTIFY_FILENAME,D as discoverNotifyCalls,K as discoverNotifyConfig};
|
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
import{S as a}from"./emit-BbLyaTLJ.mjs";import{n as i}from"./paths-BmX5O1sG.mjs";import{validatorIrToJsonSchema as s,objectSchema as c,LUNORA_ERROR_CODES as u}from"./LUNORA_ERROR_CODES-zfAI2OFs.mjs";const p="1.3.2",m={description:"Result is TS-inferred from the function's return type (no `.output()` declared); best-effort — any JSON."},d=e=>{const r=i(e.filePath),t=`${r}:${e.exportName}`;return{description:`Invoke the \`${e.kind}\` \`${t}\` over the Lunora RPC envelope (POST /_lunora/rpc, body \`{ "functionPath": "${t}", "args": { … } }\`).`,errors:u.map((o,n)=>({code:-32e3-n,data:{code:o},message:o})),name:t,params:[{description:"The function's argument object (the RPC envelope's `args`).",name:"args",required:Object.keys(e.args).length>0,schema:c(e.args)}],result:{name:"result",schema:e.output?s(e.output):m},summary:`${e.kind}: ${t}`,"x-lunora-function-kind":e.kind,"x-tags":[{name:r}]}},l=e=>{const r=e.version??"0.0.0",t=e.functions.filter(o=>o.visibility!=="internal"&&o.kind!=="stream").map(o=>d(o)).toSorted((o,n)=>o.name.localeCompare(n.name));return{info:{description:"Auto-generated from @lunora/values-typed functions by @lunora/codegen. Do not edit — run `lunora codegen` to regenerate.",title:"Lunora RPC",version:r},methods:t,openrpc:p}},h=e=>`${JSON.stringify(l(e),void 0,2)}
|
|
2
|
-
`,O=e=>`${a}export const openRpcSpec: Record<string, unknown> = ${JSON.stringify(e,void 0,4)};
|
|
3
|
-
`;export{p as OPENRPC_VERSION,l as buildOpenRpcDocument,h as emitOpenRpc,O as emitOpenRpcModule};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{existsSync as d}from"node:fs";import{join as g}from"node:path";import{LunoraError as p}from"@lunora/errors";import{queueDefaultName as l,queueBindingName as f}from"@lunora/queue";import{SyntaxKind as N,Node as u}from"ts-morph";import{diagnosticAt as a}from"./CodegenDiagnosticError-DPezpZTz.mjs";import{v as h}from"./discover-ast-7ABwvTVn.mjs";const x="queues.ts",b=i=>{const t=i.getSymbol();if(!t)return i.getText()==="defineQueue";for(const e of t.getDeclarations())if(u.isImportSpecifier(e))return e.getImportDeclaration().getModuleSpecifierValue()!=="@lunora/queue"?!1:e.getNameNode().getText()==="defineQueue";return!1},c=h("queue"),y=(i,t,e)=>{if(u.isNumericLiteral(i))return i.getLiteralValue();throw a(i,`queue "${t}": \`${e}\` must be a static numeric literal — it is deploy configuration codegen writes into wrangler.jsonc`)},w=(i,t)=>{const e=i.getProperty("name");if(!e||!u.isPropertyAssignment(e))return;const n=c(e.getInitializerOrThrow(),t,"name");if(n.length===0)throw a(e,`queue "${t}": \`name\` must be a non-empty string when provided`);return n},E=(i,t)=>{const e=i.getArguments()[0];if(!e||!u.isObjectLiteralExpression(e))throw a(i,`queue "${t}": defineQueue must be passed an inline object literal`);const n={bindingName:f(t),exportName:t,mode:"push",name:w(e,t)??l(t),tuning:{}},o=e.getProperty("mode");if(o&&u.isPropertyAssignment(o)){const r=c(o.getInitializerOrThrow(),t,"mode");if(r!=="push"&&r!=="pull")throw a(o,`queue "${t}": \`mode\` must be "push" or "pull" (got ${JSON.stringify(r)})`);n.mode=r}const s=e.getProperty("deadLetterQueue");s&&u.isPropertyAssignment(s)&&(n.tuning.deadLetterQueue=c(s.getInitializerOrThrow(),t,"deadLetterQueue"));for(const r of["maxBatchSize","maxBatchTimeout","maxRetries","retryDelay"]){const m=e.getProperty(r);m&&u.isPropertyAssignment(m)&&(n.tuning[r]=y(m.getInitializerOrThrow(),t,r))}return n},q=i=>{const t=[];for(const e of i.getVariableDeclarations()){if(!e.isExported())continue;const n=e.getInitializer();if(n?.getKind()!==N.CallExpression)continue;const o=n,s=o.getExpression();if(!u.isIdentifier(s)||!b(s))continue;const r=e.getNameNode();if(!u.isIdentifier(r))throw a(r,"defineQueue exports must be plain named exports (no destructuring)");t.push(E(o,r.getText()))}return t},I=i=>{const t=new Map,e=new Map;for(const n of i){const o=t.get(n.name);if(o!==void 0)throw new p("DUPLICATE_QUEUE_NAME",`Duplicate queue name "${n.name}": produced by both "${o}" and "${n.exportName}". Deployed queue names must be unique across the project.`,{status:500});t.set(n.name,n.exportName);const s=e.get(n.bindingName);if(s!==void 0)throw new p("DUPLICATE_QUEUE_BINDING",`Duplicate queue binding "${n.bindingName}": produced by both "${s}" and "${n.exportName}". Queue export names must yield unique binding names.`,{status:500});e.set(n.bindingName,n.exportName)}},T=(i,t)=>{const e=g(t,x);if(!d(e))return[];const n=i.getSourceFile(e)??i.addSourceFileAtPath(e),o=q(n);return o.sort((s,r)=>s.exportName.localeCompare(r.exportName)),I(o),o};export{x as QUEUES_FILENAME,T as discoverQueues};
|
|
@@ -1,9 +0,0 @@
|
|
|
1
|
-
import{existsSync as b,mkdirSync as qt,readFileSync as dt,writeFileSync as Bt,rmSync as Ut}from"node:fs";import{join as g,dirname as le}from"node:path";import{performance as ue}from"node:perf_hooks";import{runAdvisor as Vt}from"@lunora/advisor";import{LunoraError as k}from"@lunora/errors";import{SyntaxKind as l,Node as o,Project as Ge}from"ts-morph";import{serializeSchemaSnapshot as Wt}from"./SCHEMA_SNAPSHOT_VERSION-CFhF_hmg.mjs";import{toAdvisorContext as _t}from"./formatAdvisories-CQvIhQ04.mjs";import{discoverAgents as Gt}from"./AGENTS_FILENAME-Dk-k250h.mjs";import{discoverContainers as Ht}from"./CONTAINERS_FILENAME-DQpyhY6c.mjs";import{diagnosticAt as Z}from"./CodegenDiagnosticError-DPezpZTz.mjs";import{o as Y}from"./module-specifiers-8FEEiUcv.mjs";import{r as de,Q as Qt,R as Jt,a as Xt,M as Zt,V as Yt,$ as es,B as ts,p as ss,m as rs,h as ns,f as is,L as os,E as as,C as cs,P as ls,F as us}from"./emit-BbLyaTLJ.mjs";import{g as h,p as E,P as N,C as $,O as gt,z as ds,R as pt,h as gs}from"./discover-ast-7ABwvTVn.mjs";import ps from"./readPackageDependencies-CogJX1Ia.mjs";import{discoverQueues as fs}from"./QUEUES_FILENAME-QpMZsde0.mjs";import{discoverSandboxUsage as ms}from"./discoverSandboxUsage-DBM98vVh.mjs";import hs from"./discoverStorageRulesMetadata-_40MGqRX.mjs";import{discoverWorkflows as xs}from"./WORKFLOWS_FILENAME-Dz80zqeT.mjs";import{gatePlatformFeatures as Es,resolveCodegenTarget as ys}from"./DEFAULT_TARGET-CH5disA3.mjs";import{i as I,a as D,e as x,c as A,r as $s,b as vs,s as ee,d as bs,f as Ns,I as Ss}from"./discover-queries-CU9o_j87.mjs";import{classifyProcedureCall as M,inlineHandler as As,procedureHandler as ft,chainUsesWrappedCall as mt,isDatabaseAccessor as R,chainHasStep as ws,discoverFunctions as Ps,resolveStandardSchemaType as Is}from"./discoverFunctions-4TNKUv7P.mjs";import Ts from"./discoverAuthApiCalls-XfNbxqlq.mjs";import Ls from"./discoverCrons-RlATa0_t.mjs";import{discoverFlagKeys as ks}from"./FLAGS_FILENAME-Boqm0YCP.mjs";import Ds from"./discoverHttpRoutes-DQivLBqT.mjs";import Fs from"./discoverInserts-D6szWzrV.mjs";import Os,{discoverMaskStrategies as Cs,discoverMaskMetadata as Ks,discoverMaskHasNonLiteralPolicy as Rs}from"./discoverMaskProcedures-BBPqLXA5.mjs";import Ms from"./discoverMigrations-rbjxflR8.mjs";import{MUTATORS_FILENAME as js,isDefineMutatorCallee as zs,discoverMutators as qs}from"./MUTATORS_FILENAME-Cp_JxLSz.mjs";import Bs from"./discoverNondeterministicCalls-Bxr652Rz.mjs";import{discoverNotifyConfig as Us,discoverNotifyCalls as Vs}from"./NOTIFY_FILENAME-DwyJ5I4Q.mjs";import Ws from"./discoverR2sqlCalls-DMxG6gHr.mjs";import _s,{discoverRlsMetadata as Gs}from"./discoverRlsMetadata-B63ARnKG.mjs";import Hs from"./discoverSchema-BNr7PVcZ.mjs";import{secretKindOf as Qs,redact as Js,isHeuristicSecretKind as Xs,isSecretishName as Zs}from"./redact-6jD4lAhq.mjs";import{discoverShapes as Ys}from"./SHAPES_FILENAME-WxXOsYfe.mjs";import{emitApp as er}from"./emitApp-DkO-Qvoo.mjs";import{buildOpenApiDocument as tr,emitOpenApiModule as sr}from"./buildOpenApiDocument-B8-PH9af.mjs";import{buildOpenRpcDocument as rr,emitOpenRpcModule as nr}from"./OPENRPC_VERSION-Bzh1vxcl.mjs";import{y as ir}from"./parse-validator-CusS8QwU.mjs";import{buildSchemaSnapshot as or}from"./SchemaSnapshotParseError-BkgxjBPQ.mjs";const ar=e=>{const t=[],s=e.tables.filter(r=>r.shardMode==="global");return s.some(r=>r.globalBackend!=="hyperdrive")&&t.push({name:"@lunora/d1",reason:"`.global()` tables are D1-backed, so `_generated/app.ts` imports the D1 `ctx.db` adapter"}),s.some(r=>r.globalBackend==="hyperdrive")&&t.push({name:"@lunora/hyperdrive",reason:'`.global({ backend: "hyperdrive" })` tables route through `@lunora/hyperdrive/global`'}),e.vectorIndexes.length>0&&t.push({name:"@lunora/bindings",reason:"`.vectorize()` indexes make `_generated/vectors.ts` import `@lunora/bindings/vectors`"}),t},cr=(e,t)=>{if(t===void 0)return;const s=ar(e).filter(i=>!t.has(i.name));if(s.length===0)return;const r=s.map(i=>` - ${i.name} — ${i.reason}`).join(`
|
|
2
|
-
`);throw new k("INTERNAL",`@lunora/codegen: this schema's generated code imports packages the project does not declare:
|
|
3
|
-
${r}
|
|
4
|
-
|
|
5
|
-
Install them with your package manager, then re-run codegen.`)},lr="env.ts",ur=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineEnv";for(const s of t.getDeclarations())if(o.isImportSpecifier(s))return Y(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineEnv":!1;return!1},dr=e=>{const t=e.getSymbol();if(!t)return!1;for(const s of t.getDeclarations()){if(!o.isNamespaceImport(s))continue;const r=s.getFirstAncestorByKind(l.ImportDeclaration);return r!==void 0&&Y(r.getModuleSpecifierValue())}return!1},gr=e=>{if(o.isIdentifier(e))return ur(e);if(o.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineEnv"&&o.isIdentifier(t)&&dr(t)}return!1},pr=e=>{const t=[];for(const s of e.getVariableDeclarations()){if(!s.isExported())continue;const r=s.getInitializer();if(r?.getKind()!==l.CallExpression||!gr(r.getExpression()))continue;const i=s.getNameNode();if(!o.isIdentifier(i))throw Z(i,"defineEnv exports must be plain named exports (no destructuring)");t.push({exportName:i.getText()})}return t},fr=(e,t)=>{const s=g(t,lr);if(!b(s))return;const r=e.getSourceFile(s)??e.addSourceFileAtPath(s),i=pr(r);if(i.length!==0){if(i.length>1)throw Z(r,`lunora/env.ts declares ${i.length.toString()} defineEnv() contracts (${i.map(n=>n.exportName).join(", ")}); exactly one is allowed`);return i[0]}},mr=e=>{const t=r=>o.isIdentifier(r)&&r.getText()==="ctx",s=new Set;for(const r of e.getDescendantsOfKind(l.PropertyAccessExpression))t(r.getExpression())&&s.add(r.getName());for(const r of e.getDescendantsOfKind(l.VariableDeclaration)){const i=r.getInitializer(),n=r.getNameNode();if(!(i===void 0||!t(i)||!o.isObjectBindingPattern(n)))for(const a of n.getElements()){const c=a.getPropertyNameNode()?.getText()??a.getName();c&&s.add(c)}}return s},hr=(e,t)=>{const s=Object.fromEntries(de.map(r=>[r.key,!1]));for(const r of h(t)){const i=e.getSourceFile(r)??e.addSourceFileAtPath(r),n=new Set(i.getImportDeclarations().map(c=>c.getModuleSpecifierValue())),a=mr(i);for(const c of de)if(!s[c.key]){if(n.has(c.moduleSpecifier)){s[c.key]=!0;continue}c.contextProperty!==void 0&&a.has(c.contextProperty)&&(s[c.key]=!0)}if(de.every(c=>s[c.key]))break}return s},xr=["providerSubscriptionId","state"],Er=["providerEventId","processedAt"],He=(e,t)=>t.every(s=>s in e.shape),yr=e=>{const t=e.find(r=>r.name==="subscriptions"),s=e.find(r=>r.name==="events");return t!==void 0&&s!==void 0&&He(t,xr)&&He(s,Er)},$r=(e,t)=>({analytics:e.analytics||t.dependencies.has("@lunora/bindings/analytics"),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/kv"),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:e.vectors||t.vectorIndexCount>0||t.dependencies.has("@lunora/bindings/vectors"),workflows:e.workflows||t.workflowCount>0||t.dependencies.has("@lunora/workflow")}),ht="identity.ts",vr=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineIdentity";for(const s of t.getDeclarations())if(o.isImportSpecifier(s))return Y(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineIdentity":!1;return!1},br=e=>{const t=e.getSymbol();if(!t)return!1;for(const s of t.getDeclarations()){if(!o.isNamespaceImport(s))continue;const r=s.getFirstAncestorByKind(l.ImportDeclaration);return r!==void 0&&Y(r.getModuleSpecifierValue())}return!1},Nr=e=>{if(o.isIdentifier(e))return vr(e);if(o.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineIdentity"&&o.isIdentifier(t)&&br(t)}return!1},Sr=e=>{const t=[];for(const s of e.getVariableDeclarations()){if(!s.isExported())continue;const r=s.getInitializer();if(r?.getKind()!==l.CallExpression||!Nr(r.getExpression()))continue;const i=s.getNameNode();if(!o.isIdentifier(i))throw Z(i,"defineIdentity exports must be plain named exports (no destructuring)");t.push({exportName:i.getText()})}return t},Ar=(e,t)=>{const s=g(t,ht);if(!b(s))return;const r=e.getSourceFile(s)??e.addSourceFileAtPath(s),i=Sr(r);if(i.length!==0){if(i.length>1)throw Z(r,`lunora/identity.ts declares ${i.length.toString()} defineIdentity() contracts (${i.map(n=>n.exportName).join(", ")}); exactly one is allowed`);return i[0]}},wr=(e,t)=>{const s=new Map,r=new Map,i=new Map;for(const n of e)s.set(n.name,`workflow "${n.exportName}"`),r.set(n.bindingName,`workflow "${n.exportName}"`),i.set(n.className,`workflow "${n.exportName}"`);for(const n of t){const a=s.get(n.name);if(a!==void 0)throw new k("DUPLICATE_WORKFLOW_NAME",`Duplicate deployed name "${n.name}": produced by both ${a} and agent "${n.exportName}". Workflow and agent names share the same wrangler workflows[] array and must be unique together.`,{status:500});const c=r.get(n.bindingName);if(c!==void 0)throw new k("DUPLICATE_WORKFLOW_BINDING",`Duplicate binding "${n.bindingName}": produced by both ${c} and agent "${n.exportName}". Workflow and agent bindings share the same wrangler workflows[] array and must be unique together.`,{status:500});const u=i.get(n.className);if(u!==void 0)throw new k("DUPLICATE_WORKFLOW_CLASS",`Duplicate generated class "${n.className}": produced by both ${u} and agent "${n.exportName}". Workflow and agent export names must yield unique generated class names.`,{status:500})}},Pr=e=>{const{lunoraDirectory:t,project:s,projectRoot:r,schema:i}=e,n=Ar(s,t),a=fr(s,t),c=xs(s,t),u=fs(s,t),d=Gt(s,t);wr(c,d);const y=Ht(s,t),w=hs(s,t),p=Es(hr(s,t),ys(r,e.target)),v=p.usage,O=ms(s,t),j=v.browser||O.usesSandboxBrowser,z=ps(r),U=z??new Set,T=U.has("lunorash");cr(i,z);const C=b(g(t,"flags.ts")),q=b(g(t,"notify.ts"));return{agents:d,containers:y,dataModelContent:Jt(i),declaredDependencies:z,dependencies:U,env:a,featureUsage:v,hasBrowser:j,hasFlags:C,hasNotify:q,identity:n,platformGate:p,queues:u,serverContent:Qt({agents:d,containers:y,env:a,hasAccessFacade:v.access,hasAi:v.ai,hasAnalytics:v.analytics,hasBrowser:j,hasFlags:C,hasHyperdrive:v.hyperdrive,hasImages:v.images,hasKv:v.kv,hasNotify:q,hasPayments:v.payments,hasPipelines:v.pipelines,hasR2sql:v.r2sql,hasX402:v.x402,identity:n,queues:u,schema:i,storageRuleBuckets:w.rules.map(se=>se.bucket),useUmbrella:T,workflows:c}),storageRulesMetadata:w,usesSandbox:O.usesSandboxBrowser||O.usesSandboxContainer,useUmbrella:T,workflows:c}},xt=new Set(["delete","get","head","options","patch","post","put"]),Ir=new Set(["handler","stream"]),Tr=/\/(?:_|admin|internal|superuser|sudo|root|debug)/iu,Qe=new Set(["ADMIN_TOKEN","adminToken","assertAdmin","assertAuth","auth","Authorization","getSession","identity","isAdmin","requireAdmin","requireAuth","requireRole","verifyAdmin"]),Lr=e=>{if(!o.isCallExpression(e))return;const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||!xt.has(t.getName()))return;const s=t.getExpression();if(!o.isIdentifier(s)||s.getText()!=="httpRoute")return;const r=e.getArguments()[0];if(!(!r||!o.isStringLiteral(r)))return{method:t.getName().toUpperCase(),path:r.getLiteralValue()}},kr=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t))return;let s=t.getExpression();for(;o.isCallExpression(s);){const r=s.getExpression();if(!o.isPropertyAccessExpression(r)||xt.has(r.getName()))break;s=r.getExpression()}return Lr(s)},Dr=e=>{for(const t of e.getDescendantsOfKind(l.PropertyAccessExpression))if(Qe.has(t.getName()))return!0;for(const t of e.getDescendantsOfKind(l.CallExpression)){const s=t.getExpression();if(o.isIdentifier(s)&&Qe.has(s.getText()))return!0}return!1},Fr=(e,t)=>{const s=e.getInitializer();if(!s||!o.isCallExpression(s))return;const r=s.getExpression();if(!o.isPropertyAccessExpression(r)||!Ir.has(r.getName()))return;const i=kr(s);if(!i||!Tr.test(i.path))return;const n=s.getArguments()[0],a=n!==void 0&&(o.isArrowFunction(n)||o.isFunctionExpression(n))&&Dr(n);return{exportName:e.getName(),file:t,method:i.method,path:i.path,usesGuard:a}},Or=(e,t)=>{const s=[];for(const r of e.getVariableStatements())if(r.isExported())for(const i of r.getDeclarations()){const n=Fr(i,t);n&&s.push(n)}return s},Cr=(e,t)=>{const s=[];for(const r of h(t)){const i=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Or(i,E(t,r)))}return s},Kr=e=>!o.isPropertyAccessExpression(e)||e.getName()!=="run"?!1:e.getExpression().getText()==="ctx.ai",Rr=(e,t)=>{if(!Kr(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!I(s)||D(s)))return{exportName:x(e),file:t,line:e.getStartLineNumber()}},Mr=(e,t)=>N(e,t,Rr),jr=new Set(["generateText","streamText"]),zr=new Set(["messages","prompt","system"]),qr=[{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"]}],Br=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t))return;const s=t.getName(),r=t.getExpression().getText();for(const i of qr)if(i.methods.has(s)&&i.prefixes.some(n=>r===n||r.startsWith(`${n}.`)))return`${r}.${s}`},Ur=e=>{for(const t of e.getDescendantsOfKind(l.CallExpression)){const s=Br(t);if(s!==void 0)return s}},Vr=e=>{const t=new Set,s=e.getFirstAncestor(n=>o.isArrowFunction(n)||o.isFunctionExpression(n)||o.isFunctionDeclaration(n)),[r]=s?.getParameters()??[],i=r?.getNameNode();if(i===void 0||!o.isObjectBindingPattern(i))return t;for(const n of i.getElements()){const a=n.getPropertyNameNode()?.getText()??n.getName(),c=n.getNameNode();if(a==="args"&&o.isObjectBindingPattern(c))for(const u of c.getElements())t.add(u.getName())}return t},Wr=e=>{if($s(e))return!0;const t=Vr(e);return t.size===0?!1:e.getDescendantsOfKind(l.Identifier).some(s=>t.has(s.getText()))},_r=e=>{for(const t of e.getProperties()){if(!o.isPropertyAssignment(t)||!zr.has(t.getName()))continue;const s=t.getInitializer();if(s!==void 0&&Wr(s))return!0}return!1},Gr=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(l.CallExpression)){const i=A(r.getExpression());if(i===void 0||!jr.has(i))continue;const[n]=r.getArguments();if(n===void 0||!o.isObjectLiteralExpression(n))continue;let a;for(const c of n.getDescendantsOfKind(l.CallExpression))if(A(c.getExpression())==="tool"&&(a=Ur(c),a!==void 0))break;a!==void 0&&s.push({exportName:x(r),file:t,line:r.getStartLineNumber(),method:i,sideEffect:a,userInputDerived:_r(n)})}return s},Hr=(e,t)=>{const s=[];for(const r of h(t)){const i=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Gr(i,E(t,r)))}return s},Qr=e=>{if(!o.isPropertyAccessExpression(e)||e.getName()!=="fetch")return!1;const t=e.getExpression();return o.isIdentifier(t)&&t.getText()==="ctx"},Jr=(e,t)=>{if(!Qr(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!I(s)))return{exportName:x(e),file:t,line:e.getStartLineNumber()}},Xr=(e,t)=>N(e,t,Jr),Et=e=>e.getProperties().some(t=>o.isSpreadAssignment(t)),Zr=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 r=s.getInitializer();return!r||!o.isObjectLiteralExpression(r)?{objects:[],opaque:!0}:{objects:[r],opaque:Et(r)}},Yr=e=>{const t=[];let s=!1,r=e;for(;o.isCallExpression(r);){const i=r.getExpression();if(!o.isPropertyAccessExpression(i))break;if(i.getName()==="input"){const n=r.getArguments()[0];n&&o.isObjectLiteralExpression(n)?(t.push(n),s||=Et(n)):s=!0}r=i.getExpression()}return{objects:t,opaque:s}},yt=(e,t)=>t?Yr(t):Zr(e),en=e=>e.flatMap(t=>t.getProperties().filter(s=>o.isPropertyAssignment(s)||o.isShorthandPropertyAssignment(s)).map(s=>s.getName())),tn=/\.check\(|\.meta\(|length|max/iu,sn=/\bv\.any\s*\(/u,rn=/\bv\.string\s*\(/u,nn=e=>sn.test(e),on=e=>rn.test(e)&&!tn.test(e),an=e=>{const t=[],s=[];for(const r of e)for(const i of r.getProperties()){if(!o.isPropertyAssignment(i))continue;const n=i.getInitializer();if(!n)continue;const a=n.getText(),c=i.getName();nn(a)?t.push(c):on(a)&&s.push(c)}return{anyArgs:t,unboundedStringArgs:s}},cn=(e,t)=>{const s=e.getInitializer();if(!s||!o.isCallExpression(s))return;const r=M(s);if(r?.visibility!=="public")return;const{objects:i}=yt(s,r.receiver),{anyArgs:n,unboundedStringArgs:a}=an(i);if(!(n.length===0&&a.length===0))return{anyArgs:n,exportName:e.getName(),file:t,line:s.getStartLineNumber(),unboundedStringArgs:a}},ln=(e,t)=>{const s=[];for(const r of e.getVariableStatements())if(r.isExported())for(const i of r.getDeclarations()){const n=cn(i,t);n&&s.push(n)}return s},un=(e,t)=>{const s=[];for(const r of h(t)){const i=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...ln(i,E(t,r)))}return s},ge=e=>e?.getKind()===l.TrueKeyword,dn=e=>e?.getKind()===l.FalseKeyword,gn=e=>e!==void 0&&o.isNumericLiteral(e)&&e.getLiteralValue()===0,pn=new Set(["lunoraAuthAdapter","lunoraD1Adapter"]),fn=e=>!e||!o.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>o.isCallExpression(t)&&A(t.getExpression())==="scim"),mn=e=>e!==void 0&&o.isCallExpression(e)&&pn.has(A(e.getExpression())??""),hn=e=>!e||!o.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>o.isStringLiteral(t)&&t.getLiteralText()==="*"),xn=e=>{const t=$(e,"advanced"),s=$(e,"emailAndPassword"),r=$(e,"session");return{analyzable:!0,disableCsrfCheck:ge($(t,"disableCSRFCheck")),emailPasswordEnabled:ge($(s,"enabled")),requireEmailVerification:ge($(s,"requireEmailVerification")),scimOnNonTransactionalAdapter:fn($(e,"plugins"))&&mn($(e,"database")),secureCookiesDisabled:dn($(t,"useSecureCookies")),sessionFreshAgeZero:gn($(r,"freshAge")),trustedOriginsWildcard:hn($(e,"trustedOrigins"))}},En=()=>({analyzable:!1,disableCsrfCheck:!1,emailPasswordEnabled:!1,requireEmailVerification:!1,scimOnNonTransactionalAdapter:!1,secureCookiesDisabled:!1,sessionFreshAgeZero:!1,trustedOriginsWildcard:!1}),yn=(e,t)=>{if(A(e.getExpression())!=="createAuth")return;const s=e.getArguments()[0],r=s!==void 0&&o.isObjectLiteralExpression(s)&&s.getProperties().some(n=>o.isSpreadAssignment(n)),i=s!==void 0&&o.isObjectLiteralExpression(s)&&!r?xn(s):En();return{exportName:x(e),file:t,line:e.getStartLineNumber(),...i}},$n=(e,t)=>N(e,t,yn),vn=(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},bn=(e,t,s)=>{const r=vn(e.getExpression(),s);if(r===void 0)return;const i=e.getArguments()[s.argIndex];if(!(!i||!I(i)||D(i))&&!(s.requireUnmodifiedReach===!0&&!vs(i)))return{exportName:x(e),file:t,line:e.getStartLineNumber(),method:r}},Nn=(e,t,s)=>{const r=[];for(const i of e.getDescendantsOfKind(l.CallExpression)){const n=bn(i,t,s);n&&r.push(n)}return r},te=(e,t,s)=>{const r=[];for(const i of h(t)){const n=e.getSourceFile(i)??e.addSourceFileAtPath(i);r.push(...Nn(n,E(t,i),s))}return r},Sn=new Set(["content","pdf","scrape","screenshot"]),An=(e,t)=>te(e,t,{argIndex:0,matchReceiver:s=>s==="ctx.browser",methods:Sn}),wn=new Set(["createBrowser","createInboundEmailHandler","createPayment"]),Pn=new Set(["RateLimiter"]),In=new Set(["extend"]),$t=e=>{const t=[],s=[];let r=!1;for(const i of e.getProperties()){if(o.isSpreadAssignment(i)){r=!0;continue}if(o.isPropertyAssignment(i)){const n=i.getName();t.push(n),i.getInitializer()?.getKind()===l.TrueKeyword&&s.push(n);continue}(o.isShorthandPropertyAssignment(i)||o.isMethodDeclaration(i))&&t.push(i.getName())}return{analyzable:!r,presentKeys:t,trueKeys:s}},Je=e=>e&&o.isObjectLiteralExpression(e)?$t(e):{analyzable:!1,presentKeys:[],trueKeys:[]},Tn=e=>{const t=e.getStatements(),[s]=t;if(t.length!==1||s===void 0||!o.isReturnStatement(s))return;const r=s.getExpression();return r!==void 0&&o.isObjectLiteralExpression(r)?r:void 0},Ln=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)?Tn(e):void 0},kn=e=>{const t=e&&(o.isArrowFunction(e)||o.isFunctionExpression(e))?e:void 0,s=t&&Ln(t.getBody());return s?$t(s):{analyzable:!1,presentKeys:[],trueKeys:[]}},Dn=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(l.CallExpression)){const i=A(r.getExpression());i!==void 0&&(wn.has(i)?s.push({callee:i,file:t,line:r.getStartLineNumber(),...Je(r.getArguments()[0])}):In.has(i)&&s.push({callee:i,file:t,line:r.getStartLineNumber(),...kn(r.getArguments()[0])}))}for(const r of e.getDescendantsOfKind(l.NewExpression)){const i=A(r.getExpression());i===void 0||!Pn.has(i)||s.push({callee:i,file:t,line:r.getStartLineNumber(),...Je(r.getArguments()[0])})}return s},Fn=(e,t)=>{const s=[];for(const r of h(t)){const i=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Dn(i,E(t,r)))}return s},Xe="ctx.containers.",On=e=>{if(!e.startsWith(Xe))return!1;const t=e.slice(Xe.length);return t.length>0&&!t.includes(".")},Cn=(e,t)=>te(e,t,{argIndex:0,matchReceiver:On,methods:new Set(["get"])}),Kn=new Set(["allow","deny","setAllowed"]),Rn=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())},Mn=(e,t)=>{const s=e.getExpression();if(!(!o.isPropertyAccessExpression(s)||s.getName()!=="start"||!Rn(e)))return{detail:"enableInternet: true",exportName:x(e),file:t,kind:"enable_internet",line:e.getStartLineNumber()}},jn=(e,t)=>{const s=e.getExpression();if(!o.isPropertyAccessExpression(s)||!Kn.has(s.getName()))return;const r=s.getExpression();if(!(!o.isPropertyAccessExpression(r)||r.getName()!=="egress"))return{detail:s.getName(),exportName:x(e),file:t,kind:"egress_relaxation",line:e.getStartLineNumber()}},zn=(e,t)=>Mn(e,t)??jn(e,t),qn=(e,t)=>N(e,t,zn),Bn=new Set(["defineExportSink","r2Sink","webhookExportSink"]),Un=e=>{const t=e.getExpression();if(!o.isIdentifier(t))return;const s=t.getText();return Bn.has(s)?s:void 0},Vn=e=>{const t=[],s=[];for(const r of e.getProperties()){if(o.isSpreadAssignment(r))return{analyzable:!1,emptyKeys:[],presentKeys:[]};if(o.isPropertyAssignment(r)){const i=r.getName();t.push(i);const n=r.getInitializer();n&&o.isStringLiteral(n)&&n.getLiteralText()===""&&s.push(i);continue}(o.isShorthandPropertyAssignment(r)||o.isMethodDeclaration(r)||o.isGetAccessorDeclaration(r))&&t.push(r.getName())}return{analyzable:!0,emptyKeys:s,presentKeys:t}},Wn=(e,t)=>{const s=[];for(const r of h(t)){const i=e.getSourceFile(r)??e.addSourceFileAtPath(r),n=E(t,r);for(const a of i.getDescendantsOfKind(l.CallExpression)){const c=Un(a);if(c===void 0)continue;const u=a.getArguments()[0],d=u&&o.isObjectLiteralExpression(u)?Vn(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},_n=new Map([["dbRateLimit",2],["rateLimit",2],["verifyTurnstileMiddleware",0]]),Gn=new Set(["dbRateLimit","rateLimit"]),Hn=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},Qn=(e,t)=>{const s=A(e.getExpression());if(s===void 0)return;const r=_n.get(s);if(r!==void 0)return{callee:s,exportName:x(e),failOpen:Hn(e.getArguments()[r]),file:t,limitName:Gn.has(s)?gt(e):"",line:e.getStartLineNumber()}},Jn=(e,t)=>N(e,t,Qn),Xn=e=>{if(!o.isPropertyAccessExpression(e)||e.getName()!=="boolean")return!1;const t=e.getExpression();return o.isPropertyAccessExpression(t)&&t.getName()==="flags"&&ds(t.getExpression())},Zn=e=>{if(e?.getKind()===l.TrueKeyword)return!0;if(e?.getKind()===l.FalseKeyword)return!1},Yn=(e,t)=>{if(!Xn(e.getExpression()))return;const[s,r]=e.getArguments();if(!s||!(o.isStringLiteral(s)||o.isNoSubstitutionTemplateLiteral(s)))return;const i=s.getLiteralValue(),n=Zn(r);if(!(i.length===0||n===void 0))return{defaultValue:n,exportName:x(e),file:t,key:i,line:e.getStartLineNumber()}},ei=(e,t)=>N(e,t,Yn),ti=e=>{const t=e.getExpression();return o.isPropertyAccessExpression(t)&&t.getName()==="withGeoIndex"},si=e=>{const t=e.getArguments()[0];return t&&o.isStringLiteral(t)?t.getLiteralText():""},ri=(e,t)=>{const s=[];for(const r of h(t)){const i=e.getSourceFile(r)??e.addSourceFileAtPath(r),n=E(t,r);for(const a of i.getDescendantsOfKind(l.CallExpression))ti(a)&&s.push({file:n,indexName:si(a),line:a.getStartLineNumber()})}return s},ni=new Set(["delete","get","head","options","patch","post","put"]),ii=new Set(["handler","stream"]),oi=new Set(["runAction","runMutation"]),ai=new Set(["delete","insert","insertManyUnsafe","patch","replace"]),Q=(e,t)=>e!==void 0&&o.isIdentifier(e)&&e.getText()===t,Ze=e=>e!==void 0&&(o.isArrowFunction(e)||o.isFunctionExpression(e))?e:void 0,Ye=(e,t)=>{const s=e.getParameters()[0];if(s===void 0)return;const r=s.getNameNode();if(t)return o.isIdentifier(r)?r.getText():void 0;if(o.isObjectBindingPattern(r)){for(const i of r.getElements())if((i.getPropertyNameNode()?.getText()??i.getNameNode().getText())==="ctx"){const n=i.getNameNode();return o.isIdentifier(n)?n.getText():void 0}}},et=(e,t)=>{const s=e.getBody(),r=s.getDescendantsOfKind(l.CallExpression);o.isCallExpression(s)&&r.unshift(s);for(const i of r){const n=i.getExpression();if(!o.isPropertyAccessExpression(n))continue;const a=n.getName(),c=n.getExpression();if(oi.has(a)&&Q(c,t))return a;if(ai.has(a)&&o.isPropertyAccessExpression(c)&&c.getName()==="db"&&Q(c.getExpression(),t))return`db.${a}`}},tt=(e,t)=>{const s=e.getBody();for(const r of s.getDescendantsOfKind(l.PropertyAccessExpression))if(r.getName()==="auth"&&Q(r.getExpression(),t))return!0;for(const r of s.getDescendantsOfKind(l.VariableDeclaration)){const i=r.getNameNode();if(!(!o.isObjectBindingPattern(i)||!Q(r.getInitializer(),t))){for(const n of i.getElements())if((n.getPropertyNameNode()?.getText()??n.getNameNode().getText())==="auth")return!0}}return!1},ci=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||!ii.has(t.getName()))return;let s=t.getExpression();for(;o.isCallExpression(s);){const r=s.getExpression();if(!o.isPropertyAccessExpression(r))return;const i=r.getName();if(ni.has(i)){const n=r.getExpression();return o.isIdentifier(n)&&n.getText()==="httpRoute"?i.toUpperCase():void 0}s=r.getExpression()}},li=(e,t)=>{const s=e.getExpression();if(o.isIdentifier(s)&&s.getText()==="httpAction"){const c=Ze(e.getArguments()[0]),u=c&&Ye(c,!0);if(!c||u===void 0)return;const d=et(c,u);return d===void 0?void 0:{exportName:x(e),file:t,kind:"httpAction",line:e.getStartLineNumber(),readsAuth:tt(c,u),sideEffect:d}}const r=ci(e);if(r===void 0)return;const i=Ze(e.getArguments()[0]),n=i&&Ye(i,!1);if(!i||n===void 0)return;const a=et(i,n);return a===void 0?void 0:{exportName:x(e),file:t,kind:"httpRoute",line:e.getStartLineNumber(),method:r,readsAuth:tt(i,n),sideEffect:a}},ui=(e,t)=>N(e,t,li),di=new Set(["btoa","encodeURI","encodeURIComponent","isSafeHeaderValue","Number","parseFloat","parseInt"]),gi=new Set(["append","set"]),he=e=>o.isIdentifier(e)?e.getText():o.isPropertyAccessExpression(e)?e.getName():"",vt=e=>e!==void 0&&(o.isStringLiteral(e)||o.isNoSubstitutionTemplateLiteral(e))?e.getLiteralText():"",st=(e,t)=>(o.isCallExpression(e)?[e,...e.getDescendantsOfKind(l.CallExpression)]:e.getDescendantsOfKind(l.CallExpression)).some(s=>di.has(he(s.getExpression()))&&Ns(s,t)),pi=(e,t)=>{if(st(e,t))return!0;const s=ee(e);return s!==void 0&&st(s,t)},me=(e,t)=>bs(e,t)&&!pi(e,t),fi=e=>{if(o.isPropertyAccessExpression(e)&&e.getName()==="headers")return!0;const t=ee(e);return t!==void 0&&o.isNewExpression(t)&&he(t.getExpression())==="Headers"},J=e=>{if(e===void 0)return;if(o.isObjectLiteralExpression(e))return e;const t=ee(e);return t!==void 0&&o.isObjectLiteralExpression(t)?t:void 0},xe=(e,t,s)=>{for(const r of e.getProperties())if(o.isPropertyAssignment(r)){const i=r.getInitializer();i!==void 0&&me(i,s.requestName)&&s.rows.push({exportName:s.exportName,file:s.relativePath,headerName:vt(r.getNameNode()),line:i.getStartLineNumber(),via:t})}else if(o.isShorthandPropertyAssignment(r)){const i=r.getNameNode();me(i,s.requestName)&&s.rows.push({exportName:s.exportName,file:s.relativePath,headerName:r.getName(),line:i.getStartLineNumber(),via:t})}else if(o.isSpreadAssignment(r)){const i=J(r.getExpression());i!==void 0&&xe(i,t,s)}},bt=(e,t)=>{const s=J(e);if(s===void 0)return;const r=s.getProperty("headers");if(r===void 0||!o.isPropertyAssignment(r))return;const i=J(r.getInitializer());i!==void 0&&xe(i,"response-init",t)},mi=(e,t)=>{const s=he(e.getExpression());if(s==="Response")bt(e.getArguments()[1],t);else if(s==="Headers"){const r=J(e.getArguments()[0]);r!==void 0&&xe(r,"headers-ctor",t)}},hi=(e,t)=>{const s=e.getExpression();if(!o.isPropertyAccessExpression(s))return;const r=s.getName(),i=s.getExpression();if(r==="json"&&o.isIdentifier(i)&&i.getText()==="Response"){bt(e.getArguments()[1],t);return}if(gi.has(r)&&fi(i)){const n=e.getArguments()[1];n!==void 0&&me(n,t.requestName)&&t.rows.push({exportName:t.exportName,file:t.relativePath,headerName:vt(e.getArguments()[0]),line:n.getStartLineNumber(),via:r==="set"?"headers-set":"headers-append"})}},xi=(e,t)=>{for(const s of e.getDescendantsOfKind(l.NewExpression))mi(s,t);for(const s of e.getDescendantsOfKind(l.CallExpression))hi(s,t)},Ei=(e,t)=>{const s=e.getExpression();if(!o.isIdentifier(s)||s.getText()!=="httpAction")return[];const r=As(e.getArguments()[0]);if(r===void 0)return[];const i=r.getParameters()[1];if(i===void 0)return[];const n=i.getNameNode();if(!o.isIdentifier(n))return[];const a=[];return xi(r,{exportName:x(e),relativePath:t,requestName:n.getText(),rows:a}),a},yi=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(l.CallExpression))s.push(...Ei(r,t));return s},$i=(e,t)=>{const s=[];for(const r of h(t)){const i=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...yi(i,E(t,r)))}return s},vi=new Set(["auth","context.auth","ctx.auth"]),bi="userId",Ni=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},Si=(e,t)=>{const s=g(t,ht);if(!b(s))return;const r=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const i of r.getDescendantsOfKind(l.CallExpression)){if(A(i.getExpression())!=="defineIdentity")continue;const[n]=i.getArguments();return n&&o.isObjectLiteralExpression(n)?Ni(n):void 0}},rt=e=>{if(!(e===void 0||!o.isPropertyAccessExpression(e)||e.getName()!=="identity"))return vi.has(e.getExpression().getText())?e:void 0},Ai=e=>{if(o.isPropertyAccessExpression(e)&&rt(e.getExpression())!==void 0)return e.getName();if(o.isElementAccessExpression(e)&&rt(e.getExpression())!==void 0){const t=e.getArgumentExpression();return t&&o.isStringLiteral(t)?t.getLiteralValue():void 0}},wi=(e,t,s)=>{const r=[];for(const i of e.getDescendants()){const n=Ai(i);n!==void 0&&r.push({declared:n===bi||s.has(n),exportName:x(i),file:t,key:n,line:i.getStartLineNumber()})}return r},Pi=(e,t)=>{const s=Si(e,t);if(s===void 0)return[];const r=[];for(const i of h(t)){const n=e.getSourceFile(i)??e.addSourceFileAtPath(i);r.push(...wi(n,E(t,i),s))}return r},Ii=(e,t)=>{if(A(e.getExpression())!=="buildImageDeliveryUrl")return;const s=e.getArguments()[0];if(!s)return;const r=$(s,"key");if(!(!r||!I(r)||D(r)))return{exportName:x(e),file:t,line:e.getStartLineNumber()}},Ti=(e,t)=>N(e,t,Ii),Li=new Set(["delete","get","getRaw","getWithMetadata","put"]),ki=(e,t)=>te(e,t,{argIndex:0,matchReceiver:s=>s==="ctx.kv"||s.startsWith("ctx.kv."),methods:Li}),Di=new Set(["queue","send"]),nt=new Set(["bcc","cc","to"]),Fi=e=>{if(!o.isPropertyAccessExpression(e))return;const t=e.getName();if(!Di.has(t))return;const s=e.getExpression().getText();return s==="ctx.mail"||s==="ctx.email"?t:void 0},Oi=e=>o.isObjectLiteralExpression(e)?e.getProperties().some(t=>{if(o.isShorthandPropertyAssignment(t)){const r=t.getNameNode();return nt.has(t.getName())&&I(r)&&!D(r)}if(!o.isPropertyAssignment(t)||!nt.has(t.getName()))return!1;const s=t.getInitializer();return s!==void 0&&I(s)&&!D(s)}):!1,Ci=(e,t)=>{const s=Fi(e.getExpression());if(s===void 0)return;const r=e.getArguments()[0];if(!(!r||!Oi(r)))return{exportName:x(e),file:t,line:e.getStartLineNumber(),method:s}},Ki=(e,t)=>N(e,t,Ci),Ri=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||t.getName()!=="replace")return!1;const s=t.getExpression();return o.isPropertyAccessExpression(s)?s.getName()==="db":o.isIdentifier(s)&&s.getText()==="db"},Mi=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},ji=e=>{if(!e.isExported())return;const t=e.getInitializer();if(t?.getKind()!==l.CallExpression)return;const s=t;return zs(s.getExpression())?s:void 0},zi=e=>{const t=ji(e),s=t===void 0?void 0:Mi(t);if(s===void 0)return[];const r=e.getNameNode(),i=o.isIdentifier(r)?r.getText():"";return s.getDescendantsOfKind(l.CallExpression).filter(n=>Ri(n)).map(n=>({exportName:i,file:"lunora/mutators.ts",line:n.getStartLineNumber()}))},qi=e=>e.getVariableDeclarations().flatMap(t=>zi(t)),Bi=(e,t)=>{const s=g(t,js);if(!b(s))return[];const r=e.getSourceFile(s)??e.addSourceFileAtPath(s);return qi(r)},Ui=new Set(["delete","get","patch"]),Vi=new Set(["accountId","authorId","companyId","createdBy","createdById","customerId","groupId","memberId","organizationId","orgId","ownerId","projectId","teamId","tenantId","userId","workspaceId"]),Wi=new Set(["auth","identity","session","user"]),_i=new Set([l.EqualsEqualsEqualsToken,l.EqualsEqualsToken,l.ExclamationEqualsEqualsToken,l.ExclamationEqualsToken]),Gi=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||t.getName()!=="normalizeId"||!R(t.getExpression()))return;const s=e.getArguments()[0];return s&&o.isStringLiteral(s)?s.getLiteralText():""},Hi=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 r=s.getNameNode();return o.isIdentifier(r)?r.getText():void 0},Qi=(e,t)=>e.getDescendantsOfKind(l.Identifier).some(s=>s.getText()===t),Ji=e=>o.isThrowStatement(e)||o.isReturnStatement(e)||e.getDescendantsOfKind(l.ThrowStatement).length>0||e.getDescendantsOfKind(l.ReturnStatement).length>0,Xi=(e,t)=>e.getDescendantsOfKind(l.IfStatement).some(s=>Qi(s.getExpression(),t)&&Ji(s.getThenStatement())),Zi=(e,t)=>{for(const s of e.getDescendantsOfKind(l.CallExpression)){const r=s.getExpression();if(!o.isPropertyAccessExpression(r))continue;const i=r.getName();if(!Ui.has(i))continue;const n=r.getExpression();if(!(R(n)||o.isPropertyAccessExpression(n)&&R(n.getExpression())))continue;const a=s.getArguments()[0];if(a!==void 0&&o.isIdentifier(a)&&a.getText()===t)return i}},Yi=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},eo=e=>e.getDescendantsOfKind(l.CallExpression).some(t=>t.getArguments().some(s=>Yi(s)==="ctx")),to=e=>e.getDescendantsOfKind(l.BinaryExpression).some(t=>_i.has(t.getOperatorToken().getKind())?o.isPropertyAccessExpression(t.getLeft())||o.isPropertyAccessExpression(t.getRight()):!1),so=e=>{for(const t of e.getDescendantsOfKind(l.Identifier))if(Vi.has(t.getText()))return!0;for(const t of e.getDescendantsOfKind(l.PropertyAccessExpression)){const s=t.getExpression();if(o.isIdentifier(s)&&s.getText()==="ctx"&&Wi.has(t.getName()))return!0}return eo(e)||to(e)},ro=(e,t)=>{if(!o.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!o.isCallExpression(s))return[];const r=M(s);if(r?.kind!=="query"&&r?.kind!=="mutation")return[];const i=ft(s);if(i===void 0)return[];const n=r.receiver!==void 0&&mt(r.receiver,"use","rls"),a=so(i),c=new Set,u=[];for(const d of i.getDescendantsOfKind(l.CallExpression)){const y=Gi(d);if(y===void 0)continue;const w=Hi(d);if(w===void 0||c.has(w)||!Xi(i,w))continue;const p=Zi(i,w);p!==void 0&&(c.add(w),u.push({exportName:e.getName(),file:t,line:d.getStartLineNumber(),mentionsOwnership:a,sinkMethod:p,table:y,usesRls:n,visibility:r.visibility}))}return u},no=(e,t)=>{const s=[];for(const r of h(t)){const i=e.getSourceFile(r)??e.addSourceFileAtPath(r),n=E(t,r);for(const a of i.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...ro(c,n))}return s},io=new Set(["accountId","authorId","createdBy","createdById","organizationId","orgId","ownerId","tenantId","updatedBy","userId","workspaceId"]),oo=new Set(["insert","insertManyUnsafe","patch","replace"]),ao=e=>{if(!o.isPropertyAccessExpression(e))return;const t=e.getName();if(!oo.has(t))return;const s=e.getExpression();if(!o.isPropertyAccessExpression(s)||s.getName()!=="db")return;const r=s.getExpression();return o.isIdentifier(r)&&r.getText()==="ctx"?t:void 0},co=(e,t)=>{if(t!=="insertManyUnsafe")return o.isObjectLiteralExpression(e)?[e]:[];if(!o.isArrayLiteralExpression(e))return[];const s=[];for(const r of e.getElements())o.isObjectLiteralExpression(r)&&s.push(r);return s},lo=(e,t,s,r)=>{const i=[];for(const n of e.getProperties()){let a,c;o.isPropertyAssignment(n)?(a=n.getName(),c=n.getInitializer()):o.isShorthandPropertyAssignment(n)&&(a=n.getName(),c=n.getNameNode()),!(a===void 0||c===void 0||!io.has(a))&&I(c)&&!D(c)&&i.push({exportName:x(s),field:a,file:r,line:s.getStartLineNumber(),method:t})}return i},uo=(e,t)=>{const s=ao(e.getExpression());if(s===void 0)return[];const r=e.getArguments()[1];return r?co(r,s).flatMap(i=>lo(i,s,e,t)):[]},go=(e,t,s)=>{const r=[];for(const i of e.getDescendantsOfKind(l.CallExpression))for(const n of uo(i,t)){const a=s(n.exportName);r.push(a===void 0?n:{...n,visibility:a})}return r},po=(e,t,s=[])=>{const r=[],i=new Map(s.map(n=>[`${n.filePath}:${n.exportName}`,n.visibility]));for(const n of h(t)){const a=e.getSourceFile(n)??e.addSourceFileAtPath(n),c=E(t,n);r.push(...go(a,c,u=>i.get(`${c}:${u}`)))}return r},fo=new Set(["createAutumnAdapter","createDodoPaymentsAdapter","createPolarAdapter","createStripeAdapter"]),mo=e=>e&&o.isNumericLiteral(e)?Number(e.getText()):void 0,ho=e=>{const t=e.getProperty("webhookToleranceSeconds");return t&&o.isPropertyAssignment(t)?mo(t.getInitializer()):void 0},xo=(e,t)=>{const s=A(e.getExpression());if(s===void 0||!fo.has(s))return;const[r]=e.getArguments(),i=r&&o.isObjectLiteralExpression(r)?ho(r):void 0;return{callee:s,exportName:x(e),file:t,line:e.getStartLineNumber(),...i===void 0?{}:{toleranceSeconds:i}}},Eo=(e,t)=>N(e,t,xo),yo=new Set(["defineQueue","defineWorkflow"]),$o=new Set(["run","runAction","runMutation","runQuery"]),vo=new Set(["api","internal"]),bo=e=>{const t=e.getExpression();return o.isIdentifier(t)?t.getText():void 0},No=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 r=s.getInitializer();if(r&&(o.isArrowFunction(r)||o.isFunctionExpression(r)))return r},Nt=(e,t)=>{const s=e.getParameters()[t]?.getNameNode();return s&&o.isIdentifier(s)?s.getText():void 0},St=(e,t)=>e===t||e.startsWith(`${t}.`),At=e=>{const t=e.getDescendantsOfKind(l.PropertyAccessExpression);return o.isPropertyAccessExpression(e)&&t.push(e),t},it=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)},wt=e=>{const t=e.getDescendantsOfKind(l.Identifier).filter(s=>it(s));return o.isIdentifier(e)&&it(e)&&t.push(e),t},So=e=>{if(!o.isVariableDeclaration(e))return[];const t=e.getNameNode();return o.isIdentifier(t)?[t.getText()]:t.getDescendantsOfKind(l.BindingElement).map(s=>s.getName())},Ao=e=>{const t=Nt(e,1);if(t===void 0)return[];const s=[`${t}.messages`];for(const r of e.getDescendantsOfKind(l.ForOfStatement)){if(r.getExpression().getText()!==`${t}.messages`)continue;const i=r.getInitializer(),n=o.isVariableDeclarationList(i)?i.getDeclarations()[0]?.getNameNode():void 0;n&&o.isIdentifier(n)&&s.push(`${n.getText()}.body`)}return s},wo=(e,t,s)=>{const r=t==="workflow"?[`${s}.params`]:Ao(e),i=new Set,n=a=>At(a).some(c=>r.some(u=>St(c.getText(),u)))?!0:wt(a).some(c=>i.has(c.getText()));for(const a of e.getDescendantsOfKind(l.VariableDeclaration)){const c=a.getInitializer();if(c&&n(c))for(const u of So(a))i.add(u)}return{names:i,prefixes:r}},Po=(e,t)=>At(e).some(s=>t.prefixes.some(r=>St(s.getText(),r)))?!0:wt(e).some(s=>t.names.has(s.getText())),Io=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 r=t.at(-1);if(!(r===void 0||!o.isIdentifier(s)||!vo.has(s.getText())||t.length<2))return{exportName:r,file:t.slice(0,-1).join("/")}},To=(e,t,s)=>{const r=Nt(e,0);if(r===void 0)return[];const i=wo(e,t,r),n=[];for(const a of e.getDescendantsOfKind(l.CallExpression)){const c=a.getExpression();if(!o.isPropertyAccessExpression(c)||!$o.has(c.getName())||c.getExpression().getText()!==r)continue;const u=a.getArguments()[1];if(!u||!Po(u,i))continue;const d=Io(a.getArguments()[0]);d!==void 0&&n.push({dispatchKind:t,file:s,handlerExport:x(a),line:a.getStartLineNumber(),targetExport:d.exportName,targetFile:d.file})}return n},Lo=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(l.CallExpression)){const i=bo(r);if(i===void 0||!yo.has(i))continue;const n=No(r);n!==void 0&&s.push(...To(n,i==="defineQueue"?"queue":"workflow",t))}return s},ko=(e,t)=>{const s=[];for(const r of h(t)){const i=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Lo(i,E(t,r)))}return s},ot={dbRateLimit:"usesRateLimit",emailGateMiddleware:"usesEmailGate",mask:"usesMask",rateLimit:"usesRateLimit",rls:"usesRls",verifyTurnstile:"usesCaptcha",verifyTurnstileMiddleware:"usesCaptcha"},at=new Set(["account","credential","member","passkey","session","user"]),Do=e=>e.replaceAll(/[-_]/gu," ").replaceAll(/([a-z0-9])([A-Z])/gu,"$1 $2").split(" ").filter(Boolean).map(t=>t.toLowerCase()),Fo=e=>{const t=Do(e).at(-1);if(!t)return!1;const s=t.endsWith("s")?t.slice(0,-1):t;return at.has(t)||at.has(s)},Oo=e=>{const t=e.replaceAll(/[^a-z0-9]/giu,"").toLowerCase();return t.endsWith("email")||t.endsWith("emailaddress")},Co=(e,t)=>{const{objects:s,opaque:r}=yt(e,t);return en(s).some(i=>Oo(i))?!0:r?void 0:!1},Ee=e=>{const t=e.getExpression();if(o.isIdentifier(t))return t.getText();if(o.isPropertyAccessExpression(t))return t.getName()},Ko=e=>{const t=e.getArguments()[0];return!t||!o.isObjectLiteralExpression(t)?{usesCaptcha:!1,usesRateLimit:!1}:{usesCaptcha:!!t.getProperty("captcha"),usesRateLimit:!!t.getProperty("rateLimit")}},Ro=e=>{if(o.isCallExpression(e))return e;if(!o.isIdentifier(e))return;const t=e.getSourceFile().getVariableDeclaration(e.getText())?.getInitializer();return t&&o.isCallExpression(t)?t:void 0},H={usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},Mo=e=>{const t=Ro(e),s=t?Ee(t):void 0;if(t&&s==="protectPublic"){const r=Ko(t);return{...H,usesCaptcha:r.usesCaptcha,usesRateLimit:r.usesRateLimit}}return s!==void 0&&s in ot?{...H,[ot[s]]:!0}:H},jo=e=>{const t={...H};let s=e;for(;o.isCallExpression(s);){const r=s.getExpression();if(!o.isPropertyAccessExpression(r))break;const i=r.getName()==="use"?s.getArguments()[0]:void 0;if(i){const n=Mo(i);t.usesCaptcha||=n.usesCaptcha,t.usesEmailGate||=n.usesEmailGate,t.usesMask||=n.usesMask,t.usesRateLimit||=n.usesRateLimit,t.usesRls||=n.usesRls}s=r.getExpression()}return t},zo=new Set(["insert","insertMany","insertManyUnsafe","replace"]),qo=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||!zo.has(t.getName()))return!1;const s=t.getExpression();if(!(o.isPropertyAccessExpression(s)?s.getName()==="db":o.isIdentifier(s)&&s.getText()==="db"))return!1;const r=e.getArguments()[0];return!r||!(o.isStringLiteral(r)||o.isNoSubstitutionTemplateLiteral(r))?!1:Fo(r.getLiteralText())},Bo=new Set(["create","runAfter","runAt","send","sendBatch"]),Uo=new Set(["queues","scheduler","workflows"]),Vo=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||!Bo.has(t.getName()))return!1;let s=t.getExpression();for(;o.isCallExpression(s)||o.isElementAccessExpression(s)||o.isPropertyAccessExpression(s);){if(o.isPropertyAccessExpression(s)&&Uo.has(s.getName())){const r=s.getExpression();if(o.isIdentifier(r)&&r.getText()==="ctx")return!0}s=s.getExpression()}return!1},Wo=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||t.getName()!=="insertManyUnsafe")return!1;const s=t.getExpression();return o.isPropertyAccessExpression(s)?s.getName()==="db":o.isIdentifier(s)&&s.getText()==="db"},Pt=new Set(["generateObject","generateText","streamObject","streamText"]),_o=e=>{const t=Ee(e);return t!==void 0&&Pt.has(t)},Go=e=>{const t=Ee(e);if(t===void 0||!Pt.has(t))return!1;const s=e.getArguments()[0];return!s||!o.isObjectLiteralExpression(s)||s.getProperties().some(r=>o.isSpreadAssignment(r))?!1:!s.getProperty("maxOutputTokens")},Ho=new Set(["log","span","trace"]),Qo=new Set(["ai"]),Jo=new Set(["email","mail"]),Xo=new Set(["ai","browser","fetch","mail","notify","queues","sql","storage","workflows"]),pe=(e,t)=>e.getDescendantsOfKind(l.PropertyAccessExpression).some(s=>{if(!t.has(s.getName()))return!1;const r=s.getExpression();return o.isIdentifier(r)&&r.getText()==="ctx"}),Zo=new Set([l.ArrowFunction,l.FunctionDeclaration,l.FunctionExpression,l.GetAccessor,l.MethodDeclaration,l.SetAccessor]),Yo=new Set(["every","filter","flatMap","forEach","map","some"]),ea=new Set(["all","allSettled","race"]),ta=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 r=s.getName();if(Yo.has(r))return t;const i=s.getExpression();if(o.isIdentifier(i)&&i.getText()==="Promise"&&ea.has(r))return t},sa=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(Zo.has(t.getKind())){const s=ta(t);if(!s)return!1;t=s;continue}t=t.getParent()}return!1},ra=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 r=s.getParent();if(!o.isCallExpression(r)||r.getExpression()!==s)return!1;t=r}},na=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}},ia=e=>{let t=!1,s=!0;for(const r of e.getDescendantsOfKind(l.PropertyAccessExpression)){if(!Xo.has(r.getName()))continue;const i=r.getExpression();if(!o.isIdentifier(i)||i.getText()!=="ctx")continue;const n=na(r);n&&(t=!0,!sa(n)&&!ra(n)&&(s=!1))}return{handlesErrors:t&&s,reachesOutbound:t}},oa=e=>e.getDescendantsOfKind(l.ThrowStatement).some(t=>{const s=t.getExpression();if(!o.isNewExpression(s))return!1;const r=s.getExpression();return o.isIdentifier(r)&&r.getText()==="Error"}),ct="lunora-advisor-exempt",aa=/^[\s*/]+/u,ca=/[\w-]/u,la=e=>{const t=(e.getFirstAncestorByKind(l.VariableStatement)??e).getLeadingCommentRanges().map(s=>s.getText()).join(`
|
|
6
|
-
`);for(const s of t.split(`
|
|
7
|
-
`)){const r=s.replace(aa,"");if(!r.startsWith(ct))continue;const i=r.slice(ct.length);if(ca.test(i.charAt(0)))continue;const n=i.indexOf("--");return{exempt:!0,exemptReason:(n===-1?"":i.slice(n+2).split("*")[0]??"").trim()}}return{exempt:!1,exemptReason:""}},ua=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}},da=(e,t)=>{const s=ua(t);if(!s)return;if(o.isArrowFunction(s)||o.isFunctionExpression(s)||o.isMethodDeclaration(s))return e;if(!o.isIdentifier(s))return;const r=s.getSourceFile(),i=s.getText(),n=r.getVariableDeclaration(i)?.getInitializer();return n&&(o.isArrowFunction(n)||o.isFunctionExpression(n))?n:r.getFunction(i)},ga=e=>{let t=!1,s=!1,r=!1,i=!1,n=!1;for(const u of e.getDescendantsOfKind(l.CallExpression))if(qo(u)&&(n=!0),Vo(u)&&(t=!0),Wo(u)&&(i=!0),_o(u)&&(s=!0),Go(u)&&(r=!0),n&&t&&i&&r)break;const{handlesErrors:a,reachesOutbound:c}=ia(e);return{callsMail:pe(e,Jo),emitsEvent:pe(e,Ho),fanOut:t,handlesErrors:a,reachesOutbound:c,runsAiGeneration:s||pe(e,Qo),throwsBareError:oa(e),unboundedAiGeneration:r,usesInsertManyUnsafe:i,writesUserTable:n}},pa=(e,t)=>{const s=e.getInitializer();if(!s||!o.isCallExpression(s))return;const r=M(s);if(!r||r.kind!=="query"&&r.kind!=="mutation"&&r.kind!=="action")return;const i=r.receiver?jo(r.receiver):{usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},n=da(e,s);return{...n?ga(n):{},...la(e),...i,analyzableBody:n!==void 0,exportName:e.getName(),file:t,hasEmailArg:Co(s,r.receiver),kind:r.kind,visibility:r.visibility}},fa=(e,t)=>{const s=[];for(const r of e.getVariableStatements())if(r.isExported())for(const i of r.getDeclarations()){const n=pa(i,t);n&&s.push(n)}return s},ma=(e,t)=>{const s=[];for(const r of h(t)){const i=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...fa(i,E(t,r)))}return s},ha=new Set(["dbRateLimit","rateLimit"]),xa=e=>o.isArrowFunction(e)?e.getBody():e,Ea=(e,t)=>{const s=A(e.getExpression());if(s===void 0||!ha.has(s))return;const r=e.getArguments()[2];if(!r)return;const i=$(r,"key");if(!i)return;const n=xa(i);if(!(!I(n)||D(n)))return{callee:s,exportName:x(e),file:t,limitName:gt(e),line:e.getStartLineNumber()}},ya=(e,t)=>N(e,t,Ea),$a=new Set(["findFirst","findFirstOrThrow","findMany","get"]),va=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||!$a.has(t.getName()))return;const s=t.getExpression();if(R(s)){const r=e.getArguments()[0];return r&&o.isStringLiteral(r)?r.getLiteralText():""}if(o.isPropertyAccessExpression(s)&&R(s.getExpression()))return s.getName()},ba=e=>{let t=e;for(;o.isCallExpression(t);){const s=t.getExpression();if(!o.isPropertyAccessExpression(s))return;if(s.getName()==="query"&&R(s.getExpression())){const r=t.getArguments()[0];return r&&o.isStringLiteral(r)?r.getLiteralText():""}t=s.getExpression()}},Na=e=>{let t=e;for(;o.isAwaitExpression(t)||o.isParenthesizedExpression(t)||o.isNonNullExpression(t)||o.isAsExpression(t);)t=t.getExpression();return t},It=(e,t=!1)=>{const s=Na(e);if(o.isIdentifier(s)){if(t)return;const r=ee(s);return r===void 0?void 0:It(r,!0)}if(o.isCallExpression(s))return va(s)??ba(s)},Sa=e=>{const t=e.getBody();if(!o.isBlock(t))return[t];const s=[];for(const r of e.getDescendantsOfKind(l.ReturnStatement)){const i=r.getFirstAncestor(a=>o.isArrowFunction(a)||o.isFunctionExpression(a)||o.isFunctionDeclaration(a)),n=r.getExpression();i===e&&n!==void 0&&s.push(n)}return s},Aa=(e,t)=>{if(!o.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!o.isCallExpression(s))return[];const r=M(s);if(r?.kind!=="query")return[];const i=ft(s);if(i===void 0)return[];const n=r.receiver!==void 0&&ws(r.receiver,"output"),a=r.receiver!==void 0&&mt(r.receiver,"use","mask"),c=new Set,u=[];for(const d of Sa(i)){const y=It(d);y===void 0||c.has(y)||(c.add(y),u.push({exportName:e.getName(),file:t,line:d.getStartLineNumber(),table:y,usesMask:a,usesOutput:n,visibility:r.visibility}))}return u},wa=(e,t)=>{const s=[];for(const r of h(t)){const i=e.getSourceFile(r)??e.addSourceFileAtPath(r),n=E(t,r);for(const a of i.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...Aa(c,n))}return s},Pa=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},Ia=(e,t)=>{if(!o.isVariableDeclaration(e))return[];const s=e.getInitializer(),r=s&&o.isCallExpression(s)?M(s):void 0;if(!r)return[];const i=[];for(const n of e.getDescendantsOfKind(l.CallExpression)){const a=pt(n);if(a===void 0)continue;const c=Pa($(a.options,"with"));c.length!==0&&i.push({exportName:e.getName(),file:t,line:n.getStartLineNumber(),parentTable:a.table,relations:c,visibility:r.visibility})}return i},Ta=(e,t)=>{const s=[];for(const r of h(t)){const i=e.getSourceFile(r)??e.addSourceFileAtPath(r),n=E(t,r);for(const a of i.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...Ia(c,n))}return s},X=e=>{if(o.isStringLiteral(e)||o.isNoSubstitutionTemplateLiteral(e))return e.getLiteralText();if(o.isBinaryExpression(e)&&e.getOperatorToken().getKind()===l.PlusToken){const t=X(e.getLeft()),s=X(e.getRight());return t!==void 0&&s!==void 0?t+s:void 0}},La=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&&X(t)!==void 0},ka=/(?:^|\/)__tests__\//u,Da=/\.(?:spec|test)$/u,Fa=e=>ka.test(e)||Da.test(e),Oa=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()}},Ca=(e,t,s)=>Xs(e)?!Fa(s)&&Zs(Oa(t)):!0,Ka=(e,t)=>{const s=[],r=[...e.getDescendantsOfKind(l.BinaryExpression),...e.getDescendantsOfKind(l.StringLiteral),...e.getDescendantsOfKind(l.NoSubstitutionTemplateLiteral)],i=new Set;for(const n of r){if(La(n))continue;const a=X(n);if(a===void 0)continue;const c=Qs(a);if(c===void 0||!Ca(c,n,t))continue;const u=n.getStartLineNumber(),d=`${String(u)}:${c}`;i.has(d)||(i.add(d),s.push({file:t,kind:c,line:u,preview:Js(a)}))}return s},Ra=(e,t)=>{const s=[];for(const r of h(t)){const i=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Ka(i,E(t,r)))}return s},Ma=(e,t)=>{if(!o.isVariableDeclaration(e))return[];const s=e.getInitializer(),r=s&&o.isCallExpression(s)?M(s):void 0;if(!r)return[];const i=[];for(const n of e.getDescendantsOfKind(l.CallExpression)){const a=pt(n);if(a===void 0)continue;const c=$(a.options,"includeDeleted");if(c===void 0)continue;const u=o.isTrueLiteral(c),d=!u&&I(c);!u&&!d||i.push({exportName:e.getName(),file:t,fromArgs:d,hardcodedTrue:u,line:n.getStartLineNumber(),table:a.table,visibility:r.visibility})}return i},ja=(e,t)=>{const s=[];for(const r of h(t)){const i=e.getSourceFile(r)??e.addSourceFileAtPath(r),n=E(t,r);for(const a of i.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...Ma(c,n))}return s},za=new Set(["query","unsafe"]),qa=e=>{if(!o.isPropertyAccessExpression(e)||!za.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"},Ba=e=>o.isBinaryExpression(e)||o.isTemplateExpression(e),Ua=e=>e.getFirstAncestorByKind(l.VariableDeclaration)?.getName()??"<module>",Va=(e,t)=>{if(!qa(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!Ba(s)))return{exportName:Ua(e),file:t,line:s.getStartLineNumber()}},Wa=(e,t)=>N(e,t,Va),_a=[["convex",["convex","@convex-dev/"]],["supabase",["@supabase/"]],["firebase",["firebase","@firebase/","firebase-admin"]]],Ga=e=>{for(const[t,s]of _a)for(const r of s)if(e===r||e.startsWith(r.endsWith("/")?r:`${r}/`))return t},Ha=(e,t)=>{const s=[];for(const r of h(t)){const i=e.getSourceFile(r)??e.addSourceFileAtPath(r);for(const n of i.getImportDeclarations()){const a=n.getModuleSpecifierValue(),c=Ga(a);c!==void 0&&s.push({file:E(t,r),line:n.getStartLineNumber(),moduleSpecifier:a,platform:c})}}return s},Qa=new Set(["createMultipartUpload","delete","download","generateUploadUrl","get","getMetadata","getPresignedUrl","getSignedUrl","getUrl","head","put","resumeMultipartUpload","store","upload"]),Ja=(e,t,s=[])=>{const r=new Map(s.map(i=>[`${i.filePath}:${i.exportName}`,i.visibility]));return te(e,t,{argIndex:0,matchReceiver:i=>i==="ctx.storage"||i.startsWith("ctx.storage."),methods:Qa,requireUnmodifiedReach:!0}).map(i=>{const n=r.get(`${i.file}:${i.exportName}`);return n===void 0?i:{...i,visibility:n}})},Xa=new Map([["generateUploadUrl",1],["getPresignedUrl",1],["getSignedUrl",1],["store",2],["upload",2]]),Za=e=>e&&o.isNumericLiteral(e)?Number(e.getText()):void 0,Ya=e=>{if(e===void 0)return{analyzable:!0,presentKeys:[]};if(!o.isObjectLiteralExpression(e))return{analyzable:!1,presentKeys:[]};const t=[];let s,r=!1;for(const i of e.getProperties()){if(o.isSpreadAssignment(i)){r=!0;continue}if(o.isPropertyAssignment(i)){const n=i.getName();t.push(n),n==="expiresInSeconds"&&(s=Za(i.getInitializer()));continue}(o.isShorthandPropertyAssignment(i)||o.isMethodDeclaration(i))&&t.push(i.getName())}return{analyzable:!r,expiresInSeconds:s,presentKeys:t}},ec=e=>{if(!o.isPropertyAccessExpression(e))return;const t=e.getName(),s=Xa.get(t);if(s===void 0)return;const r=e.getExpression().getText();return r==="ctx.storage"||r.startsWith("ctx.storage.")?{method:t,optionsIndex:s}:void 0},tc=(e,t)=>{const s=ec(e.getExpression());if(s!==void 0)return{exportName:x(e),file:t,line:e.getStartLineNumber(),method:s.method,...Ya(e.getArguments()[s.optionsIndex])}},sc=(e,t)=>N(e,t,tc),rc=new Set(["RegisteredAction","RegisteredMutation","RegisteredQuery"]),ye=e=>{const t=e.getType(),s=t.getAliasSymbol()?.getName()??t.getSymbol()?.getName();return s!==void 0&&rc.has(s)?s:void 0},Tt=e=>{const t=e.getInitializer();return t===void 0?!1:o.isCallExpression(t)||o.isIdentifier(t)||o.isPropertyAccessExpression(t)},Lt={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."},nc={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."},$e=(e,t,s,r,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 ${r.toString()}) has type \`${s}\` but was not registered — ${i.cause}.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:t,filePath:e,line:r,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"}),ic=(e,t,s)=>{const r=[];for(const i of e.getVariableStatements().filter(n=>n.isExported()))for(const n of i.getDeclarations()){const a=n.getName();if(s.has(`${t}:${a}`)||!Tt(n))continue;const c=ye(n);c!==void 0&&r.push($e(t,a,c,n.getStartLineNumber(),Lt))}return r},oc=(e,t,s)=>{if(s.has(`${t}:default`))return[];const r=[];for(const i of e.getExportAssignments().filter(n=>!n.isExportEquals())){const n=ye(i.getExpression());n!==void 0&&r.push($e(t,"default",n,i.getStartLineNumber(),Lt))}return r},ac=(e,t,s)=>{const r=[];for(const i of e.getExportDeclarations().filter(n=>n.getModuleSpecifier()===void 0))for(const n of i.getNamedExports()){const a=n.getAliasNode()?.getText()??n.getName();if(s.has(`${t}:${a}`))continue;const c=n.getLocalTargetDeclarations().find(d=>o.isVariableDeclaration(d));if(c===void 0||!Tt(c))continue;const u=ye(c);u!==void 0&&r.push($e(t,a,u,n.getStartLineNumber(),nc))}return r},cc=(e,t,s)=>[...ic(e,t,s),...oc(e,t,s),...ac(e,t,s)],lc=(e,t,s)=>{const r=new Set(s.map(n=>`${n.filePath}:${n.exportName}`)),i=[];for(const n of h(t)){const a=e.getSourceFile(n);a!==void 0&&i.push(...cc(a,E(t,n),r))}return i.toSorted((n,a)=>n.cacheKey.localeCompare(a.cacheKey))},uc=new Set(["when","where"]),fe=new Set(["definePolicy","defineShape"]),dc=e=>{if(!o.isCallExpression(e))return;const t=e.getExpression();if(o.isPropertyAccessExpression(t)){const r=t.getName();return fe.has(r)?r:void 0}if(!o.isIdentifier(t))return;for(const r of t.getSymbol()?.getDeclarations()??[])if(o.isImportSpecifier(r)){const i=r.getNameNode().getText();return fe.has(i)?i:void 0}const s=t.getText();return fe.has(s)?s:void 0},gc=e=>o.isObjectLiteralExpression(e)&&e.getProperties().length===0,kt=e=>{if(e!==void 0){if(o.isReturnStatement(e)&&e.getExpression()===void 0||e.getKind()===l.UndefinedKeyword||e.getText()==="undefined")return"undefined";if(gc(e))return"empty-object";if(o.isParenthesizedExpression(e))return kt(e.getExpression())}},Dt=e=>e.getAncestors().find(t=>o.isArrowFunction(t)||o.isFunctionExpression(t)||o.isFunctionDeclaration(t)),Ft=e=>e.getDescendantsOfKind(l.ReturnStatement).filter(t=>Dt(t)===e),Ot=e=>e.getDescendantsOfKind(l.ConditionalExpression).filter(t=>Dt(t)===e),pc=e=>{const t=Ft(e);return t.length>1?!0:t.some(s=>s.getFirstAncestorByKind(l.IfStatement)!==void 0)||Ot(e).length>0},fc=e=>{const t=[],s=e.getBody();o.isBlock(s)||t.push(s);for(const r of Ft(e)){const i=o.isReturnStatement(r)?r.getExpression():void 0;t.push(i??r)}for(const r of Ot(e))t.push(r.getWhenTrue(),r.getWhenFalse());return t},mc=e=>{for(const t of e.getAncestors())if(o.isVariableDeclaration(t)){const s=t.getNameNode();if(o.isIdentifier(s))return s.getText()}return"<anonymous>"},hc=(e,t,s)=>{if(!o.isCallExpression(e))return[];const[r]=e.getArguments();if(!r||!o.isObjectLiteralExpression(r))return[];const i=[];for(const n of r.getProperties()){if(!o.isPropertyAssignment(n)||!uc.has(n.getName()))continue;const a=n.getInitializer();if(!(!a||!(o.isArrowFunction(a)||o.isFunctionExpression(a)))&&pc(a))for(const c of fc(a)){const u=kt(c);u!==void 0&&i.push({exportName:mc(e),file:s,form:u,key:n.getName(),line:c.getStartLineNumber(),owner:t})}}return i},xc=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(l.CallExpression)){const i=dc(r);i!==void 0&&s.push(...hc(r,i,t))}return s},Ec=(e,t)=>{const s=[];for(const r of h(t)){const i=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...xc(i,E(t,r)))}return s},yc=new Set(["query","upsert","upsertMany"]),$c=e=>{if(!o.isPropertyAccessExpression(e))return;const t=e.getName();if(yc.has(t))return e.getExpression().getText()==="ctx.vectors"?t:void 0},vc=(e,t)=>{const s=$c(e.getExpression());if(s===void 0)return;const r=e.getArguments()[1];if(!r)return;const i=$(r,"namespace");if(!(!i||!I(i)||D(i)))return{exportName:x(e),file:t,line:e.getStartLineNumber(),method:s}},bc=(e,t)=>N(e,t,vc),Nc=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"},Sc=e=>{const t=e.getArguments()[0];return t&&o.isStringLiteral(t)?t.getLiteralText():""},Ac=(e,t)=>{const s=[];for(const r of h(t)){const i=e.getSourceFile(r)??e.addSourceFileAtPath(r),n=E(t,r);for(const a of i.getDescendantsOfKind(l.CallExpression)){if(!Nc(a))continue;const c=gs(a);c!==""&&s.push({exportName:c,file:n,line:a.getStartLineNumber(),workflow:Sc(a)})}}return s},wc=".lunora-schema.json",S=(e,t)=>{b(e)&&dt(e,"utf8")===t||Bt(e,t,"utf8")},P=(e,t)=>{if(t===""){Ut(e,{force:!0});return}S(e,t)},Pc=e=>{const t=g(e,"package.json");if(b(t))try{const s=JSON.parse(dt(t,"utf8"));return typeof s.version=="string"&&s.version!==""?s.version:void 0}catch{return}},Ic=()=>{const e=process.env.LUNORA_CODEGEN_TIMING;return e!==void 0&&e!==""},Tc=e=>{let t=b(e)?e:le(e);for(;t&&t!==le(t);){const s=g(t,"tsconfig.json");if(b(s))return s;t=le(t)}},lt=e=>e.replaceAll("\\","/"),Lc=(e,t,s)=>{if(s&&e.length>0){const n=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) (${n}), 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 r=new Map;for(const n of t.columns){const a=r.get(n.table)??[];a.push(n.column),r.set(n.table,a)}const i=t.columns.length>0;for(const n of e){if(n.table===void 0){if(i)throw new k("MASK_UNSUPPORTED",`defineShape "${n.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 "${n.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=r.get(n.table);if(a===void 0)continue;const c=a.map(u=>`"${u}"`).join(", ");throw new k("MASK_UNSUPPORTED",`defineShape "${n.exportName}" replicates table "${n.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})}},ut=(e,t,s)=>{const r=e.getSourceFile(t);if(r===void 0){e.createSourceFile(t,s,{overwrite:!0});return}r.getFullText()!==s&&r.replaceWithText(s)},kc=e=>{const t=Tc(e);return t?new Ge({skipAddingFilesFromTsConfig:!1,tsConfigFilePath:t,useInMemoryFileSystem:!1}):new Ge({skipAddingFilesFromTsConfig:!0,useInMemoryFileSystem:!1})},$l=(e,t)=>{const s=h(t),r=g(t,"schema.ts");b(r)&&s.push(r);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=>lt(c))),n=lt(t),a=`${n}/`;for(const c of e.getSourceFiles()){const u=c.getFilePath();(u===n||u.startsWith(a))&&!i.has(u)&&e.removeSourceFile(c)}for(const c of e.getSourceFiles()){const u=c.getFilePath();if(!(u===n||u.startsWith(a)||u.includes("/node_modules/")))try{c.refreshFromFileSystemSync()}catch{e.removeSourceFile(c)}}},vl=e=>{const t=Ic(),s=t?ue.now():0,r=g(e.projectRoot,e.lunoraDirectory??"lunora"),i=g(r,"schema.ts");if(!b(i))throw new k("INTERNAL",`schema.ts not found at ${i}`);const n=e.project??kc(r);ir(Is);const a=Hs(n,i,e.projectRoot),{agents:c,containers:u,dataModelContent:d,dependencies:y,env:w,featureUsage:p,hasBrowser:v,hasFlags:O,hasNotify:j,identity:z,platformGate:U,queues:T,serverContent:C,storageRulesMetadata:q,usesSandbox:se,useUmbrella:K,workflows:L}=Pr({lunoraDirectory:r,project:n,projectRoot:e.projectRoot,schema:a,target:e.target}),f=g(r,"_generated"),ve=g(f,"dataModel.ts"),be=g(f,"server.ts");ut(n,ve,d),ut(n,be,C);const F=Ps(n,r),Ne=Ds(n,r),Se=Ms(n,r),B=Ys(n,r),re=qs(n,r),ne=Ls(n,r,L,c),V=e.lint===!1?void 0:_t({adminRoutes:Cr(n,r),aiRawRuns:Mr(n,r),aiToolSideEffects:Hr(n,r),argumentDerivedFetches:Xr(n,r),argumentValidators:un(n,r),authApiCalls:Ts(n,r),authConfigs:$n(n,r),browserUrlAccesses:An(n,r),configCalls:Fn(n,r),containerKeyAccesses:Cn(n,r),containerOverrides:qn(n,r),containers:u,exportSinks:Wn(n,r),staleMigrationImports:Ha(n,r),failOpenGuards:Jn(n,r),flagSecurityDefaults:ei(n,r),geoIndexUsages:ri(n,r),httpActionGuards:ui(n,r),httpHeaderWrites:$i(n,r),identityClaimReads:Pi(n,r),imageDeliveryUrlAccesses:Ti(n,r),inserts:Fs(n,r),kvKeyAccesses:ki(n,r),mailRecipientAccesses:Ki(n,r),maskProcedures:Os(n,r),maskStrategies:Cs(n,r),mutatorWrites:Bi(n,r),nondeterministicCalls:Bs(n,r),normalizeIdAuthorizations:no(n,r),notifyCalls:Vs(n,r),notifyConfig:Us(n,r),ownerFieldWrites:po(n,r,F),unrestrictedWhereBranches:Ec(n,r),paymentWebhooks:Eo(n,r),privilegedDispatches:ko(n,r),procedureProtections:ma(n,r),queries:Ss(n,r),queues:T,r2sqlCalls:Ws(n,r),ratelimitKeySelectors:ya(n,r),rawRowReturns:wa(n,r),relationLoads:Ta(n,r),rlsProcedures:_s(n,r),schema:a,secretLiterals:Ra(n,r),shapes:B,softDeleteReads:ja(n,r),sqlInterpolations:Wa(n,r),storageKeyAccesses:Ja(n,r,F),storageUploads:sc(n,r),vectorNamespaceAccesses:bc(n,r),workflowCalls:Ac(n,r),workflows:L,wranglerVariables:e.wranglerVariables}),Ae=V===void 0?[]:[...Vt(V,{source:"static"}),...lc(n,r,F)],Ct=Gs(n,r),we=Ks(n,r);Lc(B,we,Rs(n,r));const Kt=O?ks(n,r):[],W=$r(p,{containerCount:u.length,cronCount:ne.length,dependencies:y,hasPaymentTables:yr(a.tables),queueCount:T.length,storageColumnCount:Object.keys(Xt(a)).length,storageRuleCount:q.rules.length,vectorIndexCount:a.vectorIndexes.length,workflowCount:L.length}),Pe=t?ue.now():0,Ie=Zt({agents:c,functions:F,httpRoutes:Ne,mutators:re,useUmbrella:K,workflows:L}),Te=Yt({agents:c,functions:F,migrations:Se,mutators:re,shapes:B,useUmbrella:K,usesSandbox:se}),ie=or(a,Se.map(m=>m.id)),Le=es({advisories:Ae,advisorProcedures:V?.procedureProtections??[],agents:c,containers:u,env:w,flagKeys:Kt,hasAccessFacade:p.access,hasAi:p.ai,hasAnalytics:p.analytics,hasBrowser:v,hasFlags:O,hasHyperdrive:p.hyperdrive,hasImages:p.images,hasKv:p.kv,hasNotify:j,hasPayments:p.payments,hasPipelines:p.pipelines,hasR2sql:p.r2sql,hasX402:p.x402,maskMetadata:we,mutators:re,queues:T,rlsMetadata:Ct,schema:a,schemaSnapshot:ie,shapes:B,storageRules:q,studioFeatures:W,useUmbrella:K,workflows:L}),ke=ts(B,y.has("@lunora/db"),K),De=ss(u,a.jurisdiction),Fe=rs(L),Oe=ns(c),Ce=is(T),Ke=os(ne),Re=as(a.vectorIndexes),_=cs(a,K),Me=ls(y.has("@lunora/seed")),G=e.apiSpec??"openapi",oe=G==="openapi"||G==="both",ae=G==="openrpc"||G==="both",je=er({emailAgents:c.filter(m=>m.onEmail===!0).map(m=>({bindingName:m.bindingName,exportName:m.exportName})),hasAccess:y.has("@lunora/cloudflare-access"),hasAi:p.ai,hasAnalytics:p.analytics,hasAuth:y.has("@lunora/auth"),hasBrowser:v,hasFramework:y.has("@lunora/astro")||y.has("@lunora/svelte")||y.has("@lunora/vue"),hasGlobal:a.tables.some(m=>m.shardMode==="global"&&m.globalBackend!=="hyperdrive"),hasHyperdrive:p.hyperdrive,hasHyperdriveGlobal:a.tables.some(m=>m.shardMode==="global"&&m.globalBackend==="hyperdrive"),hasImages:p.images,hasKv:W.kv,hasNotify:j,hasPayments:p.payments,hasR2sql:p.r2sql,hasQueue:T.some(m=>m.mode==="push"),hasScheduler:W.scheduler,hasStorage:W.storage,hasVectors:a.vectorIndexes.length>0,hasWorkflow:L.length>0,hasX402:p.x402,identity:z,jurisdiction:a.jurisdiction,useUmbrella:K,voiceAgents:c.filter(m=>m.voice===!0&&m.voiceBindingName!==void 0).map(m=>({bindingName:m.voiceBindingName,exportName:m.exportName})),wantsOpenApi:oe,wantsOpenRpc:ae}),ze=Pc(e.projectRoot),qe=tr({functions:F,httpRoutes:Ne,version:ze}),Be=rr({functions:F,version:ze}),Ue=`${JSON.stringify(qe,void 0,2)}
|
|
8
|
-
`,Ve=`${JSON.stringify(Be,void 0,2)}
|
|
9
|
-
`,We=sr(qe),_e=nr(Be),ce=g(r,wc),Rt=b(ce);if(e.dryRun||(b(f)||qt(f,{recursive:!0}),S(g(f,"app.ts"),je),S(ve,d),S(g(f,"api.ts"),Ie),S(be,C),S(g(f,"functions.ts"),Te),S(g(f,"shard.ts"),Le),S(g(f,"crons.ts"),Ke),S(g(f,"vectors.ts"),Re),S(g(f,"drizzle.global.ts"),_.global),S(g(f,"drizzle.shard.ts"),_.shard),P(g(f,"containers.ts"),De),P(g(f,"workflows.ts"),Fe),P(g(f,"agents.ts"),Oe),P(g(f,"queues.ts"),Ce),P(g(f,"seed.ts"),Me),P(g(f,"collections.ts"),ke),P(g(f,"openapi.json"),oe?Ue:""),P(g(f,"openapi.ts"),oe?We:""),P(g(f,"openrpc.json"),ae?Ve:""),P(g(f,"openrpc.ts"),ae?_e:""),(!Rt||e.updateSchemaBaseline===!0)&&S(ce,Wt(ie))),t){const m=ue.now(),Mt=Math.round(m-s),jt=Math.round(Pe-s),zt=Math.round(m-Pe);console.error(`@lunora/codegen: codegen took ${Mt.toString()}ms (discovery ${jt.toString()}ms, emit ${zt.toString()}ms)`)}return{advisories:Ae,advisorContext:V,agents:c,containers:u,cronTriggers:us(ne),generated:{agents:Oe,api:Ie,app:je,collections:ke,containers:De,crons:Ke,dataModel:d,drizzleGlobal:_.global,drizzleShard:_.shard,functions:Te,openApi:Ue,openApiModule:We,openRpc:Ve,openRpcModule:_e,queues:Ce,seed:Me,server:C,shard:Le,vectors:Re,workflows:Fe},outputDirectory:f,platformDiagnostics:U.diagnostics,queues:T,schemaSnapshot:ie,schemaSnapshotPath:ce,workflows:L}};export{wc as SCHEMA_SNAPSHOT_FILENAME,kc as createCodegenProject,Tc as findTsconfig,$l as refreshCodegenProject,vl as runCodegen};
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
const f=1;function v(e){const a={},t=Object.keys(e);t.sort();for(const s of t)a[s]=e[s];return a}const d=e=>`${JSON.stringify(e,void 0,2)}
|
|
2
|
-
`,g=e=>{const a=d(e),t=s=>{let i=s;for(let o=0;o<a.length;o+=1)i^=a.codePointAt(o)??0,i=Math.imul(i,16777619)>>>0;return i.toString(16).padStart(8,"0")};return`${t(2166136261)}${t(16777619)}`},r=e=>typeof e=="object"&&e!==null,l=e=>r(e)&&r(e.fields)&&r(e.indexes)&&r(e.relations)&&typeof e.shardMode=="string",$=e=>{if(e===void 0||e.trim()==="")return{status:"absent"};let a;try{a=JSON.parse(e)}catch(t){return{error:`baseline is not valid JSON: ${t instanceof Error?t.message:String(t)}`,status:"invalid"}}if(!r(a)||a.version!==1||!r(a.tables))return{error:`baseline is malformed or written by an incompatible version (expected version ${String(1)})`,status:"invalid"};for(const[t,s]of Object.entries(a.tables))if(!l(s))return{error:`baseline table "${t}" has an invalid structure`,status:"invalid"};return{snapshot:{jurisdiction:typeof a.jurisdiction=="string"?a.jurisdiction:void 0,migrationIds:Array.isArray(a.migrationIds)?a.migrationIds:[],tables:a.tables,version:1},status:"ok"}},c=(e,a)=>e.unique===a.unique&&e.fields.length===a.fields.length&&e.fields.every((t,s)=>t===a.fields[s]),u=(e,a,t,s)=>{const i=[];return t.kind!==s.kind&&i.push({severity:"breaking",summary:`field ${e}.${a} changed type: ${t.kind} → ${s.kind} — add a data migration to convert existing values`,table:e,scope:"table",type:"changedFieldKind"}),t.optional&&!s.optional?i.push({severity:"breaking",summary:`field ${e}.${a} became required — rows missing it would be invalid; add a data migration to backfill it`,table:e,scope:"table",type:"fieldOptionalToRequired"}):!t.optional&&s.optional&&i.push({scope:"table",severity:"safe",summary:`field ${e}.${a} became optional`,table:e,type:"fieldRequiredToOptional"}),i},p=(e,a,t)=>t.optional?{scope:"table",severity:"safe",summary:`added optional field ${e}.${a}`,table:e,type:"addedOptionalField"}:{severity:"breaking",summary:`added required field ${e}.${a} — existing rows have no value; add a data migration to backfill it`,table:e,scope:"table",type:"addedRequiredField"},b=(e,a,t,s)=>{for(const[i,o]of Object.entries(t.fields)){const n=a.fields[i];n===void 0?s.push(p(e,i,o)):s.push(...u(e,i,n,o))}for(const i of Object.keys(a.fields))t.fields[i]===void 0&&s.push({severity:"breaking",summary:`removed field ${e}.${i} — add a data migration if stored data must be cleaned up`,table:e,scope:"table",type:"removedField"})},m=(e,a,t,s)=>{for(const[i,o]of Object.entries(t.indexes)){const n=a.indexes[i];if(n===void 0){s.push({scope:"table",severity:"safe",summary:`added index ${i} on ${e}`,table:e,type:"addedIndex"});continue}c(n,o)||s.push({severity:"breaking",summary:`index ${i} on ${e} changed shape — a query may have relied on the old index`,table:e,scope:"table",type:"changedIndex"})}for(const i of Object.keys(a.indexes))t.indexes[i]===void 0&&s.push({severity:"breaking",summary:`removed index ${i} on ${e} — a query that used \`.withIndex("${i}")\` would break`,table:e,scope:"table",type:"removedIndex"})},h=(e,a,t,s)=>{for(const i of Object.keys(t.relations))a.relations[i]===void 0&&s.push({scope:"schema",severity:"safe",summary:`added relation ${e}.${i}`,table:e,type:"addedRelation"});for(const i of Object.keys(a.relations))t.relations[i]===void 0&&s.push({scope:"schema",severity:"breaking",summary:`removed relation ${e}.${i}`,table:e,type:"removedRelation"})},y=(e,a,t,s)=>{a.shardMode!==t.shardMode&&s.push({severity:"breaking",summary:`table ${e} changed shard mode: ${a.shardMode} → ${t.shardMode} — its physical storage moves; add a data migration / re-shard plan`,table:e,scope:"table",type:"changedShardMode"}),b(e,a,t,s),m(e,a,t,s),h(e,a,t,s)},k=(e,a)=>{const t=[],s=e?.tables??{};for(const[i,o]of Object.entries(a.tables)){const n=s[i];if(n===void 0){t.push({scope:"table",severity:"safe",summary:`added table ${i}`,table:i,type:"addedTable"});continue}y(i,n,o,t)}for(const i of Object.keys(s))a.tables[i]===void 0&&t.push({scope:"table",severity:"breaking",summary:`removed table ${i} — add a data migration if its data must be archived/cleaned up`,table:i,type:"removedTable"});if(e!==void 0&&e.jurisdiction!==a.jurisdiction){const i=e.jurisdiction??"(none)",o=a.jurisdiction??"(none)";t.push({scope:"schema",severity:"breaking",summary:`Durable Object jurisdiction changed from ${i} to ${o} — this re-homes every DO and strands all existing shard, scheduler, and session-DO data in the old region (no in-place migration; export then import to move it). Revert the change, or override the gate to proceed intentionally.`,type:"changedJurisdiction"})}return{changes:t}};export{f as SCHEMA_SNAPSHOT_VERSION,k as diffSchemaSnapshots,g as hashSchemaSnapshot,l as isValidTableSnapshot,$ as parseSnapshotJson,d as serializeSchemaSnapshot,v as sortKeys};
|