@lunora/codegen 1.0.0-alpha.244 → 1.0.0-alpha.246
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 +73 -3
- package/dist/index.d.ts +73 -3
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/DEFAULT_TARGET-D-zkySYF.mjs +1 -0
- package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-KDyLA-v5.mjs +11 -0
- package/dist/packem_shared/emitAgents-CnQEPybh.mjs +1 -0
- package/dist/packem_shared/{emitApp-Cu0w-3vl.mjs → emitApp-DsMk4tpo.mjs} +2 -0
- package/dist/packem_shared/{emitServer-pF_fhA82.mjs → emitServer-nvzMxk3d.mjs} +59 -50
- package/dist/packem_shared/{emitShard-DID_s1FK.mjs → emitShard-BiKPSgNP.mjs} +1 -1
- package/dist/packem_shared/loadProjectConfig-6Zk3abcc.mjs +1 -0
- package/dist/packem_shared/readServiceBindings-D9Wi_qGU.mjs +1 -0
- package/dist/packem_shared/{shard-BVzXMtWg.mjs → shard-D6EZdlSg.mjs} +61 -61
- package/dist/packem_shared/{shard-runtime-oIXHEMU7.mjs → shard-runtime-D9GRosnD.mjs} +14 -6
- package/package.json +6 -6
- package/dist/packem_shared/DEFAULT_TARGET-BLYeFMMT.mjs +0 -1
- package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-D1zEPvOK.mjs +0 -11
- package/dist/packem_shared/emitAgents-C3ygr0M8.mjs +0 -1
- package/dist/packem_shared/loadProjectConfig-CktK_il-.mjs +0 -1
|
@@ -1,11 +0,0 @@
|
|
|
1
|
-
import{existsSync as I,mkdirSync as rn,readFileSync as as,writeFileSync as on,rmSync as an}from"node:fs";import{join as S,dirname as pe}from"node:path";import{performance as Me}from"node:perf_hooks";import{runAdvisor as cn}from"@lunora/advisor";import{LunoraError as B}from"@lunora/errors";import{SyntaxKind as l,Node as i,VariableDeclarationKind as ln,Project as Ct}from"ts-morph";import{serializeSchemaSnapshot as un}from"./SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs";import{toAdvisorContext as dn}from"./formatAdvisories-DwmUKYuc.mjs";import{readProjectConfigLiterals as fn}from"./loadProjectConfig-CktK_il-.mjs";import{a as Ft,d as pn,r as gn}from"./modules-DyCocr1e.mjs";import{QUEUES_FILENAME as mn,discoverQueueDeclarations as hn}from"./QUEUES_FILENAME-RGwht3Xu.mjs";import{WORKFLOWS_FILENAME as vn,discoverWorkflows as xn}from"./WORKFLOWS_FILENAME-4-ib4HH-.mjs";import{r as En}from"./json-data-Chfs2Cz5.mjs";import{s as ye}from"./paths-C-9fwEgQ.mjs";import{G as Sn}from"./shared-DjUziztz.mjs";import{C as ge}from"./capabilities-DJJWVEtk.mjs";import{isD1GlobalTable as cs,isHyperdriveGlobalTable as ls}from"./isD1GlobalTable-udvHAAzD.mjs";import{discoverAgents as yn}from"./AGENTS_FILENAME-D8SgT3OR.mjs";import{discoverContainers as An}from"./CONTAINERS_FILENAME-CBCG6g9n.mjs";import bn from"./discoverCrons-BEALHx1S.mjs";import{diagnosticAt as re}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{b as Ae}from"./module-specifiers-WF8iAydP.mjs";import{listLunoraSourceFiles as g,bindingKeyName as Q,propertyKeyName as y,unwrapExpression as te,listSecurityScanFiles as be,objectLiteralFromCallbackBody as us,propertyInitializer as P,lunoraRelativePath as x,enclosingExportName as Ne,collectCallRows as F,findObjectProperty as C,collectSecurityCallRows as Nn,RUN_METHODS as ds,functionReferenceSegments as fs,limitNameOf as ps,optionsObjectLiteral as gs,isContextIdentifier as je,handlerOf as Pn,isDatabaseAccessor as M,readTargetOf as ms}from"./listLunoraSourceFiles-CSlcBYlo.mjs";import wn from"./readPackageDependencies-C6h6FZuP.mjs";import{discoverSandboxUsage as In}from"./discoverSandboxUsage-DkbwwFvO.mjs";import Tn from"./discoverStorageRulesMetadata-D3Ot9g5f.mjs";import{a as b,c as z,d as hs,e as Cn}from"./classify-procedure-call-CmcShAze.mjs";import{i as Fn}from"./ir-DBSvhNa-.mjs";import{gatePlatformFeatures as On,resolveCodegenTarget as vs,readTargetDiagnostics as Rn,studioPlatformFor as kn}from"./DEFAULT_TARGET-BLYeFMMT.mjs";import{b as xs,e as Ln}from"./shard-BVzXMtWg.mjs";import Dn from"./emitServer-pF_fhA82.mjs";import{emitDataModel as Mn}from"./emitDataModel-D3WuEZ4b.mjs";import{r as Pe,s as Kn}from"./parse-validator-C6fHL7OS.mjs";import _n from"./discoverAuthApiCalls-DoSN_yc3.mjs";import{i as $n,a as zn,e as Un,b as Bn,d as qn,c as jn}from"./unwrap-handler-return-DVY_kFF7.mjs";import Wn from"./discoverFunctions-BcBzcG5x.mjs";import Vn from"./discoverHttpRoutes-CJHS4llq.mjs";import Hn from"./discoverHyperdriveCalls-Bkbh4tG7.mjs";import Gn from"./discoverInserts-DpuLYPPd.mjs";import{m as Xe,a as ve,s as Es,d as Yn}from"./index-D7dKfGPh.mjs";import{e as Ss}from"./exported-procedure-chains-D48EXUVQ.mjs";import Qn from"./discoverMigrations-Dt7ywfZv.mjs";import{MUTATORS_FILENAME as Xn,isDefineMutatorCallee as Jn,discoverMutators as Zn}from"./MUTATORS_FILENAME-DqWOgC5Z.mjs";import er from"./discoverNondeterministicCalls-CNJV2BiP.mjs";import{discoverNotifyConfig as tr,discoverNotifyCalls as sr}from"./NOTIFY_FILENAME-C1J_47et.mjs";import nr from"./discoverQueries-BcdqjYky.mjs";import rr from"./discoverR2sqlCalls-30Wtbc0P.mjs";import or from"./discoverRlsProcedures-F4Cy-kSi.mjs";import ir from"./discoverRlsMetadata-mXBmPOGj.mjs";import ar from"./discoverSchema-D5R60b4F.mjs";import{secretKindOf as cr,redact as lr,isHeuristicSecretKind as ur,isSecretishName as dr}from"./redact-Cy14LEnc.mjs";import{discoverShapes as fr}from"./SHAPES_FILENAME-DRUFomCj.mjs";import{emitApp as pr}from"./emitApp-Cu0w-3vl.mjs";import{buildOpenApiDocument as gr,emitOpenApiModule as mr}from"./buildOpenApiDocument-SxfElVzK.mjs";import{buildOpenRpcDocument as hr,emitOpenRpcModule as vr}from"./OPENRPC_VERSION-Cr7Zzp6s.mjs";import{buildSchemaSnapshot as xr}from"./SchemaSnapshotParseError-CPOXlFhI.mjs";import{emitCollections as Er,emitSeed as Sr,emitApi as yr}from"./emitApi-DdW9RyGG.mjs";import{B as Ar,C as br,A as Nr,D as Pr}from"./shard-runtime-oIXHEMU7.mjs";import{emitCrons as wr,emitScheduler as Ir,emitShardRegistry as Tr,emitVectors as Cr,emitWranglerCronTriggers as Fr}from"./emitCrons-BRKXFGFu.mjs";import Or from"./emitDrizzleSchema-Cv0HtLR3.mjs";import Rr from"./emitFunctions-BgNeOZt_.mjs";const Ot={error:"ERROR",info:"INFO",warn:"WARN"},Rt={ERROR:2,INFO:0,WARN:1},kr=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"}),Lr=(e,t)=>{const{advisor:s}=fn(e);if(s===void 0||s.minSeverity===void 0&&s.unreadable!==!0)return[...t];const{minSeverity:n}=s,o=n!==void 0&&Object.hasOwn(Ot,n)?Ot[n]:void 0;return o===void 0?[...t,kr(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=>Rt[r.level]>=Rt[o])},Dr={call:"function",enqueue:"queue",publish:"topic",schedule:"function"},ys=mn.replace(/\.ts$/u,""),Mr="crons",Kr=vn.replace(/\.ts$/u,""),Z=(e,t)=>`${ye(e)}:${t}`,Ke=(e,t,s)=>t===""?{reason:`the ${s} is not a string literal`}:{to:`${e}:${t}`},_r=e=>[...e.callEdges.map(t=>{const s=t.target===void 0?{reason:t.reason??"unreadable target"}:{to:`${Dr[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,...Ke("table",t.table,"table name")})),...[...e.inserts,...e.tableWrites].map(t=>({exportName:t.exportName,file:t.file,kind:"write",line:t.line,...Ke("table",t.table,"written table")})),...e.workflowCalls.map(t=>({exportName:t.exportName,file:t.file,kind:"start",line:t.line,...Ke("workflow",t.workflow,"workflow name")}))],$r=e=>[...e.queues.flatMap(t=>t.topic===void 0?[]:[{exportName:t.exportName,file:ys,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:Mr,from:`cron:${t.name}`,kind:"trigger",line:0,...o===void 0?{reason:"the cron has no target"}:{to:o}}})],zr=e=>new Map(e.flatMap(t=>t.tables.map(s=>[s,t.name]))),_e=(e,t)=>t===void 0?e:{...e,module:t},Ur=e=>{const t=new Map,s=new Map,n=zr(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=Z(r.filePath,r.exportName),c=`${ye(r.filePath)}.${r.exportName}`;o(_e({detail:r.kind,id:`function:${a}`,kind:"function",name:c},Ft(e.modules,r.filePath)),a)}for(const r of e.httpRoutes){const a=Z(r.filePath,r.exportName);o(_e({id:`http:${a}`,kind:"http",name:`${r.method} ${r.path}`},Ft(e.modules,r.filePath)),a)}for(const r of e.schema.tables)o(_e({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},Z(ys,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},Z(Kr,r.exportName));for(const r of e.crons)o({detail:r.cron,id:`cron:${r.name}`,kind:"cron",name:r.name});return{nodes:t,sites:s}},Br=e=>e===""?"inside a non-exported helper":e==="default"?"the default export is not a registered function":`"${e}" is not a registered function`,qr=(e,t,s)=>{if("reason"in e)return{reason:e.reason};const n=e.from??t.get(Z(e.file,e.exportName));return n===void 0?{reason:Br(e.exportName)}:s.has(e.to)?{drawn:{from:n,kind:e.kind,to:e.to}}:{reason:`${e.to} is not declared`}},$e=e=>`${e.from}|${e.kind}|${e.to}`,jr=e=>`${e.file}|${String(e.line)}|${e.kind}|${e.reason}`,Wr=e=>{const{nodes:t,sites:s}=Ur(e),n=new Map,o=new Map;for(const r of[...$r(e),..._r(e)]){const a=qr(r,s,t);if("drawn"in a)n.set($e(a.drawn),a.drawn);else{const c={file:r.file,kind:r.kind,line:r.line,reason:a.reason};o.set(jr(c),c)}}return{edges:[...n.values()].toSorted((r,a)=>$e(r).localeCompare($e(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}},Vr=e=>`${Sn}export const architecture = ${En(e,"Record<string, unknown>")};
|
|
2
|
-
`,kt=(e,t="api")=>{const s=new Map;for(const n of e){const o=ye(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 B("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})}}},Hr=(e,t={})=>{const{hasVectors:s=!0,scheduler:n=!1,storage:o=!1,usage:r}=t,a=[];e.tables.some(c=>cs(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=>ls(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?[]:ge)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)},Gr=(e,t,s={})=>{if(t===void 0)return;const n=Hr(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 B("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.`)},Yr="env.ts",Qr=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineEnv";for(const s of t.getDeclarations())if(i.isImportSpecifier(s))return Ae(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineEnv":!1;return!1},Xr=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&&Ae(n.getModuleSpecifierValue())}return!1},Jr=e=>{if(i.isIdentifier(e))return Qr(e);if(i.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineEnv"&&i.isIdentifier(t)&&Xr(t)}return!1},Zr=e=>{const t=[];for(const s of e.getVariableDeclarations()){if(!s.isExported())continue;const n=s.getInitializer();if(n?.getKind()!==l.CallExpression||!Jr(n.getExpression()))continue;const r=s.getNameNode();if(!i.isIdentifier(r))throw re(r,"defineEnv exports must be plain named exports (no destructuring)");t.push({exportName:r.getText()})}return t},eo=(e,t)=>{const s=S(t,Yr);if(!I(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s),o=Zr(n);if(o.length!==0){if(o.length>1)throw re(n,`lunora/env.ts declares ${o.length.toString()} defineEnv() contracts (${o.map(r=>r.exportName).join(", ")}); exactly one is allowed`);return o[0]}},Lt="ctx",As=e=>{const t=new Set,s=new Set([Lt]),n=r=>{if(i.isObjectBindingPattern(r))for(const a of r.getElements()){const c=Q(a);c&&t.add(c)}};for(const r of e.getDescendantsOfKind(l.BindingElement)){if(Q(r)!==Lt)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},to=(e,t)=>{const s=Object.fromEntries(ge.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=As(o);for(const c of ge)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(ge.every(c=>s[c.key]))break}return s},bs="identity.ts",so=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineIdentity";for(const s of t.getDeclarations())if(i.isImportSpecifier(s))return Ae(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineIdentity":!1;return!1},no=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&&Ae(n.getModuleSpecifierValue())}return!1},ro=e=>{if(i.isIdentifier(e))return so(e);if(i.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineIdentity"&&i.isIdentifier(t)&&no(t)}return!1},oo=e=>{const t=[];for(const s of e.getVariableDeclarations()){if(!s.isExported())continue;const n=s.getInitializer();if(n?.getKind()!==l.CallExpression||!ro(n.getExpression()))continue;const r=s.getNameNode();if(!i.isIdentifier(r))throw re(r,"defineIdentity exports must be plain named exports (no destructuring)");t.push({exportName:r.getText()})}return t},io=(e,t)=>{const s=S(t,bs);if(!I(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s),o=oo(n);if(o.length!==0){if(o.length>1)throw re(n,`lunora/identity.ts declares ${o.length.toString()} defineIdentity() contracts (${o.map(r=>r.exportName).join(", ")}); exactly one is allowed`);return o[0]}},ao=new Set(["allowedHosts","deniedHosts","interceptHttps"]),co=(e,t)=>{const s=te(t);if(s===void 0||!i.isIdentifier(s))return s;const n=s.getText();return te(e.getDescendantsOfKind(l.VariableDeclaration).find(o=>o.getName()===n)?.getInitializer())},lo=(e,t)=>e!==void 0&&i.isObjectLiteralExpression(e)&&e.getProperties().some(s=>{if(i.isShorthandPropertyAssignment(s))return t.has(y(s));if(!i.isPropertyAssignment(s)||!t.has(y(s)))return!1;const n=te(s.getInitializer())?.getText();return n!=="false"&&n!=="undefined"}),uo=new Set(["durable"]),fo=new Set(["rollback"]),po=e=>{const t=e.getExpression();return i.isPropertyAccessExpression(t)?t.getName():t.getText()},go=new Map([["defineContainer",{keys:ao,signal:"containerEgressPolicy"}],["defineStep",{keys:fo,signal:"workflowRollback"}],["stream",{keys:uo,signal:"durableStreams"}]]),mo=(e,t)=>{const s=go.get(po(t));if(s!==void 0)return t.getArguments().some(n=>lo(co(e,n),s.keys))?s.signal:void 0},ho=(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=As(o).has("secrets"));for(const r of o.getDescendantsOfKind(l.CallExpression)){const a=mo(o,r);a!==void 0&&(s[a]=!0)}if(Object.values(s).every(Boolean))break}return s},vo="createWorker",xo="extend",Dt=e=>e!==void 0&&(i.isStringLiteral(e)||i.isNoSubstitutionTemplateLiteral(e))?e.getLiteralValue():void 0,Mt=e=>{const t=[],s=Dt(P(e,"backupCron"));s!==void 0&&t.push(s);const n=P(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=Dt(o.getNameNode());r!==void 0&&t.push(r)}return t},Eo=e=>{const t=b(e.getExpression()),[s]=e.getArguments();if(s===void 0)return[];if(t===vo)return i.isObjectLiteralExpression(s)?Mt(s):[];if(t!==xo||!(i.isArrowFunction(s)||i.isFunctionExpression(s)))return[];const n=us(s.getBody());return n===void 0?[]:Mt(n)},So=(e,t)=>{const s=[];for(const{filePath:n}of be(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const r of o.getDescendantsOfKind(l.CallExpression))s.push(...Eo(r))}return[...new Set(s)]},Ns=e=>{if(e.kind==="id")return e.tableName;if(!(e.kind!=="array"&&e.kind!=="optional"))return e.inner===void 0?void 0:Ns(e.inner)},yo=e=>{const t=new Set(e.tables.map(s=>s.name));return e.tables.some(s=>Object.values(s.shape).some(n=>{const o=Ns(n);return o!==void 0&&t.has(o)}))},Ao=(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 B("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 B("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})}},bo=e=>{const{lunoraDirectory:t,project:s,projectRoot:n,schema:o}=e,r=io(s,t),a=eo(s,t),c=xn(s,t),{queues:u,topics:d}=hn(s,t),p=yn(s,t);Ao(c,p);const h=An(s,t),R=Tn(s,t),k=bn(s,t,c,p),m=So(s,t),T=ho(s,t),N=In(s,t),L=to(s,t);L.browser=L.browser||N.usesSandboxBrowser;const D=On(L,vs(n,e.target),{agents:p.length>0,commitOrderedTables:o.tables.some(E=>E.commitOrdered===!0),cronTriggers:k.length>0,crossShardFanout:o.tables.some(E=>Fn(E)),containerEgressPolicy:T.containerEgressPolicy,containerRuntimeScheduling:h.some(E=>E.schedulingPolicy==="durable_object"),durableStreams:T.durableStreams,globalTables:o.tables.some(E=>E.shardMode==="global"),queues:u.length>0,relationGraph:yo(o),secrets:T.secrets,topics:d.length>0,vectorStore:o.vectorIndexes.length>0,workerLoaders:N.usesSandboxLoader,workflowRollback:T.workflowRollback,workflowSchedules:c.some(E=>E.schedules!==void 0)}),v=D.usage,V=D.signals.vectorStore!==!1,H=wn(n),X=H??new Set,oe=X.has("lunorash");Gr(o,H,{hasVectors:V,scheduler:v.scheduler||k.length>0,storage:v.storage||R.rules.length>0||Object.keys(xs(o)).length>0,usage:v});const $=I(S(t,"flags.ts")),O=I(S(t,"notify.ts"));return{agents:p,containers:h,crons:k,dataModelContent:Mn(o),declaredDependencies:H,dependencies:X,entryCronTriggers:m,env:a,featureUsage:v,hasFlags:$,hasNotify:O,identity:r,platformGate:{...D,diagnostics:[...Rn(n,e.target),...D.diagnostics]},queues:u,serverContent:Dn({agents:p,containers:h,env:a,hasAccessFacade:v.access,hasAi:v.ai,hasAnalytics:v.analytics,hasBrowser:v.browser,hasVectors:V,hasFlags:$,hasHyperdrive:v.hyperdrive,hasImages:v.images,hasKv:v.kv,hasNotify:O,hasPayments:v.payments,hasPipelines:v.pipelines,hasR2sql:v.r2sql,hasX402:v.x402,identity:r,queues:u,schema:o,storageRuleBuckets:R.rules.map(E=>E.bucket),topics:d,useUmbrella:oe,workflows:c}),storageRulesMetadata:R,topics:d,usesSandbox:N.usesSandboxBrowser||N.usesSandboxContainer||N.usesSandboxFs,useUmbrella:oe,workflows:c}},Ps=new Set(["delete","get","head","options","patch","post","put"]),No=new Set(["handler","stream"]),Po=/\/(?:_|admin|internal|superuser|sudo|root|debug)/iu,Kt=new Set(["ADMIN_TOKEN","adminToken","assertAdmin","assertAuth","auth","Authorization","getSession","identity","isAdmin","requireAdmin","requireAuth","requireRole","verifyAdmin"]),wo=e=>{if(!i.isCallExpression(e))return;const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!Ps.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()}},Io=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)||Ps.has(n.getName()))break;s=n.getExpression()}return wo(s)},To=e=>{for(const t of e.getDescendantsOfKind(l.PropertyAccessExpression))if(Kt.has(t.getName()))return!0;for(const t of e.getDescendantsOfKind(l.CallExpression)){const s=t.getExpression();if(i.isIdentifier(s)&&Kt.has(s.getText()))return!0}return!1},Co=(e,t)=>{const s=e.getInitializer();if(!s||!i.isCallExpression(s))return;const n=s.getExpression();if(!i.isPropertyAccessExpression(n)||!No.has(n.getName()))return;const o=Io(s);if(!o||!Po.test(o.path))return;const r=s.getArguments()[0],a=r!==void 0&&(i.isArrowFunction(r)||i.isFunctionExpression(r))&&To(r);return{exportName:e.getName(),file:t,method:o.method,path:o.path,usesGuard:a}},Fo=(e,t)=>{const s=[];for(const n of e.getVariableStatements())if(n.isExported())for(const o of n.getDeclarations()){const r=Co(o,t);r&&s.push(r)}return s},Oo=(e,t)=>{const s=[];for(const n of g(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Fo(o,x(t,n)))}return s},Ro=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}},ko=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)?Q(t):void 0}},_t=(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=Ro(e);return n!==void 0&&ko(n)===t},Je=(e,t)=>i.isIdentifier(e)?_t(e,t):e.getDescendantsOfKind(l.Identifier).some(s=>_t(s,t)),ze=e=>Je(e,"ctx"),Lo=e=>{let t=e;for(;i.isPropertyAccessExpression(t)||i.isElementAccessExpression(t)||i.isNonNullExpression(t);)t=t.getExpression();return i.isIdentifier(t)?t:void 0},We=e=>Je(e,"args"),K=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},_=e=>{if(We(e))return!0;const t=K(e);return t!==void 0&&We(t)},Do=e=>{if(i.isCallExpression(e)||i.isNewExpression(e))return!1;const t=K(e);return t===void 0||!(i.isCallExpression(t)||i.isNewExpression(t))},q=e=>{if(ze(e))return!0;const t=K(e);if(t!==void 0&&ze(t))return!0;const s=t??e;return(i.isIdentifier(s)?[s]:s.getDescendantsOfKind(l.Identifier)).some(o=>{const r=K(o);return r!==void 0&&ze(r)})},me=(e,t)=>Je(e,t),Mo=(e,t)=>{if(me(e,t))return!0;const s=K(e);if(s!==void 0&&me(s,t))return!0;const n=Lo(e);if(n!==void 0){const o=K(n);return o!==void 0&&me(o,t)}return!1},A=e=>Ne(e)||"<module>",Ko=e=>!i.isPropertyAccessExpression(e)||e.getName()!=="run"?!1:e.getExpression().getText()==="ctx.ai",_o=(e,t)=>{if(!Ko(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!_(s)||q(s)))return{exportName:A(e),file:t,line:e.getStartLineNumber()}},$o=(e,t)=>F(e,t,_o),zo=new Set(["generateText","streamText"]),Uo=new Set(["messages","prompt","system"]),Bo=[{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"]}],qo=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t))return;const s=t.getName(),n=t.getExpression().getText();for(const o of Bo)if(o.methods.has(s)&&o.prefixes.some(r=>n===r||n.startsWith(`${r}.`)))return`${n}.${s}`},jo=e=>{for(const t of e.getDescendantsOfKind(l.CallExpression)){const s=qo(t);if(s!==void 0)return s}},Wo=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=Q(r),c=r.getNameNode();if(a==="args"&&i.isObjectBindingPattern(c))for(const u of c.getElements())t.add(u.getName())}return t},Vo=e=>{if(We(e))return!0;const t=Wo(e);return t.size===0?!1:e.getDescendantsOfKind(l.Identifier).some(s=>t.has(s.getText()))},Ho=e=>{for(const t of e.getProperties()){if(!i.isPropertyAssignment(t)||!Uo.has(y(t)))continue;const s=t.getInitializer();if(s!==void 0&&Vo(s))return!0}return!1},Go=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression)){const o=b(n.getExpression());if(o===void 0||!zo.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(b(c.getExpression())==="tool"&&(a=jo(c),a!==void 0))break;a!==void 0&&s.push({exportName:A(n),file:t,line:n.getStartLineNumber(),method:o,sideEffect:a,userInputDerived:Ho(r)})}return s},Yo=(e,t)=>{const s=[];for(const n of g(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Go(o,x(t,n)))}return s},Qo=e=>{if(!i.isPropertyAccessExpression(e)||e.getName()!=="fetch")return!1;const t=e.getExpression();return i.isIdentifier(t)&&t.getText()==="ctx"},Xo=(e,t)=>{if(!Qo(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!_(s)))return{exportName:A(e),file:t,line:e.getStartLineNumber()}},Jo=(e,t)=>F(e,t,Xo),Ze=(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=Pe(s.getExpression());return n===void 0||Ze(n,t)})}finally{t.delete(e)}},Zo=e=>{const t=e.getArguments()[0];if(!t||!i.isObjectLiteralExpression(t))return{objects:[],opaque:!0};const s=C(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:Pe(n);return o===void 0?{objects:[],opaque:!0}:{objects:[o],opaque:Ze(o)}},ei=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)?Pe(r):void 0;a===void 0?s=!0:(t.push(a),s||=Ze(a))}n=o.getExpression()}return{objects:t,opaque:s}},et=(e,t)=>t?ei(t):Zo(e),ws=(e,t)=>{if(t.has(e))return[];t.add(e);try{return e.getProperties().flatMap(s=>{if(i.isSpreadAssignment(s)){const n=Pe(s.getExpression());return n===void 0?[]:ws(n,t)}return i.isPropertyAssignment(s)||i.isShorthandPropertyAssignment(s)?[y(s)]:[]})}finally{t.delete(e)}},ti=e=>e.flatMap(t=>ws(t,new Set)),si=new Set(["check","length","max"]),Ve=e=>{if(!i.isCallExpression(e))return;const t=e.getExpression();if(!(!i.isPropertyAccessExpression(t)||t.getExpression().getText()!=="v"))return t.getName()},ni=e=>[e,...e.getDescendants()].filter(t=>Ve(t)!==void 0),ri=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(si.has(s.getName()))return!0;t=n}},oi=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=ni(r),c=y(o);a.some(u=>Ve(u)==="any")?t.push(c):a.some(u=>Ve(u)==="string"&&!ri(u))&&s.push(c)}return{anyArgs:t,unboundedStringArgs:s}},ii=(e,t)=>{const s=e.getInitializer();if(!s||!i.isCallExpression(s))return;const n=z(s);if(n?.visibility!=="public")return;const{objects:o}=et(s,n.receiver),{anyArgs:r,unboundedStringArgs:a}=oi(o);if(!(r.length===0&&a.length===0))return{anyArgs:r,exportName:e.getName(),file:t,line:s.getStartLineNumber(),unboundedStringArgs:a}},ai=(e,t)=>{const s=[];for(const n of e.getVariableStatements())if(n.isExported())for(const o of n.getDeclarations()){const r=ii(o,t);r&&s.push(r)}return s},ci=(e,t)=>{const s=[];for(const n of g(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...ai(o,x(t,n)))}return s},Ue=e=>e?.getKind()===l.TrueKeyword,li=e=>e?.getKind()===l.FalseKeyword,ui=e=>e!==void 0&&i.isNumericLiteral(e)&&e.getLiteralValue()===0,di=new Set(["lunoraAuthAdapter","lunoraD1Adapter"]),fi=e=>!e||!i.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>i.isCallExpression(t)&&b(t.getExpression())==="scim"),pi=e=>e!==void 0&&i.isCallExpression(e)&&di.has(b(e.getExpression())??""),gi=e=>!e||!i.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>i.isStringLiteral(t)&&t.getLiteralText()==="*"),mi=e=>{const t=P(e,"advanced"),s=P(e,"emailAndPassword"),n=P(e,"session");return{analyzable:!0,disableCsrfCheck:Ue(P(t,"disableCSRFCheck")),emailPasswordEnabled:Ue(P(s,"enabled")),requireEmailVerification:Ue(P(s,"requireEmailVerification")),scimOnNonTransactionalAdapter:fi(P(e,"plugins"))&&pi(P(e,"database")),secureCookiesDisabled:li(P(t,"useSecureCookies")),sessionFreshAgeZero:ui(P(n,"freshAge")),trustedOriginsWildcard:gi(P(e,"trustedOrigins"))}},hi=()=>({analyzable:!1,disableCsrfCheck:!1,emailPasswordEnabled:!1,requireEmailVerification:!1,scimOnNonTransactionalAdapter:!1,secureCookiesDisabled:!1,sessionFreshAgeZero:!1,trustedOriginsWildcard:!1}),vi=(e,t)=>{if(b(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?mi(s):hi();return{exportName:A(e),file:t,line:e.getStartLineNumber(),...o}},xi=(e,t)=>Nn(e,t,vi),Ei=(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},Si=(e,t,s)=>{const n=Ei(e.getExpression(),s);if(n===void 0)return;const o=e.getArguments()[s.argIndex];if(!(!o||!_(o)||q(o))&&!(s.requireUnmodifiedReach===!0&&!Do(o)))return{exportName:A(e),file:t,line:e.getStartLineNumber(),method:n}},yi=(e,t,s)=>{const n=[];for(const o of e.getDescendantsOfKind(l.CallExpression)){const r=Si(o,t,s);r&&n.push(r)}return n},we=(e,t,s)=>{const n=[];for(const o of g(t)){const r=e.getSourceFile(o)??e.addSourceFileAtPath(o);n.push(...yi(r,x(t,o),s))}return n},Ai=new Set(["content","pdf","scrape","screenshot"]),bi=(e,t)=>we(e,t,{argIndex:0,matchReceiver:s=>s==="ctx.browser",methods:Ai}),Is=e=>{const t=fs(e);return t===void 0?void 0:`${ye(t.slice(0,-1).join("/"))}:${String(t.at(-1))}`},Ni=(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},Pi=e=>{if(!i.isPropertyAccessExpression(e))return!1;const t=e.getExpression();return i.isPropertyAccessExpression(t)&&t.getName()==="scheduler"||i.isIdentifier(t)&&t.getText()==="scheduler"},wi=new Map([["publish",{kind:"publish",surface:"topics"}],["publishBatch",{kind:"publish",surface:"topics"}],["send",{kind:"enqueue",surface:"queues"}],["sendBatch",{kind:"enqueue",surface:"queues"}]]),Ii=(e,t)=>{const s=Is(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},Ti=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t))return;const s=t.getName(),[n,o]=e.getArguments();if(ds.has(s))return Ii(s,n);if((s==="runAfter"||s==="runAt")&&Pi(t)){const c=Is(o);return c===void 0?{kind:"schedule",reason:"the scheduled function is not a static api.* / internal.* chain"}:{kind:"schedule",target:c}}const r=wi.get(s),a=r===void 0?void 0:Ni(t,r.surface);return r===void 0||a===void 0?void 0:{kind:r.kind,target:a}},Ci=(e,t)=>{const s=[];for(const n of g(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=x(t,n);for(const a of o.getDescendantsOfKind(l.CallExpression)){const c=Ti(a);c!==void 0&&s.push({...c,exportName:Ne(a),file:r,line:a.getStartLineNumber()})}}return s},Fi=new Set(["createBrowser","createInboundEmailHandler","createPayment"]),Oi=new Set(["RateLimiter"]),Ri=new Set(["extend"]),$t="lunora",ki=["vite.config.ts","vite.config.mts","vite.config.js","vite.config.mjs"],Ts=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=y(o);t.push(r),o.getInitializer()?.getKind()===l.TrueKeyword&&s.push(r);continue}(i.isShorthandPropertyAssignment(o)||i.isMethodDeclaration(o))&&t.push(y(o))}return{analyzable:!n,presentKeys:t,trueKeys:s}},He=e=>e&&i.isObjectLiteralExpression(e)?Ts(e):{analyzable:!1,presentKeys:[],trueKeys:[]},Li=e=>{const t=e&&(i.isArrowFunction(e)||i.isFunctionExpression(e))?e:void 0,s=t&&us(t.getBody());return s?Ts(s):{analyzable:!1,presentKeys:[],trueKeys:[]}},Di=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression)){const o=b(n.getExpression());o!==void 0&&(Fi.has(o)?s.push({callee:o,file:t,line:n.getStartLineNumber(),...He(n.getArguments()[0])}):Ri.has(o)&&s.push({callee:o,file:t,line:n.getStartLineNumber(),...Li(n.getArguments()[0])}))}for(const n of e.getDescendantsOfKind(l.NewExpression)){const o=b(n.getExpression());o===void 0||!Oi.has(o)||s.push({callee:o,file:t,line:n.getStartLineNumber(),...He(n.getArguments()[0])})}return s},Mi=(e,t)=>{for(const s of ki){const n=S(t,s);if(!I(n))continue;const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=[];for(const a of o.getDescendantsOfKind(l.CallExpression))b(a.getExpression())===$t&&r.push({callee:$t,file:s,line:a.getStartLineNumber(),...He(a.getArguments()[0])});return r}return[]},Ki=(e,t)=>{const s=[];for(const{displayPath:n,filePath:o}of be(t)){const r=e.getSourceFile(o)??e.addSourceFileAtPath(o);s.push(...Di(r,n))}return s.push(...Mi(e,pe(t))),s},zt="ctx.containers.",_i=e=>{if(!e.startsWith(zt))return!1;const t=e.slice(zt.length);return t.length>0&&!t.includes(".")},$i=(e,t)=>we(e,t,{argIndex:0,matchReceiver:_i,methods:new Set(["get"])}),zi=new Set(["allow","deny","setAllowed"]),Ui=e=>{const t=e.getArguments()[0];if(!t||!i.isObjectLiteralExpression(t))return!1;const s=C(t,"enableInternet");return s!==void 0&&i.isPropertyAssignment(s)&&i.isTrueLiteral(s.getInitializerOrThrow())},Bi=(e,t)=>{const s=e.getExpression();if(!(!i.isPropertyAccessExpression(s)||s.getName()!=="start"||!Ui(e)))return{detail:"enableInternet: true",exportName:A(e),file:t,kind:"enable_internet",line:e.getStartLineNumber()}},qi=(e,t)=>{const s=e.getExpression();if(!i.isPropertyAccessExpression(s)||!zi.has(s.getName()))return;const n=s.getExpression();if(!(!i.isPropertyAccessExpression(n)||n.getName()!=="egress"))return{detail:s.getName(),exportName:A(e),file:t,kind:"egress_relaxation",line:e.getStartLineNumber()}},ji=(e,t)=>Bi(e,t)??qi(e,t),Wi=(e,t)=>F(e,t,ji),Vi=new Set(["defineExportSink","r2Sink","webhookExportSink"]),Hi=e=>{const t=e.getExpression();if(!i.isIdentifier(t))return;const s=t.getText();return Vi.has(s)?s:void 0},Gi=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=y(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(y(n))}return{analyzable:!0,emptyKeys:s,presentKeys:t}},Yi=(e,t)=>{const s=[];for(const{displayPath:n,filePath:o}of be(t)){const r=e.getSourceFile(o)??e.addSourceFileAtPath(o);for(const a of r.getDescendantsOfKind(l.CallExpression)){const c=Hi(a);if(c===void 0)continue;const u=a.getArguments()[0],d=u&&i.isObjectLiteralExpression(u)?Gi(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},Qi=new Map([["dbRateLimit",2],["rateLimit",2],["verifyTurnstileMiddleware",0]]),Xi=new Set(["dbRateLimit","rateLimit"]),Ji=e=>{const t=gs(e);if(!t)return!1;const s=C(t,"failOpen");return s!==void 0&&i.isPropertyAssignment(s)&&s.getInitializer()?.getKind()===l.TrueKeyword},Zi=(e,t)=>{const s=b(e.getExpression());if(s===void 0)return;const n=Qi.get(s);if(n!==void 0)return{callee:s,exportName:A(e),failOpen:Ji(e.getArguments()[n]),file:t,limitName:Xi.has(s)?ps(e):"",line:e.getStartLineNumber()}},ea=(e,t)=>F(e,t,Zi),ta=new Set(["boolean","number","object","string"]),sa=e=>{const t=e.getName();if(!ta.has(t))return;const s=e.getExpression();if(!i.isPropertyAccessExpression(s))return;if(s.getName()==="flags"&&je(s.getExpression()))return t;const n=s.getExpression();if(s.getName()==="details"&&i.isPropertyAccessExpression(n)&&n.getName()==="flags"&&je(n.getExpression()))return t},na=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t))return;const s=sa(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},ra=(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=na(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))},oa=e=>{const t=e.getInitializer();if(!t||!i.isCallExpression(t))return;const s=z(t);if(s?.kind!=="query")return;const n=Pn(t,s.receiver);return n?{exportName:e.getName(),handler:n}:void 0},Ut=e=>{const t=e.getParent();return t&&i.isPropertyAccessExpression(t)&&t.getExpression()===e?t:void 0},ia=e=>{if(!i.isPropertyAccessExpression(e)||e.getName()!=="flags")return;const t=e.getExpression();if(!i.isIdentifier(t)||t.getText()!=="ctx")return;const s=Ut(e);if(!s)return"ctx.flags";if(s.getName()==="details"){const n=Ut(s);return n?`ctx.flags.details.${n.getName()}`:"ctx.flags.details"}return`ctx.flags.${s.getName()}`},aa=(e,t)=>{const s=[];for(const n of e.handler.getDescendantsOfKind(l.PropertyAccessExpression)){const o=ia(n);o!==void 0&&s.push({callee:o,exportName:e.exportName,file:t,line:n.getStartLineNumber()})}return s},ca=(e,t)=>{const s=[];for(const n of e.getVariableStatements())if(n.isExported())for(const o of n.getDeclarations()){const r=oa(o);r&&s.push(...aa(r,t))}return s},la=(e,t)=>{const s=[];for(const n of g(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...ca(o,x(t,n)))}return s},ua=e=>{if(!i.isPropertyAccessExpression(e)||e.getName()!=="boolean")return!1;const t=e.getExpression();return i.isPropertyAccessExpression(t)&&t.getName()==="flags"&&je(t.getExpression())},da=e=>{if(e?.getKind()===l.TrueKeyword)return!0;if(e?.getKind()===l.FalseKeyword)return!1},fa=(e,t)=>{if(!ua(e.getExpression()))return;const[s,n]=e.getArguments();if(!s||!(i.isStringLiteral(s)||i.isNoSubstitutionTemplateLiteral(s)))return;const o=s.getLiteralValue(),r=da(n);if(!(o.length===0||r===void 0))return{defaultValue:r,exportName:A(e),file:t,key:o,line:e.getStartLineNumber()}},pa=(e,t)=>F(e,t,fa),ga=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"||$n(r))return;const a=e.getSourceFile().getFilePath();if(zn(o,e,a)){const c=Un(o,e,a,0,new Set);return c===void 0&&Bn(r),c}return r},ma=e=>{const t=e.getExpression();return i.isPropertyAccessExpression(t)&&t.getName()==="withGeoIndex"},ha=e=>{const t=e.getArguments()[0];return t&&i.isStringLiteral(t)?t.getLiteralText():""},va=(e,t)=>{const s=[];for(const n of g(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=x(t,n);for(const a of o.getDescendantsOfKind(l.CallExpression))ma(a)&&s.push({file:r,indexName:ha(a),line:a.getStartLineNumber()})}return s},se=e=>e!==void 0&&(i.isArrowFunction(e)||i.isFunctionExpression(e))?e:void 0,Cs=e=>{const t=e.getArguments()[0],s=se(t);if(s!==void 0)return s;if(t===void 0||!i.isObjectLiteralExpression(t))return;const n=C(t,"handler");return n!==void 0&&i.isPropertyAssignment(n)?se(n.getInitializer()):void 0},xa=new Set(["delete","get","head","options","patch","post","put"]),Ea=new Set(["handler","stream"]),Sa=new Set(["runAction","runMutation"]),ya=new Set(["delete","insert","insertManyUnsafe","patch","replace"]),ne=(e,t)=>e!==void 0&&i.isIdentifier(e)&&e.getText()===t,Fs=(e,t)=>{if(!(e===void 0||!i.isObjectBindingPattern(e))){for(const s of e.getElements())if(Q(s)===t){const o=s.getNameNode();return i.isIdentifier(o)?o.getText():void 0}}},Bt=(e,t)=>{const s=e.getParameters()[0]?.getNameNode();if(s!==void 0)return t?i.isIdentifier(s)?s.getText():void 0:Fs(s,"ctx")},qt=(e,t)=>{const s=e.getParameters()[t?1:0]?.getNameNode();return t?s!==void 0&&i.isIdentifier(s)?s.getText():void 0:Fs(s,"request")},jt=(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(Sa.has(a)&&ne(c,t))return a;if(ya.has(a)&&i.isPropertyAccessExpression(c)&&c.getName()==="db"&&ne(c.getExpression(),t))return`db.${a}`}},Wt=(e,t)=>{const s=e.getBody();for(const n of s.getDescendantsOfKind(l.PropertyAccessExpression))if(n.getName()==="auth"&&ne(n.getExpression(),t))return!0;for(const n of s.getDescendantsOfKind(l.VariableDeclaration)){const o=n.getNameNode();if(!(!i.isObjectBindingPattern(o)||!ne(n.getInitializer(),t))){for(const r of o.getElements())if(Q(r)==="auth")return!0}}return!1},Aa=/signature|hmac|digest|(?:^|[_-])sig(?:[_-]|$)/i,ba=(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"&&ne(n.getExpression(),t)},Na=e=>[...i.isStringLiteral(e)?[e.getLiteralText()]:[],...e.getDescendantsOfKind(l.StringLiteral).map(t=>t.getLiteralText())],Os=(e,t)=>{const s=e.getVariableDeclaration(t)?.getInitializer();return s===void 0?[]:Na(s)},Pa=(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)?Os(t,a.getText()):[]}return[]},wa=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=Os(s,t.getText());return n.length>0?n:Pa(t,s)},Vt=(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=>ba(o,t)&&wa(o).some(r=>Aa.test(r)))},Ia=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!Ea.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(xa.has(o)){const r=n.getExpression();return i.isIdentifier(r)&&r.getText()==="httpRoute"?o.toUpperCase():void 0}s=n.getExpression()}},Ta=(e,t)=>{const s=e.getExpression();if(i.isIdentifier(s)&&s.getText()==="httpAction"){const c=se(e.getArguments()[0]),u=c&&Bt(c,!0);if(!c||u===void 0||Vt(c,qt(c,!0)))return;const d=jt(c,u);return d===void 0?void 0:{exportName:A(e),file:t,kind:"httpAction",line:e.getStartLineNumber(),readsAuth:Wt(c,u),sideEffect:d}}const n=Ia(e);if(n===void 0)return;const o=se(e.getArguments()[0]),r=o&&Bt(o,!1);if(!o||r===void 0||Vt(o,qt(o,!1)))return;const a=jt(o,r);return a===void 0?void 0:{exportName:A(e),file:t,kind:"httpRoute",line:e.getStartLineNumber(),method:n,readsAuth:Wt(o,r),sideEffect:a}},Ca=(e,t)=>F(e,t,Ta),Fa=new Set(["btoa","encodeURI","encodeURIComponent","isSafeHeaderValue","Number","parseFloat","parseInt"]),Oa=new Set(["append","set"]),Rs=e=>e!==void 0&&(i.isStringLiteral(e)||i.isNoSubstitutionTemplateLiteral(e))?e.getLiteralText():"",Ht=(e,t)=>(i.isCallExpression(e)?[e,...e.getDescendantsOfKind(l.CallExpression)]:e.getDescendantsOfKind(l.CallExpression)).some(n=>Fa.has(b(n.getExpression())??"")&&me(n,t)),Ra=(e,t)=>{if(Ht(e,t))return!0;const s=K(e);return s!==void 0&&Ht(s,t)},Ge=(e,t)=>Mo(e,t)&&!Ra(e,t),ka=e=>{if(i.isPropertyAccessExpression(e)&&e.getName()==="headers")return!0;const t=K(e);return t!==void 0&&i.isNewExpression(t)&&b(t.getExpression())==="Headers"},xe=e=>{if(e===void 0)return;if(i.isObjectLiteralExpression(e))return e;const t=K(e);return t!==void 0&&i.isObjectLiteralExpression(t)?t:void 0},tt=(e,t,s)=>{for(const n of e.getProperties())if(i.isPropertyAssignment(n)){const o=n.getInitializer();o!==void 0&&Ge(o,s.requestName)&&s.rows.push({exportName:s.exportName,file:s.relativePath,headerName:Rs(n.getNameNode()),line:o.getStartLineNumber(),via:t})}else if(i.isShorthandPropertyAssignment(n)){const o=n.getNameNode();Ge(o,s.requestName)&&s.rows.push({exportName:s.exportName,file:s.relativePath,headerName:y(n),line:o.getStartLineNumber(),via:t})}else if(i.isSpreadAssignment(n)){const o=xe(n.getExpression());o!==void 0&&tt(o,t,s)}},ks=(e,t)=>{const s=xe(e);if(s===void 0)return;const n=C(s,"headers");if(n===void 0||!i.isPropertyAssignment(n))return;const o=xe(n.getInitializer());o!==void 0&&tt(o,"response-init",t)},La=(e,t)=>{const s=b(e.getExpression());if(s==="Response")ks(e.getArguments()[1],t);else if(s==="Headers"){const n=xe(e.getArguments()[0]);n!==void 0&&tt(n,"headers-ctor",t)}},Da=(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"){ks(e.getArguments()[1],t);return}if(Oa.has(n)&&ka(o)){const r=e.getArguments()[1];r!==void 0&&Ge(r,t.requestName)&&t.rows.push({exportName:t.exportName,file:t.relativePath,headerName:Rs(e.getArguments()[0]),line:r.getStartLineNumber(),via:n==="set"?"headers-set":"headers-append"})}},Ma=(e,t)=>{for(const s of e.getDescendantsOfKind(l.NewExpression))La(s,t);for(const s of e.getDescendantsOfKind(l.CallExpression))Da(s,t)},Ka=(e,t)=>{const s=e.getExpression();if(!i.isIdentifier(s)||s.getText()!=="httpAction")return[];const n=se(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 Ma(n,{exportName:A(e),relativePath:t,requestName:r.getText(),rows:a}),a},_a=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression))s.push(...Ka(n,t));return s},$a=(e,t)=>{const s=[];for(const n of g(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(..._a(o,x(t,n)))}return s},za=new Set(["auth","context.auth","ctx.auth"]),Ua="userId",Ba=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(y(s))}return t},qa=(e,t)=>{const s=S(t,bs);if(!I(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const o of n.getDescendantsOfKind(l.CallExpression)){if(b(o.getExpression())!=="defineIdentity")continue;const[r]=o.getArguments();return r&&i.isObjectLiteralExpression(r)?Ba(r):void 0}},Gt=e=>{if(!(e===void 0||!i.isPropertyAccessExpression(e)||e.getName()!=="identity"))return za.has(e.getExpression().getText())?e:void 0},ja=e=>{if(i.isPropertyAccessExpression(e)&&Gt(e.getExpression())!==void 0)return e.getName();if(i.isElementAccessExpression(e)&&Gt(e.getExpression())!==void 0){const t=e.getArgumentExpression();return t&&i.isStringLiteral(t)?t.getLiteralValue():void 0}},Wa=(e,t,s)=>{const n=[];for(const o of e.getDescendants()){const r=ja(o);r!==void 0&&n.push({declared:r===Ua||s.has(r),exportName:A(o),file:t,key:r,line:o.getStartLineNumber()})}return n},Va=(e,t)=>{const s=qa(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(...Wa(r,x(t,o),s))}return n},Ha=(e,t)=>{if(b(e.getExpression())!=="buildImageDeliveryUrl")return;const s=e.getArguments()[0];if(!s)return;const n=P(s,"key");if(!(!n||!_(n)||q(n)))return{exportName:A(e),file:t,line:e.getStartLineNumber()}},Ga=(e,t)=>F(e,t,Ha),Ya=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()},Qa=e=>e.getProperties().some(t=>{if(i.isSpreadAssignment(t))return!0;const s=Ya(t.getNameNode());return s===void 0||s==="namespace"}),Xa=(e,t)=>{for(const{filePath:s}of be(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)||Qa(a)))return o}}},Ja="https://lunora.sh/docs/concepts/data-residency#pinning-auth-and-voice",Za=(e,t)=>{if(!(e.jurisdiction===void 0||e.jurisdictionPinsAuth===!0||t===void 0))throw re(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 (${Ja}). 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})},ec=new Set(["delete","get","getRaw","getWithMetadata","put"]),tc=(e,t,s=[])=>{const n=new Map(s.map(r=>[`${r.filePath}:${r.exportName}`,r.visibility]));return we(e,t,{argIndex:0,matchReceiver:r=>r==="ctx.kv"||r.startsWith("ctx.kv."),methods:ec}).map(r=>{const a=n.get(`${r.file}:${r.exportName}`);return a===void 0?r:{...r,visibility:a}})},sc=new Set(["queue","send"]),Yt=new Set(["bcc","cc","to"]),nc=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName();if(!sc.has(t))return;const s=e.getExpression().getText();return s==="ctx.mail"||s==="ctx.email"?t:void 0},rc=e=>i.isObjectLiteralExpression(e)?e.getProperties().some(t=>{if(i.isShorthandPropertyAssignment(t)){const n=t.getNameNode();return Yt.has(y(t))&&_(n)&&!q(n)}if(!i.isPropertyAssignment(t)||!Yt.has(y(t)))return!1;const s=t.getInitializer();return s!==void 0&&_(s)&&!q(s)}):!1,oc=(e,t)=>{const s=nc(e.getExpression());if(s===void 0)return;const n=e.getArguments()[0];if(!(!n||!rc(n)))return{exportName:A(e),file:t,line:e.getStartLineNumber(),method:s}},ic=(e,t)=>F(e,t,oc),ac=e=>i.isPropertyAssignment(e)||i.isMethodDeclaration(e)||i.isGetAccessorDeclaration(e)?i.isComputedPropertyName(e.getNameNode()):!1,cc=e=>i.isPropertyAssignment(e)||i.isShorthandPropertyAssignment(e)||i.isMethodDeclaration(e)||i.isGetAccessorDeclaration(e)?ac(e):!0,Ls=(e,t=!1)=>{for(const s of e.getProperties()){if(cc(s))return!0;if(t)continue;if(!i.isPropertyAssignment(s))return!0;const n=s.getInitializer();if(!n||!i.isObjectLiteralExpression(n)||Ls(n,!0))return!0}return!1},lc=(e,t)=>{for(const s of g(t)){const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const{receiver:o}of Ss(n))for(const r of Xe(o)){const a=r.getArguments()[0];if(a!==void 0&&(!i.isObjectLiteralExpression(a)||Ls(a)))return!0}}return!1},uc=e=>{const t=e.getArguments()[0];if(!t||!i.isObjectLiteralExpression(t))return[];const s=[];for(const n of t.getProperties()){const o=ve(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=ve(a);c!==void 0&&s.push({column:c,strategy:Es(a),table:o})}}return s},dc=(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 Ss(o))for(const a of Xe(r))for(const c of uc(a)){const u=`${c.table}\0${c.column}`;s.has(u)||s.set(u,c)}}return{columns:[...s.values()]}},fc=(e,t,s)=>{const n=e.getArguments()[0];if(!n||!i.isObjectLiteralExpression(n))return[];const o=[];for(const r of n.getProperties()){const a=ve(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=ve(u);if(d===void 0)continue;const p=Es(u);p!=="custom"&&o.push({column:d,exportName:t,file:s,line:u.getStartLineNumber(),strategy:p,table:a})}}return o},pc=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&i.isCallExpression(s)?z(s):void 0;return n?.receiver?Xe(n.receiver).flatMap(o=>fc(o,e.getName(),t)):[]},gc=(e,t)=>{const s=[];for(const n of g(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=x(t,n);for(const a of o.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...pc(c,r))}return s},mc=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="replace")return!1;const s=t.getExpression();return M(s)},hc=e=>{const t=e.getArguments()[0];if(t===void 0||!i.isObjectLiteralExpression(t))return;const s=C(t,"server");if(s!==void 0)return i.isPropertyAssignment(s)?s.getInitializer():s},vc=e=>{if(!e.isExported())return;const t=e.getInitializer();if(t?.getKind()!==l.CallExpression)return;const s=t;return Jn(s.getExpression())?s:void 0},xc=e=>{const t=vc(e),s=t===void 0?void 0:hc(t);if(s===void 0)return[];const n=e.getNameNode(),o=i.isIdentifier(n)?n.getText():"";return s.getDescendantsOfKind(l.CallExpression).filter(r=>mc(r)).map(r=>({exportName:o,file:"lunora/mutators.ts",line:r.getStartLineNumber()}))},Ec=e=>e.getVariableDeclarations().flatMap(t=>xc(t)),Sc=(e,t)=>{const s=S(t,Xn);if(!I(s))return[];const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);return Ec(n)},yc=new Set(["delete","get","patch"]),Ac=new Set(["accountId","authorId","companyId","createdBy","createdById","customerId","groupId","memberId","organizationId","orgId","ownerId","projectId","teamId","tenantId","userId","workspaceId"]),bc=new Set(["auth","identity","session","user"]),Nc=new Set([l.EqualsEqualsEqualsToken,l.EqualsEqualsToken,l.ExclamationEqualsEqualsToken,l.ExclamationEqualsToken]),Pc=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():""},wc=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},Ic=(e,t)=>e.getDescendantsOfKind(l.Identifier).some(s=>s.getText()===t),Tc=e=>i.isThrowStatement(e)||i.isReturnStatement(e)||e.getDescendantsOfKind(l.ThrowStatement).length>0||e.getDescendantsOfKind(l.ReturnStatement).length>0,Cc=(e,t)=>e.getDescendantsOfKind(l.IfStatement).some(s=>Ic(s.getExpression(),t)&&Tc(s.getThenStatement())),Fc=(e,t)=>{for(const s of e.getDescendantsOfKind(l.CallExpression)){const n=s.getExpression();if(!i.isPropertyAccessExpression(n))continue;const o=n.getName();if(!yc.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}},Oc=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},Rc=e=>e.getDescendantsOfKind(l.CallExpression).some(t=>t.getArguments().some(s=>Oc(s)==="ctx")),kc=e=>e.getDescendantsOfKind(l.BinaryExpression).some(t=>Nc.has(t.getOperatorToken().getKind())?i.isPropertyAccessExpression(t.getLeft())||i.isPropertyAccessExpression(t.getRight()):!1),Lc=e=>{for(const t of e.getDescendantsOfKind(l.Identifier))if(Ac.has(t.getText()))return!0;for(const t of e.getDescendantsOfKind(l.PropertyAccessExpression)){const s=t.getExpression();if(i.isIdentifier(s)&&s.getText()==="ctx"&&bc.has(t.getName()))return!0}return Rc(e)||kc(e)},Dc=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!i.isCallExpression(s))return[];const n=z(s);if(n?.kind!=="query"&&n?.kind!=="mutation")return[];const o=Cs(s);if(o===void 0)return[];const r=n.receiver!==void 0&&hs(n.receiver,"use","rls"),a=Lc(o),c=new Set,u=[];for(const d of o.getDescendantsOfKind(l.CallExpression)){const p=Pc(d);if(p===void 0)continue;const h=wc(d);if(h===void 0||c.has(h)||!Cc(o,h))continue;const R=Fc(o,h);R!==void 0&&(c.add(h),u.push({exportName:e.getName(),file:t,line:d.getStartLineNumber(),mentionsOwnership:a,sinkMethod:R,table:p,usesRls:r,visibility:n.visibility}))}return u},Mc=(e,t)=>{const s=[];for(const n of g(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=x(t,n);for(const a of o.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...Dc(c,r))}return s},Kc=new Set(["accountId","authorId","createdBy","createdById","organizationId","orgId","ownerId","tenantId","updatedBy","userId","workspaceId"]),_c=new Set(["insert","insertManyUnsafe","patch","replace"]),$c=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName();if(!_c.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},zc=(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},Qt=(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},Uc=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()!==ln.Const)continue;const u=a.getInitializer(),d=a.getStart();u!==void 0&&d<n&&d>r&&(o=u,r=d)}return o},Bc=(e,t)=>{if(Qt(e,t))return!0;const s=Uc(e);return s!==void 0&&Qt(s,t)},qc=(e,t,s,n,o)=>{const r=[];for(const a of e.getProperties()){let c,u;if(i.isPropertyAssignment(a)?(c=y(a),u=a.getInitializer()):i.isShorthandPropertyAssignment(a)&&(c=y(a),u=a.getNameNode()),!(c===void 0||u===void 0||!Kc.has(c))&&_(u)&&!q(u)){const d=A(s),p=o(d)===c&&Bc(u,c);r.push({exportName:d,field:c,file:n,line:s.getStartLineNumber(),method:t,...p&&{ownerScoped:!0}})}}return r},jc=(e,t,s)=>{const n=$c(e.getExpression());if(n===void 0)return[];const o=e.getArguments()[1];return o?zc(o,n).flatMap(r=>qc(r,n,e,t,s)):[]},Wc=(e,t,s)=>{const n=[];for(const o of e.getDescendantsOfKind(l.CallExpression))for(const r of jc(o,t,a=>s(a).owner)){const{visibility:a}=s(r.exportName);n.push(a===void 0?r:{...r,visibility:a})}return n},Vc=(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=x(t,a);o.push(...Wc(c,u,d=>r.get(`${u}:${d}`)??{}))}return o},Hc=["providerSubscriptionId","state"],Gc=["providerEventId","processedAt"],Xt=(e,t)=>t.every(s=>s in e.shape),Yc=e=>{const t=e.find(n=>n.name==="subscriptions"),s=e.find(n=>n.name==="events");return t!==void 0&&s!==void 0&&Xt(t,Hc)&&Xt(s,Gc)},Qc=new Set(["createAutumnAdapter","createDodoPaymentsAdapter","createPolarAdapter","createStripeAdapter"]),Xc=e=>e&&i.isNumericLiteral(e)?Number(e.getText()):void 0,Jc=e=>{const t=C(e,"webhookToleranceSeconds");return t&&i.isPropertyAssignment(t)?Xc(t.getInitializer()):void 0},Zc=(e,t)=>{const s=b(e.getExpression());if(s===void 0||!Qc.has(s))return;const[n]=e.getArguments(),o=n&&i.isObjectLiteralExpression(n)?Jc(n):void 0;return{callee:s,exportName:A(e),file:t,line:e.getStartLineNumber(),...o===void 0?{}:{toleranceSeconds:o}}},el=(e,t)=>F(e,t,Zc),tl=new Map([["defineQueue",0],["defineSubscription",1],["defineWorkflow",0]]),sl=e=>{const t=e.getExpression();return i.isIdentifier(t)?t.getText():void 0},nl=(e,t)=>{const s=e.getArguments()[t];if(!s||!i.isObjectLiteralExpression(s))return;const n=C(s,"handler");if(n===void 0||!i.isPropertyAssignment(n))return;const o=n.getInitializer();if(o&&(i.isArrowFunction(o)||i.isFunctionExpression(o)))return o},Ds=(e,t)=>{const s=e.getParameters()[t]?.getNameNode();return s&&i.isIdentifier(s)?s.getText():void 0},Ms=(e,t)=>e===t||e.startsWith(`${t}.`),Ks=e=>{const t=e.getDescendantsOfKind(l.PropertyAccessExpression);return i.isPropertyAccessExpression(e)&&t.push(e),t},Jt=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)},_s=e=>{const t=e.getDescendantsOfKind(l.Identifier).filter(s=>Jt(s));return i.isIdentifier(e)&&Jt(e)&&t.push(e),t},rl=e=>{if(!i.isVariableDeclaration(e))return[];const t=e.getNameNode();return i.isIdentifier(t)?[t.getText()]:t.getDescendantsOfKind(l.BindingElement).map(s=>s.getName())},ol=e=>{const t=Ds(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},il=(e,t,s)=>{const n=t==="workflow"?[`${s}.params`]:ol(e),o=new Set,r=a=>Ks(a).some(c=>n.some(u=>Ms(c.getText(),u)))?!0:_s(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 rl(a))o.add(u)}return{names:o,prefixes:n}},al=(e,t)=>Ks(e).some(s=>t.prefixes.some(n=>Ms(s.getText(),n)))?!0:_s(e).some(s=>t.names.has(s.getText())),cl=e=>{const t=fs(e);return t===void 0?void 0:{exportName:String(t.at(-1)),file:t.slice(0,-1).join("/")}},ll=(e,t,s)=>{const n=Ds(e,0);if(n===void 0)return[];const o=il(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)||!ds.has(u.getName())||!r.has(u.getExpression().getText()))continue;const d=c.getArguments()[1];if(!d||!al(d,o))continue;const p=cl(c.getArguments()[0]);p!==void 0&&a.push({dispatchKind:t,file:s,handlerExport:A(c),line:c.getStartLineNumber(),targetExport:p.exportName,targetFile:p.file})}return a},ul=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression)){const o=sl(n),r=o===void 0?void 0:tl.get(o);if(r===void 0)continue;const a=nl(n,r);a!==void 0&&s.push(...ll(a,o==="defineWorkflow"?"workflow":"queue",t))}return s},dl=(e,t)=>{const s=[];for(const n of g(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...ul(o,x(t,n)))}return s},Zt={dbRateLimit:"usesRateLimit",emailGateMiddleware:"usesEmailGate",mask:"usesMask",rateLimit:"usesRateLimit",rls:"usesRls",verifyTurnstileMiddleware:"usesCaptcha"},es=new Set(["account","credential","member","passkey","session","user"]),fl=e=>e.replaceAll(/[-_]/gu," ").replaceAll(/([a-z0-9])([A-Z])/gu,"$1 $2").split(" ").filter(Boolean).map(t=>t.toLowerCase()),pl=e=>{const s=fl(e).at(-1);if(!s)return!1;const n=s.endsWith("s")?s.slice(0,-1):s;return es.has(s)||es.has(n)},gl=e=>{const t=e.replaceAll(/[^a-z0-9]/giu,"").toLowerCase();return t.endsWith("email")||t.endsWith("emailaddress")},ml=(e,t)=>{const{objects:s,opaque:n}=et(e,t);return ti(s).some(o=>gl(o))?!0:n?void 0:!1},hl=e=>{const t=e.getArguments()[0];return!t||!i.isObjectLiteralExpression(t)?{usesCaptcha:!1,usesRateLimit:!1}:{usesCaptcha:!!C(t,"captcha"),usesRateLimit:!!C(t,"rateLimit")}},vl=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},he={usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},xl=e=>{const t=vl(e),s=t?b(t.getExpression()):void 0;if(t&&s==="protectPublic"){const n=hl(t);return{...he,usesCaptcha:n.usesCaptcha,usesRateLimit:n.usesRateLimit}}return s!==void 0&&s in Zt?{...he,[Zt[s]]:!0}:he},El=e=>{const t={...he};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=xl(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},Sl=new Set(["insert","insertMany","insertManyUnsafe","replace"]),yl=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!Sl.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:pl(o.getLiteralText())},Al=new Set(["create","publish","publishBatch","runAfter","runAt","send","sendBatch"]),bl=new Set(["queues","scheduler","topics","workflows"]),Nl=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!Al.has(t.getName()))return!1;let s=t.getExpression();for(;i.isCallExpression(s)||i.isElementAccessExpression(s)||i.isPropertyAccessExpression(s);){if(i.isPropertyAccessExpression(s)&&bl.has(s.getName())){const n=s.getExpression();if(i.isIdentifier(n)&&n.getText()==="ctx")return!0}s=s.getExpression()}return!1},Pl=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="insertManyUnsafe")return!1;const s=t.getExpression();return M(s)},$s=new Set(["generateObject","generateText","streamObject","streamText"]),wl=e=>{const t=b(e.getExpression());return t!==void 0&&$s.has(t)},Il=e=>{const t=b(e.getExpression());if(t===void 0||!$s.has(t))return!1;const s=e.getArguments()[0];return!s||!i.isObjectLiteralExpression(s)||s.getProperties().some(n=>i.isSpreadAssignment(n))?!1:!C(s,"maxOutputTokens")},Tl=new Set(["log","span","trace"]),Cl=new Set(["ai"]),Fl=new Set(["email","mail"]),Ol=new Set(["ai","browser","fetch","mail","notify","queues","sql","storage","topics","workflows"]),Be=(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"}),Rl=new Set([l.ArrowFunction,l.FunctionDeclaration,l.FunctionExpression,l.GetAccessor,l.MethodDeclaration,l.SetAccessor]),kl=new Set(["every","filter","flatMap","forEach","map","some"]),Ll=new Set(["all","allSettled","race"]),Dl=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(kl.has(n))return t;const o=s.getExpression();if(i.isIdentifier(o)&&o.getText()==="Promise"&&Ll.has(n))return t},Ml=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(Rl.has(t.getKind())){const s=Dl(t);if(!s)return!1;t=s;continue}t=t.getParent()}return!1},Kl=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}},_l=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}},$l=e=>{let t=!1,s=!0;for(const n of e.getDescendantsOfKind(l.PropertyAccessExpression)){if(!Ol.has(n.getName()))continue;const o=n.getExpression();if(!i.isIdentifier(o)||o.getText()!=="ctx")continue;const r=_l(n);r&&(t=!0,!Ml(r)&&!Kl(r)&&(s=!1))}return{handlesErrors:t&&s,reachesOutbound:t}},zl=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"}),ts="lunora-advisor-exempt",Ul=/^[\s*/]+/u,Bl=/[\w-]/u,ql=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(Ul,"");if(!o.startsWith(ts))continue;const r=o.slice(ts.length);if(Bl.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:""}},jl=e=>{const[t]=e.getArguments();if(t){if(i.isObjectLiteralExpression(t)){const s=C(t,"handler");return s?i.isPropertyAssignment(s)?s.getInitializer():i.isShorthandPropertyAssignment(s)?s.getNameNode():i.isMethodDeclaration(s)?s:void 0:void 0}return t}},Wl=(e,t)=>{const s=jl(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)},Vl=e=>{let t=!1,s=!1,n=!1,o=!1,r=!1;for(const u of e.getDescendantsOfKind(l.CallExpression))if(yl(u)&&(r=!0),Nl(u)&&(t=!0),Pl(u)&&(o=!0),wl(u)&&(s=!0),Il(u)&&(n=!0),r&&t&&o&&n)break;const{handlesErrors:a,reachesOutbound:c}=$l(e);return{callsMail:Be(e,Fl),emitsEvent:Be(e,Tl),fanOut:t,handlesErrors:a,reachesOutbound:c,runsAiGeneration:s||Be(e,Cl),throwsBareError:zl(e),unboundedAiGeneration:n,usesInsertManyUnsafe:o,writesUserTable:r}},Hl=(e,t)=>{const s=e.getInitializer();if(!s||!i.isCallExpression(s))return;const n=z(s);if(!n||n.kind!=="query"&&n.kind!=="mutation"&&n.kind!=="action")return;const o=n.receiver?El(n.receiver):{usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},r=Wl(e,s);return{...r?Vl(r):{},...ql(e),...o,analyzableBody:r!==void 0,exportName:e.getName(),file:t,hasEmailArg:ml(s,n.receiver),kind:n.kind,visibility:n.visibility}},Gl=(e,t)=>{const s=[];for(const n of e.getVariableStatements())if(n.isExported())for(const o of n.getDeclarations()){const r=Hl(o,t);r&&s.push(r)}return s},Yl=(e,t)=>{const s=[];for(const n of g(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Gl(o,x(t,n)))}return s},Ql=new Set(["dbRateLimit","rateLimit"]),Xl=e=>i.isArrowFunction(e)?e.getBody():e,Jl=e=>{if(!i.isArrowFunction(e))return;const t=e.getParameters()[0]?.getNameNode();return t!==void 0&&i.isIdentifier(t)?t:void 0},zs=e=>{const t=e.getParent();return i.isPropertyAccessExpression(t)&&t.getExpression()===e&&t.getName()==="args"},Us=(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)})},Zl=(e,t)=>_(e)||t!==void 0&&Us(e,t).some(s=>zs(s)),eu=(e,t)=>t===void 0?q(e):Us(e,t).some(s=>!zs(s)),tu=(e,t)=>{const s=b(e.getExpression());if(s===void 0||!Ql.has(s))return;const n=P(gs(e.getArguments()[2]),"key");if(!n)return;const o=Xl(n),r=Jl(n);if(!(!Zl(o,r)||eu(o,r)))return{callee:s,exportName:A(e),file:t,limitName:ps(e),line:e.getStartLineNumber()}},su=(e,t)=>F(e,t,tu),nu=new Set(["findFirst","findFirstOrThrow","findMany","findUnique","get"]),ru=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!nu.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()},ou=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()}},iu=e=>{let t=te(e)??e;for(;i.isAwaitExpression(t);)t=te(t.getExpression())??t.getExpression();return t},Bs=(e,t=!1)=>{const s=iu(e);if(i.isIdentifier(s)){if(t)return;const n=K(s);return n===void 0?void 0:Bs(n,!0)}if(i.isCallExpression(s))return ru(s)??ou(s)},au=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},cu=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!i.isCallExpression(s))return[];const n=z(s);if(n?.kind!=="query")return[];const o=Cs(s);if(o===void 0)return[];const r=n.receiver!==void 0&&Cn(n.receiver,"output"),a=n.receiver!==void 0&&hs(n.receiver,"use","mask"),c=new Set,u=[];for(const d of au(o)){const p=Bs(d);p===void 0||c.has(p)||(c.add(p),u.push({exportName:e.getName(),file:t,line:d.getStartLineNumber(),table:p,usesMask:a,usesOutput:r,visibility:n.visibility}))}return u},lu=(e,t)=>{const s=[];for(const n of g(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=x(t,n);for(const a of o.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...cu(c,r))}return s},uu=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(y(s));return t},du=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&i.isCallExpression(s)?z(s):void 0;if(!n)return[];const o=[];for(const r of e.getDescendantsOfKind(l.CallExpression)){const a=ms(r);if(a===void 0)continue;const c=uu(P(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},fu=(e,t)=>{const s=[];for(const n of g(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=x(t,n);for(const a of o.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...du(c,r))}return s},Ee=e=>{if(i.isStringLiteral(e)||i.isNoSubstitutionTemplateLiteral(e))return e.getLiteralText();if(i.isBinaryExpression(e)&&e.getOperatorToken().getKind()===l.PlusToken){const t=Ee(e.getLeft()),s=Ee(e.getRight());return t!==void 0&&s!==void 0?t+s:void 0}},pu=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&&Ee(t)!==void 0},gu=/(?:^|\/)__tests__\//u,mu=/\.(?:spec|test)$/u,hu=e=>gu.test(e)||mu.test(e),vu=e=>{const t=e.getParent();if(t!==void 0){if(i.isVariableDeclaration(t)||i.isPropertyAssignment(t)||i.isPropertySignature(t))return y(t);if(i.isBinaryExpression(t)&&t.getOperatorToken().getKind()===l.EqualsToken)return t.getLeft().getText()}},xu=(e,t,s)=>ur(e)?!hu(s)&&dr(vu(t)):!0,Eu=(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(pu(r))continue;const a=Ee(r);if(a===void 0)continue;const c=cr(a);if(c===void 0||!xu(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:lr(a)}))}return s},Su=(e,t)=>{const s=[];for(const n of g(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Eu(o,x(t,n)))}return s},yu=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&i.isCallExpression(s)?z(s):void 0;if(!n)return[];const o=[];for(const r of e.getDescendantsOfKind(l.CallExpression)){const a=ms(r);if(a===void 0)continue;const c=P(a.options,"includeDeleted");if(c===void 0)continue;const u=i.isTrueLiteral(c),d=!u&&_(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},Au=(e,t)=>{const s=[];for(const n of g(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=x(t,n);for(const a of o.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...yu(c,r))}return s},bu=new Set(["query","unsafe"]),Nu=e=>{if(!i.isPropertyAccessExpression(e)||!bu.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"},Pu=e=>i.isBinaryExpression(e)||i.isTemplateExpression(e),wu=e=>e.getFirstAncestorByKind(l.VariableDeclaration)?.getName()??"<module>",Iu=(e,t)=>{if(!Nu(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!Pu(s)))return{exportName:wu(e),file:t,line:s.getStartLineNumber()}},Tu=(e,t)=>F(e,t,Iu),Cu=[["convex",["convex","@convex-dev/"]],["supabase",["@supabase/"]],["firebase",["firebase","@firebase/","firebase-admin"]]],Fu=e=>{for(const[t,s]of Cu)for(const n of s)if(e===n||e.startsWith(n.endsWith("/")?n:`${n}/`))return t},Ou=(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=Fu(a);c!==void 0&&s.push({file:x(t,n),line:r.getStartLineNumber(),moduleSpecifier:a,platform:c})}}return s},Ru=new Set(["createMultipartUpload","delete","download","generateUploadUrl","get","getMetadata","getPresignedUrl","getSignedUrl","getUrl","head","put","resumeMultipartUpload","store","upload"]),ku=(e,t,s=[])=>{const n=new Map(s.map(r=>[`${r.filePath}:${r.exportName}`,r.visibility]));return we(e,t,{argIndex:0,matchReceiver:r=>r==="ctx.storage"||r.startsWith("ctx.storage."),methods:Ru,requireUnmodifiedReach:!0}).map(r=>{const a=n.get(`${r.file}:${r.exportName}`);return a===void 0?r:{...r,visibility:a}})},Lu=new Map([["generateUploadUrl",1],["getPresignedUrl",1],["getSignedUrl",1],["store",2],["upload",2]]),Du=e=>e&&i.isNumericLiteral(e)?Number(e.getText()):void 0,Mu=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=y(o);t.push(r),r==="expiresInSeconds"&&(s=Du(o.getInitializer()));continue}(i.isShorthandPropertyAssignment(o)||i.isMethodDeclaration(o))&&t.push(y(o))}return{analyzable:!n,expiresInSeconds:s,presentKeys:t}},Ku=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName(),s=Lu.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},_u=(e,t)=>{const s=Ku(e.getExpression());if(s!==void 0)return{exportName:A(e),file:t,line:e.getStartLineNumber(),method:s.method,...Mu(e.getArguments()[s.optionsIndex])}},$u=(e,t)=>F(e,t,_u),zu=(e,t)=>{const s=kn(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")}},Uu=new Set(["delete","hardDelete","patch","replace","restore"]),Bu=new Set(["insertMany","insertManyUnsafe","patchWhere"]),qu=new Set(["delete","deleteMany","hardDelete","insert","insertMany","patch","patchMany","replace","restore","upsert","upsertMany"]),ss=(e,t)=>{const n=e.getProperty("__table")?.getTypeAtLocation(t)?.getLiteralValue();return typeof n=="string"?n:""},ju=(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?"":ss(o,e)}return ss(s,e)},Wu=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t))return;const s=t.getName(),n=t.getExpression(),[o]=e.getArguments();if(M(n))return Bu.has(s)?{method:s,table:o!==void 0&&i.isStringLiteral(o)?o.getLiteralText():""}:Uu.has(s)||s==="deleteMany"||s==="patchMany"?{method:s,table:o===void 0?"":ju(o,s)}:void 0;if(qu.has(s)&&i.isPropertyAccessExpression(n)&&M(n.getExpression()))return{method:s,table:n.getName()}},Vu=(e,t)=>{const s=[];for(const n of g(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=x(t,n);for(const a of o.getDescendantsOfKind(l.CallExpression)){const c=Wu(a),u=c===void 0?"":Ne(a);c!==void 0&&u!==""&&s.push({exportName:u,file:r,line:a.getStartLineNumber(),method:c.method,table:c.table})}}return s},Hu=(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"}),Gu=(e,t)=>{if(t===void 0){const s=e.getArguments()[0];if(s===void 0||!i.isObjectLiteralExpression(s)||C(s,"args")===void 0)return!1}return et(e,t).opaque},Yu=(e,t)=>{const s=[],n=(o,r)=>{const a=o.getInitializer();if(a===void 0||!i.isCallExpression(a))return;const c=z(a);c!==void 0&&Gu(a,c.receiver)&&s.push(Hu(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},Qu=(e,t)=>{const s=[];for(const n of g(t)){const o=e.getSourceFile(n);o!==void 0&&s.push(...Yu(o,x(t,n)))}return s.toSorted((n,o)=>n.cacheKey.localeCompare(o.cacheKey))},Xu=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"}]]),Ie=({byName:e,byPath:t},s,n)=>t.has(`${s}:${n}`)||e.has(n),qs=e=>!e.isAny(),st=e=>{const t=e.getType();if(!qs(t))return;const s=t.getAliasSymbol()?.getName()??t.getSymbol()?.getName(),n=s===void 0?void 0:Xu.get(s);return n===void 0||s===void 0?void 0:{...n,typeName:s}},js=e=>{const t=e.getInitializer();return t===void 0?!1:i.isCallExpression(t)||i.isIdentifier(t)||i.isPropertyAccessExpression(t)},Ws={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."},Ju=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.`}),Zu={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."},nt=(e,t,s,n,o)=>{const{call:r,file:a,note:c,typeName:u}=s,d=a!==void 0&&e!==a?a:void 0,p=d===void 0?o:Ju(d),h=c===void 0?p.remediation:`${c} ${p.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 — ${p.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"}},ed=(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(Ie(s,t,a)||!js(r))continue;const c=st(r);c!==void 0&&n.push(nt(t,a,c,r.getStartLineNumber(),Ws))}return n},td=(e,t,s)=>{if(Ie(s,t,"default"))return[];const n=[];for(const o of e.getExportAssignments().filter(r=>!r.isExportEquals())){const r=st(o.getExpression());r!==void 0&&n.push(nt(t,"default",r,o.getStartLineNumber(),Ws))}return n},sd=(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(Ie(s,t,a))continue;const c=r.getLocalTargetDeclarations().find(d=>i.isVariableDeclaration(d));if(c===void 0||!js(c))continue;const u=st(c);u!==void 0&&n.push(nt(t,a,u,r.getStartLineNumber(),Zu))}return n},nd=(e,t,s)=>[...ed(e,t,s),...td(e,t,s),...sd(e,t,s)],rd=(e,t,s)=>e.getVariableStatements().filter(n=>n.isExported()).flatMap(n=>n.getDeclarations()).filter(n=>Ie(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})),od=({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"}),id=(e,t,s)=>{const n=[],o=[];for(const a of g(t)){const c=e.getSourceFile(a);if(c===void 0)continue;const u=x(t,a);n.push(...nd(c,u,s)),o.push(...rd(c,u,s))}const[r]=o;return r!==void 0&&o.every(({declaration:a})=>!qs(a.getType()))&&n.push(od(r)),n.toSorted((a,c)=>a.cacheKey.localeCompare(c.cacheKey))},ad=new Set(["when","where"]),qe=new Set(["definePolicy","defineShape"]),cd=e=>{if(!i.isCallExpression(e))return;const t=e.getExpression();if(i.isPropertyAccessExpression(t)){const n=t.getName();return qe.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 qe.has(o)?o:void 0}const s=t.getText();return qe.has(s)?s:void 0},ld=e=>i.isObjectLiteralExpression(e)&&e.getProperties().length===0,Vs=e=>{if(e!==void 0){if(i.isReturnStatement(e)&&e.getExpression()===void 0||e.getKind()===l.UndefinedKeyword||e.getText()==="undefined")return"undefined";if(ld(e))return"empty-object";if(i.isParenthesizedExpression(e))return Vs(e.getExpression())}},rt=e=>e.getAncestors().find(t=>i.isArrowFunction(t)||i.isFunctionExpression(t)||i.isFunctionDeclaration(t)),ud=e=>e.getDescendantsOfKind(l.ReturnStatement).filter(t=>rt(t)===e),Hs=e=>e.getDescendantsOfKind(l.ConditionalExpression).filter(t=>rt(t)===e),dd=e=>{const t=ud(e);return t.length>1?!0:t.some(s=>s.getFirstAncestorByKind(l.IfStatement)!==void 0)||Hs(e).length>0},fd=e=>e.getDescendantsOfKind(l.IfStatement).filter(t=>rt(t)===e),Ye=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()==="",pd=(e,t)=>Ye(e)||Ye(t),gd=new Map([[l.EqualsEqualsEqualsToken,"positive"],[l.EqualsEqualsToken,"positive"],[l.ExclamationEqualsEqualsToken,"negative"],[l.ExclamationEqualsToken,"negative"]]),ns=e=>!Ye(e)&&(i.isLiteralExpression(e)||e.getKind()===l.TrueKeyword),md=(e,t,s)=>{const n=gd.get(e);if(n!==void 0)return pd(t,s)?n==="positive"?"negative":"positive":ns(t)||ns(s)?void 0:n},ee=e=>{if(i.isParenthesizedExpression(e))return ee(e.getExpression());if(i.isPrefixUnaryExpression(e)&&e.getOperatorToken()===l.ExclamationToken)return"negative";if(i.isBinaryExpression(e)){const t=e.getOperatorToken().getKind(),s=md(t,e.getLeft(),e.getRight());if(s!==void 0)return s;if(t===l.AmpersandAmpersandToken||t===l.BarBarToken){const n=ee(e.getLeft()),o=ee(e.getRight());return n===o?n:"indeterminate"}}return i.isIdentifier(e)||i.isPropertyAccessExpression(e)||i.isElementAccessExpression(e)||i.isCallExpression(e)?"positive":"indeterminate"},rs=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}}},hd=e=>{if(e.getElseStatement()!==void 0)return;const t=e.getNextSiblingIfKind(l.ReturnStatement);return t!==void 0&&t.getNextSibling()===void 0?t:void 0},vd=e=>i.isReturnStatement(e)?e.getExpression()??e:e,xd=e=>{const t=[];for(const s of Hs(e)){const n=ee(s.getCondition());n==="positive"?t.push(s.getWhenFalse()):n==="negative"&&t.push(s.getWhenTrue())}for(const s of fd(e)){const n=ee(s.getExpression());if(n==="indeterminate")continue;const o=n==="negative"?rs(s.getThenStatement()):rs(s.getElseStatement())??hd(s);o!==void 0&&t.push(vd(o))}return t},Ed=e=>{for(const t of e.getAncestors())if(i.isVariableDeclaration(t)){const s=t.getNameNode();if(i.isIdentifier(s))return s.getText()}return"<anonymous>"},Sd=(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)||!ad.has(y(r)))continue;const a=r.getInitializer();if(!(!a||!(i.isArrowFunction(a)||i.isFunctionExpression(a)))&&dd(a))for(const c of xd(a)){const u=Vs(c);u!==void 0&&o.push({exportName:Ed(e),file:s,form:u,key:y(r),line:c.getStartLineNumber(),owner:t})}}return o},yd=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression)){const o=cd(n);o!==void 0&&s.push(...Sd(n,o,t))}return s},Ad=(e,t)=>{const s=[];for(const n of g(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...yd(o,x(t,n)))}return s},bd=new Set(["query","upsert","upsertNow"]),Nd=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName();if(bd.has(t))return e.getExpression().getText()==="ctx.vectors"?t:void 0},Pd=(e,t)=>{const s=Nd(e.getExpression());if(s===void 0)return;const n=e.getArguments()[1];if(!n)return;const o=P(n,"namespace");if(!(!o||!_(o)||q(o)))return{exportName:A(e),file:t,line:e.getStartLineNumber(),method:s}},wd=(e,t)=>F(e,t,Pd),Id=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"},Td=e=>{const t=e.getArguments()[0];return t&&i.isStringLiteral(t)?t.getLiteralText():""},Cd=(e,t)=>{const s=[];for(const n of g(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=x(t,n);for(const a of o.getDescendantsOfKind(l.CallExpression)){if(!Id(a))continue;const c=Ne(a);c!==""&&s.push({exportName:c,file:r,line:a.getStartLineNumber(),workflow:Td(a)})}}return s},Fd=".lunora-schema.json",Qe=(e,t)=>{I(e)&&as(e,"utf8")===t||on(e,t,"utf8")},Od=(e,t)=>{if(t===""){an(e,{force:!0});return}Qe(e,t)},Rd=e=>{const t=S(e,"package.json");if(I(t))try{const s=JSON.parse(as(t,"utf8"));return typeof s.version=="string"&&s.version!==""?s.version:void 0}catch{return}},kd=()=>{const e=process.env.LUNORA_CODEGEN_TIMING;return e!==void 0&&e!==""},Ld=e=>{let t=I(e)?e:pe(e);for(;t&&t!==pe(t);){const s=S(t,"tsconfig.json");if(I(s))return s;t=pe(t)}},os=e=>e.replaceAll("\\","/"),Dd=(e,t,s)=>{if(s&&e.length>0){const r=e.map(a=>`"${a.exportName}"`).join(", ");throw new B("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 B("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 B("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})}},Se=(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)},is=(e,t,s)=>e.getSourceFile(t)?.getFullText()===s,Md=8,Kd=e=>{const{agents:t,apiPath:s,generatedFunctionsPath:n,lunoraDirectory:o,migrations:r,project:a,shapes:c,usesSandbox:u,useUmbrella:d,workflows:p}=e,h=()=>jn(()=>{const N=Wn(a,o),L=Zn(a,o);return{functions:N,httpRoutes:Vn(a,o),mutators:L}});let{erased:R,value:{functions:k,httpRoutes:m,mutators:T}}=h();kt([...k,...T].map(N=>N.filePath)),kt(m.filter(N=>N.stream).map(N=>N.filePath),"http-stream");for(let N=1;;N+=1){const L=yr({agents:t,functions:k,httpRoutes:m,mutators:T,useUmbrella:d,workflows:p}),D=Rr({agents:t,functions:k,migrations:r,mutators:T,shapes:c,useUmbrella:d,usesSandbox:u});if(N>=Md||is(a,s,L)&&is(a,n,D))return{apiContent:L,erased:R,functions:k,functionsContent:D,httpRoutes:m,mutators:T};Se(a,s,L),Se(a,n,D),{erased:R,value:{functions:k,httpRoutes:m,mutators:T}}=h()}},_d=e=>{const t=Ld(e);return t?new Ct({skipAddingFilesFromTsConfig:!1,tsConfigFilePath:t,useInMemoryFileSystem:!1}):new Ct({skipAddingFilesFromTsConfig:!0,useInMemoryFileSystem:!1})},Hf=(e,t)=>{const s=g(t),n=S(t,"schema.ts");I(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=>os(c))),r=os(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)}}},Gf=e=>{const t=kd(),s=t?Me.now():0,n=S(e.projectRoot,e.lunoraDirectory??"lunora"),o=S(n,"schema.ts");if(!I(o))throw new B("INTERNAL",`schema.ts not found at ${o}`);const r=e.project??_d(n);Kn(ga);const a=ar(r,o,e.projectRoot),{agents:c,containers:u,crons:d,dataModelContent:p,dependencies:h,entryCronTriggers:R,env:k,featureUsage:m,hasFlags:T,hasNotify:N,identity:L,platformGate:D,queues:v,serverContent:V,storageRulesMetadata:H,topics:X,usesSandbox:oe,useUmbrella:$,workflows:O}=bo({lunoraDirectory:n,project:r,projectRoot:e.projectRoot,schema:a,target:e.target});Za(a,a.jurisdiction===void 0?void 0:Xa(r,n));const E=S(n,"_generated"),Gs=S(E,"dataModel.ts"),Ys=S(E,"server.ts"),Qs=S(E,"api.ts"),Xs=S(E,"functions.ts");Se(r,Gs,p),Se(r,Ys,V);const ie=Qn(r,n),G=fr(r,n),{apiContent:ot,erased:Js,functions:U,functionsContent:it,httpRoutes:Te,mutators:ae}=Kd({agents:c,apiPath:Qs,generatedFunctionsPath:Xs,lunoraDirectory:n,migrations:ie,project:r,shapes:G,useUmbrella:$,usesSandbox:oe,workflows:O}),at=pn(r,n),Ce=gn(at,a,[...U,...Te].map(f=>f.filePath)),ce=at.length>0,j=e.lint===!1&&!ce?void 0:{inserts:Gn(r,n),queries:nr(r,n),tableWrites:Vu(r,n),workflowCalls:Cd(r,n)},le=e.lint===!1||j===void 0?void 0:dn({adminRoutes:Oo(r,n),aiRawRuns:$o(r,n),aiToolSideEffects:Yo(r,n),argumentDerivedFetches:Jo(r,n),argumentValidators:ci(r,n),authApiCalls:_n(r,n),authConfigs:xi(r,n),browserUrlAccesses:bi(r,n),configCalls:Ki(r,n),containerKeyAccesses:$i(r,n),containerOverrides:Wi(r,n),containers:u,exportSinks:Yi(r,n),staleMigrationImports:Ou(r,n),failOpenGuards:ea(r,n),flagReads:la(r,n),flagSecurityDefaults:pa(r,n),geoIndexUsages:va(r,n),httpActionGuards:Ca(r,n),httpHeaderWrites:$a(r,n),hyperdriveCalls:Hn(r,n),identityClaimReads:Va(r,n),imageDeliveryUrlAccesses:Ga(r,n),inserts:j.inserts,kvKeyAccesses:tc(r,n,U),mailRecipientAccesses:ic(r,n),maskProcedures:Yn(r,n),maskStrategies:gc(r,n),mutatorWrites:Sc(r,n),nondeterministicCalls:er(r,n),normalizeIdAuthorizations:Mc(r,n),notifyCalls:sr(r,n),notifyConfig:tr(r,n),mutators:ae,ownerFieldWrites:Vc(r,n,U,ae),unrestrictedWhereBranches:Ad(r,n),paymentWebhooks:el(r,n),privilegedDispatches:dl(r,n),procedureProtections:Yl(r,n),queries:j.queries,queues:v,r2sqlCalls:rr(r,n),ratelimitKeySelectors:su(r,n),rawRowReturns:lu(r,n),relationLoads:fu(r,n),rlsProcedures:or(r,n),schema:a,secretLiterals:Su(r,n),modules:Ce,shapes:G,softDeleteReads:Au(r,n),sqlInterpolations:Tu(r,n),storageKeyAccesses:ku(r,n,U),storageUploads:$u(r,n),tableWrites:j.tableWrites,vectorNamespaceAccesses:wd(r,n),workflowCalls:j.workflowCalls,workflows:O,wranglerVariables:e.wranglerVariables}),ct=le===void 0?[]:Lr(e.projectRoot,[...cn(le,{source:"static"}),...id(r,n,{byName:new Set([...O,...v,...c,...u].map(f=>f.exportName)),byPath:new Set([...U,...ae,...G,...ie].map(f=>`${f.filePath}:${f.exportName}`))}),...Qu(r,n),...qn(Js,n)]),Zs=ir(r,n),lt=dc(r,n);Dd(G,lt,lc(r,n));const en=T?ra(r,n):[],Fe=D.signals.vectorStore!==!1,J=zu(m,{containerCount:u.length,cronCount:d.length,dependencies:h,hasPaymentTables:Yc(a.tables),queueCount:v.length,storageColumnCount:Object.keys(xs(a)).length,storageRuleCount:H.rules.length,vectorIndexCount:a.vectorIndexes.length,target:vs(e.projectRoot,e.target),vectorStoreSupported:Fe,workflowCount:O.length}),ut=t?Me.now():0,Oe=xr(a,ie.map(f=>f.id)),dt=Ln({advisories:ct.filter(f=>f.name!=="procedure_type_check_unavailable"),advisorProcedures:le?.procedureProtections??[],agents:c,containers:u,env:k,flagKeys:en,hasAccessFacade:m.access,hasAi:m.ai,hasAnalytics:m.analytics,hasBrowser:m.browser,hasFlags:T,hasHyperdrive:m.hyperdrive,hasImages:m.images,hasKv:m.kv,hasNotify:N,hasPayments:m.payments,hasPipelines:m.pipelines,hasR2sql:m.r2sql,hasVectors:Fe,hasX402:m.x402,maskMetadata:lt,mutators:ae,queues:v,rlsMetadata:Zs,schema:a,schemaSnapshot:Oe,shapes:G,storageRules:H,studioFeatures:J,topics:X,useUmbrella:$,workflows:O}),ft=Er(G,h.has("@lunora/db"),$),pt=Ar(u,a.jurisdiction),gt=br(O),mt=Nr(c),ht=Pr(v),vt=wr(d),tn=Ir(J.scheduler),sn=Tr(a.tables,$),xt=Cr(a.vectorIndexes),ue=Or(a,$),Et=Sr(h.has("@lunora/seed")),de=e.apiSpec??"openapi",Re=de==="openapi"||de==="both",ke=de==="openrpc"||de==="both",St=pr({emailAgents:c.filter(f=>f.onEmail===!0).map(f=>({className:f.className,exportName:f.exportName})),hasAccess:h.has("@lunora/cloudflare-access"),hasAi:m.ai,hasAnalytics:m.analytics,hasAuth:h.has("@lunora/auth"),hasBrowser:m.browser,hasFramework:h.has("@lunora/astro")||h.has("@lunora/svelte")||h.has("@lunora/vue")||I(S(e.projectRoot,"src","worker.ts")),hasGlobal:a.tables.some(f=>cs(f)),hasHyperdrive:m.hyperdrive,hasHyperdriveGlobal:a.tables.some(f=>ls(f)),hasImages:m.images,hasKv:m.kv,hasKvIntrospector:J.kv,hasNotify:N,hasPayments:m.payments,hasR2sql:m.r2sql,hasQueue:v.some(f=>f.mode==="push"),hasScheduler:J.scheduler,hasSourcedTables:a.tables.some(f=>f.externalSource!==void 0),hasStorage:J.storage,hasVectors:Fe,hasWorkflow:O.length>0,hasX402:m.x402,identity:L,jurisdiction:a.jurisdiction,jurisdictionPinsAuth:a.jurisdictionPinsAuth===!0,tables:a.tables.map(f=>({name:f.name,shardMode:f.shardMode})),useUmbrella:$,vectorIndexCount:a.vectorIndexes.length,voiceAgents:c.filter(f=>f.voice===!0&&f.voiceBindingName!==void 0).map(f=>({bindingName:f.voiceBindingName,exportName:f.exportName})),wantsArchitecture:ce,wantsOpenApi:Re,wantsOpenRpc:ke}),yt=Rd(e.projectRoot),At=ce?Ce:[],bt=gr({functions:U,httpRoutes:Te,modules:At,version:yt}),Nt=hr({functions:U,modules:At,version:yt}),Pt=`${JSON.stringify(bt,void 0,2)}
|
|
9
|
-
`,wt=`${JSON.stringify(Nt,void 0,2)}
|
|
10
|
-
`,fe=ce&&j!==void 0?Wr({...j,callEdges:Ci(r,n),crons:d,functions:U,httpRoutes:Te,modules:Ce,queues:v,schema:a,topics:X,workflows:O}):void 0,It=mr(bt),Tt=vr(Nt),Le=S(n,Fd),nn=I(Le),De=[];if(!e.dryRun){I(E)||rn(E,{recursive:!0});const f=(W,Y)=>{Qe(S(E,W),Y),De.push(W)},w=(W,Y)=>{Od(S(E,W),Y),Y!==""&&De.push(W)};f("app.ts",St),f("dataModel.ts",p),f("api.ts",ot),f("server.ts",V),f("functions.ts",it),f("shard.ts",dt),f("crons.ts",vt),f("vectors.ts",xt),f("drizzle.global.ts",ue.global),f("drizzle.shard.ts",ue.shard),w("containers.ts",pt),w("workflows.ts",gt),w("agents.ts",mt),w("queues.ts",ht),w("scheduler.ts",tn),w("shardRegistry.ts",sn),w("seed.ts",Et),w("collections.ts",ft),w("openapi.json",Re?Pt:""),w("openapi.ts",Re?It:""),w("openrpc.json",ke?wt:""),w("openrpc.ts",ke?Tt:""),w("architecture.json",fe===void 0?"":`${JSON.stringify(fe,void 0,2)}
|
|
11
|
-
`),w("architecture.ts",fe===void 0?"":Vr(fe)),(!nn||e.updateSchemaBaseline===!0)&&Qe(Le,un(Oe))}if(t){const f=Me.now(),w=Math.round(f-s),W=Math.round(ut-s),Y=Math.round(f-ut);console.error(`@lunora/codegen: codegen took ${w.toString()}ms (discovery ${W.toString()}ms, emit ${Y.toString()}ms)`)}return{advisories:ct,advisorContext:le,agents:c,containers:u,cronTriggers:[...new Set([...Fr(d),...R])],generated:{agents:mt,api:ot,app:St,collections:ft,containers:pt,crons:vt,dataModel:p,drizzleGlobal:ue.global,drizzleShard:ue.shard,functions:it,openApi:Pt,openApiModule:It,openRpc:wt,openRpcModule:Tt,queues:ht,seed:Et,server:V,shard:dt,vectors:xt,workflows:gt},migrations:ie,outputDirectory:E,platformDiagnostics:D.diagnostics,queues:v,schemaSnapshot:Oe,schemaSnapshotPath:Le,workflows:O,writtenFiles:De}};export{Fd as SCHEMA_SNAPSHOT_FILENAME,_d as createCodegenProject,Ld as findTsconfig,Hf as refreshCodegenProject,Gf as runCodegen};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import"./ir-DBSvhNa-.mjs";import"./json-data-Chfs2Cz5.mjs";import{w as i,p as r,A as n,n as o,B as g,q as F,l as p,D as u,u as l,m as f,o as w,C as d,t as k,s as A}from"./shard-runtime-oIXHEMU7.mjs";import"./shared-DjUziztz.mjs";export{i as buildDoTypeImports,r as emitAgentFragments,n as emitAgents,o as emitContainerFragments,g as emitContainers,F as emitPaymentFragments,p as emitQueueFragments,u as emitQueues,l as emitQueuesMetadataFragments,f as emitTopicFragments,w as emitWorkflowFragments,d as emitWorkflows,k as emitWorkflowsMetadataFragments,A as emitX402Fragments};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{statSync as p,readFileSync as m}from"node:fs";import{basename as v}from"node:path";import{createJiti as E}from"jiti";import{Project as b,Node as r}from"ts-morph";import{propertyKeyName as u}from"./listLunoraSourceFiles-CSlcBYlo.mjs";import{findProjectConfigFile as f}from"./PROJECT_CONFIG_FILENAMES-DzOu-lSc.mjs";import{PROJECT_CONFIG_FILENAMES as I}from"./PROJECT_CONFIG_FILENAMES-DzOu-lSc.mjs";const g=new Map,N=async t=>{const i=f(t);if(i===void 0)return{};let e;try{const n=p(i);e=`${String(n.mtimeMs)}:${String(n.size)}`}catch{return{}}const s=g.get(i);if(s?.key===e)return s.value;const l=(async()=>{try{const o=(await E(i,{interopDefault:!1,moduleCache:!1}).import(i))?.default;return{config:o!==null&&typeof o=="object"?o:void 0}}catch(n){return{error:n instanceof Error?n.message:String(n)}}})();return g.set(i,{key:e,value:l}),l},x=t=>{let e=t.getExportAssignments().find(s=>!s.isExportEquals())?.getExpression();for(;e!==void 0&&(r.isSatisfiesExpression(e)||r.isAsExpression(e)||r.isParenthesizedExpression(e));)e=e.getExpression();if(e!==void 0&&r.isIdentifier(e))for(e=t.getVariableDeclaration(e.getText())?.getInitializer();e!==void 0&&(r.isSatisfiesExpression(e)||r.isAsExpression(e));)e=e.getExpression();return e!==void 0&&r.isObjectLiteralExpression(e)?e:void 0},c=(t,i)=>r.isPropertyAssignment(t)?t.getInitializer():i.getVariableDeclaration(u(t))?.getInitializer(),S=(t,i)=>{let e=t;for(;e!==void 0&&(r.isSatisfiesExpression(e)||r.isAsExpression(e)||r.isParenthesizedExpression(e));)e=e.getExpression();if(e===void 0||!r.isObjectLiteralExpression(e))return{advisor:{unreadable:!0}};const s=e.getProperties(),l=s.filter(a=>r.isPropertyAssignment(a)&&!r.isComputedPropertyName(a.getNameNode())||r.isShorthandPropertyAssignment(a));if(l.length!==s.length)return{advisor:{unreadable:!0}};const n=l.find(a=>u(a)==="minSeverity");if(n===void 0)return{advisor:{}};const o=c(n,i);return o!==void 0&&r.isStringLiteral(o)?{advisor:{minSeverity:o.getLiteralValue()}}:{advisor:{unreadable:!0}}},h=new Map([["advisor",{advisor:{unreadable:!0}}],["remote",{unreadable:!0}],["target",{unreadable:!0}]]),P=(t,i)=>{if(r.isGetAccessorDeclaration(t)||r.isMethodDeclaration(t))return h.get(u(t))??{};if(!r.isPropertyAssignment(t)&&!r.isShorthandPropertyAssignment(t))return{};const e=u(t);if(e==="advisor")return S(c(t,i),i);if(e!=="target"&&e!=="remote")return{};const s=c(t,i);return s===void 0?{unreadable:!0}:e==="target"?r.isStringLiteral(s)?{target:s.getLiteralValue()}:{unreadable:!0}:r.isTrueLiteral(s)||r.isFalseLiteral(s)?{remote:s.getLiteralValue()}:r.isObjectLiteralExpression(s)?{remote:!0}:{unreadable:!0}},O=t=>{const i=f(t);if(i===void 0)return{};let e;try{e=m(i,"utf8")}catch{return{unreadable:!0}}const l=new b({compilerOptions:{allowJs:!0},skipFileDependencyResolution:!0,skipLoadingLibFiles:!0,useInMemoryFileSystem:!0}).createSourceFile(v(i),e,{overwrite:!0}),n=x(l);if(n===void 0)return{unreadable:!0};if(n.getProperties().some(a=>r.isSpreadAssignment(a)))return n.getProperties().some(d=>!r.isSpreadAssignment(d)&&u(d)==="advisor")?{advisor:{unreadable:!0},unreadable:!0}:{unreadable:!0};let o={};for(const a of n.getProperties())o={...o,...P(a,l)};return o};export{I as PROJECT_CONFIG_FILENAMES,f as findProjectConfigFile,N as loadProjectConfig,O as readProjectConfigLiterals};
|