@lunora/codegen 1.0.0-alpha.245 → 1.0.0-alpha.247
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +7 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/CONTAINERS_FILENAME-C13yKxas.mjs +1 -0
- package/dist/packem_shared/DEFAULT_TARGET-DbC2AqGy.mjs +1 -0
- package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-CyA07RIr.mjs +11 -0
- package/dist/packem_shared/discoverSandboxUsage-BnsPld5I.mjs +1 -0
- package/dist/packem_shared/{emitAgents-CnQEPybh.mjs → emitAgents-D_xvTOJU.mjs} +1 -1
- package/dist/packem_shared/{emitServer-nvzMxk3d.mjs → emitServer-BpNuS8Pn.mjs} +53 -53
- package/dist/packem_shared/{emitShard-BiKPSgNP.mjs → emitShard-DYvEfiTo.mjs} +1 -1
- package/dist/packem_shared/{shard-D6EZdlSg.mjs → shard-B7t6dut5.mjs} +1 -1
- package/dist/packem_shared/{shard-runtime-D9GRosnD.mjs → shard-runtime-CT_oddIR.mjs} +45 -38
- package/package.json +7 -7
- package/dist/packem_shared/CONTAINERS_FILENAME-CBCG6g9n.mjs +0 -1
- package/dist/packem_shared/DEFAULT_TARGET-D-zkySYF.mjs +0 -1
- package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-KDyLA-v5.mjs +0 -11
- package/dist/packem_shared/discoverSandboxUsage-DkbwwFvO.mjs +0 -1
|
@@ -1,11 +0,0 @@
|
|
|
1
|
-
import{existsSync as w,mkdirSync as an,readFileSync as ls,writeFileSync as cn,rmSync as ln}from"node:fs";import{join as x,dirname as he}from"node:path";import{performance as _e}from"node:perf_hooks";import{runAdvisor as un}from"@lunora/advisor";import{LunoraError as j}from"@lunora/errors";import{SyntaxKind as l,Node as i,VariableDeclarationKind as dn,Project as Ot}from"ts-morph";import{serializeSchemaSnapshot as fn}from"./SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs";import{toAdvisorContext as pn}from"./formatAdvisories-DwmUKYuc.mjs";import{readProjectConfigLiterals as gn}from"./loadProjectConfig-6Zk3abcc.mjs";import{a as Rt,d as mn,r as hn}from"./modules-DyCocr1e.mjs";import{QUEUES_FILENAME as vn,discoverQueueDeclarations as xn}from"./QUEUES_FILENAME-RGwht3Xu.mjs";import{WORKFLOWS_FILENAME as En,discoverWorkflows as Sn}from"./WORKFLOWS_FILENAME-4-ib4HH-.mjs";import{r as yn}from"./json-data-Chfs2Cz5.mjs";import{s as Ne}from"./paths-C-9fwEgQ.mjs";import{G as An}from"./shared-DjUziztz.mjs";import{C as ve}from"./capabilities-DJJWVEtk.mjs";import{isD1GlobalTable as us,isHyperdriveGlobalTable as ds}from"./isD1GlobalTable-udvHAAzD.mjs";import{discoverAgents as bn}from"./AGENTS_FILENAME-D8SgT3OR.mjs";import{discoverContainers as Nn}from"./CONTAINERS_FILENAME-CBCG6g9n.mjs";import Pn from"./discoverCrons-BEALHx1S.mjs";import{diagnosticAt as ae}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{b as Pe}from"./module-specifiers-WF8iAydP.mjs";import{listLunoraSourceFiles as g,bindingKeyName as X,propertyKeyName as E,unwrapExpression as ne,listSecurityScanFiles as we,objectLiteralFromCallbackBody as fs,propertyInitializer as N,lunoraRelativePath as v,enclosingExportName as re,collectCallRows as O,findObjectProperty as F,collectSecurityCallRows as wn,RUN_METHODS as ps,functionReferenceSegments as gs,limitNameOf as ms,optionsObjectLiteral as hs,isContextIdentifier as Ve,handlerOf as In,isDatabaseAccessor as M,readTargetOf as vs}from"./listLunoraSourceFiles-CSlcBYlo.mjs";import Tn from"./readPackageDependencies-C6h6FZuP.mjs";import{discoverSandboxUsage as Cn}from"./discoverSandboxUsage-DkbwwFvO.mjs";import{resolveServiceBindings as Fn}from"./readServiceBindings-D9Wi_qGU.mjs";import On from"./discoverStorageRulesMetadata-D3Ot9g5f.mjs";import{a as y,c as B,d as xs,e as Rn}from"./classify-procedure-call-CmcShAze.mjs";import{i as kn}from"./ir-DBSvhNa-.mjs";import{gatePlatformFeatures as Ln,resolveCodegenTarget as Es,readTargetDiagnostics as Dn,studioPlatformFor as Mn}from"./DEFAULT_TARGET-D-zkySYF.mjs";import{b as Ss,e as Kn}from"./shard-D6EZdlSg.mjs";import _n from"./emitServer-nvzMxk3d.mjs";import{emitDataModel as $n}from"./emitDataModel-D3WuEZ4b.mjs";import{r as Ie,s as zn}from"./parse-validator-C6fHL7OS.mjs";import Un from"./discoverAuthApiCalls-DoSN_yc3.mjs";import{i as Bn,a as qn,e as jn,b as Wn,d as Vn,c as Hn}from"./unwrap-handler-return-DVY_kFF7.mjs";import Gn from"./discoverFunctions-BcBzcG5x.mjs";import Yn from"./discoverHttpRoutes-CJHS4llq.mjs";import Qn from"./discoverHyperdriveCalls-Bkbh4tG7.mjs";import Xn from"./discoverInserts-DpuLYPPd.mjs";import{m as Ze,a as Se,s as ys,d as Jn}from"./index-D7dKfGPh.mjs";import{e as As}from"./exported-procedure-chains-D48EXUVQ.mjs";import Zn from"./discoverMigrations-Dt7ywfZv.mjs";import{MUTATORS_FILENAME as er,isDefineMutatorCallee as tr,discoverMutators as sr}from"./MUTATORS_FILENAME-DqWOgC5Z.mjs";import nr from"./discoverNondeterministicCalls-CNJV2BiP.mjs";import{discoverNotifyConfig as rr,discoverNotifyCalls as or}from"./NOTIFY_FILENAME-C1J_47et.mjs";import ir from"./discoverQueries-BcdqjYky.mjs";import ar from"./discoverR2sqlCalls-30Wtbc0P.mjs";import cr from"./discoverRlsProcedures-F4Cy-kSi.mjs";import lr from"./discoverRlsMetadata-mXBmPOGj.mjs";import ur from"./discoverSchema-D5R60b4F.mjs";import{secretKindOf as dr,redact as fr,isHeuristicSecretKind as pr,isSecretishName as gr}from"./redact-Cy14LEnc.mjs";import{discoverShapes as mr}from"./SHAPES_FILENAME-DRUFomCj.mjs";import{emitApp as hr}from"./emitApp-DsMk4tpo.mjs";import{buildOpenApiDocument as vr,emitOpenApiModule as xr}from"./buildOpenApiDocument-SxfElVzK.mjs";import{buildOpenRpcDocument as Er,emitOpenRpcModule as Sr}from"./OPENRPC_VERSION-Cr7Zzp6s.mjs";import{buildSchemaSnapshot as yr}from"./SchemaSnapshotParseError-CPOXlFhI.mjs";import{emitCollections as Ar,emitSeed as br,emitApi as Nr}from"./emitApi-DdW9RyGG.mjs";import{C as Pr,D as wr,B as Ir,E as Tr}from"./shard-runtime-D9GRosnD.mjs";import{emitCrons as Cr,emitScheduler as Fr,emitShardRegistry as Or,emitVectors as Rr,emitWranglerCronTriggers as kr}from"./emitCrons-BRKXFGFu.mjs";import Lr from"./emitDrizzleSchema-Cv0HtLR3.mjs";import Dr from"./emitFunctions-BgNeOZt_.mjs";const kt={error:"ERROR",info:"INFO",warn:"WARN"},Lt={ERROR:2,INFO:0,WARN:1},Mr=e=>({cacheKey:"advisor_min_severity_invalid",categories:["SCHEMA"],description:"`advisor.minSeverity` in `lunora.config.*` sets the lowest advisory level codegen reports and writes into `_generated/shard.ts`. Codegen reads it by parsing the file, so it has to be a string literal.",detail:e,facing:"INTERNAL",level:"WARN",metadata:{},name:"advisor_min_severity_invalid",remediation:'Set `advisor: { minSeverity: "info" | "warn" | "error" }` as a literal on the config\'s default export.',title:"`advisor.minSeverity` is not a level codegen can read, so every advisory was reported"}),Kr=(e,t)=>{const{advisor:s}=gn(e);if(s===void 0||s.minSeverity===void 0&&s.unreadable!==!0)return[...t];const{minSeverity:n}=s,o=n!==void 0&&Object.hasOwn(kt,n)?kt[n]:void 0;return o===void 0?[...t,Mr(n===void 0?"`advisor.minSeverity` is not a string literal codegen can read without evaluating the config: a computed value or key, or a spread that could set or override it.":`\`advisor.minSeverity\` is "${n}", which is not one of "info", "warn" or "error".`)]:t.filter(r=>Lt[r.level]>=Lt[o])},_r={call:"function",enqueue:"queue",invoke:"service",publish:"topic",schedule:"function"},bs=vn.replace(/\.ts$/u,""),$r="crons",zr=En.replace(/\.ts$/u,""),te=(e,t)=>`${Ne(e)}:${t}`,$e=(e,t,s)=>t===""?{reason:`the ${s} is not a string literal`}:{to:`${e}:${t}`},Ur=e=>[...e.callEdges.map(t=>{const s=t.target===void 0?{reason:t.reason??"unreadable target"}:{to:`${_r[t.kind]}:${t.target}`};return{exportName:t.exportName,file:t.file,kind:t.kind,line:t.line,...s}}),...e.queries.map(t=>({exportName:t.exportName,file:t.file,kind:"read",line:t.line,...$e("table",t.table,"table name")})),...[...e.inserts,...e.tableWrites].map(t=>({exportName:t.exportName,file:t.file,kind:"write",line:t.line,...$e("table",t.table,"written table")})),...e.workflowCalls.map(t=>({exportName:t.exportName,file:t.file,kind:"start",line:t.line,...$e("workflow",t.workflow,"workflow name")}))],Br=e=>[...e.queues.flatMap(t=>t.topic===void 0?[]:[{exportName:t.exportName,file:bs,from:`topic:${t.topic}`,kind:"subscribe",line:0,to:`queue:${t.exportName}`}]),...e.crons.map(t=>{const s=t.workflow===void 0?void 0:`workflow:${t.workflow.exportName}`,n=t.functionPath===void 0?void 0:`function:${t.functionPath}`,o=s??n;return{exportName:t.name,file:$r,from:`cron:${t.name}`,kind:"trigger",line:0,...o===void 0?{reason:"the cron has no target"}:{to:o}}})],qr=e=>new Map(e.flatMap(t=>t.tables.map(s=>[s,t.name]))),ze=(e,t)=>t===void 0?e:{...e,module:t},jr=e=>{const t=new Map,s=new Map,n=qr(e.modules),o=(r,a)=>{t.set(r.id,r),a!==void 0&&s.set(a,r.id)};for(const r of e.functions){const a=te(r.filePath,r.exportName),c=`${Ne(r.filePath)}.${r.exportName}`;o(ze({detail:r.kind,id:`function:${a}`,kind:"function",name:c},Rt(e.modules,r.filePath)),a)}for(const r of e.httpRoutes){const a=te(r.filePath,r.exportName);o(ze({id:`http:${a}`,kind:"http",name:`${r.method} ${r.path}`},Rt(e.modules,r.filePath)),a)}for(const r of e.schema.tables)o(ze({id:`table:${r.name}`,kind:"table",name:r.name},n.get(r.name)));for(const r of e.queues){const a=r.topic===void 0?{}:{detail:"subscription"};o({...a,id:`queue:${r.exportName}`,kind:"queue",name:r.exportName},te(bs,r.exportName))}for(const r of e.topics)o({id:`topic:${r.exportName}`,kind:"topic",name:r.exportName});for(const r of e.workflows)o({id:`workflow:${r.exportName}`,kind:"workflow",name:r.exportName},te(zr,r.exportName));for(const r of e.crons)o({detail:r.cron,id:`cron:${r.name}`,kind:"cron",name:r.name});for(const r of e.services)o({detail:r.entrypoint===void 0?"fetch":`rpc · ${r.entrypoint}`,id:`service:${r.name}`,kind:"service",name:r.worker});return{nodes:t,sites:s}},Wr=e=>e===""?"inside a non-exported helper":e==="default"?"the default export is not a registered function":`"${e}" is not a registered function`,Vr=(e,t,s)=>{if("reason"in e)return{reason:e.reason};const n=e.from??t.get(te(e.file,e.exportName));return n===void 0?{reason:Wr(e.exportName)}:s.has(e.to)?{drawn:{from:n,kind:e.kind,to:e.to}}:{reason:`${e.to} is not declared`}},Ue=e=>`${e.from}|${e.kind}|${e.to}`,Hr=e=>`${e.file}|${String(e.line)}|${e.kind}|${e.reason}`,Gr=e=>{const{nodes:t,sites:s}=jr(e),n=new Map,o=new Map;for(const r of[...Br(e),...Ur(e)]){const a=Vr(r,s,t);if("drawn"in a)n.set(Ue(a.drawn),a.drawn);else{const c={file:r.file,kind:r.kind,line:r.line,reason:a.reason};o.set(Hr(c),c)}}return{edges:[...n.values()].toSorted((r,a)=>Ue(r).localeCompare(Ue(a))),nodes:[...t.values()].toSorted((r,a)=>r.id.localeCompare(a.id)),modules:e.modules.map(r=>({...r.description===void 0?{}:{description:r.description},...r.installed===!0?{installed:!0}:{},...r.ownsFolder===!1?{ownsFolder:!1}:{},name:r.name,tables:[...r.tables]})),unresolved:[...o.values()].toSorted((r,a)=>r.file.localeCompare(a.file)||r.line-a.line),version:1}},Yr=e=>`${An}export const architecture = ${yn(e,"Record<string, unknown>")};
|
|
2
|
-
`,Dt=(e,t="api")=>{const s=new Map;for(const n of e){const o=Ne(n),r=s.get(o);if(r===void 0){s.set(o,n);continue}if(r!==n){const a=t==="api"?`the generated api.ts would declare "${o}" twice and the dispatch key "${o}:<fn>" would be ambiguous`:`the generated api.ts would declare "${o}" twice in HttpStreamsRef and again in the httpStreams object literal`;throw new j("INTERNAL",`@lunora/codegen: "${r}" and "${n}" both map to the ${t} namespace "${o}" — ${a}. Rename one file so the two differ by more than a non-identifier character (\`-\`, \`.\`, \`/\` and \`_\` all sanitize to \`_\`).`,{status:500})}}},Qr=(e,t={})=>{const{hasVectors:s=!0,scheduler:n=!1,storage:o=!1,usage:r}=t,a=[];e.tables.some(c=>us(c))&&a.push({name:"@lunora/d1",reason:"`.global()` tables are D1-backed, so `_generated/app.ts` imports the D1 `ctx.db` adapter"}),e.tables.some(c=>ds(c))&&a.push({name:"@lunora/hyperdrive",reason:'`.global({ backend: "hyperdrive" })` tables route through `@lunora/hyperdrive/global`'},{name:"@lunora/sql-store",reason:'`.global({ backend: "hyperdrive" })` makes `_generated/app.ts` import the `SqlCtxDbOptions` / `SqlExec` types'}),n&&a.push({name:"@lunora/scheduler",reason:"a declared cron (or `ctx.scheduler` use) makes `_generated/app.ts` import `createScheduler`"}),o&&a.push({name:"@lunora/storage",reason:"a `v.storage()` column, a storage access rule (or `ctx.storage` use) makes `_generated/app.ts` import `createStorage`"}),e.vectorIndexes.length>0&&s&&a.push({name:"@lunora/bindings",reason:"`.vectorize()` indexes make `_generated/shard.ts` import `@lunora/bindings/vectors`"});for(const c of r===void 0?[]:ve)c.requiredPackage!==void 0&&r?.[c.key]===!0&&a.push({name:c.requiredPackage,reason:`\`ctx.${c.contextProperty??c.key}\` usage makes \`_generated/\` import \`${c.moduleSpecifier}\``});return a.filter((c,u)=>a.findIndex(d=>d.name===c.name)===u)},Xr=(e,t,s={})=>{if(t===void 0)return;const n=Qr(e,s).filter(r=>!t.has(r.name));if(n.length===0)return;const o=n.map(r=>` - ${r.name} — ${r.reason}`).join(`
|
|
3
|
-
`);throw new j("INTERNAL",`@lunora/codegen: this schema's generated code imports packages the project does not declare:
|
|
4
|
-
${o}
|
|
5
|
-
|
|
6
|
-
Install them with your package manager, then re-run codegen.`)},Jr="env.ts",Zr=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineEnv";for(const s of t.getDeclarations())if(i.isImportSpecifier(s))return Pe(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineEnv":!1;return!1},eo=e=>{const t=e.getSymbol();if(!t)return!1;for(const s of t.getDeclarations()){if(!i.isNamespaceImport(s))continue;const n=s.getFirstAncestorByKind(l.ImportDeclaration);return n!==void 0&&Pe(n.getModuleSpecifierValue())}return!1},to=e=>{if(i.isIdentifier(e))return Zr(e);if(i.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineEnv"&&i.isIdentifier(t)&&eo(t)}return!1},so=e=>{const t=[];for(const s of e.getVariableDeclarations()){if(!s.isExported())continue;const n=s.getInitializer();if(n?.getKind()!==l.CallExpression||!to(n.getExpression()))continue;const r=s.getNameNode();if(!i.isIdentifier(r))throw ae(r,"defineEnv exports must be plain named exports (no destructuring)");t.push({exportName:r.getText()})}return t},no=(e,t)=>{const s=x(t,Jr);if(!w(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s),o=so(n);if(o.length!==0){if(o.length>1)throw ae(n,`lunora/env.ts declares ${o.length.toString()} defineEnv() contracts (${o.map(r=>r.exportName).join(", ")}); exactly one is allowed`);return o[0]}},Mt="ctx",Ns=e=>{const t=new Set,s=new Set([Mt]),n=r=>{if(i.isObjectBindingPattern(r))for(const a of r.getElements()){const c=X(a);c&&t.add(c)}};for(const r of e.getDescendantsOfKind(l.BindingElement)){if(X(r)!==Mt)continue;const a=r.getNameNode();i.isIdentifier(a)?s.add(a.getText()):n(a)}const o=r=>i.isIdentifier(r)&&s.has(r.getText());for(const r of e.getDescendantsOfKind(l.PropertyAccessExpression))o(r.getExpression())&&t.add(r.getName());for(const r of e.getDescendantsOfKind(l.VariableDeclaration)){const a=r.getInitializer();a!==void 0&&o(a)&&n(r.getNameNode())}return t},ro=(e,t)=>{const s=Object.fromEntries(ve.map(n=>[n.key,!1]));for(const n of g(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=new Set(o.getImportDeclarations().map(c=>c.getModuleSpecifierValue())),a=Ns(o);for(const c of ve)if(!s[c.key]){if(r.has(c.moduleSpecifier)){s[c.key]=!0;continue}c.contextProperty!==void 0&&a.has(c.contextProperty)&&(s[c.key]=!0)}if(ve.every(c=>s[c.key]))break}return s},Ps="identity.ts",oo=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineIdentity";for(const s of t.getDeclarations())if(i.isImportSpecifier(s))return Pe(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineIdentity":!1;return!1},io=e=>{const t=e.getSymbol();if(!t)return!1;for(const s of t.getDeclarations()){if(!i.isNamespaceImport(s))continue;const n=s.getFirstAncestorByKind(l.ImportDeclaration);return n!==void 0&&Pe(n.getModuleSpecifierValue())}return!1},ao=e=>{if(i.isIdentifier(e))return oo(e);if(i.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineIdentity"&&i.isIdentifier(t)&&io(t)}return!1},co=e=>{const t=[];for(const s of e.getVariableDeclarations()){if(!s.isExported())continue;const n=s.getInitializer();if(n?.getKind()!==l.CallExpression||!ao(n.getExpression()))continue;const r=s.getNameNode();if(!i.isIdentifier(r))throw ae(r,"defineIdentity exports must be plain named exports (no destructuring)");t.push({exportName:r.getText()})}return t},lo=(e,t)=>{const s=x(t,Ps);if(!w(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s),o=co(n);if(o.length!==0){if(o.length>1)throw ae(n,`lunora/identity.ts declares ${o.length.toString()} defineIdentity() contracts (${o.map(r=>r.exportName).join(", ")}); exactly one is allowed`);return o[0]}},uo=new Set(["allowedHosts","deniedHosts","interceptHttps"]),fo=(e,t)=>{const s=ne(t);if(s===void 0||!i.isIdentifier(s))return s;const n=s.getText();return ne(e.getDescendantsOfKind(l.VariableDeclaration).find(o=>o.getName()===n)?.getInitializer())},po=(e,t)=>e!==void 0&&i.isObjectLiteralExpression(e)&&e.getProperties().some(s=>{if(i.isShorthandPropertyAssignment(s))return t.has(E(s));if(!i.isPropertyAssignment(s)||!t.has(E(s)))return!1;const n=ne(s.getInitializer())?.getText();return n!=="false"&&n!=="undefined"}),go=new Set(["durable"]),mo=new Set(["rollback"]),ho=e=>{const t=e.getExpression();return i.isPropertyAccessExpression(t)?t.getName():t.getText()},vo=new Map([["defineContainer",{keys:uo,signal:"containerEgressPolicy"}],["defineStep",{keys:mo,signal:"workflowRollback"}],["stream",{keys:go,signal:"durableStreams"}]]),xo=(e,t)=>{const s=vo.get(ho(t));if(s!==void 0)return t.getArguments().some(n=>po(fo(e,n),s.keys))?s.signal:void 0},Eo=(e,t)=>{const s={containerEgressPolicy:!1,durableStreams:!1,secrets:!1,workflowRollback:!1};for(const n of g(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.secrets||(s.secrets=Ns(o).has("secrets"));for(const r of o.getDescendantsOfKind(l.CallExpression)){const a=xo(o,r);a!==void 0&&(s[a]=!0)}if(Object.values(s).every(Boolean))break}return s},So="createWorker",yo="extend",Kt=e=>e!==void 0&&(i.isStringLiteral(e)||i.isNoSubstitutionTemplateLiteral(e))?e.getLiteralValue():void 0,_t=e=>{const t=[],s=Kt(N(e,"backupCron"));s!==void 0&&t.push(s);const n=N(e,"crons");if(n===void 0||!i.isObjectLiteralExpression(n))return t;for(const o of n.getProperties()){if(!i.isPropertyAssignment(o)&&!i.isMethodDeclaration(o))continue;const r=Kt(o.getNameNode());r!==void 0&&t.push(r)}return t},Ao=e=>{const t=y(e.getExpression()),[s]=e.getArguments();if(s===void 0)return[];if(t===So)return i.isObjectLiteralExpression(s)?_t(s):[];if(t!==yo||!(i.isArrowFunction(s)||i.isFunctionExpression(s)))return[];const n=fs(s.getBody());return n===void 0?[]:_t(n)},bo=(e,t)=>{const s=[];for(const{filePath:n}of we(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const r of o.getDescendantsOfKind(l.CallExpression))s.push(...Ao(r))}return[...new Set(s)]},ws=e=>{if(e.kind==="id")return e.tableName;if(!(e.kind!=="array"&&e.kind!=="optional"))return e.inner===void 0?void 0:ws(e.inner)},No=e=>{const t=new Set(e.tables.map(s=>s.name));return e.tables.some(s=>Object.values(s.shape).some(n=>{const o=ws(n);return o!==void 0&&t.has(o)}))},Po=(e,t)=>{const s=new Map,n=new Map;for(const o of e)s.set(o.name,`workflow "${o.exportName}"`),n.set(o.className,`workflow "${o.exportName}"`);for(const o of t){const r=s.get(o.name);if(r!==void 0)throw new j("DUPLICATE_WORKFLOW_NAME",`Duplicate deployed name "${o.name}": produced by both ${r} and agent "${o.exportName}". Workflow and agent names share one account-wide namespace and must be unique together.`,{status:500});const a=n.get(o.className);if(a!==void 0)throw new j("DUPLICATE_WORKFLOW_CLASS",`Duplicate generated class "${o.className}": produced by both ${a} and agent "${o.exportName}". Workflow and agent export names must yield unique generated class names.`,{status:500})}},wo=e=>{const{lunoraDirectory:t,project:s,projectRoot:n,schema:o}=e,r=lo(s,t),a=no(s,t),c=Sn(s,t),{queues:u,topics:d}=xn(s,t),m=Fn(n),h=bn(s,t);Po(c,h);const L=Nn(s,t),D=On(s,t),p=Pn(s,t,c,h),K=bo(s,t),b=Eo(s,t),T=Cn(s,t),_=ro(s,t);_.browser=_.browser||T.usesSandboxBrowser;const I=Ln(_,Es(n,e.target),{agents:h.length>0,commitOrderedTables:o.tables.some(C=>C.commitOrdered===!0),cronTriggers:p.length>0,crossShardFanout:o.tables.some(C=>kn(C)),containerEgressPolicy:b.containerEgressPolicy,containerRuntimeScheduling:L.some(C=>C.schedulingPolicy==="durable_object"),durableStreams:b.durableStreams,globalTables:o.tables.some(C=>C.shardMode==="global"),queues:u.length>0,relationGraph:No(o),secrets:b.secrets,services:m.length>0,topics:d.length>0,vectorStore:o.vectorIndexes.length>0,workerLoaders:T.usesSandboxLoader,workflowRollback:b.workflowRollback,workflowSchedules:c.some(C=>C.schedules!==void 0)}),A=I.usage,J=I.signals.vectorStore!==!1,Z=I.signals.services===!1?[]:m,G=Tn(n),ce=G??new Set,U=ce.has("lunorash");Xr(o,G,{hasVectors:J,scheduler:A.scheduler||p.length>0,storage:A.storage||D.rules.length>0||Object.keys(Ss(o)).length>0,usage:A});const R=w(x(t,"flags.ts")),k=w(x(t,"notify.ts"));return{agents:h,containers:L,crons:p,dataModelContent:$n(o),declaredDependencies:G,dependencies:ce,entryCronTriggers:K,env:a,featureUsage:A,hasFlags:R,hasNotify:k,identity:r,platformGate:{...I,diagnostics:[...Dn(n,e.target),...I.diagnostics]},queues:u,serverContent:_n({agents:h,containers:L,env:a,hasAccessFacade:A.access,hasAi:A.ai,hasAnalytics:A.analytics,hasBrowser:A.browser,hasVectors:J,hasFlags:R,hasHyperdrive:A.hyperdrive,hasImages:A.images,hasKv:A.kv,hasNotify:k,hasPayments:A.payments,hasPipelines:A.pipelines,hasR2sql:A.r2sql,hasX402:A.x402,identity:r,queues:u,schema:o,generatedDirectory:x(t,"_generated"),services:Z,storageRuleBuckets:D.rules.map(C=>C.bucket),topics:d,useUmbrella:U,workflows:c}),services:Z,storageRulesMetadata:D,topics:d,usesSandbox:T.usesSandboxBrowser||T.usesSandboxContainer||T.usesSandboxFs,useUmbrella:U,workflows:c}},Is=new Set(["delete","get","head","options","patch","post","put"]),Io=new Set(["handler","stream"]),To=/\/(?:_|admin|internal|superuser|sudo|root|debug)/iu,$t=new Set(["ADMIN_TOKEN","adminToken","assertAdmin","assertAuth","auth","Authorization","getSession","identity","isAdmin","requireAdmin","requireAuth","requireRole","verifyAdmin"]),Co=e=>{if(!i.isCallExpression(e))return;const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!Is.has(t.getName()))return;const s=t.getExpression();if(!i.isIdentifier(s)||s.getText()!=="httpRoute")return;const n=e.getArguments()[0];if(!(!n||!i.isStringLiteral(n)))return{method:t.getName().toUpperCase(),path:n.getLiteralValue()}},Fo=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t))return;let s=t.getExpression();for(;i.isCallExpression(s);){const n=s.getExpression();if(!i.isPropertyAccessExpression(n)||Is.has(n.getName()))break;s=n.getExpression()}return Co(s)},Oo=e=>{for(const t of e.getDescendantsOfKind(l.PropertyAccessExpression))if($t.has(t.getName()))return!0;for(const t of e.getDescendantsOfKind(l.CallExpression)){const s=t.getExpression();if(i.isIdentifier(s)&&$t.has(s.getText()))return!0}return!1},Ro=(e,t)=>{const s=e.getInitializer();if(!s||!i.isCallExpression(s))return;const n=s.getExpression();if(!i.isPropertyAccessExpression(n)||!Io.has(n.getName()))return;const o=Fo(s);if(!o||!To.test(o.path))return;const r=s.getArguments()[0],a=r!==void 0&&(i.isArrowFunction(r)||i.isFunctionExpression(r))&&Oo(r);return{exportName:e.getName(),file:t,method:o.method,path:o.path,usesGuard:a}},ko=(e,t)=>{const s=[];for(const n of e.getVariableStatements())if(n.isExported())for(const o of n.getDeclarations()){const r=Ro(o,t);r&&s.push(r)}return s},Lo=(e,t)=>{const s=[];for(const n of g(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...ko(o,v(t,n)))}return s},Do=e=>{const t=e.getText(),s=n=>{const o=n.getNameNode();return i.isIdentifier(o)&&o.getText()===t};for(const n of e.getAncestors())if(!(!i.isArrowFunction(n)&&!i.isFunctionExpression(n)&&!i.isFunctionDeclaration(n)))for(const o of n.getParameters()){const r=o.getDescendantsOfKind(l.BindingElement).find(a=>s(a));if(r!==void 0)return r}},Mo=e=>{let t=e;for(;;){const s=t.getParent();if(!i.isObjectBindingPattern(s))return;const n=s.getParent();if(i.isBindingElement(n)){t=n;continue}return i.isParameterDeclaration(n)?X(t):void 0}},zt=(e,t)=>{const s=e.getParent();if(i.isPropertyAccessExpression(s)&&s.getNameNode()===e||i.isPropertyAssignment(s)&&s.getNameNode()===e)return!1;if(e.getText()===t)return!0;const n=Do(e);return n!==void 0&&Mo(n)===t},et=(e,t)=>i.isIdentifier(e)?zt(e,t):e.getDescendantsOfKind(l.Identifier).some(s=>zt(s,t)),Be=e=>et(e,"ctx"),Ko=e=>{let t=e;for(;i.isPropertyAccessExpression(t)||i.isElementAccessExpression(t)||i.isNonNullExpression(t);)t=t.getExpression();return i.isIdentifier(t)?t:void 0},He=e=>et(e,"args"),$=e=>{if(!i.isIdentifier(e))return;const t=e.getText(),s=e.getFirstAncestor(a=>i.isArrowFunction(a)||i.isFunctionExpression(a)||i.isFunctionDeclaration(a));if(s===void 0)return;const n=e.getStart();let o,r=-1;for(const a of s.getDescendantsOfKind(l.VariableDeclaration)){if(a.getName()!==t)continue;const c=a.getInitializer(),u=a.getStart();c!==void 0&&u<n&&u>r&&(o=c,r=u)}return o},z=e=>{if(He(e))return!0;const t=$(e);return t!==void 0&&He(t)},_o=e=>{if(i.isCallExpression(e)||i.isNewExpression(e))return!1;const t=$(e);return t===void 0||!(i.isCallExpression(t)||i.isNewExpression(t))},W=e=>{if(Be(e))return!0;const t=$(e);if(t!==void 0&&Be(t))return!0;const s=t??e;return(i.isIdentifier(s)?[s]:s.getDescendantsOfKind(l.Identifier)).some(o=>{const r=$(o);return r!==void 0&&Be(r)})},xe=(e,t)=>et(e,t),$o=(e,t)=>{if(xe(e,t))return!0;const s=$(e);if(s!==void 0&&xe(s,t))return!0;const n=Ko(e);if(n!==void 0){const o=$(n);return o!==void 0&&xe(o,t)}return!1},S=e=>re(e)||"<module>",zo=e=>!i.isPropertyAccessExpression(e)||e.getName()!=="run"?!1:e.getExpression().getText()==="ctx.ai",Uo=(e,t)=>{if(!zo(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!z(s)||W(s)))return{exportName:S(e),file:t,line:e.getStartLineNumber()}},Bo=(e,t)=>O(e,t,Uo),qo=new Set(["generateText","streamText"]),jo=new Set(["messages","prompt","system"]),Wo=[{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"]}],Vo=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t))return;const s=t.getName(),n=t.getExpression().getText();for(const o of Wo)if(o.methods.has(s)&&o.prefixes.some(r=>n===r||n.startsWith(`${r}.`)))return`${n}.${s}`},Ho=e=>{for(const t of e.getDescendantsOfKind(l.CallExpression)){const s=Vo(t);if(s!==void 0)return s}},Go=e=>{const t=new Set,s=e.getFirstAncestor(r=>i.isArrowFunction(r)||i.isFunctionExpression(r)||i.isFunctionDeclaration(r)),[n]=s?.getParameters()??[],o=n?.getNameNode();if(o===void 0||!i.isObjectBindingPattern(o))return t;for(const r of o.getElements()){const a=X(r),c=r.getNameNode();if(a==="args"&&i.isObjectBindingPattern(c))for(const u of c.getElements())t.add(u.getName())}return t},Yo=e=>{if(He(e))return!0;const t=Go(e);return t.size===0?!1:e.getDescendantsOfKind(l.Identifier).some(s=>t.has(s.getText()))},Qo=e=>{for(const t of e.getProperties()){if(!i.isPropertyAssignment(t)||!jo.has(E(t)))continue;const s=t.getInitializer();if(s!==void 0&&Yo(s))return!0}return!1},Xo=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression)){const o=y(n.getExpression());if(o===void 0||!qo.has(o))continue;const[r]=n.getArguments();if(r===void 0||!i.isObjectLiteralExpression(r))continue;let a;for(const c of r.getDescendantsOfKind(l.CallExpression))if(y(c.getExpression())==="tool"&&(a=Ho(c),a!==void 0))break;a!==void 0&&s.push({exportName:S(n),file:t,line:n.getStartLineNumber(),method:o,sideEffect:a,userInputDerived:Qo(r)})}return s},Jo=(e,t)=>{const s=[];for(const n of g(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Xo(o,v(t,n)))}return s},Zo=e=>{if(!i.isPropertyAccessExpression(e)||e.getName()!=="fetch")return!1;const t=e.getExpression();return i.isIdentifier(t)&&t.getText()==="ctx"},ei=(e,t)=>{if(!Zo(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!z(s)))return{exportName:S(e),file:t,line:e.getStartLineNumber()}},ti=(e,t)=>O(e,t,ei),tt=(e,t=new Set)=>{if(t.has(e))return!0;t.add(e);try{return e.getProperties().some(s=>{if(!i.isSpreadAssignment(s))return!1;const n=Ie(s.getExpression());return n===void 0||tt(n,t)})}finally{t.delete(e)}},si=e=>{const t=e.getArguments()[0];if(!t||!i.isObjectLiteralExpression(t))return{objects:[],opaque:!0};const s=F(t,"args");if(!s)return{objects:[],opaque:!1};if(!i.isPropertyAssignment(s))return{objects:[],opaque:!0};const n=s.getInitializer(),o=n===void 0?void 0:Ie(n);return o===void 0?{objects:[],opaque:!0}:{objects:[o],opaque:tt(o)}},ni=e=>{const t=[];let s=!1,n=e;for(;i.isCallExpression(n);){const o=n.getExpression();if(!i.isPropertyAccessExpression(o))break;if(o.getName()==="input"){const r=n.getArguments()[0],a=r!==void 0&&i.isExpression(r)?Ie(r):void 0;a===void 0?s=!0:(t.push(a),s||=tt(a))}n=o.getExpression()}return{objects:t,opaque:s}},st=(e,t)=>t?ni(t):si(e),Ts=(e,t)=>{if(t.has(e))return[];t.add(e);try{return e.getProperties().flatMap(s=>{if(i.isSpreadAssignment(s)){const n=Ie(s.getExpression());return n===void 0?[]:Ts(n,t)}return i.isPropertyAssignment(s)||i.isShorthandPropertyAssignment(s)?[E(s)]:[]})}finally{t.delete(e)}},ri=e=>e.flatMap(t=>Ts(t,new Set)),oi=new Set(["check","length","max"]),Ge=e=>{if(!i.isCallExpression(e))return;const t=e.getExpression();if(!(!i.isPropertyAccessExpression(t)||t.getExpression().getText()!=="v"))return t.getName()},ii=e=>[e,...e.getDescendants()].filter(t=>Ge(t)!==void 0),ai=e=>{let t=e;for(;;){const s=t.getParent();if(!s||!i.isPropertyAccessExpression(s)||s.getExpression()!==t)return!1;const n=s.getParent();if(!n||!i.isCallExpression(n)||n.getExpression()!==s)return!1;if(oi.has(s.getName()))return!0;t=n}},ci=e=>{const t=[],s=[];for(const n of e)for(const o of n.getProperties()){if(!i.isPropertyAssignment(o))continue;const r=o.getInitializer();if(!r)continue;const a=ii(r),c=E(o);a.some(u=>Ge(u)==="any")?t.push(c):a.some(u=>Ge(u)==="string"&&!ai(u))&&s.push(c)}return{anyArgs:t,unboundedStringArgs:s}},li=(e,t)=>{const s=e.getInitializer();if(!s||!i.isCallExpression(s))return;const n=B(s);if(n?.visibility!=="public")return;const{objects:o}=st(s,n.receiver),{anyArgs:r,unboundedStringArgs:a}=ci(o);if(!(r.length===0&&a.length===0))return{anyArgs:r,exportName:e.getName(),file:t,line:s.getStartLineNumber(),unboundedStringArgs:a}},ui=(e,t)=>{const s=[];for(const n of e.getVariableStatements())if(n.isExported())for(const o of n.getDeclarations()){const r=li(o,t);r&&s.push(r)}return s},di=(e,t)=>{const s=[];for(const n of g(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...ui(o,v(t,n)))}return s},qe=e=>e?.getKind()===l.TrueKeyword,fi=e=>e?.getKind()===l.FalseKeyword,pi=e=>e!==void 0&&i.isNumericLiteral(e)&&e.getLiteralValue()===0,gi=new Set(["lunoraAuthAdapter","lunoraD1Adapter"]),mi=e=>!e||!i.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>i.isCallExpression(t)&&y(t.getExpression())==="scim"),hi=e=>e!==void 0&&i.isCallExpression(e)&&gi.has(y(e.getExpression())??""),vi=e=>!e||!i.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>i.isStringLiteral(t)&&t.getLiteralText()==="*"),xi=e=>{const t=N(e,"advanced"),s=N(e,"emailAndPassword"),n=N(e,"session");return{analyzable:!0,disableCsrfCheck:qe(N(t,"disableCSRFCheck")),emailPasswordEnabled:qe(N(s,"enabled")),requireEmailVerification:qe(N(s,"requireEmailVerification")),scimOnNonTransactionalAdapter:mi(N(e,"plugins"))&&hi(N(e,"database")),secureCookiesDisabled:fi(N(t,"useSecureCookies")),sessionFreshAgeZero:pi(N(n,"freshAge")),trustedOriginsWildcard:vi(N(e,"trustedOrigins"))}},Ei=()=>({analyzable:!1,disableCsrfCheck:!1,emailPasswordEnabled:!1,requireEmailVerification:!1,scimOnNonTransactionalAdapter:!1,secureCookiesDisabled:!1,sessionFreshAgeZero:!1,trustedOriginsWildcard:!1}),Si=(e,t)=>{if(y(e.getExpression())!=="createAuth")return;const s=e.getArguments()[0],n=s!==void 0&&i.isObjectLiteralExpression(s)&&s.getProperties().some(r=>i.isSpreadAssignment(r)),o=s!==void 0&&i.isObjectLiteralExpression(s)&&!n?xi(s):Ei();return{exportName:S(e),file:t,line:e.getStartLineNumber(),...o}},yi=(e,t)=>wn(e,t,Si),Ai=(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},bi=(e,t,s)=>{const n=Ai(e.getExpression(),s);if(n===void 0)return;const o=e.getArguments()[s.argIndex];if(!(!o||!z(o)||W(o))&&!(s.requireUnmodifiedReach===!0&&!_o(o)))return{exportName:S(e),file:t,line:e.getStartLineNumber(),method:n}},Ni=(e,t,s)=>{const n=[];for(const o of e.getDescendantsOfKind(l.CallExpression)){const r=bi(o,t,s);r&&n.push(r)}return n},Te=(e,t,s)=>{const n=[];for(const o of g(t)){const r=e.getSourceFile(o)??e.addSourceFileAtPath(o);n.push(...Ni(r,v(t,o),s))}return n},Pi=new Set(["content","pdf","scrape","screenshot"]),wi=(e,t)=>Te(e,t,{argIndex:0,matchReceiver:s=>s==="ctx.browser",methods:Pi}),Cs=e=>{const t=gs(e);return t===void 0?void 0:`${Ne(t.slice(0,-1).join("/"))}:${String(t.at(-1))}`},Fs=(e,t)=>{if(!i.isPropertyAccessExpression(e))return;const s=e.getExpression();if(!i.isPropertyAccessExpression(s))return;const n=s.getExpression();return i.isPropertyAccessExpression(n)&&n.getName()===t?s.getName():void 0},Ii=e=>{if(!i.isPropertyAccessExpression(e))return!1;const t=e.getExpression();return i.isPropertyAccessExpression(t)&&t.getName()==="scheduler"||i.isIdentifier(t)&&t.getText()==="scheduler"},Ti=new Map([["publish",{kind:"publish",surface:"topics"}],["publishBatch",{kind:"publish",surface:"topics"}],["send",{kind:"enqueue",surface:"queues"}],["sendBatch",{kind:"enqueue",surface:"queues"}]]),Ci=(e,t)=>{const s=Cs(t);return s!==void 0?{kind:"call",target:s}:e!=="run"&&t!==void 0?{kind:"call",reason:"the function reference is not a static api.* / internal.* chain"}:void 0},Fi=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t))return;const s=t.getName(),[n,o]=e.getArguments();if(ps.has(s))return Ci(s,n);if((s==="runAfter"||s==="runAt")&&Ii(t)){const c=Cs(o);return c===void 0?{kind:"schedule",reason:"the scheduled function is not a static api.* / internal.* chain"}:{kind:"schedule",target:c}}const r=Ti.get(s),a=r===void 0?void 0:Fs(t,r.surface);return r===void 0||a===void 0?void 0:{kind:r.kind,target:a}},Oi=(e,t)=>{const s=[];for(const n of g(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=v(t,n);for(const a of o.getDescendantsOfKind(l.CallExpression)){const c=Fi(a);c!==void 0&&s.push({...c,exportName:re(a),file:r,line:a.getStartLineNumber()})}for(const a of o.getDescendantsOfKind(l.PropertyAccessExpression)){const c=Fs(a,"services");c!==void 0&&s.push({exportName:re(a),file:r,kind:"invoke",line:a.getStartLineNumber(),target:c})}}return s},Ri=new Set(["createBrowser","createInboundEmailHandler","createPayment"]),ki=new Set(["RateLimiter"]),Li=new Set(["extend"]),Ut="lunora",Di=["vite.config.ts","vite.config.mts","vite.config.js","vite.config.mjs"],Os=e=>{const t=[],s=[];let n=!1;for(const o of e.getProperties()){if(i.isSpreadAssignment(o)){n=!0;continue}if(i.isPropertyAssignment(o)){const r=E(o);t.push(r),o.getInitializer()?.getKind()===l.TrueKeyword&&s.push(r);continue}(i.isShorthandPropertyAssignment(o)||i.isMethodDeclaration(o))&&t.push(E(o))}return{analyzable:!n,presentKeys:t,trueKeys:s}},Ye=e=>e&&i.isObjectLiteralExpression(e)?Os(e):{analyzable:!1,presentKeys:[],trueKeys:[]},Mi=e=>{const t=e&&(i.isArrowFunction(e)||i.isFunctionExpression(e))?e:void 0,s=t&&fs(t.getBody());return s?Os(s):{analyzable:!1,presentKeys:[],trueKeys:[]}},Ki=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression)){const o=y(n.getExpression());o!==void 0&&(Ri.has(o)?s.push({callee:o,file:t,line:n.getStartLineNumber(),...Ye(n.getArguments()[0])}):Li.has(o)&&s.push({callee:o,file:t,line:n.getStartLineNumber(),...Mi(n.getArguments()[0])}))}for(const n of e.getDescendantsOfKind(l.NewExpression)){const o=y(n.getExpression());o===void 0||!ki.has(o)||s.push({callee:o,file:t,line:n.getStartLineNumber(),...Ye(n.getArguments()[0])})}return s},_i=(e,t)=>{for(const s of Di){const n=x(t,s);if(!w(n))continue;const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=[];for(const a of o.getDescendantsOfKind(l.CallExpression))y(a.getExpression())===Ut&&r.push({callee:Ut,file:s,line:a.getStartLineNumber(),...Ye(a.getArguments()[0])});return r}return[]},$i=(e,t)=>{const s=[];for(const{displayPath:n,filePath:o}of we(t)){const r=e.getSourceFile(o)??e.addSourceFileAtPath(o);s.push(...Ki(r,n))}return s.push(..._i(e,he(t))),s},Bt="ctx.containers.",zi=e=>{if(!e.startsWith(Bt))return!1;const t=e.slice(Bt.length);return t.length>0&&!t.includes(".")},Ui=(e,t)=>Te(e,t,{argIndex:0,matchReceiver:zi,methods:new Set(["get"])}),Bi=new Set(["allow","deny","setAllowed"]),qi=e=>{const t=e.getArguments()[0];if(!t||!i.isObjectLiteralExpression(t))return!1;const s=F(t,"enableInternet");return s!==void 0&&i.isPropertyAssignment(s)&&i.isTrueLiteral(s.getInitializerOrThrow())},ji=(e,t)=>{const s=e.getExpression();if(!(!i.isPropertyAccessExpression(s)||s.getName()!=="start"||!qi(e)))return{detail:"enableInternet: true",exportName:S(e),file:t,kind:"enable_internet",line:e.getStartLineNumber()}},Wi=(e,t)=>{const s=e.getExpression();if(!i.isPropertyAccessExpression(s)||!Bi.has(s.getName()))return;const n=s.getExpression();if(!(!i.isPropertyAccessExpression(n)||n.getName()!=="egress"))return{detail:s.getName(),exportName:S(e),file:t,kind:"egress_relaxation",line:e.getStartLineNumber()}},Vi=(e,t)=>ji(e,t)??Wi(e,t),Hi=(e,t)=>O(e,t,Vi),Gi=new Set(["defineExportSink","r2Sink","webhookExportSink"]),Yi=e=>{const t=e.getExpression();if(!i.isIdentifier(t))return;const s=t.getText();return Gi.has(s)?s:void 0},Qi=e=>{const t=[],s=[];for(const n of e.getProperties()){if(i.isSpreadAssignment(n))return{analyzable:!1,emptyKeys:[],presentKeys:[]};if(i.isPropertyAssignment(n)){const o=E(n);t.push(o);const r=n.getInitializer();r&&i.isStringLiteral(r)&&r.getLiteralText()===""&&s.push(o);continue}(i.isShorthandPropertyAssignment(n)||i.isMethodDeclaration(n)||i.isGetAccessorDeclaration(n))&&t.push(E(n))}return{analyzable:!0,emptyKeys:s,presentKeys:t}},Xi=(e,t)=>{const s=[];for(const{displayPath:n,filePath:o}of we(t)){const r=e.getSourceFile(o)??e.addSourceFileAtPath(o);for(const a of r.getDescendantsOfKind(l.CallExpression)){const c=Yi(a);if(c===void 0)continue;const u=a.getArguments()[0],d=u&&i.isObjectLiteralExpression(u)?Qi(u):{analyzable:!1,emptyKeys:[],presentKeys:[]};s.push({analyzable:d.analyzable,emptyKeys:d.emptyKeys,factory:c,file:n,line:a.getStartLineNumber(),presentKeys:d.presentKeys})}}return s},Ji=new Map([["dbRateLimit",2],["rateLimit",2],["verifyTurnstileMiddleware",0]]),Zi=new Set(["dbRateLimit","rateLimit"]),ea=e=>{const t=hs(e);if(!t)return!1;const s=F(t,"failOpen");return s!==void 0&&i.isPropertyAssignment(s)&&s.getInitializer()?.getKind()===l.TrueKeyword},ta=(e,t)=>{const s=y(e.getExpression());if(s===void 0)return;const n=Ji.get(s);if(n!==void 0)return{callee:s,exportName:S(e),failOpen:ea(e.getArguments()[n]),file:t,limitName:Zi.has(s)?ms(e):"",line:e.getStartLineNumber()}},sa=(e,t)=>O(e,t,ta),na=new Set(["boolean","number","object","string"]),ra=e=>{const t=e.getName();if(!na.has(t))return;const s=e.getExpression();if(!i.isPropertyAccessExpression(s))return;if(s.getName()==="flags"&&Ve(s.getExpression()))return t;const n=s.getExpression();if(s.getName()==="details"&&i.isPropertyAccessExpression(n)&&n.getName()==="flags"&&Ve(n.getExpression()))return t},oa=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t))return;const s=ra(t);if(s===void 0)return;const n=e.getArguments()[0];if(!n||!(i.isStringLiteral(n)||i.isNoSubstitutionTemplateLiteral(n)))return;const o=n.getLiteralValue();return o.length>0?{key:o,type:s}:void 0},ia=(e,t)=>{const s=new Map;for(const n of g(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const r of o.getDescendantsOfKind(l.CallExpression)){const a=oa(r);a&&!s.has(a.key)&&s.set(a.key,a.type)}}return[...s.entries()].map(([n,o])=>({key:n,type:o})).toSorted((n,o)=>n.key.localeCompare(o.key))},aa=e=>{const t=e.getInitializer();if(!t||!i.isCallExpression(t))return;const s=B(t);if(s?.kind!=="query")return;const n=In(t,s.receiver);return n?{exportName:e.getName(),handler:n}:void 0},qt=e=>{const t=e.getParent();return t&&i.isPropertyAccessExpression(t)&&t.getExpression()===e?t:void 0},ca=e=>{if(!i.isPropertyAccessExpression(e)||e.getName()!=="flags")return;const t=e.getExpression();if(!i.isIdentifier(t)||t.getText()!=="ctx")return;const s=qt(e);if(!s)return"ctx.flags";if(s.getName()==="details"){const n=qt(s);return n?`ctx.flags.details.${n.getName()}`:"ctx.flags.details"}return`ctx.flags.${s.getName()}`},la=(e,t)=>{const s=[];for(const n of e.handler.getDescendantsOfKind(l.PropertyAccessExpression)){const o=ca(n);o!==void 0&&s.push({callee:o,exportName:e.exportName,file:t,line:n.getStartLineNumber()})}return s},ua=(e,t)=>{const s=[];for(const n of e.getVariableStatements())if(n.isExported())for(const o of n.getDeclarations()){const r=aa(o);r&&s.push(...la(r,t))}return s},da=(e,t)=>{const s=[];for(const n of g(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...ua(o,v(t,n)))}return s},fa=e=>{if(!i.isPropertyAccessExpression(e)||e.getName()!=="boolean")return!1;const t=e.getExpression();return i.isPropertyAccessExpression(t)&&t.getName()==="flags"&&Ve(t.getExpression())},pa=e=>{if(e?.getKind()===l.TrueKeyword)return!0;if(e?.getKind()===l.FalseKeyword)return!1},ga=(e,t)=>{if(!fa(e.getExpression()))return;const[s,n]=e.getArguments();if(!s||!(i.isStringLiteral(s)||i.isNoSubstitutionTemplateLiteral(s)))return;const o=s.getLiteralValue(),r=pa(n);if(!(o.length===0||r===void 0))return{defaultValue:r,exportName:S(e),file:t,key:o,line:e.getStartLineNumber()}},ma=(e,t)=>O(e,t,ga),ha=e=>{const t=e.getType().getProperty("~standard");if(!t)return;const s=t.getTypeAtLocation(e).getProperty("types");if(!s)return;const n=s.getTypeAtLocation(e).getNonNullableType().getProperty("output");if(!n)return;const o=n.getTypeAtLocation(e),r=o.getText(e);if(!r||r==="any"||r==="never"||Bn(r))return;const a=e.getSourceFile().getFilePath();if(qn(o,e,a)){const c=jn(o,e,a,0,new Set);return c===void 0&&Wn(r),c}return r},va=e=>{const t=e.getExpression();return i.isPropertyAccessExpression(t)&&t.getName()==="withGeoIndex"},xa=e=>{const t=e.getArguments()[0];return t&&i.isStringLiteral(t)?t.getLiteralText():""},Ea=(e,t)=>{const s=[];for(const n of g(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=v(t,n);for(const a of o.getDescendantsOfKind(l.CallExpression))va(a)&&s.push({file:r,indexName:xa(a),line:a.getStartLineNumber()})}return s},oe=e=>e!==void 0&&(i.isArrowFunction(e)||i.isFunctionExpression(e))?e:void 0,Rs=e=>{const t=e.getArguments()[0],s=oe(t);if(s!==void 0)return s;if(t===void 0||!i.isObjectLiteralExpression(t))return;const n=F(t,"handler");return n!==void 0&&i.isPropertyAssignment(n)?oe(n.getInitializer()):void 0},Sa=new Set(["delete","get","head","options","patch","post","put"]),ya=new Set(["handler","stream"]),Aa=new Set(["runAction","runMutation"]),ba=new Set(["delete","insert","insertManyUnsafe","patch","replace"]),ie=(e,t)=>e!==void 0&&i.isIdentifier(e)&&e.getText()===t,ks=(e,t)=>{if(!(e===void 0||!i.isObjectBindingPattern(e))){for(const s of e.getElements())if(X(s)===t){const o=s.getNameNode();return i.isIdentifier(o)?o.getText():void 0}}},jt=(e,t)=>{const s=e.getParameters()[0]?.getNameNode();if(s!==void 0)return t?i.isIdentifier(s)?s.getText():void 0:ks(s,"ctx")},Wt=(e,t)=>{const s=e.getParameters()[t?1:0]?.getNameNode();return t?s!==void 0&&i.isIdentifier(s)?s.getText():void 0:ks(s,"request")},Vt=(e,t)=>{const s=e.getBody(),n=s.getDescendantsOfKind(l.CallExpression);i.isCallExpression(s)&&n.unshift(s);for(const o of n){const r=o.getExpression();if(!i.isPropertyAccessExpression(r))continue;const a=r.getName(),c=r.getExpression();if(Aa.has(a)&&ie(c,t))return a;if(ba.has(a)&&i.isPropertyAccessExpression(c)&&c.getName()==="db"&&ie(c.getExpression(),t))return`db.${a}`}},Ht=(e,t)=>{const s=e.getBody();for(const n of s.getDescendantsOfKind(l.PropertyAccessExpression))if(n.getName()==="auth"&&ie(n.getExpression(),t))return!0;for(const n of s.getDescendantsOfKind(l.VariableDeclaration)){const o=n.getNameNode();if(!(!i.isObjectBindingPattern(o)||!ie(n.getInitializer(),t))){for(const r of o.getElements())if(X(r)==="auth")return!0}}return!1},Na=/signature|hmac|digest|(?:^|[_-])sig(?:[_-]|$)/i,Pa=(e,t)=>{const s=e.getExpression();if(!i.isPropertyAccessExpression(s)||s.getName()!=="get"&&s.getName()!=="has")return!1;const n=s.getExpression();return i.isPropertyAccessExpression(n)&&n.getName()==="headers"&&ie(n.getExpression(),t)},wa=e=>[...i.isStringLiteral(e)?[e.getLiteralText()]:[],...e.getDescendantsOfKind(l.StringLiteral).map(t=>t.getLiteralText())],Ls=(e,t)=>{const s=e.getVariableDeclaration(t)?.getInitializer();return s===void 0?[]:wa(s)},Ia=(e,t)=>{const s=e.getText();for(let n=e.getParent();n!==void 0;n=n.getParent()){if(!i.isArrowFunction(n)&&!i.isFunctionExpression(n)||!n.getParameters().some(c=>c.getName()===s))continue;const o=n.getParent();if(!i.isCallExpression(o))return[];const r=o.getExpression();if(!i.isPropertyAccessExpression(r))return[];const a=r.getExpression();return i.isIdentifier(a)?Ls(t,a.getText()):[]}return[]},Ta=e=>{const t=e.getArguments()[0];if(t===void 0)return[];if(i.isStringLiteral(t))return[t.getLiteralText()];if(!i.isIdentifier(t))return[];const s=e.getSourceFile(),n=Ls(s,t.getText());return n.length>0?n:Ia(t,s)},Gt=(e,t)=>{if(t===void 0)return!1;const s=e.getBody(),n=s.getDescendantsOfKind(l.CallExpression);return i.isCallExpression(s)&&n.unshift(s),n.some(o=>Pa(o,t)&&Ta(o).some(r=>Na.test(r)))},Ca=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!ya.has(t.getName()))return;let s=t.getExpression();for(;i.isCallExpression(s);){const n=s.getExpression();if(!i.isPropertyAccessExpression(n))return;const o=n.getName();if(Sa.has(o)){const r=n.getExpression();return i.isIdentifier(r)&&r.getText()==="httpRoute"?o.toUpperCase():void 0}s=n.getExpression()}},Fa=(e,t)=>{const s=e.getExpression();if(i.isIdentifier(s)&&s.getText()==="httpAction"){const c=oe(e.getArguments()[0]),u=c&&jt(c,!0);if(!c||u===void 0||Gt(c,Wt(c,!0)))return;const d=Vt(c,u);return d===void 0?void 0:{exportName:S(e),file:t,kind:"httpAction",line:e.getStartLineNumber(),readsAuth:Ht(c,u),sideEffect:d}}const n=Ca(e);if(n===void 0)return;const o=oe(e.getArguments()[0]),r=o&&jt(o,!1);if(!o||r===void 0||Gt(o,Wt(o,!1)))return;const a=Vt(o,r);return a===void 0?void 0:{exportName:S(e),file:t,kind:"httpRoute",line:e.getStartLineNumber(),method:n,readsAuth:Ht(o,r),sideEffect:a}},Oa=(e,t)=>O(e,t,Fa),Ra=new Set(["btoa","encodeURI","encodeURIComponent","isSafeHeaderValue","Number","parseFloat","parseInt"]),ka=new Set(["append","set"]),Ds=e=>e!==void 0&&(i.isStringLiteral(e)||i.isNoSubstitutionTemplateLiteral(e))?e.getLiteralText():"",Yt=(e,t)=>(i.isCallExpression(e)?[e,...e.getDescendantsOfKind(l.CallExpression)]:e.getDescendantsOfKind(l.CallExpression)).some(n=>Ra.has(y(n.getExpression())??"")&&xe(n,t)),La=(e,t)=>{if(Yt(e,t))return!0;const s=$(e);return s!==void 0&&Yt(s,t)},Qe=(e,t)=>$o(e,t)&&!La(e,t),Da=e=>{if(i.isPropertyAccessExpression(e)&&e.getName()==="headers")return!0;const t=$(e);return t!==void 0&&i.isNewExpression(t)&&y(t.getExpression())==="Headers"},ye=e=>{if(e===void 0)return;if(i.isObjectLiteralExpression(e))return e;const t=$(e);return t!==void 0&&i.isObjectLiteralExpression(t)?t:void 0},nt=(e,t,s)=>{for(const n of e.getProperties())if(i.isPropertyAssignment(n)){const o=n.getInitializer();o!==void 0&&Qe(o,s.requestName)&&s.rows.push({exportName:s.exportName,file:s.relativePath,headerName:Ds(n.getNameNode()),line:o.getStartLineNumber(),via:t})}else if(i.isShorthandPropertyAssignment(n)){const o=n.getNameNode();Qe(o,s.requestName)&&s.rows.push({exportName:s.exportName,file:s.relativePath,headerName:E(n),line:o.getStartLineNumber(),via:t})}else if(i.isSpreadAssignment(n)){const o=ye(n.getExpression());o!==void 0&&nt(o,t,s)}},Ms=(e,t)=>{const s=ye(e);if(s===void 0)return;const n=F(s,"headers");if(n===void 0||!i.isPropertyAssignment(n))return;const o=ye(n.getInitializer());o!==void 0&&nt(o,"response-init",t)},Ma=(e,t)=>{const s=y(e.getExpression());if(s==="Response")Ms(e.getArguments()[1],t);else if(s==="Headers"){const n=ye(e.getArguments()[0]);n!==void 0&&nt(n,"headers-ctor",t)}},Ka=(e,t)=>{const s=e.getExpression();if(!i.isPropertyAccessExpression(s))return;const n=s.getName(),o=s.getExpression();if(n==="json"&&i.isIdentifier(o)&&o.getText()==="Response"){Ms(e.getArguments()[1],t);return}if(ka.has(n)&&Da(o)){const r=e.getArguments()[1];r!==void 0&&Qe(r,t.requestName)&&t.rows.push({exportName:t.exportName,file:t.relativePath,headerName:Ds(e.getArguments()[0]),line:r.getStartLineNumber(),via:n==="set"?"headers-set":"headers-append"})}},_a=(e,t)=>{for(const s of e.getDescendantsOfKind(l.NewExpression))Ma(s,t);for(const s of e.getDescendantsOfKind(l.CallExpression))Ka(s,t)},$a=(e,t)=>{const s=e.getExpression();if(!i.isIdentifier(s)||s.getText()!=="httpAction")return[];const n=oe(e.getArguments()[0]);if(n===void 0)return[];const o=n.getParameters()[1];if(o===void 0)return[];const r=o.getNameNode();if(!i.isIdentifier(r))return[];const a=[];return _a(n,{exportName:S(e),relativePath:t,requestName:r.getText(),rows:a}),a},za=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression))s.push(...$a(n,t));return s},Ua=(e,t)=>{const s=[];for(const n of g(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...za(o,v(t,n)))}return s},Ba=new Set(["auth","context.auth","ctx.auth"]),qa="userId",ja=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(E(s))}return t},Wa=(e,t)=>{const s=x(t,Ps);if(!w(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const o of n.getDescendantsOfKind(l.CallExpression)){if(y(o.getExpression())!=="defineIdentity")continue;const[r]=o.getArguments();return r&&i.isObjectLiteralExpression(r)?ja(r):void 0}},Qt=e=>{if(!(e===void 0||!i.isPropertyAccessExpression(e)||e.getName()!=="identity"))return Ba.has(e.getExpression().getText())?e:void 0},Va=e=>{if(i.isPropertyAccessExpression(e)&&Qt(e.getExpression())!==void 0)return e.getName();if(i.isElementAccessExpression(e)&&Qt(e.getExpression())!==void 0){const t=e.getArgumentExpression();return t&&i.isStringLiteral(t)?t.getLiteralValue():void 0}},Ha=(e,t,s)=>{const n=[];for(const o of e.getDescendants()){const r=Va(o);r!==void 0&&n.push({declared:r===qa||s.has(r),exportName:S(o),file:t,key:r,line:o.getStartLineNumber()})}return n},Ga=(e,t)=>{const s=Wa(e,t);if(s===void 0)return[];const n=[];for(const o of g(t)){const r=e.getSourceFile(o)??e.addSourceFileAtPath(o);n.push(...Ha(r,v(t,o),s))}return n},Ya=(e,t)=>{if(y(e.getExpression())!=="buildImageDeliveryUrl")return;const s=e.getArguments()[0];if(!s)return;const n=N(s,"key");if(!(!n||!z(n)||W(n)))return{exportName:S(e),file:t,line:e.getStartLineNumber()}},Qa=(e,t)=>O(e,t,Ya),Xa=e=>{if(i.isComputedPropertyName(e)){const t=e.getExpression();return i.isStringLiteral(t)||i.isNoSubstitutionTemplateLiteral(t)?t.getLiteralValue():void 0}return i.isStringLiteral(e)?e.getLiteralValue():e.getText()},Ja=e=>e.getProperties().some(t=>{if(i.isSpreadAssignment(t))return!0;const s=Xa(t.getNameNode());return s===void 0||s==="namespace"}),Za=(e,t)=>{for(const{filePath:s}of we(t)){const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const o of n.getDescendantsOfKind(l.CallExpression)){const r=o.getExpression(),[a]=o.getArguments();if(!(!i.isPropertyAccessExpression(r)||r.getName()!=="auth"||a===void 0)&&(!i.isObjectLiteralExpression(a)||Ja(a)))return o}}},ec="https://lunora.sh/docs/concepts/data-residency#pinning-auth-and-voice",tc=(e,t)=>{if(!(e.jurisdiction===void 0||e.jurisdictionPinsAuth===!0||t===void 0))throw ae(t,`the schema pins Durable Objects to the "${e.jurisdiction}" jurisdiction, and this project also has DO-backed auth (users, sessions, accounts, credentials). Pinning the auth object resolves it to a NEW, EMPTY object: existing users stay in the unpinned one until you copy them across (${ec}). Acknowledge with \`.jurisdiction("${e.jurisdiction}", { pinAuth: true })\`, deploy, then run the copy. For D1-mode auth the acknowledgement changes nothing.`,{code:"JURISDICTION_MOVE",status:422})},sc=new Set(["delete","get","getRaw","getWithMetadata","put"]),nc=(e,t,s=[])=>{const n=new Map(s.map(r=>[`${r.filePath}:${r.exportName}`,r.visibility]));return Te(e,t,{argIndex:0,matchReceiver:r=>r==="ctx.kv"||r.startsWith("ctx.kv."),methods:sc}).map(r=>{const a=n.get(`${r.file}:${r.exportName}`);return a===void 0?r:{...r,visibility:a}})},rc=new Set(["queue","send"]),Xt=new Set(["bcc","cc","to"]),oc=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName();if(!rc.has(t))return;const s=e.getExpression().getText();return s==="ctx.mail"||s==="ctx.email"?t:void 0},ic=e=>i.isObjectLiteralExpression(e)?e.getProperties().some(t=>{if(i.isShorthandPropertyAssignment(t)){const n=t.getNameNode();return Xt.has(E(t))&&z(n)&&!W(n)}if(!i.isPropertyAssignment(t)||!Xt.has(E(t)))return!1;const s=t.getInitializer();return s!==void 0&&z(s)&&!W(s)}):!1,ac=(e,t)=>{const s=oc(e.getExpression());if(s===void 0)return;const n=e.getArguments()[0];if(!(!n||!ic(n)))return{exportName:S(e),file:t,line:e.getStartLineNumber(),method:s}},cc=(e,t)=>O(e,t,ac),lc=e=>i.isPropertyAssignment(e)||i.isMethodDeclaration(e)||i.isGetAccessorDeclaration(e)?i.isComputedPropertyName(e.getNameNode()):!1,uc=e=>i.isPropertyAssignment(e)||i.isShorthandPropertyAssignment(e)||i.isMethodDeclaration(e)||i.isGetAccessorDeclaration(e)?lc(e):!0,Ks=(e,t=!1)=>{for(const s of e.getProperties()){if(uc(s))return!0;if(t)continue;if(!i.isPropertyAssignment(s))return!0;const n=s.getInitializer();if(!n||!i.isObjectLiteralExpression(n)||Ks(n,!0))return!0}return!1},dc=(e,t)=>{for(const s of g(t)){const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const{receiver:o}of As(n))for(const r of Ze(o)){const a=r.getArguments()[0];if(a!==void 0&&(!i.isObjectLiteralExpression(a)||Ks(a)))return!0}}return!1},fc=e=>{const t=e.getArguments()[0];if(!t||!i.isObjectLiteralExpression(t))return[];const s=[];for(const n of t.getProperties()){const o=Se(n);if(o===void 0||!i.isPropertyAssignment(n))continue;const r=n.getInitializer();if(!(!r||!i.isObjectLiteralExpression(r)))for(const a of r.getProperties()){const c=Se(a);c!==void 0&&s.push({column:c,strategy:ys(a),table:o})}}return s},pc=(e,t)=>{const s=new Map;for(const n of g(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const{receiver:r}of As(o))for(const a of Ze(r))for(const c of fc(a)){const u=`${c.table}\0${c.column}`;s.has(u)||s.set(u,c)}}return{columns:[...s.values()]}},gc=(e,t,s)=>{const n=e.getArguments()[0];if(!n||!i.isObjectLiteralExpression(n))return[];const o=[];for(const r of n.getProperties()){const a=Se(r);if(a===void 0||!i.isPropertyAssignment(r))continue;const c=r.getInitializer();if(!(!c||!i.isObjectLiteralExpression(c)))for(const u of c.getProperties()){const d=Se(u);if(d===void 0)continue;const m=ys(u);m!=="custom"&&o.push({column:d,exportName:t,file:s,line:u.getStartLineNumber(),strategy:m,table:a})}}return o},mc=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&i.isCallExpression(s)?B(s):void 0;return n?.receiver?Ze(n.receiver).flatMap(o=>gc(o,e.getName(),t)):[]},hc=(e,t)=>{const s=[];for(const n of g(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=v(t,n);for(const a of o.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...mc(c,r))}return s},vc=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="replace")return!1;const s=t.getExpression();return M(s)},xc=e=>{const t=e.getArguments()[0];if(t===void 0||!i.isObjectLiteralExpression(t))return;const s=F(t,"server");if(s!==void 0)return i.isPropertyAssignment(s)?s.getInitializer():s},Ec=e=>{if(!e.isExported())return;const t=e.getInitializer();if(t?.getKind()!==l.CallExpression)return;const s=t;return tr(s.getExpression())?s:void 0},Sc=e=>{const t=Ec(e),s=t===void 0?void 0:xc(t);if(s===void 0)return[];const n=e.getNameNode(),o=i.isIdentifier(n)?n.getText():"";return s.getDescendantsOfKind(l.CallExpression).filter(r=>vc(r)).map(r=>({exportName:o,file:"lunora/mutators.ts",line:r.getStartLineNumber()}))},yc=e=>e.getVariableDeclarations().flatMap(t=>Sc(t)),Ac=(e,t)=>{const s=x(t,er);if(!w(s))return[];const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);return yc(n)},bc=new Set(["delete","get","patch"]),Nc=new Set(["accountId","authorId","companyId","createdBy","createdById","customerId","groupId","memberId","organizationId","orgId","ownerId","projectId","teamId","tenantId","userId","workspaceId"]),Pc=new Set(["auth","identity","session","user"]),wc=new Set([l.EqualsEqualsEqualsToken,l.EqualsEqualsToken,l.ExclamationEqualsEqualsToken,l.ExclamationEqualsToken]),Ic=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="normalizeId"||!M(t.getExpression()))return;const s=e.getArguments()[0];return s&&i.isStringLiteral(s)?s.getLiteralText():""},Tc=e=>{let t=e,s=t.getParent();for(;s!==void 0&&(i.isAsExpression(s)||i.isParenthesizedExpression(s)||i.isNonNullExpression(s));)t=s,s=t.getParent();if(s===void 0||!i.isVariableDeclaration(s))return;const n=s.getNameNode();return i.isIdentifier(n)?n.getText():void 0},Cc=(e,t)=>e.getDescendantsOfKind(l.Identifier).some(s=>s.getText()===t),Fc=e=>i.isThrowStatement(e)||i.isReturnStatement(e)||e.getDescendantsOfKind(l.ThrowStatement).length>0||e.getDescendantsOfKind(l.ReturnStatement).length>0,Oc=(e,t)=>e.getDescendantsOfKind(l.IfStatement).some(s=>Cc(s.getExpression(),t)&&Fc(s.getThenStatement())),Rc=(e,t)=>{for(const s of e.getDescendantsOfKind(l.CallExpression)){const n=s.getExpression();if(!i.isPropertyAccessExpression(n))continue;const o=n.getName();if(!bc.has(o))continue;const r=n.getExpression();if(!(M(r)||i.isPropertyAccessExpression(r)&&M(r.getExpression())))continue;const c=s.getArguments()[0];if(c!==void 0&&i.isIdentifier(c)&&c.getText()===t)return o}},kc=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},Lc=e=>e.getDescendantsOfKind(l.CallExpression).some(t=>t.getArguments().some(s=>kc(s)==="ctx")),Dc=e=>e.getDescendantsOfKind(l.BinaryExpression).some(t=>wc.has(t.getOperatorToken().getKind())?i.isPropertyAccessExpression(t.getLeft())||i.isPropertyAccessExpression(t.getRight()):!1),Mc=e=>{for(const t of e.getDescendantsOfKind(l.Identifier))if(Nc.has(t.getText()))return!0;for(const t of e.getDescendantsOfKind(l.PropertyAccessExpression)){const s=t.getExpression();if(i.isIdentifier(s)&&s.getText()==="ctx"&&Pc.has(t.getName()))return!0}return Lc(e)||Dc(e)},Kc=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!i.isCallExpression(s))return[];const n=B(s);if(n?.kind!=="query"&&n?.kind!=="mutation")return[];const o=Rs(s);if(o===void 0)return[];const r=n.receiver!==void 0&&xs(n.receiver,"use","rls"),a=Mc(o),c=new Set,u=[];for(const d of o.getDescendantsOfKind(l.CallExpression)){const m=Ic(d);if(m===void 0)continue;const h=Tc(d);if(h===void 0||c.has(h)||!Oc(o,h))continue;const L=Rc(o,h);L!==void 0&&(c.add(h),u.push({exportName:e.getName(),file:t,line:d.getStartLineNumber(),mentionsOwnership:a,sinkMethod:L,table:m,usesRls:r,visibility:n.visibility}))}return u},_c=(e,t)=>{const s=[];for(const n of g(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=v(t,n);for(const a of o.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...Kc(c,r))}return s},$c=new Set(["accountId","authorId","createdBy","createdById","organizationId","orgId","ownerId","tenantId","updatedBy","userId","workspaceId"]),zc=new Set(["insert","insertManyUnsafe","patch","replace"]),Uc=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName();if(!zc.has(t))return;const s=e.getExpression();if(!i.isPropertyAccessExpression(s)||s.getName()!=="db")return;const n=s.getExpression();return i.isIdentifier(n)&&n.getText()==="ctx"?t:void 0},Bc=(e,t)=>{if(t!=="insertManyUnsafe")return i.isObjectLiteralExpression(e)?[e]:[];if(!i.isArrayLiteralExpression(e))return[];const s=[];for(const n of e.getElements())i.isObjectLiteralExpression(n)&&s.push(n);return s},Jt=(e,t)=>{if(i.isPropertyAccessExpression(e)){const s=e.getExpression();return i.isIdentifier(s)&&s.getText()==="args"&&e.getName()===t}if(i.isElementAccessExpression(e)){const s=e.getExpression(),n=e.getArgumentExpression();return i.isIdentifier(s)&&s.getText()==="args"&&n!==void 0&&i.isStringLiteral(n)&&n.getLiteralValue()===t}return!1},qc=e=>{if(!i.isIdentifier(e))return;const t=e.getText(),s=e.getFirstAncestor(a=>i.isArrowFunction(a)||i.isFunctionExpression(a)||i.isFunctionDeclaration(a));if(s===void 0)return;for(const a of s.getDescendantsOfKind(l.BinaryExpression)){const c=a.getLeft();if(i.isIdentifier(c)&&c.getText()===t&&a.getOperatorToken().getText().endsWith("="))return}const n=e.getStart();let o,r=-1;for(const a of s.getDescendantsOfKind(l.VariableDeclaration)){if(a.getName()!==t)continue;const c=a.getParent();if(!i.isVariableDeclarationList(c)||c.getDeclarationKind()!==dn.Const)continue;const u=a.getInitializer(),d=a.getStart();u!==void 0&&d<n&&d>r&&(o=u,r=d)}return o},jc=(e,t)=>{if(Jt(e,t))return!0;const s=qc(e);return s!==void 0&&Jt(s,t)},Wc=(e,t,s,n,o)=>{const r=[];for(const a of e.getProperties()){let c,u;if(i.isPropertyAssignment(a)?(c=E(a),u=a.getInitializer()):i.isShorthandPropertyAssignment(a)&&(c=E(a),u=a.getNameNode()),!(c===void 0||u===void 0||!$c.has(c))&&z(u)&&!W(u)){const d=S(s),m=o(d)===c&&jc(u,c);r.push({exportName:d,field:c,file:n,line:s.getStartLineNumber(),method:t,...m&&{ownerScoped:!0}})}}return r},Vc=(e,t,s)=>{const n=Uc(e.getExpression());if(n===void 0)return[];const o=e.getArguments()[1];return o?Bc(o,n).flatMap(r=>Wc(r,n,e,t,s)):[]},Hc=(e,t,s)=>{const n=[];for(const o of e.getDescendantsOfKind(l.CallExpression))for(const r of Vc(o,t,a=>s(a).owner)){const{visibility:a}=s(r.exportName);n.push(a===void 0?r:{...r,visibility:a})}return n},Gc=(e,t,s=[],n=[])=>{const o=[],r=new Map;for(const a of s)r.set(`${a.filePath}:${a.exportName}`,{visibility:a.visibility});for(const a of n){const c=`${a.filePath}:${a.exportName}`;r.set(c,{...r.get(c),owner:a.owner})}for(const a of g(t)){const c=e.getSourceFile(a)??e.addSourceFileAtPath(a),u=v(t,a);o.push(...Hc(c,u,d=>r.get(`${u}:${d}`)??{}))}return o},Yc=["providerSubscriptionId","state"],Qc=["providerEventId","processedAt"],Zt=(e,t)=>t.every(s=>s in e.shape),Xc=e=>{const t=e.find(n=>n.name==="subscriptions"),s=e.find(n=>n.name==="events");return t!==void 0&&s!==void 0&&Zt(t,Yc)&&Zt(s,Qc)},Jc=new Set(["createAutumnAdapter","createDodoPaymentsAdapter","createPolarAdapter","createStripeAdapter"]),Zc=e=>e&&i.isNumericLiteral(e)?Number(e.getText()):void 0,el=e=>{const t=F(e,"webhookToleranceSeconds");return t&&i.isPropertyAssignment(t)?Zc(t.getInitializer()):void 0},tl=(e,t)=>{const s=y(e.getExpression());if(s===void 0||!Jc.has(s))return;const[n]=e.getArguments(),o=n&&i.isObjectLiteralExpression(n)?el(n):void 0;return{callee:s,exportName:S(e),file:t,line:e.getStartLineNumber(),...o===void 0?{}:{toleranceSeconds:o}}},sl=(e,t)=>O(e,t,tl),nl=new Map([["defineQueue",0],["defineSubscription",1],["defineWorkflow",0]]),rl=e=>{const t=e.getExpression();return i.isIdentifier(t)?t.getText():void 0},ol=(e,t)=>{const s=e.getArguments()[t];if(!s||!i.isObjectLiteralExpression(s))return;const n=F(s,"handler");if(n===void 0||!i.isPropertyAssignment(n))return;const o=n.getInitializer();if(o&&(i.isArrowFunction(o)||i.isFunctionExpression(o)))return o},_s=(e,t)=>{const s=e.getParameters()[t]?.getNameNode();return s&&i.isIdentifier(s)?s.getText():void 0},$s=(e,t)=>e===t||e.startsWith(`${t}.`),zs=e=>{const t=e.getDescendantsOfKind(l.PropertyAccessExpression);return i.isPropertyAccessExpression(e)&&t.push(e),t},es=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)},Us=e=>{const t=e.getDescendantsOfKind(l.Identifier).filter(s=>es(s));return i.isIdentifier(e)&&es(e)&&t.push(e),t},il=e=>{if(!i.isVariableDeclaration(e))return[];const t=e.getNameNode();return i.isIdentifier(t)?[t.getText()]:t.getDescendantsOfKind(l.BindingElement).map(s=>s.getName())},al=e=>{const t=_s(e,1);if(t===void 0)return[];const s=[`${t}.messages`];for(const n of e.getDescendantsOfKind(l.ForOfStatement)){if(n.getExpression().getText()!==`${t}.messages`)continue;const o=n.getInitializer(),r=i.isVariableDeclarationList(o)?o.getDeclarations()[0]?.getNameNode():void 0;r&&i.isIdentifier(r)&&s.push(`${r.getText()}.body`)}return s},cl=(e,t,s)=>{const n=t==="workflow"?[`${s}.params`]:al(e),o=new Set,r=a=>zs(a).some(c=>n.some(u=>$s(c.getText(),u)))?!0:Us(a).some(c=>o.has(c.getText()));for(const a of e.getDescendantsOfKind(l.VariableDeclaration)){const c=a.getInitializer();if(c&&r(c))for(const u of il(a))o.add(u)}return{names:o,prefixes:n}},ll=(e,t)=>zs(e).some(s=>t.prefixes.some(n=>$s(s.getText(),n)))?!0:Us(e).some(s=>t.names.has(s.getText())),ul=e=>{const t=gs(e);return t===void 0?void 0:{exportName:String(t.at(-1)),file:t.slice(0,-1).join("/")}},dl=(e,t,s)=>{const n=_s(e,0);if(n===void 0)return[];const o=cl(e,t,n),r=new Set([n,...o.prefixes.filter(c=>c.endsWith(".body")).map(c=>c.slice(0,-5))]),a=[];for(const c of e.getDescendantsOfKind(l.CallExpression)){const u=c.getExpression();if(!i.isPropertyAccessExpression(u)||!ps.has(u.getName())||!r.has(u.getExpression().getText()))continue;const d=c.getArguments()[1];if(!d||!ll(d,o))continue;const m=ul(c.getArguments()[0]);m!==void 0&&a.push({dispatchKind:t,file:s,handlerExport:S(c),line:c.getStartLineNumber(),targetExport:m.exportName,targetFile:m.file})}return a},fl=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression)){const o=rl(n),r=o===void 0?void 0:nl.get(o);if(r===void 0)continue;const a=ol(n,r);a!==void 0&&s.push(...dl(a,o==="defineWorkflow"?"workflow":"queue",t))}return s},pl=(e,t)=>{const s=[];for(const n of g(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...fl(o,v(t,n)))}return s},ts={dbRateLimit:"usesRateLimit",emailGateMiddleware:"usesEmailGate",mask:"usesMask",rateLimit:"usesRateLimit",rls:"usesRls",verifyTurnstileMiddleware:"usesCaptcha"},ss=new Set(["account","credential","member","passkey","session","user"]),gl=e=>e.replaceAll(/[-_]/gu," ").replaceAll(/([a-z0-9])([A-Z])/gu,"$1 $2").split(" ").filter(Boolean).map(t=>t.toLowerCase()),ml=e=>{const s=gl(e).at(-1);if(!s)return!1;const n=s.endsWith("s")?s.slice(0,-1):s;return ss.has(s)||ss.has(n)},hl=e=>{const t=e.replaceAll(/[^a-z0-9]/giu,"").toLowerCase();return t.endsWith("email")||t.endsWith("emailaddress")},vl=(e,t)=>{const{objects:s,opaque:n}=st(e,t);return ri(s).some(o=>hl(o))?!0:n?void 0:!1},xl=e=>{const t=e.getArguments()[0];return!t||!i.isObjectLiteralExpression(t)?{usesCaptcha:!1,usesRateLimit:!1}:{usesCaptcha:!!F(t,"captcha"),usesRateLimit:!!F(t,"rateLimit")}},El=e=>{if(i.isCallExpression(e))return e;if(!i.isIdentifier(e))return;const s=e.getSourceFile().getVariableDeclaration(e.getText())?.getInitializer();return s&&i.isCallExpression(s)?s:void 0},Ee={usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},Sl=e=>{const t=El(e),s=t?y(t.getExpression()):void 0;if(t&&s==="protectPublic"){const n=xl(t);return{...Ee,usesCaptcha:n.usesCaptcha,usesRateLimit:n.usesRateLimit}}return s!==void 0&&s in ts?{...Ee,[ts[s]]:!0}:Ee},yl=e=>{const t={...Ee};let s=e;for(;i.isCallExpression(s);){const n=s.getExpression();if(!i.isPropertyAccessExpression(n))break;const o=n.getName()==="use"?s.getArguments()[0]:void 0;if(o){const r=Sl(o);t.usesCaptcha||=r.usesCaptcha,t.usesEmailGate||=r.usesEmailGate,t.usesMask||=r.usesMask,t.usesRateLimit||=r.usesRateLimit,t.usesRls||=r.usesRls}s=n.getExpression()}return t},Al=new Set(["insert","insertMany","insertManyUnsafe","replace"]),bl=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!Al.has(t.getName()))return!1;const s=t.getExpression();if(!M(s))return!1;const o=e.getArguments()[0];return!o||!(i.isStringLiteral(o)||i.isNoSubstitutionTemplateLiteral(o))?!1:ml(o.getLiteralText())},Nl=new Set(["create","publish","publishBatch","runAfter","runAt","send","sendBatch"]),Pl=new Set(["queues","scheduler","topics","workflows"]),wl=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!Nl.has(t.getName()))return!1;let s=t.getExpression();for(;i.isCallExpression(s)||i.isElementAccessExpression(s)||i.isPropertyAccessExpression(s);){if(i.isPropertyAccessExpression(s)&&Pl.has(s.getName())){const n=s.getExpression();if(i.isIdentifier(n)&&n.getText()==="ctx")return!0}s=s.getExpression()}return!1},Il=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="insertManyUnsafe")return!1;const s=t.getExpression();return M(s)},Bs=new Set(["generateObject","generateText","streamObject","streamText"]),Tl=e=>{const t=y(e.getExpression());return t!==void 0&&Bs.has(t)},Cl=e=>{const t=y(e.getExpression());if(t===void 0||!Bs.has(t))return!1;const s=e.getArguments()[0];return!s||!i.isObjectLiteralExpression(s)||s.getProperties().some(n=>i.isSpreadAssignment(n))?!1:!F(s,"maxOutputTokens")},Fl=new Set(["log","span","trace"]),Ol=new Set(["ai"]),Rl=new Set(["email","mail"]),kl=new Set(["ai","browser","fetch","mail","notify","queues","sql","storage","topics","workflows"]),je=(e,t)=>e.getDescendantsOfKind(l.PropertyAccessExpression).some(s=>{if(!t.has(s.getName()))return!1;const n=s.getExpression();return i.isIdentifier(n)&&n.getText()==="ctx"}),Ll=new Set([l.ArrowFunction,l.FunctionDeclaration,l.FunctionExpression,l.GetAccessor,l.MethodDeclaration,l.SetAccessor]),Dl=new Set(["every","filter","flatMap","forEach","map","some"]),Ml=new Set(["all","allSettled","race"]),Kl=e=>{const t=e.getParent();if(!t||!i.isCallExpression(t)||!t.getArguments().includes(e))return;const s=t.getExpression();if(!i.isPropertyAccessExpression(s))return;const n=s.getName();if(Dl.has(n))return t;const o=s.getExpression();if(i.isIdentifier(o)&&o.getText()==="Promise"&&Ml.has(n))return t},_l=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(Ll.has(t.getKind())){const s=Kl(t);if(!s)return!1;t=s;continue}t=t.getParent()}return!1},$l=e=>{let t=e;for(;;){const s=t.getParent();if(!i.isPropertyAccessExpression(s)||s.getExpression()!==t)return!1;if(s.getName()==="catch")return!0;if(s.getName()!=="then"&&s.getName()!=="finally")return!1;const n=s.getParent();if(!i.isCallExpression(n)||n.getExpression()!==s)return!1;t=n}},zl=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}},Ul=e=>{let t=!1,s=!0;for(const n of e.getDescendantsOfKind(l.PropertyAccessExpression)){if(!kl.has(n.getName()))continue;const o=n.getExpression();if(!i.isIdentifier(o)||o.getText()!=="ctx")continue;const r=zl(n);r&&(t=!0,!_l(r)&&!$l(r)&&(s=!1))}return{handlesErrors:t&&s,reachesOutbound:t}},Bl=e=>e.getDescendantsOfKind(l.ThrowStatement).some(t=>{const s=t.getExpression();if(!i.isNewExpression(s))return!1;const n=s.getExpression();return i.isIdentifier(n)&&n.getText()==="Error"}),ns="lunora-advisor-exempt",ql=/^[\s*/]+/u,jl=/[\w-]/u,Wl=e=>{const s=(e.getFirstAncestorByKind(l.VariableStatement)??e).getLeadingCommentRanges().map(n=>n.getText()).join(`
|
|
7
|
-
`);for(const n of s.split(`
|
|
8
|
-
`)){const o=n.replace(ql,"");if(!o.startsWith(ns))continue;const r=o.slice(ns.length);if(jl.test(r.charAt(0)))continue;const a=r.indexOf("--");return{exempt:!0,exemptReason:(a===-1?"":r.slice(a+2).split("*")[0]??"").trim()}}return{exempt:!1,exemptReason:""}},Vl=e=>{const[t]=e.getArguments();if(t){if(i.isObjectLiteralExpression(t)){const s=F(t,"handler");return s?i.isPropertyAssignment(s)?s.getInitializer():i.isShorthandPropertyAssignment(s)?s.getNameNode():i.isMethodDeclaration(s)?s:void 0:void 0}return t}},Hl=(e,t)=>{const s=Vl(t);if(!s)return;if(i.isArrowFunction(s)||i.isFunctionExpression(s)||i.isMethodDeclaration(s))return e;if(!i.isIdentifier(s))return;const n=s.getSourceFile(),o=s.getText(),r=n.getVariableDeclaration(o)?.getInitializer();return r&&(i.isArrowFunction(r)||i.isFunctionExpression(r))?r:n.getFunction(o)},Gl=e=>{let t=!1,s=!1,n=!1,o=!1,r=!1;for(const u of e.getDescendantsOfKind(l.CallExpression))if(bl(u)&&(r=!0),wl(u)&&(t=!0),Il(u)&&(o=!0),Tl(u)&&(s=!0),Cl(u)&&(n=!0),r&&t&&o&&n)break;const{handlesErrors:a,reachesOutbound:c}=Ul(e);return{callsMail:je(e,Rl),emitsEvent:je(e,Fl),fanOut:t,handlesErrors:a,reachesOutbound:c,runsAiGeneration:s||je(e,Ol),throwsBareError:Bl(e),unboundedAiGeneration:n,usesInsertManyUnsafe:o,writesUserTable:r}},Yl=(e,t)=>{const s=e.getInitializer();if(!s||!i.isCallExpression(s))return;const n=B(s);if(!n||n.kind!=="query"&&n.kind!=="mutation"&&n.kind!=="action")return;const o=n.receiver?yl(n.receiver):{usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},r=Hl(e,s);return{...r?Gl(r):{},...Wl(e),...o,analyzableBody:r!==void 0,exportName:e.getName(),file:t,hasEmailArg:vl(s,n.receiver),kind:n.kind,visibility:n.visibility}},Ql=(e,t)=>{const s=[];for(const n of e.getVariableStatements())if(n.isExported())for(const o of n.getDeclarations()){const r=Yl(o,t);r&&s.push(r)}return s},Xl=(e,t)=>{const s=[];for(const n of g(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Ql(o,v(t,n)))}return s},Jl=new Set(["dbRateLimit","rateLimit"]),Zl=e=>i.isArrowFunction(e)?e.getBody():e,eu=e=>{if(!i.isArrowFunction(e))return;const t=e.getParameters()[0]?.getNameNode();return t!==void 0&&i.isIdentifier(t)?t:void 0},qs=e=>{const t=e.getParent();return i.isPropertyAccessExpression(t)&&t.getExpression()===e&&t.getName()==="args"},js=(e,t)=>{const s=t.getSymbol();return s===void 0?[]:e.getDescendantsOfKind(l.Identifier).filter(n=>{if(n.getSymbol()!==s)return!1;const o=n.getParent();return!(i.isPropertyAccessExpression(o)&&o.getNameNode()===n)})},tu=(e,t)=>z(e)||t!==void 0&&js(e,t).some(s=>qs(s)),su=(e,t)=>t===void 0?W(e):js(e,t).some(s=>!qs(s)),nu=(e,t)=>{const s=y(e.getExpression());if(s===void 0||!Jl.has(s))return;const n=N(hs(e.getArguments()[2]),"key");if(!n)return;const o=Zl(n),r=eu(n);if(!(!tu(o,r)||su(o,r)))return{callee:s,exportName:S(e),file:t,limitName:ms(e),line:e.getStartLineNumber()}},ru=(e,t)=>O(e,t,nu),ou=new Set(["findFirst","findFirstOrThrow","findMany","findUnique","get"]),iu=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!ou.has(t.getName()))return;const s=t.getExpression();if(M(s)){const n=e.getArguments()[0];return n&&i.isStringLiteral(n)?n.getLiteralText():""}if(i.isPropertyAccessExpression(s)&&M(s.getExpression()))return s.getName()},au=e=>{let t=e;for(;i.isCallExpression(t);){const s=t.getExpression();if(!i.isPropertyAccessExpression(s))return;if(s.getName()==="query"&&M(s.getExpression())){const n=t.getArguments()[0];return n&&i.isStringLiteral(n)?n.getLiteralText():""}t=s.getExpression()}},cu=e=>{let t=ne(e)??e;for(;i.isAwaitExpression(t);)t=ne(t.getExpression())??t.getExpression();return t},Ws=(e,t=!1)=>{const s=cu(e);if(i.isIdentifier(s)){if(t)return;const n=$(s);return n===void 0?void 0:Ws(n,!0)}if(i.isCallExpression(s))return iu(s)??au(s)},lu=e=>{const t=e.getBody();if(!i.isBlock(t))return[t];const s=[];for(const n of e.getDescendantsOfKind(l.ReturnStatement)){const o=n.getFirstAncestor(a=>i.isArrowFunction(a)||i.isFunctionExpression(a)||i.isFunctionDeclaration(a)),r=n.getExpression();o===e&&r!==void 0&&s.push(r)}return s},uu=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!i.isCallExpression(s))return[];const n=B(s);if(n?.kind!=="query")return[];const o=Rs(s);if(o===void 0)return[];const r=n.receiver!==void 0&&Rn(n.receiver,"output"),a=n.receiver!==void 0&&xs(n.receiver,"use","mask"),c=new Set,u=[];for(const d of lu(o)){const m=Ws(d);m===void 0||c.has(m)||(c.add(m),u.push({exportName:e.getName(),file:t,line:d.getStartLineNumber(),table:m,usesMask:a,usesOutput:r,visibility:n.visibility}))}return u},du=(e,t)=>{const s=[];for(const n of g(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=v(t,n);for(const a of o.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...uu(c,r))}return s},fu=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(E(s));return t},pu=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&i.isCallExpression(s)?B(s):void 0;if(!n)return[];const o=[];for(const r of e.getDescendantsOfKind(l.CallExpression)){const a=vs(r);if(a===void 0)continue;const c=fu(N(a.options,"with"));c.length!==0&&o.push({exportName:e.getName(),file:t,line:r.getStartLineNumber(),parentTable:a.table,relations:c,visibility:n.visibility})}return o},gu=(e,t)=>{const s=[];for(const n of g(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=v(t,n);for(const a of o.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...pu(c,r))}return s},Ae=e=>{if(i.isStringLiteral(e)||i.isNoSubstitutionTemplateLiteral(e))return e.getLiteralText();if(i.isBinaryExpression(e)&&e.getOperatorToken().getKind()===l.PlusToken){const t=Ae(e.getLeft()),s=Ae(e.getRight());return t!==void 0&&s!==void 0?t+s:void 0}},mu=e=>{let t=e,s=t.getParent();for(;s!==void 0&&i.isBinaryExpression(s)&&s.getOperatorToken().getKind()===l.PlusToken;)t=s,s=t.getParent();return t!==e&&Ae(t)!==void 0},hu=/(?:^|\/)__tests__\//u,vu=/\.(?:spec|test)$/u,xu=e=>hu.test(e)||vu.test(e),Eu=e=>{const t=e.getParent();if(t!==void 0){if(i.isVariableDeclaration(t)||i.isPropertyAssignment(t)||i.isPropertySignature(t))return E(t);if(i.isBinaryExpression(t)&&t.getOperatorToken().getKind()===l.EqualsToken)return t.getLeft().getText()}},Su=(e,t,s)=>pr(e)?!xu(s)&&gr(Eu(t)):!0,yu=(e,t)=>{const s=[],n=[...e.getDescendantsOfKind(l.BinaryExpression),...e.getDescendantsOfKind(l.StringLiteral),...e.getDescendantsOfKind(l.NoSubstitutionTemplateLiteral)],o=new Set;for(const r of n){if(mu(r))continue;const a=Ae(r);if(a===void 0)continue;const c=dr(a);if(c===void 0||!Su(c,r,t))continue;const u=r.getStartLineNumber(),d=`${String(u)}:${c}`;o.has(d)||(o.add(d),s.push({file:t,kind:c,line:u,preview:fr(a)}))}return s},Au=(e,t)=>{const s=[];for(const n of g(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...yu(o,v(t,n)))}return s},bu=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&i.isCallExpression(s)?B(s):void 0;if(!n)return[];const o=[];for(const r of e.getDescendantsOfKind(l.CallExpression)){const a=vs(r);if(a===void 0)continue;const c=N(a.options,"includeDeleted");if(c===void 0)continue;const u=i.isTrueLiteral(c),d=!u&&z(c);!u&&!d||o.push({exportName:e.getName(),file:t,fromArgs:d,hardcodedTrue:u,line:r.getStartLineNumber(),table:a.table,visibility:n.visibility})}return o},Nu=(e,t)=>{const s=[];for(const n of g(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=v(t,n);for(const a of o.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...bu(c,r))}return s},Pu=new Set(["query","unsafe"]),wu=e=>{if(!i.isPropertyAccessExpression(e)||!Pu.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"},Iu=e=>i.isBinaryExpression(e)||i.isTemplateExpression(e),Tu=e=>e.getFirstAncestorByKind(l.VariableDeclaration)?.getName()??"<module>",Cu=(e,t)=>{if(!wu(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!Iu(s)))return{exportName:Tu(e),file:t,line:s.getStartLineNumber()}},Fu=(e,t)=>O(e,t,Cu),Ou=[["convex",["convex","@convex-dev/"]],["supabase",["@supabase/"]],["firebase",["firebase","@firebase/","firebase-admin"]]],Ru=e=>{for(const[t,s]of Ou)for(const n of s)if(e===n||e.startsWith(n.endsWith("/")?n:`${n}/`))return t},ku=(e,t)=>{const s=[];for(const n of g(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const r of o.getImportDeclarations()){const a=r.getModuleSpecifierValue(),c=Ru(a);c!==void 0&&s.push({file:v(t,n),line:r.getStartLineNumber(),moduleSpecifier:a,platform:c})}}return s},Lu=new Set(["createMultipartUpload","delete","download","generateUploadUrl","get","getMetadata","getPresignedUrl","getSignedUrl","getUrl","head","put","resumeMultipartUpload","store","upload"]),Du=(e,t,s=[])=>{const n=new Map(s.map(r=>[`${r.filePath}:${r.exportName}`,r.visibility]));return Te(e,t,{argIndex:0,matchReceiver:r=>r==="ctx.storage"||r.startsWith("ctx.storage."),methods:Lu,requireUnmodifiedReach:!0}).map(r=>{const a=n.get(`${r.file}:${r.exportName}`);return a===void 0?r:{...r,visibility:a}})},Mu=new Map([["generateUploadUrl",1],["getPresignedUrl",1],["getSignedUrl",1],["store",2],["upload",2]]),Ku=e=>e&&i.isNumericLiteral(e)?Number(e.getText()):void 0,_u=e=>{if(e===void 0)return{analyzable:!0,presentKeys:[]};if(!i.isObjectLiteralExpression(e))return{analyzable:!1,presentKeys:[]};const t=[];let s,n=!1;for(const o of e.getProperties()){if(i.isSpreadAssignment(o)){n=!0;continue}if(i.isPropertyAssignment(o)){const r=E(o);t.push(r),r==="expiresInSeconds"&&(s=Ku(o.getInitializer()));continue}(i.isShorthandPropertyAssignment(o)||i.isMethodDeclaration(o))&&t.push(E(o))}return{analyzable:!n,expiresInSeconds:s,presentKeys:t}},$u=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName(),s=Mu.get(t);if(s===void 0)return;const n=e.getExpression().getText();return n==="ctx.storage"||n.startsWith("ctx.storage.")?{method:t,optionsIndex:s}:void 0},zu=(e,t)=>{const s=$u(e.getExpression());if(s!==void 0)return{exportName:S(e),file:t,line:e.getStartLineNumber(),method:s.method,..._u(e.getArguments()[s.optionsIndex])}},Uu=(e,t)=>O(e,t,zu),Bu=(e,t)=>{const s=Mn(t.target);return{...s===void 0?{}:{platform:s},analytics:e.analytics||t.dependencies.has("@lunora/bindings"),auth:t.dependencies.has("@lunora/auth"),containers:e.container||t.containerCount>0||t.dependencies.has("@lunora/container"),flags:e.flags||t.dependencies.has("@lunora/flags"),kv:e.kv||t.dependencies.has("@lunora/bindings"),mail:e.mail||t.dependencies.has("@lunora/mail"),notifications:e.notify||t.dependencies.has("@lunora/notify"),payments:e.payments||t.hasPaymentTables,queues:t.queueCount>0||t.dependencies.has("@lunora/queue"),scheduler:e.scheduler||t.cronCount>0||t.dependencies.has("@lunora/scheduler"),storage:e.storage||t.storageRuleCount>0||t.storageColumnCount>0||t.dependencies.has("@lunora/storage"),vectors:t.vectorStoreSupported&&t.vectorIndexCount>0,workflows:e.workflows||t.workflowCount>0||t.dependencies.has("@lunora/workflow")}},qu=new Set(["delete","hardDelete","patch","replace","restore"]),ju=new Set(["insertMany","insertManyUnsafe","patchWhere"]),Wu=new Set(["delete","deleteMany","hardDelete","insert","insertMany","patch","patchMany","replace","restore","upsert","upsertMany"]),rs=(e,t)=>{const n=e.getProperty("__table")?.getTypeAtLocation(t)?.getLiteralValue();return typeof n=="string"?n:""},Vu=(e,t)=>{const s=e.getType();if(t==="deleteMany"||t==="patchMany"){const n=s.getArrayElementType();if(n===void 0)return"";const o=t==="patchMany"?n.getProperty("id")?.getTypeAtLocation(e):n;return o===void 0?"":rs(o,e)}return rs(s,e)},Hu=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t))return;const s=t.getName(),n=t.getExpression(),[o]=e.getArguments();if(M(n))return ju.has(s)?{method:s,table:o!==void 0&&i.isStringLiteral(o)?o.getLiteralText():""}:qu.has(s)||s==="deleteMany"||s==="patchMany"?{method:s,table:o===void 0?"":Vu(o,s)}:void 0;if(Wu.has(s)&&i.isPropertyAccessExpression(n)&&M(n.getExpression()))return{method:s,table:n.getName()}},Gu=(e,t)=>{const s=[];for(const n of g(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=v(t,n);for(const a of o.getDescendantsOfKind(l.CallExpression)){const c=Hu(a),u=c===void 0?"":re(a);c!==void 0&&u!==""&&s.push({exportName:u,file:r,line:a.getStartLineNumber(),method:c.method,table:c.table})}}return s},Yu=(e,t,s)=>({cacheKey:`procedure_arguments_unreadable:${e}:${t}`,categories:["SCHEMA"],description:"Codegen reads an argument record statically. One built at runtime — a factory call, or a property off a value it cannot follow — has no literal to read, so the generated `FunctionReference` carries only the arguments it could see while the runtime validator still enforces all of them.",detail:`\`${t}\` in \`${e}\` (line ${s.toString()}) declares arguments codegen could not read, so its generated type is missing some of them.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:t,filePath:e,line:s},name:"procedure_arguments_unreadable",remediation:`Declare the arguments as an object literal, or as a \`const\` object literal the chain names — \`const ${t}Args = { … };\` then \`.input(${t}Args)\`. Both resolve; a record returned by a call does not.`,title:"Procedure arguments are missing from the generated type"}),Qu=(e,t)=>{if(t===void 0){const s=e.getArguments()[0];if(s===void 0||!i.isObjectLiteralExpression(s)||F(s,"args")===void 0)return!1}return st(e,t).opaque},Xu=(e,t)=>{const s=[],n=(o,r)=>{const a=o.getInitializer();if(a===void 0||!i.isCallExpression(a))return;const c=B(a);c!==void 0&&Qu(a,c.receiver)&&s.push(Yu(t,r,a.getStartLineNumber()))};for(const o of e.getVariableStatements().filter(r=>r.isExported()))for(const r of o.getDeclarations())n(r,r.getName());return s},Ju=(e,t)=>{const s=[];for(const n of g(t)){const o=e.getSourceFile(n);o!==void 0&&s.push(...Xu(o,v(t,n)))}return s.toSorted((n,o)=>n.cacheKey.localeCompare(o.cacheKey))},Zu=new Map([["AgentDefinition",{call:"defineAgent({ … })",file:"agents"}],["ContainerDefinition",{call:"defineContainer({ … })",file:"containers"}],["QueueDefinition",{call:"defineQueue({ … })",file:"queues",note:"A dropped queue has no caller to fail — its consumer is simply never wired."}],["RegisteredAction",{call:"action.input({ … }).action(handler)"}],["RegisteredLifecycleHook",{call:"onConnect(handler)",note:"Substitute the hook you called: `onConnect`, `onDisconnect` and `onShardInit` share one type, so codegen cannot tell which you wrote. A dropped hook has no caller to fail — it silently never fires."}],["RegisteredMigration",{call:"defineMigration({ … })",note:"A dropped migration never runs, so `lunora migrate up` reports nothing to do."}],["RegisteredMutation",{call:"mutation.input({ … }).mutation(handler)"}],["RegisteredMutator",{call:"defineMutator({ … })",file:"mutators"}],["RegisteredQuery",{call:"query.input({ … }).query(handler)"}],["RegisteredReactor",{call:"onQueryChange(select, handler)",note:"A dropped reactor has no caller to fail — it silently never runs."}],["RegisteredShape",{call:"defineShape({ … })",file:"shapes"}],["RegisteredStream",{call:"query.input({ … }).stream(handler)"}],["RegisteredWhisperAuthorizer",{call:"onWhisper(handler)",note:"A dropped authorizer has no caller to fail — the whisper topics it was meant to gate silently stay open to every socket on the shard."}],["SubscriptionDefinition",{call:"defineSubscription(topic, { … })",file:"queues",note:"A dropped subscription is never published to — its topic's messages simply never reach it."}],["WorkflowDefinition",{call:"defineWorkflow({ … })",file:"workflows"}]]),Ce=({byName:e,byPath:t},s,n)=>t.has(`${s}:${n}`)||e.has(n),Vs=e=>!e.isAny(),rt=e=>{const t=e.getType();if(!Vs(t))return;const s=t.getAliasSymbol()?.getName()??t.getSymbol()?.getName(),n=s===void 0?void 0:Zu.get(s);return n===void 0||s===void 0?void 0:{...n,typeName:s}},Hs=e=>{const t=e.getInitializer();return t===void 0?!1:i.isCallExpression(t)||i.isIdentifier(t)||i.isPropertyAccessExpression(t)},Gs={cause:"codegen recognises a registration only when the initializer is the registering call itself, and this one comes from a factory or an alias",remediation:"A factory that returns a registration cannot be read statically — inline it, or export what the factory builds."},ed=e=>({cause:`codegen reads this kind of registration only from \`lunora/${e}.ts\`, and this is a different module`,remediation:`Move it into \`lunora/${e}.ts\` — the declaration itself is fine.`}),td={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."},ot=(e,t,s,n,o)=>{const{call:r,file:a,note:c,typeName:u}=s,d=a!==void 0&&e!==a?a:void 0,m=d===void 0?o:ed(d),h=c===void 0?m.remediation:`${c} ${m.remediation}`;return{cacheKey:`procedure_not_registered:${e}:${t}`,categories:["SCHEMA"],description:"Codegen registers an export only when the declaration carries `export` and its initializer is literally the registering call. Written any other way it exists at runtime but never reaches the generated output — `_generated/api.ts` for a procedure, the lifecycle manifest for a hook or reactor — so a caller cannot address it and a hook never fires.",detail:`\`${t}\` in \`${e}\` (line ${n.toString()}) has type \`${u}\` but was not registered — ${m.cause}.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:t,filePath:e,line:n,typeName:u},name:"procedure_not_registered",remediation:d===void 0?`Assign the registration directly: \`export const ${t} = ${r};\`. ${h}`:h,title:"Procedure exists at runtime but is missing from the generated API"}},sd=(e,t,s)=>{const n=[];for(const o of e.getVariableStatements().filter(r=>r.isExported()))for(const r of o.getDeclarations()){const a=r.getName();if(Ce(s,t,a)||!Hs(r))continue;const c=rt(r);c!==void 0&&n.push(ot(t,a,c,r.getStartLineNumber(),Gs))}return n},nd=(e,t,s)=>{if(Ce(s,t,"default"))return[];const n=[];for(const o of e.getExportAssignments().filter(r=>!r.isExportEquals())){const r=rt(o.getExpression());r!==void 0&&n.push(ot(t,"default",r,o.getStartLineNumber(),Gs))}return n},rd=(e,t,s)=>{const n=[];for(const o of e.getExportDeclarations().filter(r=>r.getModuleSpecifier()===void 0))for(const r of o.getNamedExports()){const a=r.getAliasNode()?.getText()??r.getName();if(Ce(s,t,a))continue;const c=r.getLocalTargetDeclarations().find(d=>i.isVariableDeclaration(d));if(c===void 0||!Hs(c))continue;const u=rt(c);u!==void 0&&n.push(ot(t,a,u,r.getStartLineNumber(),td))}return n},od=(e,t,s)=>[...sd(e,t,s),...nd(e,t,s),...rd(e,t,s)],id=(e,t,s)=>e.getVariableStatements().filter(n=>n.isExported()).flatMap(n=>n.getDeclarations()).filter(n=>Ce(s,t,n.getName())).filter(n=>{const o=n.getInitializer();return o!==void 0&&i.isCallExpression(o)&&i.isPropertyAccessExpression(o.getExpression())}).map(n=>({declaration:n,exportName:n.getName(),relativePath:t})),ad=({exportName:e,relativePath:t})=>({cacheKey:"procedure_type_check_unavailable",categories:["SCHEMA"],description:"Codegen cross-checks every export in `lunora/` against its TYPE to catch a procedure the syntactic scan dropped — a factory-assigned export, an alias, a separate `export { … }`. That check needs the type checker to resolve `@lunora/server`; when it cannot, the check reports nothing regardless of what the code does.",detail:`Type resolution for \`lunora/\` is unavailable — the registered procedure \`${e}\` in \`${t}\` types as \`any\`, as does every other one — so codegen cannot tell you when an export is dropped from \`_generated/api.ts\`. A dropped procedure will surface as \`Property '<name>' does not exist\` at its call site instead.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:e,filePath:t},name:"procedure_type_check_unavailable",remediation:`Check what codegen sees: \`${e}\` should have a procedure type, not \`any\`. It needs a \`tsconfig.json\` at or above \`lunora/\` — the one codegen finds walking up from there, which is not necessarily the one your editor uses — resolving \`lunorash\` / \`@lunora/server\` to declarations that exist on disk (a workspace dependency has to be built first).`,title:"Codegen cannot type-check `lunora/`, so dropped procedures go unreported"}),cd=(e,t,s)=>{const n=[],o=[];for(const a of g(t)){const c=e.getSourceFile(a);if(c===void 0)continue;const u=v(t,a);n.push(...od(c,u,s)),o.push(...id(c,u,s))}const[r]=o;return r!==void 0&&o.every(({declaration:a})=>!Vs(a.getType()))&&n.push(ad(r)),n.toSorted((a,c)=>a.cacheKey.localeCompare(c.cacheKey))},ld=new Set(["when","where"]),We=new Set(["definePolicy","defineShape"]),ud=e=>{if(!i.isCallExpression(e))return;const t=e.getExpression();if(i.isPropertyAccessExpression(t)){const n=t.getName();return We.has(n)?n:void 0}if(!i.isIdentifier(t))return;for(const n of t.getSymbol()?.getDeclarations()??[])if(i.isImportSpecifier(n)){const o=n.getNameNode().getText();return We.has(o)?o:void 0}const s=t.getText();return We.has(s)?s:void 0},dd=e=>i.isObjectLiteralExpression(e)&&e.getProperties().length===0,Ys=e=>{if(e!==void 0){if(i.isReturnStatement(e)&&e.getExpression()===void 0||e.getKind()===l.UndefinedKeyword||e.getText()==="undefined")return"undefined";if(dd(e))return"empty-object";if(i.isParenthesizedExpression(e))return Ys(e.getExpression())}},it=e=>e.getAncestors().find(t=>i.isArrowFunction(t)||i.isFunctionExpression(t)||i.isFunctionDeclaration(t)),fd=e=>e.getDescendantsOfKind(l.ReturnStatement).filter(t=>it(t)===e),Qs=e=>e.getDescendantsOfKind(l.ConditionalExpression).filter(t=>it(t)===e),pd=e=>{const t=fd(e);return t.length>1?!0:t.some(s=>s.getFirstAncestorByKind(l.IfStatement)!==void 0)||Qs(e).length>0},gd=e=>e.getDescendantsOfKind(l.IfStatement).filter(t=>it(t)===e),Xe=e=>e.getKind()===l.NullKeyword||e.getKind()===l.FalseKeyword||i.isIdentifier(e)&&e.getText()==="undefined"?!0:i.isNumericLiteral(e)?e.getLiteralValue()===0:i.isStringLiteral(e)&&e.getLiteralValue()==="",md=(e,t)=>Xe(e)||Xe(t),hd=new Map([[l.EqualsEqualsEqualsToken,"positive"],[l.EqualsEqualsToken,"positive"],[l.ExclamationEqualsEqualsToken,"negative"],[l.ExclamationEqualsToken,"negative"]]),os=e=>!Xe(e)&&(i.isLiteralExpression(e)||e.getKind()===l.TrueKeyword),vd=(e,t,s)=>{const n=hd.get(e);if(n!==void 0)return md(t,s)?n==="positive"?"negative":"positive":os(t)||os(s)?void 0:n},se=e=>{if(i.isParenthesizedExpression(e))return se(e.getExpression());if(i.isPrefixUnaryExpression(e)&&e.getOperatorToken()===l.ExclamationToken)return"negative";if(i.isBinaryExpression(e)){const t=e.getOperatorToken().getKind(),s=vd(t,e.getLeft(),e.getRight());if(s!==void 0)return s;if(t===l.AmpersandAmpersandToken||t===l.BarBarToken){const n=se(e.getLeft()),o=se(e.getRight());return n===o?n:"indeterminate"}}return i.isIdentifier(e)||i.isPropertyAccessExpression(e)||i.isElementAccessExpression(e)||i.isCallExpression(e)?"positive":"indeterminate"},is=e=>{if(e!==void 0){if(i.isReturnStatement(e))return e;if(i.isBlock(e)){const t=e.getStatements().at(-1);return t!==void 0&&i.isReturnStatement(t)?t:void 0}}},xd=e=>{if(e.getElseStatement()!==void 0)return;const t=e.getNextSiblingIfKind(l.ReturnStatement);return t!==void 0&&t.getNextSibling()===void 0?t:void 0},Ed=e=>i.isReturnStatement(e)?e.getExpression()??e:e,Sd=e=>{const t=[];for(const s of Qs(e)){const n=se(s.getCondition());n==="positive"?t.push(s.getWhenFalse()):n==="negative"&&t.push(s.getWhenTrue())}for(const s of gd(e)){const n=se(s.getExpression());if(n==="indeterminate")continue;const o=n==="negative"?is(s.getThenStatement()):is(s.getElseStatement())??xd(s);o!==void 0&&t.push(Ed(o))}return t},yd=e=>{for(const t of e.getAncestors())if(i.isVariableDeclaration(t)){const s=t.getNameNode();if(i.isIdentifier(s))return s.getText()}return"<anonymous>"},Ad=(e,t,s)=>{if(!i.isCallExpression(e))return[];const[n]=e.getArguments();if(!n||!i.isObjectLiteralExpression(n))return[];const o=[];for(const r of n.getProperties()){if(!i.isPropertyAssignment(r)||!ld.has(E(r)))continue;const a=r.getInitializer();if(!(!a||!(i.isArrowFunction(a)||i.isFunctionExpression(a)))&&pd(a))for(const c of Sd(a)){const u=Ys(c);u!==void 0&&o.push({exportName:yd(e),file:s,form:u,key:E(r),line:c.getStartLineNumber(),owner:t})}}return o},bd=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression)){const o=ud(n);o!==void 0&&s.push(...Ad(n,o,t))}return s},Nd=(e,t)=>{const s=[];for(const n of g(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...bd(o,v(t,n)))}return s},Pd=new Set(["query","upsert","upsertNow"]),wd=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName();if(Pd.has(t))return e.getExpression().getText()==="ctx.vectors"?t:void 0},Id=(e,t)=>{const s=wd(e.getExpression());if(s===void 0)return;const n=e.getArguments()[1];if(!n)return;const o=N(n,"namespace");if(!(!o||!z(o)||W(o)))return{exportName:S(e),file:t,line:e.getStartLineNumber(),method:s}},Td=(e,t)=>O(e,t,Id),Cd=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"},Fd=e=>{const t=e.getArguments()[0];return t&&i.isStringLiteral(t)?t.getLiteralText():""},Od=(e,t)=>{const s=[];for(const n of g(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=v(t,n);for(const a of o.getDescendantsOfKind(l.CallExpression)){if(!Cd(a))continue;const c=re(a);c!==""&&s.push({exportName:c,file:r,line:a.getStartLineNumber(),workflow:Fd(a)})}}return s},Rd=".lunora-schema.json",Je=(e,t)=>{w(e)&&ls(e,"utf8")===t||cn(e,t,"utf8")},kd=(e,t)=>{if(t===""){ln(e,{force:!0});return}Je(e,t)},Ld=e=>{const t=x(e,"package.json");if(w(t))try{const s=JSON.parse(ls(t,"utf8"));return typeof s.version=="string"&&s.version!==""?s.version:void 0}catch{return}},Dd=()=>{const e=process.env.LUNORA_CODEGEN_TIMING;return e!==void 0&&e!==""},Md=e=>{let t=w(e)?e:he(e);for(;t&&t!==he(t);){const s=x(t,"tsconfig.json");if(w(s))return s;t=he(t)}},as=e=>e.replaceAll("\\","/"),Kd=(e,t,s)=>{if(s&&e.length>0){const r=e.map(a=>`"${a.exportName}"`).join(", ");throw new j("MASK_UNSUPPORTED",`This project declares a \`mask(...)\` policy whose argument isn't a plain object literal (e.g. \`mask(sharedPolicies)\` referencing a hoisted variable), or contains a spread (\`...shared\`) or computed key (\`[name]:\`) codegen can't enumerate, so codegen can't tell which columns it masks. Because the project also declares replication shape(s) (${r}), codegen can't verify none of them replicate a table that policy masks — inline every table and column as literal keys so codegen can verify it, or remove the affected shape(s).`,{status:422})}const n=new Map;for(const r of t.columns){const a=n.get(r.table)??[];a.push(r.column),n.set(r.table,a)}const o=t.columns.length>0;for(const r of e){if(r.table===void 0){if(o)throw new j("MASK_UNSUPPORTED",`defineShape "${r.exportName}" has a non-literal \`table\` (a variable or expression, not a string literal), so codegen can't statically verify it doesn't replicate a table that masks a column. This project masks at least one column elsewhere, so the combination can't be proven safe — change "${r.exportName}"'s \`table\` to a plain string literal so codegen can verify it, or remove the mask(s) on the table it targets.`,{status:422});continue}const a=n.get(r.table);if(a===void 0)continue;const c=a.map(u=>`"${u}"`).join(", ");throw new j("MASK_UNSUPPORTED",`defineShape "${r.exportName}" replicates table "${r.table}", which masks column(s) ${c} on at least one procedure. A shape runs no procedure, so \`.use(mask(...))\` never applies to its replicated rows — remove the shape, unmask the table, or wait for shape-masking support.`,{status:422})}},be=(e,t,s)=>{const n=e.getSourceFile(t);if(n===void 0){e.createSourceFile(t,s,{overwrite:!0});return}n.getFullText()!==s&&n.replaceWithText(s)},cs=(e,t,s)=>e.getSourceFile(t)?.getFullText()===s,_d=8,$d=e=>{const{agents:t,apiPath:s,generatedFunctionsPath:n,lunoraDirectory:o,migrations:r,project:a,shapes:c,usesSandbox:u,useUmbrella:d,workflows:m}=e,h=()=>Hn(()=>{const b=Gn(a,o),T=sr(a,o);return{functions:b,httpRoutes:Yn(a,o),mutators:T}});let{erased:L,value:{functions:D,httpRoutes:p,mutators:K}}=h();Dt([...D,...K].map(b=>b.filePath)),Dt(p.filter(b=>b.stream).map(b=>b.filePath),"http-stream");for(let b=1;;b+=1){const T=Nr({agents:t,functions:D,httpRoutes:p,mutators:K,useUmbrella:d,workflows:m}),_=Dr({agents:t,functions:D,migrations:r,mutators:K,shapes:c,useUmbrella:d,usesSandbox:u});if(b>=_d||cs(a,s,T)&&cs(a,n,_))return{apiContent:T,erased:L,functions:D,functionsContent:_,httpRoutes:p,mutators:K};be(a,s,T),be(a,n,_),{erased:L,value:{functions:D,httpRoutes:p,mutators:K}}=h()}},zd=e=>{const t=Md(e);return t?new Ot({skipAddingFilesFromTsConfig:!1,tsConfigFilePath:t,useInMemoryFileSystem:!1}):new Ot({skipAddingFilesFromTsConfig:!0,useInMemoryFileSystem:!1})},Qf=(e,t)=>{const s=g(t),n=x(t,"schema.ts");w(n)&&s.push(n);for(const c of s){const u=e.getSourceFile(c);u===void 0?e.addSourceFileAtPath(c):u.refreshFromFileSystemSync()}const o=new Set(s.map(c=>as(c))),r=as(t),a=`${r}/`;for(const c of e.getSourceFiles()){const u=c.getFilePath();(u===r||u.startsWith(a))&&!o.has(u)&&e.removeSourceFile(c)}for(const c of e.getSourceFiles()){const u=c.getFilePath();if(!(u===r||u.startsWith(a)||u.includes("/node_modules/")))try{c.refreshFromFileSystemSync()}catch{e.removeSourceFile(c)}}},Xf=e=>{const t=Dd(),s=t?_e.now():0,n=x(e.projectRoot,e.lunoraDirectory??"lunora"),o=x(n,"schema.ts");if(!w(o))throw new j("INTERNAL",`schema.ts not found at ${o}`);const r=e.project??zd(n);zn(ha);const a=ur(r,o,e.projectRoot),{agents:c,containers:u,crons:d,dataModelContent:m,dependencies:h,entryCronTriggers:L,env:D,featureUsage:p,hasFlags:K,hasNotify:b,identity:T,platformGate:_,queues:I,serverContent:A,services:J,storageRulesMetadata:Z,topics:G,usesSandbox:ce,useUmbrella:U,workflows:R}=wo({lunoraDirectory:n,project:r,projectRoot:e.projectRoot,schema:a,target:e.target});tc(a,a.jurisdiction===void 0?void 0:Za(r,n));const k=x(n,"_generated"),C=x(k,"dataModel.ts"),Xs=x(k,"server.ts"),Js=x(k,"api.ts"),Zs=x(k,"functions.ts");be(r,C,m),be(r,Xs,A);const le=Zn(r,n),Y=mr(r,n),{apiContent:at,erased:en,functions:q,functionsContent:ct,httpRoutes:Fe,mutators:ue}=$d({agents:c,apiPath:Js,generatedFunctionsPath:Zs,lunoraDirectory:n,migrations:le,project:r,shapes:Y,useUmbrella:U,usesSandbox:ce,workflows:R}),lt=mn(r,n),Oe=hn(lt,a,[...q,...Fe].map(f=>f.filePath)),de=lt.length>0,V=e.lint===!1&&!de?void 0:{inserts:Xn(r,n),queries:ir(r,n),tableWrites:Gu(r,n),workflowCalls:Od(r,n)},fe=e.lint===!1||V===void 0?void 0:pn({adminRoutes:Lo(r,n),aiRawRuns:Bo(r,n),aiToolSideEffects:Jo(r,n),argumentDerivedFetches:ti(r,n),argumentValidators:di(r,n),authApiCalls:Un(r,n),authConfigs:yi(r,n),browserUrlAccesses:wi(r,n),configCalls:$i(r,n),containerKeyAccesses:Ui(r,n),containerOverrides:Hi(r,n),containers:u,exportSinks:Xi(r,n),staleMigrationImports:ku(r,n),failOpenGuards:sa(r,n),flagReads:da(r,n),flagSecurityDefaults:ma(r,n),geoIndexUsages:Ea(r,n),httpActionGuards:Oa(r,n),httpHeaderWrites:Ua(r,n),hyperdriveCalls:Qn(r,n),identityClaimReads:Ga(r,n),imageDeliveryUrlAccesses:Qa(r,n),inserts:V.inserts,kvKeyAccesses:nc(r,n,q),mailRecipientAccesses:cc(r,n),maskProcedures:Jn(r,n),maskStrategies:hc(r,n),mutatorWrites:Ac(r,n),nondeterministicCalls:nr(r,n),normalizeIdAuthorizations:_c(r,n),notifyCalls:or(r,n),notifyConfig:rr(r,n),mutators:ue,ownerFieldWrites:Gc(r,n,q,ue),unrestrictedWhereBranches:Nd(r,n),paymentWebhooks:sl(r,n),privilegedDispatches:pl(r,n),procedureProtections:Xl(r,n),queries:V.queries,queues:I,r2sqlCalls:ar(r,n),ratelimitKeySelectors:ru(r,n),rawRowReturns:du(r,n),relationLoads:gu(r,n),rlsProcedures:cr(r,n),schema:a,secretLiterals:Au(r,n),modules:Oe,shapes:Y,softDeleteReads:Nu(r,n),sqlInterpolations:Fu(r,n),storageKeyAccesses:Du(r,n,q),storageUploads:Uu(r,n),tableWrites:V.tableWrites,vectorNamespaceAccesses:Td(r,n),workflowCalls:V.workflowCalls,workflows:R,wranglerVariables:e.wranglerVariables}),ut=fe===void 0?[]:Kr(e.projectRoot,[...un(fe,{source:"static"}),...cd(r,n,{byName:new Set([...R,...I,...c,...u].map(f=>f.exportName)),byPath:new Set([...q,...ue,...Y,...le].map(f=>`${f.filePath}:${f.exportName}`))}),...Ju(r,n),...Vn(en,n)]),tn=lr(r,n),dt=pc(r,n);Kd(Y,dt,dc(r,n));const sn=K?ia(r,n):[],Re=_.signals.vectorStore!==!1,ee=Bu(p,{containerCount:u.length,cronCount:d.length,dependencies:h,hasPaymentTables:Xc(a.tables),queueCount:I.length,storageColumnCount:Object.keys(Ss(a)).length,storageRuleCount:Z.rules.length,vectorIndexCount:a.vectorIndexes.length,target:Es(e.projectRoot,e.target),vectorStoreSupported:Re,workflowCount:R.length}),ft=t?_e.now():0,ke=yr(a,le.map(f=>f.id)),pt=Kn({advisories:ut.filter(f=>f.name!=="procedure_type_check_unavailable"),advisorProcedures:fe?.procedureProtections??[],agents:c,containers:u,env:D,flagKeys:sn,hasAccessFacade:p.access,hasAi:p.ai,hasAnalytics:p.analytics,hasBrowser:p.browser,hasFlags:K,hasHyperdrive:p.hyperdrive,hasImages:p.images,hasKv:p.kv,hasNotify:b,hasPayments:p.payments,hasPipelines:p.pipelines,hasR2sql:p.r2sql,hasVectors:Re,hasX402:p.x402,maskMetadata:dt,mutators:ue,queues:I,rlsMetadata:tn,schema:a,schemaSnapshot:ke,shapes:Y,services:J,storageRules:Z,studioFeatures:ee,topics:G,useUmbrella:U,workflows:R}),gt=Ar(Y,h.has("@lunora/db"),U),mt=Pr(u,a.jurisdiction),ht=wr(R),vt=Ir(c),xt=Tr(I),Et=Cr(d),nn=Fr(ee.scheduler),rn=Or(a.tables,U),St=Rr(a.vectorIndexes),pe=Lr(a,U),yt=br(h.has("@lunora/seed")),ge=e.apiSpec??"openapi",Le=ge==="openapi"||ge==="both",De=ge==="openrpc"||ge==="both",At=hr({emailAgents:c.filter(f=>f.onEmail===!0).map(f=>({className:f.className,exportName:f.exportName})),hasAccess:h.has("@lunora/cloudflare-access"),hasAi:p.ai,hasAnalytics:p.analytics,hasAuth:h.has("@lunora/auth"),hasBrowser:p.browser,hasFramework:h.has("@lunora/astro")||h.has("@lunora/svelte")||h.has("@lunora/vue")||w(x(e.projectRoot,"src","worker.ts")),hasGlobal:a.tables.some(f=>us(f)),hasHyperdrive:p.hyperdrive,hasHyperdriveGlobal:a.tables.some(f=>ds(f)),hasImages:p.images,hasKv:p.kv,hasKvIntrospector:ee.kv,hasNotify:b,hasPayments:p.payments,hasR2sql:p.r2sql,hasQueue:I.some(f=>f.mode==="push"),hasScheduler:ee.scheduler,hasSourcedTables:a.tables.some(f=>f.externalSource!==void 0),hasStorage:ee.storage,hasVectors:Re,hasWorkflow:R.length>0,hasX402:p.x402,identity:T,jurisdiction:a.jurisdiction,jurisdictionPinsAuth:a.jurisdictionPinsAuth===!0,tables:a.tables.map(f=>({name:f.name,shardMode:f.shardMode})),useUmbrella:U,vectorIndexCount:a.vectorIndexes.length,voiceAgents:c.filter(f=>f.voice===!0&&f.voiceBindingName!==void 0).map(f=>({bindingName:f.voiceBindingName,exportName:f.exportName})),wantsArchitecture:de,wantsOpenApi:Le,wantsOpenRpc:De}),bt=Ld(e.projectRoot),Nt=de?Oe:[],Pt=vr({functions:q,httpRoutes:Fe,modules:Nt,version:bt}),wt=Er({functions:q,modules:Nt,version:bt}),It=`${JSON.stringify(Pt,void 0,2)}
|
|
9
|
-
`,Tt=`${JSON.stringify(wt,void 0,2)}
|
|
10
|
-
`,me=de&&V!==void 0?Gr({...V,callEdges:Oi(r,n),crons:d,functions:q,httpRoutes:Fe,modules:Oe,queues:I,schema:a,services:J,topics:G,workflows:R}):void 0,Ct=xr(Pt),Ft=Sr(wt),Me=x(n,Rd),on=w(Me),Ke=[];if(!e.dryRun){w(k)||an(k,{recursive:!0});const f=(H,Q)=>{Je(x(k,H),Q),Ke.push(H)},P=(H,Q)=>{kd(x(k,H),Q),Q!==""&&Ke.push(H)};f("app.ts",At),f("dataModel.ts",m),f("api.ts",at),f("server.ts",A),f("functions.ts",ct),f("shard.ts",pt),f("crons.ts",Et),f("vectors.ts",St),f("drizzle.global.ts",pe.global),f("drizzle.shard.ts",pe.shard),P("containers.ts",mt),P("workflows.ts",ht),P("agents.ts",vt),P("queues.ts",xt),P("scheduler.ts",nn),P("shardRegistry.ts",rn),P("seed.ts",yt),P("collections.ts",gt),P("openapi.json",Le?It:""),P("openapi.ts",Le?Ct:""),P("openrpc.json",De?Tt:""),P("openrpc.ts",De?Ft:""),P("architecture.json",me===void 0?"":`${JSON.stringify(me,void 0,2)}
|
|
11
|
-
`),P("architecture.ts",me===void 0?"":Yr(me)),(!on||e.updateSchemaBaseline===!0)&&Je(Me,fn(ke))}if(t){const f=_e.now(),P=Math.round(f-s),H=Math.round(ft-s),Q=Math.round(f-ft);console.error(`@lunora/codegen: codegen took ${P.toString()}ms (discovery ${H.toString()}ms, emit ${Q.toString()}ms)`)}return{advisories:ut,advisorContext:fe,agents:c,containers:u,cronTriggers:[...new Set([...kr(d),...L])],generated:{agents:vt,api:at,app:At,collections:gt,containers:mt,crons:Et,dataModel:m,drizzleGlobal:pe.global,drizzleShard:pe.shard,functions:ct,openApi:It,openApiModule:Ct,openRpc:Tt,openRpcModule:Ft,queues:xt,seed:yt,server:A,shard:pt,vectors:St,workflows:ht},migrations:le,outputDirectory:k,platformDiagnostics:_.diagnostics,queues:I,schemaSnapshot:ke,schemaSnapshotPath:Me,workflows:R,writtenFiles:Ke}};export{Rd as SCHEMA_SNAPSHOT_FILENAME,zd as createCodegenProject,Md as findTsconfig,Qf as refreshCodegenProject,Xf as runCodegen};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{listLunoraSourceFiles as f}from"./listLunoraSourceFiles-CSlcBYlo.mjs";const d=new Set(["@lunora/agent","@lunora/agent/sandbox"]),t={browserTool:"usesSandboxBrowser",containerTool:"usesSandboxContainer",fsTool:"usesSandboxFs",jsCodeTool:"usesSandboxLoader"},u=()=>({usesSandboxBrowser:!1,usesSandboxContainer:!1,usesSandboxFs:!1,usesSandboxLoader:!1}),i=o=>{const s=u();if(!d.has(o.getModuleSpecifierValue())||o.isTypeOnly())return s;for(const e of o.getNamedImports()){if(e.isTypeOnly())continue;const n=t[e.getNameNode().getText()];n!==void 0&&(s[n]=!0)}return s},b=(o,s)=>{const e=u();for(const n of f(s)){const c=o.getSourceFile(n)??o.addSourceFileAtPath(n);for(const a of c.getImportDeclarations()){const l=i(a);for(const r of Object.values(t))e[r]||=l[r]}if(Object.values(t).every(a=>e[a]))break}return e};export{b as discoverSandboxUsage};
|