@lunora/codegen 1.0.0-alpha.82 → 1.0.0-alpha.83
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 +584 -549
- package/dist/index.d.ts +584 -549
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/DEFAULT_TARGET-CH5disA3.mjs +1 -0
- package/dist/packem_shared/GENERATED_HEADER-oy7DTIDi.mjs +1 -0
- package/dist/packem_shared/{OPENRPC_VERSION-IKkrtXye.mjs → OPENRPC_VERSION-K3RTK2CP.mjs} +1 -1
- package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-ZIqaP_TZ.mjs +9 -0
- package/dist/packem_shared/{buildOpenApiDocument-XeZ1ycwi.mjs → buildOpenApiDocument-Blf3mpIz.mjs} +1 -1
- package/dist/packem_shared/describeErrorLevelFindings-IhNx9gPr.mjs +1 -0
- package/dist/packem_shared/discover-queries-Bhu9SNsy.mjs +1 -0
- package/dist/packem_shared/discoverCrons-DLwFH_K5.mjs +1 -0
- package/dist/packem_shared/discoverMaskProcedures-ZewKJLXx.mjs +1 -0
- package/dist/packem_shared/{discoverQueries-2A0lbpxV.mjs → discoverQueries-g4qZzLpl.mjs} +1 -1
- package/dist/packem_shared/discoverSchema-4nJgoLaJ.mjs +1 -0
- package/dist/packem_shared/{emit-05q6XTbd.mjs → emit-B7IUlWwi.mjs} +265 -215
- package/dist/packem_shared/{emitApp-C2DhPKWE.mjs → emitApp-jRD2D9kI.mjs} +111 -37
- package/package.json +10 -10
- package/dist/packem_shared/DEFAULT_TARGET-BYPEwgZu.mjs +0 -1
- package/dist/packem_shared/GENERATED_HEADER-Cphn03Kf.mjs +0 -1
- package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-DBD0oti8.mjs +0 -12
- package/dist/packem_shared/discover-queries-Ctpk9SA-.mjs +0 -1
- package/dist/packem_shared/discoverCrons-CwtPaymU.mjs +0 -1
- package/dist/packem_shared/discoverMaskProcedures-DQ-4yUUK.mjs +0 -1
- package/dist/packem_shared/discoverSchema-CaTD2Sdx.mjs +0 -1
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{SCHEMA_SNAPSHOT_VERSION as t,diffSchemaSnapshots as s,serializeSchemaSnapshot as a}from"./packem_shared/SCHEMA_SNAPSHOT_VERSION-CFhF_hmg.mjs";import{formatAdvisories as m,lintSchema as d,toAdvisorContext as f}from"./packem_shared/formatAdvisories-BCEfzLT0.mjs";import{
|
|
1
|
+
import{SCHEMA_SNAPSHOT_VERSION as t,diffSchemaSnapshots as s,serializeSchemaSnapshot as a}from"./packem_shared/SCHEMA_SNAPSHOT_VERSION-CFhF_hmg.mjs";import{formatAdvisories as m,lintSchema as d,toAdvisorContext as f}from"./packem_shared/formatAdvisories-BCEfzLT0.mjs";import{describeErrorLevelFindings as c,errorAdvisoryNames as n,errorPlatformDiagnosticNames as l}from"./packem_shared/describeErrorLevelFindings-IhNx9gPr.mjs";import{CodegenDiagnosticError as E,diagnosticAt as x}from"./packem_shared/CodegenDiagnosticError-DPezpZTz.mjs";import{AGENTS_FILENAME as u,discoverAgents as v}from"./packem_shared/AGENTS_FILENAME-BesaDYkL.mjs";import{default as O}from"./packem_shared/discoverAuthApiCalls-CYdI8pkP.mjs";import{CONTAINERS_FILENAME as g,discoverContainers as C}from"./packem_shared/CONTAINERS_FILENAME-CFwdyaCI.mjs";import{default as I}from"./packem_shared/discoverCrons-DLwFH_K5.mjs";import{FLAGS_FILENAME as _,discoverFlags as L}from"./packem_shared/FLAGS_FILENAME-UPE377GV.mjs";import{discoverFunctions as T}from"./packem_shared/discoverFunctions-CVYkUBTm.mjs";import{default as D}from"./packem_shared/discoverHttpRoutes-DmTedJlp.mjs";import{default as H}from"./packem_shared/discoverInserts-CssZuKb6.mjs";import{default as y}from"./packem_shared/discoverMaskProcedures-ZewKJLXx.mjs";import{default as W}from"./packem_shared/discoverMigrations-qyXaVjw1.mjs";import{MUTATORS_FILENAME as V,discoverMutators as j}from"./packem_shared/MUTATORS_FILENAME-CsAoG-d2.mjs";import{default as Q}from"./packem_shared/discoverNondeterministicCalls-GNP4oKrf.mjs";import{NOTIFY_FILENAME as B,discoverNotifyCalls as K,discoverNotifyConfig as q}from"./packem_shared/NOTIFY_FILENAME-zA5OFFbv.mjs";import{default as Y}from"./packem_shared/readPackageDependencies-CogJX1Ia.mjs";import{y as X}from"./packem_shared/discover-queries-Bhu9SNsy.mjs";import{QUEUES_FILENAME as ee,discoverQueues as re}from"./packem_shared/QUEUES_FILENAME-CSE6i-ld.mjs";import{default as te}from"./packem_shared/discoverR2sqlCalls-B7uqLnVS.mjs";import{discoverRlsMetadata as ae,default as ie}from"./packem_shared/discoverRlsMetadata-Bt0QK8VM.mjs";import{discoverSandboxUsage as de}from"./packem_shared/discoverSandboxUsage-Bb2JzaIW.mjs";import{default as pe}from"./packem_shared/discoverSchema-4nJgoLaJ.mjs";import{SHAPES_FILENAME as ne,discoverShapes as le}from"./packem_shared/SHAPES_FILENAME-DyVUZzIk.mjs";import{default as Ee}from"./packem_shared/discoverStorageRulesMetadata-VJ_uXOFe.mjs";import{WORKFLOWS_FILENAME as Ae,discoverWorkflows as ue}from"./packem_shared/WORKFLOWS_FILENAME-ClsYRKXp.mjs";import{R as Ne,i as Oe,I as Re,C as ge,o as Ce,S as Me,g as Ie,v as he,B as _e,P as Le,b as Fe,$ as Te,s as Pe,A as De}from"./packem_shared/emit-B7IUlWwi.mjs";import{emitApp as He}from"./packem_shared/emitApp-jRD2D9kI.mjs";import{buildOpenApiDocument as ye,emitOpenApi as Ge,emitOpenApiModule as We}from"./packem_shared/buildOpenApiDocument-Blf3mpIz.mjs";import{OPENRPC_VERSION as Ve,buildOpenRpcDocument as je,emitOpenRpc as ze,emitOpenRpcModule as Qe}from"./packem_shared/OPENRPC_VERSION-K3RTK2CP.mjs";import{DEFAULT_TARGET as Be,platformMatrixIds as Ke,readProjectTarget as qe,resolveCodegenTarget as Je}from"./packem_shared/DEFAULT_TARGET-CH5disA3.mjs";import{SCHEMA_SNAPSHOT_FILENAME as $e,createCodegenProject as Xe,refreshCodegenProject as Ze,runCodegen as er}from"./packem_shared/SCHEMA_SNAPSHOT_FILENAME-ZIqaP_TZ.mjs";import{SchemaSnapshotParseError as or,buildSchemaSnapshot as tr,evaluateSchemaDrift as sr,parseSchemaSnapshot as ar}from"./packem_shared/SchemaSnapshotParseError-BJkhTEpi.mjs";import{schemaFromIr as mr}from"./packem_shared/schemaFromIr-R1ZFzVyy.mjs";import{LUNORA_ERROR_CODES as fr,validatorIrToJsonSchema as pr}from"./packem_shared/LUNORA_ERROR_CODES-Um9hC1gr.mjs";import{redact as nr,secretKindOf as lr}from"./packem_shared/redact-6jD4lAhq.mjs";import{MESSAGE_SOLUTIONS as Er,findSolutionByMessage as xr}from"@lunora/errors";const e="0.0.0";export{u as AGENTS_FILENAME,g as CONTAINERS_FILENAME,E as CodegenDiagnosticError,Be as DEFAULT_TARGET,_ as FLAGS_FILENAME,Ne as GENERATED_HEADER,fr as LUNORA_ERROR_CODES,Er as LUNORA_SOLUTION_RULES,V as MUTATORS_FILENAME,B as NOTIFY_FILENAME,Ve as OPENRPC_VERSION,ee as QUEUES_FILENAME,$e as SCHEMA_SNAPSHOT_FILENAME,t as SCHEMA_SNAPSHOT_VERSION,ne as SHAPES_FILENAME,or as SchemaSnapshotParseError,e as VERSION,Ae as WORKFLOWS_FILENAME,ye as buildOpenApiDocument,je as buildOpenRpcDocument,tr as buildSchemaSnapshot,Xe as createCodegenProject,c as describeErrorLevelFindings,x as diagnosticAt,s as diffSchemaSnapshots,v as discoverAgents,O as discoverAuthApiCalls,C as discoverContainers,I as discoverCrons,L as discoverFlags,T as discoverFunctions,D as discoverHttpRoutes,H as discoverInserts,y as discoverMaskProcedures,W as discoverMigrations,j as discoverMutators,Q as discoverNondeterministicCalls,K as discoverNotifyCalls,q as discoverNotifyConfig,X as discoverQueries,re as discoverQueues,te as discoverR2sqlCalls,ae as discoverRlsMetadata,ie as discoverRlsProcedures,de as discoverSandboxUsage,pe as discoverSchema,le as discoverShapes,Ee as discoverStorageRulesMetadata,ue as discoverWorkflows,Oe as emitAgents,Re as emitApi,He as emitApp,ge as emitCollections,Ce as emitContainers,Me as emitCrons,Ie as emitDataModel,he as emitDrizzleSchema,_e as emitFunctions,Ge as emitOpenApi,We as emitOpenApiModule,ze as emitOpenRpc,Qe as emitOpenRpcModule,Le as emitServer,Fe as emitShard,Te as emitVectors,Pe as emitWorkflows,De as emitWranglerCronTriggers,n as errorAdvisoryNames,l as errorPlatformDiagnosticNames,sr as evaluateSchemaDrift,xr as findLunoraSolution,m as formatAdvisories,d as lintSchema,ar as parseSchemaSnapshot,Ke as platformMatrixIds,Y as readPackageDependencies,qe as readProjectTarget,nr as redact,Ze as refreshCodegenProject,Je as resolveCodegenTarget,er as runCodegen,mr as schemaFromIr,lr as secretKindOf,a as serializeSchemaSnapshot,f as toAdvisorContext,pr as validatorIrToJsonSchema};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{existsSync as u,readFileSync as c}from"node:fs";import{join as d}from"node:path";import{NODE_CAPABILITIES as p,CLOUDFLARE_CAPABILITIES as m}from"@lunora/platform";import{parse as f}from"jsonc-parser";const g="cloudflare",h="lunora.json",y=r=>{const e=d(r,h);if(!u(e))return;let a;try{a=c(e,"utf8")}catch{return}const s=[],o=f(a,s,{allowTrailingComma:!0});if(s.length>0||o===null||typeof o!="object")return;const{target:t}=o;return typeof t=="string"&&t.length>0?t:void 0},C=(r,e)=>e??y(r)??g,i={cloudflare:m,node:p},k=()=>Object.keys(i).toSorted((r,e)=>r.localeCompare(e)),v={ai:"ai",analytics:"analytics",browser:"browser",container:"containers",hyperdrive:"hyperdrive",kv:"keyValueStore",mail:"mail",pipelines:"pipelines",scheduler:"scheduler",storage:"objectStorage",vectors:"vectorStore",workflows:"workflows"},$=(r,e,a)=>{const s={...r},o=[];for(const[t,n]of Object.entries(v)){if(!r[t])continue;const l=e.features[n]?.level;l==="unsupported"?(s[t]=!1,o.push({feature:t,level:"error",message:`${e.name} does not support "${t}" (ctx.${t}). Its surface was omitted from the generated types.`,name:"platform_unsupported_feature",remediation:`Remove the ctx.${t} usage, or deploy to a target whose capability matrix marks "${n}" as native or emulated.`,target:a})):l===void 0&&(s[t]=!1,o.push({feature:t,level:"error",message:`${e.name}'s capability matrix does not declare a support level for "${t}" (ctx.${t}). Treated as unsupported and its surface was omitted from the generated types.`,name:"platform_undeclared_feature",remediation:`Rate "${n}" in the ${e.name} capability matrix as "native", "emulated", or "unsupported" — an undeclared feature fails closed rather than shipping a surface the host may not provide.`,target:a}))}return{diagnostics:o,usage:s}},I=(r,e)=>{const a=i[e];return a===void 0?{diagnostics:[{level:"error",message:`Unknown deploy target "${e}" — no capability matrix is registered for it. Codegen emitted the full Cloudflare surface un-gated.`,name:"platform_unknown_target",remediation:`Use a registered target (${Object.keys(i).join(", ")}) or install the target's @lunora/platform-${e} package.`,target:e}],usage:{...r}}:$(r,a,e)};export{g as DEFAULT_TARGET,h as PROJECT_CONFIG_FILE,$ as gateAgainstMatrix,I as gatePlatformFeatures,k as platformMatrixIds,y as readProjectTarget,C as resolveCodegenTarget};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"@lunora/agent/component";import"@lunora/errors";import"./SCHEMA_SNAPSHOT_VERSION-CFhF_hmg.mjs";import{R as r,a as o,c as n,i as l,I as A,C as E,o as S,S as C,g,v as p,B as c,l as u,O as d,P as D,b as R,$ as B,s as _,A as b}from"./emit-B7IUlWwi.mjs";import"./paths-BmX5O1sG.mjs";export{r as GENERATED_HEADER,o as UMBRELLA_BASE_PACKAGES,n as buildStorageColumns,l as emitAgents,A as emitApi,E as emitCollections,S as emitContainers,C as emitCrons,g as emitDataModel,p as emitDrizzleSchema,c as emitFunctions,u as emitQueues,d as emitSeed,D as emitServer,R as emitShard,B as emitVectors,_ as emitWorkflows,b as emitWranglerCronTriggers};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{R as a}from"./emit-B7IUlWwi.mjs";import{n as s}from"./paths-BmX5O1sG.mjs";import{argsObjectSchema as i,LUNORA_ERROR_CODES as c}from"./LUNORA_ERROR_CODES-Um9hC1gr.mjs";const m="1.3.2",p=()=>({description:"Result is TS-inferred from the function's return type (no `.output()` declared); best-effort — any JSON."}),u=e=>{const n=s(e.filePath),t=`${n}:${e.exportName}`;return{description:`Invoke the \`${e.kind}\` \`${t}\` over the Lunora RPC envelope (POST /_lunora/rpc, body \`{ "functionPath": "${t}", "args": { … } }\`).`,errors:c.map((r,o)=>({code:-32e3-o,data:{code:r},message:r})),name:t,params:[{description:"The function's argument object (the RPC envelope's `args`).",name:"args",required:Object.keys(e.args).length>0,schema:i(e.args)}],result:{name:"result",schema:p()},summary:`${e.kind}: ${t}`,"x-lunora-function-kind":e.kind,"x-tags":[{name:n}]}},d=e=>{const n=e.version??"0.0.0",t=e.functions.filter(r=>r.visibility!=="internal"&&r.kind!=="stream").map(r=>u(r)).toSorted((r,o)=>r.name.localeCompare(o.name));return{info:{description:"Auto-generated from @lunora/values-typed functions by @lunora/codegen. Do not edit — run `lunora codegen` to regenerate.",title:"Lunora RPC",version:n},methods:t,openrpc:m}},R=e=>`${JSON.stringify(d(e),void 0,2)}
|
|
2
2
|
`,O=e=>`${a}export const openRpcSpec: Record<string, unknown> = ${JSON.stringify(e,void 0,4)};
|
|
3
3
|
`;export{m as OPENRPC_VERSION,d as buildOpenRpcDocument,R as emitOpenRpc,O as emitOpenRpcModule};
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import{existsSync as E,mkdirSync as ot,readFileSync as wt,writeFileSync as es,rmSync as ts}from"node:fs";import{join as d,dirname as he}from"node:path";import{performance as xe}from"node:perf_hooks";import{runAdvisor as ss}from"@lunora/advisor";import{LunoraError as F}from"@lunora/errors";import{Node as i,SyntaxKind as u,Project as at}from"ts-morph";import{serializeSchemaSnapshot as rs}from"./SCHEMA_SNAPSHOT_VERSION-CFhF_hmg.mjs";import{toAdvisorContext as ns}from"./formatAdvisories-BCEfzLT0.mjs";import{listLunoraSourceFiles as g,lunoraRelativePath as p,classifyProcedureCall as K,inlineHandler as is,procedureHandler as It,chainUsesWrappedCall as Tt,isDatabaseAccessor as C,chainHasStep as os,discoverFunctions as as,resolveStandardSchemaType as cs}from"./discoverFunctions-CVYkUBTm.mjs";import{discoverAgents as us}from"./AGENTS_FILENAME-BesaDYkL.mjs";import{i as w,a as O,e as x,c as S,r as ls,b as ds,s as Q,d as gs,f as ps,y as fs}from"./discover-queries-Bhu9SNsy.mjs";import ms from"./discoverAuthApiCalls-CYdI8pkP.mjs";import{discoverContainers as hs}from"./CONTAINERS_FILENAME-CFwdyaCI.mjs";import xs from"./discoverCrons-DLwFH_K5.mjs";import{diagnosticAt as J}from"./CodegenDiagnosticError-DPezpZTz.mjs";import{o as X}from"./module-specifiers-8FEEiUcv.mjs";import{r as Ee,g as ct,P as ut,c as Es,I as ys,B as $s,b as As,C as Ss,o as bs,s as vs,i as Ns,l as Ps,S as ws,$ as Is,v as Ts,O as Ls,A as Fs}from"./emit-B7IUlWwi.mjs";import{discoverFlagKeys as Os}from"./FLAGS_FILENAME-UPE377GV.mjs";import Ds from"./discoverHttpRoutes-DmTedJlp.mjs";import ks from"./discoverInserts-CssZuKb6.mjs";import Cs,{discoverMaskStrategies as Ks,discoverMaskMetadata as Rs,discoverMaskHasNonLiteralPolicy as Ms}from"./discoverMaskProcedures-ZewKJLXx.mjs";import js from"./discoverMigrations-qyXaVjw1.mjs";import{MUTATORS_FILENAME as zs,isDefineMutatorCallee as qs,discoverMutators as Bs}from"./MUTATORS_FILENAME-CsAoG-d2.mjs";import Us from"./discoverNondeterministicCalls-GNP4oKrf.mjs";import{discoverNotifyConfig as Vs,discoverNotifyCalls as Ws}from"./NOTIFY_FILENAME-zA5OFFbv.mjs";import lt from"./readPackageDependencies-CogJX1Ia.mjs";import{discoverQueues as _s}from"./QUEUES_FILENAME-CSE6i-ld.mjs";import Gs from"./discoverR2sqlCalls-B7uqLnVS.mjs";import Hs,{discoverRlsMetadata as Qs}from"./discoverRlsMetadata-Bt0QK8VM.mjs";import{discoverSandboxUsage as Js}from"./discoverSandboxUsage-Bb2JzaIW.mjs";import Xs from"./discoverSchema-4nJgoLaJ.mjs";import{secretKindOf as Zs,redact as Ys,isHeuristicSecretKind as er,isSecretishName as tr}from"./redact-6jD4lAhq.mjs";import{discoverShapes as sr}from"./SHAPES_FILENAME-DyVUZzIk.mjs";import rr from"./discoverStorageRulesMetadata-VJ_uXOFe.mjs";import{e as nr}from"./discover-ast-CezKqEhE.mjs";import{discoverWorkflows as ir}from"./WORKFLOWS_FILENAME-ClsYRKXp.mjs";import{emitApp as or}from"./emitApp-jRD2D9kI.mjs";import{buildOpenApiDocument as ar,emitOpenApiModule as cr}from"./buildOpenApiDocument-Blf3mpIz.mjs";import{buildOpenRpcDocument as ur,emitOpenRpcModule as lr}from"./OPENRPC_VERSION-K3RTK2CP.mjs";import{p as dr}from"./parse-validator-_jDrFxwt.mjs";import{gatePlatformFeatures as gr,resolveCodegenTarget as pr}from"./DEFAULT_TARGET-CH5disA3.mjs";import{buildSchemaSnapshot as fr}from"./SchemaSnapshotParseError-BJkhTEpi.mjs";const mr=e=>{const t=[],s=e.tables.filter(r=>r.shardMode==="global");return s.some(r=>r.globalBackend!=="hyperdrive")&&t.push({name:"@lunora/d1",reason:"`.global()` tables are D1-backed, so `_generated/app.ts` imports the D1 `ctx.db` adapter"}),s.some(r=>r.globalBackend==="hyperdrive")&&t.push({name:"@lunora/hyperdrive",reason:'`.global({ backend: "hyperdrive" })` tables route through `@lunora/hyperdrive/global`'}),e.vectorIndexes.length>0&&t.push({name:"@lunora/bindings",reason:"`.vectorize()` indexes make `_generated/vectors.ts` import `@lunora/bindings/vectors`"}),t},hr=(e,t)=>{if(t===void 0)return;const s=mr(e).filter(n=>!t.has(n.name));if(s.length===0)return;const r=s.map(n=>` - ${n.name} — ${n.reason}`).join(`
|
|
2
|
+
`);throw new F("INTERNAL",`@lunora/codegen: this schema's generated code imports packages the project does not declare:
|
|
3
|
+
${r}
|
|
4
|
+
|
|
5
|
+
Install them with your package manager, then re-run codegen.`)},Lt=new Set(["delete","get","head","options","patch","post","put"]),xr=new Set(["handler","stream"]),Er=/\/(?:_|admin|internal|superuser|sudo|root|debug)/iu,dt=new Set(["ADMIN_TOKEN","adminToken","assertAdmin","assertAuth","auth","Authorization","getSession","identity","isAdmin","requireAdmin","requireAuth","requireRole","verifyAdmin"]),yr=e=>{if(!i.isCallExpression(e))return;const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!Lt.has(t.getName()))return;const s=t.getExpression();if(!i.isIdentifier(s)||s.getText()!=="httpRoute")return;const r=e.getArguments()[0];if(!(!r||!i.isStringLiteral(r)))return{method:t.getName().toUpperCase(),path:r.getLiteralValue()}},$r=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t))return;let s=t.getExpression();for(;i.isCallExpression(s);){const r=s.getExpression();if(!i.isPropertyAccessExpression(r)||Lt.has(r.getName()))break;s=r.getExpression()}return yr(s)},Ar=e=>{for(const t of e.getDescendantsOfKind(u.PropertyAccessExpression))if(dt.has(t.getName()))return!0;for(const t of e.getDescendantsOfKind(u.CallExpression)){const s=t.getExpression();if(i.isIdentifier(s)&&dt.has(s.getText()))return!0}return!1},Sr=(e,t)=>{const s=e.getInitializer();if(!s||!i.isCallExpression(s))return;const r=s.getExpression();if(!i.isPropertyAccessExpression(r)||!xr.has(r.getName()))return;const n=$r(s);if(!n||!Er.test(n.path))return;const o=s.getArguments()[0],a=o!==void 0&&(i.isArrowFunction(o)||i.isFunctionExpression(o))&&Ar(o);return{exportName:e.getName(),file:t,method:n.method,path:n.path,usesGuard:a}},br=(e,t)=>{const s=[];for(const r of e.getVariableStatements())if(r.isExported())for(const n of r.getDeclarations()){const o=Sr(n,t);o&&s.push(o)}return s},vr=(e,t)=>{const s=[];for(const r of g(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...br(n,p(t,r)))}return s},Nr=e=>!i.isPropertyAccessExpression(e)||e.getName()!=="run"?!1:e.getExpression().getText()==="ctx.ai",Pr=(e,t)=>{if(!Nr(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!w(s)||O(s)))return{exportName:x(e),file:t,line:e.getStartLineNumber()}},wr=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=Pr(r,t);n&&s.push(n)}return s},Ir=(e,t)=>{const s=[];for(const r of g(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...wr(n,p(t,r)))}return s},Tr=new Set(["generateText","streamText"]),Lr=new Set(["messages","prompt","system"]),Fr=[{methods:new Set(["delete","insert","insertManyUnsafe","patch","replace"]),prefixes:["context.db","ctx.db"]},{methods:new Set(["run","runAction","runMutation"]),prefixes:["context","ctx"]},{methods:new Set(["fetch"]),prefixes:["context","ctx"]},{methods:new Set(["queue","send"]),prefixes:["context.email","context.mail","ctx.email","ctx.mail"]}],Or=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t))return;const s=t.getName(),r=t.getExpression().getText();for(const n of Fr)if(n.methods.has(s)&&n.prefixes.some(o=>r===o||r.startsWith(`${o}.`)))return`${r}.${s}`},Dr=e=>{for(const t of e.getDescendantsOfKind(u.CallExpression)){const s=Or(t);if(s!==void 0)return s}},kr=e=>{const t=new Set,s=e.getFirstAncestor(o=>i.isArrowFunction(o)||i.isFunctionExpression(o)||i.isFunctionDeclaration(o)),[r]=s?.getParameters()??[],n=r?.getNameNode();if(n===void 0||!i.isObjectBindingPattern(n))return t;for(const o of n.getElements()){const a=o.getPropertyNameNode()?.getText()??o.getName(),c=o.getNameNode();if(a==="args"&&i.isObjectBindingPattern(c))for(const l of c.getElements())t.add(l.getName())}return t},Cr=e=>{if(ls(e))return!0;const t=kr(e);return t.size===0?!1:e.getDescendantsOfKind(u.Identifier).some(s=>t.has(s.getText()))},Kr=e=>{for(const t of e.getProperties()){if(!i.isPropertyAssignment(t)||!Lr.has(t.getName()))continue;const s=t.getInitializer();if(s!==void 0&&Cr(s))return!0}return!1},Rr=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=S(r.getExpression());if(n===void 0||!Tr.has(n))continue;const[o]=r.getArguments();if(o===void 0||!i.isObjectLiteralExpression(o))continue;let a;for(const c of o.getDescendantsOfKind(u.CallExpression))if(S(c.getExpression())==="tool"&&(a=Dr(c),a!==void 0))break;a!==void 0&&s.push({exportName:x(r),file:t,line:r.getStartLineNumber(),method:n,sideEffect:a,userInputDerived:Kr(o)})}return s},Mr=(e,t)=>{const s=[];for(const r of g(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Rr(n,p(t,r)))}return s},jr=e=>{if(!i.isPropertyAccessExpression(e)||e.getName()!=="fetch")return!1;const t=e.getExpression();return i.isIdentifier(t)&&t.getText()==="ctx"},zr=(e,t)=>{if(!jr(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!w(s)))return{exportName:x(e),file:t,line:e.getStartLineNumber()}},qr=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=zr(r,t);n&&s.push(n)}return s},Br=(e,t)=>{const s=[];for(const r of g(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...qr(n,p(t,r)))}return s},Ft=e=>e.getProperties().some(t=>i.isSpreadAssignment(t)),Ur=e=>{const t=e.getArguments()[0];if(!t||!i.isObjectLiteralExpression(t))return{objects:[],opaque:!0};const s=t.getProperty("args");if(!s)return{objects:[],opaque:!1};if(!i.isPropertyAssignment(s))return{objects:[],opaque:!0};const r=s.getInitializer();return!r||!i.isObjectLiteralExpression(r)?{objects:[],opaque:!0}:{objects:[r],opaque:Ft(r)}},Vr=e=>{const t=[];let s=!1,r=e;for(;i.isCallExpression(r);){const n=r.getExpression();if(!i.isPropertyAccessExpression(n))break;if(n.getName()==="input"){const o=r.getArguments()[0];o&&i.isObjectLiteralExpression(o)?(t.push(o),s||=Ft(o)):s=!0}r=n.getExpression()}return{objects:t,opaque:s}},Ot=(e,t)=>t?Vr(t):Ur(e),Wr=e=>e.flatMap(t=>t.getProperties().filter(s=>i.isPropertyAssignment(s)||i.isShorthandPropertyAssignment(s)).map(s=>s.getName())),_r=/\.check\(|\.meta\(|length|max/iu,Gr=/\bv\.any\s*\(/u,Hr=/\bv\.string\s*\(/u,Qr=e=>Gr.test(e),Jr=e=>Hr.test(e)&&!_r.test(e),Xr=e=>{const t=[],s=[];for(const r of e)for(const n of r.getProperties()){if(!i.isPropertyAssignment(n))continue;const o=n.getInitializer();if(!o)continue;const a=o.getText(),c=n.getName();Qr(a)?t.push(c):Jr(a)&&s.push(c)}return{anyArgs:t,unboundedStringArgs:s}},Zr=(e,t)=>{const s=e.getInitializer();if(!s||!i.isCallExpression(s))return;const r=K(s);if(r?.visibility!=="public")return;const{objects:n}=Ot(s,r.receiver),{anyArgs:o,unboundedStringArgs:a}=Xr(n);if(!(o.length===0&&a.length===0))return{anyArgs:o,exportName:e.getName(),file:t,line:s.getStartLineNumber(),unboundedStringArgs:a}},Yr=(e,t)=>{const s=[];for(const r of e.getVariableStatements())if(r.isExported())for(const n of r.getDeclarations()){const o=Zr(n,t);o&&s.push(o)}return s},en=(e,t)=>{const s=[];for(const r of g(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Yr(n,p(t,r)))}return s},b=(e,t)=>{if(!e||!i.isObjectLiteralExpression(e))return;const s=e.getProperty(t);return s&&i.isPropertyAssignment(s)?s.getInitializer():void 0},ye=e=>e?.getKind()===u.TrueKeyword,tn=e=>e?.getKind()===u.FalseKeyword,sn=e=>e!==void 0&&i.isNumericLiteral(e)&&e.getLiteralValue()===0,rn=new Set(["lunoraAuthAdapter","lunoraD1Adapter"]),nn=e=>!e||!i.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>i.isCallExpression(t)&&S(t.getExpression())==="scim"),on=e=>e!==void 0&&i.isCallExpression(e)&&rn.has(S(e.getExpression())??""),an=e=>!e||!i.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>i.isStringLiteral(t)&&t.getLiteralText()==="*"),cn=e=>{const t=b(e,"advanced"),s=b(e,"emailAndPassword"),r=b(e,"session");return{analyzable:!0,disableCsrfCheck:ye(b(t,"disableCSRFCheck")),emailPasswordEnabled:ye(b(s,"enabled")),requireEmailVerification:ye(b(s,"requireEmailVerification")),scimOnNonTransactionalAdapter:nn(b(e,"plugins"))&&on(b(e,"database")),secureCookiesDisabled:tn(b(t,"useSecureCookies")),sessionFreshAgeZero:sn(b(r,"freshAge")),trustedOriginsWildcard:an(b(e,"trustedOrigins"))}},un=()=>({analyzable:!1,disableCsrfCheck:!1,emailPasswordEnabled:!1,requireEmailVerification:!1,scimOnNonTransactionalAdapter:!1,secureCookiesDisabled:!1,sessionFreshAgeZero:!1,trustedOriginsWildcard:!1}),ln=(e,t)=>{if(S(e.getExpression())!=="createAuth")return;const s=e.getArguments()[0],r=s!==void 0&&i.isObjectLiteralExpression(s)&&s.getProperties().some(o=>i.isSpreadAssignment(o)),n=s!==void 0&&i.isObjectLiteralExpression(s)&&!r?cn(s):un();return{exportName:x(e),file:t,line:e.getStartLineNumber(),...n}},dn=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=ln(r,t);n&&s.push(n)}return s},gn=(e,t)=>{const s=[];for(const r of g(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...dn(n,p(t,r)))}return s},pn=(e,t)=>{if(!i.isPropertyAccessExpression(e))return;const s=e.getName();if(t.methods.has(s))return t.matchReceiver(e.getExpression().getText())?s:void 0},fn=(e,t,s)=>{const r=pn(e.getExpression(),s);if(r===void 0)return;const n=e.getArguments()[s.argIndex];if(!(!n||!w(n)||O(n))&&!(s.requireUnmodifiedReach===!0&&!ds(n)))return{exportName:x(e),file:t,line:e.getStartLineNumber(),method:r}},mn=(e,t,s)=>{const r=[];for(const n of e.getDescendantsOfKind(u.CallExpression)){const o=fn(n,t,s);o&&r.push(o)}return r},Z=(e,t,s)=>{const r=[];for(const n of g(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);r.push(...mn(o,p(t,n),s))}return r},hn=new Set(["content","pdf","scrape","screenshot"]),xn=(e,t)=>Z(e,t,{argIndex:0,matchReceiver:s=>s==="ctx.browser",methods:hn}),En=new Set(["createBrowser","createInboundEmailHandler","createPayment"]),yn=new Set(["RateLimiter"]),$n=new Set(["extend"]),Dt=e=>{const t=[],s=[];let r=!1;for(const n of e.getProperties()){if(i.isSpreadAssignment(n)){r=!0;continue}if(i.isPropertyAssignment(n)){const o=n.getName();t.push(o),n.getInitializer()?.getKind()===u.TrueKeyword&&s.push(o);continue}(i.isShorthandPropertyAssignment(n)||i.isMethodDeclaration(n))&&t.push(n.getName())}return{analyzable:!r,presentKeys:t,trueKeys:s}},gt=e=>e&&i.isObjectLiteralExpression(e)?Dt(e):{analyzable:!1,presentKeys:[],trueKeys:[]},An=e=>{const t=e.getStatements(),[s]=t;if(t.length!==1||s===void 0||!i.isReturnStatement(s))return;const r=s.getExpression();return r!==void 0&&i.isObjectLiteralExpression(r)?r:void 0},Sn=e=>{if(i.isObjectLiteralExpression(e))return e;if(i.isParenthesizedExpression(e)){const t=e.getExpression();return i.isObjectLiteralExpression(t)?t:void 0}return i.isBlock(e)?An(e):void 0},bn=e=>{const t=e&&(i.isArrowFunction(e)||i.isFunctionExpression(e))?e:void 0,s=t&&Sn(t.getBody());return s?Dt(s):{analyzable:!1,presentKeys:[],trueKeys:[]}},vn=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=S(r.getExpression());n!==void 0&&(En.has(n)?s.push({callee:n,file:t,line:r.getStartLineNumber(),...gt(r.getArguments()[0])}):$n.has(n)&&s.push({callee:n,file:t,line:r.getStartLineNumber(),...bn(r.getArguments()[0])}))}for(const r of e.getDescendantsOfKind(u.NewExpression)){const n=S(r.getExpression());n===void 0||!yn.has(n)||s.push({callee:n,file:t,line:r.getStartLineNumber(),...gt(r.getArguments()[0])})}return s},Nn=(e,t)=>{const s=[];for(const r of g(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...vn(n,p(t,r)))}return s},pt="ctx.containers.",Pn=e=>{if(!e.startsWith(pt))return!1;const t=e.slice(pt.length);return t.length>0&&!t.includes(".")},wn=(e,t)=>Z(e,t,{argIndex:0,matchReceiver:Pn,methods:new Set(["get"])}),In=new Set(["allow","deny","setAllowed"]),Tn=e=>{const t=e.getArguments()[0];if(!t||!i.isObjectLiteralExpression(t))return!1;const s=t.getProperty("enableInternet");return s!==void 0&&i.isPropertyAssignment(s)&&i.isTrueLiteral(s.getInitializerOrThrow())},Ln=(e,t)=>{const s=e.getExpression();if(!(!i.isPropertyAccessExpression(s)||s.getName()!=="start"||!Tn(e)))return{detail:"enableInternet: true",exportName:x(e),file:t,kind:"enable_internet",line:e.getStartLineNumber()}},Fn=(e,t)=>{const s=e.getExpression();if(!i.isPropertyAccessExpression(s)||!In.has(s.getName()))return;const r=s.getExpression();if(!(!i.isPropertyAccessExpression(r)||r.getName()!=="egress"))return{detail:s.getName(),exportName:x(e),file:t,kind:"egress_relaxation",line:e.getStartLineNumber()}},On=(e,t)=>Ln(e,t)??Fn(e,t),Dn=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=On(r,t);n&&s.push(n)}return s},kn=(e,t)=>{const s=[];for(const r of g(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Dn(n,p(t,r)))}return s},Cn="env.ts",Kn=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineEnv";for(const s of t.getDeclarations())if(i.isImportSpecifier(s))return X(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineEnv":!1;return!1},Rn=e=>{const t=e.getSymbol();if(!t)return!1;for(const s of t.getDeclarations()){if(!i.isNamespaceImport(s))continue;const r=s.getFirstAncestorByKind(u.ImportDeclaration);return r!==void 0&&X(r.getModuleSpecifierValue())}return!1},Mn=e=>{if(i.isIdentifier(e))return Kn(e);if(i.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineEnv"&&i.isIdentifier(t)&&Rn(t)}return!1},jn=e=>{const t=[];for(const s of e.getVariableDeclarations()){if(!s.isExported())continue;const r=s.getInitializer();if(r?.getKind()!==u.CallExpression||!Mn(r.getExpression()))continue;const n=s.getNameNode();if(!i.isIdentifier(n))throw J(n,"defineEnv exports must be plain named exports (no destructuring)");t.push({exportName:n.getText()})}return t},zn=(e,t)=>{const s=d(t,Cn);if(!E(s))return;const r=e.getSourceFile(s)??e.addSourceFileAtPath(s),n=jn(r);if(n.length!==0){if(n.length>1)throw J(r,`lunora/env.ts declares ${n.length.toString()} defineEnv() contracts (${n.map(o=>o.exportName).join(", ")}); exactly one is allowed`);return n[0]}},qn=new Set(["defineExportSink","r2Sink","webhookExportSink"]),Bn=e=>{const t=e.getExpression();if(!i.isIdentifier(t))return;const s=t.getText();return qn.has(s)?s:void 0},Un=e=>{const t=[],s=[];for(const r of e.getProperties()){if(i.isSpreadAssignment(r))return{analyzable:!1,emptyKeys:[],presentKeys:[]};if(i.isPropertyAssignment(r)){const n=r.getName();t.push(n);const o=r.getInitializer();o&&i.isStringLiteral(o)&&o.getLiteralText()===""&&s.push(n);continue}(i.isShorthandPropertyAssignment(r)||i.isMethodDeclaration(r)||i.isGetAccessorDeclaration(r))&&t.push(r.getName())}return{analyzable:!0,emptyKeys:s,presentKeys:t}},Vn=(e,t)=>{const s=[];for(const r of g(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r),o=p(t,r);for(const a of n.getDescendantsOfKind(u.CallExpression)){const c=Bn(a);if(c===void 0)continue;const l=a.getArguments()[0],m=l&&i.isObjectLiteralExpression(l)?Un(l):{analyzable:!1,emptyKeys:[],presentKeys:[]};s.push({analyzable:m.analyzable,emptyKeys:m.emptyKeys,factory:c,file:o,line:a.getStartLineNumber(),presentKeys:m.presentKeys})}}return s},Wn=new Map([["dbRateLimit",2],["rateLimit",2],["verifyTurnstileMiddleware",0]]),_n=new Set(["dbRateLimit","rateLimit"]),Gn=e=>{if(!e||!i.isObjectLiteralExpression(e))return!1;const t=e.getProperty("failOpen");return t!==void 0&&i.isPropertyAssignment(t)&&t.getInitializer()?.getKind()===u.TrueKeyword},Hn=e=>{const t=e.getArguments()[1];return t&&i.isStringLiteral(t)?t.getLiteralValue():""},Qn=(e,t)=>{const s=S(e.getExpression());if(s===void 0)return;const r=Wn.get(s);if(r!==void 0)return{callee:s,exportName:x(e),failOpen:Gn(e.getArguments()[r]),file:t,limitName:_n.has(s)?Hn(e):"",line:e.getStartLineNumber()}},Jn=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=Qn(r,t);n&&s.push(n)}return s},Xn=(e,t)=>{const s=[];for(const r of g(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Jn(n,p(t,r)))}return s},Zn=e=>{const t=r=>i.isIdentifier(r)&&r.getText()==="ctx",s=new Set;for(const r of e.getDescendantsOfKind(u.PropertyAccessExpression))t(r.getExpression())&&s.add(r.getName());for(const r of e.getDescendantsOfKind(u.VariableDeclaration)){const n=r.getInitializer(),o=r.getNameNode();if(!(n===void 0||!t(n)||!i.isObjectBindingPattern(o)))for(const a of o.getElements()){const c=a.getPropertyNameNode()?.getText()??a.getName();c&&s.add(c)}}return s},Yn=(e,t)=>{const s=Object.fromEntries(Ee.map(r=>[r.key,!1]));for(const r of g(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r),o=new Set(n.getImportDeclarations().map(c=>c.getModuleSpecifierValue())),a=Zn(n);for(const c of Ee)if(!s[c.key]){if(o.has(c.moduleSpecifier)){s[c.key]=!0;continue}c.contextProperty!==void 0&&a.has(c.contextProperty)&&(s[c.key]=!0)}if(Ee.every(c=>s[c.key]))break}return s},ei=["providerSubscriptionId","state"],ti=["providerEventId","processedAt"],ft=(e,t)=>t.every(s=>s in e.shape),si=e=>{const t=e.find(r=>r.name==="subscriptions"),s=e.find(r=>r.name==="events");return t!==void 0&&s!==void 0&&ft(t,ei)&&ft(s,ti)},ri=(e,t)=>({analytics:e.analytics||t.dependencies.has("@lunora/bindings/analytics"),auth:t.dependencies.has("@lunora/auth"),containers:e.container||t.containerCount>0||t.dependencies.has("@lunora/container"),flags:e.flags||t.dependencies.has("@lunora/flags"),kv:e.kv||t.dependencies.has("@lunora/bindings/kv"),mail:e.mail||t.dependencies.has("@lunora/mail"),notifications:e.notify||t.dependencies.has("@lunora/notify"),payments:e.payments||t.hasPaymentTables,queues:t.queueCount>0||t.dependencies.has("@lunora/queue"),scheduler:e.scheduler||t.cronCount>0||t.dependencies.has("@lunora/scheduler"),storage:e.storage||t.storageRuleCount>0||t.storageColumnCount>0||t.dependencies.has("@lunora/storage"),vectors:e.vectors||t.vectorIndexCount>0||t.dependencies.has("@lunora/bindings/vectors"),workflows:e.workflows||t.workflowCount>0||t.dependencies.has("@lunora/workflow")}),ni=e=>i.isIdentifier(e)&&e.getText()==="ctx",ii=e=>{if(!i.isPropertyAccessExpression(e)||e.getName()!=="boolean")return!1;const t=e.getExpression();return i.isPropertyAccessExpression(t)&&t.getName()==="flags"&&ni(t.getExpression())},oi=e=>{if(e?.getKind()===u.TrueKeyword)return!0;if(e?.getKind()===u.FalseKeyword)return!1},ai=(e,t)=>{if(!ii(e.getExpression()))return;const[s,r]=e.getArguments();if(!s||!(i.isStringLiteral(s)||i.isNoSubstitutionTemplateLiteral(s)))return;const n=s.getLiteralValue(),o=oi(r);if(!(n.length===0||o===void 0))return{defaultValue:o,exportName:x(e),file:t,key:n,line:e.getStartLineNumber()}},ci=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=ai(r,t);n&&s.push(n)}return s},ui=(e,t)=>{const s=[];for(const r of g(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...ci(n,p(t,r)))}return s},li=e=>{const t=e.getExpression();return i.isPropertyAccessExpression(t)&&t.getName()==="withGeoIndex"},di=e=>{const t=e.getArguments()[0];return t&&i.isStringLiteral(t)?t.getLiteralText():""},gi=(e,t)=>{const s=[];for(const r of g(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r),o=p(t,r);for(const a of n.getDescendantsOfKind(u.CallExpression))li(a)&&s.push({file:o,indexName:di(a),line:a.getStartLineNumber()})}return s},pi=new Set(["delete","get","head","options","patch","post","put"]),fi=new Set(["handler","stream"]),mi=new Set(["runAction","runMutation"]),hi=new Set(["delete","insert","insertManyUnsafe","patch","replace"]),_=(e,t)=>e!==void 0&&i.isIdentifier(e)&&e.getText()===t,mt=e=>e!==void 0&&(i.isArrowFunction(e)||i.isFunctionExpression(e))?e:void 0,ht=(e,t)=>{const s=e.getParameters()[0];if(s===void 0)return;const r=s.getNameNode();if(t)return i.isIdentifier(r)?r.getText():void 0;if(i.isObjectBindingPattern(r)){for(const n of r.getElements())if((n.getPropertyNameNode()?.getText()??n.getNameNode().getText())==="ctx"){const o=n.getNameNode();return i.isIdentifier(o)?o.getText():void 0}}},xt=(e,t)=>{const s=e.getBody(),r=s.getDescendantsOfKind(u.CallExpression);i.isCallExpression(s)&&r.unshift(s);for(const n of r){const o=n.getExpression();if(!i.isPropertyAccessExpression(o))continue;const a=o.getName(),c=o.getExpression();if(mi.has(a)&&_(c,t))return a;if(hi.has(a)&&i.isPropertyAccessExpression(c)&&c.getName()==="db"&&_(c.getExpression(),t))return`db.${a}`}},Et=(e,t)=>{const s=e.getBody();for(const r of s.getDescendantsOfKind(u.PropertyAccessExpression))if(r.getName()==="auth"&&_(r.getExpression(),t))return!0;for(const r of s.getDescendantsOfKind(u.VariableDeclaration)){const n=r.getNameNode();if(!(!i.isObjectBindingPattern(n)||!_(r.getInitializer(),t))){for(const o of n.getElements())if((o.getPropertyNameNode()?.getText()??o.getNameNode().getText())==="auth")return!0}}return!1},xi=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!fi.has(t.getName()))return;let s=t.getExpression();for(;i.isCallExpression(s);){const r=s.getExpression();if(!i.isPropertyAccessExpression(r))return;const n=r.getName();if(pi.has(n)){const o=r.getExpression();return i.isIdentifier(o)&&o.getText()==="httpRoute"?n.toUpperCase():void 0}s=r.getExpression()}},Ei=(e,t)=>{const s=e.getExpression();if(i.isIdentifier(s)&&s.getText()==="httpAction"){const c=mt(e.getArguments()[0]),l=c&&ht(c,!0);if(!c||l===void 0)return;const m=xt(c,l);return m===void 0?void 0:{exportName:x(e),file:t,kind:"httpAction",line:e.getStartLineNumber(),readsAuth:Et(c,l),sideEffect:m}}const r=xi(e);if(r===void 0)return;const n=mt(e.getArguments()[0]),o=n&&ht(n,!1);if(!n||o===void 0)return;const a=xt(n,o);return a===void 0?void 0:{exportName:x(e),file:t,kind:"httpRoute",line:e.getStartLineNumber(),method:r,readsAuth:Et(n,o),sideEffect:a}},yi=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=Ei(r,t);n&&s.push(n)}return s},$i=(e,t)=>{const s=[];for(const r of g(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...yi(n,p(t,r)))}return s},Ai=new Set(["btoa","encodeURI","encodeURIComponent","isSafeHeaderValue","Number","parseFloat","parseInt"]),Si=new Set(["append","set"]),be=e=>i.isIdentifier(e)?e.getText():i.isPropertyAccessExpression(e)?e.getName():"",kt=e=>e!==void 0&&(i.isStringLiteral(e)||i.isNoSubstitutionTemplateLiteral(e))?e.getLiteralText():"",yt=(e,t)=>(i.isCallExpression(e)?[e,...e.getDescendantsOfKind(u.CallExpression)]:e.getDescendantsOfKind(u.CallExpression)).some(s=>Ai.has(be(s.getExpression()))&&ps(s,t)),bi=(e,t)=>{if(yt(e,t))return!0;const s=Q(e);return s!==void 0&&yt(s,t)},Se=(e,t)=>gs(e,t)&&!bi(e,t),vi=e=>{if(i.isPropertyAccessExpression(e)&&e.getName()==="headers")return!0;const t=Q(e);return t!==void 0&&i.isNewExpression(t)&&be(t.getExpression())==="Headers"},G=e=>{if(e===void 0)return;if(i.isObjectLiteralExpression(e))return e;const t=Q(e);return t!==void 0&&i.isObjectLiteralExpression(t)?t:void 0},ve=(e,t,s)=>{for(const r of e.getProperties())if(i.isPropertyAssignment(r)){const n=r.getInitializer();n!==void 0&&Se(n,s.requestName)&&s.rows.push({exportName:s.exportName,file:s.relativePath,headerName:kt(r.getNameNode()),line:n.getStartLineNumber(),via:t})}else if(i.isShorthandPropertyAssignment(r)){const n=r.getNameNode();Se(n,s.requestName)&&s.rows.push({exportName:s.exportName,file:s.relativePath,headerName:r.getName(),line:n.getStartLineNumber(),via:t})}else if(i.isSpreadAssignment(r)){const n=G(r.getExpression());n!==void 0&&ve(n,t,s)}},Ct=(e,t)=>{const s=G(e);if(s===void 0)return;const r=s.getProperty("headers");if(r===void 0||!i.isPropertyAssignment(r))return;const n=G(r.getInitializer());n!==void 0&&ve(n,"response-init",t)},Ni=(e,t)=>{const s=be(e.getExpression());if(s==="Response")Ct(e.getArguments()[1],t);else if(s==="Headers"){const r=G(e.getArguments()[0]);r!==void 0&&ve(r,"headers-ctor",t)}},Pi=(e,t)=>{const s=e.getExpression();if(!i.isPropertyAccessExpression(s))return;const r=s.getName(),n=s.getExpression();if(r==="json"&&i.isIdentifier(n)&&n.getText()==="Response"){Ct(e.getArguments()[1],t);return}if(Si.has(r)&&vi(n)){const o=e.getArguments()[1];o!==void 0&&Se(o,t.requestName)&&t.rows.push({exportName:t.exportName,file:t.relativePath,headerName:kt(e.getArguments()[0]),line:o.getStartLineNumber(),via:r==="set"?"headers-set":"headers-append"})}},wi=(e,t)=>{for(const s of e.getDescendantsOfKind(u.NewExpression))Ni(s,t);for(const s of e.getDescendantsOfKind(u.CallExpression))Pi(s,t)},Ii=(e,t)=>{const s=e.getExpression();if(!i.isIdentifier(s)||s.getText()!=="httpAction")return[];const r=is(e.getArguments()[0]);if(r===void 0)return[];const n=r.getParameters()[1];if(n===void 0)return[];const o=n.getNameNode();if(!i.isIdentifier(o))return[];const a=[];return wi(r,{exportName:x(e),relativePath:t,requestName:o.getText(),rows:a}),a},Ti=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression))s.push(...Ii(r,t));return s},Li=(e,t)=>{const s=[];for(const r of g(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Ti(n,p(t,r)))}return s},Kt="identity.ts",Fi=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineIdentity";for(const s of t.getDeclarations())if(i.isImportSpecifier(s))return X(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineIdentity":!1;return!1},Oi=e=>{const t=e.getSymbol();if(!t)return!1;for(const s of t.getDeclarations()){if(!i.isNamespaceImport(s))continue;const r=s.getFirstAncestorByKind(u.ImportDeclaration);return r!==void 0&&X(r.getModuleSpecifierValue())}return!1},Di=e=>{if(i.isIdentifier(e))return Fi(e);if(i.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineIdentity"&&i.isIdentifier(t)&&Oi(t)}return!1},ki=e=>{const t=[];for(const s of e.getVariableDeclarations()){if(!s.isExported())continue;const r=s.getInitializer();if(r?.getKind()!==u.CallExpression||!Di(r.getExpression()))continue;const n=s.getNameNode();if(!i.isIdentifier(n))throw J(n,"defineIdentity exports must be plain named exports (no destructuring)");t.push({exportName:n.getText()})}return t},Ci=(e,t)=>{const s=d(t,Kt);if(!E(s))return;const r=e.getSourceFile(s)??e.addSourceFileAtPath(s),n=ki(r);if(n.length!==0){if(n.length>1)throw J(r,`lunora/identity.ts declares ${n.length.toString()} defineIdentity() contracts (${n.map(o=>o.exportName).join(", ")}); exactly one is allowed`);return n[0]}},Ki=new Set(["auth","context.auth","ctx.auth"]),Ri="userId",Mi=e=>{const t=new Set;for(const s of e.getProperties()){if(i.isSpreadAssignment(s))return;(i.isPropertyAssignment(s)||i.isShorthandPropertyAssignment(s)||i.isMethodDeclaration(s))&&t.add(s.getName())}return t},ji=(e,t)=>{const s=d(t,Kt);if(!E(s))return;const r=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const n of r.getDescendantsOfKind(u.CallExpression)){if(S(n.getExpression())!=="defineIdentity")continue;const[o]=n.getArguments();return o&&i.isObjectLiteralExpression(o)?Mi(o):void 0}},$t=e=>{if(!(e===void 0||!i.isPropertyAccessExpression(e)||e.getName()!=="identity"))return Ki.has(e.getExpression().getText())?e:void 0},zi=e=>{if(i.isPropertyAccessExpression(e)&&$t(e.getExpression())!==void 0)return e.getName();if(i.isElementAccessExpression(e)&&$t(e.getExpression())!==void 0){const t=e.getArgumentExpression();return t&&i.isStringLiteral(t)?t.getLiteralValue():void 0}},qi=(e,t,s)=>{const r=[];for(const n of e.getDescendants()){const o=zi(n);o!==void 0&&r.push({declared:o===Ri||s.has(o),exportName:x(n),file:t,key:o,line:n.getStartLineNumber()})}return r},Bi=(e,t)=>{const s=ji(e,t);if(s===void 0)return[];const r=[];for(const n of g(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);r.push(...qi(o,p(t,n),s))}return r},Ui=e=>{if(!i.isObjectLiteralExpression(e))return;const t=e.getProperty("key");return t&&i.isPropertyAssignment(t)?t.getInitializer():void 0},Vi=(e,t)=>{if(S(e.getExpression())!=="buildImageDeliveryUrl")return;const s=e.getArguments()[0];if(!s)return;const r=Ui(s);if(!(!r||!w(r)||O(r)))return{exportName:x(e),file:t,line:e.getStartLineNumber()}},Wi=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=Vi(r,t);n&&s.push(n)}return s},_i=(e,t)=>{const s=[];for(const r of g(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Wi(n,p(t,r)))}return s},Gi=new Set(["delete","get","getRaw","getWithMetadata","put"]),Hi=(e,t)=>Z(e,t,{argIndex:0,matchReceiver:s=>s==="ctx.kv"||s.startsWith("ctx.kv."),methods:Gi}),Qi=new Set(["queue","send"]),At=new Set(["bcc","cc","to"]),Ji=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName();if(!Qi.has(t))return;const s=e.getExpression().getText();return s==="ctx.mail"||s==="ctx.email"?t:void 0},Xi=e=>i.isObjectLiteralExpression(e)?e.getProperties().some(t=>{if(i.isShorthandPropertyAssignment(t)){const r=t.getNameNode();return At.has(t.getName())&&w(r)&&!O(r)}if(!i.isPropertyAssignment(t)||!At.has(t.getName()))return!1;const s=t.getInitializer();return s!==void 0&&w(s)&&!O(s)}):!1,Zi=(e,t)=>{const s=Ji(e.getExpression());if(s===void 0)return;const r=e.getArguments()[0];if(!(!r||!Xi(r)))return{exportName:x(e),file:t,line:e.getStartLineNumber(),method:s}},Yi=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=Zi(r,t);n&&s.push(n)}return s},eo=(e,t)=>{const s=[];for(const r of g(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Yi(n,p(t,r)))}return s},to=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="replace")return!1;const s=t.getExpression();return i.isPropertyAccessExpression(s)?s.getName()==="db":i.isIdentifier(s)&&s.getText()==="db"},so=e=>{const t=e.getArguments()[0];if(t===void 0||!i.isObjectLiteralExpression(t))return;const s=t.getProperty("server");if(s!==void 0)return i.isPropertyAssignment(s)?s.getInitializer():s},ro=e=>{if(!e.isExported())return;const t=e.getInitializer();if(t?.getKind()!==u.CallExpression)return;const s=t;return qs(s.getExpression())?s:void 0},no=e=>{const t=ro(e),s=t===void 0?void 0:so(t);if(s===void 0)return[];const r=e.getNameNode(),n=i.isIdentifier(r)?r.getText():"";return s.getDescendantsOfKind(u.CallExpression).filter(o=>to(o)).map(o=>({exportName:n,file:"lunora/mutators.ts",line:o.getStartLineNumber()}))},io=e=>e.getVariableDeclarations().flatMap(t=>no(t)),oo=(e,t)=>{const s=d(t,zs);if(!E(s))return[];const r=e.getSourceFile(s)??e.addSourceFileAtPath(s);return io(r)},ao=new Set(["delete","get","patch"]),co=new Set(["accountId","authorId","companyId","createdBy","createdById","customerId","groupId","memberId","organizationId","orgId","ownerId","projectId","teamId","tenantId","userId","workspaceId"]),uo=new Set(["auth","identity","session","user"]),lo=new Set([u.EqualsEqualsEqualsToken,u.EqualsEqualsToken,u.ExclamationEqualsEqualsToken,u.ExclamationEqualsToken]),go=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="normalizeId"||!C(t.getExpression()))return;const s=e.getArguments()[0];return s&&i.isStringLiteral(s)?s.getLiteralText():""},po=e=>{let t=e,s=t.getParent();for(;s!==void 0&&(i.isAsExpression(s)||i.isParenthesizedExpression(s)||i.isNonNullExpression(s));)t=s,s=t.getParent();if(s===void 0||!i.isVariableDeclaration(s))return;const r=s.getNameNode();return i.isIdentifier(r)?r.getText():void 0},fo=(e,t)=>e.getDescendantsOfKind(u.Identifier).some(s=>s.getText()===t),mo=e=>i.isThrowStatement(e)||i.isReturnStatement(e)||e.getDescendantsOfKind(u.ThrowStatement).length>0||e.getDescendantsOfKind(u.ReturnStatement).length>0,ho=(e,t)=>e.getDescendantsOfKind(u.IfStatement).some(s=>fo(s.getExpression(),t)&&mo(s.getThenStatement())),xo=(e,t)=>{for(const s of e.getDescendantsOfKind(u.CallExpression)){const r=s.getExpression();if(!i.isPropertyAccessExpression(r))continue;const n=r.getName();if(!ao.has(n))continue;const o=r.getExpression();if(!(C(o)||i.isPropertyAccessExpression(o)&&C(o.getExpression())))continue;const a=s.getArguments()[0];if(a!==void 0&&i.isIdentifier(a)&&a.getText()===t)return n}},Eo=e=>{let t=e;for(;i.isPropertyAccessExpression(t)||i.isElementAccessExpression(t)||i.isNonNullExpression(t)||i.isParenthesizedExpression(t)||i.isAsExpression(t)||i.isAwaitExpression(t);)t=t.getExpression();return i.isIdentifier(t)?t.getText():void 0},yo=e=>e.getDescendantsOfKind(u.CallExpression).some(t=>t.getArguments().some(s=>Eo(s)==="ctx")),$o=e=>e.getDescendantsOfKind(u.BinaryExpression).some(t=>lo.has(t.getOperatorToken().getKind())?i.isPropertyAccessExpression(t.getLeft())||i.isPropertyAccessExpression(t.getRight()):!1),Ao=e=>{for(const t of e.getDescendantsOfKind(u.Identifier))if(co.has(t.getText()))return!0;for(const t of e.getDescendantsOfKind(u.PropertyAccessExpression)){const s=t.getExpression();if(i.isIdentifier(s)&&s.getText()==="ctx"&&uo.has(t.getName()))return!0}return yo(e)||$o(e)},So=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!i.isCallExpression(s))return[];const r=K(s);if(r?.kind!=="query"&&r?.kind!=="mutation")return[];const n=It(s);if(n===void 0)return[];const o=r.receiver!==void 0&&Tt(r.receiver,"use","rls"),a=Ao(n),c=new Set,l=[];for(const m of n.getDescendantsOfKind(u.CallExpression)){const $=go(m);if($===void 0)continue;const I=po(m);if(I===void 0||c.has(I)||!ho(n,I))continue;const R=xo(n,I);R!==void 0&&(c.add(I),l.push({exportName:e.getName(),file:t,line:m.getStartLineNumber(),mentionsOwnership:a,sinkMethod:R,table:$,usesRls:o,visibility:r.visibility}))}return l},bo=(e,t)=>{const s=[];for(const r of g(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r),o=p(t,r);for(const a of n.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...So(c,o))}return s},vo=new Set(["accountId","authorId","createdBy","createdById","organizationId","orgId","ownerId","tenantId","updatedBy","userId","workspaceId"]),No=new Set(["insert","insertManyUnsafe","patch","replace"]),Po=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName();if(!No.has(t))return;const s=e.getExpression();if(!i.isPropertyAccessExpression(s)||s.getName()!=="db")return;const r=s.getExpression();return i.isIdentifier(r)&&r.getText()==="ctx"?t:void 0},wo=(e,t)=>{if(t!=="insertManyUnsafe")return i.isObjectLiteralExpression(e)?[e]:[];if(!i.isArrayLiteralExpression(e))return[];const s=[];for(const r of e.getElements())i.isObjectLiteralExpression(r)&&s.push(r);return s},Io=(e,t,s,r)=>{const n=[];for(const o of e.getProperties()){let a,c;i.isPropertyAssignment(o)?(a=o.getName(),c=o.getInitializer()):i.isShorthandPropertyAssignment(o)&&(a=o.getName(),c=o.getNameNode()),!(a===void 0||c===void 0||!vo.has(a))&&w(c)&&!O(c)&&n.push({exportName:x(s),field:a,file:r,line:s.getStartLineNumber(),method:t})}return n},To=(e,t)=>{const s=Po(e.getExpression());if(s===void 0)return[];const r=e.getArguments()[1];return r?wo(r,s).flatMap(n=>Io(n,s,e,t)):[]},Lo=(e,t,s)=>{const r=[];for(const n of e.getDescendantsOfKind(u.CallExpression))for(const o of To(n,t)){const a=s(o.exportName);r.push(a===void 0?o:{...o,visibility:a})}return r},Fo=(e,t,s=[])=>{const r=[],n=new Map(s.map(o=>[`${o.filePath}:${o.exportName}`,o.visibility]));for(const o of g(t)){const a=e.getSourceFile(o)??e.addSourceFileAtPath(o),c=p(t,o);r.push(...Lo(a,c,l=>n.get(`${c}:${l}`)))}return r},Oo=new Set(["createAutumnAdapter","createDodoPaymentsAdapter","createPolarAdapter","createStripeAdapter"]),Do=e=>e&&i.isNumericLiteral(e)?Number(e.getText()):void 0,ko=e=>{const t=e.getProperty("webhookToleranceSeconds");return t&&i.isPropertyAssignment(t)?Do(t.getInitializer()):void 0},Co=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=S(r.getExpression());if(n===void 0||!Oo.has(n))continue;const[o]=r.getArguments(),a=o&&i.isObjectLiteralExpression(o)?ko(o):void 0;s.push({callee:n,exportName:x(r),file:t,line:r.getStartLineNumber(),...a===void 0?{}:{toleranceSeconds:a}})}return s},Ko=(e,t)=>{const s=[];for(const r of g(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Co(n,p(t,r)))}return s},Ro=new Set(["defineQueue","defineWorkflow"]),Mo=new Set(["run","runAction","runMutation","runQuery"]),jo=new Set(["api","internal"]),zo=e=>{const t=e.getExpression();return i.isIdentifier(t)?t.getText():void 0},qo=e=>{const t=e.getArguments()[0];if(!t||!i.isObjectLiteralExpression(t))return;const s=t.getProperty("handler");if(s===void 0||!i.isPropertyAssignment(s))return;const r=s.getInitializer();if(r&&(i.isArrowFunction(r)||i.isFunctionExpression(r)))return r},Rt=(e,t)=>{const s=e.getParameters()[t]?.getNameNode();return s&&i.isIdentifier(s)?s.getText():void 0},Mt=(e,t)=>e===t||e.startsWith(`${t}.`),jt=e=>{const t=e.getDescendantsOfKind(u.PropertyAccessExpression);return i.isPropertyAccessExpression(e)&&t.push(e),t},St=e=>{const t=e.getParent();return i.isPropertyAccessExpression(t)&&t.getNameNode()===e||i.isPropertyAssignment(t)&&t.getNameNode()===e?!1:!(i.isBindingElement(t)&&t.getNameNode()===e)},zt=e=>{const t=e.getDescendantsOfKind(u.Identifier).filter(s=>St(s));return i.isIdentifier(e)&&St(e)&&t.push(e),t},Bo=e=>{if(!i.isVariableDeclaration(e))return[];const t=e.getNameNode();return i.isIdentifier(t)?[t.getText()]:t.getDescendantsOfKind(u.BindingElement).map(s=>s.getName())},Uo=e=>{const t=Rt(e,1);if(t===void 0)return[];const s=[`${t}.messages`];for(const r of e.getDescendantsOfKind(u.ForOfStatement)){if(r.getExpression().getText()!==`${t}.messages`)continue;const n=r.getInitializer(),o=i.isVariableDeclarationList(n)?n.getDeclarations()[0]?.getNameNode():void 0;o&&i.isIdentifier(o)&&s.push(`${o.getText()}.body`)}return s},Vo=(e,t,s)=>{const r=t==="workflow"?[`${s}.params`]:Uo(e),n=new Set,o=a=>jt(a).some(c=>r.some(l=>Mt(c.getText(),l)))?!0:zt(a).some(c=>n.has(c.getText()));for(const a of e.getDescendantsOfKind(u.VariableDeclaration)){const c=a.getInitializer();if(c&&o(c))for(const l of Bo(a))n.add(l)}return{names:n,prefixes:r}},Wo=(e,t)=>jt(e).some(s=>t.prefixes.some(r=>Mt(s.getText(),r)))?!0:zt(e).some(s=>t.names.has(s.getText())),_o=e=>{if(e===void 0||!i.isPropertyAccessExpression(e))return;const t=[];let s=e;for(;i.isPropertyAccessExpression(s);)t.unshift(s.getName()),s=s.getExpression();const r=t.at(-1);if(!(r===void 0||!i.isIdentifier(s)||!jo.has(s.getText())||t.length<2))return{exportName:r,file:t.slice(0,-1).join("/")}},Go=(e,t,s)=>{const r=Rt(e,0);if(r===void 0)return[];const n=Vo(e,t,r),o=[];for(const a of e.getDescendantsOfKind(u.CallExpression)){const c=a.getExpression();if(!i.isPropertyAccessExpression(c)||!Mo.has(c.getName())||c.getExpression().getText()!==r)continue;const l=a.getArguments()[1];if(!l||!Wo(l,n))continue;const m=_o(a.getArguments()[0]);m!==void 0&&o.push({dispatchKind:t,file:s,handlerExport:x(a),line:a.getStartLineNumber(),targetExport:m.exportName,targetFile:m.file})}return o},Ho=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=zo(r);if(n===void 0||!Ro.has(n))continue;const o=qo(r);o!==void 0&&s.push(...Go(o,n==="defineQueue"?"queue":"workflow",t))}return s},Qo=(e,t)=>{const s=[];for(const r of g(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Ho(n,p(t,r)))}return s},bt={dbRateLimit:"usesRateLimit",emailGateMiddleware:"usesEmailGate",mask:"usesMask",rateLimit:"usesRateLimit",rls:"usesRls",verifyTurnstile:"usesCaptcha",verifyTurnstileMiddleware:"usesCaptcha"},vt=new Set(["account","credential","member","passkey","session","user"]),Jo=e=>e.replaceAll(/[-_]/gu," ").replaceAll(/([a-z0-9])([A-Z])/gu,"$1 $2").split(" ").filter(Boolean).map(t=>t.toLowerCase()),Xo=e=>{const t=Jo(e).at(-1);if(!t)return!1;const s=t.endsWith("s")?t.slice(0,-1):t;return vt.has(t)||vt.has(s)},Zo=e=>{const t=e.replaceAll(/[^a-z0-9]/giu,"").toLowerCase();return t.endsWith("email")||t.endsWith("emailaddress")},Yo=(e,t)=>{const{objects:s,opaque:r}=Ot(e,t);return Wr(s).some(n=>Zo(n))?!0:r?void 0:!1},Ne=e=>{const t=e.getExpression();if(i.isIdentifier(t))return t.getText();if(i.isPropertyAccessExpression(t))return t.getName()},ea=e=>{const t=e.getArguments()[0];return!t||!i.isObjectLiteralExpression(t)?{usesCaptcha:!1,usesRateLimit:!1}:{usesCaptcha:!!t.getProperty("captcha"),usesRateLimit:!!t.getProperty("rateLimit")}},ta=e=>{if(i.isCallExpression(e))return e;if(!i.isIdentifier(e))return;const t=e.getSourceFile().getVariableDeclaration(e.getText())?.getInitializer();return t&&i.isCallExpression(t)?t:void 0},W={usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},sa=e=>{const t=ta(e),s=t?Ne(t):void 0;if(t&&s==="protectPublic"){const r=ea(t);return{...W,usesCaptcha:r.usesCaptcha,usesRateLimit:r.usesRateLimit}}return s!==void 0&&s in bt?{...W,[bt[s]]:!0}:W},ra=e=>{const t={...W};let s=e;for(;i.isCallExpression(s);){const r=s.getExpression();if(!i.isPropertyAccessExpression(r))break;const n=r.getName()==="use"?s.getArguments()[0]:void 0;if(n){const o=sa(n);t.usesCaptcha||=o.usesCaptcha,t.usesEmailGate||=o.usesEmailGate,t.usesMask||=o.usesMask,t.usesRateLimit||=o.usesRateLimit,t.usesRls||=o.usesRls}s=r.getExpression()}return t},na=new Set(["insert","insertMany","insertManyUnsafe","replace"]),ia=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!na.has(t.getName()))return!1;const s=t.getExpression();if(!(i.isPropertyAccessExpression(s)?s.getName()==="db":i.isIdentifier(s)&&s.getText()==="db"))return!1;const r=e.getArguments()[0];return!r||!(i.isStringLiteral(r)||i.isNoSubstitutionTemplateLiteral(r))?!1:Xo(r.getLiteralText())},oa=new Set(["create","runAfter","runAt","send","sendBatch"]),aa=new Set(["queues","scheduler","workflows"]),ca=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!oa.has(t.getName()))return!1;let s=t.getExpression();for(;i.isCallExpression(s)||i.isElementAccessExpression(s)||i.isPropertyAccessExpression(s);){if(i.isPropertyAccessExpression(s)&&aa.has(s.getName())){const r=s.getExpression();if(i.isIdentifier(r)&&r.getText()==="ctx")return!0}s=s.getExpression()}return!1},ua=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="insertManyUnsafe")return!1;const s=t.getExpression();return i.isPropertyAccessExpression(s)?s.getName()==="db":i.isIdentifier(s)&&s.getText()==="db"},qt=new Set(["generateObject","generateText","streamObject","streamText"]),la=e=>{const t=Ne(e);return t!==void 0&&qt.has(t)},da=e=>{const t=Ne(e);if(t===void 0||!qt.has(t))return!1;const s=e.getArguments()[0];return!s||!i.isObjectLiteralExpression(s)||s.getProperties().some(r=>i.isSpreadAssignment(r))?!1:!s.getProperty("maxOutputTokens")},ga=new Set(["log","span","trace"]),pa=new Set(["ai"]),fa=new Set(["email","mail"]),ma=new Set(["ai","browser","fetch","mail","notify","queues","sql","storage","workflows"]),$e=(e,t)=>e.getDescendantsOfKind(u.PropertyAccessExpression).some(s=>{if(!t.has(s.getName()))return!1;const r=s.getExpression();return i.isIdentifier(r)&&r.getText()==="ctx"}),ha=new Set([u.ArrowFunction,u.FunctionDeclaration,u.FunctionExpression,u.GetAccessor,u.MethodDeclaration,u.SetAccessor]),xa=new Set(["every","filter","flatMap","forEach","map","some"]),Ea=new Set(["all","allSettled","race"]),ya=e=>{const t=e.getParent();if(!t||!i.isCallExpression(t)||!t.getArguments().includes(e))return;const s=t.getExpression();if(!i.isPropertyAccessExpression(s))return;const r=s.getName();if(xa.has(r))return t;const n=s.getExpression();if(i.isIdentifier(n)&&n.getText()==="Promise"&&Ea.has(r))return t},$a=e=>{let t=e.getParent();for(;t;){if(i.isTryStatement(t)){const s=t.getTryBlock();if(e.getPos()>=s.getPos()&&e.getEnd()<=s.getEnd())return!0}if(ha.has(t.getKind())){const s=ya(t);if(!s)return!1;t=s;continue}t=t.getParent()}return!1},Aa=e=>{let t=e;for(;;){const s=t.getParent();if(!i.isPropertyAccessExpression(s)||s.getExpression()!==t)return!1;if(s.getName()==="catch")return!0;if(s.getName()!=="then"&&s.getName()!=="finally")return!1;const r=s.getParent();if(!i.isCallExpression(r)||r.getExpression()!==s)return!1;t=r}},Sa=e=>{let t=e;for(;;){const s=t.getParent();if(i.isPropertyAccessExpression(s)&&s.getExpression()===t){t=s;continue}return i.isCallExpression(s)&&s.getExpression()===t?s:void 0}},ba=e=>{let t=!1,s=!0;for(const r of e.getDescendantsOfKind(u.PropertyAccessExpression)){if(!ma.has(r.getName()))continue;const n=r.getExpression();if(!i.isIdentifier(n)||n.getText()!=="ctx")continue;const o=Sa(r);o&&(t=!0,!$a(o)&&!Aa(o)&&(s=!1))}return{handlesErrors:t&&s,reachesOutbound:t}},va=e=>e.getDescendantsOfKind(u.ThrowStatement).some(t=>{const s=t.getExpression();if(!i.isNewExpression(s))return!1;const r=s.getExpression();return i.isIdentifier(r)&&r.getText()==="Error"}),Nt="lunora-advisor-exempt",Na=/^[\s*/]+/u,Pa=/[\w-]/u,wa=e=>{const t=(e.getFirstAncestorByKind(u.VariableStatement)??e).getLeadingCommentRanges().map(s=>s.getText()).join(`
|
|
6
|
+
`);for(const s of t.split(`
|
|
7
|
+
`)){const r=s.replace(Na,"");if(!r.startsWith(Nt))continue;const n=r.slice(Nt.length);if(Pa.test(n.charAt(0)))continue;const o=n.indexOf("--");return{exempt:!0,exemptReason:(o===-1?"":n.slice(o+2).split("*")[0]??"").trim()}}return{exempt:!1,exemptReason:""}},Ia=e=>{const[t]=e.getArguments();if(t){if(i.isObjectLiteralExpression(t)){const s=t.getProperty("handler");return s?i.isPropertyAssignment(s)?s.getInitializer():i.isShorthandPropertyAssignment(s)?s.getNameNode():i.isMethodDeclaration(s)?s:void 0:void 0}return t}},Ta=(e,t)=>{const s=Ia(t);if(!s)return;if(i.isArrowFunction(s)||i.isFunctionExpression(s)||i.isMethodDeclaration(s))return e;if(!i.isIdentifier(s))return;const r=s.getSourceFile(),n=s.getText(),o=r.getVariableDeclaration(n)?.getInitializer();return o&&(i.isArrowFunction(o)||i.isFunctionExpression(o))?o:r.getFunction(n)},La=e=>{let t=!1,s=!1,r=!1,n=!1,o=!1;for(const l of e.getDescendantsOfKind(u.CallExpression))if(ia(l)&&(o=!0),ca(l)&&(t=!0),ua(l)&&(n=!0),la(l)&&(s=!0),da(l)&&(r=!0),o&&t&&n&&r)break;const{handlesErrors:a,reachesOutbound:c}=ba(e);return{callsMail:$e(e,fa),emitsEvent:$e(e,ga),fanOut:t,handlesErrors:a,reachesOutbound:c,runsAiGeneration:s||$e(e,pa),throwsBareError:va(e),unboundedAiGeneration:r,usesInsertManyUnsafe:n,writesUserTable:o}},Fa=(e,t)=>{const s=e.getInitializer();if(!s||!i.isCallExpression(s))return;const r=K(s);if(!r||r.kind!=="query"&&r.kind!=="mutation"&&r.kind!=="action")return;const n=r.receiver?ra(r.receiver):{usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},o=Ta(e,s);return{...o?La(o):{},...wa(e),...n,analyzableBody:o!==void 0,exportName:e.getName(),file:t,hasEmailArg:Yo(s,r.receiver),kind:r.kind,visibility:r.visibility}},Oa=(e,t)=>{const s=[];for(const r of e.getVariableStatements())if(r.isExported())for(const n of r.getDeclarations()){const o=Fa(n,t);o&&s.push(o)}return s},Da=(e,t)=>{const s=[];for(const r of g(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Oa(n,p(t,r)))}return s},ka=new Set(["dbRateLimit","rateLimit"]),Ca=e=>{if(!i.isObjectLiteralExpression(e))return;const t=e.getProperty("key");return t&&i.isPropertyAssignment(t)?t.getInitializer():void 0},Ka=e=>{const t=e.getArguments()[1];return t&&i.isStringLiteral(t)?t.getLiteralValue():""},Ra=e=>i.isArrowFunction(e)?e.getBody():e,Ma=(e,t)=>{const s=S(e.getExpression());if(s===void 0||!ka.has(s))return;const r=e.getArguments()[2];if(!r)return;const n=Ca(r);if(!n)return;const o=Ra(n);if(!(!w(o)||O(o)))return{callee:s,exportName:x(e),file:t,limitName:Ka(e),line:e.getStartLineNumber()}},ja=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=Ma(r,t);n&&s.push(n)}return s},za=(e,t)=>{const s=[];for(const r of g(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...ja(n,p(t,r)))}return s},qa=new Set(["findFirst","findFirstOrThrow","findMany","get"]),Ba=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!qa.has(t.getName()))return;const s=t.getExpression();if(C(s)){const r=e.getArguments()[0];return r&&i.isStringLiteral(r)?r.getLiteralText():""}if(i.isPropertyAccessExpression(s)&&C(s.getExpression()))return s.getName()},Ua=e=>{let t=e;for(;i.isCallExpression(t);){const s=t.getExpression();if(!i.isPropertyAccessExpression(s))return;if(s.getName()==="query"&&C(s.getExpression())){const r=t.getArguments()[0];return r&&i.isStringLiteral(r)?r.getLiteralText():""}t=s.getExpression()}},Va=e=>{let t=e;for(;i.isAwaitExpression(t)||i.isParenthesizedExpression(t)||i.isNonNullExpression(t)||i.isAsExpression(t);)t=t.getExpression();return t},Bt=(e,t=!1)=>{const s=Va(e);if(i.isIdentifier(s)){if(t)return;const r=Q(s);return r===void 0?void 0:Bt(r,!0)}if(i.isCallExpression(s))return Ba(s)??Ua(s)},Wa=e=>{const t=e.getBody();if(!i.isBlock(t))return[t];const s=[];for(const r of e.getDescendantsOfKind(u.ReturnStatement)){const n=r.getFirstAncestor(a=>i.isArrowFunction(a)||i.isFunctionExpression(a)||i.isFunctionDeclaration(a)),o=r.getExpression();n===e&&o!==void 0&&s.push(o)}return s},_a=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!i.isCallExpression(s))return[];const r=K(s);if(r?.kind!=="query")return[];const n=It(s);if(n===void 0)return[];const o=r.receiver!==void 0&&os(r.receiver,"output"),a=r.receiver!==void 0&&Tt(r.receiver,"use","mask"),c=new Set,l=[];for(const m of Wa(n)){const $=Bt(m);$===void 0||c.has($)||(c.add($),l.push({exportName:e.getName(),file:t,line:m.getStartLineNumber(),table:$,usesMask:a,usesOutput:o,visibility:r.visibility}))}return l},Ga=(e,t)=>{const s=[];for(const r of g(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r),o=p(t,r);for(const a of n.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(..._a(c,o))}return s},Ha=new Set(["findFirst","findFirstOrThrow","findMany"]),Qa=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!Ha.has(t.getName()))return;const s=t.getExpression();if(i.isPropertyAccessExpression(s)&&s.getName()==="db"||i.isIdentifier(s)&&s.getText()==="db"){const r=e.getArguments()[0];return{options:e.getArguments()[1],table:r&&i.isStringLiteral(r)?r.getLiteralText():""}}if(i.isPropertyAccessExpression(s)){const r=s.getExpression();if(i.isPropertyAccessExpression(r)&&r.getName()==="db"||i.isIdentifier(r)&&r.getText()==="db")return{options:e.getArguments()[0],table:s.getName()}}},Ja=e=>{if(!e||!i.isObjectLiteralExpression(e))return[];const t=[];for(const s of e.getProperties())(i.isPropertyAssignment(s)||i.isShorthandPropertyAssignment(s)||i.isMethodDeclaration(s)||i.isGetAccessorDeclaration(s))&&t.push(s.getName());return t},Xa=(e,t)=>{if(!e||!i.isObjectLiteralExpression(e))return;const s=e.getProperty(t);return s&&i.isPropertyAssignment(s)?s.getInitializer():void 0},Za=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer(),r=s&&i.isCallExpression(s)?K(s):void 0;if(!r)return[];const n=[];for(const o of e.getDescendantsOfKind(u.CallExpression)){const a=Qa(o);if(a===void 0)continue;const c=Ja(Xa(a.options,"with"));c.length!==0&&n.push({exportName:e.getName(),file:t,line:o.getStartLineNumber(),parentTable:a.table,relations:c,visibility:r.visibility})}return n},Ya=(e,t)=>{const s=[];for(const r of g(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r),o=p(t,r);for(const a of n.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...Za(c,o))}return s},H=e=>{if(i.isStringLiteral(e)||i.isNoSubstitutionTemplateLiteral(e))return e.getLiteralText();if(i.isBinaryExpression(e)&&e.getOperatorToken().getKind()===u.PlusToken){const t=H(e.getLeft()),s=H(e.getRight());return t!==void 0&&s!==void 0?t+s:void 0}},ec=e=>{let t=e,s=t.getParent();for(;s!==void 0&&i.isBinaryExpression(s)&&s.getOperatorToken().getKind()===u.PlusToken;)t=s,s=t.getParent();return t!==e&&H(t)!==void 0},tc=/(?:^|\/)__tests__\//u,sc=/\.(?:spec|test)$/u,rc=e=>tc.test(e)||sc.test(e),nc=e=>{const t=e.getParent();if(t!==void 0){if(i.isVariableDeclaration(t)||i.isPropertyAssignment(t)||i.isPropertySignature(t))return t.getName();if(i.isBinaryExpression(t)&&t.getOperatorToken().getKind()===u.EqualsToken)return t.getLeft().getText()}},ic=(e,t,s)=>er(e)?!rc(s)&&tr(nc(t)):!0,oc=(e,t)=>{const s=[],r=[...e.getDescendantsOfKind(u.BinaryExpression),...e.getDescendantsOfKind(u.StringLiteral),...e.getDescendantsOfKind(u.NoSubstitutionTemplateLiteral)],n=new Set;for(const o of r){if(ec(o))continue;const a=H(o);if(a===void 0)continue;const c=Zs(a);if(c===void 0||!ic(c,o,t))continue;const l=o.getStartLineNumber(),m=`${String(l)}:${c}`;n.has(m)||(n.add(m),s.push({file:t,kind:c,line:l,preview:Ys(a)}))}return s},ac=(e,t)=>{const s=[];for(const r of g(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...oc(n,p(t,r)))}return s},cc=new Set(["findFirst","findFirstOrThrow","findMany"]),uc=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!cc.has(t.getName()))return;const s=t.getExpression();if(i.isPropertyAccessExpression(s)&&s.getName()==="db"||i.isIdentifier(s)&&s.getText()==="db"){const r=e.getArguments()[0];return{options:e.getArguments()[1],table:r&&i.isStringLiteral(r)?r.getLiteralText():""}}if(i.isPropertyAccessExpression(s)){const r=s.getExpression();if(i.isPropertyAccessExpression(r)&&r.getName()==="db"||i.isIdentifier(r)&&r.getText()==="db")return{options:e.getArguments()[0],table:s.getName()}}},lc=(e,t)=>{if(!e||!i.isObjectLiteralExpression(e))return;const s=e.getProperty(t);return s&&i.isPropertyAssignment(s)?s.getInitializer():void 0},dc=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer(),r=s&&i.isCallExpression(s)?K(s):void 0;if(!r)return[];const n=[];for(const o of e.getDescendantsOfKind(u.CallExpression)){const a=uc(o);if(a===void 0)continue;const c=lc(a.options,"includeDeleted");if(c===void 0)continue;const l=i.isTrueLiteral(c),m=!l&&w(c);!l&&!m||n.push({exportName:e.getName(),file:t,fromArgs:m,hardcodedTrue:l,line:o.getStartLineNumber(),table:a.table,visibility:r.visibility})}return n},gc=(e,t)=>{const s=[];for(const r of g(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r),o=p(t,r);for(const a of n.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...dc(c,o))}return s},pc=new Set(["query","unsafe"]),fc=e=>{if(!i.isPropertyAccessExpression(e)||!pc.has(e.getName()))return!1;const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="sql")return!1;const s=t.getExpression();return i.isIdentifier(s)&&s.getText()==="ctx"},mc=e=>i.isBinaryExpression(e)||i.isTemplateExpression(e),hc=e=>e.getFirstAncestorByKind(u.VariableDeclaration)?.getName()??"<module>",xc=(e,t)=>{if(!fc(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!mc(s)))return{exportName:hc(e),file:t,line:s.getStartLineNumber()}},Ec=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=xc(r,t);n&&s.push(n)}return s},yc=(e,t)=>{const s=[];for(const r of g(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Ec(n,p(t,r)))}return s},$c=new Set(["createMultipartUpload","delete","download","generateUploadUrl","get","getMetadata","getPresignedUrl","getSignedUrl","getUrl","head","put","resumeMultipartUpload","store","upload"]),Ac=(e,t,s=[])=>{const r=new Map(s.map(n=>[`${n.filePath}:${n.exportName}`,n.visibility]));return Z(e,t,{argIndex:0,matchReceiver:n=>n==="ctx.storage"||n.startsWith("ctx.storage."),methods:$c,requireUnmodifiedReach:!0}).map(n=>{const o=r.get(`${n.file}:${n.exportName}`);return o===void 0?n:{...n,visibility:o}})},Sc=new Map([["generateUploadUrl",1],["getPresignedUrl",1],["getSignedUrl",1],["store",2],["upload",2]]),bc=e=>e&&i.isNumericLiteral(e)?Number(e.getText()):void 0,vc=e=>{if(e===void 0)return{analyzable:!0,presentKeys:[]};if(!i.isObjectLiteralExpression(e))return{analyzable:!1,presentKeys:[]};const t=[];let s,r=!1;for(const n of e.getProperties()){if(i.isSpreadAssignment(n)){r=!0;continue}if(i.isPropertyAssignment(n)){const o=n.getName();t.push(o),o==="expiresInSeconds"&&(s=bc(n.getInitializer()));continue}(i.isShorthandPropertyAssignment(n)||i.isMethodDeclaration(n))&&t.push(n.getName())}return{analyzable:!r,expiresInSeconds:s,presentKeys:t}},Nc=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName(),s=Sc.get(t);if(s===void 0)return;const r=e.getExpression().getText();return r==="ctx.storage"||r.startsWith("ctx.storage.")?{method:t,optionsIndex:s}:void 0},Pc=(e,t)=>{const s=Nc(e.getExpression());if(s!==void 0)return{exportName:x(e),file:t,line:e.getStartLineNumber(),method:s.method,...vc(e.getArguments()[s.optionsIndex])}},wc=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=Pc(r,t);n&&s.push(n)}return s},Ic=(e,t)=>{const s=[];for(const r of g(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...wc(n,p(t,r)))}return s},Tc=new Set(["RegisteredAction","RegisteredMutation","RegisteredQuery"]),Pe=e=>{const t=e.getType(),s=t.getAliasSymbol()?.getName()??t.getSymbol()?.getName();return s!==void 0&&Tc.has(s)?s:void 0},Ut=e=>{const t=e.getInitializer();return t===void 0?!1:i.isCallExpression(t)||i.isIdentifier(t)||i.isPropertyAccessExpression(t)},Vt={cause:"codegen recognises a procedure only when the initializer is a builder chain, and this one is produced by a call or an alias",remediation:"A factory that returns a procedure cannot be read statically — inline it, or export the chain the factory builds."},Lc={cause:"the binding is exported by a separate `export { … }` statement, and codegen reads the `export` keyword on the declaration itself",remediation:"Move the keyword onto the declaration and drop the separate export statement."},we=(e,t,s,r,n)=>({cacheKey:`procedure_not_registered:${e}:${t}`,categories:["SCHEMA"],description:"Codegen registers an export only when the declaration carries `export` and its initializer is literally a builder chain. A procedure written any other way exists at runtime but never reaches `_generated/api.ts`, so no caller can address it.",detail:`\`${t}\` in \`${e}\` (line ${r.toString()}) has type \`${s}\` but was not registered — ${n.cause}.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:t,filePath:e,line:r,typeName:s},name:"procedure_not_registered",remediation:`Assign the builder chain directly: \`export const ${t} = query.input({ … }).query(handler);\`. ${n.remediation}`,title:"Procedure exists at runtime but is missing from the generated API"}),Fc=(e,t,s)=>{const r=[];for(const n of e.getVariableStatements().filter(o=>o.isExported()))for(const o of n.getDeclarations()){const a=o.getName();if(s.has(`${t}:${a}`)||!Ut(o))continue;const c=Pe(o);c!==void 0&&r.push(we(t,a,c,o.getStartLineNumber(),Vt))}return r},Oc=(e,t,s)=>{if(s.has(`${t}:default`))return[];const r=[];for(const n of e.getExportAssignments().filter(o=>!o.isExportEquals())){const o=Pe(n.getExpression());o!==void 0&&r.push(we(t,"default",o,n.getStartLineNumber(),Vt))}return r},Dc=(e,t,s)=>{const r=[];for(const n of e.getExportDeclarations().filter(o=>o.getModuleSpecifier()===void 0))for(const o of n.getNamedExports()){const a=o.getAliasNode()?.getText()??o.getName();if(s.has(`${t}:${a}`))continue;const c=o.getLocalTargetDeclarations().find(m=>i.isVariableDeclaration(m));if(c===void 0||!Ut(c))continue;const l=Pe(c);l!==void 0&&r.push(we(t,a,l,o.getStartLineNumber(),Lc))}return r},kc=(e,t,s)=>[...Fc(e,t,s),...Oc(e,t,s),...Dc(e,t,s)],Cc=(e,t,s)=>{const r=new Set(s.map(o=>`${o.filePath}:${o.exportName}`)),n=[];for(const o of g(t)){const a=e.getSourceFile(o);a!==void 0&&n.push(...kc(a,p(t,o),r))}return n.toSorted((o,a)=>o.cacheKey.localeCompare(a.cacheKey))},Kc=new Set(["when","where"]),Ae=new Set(["definePolicy","defineShape"]),Rc=e=>{if(!i.isCallExpression(e))return;const t=e.getExpression();if(i.isPropertyAccessExpression(t)){const r=t.getName();return Ae.has(r)?r:void 0}if(!i.isIdentifier(t))return;for(const r of t.getSymbol()?.getDeclarations()??[])if(i.isImportSpecifier(r)){const n=r.getNameNode().getText();return Ae.has(n)?n:void 0}const s=t.getText();return Ae.has(s)?s:void 0},Mc=e=>i.isObjectLiteralExpression(e)&&e.getProperties().length===0,Wt=e=>{if(e!==void 0){if(i.isReturnStatement(e)&&e.getExpression()===void 0||e.getKind()===u.UndefinedKeyword||e.getText()==="undefined")return"undefined";if(Mc(e))return"empty-object";if(i.isParenthesizedExpression(e))return Wt(e.getExpression())}},_t=e=>e.getAncestors().find(t=>i.isArrowFunction(t)||i.isFunctionExpression(t)||i.isFunctionDeclaration(t)),Gt=e=>e.getDescendantsOfKind(u.ReturnStatement).filter(t=>_t(t)===e),Ht=e=>e.getDescendantsOfKind(u.ConditionalExpression).filter(t=>_t(t)===e),jc=e=>{const t=Gt(e);return t.length>1?!0:t.some(s=>s.getFirstAncestorByKind(u.IfStatement)!==void 0)||Ht(e).length>0},zc=e=>{const t=[],s=e.getBody();i.isBlock(s)||t.push(s);for(const r of Gt(e)){const n=i.isReturnStatement(r)?r.getExpression():void 0;t.push(n??r)}for(const r of Ht(e))t.push(r.getWhenTrue(),r.getWhenFalse());return t},qc=e=>{for(const t of e.getAncestors())if(i.isVariableDeclaration(t)){const s=t.getNameNode();if(i.isIdentifier(s))return s.getText()}return"<anonymous>"},Bc=(e,t,s)=>{if(!i.isCallExpression(e))return[];const[r]=e.getArguments();if(!r||!i.isObjectLiteralExpression(r))return[];const n=[];for(const o of r.getProperties()){if(!i.isPropertyAssignment(o)||!Kc.has(o.getName()))continue;const a=o.getInitializer();if(!(!a||!(i.isArrowFunction(a)||i.isFunctionExpression(a)))&&jc(a))for(const c of zc(a)){const l=Wt(c);l!==void 0&&n.push({exportName:qc(e),file:s,form:l,key:o.getName(),line:c.getStartLineNumber(),owner:t})}}return n},Uc=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=Rc(r);n!==void 0&&s.push(...Bc(r,n,t))}return s},Vc=(e,t)=>{const s=[];for(const r of g(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Uc(n,p(t,r)))}return s},Wc=new Set(["query","upsert","upsertMany"]),_c=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName();if(Wc.has(t))return e.getExpression().getText()==="ctx.vectors"?t:void 0},Gc=e=>{if(!i.isObjectLiteralExpression(e))return;const t=e.getProperty("namespace");return t&&i.isPropertyAssignment(t)?t.getInitializer():void 0},Hc=(e,t)=>{const s=_c(e.getExpression());if(s===void 0)return;const r=e.getArguments()[1];if(!r)return;const n=Gc(r);if(!(!n||!w(n)||O(n)))return{exportName:x(e),file:t,line:e.getStartLineNumber(),method:s}},Qc=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=Hc(r,t);n&&s.push(n)}return s},Jc=(e,t)=>{const s=[];for(const r of g(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Qc(n,p(t,r)))}return s},Xc=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="get")return!1;const s=t.getExpression();return i.isPropertyAccessExpression(s)?s.getName()==="workflows":i.isIdentifier(s)&&s.getText()==="workflows"},Zc=e=>{const t=e.getArguments()[0];return t&&i.isStringLiteral(t)?t.getLiteralText():""},Yc=(e,t)=>{const s=[];for(const r of g(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r),o=p(t,r);for(const a of n.getDescendantsOfKind(u.CallExpression)){if(!Xc(a))continue;const c=nr(a);c!==""&&s.push({exportName:c,file:o,line:a.getStartLineNumber(),workflow:Zc(a)})}}return s},eu=".lunora-schema.json",y=(e,t)=>{E(e)&&wt(e,"utf8")===t||es(e,t,"utf8")},P=(e,t)=>{if(t===""){ts(e,{force:!0});return}y(e,t)},tu=e=>{const t=d(e,"package.json");if(E(t))try{const s=JSON.parse(wt(t,"utf8"));return typeof s.version=="string"&&s.version!==""?s.version:void 0}catch{return}},su=()=>{const e=process.env.LUNORA_CODEGEN_TIMING;return e!==void 0&&e!==""},ru=e=>{let t=E(e)?e:he(e);for(;t&&t!==he(t);){const s=d(t,"tsconfig.json");if(E(s))return s;t=he(t)}},Pt=e=>e.replaceAll("\\","/"),nu=(e,t)=>{const s=new Map,r=new Map,n=new Map;for(const o of e)s.set(o.name,`workflow "${o.exportName}"`),r.set(o.bindingName,`workflow "${o.exportName}"`),n.set(o.className,`workflow "${o.exportName}"`);for(const o of t){const a=s.get(o.name);if(a!==void 0)throw new F("DUPLICATE_WORKFLOW_NAME",`Duplicate deployed name "${o.name}": produced by both ${a} and agent "${o.exportName}". Workflow and agent names share the same wrangler workflows[] array and must be unique together.`,{status:500});const c=r.get(o.bindingName);if(c!==void 0)throw new F("DUPLICATE_WORKFLOW_BINDING",`Duplicate binding "${o.bindingName}": produced by both ${c} and agent "${o.exportName}". Workflow and agent bindings share the same wrangler workflows[] array and must be unique together.`,{status:500});const l=n.get(o.className);if(l!==void 0)throw new F("DUPLICATE_WORKFLOW_CLASS",`Duplicate generated class "${o.className}": produced by both ${l} and agent "${o.exportName}". Workflow and agent export names must yield unique generated class names.`,{status:500})}},iu=(e,t,s)=>{if(s&&e.length>0){const o=e.map(a=>`"${a.exportName}"`).join(", ");throw new F("MASK_UNSUPPORTED",`This project declares a \`mask(...)\` policy whose argument isn't a plain object literal (e.g. \`mask(sharedPolicies)\` referencing a hoisted variable), or contains a spread (\`...shared\`) or computed key (\`[name]:\`) codegen can't enumerate, so codegen can't tell which columns it masks. Because the project also declares replication shape(s) (${o}), codegen can't verify none of them replicate a table that policy masks — inline every table and column as literal keys so codegen can verify it, or remove the affected shape(s).`,{status:422})}const r=new Map;for(const o of t.columns){const a=r.get(o.table)??[];a.push(o.column),r.set(o.table,a)}const n=t.columns.length>0;for(const o of e){if(o.table===void 0){if(n)throw new F("MASK_UNSUPPORTED",`defineShape "${o.exportName}" has a non-literal \`table\` (a variable or expression, not a string literal), so codegen can't statically verify it doesn't replicate a table that masks a column. This project masks at least one column elsewhere, so the combination can't be proven safe — change "${o.exportName}"'s \`table\` to a plain string literal so codegen can verify it, or remove the mask(s) on the table it targets.`,{status:422});continue}const a=r.get(o.table);if(a===void 0)continue;const c=a.map(l=>`"${l}"`).join(", ");throw new F("MASK_UNSUPPORTED",`defineShape "${o.exportName}" replicates table "${o.table}", which masks column(s) ${c} on at least one procedure. A shape runs no procedure, so \`.use(mask(...))\` never applies to its replicated rows — remove the shape, unmask the table, or wait for shape-masking support.`,{status:422})}},ou=e=>{const t=ru(e);return t?new at({skipAddingFilesFromTsConfig:!1,tsConfigFilePath:t,useInMemoryFileSystem:!1}):new at({skipAddingFilesFromTsConfig:!0,useInMemoryFileSystem:!1})},Qu=(e,t)=>{const s=g(t),r=d(t,"schema.ts");E(r)&&s.push(r);for(const c of s){const l=e.getSourceFile(c);l===void 0?e.addSourceFileAtPath(c):l.refreshFromFileSystemSync()}const n=new Set(s.map(c=>Pt(c))),o=Pt(t),a=`${o}/`;for(const c of e.getSourceFiles()){const l=c.getFilePath();(l===o||l.startsWith(a))&&!n.has(l)&&e.removeSourceFile(c)}},Ju=e=>{const t=su(),s=t?xe.now():0,r=d(e.projectRoot,e.lunoraDirectory??"lunora"),n=d(r,"schema.ts");if(!E(n))throw new F("INTERNAL",`schema.ts not found at ${n}`);const o=e.project??ou(r);dr(cs);const a=Xs(o,n,e.projectRoot);if(!e.dryRun){const f=d(r,"_generated"),M=d(f,"dataModel.ts"),j=d(f,"server.ts");if(!E(M)||!E(j)){const V=(lt(e.projectRoot)??new Set).has("lunorash"),nt=ct(a,V),it=ut({schema:a,useUmbrella:V});E(f)||ot(f,{recursive:!0}),y(M,nt),y(j,it),o.createSourceFile(M,nt,{overwrite:!0}),o.createSourceFile(j,it,{overwrite:!0})}}const c=as(o,r),l=Ds(o,r),m=js(o,r),$=sr(o,r),I=Bs(o,r),R=Ci(o,r),Ie=zn(o,r),v=ir(o,r),D=_s(o,r),N=us(o,r);nu(v,N);const Y=xs(o,r,v,N),k=hs(o,r),z=e.lint===!1?void 0:ns({adminRoutes:vr(o,r),aiRawRuns:Ir(o,r),aiToolSideEffects:Mr(o,r),argumentDerivedFetches:Br(o,r),argumentValidators:en(o,r),authApiCalls:ms(o,r),authConfigs:gn(o,r),browserUrlAccesses:xn(o,r),configCalls:Nn(o,r),containerKeyAccesses:wn(o,r),containerOverrides:kn(o,r),containers:k,exportSinks:Vn(o,r),failOpenGuards:Xn(o,r),flagSecurityDefaults:ui(o,r),geoIndexUsages:gi(o,r),httpActionGuards:$i(o,r),httpHeaderWrites:Li(o,r),identityClaimReads:Bi(o,r),imageDeliveryUrlAccesses:_i(o,r),inserts:ks(o,r),kvKeyAccesses:Hi(o,r),mailRecipientAccesses:eo(o,r),maskProcedures:Cs(o,r),maskStrategies:Ks(o,r),mutatorWrites:oo(o,r),nondeterministicCalls:Us(o,r),normalizeIdAuthorizations:bo(o,r),notifyCalls:Ws(o,r),notifyConfig:Vs(o,r),ownerFieldWrites:Fo(o,r,c),unrestrictedWhereBranches:Vc(o,r),paymentWebhooks:Ko(o,r),privilegedDispatches:Qo(o,r),procedureProtections:Da(o,r),queries:fs(o,r),queues:D,r2sqlCalls:Gs(o,r),ratelimitKeySelectors:za(o,r),rawRowReturns:Ga(o,r),relationLoads:Ya(o,r),rlsProcedures:Hs(o,r),schema:a,secretLiterals:ac(o,r),shapes:$,softDeleteReads:gc(o,r),sqlInterpolations:yc(o,r),storageKeyAccesses:Ac(o,r,c),storageUploads:Ic(o,r),vectorNamespaceAccesses:Jc(o,r),workflowCalls:Yc(o,r),workflows:v,wranglerVariables:e.wranglerVariables}),Te=z===void 0?[]:[...ss(z,{source:"static"}),...Cc(o,r,c)],Qt=Qs(o,r),Le=Rs(o,r);iu($,Le,Ms(o,r));const ee=rr(o,r),Jt=Yn(o,r),Fe=gr(Jt,pr(e.projectRoot,e.target)),A=Fe.usage,te=A.ai,se=A.payments,Oe=A.kv,De=A.access,re=E(d(r,"flags.ts")),Xt=re?Os(o,r):[],ne=E(d(r,"notify.ts")),ie=A.hyperdrive,oe=Js(o,r),Zt=oe.usesSandboxBrowser||oe.usesSandboxContainer,ae=A.browser||oe.usesSandboxBrowser,ce=A.images,ue=A.analytics,ke=A.pipelines,le=A.r2sql,de=A.x402,Ce=lt(e.projectRoot),T=Ce??new Set,q=ri(A,{containerCount:k.length,cronCount:Y.length,dependencies:T,hasPaymentTables:si(a.tables),queueCount:D.length,storageColumnCount:Object.keys(Es(a)).length,storageRuleCount:ee.rules.length,vectorIndexCount:a.vectorIndexes.length,workflowCount:v.length}),L=T.has("lunorash");hr(a,Ce);const Ke=t?xe.now():0,Re=ct(a,L),Me=ys({agents:N,functions:c,httpRoutes:l,mutators:I,useUmbrella:L,workflows:v}),je=ut({agents:N,containers:k,env:Ie,hasAccessFacade:De,hasAi:te,hasAnalytics:ue,hasBrowser:ae,hasFlags:re,hasHyperdrive:ie,hasImages:ce,hasKv:Oe,hasNotify:ne,hasPayments:se,hasPipelines:ke,hasR2sql:le,hasX402:de,identity:R,queues:D,schema:a,storageRuleBuckets:ee.rules.map(f=>f.bucket),useUmbrella:L,workflows:v}),ze=$s({agents:N,functions:c,migrations:m,mutators:I,shapes:$,useUmbrella:L,usesSandbox:Zt}),ge=fr(a,m.map(f=>f.id)),qe=As({advisories:Te,advisorProcedures:z?.procedureProtections??[],agents:N,containers:k,env:Ie,flagKeys:Xt,hasAccessFacade:De,hasAi:te,hasAnalytics:ue,hasBrowser:ae,hasFlags:re,hasHyperdrive:ie,hasImages:ce,hasKv:Oe,hasNotify:ne,hasPayments:se,hasPipelines:ke,hasR2sql:le,hasX402:de,maskMetadata:Le,mutators:I,queues:D,rlsMetadata:Qt,schema:a,schemaSnapshot:ge,shapes:$,storageRules:ee,studioFeatures:q,useUmbrella:L,workflows:v}),Be=Ss($,T.has("@lunora/db"),L),Ue=bs(k,a.jurisdiction),Ve=vs(v),We=Ns(N),_e=Ps(D),Ge=ws(Y),He=Is(a.vectorIndexes),B=Ts(a,L),Qe=Ls(T.has("@lunora/seed")),U=e.apiSpec??"openapi",pe=U==="openapi"||U==="both",fe=U==="openrpc"||U==="both",Je=or({emailAgents:N.filter(f=>f.onEmail===!0).map(f=>({bindingName:f.bindingName,exportName:f.exportName})),hasAccess:T.has("@lunora/cloudflare-access"),hasAi:te,hasAnalytics:ue,hasAuth:T.has("@lunora/auth"),hasBrowser:ae,hasFramework:T.has("@lunora/astro")||T.has("@lunora/svelte")||T.has("@lunora/vue"),hasGlobal:a.tables.some(f=>f.shardMode==="global"&&f.globalBackend!=="hyperdrive"),hasHyperdrive:ie,hasHyperdriveGlobal:a.tables.some(f=>f.shardMode==="global"&&f.globalBackend==="hyperdrive"),hasImages:ce,hasKv:q.kv,hasNotify:ne,hasPayments:se,hasR2sql:le,hasQueue:D.some(f=>f.mode==="push"),hasScheduler:q.scheduler,hasStorage:q.storage,hasVectors:a.vectorIndexes.length>0,hasWorkflow:v.length>0,hasX402:de,identity:R,jurisdiction:a.jurisdiction,useUmbrella:L,voiceAgents:N.filter(f=>f.voice===!0&&f.voiceBindingName!==void 0).map(f=>({bindingName:f.voiceBindingName,exportName:f.exportName})),wantsOpenApi:pe,wantsOpenRpc:fe}),Xe=tu(e.projectRoot),Ze=ar({functions:c,httpRoutes:l,version:Xe}),Ye=ur({functions:c,version:Xe}),et=`${JSON.stringify(Ze,void 0,2)}
|
|
8
|
+
`,tt=`${JSON.stringify(Ye,void 0,2)}
|
|
9
|
+
`,st=cr(Ze),rt=lr(Ye),me=d(r,eu),Yt=E(me),h=d(r,"_generated");if(e.dryRun||(E(h)||ot(h,{recursive:!0}),y(d(h,"app.ts"),Je),y(d(h,"dataModel.ts"),Re),y(d(h,"api.ts"),Me),y(d(h,"server.ts"),je),y(d(h,"functions.ts"),ze),y(d(h,"shard.ts"),qe),y(d(h,"crons.ts"),Ge),y(d(h,"vectors.ts"),He),y(d(h,"drizzle.global.ts"),B.global),y(d(h,"drizzle.shard.ts"),B.shard),P(d(h,"containers.ts"),Ue),P(d(h,"workflows.ts"),Ve),P(d(h,"agents.ts"),We),P(d(h,"queues.ts"),_e),P(d(h,"seed.ts"),Qe),P(d(h,"collections.ts"),Be),P(d(h,"openapi.json"),pe?et:""),P(d(h,"openapi.ts"),pe?st:""),P(d(h,"openrpc.json"),fe?tt:""),P(d(h,"openrpc.ts"),fe?rt:""),(!Yt||e.updateSchemaBaseline===!0)&&y(me,rs(ge))),t){const f=xe.now(),M=Math.round(f-s),j=Math.round(Ke-s),V=Math.round(f-Ke);console.error(`@lunora/codegen: codegen took ${M.toString()}ms (discovery ${j.toString()}ms, emit ${V.toString()}ms)`)}return{advisories:Te,advisorContext:z,agents:N,containers:k,cronTriggers:Fs(Y),generated:{agents:We,api:Me,app:Je,collections:Be,containers:Ue,crons:Ge,dataModel:Re,drizzleGlobal:B.global,drizzleShard:B.shard,functions:ze,openApi:et,openApiModule:st,openRpc:tt,openRpcModule:rt,queues:_e,seed:Qe,server:je,shard:qe,vectors:He,workflows:Ve},outputDirectory:h,platformDiagnostics:Fe.diagnostics,queues:D,schemaSnapshot:ge,schemaSnapshotPath:me,workflows:v}};export{eu as SCHEMA_SNAPSHOT_FILENAME,ou as createCodegenProject,Qu as refreshCodegenProject,Ju as runCodegen};
|
package/dist/packem_shared/{buildOpenApiDocument-XeZ1ycwi.mjs → buildOpenApiDocument-Blf3mpIz.mjs}
RENAMED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{R as v}from"./emit-B7IUlWwi.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]),N=e=>e.replaceAll(y,"{$1}"),w=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=w(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=N(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
|
+
const a=r=>[...new Set(r)].toSorted((e,o)=>e.localeCompare(o)),s=r=>a(r.filter(e=>e.level==="ERROR").map(e=>e.name)),i=r=>a(r.filter(e=>e.level==="error").map(e=>e.name)),t=r=>({advisoryNames:s(r.advisories),platformDiagnosticNames:i(r.platformDiagnostics)});export{t as describeErrorLevelFindings,s as errorAdvisoryNames,i as errorPlatformDiagnosticNames};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Node as r,SyntaxKind as c}from"ts-morph";import{listLunoraSourceFiles as E,lunoraRelativePath as P}from"./discoverFunctions-CVYkUBTm.mjs";const p=e=>{if(e.getText()!=="args")return!1;const t=e.getParent();return r.isPropertyAccessExpression(t)&&t.getNameNode()===e?!1:!(r.isPropertyAssignment(t)&&t.getNameNode()===e)},x=e=>{if(e.getText()!=="ctx")return!1;const t=e.getParent();return r.isPropertyAccessExpression(t)&&t.getNameNode()===e?!1:!(r.isPropertyAssignment(t)&&t.getNameNode()===e)},d=e=>r.isIdentifier(e)?x(e):e.getDescendantsOfKind(c.Identifier).some(t=>x(t)),m=(e,t)=>{if(e.getText()!==t)return!1;const s=e.getParent();return r.isPropertyAccessExpression(s)&&s.getNameNode()===e?!1:!(r.isPropertyAssignment(s)&&s.getNameNode()===e)},A=e=>{let t=e;for(;r.isPropertyAccessExpression(t)||r.isElementAccessExpression(t)||r.isNonNullExpression(t);)t=t.getExpression();return r.isIdentifier(t)?t:void 0},F=e=>{if(r.isIdentifier(e))return e.getText();if(r.isPropertyAccessExpression(e))return e.getName()},N=e=>r.isIdentifier(e)?p(e):e.getDescendantsOfKind(c.Identifier).some(t=>p(t)),a=e=>{if(!r.isIdentifier(e))return;const t=e.getText(),s=e.getFirstAncestor(o=>r.isArrowFunction(o)||r.isFunctionExpression(o)||r.isFunctionDeclaration(o));if(s===void 0)return;const n=e.getStart();let i,g=-1;for(const o of s.getDescendantsOfKind(c.VariableDeclaration)){if(o.getName()!==t)continue;const f=o.getInitializer(),u=o.getStart();f!==void 0&&u<n&&u>g&&(i=f,g=u)}return i},T=e=>{if(N(e))return!0;const t=a(e);return t!==void 0&&N(t)},C=e=>{if(r.isCallExpression(e)||r.isNewExpression(e))return!1;const t=a(e);return t===void 0||!(r.isCallExpression(t)||r.isNewExpression(t))},O=e=>{if(d(e))return!0;const t=a(e);if(t!==void 0&&d(t))return!0;const s=t??e;return(r.isIdentifier(s)?[s]:s.getDescendantsOfKind(c.Identifier)).some(n=>{const i=a(n);return i!==void 0&&d(i)})},l=(e,t)=>r.isIdentifier(e)?m(e,t):e.getDescendantsOfKind(c.Identifier).some(s=>m(s,t)),L=(e,t)=>{if(l(e,t))return!0;const s=a(e);if(s!==void 0&&l(s,t))return!0;const n=A(e);if(n!==void 0){const i=a(n);return i!==void 0&&l(i,t)}return!1},y=e=>{for(const t of e.getAncestors())if(r.isVariableDeclaration(t)&&t.getVariableStatement()?.hasExportKeyword()===!0)return t.getName();return"<module>"},I=new Set(["withIndex","withSearchIndex"]),h=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||t.getName()!=="query")return!1;const s=t.getExpression();return r.isPropertyAccessExpression(s)?s.getName()==="db":r.isIdentifier(s)&&s.getText()==="db"},v=e=>{const t=[];let s=e;for(;;){const n=s.getParent();if(!n||!r.isPropertyAccessExpression(n))break;const i=n.getParent();if(!i||!r.isCallExpression(i))break;t.push(n.getName()),s=i}return t},S=/\b[A-Za-z_$][\w$]*\._id\s*===?[^=]/u,b=e=>{let t=e;for(;;){const s=t.getParent();if(!s||!r.isPropertyAccessExpression(s))return!1;const n=s.getParent();if(!n||!r.isCallExpression(n))return!1;if(s.getName()==="filter"){const i=n.getArguments()[0];if(i&&S.test(i.getText()))return!0}t=n}},D=e=>{const t=e.getArguments()[0];return t&&r.isStringLiteral(t)?t.getLiteralText():""},$=(e,t)=>{const s=[];for(const n of E(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),g=P(t,n);for(const o of i.getDescendantsOfKind(c.CallExpression)){if(!h(o))continue;const f=v(o);f.includes("filter")&&s.push({exportName:y(o),file:g,filtersPrimaryKey:b(o),hasFilter:!0,hasIndex:f.some(u=>I.has(u)),line:o.getStartLineNumber(),table:D(o)})}}return s};export{O as a,C as b,F as c,L as d,y as e,l as f,T as i,N as r,a as s,$ as y};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as T}from"@lunora/errors";import{CRON_SCHEDULE_KINDS as b,isValidCronExpression as A,warnIfSecondsLeading as S,compileCronSchedule as O}from"@lunora/scheduler";import{SyntaxKind as m,Node as s}from"ts-morph";import{diagnosticAt as u,CodegenDiagnosticError as I}from"./CodegenDiagnosticError-DPezpZTz.mjs";import{listLunoraSourceFiles as $}from"./discoverFunctions-CVYkUBTm.mjs";import{E as j}from"./module-specifiers-8FEEiUcv.mjs";import{n as y}from"./paths-BmX5O1sG.mjs";const R=new Set([...b,"cron"]),D=e=>{const t=e.getSymbol();if(!t)return e.getText()==="cronJobs";for(const r of t.getDeclarations())if(s.isImportSpecifier(r))return j(r.getImportDeclaration().getModuleSpecifierValue())?r.getNameNode().getText()==="cronJobs":!1;return!1},P=e=>{const t=new Set;for(const r of e.getVariableDeclarations()){const n=r.getInitializer();if(n?.getKind()!==m.CallExpression)continue;const i=n.getExpression();s.isIdentifier(i)&&D(i)&&t.add(r.getName())}return t},V=e=>{let t=e;for(;s.isCallExpression(t)||s.isPropertyAccessExpression(t);)t=t.getExpression();return s.isIdentifier(t)?t.getText():void 0},L=(e,t)=>{const r=e.getArguments()[t];return r&&(s.isStringLiteral(r)||s.isNoSubstitutionTemplateLiteral(r))?r.getLiteralValue():void 0},_=(e,t)=>{if(s.isStringLiteral(e)||s.isNoSubstitutionTemplateLiteral(e)||s.isNumericLiteral(e))return e.getLiteralValue();if(s.isTrueLiteral(e))return!0;if(s.isFalseLiteral(e))return!1;if(s.isPrefixUnaryExpression(e)&&e.getOperatorToken()===m.MinusToken){const r=e.getOperand();if(s.isNumericLiteral(r))return-r.getLiteralValue()}if(s.isObjectLiteralExpression(e))return g(e,t);if(s.isArrayLiteralExpression(e))return e.getElements().map(r=>_(r,t));throw u(e,`Cron job "${t}" passes a non-static value where a literal is required; codegen can only read literals.`,{code:"CRON_NON_STATIC_VALUE",name:"LunoraError",status:500})},g=(e,t)=>{const r={};for(const n of e.getProperties()){if(!s.isPropertyAssignment(n))throw u(n,`Cron job "${t}" uses an unsupported object property (shorthand/spread/method) where a static literal is required.`,{code:"CRON_NON_STATIC_VALUE",name:"LunoraError",status:500});const i=n.getInitializer();i&&(r[n.getName()]=_(i,t))}return r},C=(e,t,r)=>{const n=e.getArguments()[t];if(!n||!s.isPropertyAccessExpression(n))throw u(e,`Cron job "${r}" must reference a function statically (e.g. internal.email.digest); codegen cannot resolve a dynamic reference.`,{code:"CRON_NON_STATIC_FN",name:"LunoraError",status:500});const i=n.getName(),o=n.getExpression();if(!s.isPropertyAccessExpression(o))throw u(n,`Cron job "${r}" function reference must be of the form internal.file.fn (two property accesses).`,{code:"CRON_NON_STATIC_FN",name:"LunoraError",status:500});const a=o.getName();return`${y(a)}:${i}`},h=e=>({workflow:{binding:e.bindingName,exportName:e.exportName}}),x=e=>({workflow:{binding:e.bindingName,exportName:e.exportName}}),w=(e,t,r,n,i,o)=>{const a=e.getExpression();if(!s.isIdentifier(a)||a.getText()!==t)return;const l=r.get(e.getName());if(l)return o(l);throw u(e,`Cron job "${n}" targets ${t}.${e.getName()}, but no such ${i} is declared in lunora/${i}s.ts.`,{code:"CRON_NON_STATIC_FN",name:"LunoraError",status:500})},k=(e,t,r,n,i)=>{const o=e.getArguments()[t];if(o&&s.isPropertyAccessExpression(o)){const a=w(o,"workflows",n,r,"workflow",h);return a||w(o,"agents",i,r,"agent",x)||{functionPath:C(e,t,r)}}if(o&&s.isIdentifier(o)){const a=n.get(o.getText()),l=i.get(o.getText());if(a&&l)throw u(o,`Cron job "${r}" references "${o.getText()}", which is ambiguous: a workflow and an agent are both declared under that name.`,{code:"CRON_NON_STATIC_FN",name:"LunoraError",status:500});if(a)return h(a);if(l)return x(l);throw u(o,`Cron job "${r}" references "${o.getText()}", which is neither a function (internal.file.fn / api.file.fn) nor a declared workflow in lunora/workflows.ts nor a declared agent in lunora/agents.ts.`,{code:"CRON_NON_STATIC_FN",name:"LunoraError",status:500})}return{functionPath:C(e,t,r)}},F=/^@lunora\/scheduler:\s*/u,v=(e,t)=>{const r=L(e,1);if(r===void 0)throw u(e,`Cron job "${t}" must pass a string-literal cron expression to ".cron(...)".`,{code:"CRON_EXPR_NOT_STATIC",name:"LunoraError",status:500});if(!A(r))throw u(e,`Cron job "${t}" has an invalid cron expression "${r}" — expected 5 or 6 space-separated fields.`,{code:"CRON_EXPR_INVALID",name:"LunoraError",status:500});return S(r,`cron expression for job "${t}"`),r},U=(e,t,r)=>{const n=e.getArguments()[1];if(!n||!s.isObjectLiteralExpression(n))throw u(e,`Cron job "${r}" must pass an object-literal schedule to ".${t}(...)".`,{code:"CRON_SCHEDULE_NOT_STATIC",name:"LunoraError",status:500});try{return O(t,g(n,r),r)}catch(i){if(i instanceof I)throw i;const o=i instanceof Error?i.message.replace(F,""):String(i);throw u(e,o,{code:"CRON_SCHEDULE_INVALID",name:"LunoraError",status:500})}},M=(e,t,r,n,i)=>{const o=t.getName();if(!R.has(o)||!r.has(V(t.getExpression())??""))return;const a=L(e,0);if(a===void 0||a.trim()==="")throw u(e,`A cron ".${o}(...)" registration must pass a non-empty string-literal name as its first argument.`,{code:"CRON_NAME_NOT_STATIC",name:"LunoraError",status:500});const l=o==="cron"?v(e,a):U(e,o,a),c=k(e,2,a,n,i),f=e.getArguments()[3];return{args:f&&s.isObjectLiteralExpression(f)?g(f,a):{},cron:l,name:a,...c}},z=e=>{const t=new Set;for(const r of e){if(t.has(r.name))throw new T("DUPLICATE_CRON_NAME",`Duplicate cron job name "${r.name}": cron names must be unique across the project.`,{status:500});t.add(r.name)}},Q=(e,t,r=[],n=[])=>{const i=$(t),o=[],a=new Map(r.map(c=>[c.exportName,c])),l=new Map(n.map(c=>[c.exportName,c]));for(const c of i){const f=e.getSourceFile(c)??e.addSourceFileAtPath(c),p=P(f);if(p.size!==0)for(const d of f.getDescendantsOfKind(m.CallExpression)){const N=d.getExpression();if(!s.isPropertyAccessExpression(N))continue;const E=M(d,N,p,a,l);E&&o.push(E)}}return o.sort((c,f)=>c.name.localeCompare(f.name)),z(o),o};export{Q as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Node as i,SyntaxKind as y}from"ts-morph";import{listLunoraSourceFiles as u,lunoraRelativePath as P,classifyProcedureCall as p}from"./discoverFunctions-CVYkUBTm.mjs";const S=t=>{if(!i.isCallExpression(t))return!1;const s=t.getExpression();return i.isIdentifier(s)?s.getText()==="mask":i.isPropertyAccessExpression(s)?s.getName()==="mask":!1},f=t=>{if(i.isPropertyAssignment(t)||i.isShorthandPropertyAssignment(t)||i.isMethodDeclaration(t)||i.isGetAccessorDeclaration(t))return t.getName()},v=t=>{const s=t.getArguments()[0];if(!s||!i.isObjectLiteralExpression(s))return[];const e=[];for(const r of s.getProperties()){const o=f(r);if(o===void 0||!i.isPropertyAssignment(r))continue;const n=r.getInitializer();if(!(!n||!i.isObjectLiteralExpression(n)))for(const a of n.getProperties()){const c=f(a);c!==void 0&&e.push({column:c,table:o})}}return e},g=t=>{const s=[];let e=t;for(;i.isCallExpression(e);){const r=e.getExpression();if(!i.isPropertyAccessExpression(r))break;if(r.getName()==="use"){const o=e.getArguments()[0];o&&S(o)&&s.push(o)}e=r.getExpression()}return s},L=t=>{const s=g(t);return{maskColumns:s.flatMap(e=>v(e)),usesMask:s.length>0}},M=new Set(["findFirst","findFirstOrThrow","findMany","get","query"]),N=new Set(["delete","insert","patch","replace"]),x=(t,s)=>{const e=t.getExpression();if(!i.isPropertyAccessExpression(e)||!s.has(e.getName()))return!1;const r=e.getExpression();return i.isPropertyAccessExpression(r)?r.getName()==="db":i.isIdentifier(r)&&r.getText()==="db"},b=t=>{const s=t.getArguments()[0];return s&&i.isStringLiteral(s)?s.getLiteralText():""},k=t=>{const s=new Set,e=new Set;for(const r of t.getDescendantsOfKind(y.CallExpression))if(x(r,M)){const o=b(r);o!==""&&s.add(o)}else if(x(r,N)){const o=b(r);o!==""&&e.add(o)}return{tablesRead:[...s],tablesWritten:[...e]}},C=(t,s)=>{if(!i.isVariableDeclaration(t))return;const e=t.getInitializer();if(!e||!i.isCallExpression(e))return;const r=p(e);if(!r)return;const o=r.receiver?L(r.receiver):{maskColumns:[],usesMask:!1},{tablesRead:n,tablesWritten:a}=k(t);return{exportName:t.getName(),file:s,maskColumns:o.maskColumns,tablesRead:n,tablesWritten:a,usesMask:o.usesMask,visibility:r.visibility}},T=(t,s)=>{const e=[];for(const r of u(s)){const o=t.getSourceFile(r)??t.addSourceFileAtPath(r),n=P(s,r);for(const a of o.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations()){const l=C(c,n);l&&e.push(l)}}return e},A=t=>{if(i.isPropertyAssignment(t)){const s=t.getInitializer();if(s&&i.isStringLiteral(s)){const e=s.getLiteralText();if(e==="redact"||e==="hash")return e}}return"custom"},D=t=>{const s=t.getArguments()[0];if(!s||!i.isObjectLiteralExpression(s))return[];const e=[];for(const r of s.getProperties()){const o=f(r);if(o===void 0||!i.isPropertyAssignment(r))continue;const n=r.getInitializer();if(!(!n||!i.isObjectLiteralExpression(n)))for(const a of n.getProperties()){const c=f(a);c!==void 0&&e.push({column:c,strategy:A(a),table:o})}}return e},h=t=>{const s=[];for(const e of t.getVariableStatements())if(e.isExported())for(const r of e.getDeclarations()){const o=r.getInitializer(),n=o&&i.isCallExpression(o)?p(o):void 0;n?.receiver&&s.push(n.receiver)}return s},R=(t,s)=>{const e=new Map;for(const r of u(s)){const o=t.getSourceFile(r)??t.addSourceFileAtPath(r);for(const n of h(o))for(const a of g(n))for(const c of D(a)){const l=`${c.table}\0${c.column}`;e.has(l)||e.set(l,c)}}return{columns:[...e.values()]}},F=(t,s,e)=>{const r=t.getArguments()[0];if(!r||!i.isObjectLiteralExpression(r))return[];const o=[];for(const n of r.getProperties()){const a=f(n);if(a===void 0||!i.isPropertyAssignment(n))continue;const c=n.getInitializer();if(!(!c||!i.isObjectLiteralExpression(c)))for(const l of c.getProperties()){const d=f(l);if(d===void 0)continue;const m=A(l);m!=="custom"&&o.push({column:d,exportName:s,file:e,line:l.getStartLineNumber(),strategy:m,table:a})}}return o},I=(t,s)=>{if(!i.isVariableDeclaration(t))return[];const e=t.getInitializer(),r=e&&i.isCallExpression(e)?p(e):void 0;return r?.receiver?g(r.receiver).flatMap(o=>F(o,t.getName(),s)):[]},V=(t,s)=>{const e=[];for(const r of u(s)){const o=t.getSourceFile(r)??t.addSourceFileAtPath(r),n=P(s,r);for(const a of o.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())e.push(...I(c,n))}return e},O=t=>i.isPropertyAssignment(t)||i.isMethodDeclaration(t)||i.isGetAccessorDeclaration(t)?i.isComputedPropertyName(t.getNameNode()):!1,j=t=>i.isPropertyAssignment(t)||i.isShorthandPropertyAssignment(t)||i.isMethodDeclaration(t)||i.isGetAccessorDeclaration(t)?O(t):!0,E=(t,s=!1)=>{for(const e of t.getProperties()){if(j(e))return!0;if(s)continue;if(!i.isPropertyAssignment(e))return!0;const r=e.getInitializer();if(!r||!i.isObjectLiteralExpression(r)||E(r,!0))return!0}return!1},$=(t,s)=>{for(const e of u(s)){const r=t.getSourceFile(e)??t.addSourceFileAtPath(e);for(const o of h(r))for(const n of g(o)){const a=n.getArguments()[0];if(a!==void 0&&(!i.isObjectLiteralExpression(a)||E(a)))return!0}}return!1};export{T as default,$ as discoverMaskHasNonLiteralPolicy,R as discoverMaskMetadata,V as discoverMaskStrategies};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import"ts-morph";import{y as p}from"./discover-queries-
|
|
1
|
+
import"ts-morph";import{y as p}from"./discover-queries-Bhu9SNsy.mjs";import"./discoverFunctions-CVYkUBTm.mjs";export{p as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as A}from"@lunora/errors";import{Node as s,SyntaxKind as T}from"ts-morph";import{diagnosticAt as u}from"./CodegenDiagnosticError-DPezpZTz.mjs";import{c as j}from"./parse-validator-_jDrFxwt.mjs";import{createRequire as _}from"node:module";import{join as N}from"node:path";const O=e=>{switch(typeof e){case"bigint":return e.toString();case"boolean":case"number":return String(e);case"string":return JSON.stringify(e);default:return e===null?"null":void 0}},z=e=>({...e?.defaultValue!==void 0||e?.defaultFn!==void 0||e?.serverDefault!==void 0?{hasDefault:!0}:{},...e?.onUpdateFn===void 0?{}:{hasOnUpdate:!0},notNull:e?.notNull??!0,...e?.unique===!0?{unique:!0}:{}}),f=e=>{const r=e?._meta??{},t=e?.kind??"unknown",n={column:z(r.column),kind:t};switch(t){case"array":case"optional":{n.inner=f(r.inner);break}case"id":{n.tableName=r.tableName;break}case"literal":{n.literalValue=O(r.value);break}case"object":{const i=r.shape??{};n.shape=Object.fromEntries(Object.entries(i).map(([o,a])=>[o,f(a)]));break}case"record":{n.valueType=f(r.valueValidator),r.keyValidator!==void 0&&(n.keyType=f(r.keyValidator));break}case"storage":{typeof r.bucket=="string"&&(n.bucket=r.bucket);break}case"union":{const i=r.members??[];n.members=i.map(o=>f(o));break}}return n},D=e=>e?.kind==="global"?"global":e?.kind==="shardBy"&&typeof e.field=="string"?{field:e.field,kind:"shardBy"}:"root",M=(e,r)=>{const t=[];e.relationMap&&Object.keys(e.relationMap).length>0&&t.push("relations"),e.rankIndexes&&e.rankIndexes.length>0&&t.push("rank indexes"),e.vectorIndexes&&e.vectorIndexes.length>0&&t.push("vector indexes"),t.length>0&&console.warn(`@lunora/codegen: package schema-extension table "${r}" declares ${t.join(" + ")}, which are not yet introspected from a node_modules extension — they will be absent from the generated types.`)},B=(e,r)=>{const t=e.shape??{},n=(e.indexes??[]).map(i=>({fields:i.fields,name:i.name,...i.unique?{unique:!0}:{}}));return M(e,r),{...e.isExternallyManaged?{externallyManaged:!0}:{},geoIndexes:[],indexes:n,name:r,rankIndexes:[],relations:[],searchIndexes:(e.searchIndexes??[]).map(i=>({field:i.field,...i.filterFields?{filterFields:i.filterFields}:{},...i.language===void 0?{}:{language:i.language},...i.staged===void 0?{}:{staged:i.staged},...i.strategy===void 0?{}:{strategy:i.strategy},name:i.name})),shape:Object.fromEntries(Object.entries(t).map(([i,o])=>[i,f(o)])),shardMode:D(e.shardMode),vectorIndexes:[]}},F=e=>{const{key:r,tables:t}=e;if(typeof r!="string"||typeof t!="object"||t===null)return;const n=Object.entries(t).map(([a,l])=>B(l,a)),i=e.vectorIndexes??{},o=Object.entries(i??{}).map(([a,l])=>({...l.dimensions===void 0?{}:{dimensions:l.dimensions},...l.field===void 0?{}:{field:l.field},...l.metadata===void 0?{}:{metadata:l.metadata},...l.metric===void 0?{}:{metric:l.metric},name:a,table:l.table??""}));return{bareTables:n,bareVectorIndexes:o,key:r}},q=e=>{if(s.isIdentifier(e))return e.getText();if(s.isPropertyAccessExpression(e)){const r=e.getExpression();return s.isIdentifier(r)?r.getText():void 0}},R=e=>{const r=q(e);if(r===void 0)return;const t=s.isPropertyAccessExpression(e)?e.getName():void 0,n=t===void 0?[]:[t];for(const i of e.getSourceFile().getImportDeclarations()){const o=i.getModuleSpecifierValue();for(const a of i.getNamedImports())if((a.getAliasNode()?.getText()??a.getName())===r)return{importedName:a.getName(),moduleSpecifier:o,propertyPath:n};if(i.getDefaultImport()?.getText()===r)return{importedName:"default",moduleSpecifier:o,propertyPath:n};if(i.getNamespaceImport()?.getText()===r&&t!==void 0)return{importedName:t,moduleSpecifier:o,propertyPath:[]}}},C=(e,r)=>{let t=e[r.importedName];for(const n of r.propertyPath){if(typeof t!="object"||t===null)return;t=t[n]}return t},V=(e,r)=>{const t=R(e);if(t)try{const n=_(N(r,"noop.cjs")),i=n.resolve(t.moduleSpecifier),o=n(i),a=C(o,t);return typeof a!="object"||a===null?void 0:F(a)}catch{return}},J=new Set(["cosine","dot-product","euclidean"]),U=new Set(["cascade","restrict","set null"]),k=new Set(["delete","get","insert","normalizeId","patch","query","replace","system"]),K=/^[A-Za-z_$][\w$]*$/u,Z=e=>e.replaceAll(/^["']|["']$/gu,""),Q=(e,r)=>{const t=Z(e);if(k.has(t))throw u(r,`table name "${t}" is reserved — it collides with a \`ctx.db\` member (one of ${[...k].map(n=>`"${n}"`).join(", ")}). Rename the table.`);if(!K.test(t))throw u(r,`table name ${JSON.stringify(t)} is not a valid JS identifier — table names are used in generated type names (Doc_<name>) and must match [A-Za-z_$][A-Za-z0-9_$]*. Rename the table.`)},d=(e,r)=>{const t=e.getProperty(r);if(t&&s.isPropertyAssignment(t)){const n=t.getInitializer();if(n&&s.isStringLiteral(n))return n.getLiteralText()}},m=(e,r)=>{const t=e.getProperty(r);if(t&&s.isPropertyAssignment(t)){const n=t.getInitializer();if(n&&s.isNumericLiteral(n))return Number(n.getLiteralText())}},X=(e,r)=>{const t=e.getProperty(r);if(t&&s.isPropertyAssignment(t)){const n=t.getInitializer();if(n&&(s.isTrueLiteral(n)||s.isFalseLiteral(n)))return n.getLiteralValue()}},h=(e,r)=>{const t=e.getProperty(r);if(t&&s.isPropertyAssignment(t)){const n=t.getInitializer();if(n&&s.isArrayLiteralExpression(n))return n.getElements().filter(i=>s.isStringLiteral(i)).map(i=>i.getLiteralText())}},L=e=>e&&J.has(e)?e:void 0,G=e=>e&&U.has(e)?e:void 0,H=e=>{if(!s.isArrowFunction(e))return;let r=e.getBody();if(s.isParenthesizedExpression(r))r=r.getExpression();else if(s.isBlock(r)){const t=r.getStatements().find(n=>s.isReturnStatement(n));r=t&&s.isReturnStatement(t)?t.getExpression()??r:r}return s.isObjectLiteralExpression(r)?r:void 0},W=e=>{if(!s.isPropertyAssignment(e))return;const r=e.getInitializer();if(!r||!s.isCallExpression(r))return;const t=r.getExpression();if(!s.isPropertyAccessExpression(t))return;const n=t.getName();if(n!=="one"&&n!=="many")return;const[i,o]=r.getArguments(),a=i&&s.isStringLiteral(i)?i.getLiteralText():"_unknown_";let l="_unknown_",c="_id",g;return o&&s.isObjectLiteralExpression(o)&&(l=d(o,"field")??l,c=d(o,"references")??c,g=n==="one"?G(d(o,"onDelete")):void 0),{field:l,kind:n,name:e.getName(),onDelete:g,references:c,table:a}},Y=e=>{const r=H(e);if(!r)return[];const t=[];for(const n of r.getProperties()){const i=W(n);i&&t.push(i)}return t},x=e=>e&&s.isStringLiteral(e)?e.getLiteralText():"_unnamed_",ee=(e,r,t)=>{if(!r.includes("."))return;const[n="",...i]=r.split("."),o=`${n}${i.map(a=>a.charAt(0).toUpperCase()+a.slice(1)).join("")}`;throw u(e,`index "${t}" indexes the nested path ${JSON.stringify(r)} — Lunora indexes only top-level columns. Denormalise the value into its own column (e.g. \`${o}\`), index that instead, and keep it in sync with a table \`.triggers()\` beforeInsert/beforeUpdate.`)},te=e=>{if(!e||!s.isObjectLiteralExpression(e))return!1;const r=e.getProperty("unique");if(!r||!s.isPropertyAssignment(r))return!1;const t=r.getInitializer();if(t===void 0)return!1;if(!s.isTrueLiteral(t)&&!s.isFalseLiteral(t))throw u(t,`\`unique\` must be a literal \`true\` or \`false\`, got ${JSON.stringify(t.getText())}`);return s.isTrueLiteral(t)},re=e=>{const[r,t,n]=e,i=te(n),o=x(r),a=t&&s.isArrayLiteralExpression(t)?t.getElements():[];for(const c of a)if(!s.isStringLiteral(c))throw u(c,`index "${o}" lists a non-literal field (${JSON.stringify(c.getText())}); codegen reads index fields statically, so every entry must be a string literal.`);const l=a.filter(c=>s.isStringLiteral(c));for(const c of l)ee(c,c.getLiteralText(),o);return{fields:l.map(c=>c.getLiteralText()),name:o,unique:i}},ne=e=>{const[r,t]=e;let n="_unknown_",i,o,a,l;return t&&s.isObjectLiteralExpression(t)&&(n=d(t,"field")??n,i=h(t,"filterFields"),o=d(t,"language"),a=X(t,"staged"),l=d(t,"strategy")),{field:n,filterFields:i,language:o,name:x(r),staged:a,strategy:l}},ie=e=>{const[r,t]=e;let n="_unknown_",i;return t&&s.isObjectLiteralExpression(t)&&(n=d(t,"field")??n,i=m(t,"precision")),{field:n,name:x(r),precision:i}},se=e=>{const[r,t]=e,n=r&&s.isStringLiteral(r)?r.getLiteralText():"_unknown_";let i;return t&&s.isObjectLiteralExpression(t)&&(i=m(t,"after")),{after:i,field:n}},oe=e=>{if(!s.isObjectLiteralExpression(e))return;const r=d(e,"field");return r===void 0?void 0:{direction:d(e,"direction")==="desc"?"desc":"asc",field:r}},ae=e=>{const[r,t]=e;let n=[],i;if(t&&s.isObjectLiteralExpression(t)){const o=t.getProperty("sortBy");if(o&&s.isPropertyAssignment(o)){const a=o.getInitializer();a&&s.isArrayLiteralExpression(a)&&(n=a.getElements().map(l=>oe(l)).filter(l=>l!==void 0))}i=h(t,"partitionBy")}return{name:x(r),partitionBy:i,sortBy:n}},le=(e,r)=>{const[t,n]=e,i=t&&s.isStringLiteral(t)?t.getLiteralText():"_unknown_";if(!(!n||!s.isObjectLiteralExpression(n)))return{dimensions:m(n,"dimensions"),field:i,metadata:h(n,"metadata"),metric:L(d(n,"metric")),name:d(n,"index")??"_unnamed_",table:r}},ce=e=>{const r=e[0];return r&&s.isObjectLiteralExpression(r)&&d(r,"backend")==="hyperdrive"?"hyperdrive":"d1"},de=e=>{if(e&&s.isObjectLiteralExpression(e)){const r=e.getProperty("field");if(r&&s.isPropertyAssignment(r)){const t=r.getInitializer();if(t&&s.isStringLiteral(t))return t.getLiteralText()}}return"deletedAt"},p=(e,r)=>{const t=e.getProperty(r);if(t&&s.isPropertyAssignment(t)){const n=t.getInitializer();if(n&&s.isStringLiteral(n))return n.getLiteralText()}},ue=(e,r)=>{const t=e.getProperty(r);if(t&&s.isPropertyAssignment(t)){const n=t.getInitializer();if(n&&s.isArrayLiteralExpression(n)){const i=n.getElements().filter(o=>s.isStringLiteral(o)).map(o=>o.getLiteralText());return i.length>0?i:void 0}}},ge=e=>{const r=e[0];return!r||!s.isObjectLiteralExpression(r)?{binding:"",hasTenantBy:!1,unanalyzable:!0}:{binding:p(r,"binding")??"",columns:ue(r,"columns"),hasReconcile:r.getProperty("reconcileEveryMs")!==void 0,hasSoftDelete:r.getProperty("softDeleteColumn")!==void 0,hasTenantBy:r.getProperty("tenantBy")!==void 0,idColumn:p(r,"idColumn"),mode:p(r,"mode"),query:p(r,"query")}},fe=(e,r,t,n)=>{switch(r){case"externallyManaged":{e.externallyManaged=!0;break}case"geoIndex":{e.geoIndexes.push(ie(t));break}case"global":{e.shardMode="global",e.globalBackend=ce(t);break}case"index":{e.indexes.push(re(t));break}case"public":{e.isPublic=!0;break}case"rankIndex":{e.rankIndexes.push(ae(t));break}case"relations":{const i=t[0];i&&e.relations.push(...Y(i));break}case"searchIndex":{e.searchIndexes.push(ne(t));break}case"shardBy":{const i=t[0];e.shardMode={field:i&&s.isStringLiteral(i)?i.getLiteralText():"_unknown_",kind:"shardBy"};break}case"softDelete":{e.softDelete={field:de(t[0])};break}case"source":{e.externalSource=ge(t),e.externallyManaged=!0;break}case"ttl":{e.ttl=se(t);break}case"vectorize":{const i=le(t,n);i&&e.vectorIndexes.push(i);break}}},E=["__vocab","_config","_content","_data","_docsize","_idx"],pe=(e,r,t)=>{const n=new Set(t.map(i=>i.name));for(const i of t)for(const o of E){const a=`${i.name}${o}`;if(!n.has(a))continue;const l=o==="__vocab"?`the \`fts5vocab\` companion for "${a}" is created \`IF NOT EXISTS\`, so it silently resolves to "${i.name}"'s — the second index then reads the wrong vocabulary and returns wrong results, with no error`:`creating "${a}" is rejected (\`object name reserved for internal use: SQLITE_ERROR\`), which aborts the shard migration and leaves every sharded table unreadable`;throw u(e,`table "${r}" declares search indexes "${i.name}" and "${a}", whose generated FTS5 tables collide: "${i.name}" already owns "${r}__fts_${a}" as its "${o}" companion, so ${l}. Rename one of them so neither ends with another's name plus ${E.join(", ")}.`)}},S=(e,r)=>{const t={externallyManaged:!1,geoIndexes:[],indexes:[],isPublic:!1,rankIndexes:[],relations:[],searchIndexes:[],shardMode:"root",vectorIndexes:[]};let n={},i=e;for(;s.isCallExpression(i);){const o=i.getExpression(),a=i.getArguments();if(s.isPropertyAccessExpression(o))fe(t,o.getName(),a,r),i=o.getExpression();else if(s.isIdentifier(o)&&o.getText()==="defineTable"){const l=a[0];if(l&&s.isObjectLiteralExpression(l))n=j(l);else if(l)throw u(l,`table "${r}" calls defineTable(${JSON.stringify(l.getText())}), but codegen reads the field map syntactically and can only read an object literal. Inline the fields into the defineTable(...) call. To reuse them in an \`.input()\`, derive from the generated \`Doc_${r}\` / \`Insert_${r}\` type instead of sharing the runtime value.`);break}else break}return t.softDelete&&!(t.softDelete.field in n)&&(n={...n,[t.softDelete.field]:{inner:{kind:"number"},kind:"optional"}}),pe(e,r,t.searchIndexes),{externallyManaged:t.externallyManaged,externalSource:t.externalSource,geoIndexes:t.geoIndexes,globalBackend:t.shardMode==="global"?t.globalBackend??"d1":void 0,indexes:t.indexes,isPublic:t.isPublic,name:r,rankIndexes:t.rankIndexes,relations:t.relations,searchIndexes:t.searchIndexes,shape:n,shardMode:t.shardMode,softDelete:t.softDelete,ttl:t.ttl,vectorIndexes:t.vectorIndexes}},me=e=>{const r=e.getProperty("source");if(r&&s.isPropertyAssignment(r)){const t=r.getInitializer();if(t&&s.isObjectLiteralExpression(t))return d(t,"table")??"_unknown_"}return"_unknown_"},xe=e=>{if(!s.isPropertyAssignment(e))return;const r=e.getInitializer();if(!r||!s.isCallExpression(r))return;const t=r.getExpression();if(!s.isIdentifier(t)||t.getText()!=="defineVectorIndex")return;const n=r.getArguments()[0];if(!n||!s.isObjectLiteralExpression(n))return;const i=e.getNameNode(),o=s.isStringLiteral(i)?i.getLiteralText():i.getText();return{dimensions:m(n,"dimensions"),metric:L(d(n,"metric")),name:o,table:me(n)}},P=e=>{const r=[];for(const t of e.getProperties()){const n=xe(t);n&&r.push(n)}return r},I=(e,r)=>`${e}_${r}`,y=(e,r,t)=>t.has(e)?I(r,e):e,be=(e,r,t)=>{const n=I(r,e.name);return{...e,extensionKey:r,name:n,relations:e.relations.map(i=>({...i,table:y(i.table,r,t)})),vectorIndexes:e.vectorIndexes.map(i=>({...i,table:y(i.table,r,t)}))}},ye=e=>{if(s.isVariableDeclaration(e)||s.isPropertyAssignment(e))return e.getInitializer();if(s.isShorthandPropertyAssignment(e))return e.getNameNode()},he=(e,r)=>{const t=e.getProperty(r);if(t&&s.isPropertyAssignment(t))return t.getInitializer()},Ie=e=>{if(!s.isCallExpression(e))return!1;const r=e.getExpression();return s.isIdentifier(r)&&r.getText()==="defineSchemaExtension"},ve=e=>{if(s.isIdentifier(e))return e;if(s.isPropertyAccessExpression(e)){const r=e.getExpression();return s.isIdentifier(r)?r:void 0}},ke=e=>{if(s.isObjectLiteralExpression(e))return e;if(s.isCallExpression(e)){const r=e.getExpression();let t;if(s.isIdentifier(r)?t=r.getText():s.isPropertyAccessExpression(r)&&(t=r.getName()),t==="definePlugin"){const n=e.getArguments()[1];return n&&s.isObjectLiteralExpression(n)?n:void 0}}},Ee=(e,r)=>{const t=ye(e);if(t){if(s.isPropertyAccessExpression(r)){const n=ke(t);return n?he(n,r.getName()):void 0}return t}},Le=e=>{let r=e,t=0;for(;r&&t<32;){if(t+=1,Ie(r))return r;const n=ve(r),i=n&&s.isIdentifier(n)?n.getSymbol():void 0,o=(i?.getAliasedSymbol()?.getDeclarations()??i?.getDeclarations()??[])[0];if(!o)return;const a=o.getSourceFile();if(a.isInNodeModules()||a.isDeclarationFile())return;r=Ee(o,r)}},Se=e=>{const[r,t]=e.getArguments();if(!(!r||!s.isStringLiteral(r))&&!(!t||!s.isObjectLiteralExpression(t)))return{key:r.getLiteralText(),options:t}},Pe=e=>{const r=e.getProperty("tables");if(!r||!s.isPropertyAssignment(r))return[];const t=r.getInitializer();if(!t||!s.isObjectLiteralExpression(t))return[];const n=[];for(const i of t.getProperties()){if(!s.isPropertyAssignment(i))continue;const o=i.getInitializer();o&&n.push(S(o,i.getName()))}return n},$e=e=>{const r=e.getProperty("vectorIndexes");if(!r||!s.isPropertyAssignment(r))return[];const t=r.getInitializer();return!t||!s.isObjectLiteralExpression(t)?[]:P(t)},$=(e,r,t)=>{const n=new Set(r.map(a=>a.name)),i=r.map(a=>be(a,e,n)),o=t.map(a=>({...a,name:I(e,a.name),table:y(a.table,e,n)}));return{tables:i,vectorIndexes:o}},we=(e,r)=>$(e,Pe(r),$e(r)),Ae=(e,r)=>{const t=e.getArguments()[0];if(!t)return;const n=Le(t);if(!n){if(r!==void 0){const o=V(t,r);if(o)return $(o.key,o.bareTables,o.bareVectorIndexes)}console.warn(`@lunora/codegen: skipping \`.extend(${t.getText()})\` — its \`defineSchemaExtension(...)\` could not be resolved from local sources, and ${r===void 0?"no project root was available to resolve the package":"the package could not be imported/introspected"}. Extension tables will be absent from the generated types.`);return}const i=Se(n);if(!i){console.warn("@lunora/codegen: skipping `.extend(...)` — `defineSchemaExtension` requires a string `key` and an options object literal.");return}return we(i.key,i.options)},Te=e=>{const r=[];let t=e;for(;;){const n=t.getParent();if(!n||!s.isPropertyAccessExpression(n))break;const i=n.getParent();if(!i||!s.isCallExpression(i))break;n.getName()==="extend"&&r.push(i),t=i}return r},w=(e,r,t,n,i)=>{let o=e;for(;;){const a=o.getParent();if(!a||!s.isPropertyAccessExpression(a))break;const l=a.getParent();if(!l||!s.isCallExpression(l))break;if(a.getName()===r){const c=l.getArguments()[0];if(!c||!s.isStringLiteral(c))throw u(l,`\`.${r}(...)\` expects a string literal (${i})`);const g=c.getLiteralText();if(!n.has(g))throw u(c,`unknown ${t} ${JSON.stringify(g)} — expected ${i}`);return g}o=l}},je=new Set(["eu","fedramp","us"]),_e=e=>w(e,"jurisdiction","jurisdiction",je,'"eu", "us", or "fedramp"'),Ne=new Set(["required"]),Oe=e=>w(e,"rls","rls mode",Ne,'"required"'),ze=e=>{const r=[];for(const t of e.getProperties()){if(!s.isPropertyAssignment(t))continue;const n=t.getInitializer();if(n){const i=t.getName();Q(i,t.getNameNode()),r.push(S(n,i))}}return r},De=(e,r,t)=>{const n=new Set(r.map(o=>o.name)),i=[];for(const o of Te(e)){const a=Ae(o,t);if(a){for(const l of a.tables){if(n.has(l.name))throw u(o,`defineSchema(...).extend(...): table "${l.name}" already exists — another extension with the same key already contributed it.`);n.add(l.name),r.push(l)}i.push(...a.vectorIndexes)}}return i},Ve=(e,r,t)=>{const n=e.addSourceFileAtPath(r).getDescendantsOfKind(T.CallExpression).find(b=>{const v=b.getExpression();return s.isIdentifier(v)&&v.getText()==="defineSchema"});if(!n)throw new A("INTERNAL",`defineSchema() not found in ${r}`);const i=n.getArguments()[0];if(!i||!s.isObjectLiteralExpression(i))throw u(n,"defineSchema() expects an object literal");const o=ze(i),a=n.getArguments()[1],l=a&&s.isObjectLiteralExpression(a)?P(a):[],c=De(n,o,t),g=[...o.flatMap(b=>b.vectorIndexes),...l,...c];return{jurisdiction:_e(n),rlsMode:Oe(n),tables:o,vectorIndexes:g}};export{Ve as default};
|