@lunora/codegen 1.0.0-alpha.113 → 1.0.0-alpha.115

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (23) hide show
  1. package/dist/index.mjs +1 -1
  2. package/dist/packem_shared/{GENERATED_HEADER-GSCh67g3.mjs → GENERATED_HEADER-hlnTcuPd.mjs} +1 -1
  3. package/dist/packem_shared/{MUTATORS_FILENAME-CRmTpN4y.mjs → MUTATORS_FILENAME-sGAt-yC1.mjs} +1 -1
  4. package/dist/packem_shared/{NOTIFY_FILENAME-BybR3Xbd.mjs → NOTIFY_FILENAME-CTZI61e3.mjs} +1 -1
  5. package/dist/packem_shared/{OPENRPC_VERSION-DB1PSt8W.mjs → OPENRPC_VERSION-DpRms_jN.mjs} +1 -1
  6. package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-CGCzlXbr.mjs +9 -0
  7. package/dist/packem_shared/{SHAPES_FILENAME-DxoIrQhA.mjs → SHAPES_FILENAME-DTp6VI6K.mjs} +1 -1
  8. package/dist/packem_shared/{buildOpenApiDocument-B2mW3f5a.mjs → buildOpenApiDocument-ClEtrbbS.mjs} +1 -1
  9. package/dist/packem_shared/{discoverFunctions-h8i51Mec.mjs → discoverFunctions-4eSpCR6m.mjs} +1 -1
  10. package/dist/packem_shared/{discoverHttpRoutes-MX6y-iVE.mjs → discoverHttpRoutes-DOirwCWw.mjs} +1 -1
  11. package/dist/packem_shared/{discoverMaskProcedures-DhcK-YMG.mjs → discoverMaskProcedures-D-09Qb8S.mjs} +1 -1
  12. package/dist/packem_shared/{discoverNondeterministicCalls-CjS2Mznw.mjs → discoverNondeterministicCalls-DhNToI6C.mjs} +1 -1
  13. package/dist/packem_shared/{discoverR2sqlCalls-DuTuaSMM.mjs → discoverR2sqlCalls-B6e4j4rD.mjs} +1 -1
  14. package/dist/packem_shared/{discoverRlsMetadata-BYVq6cVp.mjs → discoverRlsMetadata-Pw0_c1aS.mjs} +1 -1
  15. package/dist/packem_shared/discoverSchema-D_wHstA-.mjs +1 -0
  16. package/dist/packem_shared/{discoverStorageRulesMetadata-CKPFWHT5.mjs → discoverStorageRulesMetadata-DthHu3mC.mjs} +1 -1
  17. package/dist/packem_shared/{emit-Ba3NiOwK.mjs → emit-CV6JjAt9.mjs} +78 -64
  18. package/dist/packem_shared/{emitApp-DZlIvflD.mjs → emitApp-BBcZ_fPU.mjs} +55 -31
  19. package/dist/packem_shared/parse-validator-C5ycrhR3.mjs +1 -0
  20. package/package.json +7 -7
  21. package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-BYsNQnIS.mjs +0 -9
  22. package/dist/packem_shared/discoverSchema-BtlNz9b_.mjs +0 -1
  23. package/dist/packem_shared/parse-validator-DtALyvid.mjs +0 -1
@@ -1,4 +1,4 @@
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,C=e=>k(e)?['import { dispatchAgentEmail } from "@lunora/agent/inbound";']:[],L=e=>k(e)?['import * as lunoraAgentDefinitions from "../agents.js";']:[],T=e=>{const{hasAccess:t,hasAuth:r,hasFramework:a,hasGlobal:n,hasHyperdriveGlobal:o,hasKv: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";']:[],...C(e),`import type { ${[...m].toSorted((w,y)=>w.localeCompare(y)).join(", ")} } from "${i}";`,`import { ${f} } from "${i}";`,"",...A(e.identity),...L(e),...n||o?['import schema from "../schema.js";']:[],...O(e.hasNotify),'import { LUNORA_CRONS } from "./crons.js";','import { LUNORA_FUNCTIONS } from "./functions.js";',...s?['import { createQueueCaptureSink, dispatchQueueBatch, shouldCaptureQueue } from "@lunora/queue";','import { LUNORA_QUEUE_REGISTRY } from "./queues.js";']:[],...p?['import { openApiSpec } from "./openapi.js";']:[],...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. */
1
+ import{A as S,G as D}from"./emit-CV6JjAt9.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,C=e=>k(e)?['import { dispatchAgentEmail } from "@lunora/agent/inbound";']:[],L=e=>k(e)?['import * as lunoraAgentDefinitions from "../agents.js";']:[],T=e=>{const{hasAccess:t,hasAuth:r,hasFramework:a,hasGlobal:n,hasHyperdriveGlobal:o,hasKv:l,hasQueue:s,hasScheduler:d,hasStorage:u,hasWorkflow:h,useUmbrella:c,wantsOpenApi:p,wantsOpenRpc:b}=e,i=c?"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, retryingExec } 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(l),...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";']:[],...C(e),`import type { ${[...m].toSorted((w,y)=>w.localeCompare(y)).join(", ")} } from "${i}";`,`import { ${f} } from "${i}";`,"",...A(e.identity),...L(e),...n||o?['import schema from "../schema.js";']:[],...O(e.hasNotify),'import { LUNORA_CRONS } from "./crons.js";','import { LUNORA_FUNCTIONS } from "./functions.js";',...s?['import { createQueueCaptureSink, dispatchQueueBatch, shouldCaptureQueue } from "@lunora/queue";','import { LUNORA_QUEUE_REGISTRY } from "./queues.js";']:[],...p?['import { openApiSpec } from "./openapi.js";']:[],...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>;
@@ -53,9 +53,9 @@ interface StorageDeclaration<Env> {
53
53
  this.storageDeclaration = declaration;
54
54
 
55
55
  return this;
56
- }`]:[],...N(e)],G=e=>{const t=[...e.hasGlobal?[` ...(this.globalDeclaration
56
+ }`]:[],...N(e)],B=e=>{const t=[...e.hasGlobal?[` ...(this.globalDeclaration
57
57
  ? {
58
- d1: (rawEnv: Record<string, unknown>, request?: { identity?: Record<string, unknown>; userId?: string | null }) => {
58
+ d1: (rawEnv: Record<string, unknown>, request?: { bookmark?: string; identity?: Record<string, unknown>; onBookmark?: (bookmark: string | undefined) => void; userId?: string | null }) => {
59
59
  const env = rawEnv as Env;
60
60
  const database = this.globalDeclaration?.d1(env);
61
61
 
@@ -71,7 +71,7 @@ interface StorageDeclaration<Env> {
71
71
  return createD1CtxDb({
72
72
  ...(crossShard ? { crossShardCounter: crossShard.crossShardCounter, crossShardReader: crossShard.crossShardReader } : {}),
73
73
  auth: { identity: request?.identity ?? null, userId: request?.userId ?? null },
74
- exec: buildExec(database),
74
+ exec: buildExec(database, request?.bookmark, request?.onBookmark),
75
75
  schema: schema as unknown as D1CtxDbOptions["schema"],
76
76
  });
77
77
  },
@@ -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
- };`]:[]],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?`
203
+ };`]:[]],G=e=>[" cronJobs: LUNORA_CRONS,"," functions: LUNORA_FUNCTIONS,",...e.identity?[` identity: lunoraIdentityContract.${e.identity.exportName},`]:[],...e.jurisdiction?[` jurisdiction: ${JSON.stringify(e.jurisdiction)},`]:[],...e.wantsOpenApi?[" openApiSpec,"]:[],...e.wantsOpenRpc?[" openRpcSpec,"]:[],...e.hasQueue?[" queue: (batch: unknown, queueEnv: unknown, _context: ExecutionContextLike): Promise<void> =>"," dispatchQueueBatch(batch as Parameters<typeof dispatchQueueBatch>[0], LUNORA_QUEUE_REGISTRY, {"," capture: shouldCaptureQueue(queueEnv as Record<string, unknown>)",` ? createQueueCaptureSink(queueEnv as Record<string, unknown>${e.jurisdiction?`, { jurisdiction: ${JSON.stringify(e.jurisdiction)} }`:""})`," : undefined,"," env: queueEnv as Record<string, unknown>,"," }),"]:[]," ...(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;
@@ -281,13 +281,35 @@ ${e.voiceAgents.map(t=>` ${JSON.stringify(t.exportName)}: (env as Rec
281
281
  };
282
282
  }
283
283
  `:"",H=e=>e?`
284
- /** Adapt the raw D1 binding to \`@lunora/d1\`'s \`D1Exec\` (reads via \`all\`, writes via \`run\`, and — when the binding exposes it — several writes in one round trip via \`batch\`). */
285
- const buildExec = (database: D1DatabaseLike): D1Exec => {
286
- const batchFn = database.batch;
287
-
288
- return {
284
+ /**
285
+ * Adapt the raw D1 binding to \`@lunora/d1\`'s \`D1Exec\` (reads via \`all\`, writes via \`run\`, and — when the binding exposes it — several writes in one round trip via \`batch\`).
286
+ *
287
+ * Opens a D1 Sessions API session pinned to \`bookmark\` (the caller's own
288
+ * last-known write, when supplied) so reads observe it — read-your-writes
289
+ * across replicas. \`onBookmark\`, when supplied, is invoked with the bookmark
290
+ * produced by each write so the caller (the generated DO) can record it via
291
+ * \`setOutboundBookmark\` and echo \`x-d1-bookmark\` on the response.
292
+ *
293
+ * Wrapped in \`retryingExec\` so D1's documented baseline of transient failures
294
+ * (storage-object resets, isolate memory evictions, dropped connections) does
295
+ * not surface on every \`.global()\` read. Only statements that are provably
296
+ * read-only retry; writes — including the \`UPDATE … RETURNING\` the store's
297
+ * optimistic-concurrency check issues through \`all\` — pass straight through,
298
+ * because a transient error never says whether the write applied.
299
+ */
300
+ const buildExec = (database: D1DatabaseLike, bookmark?: string, onBookmark?: (bookmark: string | undefined) => void): D1Exec => {
301
+ // Real D1 always exposes \`withSession\`; guarded the same way as \`batch\`
302
+ // below so a hand-rolled test double that omits it keeps working via
303
+ // \`prepare()\` straight on the raw binding — today's behaviour. With no
304
+ // inbound bookmark, \`"first-unconstrained"\` is the documented no-op
305
+ // equivalent (lowest latency, may read any replica) — see \`D1Client.withSession\`.
306
+ const session = typeof database.withSession === "function" ? database.withSession(bookmark ?? "first-unconstrained") : undefined;
307
+ const target = session ?? database;
308
+ const batchFn = target.batch;
309
+
310
+ return retryingExec({
289
311
  all: async (sql, parameters) => {
290
- const result = await database
312
+ const result = await target
291
313
  .prepare(sql)
292
314
  .bind(...parameters)
293
315
  .all<Record<string, unknown>>();
@@ -295,32 +317,34 @@ const buildExec = (database: D1DatabaseLike): D1Exec => {
295
317
  return result.results;
296
318
  },
297
319
  // D1's own \`batch\` runs the whole array as one atomic SQLite
298
- // transaction. Guarded because \`D1DatabaseLike.batch\` is optional in
299
- // the structural type (test doubles may omit it) — real D1 always has
300
- // it; a double without it still works through the store's sequential
301
- // fallback. Invoked via \`.call(database, ...)\` rather than
302
- // \`database.batch(...)\` directly so TS can narrow the captured
303
- // \`batchFn\` across the closure boundary (a property-access narrowing
304
- // like \`hasBatch = typeof database.batch === "function"\` does not
305
- // survive into a nested arrow function); \`.call\` still binds \`this\`
306
- // to \`database\`, so the real workerd \`D1Database\` doesn't throw
320
+ // transaction. Guarded because \`batch\` is optional in the structural
321
+ // type (test doubles may omit it) — real D1 always has it; a double
322
+ // without it still works through the store's sequential fallback.
323
+ // Invoked via \`.call(target, ...)\` rather than \`target.batch(...)\`
324
+ // directly so TS can narrow the captured \`batchFn\` across the closure
325
+ // boundary (a property-access narrowing like
326
+ // \`hasBatch = typeof target.batch === "function"\` does not survive
327
+ // into a nested arrow function); \`.call\` still binds \`this\` to
328
+ // \`target\`, so the real workerd \`D1Database\`/session doesn't throw
307
329
  // \`TypeError: Illegal invocation\` the way a detached
308
- // \`const fn = database.batch; fn(...)\` capture would.
330
+ // \`const fn = target.batch; fn(...)\` capture would.
309
331
  batch: batchFn
310
332
  ? async (statements) => {
311
333
  await batchFn.call(
312
- database,
313
- statements.map(({ params, sql }) => database.prepare(sql).bind(...params)),
334
+ target,
335
+ statements.map(({ params, sql }) => target.prepare(sql).bind(...params)),
314
336
  );
337
+ onBookmark?.(session?.getBookmark() ?? undefined);
315
338
  }
316
339
  : undefined,
317
340
  run: async (sql, parameters) => {
318
- await database
341
+ await target
319
342
  .prepare(sql)
320
343
  .bind(...parameters)
321
344
  .run();
345
+ onBookmark?.(session?.getBookmark() ?? undefined);
322
346
  },
323
- };
347
+ });
324
348
  };
325
349
 
326
350
  /** Introspect \`.global()\` (D1-backed) tables for the studio's global data browser. */
@@ -395,10 +419,10 @@ const buildGlobalImporter =
395
419
  // migrator). For production run the migrate command ahead of deploy.
396
420
  await ensureMigrated(createAuth({ ...this.authDeclaration.options(env), database: d1(env) as never }));
397
421
  };
398
- `:"",c=t?`
422
+ `:"",l=t?`
399
423
  await ensureAuth(env);`:"",s=t?"() => auth":"() => null",d=t?"getAuth: () => LunoraAuth | null":"_getAuth: () => null",u=e.hasFramework?` const buildWorker = (env: Env): LunoraWorker =>
400
- host ? withFrameworkWorker(host, (hostEnv) => this.buildWorkerOptions(hostEnv as Env, ${s})) : createWorker(this.buildWorkerOptions(env, ${s}));`:` const buildWorker = (env: Env): LunoraWorker => createWorker(this.buildWorkerOptions(env, ${s}));`,h=e.hasFramework?"host?: FrameworkHostHandler":"",l=e.emailAgents??[],p=l.length>0?` composed.email = dispatchAgentEmail([
401
- ${l.map(i=>` { agent: lunoraAgentDefinitions.${i.exportName}, binding: ${JSON.stringify(i.bindingName)} },`).join(`
424
+ host ? withFrameworkWorker(host, (hostEnv) => this.buildWorkerOptions(hostEnv as Env, ${s})) : createWorker(this.buildWorkerOptions(env, ${s}));`:` const buildWorker = (env: Env): LunoraWorker => createWorker(this.buildWorkerOptions(env, ${s}));`,h=e.hasFramework?"host?: FrameworkHostHandler":"",c=e.emailAgents??[],p=c.length>0?` composed.email = dispatchAgentEmail([
425
+ ${c.map(i=>` { agent: lunoraAgentDefinitions.${i.exportName}, binding: ${JSON.stringify(i.bindingName)} },`).join(`
402
426
  `)}
403
427
  ]);
404
428
 
@@ -443,7 +467,7 @@ ${b}
443
467
 
444
468
  /** Build the shard DO + compose the worker (standalone or framework-hosted), wrapping the lazy per-isolate singletons + auth init. */
445
469
  private assemble(${h}): ComposedApp {
446
- const ShardDO = createShardDO({${G(e)}});
470
+ const ShardDO = createShardDO({${B(e)}});
447
471
 
448
472
  // Per-isolate singletons: the worker (and auth instance) are expensive to
449
473
  // build, so the first request constructs them and every later request on
@@ -455,7 +479,7 @@ ${u}
455
479
  const composed: ComposedApp = {
456
480
  ShardDO,
457
481
  fetch: async (request: Request, rawEnv: unknown, context: ExecutionContextLike): Promise<Response> => {
458
- const env = rawEnv as Env;${c}
482
+ const env = rawEnv as Env;${l}
459
483
  worker ??= buildWorker(env);
460
484
 
461
485
  return worker.fetch(request, rawEnv, context);
@@ -489,7 +513,7 @@ ${$(e.hasStorage)}
489
513
  /** Fan the recorded declarations into the worker-side \`createWorker\` options. */
490
514
  private buildWorkerOptions(env: Env, ${d}): WorkerOptions {
491
515
  const options: WorkerOptions = {
492
- ${B(e).join(`
516
+ ${G(e).join(`
493
517
  `)}
494
518
  };
495
519
 
@@ -0,0 +1 @@
1
+ import{LunoraError as g}from"@lunora/errors";import{Node as i}from"ts-morph";import{diagnosticAt as p}from"./CodegenDiagnosticError-BUXlG3P-.mjs";let d;const R=e=>{d=e},y=/^[A-Za-z_$][\w$]*$/u,f=new Set(["$defaultFn","$onUpdateFn","$type","default","defaultNow","nullable","unique"]),m=(e,t)=>{const r={notNull:!0,...e.column};switch(t){case"$defaultFn":case"default":case"defaultNow":{r.hasDefault=!0;break}case"$onUpdateFn":{r.hasOnUpdate=!0;break}case"$type":break;case"nullable":{r.notNull=!1;break}case"unique":{r.unique=!0;break}}return{...e,column:r}},k=new Set(["any","bigint","boolean","bytes","date","geoPoint","null","number","string","timestamp"]),N=new Set(["check","meta"]),u=new Set,b=e=>{const t=e.getSymbol(),r=(t?.getAliasedSymbol()??t)?.getValueDeclaration();if(!(r===void 0||!i.isVariableDeclaration(r)))return r.getInitializer()},E="v",S=e=>{if(i.isIdentifier(e))return!0;let t=e;for(;i.isCallExpression(t);){const r=t.getExpression();if(!i.isPropertyAccessExpression(r))return!1;t=r.getExpression()}return i.isIdentifier(t)&&t.getText()===E},o=e=>{if(i.isIdentifier(e)&&!u.has(e)){const t=b(e);if(t!==void 0&&S(t)){u.add(e);try{return o(t)}finally{u.delete(e)}}}return i.isCallExpression(e)?L(e):{kind:"any",sourceText:e.getText()}},h=e=>{const t={};for(const r of e.getProperties()){const n=i.isShorthandPropertyAssignment(r);if(!n&&!i.isPropertyAssignment(r))continue;const s=r.getNameNode();if(i.isComputedPropertyName(s))continue;const a=n?r.getNameNode():r.getInitializer();if(!a)continue;const c=r.getName();if(!y.test(c))throw new g("INTERNAL",`@lunora/codegen: field name is not a valid JS identifier: ${JSON.stringify(c)}`);t[c]=o(a)}return t},l=(e,t)=>e&&i.isExpression(e)?o(e):t,A=e=>e===void 0?"undefined":i.isStringLiteral(e)||i.isNoSubstitutionTemplateLiteral(e)?JSON.stringify(e.getLiteralValue()):e.getText(),T=e=>{const t=e&&d?d(e):void 0;return t===void 0?{kind:"from"}:{kind:"from",tsType:t}},v=(e,t,r)=>{if(k.has(e))return{kind:e};const[n,s]=t;switch(e){case"array":return{inner:l(n,{kind:"any"}),kind:"array"};case"from":return T(n);case"id":{if(!n||!i.isStringLiteral(n))throw p(n??r,`v.id(...) target table must be a string literal — codegen resolves foreign-key targets statically. Got ${n?n.getText():"no argument"}.`);return{kind:"id",tableName:n.getLiteralText()}}case"literal":return{kind:"literal",literalValue:A(n)};case"object":return n&&i.isObjectLiteralExpression(n)?{kind:"object",shape:h(n)}:{kind:"object",shape:{}};case"optional":return{inner:l(n,{kind:"any"}),kind:"optional"};case"record":return{keyType:l(n,{kind:"string"}),kind:"record",valueType:l(s,{kind:"any"})};case"storage":return n&&i.isStringLiteral(n)?{bucket:n.getLiteralText(),kind:"storage"}:{kind:"storage"};case"union":return{kind:"union",members:t.filter(a=>i.isExpression(a)).map(a=>o(a))};default:throw new g("INTERNAL",`Unsupported validator kind: ${e}`)}},L=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t))return{kind:"any",sourceText:e.getText()};const r=t.getName(),n=e.getArguments();if(f.has(r)||N.has(r)){const s=t.getExpression(),a=i.isExpression(s)?o(s):{kind:"any"};return f.has(r)?m(a,r):r==="check"?{...a,hasRefinement:!0}:a}return v(r,n,e)};export{h as a,o as p,R as s};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/codegen",
3
- "version": "1.0.0-alpha.113",
3
+ "version": "1.0.0-alpha.115",
4
4
  "description": "Code generator for Lunora: emits _generated/{api,server,dataModel}.ts from your schema",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -46,13 +46,13 @@
46
46
  "access": "public"
47
47
  },
48
48
  "dependencies": {
49
- "@lunora/advisor": "1.0.0-alpha.82",
50
- "@lunora/agent": "1.0.0-alpha.57",
51
- "@lunora/container": "1.0.0-alpha.31",
49
+ "@lunora/advisor": "1.0.0-alpha.84",
50
+ "@lunora/agent": "1.0.0-alpha.59",
51
+ "@lunora/container": "1.0.0-alpha.32",
52
52
  "@lunora/errors": "1.0.0-alpha.22",
53
- "@lunora/platform": "1.0.0-alpha.12",
54
- "@lunora/queue": "1.0.0-alpha.28",
55
- "@lunora/scheduler": "1.0.0-alpha.32",
53
+ "@lunora/platform": "1.0.0-alpha.14",
54
+ "@lunora/queue": "1.0.0-alpha.30",
55
+ "@lunora/scheduler": "1.0.0-alpha.34",
56
56
  "@lunora/values": "1.0.0-alpha.27",
57
57
  "@lunora/workflow": "1.0.0-alpha.30",
58
58
  "jsonc-parser": "^3.3.1",
@@ -1,9 +0,0 @@
1
- import{existsSync as N,mkdirSync as Bt,readFileSync as dt,writeFileSync as $t,rmSync as qt}from"node:fs";import{join as f,dirname as le}from"node:path";import{performance as ue}from"node:perf_hooks";import{runAdvisor as jt}from"@lunora/advisor";import{LunoraError as R}from"@lunora/errors";import{SyntaxKind as l,Node as i,Project as He}from"ts-morph";import{serializeSchemaSnapshot as Wt}from"./SCHEMA_SNAPSHOT_VERSION-DIqnj_32.mjs";import{toAdvisorContext as Vt}from"./formatAdvisories-BjTV22uR.mjs";import{discoverAgents as Ht}from"./AGENTS_FILENAME-CPHo8Se5.mjs";import{discoverContainers as Gt}from"./CONTAINERS_FILENAME-Bvn6LZP6.mjs";import{diagnosticAt as Z}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{b as J}from"./module-specifiers-WF8iAydP.mjs";import{C as de,i as Yt,f as Xt,n as Qt,a as Zt,h as Jt,j as es,b as ts,c as ss,l as ns,e as rs,o as is,d as os,k as as,g as cs,p as ls,m as us}from"./emit-Ba3NiOwK.mjs";import{l as h,a as E,c as y,p as S,f as ft,i as ds,r as pt,e as fs}from"./discover-ast-D33zP-NZ.mjs";import ps from"./readPackageDependencies-C6h6FZuP.mjs";import{discoverQueues as gs}from"./QUEUES_FILENAME-BnGLtAIu.mjs";import{discoverSandboxUsage as ms}from"./discoverSandboxUsage-L0lV17de.mjs";import hs from"./discoverStorageRulesMetadata-CKPFWHT5.mjs";import{discoverWorkflows as xs}from"./WORKFLOWS_FILENAME-B8y51Frf.mjs";import{gatePlatformFeatures as Es,resolveCodegenTarget as vs}from"./DEFAULT_TARGET-CIH5PRk1.mjs";import{i as T,a as F,e as x,c as I,r as Ss,b as As,s as ee,f as Ns,g as ys,d as bs}from"./discover-queries-Dfj_0WJG.mjs";import{classifyProcedureCall as _,inlineHandler as Is,procedureHandler as gt,chainUsesWrappedCall as mt,isDatabaseAccessor as K,chainHasStep as Ps,discoverFunctions as ws,resolveStandardSchemaType as Ts}from"./discoverFunctions-h8i51Mec.mjs";import Cs from"./discoverAuthApiCalls-DUjcl0SB.mjs";import Os from"./discoverCrons-BUJO2ipU.mjs";import{discoverFlagKeys as Rs}from"./FLAGS_FILENAME-DtBWyUKq.mjs";import Fs from"./discoverHttpRoutes-MX6y-iVE.mjs";import Ls from"./discoverInserts-YX8AmrzL.mjs";import Ds,{discoverMaskStrategies as ks,discoverMaskMetadata as Ms,discoverMaskHasNonLiteralPolicy as Ks}from"./discoverMaskProcedures-DhcK-YMG.mjs";import _s from"./discoverMigrations-4Jjf5DJE.mjs";import{MUTATORS_FILENAME as zs,isDefineMutatorCallee as Us,discoverMutators as Bs}from"./MUTATORS_FILENAME-CRmTpN4y.mjs";import $s from"./discoverNondeterministicCalls-CjS2Mznw.mjs";import{discoverNotifyConfig as qs,discoverNotifyCalls as js}from"./NOTIFY_FILENAME-BybR3Xbd.mjs";import Ws from"./discoverR2sqlCalls-DuTuaSMM.mjs";import Vs,{discoverRlsMetadata as Hs}from"./discoverRlsMetadata-BYVq6cVp.mjs";import Gs from"./discoverSchema-BtlNz9b_.mjs";import{secretKindOf as Ys,redact as Xs,isHeuristicSecretKind as Qs,isSecretishName as Zs}from"./redact-Cy14LEnc.mjs";import{discoverShapes as Js}from"./SHAPES_FILENAME-DxoIrQhA.mjs";import{emitApp as en}from"./emitApp-DZlIvflD.mjs";import{buildOpenApiDocument as tn,emitOpenApiModule as sn}from"./buildOpenApiDocument-B2mW3f5a.mjs";import{buildOpenRpcDocument as nn,emitOpenRpcModule as rn}from"./OPENRPC_VERSION-DB1PSt8W.mjs";import{s as on}from"./parse-validator-DtALyvid.mjs";import{buildSchemaSnapshot as an}from"./SchemaSnapshotParseError-Dc1aZAph.mjs";const cn=e=>{const t=[],s=e.tables.filter(n=>n.shardMode==="global");return s.some(n=>n.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(n=>n.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},ln=(e,t)=>{if(t===void 0)return;const s=cn(e).filter(o=>!t.has(o.name));if(s.length===0)return;const n=s.map(o=>` - ${o.name} — ${o.reason}`).join(`
2
- `);throw new R("INTERNAL",`@lunora/codegen: this schema's generated code imports packages the project does not declare:
3
- ${n}
4
-
5
- Install them with your package manager, then re-run codegen.`)},un="env.ts",dn=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineEnv";for(const s of t.getDeclarations())if(i.isImportSpecifier(s))return J(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineEnv":!1;return!1},fn=e=>{const t=e.getSymbol();if(!t)return!1;for(const s of t.getDeclarations()){if(!i.isNamespaceImport(s))continue;const n=s.getFirstAncestorByKind(l.ImportDeclaration);return n!==void 0&&J(n.getModuleSpecifierValue())}return!1},pn=e=>{if(i.isIdentifier(e))return dn(e);if(i.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineEnv"&&i.isIdentifier(t)&&fn(t)}return!1},gn=e=>{const t=[];for(const s of e.getVariableDeclarations()){if(!s.isExported())continue;const n=s.getInitializer();if(n?.getKind()!==l.CallExpression||!pn(n.getExpression()))continue;const r=s.getNameNode();if(!i.isIdentifier(r))throw Z(r,"defineEnv exports must be plain named exports (no destructuring)");t.push({exportName:r.getText()})}return t},mn=(e,t)=>{const s=f(t,un);if(!N(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s),o=gn(n);if(o.length!==0){if(o.length>1)throw Z(n,`lunora/env.ts declares ${o.length.toString()} defineEnv() contracts (${o.map(r=>r.exportName).join(", ")}); exactly one is allowed`);return o[0]}},hn=e=>{const t=n=>i.isIdentifier(n)&&n.getText()==="ctx",s=new Set;for(const n of e.getDescendantsOfKind(l.PropertyAccessExpression))t(n.getExpression())&&s.add(n.getName());for(const n of e.getDescendantsOfKind(l.VariableDeclaration)){const o=n.getInitializer(),r=n.getNameNode();if(!(o===void 0||!t(o)||!i.isObjectBindingPattern(r)))for(const a of r.getElements()){const c=a.getPropertyNameNode()?.getText()??a.getName();c&&s.add(c)}}return s},xn=(e,t)=>{const s=Object.fromEntries(de.map(n=>[n.key,!1]));for(const n of h(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=new Set(o.getImportDeclarations().map(c=>c.getModuleSpecifierValue())),a=hn(o);for(const c of de)if(!s[c.key]){if(r.has(c.moduleSpecifier)){s[c.key]=!0;continue}c.contextProperty!==void 0&&a.has(c.contextProperty)&&(s[c.key]=!0)}if(de.every(c=>s[c.key]))break}return s},En=["providerSubscriptionId","state"],vn=["providerEventId","processedAt"],Ge=(e,t)=>t.every(s=>s in e.shape),Sn=e=>{const t=e.find(n=>n.name==="subscriptions"),s=e.find(n=>n.name==="events");return t!==void 0&&s!==void 0&&Ge(t,En)&&Ge(s,vn)},An=(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",Nn=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineIdentity";for(const s of t.getDeclarations())if(i.isImportSpecifier(s))return J(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineIdentity":!1;return!1},yn=e=>{const t=e.getSymbol();if(!t)return!1;for(const s of t.getDeclarations()){if(!i.isNamespaceImport(s))continue;const n=s.getFirstAncestorByKind(l.ImportDeclaration);return n!==void 0&&J(n.getModuleSpecifierValue())}return!1},bn=e=>{if(i.isIdentifier(e))return Nn(e);if(i.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineIdentity"&&i.isIdentifier(t)&&yn(t)}return!1},In=e=>{const t=[];for(const s of e.getVariableDeclarations()){if(!s.isExported())continue;const n=s.getInitializer();if(n?.getKind()!==l.CallExpression||!bn(n.getExpression()))continue;const r=s.getNameNode();if(!i.isIdentifier(r))throw Z(r,"defineIdentity exports must be plain named exports (no destructuring)");t.push({exportName:r.getText()})}return t},Pn=(e,t)=>{const s=f(t,ht);if(!N(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s),o=In(n);if(o.length!==0){if(o.length>1)throw Z(n,`lunora/identity.ts declares ${o.length.toString()} defineIdentity() contracts (${o.map(r=>r.exportName).join(", ")}); exactly one is allowed`);return o[0]}},wn=(e,t)=>{const s=new Map,n=new Map,o=new Map;for(const r of e)s.set(r.name,`workflow "${r.exportName}"`),n.set(r.bindingName,`workflow "${r.exportName}"`),o.set(r.className,`workflow "${r.exportName}"`);for(const r of t){const a=s.get(r.name);if(a!==void 0)throw new R("DUPLICATE_WORKFLOW_NAME",`Duplicate deployed name "${r.name}": produced by both ${a} and agent "${r.exportName}". Workflow and agent names share the same wrangler workflows[] array and must be unique together.`,{status:500});const c=n.get(r.bindingName);if(c!==void 0)throw new R("DUPLICATE_WORKFLOW_BINDING",`Duplicate binding "${r.bindingName}": produced by both ${c} and agent "${r.exportName}". Workflow and agent bindings share the same wrangler workflows[] array and must be unique together.`,{status:500});const u=o.get(r.className);if(u!==void 0)throw new R("DUPLICATE_WORKFLOW_CLASS",`Duplicate generated class "${r.className}": produced by both ${u} and agent "${r.exportName}". Workflow and agent export names must yield unique generated class names.`,{status:500})}},Tn=e=>{const{lunoraDirectory:t,project:s,projectRoot:n,schema:o}=e,r=Pn(s,t),a=mn(s,t),c=xs(s,t),u=gs(s,t),d=Ht(s,t);wn(c,d);const v=Gt(s,t),P=hs(s,t),p=Es(xn(s,t),vs(n,e.target)),A=p.usage,D=ms(s,t),z=A.browser||D.usesSandboxBrowser,U=ps(n),q=U??new Set,C=q.has("lunorash");ln(o,U);const k=N(f(t,"flags.ts")),B=N(f(t,"notify.ts"));return{agents:d,containers:v,dataModelContent:Xt(o),declaredDependencies:U,dependencies:q,env:a,featureUsage:A,hasBrowser:z,hasFlags:k,hasNotify:B,identity:r,platformGate:p,queues:u,serverContent:Yt({agents:d,containers:v,env:a,hasAccessFacade:A.access,hasAi:A.ai,hasAnalytics:A.analytics,hasBrowser:z,hasFlags:k,hasHyperdrive:A.hyperdrive,hasImages:A.images,hasKv:A.kv,hasNotify:B,hasPayments:A.payments,hasPipelines:A.pipelines,hasR2sql:A.r2sql,hasX402:A.x402,identity:r,queues:u,schema:o,storageRuleBuckets:P.rules.map(se=>se.bucket),useUmbrella:C,workflows:c}),storageRulesMetadata:P,usesSandbox:D.usesSandboxBrowser||D.usesSandboxContainer,useUmbrella:C,workflows:c}},xt=new Set(["delete","get","head","options","patch","post","put"]),Cn=new Set(["handler","stream"]),On=/\/(?:_|admin|internal|superuser|sudo|root|debug)/iu,Ye=new Set(["ADMIN_TOKEN","adminToken","assertAdmin","assertAuth","auth","Authorization","getSession","identity","isAdmin","requireAdmin","requireAuth","requireRole","verifyAdmin"]),Rn=e=>{if(!i.isCallExpression(e))return;const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!xt.has(t.getName()))return;const s=t.getExpression();if(!i.isIdentifier(s)||s.getText()!=="httpRoute")return;const n=e.getArguments()[0];if(!(!n||!i.isStringLiteral(n)))return{method:t.getName().toUpperCase(),path:n.getLiteralValue()}},Fn=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t))return;let s=t.getExpression();for(;i.isCallExpression(s);){const n=s.getExpression();if(!i.isPropertyAccessExpression(n)||xt.has(n.getName()))break;s=n.getExpression()}return Rn(s)},Ln=e=>{for(const t of e.getDescendantsOfKind(l.PropertyAccessExpression))if(Ye.has(t.getName()))return!0;for(const t of e.getDescendantsOfKind(l.CallExpression)){const s=t.getExpression();if(i.isIdentifier(s)&&Ye.has(s.getText()))return!0}return!1},Dn=(e,t)=>{const s=e.getInitializer();if(!s||!i.isCallExpression(s))return;const n=s.getExpression();if(!i.isPropertyAccessExpression(n)||!Cn.has(n.getName()))return;const o=Fn(s);if(!o||!On.test(o.path))return;const r=s.getArguments()[0],a=r!==void 0&&(i.isArrowFunction(r)||i.isFunctionExpression(r))&&Ln(r);return{exportName:e.getName(),file:t,method:o.method,path:o.path,usesGuard:a}},kn=(e,t)=>{const s=[];for(const n of e.getVariableStatements())if(n.isExported())for(const o of n.getDeclarations()){const r=Dn(o,t);r&&s.push(r)}return s},Mn=(e,t)=>{const s=[];for(const n of h(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...kn(o,E(t,n)))}return s},Kn=e=>!i.isPropertyAccessExpression(e)||e.getName()!=="run"?!1:e.getExpression().getText()==="ctx.ai",_n=(e,t)=>{if(!Kn(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!T(s)||F(s)))return{exportName:x(e),file:t,line:e.getStartLineNumber()}},zn=(e,t)=>y(e,t,_n),Un=new Set(["generateText","streamText"]),Bn=new Set(["messages","prompt","system"]),$n=[{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"]}],qn=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t))return;const s=t.getName(),n=t.getExpression().getText();for(const o of $n)if(o.methods.has(s)&&o.prefixes.some(r=>n===r||n.startsWith(`${r}.`)))return`${n}.${s}`},jn=e=>{for(const t of e.getDescendantsOfKind(l.CallExpression)){const s=qn(t);if(s!==void 0)return s}},Wn=e=>{const t=new Set,s=e.getFirstAncestor(r=>i.isArrowFunction(r)||i.isFunctionExpression(r)||i.isFunctionDeclaration(r)),[n]=s?.getParameters()??[],o=n?.getNameNode();if(o===void 0||!i.isObjectBindingPattern(o))return t;for(const r of o.getElements()){const a=r.getPropertyNameNode()?.getText()??r.getName(),c=r.getNameNode();if(a==="args"&&i.isObjectBindingPattern(c))for(const u of c.getElements())t.add(u.getName())}return t},Vn=e=>{if(Ss(e))return!0;const t=Wn(e);return t.size===0?!1:e.getDescendantsOfKind(l.Identifier).some(s=>t.has(s.getText()))},Hn=e=>{for(const t of e.getProperties()){if(!i.isPropertyAssignment(t)||!Bn.has(t.getName()))continue;const s=t.getInitializer();if(s!==void 0&&Vn(s))return!0}return!1},Gn=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression)){const o=I(n.getExpression());if(o===void 0||!Un.has(o))continue;const[r]=n.getArguments();if(r===void 0||!i.isObjectLiteralExpression(r))continue;let a;for(const c of r.getDescendantsOfKind(l.CallExpression))if(I(c.getExpression())==="tool"&&(a=jn(c),a!==void 0))break;a!==void 0&&s.push({exportName:x(n),file:t,line:n.getStartLineNumber(),method:o,sideEffect:a,userInputDerived:Hn(r)})}return s},Yn=(e,t)=>{const s=[];for(const n of h(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Gn(o,E(t,n)))}return s},Xn=e=>{if(!i.isPropertyAccessExpression(e)||e.getName()!=="fetch")return!1;const t=e.getExpression();return i.isIdentifier(t)&&t.getText()==="ctx"},Qn=(e,t)=>{if(!Xn(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!T(s)))return{exportName:x(e),file:t,line:e.getStartLineNumber()}},Zn=(e,t)=>y(e,t,Qn),Et=e=>e.getProperties().some(t=>i.isSpreadAssignment(t)),Jn=e=>{const t=e.getArguments()[0];if(!t||!i.isObjectLiteralExpression(t))return{objects:[],opaque:!0};const s=t.getProperty("args");if(!s)return{objects:[],opaque:!1};if(!i.isPropertyAssignment(s))return{objects:[],opaque:!0};const n=s.getInitializer();return!n||!i.isObjectLiteralExpression(n)?{objects:[],opaque:!0}:{objects:[n],opaque:Et(n)}},er=e=>{const t=[];let s=!1,n=e;for(;i.isCallExpression(n);){const o=n.getExpression();if(!i.isPropertyAccessExpression(o))break;if(o.getName()==="input"){const r=n.getArguments()[0];r&&i.isObjectLiteralExpression(r)?(t.push(r),s||=Et(r)):s=!0}n=o.getExpression()}return{objects:t,opaque:s}},vt=(e,t)=>t?er(t):Jn(e),tr=e=>e.flatMap(t=>t.getProperties().filter(s=>i.isPropertyAssignment(s)||i.isShorthandPropertyAssignment(s)).map(s=>s.getName())),sr=/\.check\(|\.meta\(|length|max/iu,nr=/\bv\.any\s*\(/u,rr=/\bv\.string\s*\(/u,ir=e=>nr.test(e),or=e=>rr.test(e)&&!sr.test(e),ar=e=>{const t=[],s=[];for(const n of e)for(const o of n.getProperties()){if(!i.isPropertyAssignment(o))continue;const r=o.getInitializer();if(!r)continue;const a=r.getText(),c=o.getName();ir(a)?t.push(c):or(a)&&s.push(c)}return{anyArgs:t,unboundedStringArgs:s}},cr=(e,t)=>{const s=e.getInitializer();if(!s||!i.isCallExpression(s))return;const n=_(s);if(n?.visibility!=="public")return;const{objects:o}=vt(s,n.receiver),{anyArgs:r,unboundedStringArgs:a}=ar(o);if(!(r.length===0&&a.length===0))return{anyArgs:r,exportName:e.getName(),file:t,line:s.getStartLineNumber(),unboundedStringArgs:a}},lr=(e,t)=>{const s=[];for(const n of e.getVariableStatements())if(n.isExported())for(const o of n.getDeclarations()){const r=cr(o,t);r&&s.push(r)}return s},ur=(e,t)=>{const s=[];for(const n of h(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...lr(o,E(t,n)))}return s},fe=e=>e?.getKind()===l.TrueKeyword,dr=e=>e?.getKind()===l.FalseKeyword,fr=e=>e!==void 0&&i.isNumericLiteral(e)&&e.getLiteralValue()===0,pr=new Set(["lunoraAuthAdapter","lunoraD1Adapter"]),gr=e=>!e||!i.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>i.isCallExpression(t)&&I(t.getExpression())==="scim"),mr=e=>e!==void 0&&i.isCallExpression(e)&&pr.has(I(e.getExpression())??""),hr=e=>!e||!i.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>i.isStringLiteral(t)&&t.getLiteralText()==="*"),xr=e=>{const t=S(e,"advanced"),s=S(e,"emailAndPassword"),n=S(e,"session");return{analyzable:!0,disableCsrfCheck:fe(S(t,"disableCSRFCheck")),emailPasswordEnabled:fe(S(s,"enabled")),requireEmailVerification:fe(S(s,"requireEmailVerification")),scimOnNonTransactionalAdapter:gr(S(e,"plugins"))&&mr(S(e,"database")),secureCookiesDisabled:dr(S(t,"useSecureCookies")),sessionFreshAgeZero:fr(S(n,"freshAge")),trustedOriginsWildcard:hr(S(e,"trustedOrigins"))}},Er=()=>({analyzable:!1,disableCsrfCheck:!1,emailPasswordEnabled:!1,requireEmailVerification:!1,scimOnNonTransactionalAdapter:!1,secureCookiesDisabled:!1,sessionFreshAgeZero:!1,trustedOriginsWildcard:!1}),vr=(e,t)=>{if(I(e.getExpression())!=="createAuth")return;const s=e.getArguments()[0],n=s!==void 0&&i.isObjectLiteralExpression(s)&&s.getProperties().some(r=>i.isSpreadAssignment(r)),o=s!==void 0&&i.isObjectLiteralExpression(s)&&!n?xr(s):Er();return{exportName:x(e),file:t,line:e.getStartLineNumber(),...o}},Sr=(e,t)=>y(e,t,vr),Ar=(e,t)=>{if(!i.isPropertyAccessExpression(e))return;const s=e.getName();if(t.methods.has(s))return t.matchReceiver(e.getExpression().getText())?s:void 0},Nr=(e,t,s)=>{const n=Ar(e.getExpression(),s);if(n===void 0)return;const o=e.getArguments()[s.argIndex];if(!(!o||!T(o)||F(o))&&!(s.requireUnmodifiedReach===!0&&!As(o)))return{exportName:x(e),file:t,line:e.getStartLineNumber(),method:n}},yr=(e,t,s)=>{const n=[];for(const o of e.getDescendantsOfKind(l.CallExpression)){const r=Nr(o,t,s);r&&n.push(r)}return n},te=(e,t,s)=>{const n=[];for(const o of h(t)){const r=e.getSourceFile(o)??e.addSourceFileAtPath(o);n.push(...yr(r,E(t,o),s))}return n},br=new Set(["content","pdf","scrape","screenshot"]),Ir=(e,t)=>te(e,t,{argIndex:0,matchReceiver:s=>s==="ctx.browser",methods:br}),Pr=new Set(["createBrowser","createInboundEmailHandler","createPayment"]),wr=new Set(["RateLimiter"]),Tr=new Set(["extend"]),St=e=>{const t=[],s=[];let n=!1;for(const o of e.getProperties()){if(i.isSpreadAssignment(o)){n=!0;continue}if(i.isPropertyAssignment(o)){const r=o.getName();t.push(r),o.getInitializer()?.getKind()===l.TrueKeyword&&s.push(r);continue}(i.isShorthandPropertyAssignment(o)||i.isMethodDeclaration(o))&&t.push(o.getName())}return{analyzable:!n,presentKeys:t,trueKeys:s}},Xe=e=>e&&i.isObjectLiteralExpression(e)?St(e):{analyzable:!1,presentKeys:[],trueKeys:[]},Cr=e=>{const t=e.getStatements(),[s]=t;if(t.length!==1||s===void 0||!i.isReturnStatement(s))return;const n=s.getExpression();return n!==void 0&&i.isObjectLiteralExpression(n)?n:void 0},Or=e=>{if(i.isObjectLiteralExpression(e))return e;if(i.isParenthesizedExpression(e)){const t=e.getExpression();return i.isObjectLiteralExpression(t)?t:void 0}return i.isBlock(e)?Cr(e):void 0},Rr=e=>{const t=e&&(i.isArrowFunction(e)||i.isFunctionExpression(e))?e:void 0,s=t&&Or(t.getBody());return s?St(s):{analyzable:!1,presentKeys:[],trueKeys:[]}},Fr=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression)){const o=I(n.getExpression());o!==void 0&&(Pr.has(o)?s.push({callee:o,file:t,line:n.getStartLineNumber(),...Xe(n.getArguments()[0])}):Tr.has(o)&&s.push({callee:o,file:t,line:n.getStartLineNumber(),...Rr(n.getArguments()[0])}))}for(const n of e.getDescendantsOfKind(l.NewExpression)){const o=I(n.getExpression());o===void 0||!wr.has(o)||s.push({callee:o,file:t,line:n.getStartLineNumber(),...Xe(n.getArguments()[0])})}return s},Lr=(e,t)=>{const s=[];for(const n of h(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Fr(o,E(t,n)))}return s},Qe="ctx.containers.",Dr=e=>{if(!e.startsWith(Qe))return!1;const t=e.slice(Qe.length);return t.length>0&&!t.includes(".")},kr=(e,t)=>te(e,t,{argIndex:0,matchReceiver:Dr,methods:new Set(["get"])}),Mr=new Set(["allow","deny","setAllowed"]),Kr=e=>{const t=e.getArguments()[0];if(!t||!i.isObjectLiteralExpression(t))return!1;const s=t.getProperty("enableInternet");return s!==void 0&&i.isPropertyAssignment(s)&&i.isTrueLiteral(s.getInitializerOrThrow())},_r=(e,t)=>{const s=e.getExpression();if(!(!i.isPropertyAccessExpression(s)||s.getName()!=="start"||!Kr(e)))return{detail:"enableInternet: true",exportName:x(e),file:t,kind:"enable_internet",line:e.getStartLineNumber()}},zr=(e,t)=>{const s=e.getExpression();if(!i.isPropertyAccessExpression(s)||!Mr.has(s.getName()))return;const n=s.getExpression();if(!(!i.isPropertyAccessExpression(n)||n.getName()!=="egress"))return{detail:s.getName(),exportName:x(e),file:t,kind:"egress_relaxation",line:e.getStartLineNumber()}},Ur=(e,t)=>_r(e,t)??zr(e,t),Br=(e,t)=>y(e,t,Ur),$r=new Set(["defineExportSink","r2Sink","webhookExportSink"]),qr=e=>{const t=e.getExpression();if(!i.isIdentifier(t))return;const s=t.getText();return $r.has(s)?s:void 0},jr=e=>{const t=[],s=[];for(const n of e.getProperties()){if(i.isSpreadAssignment(n))return{analyzable:!1,emptyKeys:[],presentKeys:[]};if(i.isPropertyAssignment(n)){const o=n.getName();t.push(o);const r=n.getInitializer();r&&i.isStringLiteral(r)&&r.getLiteralText()===""&&s.push(o);continue}(i.isShorthandPropertyAssignment(n)||i.isMethodDeclaration(n)||i.isGetAccessorDeclaration(n))&&t.push(n.getName())}return{analyzable:!0,emptyKeys:s,presentKeys:t}},Wr=(e,t)=>{const s=[];for(const n of h(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=E(t,n);for(const a of o.getDescendantsOfKind(l.CallExpression)){const c=qr(a);if(c===void 0)continue;const u=a.getArguments()[0],d=u&&i.isObjectLiteralExpression(u)?jr(u):{analyzable:!1,emptyKeys:[],presentKeys:[]};s.push({analyzable:d.analyzable,emptyKeys:d.emptyKeys,factory:c,file:r,line:a.getStartLineNumber(),presentKeys:d.presentKeys})}}return s},Vr=new Map([["dbRateLimit",2],["rateLimit",2],["verifyTurnstileMiddleware",0]]),Hr=new Set(["dbRateLimit","rateLimit"]),Gr=e=>{if(!e||!i.isObjectLiteralExpression(e))return!1;const t=e.getProperty("failOpen");return t!==void 0&&i.isPropertyAssignment(t)&&t.getInitializer()?.getKind()===l.TrueKeyword},Yr=(e,t)=>{const s=I(e.getExpression());if(s===void 0)return;const n=Vr.get(s);if(n!==void 0)return{callee:s,exportName:x(e),failOpen:Gr(e.getArguments()[n]),file:t,limitName:Hr.has(s)?ft(e):"",line:e.getStartLineNumber()}},Xr=(e,t)=>y(e,t,Yr),Qr=e=>{if(!i.isPropertyAccessExpression(e)||e.getName()!=="boolean")return!1;const t=e.getExpression();return i.isPropertyAccessExpression(t)&&t.getName()==="flags"&&ds(t.getExpression())},Zr=e=>{if(e?.getKind()===l.TrueKeyword)return!0;if(e?.getKind()===l.FalseKeyword)return!1},Jr=(e,t)=>{if(!Qr(e.getExpression()))return;const[s,n]=e.getArguments();if(!s||!(i.isStringLiteral(s)||i.isNoSubstitutionTemplateLiteral(s)))return;const o=s.getLiteralValue(),r=Zr(n);if(!(o.length===0||r===void 0))return{defaultValue:r,exportName:x(e),file:t,key:o,line:e.getStartLineNumber()}},ei=(e,t)=>y(e,t,Jr),ti=e=>{const t=e.getExpression();return i.isPropertyAccessExpression(t)&&t.getName()==="withGeoIndex"},si=e=>{const t=e.getArguments()[0];return t&&i.isStringLiteral(t)?t.getLiteralText():""},ni=(e,t)=>{const s=[];for(const n of h(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=E(t,n);for(const a of o.getDescendantsOfKind(l.CallExpression))ti(a)&&s.push({file:r,indexName:si(a),line:a.getStartLineNumber()})}return s},ri=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"]),Y=(e,t)=>e!==void 0&&i.isIdentifier(e)&&e.getText()===t,Ze=e=>e!==void 0&&(i.isArrowFunction(e)||i.isFunctionExpression(e))?e:void 0,Je=(e,t)=>{const s=e.getParameters()[0];if(s===void 0)return;const n=s.getNameNode();if(t)return i.isIdentifier(n)?n.getText():void 0;if(i.isObjectBindingPattern(n)){for(const o of n.getElements())if((o.getPropertyNameNode()?.getText()??o.getNameNode().getText())==="ctx"){const a=o.getNameNode();return i.isIdentifier(a)?a.getText():void 0}}},et=(e,t)=>{const s=e.getBody(),n=s.getDescendantsOfKind(l.CallExpression);i.isCallExpression(s)&&n.unshift(s);for(const o of n){const r=o.getExpression();if(!i.isPropertyAccessExpression(r))continue;const a=r.getName(),c=r.getExpression();if(oi.has(a)&&Y(c,t))return a;if(ai.has(a)&&i.isPropertyAccessExpression(c)&&c.getName()==="db"&&Y(c.getExpression(),t))return`db.${a}`}},tt=(e,t)=>{const s=e.getBody();for(const n of s.getDescendantsOfKind(l.PropertyAccessExpression))if(n.getName()==="auth"&&Y(n.getExpression(),t))return!0;for(const n of s.getDescendantsOfKind(l.VariableDeclaration)){const o=n.getNameNode();if(!(!i.isObjectBindingPattern(o)||!Y(n.getInitializer(),t))){for(const r of o.getElements())if((r.getPropertyNameNode()?.getText()??r.getNameNode().getText())==="auth")return!0}}return!1},ci=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!ii.has(t.getName()))return;let s=t.getExpression();for(;i.isCallExpression(s);){const n=s.getExpression();if(!i.isPropertyAccessExpression(n))return;const o=n.getName();if(ri.has(o)){const r=n.getExpression();return i.isIdentifier(r)&&r.getText()==="httpRoute"?o.toUpperCase():void 0}s=n.getExpression()}},li=(e,t)=>{const s=e.getExpression();if(i.isIdentifier(s)&&s.getText()==="httpAction"){const c=Ze(e.getArguments()[0]),u=c&&Je(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 n=ci(e);if(n===void 0)return;const o=Ze(e.getArguments()[0]),r=o&&Je(o,!1);if(!o||r===void 0)return;const a=et(o,r);return a===void 0?void 0:{exportName:x(e),file:t,kind:"httpRoute",line:e.getStartLineNumber(),method:n,readsAuth:tt(o,r),sideEffect:a}},ui=(e,t)=>y(e,t,li),di=new Set(["btoa","encodeURI","encodeURIComponent","isSafeHeaderValue","Number","parseFloat","parseInt"]),fi=new Set(["append","set"]),he=e=>i.isIdentifier(e)?e.getText():i.isPropertyAccessExpression(e)?e.getName():"",At=e=>e!==void 0&&(i.isStringLiteral(e)||i.isNoSubstitutionTemplateLiteral(e))?e.getLiteralText():"",st=(e,t)=>(i.isCallExpression(e)?[e,...e.getDescendantsOfKind(l.CallExpression)]:e.getDescendantsOfKind(l.CallExpression)).some(n=>di.has(he(n.getExpression()))&&ys(n,t)),pi=(e,t)=>{if(st(e,t))return!0;const s=ee(e);return s!==void 0&&st(s,t)},me=(e,t)=>Ns(e,t)&&!pi(e,t),gi=e=>{if(i.isPropertyAccessExpression(e)&&e.getName()==="headers")return!0;const t=ee(e);return t!==void 0&&i.isNewExpression(t)&&he(t.getExpression())==="Headers"},X=e=>{if(e===void 0)return;if(i.isObjectLiteralExpression(e))return e;const t=ee(e);return t!==void 0&&i.isObjectLiteralExpression(t)?t:void 0},xe=(e,t,s)=>{for(const n of e.getProperties())if(i.isPropertyAssignment(n)){const o=n.getInitializer();o!==void 0&&me(o,s.requestName)&&s.rows.push({exportName:s.exportName,file:s.relativePath,headerName:At(n.getNameNode()),line:o.getStartLineNumber(),via:t})}else if(i.isShorthandPropertyAssignment(n)){const o=n.getNameNode();me(o,s.requestName)&&s.rows.push({exportName:s.exportName,file:s.relativePath,headerName:n.getName(),line:o.getStartLineNumber(),via:t})}else if(i.isSpreadAssignment(n)){const o=X(n.getExpression());o!==void 0&&xe(o,t,s)}},Nt=(e,t)=>{const s=X(e);if(s===void 0)return;const n=s.getProperty("headers");if(n===void 0||!i.isPropertyAssignment(n))return;const o=X(n.getInitializer());o!==void 0&&xe(o,"response-init",t)},mi=(e,t)=>{const s=he(e.getExpression());if(s==="Response")Nt(e.getArguments()[1],t);else if(s==="Headers"){const n=X(e.getArguments()[0]);n!==void 0&&xe(n,"headers-ctor",t)}},hi=(e,t)=>{const s=e.getExpression();if(!i.isPropertyAccessExpression(s))return;const n=s.getName(),o=s.getExpression();if(n==="json"&&i.isIdentifier(o)&&o.getText()==="Response"){Nt(e.getArguments()[1],t);return}if(fi.has(n)&&gi(o)){const r=e.getArguments()[1];r!==void 0&&me(r,t.requestName)&&t.rows.push({exportName:t.exportName,file:t.relativePath,headerName:At(e.getArguments()[0]),line:r.getStartLineNumber(),via:n==="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(!i.isIdentifier(s)||s.getText()!=="httpAction")return[];const n=Is(e.getArguments()[0]);if(n===void 0)return[];const o=n.getParameters()[1];if(o===void 0)return[];const r=o.getNameNode();if(!i.isIdentifier(r))return[];const a=[];return xi(n,{exportName:x(e),relativePath:t,requestName:r.getText(),rows:a}),a},vi=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression))s.push(...Ei(n,t));return s},Si=(e,t)=>{const s=[];for(const n of h(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...vi(o,E(t,n)))}return s},Ai=new Set(["auth","context.auth","ctx.auth"]),Ni="userId",yi=e=>{const t=new Set;for(const s of e.getProperties()){if(i.isSpreadAssignment(s))return;(i.isPropertyAssignment(s)||i.isShorthandPropertyAssignment(s)||i.isMethodDeclaration(s))&&t.add(s.getName())}return t},bi=(e,t)=>{const s=f(t,ht);if(!N(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const o of n.getDescendantsOfKind(l.CallExpression)){if(I(o.getExpression())!=="defineIdentity")continue;const[r]=o.getArguments();return r&&i.isObjectLiteralExpression(r)?yi(r):void 0}},nt=e=>{if(!(e===void 0||!i.isPropertyAccessExpression(e)||e.getName()!=="identity"))return Ai.has(e.getExpression().getText())?e:void 0},Ii=e=>{if(i.isPropertyAccessExpression(e)&&nt(e.getExpression())!==void 0)return e.getName();if(i.isElementAccessExpression(e)&&nt(e.getExpression())!==void 0){const t=e.getArgumentExpression();return t&&i.isStringLiteral(t)?t.getLiteralValue():void 0}},Pi=(e,t,s)=>{const n=[];for(const o of e.getDescendants()){const r=Ii(o);r!==void 0&&n.push({declared:r===Ni||s.has(r),exportName:x(o),file:t,key:r,line:o.getStartLineNumber()})}return n},wi=(e,t)=>{const s=bi(e,t);if(s===void 0)return[];const n=[];for(const o of h(t)){const r=e.getSourceFile(o)??e.addSourceFileAtPath(o);n.push(...Pi(r,E(t,o),s))}return n},Ti=(e,t)=>{if(I(e.getExpression())!=="buildImageDeliveryUrl")return;const s=e.getArguments()[0];if(!s)return;const n=S(s,"key");if(!(!n||!T(n)||F(n)))return{exportName:x(e),file:t,line:e.getStartLineNumber()}},Ci=(e,t)=>y(e,t,Ti),Oi=new Set(["delete","get","getRaw","getWithMetadata","put"]),Ri=(e,t)=>te(e,t,{argIndex:0,matchReceiver:s=>s==="ctx.kv"||s.startsWith("ctx.kv."),methods:Oi}),Fi=new Set(["queue","send"]),rt=new Set(["bcc","cc","to"]),Li=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName();if(!Fi.has(t))return;const s=e.getExpression().getText();return s==="ctx.mail"||s==="ctx.email"?t:void 0},Di=e=>i.isObjectLiteralExpression(e)?e.getProperties().some(t=>{if(i.isShorthandPropertyAssignment(t)){const n=t.getNameNode();return rt.has(t.getName())&&T(n)&&!F(n)}if(!i.isPropertyAssignment(t)||!rt.has(t.getName()))return!1;const s=t.getInitializer();return s!==void 0&&T(s)&&!F(s)}):!1,ki=(e,t)=>{const s=Li(e.getExpression());if(s===void 0)return;const n=e.getArguments()[0];if(!(!n||!Di(n)))return{exportName:x(e),file:t,line:e.getStartLineNumber(),method:s}},Mi=(e,t)=>y(e,t,ki),Ki=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="replace")return!1;const s=t.getExpression();return i.isPropertyAccessExpression(s)?s.getName()==="db":i.isIdentifier(s)&&s.getText()==="db"},_i=e=>{const t=e.getArguments()[0];if(t===void 0||!i.isObjectLiteralExpression(t))return;const s=t.getProperty("server");if(s!==void 0)return i.isPropertyAssignment(s)?s.getInitializer():s},zi=e=>{if(!e.isExported())return;const t=e.getInitializer();if(t?.getKind()!==l.CallExpression)return;const s=t;return Us(s.getExpression())?s:void 0},Ui=e=>{const t=zi(e),s=t===void 0?void 0:_i(t);if(s===void 0)return[];const n=e.getNameNode(),o=i.isIdentifier(n)?n.getText():"";return s.getDescendantsOfKind(l.CallExpression).filter(r=>Ki(r)).map(r=>({exportName:o,file:"lunora/mutators.ts",line:r.getStartLineNumber()}))},Bi=e=>e.getVariableDeclarations().flatMap(t=>Ui(t)),$i=(e,t)=>{const s=f(t,zs);if(!N(s))return[];const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);return Bi(n)},qi=new Set(["delete","get","patch"]),ji=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"]),Vi=new Set([l.EqualsEqualsEqualsToken,l.EqualsEqualsToken,l.ExclamationEqualsEqualsToken,l.ExclamationEqualsToken]),Hi=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="normalizeId"||!K(t.getExpression()))return;const s=e.getArguments()[0];return s&&i.isStringLiteral(s)?s.getLiteralText():""},Gi=e=>{let t=e,s=t.getParent();for(;s!==void 0&&(i.isAsExpression(s)||i.isParenthesizedExpression(s)||i.isNonNullExpression(s));)t=s,s=t.getParent();if(s===void 0||!i.isVariableDeclaration(s))return;const n=s.getNameNode();return i.isIdentifier(n)?n.getText():void 0},Yi=(e,t)=>e.getDescendantsOfKind(l.Identifier).some(s=>s.getText()===t),Xi=e=>i.isThrowStatement(e)||i.isReturnStatement(e)||e.getDescendantsOfKind(l.ThrowStatement).length>0||e.getDescendantsOfKind(l.ReturnStatement).length>0,Qi=(e,t)=>e.getDescendantsOfKind(l.IfStatement).some(s=>Yi(s.getExpression(),t)&&Xi(s.getThenStatement())),Zi=(e,t)=>{for(const s of e.getDescendantsOfKind(l.CallExpression)){const n=s.getExpression();if(!i.isPropertyAccessExpression(n))continue;const o=n.getName();if(!qi.has(o))continue;const r=n.getExpression();if(!(K(r)||i.isPropertyAccessExpression(r)&&K(r.getExpression())))continue;const c=s.getArguments()[0];if(c!==void 0&&i.isIdentifier(c)&&c.getText()===t)return o}},Ji=e=>{let t=e;for(;i.isPropertyAccessExpression(t)||i.isElementAccessExpression(t)||i.isNonNullExpression(t)||i.isParenthesizedExpression(t)||i.isAsExpression(t)||i.isAwaitExpression(t);)t=t.getExpression();return i.isIdentifier(t)?t.getText():void 0},eo=e=>e.getDescendantsOfKind(l.CallExpression).some(t=>t.getArguments().some(s=>Ji(s)==="ctx")),to=e=>e.getDescendantsOfKind(l.BinaryExpression).some(t=>Vi.has(t.getOperatorToken().getKind())?i.isPropertyAccessExpression(t.getLeft())||i.isPropertyAccessExpression(t.getRight()):!1),so=e=>{for(const t of e.getDescendantsOfKind(l.Identifier))if(ji.has(t.getText()))return!0;for(const t of e.getDescendantsOfKind(l.PropertyAccessExpression)){const s=t.getExpression();if(i.isIdentifier(s)&&s.getText()==="ctx"&&Wi.has(t.getName()))return!0}return eo(e)||to(e)},no=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!i.isCallExpression(s))return[];const n=_(s);if(n?.kind!=="query"&&n?.kind!=="mutation")return[];const o=gt(s);if(o===void 0)return[];const r=n.receiver!==void 0&&mt(n.receiver,"use","rls"),a=so(o),c=new Set,u=[];for(const d of o.getDescendantsOfKind(l.CallExpression)){const v=Hi(d);if(v===void 0)continue;const P=Gi(d);if(P===void 0||c.has(P)||!Qi(o,P))continue;const p=Zi(o,P);p!==void 0&&(c.add(P),u.push({exportName:e.getName(),file:t,line:d.getStartLineNumber(),mentionsOwnership:a,sinkMethod:p,table:v,usesRls:r,visibility:n.visibility}))}return u},ro=(e,t)=>{const s=[];for(const n of h(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=E(t,n);for(const a of o.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...no(c,r))}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(!i.isPropertyAccessExpression(e))return;const t=e.getName();if(!oo.has(t))return;const s=e.getExpression();if(!i.isPropertyAccessExpression(s)||s.getName()!=="db")return;const n=s.getExpression();return i.isIdentifier(n)&&n.getText()==="ctx"?t:void 0},co=(e,t)=>{if(t!=="insertManyUnsafe")return i.isObjectLiteralExpression(e)?[e]:[];if(!i.isArrayLiteralExpression(e))return[];const s=[];for(const n of e.getElements())i.isObjectLiteralExpression(n)&&s.push(n);return s},lo=(e,t,s,n)=>{const o=[];for(const r of e.getProperties()){let a,c;i.isPropertyAssignment(r)?(a=r.getName(),c=r.getInitializer()):i.isShorthandPropertyAssignment(r)&&(a=r.getName(),c=r.getNameNode()),!(a===void 0||c===void 0||!io.has(a))&&T(c)&&!F(c)&&o.push({exportName:x(s),field:a,file:n,line:s.getStartLineNumber(),method:t})}return o},uo=(e,t)=>{const s=ao(e.getExpression());if(s===void 0)return[];const n=e.getArguments()[1];return n?co(n,s).flatMap(o=>lo(o,s,e,t)):[]},fo=(e,t,s)=>{const n=[];for(const o of e.getDescendantsOfKind(l.CallExpression))for(const r of uo(o,t)){const a=s(r.exportName);n.push(a===void 0?r:{...r,visibility:a})}return n},po=(e,t,s=[])=>{const n=[],o=new Map(s.map(r=>[`${r.filePath}:${r.exportName}`,r.visibility]));for(const r of h(t)){const a=e.getSourceFile(r)??e.addSourceFileAtPath(r),c=E(t,r);n.push(...fo(a,c,u=>o.get(`${c}:${u}`)))}return n},go=new Set(["createAutumnAdapter","createDodoPaymentsAdapter","createPolarAdapter","createStripeAdapter"]),mo=e=>e&&i.isNumericLiteral(e)?Number(e.getText()):void 0,ho=e=>{const t=e.getProperty("webhookToleranceSeconds");return t&&i.isPropertyAssignment(t)?mo(t.getInitializer()):void 0},xo=(e,t)=>{const s=I(e.getExpression());if(s===void 0||!go.has(s))return;const[n]=e.getArguments(),o=n&&i.isObjectLiteralExpression(n)?ho(n):void 0;return{callee:s,exportName:x(e),file:t,line:e.getStartLineNumber(),...o===void 0?{}:{toleranceSeconds:o}}},Eo=(e,t)=>y(e,t,xo),vo=new Set(["defineQueue","defineWorkflow"]),So=new Set(["run","runAction","runMutation","runQuery"]),Ao=new Set(["api","internal"]),No=e=>{const t=e.getExpression();return i.isIdentifier(t)?t.getText():void 0},yo=e=>{const t=e.getArguments()[0];if(!t||!i.isObjectLiteralExpression(t))return;const s=t.getProperty("handler");if(s===void 0||!i.isPropertyAssignment(s))return;const n=s.getInitializer();if(n&&(i.isArrowFunction(n)||i.isFunctionExpression(n)))return n},yt=(e,t)=>{const s=e.getParameters()[t]?.getNameNode();return s&&i.isIdentifier(s)?s.getText():void 0},bt=(e,t)=>e===t||e.startsWith(`${t}.`),It=e=>{const t=e.getDescendantsOfKind(l.PropertyAccessExpression);return i.isPropertyAccessExpression(e)&&t.push(e),t},it=e=>{const t=e.getParent();return i.isPropertyAccessExpression(t)&&t.getNameNode()===e||i.isPropertyAssignment(t)&&t.getNameNode()===e?!1:!(i.isBindingElement(t)&&t.getNameNode()===e)},Pt=e=>{const t=e.getDescendantsOfKind(l.Identifier).filter(s=>it(s));return i.isIdentifier(e)&&it(e)&&t.push(e),t},bo=e=>{if(!i.isVariableDeclaration(e))return[];const t=e.getNameNode();return i.isIdentifier(t)?[t.getText()]:t.getDescendantsOfKind(l.BindingElement).map(s=>s.getName())},Io=e=>{const t=yt(e,1);if(t===void 0)return[];const s=[`${t}.messages`];for(const n of e.getDescendantsOfKind(l.ForOfStatement)){if(n.getExpression().getText()!==`${t}.messages`)continue;const o=n.getInitializer(),r=i.isVariableDeclarationList(o)?o.getDeclarations()[0]?.getNameNode():void 0;r&&i.isIdentifier(r)&&s.push(`${r.getText()}.body`)}return s},Po=(e,t,s)=>{const n=t==="workflow"?[`${s}.params`]:Io(e),o=new Set,r=a=>It(a).some(c=>n.some(u=>bt(c.getText(),u)))?!0:Pt(a).some(c=>o.has(c.getText()));for(const a of e.getDescendantsOfKind(l.VariableDeclaration)){const c=a.getInitializer();if(c&&r(c))for(const u of bo(a))o.add(u)}return{names:o,prefixes:n}},wo=(e,t)=>It(e).some(s=>t.prefixes.some(n=>bt(s.getText(),n)))?!0:Pt(e).some(s=>t.names.has(s.getText())),To=e=>{if(e===void 0||!i.isPropertyAccessExpression(e))return;const t=[];let s=e;for(;i.isPropertyAccessExpression(s);)t.unshift(s.getName()),s=s.getExpression();const n=t.at(-1);if(!(n===void 0||!i.isIdentifier(s)||!Ao.has(s.getText())||t.length<2))return{exportName:n,file:t.slice(0,-1).join("/")}},Co=(e,t,s)=>{const n=yt(e,0);if(n===void 0)return[];const o=Po(e,t,n),r=[];for(const a of e.getDescendantsOfKind(l.CallExpression)){const c=a.getExpression();if(!i.isPropertyAccessExpression(c)||!So.has(c.getName())||c.getExpression().getText()!==n)continue;const u=a.getArguments()[1];if(!u||!wo(u,o))continue;const d=To(a.getArguments()[0]);d!==void 0&&r.push({dispatchKind:t,file:s,handlerExport:x(a),line:a.getStartLineNumber(),targetExport:d.exportName,targetFile:d.file})}return r},Oo=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression)){const o=No(n);if(o===void 0||!vo.has(o))continue;const r=yo(n);r!==void 0&&s.push(...Co(r,o==="defineQueue"?"queue":"workflow",t))}return s},Ro=(e,t)=>{const s=[];for(const n of h(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Oo(o,E(t,n)))}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"]),Fo=e=>e.replaceAll(/[-_]/gu," ").replaceAll(/([a-z0-9])([A-Z])/gu,"$1 $2").split(" ").filter(Boolean).map(t=>t.toLowerCase()),Lo=e=>{const s=Fo(e).at(-1);if(!s)return!1;const n=s.endsWith("s")?s.slice(0,-1):s;return at.has(s)||at.has(n)},Do=e=>{const t=e.replaceAll(/[^a-z0-9]/giu,"").toLowerCase();return t.endsWith("email")||t.endsWith("emailaddress")},ko=(e,t)=>{const{objects:s,opaque:n}=vt(e,t);return tr(s).some(o=>Do(o))?!0:n?void 0:!1},Ee=e=>{const t=e.getExpression();if(i.isIdentifier(t))return t.getText();if(i.isPropertyAccessExpression(t))return t.getName()},Mo=e=>{const t=e.getArguments()[0];return!t||!i.isObjectLiteralExpression(t)?{usesCaptcha:!1,usesRateLimit:!1}:{usesCaptcha:!!t.getProperty("captcha"),usesRateLimit:!!t.getProperty("rateLimit")}},Ko=e=>{if(i.isCallExpression(e))return e;if(!i.isIdentifier(e))return;const s=e.getSourceFile().getVariableDeclaration(e.getText())?.getInitializer();return s&&i.isCallExpression(s)?s:void 0},G={usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},_o=e=>{const t=Ko(e),s=t?Ee(t):void 0;if(t&&s==="protectPublic"){const n=Mo(t);return{...G,usesCaptcha:n.usesCaptcha,usesRateLimit:n.usesRateLimit}}return s!==void 0&&s in ot?{...G,[ot[s]]:!0}:G},zo=e=>{const t={...G};let s=e;for(;i.isCallExpression(s);){const n=s.getExpression();if(!i.isPropertyAccessExpression(n))break;const o=n.getName()==="use"?s.getArguments()[0]:void 0;if(o){const r=_o(o);t.usesCaptcha||=r.usesCaptcha,t.usesEmailGate||=r.usesEmailGate,t.usesMask||=r.usesMask,t.usesRateLimit||=r.usesRateLimit,t.usesRls||=r.usesRls}s=n.getExpression()}return t},Uo=new Set(["insert","insertMany","insertManyUnsafe","replace"]),Bo=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!Uo.has(t.getName()))return!1;const s=t.getExpression();if(!(i.isPropertyAccessExpression(s)?s.getName()==="db":i.isIdentifier(s)&&s.getText()==="db"))return!1;const o=e.getArguments()[0];return!o||!(i.isStringLiteral(o)||i.isNoSubstitutionTemplateLiteral(o))?!1:Lo(o.getLiteralText())},$o=new Set(["create","runAfter","runAt","send","sendBatch"]),qo=new Set(["queues","scheduler","workflows"]),jo=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!$o.has(t.getName()))return!1;let s=t.getExpression();for(;i.isCallExpression(s)||i.isElementAccessExpression(s)||i.isPropertyAccessExpression(s);){if(i.isPropertyAccessExpression(s)&&qo.has(s.getName())){const n=s.getExpression();if(i.isIdentifier(n)&&n.getText()==="ctx")return!0}s=s.getExpression()}return!1},Wo=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="insertManyUnsafe")return!1;const s=t.getExpression();return i.isPropertyAccessExpression(s)?s.getName()==="db":i.isIdentifier(s)&&s.getText()==="db"},wt=new Set(["generateObject","generateText","streamObject","streamText"]),Vo=e=>{const t=Ee(e);return t!==void 0&&wt.has(t)},Ho=e=>{const t=Ee(e);if(t===void 0||!wt.has(t))return!1;const s=e.getArguments()[0];return!s||!i.isObjectLiteralExpression(s)||s.getProperties().some(n=>i.isSpreadAssignment(n))?!1:!s.getProperty("maxOutputTokens")},Go=new Set(["log","span","trace"]),Yo=new Set(["ai"]),Xo=new Set(["email","mail"]),Qo=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 n=s.getExpression();return i.isIdentifier(n)&&n.getText()==="ctx"}),Zo=new Set([l.ArrowFunction,l.FunctionDeclaration,l.FunctionExpression,l.GetAccessor,l.MethodDeclaration,l.SetAccessor]),Jo=new Set(["every","filter","flatMap","forEach","map","some"]),ea=new Set(["all","allSettled","race"]),ta=e=>{const t=e.getParent();if(!t||!i.isCallExpression(t)||!t.getArguments().includes(e))return;const s=t.getExpression();if(!i.isPropertyAccessExpression(s))return;const n=s.getName();if(Jo.has(n))return t;const o=s.getExpression();if(i.isIdentifier(o)&&o.getText()==="Promise"&&ea.has(n))return t},sa=e=>{let t=e.getParent();for(;t;){if(i.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},na=e=>{let t=e;for(;;){const s=t.getParent();if(!i.isPropertyAccessExpression(s)||s.getExpression()!==t)return!1;if(s.getName()==="catch")return!0;if(s.getName()!=="then"&&s.getName()!=="finally")return!1;const n=s.getParent();if(!i.isCallExpression(n)||n.getExpression()!==s)return!1;t=n}},ra=e=>{let t=e;for(;;){const s=t.getParent();if(i.isPropertyAccessExpression(s)&&s.getExpression()===t){t=s;continue}return i.isCallExpression(s)&&s.getExpression()===t?s:void 0}},ia=e=>{let t=!1,s=!0;for(const n of e.getDescendantsOfKind(l.PropertyAccessExpression)){if(!Qo.has(n.getName()))continue;const o=n.getExpression();if(!i.isIdentifier(o)||o.getText()!=="ctx")continue;const r=ra(n);r&&(t=!0,!sa(r)&&!na(r)&&(s=!1))}return{handlesErrors:t&&s,reachesOutbound:t}},oa=e=>e.getDescendantsOfKind(l.ThrowStatement).some(t=>{const s=t.getExpression();if(!i.isNewExpression(s))return!1;const n=s.getExpression();return i.isIdentifier(n)&&n.getText()==="Error"}),ct="lunora-advisor-exempt",aa=/^[\s*/]+/u,ca=/[\w-]/u,la=e=>{const s=(e.getFirstAncestorByKind(l.VariableStatement)??e).getLeadingCommentRanges().map(n=>n.getText()).join(`
6
- `);for(const n of s.split(`
7
- `)){const o=n.replace(aa,"");if(!o.startsWith(ct))continue;const r=o.slice(ct.length);if(ca.test(r.charAt(0)))continue;const a=r.indexOf("--");return{exempt:!0,exemptReason:(a===-1?"":r.slice(a+2).split("*")[0]??"").trim()}}return{exempt:!1,exemptReason:""}},ua=e=>{const[t]=e.getArguments();if(t){if(i.isObjectLiteralExpression(t)){const s=t.getProperty("handler");return s?i.isPropertyAssignment(s)?s.getInitializer():i.isShorthandPropertyAssignment(s)?s.getNameNode():i.isMethodDeclaration(s)?s:void 0:void 0}return t}},da=(e,t)=>{const s=ua(t);if(!s)return;if(i.isArrowFunction(s)||i.isFunctionExpression(s)||i.isMethodDeclaration(s))return e;if(!i.isIdentifier(s))return;const n=s.getSourceFile(),o=s.getText(),r=n.getVariableDeclaration(o)?.getInitializer();return r&&(i.isArrowFunction(r)||i.isFunctionExpression(r))?r:n.getFunction(o)},fa=e=>{let t=!1,s=!1,n=!1,o=!1,r=!1;for(const u of e.getDescendantsOfKind(l.CallExpression))if(Bo(u)&&(r=!0),jo(u)&&(t=!0),Wo(u)&&(o=!0),Vo(u)&&(s=!0),Ho(u)&&(n=!0),r&&t&&o&&n)break;const{handlesErrors:a,reachesOutbound:c}=ia(e);return{callsMail:pe(e,Xo),emitsEvent:pe(e,Go),fanOut:t,handlesErrors:a,reachesOutbound:c,runsAiGeneration:s||pe(e,Yo),throwsBareError:oa(e),unboundedAiGeneration:n,usesInsertManyUnsafe:o,writesUserTable:r}},pa=(e,t)=>{const s=e.getInitializer();if(!s||!i.isCallExpression(s))return;const n=_(s);if(!n||n.kind!=="query"&&n.kind!=="mutation"&&n.kind!=="action")return;const o=n.receiver?zo(n.receiver):{usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},r=da(e,s);return{...r?fa(r):{},...la(e),...o,analyzableBody:r!==void 0,exportName:e.getName(),file:t,hasEmailArg:ko(s,n.receiver),kind:n.kind,visibility:n.visibility}},ga=(e,t)=>{const s=[];for(const n of e.getVariableStatements())if(n.isExported())for(const o of n.getDeclarations()){const r=pa(o,t);r&&s.push(r)}return s},ma=(e,t)=>{const s=[];for(const n of h(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...ga(o,E(t,n)))}return s},ha=new Set(["dbRateLimit","rateLimit"]),xa=e=>i.isArrowFunction(e)?e.getBody():e,Ea=(e,t)=>{const s=I(e.getExpression());if(s===void 0||!ha.has(s))return;const n=e.getArguments()[2];if(!n)return;const o=S(n,"key");if(!o)return;const r=xa(o);if(!(!T(r)||F(r)))return{callee:s,exportName:x(e),file:t,limitName:ft(e),line:e.getStartLineNumber()}},va=(e,t)=>y(e,t,Ea),Sa=new Set(["findFirst","findFirstOrThrow","findMany","get"]),Aa=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!Sa.has(t.getName()))return;const s=t.getExpression();if(K(s)){const n=e.getArguments()[0];return n&&i.isStringLiteral(n)?n.getLiteralText():""}if(i.isPropertyAccessExpression(s)&&K(s.getExpression()))return s.getName()},Na=e=>{let t=e;for(;i.isCallExpression(t);){const s=t.getExpression();if(!i.isPropertyAccessExpression(s))return;if(s.getName()==="query"&&K(s.getExpression())){const n=t.getArguments()[0];return n&&i.isStringLiteral(n)?n.getLiteralText():""}t=s.getExpression()}},ya=e=>{let t=e;for(;i.isAwaitExpression(t)||i.isParenthesizedExpression(t)||i.isNonNullExpression(t)||i.isAsExpression(t);)t=t.getExpression();return t},Tt=(e,t=!1)=>{const s=ya(e);if(i.isIdentifier(s)){if(t)return;const n=ee(s);return n===void 0?void 0:Tt(n,!0)}if(i.isCallExpression(s))return Aa(s)??Na(s)},ba=e=>{const t=e.getBody();if(!i.isBlock(t))return[t];const s=[];for(const n of e.getDescendantsOfKind(l.ReturnStatement)){const o=n.getFirstAncestor(a=>i.isArrowFunction(a)||i.isFunctionExpression(a)||i.isFunctionDeclaration(a)),r=n.getExpression();o===e&&r!==void 0&&s.push(r)}return s},Ia=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!i.isCallExpression(s))return[];const n=_(s);if(n?.kind!=="query")return[];const o=gt(s);if(o===void 0)return[];const r=n.receiver!==void 0&&Ps(n.receiver,"output"),a=n.receiver!==void 0&&mt(n.receiver,"use","mask"),c=new Set,u=[];for(const d of ba(o)){const v=Tt(d);v===void 0||c.has(v)||(c.add(v),u.push({exportName:e.getName(),file:t,line:d.getStartLineNumber(),table:v,usesMask:a,usesOutput:r,visibility:n.visibility}))}return u},Pa=(e,t)=>{const s=[];for(const n of h(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=E(t,n);for(const a of o.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...Ia(c,r))}return s},wa=e=>{if(!e||!i.isObjectLiteralExpression(e))return[];const t=[];for(const s of e.getProperties())(i.isPropertyAssignment(s)||i.isShorthandPropertyAssignment(s)||i.isMethodDeclaration(s)||i.isGetAccessorDeclaration(s))&&t.push(s.getName());return t},Ta=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&i.isCallExpression(s)?_(s):void 0;if(!n)return[];const o=[];for(const r of e.getDescendantsOfKind(l.CallExpression)){const a=pt(r);if(a===void 0)continue;const c=wa(S(a.options,"with"));c.length!==0&&o.push({exportName:e.getName(),file:t,line:r.getStartLineNumber(),parentTable:a.table,relations:c,visibility:n.visibility})}return o},Ca=(e,t)=>{const s=[];for(const n of h(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=E(t,n);for(const a of o.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...Ta(c,r))}return s},Q=e=>{if(i.isStringLiteral(e)||i.isNoSubstitutionTemplateLiteral(e))return e.getLiteralText();if(i.isBinaryExpression(e)&&e.getOperatorToken().getKind()===l.PlusToken){const t=Q(e.getLeft()),s=Q(e.getRight());return t!==void 0&&s!==void 0?t+s:void 0}},Oa=e=>{let t=e,s=t.getParent();for(;s!==void 0&&i.isBinaryExpression(s)&&s.getOperatorToken().getKind()===l.PlusToken;)t=s,s=t.getParent();return t!==e&&Q(t)!==void 0},Ra=/(?:^|\/)__tests__\//u,Fa=/\.(?:spec|test)$/u,La=e=>Ra.test(e)||Fa.test(e),Da=e=>{const t=e.getParent();if(t!==void 0){if(i.isVariableDeclaration(t)||i.isPropertyAssignment(t)||i.isPropertySignature(t))return t.getName();if(i.isBinaryExpression(t)&&t.getOperatorToken().getKind()===l.EqualsToken)return t.getLeft().getText()}},ka=(e,t,s)=>Qs(e)?!La(s)&&Zs(Da(t)):!0,Ma=(e,t)=>{const s=[],n=[...e.getDescendantsOfKind(l.BinaryExpression),...e.getDescendantsOfKind(l.StringLiteral),...e.getDescendantsOfKind(l.NoSubstitutionTemplateLiteral)],o=new Set;for(const r of n){if(Oa(r))continue;const a=Q(r);if(a===void 0)continue;const c=Ys(a);if(c===void 0||!ka(c,r,t))continue;const u=r.getStartLineNumber(),d=`${String(u)}:${c}`;o.has(d)||(o.add(d),s.push({file:t,kind:c,line:u,preview:Xs(a)}))}return s},Ka=(e,t)=>{const s=[];for(const n of h(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Ma(o,E(t,n)))}return s},_a=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&i.isCallExpression(s)?_(s):void 0;if(!n)return[];const o=[];for(const r of e.getDescendantsOfKind(l.CallExpression)){const a=pt(r);if(a===void 0)continue;const c=S(a.options,"includeDeleted");if(c===void 0)continue;const u=i.isTrueLiteral(c),d=!u&&T(c);!u&&!d||o.push({exportName:e.getName(),file:t,fromArgs:d,hardcodedTrue:u,line:r.getStartLineNumber(),table:a.table,visibility:n.visibility})}return o},za=(e,t)=>{const s=[];for(const n of h(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=E(t,n);for(const a of o.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(..._a(c,r))}return s},Ua=new Set(["query","unsafe"]),Ba=e=>{if(!i.isPropertyAccessExpression(e)||!Ua.has(e.getName()))return!1;const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="sql")return!1;const s=t.getExpression();return i.isIdentifier(s)&&s.getText()==="ctx"},$a=e=>i.isBinaryExpression(e)||i.isTemplateExpression(e),qa=e=>e.getFirstAncestorByKind(l.VariableDeclaration)?.getName()??"<module>",ja=(e,t)=>{if(!Ba(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!$a(s)))return{exportName:qa(e),file:t,line:s.getStartLineNumber()}},Wa=(e,t)=>y(e,t,ja),Va=[["convex",["convex","@convex-dev/"]],["supabase",["@supabase/"]],["firebase",["firebase","@firebase/","firebase-admin"]]],Ha=e=>{for(const[t,s]of Va)for(const n of s)if(e===n||e.startsWith(n.endsWith("/")?n:`${n}/`))return t},Ga=(e,t)=>{const s=[];for(const n of h(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const r of o.getImportDeclarations()){const a=r.getModuleSpecifierValue(),c=Ha(a);c!==void 0&&s.push({file:E(t,n),line:r.getStartLineNumber(),moduleSpecifier:a,platform:c})}}return s},Ya=new Set(["createMultipartUpload","delete","download","generateUploadUrl","get","getMetadata","getPresignedUrl","getSignedUrl","getUrl","head","put","resumeMultipartUpload","store","upload"]),Xa=(e,t,s=[])=>{const n=new Map(s.map(r=>[`${r.filePath}:${r.exportName}`,r.visibility]));return te(e,t,{argIndex:0,matchReceiver:r=>r==="ctx.storage"||r.startsWith("ctx.storage."),methods:Ya,requireUnmodifiedReach:!0}).map(r=>{const a=n.get(`${r.file}:${r.exportName}`);return a===void 0?r:{...r,visibility:a}})},Qa=new Map([["generateUploadUrl",1],["getPresignedUrl",1],["getSignedUrl",1],["store",2],["upload",2]]),Za=e=>e&&i.isNumericLiteral(e)?Number(e.getText()):void 0,Ja=e=>{if(e===void 0)return{analyzable:!0,presentKeys:[]};if(!i.isObjectLiteralExpression(e))return{analyzable:!1,presentKeys:[]};const t=[];let s,n=!1;for(const o of e.getProperties()){if(i.isSpreadAssignment(o)){n=!0;continue}if(i.isPropertyAssignment(o)){const r=o.getName();t.push(r),r==="expiresInSeconds"&&(s=Za(o.getInitializer()));continue}(i.isShorthandPropertyAssignment(o)||i.isMethodDeclaration(o))&&t.push(o.getName())}return{analyzable:!n,expiresInSeconds:s,presentKeys:t}},ec=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName(),s=Qa.get(t);if(s===void 0)return;const n=e.getExpression().getText();return n==="ctx.storage"||n.startsWith("ctx.storage.")?{method:t,optionsIndex:s}:void 0},tc=(e,t)=>{const s=ec(e.getExpression());if(s!==void 0)return{exportName:x(e),file:t,line:e.getStartLineNumber(),method:s.method,...Ja(e.getArguments()[s.optionsIndex])}},sc=(e,t)=>y(e,t,tc),nc=new Set(["RegisteredAction","RegisteredMutation","RegisteredQuery"]),ve=e=>{const t=e.getType(),s=t.getAliasSymbol()?.getName()??t.getSymbol()?.getName();return s!==void 0&&nc.has(s)?s:void 0},Ct=e=>{const t=e.getInitializer();return t===void 0?!1:i.isCallExpression(t)||i.isIdentifier(t)||i.isPropertyAccessExpression(t)},Ot={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."},rc={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."},Se=(e,t,s,n,o)=>({cacheKey:`procedure_not_registered:${e}:${t}`,categories:["SCHEMA"],description:"Codegen registers an export only when the declaration carries `export` and its initializer is literally a builder chain. A procedure written any other way exists at runtime but never reaches `_generated/api.ts`, so no caller can address it.",detail:`\`${t}\` in \`${e}\` (line ${n.toString()}) has type \`${s}\` but was not registered — ${o.cause}.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:t,filePath:e,line:n,typeName:s},name:"procedure_not_registered",remediation:`Assign the builder chain directly: \`export const ${t} = query.input({ … }).query(handler);\`. ${o.remediation}`,title:"Procedure exists at runtime but is missing from the generated API"}),ic=(e,t,s)=>{const n=[];for(const o of e.getVariableStatements().filter(r=>r.isExported()))for(const r of o.getDeclarations()){const a=r.getName();if(s.has(`${t}:${a}`)||!Ct(r))continue;const c=ve(r);c!==void 0&&n.push(Se(t,a,c,r.getStartLineNumber(),Ot))}return n},oc=(e,t,s)=>{if(s.has(`${t}:default`))return[];const n=[];for(const o of e.getExportAssignments().filter(r=>!r.isExportEquals())){const r=ve(o.getExpression());r!==void 0&&n.push(Se(t,"default",r,o.getStartLineNumber(),Ot))}return n},ac=(e,t,s)=>{const n=[];for(const o of e.getExportDeclarations().filter(r=>r.getModuleSpecifier()===void 0))for(const r of o.getNamedExports()){const a=r.getAliasNode()?.getText()??r.getName();if(s.has(`${t}:${a}`))continue;const c=r.getLocalTargetDeclarations().find(d=>i.isVariableDeclaration(d));if(c===void 0||!Ct(c))continue;const u=ve(c);u!==void 0&&n.push(Se(t,a,u,r.getStartLineNumber(),rc))}return n},cc=(e,t,s)=>[...ic(e,t,s),...oc(e,t,s),...ac(e,t,s)],lc=(e,t,s)=>{const n=new Set(s.map(r=>`${r.filePath}:${r.exportName}`)),o=[];for(const r of h(t)){const a=e.getSourceFile(r);a!==void 0&&o.push(...cc(a,E(t,r),n))}return o.toSorted((r,a)=>r.cacheKey.localeCompare(a.cacheKey))},uc=new Set(["when","where"]),ge=new Set(["definePolicy","defineShape"]),dc=e=>{if(!i.isCallExpression(e))return;const t=e.getExpression();if(i.isPropertyAccessExpression(t)){const n=t.getName();return ge.has(n)?n:void 0}if(!i.isIdentifier(t))return;for(const n of t.getSymbol()?.getDeclarations()??[])if(i.isImportSpecifier(n)){const o=n.getNameNode().getText();return ge.has(o)?o:void 0}const s=t.getText();return ge.has(s)?s:void 0},fc=e=>i.isObjectLiteralExpression(e)&&e.getProperties().length===0,Rt=e=>{if(e!==void 0){if(i.isReturnStatement(e)&&e.getExpression()===void 0||e.getKind()===l.UndefinedKeyword||e.getText()==="undefined")return"undefined";if(fc(e))return"empty-object";if(i.isParenthesizedExpression(e))return Rt(e.getExpression())}},Ft=e=>e.getAncestors().find(t=>i.isArrowFunction(t)||i.isFunctionExpression(t)||i.isFunctionDeclaration(t)),Lt=e=>e.getDescendantsOfKind(l.ReturnStatement).filter(t=>Ft(t)===e),Dt=e=>e.getDescendantsOfKind(l.ConditionalExpression).filter(t=>Ft(t)===e),pc=e=>{const t=Lt(e);return t.length>1?!0:t.some(s=>s.getFirstAncestorByKind(l.IfStatement)!==void 0)||Dt(e).length>0},gc=e=>{const t=[],s=e.getBody();i.isBlock(s)||t.push(s);for(const n of Lt(e)){const o=i.isReturnStatement(n)?n.getExpression():void 0;t.push(o??n)}for(const n of Dt(e))t.push(n.getWhenTrue(),n.getWhenFalse());return t},mc=e=>{for(const t of e.getAncestors())if(i.isVariableDeclaration(t)){const s=t.getNameNode();if(i.isIdentifier(s))return s.getText()}return"<anonymous>"},hc=(e,t,s)=>{if(!i.isCallExpression(e))return[];const[n]=e.getArguments();if(!n||!i.isObjectLiteralExpression(n))return[];const o=[];for(const r of n.getProperties()){if(!i.isPropertyAssignment(r)||!uc.has(r.getName()))continue;const a=r.getInitializer();if(!(!a||!(i.isArrowFunction(a)||i.isFunctionExpression(a)))&&pc(a))for(const c of gc(a)){const u=Rt(c);u!==void 0&&o.push({exportName:mc(e),file:s,form:u,key:r.getName(),line:c.getStartLineNumber(),owner:t})}}return o},xc=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression)){const o=dc(n);o!==void 0&&s.push(...hc(n,o,t))}return s},Ec=(e,t)=>{const s=[];for(const n of h(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...xc(o,E(t,n)))}return s},vc=new Set(["query","upsert","upsertMany"]),Sc=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName();if(vc.has(t))return e.getExpression().getText()==="ctx.vectors"?t:void 0},Ac=(e,t)=>{const s=Sc(e.getExpression());if(s===void 0)return;const n=e.getArguments()[1];if(!n)return;const o=S(n,"namespace");if(!(!o||!T(o)||F(o)))return{exportName:x(e),file:t,line:e.getStartLineNumber(),method:s}},Nc=(e,t)=>y(e,t,Ac),yc=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="get")return!1;const s=t.getExpression();return i.isPropertyAccessExpression(s)?s.getName()==="workflows":i.isIdentifier(s)&&s.getText()==="workflows"},bc=e=>{const t=e.getArguments()[0];return t&&i.isStringLiteral(t)?t.getLiteralText():""},Ic=(e,t)=>{const s=[];for(const n of h(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=E(t,n);for(const a of o.getDescendantsOfKind(l.CallExpression)){if(!yc(a))continue;const c=fs(a);c!==""&&s.push({exportName:c,file:r,line:a.getStartLineNumber(),workflow:bc(a)})}}return s},Pc=".lunora-schema.json",b=(e,t)=>{N(e)&&dt(e,"utf8")===t||$t(e,t,"utf8")},w=(e,t)=>{if(t===""){qt(e,{force:!0});return}b(e,t)},wc=e=>{const t=f(e,"package.json");if(N(t))try{const s=JSON.parse(dt(t,"utf8"));return typeof s.version=="string"&&s.version!==""?s.version:void 0}catch{return}},Tc=()=>{const e=process.env.LUNORA_CODEGEN_TIMING;return e!==void 0&&e!==""},Cc=e=>{let t=N(e)?e:le(e);for(;t&&t!==le(t);){const s=f(t,"tsconfig.json");if(N(s))return s;t=le(t)}},lt=e=>e.replaceAll("\\","/"),Oc=(e,t,s)=>{if(s&&e.length>0){const r=e.map(a=>`"${a.exportName}"`).join(", ");throw new R("MASK_UNSUPPORTED",`This project declares a \`mask(...)\` policy whose argument isn't a plain object literal (e.g. \`mask(sharedPolicies)\` referencing a hoisted variable), or contains a spread (\`...shared\`) or computed key (\`[name]:\`) codegen can't enumerate, so codegen can't tell which columns it masks. Because the project also declares replication shape(s) (${r}), codegen can't verify none of them replicate a table that policy masks — inline every table and column as literal keys so codegen can verify it, or remove the affected shape(s).`,{status:422})}const n=new Map;for(const r of t.columns){const a=n.get(r.table)??[];a.push(r.column),n.set(r.table,a)}const o=t.columns.length>0;for(const r of e){if(r.table===void 0){if(o)throw new R("MASK_UNSUPPORTED",`defineShape "${r.exportName}" has a non-literal \`table\` (a variable or expression, not a string literal), so codegen can't statically verify it doesn't replicate a table that masks a column. This project masks at least one column elsewhere, so the combination can't be proven safe — change "${r.exportName}"'s \`table\` to a plain string literal so codegen can verify it, or remove the mask(s) on the table it targets.`,{status:422});continue}const a=n.get(r.table);if(a===void 0)continue;const c=a.map(u=>`"${u}"`).join(", ");throw new R("MASK_UNSUPPORTED",`defineShape "${r.exportName}" replicates table "${r.table}", which masks column(s) ${c} on at least one procedure. A shape runs no procedure, so \`.use(mask(...))\` never applies to its replicated rows — remove the shape, unmask the table, or wait for shape-masking support.`,{status:422})}},ut=(e,t,s)=>{const n=e.getSourceFile(t);if(n===void 0){e.createSourceFile(t,s,{overwrite:!0});return}n.getFullText()!==s&&n.replaceWithText(s)},Rc=e=>{const t=Cc(e);return t?new He({skipAddingFilesFromTsConfig:!1,tsConfigFilePath:t,useInMemoryFileSystem:!1}):new He({skipAddingFilesFromTsConfig:!0,useInMemoryFileSystem:!1})},Sl=(e,t)=>{const s=h(t),n=f(t,"schema.ts");N(n)&&s.push(n);for(const c of s){const u=e.getSourceFile(c);u===void 0?e.addSourceFileAtPath(c):u.refreshFromFileSystemSync()}const o=new Set(s.map(c=>lt(c))),r=lt(t),a=`${r}/`;for(const c of e.getSourceFiles()){const u=c.getFilePath();(u===r||u.startsWith(a))&&!o.has(u)&&e.removeSourceFile(c)}for(const c of e.getSourceFiles()){const u=c.getFilePath();if(!(u===r||u.startsWith(a)||u.includes("/node_modules/")))try{c.refreshFromFileSystemSync()}catch{e.removeSourceFile(c)}}},Al=e=>{const t=Tc(),s=t?ue.now():0,n=f(e.projectRoot,e.lunoraDirectory??"lunora"),o=f(n,"schema.ts");if(!N(o))throw new R("INTERNAL",`schema.ts not found at ${o}`);const r=e.project??Rc(n);on(Ts);const a=Gs(r,o,e.projectRoot),{agents:c,containers:u,dataModelContent:d,dependencies:v,env:P,featureUsage:p,hasBrowser:A,hasFlags:D,hasNotify:z,identity:U,platformGate:q,queues:C,serverContent:k,storageRulesMetadata:B,usesSandbox:se,useUmbrella:M,workflows:O}=Tn({lunoraDirectory:n,project:r,projectRoot:e.projectRoot,schema:a,target:e.target}),g=f(n,"_generated"),Ae=f(g,"dataModel.ts"),Ne=f(g,"server.ts");ut(r,Ae,d),ut(r,Ne,k);const L=ws(r,n),ye=Fs(r,n),be=_s(r,n),$=Js(r,n),ne=Bs(r,n),re=Os(r,n,O,c),j=e.lint===!1?void 0:Vt({adminRoutes:Mn(r,n),aiRawRuns:zn(r,n),aiToolSideEffects:Yn(r,n),argumentDerivedFetches:Zn(r,n),argumentValidators:ur(r,n),authApiCalls:Cs(r,n),authConfigs:Sr(r,n),browserUrlAccesses:Ir(r,n),configCalls:Lr(r,n),containerKeyAccesses:kr(r,n),containerOverrides:Br(r,n),containers:u,exportSinks:Wr(r,n),staleMigrationImports:Ga(r,n),failOpenGuards:Xr(r,n),flagSecurityDefaults:ei(r,n),geoIndexUsages:ni(r,n),httpActionGuards:ui(r,n),httpHeaderWrites:Si(r,n),identityClaimReads:wi(r,n),imageDeliveryUrlAccesses:Ci(r,n),inserts:Ls(r,n),kvKeyAccesses:Ri(r,n),mailRecipientAccesses:Mi(r,n),maskProcedures:Ds(r,n),maskStrategies:ks(r,n),mutatorWrites:$i(r,n),nondeterministicCalls:$s(r,n),normalizeIdAuthorizations:ro(r,n),notifyCalls:js(r,n),notifyConfig:qs(r,n),ownerFieldWrites:po(r,n,L),unrestrictedWhereBranches:Ec(r,n),paymentWebhooks:Eo(r,n),privilegedDispatches:Ro(r,n),procedureProtections:ma(r,n),queries:bs(r,n),queues:C,r2sqlCalls:Ws(r,n),ratelimitKeySelectors:va(r,n),rawRowReturns:Pa(r,n),relationLoads:Ca(r,n),rlsProcedures:Vs(r,n),schema:a,secretLiterals:Ka(r,n),shapes:$,softDeleteReads:za(r,n),sqlInterpolations:Wa(r,n),storageKeyAccesses:Xa(r,n,L),storageUploads:sc(r,n),vectorNamespaceAccesses:Nc(r,n),workflowCalls:Ic(r,n),workflows:O,wranglerVariables:e.wranglerVariables}),Ie=j===void 0?[]:[...jt(j,{source:"static"}),...lc(r,n,L)],kt=Hs(r,n),Pe=Ms(r,n);Oc($,Pe,Ks(r,n));const Mt=D?Rs(r,n):[],W=An(p,{containerCount:u.length,cronCount:re.length,dependencies:v,hasPaymentTables:Sn(a.tables),queueCount:C.length,storageColumnCount:Object.keys(Qt(a)).length,storageRuleCount:B.rules.length,vectorIndexCount:a.vectorIndexes.length,workflowCount:O.length}),we=t?ue.now():0,Te=Zt({agents:c,functions:L,httpRoutes:ye,mutators:ne,useUmbrella:M,workflows:O}),Ce=Jt({agents:c,functions:L,migrations:be,mutators:ne,shapes:$,useUmbrella:M,usesSandbox:se}),ie=an(a,be.map(m=>m.id)),Oe=es({advisories:Ie,advisorProcedures:j?.procedureProtections??[],agents:c,containers:u,env:P,flagKeys:Mt,hasAccessFacade:p.access,hasAi:p.ai,hasAnalytics:p.analytics,hasBrowser:A,hasFlags:D,hasHyperdrive:p.hyperdrive,hasImages:p.images,hasKv:p.kv,hasNotify:z,hasPayments:p.payments,hasPipelines:p.pipelines,hasR2sql:p.r2sql,hasX402:p.x402,maskMetadata:Pe,mutators:ne,queues:C,rlsMetadata:kt,schema:a,schemaSnapshot:ie,shapes:$,storageRules:B,studioFeatures:W,useUmbrella:M,workflows:O}),Re=ts($,v.has("@lunora/db"),M),Fe=ss(u,a.jurisdiction),Le=ns(O),De=rs(c),ke=is(C),Me=os(re),Ke=as(a.vectorIndexes),V=cs(a,M),_e=ls(v.has("@lunora/seed")),H=e.apiSpec??"openapi",oe=H==="openapi"||H==="both",ae=H==="openrpc"||H==="both",ze=en({emailAgents:c.filter(m=>m.onEmail===!0).map(m=>({bindingName:m.bindingName,exportName:m.exportName})),hasAccess:v.has("@lunora/cloudflare-access"),hasAi:p.ai,hasAnalytics:p.analytics,hasAuth:v.has("@lunora/auth"),hasBrowser:A,hasFramework:v.has("@lunora/astro")||v.has("@lunora/svelte")||v.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:z,hasPayments:p.payments,hasR2sql:p.r2sql,hasQueue:C.some(m=>m.mode==="push"),hasScheduler:W.scheduler,hasStorage:W.storage,hasVectors:a.vectorIndexes.length>0,hasWorkflow:O.length>0,hasX402:p.x402,identity:U,jurisdiction:a.jurisdiction,useUmbrella:M,voiceAgents:c.filter(m=>m.voice===!0&&m.voiceBindingName!==void 0).map(m=>({bindingName:m.voiceBindingName,exportName:m.exportName})),wantsOpenApi:oe,wantsOpenRpc:ae}),Ue=wc(e.projectRoot),Be=tn({functions:L,httpRoutes:ye,version:Ue}),$e=nn({functions:L,version:Ue}),qe=`${JSON.stringify(Be,void 0,2)}
8
- `,je=`${JSON.stringify($e,void 0,2)}
9
- `,We=sn(Be),Ve=rn($e),ce=f(n,Pc),Kt=N(ce);if(e.dryRun||(N(g)||Bt(g,{recursive:!0}),b(f(g,"app.ts"),ze),b(Ae,d),b(f(g,"api.ts"),Te),b(Ne,k),b(f(g,"functions.ts"),Ce),b(f(g,"shard.ts"),Oe),b(f(g,"crons.ts"),Me),b(f(g,"vectors.ts"),Ke),b(f(g,"drizzle.global.ts"),V.global),b(f(g,"drizzle.shard.ts"),V.shard),w(f(g,"containers.ts"),Fe),w(f(g,"workflows.ts"),Le),w(f(g,"agents.ts"),De),w(f(g,"queues.ts"),ke),w(f(g,"seed.ts"),_e),w(f(g,"collections.ts"),Re),w(f(g,"openapi.json"),oe?qe:""),w(f(g,"openapi.ts"),oe?We:""),w(f(g,"openrpc.json"),ae?je:""),w(f(g,"openrpc.ts"),ae?Ve:""),(!Kt||e.updateSchemaBaseline===!0)&&b(ce,Wt(ie))),t){const m=ue.now(),_t=Math.round(m-s),zt=Math.round(we-s),Ut=Math.round(m-we);console.error(`@lunora/codegen: codegen took ${_t.toString()}ms (discovery ${zt.toString()}ms, emit ${Ut.toString()}ms)`)}return{advisories:Ie,advisorContext:j,agents:c,containers:u,cronTriggers:us(re),generated:{agents:De,api:Te,app:ze,collections:Re,containers:Fe,crons:Me,dataModel:d,drizzleGlobal:V.global,drizzleShard:V.shard,functions:Ce,openApi:qe,openApiModule:We,openRpc:je,openRpcModule:Ve,queues:ke,seed:_e,server:k,shard:Oe,vectors:Ke,workflows:Le},outputDirectory:g,platformDiagnostics:q.diagnostics,queues:C,schemaSnapshot:ie,schemaSnapshotPath:ce,workflows:O}};export{Pc as SCHEMA_SNAPSHOT_FILENAME,Rc as createCodegenProject,Cc as findTsconfig,Sl as refreshCodegenProject,Al as runCodegen};
@@ -1 +0,0 @@
1
- import{LunoraError as O}from"@lunora/errors";import{Node as i,SyntaxKind as A}from"ts-morph";import{diagnosticAt as f}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{a as _}from"./parse-validator-DtALyvid.mjs";import{createRequire as j}from"node:module";import{join as $}from"node:path";const z=e=>{switch(typeof e){case"bigint":return e.toString();case"boolean":case"number":return String(e);case"string":return JSON.stringify(e);default:return e===null?"null":void 0}},D=e=>({...e?.defaultValue!==void 0||e?.defaultFn!==void 0||e?.serverDefault!==void 0?{hasDefault:!0}:{},...e?.onUpdateFn===void 0?{}:{hasOnUpdate:!0},notNull:e?.notNull??!0,...e?.unique===!0?{unique:!0}:{}}),p=e=>{const n=e?._meta??{},t=e?.kind??"unknown",s={column:D(n.column),kind:t};switch(t){case"array":case"optional":{s.inner=p(n.inner);break}case"from":break;case"id":{s.tableName=n.tableName;break}case"literal":{s.literalValue=z(n.value);break}case"object":{const r=n.shape??{};s.shape=Object.fromEntries(Object.entries(r).map(([o,a])=>[o,p(a)]));break}case"record":{s.valueType=p(n.valueValidator),n.keyValidator!==void 0&&(s.keyType=p(n.keyValidator));break}case"storage":{typeof n.bucket=="string"&&(s.bucket=n.bucket);break}case"union":{const r=n.members??[];s.members=r.map(o=>p(o));break}}return s},C=e=>e?.kind==="global"?"global":e?.kind==="shardBy"&&typeof e.field=="string"?{field:e.field,kind:"shardBy"}:"root",M=(e,n)=>{const t=[];e.relationMap&&Object.keys(e.relationMap).length>0&&t.push("relations"),e.rankIndexes&&e.rankIndexes.length>0&&t.push("rank indexes"),e.vectorIndexes&&e.vectorIndexes.length>0&&t.push("vector indexes"),t.length>0&&console.warn(`@lunora/codegen: package schema-extension table "${n}" declares ${t.join(" + ")}, which are not yet introspected from a node_modules extension — they will be absent from the generated types.`)},F=(e,n)=>{const t=e.shape??{},s=(e.indexes??[]).map(r=>({fields:r.fields,name:r.name,...r.unique?{unique:!0}:{}}));return M(e,n),{...e.isExternallyManaged?{externallyManaged:!0}:{},geoIndexes:[],indexes:s,name:n,rankIndexes:[],relations:[],searchIndexes:(e.searchIndexes??[]).map(r=>({field:r.field,...r.filterFields?{filterFields:r.filterFields}:{},...r.language===void 0?{}:{language:r.language},...r.staged===void 0?{}:{staged:r.staged},...r.strategy===void 0?{}:{strategy:r.strategy},name:r.name})),shape:Object.fromEntries(Object.entries(t).map(([r,o])=>[r,p(o)])),shardMode:C(e.shardMode),vectorIndexes:[]}},R=e=>{const{key:n,tables:t}=e;if(typeof n!="string"||typeof t!="object"||t===null)return;const s=Object.entries(t).map(([a,l])=>F(l,a)),r=e.vectorIndexes??{},o=Object.entries(r??{}).map(([a,l])=>({...l.dimensions===void 0?{}:{dimensions:l.dimensions},...l.field===void 0?{}:{field:l.field},...l.metadata===void 0?{}:{metadata:l.metadata},...l.metric===void 0?{}:{metric:l.metric},name:a,table:l.table??""}));return{bareTables:s,bareVectorIndexes:o,key:n}},B=e=>{if(i.isIdentifier(e))return e.getText();if(i.isPropertyAccessExpression(e)){const n=e.getExpression();return i.isIdentifier(n)?n.getText():void 0}},V=e=>{const n=B(e);if(n===void 0)return;const t=i.isPropertyAccessExpression(e)?e.getName():void 0,s=t===void 0?[]:[t];for(const r of e.getSourceFile().getImportDeclarations()){const o=r.getModuleSpecifierValue();for(const a of r.getNamedImports())if((a.getAliasNode()?.getText()??a.getName())===n)return{importedName:a.getName(),moduleSpecifier:o,propertyPath:s};if(r.getDefaultImport()?.getText()===n)return{importedName:"default",moduleSpecifier:o,propertyPath:s};if(r.getNamespaceImport()?.getText()===n&&t!==void 0)return{importedName:t,moduleSpecifier:o,propertyPath:[]}}},q=(e,n)=>{let t=e[n.importedName];for(const s of n.propertyPath){if(typeof t!="object"||t===null)return;t=t[s]}return t},J=(e,n)=>{const t=V(e);if(t)try{const s=j($(n,"noop.cjs")),r=s.resolve(t.moduleSpecifier),o=s(r),a=q(o,t);return typeof a!="object"||a===null?void 0:R(a)}catch{return}},U=new Set(["cosine","dot-product","euclidean"]),K=new Set(["cascade","restrict","set null"]),I=new Set(["delete","get","insert","normalizeId","patch","query","replace","system"]),Z=/^[A-Za-z_$][\w$]*$/u,G=e=>e.replaceAll(/^["']|["']$/gu,""),Q=(e,n)=>{const t=G(e);if(I.has(t))throw f(n,`table name "${t}" is reserved — it collides with a \`ctx.db\` member (one of ${[...I].map(s=>`"${s}"`).join(", ")}). Rename the table.`);if(!Z.test(t))throw f(n,`table name ${JSON.stringify(t)} is not a valid JS identifier — table names are used in generated type names (Doc_<name>) and must match [A-Za-z_$][A-Za-z0-9_$]*. Rename the table.`)},g=(e,n)=>{const t=e.getProperty(n);if(t&&i.isPropertyAssignment(t))return t.getInitializer()},d=(e,n)=>{const t=g(e,n);if(t&&i.isStringLiteral(t))return t.getLiteralText()},m=(e,n)=>{const t=g(e,n);if(t&&i.isNumericLiteral(t))return Number(t.getLiteralText())},X=(e,n)=>{const t=g(e,n);if(t&&(i.isTrueLiteral(t)||i.isFalseLiteral(t)))return t.getLiteralValue()},x=(e,n)=>{const t=g(e,n);if(t&&i.isArrayLiteralExpression(t))return t.getElements().filter(s=>i.isStringLiteral(s)).map(s=>s.getLiteralText())},k=e=>e&&U.has(e)?e:void 0,H=e=>e&&K.has(e)?e:void 0,W=e=>{if(!i.isArrowFunction(e))return;let n=e.getBody();if(i.isParenthesizedExpression(n))n=n.getExpression();else if(i.isBlock(n)){const t=n.getStatements().find(s=>i.isReturnStatement(s));n=t&&i.isReturnStatement(t)?t.getExpression()??n:n}return i.isObjectLiteralExpression(n)?n:void 0},Y=e=>{if(!i.isPropertyAssignment(e))return;const n=e.getInitializer();if(!n||!i.isCallExpression(n))return;const t=n.getExpression();if(!i.isPropertyAccessExpression(t))return;const s=t.getName();if(s!=="one"&&s!=="many")return;const[r,o]=n.getArguments(),a=r&&i.isStringLiteral(r)?r.getLiteralText():"_unknown_";let l="_unknown_",c="_id",u;return o&&i.isObjectLiteralExpression(o)&&(l=d(o,"field")??l,c=d(o,"references")??c,u=s==="one"?H(d(o,"onDelete")):void 0),{field:l,kind:s,name:e.getName(),onDelete:u,references:c,table:a}},ee=e=>{const n=W(e);if(!n)return[];const t=[];for(const s of n.getProperties()){const r=Y(s);r&&t.push(r)}return t},b=e=>e&&i.isStringLiteral(e)?e.getLiteralText():"_unnamed_",te=(e,n,t)=>{if(!n.includes("."))return;const[s="",...r]=n.split("."),o=`${s}${r.map(a=>a.charAt(0).toUpperCase()+a.slice(1)).join("")}`;throw f(e,`index "${t}" indexes the nested path ${JSON.stringify(n)} — Lunora indexes only top-level columns. Denormalise the value into its own column (e.g. \`${o}\`), index that instead, and keep it in sync with a table \`.triggers()\` beforeInsert/beforeUpdate.`)},ne=e=>{if(!e||!i.isObjectLiteralExpression(e))return!1;const n=e.getProperty("unique");if(!n||!i.isPropertyAssignment(n))return!1;const t=n.getInitializer();if(t===void 0)return!1;if(!i.isTrueLiteral(t)&&!i.isFalseLiteral(t))throw f(t,`\`unique\` must be a literal \`true\` or \`false\`, got ${JSON.stringify(t.getText())}`);return i.isTrueLiteral(t)},re=e=>{const[n,t,s]=e,r=ne(s),o=b(n),a=t&&i.isArrayLiteralExpression(t)?t.getElements():[];for(const c of a)if(!i.isStringLiteral(c))throw f(c,`index "${o}" lists a non-literal field (${JSON.stringify(c.getText())}); codegen reads index fields statically, so every entry must be a string literal.`);const l=a.filter(c=>i.isStringLiteral(c));for(const c of l)te(c,c.getLiteralText(),o);return{fields:l.map(c=>c.getLiteralText()),name:o,unique:r}},se=e=>{const[n,t]=e;let s="_unknown_",r,o,a,l;return t&&i.isObjectLiteralExpression(t)&&(s=d(t,"field")??s,r=x(t,"filterFields"),o=d(t,"language"),a=X(t,"staged"),l=d(t,"strategy")),{field:s,filterFields:r,language:o,name:b(n),staged:a,strategy:l}},ie=e=>{const[n,t]=e;let s="_unknown_",r;return t&&i.isObjectLiteralExpression(t)&&(s=d(t,"field")??s,r=m(t,"precision")),{field:s,name:b(n),precision:r}},oe=e=>{const[n,t]=e,s=n&&i.isStringLiteral(n)?n.getLiteralText():"_unknown_";let r;return t&&i.isObjectLiteralExpression(t)&&(r=m(t,"after")),{after:r,field:s}},ae=e=>{if(!i.isObjectLiteralExpression(e))return;const n=d(e,"field");return n===void 0?void 0:{direction:d(e,"direction")==="desc"?"desc":"asc",field:n}},le=e=>{const[n,t]=e;let s=[],r;if(t&&i.isObjectLiteralExpression(t)){const o=t.getProperty("sortBy");if(o&&i.isPropertyAssignment(o)){const a=o.getInitializer();a&&i.isArrayLiteralExpression(a)&&(s=a.getElements().map(l=>ae(l)).filter(l=>l!==void 0))}r=x(t,"partitionBy")}return{name:b(n),partitionBy:r,sortBy:s}},ce=(e,n)=>{const[t,s]=e,r=t&&i.isStringLiteral(t)?t.getLiteralText():"_unknown_";if(!(!s||!i.isObjectLiteralExpression(s)))return{dimensions:m(s,"dimensions"),field:r,metadata:x(s,"metadata"),metric:k(d(s,"metric")),name:d(s,"index")??"_unnamed_",table:n}},de=e=>{const n=e[0];return n&&i.isObjectLiteralExpression(n)&&d(n,"backend")==="hyperdrive"?"hyperdrive":"d1"},fe=e=>{if(e&&i.isObjectLiteralExpression(e)){const n=e.getProperty("field");if(n&&i.isPropertyAssignment(n)){const t=n.getInitializer();if(t&&i.isStringLiteral(t))return t.getLiteralText()}}return"deletedAt"},ue=(e,n)=>{const t=x(e,n);return t!==void 0&&t.length>0?t:void 0},pe=e=>{const n=e[0];return!n||!i.isObjectLiteralExpression(n)?{binding:"",hasTenantBy:!1,unanalyzable:!0}:{binding:d(n,"binding")??"",columns:ue(n,"columns"),hasReconcile:n.getProperty("reconcileEveryMs")!==void 0,hasSoftDelete:n.getProperty("softDeleteColumn")!==void 0,hasTenantBy:n.getProperty("tenantBy")!==void 0,idColumn:d(n,"idColumn"),mode:d(n,"mode"),query:d(n,"query")}},ge=(e,n,t,s)=>{switch(n){case"externallyManaged":{e.externallyManaged=!0;break}case"geoIndex":{e.geoIndexes.push(ie(t));break}case"global":{e.shardMode="global",e.globalBackend=de(t);break}case"index":{e.indexes.push(re(t));break}case"public":{e.isPublic=!0;break}case"rankIndex":{e.rankIndexes.push(le(t));break}case"relations":{const r=t[0];r&&e.relations.push(...ee(r));break}case"searchIndex":{e.searchIndexes.push(se(t));break}case"shardBy":{const r=t[0];e.shardMode={field:r&&i.isStringLiteral(r)?r.getLiteralText():"_unknown_",kind:"shardBy"};break}case"softDelete":{e.softDelete={field:fe(t[0])};break}case"source":{e.externalSource=pe(t),e.externallyManaged=!0;break}case"ttl":{e.ttl=oe(t);break}case"vectorize":{const r=ce(t,s);r&&e.vectorIndexes.push(r);break}}},S=["__vocab","_config","_content","_data","_docsize","_idx"],me=(e,n,t)=>{const s=new Set(t.map(r=>r.name));for(const r of t)for(const o of S){const a=`${r.name}${o}`;if(!s.has(a))continue;const l=o==="__vocab"?`the \`fts5vocab\` companion for "${a}" is created \`IF NOT EXISTS\`, so it silently resolves to "${r.name}"'s — the second index then reads the wrong vocabulary and returns wrong results, with no error`:`creating "${a}" is rejected (\`object name reserved for internal use: SQLITE_ERROR\`), which aborts the shard migration and leaves every sharded table unreadable`;throw f(e,`table "${n}" declares search indexes "${r.name}" and "${a}", whose generated FTS5 tables collide: "${r.name}" already owns "${n}__fts_${a}" as its "${o}" companion, so ${l}. Rename one of them so neither ends with another's name plus ${S.join(", ")}.`)}},T=(e,n)=>{const t={externallyManaged:!1,geoIndexes:[],indexes:[],isPublic:!1,rankIndexes:[],relations:[],searchIndexes:[],shardMode:"root",vectorIndexes:[]};let s={},r=e;for(;i.isCallExpression(r);){const o=r.getExpression(),a=r.getArguments();if(i.isPropertyAccessExpression(o))ge(t,o.getName(),a,n),r=o.getExpression();else if(i.isIdentifier(o)&&o.getText()==="defineTable"){const l=a[0];if(l&&i.isObjectLiteralExpression(l))s=_(l);else if(l)throw f(l,`table "${n}" calls defineTable(${JSON.stringify(l.getText())}), but codegen reads the field map syntactically and can only read an object literal. Inline the fields into the defineTable(...) call. To reuse them in an \`.input()\`, derive from the generated \`Doc_${n}\` / \`Insert_${n}\` type instead of sharing the runtime value.`);break}else break}return t.softDelete&&!(t.softDelete.field in s)&&(s={...s,[t.softDelete.field]:{inner:{kind:"number"},kind:"optional"}}),me(e,n,t.searchIndexes),{externallyManaged:t.externallyManaged,externalSource:t.externalSource,geoIndexes:t.geoIndexes,globalBackend:t.shardMode==="global"?t.globalBackend??"d1":void 0,indexes:t.indexes,isPublic:t.isPublic,name:n,rankIndexes:t.rankIndexes,relations:t.relations,searchIndexes:t.searchIndexes,shape:s,shardMode:t.shardMode,softDelete:t.softDelete,ttl:t.ttl,vectorIndexes:t.vectorIndexes}},xe=e=>{const n=e.getProperty("source");if(n&&i.isPropertyAssignment(n)){const t=n.getInitializer();if(t&&i.isObjectLiteralExpression(t))return d(t,"table")??"_unknown_"}return"_unknown_"},be=e=>{if(!i.isPropertyAssignment(e))return;const n=e.getInitializer();if(!n||!i.isCallExpression(n))return;const t=n.getExpression();if(!i.isIdentifier(t)||t.getText()!=="defineVectorIndex")return;const s=n.getArguments()[0];if(!s||!i.isObjectLiteralExpression(s))return;const r=e.getNameNode(),o=i.isStringLiteral(r)?r.getLiteralText():r.getText();return{dimensions:m(s,"dimensions"),metric:k(d(s,"metric")),name:o,table:xe(s)}},L=e=>{const n=[];for(const t of e.getProperties()){const s=be(t);s&&n.push(s)}return n},v=(e,n)=>`${e}_${n}`,y=(e,n,t)=>t.has(e)?v(n,e):e,he=(e,n,t)=>{const s=v(n,e.name);return{...e,extensionKey:n,name:s,relations:e.relations.map(r=>({...r,table:y(r.table,n,t)})),vectorIndexes:e.vectorIndexes.map(r=>({...r,table:y(r.table,n,t)}))}},ye=e=>{if(i.isVariableDeclaration(e)||i.isPropertyAssignment(e))return e.getInitializer();if(i.isShorthandPropertyAssignment(e))return e.getNameNode()},ve=e=>{if(!i.isCallExpression(e))return!1;const n=e.getExpression();return i.isIdentifier(n)&&n.getText()==="defineSchemaExtension"},Ee=e=>{if(i.isIdentifier(e))return e;if(i.isPropertyAccessExpression(e)){const n=e.getExpression();return i.isIdentifier(n)?n:void 0}},Ie=e=>{if(i.isObjectLiteralExpression(e))return e;if(i.isCallExpression(e)){const n=e.getExpression();let t;if(i.isIdentifier(n)?t=n.getText():i.isPropertyAccessExpression(n)&&(t=n.getName()),t==="definePlugin"){const s=e.getArguments()[1];return s&&i.isObjectLiteralExpression(s)?s:void 0}}},Se=(e,n)=>{const t=ye(e);if(t){if(i.isPropertyAccessExpression(n)){const s=Ie(t);return s?g(s,n.getName()):void 0}return t}},ke=e=>{let n=e,t=0;for(;n&&t<32;){if(t+=1,ve(n))return n;const s=Ee(n),r=s&&i.isIdentifier(s)?s.getSymbol():void 0,a=(r?.getAliasedSymbol()?.getDeclarations()??r?.getDeclarations()??[])[0];if(!a)return;const l=a.getSourceFile();if(l.isInNodeModules()||l.isDeclarationFile())return;n=Se(a,n)}},Te=e=>{const[n,t]=e.getArguments();if(!(!n||!i.isStringLiteral(n))&&!(!t||!i.isObjectLiteralExpression(t)))return{key:n.getLiteralText(),options:t}},Le=e=>{const n=e.getProperty("tables");if(!n||!i.isPropertyAssignment(n))return[];const t=n.getInitializer();if(!t||!i.isObjectLiteralExpression(t))return[];const s=[];for(const r of t.getProperties()){if(!i.isPropertyAssignment(r))continue;const o=r.getInitializer();o&&s.push(T(o,r.getName()))}return s},Pe=e=>{const n=e.getProperty("vectorIndexes");if(!n||!i.isPropertyAssignment(n))return[];const t=n.getInitializer();return!t||!i.isObjectLiteralExpression(t)?[]:L(t)},P=(e,n,t)=>{const s=new Set(n.map(a=>a.name)),r=n.map(a=>he(a,e,s)),o=t.map(a=>({...a,name:v(e,a.name),table:y(a.table,e,s)}));return{tables:r,vectorIndexes:o}},we=(e,n)=>P(e,Le(n),Pe(n)),Ne=(e,n)=>{const t=e.getArguments()[0];if(!t)return;const s=ke(t);if(!s){if(n!==void 0){const o=J(t,n);if(o)return P(o.key,o.bareTables,o.bareVectorIndexes)}console.warn(`@lunora/codegen: skipping \`.extend(${t.getText()})\` — its \`defineSchemaExtension(...)\` could not be resolved from local sources, and ${n===void 0?"no project root was available to resolve the package":"the package could not be imported/introspected"}. Extension tables will be absent from the generated types.`);return}const r=Te(s);if(!r){console.warn("@lunora/codegen: skipping `.extend(...)` — `defineSchemaExtension` requires a string `key` and an options object literal.");return}return we(r.key,r.options)},Oe=e=>{const n=[];let t=e;for(;;){const s=t.getParent();if(!s||!i.isPropertyAccessExpression(s))break;const r=s.getParent();if(!r||!i.isCallExpression(r))break;s.getName()==="extend"&&n.push(r),t=r}return n},w=(e,n,t,s,r)=>{let o=e;for(;;){const a=o.getParent();if(!a||!i.isPropertyAccessExpression(a))break;const l=a.getParent();if(!l||!i.isCallExpression(l))break;if(a.getName()===n){const c=l.getArguments()[0];if(!c||!i.isStringLiteral(c))throw f(l,`\`.${n}(...)\` expects a string literal (${r})`);const u=c.getLiteralText();if(!s.has(u))throw f(c,`unknown ${t} ${JSON.stringify(u)} — expected ${r}`);return u}o=l}},Ae=new Set(["eu","fedramp","us"]),_e=e=>w(e,"jurisdiction","jurisdiction",Ae,'"eu", "us", or "fedramp"'),je=new Set(["required"]),$e=e=>w(e,"rls","rls mode",je,'"required"'),ze=e=>{const n=[];for(const t of e.getProperties()){if(!i.isPropertyAssignment(t))continue;const s=t.getInitializer();if(s){const r=t.getName();Q(r,t.getNameNode()),n.push(T(s,r))}}return n},De=(e,n,t)=>{const s=new Set(n.map(o=>o.name)),r=[];for(const o of Oe(e)){const a=Ne(o,t);if(a){for(const l of a.tables){if(s.has(l.name))throw f(o,`defineSchema(...).extend(...): table "${l.name}" already exists — another extension with the same key already contributed it.`);s.add(l.name),n.push(l)}r.push(...a.vectorIndexes)}}return r},qe=(e,n,t)=>{const r=e.addSourceFileAtPath(n).getDescendantsOfKind(A.CallExpression).find(h=>{const E=h.getExpression();return i.isIdentifier(E)&&E.getText()==="defineSchema"});if(!r)throw new O("INTERNAL",`defineSchema() not found in ${n}`);const o=r.getArguments()[0];if(!o||!i.isObjectLiteralExpression(o))throw f(r,"defineSchema() expects an object literal");const a=ze(o),l=r.getArguments()[1],c=l&&i.isObjectLiteralExpression(l)?L(l):[],u=De(r,a,t),N=[...a.flatMap(h=>h.vectorIndexes),...c,...u];return{jurisdiction:_e(r),rlsMode:$e(r),tables:a,vectorIndexes:N}};export{qe as default};
@@ -1 +0,0 @@
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};