@lunora/codegen 1.0.0-alpha.77 → 1.0.0-alpha.79

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.
@@ -0,0 +1,5 @@
1
+ import{existsSync as E,readFileSync as $e,mkdirSync as Bt,writeFileSync as Vt,rmSync as Ut}from"node:fs";import{join as g,dirname as pe}from"node:path";import{performance as me}from"node:perf_hooks";import{runAdvisor as Wt}from"@lunora/advisor";import{LunoraError as B}from"@lunora/errors";import{Node as i,SyntaxKind as u,Project as Ze}from"ts-morph";import{serializeSchemaSnapshot as Gt}from"./SCHEMA_SNAPSHOT_VERSION-CFhF_hmg.mjs";import{toAdvisorContext as Ht}from"./formatAdvisories-BCEfzLT0.mjs";import{listLunoraSourceFiles as d,lunoraRelativePath as f,classifyProcedureCall as K,inlineHandler as _t,procedureHandler as pt,chainUsesWrappedCall as mt,isDatabaseAccessor as C,chainHasStep as Qt,discoverFunctions as Jt}from"./discoverFunctions-DnqHgv0t.mjs";import{discoverAgents as Xt}from"./AGENTS_FILENAME-BesaDYkL.mjs";import{i as w,a as F,e as h,c as S,r as Zt,s as H,b as Yt,d as es,E as ts}from"./discover-queries-LfER8HbK.mjs";import ss from"./discoverAuthApiCalls-CEk3J0kc.mjs";import{discoverContainers as rs}from"./CONTAINERS_FILENAME-CFwdyaCI.mjs";import ns from"./discoverCrons-kIgM9ZJC.mjs";import{diagnosticAt as _}from"./CodegenDiagnosticError-DPezpZTz.mjs";import{o as Q}from"./module-specifiers-8FEEiUcv.mjs";import{a as xe,n as is,t as os,h as as,v as cs,$ as us,r as ls,b as ds,Q as gs,K as fs,H as ps,G as ms,c as xs,d as hs,l as Es,f as ys,u as $s}from"./emit-BtiV37rG.mjs";import{discoverFlagKeys as As}from"./FLAGS_FILENAME-CQDN7BKc.mjs";import Ss from"./discoverHttpRoutes-CLn3VDRI.mjs";import Ns from"./discoverInserts-Cn-CLKET.mjs";import vs,{discoverMaskStrategies as bs,discoverMaskMetadata as Ps}from"./discoverMaskProcedures-fZtvsy8v.mjs";import ws from"./discoverMigrations-BH_IKdFk.mjs";import{MUTATORS_FILENAME as Is,isDefineMutatorCallee as Ls,discoverMutators as Os}from"./MUTATORS_FILENAME-3Akvs4aT.mjs";import Fs from"./discoverNondeterministicCalls-Cl7qNL0J.mjs";import{discoverNotifyConfig as Ts,discoverNotifyCalls as Ds}from"./NOTIFY_FILENAME-B2lXWa7r.mjs";import{discoverQueues as Cs}from"./QUEUES_FILENAME-CSE6i-ld.mjs";import Ks from"./discoverR2sqlCalls-CMNfDWlq.mjs";import ks,{discoverRlsMetadata as Rs}from"./discoverRlsMetadata-Bf4_2S0t.mjs";import{discoverSandboxUsage as js}from"./discoverSandboxUsage-Bn1X9COt.mjs";import Ms from"./discoverSchema-Cy4OQ0Cu.mjs";import{secretKindOf as zs,redact as qs}from"./redact-CQ8-to6l.mjs";import{discoverShapes as Bs}from"./SHAPES_FILENAME-maut3z1K.mjs";import Vs from"./discoverStorageRulesMetadata-CL8J41rX.mjs";import{e as Us}from"./discover-ast-CezKqEhE.mjs";import{discoverWorkflows as Ws}from"./WORKFLOWS_FILENAME-Bk5upkGM.mjs";import{emitApp as Gs}from"./emitApp-Bc3G4eki.mjs";import{buildOpenApiDocument as Hs,emitOpenApiModule as _s}from"./buildOpenApiDocument-D6xm3JqM.mjs";import{buildOpenRpcDocument as Qs,emitOpenRpcModule as Js}from"./OPENRPC_VERSION-BPT6vyLU.mjs";import{gatePlatformFeatures as Xs,resolveCodegenTarget as Zs}from"./DEFAULT_TARGET-BYPEwgZu.mjs";import{buildSchemaSnapshot as Ys}from"./SchemaSnapshotParseError-0KRzSjo4.mjs";const xt=new Set(["delete","get","head","options","patch","post","put"]),er=new Set(["handler","stream"]),tr=/\/(?:_|admin|internal|superuser|sudo|root|debug)/iu,Ye=new Set(["ADMIN_TOKEN","adminToken","assertAdmin","assertAuth","auth","Authorization","getSession","identity","isAdmin","requireAdmin","requireAuth","requireRole","verifyAdmin"]),sr=e=>{if(!i.isCallExpression(e))return;const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!xt.has(t.getName()))return;const s=t.getExpression();if(!i.isIdentifier(s)||s.getText()!=="httpRoute")return;const r=e.getArguments()[0];if(!(!r||!i.isStringLiteral(r)))return{method:t.getName().toUpperCase(),path:r.getLiteralValue()}},rr=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t))return;let s=t.getExpression();for(;i.isCallExpression(s);){const r=s.getExpression();if(!i.isPropertyAccessExpression(r)||xt.has(r.getName()))break;s=r.getExpression()}return sr(s)},nr=e=>{for(const t of e.getDescendantsOfKind(u.PropertyAccessExpression))if(Ye.has(t.getName()))return!0;for(const t of e.getDescendantsOfKind(u.CallExpression)){const s=t.getExpression();if(i.isIdentifier(s)&&Ye.has(s.getText()))return!0}return!1},ir=(e,t)=>{const s=e.getInitializer();if(!s||!i.isCallExpression(s))return;const r=s.getExpression();if(!i.isPropertyAccessExpression(r)||!er.has(r.getName()))return;const n=rr(s);if(!n||!tr.test(n.path))return;const o=s.getArguments()[0],a=o!==void 0&&(i.isArrowFunction(o)||i.isFunctionExpression(o))&&nr(o);return{exportName:e.getName(),file:t,method:n.method,path:n.path,usesGuard:a}},or=(e,t)=>{const s=[];for(const r of e.getVariableStatements())if(r.isExported())for(const n of r.getDeclarations()){const o=ir(n,t);o&&s.push(o)}return s},ar=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...or(n,f(t,r)))}return s},cr=e=>!i.isPropertyAccessExpression(e)||e.getName()!=="run"?!1:e.getExpression().getText()==="ctx.ai",ur=(e,t)=>{if(!cr(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!w(s)||F(s)))return{exportName:h(e),file:t,line:e.getStartLineNumber()}},lr=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=ur(r,t);n&&s.push(n)}return s},dr=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...lr(n,f(t,r)))}return s},gr=new Set(["generateText","streamText"]),fr=new Set(["messages","prompt","system"]),pr=[{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"]}],mr=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t))return;const s=t.getName(),r=t.getExpression().getText();for(const n of pr)if(n.methods.has(s)&&n.prefixes.some(o=>r===o||r.startsWith(`${o}.`)))return`${r}.${s}`},xr=e=>{for(const t of e.getDescendantsOfKind(u.CallExpression)){const s=mr(t);if(s!==void 0)return s}},hr=e=>{const t=new Set,s=e.getFirstAncestor(o=>i.isArrowFunction(o)||i.isFunctionExpression(o)||i.isFunctionDeclaration(o)),[r]=s?.getParameters()??[],n=r?.getNameNode();if(n===void 0||!i.isObjectBindingPattern(n))return t;for(const o of n.getElements()){const a=o.getPropertyNameNode()?.getText()??o.getName(),c=o.getNameNode();if(a==="args"&&i.isObjectBindingPattern(c))for(const l of c.getElements())t.add(l.getName())}return t},Er=e=>{if(Zt(e))return!0;const t=hr(e);return t.size===0?!1:e.getDescendantsOfKind(u.Identifier).some(s=>t.has(s.getText()))},yr=e=>{for(const t of e.getProperties()){if(!i.isPropertyAssignment(t)||!fr.has(t.getName()))continue;const s=t.getInitializer();if(s!==void 0&&Er(s))return!0}return!1},$r=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=S(r.getExpression());if(n===void 0||!gr.has(n))continue;const[o]=r.getArguments();if(o===void 0||!i.isObjectLiteralExpression(o))continue;let a;for(const c of o.getDescendantsOfKind(u.CallExpression))if(S(c.getExpression())==="tool"&&(a=xr(c),a!==void 0))break;a!==void 0&&s.push({exportName:h(r),file:t,line:r.getStartLineNumber(),method:n,sideEffect:a,userInputDerived:yr(o)})}return s},Ar=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...$r(n,f(t,r)))}return s},Sr=e=>{if(!i.isPropertyAccessExpression(e)||e.getName()!=="fetch")return!1;const t=e.getExpression();return i.isIdentifier(t)&&t.getText()==="ctx"},Nr=(e,t)=>{if(!Sr(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!w(s)))return{exportName:h(e),file:t,line:e.getStartLineNumber()}},vr=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=Nr(r,t);n&&s.push(n)}return s},br=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...vr(n,f(t,r)))}return s},ht=e=>e.getProperties().some(t=>i.isSpreadAssignment(t)),Pr=e=>{const t=e.getArguments()[0];if(!t||!i.isObjectLiteralExpression(t))return{objects:[],opaque:!0};const s=t.getProperty("args");if(!s)return{objects:[],opaque:!1};if(!i.isPropertyAssignment(s))return{objects:[],opaque:!0};const r=s.getInitializer();return!r||!i.isObjectLiteralExpression(r)?{objects:[],opaque:!0}:{objects:[r],opaque:ht(r)}},wr=e=>{const t=[];let s=!1,r=e;for(;i.isCallExpression(r);){const n=r.getExpression();if(!i.isPropertyAccessExpression(n))break;if(n.getName()==="input"){const o=r.getArguments()[0];o&&i.isObjectLiteralExpression(o)?(t.push(o),s||=ht(o)):s=!0}r=n.getExpression()}return{objects:t,opaque:s}},Et=(e,t)=>t?wr(t):Pr(e),Ir=e=>e.flatMap(t=>t.getProperties().filter(s=>i.isPropertyAssignment(s)||i.isShorthandPropertyAssignment(s)).map(s=>s.getName())),Lr=/\.check\(|\.meta\(|length|max/iu,Or=/\bv\.any\s*\(/u,Fr=/\bv\.string\s*\(/u,Tr=e=>Or.test(e),Dr=e=>Fr.test(e)&&!Lr.test(e),Cr=e=>{const t=[],s=[];for(const r of e)for(const n of r.getProperties()){if(!i.isPropertyAssignment(n))continue;const o=n.getInitializer();if(!o)continue;const a=o.getText(),c=n.getName();Tr(a)?t.push(c):Dr(a)&&s.push(c)}return{anyArgs:t,unboundedStringArgs:s}},Kr=(e,t)=>{const s=e.getInitializer();if(!s||!i.isCallExpression(s))return;const r=K(s);if(r?.visibility!=="public")return;const{objects:n}=Et(s,r.receiver),{anyArgs:o,unboundedStringArgs:a}=Cr(n);if(!(o.length===0&&a.length===0))return{anyArgs:o,exportName:e.getName(),file:t,line:s.getStartLineNumber(),unboundedStringArgs:a}},kr=(e,t)=>{const s=[];for(const r of e.getVariableStatements())if(r.isExported())for(const n of r.getDeclarations()){const o=Kr(n,t);o&&s.push(o)}return s},Rr=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...kr(n,f(t,r)))}return s},N=(e,t)=>{if(!e||!i.isObjectLiteralExpression(e))return;const s=e.getProperty(t);return s&&i.isPropertyAssignment(s)?s.getInitializer():void 0},he=e=>e?.getKind()===u.TrueKeyword,jr=e=>e?.getKind()===u.FalseKeyword,Mr=e=>e!==void 0&&i.isNumericLiteral(e)&&e.getLiteralValue()===0,zr=new Set(["lunoraAuthAdapter","lunoraD1Adapter"]),qr=e=>!e||!i.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>i.isCallExpression(t)&&S(t.getExpression())==="scim"),Br=e=>e!==void 0&&i.isCallExpression(e)&&zr.has(S(e.getExpression())??""),Vr=e=>!e||!i.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>i.isStringLiteral(t)&&t.getLiteralText()==="*"),Ur=e=>{const t=N(e,"advanced"),s=N(e,"emailAndPassword"),r=N(e,"session");return{analyzable:!0,disableCsrfCheck:he(N(t,"disableCSRFCheck")),emailPasswordEnabled:he(N(s,"enabled")),requireEmailVerification:he(N(s,"requireEmailVerification")),scimOnNonTransactionalAdapter:qr(N(e,"plugins"))&&Br(N(e,"database")),secureCookiesDisabled:jr(N(t,"useSecureCookies")),sessionFreshAgeZero:Mr(N(r,"freshAge")),trustedOriginsWildcard:Vr(N(e,"trustedOrigins"))}},Wr=()=>({analyzable:!1,disableCsrfCheck:!1,emailPasswordEnabled:!1,requireEmailVerification:!1,scimOnNonTransactionalAdapter:!1,secureCookiesDisabled:!1,sessionFreshAgeZero:!1,trustedOriginsWildcard:!1}),Gr=(e,t)=>{if(S(e.getExpression())!=="createAuth")return;const s=e.getArguments()[0],r=s!==void 0&&i.isObjectLiteralExpression(s)&&s.getProperties().some(o=>i.isSpreadAssignment(o)),n=s!==void 0&&i.isObjectLiteralExpression(s)&&!r?Ur(s):Wr();return{exportName:h(e),file:t,line:e.getStartLineNumber(),...n}},Hr=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=Gr(r,t);n&&s.push(n)}return s},_r=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Hr(n,f(t,r)))}return s},Qr=(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},Jr=(e,t,s)=>{const r=Qr(e.getExpression(),s);if(r===void 0)return;const n=e.getArguments()[s.argIndex];if(!(!n||!w(n)||F(n)))return{exportName:h(e),file:t,line:e.getStartLineNumber(),method:r}},Xr=(e,t,s)=>{const r=[];for(const n of e.getDescendantsOfKind(u.CallExpression)){const o=Jr(n,t,s);o&&r.push(o)}return r},J=(e,t,s)=>{const r=[];for(const n of d(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);r.push(...Xr(o,f(t,n),s))}return r},Zr=new Set(["content","pdf","scrape","screenshot"]),Yr=(e,t)=>J(e,t,{argIndex:0,matchReceiver:s=>s==="ctx.browser",methods:Zr}),en=new Set(["createBrowser","createInboundEmailHandler","createPayment"]),tn=new Set(["RateLimiter"]),sn=new Set(["extend"]),yt=e=>{const t=[],s=[];let r=!1;for(const n of e.getProperties()){if(i.isSpreadAssignment(n)){r=!0;continue}if(i.isPropertyAssignment(n)){const o=n.getName();t.push(o),n.getInitializer()?.getKind()===u.TrueKeyword&&s.push(o);continue}(i.isShorthandPropertyAssignment(n)||i.isMethodDeclaration(n))&&t.push(n.getName())}return{analyzable:!r,presentKeys:t,trueKeys:s}},et=e=>e&&i.isObjectLiteralExpression(e)?yt(e):{analyzable:!1,presentKeys:[],trueKeys:[]},rn=e=>{const t=e.getStatements(),[s]=t;if(t.length!==1||s===void 0||!i.isReturnStatement(s))return;const r=s.getExpression();return r!==void 0&&i.isObjectLiteralExpression(r)?r:void 0},nn=e=>{if(i.isObjectLiteralExpression(e))return e;if(i.isParenthesizedExpression(e)){const t=e.getExpression();return i.isObjectLiteralExpression(t)?t:void 0}return i.isBlock(e)?rn(e):void 0},on=e=>{const t=e&&(i.isArrowFunction(e)||i.isFunctionExpression(e))?e:void 0,s=t&&nn(t.getBody());return s?yt(s):{analyzable:!1,presentKeys:[],trueKeys:[]}},an=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=S(r.getExpression());n!==void 0&&(en.has(n)?s.push({callee:n,file:t,line:r.getStartLineNumber(),...et(r.getArguments()[0])}):sn.has(n)&&s.push({callee:n,file:t,line:r.getStartLineNumber(),...on(r.getArguments()[0])}))}for(const r of e.getDescendantsOfKind(u.NewExpression)){const n=S(r.getExpression());n===void 0||!tn.has(n)||s.push({callee:n,file:t,line:r.getStartLineNumber(),...et(r.getArguments()[0])})}return s},cn=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...an(n,f(t,r)))}return s},tt="ctx.containers.",un=e=>{if(!e.startsWith(tt))return!1;const t=e.slice(tt.length);return t.length>0&&!t.includes(".")},ln=(e,t)=>J(e,t,{argIndex:0,matchReceiver:un,methods:new Set(["get"])}),dn=new Set(["allow","deny","setAllowed"]),gn=e=>{const t=e.getArguments()[0];if(!t||!i.isObjectLiteralExpression(t))return!1;const s=t.getProperty("enableInternet");return s!==void 0&&i.isPropertyAssignment(s)&&i.isTrueLiteral(s.getInitializerOrThrow())},fn=(e,t)=>{const s=e.getExpression();if(!(!i.isPropertyAccessExpression(s)||s.getName()!=="start"||!gn(e)))return{detail:"enableInternet: true",exportName:h(e),file:t,kind:"enable_internet",line:e.getStartLineNumber()}},pn=(e,t)=>{const s=e.getExpression();if(!i.isPropertyAccessExpression(s)||!dn.has(s.getName()))return;const r=s.getExpression();if(!(!i.isPropertyAccessExpression(r)||r.getName()!=="egress"))return{detail:s.getName(),exportName:h(e),file:t,kind:"egress_relaxation",line:e.getStartLineNumber()}},mn=(e,t)=>fn(e,t)??pn(e,t),xn=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=mn(r,t);n&&s.push(n)}return s},hn=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...xn(n,f(t,r)))}return s},En="env.ts",yn=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineEnv";for(const s of t.getDeclarations())if(i.isImportSpecifier(s))return Q(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineEnv":!1;return!1},$n=e=>{const t=e.getSymbol();if(!t)return!1;for(const s of t.getDeclarations()){if(!i.isNamespaceImport(s))continue;const r=s.getFirstAncestorByKind(u.ImportDeclaration);return r!==void 0&&Q(r.getModuleSpecifierValue())}return!1},An=e=>{if(i.isIdentifier(e))return yn(e);if(i.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineEnv"&&i.isIdentifier(t)&&$n(t)}return!1},Sn=e=>{const t=[];for(const s of e.getVariableDeclarations()){if(!s.isExported())continue;const r=s.getInitializer();if(r?.getKind()!==u.CallExpression||!An(r.getExpression()))continue;const n=s.getNameNode();if(!i.isIdentifier(n))throw _(n,"defineEnv exports must be plain named exports (no destructuring)");t.push({exportName:n.getText()})}return t},Nn=(e,t)=>{const s=g(t,En);if(!E(s))return;const r=e.getSourceFile(s)??e.addSourceFileAtPath(s),n=Sn(r);if(n.length!==0){if(n.length>1)throw _(r,`lunora/env.ts declares ${n.length.toString()} defineEnv() contracts (${n.map(o=>o.exportName).join(", ")}); exactly one is allowed`);return n[0]}},vn=new Set(["defineExportSink","r2Sink","webhookExportSink"]),bn=e=>{const t=e.getExpression();if(!i.isIdentifier(t))return;const s=t.getText();return vn.has(s)?s:void 0},Pn=e=>{const t=[],s=[];for(const r of e.getProperties()){if(i.isSpreadAssignment(r))return{analyzable:!1,emptyKeys:[],presentKeys:[]};if(i.isPropertyAssignment(r)){const n=r.getName();t.push(n);const o=r.getInitializer();o&&i.isStringLiteral(o)&&o.getLiteralText()===""&&s.push(n);continue}(i.isShorthandPropertyAssignment(r)||i.isMethodDeclaration(r)||i.isGetAccessorDeclaration(r))&&t.push(r.getName())}return{analyzable:!0,emptyKeys:s,presentKeys:t}},wn=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r),o=f(t,r);for(const a of n.getDescendantsOfKind(u.CallExpression)){const c=bn(a);if(c===void 0)continue;const l=a.getArguments()[0],p=l&&i.isObjectLiteralExpression(l)?Pn(l):{analyzable:!1,emptyKeys:[],presentKeys:[]};s.push({analyzable:p.analyzable,emptyKeys:p.emptyKeys,factory:c,file:o,line:a.getStartLineNumber(),presentKeys:p.presentKeys})}}return s},In=new Map([["dbRateLimit",2],["rateLimit",2],["verifyTurnstileMiddleware",0]]),Ln=new Set(["dbRateLimit","rateLimit"]),On=e=>{if(!e||!i.isObjectLiteralExpression(e))return!1;const t=e.getProperty("failOpen");return t!==void 0&&i.isPropertyAssignment(t)&&t.getInitializer()?.getKind()===u.TrueKeyword},Fn=e=>{const t=e.getArguments()[1];return t&&i.isStringLiteral(t)?t.getLiteralValue():""},Tn=(e,t)=>{const s=S(e.getExpression());if(s===void 0)return;const r=In.get(s);if(r!==void 0)return{callee:s,exportName:h(e),failOpen:On(e.getArguments()[r]),file:t,limitName:Ln.has(s)?Fn(e):"",line:e.getStartLineNumber()}},Dn=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=Tn(r,t);n&&s.push(n)}return s},Cn=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Dn(n,f(t,r)))}return s},Kn=e=>{const t=r=>i.isIdentifier(r)&&r.getText()==="ctx",s=new Set;for(const r of e.getDescendantsOfKind(u.PropertyAccessExpression))t(r.getExpression())&&s.add(r.getName());for(const r of e.getDescendantsOfKind(u.VariableDeclaration)){const n=r.getInitializer(),o=r.getNameNode();if(!(n===void 0||!t(n)||!i.isObjectBindingPattern(o)))for(const a of o.getElements()){const c=a.getPropertyNameNode()?.getText()??a.getName();c&&s.add(c)}}return s},kn=(e,t)=>{const s=Object.fromEntries(xe.map(r=>[r.key,!1]));for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r),o=new Set(n.getImportDeclarations().map(c=>c.getModuleSpecifierValue())),a=Kn(n);for(const c of xe)if(!s[c.key]){if(o.has(c.moduleSpecifier)){s[c.key]=!0;continue}c.contextProperty!==void 0&&a.has(c.contextProperty)&&(s[c.key]=!0)}if(xe.every(c=>s[c.key]))break}return s},Rn=["providerSubscriptionId","state"],jn=["providerEventId","processedAt"],st=(e,t)=>t.every(s=>s in e.shape),Mn=e=>{const t=e.find(r=>r.name==="subscriptions"),s=e.find(r=>r.name==="events");return t!==void 0&&s!==void 0&&st(t,Rn)&&st(s,jn)},zn=(e,t)=>({analytics:e.analytics||t.dependencies.has("@lunora/bindings/analytics"),auth:t.dependencies.has("@lunora/auth"),containers:e.container||t.containerCount>0||t.dependencies.has("@lunora/container"),flags:e.flags||t.dependencies.has("@lunora/flags"),kv:e.kv||t.dependencies.has("@lunora/bindings/kv"),mail:e.mail||t.dependencies.has("@lunora/mail"),notifications:e.notify||t.dependencies.has("@lunora/notify"),payments:e.payments||t.hasPaymentTables,queues:t.queueCount>0||t.dependencies.has("@lunora/queue"),scheduler:e.scheduler||t.cronCount>0||t.dependencies.has("@lunora/scheduler"),storage:e.storage||t.storageRuleCount>0||t.storageColumnCount>0||t.dependencies.has("@lunora/storage"),vectors:e.vectors||t.vectorIndexCount>0||t.dependencies.has("@lunora/bindings/vectors"),workflows:e.workflows||t.workflowCount>0||t.dependencies.has("@lunora/workflow")}),qn=e=>i.isIdentifier(e)&&e.getText()==="ctx",Bn=e=>{if(!i.isPropertyAccessExpression(e)||e.getName()!=="boolean")return!1;const t=e.getExpression();return i.isPropertyAccessExpression(t)&&t.getName()==="flags"&&qn(t.getExpression())},Vn=e=>{if(e?.getKind()===u.TrueKeyword)return!0;if(e?.getKind()===u.FalseKeyword)return!1},Un=(e,t)=>{if(!Bn(e.getExpression()))return;const[s,r]=e.getArguments();if(!s||!(i.isStringLiteral(s)||i.isNoSubstitutionTemplateLiteral(s)))return;const n=s.getLiteralValue(),o=Vn(r);if(!(n.length===0||o===void 0))return{defaultValue:o,exportName:h(e),file:t,key:n,line:e.getStartLineNumber()}},Wn=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=Un(r,t);n&&s.push(n)}return s},Gn=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Wn(n,f(t,r)))}return s},Hn=e=>{const t=e.getExpression();return i.isPropertyAccessExpression(t)&&t.getName()==="withGeoIndex"},_n=e=>{const t=e.getArguments()[0];return t&&i.isStringLiteral(t)?t.getLiteralText():""},Qn=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r),o=f(t,r);for(const a of n.getDescendantsOfKind(u.CallExpression))Hn(a)&&s.push({file:o,indexName:_n(a),line:a.getStartLineNumber()})}return s},Jn=new Set(["delete","get","head","options","patch","post","put"]),Xn=new Set(["handler","stream"]),Zn=new Set(["runAction","runMutation"]),Yn=new Set(["delete","insert","insertManyUnsafe","patch","replace"]),U=(e,t)=>e!==void 0&&i.isIdentifier(e)&&e.getText()===t,rt=e=>e!==void 0&&(i.isArrowFunction(e)||i.isFunctionExpression(e))?e:void 0,nt=(e,t)=>{const s=e.getParameters()[0];if(s===void 0)return;const r=s.getNameNode();if(t)return i.isIdentifier(r)?r.getText():void 0;if(i.isObjectBindingPattern(r)){for(const n of r.getElements())if((n.getPropertyNameNode()?.getText()??n.getNameNode().getText())==="ctx"){const o=n.getNameNode();return i.isIdentifier(o)?o.getText():void 0}}},it=(e,t)=>{const s=e.getBody(),r=s.getDescendantsOfKind(u.CallExpression);i.isCallExpression(s)&&r.unshift(s);for(const n of r){const o=n.getExpression();if(!i.isPropertyAccessExpression(o))continue;const a=o.getName(),c=o.getExpression();if(Zn.has(a)&&U(c,t))return a;if(Yn.has(a)&&i.isPropertyAccessExpression(c)&&c.getName()==="db"&&U(c.getExpression(),t))return`db.${a}`}},ot=(e,t)=>{const s=e.getBody();for(const r of s.getDescendantsOfKind(u.PropertyAccessExpression))if(r.getName()==="auth"&&U(r.getExpression(),t))return!0;for(const r of s.getDescendantsOfKind(u.VariableDeclaration)){const n=r.getNameNode();if(!(!i.isObjectBindingPattern(n)||!U(r.getInitializer(),t))){for(const o of n.getElements())if((o.getPropertyNameNode()?.getText()??o.getNameNode().getText())==="auth")return!0}}return!1},ei=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!Xn.has(t.getName()))return;let s=t.getExpression();for(;i.isCallExpression(s);){const r=s.getExpression();if(!i.isPropertyAccessExpression(r))return;const n=r.getName();if(Jn.has(n)){const o=r.getExpression();return i.isIdentifier(o)&&o.getText()==="httpRoute"?n.toUpperCase():void 0}s=r.getExpression()}},ti=(e,t)=>{const s=e.getExpression();if(i.isIdentifier(s)&&s.getText()==="httpAction"){const c=rt(e.getArguments()[0]),l=c&&nt(c,!0);if(!c||l===void 0)return;const p=it(c,l);return p===void 0?void 0:{exportName:h(e),file:t,kind:"httpAction",line:e.getStartLineNumber(),readsAuth:ot(c,l),sideEffect:p}}const r=ei(e);if(r===void 0)return;const n=rt(e.getArguments()[0]),o=n&&nt(n,!1);if(!n||o===void 0)return;const a=it(n,o);return a===void 0?void 0:{exportName:h(e),file:t,kind:"httpRoute",line:e.getStartLineNumber(),method:r,readsAuth:ot(n,o),sideEffect:a}},si=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=ti(r,t);n&&s.push(n)}return s},ri=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...si(n,f(t,r)))}return s},ni=new Set(["btoa","encodeURI","encodeURIComponent","isSafeHeaderValue","Number","parseFloat","parseInt"]),ii=new Set(["append","set"]),Ae=e=>i.isIdentifier(e)?e.getText():i.isPropertyAccessExpression(e)?e.getName():"",$t=e=>e!==void 0&&(i.isStringLiteral(e)||i.isNoSubstitutionTemplateLiteral(e))?e.getLiteralText():"",at=(e,t)=>(i.isCallExpression(e)?[e,...e.getDescendantsOfKind(u.CallExpression)]:e.getDescendantsOfKind(u.CallExpression)).some(s=>ni.has(Ae(s.getExpression()))&&es(s,t)),oi=(e,t)=>{if(at(e,t))return!0;const s=H(e);return s!==void 0&&at(s,t)},ye=(e,t)=>Yt(e,t)&&!oi(e,t),ai=e=>{if(i.isPropertyAccessExpression(e)&&e.getName()==="headers")return!0;const t=H(e);return t!==void 0&&i.isNewExpression(t)&&Ae(t.getExpression())==="Headers"},W=e=>{if(e===void 0)return;if(i.isObjectLiteralExpression(e))return e;const t=H(e);return t!==void 0&&i.isObjectLiteralExpression(t)?t:void 0},Se=(e,t,s)=>{for(const r of e.getProperties())if(i.isPropertyAssignment(r)){const n=r.getInitializer();n!==void 0&&ye(n,s.requestName)&&s.rows.push({exportName:s.exportName,file:s.relativePath,headerName:$t(r.getNameNode()),line:n.getStartLineNumber(),via:t})}else if(i.isShorthandPropertyAssignment(r)){const n=r.getNameNode();ye(n,s.requestName)&&s.rows.push({exportName:s.exportName,file:s.relativePath,headerName:r.getName(),line:n.getStartLineNumber(),via:t})}else if(i.isSpreadAssignment(r)){const n=W(r.getExpression());n!==void 0&&Se(n,t,s)}},At=(e,t)=>{const s=W(e);if(s===void 0)return;const r=s.getProperty("headers");if(r===void 0||!i.isPropertyAssignment(r))return;const n=W(r.getInitializer());n!==void 0&&Se(n,"response-init",t)},ci=(e,t)=>{const s=Ae(e.getExpression());if(s==="Response")At(e.getArguments()[1],t);else if(s==="Headers"){const r=W(e.getArguments()[0]);r!==void 0&&Se(r,"headers-ctor",t)}},ui=(e,t)=>{const s=e.getExpression();if(!i.isPropertyAccessExpression(s))return;const r=s.getName(),n=s.getExpression();if(r==="json"&&i.isIdentifier(n)&&n.getText()==="Response"){At(e.getArguments()[1],t);return}if(ii.has(r)&&ai(n)){const o=e.getArguments()[1];o!==void 0&&ye(o,t.requestName)&&t.rows.push({exportName:t.exportName,file:t.relativePath,headerName:$t(e.getArguments()[0]),line:o.getStartLineNumber(),via:r==="set"?"headers-set":"headers-append"})}},li=(e,t)=>{for(const s of e.getDescendantsOfKind(u.NewExpression))ci(s,t);for(const s of e.getDescendantsOfKind(u.CallExpression))ui(s,t)},di=(e,t)=>{const s=e.getExpression();if(!i.isIdentifier(s)||s.getText()!=="httpAction")return[];const r=_t(e.getArguments()[0]);if(r===void 0)return[];const n=r.getParameters()[1];if(n===void 0)return[];const o=n.getNameNode();if(!i.isIdentifier(o))return[];const a=[];return li(r,{exportName:h(e),relativePath:t,requestName:o.getText(),rows:a}),a},gi=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression))s.push(...di(r,t));return s},fi=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...gi(n,f(t,r)))}return s},St="identity.ts",pi=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineIdentity";for(const s of t.getDeclarations())if(i.isImportSpecifier(s))return Q(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineIdentity":!1;return!1},mi=e=>{const t=e.getSymbol();if(!t)return!1;for(const s of t.getDeclarations()){if(!i.isNamespaceImport(s))continue;const r=s.getFirstAncestorByKind(u.ImportDeclaration);return r!==void 0&&Q(r.getModuleSpecifierValue())}return!1},xi=e=>{if(i.isIdentifier(e))return pi(e);if(i.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineIdentity"&&i.isIdentifier(t)&&mi(t)}return!1},hi=e=>{const t=[];for(const s of e.getVariableDeclarations()){if(!s.isExported())continue;const r=s.getInitializer();if(r?.getKind()!==u.CallExpression||!xi(r.getExpression()))continue;const n=s.getNameNode();if(!i.isIdentifier(n))throw _(n,"defineIdentity exports must be plain named exports (no destructuring)");t.push({exportName:n.getText()})}return t},Ei=(e,t)=>{const s=g(t,St);if(!E(s))return;const r=e.getSourceFile(s)??e.addSourceFileAtPath(s),n=hi(r);if(n.length!==0){if(n.length>1)throw _(r,`lunora/identity.ts declares ${n.length.toString()} defineIdentity() contracts (${n.map(o=>o.exportName).join(", ")}); exactly one is allowed`);return n[0]}},yi=new Set(["auth","context.auth","ctx.auth"]),$i="userId",Ai=e=>{const t=new Set;for(const s of e.getProperties()){if(i.isSpreadAssignment(s))return;(i.isPropertyAssignment(s)||i.isShorthandPropertyAssignment(s)||i.isMethodDeclaration(s))&&t.add(s.getName())}return t},Si=(e,t)=>{const s=g(t,St);if(!E(s))return;const r=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const n of r.getDescendantsOfKind(u.CallExpression)){if(S(n.getExpression())!=="defineIdentity")continue;const[o]=n.getArguments();return o&&i.isObjectLiteralExpression(o)?Ai(o):void 0}},ct=e=>{if(!(e===void 0||!i.isPropertyAccessExpression(e)||e.getName()!=="identity"))return yi.has(e.getExpression().getText())?e:void 0},Ni=e=>{if(i.isPropertyAccessExpression(e)&&ct(e.getExpression())!==void 0)return e.getName();if(i.isElementAccessExpression(e)&&ct(e.getExpression())!==void 0){const t=e.getArgumentExpression();return t&&i.isStringLiteral(t)?t.getLiteralValue():void 0}},vi=(e,t,s)=>{const r=[];for(const n of e.getDescendants()){const o=Ni(n);o!==void 0&&r.push({declared:o===$i||s.has(o),exportName:h(n),file:t,key:o,line:n.getStartLineNumber()})}return r},bi=(e,t)=>{const s=Si(e,t);if(s===void 0)return[];const r=[];for(const n of d(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);r.push(...vi(o,f(t,n),s))}return r},Pi=e=>{if(!i.isObjectLiteralExpression(e))return;const t=e.getProperty("key");return t&&i.isPropertyAssignment(t)?t.getInitializer():void 0},wi=(e,t)=>{if(S(e.getExpression())!=="buildImageDeliveryUrl")return;const s=e.getArguments()[0];if(!s)return;const r=Pi(s);if(!(!r||!w(r)||F(r)))return{exportName:h(e),file:t,line:e.getStartLineNumber()}},Ii=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=wi(r,t);n&&s.push(n)}return s},Li=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Ii(n,f(t,r)))}return s},Oi=new Set(["delete","get","getRaw","getWithMetadata","put"]),Fi=(e,t)=>J(e,t,{argIndex:0,matchReceiver:s=>s==="ctx.kv"||s.startsWith("ctx.kv."),methods:Oi}),Ti=new Set(["queue","send"]),ut=new Set(["bcc","cc","to"]),Di=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName();if(!Ti.has(t))return;const s=e.getExpression().getText();return s==="ctx.mail"||s==="ctx.email"?t:void 0},Ci=e=>i.isObjectLiteralExpression(e)?e.getProperties().some(t=>{if(i.isShorthandPropertyAssignment(t)){const r=t.getNameNode();return ut.has(t.getName())&&w(r)&&!F(r)}if(!i.isPropertyAssignment(t)||!ut.has(t.getName()))return!1;const s=t.getInitializer();return s!==void 0&&w(s)&&!F(s)}):!1,Ki=(e,t)=>{const s=Di(e.getExpression());if(s===void 0)return;const r=e.getArguments()[0];if(!(!r||!Ci(r)))return{exportName:h(e),file:t,line:e.getStartLineNumber(),method:s}},ki=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=Ki(r,t);n&&s.push(n)}return s},Ri=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...ki(n,f(t,r)))}return s},ji=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="replace")return!1;const s=t.getExpression();return i.isPropertyAccessExpression(s)?s.getName()==="db":i.isIdentifier(s)&&s.getText()==="db"},Mi=e=>{const t=e.getArguments()[0];if(t===void 0||!i.isObjectLiteralExpression(t))return;const s=t.getProperty("server");if(s!==void 0)return i.isPropertyAssignment(s)?s.getInitializer():s},zi=e=>{if(!e.isExported())return;const t=e.getInitializer();if(t?.getKind()!==u.CallExpression)return;const s=t;return Ls(s.getExpression())?s:void 0},qi=e=>{const t=zi(e),s=t===void 0?void 0:Mi(t);if(s===void 0)return[];const r=e.getNameNode(),n=i.isIdentifier(r)?r.getText():"";return s.getDescendantsOfKind(u.CallExpression).filter(o=>ji(o)).map(o=>({exportName:n,file:"lunora/mutators.ts",line:o.getStartLineNumber()}))},Bi=e=>e.getVariableDeclarations().flatMap(t=>qi(t)),Vi=(e,t)=>{const s=g(t,Is);if(!E(s))return[];const r=e.getSourceFile(s)??e.addSourceFileAtPath(s);return Bi(r)},Ui=new Set(["delete","get","patch"]),Wi=new Set(["accountId","authorId","companyId","createdBy","createdById","customerId","groupId","memberId","organizationId","orgId","ownerId","projectId","teamId","tenantId","userId","workspaceId"]),Gi=new Set(["auth","identity","session","user"]),Hi=new Set([u.EqualsEqualsEqualsToken,u.EqualsEqualsToken,u.ExclamationEqualsEqualsToken,u.ExclamationEqualsToken]),_i=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="normalizeId"||!C(t.getExpression()))return;const s=e.getArguments()[0];return s&&i.isStringLiteral(s)?s.getLiteralText():""},Qi=e=>{let t=e,s=t.getParent();for(;s!==void 0&&(i.isAsExpression(s)||i.isParenthesizedExpression(s)||i.isNonNullExpression(s));)t=s,s=t.getParent();if(s===void 0||!i.isVariableDeclaration(s))return;const r=s.getNameNode();return i.isIdentifier(r)?r.getText():void 0},Ji=(e,t)=>e.getDescendantsOfKind(u.Identifier).some(s=>s.getText()===t),Xi=e=>i.isThrowStatement(e)||i.isReturnStatement(e)||e.getDescendantsOfKind(u.ThrowStatement).length>0||e.getDescendantsOfKind(u.ReturnStatement).length>0,Zi=(e,t)=>e.getDescendantsOfKind(u.IfStatement).some(s=>Ji(s.getExpression(),t)&&Xi(s.getThenStatement())),Yi=(e,t)=>{for(const s of e.getDescendantsOfKind(u.CallExpression)){const r=s.getExpression();if(!i.isPropertyAccessExpression(r))continue;const n=r.getName();if(!Ui.has(n))continue;const o=r.getExpression();if(!(C(o)||i.isPropertyAccessExpression(o)&&C(o.getExpression())))continue;const a=s.getArguments()[0];if(a!==void 0&&i.isIdentifier(a)&&a.getText()===t)return n}},eo=e=>{let t=e;for(;i.isPropertyAccessExpression(t)||i.isElementAccessExpression(t)||i.isNonNullExpression(t)||i.isParenthesizedExpression(t)||i.isAsExpression(t)||i.isAwaitExpression(t);)t=t.getExpression();return i.isIdentifier(t)?t.getText():void 0},to=e=>e.getDescendantsOfKind(u.CallExpression).some(t=>t.getArguments().some(s=>eo(s)==="ctx")),so=e=>e.getDescendantsOfKind(u.BinaryExpression).some(t=>Hi.has(t.getOperatorToken().getKind())?i.isPropertyAccessExpression(t.getLeft())||i.isPropertyAccessExpression(t.getRight()):!1),ro=e=>{for(const t of e.getDescendantsOfKind(u.Identifier))if(Wi.has(t.getText()))return!0;for(const t of e.getDescendantsOfKind(u.PropertyAccessExpression)){const s=t.getExpression();if(i.isIdentifier(s)&&s.getText()==="ctx"&&Gi.has(t.getName()))return!0}return to(e)||so(e)},no=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!i.isCallExpression(s))return[];const r=K(s);if(r?.kind!=="query"&&r?.kind!=="mutation")return[];const n=pt(s);if(n===void 0)return[];const o=r.receiver!==void 0&&mt(r.receiver,"use","rls"),a=ro(n),c=new Set,l=[];for(const p of n.getDescendantsOfKind(u.CallExpression)){const y=_i(p);if(y===void 0)continue;const I=Qi(p);if(I===void 0||c.has(I)||!Zi(n,I))continue;const k=Yi(n,I);k!==void 0&&(c.add(I),l.push({exportName:e.getName(),file:t,line:p.getStartLineNumber(),mentionsOwnership:a,sinkMethod:k,table:y,usesRls:o,visibility:r.visibility}))}return l},io=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r),o=f(t,r);for(const a of n.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...no(c,o))}return s},oo=new Set(["accountId","authorId","createdBy","createdById","organizationId","orgId","ownerId","tenantId","updatedBy","userId","workspaceId"]),ao=new Set(["insert","insertManyUnsafe","patch","replace"]),co=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName();if(!ao.has(t))return;const s=e.getExpression();if(!i.isPropertyAccessExpression(s)||s.getName()!=="db")return;const r=s.getExpression();return i.isIdentifier(r)&&r.getText()==="ctx"?t:void 0},uo=(e,t)=>{if(t!=="insertManyUnsafe")return i.isObjectLiteralExpression(e)?[e]:[];if(!i.isArrayLiteralExpression(e))return[];const s=[];for(const r of e.getElements())i.isObjectLiteralExpression(r)&&s.push(r);return s},lo=(e,t,s,r)=>{const n=[];for(const o of e.getProperties()){let a,c;i.isPropertyAssignment(o)?(a=o.getName(),c=o.getInitializer()):i.isShorthandPropertyAssignment(o)&&(a=o.getName(),c=o.getNameNode()),!(a===void 0||c===void 0||!oo.has(a))&&w(c)&&!F(c)&&n.push({exportName:h(s),field:a,file:r,line:s.getStartLineNumber(),method:t})}return n},go=(e,t)=>{const s=co(e.getExpression());if(s===void 0)return[];const r=e.getArguments()[1];return r?uo(r,s).flatMap(n=>lo(n,s,e,t)):[]},fo=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression))s.push(...go(r,t));return s},po=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...fo(n,f(t,r)))}return s},mo=e=>{const t=g(e,"package.json");if(!E(t))return new Set;try{const s=JSON.parse($e(t,"utf8")),r=new Set;for(const n of["dependencies","devDependencies","peerDependencies","optionalDependencies"]){const o=s[n];if(o!==null&&typeof o=="object")for(const a of Object.keys(o))r.add(a)}return r}catch{return new Set}},xo=new Set(["createAutumnAdapter","createDodoPaymentsAdapter","createPolarAdapter","createStripeAdapter"]),ho=e=>e&&i.isNumericLiteral(e)?Number(e.getText()):void 0,Eo=e=>{const t=e.getProperty("webhookToleranceSeconds");return t&&i.isPropertyAssignment(t)?ho(t.getInitializer()):void 0},yo=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=S(r.getExpression());if(n===void 0||!xo.has(n))continue;const[o]=r.getArguments(),a=o&&i.isObjectLiteralExpression(o)?Eo(o):void 0;s.push({callee:n,exportName:h(r),file:t,line:r.getStartLineNumber(),...a===void 0?{}:{toleranceSeconds:a}})}return s},$o=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...yo(n,f(t,r)))}return s},Ao=new Set(["defineQueue","defineWorkflow"]),So=new Set(["run","runAction","runMutation","runQuery"]),No=new Set(["api","internal"]),vo=e=>{const t=e.getExpression();return i.isIdentifier(t)?t.getText():void 0},bo=e=>{const t=e.getArguments()[0];if(!t||!i.isObjectLiteralExpression(t))return;const s=t.getProperty("handler");if(s===void 0||!i.isPropertyAssignment(s))return;const r=s.getInitializer();if(r&&(i.isArrowFunction(r)||i.isFunctionExpression(r)))return r},Nt=(e,t)=>{const s=e.getParameters()[t]?.getNameNode();return s&&i.isIdentifier(s)?s.getText():void 0},vt=(e,t)=>e===t||e.startsWith(`${t}.`),bt=e=>{const t=e.getDescendantsOfKind(u.PropertyAccessExpression);return i.isPropertyAccessExpression(e)&&t.push(e),t},lt=e=>{const t=e.getParent();return i.isPropertyAccessExpression(t)&&t.getNameNode()===e||i.isPropertyAssignment(t)&&t.getNameNode()===e?!1:!(i.isBindingElement(t)&&t.getNameNode()===e)},Pt=e=>{const t=e.getDescendantsOfKind(u.Identifier).filter(s=>lt(s));return i.isIdentifier(e)&&lt(e)&&t.push(e),t},Po=e=>{if(!i.isVariableDeclaration(e))return[];const t=e.getNameNode();return i.isIdentifier(t)?[t.getText()]:t.getDescendantsOfKind(u.BindingElement).map(s=>s.getName())},wo=e=>{const t=Nt(e,1);if(t===void 0)return[];const s=[`${t}.messages`];for(const r of e.getDescendantsOfKind(u.ForOfStatement)){if(r.getExpression().getText()!==`${t}.messages`)continue;const n=r.getInitializer(),o=i.isVariableDeclarationList(n)?n.getDeclarations()[0]?.getNameNode():void 0;o&&i.isIdentifier(o)&&s.push(`${o.getText()}.body`)}return s},Io=(e,t,s)=>{const r=t==="workflow"?[`${s}.params`]:wo(e),n=new Set,o=a=>bt(a).some(c=>r.some(l=>vt(c.getText(),l)))?!0:Pt(a).some(c=>n.has(c.getText()));for(const a of e.getDescendantsOfKind(u.VariableDeclaration)){const c=a.getInitializer();if(c&&o(c))for(const l of Po(a))n.add(l)}return{names:n,prefixes:r}},Lo=(e,t)=>bt(e).some(s=>t.prefixes.some(r=>vt(s.getText(),r)))?!0:Pt(e).some(s=>t.names.has(s.getText())),Oo=e=>{if(e===void 0||!i.isPropertyAccessExpression(e))return;const t=[];let s=e;for(;i.isPropertyAccessExpression(s);)t.unshift(s.getName()),s=s.getExpression();const r=t.at(-1);if(!(r===void 0||!i.isIdentifier(s)||!No.has(s.getText())||t.length<2))return{exportName:r,file:t.slice(0,-1).join("/")}},Fo=(e,t,s)=>{const r=Nt(e,0);if(r===void 0)return[];const n=Io(e,t,r),o=[];for(const a of e.getDescendantsOfKind(u.CallExpression)){const c=a.getExpression();if(!i.isPropertyAccessExpression(c)||!So.has(c.getName())||c.getExpression().getText()!==r)continue;const l=a.getArguments()[1];if(!l||!Lo(l,n))continue;const p=Oo(a.getArguments()[0]);p!==void 0&&o.push({dispatchKind:t,file:s,handlerExport:h(a),line:a.getStartLineNumber(),targetExport:p.exportName,targetFile:p.file})}return o},To=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=vo(r);if(n===void 0||!Ao.has(n))continue;const o=bo(r);o!==void 0&&s.push(...Fo(o,n==="defineQueue"?"queue":"workflow",t))}return s},Do=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...To(n,f(t,r)))}return s},dt={dbRateLimit:"usesRateLimit",emailGateMiddleware:"usesEmailGate",mask:"usesMask",rateLimit:"usesRateLimit",rls:"usesRls",verifyTurnstile:"usesCaptcha",verifyTurnstileMiddleware:"usesCaptcha"},Co=/account|credential|member|passkey|session|user/iu,Ko=e=>{const t=e.replaceAll(/[^a-z0-9]/giu,"").toLowerCase();return t.endsWith("email")||t.endsWith("emailaddress")},ko=(e,t)=>{const{objects:s,opaque:r}=Et(e,t);return Ir(s).some(n=>Ko(n))?!0:r?void 0:!1},Ne=e=>{const t=e.getExpression();if(i.isIdentifier(t))return t.getText();if(i.isPropertyAccessExpression(t))return t.getName()},Ro=e=>{const t=e.getArguments()[0];return!t||!i.isObjectLiteralExpression(t)?{usesCaptcha:!1,usesRateLimit:!1}:{usesCaptcha:!!t.getProperty("captcha"),usesRateLimit:!!t.getProperty("rateLimit")}},jo=e=>{if(i.isCallExpression(e))return e;if(!i.isIdentifier(e))return;const t=e.getSourceFile().getVariableDeclaration(e.getText())?.getInitializer();return t&&i.isCallExpression(t)?t:void 0},V={usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},Mo=e=>{const t=jo(e),s=t?Ne(t):void 0;if(t&&s==="protectPublic"){const r=Ro(t);return{...V,usesCaptcha:r.usesCaptcha,usesRateLimit:r.usesRateLimit}}return s!==void 0&&s in dt?{...V,[dt[s]]:!0}:V},zo=e=>{const t={...V};let s=e;for(;i.isCallExpression(s);){const r=s.getExpression();if(!i.isPropertyAccessExpression(r))break;const n=r.getName()==="use"?s.getArguments()[0]:void 0;if(n){const o=Mo(n);t.usesCaptcha||=o.usesCaptcha,t.usesEmailGate||=o.usesEmailGate,t.usesMask||=o.usesMask,t.usesRateLimit||=o.usesRateLimit,t.usesRls||=o.usesRls}s=r.getExpression()}return t},qo=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="insert")return!1;const s=t.getExpression();if(!(i.isPropertyAccessExpression(s)?s.getName()==="db":i.isIdentifier(s)&&s.getText()==="db"))return!1;const r=e.getArguments()[0];return!!(r&&i.isStringLiteral(r)&&Co.test(r.getLiteralText()))},Bo=new Set(["create","runAfter","runAt","send","sendBatch"]),Vo=new Set(["queues","scheduler","workflows"]),Uo=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!Bo.has(t.getName()))return!1;let s=t.getExpression();for(;i.isCallExpression(s)||i.isElementAccessExpression(s)||i.isPropertyAccessExpression(s);){if(i.isPropertyAccessExpression(s)&&Vo.has(s.getName())){const r=s.getExpression();if(i.isIdentifier(r)&&r.getText()==="ctx")return!0}s=s.getExpression()}return!1},Wo=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="insertManyUnsafe")return!1;const s=t.getExpression();return i.isPropertyAccessExpression(s)?s.getName()==="db":i.isIdentifier(s)&&s.getText()==="db"},wt=new Set(["generateObject","generateText","streamObject","streamText"]),Go=e=>{const t=Ne(e);return t!==void 0&&wt.has(t)},Ho=e=>{const t=Ne(e);if(t===void 0||!wt.has(t))return!1;const s=e.getArguments()[0];return!s||!i.isObjectLiteralExpression(s)||s.getProperties().some(r=>i.isSpreadAssignment(r))?!1:!s.getProperty("maxOutputTokens")},_o=new Set(["log","span","trace"]),Qo=new Set(["ai"]),Jo=new Set(["email","mail"]),Xo=new Set(["ai","browser","fetch","mail","notify","queues","sql","storage","workflows"]),q=(e,t)=>e.getDescendantsOfKind(u.PropertyAccessExpression).some(s=>{if(!t.has(s.getName()))return!1;const r=s.getExpression();return i.isIdentifier(r)&&r.getText()==="ctx"}),Zo=e=>e.getDescendantsOfKind(u.ThrowStatement).some(t=>{const s=t.getExpression();if(!i.isNewExpression(s))return!1;const r=s.getExpression();return i.isIdentifier(r)&&r.getText()==="Error"}),gt="lunora-advisor-exempt",Yo=/^[\s*/]+/u,ea=/[\w-]/u,ta=e=>{const t=(e.getFirstAncestorByKind(u.VariableStatement)??e).getLeadingCommentRanges().map(s=>s.getText()).join(`
2
+ `);for(const s of t.split(`
3
+ `)){const r=s.replace(Yo,"");if(!r.startsWith(gt))continue;const n=r.slice(gt.length);if(ea.test(n.charAt(0)))continue;const o=n.indexOf("--");return{exempt:!0,exemptReason:(o===-1?"":n.slice(o+2).split("*")[0]??"").trim()}}return{exempt:!1,exemptReason:""}},sa=e=>{let t=!1,s=!1,r=!1,n=!1,o=!1;for(const a of e.getDescendantsOfKind(u.CallExpression))if(qo(a)&&(o=!0),Uo(a)&&(t=!0),Wo(a)&&(n=!0),Go(a)&&(s=!0),Ho(a)&&(r=!0),o&&t&&n&&r)break;return{callsMail:q(e,Jo),emitsEvent:q(e,_o),fanOut:t,handlesErrors:e.getDescendantsOfKind(u.TryStatement).length>0,reachesOutbound:q(e,Xo),runsAiGeneration:s||q(e,Qo),throwsBareError:Zo(e),unboundedAiGeneration:r,usesInsertManyUnsafe:n,writesUserTable:o}},ra=(e,t)=>{const s=e.getInitializer();if(!s||!i.isCallExpression(s))return;const r=K(s);if(!r||r.kind!=="query"&&r.kind!=="mutation"&&r.kind!=="action")return;const n=r.receiver?zo(r.receiver):{usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1};return{...sa(e),...ta(e),...n,exportName:e.getName(),file:t,hasEmailArg:ko(s,r.receiver),kind:r.kind,visibility:r.visibility}},na=(e,t)=>{const s=[];for(const r of e.getVariableStatements())if(r.isExported())for(const n of r.getDeclarations()){const o=ra(n,t);o&&s.push(o)}return s},ia=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...na(n,f(t,r)))}return s},oa=new Set(["dbRateLimit","rateLimit"]),aa=e=>{if(!i.isObjectLiteralExpression(e))return;const t=e.getProperty("key");return t&&i.isPropertyAssignment(t)?t.getInitializer():void 0},ca=e=>{const t=e.getArguments()[1];return t&&i.isStringLiteral(t)?t.getLiteralValue():""},ua=e=>i.isArrowFunction(e)?e.getBody():e,la=(e,t)=>{const s=S(e.getExpression());if(s===void 0||!oa.has(s))return;const r=e.getArguments()[2];if(!r)return;const n=aa(r);if(!n)return;const o=ua(n);if(!(!w(o)||F(o)))return{callee:s,exportName:h(e),file:t,limitName:ca(e),line:e.getStartLineNumber()}},da=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=la(r,t);n&&s.push(n)}return s},ga=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...da(n,f(t,r)))}return s},fa=new Set(["findFirst","findFirstOrThrow","findMany","get"]),pa=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!fa.has(t.getName()))return;const s=t.getExpression();if(C(s)){const r=e.getArguments()[0];return r&&i.isStringLiteral(r)?r.getLiteralText():""}if(i.isPropertyAccessExpression(s)&&C(s.getExpression()))return s.getName()},ma=e=>{let t=e;for(;i.isCallExpression(t);){const s=t.getExpression();if(!i.isPropertyAccessExpression(s))return;if(s.getName()==="query"&&C(s.getExpression())){const r=t.getArguments()[0];return r&&i.isStringLiteral(r)?r.getLiteralText():""}t=s.getExpression()}},xa=e=>{let t=e;for(;i.isAwaitExpression(t)||i.isParenthesizedExpression(t)||i.isNonNullExpression(t)||i.isAsExpression(t);)t=t.getExpression();return t},It=(e,t=!1)=>{const s=xa(e);if(i.isIdentifier(s)){if(t)return;const r=H(s);return r===void 0?void 0:It(r,!0)}if(i.isCallExpression(s))return pa(s)??ma(s)},ha=e=>{const t=e.getBody();if(!i.isBlock(t))return[t];const s=[];for(const r of e.getDescendantsOfKind(u.ReturnStatement)){const n=r.getFirstAncestor(a=>i.isArrowFunction(a)||i.isFunctionExpression(a)||i.isFunctionDeclaration(a)),o=r.getExpression();n===e&&o!==void 0&&s.push(o)}return s},Ea=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!i.isCallExpression(s))return[];const r=K(s);if(r?.kind!=="query")return[];const n=pt(s);if(n===void 0)return[];const o=r.receiver!==void 0&&Qt(r.receiver,"output"),a=r.receiver!==void 0&&mt(r.receiver,"use","mask"),c=new Set,l=[];for(const p of ha(n)){const y=It(p);y===void 0||c.has(y)||(c.add(y),l.push({exportName:e.getName(),file:t,line:p.getStartLineNumber(),table:y,usesMask:a,usesOutput:o,visibility:r.visibility}))}return l},ya=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r),o=f(t,r);for(const a of n.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...Ea(c,o))}return s},$a=new Set(["findFirst","findFirstOrThrow","findMany"]),Aa=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!$a.has(t.getName()))return;const s=t.getExpression();if(i.isPropertyAccessExpression(s)&&s.getName()==="db"||i.isIdentifier(s)&&s.getText()==="db"){const r=e.getArguments()[0];return{options:e.getArguments()[1],table:r&&i.isStringLiteral(r)?r.getLiteralText():""}}if(i.isPropertyAccessExpression(s)){const r=s.getExpression();if(i.isPropertyAccessExpression(r)&&r.getName()==="db"||i.isIdentifier(r)&&r.getText()==="db")return{options:e.getArguments()[0],table:s.getName()}}},Sa=e=>{if(!e||!i.isObjectLiteralExpression(e))return[];const t=[];for(const s of e.getProperties())(i.isPropertyAssignment(s)||i.isShorthandPropertyAssignment(s)||i.isMethodDeclaration(s)||i.isGetAccessorDeclaration(s))&&t.push(s.getName());return t},Na=(e,t)=>{if(!e||!i.isObjectLiteralExpression(e))return;const s=e.getProperty(t);return s&&i.isPropertyAssignment(s)?s.getInitializer():void 0},va=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer(),r=s&&i.isCallExpression(s)?K(s):void 0;if(!r)return[];const n=[];for(const o of e.getDescendantsOfKind(u.CallExpression)){const a=Aa(o);if(a===void 0)continue;const c=Sa(Na(a.options,"with"));c.length!==0&&n.push({exportName:e.getName(),file:t,line:o.getStartLineNumber(),parentTable:a.table,relations:c,visibility:r.visibility})}return n},ba=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r),o=f(t,r);for(const a of n.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...va(c,o))}return s},G=e=>{if(i.isStringLiteral(e)||i.isNoSubstitutionTemplateLiteral(e))return e.getLiteralText();if(i.isBinaryExpression(e)&&e.getOperatorToken().getKind()===u.PlusToken){const t=G(e.getLeft()),s=G(e.getRight());return t!==void 0&&s!==void 0?t+s:void 0}},Pa=e=>{let t=e,s=t.getParent();for(;s!==void 0&&i.isBinaryExpression(s)&&s.getOperatorToken().getKind()===u.PlusToken;)t=s,s=t.getParent();return t!==e&&G(t)!==void 0},wa=(e,t)=>{const s=[],r=[...e.getDescendantsOfKind(u.BinaryExpression),...e.getDescendantsOfKind(u.StringLiteral),...e.getDescendantsOfKind(u.NoSubstitutionTemplateLiteral)],n=new Set;for(const o of r){if(Pa(o))continue;const a=G(o);if(a===void 0)continue;const c=zs(a);if(c===void 0)continue;const l=o.getStartLineNumber(),p=`${String(l)}:${c}`;n.has(p)||(n.add(p),s.push({file:t,kind:c,line:l,preview:qs(a)}))}return s},Ia=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...wa(n,f(t,r)))}return s},La=new Set(["findFirst","findFirstOrThrow","findMany"]),Oa=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!La.has(t.getName()))return;const s=t.getExpression();if(i.isPropertyAccessExpression(s)&&s.getName()==="db"||i.isIdentifier(s)&&s.getText()==="db"){const r=e.getArguments()[0];return{options:e.getArguments()[1],table:r&&i.isStringLiteral(r)?r.getLiteralText():""}}if(i.isPropertyAccessExpression(s)){const r=s.getExpression();if(i.isPropertyAccessExpression(r)&&r.getName()==="db"||i.isIdentifier(r)&&r.getText()==="db")return{options:e.getArguments()[0],table:s.getName()}}},Fa=(e,t)=>{if(!e||!i.isObjectLiteralExpression(e))return;const s=e.getProperty(t);return s&&i.isPropertyAssignment(s)?s.getInitializer():void 0},Ta=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer(),r=s&&i.isCallExpression(s)?K(s):void 0;if(!r)return[];const n=[];for(const o of e.getDescendantsOfKind(u.CallExpression)){const a=Oa(o);if(a===void 0)continue;const c=Fa(a.options,"includeDeleted");if(c===void 0)continue;const l=i.isTrueLiteral(c),p=!l&&w(c);!l&&!p||n.push({exportName:e.getName(),file:t,fromArgs:p,hardcodedTrue:l,line:o.getStartLineNumber(),table:a.table,visibility:r.visibility})}return n},Da=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r),o=f(t,r);for(const a of n.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...Ta(c,o))}return s},Ca=new Set(["query","unsafe"]),Ka=e=>{if(!i.isPropertyAccessExpression(e)||!Ca.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"},ka=e=>i.isBinaryExpression(e)||i.isTemplateExpression(e),Ra=e=>e.getFirstAncestorByKind(u.VariableDeclaration)?.getName()??"<module>",ja=(e,t)=>{if(!Ka(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!ka(s)))return{exportName:Ra(e),file:t,line:s.getStartLineNumber()}},Ma=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=ja(r,t);n&&s.push(n)}return s},za=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Ma(n,f(t,r)))}return s},qa=new Set(["createMultipartUpload","delete","download","generateUploadUrl","get","getMetadata","getPresignedUrl","getSignedUrl","getUrl","head","put","resumeMultipartUpload","store","upload"]),Ba=(e,t)=>J(e,t,{argIndex:0,matchReceiver:s=>s==="ctx.storage"||s.startsWith("ctx.storage."),methods:qa}),Va=new Map([["generateUploadUrl",1],["getPresignedUrl",1],["getSignedUrl",1],["store",2],["upload",2]]),Ua=e=>e&&i.isNumericLiteral(e)?Number(e.getText()):void 0,Wa=e=>{if(e===void 0)return{analyzable:!0,presentKeys:[]};if(!i.isObjectLiteralExpression(e))return{analyzable:!1,presentKeys:[]};const t=[];let s,r=!1;for(const n of e.getProperties()){if(i.isSpreadAssignment(n)){r=!0;continue}if(i.isPropertyAssignment(n)){const o=n.getName();t.push(o),o==="expiresInSeconds"&&(s=Ua(n.getInitializer()));continue}(i.isShorthandPropertyAssignment(n)||i.isMethodDeclaration(n))&&t.push(n.getName())}return{analyzable:!r,expiresInSeconds:s,presentKeys:t}},Ga=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName(),s=Va.get(t);if(s===void 0)return;const r=e.getExpression().getText();return r==="ctx.storage"||r.startsWith("ctx.storage.")?{method:t,optionsIndex:s}:void 0},Ha=(e,t)=>{const s=Ga(e.getExpression());if(s!==void 0)return{exportName:h(e),file:t,line:e.getStartLineNumber(),method:s.method,...Wa(e.getArguments()[s.optionsIndex])}},_a=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=Ha(r,t);n&&s.push(n)}return s},Qa=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(..._a(n,f(t,r)))}return s},Ja=new Set(["when","where"]),Ee=new Set(["definePolicy","defineShape"]),Xa=e=>{if(!i.isCallExpression(e))return;const t=e.getExpression();if(i.isPropertyAccessExpression(t)){const r=t.getName();return Ee.has(r)?r:void 0}if(!i.isIdentifier(t))return;for(const r of t.getSymbol()?.getDeclarations()??[])if(i.isImportSpecifier(r)){const n=r.getNameNode().getText();return Ee.has(n)?n:void 0}const s=t.getText();return Ee.has(s)?s:void 0},Za=e=>i.isObjectLiteralExpression(e)&&e.getProperties().length===0,Lt=e=>{if(e!==void 0){if(i.isReturnStatement(e)&&e.getExpression()===void 0||e.getKind()===u.UndefinedKeyword||e.getText()==="undefined")return"undefined";if(Za(e))return"empty-object";if(i.isParenthesizedExpression(e))return Lt(e.getExpression())}},Ot=e=>e.getAncestors().find(t=>i.isArrowFunction(t)||i.isFunctionExpression(t)||i.isFunctionDeclaration(t)),Ft=e=>e.getDescendantsOfKind(u.ReturnStatement).filter(t=>Ot(t)===e),Tt=e=>e.getDescendantsOfKind(u.ConditionalExpression).filter(t=>Ot(t)===e),Ya=e=>{const t=Ft(e);return t.length>1?!0:t.some(s=>s.getFirstAncestorByKind(u.IfStatement)!==void 0)||Tt(e).length>0},ec=e=>{const t=[],s=e.getBody();i.isBlock(s)||t.push(s);for(const r of Ft(e)){const n=i.isReturnStatement(r)?r.getExpression():void 0;t.push(n??r)}for(const r of Tt(e))t.push(r.getWhenTrue(),r.getWhenFalse());return t},tc=e=>{for(const t of e.getAncestors())if(i.isVariableDeclaration(t)){const s=t.getNameNode();if(i.isIdentifier(s))return s.getText()}return"<anonymous>"},sc=(e,t,s)=>{if(!i.isCallExpression(e))return[];const[r]=e.getArguments();if(!r||!i.isObjectLiteralExpression(r))return[];const n=[];for(const o of r.getProperties()){if(!i.isPropertyAssignment(o)||!Ja.has(o.getName()))continue;const a=o.getInitializer();if(!(!a||!(i.isArrowFunction(a)||i.isFunctionExpression(a)))&&Ya(a))for(const c of ec(a)){const l=Lt(c);l!==void 0&&n.push({exportName:tc(e),file:s,form:l,key:o.getName(),line:c.getStartLineNumber(),owner:t})}}return n},rc=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=Xa(r);n!==void 0&&s.push(...sc(r,n,t))}return s},nc=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...rc(n,f(t,r)))}return s},ic=new Set(["query","upsert","upsertMany"]),oc=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName();if(ic.has(t))return e.getExpression().getText()==="ctx.vectors"?t:void 0},ac=e=>{if(!i.isObjectLiteralExpression(e))return;const t=e.getProperty("namespace");return t&&i.isPropertyAssignment(t)?t.getInitializer():void 0},cc=(e,t)=>{const s=oc(e.getExpression());if(s===void 0)return;const r=e.getArguments()[1];if(!r)return;const n=ac(r);if(!(!n||!w(n)||F(n)))return{exportName:h(e),file:t,line:e.getStartLineNumber(),method:s}},uc=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=cc(r,t);n&&s.push(n)}return s},lc=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...uc(n,f(t,r)))}return s},dc=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"},gc=e=>{const t=e.getArguments()[0];return t&&i.isStringLiteral(t)?t.getLiteralText():""},fc=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r),o=f(t,r);for(const a of n.getDescendantsOfKind(u.CallExpression)){if(!dc(a))continue;const c=Us(a);c!==""&&s.push({exportName:c,file:o,line:a.getStartLineNumber(),workflow:gc(a)})}}return s},pc=".lunora-schema.json",A=(e,t)=>{E(e)&&$e(e,"utf8")===t||Vt(e,t,"utf8")},P=(e,t)=>{if(t===""){Ut(e,{force:!0});return}A(e,t)},mc=e=>{const t=g(e,"package.json");if(E(t))try{const s=JSON.parse($e(t,"utf8"));return typeof s.version=="string"&&s.version!==""?s.version:void 0}catch{return}},xc=()=>{const e=process.env.LUNORA_CODEGEN_TIMING;return e!==void 0&&e!==""},hc=e=>{let t=E(e)?e:pe(e);for(;t&&t!==pe(t);){const s=g(t,"tsconfig.json");if(E(s))return s;t=pe(t)}},ft=e=>e.replaceAll("\\","/"),Ec=(e,t)=>{const s=new Map,r=new Map,n=new Map;for(const o of e)s.set(o.name,`workflow "${o.exportName}"`),r.set(o.bindingName,`workflow "${o.exportName}"`),n.set(o.className,`workflow "${o.exportName}"`);for(const o of t){const a=s.get(o.name);if(a!==void 0)throw new B("DUPLICATE_WORKFLOW_NAME",`Duplicate deployed name "${o.name}": produced by both ${a} and agent "${o.exportName}". Workflow and agent names share the same wrangler workflows[] array and must be unique together.`,{status:500});const c=r.get(o.bindingName);if(c!==void 0)throw new B("DUPLICATE_WORKFLOW_BINDING",`Duplicate binding "${o.bindingName}": produced by both ${c} and agent "${o.exportName}". Workflow and agent bindings share the same wrangler workflows[] array and must be unique together.`,{status:500});const l=n.get(o.className);if(l!==void 0)throw new B("DUPLICATE_WORKFLOW_CLASS",`Duplicate generated class "${o.className}": produced by both ${l} and agent "${o.exportName}". Workflow and agent export names must yield unique generated class names.`,{status:500})}},yc=e=>{const t=hc(e);return t?new Ze({skipAddingFilesFromTsConfig:!1,tsConfigFilePath:t,useInMemoryFileSystem:!1}):new Ze({skipAddingFilesFromTsConfig:!0,useInMemoryFileSystem:!1})},ou=(e,t)=>{const s=d(t),r=g(t,"schema.ts");E(r)&&s.push(r);for(const c of s){const l=e.getSourceFile(c);l===void 0?e.addSourceFileAtPath(c):l.refreshFromFileSystemSync()}const n=new Set(s.map(c=>ft(c))),o=ft(t),a=`${o}/`;for(const c of e.getSourceFiles()){const l=c.getFilePath();(l===o||l.startsWith(a))&&!n.has(l)&&e.removeSourceFile(c)}},au=e=>{const t=xc(),s=t?me.now():0,r=g(e.projectRoot,e.lunoraDirectory??"lunora"),n=g(r,"schema.ts");if(!E(n))throw new B("INTERNAL",`schema.ts not found at ${n}`);const o=e.project??yc(r),a=Ms(o,n,e.projectRoot),c=Jt(o,r),l=Ss(o,r),p=ws(o,r),y=Bs(o,r),I=Os(o,r),k=Ei(o,r),ve=Nn(o,r),v=Ws(o,r),T=Cs(o,r),b=Xt(o,r);Ec(v,b);const X=ns(o,r,v,b),D=rs(o,r),R=e.lint===!1?void 0:Ht({adminRoutes:ar(o,r),aiRawRuns:dr(o,r),aiToolSideEffects:Ar(o,r),argumentDerivedFetches:br(o,r),argumentValidators:Rr(o,r),authApiCalls:ss(o,r),authConfigs:_r(o,r),browserUrlAccesses:Yr(o,r),configCalls:cn(o,r),containerKeyAccesses:ln(o,r),containerOverrides:hn(o,r),containers:D,exportSinks:wn(o,r),failOpenGuards:Cn(o,r),flagSecurityDefaults:Gn(o,r),geoIndexUsages:Qn(o,r),httpActionGuards:ri(o,r),httpHeaderWrites:fi(o,r),identityClaimReads:bi(o,r),imageDeliveryUrlAccesses:Li(o,r),inserts:Ns(o,r),kvKeyAccesses:Fi(o,r),mailRecipientAccesses:Ri(o,r),maskProcedures:vs(o,r),maskStrategies:bs(o,r),mutatorWrites:Vi(o,r),nondeterministicCalls:Fs(o,r),normalizeIdAuthorizations:io(o,r),notifyCalls:Ds(o,r),notifyConfig:Ts(o,r),ownerFieldWrites:po(o,r),unrestrictedWhereBranches:nc(o,r),paymentWebhooks:$o(o,r),privilegedDispatches:Do(o,r),procedureProtections:ia(o,r),queries:ts(o,r),queues:T,r2sqlCalls:Ks(o,r),ratelimitKeySelectors:ga(o,r),rawRowReturns:ya(o,r),relationLoads:ba(o,r),rlsProcedures:ks(o,r),schema:a,secretLiterals:Ia(o,r),shapes:y,softDeleteReads:Da(o,r),sqlInterpolations:za(o,r),storageKeyAccesses:Ba(o,r),storageUploads:Qa(o,r),vectorNamespaceAccesses:lc(o,r),workflowCalls:fc(o,r),workflows:v,wranglerVariables:e.wranglerVariables}),be=R===void 0?[]:Wt(R,{source:"static"}),Dt=Rs(o,r),Ct=Ps(o,r),Z=Vs(o,r),Kt=kn(o,r),Pe=Xs(Kt,Zs(e.projectRoot,e.target)),$=Pe.usage,Y=$.ai,ee=$.payments,we=$.kv,Ie=$.access,te=E(g(r,"flags.ts")),kt=te?As(o,r):[],se=E(g(r,"notify.ts")),re=$.hyperdrive,ne=js(o,r),Rt=ne.usesSandboxBrowser||ne.usesSandboxContainer,ie=$.browser||ne.usesSandboxBrowser,oe=$.images,ae=$.analytics,Le=$.pipelines,ce=$.r2sql,ue=$.x402,L=mo(e.projectRoot),j=zn($,{containerCount:D.length,cronCount:X.length,dependencies:L,hasPaymentTables:Mn(a.tables),queueCount:T.length,storageColumnCount:Object.keys(is(a)).length,storageRuleCount:Z.rules.length,vectorIndexCount:a.vectorIndexes.length,workflowCount:v.length}),O=L.has("lunorash"),Oe=t?me.now():0,Fe=os(a,O),Te=as({agents:b,functions:c,httpRoutes:l,mutators:I,useUmbrella:O,workflows:v}),De=cs({agents:b,containers:D,env:ve,hasAccessFacade:Ie,hasAi:Y,hasAnalytics:ae,hasBrowser:ie,hasFlags:te,hasHyperdrive:re,hasImages:oe,hasKv:we,hasNotify:se,hasPayments:ee,hasPipelines:Le,hasR2sql:ce,hasX402:ue,identity:k,queues:T,schema:a,storageRuleBuckets:Z.rules.map(m=>m.bucket),useUmbrella:O,workflows:v}),Ce=us({agents:b,functions:c,migrations:p,mutators:I,shapes:y,useUmbrella:O,usesSandbox:Rt}),le=Ys(a,p.map(m=>m.id)),Ke=ls({advisories:be,advisorProcedures:R?.procedureProtections??[],agents:b,containers:D,env:ve,flagKeys:kt,hasAccessFacade:Ie,hasAi:Y,hasAnalytics:ae,hasBrowser:ie,hasFlags:te,hasHyperdrive:re,hasImages:oe,hasKv:we,hasNotify:se,hasPayments:ee,hasPipelines:Le,hasR2sql:ce,hasX402:ue,maskMetadata:Ct,mutators:I,queues:T,rlsMetadata:Dt,schema:a,schemaSnapshot:le,shapes:y,storageRules:Z,studioFeatures:j,useUmbrella:O,workflows:v}),ke=ds(y,L.has("@lunora/db"),O),Re=gs(D,a.jurisdiction),je=fs(v),Me=ps(b),ze=ms(T),qe=xs(X),Be=hs(a.vectorIndexes),M=Es(a,O),Ve=ys(L.has("@lunora/seed")),z=e.apiSpec??"openapi",de=z==="openapi"||z==="both",ge=z==="openrpc"||z==="both",Ue=Gs({emailAgents:b.filter(m=>m.onEmail===!0).map(m=>({bindingName:m.bindingName,exportName:m.exportName})),hasAccess:L.has("@lunora/cloudflare-access"),hasAi:Y,hasAnalytics:ae,hasAuth:L.has("@lunora/auth"),hasBrowser:ie,hasFramework:L.has("@lunora/astro")||L.has("@lunora/svelte")||L.has("@lunora/vue"),hasGlobal:a.tables.some(m=>m.shardMode==="global"&&m.globalBackend!=="hyperdrive"),hasHyperdrive:re,hasHyperdriveGlobal:a.tables.some(m=>m.shardMode==="global"&&m.globalBackend==="hyperdrive"),hasImages:oe,hasKv:j.kv,hasNotify:se,hasPayments:ee,hasR2sql:ce,hasQueue:T.some(m=>m.mode==="push"),hasScheduler:j.scheduler,hasStorage:j.storage,hasVectors:a.vectorIndexes.length>0,hasWorkflow:v.length>0,hasX402:ue,identity:k,jurisdiction:a.jurisdiction,useUmbrella:O,voiceAgents:b.filter(m=>m.voice===!0&&m.voiceBindingName!==void 0).map(m=>({bindingName:m.voiceBindingName,exportName:m.exportName})),wantsOpenApi:de,wantsOpenRpc:ge}),We=mc(e.projectRoot),Ge=Hs({functions:c,httpRoutes:l,version:We}),He=Qs({functions:c,version:We}),_e=`${JSON.stringify(Ge,void 0,2)}
4
+ `,Qe=`${JSON.stringify(He,void 0,2)}
5
+ `,Je=_s(Ge),Xe=Js(He),fe=g(r,pc),jt=E(fe),x=g(r,"_generated");if(e.dryRun||(E(x)||Bt(x,{recursive:!0}),A(g(x,"app.ts"),Ue),A(g(x,"dataModel.ts"),Fe),A(g(x,"api.ts"),Te),A(g(x,"server.ts"),De),A(g(x,"functions.ts"),Ce),A(g(x,"shard.ts"),Ke),A(g(x,"crons.ts"),qe),A(g(x,"vectors.ts"),Be),A(g(x,"drizzle.global.ts"),M.global),A(g(x,"drizzle.shard.ts"),M.shard),P(g(x,"containers.ts"),Re),P(g(x,"workflows.ts"),je),P(g(x,"agents.ts"),Me),P(g(x,"queues.ts"),ze),P(g(x,"seed.ts"),Ve),P(g(x,"collections.ts"),ke),P(g(x,"openapi.json"),de?_e:""),P(g(x,"openapi.ts"),de?Je:""),P(g(x,"openrpc.json"),ge?Qe:""),P(g(x,"openrpc.ts"),ge?Xe:""),(!jt||e.updateSchemaBaseline===!0)&&A(fe,Gt(le))),t){const m=me.now(),Mt=Math.round(m-s),zt=Math.round(Oe-s),qt=Math.round(m-Oe);console.error(`@lunora/codegen: codegen took ${Mt.toString()}ms (discovery ${zt.toString()}ms, emit ${qt.toString()}ms)`)}return{advisories:be,advisorContext:R,agents:b,containers:D,cronTriggers:$s(X),generated:{agents:Me,api:Te,app:Ue,collections:ke,containers:Re,crons:qe,dataModel:Fe,drizzleGlobal:M.global,drizzleShard:M.shard,functions:Ce,openApi:_e,openApiModule:Je,openRpc:Qe,openRpcModule:Xe,queues:ze,seed:Ve,server:De,shard:Ke,vectors:Be,workflows:je},outputDirectory:x,platformDiagnostics:Pe.diagnostics,queues:T,schemaSnapshot:le,schemaSnapshotPath:fe,workflows:v}};export{pc as SCHEMA_SNAPSHOT_FILENAME,yc as createCodegenProject,ou as refreshCodegenProject,au as runCodegen};
@@ -1,3 +1,3 @@
1
- import{w as v}from"./emit-sQzv_a8t.mjs";import{n as c}from"./paths-BmX5O1sG.mjs";import{LUNORA_ERROR_CODES as S,objectSchema as b,argsObjectSchema as g,validatorIrToJsonSchema as u}from"./LUNORA_ERROR_CODES-Um9hC1gr.mjs";const O="/_lunora/rest",x=["authorization","cf-access-jwt-assertion","cookie"],h=["x-d1-bookmark","x-lunora-shard-key"],P=e=>[...x,...(e.credentialHeaders??[]).map(t=>t.toLowerCase())],m=e=>Number.isFinite(e)?Math.max(0,Math.floor(e)):0,f=(...e)=>{const t=[];for(const r of e)for(const o of r?.split(",")??[]){const n=o.trim().toLowerCase();n!==""&&!t.includes(n)&&t.push(n)}return t.length===0?void 0:t.join(", ")},T=(e,t)=>{const r=[t,`max-age=${String(m(e.maxAge))}`];return e.staleWhileRevalidate!==void 0&&r.push(`stale-while-revalidate=${String(m(e.staleWhileRevalidate))}`),r.join(", ")},k=e=>e.scope==="public"?f(e.vary,...P(e),...h):f(e.vary,...h),R=e=>{const t=e.indexOf(":");if(!(t<=0||t>=e.length-1||e.indexOf(":",t+1)!==-1))return{name:e.slice(t+1),namespace:e.slice(0,t)}},j=e=>{const t=R(e);if(t!==void 0)return`${O}/${t.namespace}/${t.name}`},q=e=>e==="query"?"GET":"POST",l="#/components/responses/LunoraError",y=/:([A-Za-z_$][\w$]*)/gu,A=e=>[...e.matchAll(y)].map(t=>t[1]),w=e=>e.replaceAll(y,"{$1}"),N=e=>{const t=new Set(A(e.path)),r=[];for(const[o,n]of Object.entries(e.searchParams)){const p=n.kind==="optional"?n.inner??n:n;r.push({description:`Query parameter \`${o}\``,in:"query",name:o,required:n.kind!=="optional",schema:u(p)})}for(const[o,n]of Object.entries(e.params)){const p=n.kind==="optional"?n.inner??n:n;r.push({description:`Path parameter \`${o}\``,in:t.has(o)?"path":"query",name:o,required:t.has(o)?!0:n.kind!=="optional",schema:u(p)})}return r},C=e=>e?{content:{"application/json":{schema:u(e)}},description:"Successful response."}:{content:{"application/json":{schema:{description:"Return shape is TS-inferred (no `.output()` declared); best-effort — any JSON."}}},description:"Successful response. The return shape is TypeScript-inferred and not declared via `.output()`, so it is documented best-effort."},E=e=>{const t=c(e.filePath),r=N(e),o={description:`${e.stream?"Streaming (SSE) ":""}HTTP route handler \`${e.exportName}\` (${e.method} ${e.path}).`,operationId:`${e.method.toLowerCase()}_${c(e.path)}`,responses:{200:C(e.output),204:{description:"No content (handler returned `undefined`)."},default:{$ref:l}},summary:`${e.method} ${e.path}`,tags:[t]};return r.length>0&&(o.parameters=r),Object.keys(e.body).length>0&&(o.requestBody={content:{"application/json":{schema:b(e.body)}},required:!0}),e.stream&&(o["x-lunora-stream"]="text/event-stream"),o},L=e=>{const t=`${c(e.filePath)}:${e.exportName}`,r=c(e.filePath),o={additionalProperties:!1,properties:{args:g(e.args),functionPath:{const:t,type:"string"},shardKey:{description:"Optional shard key; omitted routes to the default shard.",type:"string"}},required:["functionPath"],type:"object"};return{operation:{description:`Invoke the \`${e.kind}\` \`${t}\` over the Lunora RPC envelope (POST /_lunora/rpc).`,operationId:t,requestBody:{content:{"application/json":{schema:o}},required:!0},responses:{200:{content:{"application/json":{schema:{description:"RPC result. The shape is TS-inferred from the function's return type; best-effort — any JSON."}}},description:"Successful RPC result (TypeScript-inferred return shape, documented best-effort)."},default:{$ref:l}},summary:`${e.kind}: ${t}`,tags:[r],"x-lunora-function-kind":e.kind},pathKey:`/_lunora/rpc#${t}`}},_=(e,t)=>{if(e===void 0||t!=="get"||e.scope===void 0||e.maxAge===void 0)return{};const r={maxAge:e.maxAge,scope:e.scope,...e.staleWhileRevalidate===void 0?{}:{staleWhileRevalidate:e.staleWhileRevalidate},...e.tag===void 0?{}:{tag:e.tag},...e.vary===void 0?{}:{vary:e.vary}},o={"Cache-Control":{description:r.scope==="public"?"Caching policy. `public` applies only to an uncredentialed request — a request carrying `Authorization` or `Cookie` is always answered `private`.":"Caching policy. Restricted to the caller's own cache; never stored by a shared/edge cache.",schema:{example:T(r,r.scope),type:"string"}}};r.tag!==void 0&&(o["Cache-Tag"]={description:"Purge tag for `ctx.cache.purge({ tags: [...] })`.",schema:{example:r.tag,type:"string"}});const n=k(r);return n!==void 0&&(o.Vary={description:"Request headers this response varies by. The endpoint's own negotiated headers are merged in at runtime.",schema:{example:n,type:"string"}}),{headers:o}},I=e=>{const t=`${c(e.filePath)}:${e.exportName}`,r=j(t);if(r===void 0)return;const o=c(e.filePath),n=q(e.kind),p=n==="GET",a={description:`Public REST endpoint for the \`${e.kind}\` \`${t}\` (opt-in via \`.expose({ rest: true })\`). Routed through the procedure, so auth / RLS / validators are enforced.`,operationId:`rest_${c(r)}`,responses:{200:{content:{"application/json":{schema:{description:"Procedure result. The shape is TS-inferred from the return type; best-effort — any JSON."}}},description:"Successful result (TypeScript-inferred return shape, documented best-effort).",..._(e.expose?.cache,p?"get":"post")},default:{$ref:l}},summary:`${n} ${r}`,tags:[o],"x-lunora-function-kind":e.kind};if(p){const s=Object.entries(e.args).map(([i,d])=>{const $=d.kind==="optional"?d.inner??d:d;return{description:`Argument \`${i}\` (JSON-encoded for non-string values).`,in:"query",name:i,required:d.kind!=="optional",schema:u($)}});return s.length>0&&(a.parameters=s),{method:"get",operation:a,path:r}}return a.requestBody={content:{"application/json":{schema:g(e.args)}},required:Object.keys(e.args).length>0},{method:"post",operation:a,path:r}},D=e=>{const t=e.version??"0.0.0",r={},o=new Set;for(const a of e.httpRoutes){const s=w(a.path),i=r[s]??{};i[a.method.toLowerCase()]=E(a),r[s]=i,o.add(c(a.filePath))}const n=e.functions.filter(a=>a.visibility!=="internal"&&a.kind!=="stream");for(const a of n){const{operation:s,pathKey:i}=L(a);r[i]={post:s},o.add(c(a.filePath))}for(const a of n){if(a.expose?.rest!==!0)continue;const s=I(a);if(s===void 0)continue;const i=r[s.path]??{};i[s.method]=s.operation,r[s.path]=i,o.add(c(a.filePath))}const p=[...o].toSorted((a,s)=>a.localeCompare(s)).map(a=>({description:`Operations declared in \`lunora/${a}\`.`,name:a}));return{components:{responses:{LunoraError:{content:{"application/json":{schema:{additionalProperties:!1,description:"Standard Lunora error envelope.",properties:{error:{additionalProperties:!1,properties:{code:{description:"Machine-readable error code. Clients switch on this value.",enum:S,type:"string"},message:{description:"Human-readable error message (never echoes internal details).",type:"string"}},required:["code","message"],type:"object"}},required:["error"],type:"object"}}},description:"A Lunora error response. The HTTP status reflects the error code (e.g. BAD_REQUEST→400, UNAUTHORIZED→401, FORBIDDEN→403, NOT_FOUND→404)."}}},info:{description:"Auto-generated from @lunora/values-typed functions by @lunora/codegen. Do not edit — run `lunora codegen` to regenerate.",title:"Lunora API",version:t},openapi:"3.1.0",paths:r,tags:p}},U=e=>`${JSON.stringify(D(e),void 0,2)}
1
+ import{w as v}from"./emit-BtiV37rG.mjs";import{n as c}from"./paths-BmX5O1sG.mjs";import{LUNORA_ERROR_CODES as S,objectSchema as b,argsObjectSchema as g,validatorIrToJsonSchema as u}from"./LUNORA_ERROR_CODES-Um9hC1gr.mjs";const O="/_lunora/rest",x=["authorization","cf-access-jwt-assertion","cookie"],h=["x-d1-bookmark","x-lunora-shard-key"],P=e=>[...x,...(e.credentialHeaders??[]).map(t=>t.toLowerCase())],m=e=>Number.isFinite(e)?Math.max(0,Math.floor(e)):0,f=(...e)=>{const t=[];for(const r of e)for(const o of r?.split(",")??[]){const n=o.trim().toLowerCase();n!==""&&!t.includes(n)&&t.push(n)}return t.length===0?void 0:t.join(", ")},T=(e,t)=>{const r=[t,`max-age=${String(m(e.maxAge))}`];return e.staleWhileRevalidate!==void 0&&r.push(`stale-while-revalidate=${String(m(e.staleWhileRevalidate))}`),r.join(", ")},k=e=>e.scope==="public"?f(e.vary,...P(e),...h):f(e.vary,...h),R=e=>{const t=e.indexOf(":");if(!(t<=0||t>=e.length-1||e.indexOf(":",t+1)!==-1))return{name:e.slice(t+1),namespace:e.slice(0,t)}},j=e=>{const t=R(e);if(t!==void 0)return`${O}/${t.namespace}/${t.name}`},q=e=>e==="query"?"GET":"POST",l="#/components/responses/LunoraError",y=/:([A-Za-z_$][\w$]*)/gu,A=e=>[...e.matchAll(y)].map(t=>t[1]),w=e=>e.replaceAll(y,"{$1}"),N=e=>{const t=new Set(A(e.path)),r=[];for(const[o,n]of Object.entries(e.searchParams)){const p=n.kind==="optional"?n.inner??n:n;r.push({description:`Query parameter \`${o}\``,in:"query",name:o,required:n.kind!=="optional",schema:u(p)})}for(const[o,n]of Object.entries(e.params)){const p=n.kind==="optional"?n.inner??n:n;r.push({description:`Path parameter \`${o}\``,in:t.has(o)?"path":"query",name:o,required:t.has(o)?!0:n.kind!=="optional",schema:u(p)})}return r},C=e=>e?{content:{"application/json":{schema:u(e)}},description:"Successful response."}:{content:{"application/json":{schema:{description:"Return shape is TS-inferred (no `.output()` declared); best-effort — any JSON."}}},description:"Successful response. The return shape is TypeScript-inferred and not declared via `.output()`, so it is documented best-effort."},E=e=>{const t=c(e.filePath),r=N(e),o={description:`${e.stream?"Streaming (SSE) ":""}HTTP route handler \`${e.exportName}\` (${e.method} ${e.path}).`,operationId:`${e.method.toLowerCase()}_${c(e.path)}`,responses:{200:C(e.output),204:{description:"No content (handler returned `undefined`)."},default:{$ref:l}},summary:`${e.method} ${e.path}`,tags:[t]};return r.length>0&&(o.parameters=r),Object.keys(e.body).length>0&&(o.requestBody={content:{"application/json":{schema:b(e.body)}},required:!0}),e.stream&&(o["x-lunora-stream"]="text/event-stream"),o},L=e=>{const t=`${c(e.filePath)}:${e.exportName}`,r=c(e.filePath),o={additionalProperties:!1,properties:{args:g(e.args),functionPath:{const:t,type:"string"},shardKey:{description:"Optional shard key; omitted routes to the default shard.",type:"string"}},required:["functionPath"],type:"object"};return{operation:{description:`Invoke the \`${e.kind}\` \`${t}\` over the Lunora RPC envelope (POST /_lunora/rpc).`,operationId:t,requestBody:{content:{"application/json":{schema:o}},required:!0},responses:{200:{content:{"application/json":{schema:{description:"RPC result. The shape is TS-inferred from the function's return type; best-effort — any JSON."}}},description:"Successful RPC result (TypeScript-inferred return shape, documented best-effort)."},default:{$ref:l}},summary:`${e.kind}: ${t}`,tags:[r],"x-lunora-function-kind":e.kind},pathKey:`/_lunora/rpc#${t}`}},_=(e,t)=>{if(e===void 0||t!=="get"||e.scope===void 0||e.maxAge===void 0)return{};const r={maxAge:e.maxAge,scope:e.scope,...e.staleWhileRevalidate===void 0?{}:{staleWhileRevalidate:e.staleWhileRevalidate},...e.tag===void 0?{}:{tag:e.tag},...e.vary===void 0?{}:{vary:e.vary}},o={"Cache-Control":{description:r.scope==="public"?"Caching policy. `public` applies only to an uncredentialed request — a request carrying `Authorization` or `Cookie` is always answered `private`.":"Caching policy. Restricted to the caller's own cache; never stored by a shared/edge cache.",schema:{example:T(r,r.scope),type:"string"}}};r.tag!==void 0&&(o["Cache-Tag"]={description:"Purge tag for `ctx.cache.purge({ tags: [...] })`.",schema:{example:r.tag,type:"string"}});const n=k(r);return n!==void 0&&(o.Vary={description:"Request headers this response varies by. The endpoint's own negotiated headers are merged in at runtime.",schema:{example:n,type:"string"}}),{headers:o}},I=e=>{const t=`${c(e.filePath)}:${e.exportName}`,r=j(t);if(r===void 0)return;const o=c(e.filePath),n=q(e.kind),p=n==="GET",a={description:`Public REST endpoint for the \`${e.kind}\` \`${t}\` (opt-in via \`.expose({ rest: true })\`). Routed through the procedure, so auth / RLS / validators are enforced.`,operationId:`rest_${c(r)}`,responses:{200:{content:{"application/json":{schema:{description:"Procedure result. The shape is TS-inferred from the return type; best-effort — any JSON."}}},description:"Successful result (TypeScript-inferred return shape, documented best-effort).",..._(e.expose?.cache,p?"get":"post")},default:{$ref:l}},summary:`${n} ${r}`,tags:[o],"x-lunora-function-kind":e.kind};if(p){const s=Object.entries(e.args).map(([i,d])=>{const $=d.kind==="optional"?d.inner??d:d;return{description:`Argument \`${i}\` (JSON-encoded for non-string values).`,in:"query",name:i,required:d.kind!=="optional",schema:u($)}});return s.length>0&&(a.parameters=s),{method:"get",operation:a,path:r}}return a.requestBody={content:{"application/json":{schema:g(e.args)}},required:Object.keys(e.args).length>0},{method:"post",operation:a,path:r}},D=e=>{const t=e.version??"0.0.0",r={},o=new Set;for(const a of e.httpRoutes){const s=w(a.path),i=r[s]??{};i[a.method.toLowerCase()]=E(a),r[s]=i,o.add(c(a.filePath))}const n=e.functions.filter(a=>a.visibility!=="internal"&&a.kind!=="stream");for(const a of n){const{operation:s,pathKey:i}=L(a);r[i]={post:s},o.add(c(a.filePath))}for(const a of n){if(a.expose?.rest!==!0)continue;const s=I(a);if(s===void 0)continue;const i=r[s.path]??{};i[s.method]=s.operation,r[s.path]=i,o.add(c(a.filePath))}const p=[...o].toSorted((a,s)=>a.localeCompare(s)).map(a=>({description:`Operations declared in \`lunora/${a}\`.`,name:a}));return{components:{responses:{LunoraError:{content:{"application/json":{schema:{additionalProperties:!1,description:"Standard Lunora error envelope.",properties:{error:{additionalProperties:!1,properties:{code:{description:"Machine-readable error code. Clients switch on this value.",enum:S,type:"string"},message:{description:"Human-readable error message (never echoes internal details).",type:"string"}},required:["code","message"],type:"object"}},required:["error"],type:"object"}}},description:"A Lunora error response. The HTTP status reflects the error code (e.g. BAD_REQUEST→400, UNAUTHORIZED→401, FORBIDDEN→403, NOT_FOUND→404)."}}},info:{description:"Auto-generated from @lunora/values-typed functions by @lunora/codegen. Do not edit — run `lunora codegen` to regenerate.",title:"Lunora API",version:t},openapi:"3.1.0",paths:r,tags:p}},U=e=>`${JSON.stringify(D(e),void 0,2)}
2
2
  `,W=e=>`${v}export const openApiSpec: Record<string, unknown> = ${JSON.stringify(e,void 0,4)};
3
3
  `;export{D as buildOpenApiDocument,U as emitOpenApi,W as emitOpenApiModule};
@@ -0,0 +1 @@
1
+ import{Node as s,SyntaxKind as a}from"ts-morph";import{listLunoraSourceFiles as E,lunoraRelativePath as A}from"./discoverFunctions-DnqHgv0t.mjs";const p=e=>{if(e.getText()!=="args")return!1;const t=e.getParent();return s.isPropertyAccessExpression(t)&&t.getNameNode()===e?!1:!(s.isPropertyAssignment(t)&&t.getNameNode()===e)},m=e=>{if(e.getText()!=="ctx")return!1;const t=e.getParent();return s.isPropertyAccessExpression(t)&&t.getNameNode()===e?!1:!(s.isPropertyAssignment(t)&&t.getNameNode()===e)},g=e=>s.isIdentifier(e)?m(e):e.getDescendantsOfKind(a.Identifier).some(t=>m(t)),x=(e,t)=>{if(e.getText()!==t)return!1;const r=e.getParent();return s.isPropertyAccessExpression(r)&&r.getNameNode()===e?!1:!(s.isPropertyAssignment(r)&&r.getNameNode()===e)},I=e=>{let t=e;for(;s.isPropertyAccessExpression(t)||s.isElementAccessExpression(t)||s.isNonNullExpression(t);)t=t.getExpression();return s.isIdentifier(t)?t:void 0},F=e=>{if(s.isIdentifier(e))return e.getText();if(s.isPropertyAccessExpression(e))return e.getName()},N=e=>s.isIdentifier(e)?p(e):e.getDescendantsOfKind(a.Identifier).some(t=>p(t)),u=e=>{if(!s.isIdentifier(e))return;const t=e.getText(),r=e.getFirstAncestor(o=>s.isArrowFunction(o)||s.isFunctionExpression(o)||s.isFunctionDeclaration(o));if(r===void 0)return;const n=e.getStart();let i,d=-1;for(const o of r.getDescendantsOfKind(a.VariableDeclaration)){if(o.getName()!==t)continue;const c=o.getInitializer(),f=o.getStart();c!==void 0&&f<n&&f>d&&(i=c,d=f)}return i},K=e=>{if(N(e))return!0;const t=u(e);return t!==void 0&&N(t)},T=e=>{if(g(e))return!0;const t=u(e);if(t!==void 0&&g(t))return!0;const r=t??e;return(s.isIdentifier(r)?[r]:r.getDescendantsOfKind(a.Identifier)).some(n=>{const i=u(n);return i!==void 0&&g(i)})},l=(e,t)=>s.isIdentifier(e)?x(e,t):e.getDescendantsOfKind(a.Identifier).some(r=>x(r,t)),O=(e,t)=>{if(l(e,t))return!0;const r=u(e);if(r!==void 0&&l(r,t))return!0;const n=I(e);if(n!==void 0){const i=u(n);return i!==void 0&&l(i,t)}return!1},P=e=>{for(const t of e.getAncestors())if(s.isVariableDeclaration(t)&&t.getVariableStatement()?.hasExportKeyword()===!0)return t.getName();return"<module>"},y=new Set(["withIndex","withSearchIndex"]),h=e=>{const t=e.getExpression();if(!s.isPropertyAccessExpression(t)||t.getName()!=="query")return!1;const r=t.getExpression();return s.isPropertyAccessExpression(r)?r.getName()==="db":s.isIdentifier(r)&&r.getText()==="db"},v=e=>{const t=[];let r=e;for(;;){const n=r.getParent();if(!n||!s.isPropertyAccessExpression(n))break;const i=n.getParent();if(!i||!s.isCallExpression(i))break;t.push(n.getName()),r=i}return t},S=e=>{const t=e.getArguments()[0];return t&&s.isStringLiteral(t)?t.getLiteralText():""},w=(e,t)=>{const r=[];for(const n of E(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),d=A(t,n);for(const o of i.getDescendantsOfKind(a.CallExpression)){if(!h(o))continue;const c=v(o);c.includes("filter")&&r.push({exportName:P(o),file:d,hasFilter:!0,hasIndex:c.some(f=>y.has(f)),line:o.getStartLineNumber(),table:S(o)})}}return r};export{w as E,T as a,O as b,F as c,l as d,P as e,K as i,N as r,u as s};
@@ -0,0 +1 @@
1
+ import"ts-morph";import{E as p}from"./discover-queries-LfER8HbK.mjs";import"./discoverFunctions-DnqHgv0t.mjs";export{p as default};