@lunora/codegen 1.0.0-alpha.85 → 1.0.0-alpha.87

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 (36) hide show
  1. package/dist/index.d.mts +1 -1
  2. package/dist/index.d.ts +1 -1
  3. package/dist/index.mjs +1 -1
  4. package/dist/packem_shared/{FLAGS_FILENAME-BiJh08O0.mjs → FLAGS_FILENAME-CHaH6obH.mjs} +1 -1
  5. package/dist/packem_shared/GENERATED_HEADER-CUBdTCVk.mjs +1 -0
  6. package/dist/packem_shared/{MUTATORS_FILENAME-9652koWz.mjs → MUTATORS_FILENAME-DY3rgWGl.mjs} +1 -1
  7. package/dist/packem_shared/{NOTIFY_FILENAME-DeIlwPBu.mjs → NOTIFY_FILENAME-CDvoTY3Y.mjs} +1 -1
  8. package/dist/packem_shared/{OPENRPC_VERSION-K3RTK2CP.mjs → OPENRPC_VERSION-aq5eyIkd.mjs} +1 -1
  9. package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-ChA6rpGP.mjs +9 -0
  10. package/dist/packem_shared/{SHAPES_FILENAME-Cwn4I4UB.mjs → SHAPES_FILENAME-BdLj5-mD.mjs} +1 -1
  11. package/dist/packem_shared/{buildOpenApiDocument-Blf3mpIz.mjs → buildOpenApiDocument-Bw3MChvT.mjs} +1 -1
  12. package/dist/packem_shared/{discover-queries-B4Lw0cEr.mjs → discover-queries-BmZeJ--u.mjs} +1 -1
  13. package/dist/packem_shared/{discoverAuthApiCalls-CVTXSguP.mjs → discoverAuthApiCalls-BgL6nj03.mjs} +1 -1
  14. package/dist/packem_shared/{discoverCrons-CZ0_RXUc.mjs → discoverCrons-WJscxQFl.mjs} +1 -1
  15. package/dist/packem_shared/discoverFunctions-BgGmxEqW.mjs +1 -0
  16. package/dist/packem_shared/{discoverHttpRoutes-VyBQ9CbN.mjs → discoverHttpRoutes-eW8RbVOr.mjs} +1 -1
  17. package/dist/packem_shared/{discoverInserts-BGlOx2Cg.mjs → discoverInserts-BCz6zpI0.mjs} +1 -1
  18. package/dist/packem_shared/{discoverMaskProcedures-DpAT4zsu.mjs → discoverMaskProcedures-DLfQRsQc.mjs} +1 -1
  19. package/dist/packem_shared/{discoverMigrations-CcOvlTA7.mjs → discoverMigrations-Cbc4W765.mjs} +1 -1
  20. package/dist/packem_shared/{discoverNondeterministicCalls-CVY5_-x1.mjs → discoverNondeterministicCalls-x9IhWxPP.mjs} +1 -1
  21. package/dist/packem_shared/discoverQueries-Cf0LGoQG.mjs +1 -0
  22. package/dist/packem_shared/{discoverR2sqlCalls-BKn9ogOI.mjs → discoverR2sqlCalls--MSfSeDm.mjs} +1 -1
  23. package/dist/packem_shared/{discoverRlsMetadata-B2iTIbm0.mjs → discoverRlsMetadata-DTRS0ROc.mjs} +1 -1
  24. package/dist/packem_shared/{discoverSandboxUsage-rkLj3ZC0.mjs → discoverSandboxUsage-BDyeyuYo.mjs} +1 -1
  25. package/dist/packem_shared/discoverSchema-DSJSX4Ss.mjs +1 -0
  26. package/dist/packem_shared/{discoverStorageRulesMetadata-AD_GPKdF.mjs → discoverStorageRulesMetadata-Cic97L-2.mjs} +1 -1
  27. package/dist/packem_shared/{emit-B7IUlWwi.mjs → emit-DMvG162j.mjs} +335 -324
  28. package/dist/packem_shared/{emitApp-jRD2D9kI.mjs → emitApp--dJ6EnFn.mjs} +1 -1
  29. package/dist/packem_shared/parse-validator-CkLxY-Mr.mjs +1 -0
  30. package/package.json +10 -10
  31. package/dist/packem_shared/GENERATED_HEADER-oy7DTIDi.mjs +0 -1
  32. package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-DHVrsPNK.mjs +0 -9
  33. package/dist/packem_shared/discoverFunctions-9GMvSwz7.mjs +0 -1
  34. package/dist/packem_shared/discoverQueries-BFFoJLOQ.mjs +0 -1
  35. package/dist/packem_shared/discoverSchema-1zm6abY5.mjs +0 -1
  36. package/dist/packem_shared/parse-validator-DCrBLhq7.mjs +0 -1
@@ -1,4 +1,4 @@
1
- import{n as S,R as D}from"./emit-B7IUlWwi.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]),m=e=>v.some(([t])=>e[t]),R=e=>e?['import * as lunoraIdentityContract from "../identity.js";']:[],A=(e,t)=>e?['import type { CreateAccessResolverOptions } from "@lunora/cloudflare-access";',`import { createAccessResolver${t?", composeResolvers":""} } from "@lunora/cloudflare-access";`]:[],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",g=["ExecutionContextLike","HttpRouterLike","LunoraWorker","Route","ScheduledControllerLike","ShardNamespaceLike","WorkerOptions"];n&&g.push("GlobalIntrospector","AdminTableResolver"),a&&g.push("FrameworkHostHandler");const f=[...n||o?["createCrossShardRelationCapabilities"]:[],"createWorker","resolveLogArchiveFromEnv",...a?["withFrameworkWorker"]:[]].join(", ");return[...r?['import type { LunoraAuth, LunoraAuthOptions } from "@lunora/auth";','import { createAuth, createAuthAdmin, createAuthAuditReader, createDoAuthWiring, d1Executor, ensureMigrated, handleAuthRequest, lunoraD1Adapter } from "@lunora/auth";']:[],...A(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 { ${[...g].toSorted((w,y)=>w.localeCompare(y)).join(", ")} } from "${i}";`,`import { ${f} } from "${i}";`,"",...R(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";']},j=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{n as S,S as D}from"./emit-DMvG162j.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]),m=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",g=["ExecutionContextLike","HttpRouterLike","LunoraWorker","Route","ScheduledControllerLike","ShardNamespaceLike","WorkerOptions"];n&&g.push("GlobalIntrospector","AdminTableResolver"),a&&g.push("FrameworkHostHandler");const f=[...n||o?["createCrossShardRelationCapabilities"]:[],"createWorker","resolveLogArchiveFromEnv",...a?["withFrameworkWorker"]:[]].join(", ");return[...r?['import type { LunoraAuth, LunoraAuthOptions } from "@lunora/auth";','import { createAuth, createAuthAdmin, createAuthAuditReader, 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 { ${[...g].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";']},j=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>;
@@ -0,0 +1 @@
1
+ import{LunoraError as f}from"@lunora/errors";import{Node as i}from"ts-morph";let c;const A=e=>{c=e},p=/^[A-Za-z_$][\w$]*$/u,g=new Set(["$defaultFn","$onUpdateFn","$type","default","defaultNow","nullable","unique"]),k=(e,n)=>{const t={notNull:!0,...e.column};switch(n){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}},m=new Set(["any","bigint","boolean","bytes","date","geoPoint","null","number","string","timestamp"]),y=new Set(["check","meta"]),d=new Set,x=e=>{const n=e.getSymbol(),t=(n?.getAliasedSymbol()??n)?.getValueDeclaration();if(!(t===void 0||!i.isVariableDeclaration(t)))return t.getInitializer()},b="v",N=e=>{if(i.isIdentifier(e))return!0;let n=e;for(;i.isCallExpression(n);){const t=n.getExpression();if(!i.isPropertyAccessExpression(t))return!1;n=t.getExpression()}return i.isIdentifier(n)&&n.getText()===b},o=e=>{if(i.isIdentifier(e)&&!d.has(e)){const n=x(e);if(n!==void 0&&N(n)){d.add(e);try{return o(n)}finally{d.delete(e)}}}return i.isCallExpression(e)?w(e):{kind:"any",sourceText:e.getText()}},E=e=>{const n={};for(const t of e.getProperties()){const a=i.isShorthandPropertyAssignment(t);if(!a&&!i.isPropertyAssignment(t))continue;const r=t.getNameNode();if(i.isComputedPropertyName(r))continue;const s=a?t.getNameNode():t.getInitializer();if(!s)continue;const l=t.getName();if(!p.test(l))throw new f("INTERNAL",`@lunora/codegen: field name is not a valid JS identifier: ${JSON.stringify(l)}`);n[l]=o(s)}return n},u=(e,n)=>e&&i.isExpression(e)?o(e):n,h=e=>e===void 0?"undefined":i.isStringLiteral(e)||i.isNoSubstitutionTemplateLiteral(e)?JSON.stringify(e.getLiteralValue()):e.getText(),S=e=>{const n=e&&c?c(e):void 0;return n===void 0?{kind:"from"}:{kind:"from",tsType:n}},T=(e,n)=>{if(m.has(e))return{kind:e};const[t,a]=n;switch(e){case"array":return{inner:u(t,{kind:"any"}),kind:"array"};case"from":return S(t);case"id":return{kind:"id",tableName:t&&i.isStringLiteral(t)?t.getLiteralText():"_unknown_"};case"literal":return{kind:"literal",literalValue:h(t)};case"object":return t&&i.isObjectLiteralExpression(t)?{kind:"object",shape:E(t)}:{kind:"object",shape:{}};case"optional":return{inner:u(t,{kind:"any"}),kind:"optional"};case"record":return{keyType:u(t,{kind:"string"}),kind:"record",valueType:u(a,{kind:"any"})};case"storage":return t&&i.isStringLiteral(t)?{bucket:t.getLiteralText(),kind:"storage"}:{kind:"storage"};case"union":return{kind:"union",members:n.filter(r=>i.isExpression(r)).map(r=>o(r))};default:throw new f("INTERNAL",`Unsupported validator kind: ${e}`)}},w=e=>{const n=e.getExpression();if(!i.isPropertyAccessExpression(n))return{kind:"any",sourceText:e.getText()};const t=n.getName(),a=e.getArguments();if(g.has(t)){const r=n.getExpression(),s=i.isExpression(r)?o(r):{kind:"any"};return k(s,t)}if(y.has(t)){const r=n.getExpression(),s=i.isExpression(r)?o(r):{kind:"any"};return t==="check"?{...s,hasRefinement:!0}:s}return T(t,a)};export{E as f,A as g,o as s};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/codegen",
3
- "version": "1.0.0-alpha.85",
3
+ "version": "1.0.0-alpha.87",
4
4
  "description": "Code generator for Lunora: emits _generated/{api,server,dataModel}.ts from your schema",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -46,15 +46,15 @@
46
46
  "access": "public"
47
47
  },
48
48
  "dependencies": {
49
- "@lunora/advisor": "1.0.0-alpha.62",
50
- "@lunora/agent": "1.0.0-alpha.37",
51
- "@lunora/container": "1.0.0-alpha.20",
52
- "@lunora/errors": "1.0.0-alpha.12",
53
- "@lunora/platform": "1.0.0-alpha.4",
54
- "@lunora/queue": "1.0.0-alpha.16",
55
- "@lunora/scheduler": "1.0.0-alpha.19",
56
- "@lunora/values": "1.0.0-alpha.15",
57
- "@lunora/workflow": "1.0.0-alpha.17",
49
+ "@lunora/advisor": "1.0.0-alpha.64",
50
+ "@lunora/agent": "1.0.0-alpha.39",
51
+ "@lunora/container": "1.0.0-alpha.21",
52
+ "@lunora/errors": "1.0.0-alpha.13",
53
+ "@lunora/platform": "1.0.0-alpha.5",
54
+ "@lunora/queue": "1.0.0-alpha.17",
55
+ "@lunora/scheduler": "1.0.0-alpha.20",
56
+ "@lunora/values": "1.0.0-alpha.17",
57
+ "@lunora/workflow": "1.0.0-alpha.19",
58
58
  "jsonc-parser": "^3.3.1",
59
59
  "ts-morph": "^28.0.0"
60
60
  },
@@ -1 +0,0 @@
1
- import"@lunora/agent/component";import"@lunora/errors";import"./SCHEMA_SNAPSHOT_VERSION-CFhF_hmg.mjs";import{R as r,a as o,c as n,i as l,I as A,C as E,o as S,S as C,g,v as p,B as c,l as u,O as d,P as D,b as R,$ as B,s as _,A as b}from"./emit-B7IUlWwi.mjs";import"./paths-BmX5O1sG.mjs";export{r as GENERATED_HEADER,o as UMBRELLA_BASE_PACKAGES,n as buildStorageColumns,l as emitAgents,A as emitApi,E as emitCollections,S as emitContainers,C as emitCrons,g as emitDataModel,p as emitDrizzleSchema,c as emitFunctions,u as emitQueues,d as emitSeed,D as emitServer,R as emitShard,B as emitVectors,_ as emitWorkflows,b as emitWranglerCronTriggers};
@@ -1,9 +0,0 @@
1
- import{existsSync as E,mkdirSync as ot,readFileSync as wt,writeFileSync as es,rmSync as ts}from"node:fs";import{join as d,dirname as he}from"node:path";import{performance as xe}from"node:perf_hooks";import{runAdvisor as ss}from"@lunora/advisor";import{LunoraError as F}from"@lunora/errors";import{Node as i,SyntaxKind as u,Project as at}from"ts-morph";import{serializeSchemaSnapshot as rs}from"./SCHEMA_SNAPSHOT_VERSION-CFhF_hmg.mjs";import{toAdvisorContext as ns}from"./formatAdvisories-BCEfzLT0.mjs";import{listLunoraSourceFiles as g,lunoraRelativePath as p,classifyProcedureCall as K,inlineHandler as is,procedureHandler as It,chainUsesWrappedCall as Tt,isDatabaseAccessor as C,chainHasStep as os,discoverFunctions as as,resolveStandardSchemaType as cs}from"./discoverFunctions-9GMvSwz7.mjs";import{discoverAgents as us}from"./AGENTS_FILENAME-BesaDYkL.mjs";import{i as w,a as O,e as x,c as S,r as ls,b as ds,s as Q,d as gs,f as ps,y as fs}from"./discover-queries-B4Lw0cEr.mjs";import ms from"./discoverAuthApiCalls-CVTXSguP.mjs";import{discoverContainers as hs}from"./CONTAINERS_FILENAME-CFwdyaCI.mjs";import xs from"./discoverCrons-CZ0_RXUc.mjs";import{diagnosticAt as J}from"./CodegenDiagnosticError-DPezpZTz.mjs";import{o as X}from"./module-specifiers-8FEEiUcv.mjs";import{r as Ee,g as ct,P as ut,c as Es,I as ys,B as $s,b as As,C as Ss,o as bs,s as vs,i as Ns,l as Ps,S as ws,$ as Is,v as Ts,O as Ls,A as Fs}from"./emit-B7IUlWwi.mjs";import{discoverFlagKeys as Os}from"./FLAGS_FILENAME-BiJh08O0.mjs";import Ds from"./discoverHttpRoutes-VyBQ9CbN.mjs";import ks from"./discoverInserts-BGlOx2Cg.mjs";import Cs,{discoverMaskStrategies as Ks,discoverMaskMetadata as Rs,discoverMaskHasNonLiteralPolicy as Ms}from"./discoverMaskProcedures-DpAT4zsu.mjs";import js from"./discoverMigrations-CcOvlTA7.mjs";import{MUTATORS_FILENAME as zs,isDefineMutatorCallee as qs,discoverMutators as Bs}from"./MUTATORS_FILENAME-9652koWz.mjs";import Us from"./discoverNondeterministicCalls-CVY5_-x1.mjs";import{discoverNotifyConfig as Vs,discoverNotifyCalls as Ws}from"./NOTIFY_FILENAME-DeIlwPBu.mjs";import lt from"./readPackageDependencies-CogJX1Ia.mjs";import{discoverQueues as _s}from"./QUEUES_FILENAME-CSE6i-ld.mjs";import Gs from"./discoverR2sqlCalls-BKn9ogOI.mjs";import Hs,{discoverRlsMetadata as Qs}from"./discoverRlsMetadata-B2iTIbm0.mjs";import{discoverSandboxUsage as Js}from"./discoverSandboxUsage-rkLj3ZC0.mjs";import Xs from"./discoverSchema-1zm6abY5.mjs";import{secretKindOf as Zs,redact as Ys,isHeuristicSecretKind as er,isSecretishName as tr}from"./redact-6jD4lAhq.mjs";import{discoverShapes as sr}from"./SHAPES_FILENAME-Cwn4I4UB.mjs";import rr from"./discoverStorageRulesMetadata-AD_GPKdF.mjs";import{e as nr}from"./discover-ast-CezKqEhE.mjs";import{discoverWorkflows as ir}from"./WORKFLOWS_FILENAME-ClsYRKXp.mjs";import{emitApp as or}from"./emitApp-jRD2D9kI.mjs";import{buildOpenApiDocument as ar,emitOpenApiModule as cr}from"./buildOpenApiDocument-Blf3mpIz.mjs";import{buildOpenRpcDocument as ur,emitOpenRpcModule as lr}from"./OPENRPC_VERSION-K3RTK2CP.mjs";import{f as dr}from"./parse-validator-DCrBLhq7.mjs";import{gatePlatformFeatures as gr,resolveCodegenTarget as pr}from"./DEFAULT_TARGET-CH5disA3.mjs";import{buildSchemaSnapshot as fr}from"./SchemaSnapshotParseError-BJkhTEpi.mjs";const mr=e=>{const t=[],s=e.tables.filter(r=>r.shardMode==="global");return s.some(r=>r.globalBackend!=="hyperdrive")&&t.push({name:"@lunora/d1",reason:"`.global()` tables are D1-backed, so `_generated/app.ts` imports the D1 `ctx.db` adapter"}),s.some(r=>r.globalBackend==="hyperdrive")&&t.push({name:"@lunora/hyperdrive",reason:'`.global({ backend: "hyperdrive" })` tables route through `@lunora/hyperdrive/global`'}),e.vectorIndexes.length>0&&t.push({name:"@lunora/bindings",reason:"`.vectorize()` indexes make `_generated/vectors.ts` import `@lunora/bindings/vectors`"}),t},hr=(e,t)=>{if(t===void 0)return;const s=mr(e).filter(n=>!t.has(n.name));if(s.length===0)return;const r=s.map(n=>` - ${n.name} — ${n.reason}`).join(`
2
- `);throw new F("INTERNAL",`@lunora/codegen: this schema's generated code imports packages the project does not declare:
3
- ${r}
4
-
5
- Install them with your package manager, then re-run codegen.`)},Lt=new Set(["delete","get","head","options","patch","post","put"]),xr=new Set(["handler","stream"]),Er=/\/(?:_|admin|internal|superuser|sudo|root|debug)/iu,dt=new Set(["ADMIN_TOKEN","adminToken","assertAdmin","assertAuth","auth","Authorization","getSession","identity","isAdmin","requireAdmin","requireAuth","requireRole","verifyAdmin"]),yr=e=>{if(!i.isCallExpression(e))return;const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!Lt.has(t.getName()))return;const s=t.getExpression();if(!i.isIdentifier(s)||s.getText()!=="httpRoute")return;const r=e.getArguments()[0];if(!(!r||!i.isStringLiteral(r)))return{method:t.getName().toUpperCase(),path:r.getLiteralValue()}},$r=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t))return;let s=t.getExpression();for(;i.isCallExpression(s);){const r=s.getExpression();if(!i.isPropertyAccessExpression(r)||Lt.has(r.getName()))break;s=r.getExpression()}return yr(s)},Ar=e=>{for(const t of e.getDescendantsOfKind(u.PropertyAccessExpression))if(dt.has(t.getName()))return!0;for(const t of e.getDescendantsOfKind(u.CallExpression)){const s=t.getExpression();if(i.isIdentifier(s)&&dt.has(s.getText()))return!0}return!1},Sr=(e,t)=>{const s=e.getInitializer();if(!s||!i.isCallExpression(s))return;const r=s.getExpression();if(!i.isPropertyAccessExpression(r)||!xr.has(r.getName()))return;const n=$r(s);if(!n||!Er.test(n.path))return;const o=s.getArguments()[0],a=o!==void 0&&(i.isArrowFunction(o)||i.isFunctionExpression(o))&&Ar(o);return{exportName:e.getName(),file:t,method:n.method,path:n.path,usesGuard:a}},br=(e,t)=>{const s=[];for(const r of e.getVariableStatements())if(r.isExported())for(const n of r.getDeclarations()){const o=Sr(n,t);o&&s.push(o)}return s},vr=(e,t)=>{const s=[];for(const r of g(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...br(n,p(t,r)))}return s},Nr=e=>!i.isPropertyAccessExpression(e)||e.getName()!=="run"?!1:e.getExpression().getText()==="ctx.ai",Pr=(e,t)=>{if(!Nr(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!w(s)||O(s)))return{exportName:x(e),file:t,line:e.getStartLineNumber()}},wr=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=Pr(r,t);n&&s.push(n)}return s},Ir=(e,t)=>{const s=[];for(const r of g(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...wr(n,p(t,r)))}return s},Tr=new Set(["generateText","streamText"]),Lr=new Set(["messages","prompt","system"]),Fr=[{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"]}],Or=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t))return;const s=t.getName(),r=t.getExpression().getText();for(const n of Fr)if(n.methods.has(s)&&n.prefixes.some(o=>r===o||r.startsWith(`${o}.`)))return`${r}.${s}`},Dr=e=>{for(const t of e.getDescendantsOfKind(u.CallExpression)){const s=Or(t);if(s!==void 0)return s}},kr=e=>{const t=new Set,s=e.getFirstAncestor(o=>i.isArrowFunction(o)||i.isFunctionExpression(o)||i.isFunctionDeclaration(o)),[r]=s?.getParameters()??[],n=r?.getNameNode();if(n===void 0||!i.isObjectBindingPattern(n))return t;for(const o of n.getElements()){const a=o.getPropertyNameNode()?.getText()??o.getName(),c=o.getNameNode();if(a==="args"&&i.isObjectBindingPattern(c))for(const l of c.getElements())t.add(l.getName())}return t},Cr=e=>{if(ls(e))return!0;const t=kr(e);return t.size===0?!1:e.getDescendantsOfKind(u.Identifier).some(s=>t.has(s.getText()))},Kr=e=>{for(const t of e.getProperties()){if(!i.isPropertyAssignment(t)||!Lr.has(t.getName()))continue;const s=t.getInitializer();if(s!==void 0&&Cr(s))return!0}return!1},Rr=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=S(r.getExpression());if(n===void 0||!Tr.has(n))continue;const[o]=r.getArguments();if(o===void 0||!i.isObjectLiteralExpression(o))continue;let a;for(const c of o.getDescendantsOfKind(u.CallExpression))if(S(c.getExpression())==="tool"&&(a=Dr(c),a!==void 0))break;a!==void 0&&s.push({exportName:x(r),file:t,line:r.getStartLineNumber(),method:n,sideEffect:a,userInputDerived:Kr(o)})}return s},Mr=(e,t)=>{const s=[];for(const r of g(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Rr(n,p(t,r)))}return s},jr=e=>{if(!i.isPropertyAccessExpression(e)||e.getName()!=="fetch")return!1;const t=e.getExpression();return i.isIdentifier(t)&&t.getText()==="ctx"},zr=(e,t)=>{if(!jr(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!w(s)))return{exportName:x(e),file:t,line:e.getStartLineNumber()}},qr=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=zr(r,t);n&&s.push(n)}return s},Br=(e,t)=>{const s=[];for(const r of g(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...qr(n,p(t,r)))}return s},Ft=e=>e.getProperties().some(t=>i.isSpreadAssignment(t)),Ur=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 r=s.getInitializer();return!r||!i.isObjectLiteralExpression(r)?{objects:[],opaque:!0}:{objects:[r],opaque:Ft(r)}},Vr=e=>{const t=[];let s=!1,r=e;for(;i.isCallExpression(r);){const n=r.getExpression();if(!i.isPropertyAccessExpression(n))break;if(n.getName()==="input"){const o=r.getArguments()[0];o&&i.isObjectLiteralExpression(o)?(t.push(o),s||=Ft(o)):s=!0}r=n.getExpression()}return{objects:t,opaque:s}},Ot=(e,t)=>t?Vr(t):Ur(e),Wr=e=>e.flatMap(t=>t.getProperties().filter(s=>i.isPropertyAssignment(s)||i.isShorthandPropertyAssignment(s)).map(s=>s.getName())),_r=/\.check\(|\.meta\(|length|max/iu,Gr=/\bv\.any\s*\(/u,Hr=/\bv\.string\s*\(/u,Qr=e=>Gr.test(e),Jr=e=>Hr.test(e)&&!_r.test(e),Xr=e=>{const t=[],s=[];for(const r of e)for(const n of r.getProperties()){if(!i.isPropertyAssignment(n))continue;const o=n.getInitializer();if(!o)continue;const a=o.getText(),c=n.getName();Qr(a)?t.push(c):Jr(a)&&s.push(c)}return{anyArgs:t,unboundedStringArgs:s}},Zr=(e,t)=>{const s=e.getInitializer();if(!s||!i.isCallExpression(s))return;const r=K(s);if(r?.visibility!=="public")return;const{objects:n}=Ot(s,r.receiver),{anyArgs:o,unboundedStringArgs:a}=Xr(n);if(!(o.length===0&&a.length===0))return{anyArgs:o,exportName:e.getName(),file:t,line:s.getStartLineNumber(),unboundedStringArgs:a}},Yr=(e,t)=>{const s=[];for(const r of e.getVariableStatements())if(r.isExported())for(const n of r.getDeclarations()){const o=Zr(n,t);o&&s.push(o)}return s},en=(e,t)=>{const s=[];for(const r of g(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Yr(n,p(t,r)))}return s},b=(e,t)=>{if(!e||!i.isObjectLiteralExpression(e))return;const s=e.getProperty(t);return s&&i.isPropertyAssignment(s)?s.getInitializer():void 0},ye=e=>e?.getKind()===u.TrueKeyword,tn=e=>e?.getKind()===u.FalseKeyword,sn=e=>e!==void 0&&i.isNumericLiteral(e)&&e.getLiteralValue()===0,rn=new Set(["lunoraAuthAdapter","lunoraD1Adapter"]),nn=e=>!e||!i.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>i.isCallExpression(t)&&S(t.getExpression())==="scim"),on=e=>e!==void 0&&i.isCallExpression(e)&&rn.has(S(e.getExpression())??""),an=e=>!e||!i.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>i.isStringLiteral(t)&&t.getLiteralText()==="*"),cn=e=>{const t=b(e,"advanced"),s=b(e,"emailAndPassword"),r=b(e,"session");return{analyzable:!0,disableCsrfCheck:ye(b(t,"disableCSRFCheck")),emailPasswordEnabled:ye(b(s,"enabled")),requireEmailVerification:ye(b(s,"requireEmailVerification")),scimOnNonTransactionalAdapter:nn(b(e,"plugins"))&&on(b(e,"database")),secureCookiesDisabled:tn(b(t,"useSecureCookies")),sessionFreshAgeZero:sn(b(r,"freshAge")),trustedOriginsWildcard:an(b(e,"trustedOrigins"))}},un=()=>({analyzable:!1,disableCsrfCheck:!1,emailPasswordEnabled:!1,requireEmailVerification:!1,scimOnNonTransactionalAdapter:!1,secureCookiesDisabled:!1,sessionFreshAgeZero:!1,trustedOriginsWildcard:!1}),ln=(e,t)=>{if(S(e.getExpression())!=="createAuth")return;const s=e.getArguments()[0],r=s!==void 0&&i.isObjectLiteralExpression(s)&&s.getProperties().some(o=>i.isSpreadAssignment(o)),n=s!==void 0&&i.isObjectLiteralExpression(s)&&!r?cn(s):un();return{exportName:x(e),file:t,line:e.getStartLineNumber(),...n}},dn=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=ln(r,t);n&&s.push(n)}return s},gn=(e,t)=>{const s=[];for(const r of g(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...dn(n,p(t,r)))}return s},pn=(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},fn=(e,t,s)=>{const r=pn(e.getExpression(),s);if(r===void 0)return;const n=e.getArguments()[s.argIndex];if(!(!n||!w(n)||O(n))&&!(s.requireUnmodifiedReach===!0&&!ds(n)))return{exportName:x(e),file:t,line:e.getStartLineNumber(),method:r}},mn=(e,t,s)=>{const r=[];for(const n of e.getDescendantsOfKind(u.CallExpression)){const o=fn(n,t,s);o&&r.push(o)}return r},Z=(e,t,s)=>{const r=[];for(const n of g(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);r.push(...mn(o,p(t,n),s))}return r},hn=new Set(["content","pdf","scrape","screenshot"]),xn=(e,t)=>Z(e,t,{argIndex:0,matchReceiver:s=>s==="ctx.browser",methods:hn}),En=new Set(["createBrowser","createInboundEmailHandler","createPayment"]),yn=new Set(["RateLimiter"]),$n=new Set(["extend"]),Dt=e=>{const t=[],s=[];let r=!1;for(const n of e.getProperties()){if(i.isSpreadAssignment(n)){r=!0;continue}if(i.isPropertyAssignment(n)){const o=n.getName();t.push(o),n.getInitializer()?.getKind()===u.TrueKeyword&&s.push(o);continue}(i.isShorthandPropertyAssignment(n)||i.isMethodDeclaration(n))&&t.push(n.getName())}return{analyzable:!r,presentKeys:t,trueKeys:s}},gt=e=>e&&i.isObjectLiteralExpression(e)?Dt(e):{analyzable:!1,presentKeys:[],trueKeys:[]},An=e=>{const t=e.getStatements(),[s]=t;if(t.length!==1||s===void 0||!i.isReturnStatement(s))return;const r=s.getExpression();return r!==void 0&&i.isObjectLiteralExpression(r)?r:void 0},Sn=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)?An(e):void 0},bn=e=>{const t=e&&(i.isArrowFunction(e)||i.isFunctionExpression(e))?e:void 0,s=t&&Sn(t.getBody());return s?Dt(s):{analyzable:!1,presentKeys:[],trueKeys:[]}},vn=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=S(r.getExpression());n!==void 0&&(En.has(n)?s.push({callee:n,file:t,line:r.getStartLineNumber(),...gt(r.getArguments()[0])}):$n.has(n)&&s.push({callee:n,file:t,line:r.getStartLineNumber(),...bn(r.getArguments()[0])}))}for(const r of e.getDescendantsOfKind(u.NewExpression)){const n=S(r.getExpression());n===void 0||!yn.has(n)||s.push({callee:n,file:t,line:r.getStartLineNumber(),...gt(r.getArguments()[0])})}return s},Nn=(e,t)=>{const s=[];for(const r of g(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...vn(n,p(t,r)))}return s},pt="ctx.containers.",Pn=e=>{if(!e.startsWith(pt))return!1;const t=e.slice(pt.length);return t.length>0&&!t.includes(".")},wn=(e,t)=>Z(e,t,{argIndex:0,matchReceiver:Pn,methods:new Set(["get"])}),In=new Set(["allow","deny","setAllowed"]),Tn=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())},Ln=(e,t)=>{const s=e.getExpression();if(!(!i.isPropertyAccessExpression(s)||s.getName()!=="start"||!Tn(e)))return{detail:"enableInternet: true",exportName:x(e),file:t,kind:"enable_internet",line:e.getStartLineNumber()}},Fn=(e,t)=>{const s=e.getExpression();if(!i.isPropertyAccessExpression(s)||!In.has(s.getName()))return;const r=s.getExpression();if(!(!i.isPropertyAccessExpression(r)||r.getName()!=="egress"))return{detail:s.getName(),exportName:x(e),file:t,kind:"egress_relaxation",line:e.getStartLineNumber()}},On=(e,t)=>Ln(e,t)??Fn(e,t),Dn=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=On(r,t);n&&s.push(n)}return s},kn=(e,t)=>{const s=[];for(const r of g(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Dn(n,p(t,r)))}return s},Cn="env.ts",Kn=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineEnv";for(const s of t.getDeclarations())if(i.isImportSpecifier(s))return X(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineEnv":!1;return!1},Rn=e=>{const t=e.getSymbol();if(!t)return!1;for(const s of t.getDeclarations()){if(!i.isNamespaceImport(s))continue;const r=s.getFirstAncestorByKind(u.ImportDeclaration);return r!==void 0&&X(r.getModuleSpecifierValue())}return!1},Mn=e=>{if(i.isIdentifier(e))return Kn(e);if(i.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineEnv"&&i.isIdentifier(t)&&Rn(t)}return!1},jn=e=>{const t=[];for(const s of e.getVariableDeclarations()){if(!s.isExported())continue;const r=s.getInitializer();if(r?.getKind()!==u.CallExpression||!Mn(r.getExpression()))continue;const n=s.getNameNode();if(!i.isIdentifier(n))throw J(n,"defineEnv exports must be plain named exports (no destructuring)");t.push({exportName:n.getText()})}return t},zn=(e,t)=>{const s=d(t,Cn);if(!E(s))return;const r=e.getSourceFile(s)??e.addSourceFileAtPath(s),n=jn(r);if(n.length!==0){if(n.length>1)throw J(r,`lunora/env.ts declares ${n.length.toString()} defineEnv() contracts (${n.map(o=>o.exportName).join(", ")}); exactly one is allowed`);return n[0]}},qn=new Set(["defineExportSink","r2Sink","webhookExportSink"]),Bn=e=>{const t=e.getExpression();if(!i.isIdentifier(t))return;const s=t.getText();return qn.has(s)?s:void 0},Un=e=>{const t=[],s=[];for(const r of e.getProperties()){if(i.isSpreadAssignment(r))return{analyzable:!1,emptyKeys:[],presentKeys:[]};if(i.isPropertyAssignment(r)){const n=r.getName();t.push(n);const o=r.getInitializer();o&&i.isStringLiteral(o)&&o.getLiteralText()===""&&s.push(n);continue}(i.isShorthandPropertyAssignment(r)||i.isMethodDeclaration(r)||i.isGetAccessorDeclaration(r))&&t.push(r.getName())}return{analyzable:!0,emptyKeys:s,presentKeys:t}},Vn=(e,t)=>{const s=[];for(const r of g(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r),o=p(t,r);for(const a of n.getDescendantsOfKind(u.CallExpression)){const c=Bn(a);if(c===void 0)continue;const l=a.getArguments()[0],m=l&&i.isObjectLiteralExpression(l)?Un(l):{analyzable:!1,emptyKeys:[],presentKeys:[]};s.push({analyzable:m.analyzable,emptyKeys:m.emptyKeys,factory:c,file:o,line:a.getStartLineNumber(),presentKeys:m.presentKeys})}}return s},Wn=new Map([["dbRateLimit",2],["rateLimit",2],["verifyTurnstileMiddleware",0]]),_n=new Set(["dbRateLimit","rateLimit"]),Gn=e=>{if(!e||!i.isObjectLiteralExpression(e))return!1;const t=e.getProperty("failOpen");return t!==void 0&&i.isPropertyAssignment(t)&&t.getInitializer()?.getKind()===u.TrueKeyword},Hn=e=>{const t=e.getArguments()[1];return t&&i.isStringLiteral(t)?t.getLiteralValue():""},Qn=(e,t)=>{const s=S(e.getExpression());if(s===void 0)return;const r=Wn.get(s);if(r!==void 0)return{callee:s,exportName:x(e),failOpen:Gn(e.getArguments()[r]),file:t,limitName:_n.has(s)?Hn(e):"",line:e.getStartLineNumber()}},Jn=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=Qn(r,t);n&&s.push(n)}return s},Xn=(e,t)=>{const s=[];for(const r of g(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Jn(n,p(t,r)))}return s},Zn=e=>{const t=r=>i.isIdentifier(r)&&r.getText()==="ctx",s=new Set;for(const r of e.getDescendantsOfKind(u.PropertyAccessExpression))t(r.getExpression())&&s.add(r.getName());for(const r of e.getDescendantsOfKind(u.VariableDeclaration)){const n=r.getInitializer(),o=r.getNameNode();if(!(n===void 0||!t(n)||!i.isObjectBindingPattern(o)))for(const a of o.getElements()){const c=a.getPropertyNameNode()?.getText()??a.getName();c&&s.add(c)}}return s},Yn=(e,t)=>{const s=Object.fromEntries(Ee.map(r=>[r.key,!1]));for(const r of g(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r),o=new Set(n.getImportDeclarations().map(c=>c.getModuleSpecifierValue())),a=Zn(n);for(const c of Ee)if(!s[c.key]){if(o.has(c.moduleSpecifier)){s[c.key]=!0;continue}c.contextProperty!==void 0&&a.has(c.contextProperty)&&(s[c.key]=!0)}if(Ee.every(c=>s[c.key]))break}return s},ei=["providerSubscriptionId","state"],ti=["providerEventId","processedAt"],ft=(e,t)=>t.every(s=>s in e.shape),si=e=>{const t=e.find(r=>r.name==="subscriptions"),s=e.find(r=>r.name==="events");return t!==void 0&&s!==void 0&&ft(t,ei)&&ft(s,ti)},ri=(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")}),ni=e=>i.isIdentifier(e)&&e.getText()==="ctx",ii=e=>{if(!i.isPropertyAccessExpression(e)||e.getName()!=="boolean")return!1;const t=e.getExpression();return i.isPropertyAccessExpression(t)&&t.getName()==="flags"&&ni(t.getExpression())},oi=e=>{if(e?.getKind()===u.TrueKeyword)return!0;if(e?.getKind()===u.FalseKeyword)return!1},ai=(e,t)=>{if(!ii(e.getExpression()))return;const[s,r]=e.getArguments();if(!s||!(i.isStringLiteral(s)||i.isNoSubstitutionTemplateLiteral(s)))return;const n=s.getLiteralValue(),o=oi(r);if(!(n.length===0||o===void 0))return{defaultValue:o,exportName:x(e),file:t,key:n,line:e.getStartLineNumber()}},ci=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=ai(r,t);n&&s.push(n)}return s},ui=(e,t)=>{const s=[];for(const r of g(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...ci(n,p(t,r)))}return s},li=e=>{const t=e.getExpression();return i.isPropertyAccessExpression(t)&&t.getName()==="withGeoIndex"},di=e=>{const t=e.getArguments()[0];return t&&i.isStringLiteral(t)?t.getLiteralText():""},gi=(e,t)=>{const s=[];for(const r of g(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r),o=p(t,r);for(const a of n.getDescendantsOfKind(u.CallExpression))li(a)&&s.push({file:o,indexName:di(a),line:a.getStartLineNumber()})}return s},pi=new Set(["delete","get","head","options","patch","post","put"]),fi=new Set(["handler","stream"]),mi=new Set(["runAction","runMutation"]),hi=new Set(["delete","insert","insertManyUnsafe","patch","replace"]),_=(e,t)=>e!==void 0&&i.isIdentifier(e)&&e.getText()===t,mt=e=>e!==void 0&&(i.isArrowFunction(e)||i.isFunctionExpression(e))?e:void 0,ht=(e,t)=>{const s=e.getParameters()[0];if(s===void 0)return;const r=s.getNameNode();if(t)return i.isIdentifier(r)?r.getText():void 0;if(i.isObjectBindingPattern(r)){for(const n of r.getElements())if((n.getPropertyNameNode()?.getText()??n.getNameNode().getText())==="ctx"){const o=n.getNameNode();return i.isIdentifier(o)?o.getText():void 0}}},xt=(e,t)=>{const s=e.getBody(),r=s.getDescendantsOfKind(u.CallExpression);i.isCallExpression(s)&&r.unshift(s);for(const n of r){const o=n.getExpression();if(!i.isPropertyAccessExpression(o))continue;const a=o.getName(),c=o.getExpression();if(mi.has(a)&&_(c,t))return a;if(hi.has(a)&&i.isPropertyAccessExpression(c)&&c.getName()==="db"&&_(c.getExpression(),t))return`db.${a}`}},Et=(e,t)=>{const s=e.getBody();for(const r of s.getDescendantsOfKind(u.PropertyAccessExpression))if(r.getName()==="auth"&&_(r.getExpression(),t))return!0;for(const r of s.getDescendantsOfKind(u.VariableDeclaration)){const n=r.getNameNode();if(!(!i.isObjectBindingPattern(n)||!_(r.getInitializer(),t))){for(const o of n.getElements())if((o.getPropertyNameNode()?.getText()??o.getNameNode().getText())==="auth")return!0}}return!1},xi=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!fi.has(t.getName()))return;let s=t.getExpression();for(;i.isCallExpression(s);){const r=s.getExpression();if(!i.isPropertyAccessExpression(r))return;const n=r.getName();if(pi.has(n)){const o=r.getExpression();return i.isIdentifier(o)&&o.getText()==="httpRoute"?n.toUpperCase():void 0}s=r.getExpression()}},Ei=(e,t)=>{const s=e.getExpression();if(i.isIdentifier(s)&&s.getText()==="httpAction"){const c=mt(e.getArguments()[0]),l=c&&ht(c,!0);if(!c||l===void 0)return;const m=xt(c,l);return m===void 0?void 0:{exportName:x(e),file:t,kind:"httpAction",line:e.getStartLineNumber(),readsAuth:Et(c,l),sideEffect:m}}const r=xi(e);if(r===void 0)return;const n=mt(e.getArguments()[0]),o=n&&ht(n,!1);if(!n||o===void 0)return;const a=xt(n,o);return a===void 0?void 0:{exportName:x(e),file:t,kind:"httpRoute",line:e.getStartLineNumber(),method:r,readsAuth:Et(n,o),sideEffect:a}},yi=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=Ei(r,t);n&&s.push(n)}return s},$i=(e,t)=>{const s=[];for(const r of g(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...yi(n,p(t,r)))}return s},Ai=new Set(["btoa","encodeURI","encodeURIComponent","isSafeHeaderValue","Number","parseFloat","parseInt"]),Si=new Set(["append","set"]),be=e=>i.isIdentifier(e)?e.getText():i.isPropertyAccessExpression(e)?e.getName():"",kt=e=>e!==void 0&&(i.isStringLiteral(e)||i.isNoSubstitutionTemplateLiteral(e))?e.getLiteralText():"",yt=(e,t)=>(i.isCallExpression(e)?[e,...e.getDescendantsOfKind(u.CallExpression)]:e.getDescendantsOfKind(u.CallExpression)).some(s=>Ai.has(be(s.getExpression()))&&ps(s,t)),bi=(e,t)=>{if(yt(e,t))return!0;const s=Q(e);return s!==void 0&&yt(s,t)},Se=(e,t)=>gs(e,t)&&!bi(e,t),vi=e=>{if(i.isPropertyAccessExpression(e)&&e.getName()==="headers")return!0;const t=Q(e);return t!==void 0&&i.isNewExpression(t)&&be(t.getExpression())==="Headers"},G=e=>{if(e===void 0)return;if(i.isObjectLiteralExpression(e))return e;const t=Q(e);return t!==void 0&&i.isObjectLiteralExpression(t)?t:void 0},ve=(e,t,s)=>{for(const r of e.getProperties())if(i.isPropertyAssignment(r)){const n=r.getInitializer();n!==void 0&&Se(n,s.requestName)&&s.rows.push({exportName:s.exportName,file:s.relativePath,headerName:kt(r.getNameNode()),line:n.getStartLineNumber(),via:t})}else if(i.isShorthandPropertyAssignment(r)){const n=r.getNameNode();Se(n,s.requestName)&&s.rows.push({exportName:s.exportName,file:s.relativePath,headerName:r.getName(),line:n.getStartLineNumber(),via:t})}else if(i.isSpreadAssignment(r)){const n=G(r.getExpression());n!==void 0&&ve(n,t,s)}},Ct=(e,t)=>{const s=G(e);if(s===void 0)return;const r=s.getProperty("headers");if(r===void 0||!i.isPropertyAssignment(r))return;const n=G(r.getInitializer());n!==void 0&&ve(n,"response-init",t)},Ni=(e,t)=>{const s=be(e.getExpression());if(s==="Response")Ct(e.getArguments()[1],t);else if(s==="Headers"){const r=G(e.getArguments()[0]);r!==void 0&&ve(r,"headers-ctor",t)}},Pi=(e,t)=>{const s=e.getExpression();if(!i.isPropertyAccessExpression(s))return;const r=s.getName(),n=s.getExpression();if(r==="json"&&i.isIdentifier(n)&&n.getText()==="Response"){Ct(e.getArguments()[1],t);return}if(Si.has(r)&&vi(n)){const o=e.getArguments()[1];o!==void 0&&Se(o,t.requestName)&&t.rows.push({exportName:t.exportName,file:t.relativePath,headerName:kt(e.getArguments()[0]),line:o.getStartLineNumber(),via:r==="set"?"headers-set":"headers-append"})}},wi=(e,t)=>{for(const s of e.getDescendantsOfKind(u.NewExpression))Ni(s,t);for(const s of e.getDescendantsOfKind(u.CallExpression))Pi(s,t)},Ii=(e,t)=>{const s=e.getExpression();if(!i.isIdentifier(s)||s.getText()!=="httpAction")return[];const r=is(e.getArguments()[0]);if(r===void 0)return[];const n=r.getParameters()[1];if(n===void 0)return[];const o=n.getNameNode();if(!i.isIdentifier(o))return[];const a=[];return wi(r,{exportName:x(e),relativePath:t,requestName:o.getText(),rows:a}),a},Ti=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression))s.push(...Ii(r,t));return s},Li=(e,t)=>{const s=[];for(const r of g(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Ti(n,p(t,r)))}return s},Kt="identity.ts",Fi=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineIdentity";for(const s of t.getDeclarations())if(i.isImportSpecifier(s))return X(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineIdentity":!1;return!1},Oi=e=>{const t=e.getSymbol();if(!t)return!1;for(const s of t.getDeclarations()){if(!i.isNamespaceImport(s))continue;const r=s.getFirstAncestorByKind(u.ImportDeclaration);return r!==void 0&&X(r.getModuleSpecifierValue())}return!1},Di=e=>{if(i.isIdentifier(e))return Fi(e);if(i.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineIdentity"&&i.isIdentifier(t)&&Oi(t)}return!1},ki=e=>{const t=[];for(const s of e.getVariableDeclarations()){if(!s.isExported())continue;const r=s.getInitializer();if(r?.getKind()!==u.CallExpression||!Di(r.getExpression()))continue;const n=s.getNameNode();if(!i.isIdentifier(n))throw J(n,"defineIdentity exports must be plain named exports (no destructuring)");t.push({exportName:n.getText()})}return t},Ci=(e,t)=>{const s=d(t,Kt);if(!E(s))return;const r=e.getSourceFile(s)??e.addSourceFileAtPath(s),n=ki(r);if(n.length!==0){if(n.length>1)throw J(r,`lunora/identity.ts declares ${n.length.toString()} defineIdentity() contracts (${n.map(o=>o.exportName).join(", ")}); exactly one is allowed`);return n[0]}},Ki=new Set(["auth","context.auth","ctx.auth"]),Ri="userId",Mi=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},ji=(e,t)=>{const s=d(t,Kt);if(!E(s))return;const r=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const n of r.getDescendantsOfKind(u.CallExpression)){if(S(n.getExpression())!=="defineIdentity")continue;const[o]=n.getArguments();return o&&i.isObjectLiteralExpression(o)?Mi(o):void 0}},$t=e=>{if(!(e===void 0||!i.isPropertyAccessExpression(e)||e.getName()!=="identity"))return Ki.has(e.getExpression().getText())?e:void 0},zi=e=>{if(i.isPropertyAccessExpression(e)&&$t(e.getExpression())!==void 0)return e.getName();if(i.isElementAccessExpression(e)&&$t(e.getExpression())!==void 0){const t=e.getArgumentExpression();return t&&i.isStringLiteral(t)?t.getLiteralValue():void 0}},qi=(e,t,s)=>{const r=[];for(const n of e.getDescendants()){const o=zi(n);o!==void 0&&r.push({declared:o===Ri||s.has(o),exportName:x(n),file:t,key:o,line:n.getStartLineNumber()})}return r},Bi=(e,t)=>{const s=ji(e,t);if(s===void 0)return[];const r=[];for(const n of g(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);r.push(...qi(o,p(t,n),s))}return r},Ui=e=>{if(!i.isObjectLiteralExpression(e))return;const t=e.getProperty("key");return t&&i.isPropertyAssignment(t)?t.getInitializer():void 0},Vi=(e,t)=>{if(S(e.getExpression())!=="buildImageDeliveryUrl")return;const s=e.getArguments()[0];if(!s)return;const r=Ui(s);if(!(!r||!w(r)||O(r)))return{exportName:x(e),file:t,line:e.getStartLineNumber()}},Wi=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=Vi(r,t);n&&s.push(n)}return s},_i=(e,t)=>{const s=[];for(const r of g(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Wi(n,p(t,r)))}return s},Gi=new Set(["delete","get","getRaw","getWithMetadata","put"]),Hi=(e,t)=>Z(e,t,{argIndex:0,matchReceiver:s=>s==="ctx.kv"||s.startsWith("ctx.kv."),methods:Gi}),Qi=new Set(["queue","send"]),At=new Set(["bcc","cc","to"]),Ji=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName();if(!Qi.has(t))return;const s=e.getExpression().getText();return s==="ctx.mail"||s==="ctx.email"?t:void 0},Xi=e=>i.isObjectLiteralExpression(e)?e.getProperties().some(t=>{if(i.isShorthandPropertyAssignment(t)){const r=t.getNameNode();return At.has(t.getName())&&w(r)&&!O(r)}if(!i.isPropertyAssignment(t)||!At.has(t.getName()))return!1;const s=t.getInitializer();return s!==void 0&&w(s)&&!O(s)}):!1,Zi=(e,t)=>{const s=Ji(e.getExpression());if(s===void 0)return;const r=e.getArguments()[0];if(!(!r||!Xi(r)))return{exportName:x(e),file:t,line:e.getStartLineNumber(),method:s}},Yi=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=Zi(r,t);n&&s.push(n)}return s},eo=(e,t)=>{const s=[];for(const r of g(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Yi(n,p(t,r)))}return s},to=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"},so=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},ro=e=>{if(!e.isExported())return;const t=e.getInitializer();if(t?.getKind()!==u.CallExpression)return;const s=t;return qs(s.getExpression())?s:void 0},no=e=>{const t=ro(e),s=t===void 0?void 0:so(t);if(s===void 0)return[];const r=e.getNameNode(),n=i.isIdentifier(r)?r.getText():"";return s.getDescendantsOfKind(u.CallExpression).filter(o=>to(o)).map(o=>({exportName:n,file:"lunora/mutators.ts",line:o.getStartLineNumber()}))},io=e=>e.getVariableDeclarations().flatMap(t=>no(t)),oo=(e,t)=>{const s=d(t,zs);if(!E(s))return[];const r=e.getSourceFile(s)??e.addSourceFileAtPath(s);return io(r)},ao=new Set(["delete","get","patch"]),co=new Set(["accountId","authorId","companyId","createdBy","createdById","customerId","groupId","memberId","organizationId","orgId","ownerId","projectId","teamId","tenantId","userId","workspaceId"]),uo=new Set(["auth","identity","session","user"]),lo=new Set([u.EqualsEqualsEqualsToken,u.EqualsEqualsToken,u.ExclamationEqualsEqualsToken,u.ExclamationEqualsToken]),go=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="normalizeId"||!C(t.getExpression()))return;const s=e.getArguments()[0];return s&&i.isStringLiteral(s)?s.getLiteralText():""},po=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 r=s.getNameNode();return i.isIdentifier(r)?r.getText():void 0},fo=(e,t)=>e.getDescendantsOfKind(u.Identifier).some(s=>s.getText()===t),mo=e=>i.isThrowStatement(e)||i.isReturnStatement(e)||e.getDescendantsOfKind(u.ThrowStatement).length>0||e.getDescendantsOfKind(u.ReturnStatement).length>0,ho=(e,t)=>e.getDescendantsOfKind(u.IfStatement).some(s=>fo(s.getExpression(),t)&&mo(s.getThenStatement())),xo=(e,t)=>{for(const s of e.getDescendantsOfKind(u.CallExpression)){const r=s.getExpression();if(!i.isPropertyAccessExpression(r))continue;const n=r.getName();if(!ao.has(n))continue;const o=r.getExpression();if(!(C(o)||i.isPropertyAccessExpression(o)&&C(o.getExpression())))continue;const a=s.getArguments()[0];if(a!==void 0&&i.isIdentifier(a)&&a.getText()===t)return n}},Eo=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},yo=e=>e.getDescendantsOfKind(u.CallExpression).some(t=>t.getArguments().some(s=>Eo(s)==="ctx")),$o=e=>e.getDescendantsOfKind(u.BinaryExpression).some(t=>lo.has(t.getOperatorToken().getKind())?i.isPropertyAccessExpression(t.getLeft())||i.isPropertyAccessExpression(t.getRight()):!1),Ao=e=>{for(const t of e.getDescendantsOfKind(u.Identifier))if(co.has(t.getText()))return!0;for(const t of e.getDescendantsOfKind(u.PropertyAccessExpression)){const s=t.getExpression();if(i.isIdentifier(s)&&s.getText()==="ctx"&&uo.has(t.getName()))return!0}return yo(e)||$o(e)},So=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!i.isCallExpression(s))return[];const r=K(s);if(r?.kind!=="query"&&r?.kind!=="mutation")return[];const n=It(s);if(n===void 0)return[];const o=r.receiver!==void 0&&Tt(r.receiver,"use","rls"),a=Ao(n),c=new Set,l=[];for(const m of n.getDescendantsOfKind(u.CallExpression)){const $=go(m);if($===void 0)continue;const I=po(m);if(I===void 0||c.has(I)||!ho(n,I))continue;const R=xo(n,I);R!==void 0&&(c.add(I),l.push({exportName:e.getName(),file:t,line:m.getStartLineNumber(),mentionsOwnership:a,sinkMethod:R,table:$,usesRls:o,visibility:r.visibility}))}return l},bo=(e,t)=>{const s=[];for(const r of g(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r),o=p(t,r);for(const a of n.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...So(c,o))}return s},vo=new Set(["accountId","authorId","createdBy","createdById","organizationId","orgId","ownerId","tenantId","updatedBy","userId","workspaceId"]),No=new Set(["insert","insertManyUnsafe","patch","replace"]),Po=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName();if(!No.has(t))return;const s=e.getExpression();if(!i.isPropertyAccessExpression(s)||s.getName()!=="db")return;const r=s.getExpression();return i.isIdentifier(r)&&r.getText()==="ctx"?t:void 0},wo=(e,t)=>{if(t!=="insertManyUnsafe")return i.isObjectLiteralExpression(e)?[e]:[];if(!i.isArrayLiteralExpression(e))return[];const s=[];for(const r of e.getElements())i.isObjectLiteralExpression(r)&&s.push(r);return s},Io=(e,t,s,r)=>{const n=[];for(const o of e.getProperties()){let a,c;i.isPropertyAssignment(o)?(a=o.getName(),c=o.getInitializer()):i.isShorthandPropertyAssignment(o)&&(a=o.getName(),c=o.getNameNode()),!(a===void 0||c===void 0||!vo.has(a))&&w(c)&&!O(c)&&n.push({exportName:x(s),field:a,file:r,line:s.getStartLineNumber(),method:t})}return n},To=(e,t)=>{const s=Po(e.getExpression());if(s===void 0)return[];const r=e.getArguments()[1];return r?wo(r,s).flatMap(n=>Io(n,s,e,t)):[]},Lo=(e,t,s)=>{const r=[];for(const n of e.getDescendantsOfKind(u.CallExpression))for(const o of To(n,t)){const a=s(o.exportName);r.push(a===void 0?o:{...o,visibility:a})}return r},Fo=(e,t,s=[])=>{const r=[],n=new Map(s.map(o=>[`${o.filePath}:${o.exportName}`,o.visibility]));for(const o of g(t)){const a=e.getSourceFile(o)??e.addSourceFileAtPath(o),c=p(t,o);r.push(...Lo(a,c,l=>n.get(`${c}:${l}`)))}return r},Oo=new Set(["createAutumnAdapter","createDodoPaymentsAdapter","createPolarAdapter","createStripeAdapter"]),Do=e=>e&&i.isNumericLiteral(e)?Number(e.getText()):void 0,ko=e=>{const t=e.getProperty("webhookToleranceSeconds");return t&&i.isPropertyAssignment(t)?Do(t.getInitializer()):void 0},Co=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=S(r.getExpression());if(n===void 0||!Oo.has(n))continue;const[o]=r.getArguments(),a=o&&i.isObjectLiteralExpression(o)?ko(o):void 0;s.push({callee:n,exportName:x(r),file:t,line:r.getStartLineNumber(),...a===void 0?{}:{toleranceSeconds:a}})}return s},Ko=(e,t)=>{const s=[];for(const r of g(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Co(n,p(t,r)))}return s},Ro=new Set(["defineQueue","defineWorkflow"]),Mo=new Set(["run","runAction","runMutation","runQuery"]),jo=new Set(["api","internal"]),zo=e=>{const t=e.getExpression();return i.isIdentifier(t)?t.getText():void 0},qo=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 r=s.getInitializer();if(r&&(i.isArrowFunction(r)||i.isFunctionExpression(r)))return r},Rt=(e,t)=>{const s=e.getParameters()[t]?.getNameNode();return s&&i.isIdentifier(s)?s.getText():void 0},Mt=(e,t)=>e===t||e.startsWith(`${t}.`),jt=e=>{const t=e.getDescendantsOfKind(u.PropertyAccessExpression);return i.isPropertyAccessExpression(e)&&t.push(e),t},St=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)},zt=e=>{const t=e.getDescendantsOfKind(u.Identifier).filter(s=>St(s));return i.isIdentifier(e)&&St(e)&&t.push(e),t},Bo=e=>{if(!i.isVariableDeclaration(e))return[];const t=e.getNameNode();return i.isIdentifier(t)?[t.getText()]:t.getDescendantsOfKind(u.BindingElement).map(s=>s.getName())},Uo=e=>{const t=Rt(e,1);if(t===void 0)return[];const s=[`${t}.messages`];for(const r of e.getDescendantsOfKind(u.ForOfStatement)){if(r.getExpression().getText()!==`${t}.messages`)continue;const n=r.getInitializer(),o=i.isVariableDeclarationList(n)?n.getDeclarations()[0]?.getNameNode():void 0;o&&i.isIdentifier(o)&&s.push(`${o.getText()}.body`)}return s},Vo=(e,t,s)=>{const r=t==="workflow"?[`${s}.params`]:Uo(e),n=new Set,o=a=>jt(a).some(c=>r.some(l=>Mt(c.getText(),l)))?!0:zt(a).some(c=>n.has(c.getText()));for(const a of e.getDescendantsOfKind(u.VariableDeclaration)){const c=a.getInitializer();if(c&&o(c))for(const l of Bo(a))n.add(l)}return{names:n,prefixes:r}},Wo=(e,t)=>jt(e).some(s=>t.prefixes.some(r=>Mt(s.getText(),r)))?!0:zt(e).some(s=>t.names.has(s.getText())),_o=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 r=t.at(-1);if(!(r===void 0||!i.isIdentifier(s)||!jo.has(s.getText())||t.length<2))return{exportName:r,file:t.slice(0,-1).join("/")}},Go=(e,t,s)=>{const r=Rt(e,0);if(r===void 0)return[];const n=Vo(e,t,r),o=[];for(const a of e.getDescendantsOfKind(u.CallExpression)){const c=a.getExpression();if(!i.isPropertyAccessExpression(c)||!Mo.has(c.getName())||c.getExpression().getText()!==r)continue;const l=a.getArguments()[1];if(!l||!Wo(l,n))continue;const m=_o(a.getArguments()[0]);m!==void 0&&o.push({dispatchKind:t,file:s,handlerExport:x(a),line:a.getStartLineNumber(),targetExport:m.exportName,targetFile:m.file})}return o},Ho=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=zo(r);if(n===void 0||!Ro.has(n))continue;const o=qo(r);o!==void 0&&s.push(...Go(o,n==="defineQueue"?"queue":"workflow",t))}return s},Qo=(e,t)=>{const s=[];for(const r of g(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Ho(n,p(t,r)))}return s},bt={dbRateLimit:"usesRateLimit",emailGateMiddleware:"usesEmailGate",mask:"usesMask",rateLimit:"usesRateLimit",rls:"usesRls",verifyTurnstile:"usesCaptcha",verifyTurnstileMiddleware:"usesCaptcha"},vt=new Set(["account","credential","member","passkey","session","user"]),Jo=e=>e.replaceAll(/[-_]/gu," ").replaceAll(/([a-z0-9])([A-Z])/gu,"$1 $2").split(" ").filter(Boolean).map(t=>t.toLowerCase()),Xo=e=>{const t=Jo(e).at(-1);if(!t)return!1;const s=t.endsWith("s")?t.slice(0,-1):t;return vt.has(t)||vt.has(s)},Zo=e=>{const t=e.replaceAll(/[^a-z0-9]/giu,"").toLowerCase();return t.endsWith("email")||t.endsWith("emailaddress")},Yo=(e,t)=>{const{objects:s,opaque:r}=Ot(e,t);return Wr(s).some(n=>Zo(n))?!0:r?void 0:!1},Ne=e=>{const t=e.getExpression();if(i.isIdentifier(t))return t.getText();if(i.isPropertyAccessExpression(t))return t.getName()},ea=e=>{const t=e.getArguments()[0];return!t||!i.isObjectLiteralExpression(t)?{usesCaptcha:!1,usesRateLimit:!1}:{usesCaptcha:!!t.getProperty("captcha"),usesRateLimit:!!t.getProperty("rateLimit")}},ta=e=>{if(i.isCallExpression(e))return e;if(!i.isIdentifier(e))return;const t=e.getSourceFile().getVariableDeclaration(e.getText())?.getInitializer();return t&&i.isCallExpression(t)?t:void 0},W={usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},sa=e=>{const t=ta(e),s=t?Ne(t):void 0;if(t&&s==="protectPublic"){const r=ea(t);return{...W,usesCaptcha:r.usesCaptcha,usesRateLimit:r.usesRateLimit}}return s!==void 0&&s in bt?{...W,[bt[s]]:!0}:W},ra=e=>{const t={...W};let s=e;for(;i.isCallExpression(s);){const r=s.getExpression();if(!i.isPropertyAccessExpression(r))break;const n=r.getName()==="use"?s.getArguments()[0]:void 0;if(n){const o=sa(n);t.usesCaptcha||=o.usesCaptcha,t.usesEmailGate||=o.usesEmailGate,t.usesMask||=o.usesMask,t.usesRateLimit||=o.usesRateLimit,t.usesRls||=o.usesRls}s=r.getExpression()}return t},na=new Set(["insert","insertMany","insertManyUnsafe","replace"]),ia=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!na.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 r=e.getArguments()[0];return!r||!(i.isStringLiteral(r)||i.isNoSubstitutionTemplateLiteral(r))?!1:Xo(r.getLiteralText())},oa=new Set(["create","runAfter","runAt","send","sendBatch"]),aa=new Set(["queues","scheduler","workflows"]),ca=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!oa.has(t.getName()))return!1;let s=t.getExpression();for(;i.isCallExpression(s)||i.isElementAccessExpression(s)||i.isPropertyAccessExpression(s);){if(i.isPropertyAccessExpression(s)&&aa.has(s.getName())){const r=s.getExpression();if(i.isIdentifier(r)&&r.getText()==="ctx")return!0}s=s.getExpression()}return!1},ua=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"},qt=new Set(["generateObject","generateText","streamObject","streamText"]),la=e=>{const t=Ne(e);return t!==void 0&&qt.has(t)},da=e=>{const t=Ne(e);if(t===void 0||!qt.has(t))return!1;const s=e.getArguments()[0];return!s||!i.isObjectLiteralExpression(s)||s.getProperties().some(r=>i.isSpreadAssignment(r))?!1:!s.getProperty("maxOutputTokens")},ga=new Set(["log","span","trace"]),pa=new Set(["ai"]),fa=new Set(["email","mail"]),ma=new Set(["ai","browser","fetch","mail","notify","queues","sql","storage","workflows"]),$e=(e,t)=>e.getDescendantsOfKind(u.PropertyAccessExpression).some(s=>{if(!t.has(s.getName()))return!1;const r=s.getExpression();return i.isIdentifier(r)&&r.getText()==="ctx"}),ha=new Set([u.ArrowFunction,u.FunctionDeclaration,u.FunctionExpression,u.GetAccessor,u.MethodDeclaration,u.SetAccessor]),xa=new Set(["every","filter","flatMap","forEach","map","some"]),Ea=new Set(["all","allSettled","race"]),ya=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 r=s.getName();if(xa.has(r))return t;const n=s.getExpression();if(i.isIdentifier(n)&&n.getText()==="Promise"&&Ea.has(r))return t},$a=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(ha.has(t.getKind())){const s=ya(t);if(!s)return!1;t=s;continue}t=t.getParent()}return!1},Aa=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 r=s.getParent();if(!i.isCallExpression(r)||r.getExpression()!==s)return!1;t=r}},Sa=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}},ba=e=>{let t=!1,s=!0;for(const r of e.getDescendantsOfKind(u.PropertyAccessExpression)){if(!ma.has(r.getName()))continue;const n=r.getExpression();if(!i.isIdentifier(n)||n.getText()!=="ctx")continue;const o=Sa(r);o&&(t=!0,!$a(o)&&!Aa(o)&&(s=!1))}return{handlesErrors:t&&s,reachesOutbound:t}},va=e=>e.getDescendantsOfKind(u.ThrowStatement).some(t=>{const s=t.getExpression();if(!i.isNewExpression(s))return!1;const r=s.getExpression();return i.isIdentifier(r)&&r.getText()==="Error"}),Nt="lunora-advisor-exempt",Na=/^[\s*/]+/u,Pa=/[\w-]/u,wa=e=>{const t=(e.getFirstAncestorByKind(u.VariableStatement)??e).getLeadingCommentRanges().map(s=>s.getText()).join(`
6
- `);for(const s of t.split(`
7
- `)){const r=s.replace(Na,"");if(!r.startsWith(Nt))continue;const n=r.slice(Nt.length);if(Pa.test(n.charAt(0)))continue;const o=n.indexOf("--");return{exempt:!0,exemptReason:(o===-1?"":n.slice(o+2).split("*")[0]??"").trim()}}return{exempt:!1,exemptReason:""}},Ia=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}},Ta=(e,t)=>{const s=Ia(t);if(!s)return;if(i.isArrowFunction(s)||i.isFunctionExpression(s)||i.isMethodDeclaration(s))return e;if(!i.isIdentifier(s))return;const r=s.getSourceFile(),n=s.getText(),o=r.getVariableDeclaration(n)?.getInitializer();return o&&(i.isArrowFunction(o)||i.isFunctionExpression(o))?o:r.getFunction(n)},La=e=>{let t=!1,s=!1,r=!1,n=!1,o=!1;for(const l of e.getDescendantsOfKind(u.CallExpression))if(ia(l)&&(o=!0),ca(l)&&(t=!0),ua(l)&&(n=!0),la(l)&&(s=!0),da(l)&&(r=!0),o&&t&&n&&r)break;const{handlesErrors:a,reachesOutbound:c}=ba(e);return{callsMail:$e(e,fa),emitsEvent:$e(e,ga),fanOut:t,handlesErrors:a,reachesOutbound:c,runsAiGeneration:s||$e(e,pa),throwsBareError:va(e),unboundedAiGeneration:r,usesInsertManyUnsafe:n,writesUserTable:o}},Fa=(e,t)=>{const s=e.getInitializer();if(!s||!i.isCallExpression(s))return;const r=K(s);if(!r||r.kind!=="query"&&r.kind!=="mutation"&&r.kind!=="action")return;const n=r.receiver?ra(r.receiver):{usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},o=Ta(e,s);return{...o?La(o):{},...wa(e),...n,analyzableBody:o!==void 0,exportName:e.getName(),file:t,hasEmailArg:Yo(s,r.receiver),kind:r.kind,visibility:r.visibility}},Oa=(e,t)=>{const s=[];for(const r of e.getVariableStatements())if(r.isExported())for(const n of r.getDeclarations()){const o=Fa(n,t);o&&s.push(o)}return s},Da=(e,t)=>{const s=[];for(const r of g(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Oa(n,p(t,r)))}return s},ka=new Set(["dbRateLimit","rateLimit"]),Ca=e=>{if(!i.isObjectLiteralExpression(e))return;const t=e.getProperty("key");return t&&i.isPropertyAssignment(t)?t.getInitializer():void 0},Ka=e=>{const t=e.getArguments()[1];return t&&i.isStringLiteral(t)?t.getLiteralValue():""},Ra=e=>i.isArrowFunction(e)?e.getBody():e,Ma=(e,t)=>{const s=S(e.getExpression());if(s===void 0||!ka.has(s))return;const r=e.getArguments()[2];if(!r)return;const n=Ca(r);if(!n)return;const o=Ra(n);if(!(!w(o)||O(o)))return{callee:s,exportName:x(e),file:t,limitName:Ka(e),line:e.getStartLineNumber()}},ja=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=Ma(r,t);n&&s.push(n)}return s},za=(e,t)=>{const s=[];for(const r of g(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...ja(n,p(t,r)))}return s},qa=new Set(["findFirst","findFirstOrThrow","findMany","get"]),Ba=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!qa.has(t.getName()))return;const s=t.getExpression();if(C(s)){const r=e.getArguments()[0];return r&&i.isStringLiteral(r)?r.getLiteralText():""}if(i.isPropertyAccessExpression(s)&&C(s.getExpression()))return s.getName()},Ua=e=>{let t=e;for(;i.isCallExpression(t);){const s=t.getExpression();if(!i.isPropertyAccessExpression(s))return;if(s.getName()==="query"&&C(s.getExpression())){const r=t.getArguments()[0];return r&&i.isStringLiteral(r)?r.getLiteralText():""}t=s.getExpression()}},Va=e=>{let t=e;for(;i.isAwaitExpression(t)||i.isParenthesizedExpression(t)||i.isNonNullExpression(t)||i.isAsExpression(t);)t=t.getExpression();return t},Bt=(e,t=!1)=>{const s=Va(e);if(i.isIdentifier(s)){if(t)return;const r=Q(s);return r===void 0?void 0:Bt(r,!0)}if(i.isCallExpression(s))return Ba(s)??Ua(s)},Wa=e=>{const t=e.getBody();if(!i.isBlock(t))return[t];const s=[];for(const r of e.getDescendantsOfKind(u.ReturnStatement)){const n=r.getFirstAncestor(a=>i.isArrowFunction(a)||i.isFunctionExpression(a)||i.isFunctionDeclaration(a)),o=r.getExpression();n===e&&o!==void 0&&s.push(o)}return s},_a=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!i.isCallExpression(s))return[];const r=K(s);if(r?.kind!=="query")return[];const n=It(s);if(n===void 0)return[];const o=r.receiver!==void 0&&os(r.receiver,"output"),a=r.receiver!==void 0&&Tt(r.receiver,"use","mask"),c=new Set,l=[];for(const m of Wa(n)){const $=Bt(m);$===void 0||c.has($)||(c.add($),l.push({exportName:e.getName(),file:t,line:m.getStartLineNumber(),table:$,usesMask:a,usesOutput:o,visibility:r.visibility}))}return l},Ga=(e,t)=>{const s=[];for(const r of g(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r),o=p(t,r);for(const a of n.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(..._a(c,o))}return s},Ha=new Set(["findFirst","findFirstOrThrow","findMany"]),Qa=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!Ha.has(t.getName()))return;const s=t.getExpression();if(i.isPropertyAccessExpression(s)&&s.getName()==="db"||i.isIdentifier(s)&&s.getText()==="db"){const r=e.getArguments()[0];return{options:e.getArguments()[1],table:r&&i.isStringLiteral(r)?r.getLiteralText():""}}if(i.isPropertyAccessExpression(s)){const r=s.getExpression();if(i.isPropertyAccessExpression(r)&&r.getName()==="db"||i.isIdentifier(r)&&r.getText()==="db")return{options:e.getArguments()[0],table:s.getName()}}},Ja=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},Xa=(e,t)=>{if(!e||!i.isObjectLiteralExpression(e))return;const s=e.getProperty(t);return s&&i.isPropertyAssignment(s)?s.getInitializer():void 0},Za=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer(),r=s&&i.isCallExpression(s)?K(s):void 0;if(!r)return[];const n=[];for(const o of e.getDescendantsOfKind(u.CallExpression)){const a=Qa(o);if(a===void 0)continue;const c=Ja(Xa(a.options,"with"));c.length!==0&&n.push({exportName:e.getName(),file:t,line:o.getStartLineNumber(),parentTable:a.table,relations:c,visibility:r.visibility})}return n},Ya=(e,t)=>{const s=[];for(const r of g(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r),o=p(t,r);for(const a of n.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...Za(c,o))}return s},H=e=>{if(i.isStringLiteral(e)||i.isNoSubstitutionTemplateLiteral(e))return e.getLiteralText();if(i.isBinaryExpression(e)&&e.getOperatorToken().getKind()===u.PlusToken){const t=H(e.getLeft()),s=H(e.getRight());return t!==void 0&&s!==void 0?t+s:void 0}},ec=e=>{let t=e,s=t.getParent();for(;s!==void 0&&i.isBinaryExpression(s)&&s.getOperatorToken().getKind()===u.PlusToken;)t=s,s=t.getParent();return t!==e&&H(t)!==void 0},tc=/(?:^|\/)__tests__\//u,sc=/\.(?:spec|test)$/u,rc=e=>tc.test(e)||sc.test(e),nc=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()===u.EqualsToken)return t.getLeft().getText()}},ic=(e,t,s)=>er(e)?!rc(s)&&tr(nc(t)):!0,oc=(e,t)=>{const s=[],r=[...e.getDescendantsOfKind(u.BinaryExpression),...e.getDescendantsOfKind(u.StringLiteral),...e.getDescendantsOfKind(u.NoSubstitutionTemplateLiteral)],n=new Set;for(const o of r){if(ec(o))continue;const a=H(o);if(a===void 0)continue;const c=Zs(a);if(c===void 0||!ic(c,o,t))continue;const l=o.getStartLineNumber(),m=`${String(l)}:${c}`;n.has(m)||(n.add(m),s.push({file:t,kind:c,line:l,preview:Ys(a)}))}return s},ac=(e,t)=>{const s=[];for(const r of g(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...oc(n,p(t,r)))}return s},cc=new Set(["findFirst","findFirstOrThrow","findMany"]),uc=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!cc.has(t.getName()))return;const s=t.getExpression();if(i.isPropertyAccessExpression(s)&&s.getName()==="db"||i.isIdentifier(s)&&s.getText()==="db"){const r=e.getArguments()[0];return{options:e.getArguments()[1],table:r&&i.isStringLiteral(r)?r.getLiteralText():""}}if(i.isPropertyAccessExpression(s)){const r=s.getExpression();if(i.isPropertyAccessExpression(r)&&r.getName()==="db"||i.isIdentifier(r)&&r.getText()==="db")return{options:e.getArguments()[0],table:s.getName()}}},lc=(e,t)=>{if(!e||!i.isObjectLiteralExpression(e))return;const s=e.getProperty(t);return s&&i.isPropertyAssignment(s)?s.getInitializer():void 0},dc=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer(),r=s&&i.isCallExpression(s)?K(s):void 0;if(!r)return[];const n=[];for(const o of e.getDescendantsOfKind(u.CallExpression)){const a=uc(o);if(a===void 0)continue;const c=lc(a.options,"includeDeleted");if(c===void 0)continue;const l=i.isTrueLiteral(c),m=!l&&w(c);!l&&!m||n.push({exportName:e.getName(),file:t,fromArgs:m,hardcodedTrue:l,line:o.getStartLineNumber(),table:a.table,visibility:r.visibility})}return n},gc=(e,t)=>{const s=[];for(const r of g(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r),o=p(t,r);for(const a of n.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...dc(c,o))}return s},pc=new Set(["query","unsafe"]),fc=e=>{if(!i.isPropertyAccessExpression(e)||!pc.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"},mc=e=>i.isBinaryExpression(e)||i.isTemplateExpression(e),hc=e=>e.getFirstAncestorByKind(u.VariableDeclaration)?.getName()??"<module>",xc=(e,t)=>{if(!fc(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!mc(s)))return{exportName:hc(e),file:t,line:s.getStartLineNumber()}},Ec=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=xc(r,t);n&&s.push(n)}return s},yc=(e,t)=>{const s=[];for(const r of g(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Ec(n,p(t,r)))}return s},$c=new Set(["createMultipartUpload","delete","download","generateUploadUrl","get","getMetadata","getPresignedUrl","getSignedUrl","getUrl","head","put","resumeMultipartUpload","store","upload"]),Ac=(e,t,s=[])=>{const r=new Map(s.map(n=>[`${n.filePath}:${n.exportName}`,n.visibility]));return Z(e,t,{argIndex:0,matchReceiver:n=>n==="ctx.storage"||n.startsWith("ctx.storage."),methods:$c,requireUnmodifiedReach:!0}).map(n=>{const o=r.get(`${n.file}:${n.exportName}`);return o===void 0?n:{...n,visibility:o}})},Sc=new Map([["generateUploadUrl",1],["getPresignedUrl",1],["getSignedUrl",1],["store",2],["upload",2]]),bc=e=>e&&i.isNumericLiteral(e)?Number(e.getText()):void 0,vc=e=>{if(e===void 0)return{analyzable:!0,presentKeys:[]};if(!i.isObjectLiteralExpression(e))return{analyzable:!1,presentKeys:[]};const t=[];let s,r=!1;for(const n of e.getProperties()){if(i.isSpreadAssignment(n)){r=!0;continue}if(i.isPropertyAssignment(n)){const o=n.getName();t.push(o),o==="expiresInSeconds"&&(s=bc(n.getInitializer()));continue}(i.isShorthandPropertyAssignment(n)||i.isMethodDeclaration(n))&&t.push(n.getName())}return{analyzable:!r,expiresInSeconds:s,presentKeys:t}},Nc=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName(),s=Sc.get(t);if(s===void 0)return;const r=e.getExpression().getText();return r==="ctx.storage"||r.startsWith("ctx.storage.")?{method:t,optionsIndex:s}:void 0},Pc=(e,t)=>{const s=Nc(e.getExpression());if(s!==void 0)return{exportName:x(e),file:t,line:e.getStartLineNumber(),method:s.method,...vc(e.getArguments()[s.optionsIndex])}},wc=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=Pc(r,t);n&&s.push(n)}return s},Ic=(e,t)=>{const s=[];for(const r of g(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...wc(n,p(t,r)))}return s},Tc=new Set(["RegisteredAction","RegisteredMutation","RegisteredQuery"]),Pe=e=>{const t=e.getType(),s=t.getAliasSymbol()?.getName()??t.getSymbol()?.getName();return s!==void 0&&Tc.has(s)?s:void 0},Ut=e=>{const t=e.getInitializer();return t===void 0?!1:i.isCallExpression(t)||i.isIdentifier(t)||i.isPropertyAccessExpression(t)},Vt={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."},Lc={cause:"the binding is exported by a separate `export { … }` statement, and codegen reads the `export` keyword on the declaration itself",remediation:"Move the keyword onto the declaration and drop the separate export statement."},we=(e,t,s,r,n)=>({cacheKey:`procedure_not_registered:${e}:${t}`,categories:["SCHEMA"],description:"Codegen registers an export only when the declaration carries `export` and its initializer is literally a builder chain. A procedure written any other way exists at runtime but never reaches `_generated/api.ts`, so no caller can address it.",detail:`\`${t}\` in \`${e}\` (line ${r.toString()}) has type \`${s}\` but was not registered — ${n.cause}.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:t,filePath:e,line:r,typeName:s},name:"procedure_not_registered",remediation:`Assign the builder chain directly: \`export const ${t} = query.input({ … }).query(handler);\`. ${n.remediation}`,title:"Procedure exists at runtime but is missing from the generated API"}),Fc=(e,t,s)=>{const r=[];for(const n of e.getVariableStatements().filter(o=>o.isExported()))for(const o of n.getDeclarations()){const a=o.getName();if(s.has(`${t}:${a}`)||!Ut(o))continue;const c=Pe(o);c!==void 0&&r.push(we(t,a,c,o.getStartLineNumber(),Vt))}return r},Oc=(e,t,s)=>{if(s.has(`${t}:default`))return[];const r=[];for(const n of e.getExportAssignments().filter(o=>!o.isExportEquals())){const o=Pe(n.getExpression());o!==void 0&&r.push(we(t,"default",o,n.getStartLineNumber(),Vt))}return r},Dc=(e,t,s)=>{const r=[];for(const n of e.getExportDeclarations().filter(o=>o.getModuleSpecifier()===void 0))for(const o of n.getNamedExports()){const a=o.getAliasNode()?.getText()??o.getName();if(s.has(`${t}:${a}`))continue;const c=o.getLocalTargetDeclarations().find(m=>i.isVariableDeclaration(m));if(c===void 0||!Ut(c))continue;const l=Pe(c);l!==void 0&&r.push(we(t,a,l,o.getStartLineNumber(),Lc))}return r},kc=(e,t,s)=>[...Fc(e,t,s),...Oc(e,t,s),...Dc(e,t,s)],Cc=(e,t,s)=>{const r=new Set(s.map(o=>`${o.filePath}:${o.exportName}`)),n=[];for(const o of g(t)){const a=e.getSourceFile(o);a!==void 0&&n.push(...kc(a,p(t,o),r))}return n.toSorted((o,a)=>o.cacheKey.localeCompare(a.cacheKey))},Kc=new Set(["when","where"]),Ae=new Set(["definePolicy","defineShape"]),Rc=e=>{if(!i.isCallExpression(e))return;const t=e.getExpression();if(i.isPropertyAccessExpression(t)){const r=t.getName();return Ae.has(r)?r:void 0}if(!i.isIdentifier(t))return;for(const r of t.getSymbol()?.getDeclarations()??[])if(i.isImportSpecifier(r)){const n=r.getNameNode().getText();return Ae.has(n)?n:void 0}const s=t.getText();return Ae.has(s)?s:void 0},Mc=e=>i.isObjectLiteralExpression(e)&&e.getProperties().length===0,Wt=e=>{if(e!==void 0){if(i.isReturnStatement(e)&&e.getExpression()===void 0||e.getKind()===u.UndefinedKeyword||e.getText()==="undefined")return"undefined";if(Mc(e))return"empty-object";if(i.isParenthesizedExpression(e))return Wt(e.getExpression())}},_t=e=>e.getAncestors().find(t=>i.isArrowFunction(t)||i.isFunctionExpression(t)||i.isFunctionDeclaration(t)),Gt=e=>e.getDescendantsOfKind(u.ReturnStatement).filter(t=>_t(t)===e),Ht=e=>e.getDescendantsOfKind(u.ConditionalExpression).filter(t=>_t(t)===e),jc=e=>{const t=Gt(e);return t.length>1?!0:t.some(s=>s.getFirstAncestorByKind(u.IfStatement)!==void 0)||Ht(e).length>0},zc=e=>{const t=[],s=e.getBody();i.isBlock(s)||t.push(s);for(const r of Gt(e)){const n=i.isReturnStatement(r)?r.getExpression():void 0;t.push(n??r)}for(const r of Ht(e))t.push(r.getWhenTrue(),r.getWhenFalse());return t},qc=e=>{for(const t of e.getAncestors())if(i.isVariableDeclaration(t)){const s=t.getNameNode();if(i.isIdentifier(s))return s.getText()}return"<anonymous>"},Bc=(e,t,s)=>{if(!i.isCallExpression(e))return[];const[r]=e.getArguments();if(!r||!i.isObjectLiteralExpression(r))return[];const n=[];for(const o of r.getProperties()){if(!i.isPropertyAssignment(o)||!Kc.has(o.getName()))continue;const a=o.getInitializer();if(!(!a||!(i.isArrowFunction(a)||i.isFunctionExpression(a)))&&jc(a))for(const c of zc(a)){const l=Wt(c);l!==void 0&&n.push({exportName:qc(e),file:s,form:l,key:o.getName(),line:c.getStartLineNumber(),owner:t})}}return n},Uc=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=Rc(r);n!==void 0&&s.push(...Bc(r,n,t))}return s},Vc=(e,t)=>{const s=[];for(const r of g(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Uc(n,p(t,r)))}return s},Wc=new Set(["query","upsert","upsertMany"]),_c=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName();if(Wc.has(t))return e.getExpression().getText()==="ctx.vectors"?t:void 0},Gc=e=>{if(!i.isObjectLiteralExpression(e))return;const t=e.getProperty("namespace");return t&&i.isPropertyAssignment(t)?t.getInitializer():void 0},Hc=(e,t)=>{const s=_c(e.getExpression());if(s===void 0)return;const r=e.getArguments()[1];if(!r)return;const n=Gc(r);if(!(!n||!w(n)||O(n)))return{exportName:x(e),file:t,line:e.getStartLineNumber(),method:s}},Qc=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=Hc(r,t);n&&s.push(n)}return s},Jc=(e,t)=>{const s=[];for(const r of g(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Qc(n,p(t,r)))}return s},Xc=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"},Zc=e=>{const t=e.getArguments()[0];return t&&i.isStringLiteral(t)?t.getLiteralText():""},Yc=(e,t)=>{const s=[];for(const r of g(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r),o=p(t,r);for(const a of n.getDescendantsOfKind(u.CallExpression)){if(!Xc(a))continue;const c=nr(a);c!==""&&s.push({exportName:c,file:o,line:a.getStartLineNumber(),workflow:Zc(a)})}}return s},eu=".lunora-schema.json",y=(e,t)=>{E(e)&&wt(e,"utf8")===t||es(e,t,"utf8")},P=(e,t)=>{if(t===""){ts(e,{force:!0});return}y(e,t)},tu=e=>{const t=d(e,"package.json");if(E(t))try{const s=JSON.parse(wt(t,"utf8"));return typeof s.version=="string"&&s.version!==""?s.version:void 0}catch{return}},su=()=>{const e=process.env.LUNORA_CODEGEN_TIMING;return e!==void 0&&e!==""},ru=e=>{let t=E(e)?e:he(e);for(;t&&t!==he(t);){const s=d(t,"tsconfig.json");if(E(s))return s;t=he(t)}},Pt=e=>e.replaceAll("\\","/"),nu=(e,t)=>{const s=new Map,r=new Map,n=new Map;for(const o of e)s.set(o.name,`workflow "${o.exportName}"`),r.set(o.bindingName,`workflow "${o.exportName}"`),n.set(o.className,`workflow "${o.exportName}"`);for(const o of t){const a=s.get(o.name);if(a!==void 0)throw new F("DUPLICATE_WORKFLOW_NAME",`Duplicate deployed name "${o.name}": produced by both ${a} and agent "${o.exportName}". Workflow and agent names share the same wrangler workflows[] array and must be unique together.`,{status:500});const c=r.get(o.bindingName);if(c!==void 0)throw new F("DUPLICATE_WORKFLOW_BINDING",`Duplicate binding "${o.bindingName}": produced by both ${c} and agent "${o.exportName}". Workflow and agent bindings share the same wrangler workflows[] array and must be unique together.`,{status:500});const l=n.get(o.className);if(l!==void 0)throw new F("DUPLICATE_WORKFLOW_CLASS",`Duplicate generated class "${o.className}": produced by both ${l} and agent "${o.exportName}". Workflow and agent export names must yield unique generated class names.`,{status:500})}},iu=(e,t,s)=>{if(s&&e.length>0){const o=e.map(a=>`"${a.exportName}"`).join(", ");throw new F("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) (${o}), codegen can't verify none of them replicate a table that policy masks — inline every table and column as literal keys so codegen can verify it, or remove the affected shape(s).`,{status:422})}const r=new Map;for(const o of t.columns){const a=r.get(o.table)??[];a.push(o.column),r.set(o.table,a)}const n=t.columns.length>0;for(const o of e){if(o.table===void 0){if(n)throw new F("MASK_UNSUPPORTED",`defineShape "${o.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 "${o.exportName}"'s \`table\` to a plain string literal so codegen can verify it, or remove the mask(s) on the table it targets.`,{status:422});continue}const a=r.get(o.table);if(a===void 0)continue;const c=a.map(l=>`"${l}"`).join(", ");throw new F("MASK_UNSUPPORTED",`defineShape "${o.exportName}" replicates table "${o.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})}},ou=e=>{const t=ru(e);return t?new at({skipAddingFilesFromTsConfig:!1,tsConfigFilePath:t,useInMemoryFileSystem:!1}):new at({skipAddingFilesFromTsConfig:!0,useInMemoryFileSystem:!1})},Qu=(e,t)=>{const s=g(t),r=d(t,"schema.ts");E(r)&&s.push(r);for(const c of s){const l=e.getSourceFile(c);l===void 0?e.addSourceFileAtPath(c):l.refreshFromFileSystemSync()}const n=new Set(s.map(c=>Pt(c))),o=Pt(t),a=`${o}/`;for(const c of e.getSourceFiles()){const l=c.getFilePath();(l===o||l.startsWith(a))&&!n.has(l)&&e.removeSourceFile(c)}},Ju=e=>{const t=su(),s=t?xe.now():0,r=d(e.projectRoot,e.lunoraDirectory??"lunora"),n=d(r,"schema.ts");if(!E(n))throw new F("INTERNAL",`schema.ts not found at ${n}`);const o=e.project??ou(r);dr(cs);const a=Xs(o,n,e.projectRoot);if(!e.dryRun){const f=d(r,"_generated"),M=d(f,"dataModel.ts"),j=d(f,"server.ts");if(!E(M)||!E(j)){const V=(lt(e.projectRoot)??new Set).has("lunorash"),nt=ct(a,V),it=ut({schema:a,useUmbrella:V});E(f)||ot(f,{recursive:!0}),y(M,nt),y(j,it),o.createSourceFile(M,nt,{overwrite:!0}),o.createSourceFile(j,it,{overwrite:!0})}}const c=as(o,r),l=Ds(o,r),m=js(o,r),$=sr(o,r),I=Bs(o,r),R=Ci(o,r),Ie=zn(o,r),v=ir(o,r),D=_s(o,r),N=us(o,r);nu(v,N);const Y=xs(o,r,v,N),k=hs(o,r),z=e.lint===!1?void 0:ns({adminRoutes:vr(o,r),aiRawRuns:Ir(o,r),aiToolSideEffects:Mr(o,r),argumentDerivedFetches:Br(o,r),argumentValidators:en(o,r),authApiCalls:ms(o,r),authConfigs:gn(o,r),browserUrlAccesses:xn(o,r),configCalls:Nn(o,r),containerKeyAccesses:wn(o,r),containerOverrides:kn(o,r),containers:k,exportSinks:Vn(o,r),failOpenGuards:Xn(o,r),flagSecurityDefaults:ui(o,r),geoIndexUsages:gi(o,r),httpActionGuards:$i(o,r),httpHeaderWrites:Li(o,r),identityClaimReads:Bi(o,r),imageDeliveryUrlAccesses:_i(o,r),inserts:ks(o,r),kvKeyAccesses:Hi(o,r),mailRecipientAccesses:eo(o,r),maskProcedures:Cs(o,r),maskStrategies:Ks(o,r),mutatorWrites:oo(o,r),nondeterministicCalls:Us(o,r),normalizeIdAuthorizations:bo(o,r),notifyCalls:Ws(o,r),notifyConfig:Vs(o,r),ownerFieldWrites:Fo(o,r,c),unrestrictedWhereBranches:Vc(o,r),paymentWebhooks:Ko(o,r),privilegedDispatches:Qo(o,r),procedureProtections:Da(o,r),queries:fs(o,r),queues:D,r2sqlCalls:Gs(o,r),ratelimitKeySelectors:za(o,r),rawRowReturns:Ga(o,r),relationLoads:Ya(o,r),rlsProcedures:Hs(o,r),schema:a,secretLiterals:ac(o,r),shapes:$,softDeleteReads:gc(o,r),sqlInterpolations:yc(o,r),storageKeyAccesses:Ac(o,r,c),storageUploads:Ic(o,r),vectorNamespaceAccesses:Jc(o,r),workflowCalls:Yc(o,r),workflows:v,wranglerVariables:e.wranglerVariables}),Te=z===void 0?[]:[...ss(z,{source:"static"}),...Cc(o,r,c)],Qt=Qs(o,r),Le=Rs(o,r);iu($,Le,Ms(o,r));const ee=rr(o,r),Jt=Yn(o,r),Fe=gr(Jt,pr(e.projectRoot,e.target)),A=Fe.usage,te=A.ai,se=A.payments,Oe=A.kv,De=A.access,re=E(d(r,"flags.ts")),Xt=re?Os(o,r):[],ne=E(d(r,"notify.ts")),ie=A.hyperdrive,oe=Js(o,r),Zt=oe.usesSandboxBrowser||oe.usesSandboxContainer,ae=A.browser||oe.usesSandboxBrowser,ce=A.images,ue=A.analytics,ke=A.pipelines,le=A.r2sql,de=A.x402,Ce=lt(e.projectRoot),T=Ce??new Set,q=ri(A,{containerCount:k.length,cronCount:Y.length,dependencies:T,hasPaymentTables:si(a.tables),queueCount:D.length,storageColumnCount:Object.keys(Es(a)).length,storageRuleCount:ee.rules.length,vectorIndexCount:a.vectorIndexes.length,workflowCount:v.length}),L=T.has("lunorash");hr(a,Ce);const Ke=t?xe.now():0,Re=ct(a,L),Me=ys({agents:N,functions:c,httpRoutes:l,mutators:I,useUmbrella:L,workflows:v}),je=ut({agents:N,containers:k,env:Ie,hasAccessFacade:De,hasAi:te,hasAnalytics:ue,hasBrowser:ae,hasFlags:re,hasHyperdrive:ie,hasImages:ce,hasKv:Oe,hasNotify:ne,hasPayments:se,hasPipelines:ke,hasR2sql:le,hasX402:de,identity:R,queues:D,schema:a,storageRuleBuckets:ee.rules.map(f=>f.bucket),useUmbrella:L,workflows:v}),ze=$s({agents:N,functions:c,migrations:m,mutators:I,shapes:$,useUmbrella:L,usesSandbox:Zt}),ge=fr(a,m.map(f=>f.id)),qe=As({advisories:Te,advisorProcedures:z?.procedureProtections??[],agents:N,containers:k,env:Ie,flagKeys:Xt,hasAccessFacade:De,hasAi:te,hasAnalytics:ue,hasBrowser:ae,hasFlags:re,hasHyperdrive:ie,hasImages:ce,hasKv:Oe,hasNotify:ne,hasPayments:se,hasPipelines:ke,hasR2sql:le,hasX402:de,maskMetadata:Le,mutators:I,queues:D,rlsMetadata:Qt,schema:a,schemaSnapshot:ge,shapes:$,storageRules:ee,studioFeatures:q,useUmbrella:L,workflows:v}),Be=Ss($,T.has("@lunora/db"),L),Ue=bs(k,a.jurisdiction),Ve=vs(v),We=Ns(N),_e=Ps(D),Ge=ws(Y),He=Is(a.vectorIndexes),B=Ts(a,L),Qe=Ls(T.has("@lunora/seed")),U=e.apiSpec??"openapi",pe=U==="openapi"||U==="both",fe=U==="openrpc"||U==="both",Je=or({emailAgents:N.filter(f=>f.onEmail===!0).map(f=>({bindingName:f.bindingName,exportName:f.exportName})),hasAccess:T.has("@lunora/cloudflare-access"),hasAi:te,hasAnalytics:ue,hasAuth:T.has("@lunora/auth"),hasBrowser:ae,hasFramework:T.has("@lunora/astro")||T.has("@lunora/svelte")||T.has("@lunora/vue"),hasGlobal:a.tables.some(f=>f.shardMode==="global"&&f.globalBackend!=="hyperdrive"),hasHyperdrive:ie,hasHyperdriveGlobal:a.tables.some(f=>f.shardMode==="global"&&f.globalBackend==="hyperdrive"),hasImages:ce,hasKv:q.kv,hasNotify:ne,hasPayments:se,hasR2sql:le,hasQueue:D.some(f=>f.mode==="push"),hasScheduler:q.scheduler,hasStorage:q.storage,hasVectors:a.vectorIndexes.length>0,hasWorkflow:v.length>0,hasX402:de,identity:R,jurisdiction:a.jurisdiction,useUmbrella:L,voiceAgents:N.filter(f=>f.voice===!0&&f.voiceBindingName!==void 0).map(f=>({bindingName:f.voiceBindingName,exportName:f.exportName})),wantsOpenApi:pe,wantsOpenRpc:fe}),Xe=tu(e.projectRoot),Ze=ar({functions:c,httpRoutes:l,version:Xe}),Ye=ur({functions:c,version:Xe}),et=`${JSON.stringify(Ze,void 0,2)}
8
- `,tt=`${JSON.stringify(Ye,void 0,2)}
9
- `,st=cr(Ze),rt=lr(Ye),me=d(r,eu),Yt=E(me),h=d(r,"_generated");if(e.dryRun||(E(h)||ot(h,{recursive:!0}),y(d(h,"app.ts"),Je),y(d(h,"dataModel.ts"),Re),y(d(h,"api.ts"),Me),y(d(h,"server.ts"),je),y(d(h,"functions.ts"),ze),y(d(h,"shard.ts"),qe),y(d(h,"crons.ts"),Ge),y(d(h,"vectors.ts"),He),y(d(h,"drizzle.global.ts"),B.global),y(d(h,"drizzle.shard.ts"),B.shard),P(d(h,"containers.ts"),Ue),P(d(h,"workflows.ts"),Ve),P(d(h,"agents.ts"),We),P(d(h,"queues.ts"),_e),P(d(h,"seed.ts"),Qe),P(d(h,"collections.ts"),Be),P(d(h,"openapi.json"),pe?et:""),P(d(h,"openapi.ts"),pe?st:""),P(d(h,"openrpc.json"),fe?tt:""),P(d(h,"openrpc.ts"),fe?rt:""),(!Yt||e.updateSchemaBaseline===!0)&&y(me,rs(ge))),t){const f=xe.now(),M=Math.round(f-s),j=Math.round(Ke-s),V=Math.round(f-Ke);console.error(`@lunora/codegen: codegen took ${M.toString()}ms (discovery ${j.toString()}ms, emit ${V.toString()}ms)`)}return{advisories:Te,advisorContext:z,agents:N,containers:k,cronTriggers:Fs(Y),generated:{agents:We,api:Me,app:Je,collections:Be,containers:Ue,crons:Ge,dataModel:Re,drizzleGlobal:B.global,drizzleShard:B.shard,functions:ze,openApi:et,openApiModule:st,openRpc:tt,openRpcModule:rt,queues:_e,seed:Qe,server:je,shard:qe,vectors:He,workflows:Ve},outputDirectory:h,platformDiagnostics:Fe.diagnostics,queues:D,schemaSnapshot:ge,schemaSnapshotPath:me,workflows:v}};export{eu as SCHEMA_SNAPSHOT_FILENAME,ou as createCodegenProject,Qu as refreshCodegenProject,Ju as runCodegen};
@@ -1 +0,0 @@
1
- import{readdirSync as C,lstatSync as $}from"node:fs";import{join as O,extname as j,relative as z,sep as U}from"node:path";import{Node as s,SyntaxKind as V}from"ts-morph";import{t as _}from"./module-specifiers-8FEEiUcv.mjs";import{o as R,p as h}from"./parse-validator-DCrBLhq7.mjs";import{n as M}from"./paths-BmX5O1sG.mjs";const y=new Set(["action","mutation","query","stream"]),P=/\bany\b(?!\s*(?:\?\s*)?:)/u,b=/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|`(?:[^`\\]|\\.)*`/gu,q=/^[A-Za-z_$][\w$]*$/u,B=e=>q.test(e)?e:JSON.stringify(e),H=/\.ts$/u,W=(e,t)=>z(e,t).split(U).join("/").replace(H,""),T={internalAction:"action",internalMutation:"mutation",internalQuery:"query"},J={onConnect:"connect",onDisconnect:"disconnect"},Q=_,N=e=>{const t=e.getSymbol();if(!t)return e.getText();const i=t.getDeclarations();for(const r of i){if(!s.isImportSpecifier(r))continue;const n=r.getImportDeclaration().getModuleSpecifierValue();return Q(n)?r.getNameNode().getText():void 0}},S=(e,t=!1)=>{let i=e;for(;s.isCallExpression(i);){const n=i.getExpression();if(!s.isPropertyAccessExpression(n))return;i=n.getExpression()}if(!s.isIdentifier(i))return;const r=N(i);if(r===void 0){if(t)return;const n=i.getSymbol()?.getValueDeclaration();if(n&&s.isVariableDeclaration(n)){const o=n.getInitializer();return o?S(o,!0):void 0}return}return y.has(r)?"public":T[r]?"internal":void 0},d=(e,t)=>{const i=e.getProperty(t);if(i===void 0||!s.isPropertyAssignment(i))return;const r=i.getInitializer();return r!==void 0&&s.isStringLiteral(r)?r.getLiteralValue():void 0},E=(e,t)=>{const i=e.getProperty(t);if(i===void 0||!s.isPropertyAssignment(i))return;const r=i.getInitializer();return r!==void 0&&s.isNumericLiteral(r)?r.getLiteralValue():void 0},G=e=>{const t=e.getProperty("cache");if(t===void 0||!s.isPropertyAssignment(t))return;const i=t.getInitializer();if(i===void 0||!s.isObjectLiteralExpression(i))return;const r=d(i,"scope"),n=E(i,"maxAge"),o=E(i,"staleWhileRevalidate"),a=d(i,"tag"),c=d(i,"vary"),l={...n===void 0?{}:{maxAge:n},...r==="private"||r==="public"?{scope:r}:{},...o===void 0?{}:{staleWhileRevalidate:o},...a===void 0?{}:{tag:a},...c===void 0?{}:{vary:c}};return Object.keys(l).length===0?void 0:l},K=e=>{if(e===void 0||!s.isObjectLiteralExpression(e))return{};const t=G(e),i=e.getProperty("rest");return i!==void 0&&s.isPropertyAssignment(i)?{...t===void 0?{}:{cache:t},rest:i.getInitializer()?.getText()==="true"}:t===void 0?{}:{cache:t}},Z=e=>{let t=e;for(;s.isCallExpression(t);){const i=t.getExpression();if(!s.isPropertyAccessExpression(i))return;if(i.getName()==="expose")return K(t.getArguments()[0]);t=i.getExpression()}},X=e=>{const t=e.getArguments()[0];if(!t||!s.isObjectLiteralExpression(t))return{};const i=t.getProperty("args");if(!i||!s.isPropertyAssignment(i))return{};const r=i.getInitializer();return!r||!s.isObjectLiteralExpression(r)?{}:h(r)},Y=(e,t)=>{for(const i of[e.getSymbol(),e.getAliasSymbol()])if(i)for(const r of i.getDeclarations()){const n=r.getSourceFile();if(!(n.isInNodeModules()||n.isDeclarationFile())&&n.getFilePath()===t&&(s.isInterfaceDeclaration(r)||s.isTypeAliasDeclaration(r)))return!0}return!1},ee=e=>{const t=[...e.getTypeArguments()];return e.isUnion()&&t.push(...e.getUnionTypes()),e.isIntersection()&&t.push(...e.getIntersectionTypes()),t},I=e=>!e.isObject()||e.isArray()||e.isTuple()||e.getCallSignatures().length>0||e.getConstructSignatures().length>0?!1:e.getStringIndexType()===void 0&&e.getNumberIndexType()===void 0,g=(e,t,i,r=new Set)=>r.has(e)?!1:(r.add(e),Y(e,i)||ee(e).some(n=>g(n,t,i,r))?!0:I(e)?e.getProperties().some(n=>g(n.getTypeAtLocation(t),t,i,r)):!1),te=(e,t)=>{const i=e.getValueDeclaration()??e.getDeclarations()[0];return i&&(s.isPropertySignature(i)||s.isPropertyDeclaration(i))&&i.hasQuestionToken()?!0:t.isUnion()&&t.getUnionTypes().some(r=>r.isUndefined())},ie=8,re=(e,t,i,r,n,o)=>{const a=e.getArrayElementType(),c=a?o(a,t,i,r,n):void 0;if(c!==void 0)return a?.isUnion()?`(${c})[]`:`${c}[]`},ne=(e,t,i,r,n,o)=>{const a=[];for(const c of e.getUnionTypes()){const l=o(c,t,i,r,n);if(l===void 0)return;a.push(l)}return a.join(" | ")},se=(e,t,i,r,n,o)=>{if(!I(e))return;const a=[];for(const c of e.getProperties()){const l=c.getTypeAtLocation(t),m=te(c,l),D=m&&l.isUnion()?l.getUnionTypes().filter(f=>!f.isUndefined()):[l],x=[];for(const f of D){const v=o(f,t,i,r+1,n);if(v===void 0)return;x.push(v)}a.push(`${B(c.getName())}${m?"?":""}: ${x.join(" | ")}`)}return a.length>0?`{ ${a.join("; ")} }`:"{}"},p=(e,t,i,r,n)=>{if(r>ie||n.has(e))return;if(!g(e,t,i))return e.getText(t);const o=new Set(n).add(e);return e.isArray()?re(e,t,i,r,o,p):e.isUnion()?ne(e,t,i,r,o,p):se(e,t,i,r,o,p)},k=e=>{const t=e.getType().getCallSignatures()[0];if(!t)return"unknown";let i=t.getReturnType();const r=(i.getSymbol()??i.getAliasSymbol())?.getName();if(r==="Promise"||r==="AsyncIterable"||r==="AsyncIterableIterator"||r==="AsyncGenerator"){const a=i.getTypeArguments()[0];a&&(i=a)}const n=i.getText(e);if(!n||n==="any"||n==="never"||P.test(n.replaceAll(b,"")))return"unknown";const o=e.getSourceFile().getFilePath();return g(i,e,o)?p(i,e,o,0,new Set)??"unknown":n},Te=e=>{const t=e.getType().getProperty("~standard");if(!t)return;const i=t.getTypeAtLocation(e).getProperty("types");if(!i)return;const r=i.getTypeAtLocation(e).getNonNullableType().getProperty("output");if(!r)return;const n=r.getTypeAtLocation(e),o=n.getText(e);if(!o||o==="any"||o==="never"||P.test(o.replaceAll(b,"")))return;const a=e.getSourceFile().getFilePath();return g(n,e,a)?p(n,e,a,0,new Set):o},oe=e=>{const t=e.getArguments()[0];if(!t||!s.isObjectLiteralExpression(t))return"unknown";const i=t.getProperty("handler");if(!i||!s.isPropertyAssignment(i))return"unknown";const r=i.getInitializer();return!r||!(s.isArrowFunction(r)||s.isFunctionExpression(r))?"unknown":k(r)},ae=e=>{const t=e.getArguments()[0];return!t||!(s.isArrowFunction(t)||s.isFunctionExpression(t))?"unknown":k(t)},ce=e=>{let t={},i=e;for(;s.isCallExpression(i);){const r=i.getExpression();if(!s.isPropertyAccessExpression(r))break;if(r.getName()==="input"){const n=i.getArguments()[0];n&&s.isObjectLiteralExpression(n)&&(t={...h(n),...t})}i=r.getExpression()}return t},le=e=>{let t=e;for(;s.isCallExpression(t);){const i=t.getExpression();if(!s.isPropertyAccessExpression(i))return;if(i.getName()==="output"){const r=t.getArguments()[0];return r&&s.isExpression(r)?R(r):void 0}t=i.getExpression()}},ue=e=>{const t=e.getExpression();if(s.isPropertyAccessExpression(t)){const o=t.getName();if(!y.has(o))return;const a=t.getExpression();if(a.getType().getProperty("__lunoraProcedure"))return{kind:o,receiver:a,visibility:a.getType().getProperty("__lunoraVisibility")?"internal":"public"};const c=S(a);return c?{kind:o,receiver:a,visibility:c}:void 0}if(!s.isIdentifier(t))return;const i=N(t);if(!i)return;if(y.has(i))return{kind:i,visibility:"public"};const r=T[i];if(r)return{kind:r,visibility:"internal"};const n=J[i];if(n)return{kind:"mutation",lifecycle:n,visibility:"internal"}},A=e=>e!==void 0&&(s.isArrowFunction(e)||s.isFunctionExpression(e))?e:void 0,Ne=e=>s.isPropertyAccessExpression(e)&&e.getName()==="db"||s.isIdentifier(e)&&e.getText()==="db",Se=e=>{const t=e.getArguments()[0],i=A(t);if(i!==void 0)return i;if(t===void 0||!s.isObjectLiteralExpression(t))return;const r=t.getProperty("handler");return r!==void 0&&s.isPropertyAssignment(r)?A(r.getInitializer()):void 0},pe=e=>s.isIdentifier(e)?e.getText():s.isPropertyAccessExpression(e)?e.getName():"",Ie=(e,t)=>{let i=e;for(;s.isCallExpression(i);){const r=i.getExpression();if(!s.isPropertyAccessExpression(r))break;if(r.getName()===t)return!0;i=r.getExpression()}return!1},ke=(e,t,i)=>{let r=e;for(;s.isCallExpression(r);){const n=r.getExpression();if(!s.isPropertyAccessExpression(n))break;const o=r.getArguments()[0];if(n.getName()===t&&o!==void 0&&s.isCallExpression(o)&&pe(o.getExpression())===i)return!0;r=n.getExpression()}return!1},w=(e,t=[],i=e)=>{let r;try{r=C(e)}catch{return t}for(const n of r){const o=O(e,n),a=$(o);if(a.isDirectory()){if(n==="_generated"||n==="node_modules")continue;w(o,t,i)}else if(a.isFile()&&j(n)===".ts"){if(n==="schema.ts"&&e===i)continue;t.push(o)}}return t},ge=e=>{const t=ue(e);if(t){if(t.receiver){const i=Z(t.receiver),r=le(t.receiver);return{args:ce(t.receiver),...i?{expose:i}:{},kind:t.kind,...r?{output:r}:{},returnType:ae(e),visibility:t.visibility}}return t.lifecycle?{args:{},kind:t.kind,lifecycle:t.lifecycle,returnType:"void",visibility:t.visibility}:{args:X(e),kind:t.kind,returnType:oe(e),visibility:t.visibility}}},fe=8,u=(e,t=0)=>{if(t>fe)return;if(s.isCallExpression(e))return e;if(s.isParenthesizedExpression(e)||s.isAsExpression(e)||s.isSatisfiesExpression(e)||s.isNonNullExpression(e))return u(e.getExpression(),t+1);if(!s.isIdentifier(e)&&!s.isPropertyAccessExpression(e))return;const i=e.getSymbol()?.getValueDeclaration();return i?F(i,t+1):void 0},F=(e,t)=>{if(s.isVariableDeclaration(e)||s.isPropertyAssignment(e)){const i=e.getInitializer();return i?u(i,t):void 0}if(s.isShorthandPropertyAssignment(e))return u(e.getNameNode(),t);if(s.isBindingElement(e)){const i=e.getPropertyNameNode()?.getText()??e.getName(),r=e.getFirstAncestorByKind(V.VariableDeclaration)?.getInitializer()?.getType().getProperty(i)?.getValueDeclaration();return r?F(r,t+1):void 0}},de=e=>{const t=e.getNameNode();if(s.isObjectBindingPattern(t)){const n=[];for(const o of t.getElements()){const a=u(o.getNameNode());a&&n.push([o.getName(),a])}return n}const i=e.getInitializer(),r=i&&(s.isCallExpression(i)?i:u(i));return r?[[e.getName(),r]]:[]},L=(e,t,i)=>{const r=ge(e);if(r)return{args:r.args,exportName:t,filePath:i,kind:r.kind,returnType:r.returnType,...r.output?{output:r.output}:{},visibility:r.visibility,...r.expose?{expose:r.expose}:{},...r.lifecycle?{lifecycle:r.lifecycle}:{}}},ye=(e,t)=>{const i=[];for(const r of e.getExportAssignments()){if(r.isExportEquals())continue;const n=u(r.getExpression()),o=n?L(n,"default",t):void 0;o&&i.push(o)}return i},me=(e,t)=>{const i=[];for(const r of e.getVariableStatements())if(r.isExported())for(const n of r.getDeclarations())for(const[o,a]of de(n)){const c=L(a,o,t);c&&i.push(c)}return i.push(...ye(e,t)),i},xe=e=>{const t=new Map;for(const i of e){const r=M(i.filePath),n=t.get(r);if(n&&n!==i.filePath)throw Object.assign(new Error(`Namespace collision: "${n}" and "${i.filePath}" both resolve to "${r}". Rename one of the files so the JS-identifier-sanitized names differ. (note: case-insensitive filesystems may also cause this — \`foo\` and \`FOO\` map to the same identifier)`),{code:"NAMESPACE_COLLISION",name:"LunoraError",paths:[n,i.filePath],status:500});t.set(r,i.filePath)}},we=(e,t)=>{const i=w(t),r=[];for(const n of i){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),a=W(t,n);r.push(...me(o,a))}return r.sort((n,o)=>`${n.filePath}:${n.exportName}`.localeCompare(`${o.filePath}:${o.exportName}`)),xe(r),r};export{Ie as chainHasStep,ke as chainUsesWrappedCall,ue as classifyProcedureCall,we as discoverFunctions,A as inlineHandler,Ne as isDatabaseAccessor,w as listLunoraSourceFiles,W as lunoraRelativePath,Se as procedureHandler,Te as resolveStandardSchemaType,k as unwrapHandlerReturn};
@@ -1 +0,0 @@
1
- import"ts-morph";import{y as p}from"./discover-queries-B4Lw0cEr.mjs";import"./discoverFunctions-9GMvSwz7.mjs";export{p as default};
@@ -1 +0,0 @@
1
- import{LunoraError as A}from"@lunora/errors";import{Node as s,SyntaxKind as T}from"ts-morph";import{diagnosticAt as u}from"./CodegenDiagnosticError-DPezpZTz.mjs";import{p as j}from"./parse-validator-DCrBLhq7.mjs";import{createRequire as _}from"node:module";import{join as N}from"node:path";const O=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}},z=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}:{}}),f=e=>{const r=e?._meta??{},t=e?.kind??"unknown",n={column:z(r.column),kind:t};switch(t){case"array":case"optional":{n.inner=f(r.inner);break}case"id":{n.tableName=r.tableName;break}case"literal":{n.literalValue=O(r.value);break}case"object":{const i=r.shape??{};n.shape=Object.fromEntries(Object.entries(i).map(([o,a])=>[o,f(a)]));break}case"record":{n.valueType=f(r.valueValidator),r.keyValidator!==void 0&&(n.keyType=f(r.keyValidator));break}case"storage":{typeof r.bucket=="string"&&(n.bucket=r.bucket);break}case"union":{const i=r.members??[];n.members=i.map(o=>f(o));break}}return n},D=e=>e?.kind==="global"?"global":e?.kind==="shardBy"&&typeof e.field=="string"?{field:e.field,kind:"shardBy"}:"root",M=(e,r)=>{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 "${r}" declares ${t.join(" + ")}, which are not yet introspected from a node_modules extension — they will be absent from the generated types.`)},B=(e,r)=>{const t=e.shape??{},n=(e.indexes??[]).map(i=>({fields:i.fields,name:i.name,...i.unique?{unique:!0}:{}}));return M(e,r),{...e.isExternallyManaged?{externallyManaged:!0}:{},geoIndexes:[],indexes:n,name:r,rankIndexes:[],relations:[],searchIndexes:(e.searchIndexes??[]).map(i=>({field:i.field,...i.filterFields?{filterFields:i.filterFields}:{},...i.language===void 0?{}:{language:i.language},...i.staged===void 0?{}:{staged:i.staged},...i.strategy===void 0?{}:{strategy:i.strategy},name:i.name})),shape:Object.fromEntries(Object.entries(t).map(([i,o])=>[i,f(o)])),shardMode:D(e.shardMode),vectorIndexes:[]}},F=e=>{const{key:r,tables:t}=e;if(typeof r!="string"||typeof t!="object"||t===null)return;const n=Object.entries(t).map(([a,l])=>B(l,a)),i=e.vectorIndexes??{},o=Object.entries(i??{}).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:n,bareVectorIndexes:o,key:r}},q=e=>{if(s.isIdentifier(e))return e.getText();if(s.isPropertyAccessExpression(e)){const r=e.getExpression();return s.isIdentifier(r)?r.getText():void 0}},R=e=>{const r=q(e);if(r===void 0)return;const t=s.isPropertyAccessExpression(e)?e.getName():void 0,n=t===void 0?[]:[t];for(const i of e.getSourceFile().getImportDeclarations()){const o=i.getModuleSpecifierValue();for(const a of i.getNamedImports())if((a.getAliasNode()?.getText()??a.getName())===r)return{importedName:a.getName(),moduleSpecifier:o,propertyPath:n};if(i.getDefaultImport()?.getText()===r)return{importedName:"default",moduleSpecifier:o,propertyPath:n};if(i.getNamespaceImport()?.getText()===r&&t!==void 0)return{importedName:t,moduleSpecifier:o,propertyPath:[]}}},C=(e,r)=>{let t=e[r.importedName];for(const n of r.propertyPath){if(typeof t!="object"||t===null)return;t=t[n]}return t},V=(e,r)=>{const t=R(e);if(t)try{const n=_(N(r,"noop.cjs")),i=n.resolve(t.moduleSpecifier),o=n(i),a=C(o,t);return typeof a!="object"||a===null?void 0:F(a)}catch{return}},J=new Set(["cosine","dot-product","euclidean"]),U=new Set(["cascade","restrict","set null"]),k=new Set(["delete","get","insert","normalizeId","patch","query","replace","system"]),K=/^[A-Za-z_$][\w$]*$/u,Z=e=>e.replaceAll(/^["']|["']$/gu,""),Q=(e,r)=>{const t=Z(e);if(k.has(t))throw u(r,`table name "${t}" is reserved — it collides with a \`ctx.db\` member (one of ${[...k].map(n=>`"${n}"`).join(", ")}). Rename the table.`);if(!K.test(t))throw u(r,`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.`)},d=(e,r)=>{const t=e.getProperty(r);if(t&&s.isPropertyAssignment(t)){const n=t.getInitializer();if(n&&s.isStringLiteral(n))return n.getLiteralText()}},m=(e,r)=>{const t=e.getProperty(r);if(t&&s.isPropertyAssignment(t)){const n=t.getInitializer();if(n&&s.isNumericLiteral(n))return Number(n.getLiteralText())}},X=(e,r)=>{const t=e.getProperty(r);if(t&&s.isPropertyAssignment(t)){const n=t.getInitializer();if(n&&(s.isTrueLiteral(n)||s.isFalseLiteral(n)))return n.getLiteralValue()}},h=(e,r)=>{const t=e.getProperty(r);if(t&&s.isPropertyAssignment(t)){const n=t.getInitializer();if(n&&s.isArrayLiteralExpression(n))return n.getElements().filter(i=>s.isStringLiteral(i)).map(i=>i.getLiteralText())}},L=e=>e&&J.has(e)?e:void 0,G=e=>e&&U.has(e)?e:void 0,H=e=>{if(!s.isArrowFunction(e))return;let r=e.getBody();if(s.isParenthesizedExpression(r))r=r.getExpression();else if(s.isBlock(r)){const t=r.getStatements().find(n=>s.isReturnStatement(n));r=t&&s.isReturnStatement(t)?t.getExpression()??r:r}return s.isObjectLiteralExpression(r)?r:void 0},W=e=>{if(!s.isPropertyAssignment(e))return;const r=e.getInitializer();if(!r||!s.isCallExpression(r))return;const t=r.getExpression();if(!s.isPropertyAccessExpression(t))return;const n=t.getName();if(n!=="one"&&n!=="many")return;const[i,o]=r.getArguments(),a=i&&s.isStringLiteral(i)?i.getLiteralText():"_unknown_";let l="_unknown_",c="_id",g;return o&&s.isObjectLiteralExpression(o)&&(l=d(o,"field")??l,c=d(o,"references")??c,g=n==="one"?G(d(o,"onDelete")):void 0),{field:l,kind:n,name:e.getName(),onDelete:g,references:c,table:a}},Y=e=>{const r=H(e);if(!r)return[];const t=[];for(const n of r.getProperties()){const i=W(n);i&&t.push(i)}return t},x=e=>e&&s.isStringLiteral(e)?e.getLiteralText():"_unnamed_",ee=(e,r,t)=>{if(!r.includes("."))return;const[n="",...i]=r.split("."),o=`${n}${i.map(a=>a.charAt(0).toUpperCase()+a.slice(1)).join("")}`;throw u(e,`index "${t}" indexes the nested path ${JSON.stringify(r)} — 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.`)},te=e=>{if(!e||!s.isObjectLiteralExpression(e))return!1;const r=e.getProperty("unique");if(!r||!s.isPropertyAssignment(r))return!1;const t=r.getInitializer();if(t===void 0)return!1;if(!s.isTrueLiteral(t)&&!s.isFalseLiteral(t))throw u(t,`\`unique\` must be a literal \`true\` or \`false\`, got ${JSON.stringify(t.getText())}`);return s.isTrueLiteral(t)},re=e=>{const[r,t,n]=e,i=te(n),o=x(r),a=t&&s.isArrayLiteralExpression(t)?t.getElements():[];for(const c of a)if(!s.isStringLiteral(c))throw u(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=>s.isStringLiteral(c));for(const c of l)ee(c,c.getLiteralText(),o);return{fields:l.map(c=>c.getLiteralText()),name:o,unique:i}},ne=e=>{const[r,t]=e;let n="_unknown_",i,o,a,l;return t&&s.isObjectLiteralExpression(t)&&(n=d(t,"field")??n,i=h(t,"filterFields"),o=d(t,"language"),a=X(t,"staged"),l=d(t,"strategy")),{field:n,filterFields:i,language:o,name:x(r),staged:a,strategy:l}},ie=e=>{const[r,t]=e;let n="_unknown_",i;return t&&s.isObjectLiteralExpression(t)&&(n=d(t,"field")??n,i=m(t,"precision")),{field:n,name:x(r),precision:i}},se=e=>{const[r,t]=e,n=r&&s.isStringLiteral(r)?r.getLiteralText():"_unknown_";let i;return t&&s.isObjectLiteralExpression(t)&&(i=m(t,"after")),{after:i,field:n}},oe=e=>{if(!s.isObjectLiteralExpression(e))return;const r=d(e,"field");return r===void 0?void 0:{direction:d(e,"direction")==="desc"?"desc":"asc",field:r}},ae=e=>{const[r,t]=e;let n=[],i;if(t&&s.isObjectLiteralExpression(t)){const o=t.getProperty("sortBy");if(o&&s.isPropertyAssignment(o)){const a=o.getInitializer();a&&s.isArrayLiteralExpression(a)&&(n=a.getElements().map(l=>oe(l)).filter(l=>l!==void 0))}i=h(t,"partitionBy")}return{name:x(r),partitionBy:i,sortBy:n}},le=(e,r)=>{const[t,n]=e,i=t&&s.isStringLiteral(t)?t.getLiteralText():"_unknown_";if(!(!n||!s.isObjectLiteralExpression(n)))return{dimensions:m(n,"dimensions"),field:i,metadata:h(n,"metadata"),metric:L(d(n,"metric")),name:d(n,"index")??"_unnamed_",table:r}},ce=e=>{const r=e[0];return r&&s.isObjectLiteralExpression(r)&&d(r,"backend")==="hyperdrive"?"hyperdrive":"d1"},de=e=>{if(e&&s.isObjectLiteralExpression(e)){const r=e.getProperty("field");if(r&&s.isPropertyAssignment(r)){const t=r.getInitializer();if(t&&s.isStringLiteral(t))return t.getLiteralText()}}return"deletedAt"},p=(e,r)=>{const t=e.getProperty(r);if(t&&s.isPropertyAssignment(t)){const n=t.getInitializer();if(n&&s.isStringLiteral(n))return n.getLiteralText()}},ue=(e,r)=>{const t=e.getProperty(r);if(t&&s.isPropertyAssignment(t)){const n=t.getInitializer();if(n&&s.isArrayLiteralExpression(n)){const i=n.getElements().filter(o=>s.isStringLiteral(o)).map(o=>o.getLiteralText());return i.length>0?i:void 0}}},ge=e=>{const r=e[0];return!r||!s.isObjectLiteralExpression(r)?{binding:"",hasTenantBy:!1,unanalyzable:!0}:{binding:p(r,"binding")??"",columns:ue(r,"columns"),hasReconcile:r.getProperty("reconcileEveryMs")!==void 0,hasSoftDelete:r.getProperty("softDeleteColumn")!==void 0,hasTenantBy:r.getProperty("tenantBy")!==void 0,idColumn:p(r,"idColumn"),mode:p(r,"mode"),query:p(r,"query")}},fe=(e,r,t,n)=>{switch(r){case"externallyManaged":{e.externallyManaged=!0;break}case"geoIndex":{e.geoIndexes.push(ie(t));break}case"global":{e.shardMode="global",e.globalBackend=ce(t);break}case"index":{e.indexes.push(re(t));break}case"public":{e.isPublic=!0;break}case"rankIndex":{e.rankIndexes.push(ae(t));break}case"relations":{const i=t[0];i&&e.relations.push(...Y(i));break}case"searchIndex":{e.searchIndexes.push(ne(t));break}case"shardBy":{const i=t[0];e.shardMode={field:i&&s.isStringLiteral(i)?i.getLiteralText():"_unknown_",kind:"shardBy"};break}case"softDelete":{e.softDelete={field:de(t[0])};break}case"source":{e.externalSource=ge(t),e.externallyManaged=!0;break}case"ttl":{e.ttl=se(t);break}case"vectorize":{const i=le(t,n);i&&e.vectorIndexes.push(i);break}}},E=["__vocab","_config","_content","_data","_docsize","_idx"],pe=(e,r,t)=>{const n=new Set(t.map(i=>i.name));for(const i of t)for(const o of E){const a=`${i.name}${o}`;if(!n.has(a))continue;const l=o==="__vocab"?`the \`fts5vocab\` companion for "${a}" is created \`IF NOT EXISTS\`, so it silently resolves to "${i.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 u(e,`table "${r}" declares search indexes "${i.name}" and "${a}", whose generated FTS5 tables collide: "${i.name}" already owns "${r}__fts_${a}" as its "${o}" companion, so ${l}. Rename one of them so neither ends with another's name plus ${E.join(", ")}.`)}},S=(e,r)=>{const t={externallyManaged:!1,geoIndexes:[],indexes:[],isPublic:!1,rankIndexes:[],relations:[],searchIndexes:[],shardMode:"root",vectorIndexes:[]};let n={},i=e;for(;s.isCallExpression(i);){const o=i.getExpression(),a=i.getArguments();if(s.isPropertyAccessExpression(o))fe(t,o.getName(),a,r),i=o.getExpression();else if(s.isIdentifier(o)&&o.getText()==="defineTable"){const l=a[0];if(l&&s.isObjectLiteralExpression(l))n=j(l);else if(l)throw u(l,`table "${r}" 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_${r}\` / \`Insert_${r}\` type instead of sharing the runtime value.`);break}else break}return t.softDelete&&!(t.softDelete.field in n)&&(n={...n,[t.softDelete.field]:{inner:{kind:"number"},kind:"optional"}}),pe(e,r,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:r,rankIndexes:t.rankIndexes,relations:t.relations,searchIndexes:t.searchIndexes,shape:n,shardMode:t.shardMode,softDelete:t.softDelete,ttl:t.ttl,vectorIndexes:t.vectorIndexes}},me=e=>{const r=e.getProperty("source");if(r&&s.isPropertyAssignment(r)){const t=r.getInitializer();if(t&&s.isObjectLiteralExpression(t))return d(t,"table")??"_unknown_"}return"_unknown_"},xe=e=>{if(!s.isPropertyAssignment(e))return;const r=e.getInitializer();if(!r||!s.isCallExpression(r))return;const t=r.getExpression();if(!s.isIdentifier(t)||t.getText()!=="defineVectorIndex")return;const n=r.getArguments()[0];if(!n||!s.isObjectLiteralExpression(n))return;const i=e.getNameNode(),o=s.isStringLiteral(i)?i.getLiteralText():i.getText();return{dimensions:m(n,"dimensions"),metric:L(d(n,"metric")),name:o,table:me(n)}},P=e=>{const r=[];for(const t of e.getProperties()){const n=xe(t);n&&r.push(n)}return r},I=(e,r)=>`${e}_${r}`,y=(e,r,t)=>t.has(e)?I(r,e):e,be=(e,r,t)=>{const n=I(r,e.name);return{...e,extensionKey:r,name:n,relations:e.relations.map(i=>({...i,table:y(i.table,r,t)})),vectorIndexes:e.vectorIndexes.map(i=>({...i,table:y(i.table,r,t)}))}},ye=e=>{if(s.isVariableDeclaration(e)||s.isPropertyAssignment(e))return e.getInitializer();if(s.isShorthandPropertyAssignment(e))return e.getNameNode()},he=(e,r)=>{const t=e.getProperty(r);if(t&&s.isPropertyAssignment(t))return t.getInitializer()},Ie=e=>{if(!s.isCallExpression(e))return!1;const r=e.getExpression();return s.isIdentifier(r)&&r.getText()==="defineSchemaExtension"},ve=e=>{if(s.isIdentifier(e))return e;if(s.isPropertyAccessExpression(e)){const r=e.getExpression();return s.isIdentifier(r)?r:void 0}},ke=e=>{if(s.isObjectLiteralExpression(e))return e;if(s.isCallExpression(e)){const r=e.getExpression();let t;if(s.isIdentifier(r)?t=r.getText():s.isPropertyAccessExpression(r)&&(t=r.getName()),t==="definePlugin"){const n=e.getArguments()[1];return n&&s.isObjectLiteralExpression(n)?n:void 0}}},Ee=(e,r)=>{const t=ye(e);if(t){if(s.isPropertyAccessExpression(r)){const n=ke(t);return n?he(n,r.getName()):void 0}return t}},Le=e=>{let r=e,t=0;for(;r&&t<32;){if(t+=1,Ie(r))return r;const n=ve(r),i=n&&s.isIdentifier(n)?n.getSymbol():void 0,o=(i?.getAliasedSymbol()?.getDeclarations()??i?.getDeclarations()??[])[0];if(!o)return;const a=o.getSourceFile();if(a.isInNodeModules()||a.isDeclarationFile())return;r=Ee(o,r)}},Se=e=>{const[r,t]=e.getArguments();if(!(!r||!s.isStringLiteral(r))&&!(!t||!s.isObjectLiteralExpression(t)))return{key:r.getLiteralText(),options:t}},Pe=e=>{const r=e.getProperty("tables");if(!r||!s.isPropertyAssignment(r))return[];const t=r.getInitializer();if(!t||!s.isObjectLiteralExpression(t))return[];const n=[];for(const i of t.getProperties()){if(!s.isPropertyAssignment(i))continue;const o=i.getInitializer();o&&n.push(S(o,i.getName()))}return n},$e=e=>{const r=e.getProperty("vectorIndexes");if(!r||!s.isPropertyAssignment(r))return[];const t=r.getInitializer();return!t||!s.isObjectLiteralExpression(t)?[]:P(t)},$=(e,r,t)=>{const n=new Set(r.map(a=>a.name)),i=r.map(a=>be(a,e,n)),o=t.map(a=>({...a,name:I(e,a.name),table:y(a.table,e,n)}));return{tables:i,vectorIndexes:o}},we=(e,r)=>$(e,Pe(r),$e(r)),Ae=(e,r)=>{const t=e.getArguments()[0];if(!t)return;const n=Le(t);if(!n){if(r!==void 0){const o=V(t,r);if(o)return $(o.key,o.bareTables,o.bareVectorIndexes)}console.warn(`@lunora/codegen: skipping \`.extend(${t.getText()})\` — its \`defineSchemaExtension(...)\` could not be resolved from local sources, and ${r===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 i=Se(n);if(!i){console.warn("@lunora/codegen: skipping `.extend(...)` — `defineSchemaExtension` requires a string `key` and an options object literal.");return}return we(i.key,i.options)},Te=e=>{const r=[];let t=e;for(;;){const n=t.getParent();if(!n||!s.isPropertyAccessExpression(n))break;const i=n.getParent();if(!i||!s.isCallExpression(i))break;n.getName()==="extend"&&r.push(i),t=i}return r},w=(e,r,t,n,i)=>{let o=e;for(;;){const a=o.getParent();if(!a||!s.isPropertyAccessExpression(a))break;const l=a.getParent();if(!l||!s.isCallExpression(l))break;if(a.getName()===r){const c=l.getArguments()[0];if(!c||!s.isStringLiteral(c))throw u(l,`\`.${r}(...)\` expects a string literal (${i})`);const g=c.getLiteralText();if(!n.has(g))throw u(c,`unknown ${t} ${JSON.stringify(g)} — expected ${i}`);return g}o=l}},je=new Set(["eu","fedramp","us"]),_e=e=>w(e,"jurisdiction","jurisdiction",je,'"eu", "us", or "fedramp"'),Ne=new Set(["required"]),Oe=e=>w(e,"rls","rls mode",Ne,'"required"'),ze=e=>{const r=[];for(const t of e.getProperties()){if(!s.isPropertyAssignment(t))continue;const n=t.getInitializer();if(n){const i=t.getName();Q(i,t.getNameNode()),r.push(S(n,i))}}return r},De=(e,r,t)=>{const n=new Set(r.map(o=>o.name)),i=[];for(const o of Te(e)){const a=Ae(o,t);if(a){for(const l of a.tables){if(n.has(l.name))throw u(o,`defineSchema(...).extend(...): table "${l.name}" already exists — another extension with the same key already contributed it.`);n.add(l.name),r.push(l)}i.push(...a.vectorIndexes)}}return i},Ve=(e,r,t)=>{const n=e.addSourceFileAtPath(r).getDescendantsOfKind(T.CallExpression).find(b=>{const v=b.getExpression();return s.isIdentifier(v)&&v.getText()==="defineSchema"});if(!n)throw new A("INTERNAL",`defineSchema() not found in ${r}`);const i=n.getArguments()[0];if(!i||!s.isObjectLiteralExpression(i))throw u(n,"defineSchema() expects an object literal");const o=ze(i),a=n.getArguments()[1],l=a&&s.isObjectLiteralExpression(a)?P(a):[],c=De(n,o,t),g=[...o.flatMap(b=>b.vectorIndexes),...l,...c];return{jurisdiction:_e(n),rlsMode:Oe(n),tables:o,vectorIndexes:g}};export{Ve as default};
@@ -1 +0,0 @@
1
- import{LunoraError as c}from"@lunora/errors";import{Node as r}from"ts-morph";let d;const T=n=>{d=n},p=/^[A-Za-z_$][\w$]*$/u,g=new Set(["$defaultFn","$onUpdateFn","$type","default","defaultNow","nullable","unique"]),k=(n,t)=>{const e={notNull:!0,...n.column};switch(t){case"$defaultFn":case"default":case"defaultNow":{e.hasDefault=!0;break}case"$onUpdateFn":{e.hasOnUpdate=!0;break}case"$type":break;case"nullable":{e.notNull=!1;break}case"unique":{e.unique=!0;break}}return{...n,column:e}},f=new Set(["any","bigint","boolean","bytes","date","geoPoint","null","number","string","timestamp"]),m=new Set(["check","meta"]),o=n=>r.isCallExpression(n)?h(n):{kind:"any",sourceText:n.getText()},y=n=>{const t={};for(const e of n.getProperties()){const a=r.isShorthandPropertyAssignment(e);if(!a&&!r.isPropertyAssignment(e))continue;const i=e.getNameNode();if(r.isComputedPropertyName(i))continue;const s=a?e.getNameNode():e.getInitializer();if(!s)continue;const l=e.getName();if(!p.test(l))throw new c("INTERNAL",`@lunora/codegen: field name is not a valid JS identifier: ${JSON.stringify(l)}`);t[l]=o(s)}return t},u=(n,t)=>n&&r.isExpression(n)?o(n):t,N=n=>n===void 0?"undefined":r.isStringLiteral(n)||r.isNoSubstitutionTemplateLiteral(n)?JSON.stringify(n.getLiteralValue()):n.getText(),b=n=>{const t=n&&d?d(n):void 0;return t===void 0?{kind:"from"}:{kind:"from",tsType:t}},x=(n,t)=>{if(f.has(n))return{kind:n};const[e,a]=t;switch(n){case"array":return{inner:u(e,{kind:"any"}),kind:"array"};case"from":return b(e);case"id":return{kind:"id",tableName:e&&r.isStringLiteral(e)?e.getLiteralText():"_unknown_"};case"literal":return{kind:"literal",literalValue:N(e)};case"object":return e&&r.isObjectLiteralExpression(e)?{kind:"object",shape:y(e)}:{kind:"object",shape:{}};case"optional":return{inner:u(e,{kind:"any"}),kind:"optional"};case"record":return{keyType:u(e,{kind:"string"}),kind:"record",valueType:u(a,{kind:"any"})};case"storage":return e&&r.isStringLiteral(e)?{bucket:e.getLiteralText(),kind:"storage"}:{kind:"storage"};case"union":return{kind:"union",members:t.filter(i=>r.isExpression(i)).map(i=>o(i))};default:throw new c("INTERNAL",`Unsupported validator kind: ${n}`)}},h=n=>{const t=n.getExpression();if(!r.isPropertyAccessExpression(t))return{kind:"any",sourceText:n.getText()};const e=t.getName(),a=n.getArguments();if(g.has(e)){const i=t.getExpression(),s=r.isExpression(i)?o(i):{kind:"any"};return k(s,e)}if(m.has(e)){const i=t.getExpression(),s=r.isExpression(i)?o(i):{kind:"any"};return e==="check"?{...s,hasRefinement:!0}:s}return x(e,a)};export{T as f,o,y as p};