@lunora/codegen 1.0.0-alpha.243 → 1.0.0-alpha.245
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 +132 -4
- package/dist/index.d.ts +132 -4
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/{AGENTS_FILENAME-Bb2jxbOa.mjs → AGENTS_FILENAME-D8SgT3OR.mjs} +1 -1
- package/dist/packem_shared/{CONTAINERS_FILENAME-CGB4bqUr.mjs → CONTAINERS_FILENAME-CBCG6g9n.mjs} +1 -1
- package/dist/packem_shared/DEFAULT_TARGET-D-zkySYF.mjs +1 -0
- package/dist/packem_shared/{FLAGS_FILENAME-BedPDCsR.mjs → FLAGS_FILENAME-W5XQz_Po.mjs} +1 -1
- package/dist/packem_shared/{MUTATORS_FILENAME-B6cKrN_m.mjs → MUTATORS_FILENAME-DqWOgC5Z.mjs} +1 -1
- package/dist/packem_shared/{NOTIFY_FILENAME-Cri3NT5U.mjs → NOTIFY_FILENAME-C1J_47et.mjs} +1 -1
- package/dist/packem_shared/OPENRPC_VERSION-Cr7Zzp6s.mjs +3 -0
- package/dist/packem_shared/{QUEUES_FILENAME-BzOl92QK.mjs → QUEUES_FILENAME-RGwht3Xu.mjs} +1 -1
- package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-KDyLA-v5.mjs +11 -0
- package/dist/packem_shared/{SHAPES_FILENAME-zJgzynXR.mjs → SHAPES_FILENAME-DRUFomCj.mjs} +1 -1
- package/dist/packem_shared/{WORKFLOWS_FILENAME-DNaUHGS8.mjs → WORKFLOWS_FILENAME-4-ib4HH-.mjs} +1 -1
- package/dist/packem_shared/buildOpenApiDocument-SxfElVzK.mjs +3 -0
- package/dist/packem_shared/chain-mte5djRJ.mjs +1 -0
- package/dist/packem_shared/{classify-procedure-call-BztLe76A.mjs → classify-procedure-call-CmcShAze.mjs} +1 -1
- package/dist/packem_shared/{context-property-calls-CjDzLU8p.mjs → context-property-calls-CWf9-6G5.mjs} +1 -1
- package/dist/packem_shared/{discoverAuthApiCalls-FxrdBeVt.mjs → discoverAuthApiCalls-DoSN_yc3.mjs} +1 -1
- package/dist/packem_shared/{discoverCrons-0lNudk0S.mjs → discoverCrons-BEALHx1S.mjs} +1 -1
- package/dist/packem_shared/{discoverFunctions-BsmX-sEq.mjs → discoverFunctions-BcBzcG5x.mjs} +1 -1
- package/dist/packem_shared/{discoverHttpRoutes-BcXI9CNt.mjs → discoverHttpRoutes-CJHS4llq.mjs} +1 -1
- package/dist/packem_shared/discoverHyperdriveCalls-Bkbh4tG7.mjs +1 -0
- package/dist/packem_shared/{discoverInserts-CFJ3IVeI.mjs → discoverInserts-DpuLYPPd.mjs} +1 -1
- package/dist/packem_shared/discoverMaskProcedures-B0w8gM0S.mjs +1 -0
- package/dist/packem_shared/{discoverMigrations-DbrHwcGE.mjs → discoverMigrations-Dt7ywfZv.mjs} +1 -1
- package/dist/packem_shared/{discoverNondeterministicCalls-CSQ_GDcA.mjs → discoverNondeterministicCalls-CNJV2BiP.mjs} +1 -1
- package/dist/packem_shared/discoverQueries-BcdqjYky.mjs +1 -0
- package/dist/packem_shared/discoverR2sqlCalls-30Wtbc0P.mjs +1 -0
- package/dist/packem_shared/{discoverRlsMetadata-CPmAGL0W.mjs → discoverRlsMetadata-mXBmPOGj.mjs} +1 -1
- package/dist/packem_shared/{discoverRlsProcedures-BO4qC77y.mjs → discoverRlsProcedures-F4Cy-kSi.mjs} +1 -1
- package/dist/packem_shared/{discoverSandboxUsage-CrjZ6yNg.mjs → discoverSandboxUsage-DkbwwFvO.mjs} +1 -1
- package/dist/packem_shared/discoverSchema-D5R60b4F.mjs +1 -0
- package/dist/packem_shared/{discoverStorageRulesMetadata-D8VYflWt.mjs → discoverStorageRulesMetadata-D3Ot9g5f.mjs} +1 -1
- package/dist/packem_shared/emitAgents-CnQEPybh.mjs +1 -0
- package/dist/packem_shared/{emitApp-D_9NVcvv.mjs → emitApp-DsMk4tpo.mjs} +4 -2
- package/dist/packem_shared/{emitServer-pF_fhA82.mjs → emitServer-nvzMxk3d.mjs} +59 -50
- package/dist/packem_shared/{emitShard-DID_s1FK.mjs → emitShard-BiKPSgNP.mjs} +1 -1
- package/dist/packem_shared/{exported-procedure-chains-CmCDiPBV.mjs → exported-procedure-chains-D48EXUVQ.mjs} +1 -1
- package/dist/packem_shared/{fingerprintSchemaSources-L3nGKDQt.mjs → fingerprintSchemaSources-Cl1CJFeh.mjs} +1 -1
- package/dist/packem_shared/{index-BoaHhVtM.mjs → index-D7dKfGPh.mjs} +1 -1
- package/dist/packem_shared/listLunoraSourceFiles-CSlcBYlo.mjs +1 -0
- package/dist/packem_shared/loadProjectConfig-6Zk3abcc.mjs +1 -0
- package/dist/packem_shared/modules-DyCocr1e.mjs +1 -0
- package/dist/packem_shared/{parse-validator-C94Yiabo.mjs → parse-validator-C6fHL7OS.mjs} +1 -1
- package/dist/packem_shared/readServiceBindings-D9Wi_qGU.mjs +1 -0
- package/dist/packem_shared/{shard-BVzXMtWg.mjs → shard-D6EZdlSg.mjs} +61 -61
- package/dist/packem_shared/{shard-runtime-oIXHEMU7.mjs → shard-runtime-D9GRosnD.mjs} +14 -6
- package/dist/packem_shared/{unwrap-handler-return-CoV_GK33.mjs → unwrap-handler-return-DVY_kFF7.mjs} +1 -1
- package/package.json +6 -6
- package/dist/packem_shared/DEFAULT_TARGET-wK6-Tado.mjs +0 -1
- package/dist/packem_shared/OPENRPC_VERSION-Cl6P9WGv.mjs +0 -3
- package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-DX6sZtLG.mjs +0 -9
- package/dist/packem_shared/buildOpenApiDocument-nYvBhjxu.mjs +0 -3
- package/dist/packem_shared/chain-H2N_uKgj.mjs +0 -1
- package/dist/packem_shared/discoverHyperdriveCalls-D9qXqTq3.mjs +0 -1
- package/dist/packem_shared/discoverMaskProcedures-CV_Cc2_g.mjs +0 -1
- package/dist/packem_shared/discoverQueries-C7y8i_Ga.mjs +0 -1
- package/dist/packem_shared/discoverR2sqlCalls-fu7fC0i_.mjs +0 -1
- package/dist/packem_shared/discoverSchema-D8DBDHEg.mjs +0 -1
- package/dist/packem_shared/emitAgents-C3ygr0M8.mjs +0 -1
- package/dist/packem_shared/listLunoraSourceFiles-DP-5e-RE.mjs +0 -1
- package/dist/packem_shared/loadProjectConfig-CKsFNgn3.mjs +0 -1
- package/dist/packem_shared/queries-B-f4jO-x.mjs +0 -1
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
import{r as c}from"./json-data-Chfs2Cz5.mjs";import{s as u}from"./paths-C-9fwEgQ.mjs";import{validatorIrToJsonSchema as m,objectSchema as p,LUNORA_ERROR_CODES as i}from"./LUNORA_ERROR_CODES-C2s0xWQD.mjs";import{G as l}from"./shared-DjUziztz.mjs";const d="1.3.2",R={description:"Result is TS-inferred from the function's return type (no `.output()` declared); best-effort — any JSON."},h=e=>{const r=u(e.filePath),o=`${r}:${e.exportName}`;return{description:`Invoke the \`${e.kind}\` \`${o}\` over the Lunora RPC envelope (POST /_lunora/rpc, body \`{ "functionPath": "${o}", "args": { … } }\`).`,errors:i.map((n,s)=>({code:-32e3-s,data:{code:n},message:n})),name:o,params:[{description:"The function's argument object (the RPC envelope's `args`).",name:"args",required:Object.keys(e.args).length>0,schema:p(e.args)}],result:{name:"result",schema:e.output?m(e.output):R},summary:`${e.kind}: ${o}`,"x-lunora-function-kind":e.kind,"x-tags":[{name:r}]}},g=e=>{const r=e.version??"0.0.0",n=e.functions.filter(t=>t.visibility!=="internal"&&t.kind!=="stream").map(t=>h(t)).toSorted((t,a)=>t.name.localeCompare(a.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:r},methods:n,openrpc:d}},$=e=>`${JSON.stringify(g(e),void 0,2)}
|
|
2
|
-
`,y=e=>`${l}export const openRpcSpec = ${c(e,"Record<string, unknown>")};
|
|
3
|
-
`;export{d as OPENRPC_VERSION,g as buildOpenRpcDocument,$ as emitOpenRpc,y as emitOpenRpcModule};
|
|
@@ -1,9 +0,0 @@
|
|
|
1
|
-
import{existsSync as w,mkdirSync as ks,readFileSync as Ut,writeFileSync as Ms,rmSync as Ks}from"node:fs";import{join as S,dirname as ce}from"node:path";import{performance as Ie}from"node:perf_hooks";import{runAdvisor as _s}from"@lunora/advisor";import{LunoraError as $}from"@lunora/errors";import{SyntaxKind as l,Node as o,VariableDeclarationKind as zs,Project as ft}from"ts-morph";import{serializeSchemaSnapshot as $s}from"./SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs";import{toAdvisorContext as Us}from"./formatAdvisories-DwmUKYuc.mjs";import{readProjectConfigLiterals as Bs}from"./loadProjectConfig-CKsFNgn3.mjs";import{s as qs}from"./paths-C-9fwEgQ.mjs";import{C as le}from"./capabilities-DJJWVEtk.mjs";import{isD1GlobalTable as Bt,isHyperdriveGlobalTable as qt}from"./isD1GlobalTable-udvHAAzD.mjs";import{discoverAgents as js}from"./AGENTS_FILENAME-Bb2jxbOa.mjs";import{discoverContainers as Vs}from"./CONTAINERS_FILENAME-CGB4bqUr.mjs";import Ws from"./discoverCrons-0lNudk0S.mjs";import{diagnosticAt as ee}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{b as me}from"./module-specifiers-WF8iAydP.mjs";import{listLunoraSourceFiles as m,bindingKeyName as Q,propertyKeyName as y,unwrapExpression as X,listSecurityScanFiles as he,objectLiteralFromCallbackBody as jt,propertyInitializer as P,lunoraRelativePath as x,collectCallRows as F,findObjectProperty as C,collectSecurityCallRows as Hs,limitNameOf as Vt,optionsObjectLiteral as Wt,isContextIdentifier as Oe,handlerOf as Gs,isDatabaseAccessor as _,readTargetOf as Ht,enclosingExportName as Ys}from"./listLunoraSourceFiles-DP-5e-RE.mjs";import Qs from"./readPackageDependencies-C6h6FZuP.mjs";import{discoverQueueDeclarations as Xs}from"./QUEUES_FILENAME-BzOl92QK.mjs";import{discoverSandboxUsage as Zs}from"./discoverSandboxUsage-CrjZ6yNg.mjs";import Js from"./discoverStorageRulesMetadata-D8VYflWt.mjs";import{a as b,c as z,d as Gt,e as en}from"./classify-procedure-call-BztLe76A.mjs";import{discoverWorkflows as tn}from"./WORKFLOWS_FILENAME-DNaUHGS8.mjs";import{i as sn}from"./ir-DBSvhNa-.mjs";import{gatePlatformFeatures as nn,resolveCodegenTarget as Yt,readTargetDiagnostics as rn,studioPlatformFor as on}from"./DEFAULT_TARGET-wK6-Tado.mjs";import{b as Qt,e as an}from"./shard-BVzXMtWg.mjs";import cn from"./emitServer-pF_fhA82.mjs";import{emitDataModel as ln}from"./emitDataModel-D3WuEZ4b.mjs";import{i as M,a as U,e as A,r as un,b as dn,s as ve,c as fn,f as gn,d as pn}from"./queries-B-f4jO-x.mjs";import{r as xe,s as mn}from"./parse-validator-C94Yiabo.mjs";import hn from"./discoverAuthApiCalls-FxrdBeVt.mjs";import{i as vn,a as xn,e as En,b as Sn,d as yn,c as An}from"./unwrap-handler-return-CoV_GK33.mjs";import bn from"./discoverFunctions-BsmX-sEq.mjs";import Nn from"./discoverHttpRoutes-BcXI9CNt.mjs";import Pn from"./discoverHyperdriveCalls-D9qXqTq3.mjs";import wn from"./discoverInserts-CFJ3IVeI.mjs";import{m as Ke,a as de,s as Xt,d as In}from"./index-BoaHhVtM.mjs";import{e as Zt}from"./exported-procedure-chains-CmCDiPBV.mjs";import Tn from"./discoverMigrations-DbrHwcGE.mjs";import{MUTATORS_FILENAME as Cn,isDefineMutatorCallee as Fn,discoverMutators as On}from"./MUTATORS_FILENAME-B6cKrN_m.mjs";import Rn from"./discoverNondeterministicCalls-CSQ_GDcA.mjs";import{discoverNotifyConfig as Ln,discoverNotifyCalls as Dn}from"./NOTIFY_FILENAME-Cri3NT5U.mjs";import kn from"./discoverR2sqlCalls-fu7fC0i_.mjs";import Mn from"./discoverRlsProcedures-BO4qC77y.mjs";import Kn from"./discoverRlsMetadata-CPmAGL0W.mjs";import _n from"./discoverSchema-D8DBDHEg.mjs";import{secretKindOf as zn,redact as $n,isHeuristicSecretKind as Un,isSecretishName as Bn}from"./redact-Cy14LEnc.mjs";import{discoverShapes as qn}from"./SHAPES_FILENAME-zJgzynXR.mjs";import{emitApp as jn}from"./emitApp-D_9NVcvv.mjs";import{buildOpenApiDocument as Vn,emitOpenApiModule as Wn}from"./buildOpenApiDocument-nYvBhjxu.mjs";import{buildOpenRpcDocument as Hn,emitOpenRpcModule as Gn}from"./OPENRPC_VERSION-Cl6P9WGv.mjs";import{buildSchemaSnapshot as Yn}from"./SchemaSnapshotParseError-CPOXlFhI.mjs";import{emitCollections as Qn,emitSeed as Xn,emitApi as Zn}from"./emitApi-DdW9RyGG.mjs";import{B as Jn,C as er,A as tr,D as sr}from"./shard-runtime-oIXHEMU7.mjs";import{emitCrons as nr,emitScheduler as rr,emitShardRegistry as ir,emitVectors as or,emitWranglerCronTriggers as ar}from"./emitCrons-BRKXFGFu.mjs";import cr from"./emitDrizzleSchema-Cv0HtLR3.mjs";import lr from"./emitFunctions-BgNeOZt_.mjs";const gt={error:"ERROR",info:"INFO",warn:"WARN"},pt={ERROR:2,INFO:0,WARN:1},ur=e=>({cacheKey:"advisor_min_severity_invalid",categories:["SCHEMA"],description:"`advisor.minSeverity` in `lunora.config.*` sets the lowest advisory level codegen reports and writes into `_generated/shard.ts`. Codegen reads it by parsing the file, so it has to be a string literal.",detail:e,facing:"INTERNAL",level:"WARN",metadata:{},name:"advisor_min_severity_invalid",remediation:'Set `advisor: { minSeverity: "info" | "warn" | "error" }` as a literal on the config\'s default export.',title:"`advisor.minSeverity` is not a level codegen can read, so every advisory was reported"}),dr=(e,t)=>{const{advisor:s}=Bs(e);if(s===void 0||s.minSeverity===void 0&&s.unreadable!==!0)return[...t];const{minSeverity:n}=s,r=n!==void 0&&Object.hasOwn(gt,n)?gt[n]:void 0;return r===void 0?[...t,ur(n===void 0?"`advisor.minSeverity` is not a string literal codegen can read without evaluating the config: a computed value or key, or a spread that could set or override it.":`\`advisor.minSeverity\` is "${n}", which is not one of "info", "warn" or "error".`)]:t.filter(i=>pt[i.level]>=pt[r])},mt=(e,t="api")=>{const s=new Map;for(const n of e){const r=qs(n),i=s.get(r);if(i===void 0){s.set(r,n);continue}if(i!==n){const a=t==="api"?`the generated api.ts would declare "${r}" twice and the dispatch key "${r}:<fn>" would be ambiguous`:`the generated api.ts would declare "${r}" twice in HttpStreamsRef and again in the httpStreams object literal`;throw new $("INTERNAL",`@lunora/codegen: "${i}" and "${n}" both map to the ${t} namespace "${r}" — ${a}. Rename one file so the two differ by more than a non-identifier character (\`-\`, \`.\`, \`/\` and \`_\` all sanitize to \`_\`).`,{status:500})}}},fr=(e,t={})=>{const{hasVectors:s=!0,scheduler:n=!1,storage:r=!1,usage:i}=t,a=[];e.tables.some(c=>Bt(c))&&a.push({name:"@lunora/d1",reason:"`.global()` tables are D1-backed, so `_generated/app.ts` imports the D1 `ctx.db` adapter"}),e.tables.some(c=>qt(c))&&a.push({name:"@lunora/hyperdrive",reason:'`.global({ backend: "hyperdrive" })` tables route through `@lunora/hyperdrive/global`'},{name:"@lunora/sql-store",reason:'`.global({ backend: "hyperdrive" })` makes `_generated/app.ts` import the `SqlCtxDbOptions` / `SqlExec` types'}),n&&a.push({name:"@lunora/scheduler",reason:"a declared cron (or `ctx.scheduler` use) makes `_generated/app.ts` import `createScheduler`"}),r&&a.push({name:"@lunora/storage",reason:"a `v.storage()` column, a storage access rule (or `ctx.storage` use) makes `_generated/app.ts` import `createStorage`"}),e.vectorIndexes.length>0&&s&&a.push({name:"@lunora/bindings",reason:"`.vectorize()` indexes make `_generated/shard.ts` import `@lunora/bindings/vectors`"});for(const c of i===void 0?[]:le)c.requiredPackage!==void 0&&i?.[c.key]===!0&&a.push({name:c.requiredPackage,reason:`\`ctx.${c.contextProperty??c.key}\` usage makes \`_generated/\` import \`${c.moduleSpecifier}\``});return a.filter((c,u)=>a.findIndex(d=>d.name===c.name)===u)},gr=(e,t,s={})=>{if(t===void 0)return;const n=fr(e,s).filter(i=>!t.has(i.name));if(n.length===0)return;const r=n.map(i=>` - ${i.name} — ${i.reason}`).join(`
|
|
2
|
-
`);throw new $("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.`)},pr="env.ts",mr=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineEnv";for(const s of t.getDeclarations())if(o.isImportSpecifier(s))return me(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineEnv":!1;return!1},hr=e=>{const t=e.getSymbol();if(!t)return!1;for(const s of t.getDeclarations()){if(!o.isNamespaceImport(s))continue;const n=s.getFirstAncestorByKind(l.ImportDeclaration);return n!==void 0&&me(n.getModuleSpecifierValue())}return!1},vr=e=>{if(o.isIdentifier(e))return mr(e);if(o.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineEnv"&&o.isIdentifier(t)&&hr(t)}return!1},xr=e=>{const t=[];for(const s of e.getVariableDeclarations()){if(!s.isExported())continue;const n=s.getInitializer();if(n?.getKind()!==l.CallExpression||!vr(n.getExpression()))continue;const i=s.getNameNode();if(!o.isIdentifier(i))throw ee(i,"defineEnv exports must be plain named exports (no destructuring)");t.push({exportName:i.getText()})}return t},Er=(e,t)=>{const s=S(t,pr);if(!w(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s),r=xr(n);if(r.length!==0){if(r.length>1)throw ee(n,`lunora/env.ts declares ${r.length.toString()} defineEnv() contracts (${r.map(i=>i.exportName).join(", ")}); exactly one is allowed`);return r[0]}},ht="ctx",Jt=e=>{const t=new Set,s=new Set([ht]),n=i=>{if(o.isObjectBindingPattern(i))for(const a of i.getElements()){const c=Q(a);c&&t.add(c)}};for(const i of e.getDescendantsOfKind(l.BindingElement)){if(Q(i)!==ht)continue;const a=i.getNameNode();o.isIdentifier(a)?s.add(a.getText()):n(a)}const r=i=>o.isIdentifier(i)&&s.has(i.getText());for(const i of e.getDescendantsOfKind(l.PropertyAccessExpression))r(i.getExpression())&&t.add(i.getName());for(const i of e.getDescendantsOfKind(l.VariableDeclaration)){const a=i.getInitializer();a!==void 0&&r(a)&&n(i.getNameNode())}return t},Sr=(e,t)=>{const s=Object.fromEntries(le.map(n=>[n.key,!1]));for(const n of m(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n),i=new Set(r.getImportDeclarations().map(c=>c.getModuleSpecifierValue())),a=Jt(r);for(const c of le)if(!s[c.key]){if(i.has(c.moduleSpecifier)){s[c.key]=!0;continue}c.contextProperty!==void 0&&a.has(c.contextProperty)&&(s[c.key]=!0)}if(le.every(c=>s[c.key]))break}return s},es="identity.ts",yr=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineIdentity";for(const s of t.getDeclarations())if(o.isImportSpecifier(s))return me(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineIdentity":!1;return!1},Ar=e=>{const t=e.getSymbol();if(!t)return!1;for(const s of t.getDeclarations()){if(!o.isNamespaceImport(s))continue;const n=s.getFirstAncestorByKind(l.ImportDeclaration);return n!==void 0&&me(n.getModuleSpecifierValue())}return!1},br=e=>{if(o.isIdentifier(e))return yr(e);if(o.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineIdentity"&&o.isIdentifier(t)&&Ar(t)}return!1},Nr=e=>{const t=[];for(const s of e.getVariableDeclarations()){if(!s.isExported())continue;const n=s.getInitializer();if(n?.getKind()!==l.CallExpression||!br(n.getExpression()))continue;const i=s.getNameNode();if(!o.isIdentifier(i))throw ee(i,"defineIdentity exports must be plain named exports (no destructuring)");t.push({exportName:i.getText()})}return t},Pr=(e,t)=>{const s=S(t,es);if(!w(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s),r=Nr(n);if(r.length!==0){if(r.length>1)throw ee(n,`lunora/identity.ts declares ${r.length.toString()} defineIdentity() contracts (${r.map(i=>i.exportName).join(", ")}); exactly one is allowed`);return r[0]}},wr=new Set(["allowedHosts","deniedHosts","interceptHttps"]),Ir=(e,t)=>{const s=X(t);if(s===void 0||!o.isIdentifier(s))return s;const n=s.getText();return X(e.getDescendantsOfKind(l.VariableDeclaration).find(r=>r.getName()===n)?.getInitializer())},Tr=(e,t)=>e!==void 0&&o.isObjectLiteralExpression(e)&&e.getProperties().some(s=>{if(o.isShorthandPropertyAssignment(s))return t.has(y(s));if(!o.isPropertyAssignment(s)||!t.has(y(s)))return!1;const n=X(s.getInitializer())?.getText();return n!=="false"&&n!=="undefined"}),Cr=new Set(["durable"]),Fr=new Set(["rollback"]),Or=e=>{const t=e.getExpression();return o.isPropertyAccessExpression(t)?t.getName():t.getText()},Rr=new Map([["defineContainer",{keys:wr,signal:"containerEgressPolicy"}],["defineStep",{keys:Fr,signal:"workflowRollback"}],["stream",{keys:Cr,signal:"durableStreams"}]]),Lr=(e,t)=>{const s=Rr.get(Or(t));if(s!==void 0)return t.getArguments().some(n=>Tr(Ir(e,n),s.keys))?s.signal:void 0},Dr=(e,t)=>{const s={containerEgressPolicy:!1,durableStreams:!1,secrets:!1,workflowRollback:!1};for(const n of m(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.secrets||(s.secrets=Jt(r).has("secrets"));for(const i of r.getDescendantsOfKind(l.CallExpression)){const a=Lr(r,i);a!==void 0&&(s[a]=!0)}if(Object.values(s).every(Boolean))break}return s},kr="createWorker",Mr="extend",vt=e=>e!==void 0&&(o.isStringLiteral(e)||o.isNoSubstitutionTemplateLiteral(e))?e.getLiteralValue():void 0,xt=e=>{const t=[],s=vt(P(e,"backupCron"));s!==void 0&&t.push(s);const n=P(e,"crons");if(n===void 0||!o.isObjectLiteralExpression(n))return t;for(const r of n.getProperties()){if(!o.isPropertyAssignment(r)&&!o.isMethodDeclaration(r))continue;const i=vt(r.getNameNode());i!==void 0&&t.push(i)}return t},Kr=e=>{const t=b(e.getExpression()),[s]=e.getArguments();if(s===void 0)return[];if(t===kr)return o.isObjectLiteralExpression(s)?xt(s):[];if(t!==Mr||!(o.isArrowFunction(s)||o.isFunctionExpression(s)))return[];const n=jt(s.getBody());return n===void 0?[]:xt(n)},_r=(e,t)=>{const s=[];for(const{filePath:n}of he(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const i of r.getDescendantsOfKind(l.CallExpression))s.push(...Kr(i))}return[...new Set(s)]},ts=e=>{if(e.kind==="id")return e.tableName;if(!(e.kind!=="array"&&e.kind!=="optional"))return e.inner===void 0?void 0:ts(e.inner)},zr=e=>{const t=new Set(e.tables.map(s=>s.name));return e.tables.some(s=>Object.values(s.shape).some(n=>{const r=ts(n);return r!==void 0&&t.has(r)}))},$r=(e,t)=>{const s=new Map,n=new Map;for(const r of e)s.set(r.name,`workflow "${r.exportName}"`),n.set(r.className,`workflow "${r.exportName}"`);for(const r of t){const i=s.get(r.name);if(i!==void 0)throw new $("DUPLICATE_WORKFLOW_NAME",`Duplicate deployed name "${r.name}": produced by both ${i} and agent "${r.exportName}". Workflow and agent names share one account-wide namespace and must be unique together.`,{status:500});const a=n.get(r.className);if(a!==void 0)throw new $("DUPLICATE_WORKFLOW_CLASS",`Duplicate generated class "${r.className}": produced by both ${a} and agent "${r.exportName}". Workflow and agent export names must yield unique generated class names.`,{status:500})}},Ur=e=>{const{lunoraDirectory:t,project:s,projectRoot:n,schema:r}=e,i=Pr(s,t),a=Er(s,t),c=tn(s,t),{queues:u,topics:d}=Xs(s,t),g=js(s,t);$r(c,g);const h=Vs(s,t),O=Js(s,t),R=Ws(s,t,c,g),p=_r(s,t),T=Dr(s,t),N=Zs(s,t),L=Sr(s,t);L.browser=L.browser||N.usesSandboxBrowser;const D=nn(L,Yt(n,e.target),{agents:g.length>0,commitOrderedTables:r.tables.some(E=>E.commitOrdered===!0),cronTriggers:R.length>0,crossShardFanout:r.tables.some(E=>sn(E)),containerEgressPolicy:T.containerEgressPolicy,containerRuntimeScheduling:h.some(E=>E.schedulingPolicy==="durable_object"),durableStreams:T.durableStreams,globalTables:r.tables.some(E=>E.shardMode==="global"),queues:u.length>0,relationGraph:zr(r),secrets:T.secrets,topics:d.length>0,vectorStore:r.vectorIndexes.length>0,workerLoaders:N.usesSandboxLoader,workflowRollback:T.workflowRollback,workflowSchedules:c.some(E=>E.schedules!==void 0)}),v=D.usage,q=D.signals.vectorStore!==!1,j=Qs(n),te=j??new Set,se=te.has("lunorash");gr(r,j,{hasVectors:q,scheduler:v.scheduler||R.length>0,storage:v.storage||O.rules.length>0||Object.keys(Qt(r)).length>0,usage:v});const K=w(S(t,"flags.ts")),k=w(S(t,"notify.ts"));return{agents:g,containers:h,crons:R,dataModelContent:ln(r),declaredDependencies:j,dependencies:te,entryCronTriggers:p,env:a,featureUsage:v,hasFlags:K,hasNotify:k,identity:i,platformGate:{...D,diagnostics:[...rn(n,e.target),...D.diagnostics]},queues:u,serverContent:cn({agents:g,containers:h,env:a,hasAccessFacade:v.access,hasAi:v.ai,hasAnalytics:v.analytics,hasBrowser:v.browser,hasVectors:q,hasFlags:K,hasHyperdrive:v.hyperdrive,hasImages:v.images,hasKv:v.kv,hasNotify:k,hasPayments:v.payments,hasPipelines:v.pipelines,hasR2sql:v.r2sql,hasX402:v.x402,identity:i,queues:u,schema:r,storageRuleBuckets:O.rules.map(E=>E.bucket),topics:d,useUmbrella:se,workflows:c}),storageRulesMetadata:O,topics:d,usesSandbox:N.usesSandboxBrowser||N.usesSandboxContainer||N.usesSandboxFs,useUmbrella:se,workflows:c}},ss=new Set(["delete","get","head","options","patch","post","put"]),Br=new Set(["handler","stream"]),qr=/\/(?:_|admin|internal|superuser|sudo|root|debug)/iu,Et=new Set(["ADMIN_TOKEN","adminToken","assertAdmin","assertAuth","auth","Authorization","getSession","identity","isAdmin","requireAdmin","requireAuth","requireRole","verifyAdmin"]),jr=e=>{if(!o.isCallExpression(e))return;const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||!ss.has(t.getName()))return;const s=t.getExpression();if(!o.isIdentifier(s)||s.getText()!=="httpRoute")return;const n=e.getArguments()[0];if(!(!n||!o.isStringLiteral(n)))return{method:t.getName().toUpperCase(),path:n.getLiteralValue()}},Vr=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t))return;let s=t.getExpression();for(;o.isCallExpression(s);){const n=s.getExpression();if(!o.isPropertyAccessExpression(n)||ss.has(n.getName()))break;s=n.getExpression()}return jr(s)},Wr=e=>{for(const t of e.getDescendantsOfKind(l.PropertyAccessExpression))if(Et.has(t.getName()))return!0;for(const t of e.getDescendantsOfKind(l.CallExpression)){const s=t.getExpression();if(o.isIdentifier(s)&&Et.has(s.getText()))return!0}return!1},Hr=(e,t)=>{const s=e.getInitializer();if(!s||!o.isCallExpression(s))return;const n=s.getExpression();if(!o.isPropertyAccessExpression(n)||!Br.has(n.getName()))return;const r=Vr(s);if(!r||!qr.test(r.path))return;const i=s.getArguments()[0],a=i!==void 0&&(o.isArrowFunction(i)||o.isFunctionExpression(i))&&Wr(i);return{exportName:e.getName(),file:t,method:r.method,path:r.path,usesGuard:a}},Gr=(e,t)=>{const s=[];for(const n of e.getVariableStatements())if(n.isExported())for(const r of n.getDeclarations()){const i=Hr(r,t);i&&s.push(i)}return s},Yr=(e,t)=>{const s=[];for(const n of m(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Gr(r,x(t,n)))}return s},Qr=e=>!o.isPropertyAccessExpression(e)||e.getName()!=="run"?!1:e.getExpression().getText()==="ctx.ai",Xr=(e,t)=>{if(!Qr(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!M(s)||U(s)))return{exportName:A(e),file:t,line:e.getStartLineNumber()}},Zr=(e,t)=>F(e,t,Xr),Jr=new Set(["generateText","streamText"]),ei=new Set(["messages","prompt","system"]),ti=[{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"]}],si=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t))return;const s=t.getName(),n=t.getExpression().getText();for(const r of ti)if(r.methods.has(s)&&r.prefixes.some(i=>n===i||n.startsWith(`${i}.`)))return`${n}.${s}`},ni=e=>{for(const t of e.getDescendantsOfKind(l.CallExpression)){const s=si(t);if(s!==void 0)return s}},ri=e=>{const t=new Set,s=e.getFirstAncestor(i=>o.isArrowFunction(i)||o.isFunctionExpression(i)||o.isFunctionDeclaration(i)),[n]=s?.getParameters()??[],r=n?.getNameNode();if(r===void 0||!o.isObjectBindingPattern(r))return t;for(const i of r.getElements()){const a=Q(i),c=i.getNameNode();if(a==="args"&&o.isObjectBindingPattern(c))for(const u of c.getElements())t.add(u.getName())}return t},ii=e=>{if(un(e))return!0;const t=ri(e);return t.size===0?!1:e.getDescendantsOfKind(l.Identifier).some(s=>t.has(s.getText()))},oi=e=>{for(const t of e.getProperties()){if(!o.isPropertyAssignment(t)||!ei.has(y(t)))continue;const s=t.getInitializer();if(s!==void 0&&ii(s))return!0}return!1},ai=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression)){const r=b(n.getExpression());if(r===void 0||!Jr.has(r))continue;const[i]=n.getArguments();if(i===void 0||!o.isObjectLiteralExpression(i))continue;let a;for(const c of i.getDescendantsOfKind(l.CallExpression))if(b(c.getExpression())==="tool"&&(a=ni(c),a!==void 0))break;a!==void 0&&s.push({exportName:A(n),file:t,line:n.getStartLineNumber(),method:r,sideEffect:a,userInputDerived:oi(i)})}return s},ci=(e,t)=>{const s=[];for(const n of m(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...ai(r,x(t,n)))}return s},li=e=>{if(!o.isPropertyAccessExpression(e)||e.getName()!=="fetch")return!1;const t=e.getExpression();return o.isIdentifier(t)&&t.getText()==="ctx"},ui=(e,t)=>{if(!li(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!M(s)))return{exportName:A(e),file:t,line:e.getStartLineNumber()}},di=(e,t)=>F(e,t,ui),_e=(e,t=new Set)=>{if(t.has(e))return!0;t.add(e);try{return e.getProperties().some(s=>{if(!o.isSpreadAssignment(s))return!1;const n=xe(s.getExpression());return n===void 0||_e(n,t)})}finally{t.delete(e)}},fi=e=>{const t=e.getArguments()[0];if(!t||!o.isObjectLiteralExpression(t))return{objects:[],opaque:!0};const s=C(t,"args");if(!s)return{objects:[],opaque:!1};if(!o.isPropertyAssignment(s))return{objects:[],opaque:!0};const n=s.getInitializer(),r=n===void 0?void 0:xe(n);return r===void 0?{objects:[],opaque:!0}:{objects:[r],opaque:_e(r)}},gi=e=>{const t=[];let s=!1,n=e;for(;o.isCallExpression(n);){const r=n.getExpression();if(!o.isPropertyAccessExpression(r))break;if(r.getName()==="input"){const i=n.getArguments()[0],a=i!==void 0&&o.isExpression(i)?xe(i):void 0;a===void 0?s=!0:(t.push(a),s||=_e(a))}n=r.getExpression()}return{objects:t,opaque:s}},ze=(e,t)=>t?gi(t):fi(e),ns=(e,t)=>{if(t.has(e))return[];t.add(e);try{return e.getProperties().flatMap(s=>{if(o.isSpreadAssignment(s)){const n=xe(s.getExpression());return n===void 0?[]:ns(n,t)}return o.isPropertyAssignment(s)||o.isShorthandPropertyAssignment(s)?[y(s)]:[]})}finally{t.delete(e)}},pi=e=>e.flatMap(t=>ns(t,new Set)),mi=new Set(["check","length","max"]),Re=e=>{if(!o.isCallExpression(e))return;const t=e.getExpression();if(!(!o.isPropertyAccessExpression(t)||t.getExpression().getText()!=="v"))return t.getName()},hi=e=>[e,...e.getDescendants()].filter(t=>Re(t)!==void 0),vi=e=>{let t=e;for(;;){const s=t.getParent();if(!s||!o.isPropertyAccessExpression(s)||s.getExpression()!==t)return!1;const n=s.getParent();if(!n||!o.isCallExpression(n)||n.getExpression()!==s)return!1;if(mi.has(s.getName()))return!0;t=n}},xi=e=>{const t=[],s=[];for(const n of e)for(const r of n.getProperties()){if(!o.isPropertyAssignment(r))continue;const i=r.getInitializer();if(!i)continue;const a=hi(i),c=y(r);a.some(u=>Re(u)==="any")?t.push(c):a.some(u=>Re(u)==="string"&&!vi(u))&&s.push(c)}return{anyArgs:t,unboundedStringArgs:s}},Ei=(e,t)=>{const s=e.getInitializer();if(!s||!o.isCallExpression(s))return;const n=z(s);if(n?.visibility!=="public")return;const{objects:r}=ze(s,n.receiver),{anyArgs:i,unboundedStringArgs:a}=xi(r);if(!(i.length===0&&a.length===0))return{anyArgs:i,exportName:e.getName(),file:t,line:s.getStartLineNumber(),unboundedStringArgs:a}},Si=(e,t)=>{const s=[];for(const n of e.getVariableStatements())if(n.isExported())for(const r of n.getDeclarations()){const i=Ei(r,t);i&&s.push(i)}return s},yi=(e,t)=>{const s=[];for(const n of m(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Si(r,x(t,n)))}return s},Te=e=>e?.getKind()===l.TrueKeyword,Ai=e=>e?.getKind()===l.FalseKeyword,bi=e=>e!==void 0&&o.isNumericLiteral(e)&&e.getLiteralValue()===0,Ni=new Set(["lunoraAuthAdapter","lunoraD1Adapter"]),Pi=e=>!e||!o.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>o.isCallExpression(t)&&b(t.getExpression())==="scim"),wi=e=>e!==void 0&&o.isCallExpression(e)&&Ni.has(b(e.getExpression())??""),Ii=e=>!e||!o.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>o.isStringLiteral(t)&&t.getLiteralText()==="*"),Ti=e=>{const t=P(e,"advanced"),s=P(e,"emailAndPassword"),n=P(e,"session");return{analyzable:!0,disableCsrfCheck:Te(P(t,"disableCSRFCheck")),emailPasswordEnabled:Te(P(s,"enabled")),requireEmailVerification:Te(P(s,"requireEmailVerification")),scimOnNonTransactionalAdapter:Pi(P(e,"plugins"))&&wi(P(e,"database")),secureCookiesDisabled:Ai(P(t,"useSecureCookies")),sessionFreshAgeZero:bi(P(n,"freshAge")),trustedOriginsWildcard:Ii(P(e,"trustedOrigins"))}},Ci=()=>({analyzable:!1,disableCsrfCheck:!1,emailPasswordEnabled:!1,requireEmailVerification:!1,scimOnNonTransactionalAdapter:!1,secureCookiesDisabled:!1,sessionFreshAgeZero:!1,trustedOriginsWildcard:!1}),Fi=(e,t)=>{if(b(e.getExpression())!=="createAuth")return;const s=e.getArguments()[0],n=s!==void 0&&o.isObjectLiteralExpression(s)&&s.getProperties().some(i=>o.isSpreadAssignment(i)),r=s!==void 0&&o.isObjectLiteralExpression(s)&&!n?Ti(s):Ci();return{exportName:A(e),file:t,line:e.getStartLineNumber(),...r}},Oi=(e,t)=>Hs(e,t,Fi),Ri=(e,t)=>{if(!o.isPropertyAccessExpression(e))return;const s=e.getName();if(t.methods.has(s))return t.matchReceiver(e.getExpression().getText())?s:void 0},Li=(e,t,s)=>{const n=Ri(e.getExpression(),s);if(n===void 0)return;const r=e.getArguments()[s.argIndex];if(!(!r||!M(r)||U(r))&&!(s.requireUnmodifiedReach===!0&&!dn(r)))return{exportName:A(e),file:t,line:e.getStartLineNumber(),method:n}},Di=(e,t,s)=>{const n=[];for(const r of e.getDescendantsOfKind(l.CallExpression)){const i=Li(r,t,s);i&&n.push(i)}return n},Ee=(e,t,s)=>{const n=[];for(const r of m(t)){const i=e.getSourceFile(r)??e.addSourceFileAtPath(r);n.push(...Di(i,x(t,r),s))}return n},ki=new Set(["content","pdf","scrape","screenshot"]),Mi=(e,t)=>Ee(e,t,{argIndex:0,matchReceiver:s=>s==="ctx.browser",methods:ki}),Ki=new Set(["createBrowser","createInboundEmailHandler","createPayment"]),_i=new Set(["RateLimiter"]),zi=new Set(["extend"]),St="lunora",$i=["vite.config.ts","vite.config.mts","vite.config.js","vite.config.mjs"],rs=e=>{const t=[],s=[];let n=!1;for(const r of e.getProperties()){if(o.isSpreadAssignment(r)){n=!0;continue}if(o.isPropertyAssignment(r)){const i=y(r);t.push(i),r.getInitializer()?.getKind()===l.TrueKeyword&&s.push(i);continue}(o.isShorthandPropertyAssignment(r)||o.isMethodDeclaration(r))&&t.push(y(r))}return{analyzable:!n,presentKeys:t,trueKeys:s}},Le=e=>e&&o.isObjectLiteralExpression(e)?rs(e):{analyzable:!1,presentKeys:[],trueKeys:[]},Ui=e=>{const t=e&&(o.isArrowFunction(e)||o.isFunctionExpression(e))?e:void 0,s=t&&jt(t.getBody());return s?rs(s):{analyzable:!1,presentKeys:[],trueKeys:[]}},Bi=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression)){const r=b(n.getExpression());r!==void 0&&(Ki.has(r)?s.push({callee:r,file:t,line:n.getStartLineNumber(),...Le(n.getArguments()[0])}):zi.has(r)&&s.push({callee:r,file:t,line:n.getStartLineNumber(),...Ui(n.getArguments()[0])}))}for(const n of e.getDescendantsOfKind(l.NewExpression)){const r=b(n.getExpression());r===void 0||!_i.has(r)||s.push({callee:r,file:t,line:n.getStartLineNumber(),...Le(n.getArguments()[0])})}return s},qi=(e,t)=>{for(const s of $i){const n=S(t,s);if(!w(n))continue;const r=e.getSourceFile(n)??e.addSourceFileAtPath(n),i=[];for(const a of r.getDescendantsOfKind(l.CallExpression))b(a.getExpression())===St&&i.push({callee:St,file:s,line:a.getStartLineNumber(),...Le(a.getArguments()[0])});return i}return[]},ji=(e,t)=>{const s=[];for(const{displayPath:n,filePath:r}of he(t)){const i=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Bi(i,n))}return s.push(...qi(e,ce(t))),s},yt="ctx.containers.",Vi=e=>{if(!e.startsWith(yt))return!1;const t=e.slice(yt.length);return t.length>0&&!t.includes(".")},Wi=(e,t)=>Ee(e,t,{argIndex:0,matchReceiver:Vi,methods:new Set(["get"])}),Hi=new Set(["allow","deny","setAllowed"]),Gi=e=>{const t=e.getArguments()[0];if(!t||!o.isObjectLiteralExpression(t))return!1;const s=C(t,"enableInternet");return s!==void 0&&o.isPropertyAssignment(s)&&o.isTrueLiteral(s.getInitializerOrThrow())},Yi=(e,t)=>{const s=e.getExpression();if(!(!o.isPropertyAccessExpression(s)||s.getName()!=="start"||!Gi(e)))return{detail:"enableInternet: true",exportName:A(e),file:t,kind:"enable_internet",line:e.getStartLineNumber()}},Qi=(e,t)=>{const s=e.getExpression();if(!o.isPropertyAccessExpression(s)||!Hi.has(s.getName()))return;const n=s.getExpression();if(!(!o.isPropertyAccessExpression(n)||n.getName()!=="egress"))return{detail:s.getName(),exportName:A(e),file:t,kind:"egress_relaxation",line:e.getStartLineNumber()}},Xi=(e,t)=>Yi(e,t)??Qi(e,t),Zi=(e,t)=>F(e,t,Xi),Ji=new Set(["defineExportSink","r2Sink","webhookExportSink"]),eo=e=>{const t=e.getExpression();if(!o.isIdentifier(t))return;const s=t.getText();return Ji.has(s)?s:void 0},to=e=>{const t=[],s=[];for(const n of e.getProperties()){if(o.isSpreadAssignment(n))return{analyzable:!1,emptyKeys:[],presentKeys:[]};if(o.isPropertyAssignment(n)){const r=y(n);t.push(r);const i=n.getInitializer();i&&o.isStringLiteral(i)&&i.getLiteralText()===""&&s.push(r);continue}(o.isShorthandPropertyAssignment(n)||o.isMethodDeclaration(n)||o.isGetAccessorDeclaration(n))&&t.push(y(n))}return{analyzable:!0,emptyKeys:s,presentKeys:t}},so=(e,t)=>{const s=[];for(const{displayPath:n,filePath:r}of he(t)){const i=e.getSourceFile(r)??e.addSourceFileAtPath(r);for(const a of i.getDescendantsOfKind(l.CallExpression)){const c=eo(a);if(c===void 0)continue;const u=a.getArguments()[0],d=u&&o.isObjectLiteralExpression(u)?to(u):{analyzable:!1,emptyKeys:[],presentKeys:[]};s.push({analyzable:d.analyzable,emptyKeys:d.emptyKeys,factory:c,file:n,line:a.getStartLineNumber(),presentKeys:d.presentKeys})}}return s},no=new Map([["dbRateLimit",2],["rateLimit",2],["verifyTurnstileMiddleware",0]]),ro=new Set(["dbRateLimit","rateLimit"]),io=e=>{const t=Wt(e);if(!t)return!1;const s=C(t,"failOpen");return s!==void 0&&o.isPropertyAssignment(s)&&s.getInitializer()?.getKind()===l.TrueKeyword},oo=(e,t)=>{const s=b(e.getExpression());if(s===void 0)return;const n=no.get(s);if(n!==void 0)return{callee:s,exportName:A(e),failOpen:io(e.getArguments()[n]),file:t,limitName:ro.has(s)?Vt(e):"",line:e.getStartLineNumber()}},ao=(e,t)=>F(e,t,oo),co=new Set(["boolean","number","object","string"]),lo=e=>{const t=e.getName();if(!co.has(t))return;const s=e.getExpression();if(!o.isPropertyAccessExpression(s))return;if(s.getName()==="flags"&&Oe(s.getExpression()))return t;const n=s.getExpression();if(s.getName()==="details"&&o.isPropertyAccessExpression(n)&&n.getName()==="flags"&&Oe(n.getExpression()))return t},uo=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t))return;const s=lo(t);if(s===void 0)return;const n=e.getArguments()[0];if(!n||!(o.isStringLiteral(n)||o.isNoSubstitutionTemplateLiteral(n)))return;const r=n.getLiteralValue();return r.length>0?{key:r,type:s}:void 0},fo=(e,t)=>{const s=new Map;for(const n of m(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const i of r.getDescendantsOfKind(l.CallExpression)){const a=uo(i);a&&!s.has(a.key)&&s.set(a.key,a.type)}}return[...s.entries()].map(([n,r])=>({key:n,type:r})).toSorted((n,r)=>n.key.localeCompare(r.key))},go=e=>{const t=e.getInitializer();if(!t||!o.isCallExpression(t))return;const s=z(t);if(s?.kind!=="query")return;const n=Gs(t,s.receiver);return n?{exportName:e.getName(),handler:n}:void 0},At=e=>{const t=e.getParent();return t&&o.isPropertyAccessExpression(t)&&t.getExpression()===e?t:void 0},po=e=>{if(!o.isPropertyAccessExpression(e)||e.getName()!=="flags")return;const t=e.getExpression();if(!o.isIdentifier(t)||t.getText()!=="ctx")return;const s=At(e);if(!s)return"ctx.flags";if(s.getName()==="details"){const n=At(s);return n?`ctx.flags.details.${n.getName()}`:"ctx.flags.details"}return`ctx.flags.${s.getName()}`},mo=(e,t)=>{const s=[];for(const n of e.handler.getDescendantsOfKind(l.PropertyAccessExpression)){const r=po(n);r!==void 0&&s.push({callee:r,exportName:e.exportName,file:t,line:n.getStartLineNumber()})}return s},ho=(e,t)=>{const s=[];for(const n of e.getVariableStatements())if(n.isExported())for(const r of n.getDeclarations()){const i=go(r);i&&s.push(...mo(i,t))}return s},vo=(e,t)=>{const s=[];for(const n of m(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...ho(r,x(t,n)))}return s},xo=e=>{if(!o.isPropertyAccessExpression(e)||e.getName()!=="boolean")return!1;const t=e.getExpression();return o.isPropertyAccessExpression(t)&&t.getName()==="flags"&&Oe(t.getExpression())},Eo=e=>{if(e?.getKind()===l.TrueKeyword)return!0;if(e?.getKind()===l.FalseKeyword)return!1},So=(e,t)=>{if(!xo(e.getExpression()))return;const[s,n]=e.getArguments();if(!s||!(o.isStringLiteral(s)||o.isNoSubstitutionTemplateLiteral(s)))return;const r=s.getLiteralValue(),i=Eo(n);if(!(r.length===0||i===void 0))return{defaultValue:i,exportName:A(e),file:t,key:r,line:e.getStartLineNumber()}},yo=(e,t)=>F(e,t,So),Ao=e=>{const t=e.getType().getProperty("~standard");if(!t)return;const s=t.getTypeAtLocation(e).getProperty("types");if(!s)return;const n=s.getTypeAtLocation(e).getNonNullableType().getProperty("output");if(!n)return;const r=n.getTypeAtLocation(e),i=r.getText(e);if(!i||i==="any"||i==="never"||vn(i))return;const a=e.getSourceFile().getFilePath();if(xn(r,e,a)){const c=En(r,e,a,0,new Set);return c===void 0&&Sn(i),c}return i},bo=e=>{const t=e.getExpression();return o.isPropertyAccessExpression(t)&&t.getName()==="withGeoIndex"},No=e=>{const t=e.getArguments()[0];return t&&o.isStringLiteral(t)?t.getLiteralText():""},Po=(e,t)=>{const s=[];for(const n of m(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n),i=x(t,n);for(const a of r.getDescendantsOfKind(l.CallExpression))bo(a)&&s.push({file:i,indexName:No(a),line:a.getStartLineNumber()})}return s},Z=e=>e!==void 0&&(o.isArrowFunction(e)||o.isFunctionExpression(e))?e:void 0,is=e=>{const t=e.getArguments()[0],s=Z(t);if(s!==void 0)return s;if(t===void 0||!o.isObjectLiteralExpression(t))return;const n=C(t,"handler");return n!==void 0&&o.isPropertyAssignment(n)?Z(n.getInitializer()):void 0},wo=new Set(["delete","get","head","options","patch","post","put"]),Io=new Set(["handler","stream"]),To=new Set(["runAction","runMutation"]),Co=new Set(["delete","insert","insertManyUnsafe","patch","replace"]),J=(e,t)=>e!==void 0&&o.isIdentifier(e)&&e.getText()===t,os=(e,t)=>{if(!(e===void 0||!o.isObjectBindingPattern(e))){for(const s of e.getElements())if(Q(s)===t){const r=s.getNameNode();return o.isIdentifier(r)?r.getText():void 0}}},bt=(e,t)=>{const s=e.getParameters()[0]?.getNameNode();if(s!==void 0)return t?o.isIdentifier(s)?s.getText():void 0:os(s,"ctx")},Nt=(e,t)=>{const s=e.getParameters()[t?1:0]?.getNameNode();return t?s!==void 0&&o.isIdentifier(s)?s.getText():void 0:os(s,"request")},Pt=(e,t)=>{const s=e.getBody(),n=s.getDescendantsOfKind(l.CallExpression);o.isCallExpression(s)&&n.unshift(s);for(const r of n){const i=r.getExpression();if(!o.isPropertyAccessExpression(i))continue;const a=i.getName(),c=i.getExpression();if(To.has(a)&&J(c,t))return a;if(Co.has(a)&&o.isPropertyAccessExpression(c)&&c.getName()==="db"&&J(c.getExpression(),t))return`db.${a}`}},wt=(e,t)=>{const s=e.getBody();for(const n of s.getDescendantsOfKind(l.PropertyAccessExpression))if(n.getName()==="auth"&&J(n.getExpression(),t))return!0;for(const n of s.getDescendantsOfKind(l.VariableDeclaration)){const r=n.getNameNode();if(!(!o.isObjectBindingPattern(r)||!J(n.getInitializer(),t))){for(const i of r.getElements())if(Q(i)==="auth")return!0}}return!1},Fo=/signature|hmac|digest|(?:^|[_-])sig(?:[_-]|$)/i,Oo=(e,t)=>{const s=e.getExpression();if(!o.isPropertyAccessExpression(s)||s.getName()!=="get"&&s.getName()!=="has")return!1;const n=s.getExpression();return o.isPropertyAccessExpression(n)&&n.getName()==="headers"&&J(n.getExpression(),t)},Ro=e=>[...o.isStringLiteral(e)?[e.getLiteralText()]:[],...e.getDescendantsOfKind(l.StringLiteral).map(t=>t.getLiteralText())],as=(e,t)=>{const s=e.getVariableDeclaration(t)?.getInitializer();return s===void 0?[]:Ro(s)},Lo=(e,t)=>{const s=e.getText();for(let n=e.getParent();n!==void 0;n=n.getParent()){if(!o.isArrowFunction(n)&&!o.isFunctionExpression(n)||!n.getParameters().some(c=>c.getName()===s))continue;const r=n.getParent();if(!o.isCallExpression(r))return[];const i=r.getExpression();if(!o.isPropertyAccessExpression(i))return[];const a=i.getExpression();return o.isIdentifier(a)?as(t,a.getText()):[]}return[]},Do=e=>{const t=e.getArguments()[0];if(t===void 0)return[];if(o.isStringLiteral(t))return[t.getLiteralText()];if(!o.isIdentifier(t))return[];const s=e.getSourceFile(),n=as(s,t.getText());return n.length>0?n:Lo(t,s)},It=(e,t)=>{if(t===void 0)return!1;const s=e.getBody(),n=s.getDescendantsOfKind(l.CallExpression);return o.isCallExpression(s)&&n.unshift(s),n.some(r=>Oo(r,t)&&Do(r).some(i=>Fo.test(i)))},ko=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||!Io.has(t.getName()))return;let s=t.getExpression();for(;o.isCallExpression(s);){const n=s.getExpression();if(!o.isPropertyAccessExpression(n))return;const r=n.getName();if(wo.has(r)){const i=n.getExpression();return o.isIdentifier(i)&&i.getText()==="httpRoute"?r.toUpperCase():void 0}s=n.getExpression()}},Mo=(e,t)=>{const s=e.getExpression();if(o.isIdentifier(s)&&s.getText()==="httpAction"){const c=Z(e.getArguments()[0]),u=c&&bt(c,!0);if(!c||u===void 0||It(c,Nt(c,!0)))return;const d=Pt(c,u);return d===void 0?void 0:{exportName:A(e),file:t,kind:"httpAction",line:e.getStartLineNumber(),readsAuth:wt(c,u),sideEffect:d}}const n=ko(e);if(n===void 0)return;const r=Z(e.getArguments()[0]),i=r&&bt(r,!1);if(!r||i===void 0||It(r,Nt(r,!1)))return;const a=Pt(r,i);return a===void 0?void 0:{exportName:A(e),file:t,kind:"httpRoute",line:e.getStartLineNumber(),method:n,readsAuth:wt(r,i),sideEffect:a}},Ko=(e,t)=>F(e,t,Mo),_o=new Set(["btoa","encodeURI","encodeURIComponent","isSafeHeaderValue","Number","parseFloat","parseInt"]),zo=new Set(["append","set"]),cs=e=>e!==void 0&&(o.isStringLiteral(e)||o.isNoSubstitutionTemplateLiteral(e))?e.getLiteralText():"",Tt=(e,t)=>(o.isCallExpression(e)?[e,...e.getDescendantsOfKind(l.CallExpression)]:e.getDescendantsOfKind(l.CallExpression)).some(n=>_o.has(b(n.getExpression())??"")&&gn(n,t)),$o=(e,t)=>{if(Tt(e,t))return!0;const s=ve(e);return s!==void 0&&Tt(s,t)},De=(e,t)=>fn(e,t)&&!$o(e,t),Uo=e=>{if(o.isPropertyAccessExpression(e)&&e.getName()==="headers")return!0;const t=ve(e);return t!==void 0&&o.isNewExpression(t)&&b(t.getExpression())==="Headers"},fe=e=>{if(e===void 0)return;if(o.isObjectLiteralExpression(e))return e;const t=ve(e);return t!==void 0&&o.isObjectLiteralExpression(t)?t:void 0},$e=(e,t,s)=>{for(const n of e.getProperties())if(o.isPropertyAssignment(n)){const r=n.getInitializer();r!==void 0&&De(r,s.requestName)&&s.rows.push({exportName:s.exportName,file:s.relativePath,headerName:cs(n.getNameNode()),line:r.getStartLineNumber(),via:t})}else if(o.isShorthandPropertyAssignment(n)){const r=n.getNameNode();De(r,s.requestName)&&s.rows.push({exportName:s.exportName,file:s.relativePath,headerName:y(n),line:r.getStartLineNumber(),via:t})}else if(o.isSpreadAssignment(n)){const r=fe(n.getExpression());r!==void 0&&$e(r,t,s)}},ls=(e,t)=>{const s=fe(e);if(s===void 0)return;const n=C(s,"headers");if(n===void 0||!o.isPropertyAssignment(n))return;const r=fe(n.getInitializer());r!==void 0&&$e(r,"response-init",t)},Bo=(e,t)=>{const s=b(e.getExpression());if(s==="Response")ls(e.getArguments()[1],t);else if(s==="Headers"){const n=fe(e.getArguments()[0]);n!==void 0&&$e(n,"headers-ctor",t)}},qo=(e,t)=>{const s=e.getExpression();if(!o.isPropertyAccessExpression(s))return;const n=s.getName(),r=s.getExpression();if(n==="json"&&o.isIdentifier(r)&&r.getText()==="Response"){ls(e.getArguments()[1],t);return}if(zo.has(n)&&Uo(r)){const i=e.getArguments()[1];i!==void 0&&De(i,t.requestName)&&t.rows.push({exportName:t.exportName,file:t.relativePath,headerName:cs(e.getArguments()[0]),line:i.getStartLineNumber(),via:n==="set"?"headers-set":"headers-append"})}},jo=(e,t)=>{for(const s of e.getDescendantsOfKind(l.NewExpression))Bo(s,t);for(const s of e.getDescendantsOfKind(l.CallExpression))qo(s,t)},Vo=(e,t)=>{const s=e.getExpression();if(!o.isIdentifier(s)||s.getText()!=="httpAction")return[];const n=Z(e.getArguments()[0]);if(n===void 0)return[];const r=n.getParameters()[1];if(r===void 0)return[];const i=r.getNameNode();if(!o.isIdentifier(i))return[];const a=[];return jo(n,{exportName:A(e),relativePath:t,requestName:i.getText(),rows:a}),a},Wo=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression))s.push(...Vo(n,t));return s},Ho=(e,t)=>{const s=[];for(const n of m(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Wo(r,x(t,n)))}return s},Go=new Set(["auth","context.auth","ctx.auth"]),Yo="userId",Qo=e=>{const t=new Set;for(const s of e.getProperties()){if(o.isSpreadAssignment(s))return;(o.isPropertyAssignment(s)||o.isShorthandPropertyAssignment(s)||o.isMethodDeclaration(s))&&t.add(y(s))}return t},Xo=(e,t)=>{const s=S(t,es);if(!w(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const r of n.getDescendantsOfKind(l.CallExpression)){if(b(r.getExpression())!=="defineIdentity")continue;const[i]=r.getArguments();return i&&o.isObjectLiteralExpression(i)?Qo(i):void 0}},Ct=e=>{if(!(e===void 0||!o.isPropertyAccessExpression(e)||e.getName()!=="identity"))return Go.has(e.getExpression().getText())?e:void 0},Zo=e=>{if(o.isPropertyAccessExpression(e)&&Ct(e.getExpression())!==void 0)return e.getName();if(o.isElementAccessExpression(e)&&Ct(e.getExpression())!==void 0){const t=e.getArgumentExpression();return t&&o.isStringLiteral(t)?t.getLiteralValue():void 0}},Jo=(e,t,s)=>{const n=[];for(const r of e.getDescendants()){const i=Zo(r);i!==void 0&&n.push({declared:i===Yo||s.has(i),exportName:A(r),file:t,key:i,line:r.getStartLineNumber()})}return n},ea=(e,t)=>{const s=Xo(e,t);if(s===void 0)return[];const n=[];for(const r of m(t)){const i=e.getSourceFile(r)??e.addSourceFileAtPath(r);n.push(...Jo(i,x(t,r),s))}return n},ta=(e,t)=>{if(b(e.getExpression())!=="buildImageDeliveryUrl")return;const s=e.getArguments()[0];if(!s)return;const n=P(s,"key");if(!(!n||!M(n)||U(n)))return{exportName:A(e),file:t,line:e.getStartLineNumber()}},sa=(e,t)=>F(e,t,ta),na=e=>{if(o.isComputedPropertyName(e)){const t=e.getExpression();return o.isStringLiteral(t)||o.isNoSubstitutionTemplateLiteral(t)?t.getLiteralValue():void 0}return o.isStringLiteral(e)?e.getLiteralValue():e.getText()},ra=e=>e.getProperties().some(t=>{if(o.isSpreadAssignment(t))return!0;const s=na(t.getNameNode());return s===void 0||s==="namespace"}),ia=(e,t)=>{for(const{filePath:s}of he(t)){const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const r of n.getDescendantsOfKind(l.CallExpression)){const i=r.getExpression(),[a]=r.getArguments();if(!(!o.isPropertyAccessExpression(i)||i.getName()!=="auth"||a===void 0)&&(!o.isObjectLiteralExpression(a)||ra(a)))return r}}},oa="https://lunora.sh/docs/concepts/data-residency#pinning-auth-and-voice",aa=(e,t)=>{if(!(e.jurisdiction===void 0||e.jurisdictionPinsAuth===!0||t===void 0))throw ee(t,`the schema pins Durable Objects to the "${e.jurisdiction}" jurisdiction, and this project also has DO-backed auth (users, sessions, accounts, credentials). Pinning the auth object resolves it to a NEW, EMPTY object: existing users stay in the unpinned one until you copy them across (${oa}). Acknowledge with \`.jurisdiction("${e.jurisdiction}", { pinAuth: true })\`, deploy, then run the copy. For D1-mode auth the acknowledgement changes nothing.`,{code:"JURISDICTION_MOVE",status:422})},ca=new Set(["delete","get","getRaw","getWithMetadata","put"]),la=(e,t,s=[])=>{const n=new Map(s.map(i=>[`${i.filePath}:${i.exportName}`,i.visibility]));return Ee(e,t,{argIndex:0,matchReceiver:i=>i==="ctx.kv"||i.startsWith("ctx.kv."),methods:ca}).map(i=>{const a=n.get(`${i.file}:${i.exportName}`);return a===void 0?i:{...i,visibility:a}})},ua=new Set(["queue","send"]),Ft=new Set(["bcc","cc","to"]),da=e=>{if(!o.isPropertyAccessExpression(e))return;const t=e.getName();if(!ua.has(t))return;const s=e.getExpression().getText();return s==="ctx.mail"||s==="ctx.email"?t:void 0},fa=e=>o.isObjectLiteralExpression(e)?e.getProperties().some(t=>{if(o.isShorthandPropertyAssignment(t)){const n=t.getNameNode();return Ft.has(y(t))&&M(n)&&!U(n)}if(!o.isPropertyAssignment(t)||!Ft.has(y(t)))return!1;const s=t.getInitializer();return s!==void 0&&M(s)&&!U(s)}):!1,ga=(e,t)=>{const s=da(e.getExpression());if(s===void 0)return;const n=e.getArguments()[0];if(!(!n||!fa(n)))return{exportName:A(e),file:t,line:e.getStartLineNumber(),method:s}},pa=(e,t)=>F(e,t,ga),ma=e=>o.isPropertyAssignment(e)||o.isMethodDeclaration(e)||o.isGetAccessorDeclaration(e)?o.isComputedPropertyName(e.getNameNode()):!1,ha=e=>o.isPropertyAssignment(e)||o.isShorthandPropertyAssignment(e)||o.isMethodDeclaration(e)||o.isGetAccessorDeclaration(e)?ma(e):!0,us=(e,t=!1)=>{for(const s of e.getProperties()){if(ha(s))return!0;if(t)continue;if(!o.isPropertyAssignment(s))return!0;const n=s.getInitializer();if(!n||!o.isObjectLiteralExpression(n)||us(n,!0))return!0}return!1},va=(e,t)=>{for(const s of m(t)){const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const{receiver:r}of Zt(n))for(const i of Ke(r)){const a=i.getArguments()[0];if(a!==void 0&&(!o.isObjectLiteralExpression(a)||us(a)))return!0}}return!1},xa=e=>{const t=e.getArguments()[0];if(!t||!o.isObjectLiteralExpression(t))return[];const s=[];for(const n of t.getProperties()){const r=de(n);if(r===void 0||!o.isPropertyAssignment(n))continue;const i=n.getInitializer();if(!(!i||!o.isObjectLiteralExpression(i)))for(const a of i.getProperties()){const c=de(a);c!==void 0&&s.push({column:c,strategy:Xt(a),table:r})}}return s},Ea=(e,t)=>{const s=new Map;for(const n of m(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const{receiver:i}of Zt(r))for(const a of Ke(i))for(const c of xa(a)){const u=`${c.table}\0${c.column}`;s.has(u)||s.set(u,c)}}return{columns:[...s.values()]}},Sa=(e,t,s)=>{const n=e.getArguments()[0];if(!n||!o.isObjectLiteralExpression(n))return[];const r=[];for(const i of n.getProperties()){const a=de(i);if(a===void 0||!o.isPropertyAssignment(i))continue;const c=i.getInitializer();if(!(!c||!o.isObjectLiteralExpression(c)))for(const u of c.getProperties()){const d=de(u);if(d===void 0)continue;const g=Xt(u);g!=="custom"&&r.push({column:d,exportName:t,file:s,line:u.getStartLineNumber(),strategy:g,table:a})}}return r},ya=(e,t)=>{if(!o.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&o.isCallExpression(s)?z(s):void 0;return n?.receiver?Ke(n.receiver).flatMap(r=>Sa(r,e.getName(),t)):[]},Aa=(e,t)=>{const s=[];for(const n of m(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n),i=x(t,n);for(const a of r.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...ya(c,i))}return s},ba=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||t.getName()!=="replace")return!1;const s=t.getExpression();return _(s)},Na=e=>{const t=e.getArguments()[0];if(t===void 0||!o.isObjectLiteralExpression(t))return;const s=C(t,"server");if(s!==void 0)return o.isPropertyAssignment(s)?s.getInitializer():s},Pa=e=>{if(!e.isExported())return;const t=e.getInitializer();if(t?.getKind()!==l.CallExpression)return;const s=t;return Fn(s.getExpression())?s:void 0},wa=e=>{const t=Pa(e),s=t===void 0?void 0:Na(t);if(s===void 0)return[];const n=e.getNameNode(),r=o.isIdentifier(n)?n.getText():"";return s.getDescendantsOfKind(l.CallExpression).filter(i=>ba(i)).map(i=>({exportName:r,file:"lunora/mutators.ts",line:i.getStartLineNumber()}))},Ia=e=>e.getVariableDeclarations().flatMap(t=>wa(t)),Ta=(e,t)=>{const s=S(t,Cn);if(!w(s))return[];const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);return Ia(n)},Ca=new Set(["delete","get","patch"]),Fa=new Set(["accountId","authorId","companyId","createdBy","createdById","customerId","groupId","memberId","organizationId","orgId","ownerId","projectId","teamId","tenantId","userId","workspaceId"]),Oa=new Set(["auth","identity","session","user"]),Ra=new Set([l.EqualsEqualsEqualsToken,l.EqualsEqualsToken,l.ExclamationEqualsEqualsToken,l.ExclamationEqualsToken]),La=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||t.getName()!=="normalizeId"||!_(t.getExpression()))return;const s=e.getArguments()[0];return s&&o.isStringLiteral(s)?s.getLiteralText():""},Da=e=>{let t=e,s=t.getParent();for(;s!==void 0&&(o.isAsExpression(s)||o.isParenthesizedExpression(s)||o.isNonNullExpression(s));)t=s,s=t.getParent();if(s===void 0||!o.isVariableDeclaration(s))return;const n=s.getNameNode();return o.isIdentifier(n)?n.getText():void 0},ka=(e,t)=>e.getDescendantsOfKind(l.Identifier).some(s=>s.getText()===t),Ma=e=>o.isThrowStatement(e)||o.isReturnStatement(e)||e.getDescendantsOfKind(l.ThrowStatement).length>0||e.getDescendantsOfKind(l.ReturnStatement).length>0,Ka=(e,t)=>e.getDescendantsOfKind(l.IfStatement).some(s=>ka(s.getExpression(),t)&&Ma(s.getThenStatement())),_a=(e,t)=>{for(const s of e.getDescendantsOfKind(l.CallExpression)){const n=s.getExpression();if(!o.isPropertyAccessExpression(n))continue;const r=n.getName();if(!Ca.has(r))continue;const i=n.getExpression();if(!(_(i)||o.isPropertyAccessExpression(i)&&_(i.getExpression())))continue;const c=s.getArguments()[0];if(c!==void 0&&o.isIdentifier(c)&&c.getText()===t)return r}},za=e=>{let t=e;for(;o.isPropertyAccessExpression(t)||o.isElementAccessExpression(t)||o.isNonNullExpression(t)||o.isParenthesizedExpression(t)||o.isAsExpression(t)||o.isAwaitExpression(t);)t=t.getExpression();return o.isIdentifier(t)?t.getText():void 0},$a=e=>e.getDescendantsOfKind(l.CallExpression).some(t=>t.getArguments().some(s=>za(s)==="ctx")),Ua=e=>e.getDescendantsOfKind(l.BinaryExpression).some(t=>Ra.has(t.getOperatorToken().getKind())?o.isPropertyAccessExpression(t.getLeft())||o.isPropertyAccessExpression(t.getRight()):!1),Ba=e=>{for(const t of e.getDescendantsOfKind(l.Identifier))if(Fa.has(t.getText()))return!0;for(const t of e.getDescendantsOfKind(l.PropertyAccessExpression)){const s=t.getExpression();if(o.isIdentifier(s)&&s.getText()==="ctx"&&Oa.has(t.getName()))return!0}return $a(e)||Ua(e)},qa=(e,t)=>{if(!o.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!o.isCallExpression(s))return[];const n=z(s);if(n?.kind!=="query"&&n?.kind!=="mutation")return[];const r=is(s);if(r===void 0)return[];const i=n.receiver!==void 0&&Gt(n.receiver,"use","rls"),a=Ba(r),c=new Set,u=[];for(const d of r.getDescendantsOfKind(l.CallExpression)){const g=La(d);if(g===void 0)continue;const h=Da(d);if(h===void 0||c.has(h)||!Ka(r,h))continue;const O=_a(r,h);O!==void 0&&(c.add(h),u.push({exportName:e.getName(),file:t,line:d.getStartLineNumber(),mentionsOwnership:a,sinkMethod:O,table:g,usesRls:i,visibility:n.visibility}))}return u},ja=(e,t)=>{const s=[];for(const n of m(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n),i=x(t,n);for(const a of r.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...qa(c,i))}return s},Va=new Set(["accountId","authorId","createdBy","createdById","organizationId","orgId","ownerId","tenantId","updatedBy","userId","workspaceId"]),Wa=new Set(["insert","insertManyUnsafe","patch","replace"]),Ha=e=>{if(!o.isPropertyAccessExpression(e))return;const t=e.getName();if(!Wa.has(t))return;const s=e.getExpression();if(!o.isPropertyAccessExpression(s)||s.getName()!=="db")return;const n=s.getExpression();return o.isIdentifier(n)&&n.getText()==="ctx"?t:void 0},Ga=(e,t)=>{if(t!=="insertManyUnsafe")return o.isObjectLiteralExpression(e)?[e]:[];if(!o.isArrayLiteralExpression(e))return[];const s=[];for(const n of e.getElements())o.isObjectLiteralExpression(n)&&s.push(n);return s},Ot=(e,t)=>{if(o.isPropertyAccessExpression(e)){const s=e.getExpression();return o.isIdentifier(s)&&s.getText()==="args"&&e.getName()===t}if(o.isElementAccessExpression(e)){const s=e.getExpression(),n=e.getArgumentExpression();return o.isIdentifier(s)&&s.getText()==="args"&&n!==void 0&&o.isStringLiteral(n)&&n.getLiteralValue()===t}return!1},Ya=e=>{if(!o.isIdentifier(e))return;const t=e.getText(),s=e.getFirstAncestor(a=>o.isArrowFunction(a)||o.isFunctionExpression(a)||o.isFunctionDeclaration(a));if(s===void 0)return;for(const a of s.getDescendantsOfKind(l.BinaryExpression)){const c=a.getLeft();if(o.isIdentifier(c)&&c.getText()===t&&a.getOperatorToken().getText().endsWith("="))return}const n=e.getStart();let r,i=-1;for(const a of s.getDescendantsOfKind(l.VariableDeclaration)){if(a.getName()!==t)continue;const c=a.getParent();if(!o.isVariableDeclarationList(c)||c.getDeclarationKind()!==zs.Const)continue;const u=a.getInitializer(),d=a.getStart();u!==void 0&&d<n&&d>i&&(r=u,i=d)}return r},Qa=(e,t)=>{if(Ot(e,t))return!0;const s=Ya(e);return s!==void 0&&Ot(s,t)},Xa=(e,t,s,n,r)=>{const i=[];for(const a of e.getProperties()){let c,u;if(o.isPropertyAssignment(a)?(c=y(a),u=a.getInitializer()):o.isShorthandPropertyAssignment(a)&&(c=y(a),u=a.getNameNode()),!(c===void 0||u===void 0||!Va.has(c))&&M(u)&&!U(u)){const d=A(s),g=r(d)===c&&Qa(u,c);i.push({exportName:d,field:c,file:n,line:s.getStartLineNumber(),method:t,...g&&{ownerScoped:!0}})}}return i},Za=(e,t,s)=>{const n=Ha(e.getExpression());if(n===void 0)return[];const r=e.getArguments()[1];return r?Ga(r,n).flatMap(i=>Xa(i,n,e,t,s)):[]},Ja=(e,t,s)=>{const n=[];for(const r of e.getDescendantsOfKind(l.CallExpression))for(const i of Za(r,t,a=>s(a).owner)){const{visibility:a}=s(i.exportName);n.push(a===void 0?i:{...i,visibility:a})}return n},ec=(e,t,s=[],n=[])=>{const r=[],i=new Map;for(const a of s)i.set(`${a.filePath}:${a.exportName}`,{visibility:a.visibility});for(const a of n){const c=`${a.filePath}:${a.exportName}`;i.set(c,{...i.get(c),owner:a.owner})}for(const a of m(t)){const c=e.getSourceFile(a)??e.addSourceFileAtPath(a),u=x(t,a);r.push(...Ja(c,u,d=>i.get(`${u}:${d}`)??{}))}return r},tc=["providerSubscriptionId","state"],sc=["providerEventId","processedAt"],Rt=(e,t)=>t.every(s=>s in e.shape),nc=e=>{const t=e.find(n=>n.name==="subscriptions"),s=e.find(n=>n.name==="events");return t!==void 0&&s!==void 0&&Rt(t,tc)&&Rt(s,sc)},rc=new Set(["createAutumnAdapter","createDodoPaymentsAdapter","createPolarAdapter","createStripeAdapter"]),ic=e=>e&&o.isNumericLiteral(e)?Number(e.getText()):void 0,oc=e=>{const t=C(e,"webhookToleranceSeconds");return t&&o.isPropertyAssignment(t)?ic(t.getInitializer()):void 0},ac=(e,t)=>{const s=b(e.getExpression());if(s===void 0||!rc.has(s))return;const[n]=e.getArguments(),r=n&&o.isObjectLiteralExpression(n)?oc(n):void 0;return{callee:s,exportName:A(e),file:t,line:e.getStartLineNumber(),...r===void 0?{}:{toleranceSeconds:r}}},cc=(e,t)=>F(e,t,ac),lc=new Map([["defineQueue",0],["defineSubscription",1],["defineWorkflow",0]]),uc=new Set(["run","runAction","runMutation","runQuery"]),dc=new Set(["api","internal"]),fc=e=>{const t=e.getExpression();return o.isIdentifier(t)?t.getText():void 0},gc=(e,t)=>{const s=e.getArguments()[t];if(!s||!o.isObjectLiteralExpression(s))return;const n=C(s,"handler");if(n===void 0||!o.isPropertyAssignment(n))return;const r=n.getInitializer();if(r&&(o.isArrowFunction(r)||o.isFunctionExpression(r)))return r},ds=(e,t)=>{const s=e.getParameters()[t]?.getNameNode();return s&&o.isIdentifier(s)?s.getText():void 0},fs=(e,t)=>e===t||e.startsWith(`${t}.`),gs=e=>{const t=e.getDescendantsOfKind(l.PropertyAccessExpression);return o.isPropertyAccessExpression(e)&&t.push(e),t},Lt=e=>{const t=e.getParent();return o.isPropertyAccessExpression(t)&&t.getNameNode()===e||o.isPropertyAssignment(t)&&t.getNameNode()===e?!1:!(o.isBindingElement(t)&&t.getNameNode()===e)},ps=e=>{const t=e.getDescendantsOfKind(l.Identifier).filter(s=>Lt(s));return o.isIdentifier(e)&&Lt(e)&&t.push(e),t},pc=e=>{if(!o.isVariableDeclaration(e))return[];const t=e.getNameNode();return o.isIdentifier(t)?[t.getText()]:t.getDescendantsOfKind(l.BindingElement).map(s=>s.getName())},mc=e=>{const t=ds(e,1);if(t===void 0)return[];const s=[`${t}.messages`];for(const n of e.getDescendantsOfKind(l.ForOfStatement)){if(n.getExpression().getText()!==`${t}.messages`)continue;const r=n.getInitializer(),i=o.isVariableDeclarationList(r)?r.getDeclarations()[0]?.getNameNode():void 0;i&&o.isIdentifier(i)&&s.push(`${i.getText()}.body`)}return s},hc=(e,t,s)=>{const n=t==="workflow"?[`${s}.params`]:mc(e),r=new Set,i=a=>gs(a).some(c=>n.some(u=>fs(c.getText(),u)))?!0:ps(a).some(c=>r.has(c.getText()));for(const a of e.getDescendantsOfKind(l.VariableDeclaration)){const c=a.getInitializer();if(c&&i(c))for(const u of pc(a))r.add(u)}return{names:r,prefixes:n}},vc=(e,t)=>gs(e).some(s=>t.prefixes.some(n=>fs(s.getText(),n)))?!0:ps(e).some(s=>t.names.has(s.getText())),xc=e=>{if(e===void 0||!o.isPropertyAccessExpression(e))return;const t=[];let s=e;for(;o.isPropertyAccessExpression(s);)t.unshift(s.getName()),s=s.getExpression();const n=t.at(-1);if(!(n===void 0||!o.isIdentifier(s)||!dc.has(s.getText())||t.length<2))return{exportName:n,file:t.slice(0,-1).join("/")}},Ec=(e,t,s)=>{const n=ds(e,0);if(n===void 0)return[];const r=hc(e,t,n),i=new Set([n,...r.prefixes.filter(c=>c.endsWith(".body")).map(c=>c.slice(0,-5))]),a=[];for(const c of e.getDescendantsOfKind(l.CallExpression)){const u=c.getExpression();if(!o.isPropertyAccessExpression(u)||!uc.has(u.getName())||!i.has(u.getExpression().getText()))continue;const d=c.getArguments()[1];if(!d||!vc(d,r))continue;const g=xc(c.getArguments()[0]);g!==void 0&&a.push({dispatchKind:t,file:s,handlerExport:A(c),line:c.getStartLineNumber(),targetExport:g.exportName,targetFile:g.file})}return a},Sc=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression)){const r=fc(n),i=r===void 0?void 0:lc.get(r);if(i===void 0)continue;const a=gc(n,i);a!==void 0&&s.push(...Ec(a,r==="defineWorkflow"?"workflow":"queue",t))}return s},yc=(e,t)=>{const s=[];for(const n of m(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Sc(r,x(t,n)))}return s},Dt={dbRateLimit:"usesRateLimit",emailGateMiddleware:"usesEmailGate",mask:"usesMask",rateLimit:"usesRateLimit",rls:"usesRls",verifyTurnstileMiddleware:"usesCaptcha"},kt=new Set(["account","credential","member","passkey","session","user"]),Ac=e=>e.replaceAll(/[-_]/gu," ").replaceAll(/([a-z0-9])([A-Z])/gu,"$1 $2").split(" ").filter(Boolean).map(t=>t.toLowerCase()),bc=e=>{const s=Ac(e).at(-1);if(!s)return!1;const n=s.endsWith("s")?s.slice(0,-1):s;return kt.has(s)||kt.has(n)},Nc=e=>{const t=e.replaceAll(/[^a-z0-9]/giu,"").toLowerCase();return t.endsWith("email")||t.endsWith("emailaddress")},Pc=(e,t)=>{const{objects:s,opaque:n}=ze(e,t);return pi(s).some(r=>Nc(r))?!0:n?void 0:!1},wc=e=>{const t=e.getArguments()[0];return!t||!o.isObjectLiteralExpression(t)?{usesCaptcha:!1,usesRateLimit:!1}:{usesCaptcha:!!C(t,"captcha"),usesRateLimit:!!C(t,"rateLimit")}},Ic=e=>{if(o.isCallExpression(e))return e;if(!o.isIdentifier(e))return;const s=e.getSourceFile().getVariableDeclaration(e.getText())?.getInitializer();return s&&o.isCallExpression(s)?s:void 0},ue={usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},Tc=e=>{const t=Ic(e),s=t?b(t.getExpression()):void 0;if(t&&s==="protectPublic"){const n=wc(t);return{...ue,usesCaptcha:n.usesCaptcha,usesRateLimit:n.usesRateLimit}}return s!==void 0&&s in Dt?{...ue,[Dt[s]]:!0}:ue},Cc=e=>{const t={...ue};let s=e;for(;o.isCallExpression(s);){const n=s.getExpression();if(!o.isPropertyAccessExpression(n))break;const r=n.getName()==="use"?s.getArguments()[0]:void 0;if(r){const i=Tc(r);t.usesCaptcha||=i.usesCaptcha,t.usesEmailGate||=i.usesEmailGate,t.usesMask||=i.usesMask,t.usesRateLimit||=i.usesRateLimit,t.usesRls||=i.usesRls}s=n.getExpression()}return t},Fc=new Set(["insert","insertMany","insertManyUnsafe","replace"]),Oc=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||!Fc.has(t.getName()))return!1;const s=t.getExpression();if(!_(s))return!1;const r=e.getArguments()[0];return!r||!(o.isStringLiteral(r)||o.isNoSubstitutionTemplateLiteral(r))?!1:bc(r.getLiteralText())},Rc=new Set(["create","publish","publishBatch","runAfter","runAt","send","sendBatch"]),Lc=new Set(["queues","scheduler","topics","workflows"]),Dc=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||!Rc.has(t.getName()))return!1;let s=t.getExpression();for(;o.isCallExpression(s)||o.isElementAccessExpression(s)||o.isPropertyAccessExpression(s);){if(o.isPropertyAccessExpression(s)&&Lc.has(s.getName())){const n=s.getExpression();if(o.isIdentifier(n)&&n.getText()==="ctx")return!0}s=s.getExpression()}return!1},kc=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||t.getName()!=="insertManyUnsafe")return!1;const s=t.getExpression();return _(s)},ms=new Set(["generateObject","generateText","streamObject","streamText"]),Mc=e=>{const t=b(e.getExpression());return t!==void 0&&ms.has(t)},Kc=e=>{const t=b(e.getExpression());if(t===void 0||!ms.has(t))return!1;const s=e.getArguments()[0];return!s||!o.isObjectLiteralExpression(s)||s.getProperties().some(n=>o.isSpreadAssignment(n))?!1:!C(s,"maxOutputTokens")},_c=new Set(["log","span","trace"]),zc=new Set(["ai"]),$c=new Set(["email","mail"]),Uc=new Set(["ai","browser","fetch","mail","notify","queues","sql","storage","topics","workflows"]),Ce=(e,t)=>e.getDescendantsOfKind(l.PropertyAccessExpression).some(s=>{if(!t.has(s.getName()))return!1;const n=s.getExpression();return o.isIdentifier(n)&&n.getText()==="ctx"}),Bc=new Set([l.ArrowFunction,l.FunctionDeclaration,l.FunctionExpression,l.GetAccessor,l.MethodDeclaration,l.SetAccessor]),qc=new Set(["every","filter","flatMap","forEach","map","some"]),jc=new Set(["all","allSettled","race"]),Vc=e=>{const t=e.getParent();if(!t||!o.isCallExpression(t)||!t.getArguments().includes(e))return;const s=t.getExpression();if(!o.isPropertyAccessExpression(s))return;const n=s.getName();if(qc.has(n))return t;const r=s.getExpression();if(o.isIdentifier(r)&&r.getText()==="Promise"&&jc.has(n))return t},Wc=e=>{let t=e.getParent();for(;t;){if(o.isTryStatement(t)){const s=t.getTryBlock();if(e.getPos()>=s.getPos()&&e.getEnd()<=s.getEnd())return!0}if(Bc.has(t.getKind())){const s=Vc(t);if(!s)return!1;t=s;continue}t=t.getParent()}return!1},Hc=e=>{let t=e;for(;;){const s=t.getParent();if(!o.isPropertyAccessExpression(s)||s.getExpression()!==t)return!1;if(s.getName()==="catch")return!0;if(s.getName()!=="then"&&s.getName()!=="finally")return!1;const n=s.getParent();if(!o.isCallExpression(n)||n.getExpression()!==s)return!1;t=n}},Gc=e=>{let t=e;for(;;){const s=t.getParent();if(o.isPropertyAccessExpression(s)&&s.getExpression()===t){t=s;continue}return o.isCallExpression(s)&&s.getExpression()===t?s:void 0}},Yc=e=>{let t=!1,s=!0;for(const n of e.getDescendantsOfKind(l.PropertyAccessExpression)){if(!Uc.has(n.getName()))continue;const r=n.getExpression();if(!o.isIdentifier(r)||r.getText()!=="ctx")continue;const i=Gc(n);i&&(t=!0,!Wc(i)&&!Hc(i)&&(s=!1))}return{handlesErrors:t&&s,reachesOutbound:t}},Qc=e=>e.getDescendantsOfKind(l.ThrowStatement).some(t=>{const s=t.getExpression();if(!o.isNewExpression(s))return!1;const n=s.getExpression();return o.isIdentifier(n)&&n.getText()==="Error"}),Mt="lunora-advisor-exempt",Xc=/^[\s*/]+/u,Zc=/[\w-]/u,Jc=e=>{const s=(e.getFirstAncestorByKind(l.VariableStatement)??e).getLeadingCommentRanges().map(n=>n.getText()).join(`
|
|
6
|
-
`);for(const n of s.split(`
|
|
7
|
-
`)){const r=n.replace(Xc,"");if(!r.startsWith(Mt))continue;const i=r.slice(Mt.length);if(Zc.test(i.charAt(0)))continue;const a=i.indexOf("--");return{exempt:!0,exemptReason:(a===-1?"":i.slice(a+2).split("*")[0]??"").trim()}}return{exempt:!1,exemptReason:""}},el=e=>{const[t]=e.getArguments();if(t){if(o.isObjectLiteralExpression(t)){const s=C(t,"handler");return s?o.isPropertyAssignment(s)?s.getInitializer():o.isShorthandPropertyAssignment(s)?s.getNameNode():o.isMethodDeclaration(s)?s:void 0:void 0}return t}},tl=(e,t)=>{const s=el(t);if(!s)return;if(o.isArrowFunction(s)||o.isFunctionExpression(s)||o.isMethodDeclaration(s))return e;if(!o.isIdentifier(s))return;const n=s.getSourceFile(),r=s.getText(),i=n.getVariableDeclaration(r)?.getInitializer();return i&&(o.isArrowFunction(i)||o.isFunctionExpression(i))?i:n.getFunction(r)},sl=e=>{let t=!1,s=!1,n=!1,r=!1,i=!1;for(const u of e.getDescendantsOfKind(l.CallExpression))if(Oc(u)&&(i=!0),Dc(u)&&(t=!0),kc(u)&&(r=!0),Mc(u)&&(s=!0),Kc(u)&&(n=!0),i&&t&&r&&n)break;const{handlesErrors:a,reachesOutbound:c}=Yc(e);return{callsMail:Ce(e,$c),emitsEvent:Ce(e,_c),fanOut:t,handlesErrors:a,reachesOutbound:c,runsAiGeneration:s||Ce(e,zc),throwsBareError:Qc(e),unboundedAiGeneration:n,usesInsertManyUnsafe:r,writesUserTable:i}},nl=(e,t)=>{const s=e.getInitializer();if(!s||!o.isCallExpression(s))return;const n=z(s);if(!n||n.kind!=="query"&&n.kind!=="mutation"&&n.kind!=="action")return;const r=n.receiver?Cc(n.receiver):{usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},i=tl(e,s);return{...i?sl(i):{},...Jc(e),...r,analyzableBody:i!==void 0,exportName:e.getName(),file:t,hasEmailArg:Pc(s,n.receiver),kind:n.kind,visibility:n.visibility}},rl=(e,t)=>{const s=[];for(const n of e.getVariableStatements())if(n.isExported())for(const r of n.getDeclarations()){const i=nl(r,t);i&&s.push(i)}return s},il=(e,t)=>{const s=[];for(const n of m(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...rl(r,x(t,n)))}return s},ol=new Set(["dbRateLimit","rateLimit"]),al=e=>o.isArrowFunction(e)?e.getBody():e,cl=e=>{if(!o.isArrowFunction(e))return;const t=e.getParameters()[0]?.getNameNode();return t!==void 0&&o.isIdentifier(t)?t:void 0},hs=e=>{const t=e.getParent();return o.isPropertyAccessExpression(t)&&t.getExpression()===e&&t.getName()==="args"},vs=(e,t)=>{const s=t.getSymbol();return s===void 0?[]:e.getDescendantsOfKind(l.Identifier).filter(n=>{if(n.getSymbol()!==s)return!1;const r=n.getParent();return!(o.isPropertyAccessExpression(r)&&r.getNameNode()===n)})},ll=(e,t)=>M(e)||t!==void 0&&vs(e,t).some(s=>hs(s)),ul=(e,t)=>t===void 0?U(e):vs(e,t).some(s=>!hs(s)),dl=(e,t)=>{const s=b(e.getExpression());if(s===void 0||!ol.has(s))return;const n=P(Wt(e.getArguments()[2]),"key");if(!n)return;const r=al(n),i=cl(n);if(!(!ll(r,i)||ul(r,i)))return{callee:s,exportName:A(e),file:t,limitName:Vt(e),line:e.getStartLineNumber()}},fl=(e,t)=>F(e,t,dl),gl=new Set(["findFirst","findFirstOrThrow","findMany","findUnique","get"]),pl=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||!gl.has(t.getName()))return;const s=t.getExpression();if(_(s)){const n=e.getArguments()[0];return n&&o.isStringLiteral(n)?n.getLiteralText():""}if(o.isPropertyAccessExpression(s)&&_(s.getExpression()))return s.getName()},ml=e=>{let t=e;for(;o.isCallExpression(t);){const s=t.getExpression();if(!o.isPropertyAccessExpression(s))return;if(s.getName()==="query"&&_(s.getExpression())){const n=t.getArguments()[0];return n&&o.isStringLiteral(n)?n.getLiteralText():""}t=s.getExpression()}},hl=e=>{let t=X(e)??e;for(;o.isAwaitExpression(t);)t=X(t.getExpression())??t.getExpression();return t},xs=(e,t=!1)=>{const s=hl(e);if(o.isIdentifier(s)){if(t)return;const n=ve(s);return n===void 0?void 0:xs(n,!0)}if(o.isCallExpression(s))return pl(s)??ml(s)},vl=e=>{const t=e.getBody();if(!o.isBlock(t))return[t];const s=[];for(const n of e.getDescendantsOfKind(l.ReturnStatement)){const r=n.getFirstAncestor(a=>o.isArrowFunction(a)||o.isFunctionExpression(a)||o.isFunctionDeclaration(a)),i=n.getExpression();r===e&&i!==void 0&&s.push(i)}return s},xl=(e,t)=>{if(!o.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!o.isCallExpression(s))return[];const n=z(s);if(n?.kind!=="query")return[];const r=is(s);if(r===void 0)return[];const i=n.receiver!==void 0&&en(n.receiver,"output"),a=n.receiver!==void 0&&Gt(n.receiver,"use","mask"),c=new Set,u=[];for(const d of vl(r)){const g=xs(d);g===void 0||c.has(g)||(c.add(g),u.push({exportName:e.getName(),file:t,line:d.getStartLineNumber(),table:g,usesMask:a,usesOutput:i,visibility:n.visibility}))}return u},El=(e,t)=>{const s=[];for(const n of m(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n),i=x(t,n);for(const a of r.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...xl(c,i))}return s},Sl=e=>{if(!e||!o.isObjectLiteralExpression(e))return[];const t=[];for(const s of e.getProperties())(o.isPropertyAssignment(s)||o.isShorthandPropertyAssignment(s)||o.isMethodDeclaration(s)||o.isGetAccessorDeclaration(s))&&t.push(y(s));return t},yl=(e,t)=>{if(!o.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&o.isCallExpression(s)?z(s):void 0;if(!n)return[];const r=[];for(const i of e.getDescendantsOfKind(l.CallExpression)){const a=Ht(i);if(a===void 0)continue;const c=Sl(P(a.options,"with"));c.length!==0&&r.push({exportName:e.getName(),file:t,line:i.getStartLineNumber(),parentTable:a.table,relations:c,visibility:n.visibility})}return r},Al=(e,t)=>{const s=[];for(const n of m(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n),i=x(t,n);for(const a of r.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...yl(c,i))}return s},ge=e=>{if(o.isStringLiteral(e)||o.isNoSubstitutionTemplateLiteral(e))return e.getLiteralText();if(o.isBinaryExpression(e)&&e.getOperatorToken().getKind()===l.PlusToken){const t=ge(e.getLeft()),s=ge(e.getRight());return t!==void 0&&s!==void 0?t+s:void 0}},bl=e=>{let t=e,s=t.getParent();for(;s!==void 0&&o.isBinaryExpression(s)&&s.getOperatorToken().getKind()===l.PlusToken;)t=s,s=t.getParent();return t!==e&&ge(t)!==void 0},Nl=/(?:^|\/)__tests__\//u,Pl=/\.(?:spec|test)$/u,wl=e=>Nl.test(e)||Pl.test(e),Il=e=>{const t=e.getParent();if(t!==void 0){if(o.isVariableDeclaration(t)||o.isPropertyAssignment(t)||o.isPropertySignature(t))return y(t);if(o.isBinaryExpression(t)&&t.getOperatorToken().getKind()===l.EqualsToken)return t.getLeft().getText()}},Tl=(e,t,s)=>Un(e)?!wl(s)&&Bn(Il(t)):!0,Cl=(e,t)=>{const s=[],n=[...e.getDescendantsOfKind(l.BinaryExpression),...e.getDescendantsOfKind(l.StringLiteral),...e.getDescendantsOfKind(l.NoSubstitutionTemplateLiteral)],r=new Set;for(const i of n){if(bl(i))continue;const a=ge(i);if(a===void 0)continue;const c=zn(a);if(c===void 0||!Tl(c,i,t))continue;const u=i.getStartLineNumber(),d=`${String(u)}:${c}`;r.has(d)||(r.add(d),s.push({file:t,kind:c,line:u,preview:$n(a)}))}return s},Fl=(e,t)=>{const s=[];for(const n of m(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Cl(r,x(t,n)))}return s},Ol=(e,t)=>{if(!o.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&o.isCallExpression(s)?z(s):void 0;if(!n)return[];const r=[];for(const i of e.getDescendantsOfKind(l.CallExpression)){const a=Ht(i);if(a===void 0)continue;const c=P(a.options,"includeDeleted");if(c===void 0)continue;const u=o.isTrueLiteral(c),d=!u&&M(c);!u&&!d||r.push({exportName:e.getName(),file:t,fromArgs:d,hardcodedTrue:u,line:i.getStartLineNumber(),table:a.table,visibility:n.visibility})}return r},Rl=(e,t)=>{const s=[];for(const n of m(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n),i=x(t,n);for(const a of r.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...Ol(c,i))}return s},Ll=new Set(["query","unsafe"]),Dl=e=>{if(!o.isPropertyAccessExpression(e)||!Ll.has(e.getName()))return!1;const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||t.getName()!=="sql")return!1;const s=t.getExpression();return o.isIdentifier(s)&&s.getText()==="ctx"},kl=e=>o.isBinaryExpression(e)||o.isTemplateExpression(e),Ml=e=>e.getFirstAncestorByKind(l.VariableDeclaration)?.getName()??"<module>",Kl=(e,t)=>{if(!Dl(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!kl(s)))return{exportName:Ml(e),file:t,line:s.getStartLineNumber()}},_l=(e,t)=>F(e,t,Kl),zl=[["convex",["convex","@convex-dev/"]],["supabase",["@supabase/"]],["firebase",["firebase","@firebase/","firebase-admin"]]],$l=e=>{for(const[t,s]of zl)for(const n of s)if(e===n||e.startsWith(n.endsWith("/")?n:`${n}/`))return t},Ul=(e,t)=>{const s=[];for(const n of m(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const i of r.getImportDeclarations()){const a=i.getModuleSpecifierValue(),c=$l(a);c!==void 0&&s.push({file:x(t,n),line:i.getStartLineNumber(),moduleSpecifier:a,platform:c})}}return s},Bl=new Set(["createMultipartUpload","delete","download","generateUploadUrl","get","getMetadata","getPresignedUrl","getSignedUrl","getUrl","head","put","resumeMultipartUpload","store","upload"]),ql=(e,t,s=[])=>{const n=new Map(s.map(i=>[`${i.filePath}:${i.exportName}`,i.visibility]));return Ee(e,t,{argIndex:0,matchReceiver:i=>i==="ctx.storage"||i.startsWith("ctx.storage."),methods:Bl,requireUnmodifiedReach:!0}).map(i=>{const a=n.get(`${i.file}:${i.exportName}`);return a===void 0?i:{...i,visibility:a}})},jl=new Map([["generateUploadUrl",1],["getPresignedUrl",1],["getSignedUrl",1],["store",2],["upload",2]]),Vl=e=>e&&o.isNumericLiteral(e)?Number(e.getText()):void 0,Wl=e=>{if(e===void 0)return{analyzable:!0,presentKeys:[]};if(!o.isObjectLiteralExpression(e))return{analyzable:!1,presentKeys:[]};const t=[];let s,n=!1;for(const r of e.getProperties()){if(o.isSpreadAssignment(r)){n=!0;continue}if(o.isPropertyAssignment(r)){const i=y(r);t.push(i),i==="expiresInSeconds"&&(s=Vl(r.getInitializer()));continue}(o.isShorthandPropertyAssignment(r)||o.isMethodDeclaration(r))&&t.push(y(r))}return{analyzable:!n,expiresInSeconds:s,presentKeys:t}},Hl=e=>{if(!o.isPropertyAccessExpression(e))return;const t=e.getName(),s=jl.get(t);if(s===void 0)return;const n=e.getExpression().getText();return n==="ctx.storage"||n.startsWith("ctx.storage.")?{method:t,optionsIndex:s}:void 0},Gl=(e,t)=>{const s=Hl(e.getExpression());if(s!==void 0)return{exportName:A(e),file:t,line:e.getStartLineNumber(),method:s.method,...Wl(e.getArguments()[s.optionsIndex])}},Yl=(e,t)=>F(e,t,Gl),Ql=(e,t)=>{const s=on(t.target);return{...s===void 0?{}:{platform:s},analytics:e.analytics||t.dependencies.has("@lunora/bindings"),auth:t.dependencies.has("@lunora/auth"),containers:e.container||t.containerCount>0||t.dependencies.has("@lunora/container"),flags:e.flags||t.dependencies.has("@lunora/flags"),kv:e.kv||t.dependencies.has("@lunora/bindings"),mail:e.mail||t.dependencies.has("@lunora/mail"),notifications:e.notify||t.dependencies.has("@lunora/notify"),payments:e.payments||t.hasPaymentTables,queues:t.queueCount>0||t.dependencies.has("@lunora/queue"),scheduler:e.scheduler||t.cronCount>0||t.dependencies.has("@lunora/scheduler"),storage:e.storage||t.storageRuleCount>0||t.storageColumnCount>0||t.dependencies.has("@lunora/storage"),vectors:t.vectorStoreSupported&&t.vectorIndexCount>0,workflows:e.workflows||t.workflowCount>0||t.dependencies.has("@lunora/workflow")}},Xl=(e,t,s)=>({cacheKey:`procedure_arguments_unreadable:${e}:${t}`,categories:["SCHEMA"],description:"Codegen reads an argument record statically. One built at runtime — a factory call, or a property off a value it cannot follow — has no literal to read, so the generated `FunctionReference` carries only the arguments it could see while the runtime validator still enforces all of them.",detail:`\`${t}\` in \`${e}\` (line ${s.toString()}) declares arguments codegen could not read, so its generated type is missing some of them.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:t,filePath:e,line:s},name:"procedure_arguments_unreadable",remediation:`Declare the arguments as an object literal, or as a \`const\` object literal the chain names — \`const ${t}Args = { … };\` then \`.input(${t}Args)\`. Both resolve; a record returned by a call does not.`,title:"Procedure arguments are missing from the generated type"}),Zl=(e,t)=>{if(t===void 0){const s=e.getArguments()[0];if(s===void 0||!o.isObjectLiteralExpression(s)||C(s,"args")===void 0)return!1}return ze(e,t).opaque},Jl=(e,t)=>{const s=[],n=(r,i)=>{const a=r.getInitializer();if(a===void 0||!o.isCallExpression(a))return;const c=z(a);c!==void 0&&Zl(a,c.receiver)&&s.push(Xl(t,i,a.getStartLineNumber()))};for(const r of e.getVariableStatements().filter(i=>i.isExported()))for(const i of r.getDeclarations())n(i,i.getName());return s},eu=(e,t)=>{const s=[];for(const n of m(t)){const r=e.getSourceFile(n);r!==void 0&&s.push(...Jl(r,x(t,n)))}return s.toSorted((n,r)=>n.cacheKey.localeCompare(r.cacheKey))},tu=new Map([["AgentDefinition",{call:"defineAgent({ … })",file:"agents"}],["ContainerDefinition",{call:"defineContainer({ … })",file:"containers"}],["QueueDefinition",{call:"defineQueue({ … })",file:"queues",note:"A dropped queue has no caller to fail — its consumer is simply never wired."}],["RegisteredAction",{call:"action.input({ … }).action(handler)"}],["RegisteredLifecycleHook",{call:"onConnect(handler)",note:"Substitute the hook you called: `onConnect`, `onDisconnect` and `onShardInit` share one type, so codegen cannot tell which you wrote. A dropped hook has no caller to fail — it silently never fires."}],["RegisteredMigration",{call:"defineMigration({ … })",note:"A dropped migration never runs, so `lunora migrate up` reports nothing to do."}],["RegisteredMutation",{call:"mutation.input({ … }).mutation(handler)"}],["RegisteredMutator",{call:"defineMutator({ … })",file:"mutators"}],["RegisteredQuery",{call:"query.input({ … }).query(handler)"}],["RegisteredReactor",{call:"onQueryChange(select, handler)",note:"A dropped reactor has no caller to fail — it silently never runs."}],["RegisteredShape",{call:"defineShape({ … })",file:"shapes"}],["RegisteredStream",{call:"query.input({ … }).stream(handler)"}],["RegisteredWhisperAuthorizer",{call:"onWhisper(handler)",note:"A dropped authorizer has no caller to fail — the whisper topics it was meant to gate silently stay open to every socket on the shard."}],["SubscriptionDefinition",{call:"defineSubscription(topic, { … })",file:"queues",note:"A dropped subscription is never published to — its topic's messages simply never reach it."}],["WorkflowDefinition",{call:"defineWorkflow({ … })",file:"workflows"}]]),Se=({byName:e,byPath:t},s,n)=>t.has(`${s}:${n}`)||e.has(n),Es=e=>!e.isAny(),Ue=e=>{const t=e.getType();if(!Es(t))return;const s=t.getAliasSymbol()?.getName()??t.getSymbol()?.getName(),n=s===void 0?void 0:tu.get(s);return n===void 0||s===void 0?void 0:{...n,typeName:s}},Ss=e=>{const t=e.getInitializer();return t===void 0?!1:o.isCallExpression(t)||o.isIdentifier(t)||o.isPropertyAccessExpression(t)},ys={cause:"codegen recognises a registration only when the initializer is the registering call itself, and this one comes from a factory or an alias",remediation:"A factory that returns a registration cannot be read statically — inline it, or export what the factory builds."},su=e=>({cause:`codegen reads this kind of registration only from \`lunora/${e}.ts\`, and this is a different module`,remediation:`Move it into \`lunora/${e}.ts\` — the declaration itself is fine.`}),nu={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."},Be=(e,t,s,n,r)=>{const{call:i,file:a,note:c,typeName:u}=s,d=a!==void 0&&e!==a?a:void 0,g=d===void 0?r:su(d),h=c===void 0?g.remediation:`${c} ${g.remediation}`;return{cacheKey:`procedure_not_registered:${e}:${t}`,categories:["SCHEMA"],description:"Codegen registers an export only when the declaration carries `export` and its initializer is literally the registering call. Written any other way it exists at runtime but never reaches the generated output — `_generated/api.ts` for a procedure, the lifecycle manifest for a hook or reactor — so a caller cannot address it and a hook never fires.",detail:`\`${t}\` in \`${e}\` (line ${n.toString()}) has type \`${u}\` but was not registered — ${g.cause}.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:t,filePath:e,line:n,typeName:u},name:"procedure_not_registered",remediation:d===void 0?`Assign the registration directly: \`export const ${t} = ${i};\`. ${h}`:h,title:"Procedure exists at runtime but is missing from the generated API"}},ru=(e,t,s)=>{const n=[];for(const r of e.getVariableStatements().filter(i=>i.isExported()))for(const i of r.getDeclarations()){const a=i.getName();if(Se(s,t,a)||!Ss(i))continue;const c=Ue(i);c!==void 0&&n.push(Be(t,a,c,i.getStartLineNumber(),ys))}return n},iu=(e,t,s)=>{if(Se(s,t,"default"))return[];const n=[];for(const r of e.getExportAssignments().filter(i=>!i.isExportEquals())){const i=Ue(r.getExpression());i!==void 0&&n.push(Be(t,"default",i,r.getStartLineNumber(),ys))}return n},ou=(e,t,s)=>{const n=[];for(const r of e.getExportDeclarations().filter(i=>i.getModuleSpecifier()===void 0))for(const i of r.getNamedExports()){const a=i.getAliasNode()?.getText()??i.getName();if(Se(s,t,a))continue;const c=i.getLocalTargetDeclarations().find(d=>o.isVariableDeclaration(d));if(c===void 0||!Ss(c))continue;const u=Ue(c);u!==void 0&&n.push(Be(t,a,u,i.getStartLineNumber(),nu))}return n},au=(e,t,s)=>[...ru(e,t,s),...iu(e,t,s),...ou(e,t,s)],cu=(e,t,s)=>e.getVariableStatements().filter(n=>n.isExported()).flatMap(n=>n.getDeclarations()).filter(n=>Se(s,t,n.getName())).filter(n=>{const r=n.getInitializer();return r!==void 0&&o.isCallExpression(r)&&o.isPropertyAccessExpression(r.getExpression())}).map(n=>({declaration:n,exportName:n.getName(),relativePath:t})),lu=({exportName:e,relativePath:t})=>({cacheKey:"procedure_type_check_unavailable",categories:["SCHEMA"],description:"Codegen cross-checks every export in `lunora/` against its TYPE to catch a procedure the syntactic scan dropped — a factory-assigned export, an alias, a separate `export { … }`. That check needs the type checker to resolve `@lunora/server`; when it cannot, the check reports nothing regardless of what the code does.",detail:`Type resolution for \`lunora/\` is unavailable — the registered procedure \`${e}\` in \`${t}\` types as \`any\`, as does every other one — so codegen cannot tell you when an export is dropped from \`_generated/api.ts\`. A dropped procedure will surface as \`Property '<name>' does not exist\` at its call site instead.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:e,filePath:t},name:"procedure_type_check_unavailable",remediation:`Check what codegen sees: \`${e}\` should have a procedure type, not \`any\`. It needs a \`tsconfig.json\` at or above \`lunora/\` — the one codegen finds walking up from there, which is not necessarily the one your editor uses — resolving \`lunorash\` / \`@lunora/server\` to declarations that exist on disk (a workspace dependency has to be built first).`,title:"Codegen cannot type-check `lunora/`, so dropped procedures go unreported"}),uu=(e,t,s)=>{const n=[],r=[];for(const a of m(t)){const c=e.getSourceFile(a);if(c===void 0)continue;const u=x(t,a);n.push(...au(c,u,s)),r.push(...cu(c,u,s))}const[i]=r;return i!==void 0&&r.every(({declaration:a})=>!Es(a.getType()))&&n.push(lu(i)),n.toSorted((a,c)=>a.cacheKey.localeCompare(c.cacheKey))},du=new Set(["when","where"]),Fe=new Set(["definePolicy","defineShape"]),fu=e=>{if(!o.isCallExpression(e))return;const t=e.getExpression();if(o.isPropertyAccessExpression(t)){const n=t.getName();return Fe.has(n)?n:void 0}if(!o.isIdentifier(t))return;for(const n of t.getSymbol()?.getDeclarations()??[])if(o.isImportSpecifier(n)){const r=n.getNameNode().getText();return Fe.has(r)?r:void 0}const s=t.getText();return Fe.has(s)?s:void 0},gu=e=>o.isObjectLiteralExpression(e)&&e.getProperties().length===0,As=e=>{if(e!==void 0){if(o.isReturnStatement(e)&&e.getExpression()===void 0||e.getKind()===l.UndefinedKeyword||e.getText()==="undefined")return"undefined";if(gu(e))return"empty-object";if(o.isParenthesizedExpression(e))return As(e.getExpression())}},qe=e=>e.getAncestors().find(t=>o.isArrowFunction(t)||o.isFunctionExpression(t)||o.isFunctionDeclaration(t)),pu=e=>e.getDescendantsOfKind(l.ReturnStatement).filter(t=>qe(t)===e),bs=e=>e.getDescendantsOfKind(l.ConditionalExpression).filter(t=>qe(t)===e),mu=e=>{const t=pu(e);return t.length>1?!0:t.some(s=>s.getFirstAncestorByKind(l.IfStatement)!==void 0)||bs(e).length>0},hu=e=>e.getDescendantsOfKind(l.IfStatement).filter(t=>qe(t)===e),ke=e=>e.getKind()===l.NullKeyword||e.getKind()===l.FalseKeyword||o.isIdentifier(e)&&e.getText()==="undefined"?!0:o.isNumericLiteral(e)?e.getLiteralValue()===0:o.isStringLiteral(e)&&e.getLiteralValue()==="",vu=(e,t)=>ke(e)||ke(t),xu=new Map([[l.EqualsEqualsEqualsToken,"positive"],[l.EqualsEqualsToken,"positive"],[l.ExclamationEqualsEqualsToken,"negative"],[l.ExclamationEqualsToken,"negative"]]),Kt=e=>!ke(e)&&(o.isLiteralExpression(e)||e.getKind()===l.TrueKeyword),Eu=(e,t,s)=>{const n=xu.get(e);if(n!==void 0)return vu(t,s)?n==="positive"?"negative":"positive":Kt(t)||Kt(s)?void 0:n},Y=e=>{if(o.isParenthesizedExpression(e))return Y(e.getExpression());if(o.isPrefixUnaryExpression(e)&&e.getOperatorToken()===l.ExclamationToken)return"negative";if(o.isBinaryExpression(e)){const t=e.getOperatorToken().getKind(),s=Eu(t,e.getLeft(),e.getRight());if(s!==void 0)return s;if(t===l.AmpersandAmpersandToken||t===l.BarBarToken){const n=Y(e.getLeft()),r=Y(e.getRight());return n===r?n:"indeterminate"}}return o.isIdentifier(e)||o.isPropertyAccessExpression(e)||o.isElementAccessExpression(e)||o.isCallExpression(e)?"positive":"indeterminate"},_t=e=>{if(e!==void 0){if(o.isReturnStatement(e))return e;if(o.isBlock(e)){const t=e.getStatements().at(-1);return t!==void 0&&o.isReturnStatement(t)?t:void 0}}},Su=e=>{if(e.getElseStatement()!==void 0)return;const t=e.getNextSiblingIfKind(l.ReturnStatement);return t!==void 0&&t.getNextSibling()===void 0?t:void 0},yu=e=>o.isReturnStatement(e)?e.getExpression()??e:e,Au=e=>{const t=[];for(const s of bs(e)){const n=Y(s.getCondition());n==="positive"?t.push(s.getWhenFalse()):n==="negative"&&t.push(s.getWhenTrue())}for(const s of hu(e)){const n=Y(s.getExpression());if(n==="indeterminate")continue;const r=n==="negative"?_t(s.getThenStatement()):_t(s.getElseStatement())??Su(s);r!==void 0&&t.push(yu(r))}return t},bu=e=>{for(const t of e.getAncestors())if(o.isVariableDeclaration(t)){const s=t.getNameNode();if(o.isIdentifier(s))return s.getText()}return"<anonymous>"},Nu=(e,t,s)=>{if(!o.isCallExpression(e))return[];const[n]=e.getArguments();if(!n||!o.isObjectLiteralExpression(n))return[];const r=[];for(const i of n.getProperties()){if(!o.isPropertyAssignment(i)||!du.has(y(i)))continue;const a=i.getInitializer();if(!(!a||!(o.isArrowFunction(a)||o.isFunctionExpression(a)))&&mu(a))for(const c of Au(a)){const u=As(c);u!==void 0&&r.push({exportName:bu(e),file:s,form:u,key:y(i),line:c.getStartLineNumber(),owner:t})}}return r},Pu=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression)){const r=fu(n);r!==void 0&&s.push(...Nu(n,r,t))}return s},wu=(e,t)=>{const s=[];for(const n of m(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Pu(r,x(t,n)))}return s},Iu=new Set(["query","upsert","upsertNow"]),Tu=e=>{if(!o.isPropertyAccessExpression(e))return;const t=e.getName();if(Iu.has(t))return e.getExpression().getText()==="ctx.vectors"?t:void 0},Cu=(e,t)=>{const s=Tu(e.getExpression());if(s===void 0)return;const n=e.getArguments()[1];if(!n)return;const r=P(n,"namespace");if(!(!r||!M(r)||U(r)))return{exportName:A(e),file:t,line:e.getStartLineNumber(),method:s}},Fu=(e,t)=>F(e,t,Cu),Ou=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||t.getName()!=="get")return!1;const s=t.getExpression();return o.isPropertyAccessExpression(s)?s.getName()==="workflows":o.isIdentifier(s)&&s.getText()==="workflows"},Ru=e=>{const t=e.getArguments()[0];return t&&o.isStringLiteral(t)?t.getLiteralText():""},Lu=(e,t)=>{const s=[];for(const n of m(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n),i=x(t,n);for(const a of r.getDescendantsOfKind(l.CallExpression)){if(!Ou(a))continue;const c=Ys(a);c!==""&&s.push({exportName:c,file:i,line:a.getStartLineNumber(),workflow:Ru(a)})}}return s},Du=".lunora-schema.json",Me=(e,t)=>{w(e)&&Ut(e,"utf8")===t||Ms(e,t,"utf8")},ku=(e,t)=>{if(t===""){Ks(e,{force:!0});return}Me(e,t)},Mu=e=>{const t=S(e,"package.json");if(w(t))try{const s=JSON.parse(Ut(t,"utf8"));return typeof s.version=="string"&&s.version!==""?s.version:void 0}catch{return}},Ku=()=>{const e=process.env.LUNORA_CODEGEN_TIMING;return e!==void 0&&e!==""},_u=e=>{let t=w(e)?e:ce(e);for(;t&&t!==ce(t);){const s=S(t,"tsconfig.json");if(w(s))return s;t=ce(t)}},zt=e=>e.replaceAll("\\","/"),zu=(e,t,s)=>{if(s&&e.length>0){const i=e.map(a=>`"${a.exportName}"`).join(", ");throw new $("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) (${i}), codegen can't verify none of them replicate a table that policy masks — inline every table and column as literal keys so codegen can verify it, or remove the affected shape(s).`,{status:422})}const n=new Map;for(const i of t.columns){const a=n.get(i.table)??[];a.push(i.column),n.set(i.table,a)}const r=t.columns.length>0;for(const i of e){if(i.table===void 0){if(r)throw new $("MASK_UNSUPPORTED",`defineShape "${i.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 "${i.exportName}"'s \`table\` to a plain string literal so codegen can verify it, or remove the mask(s) on the table it targets.`,{status:422});continue}const a=n.get(i.table);if(a===void 0)continue;const c=a.map(u=>`"${u}"`).join(", ");throw new $("MASK_UNSUPPORTED",`defineShape "${i.exportName}" replicates table "${i.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})}},pe=(e,t,s)=>{const n=e.getSourceFile(t);if(n===void 0){e.createSourceFile(t,s,{overwrite:!0});return}n.getFullText()!==s&&n.replaceWithText(s)},$t=(e,t,s)=>e.getSourceFile(t)?.getFullText()===s,$u=8,Uu=e=>{const{agents:t,apiPath:s,generatedFunctionsPath:n,lunoraDirectory:r,migrations:i,project:a,shapes:c,usesSandbox:u,useUmbrella:d,workflows:g}=e,h=()=>An(()=>{const N=bn(a,r),L=On(a,r);return{functions:N,httpRoutes:Nn(a,r),mutators:L}});let{erased:O,value:{functions:R,httpRoutes:p,mutators:T}}=h();mt([...R,...T].map(N=>N.filePath)),mt(p.filter(N=>N.stream).map(N=>N.filePath),"http-stream");for(let N=1;;N+=1){const L=Zn({agents:t,functions:R,httpRoutes:p,mutators:T,useUmbrella:d,workflows:g}),D=lr({agents:t,functions:R,migrations:i,mutators:T,shapes:c,useUmbrella:d,usesSandbox:u});if(N>=$u||$t(a,s,L)&&$t(a,n,D))return{apiContent:L,erased:O,functions:R,functionsContent:D,httpRoutes:p,mutators:T};pe(a,s,L),pe(a,n,D),{erased:O,value:{functions:R,httpRoutes:p,mutators:T}}=h()}},Bu=e=>{const t=_u(e);return t?new ft({skipAddingFilesFromTsConfig:!1,tsConfigFilePath:t,useInMemoryFileSystem:!1}):new ft({skipAddingFilesFromTsConfig:!0,useInMemoryFileSystem:!1})},Hd=(e,t)=>{const s=m(t),n=S(t,"schema.ts");w(n)&&s.push(n);for(const c of s){const u=e.getSourceFile(c);u===void 0?e.addSourceFileAtPath(c):u.refreshFromFileSystemSync()}const r=new Set(s.map(c=>zt(c))),i=zt(t),a=`${i}/`;for(const c of e.getSourceFiles()){const u=c.getFilePath();(u===i||u.startsWith(a))&&!r.has(u)&&e.removeSourceFile(c)}for(const c of e.getSourceFiles()){const u=c.getFilePath();if(!(u===i||u.startsWith(a)||u.includes("/node_modules/")))try{c.refreshFromFileSystemSync()}catch{e.removeSourceFile(c)}}},Gd=e=>{const t=Ku(),s=t?Ie.now():0,n=S(e.projectRoot,e.lunoraDirectory??"lunora"),r=S(n,"schema.ts");if(!w(r))throw new $("INTERNAL",`schema.ts not found at ${r}`);const i=e.project??Bu(n);mn(Ao);const a=_n(i,r,e.projectRoot),{agents:c,containers:u,crons:d,dataModelContent:g,dependencies:h,entryCronTriggers:O,env:R,featureUsage:p,hasFlags:T,hasNotify:N,identity:L,platformGate:D,queues:v,serverContent:q,storageRulesMetadata:j,topics:te,usesSandbox:se,useUmbrella:K,workflows:k}=Ur({lunoraDirectory:n,project:i,projectRoot:e.projectRoot,schema:a,target:e.target});aa(a,a.jurisdiction===void 0?void 0:ia(i,n));const E=S(n,"_generated"),Ns=S(E,"dataModel.ts"),Ps=S(E,"server.ts"),ws=S(E,"api.ts"),Is=S(E,"functions.ts");pe(i,Ns,g),pe(i,Ps,q);const ne=Tn(i,n),V=qn(i,n),{apiContent:je,erased:Ts,functions:W,functionsContent:Ve,httpRoutes:Cs,mutators:re}=Uu({agents:c,apiPath:ws,generatedFunctionsPath:Is,lunoraDirectory:n,migrations:ne,project:i,shapes:V,useUmbrella:K,usesSandbox:se,workflows:k}),ie=e.lint===!1?void 0:Us({adminRoutes:Yr(i,n),aiRawRuns:Zr(i,n),aiToolSideEffects:ci(i,n),argumentDerivedFetches:di(i,n),argumentValidators:yi(i,n),authApiCalls:hn(i,n),authConfigs:Oi(i,n),browserUrlAccesses:Mi(i,n),configCalls:ji(i,n),containerKeyAccesses:Wi(i,n),containerOverrides:Zi(i,n),containers:u,exportSinks:so(i,n),staleMigrationImports:Ul(i,n),failOpenGuards:ao(i,n),flagReads:vo(i,n),flagSecurityDefaults:yo(i,n),geoIndexUsages:Po(i,n),httpActionGuards:Ko(i,n),httpHeaderWrites:Ho(i,n),hyperdriveCalls:Pn(i,n),identityClaimReads:ea(i,n),imageDeliveryUrlAccesses:sa(i,n),inserts:wn(i,n),kvKeyAccesses:la(i,n,W),mailRecipientAccesses:pa(i,n),maskProcedures:In(i,n),maskStrategies:Aa(i,n),mutatorWrites:Ta(i,n),nondeterministicCalls:Rn(i,n),normalizeIdAuthorizations:ja(i,n),notifyCalls:Dn(i,n),notifyConfig:Ln(i,n),mutators:re,ownerFieldWrites:ec(i,n,W,re),unrestrictedWhereBranches:wu(i,n),paymentWebhooks:cc(i,n),privilegedDispatches:yc(i,n),procedureProtections:il(i,n),queries:pn(i,n),queues:v,r2sqlCalls:kn(i,n),ratelimitKeySelectors:fl(i,n),rawRowReturns:El(i,n),relationLoads:Al(i,n),rlsProcedures:Mn(i,n),schema:a,secretLiterals:Fl(i,n),shapes:V,softDeleteReads:Rl(i,n),sqlInterpolations:_l(i,n),storageKeyAccesses:ql(i,n,W),storageUploads:Yl(i,n),vectorNamespaceAccesses:Fu(i,n),workflowCalls:Lu(i,n),workflows:k,wranglerVariables:e.wranglerVariables}),We=ie===void 0?[]:dr(e.projectRoot,[..._s(ie,{source:"static"}),...uu(i,n,{byName:new Set([...k,...v,...c,...u].map(f=>f.exportName)),byPath:new Set([...W,...re,...V,...ne].map(f=>`${f.filePath}:${f.exportName}`))}),...eu(i,n),...yn(Ts,n)]),Fs=Kn(i,n),He=Ea(i,n);zu(V,He,va(i,n));const Os=T?fo(i,n):[],ye=D.signals.vectorStore!==!1,G=Ql(p,{containerCount:u.length,cronCount:d.length,dependencies:h,hasPaymentTables:nc(a.tables),queueCount:v.length,storageColumnCount:Object.keys(Qt(a)).length,storageRuleCount:j.rules.length,vectorIndexCount:a.vectorIndexes.length,target:Yt(e.projectRoot,e.target),vectorStoreSupported:ye,workflowCount:k.length}),Ge=t?Ie.now():0,Ae=Yn(a,ne.map(f=>f.id)),Ye=an({advisories:We.filter(f=>f.name!=="procedure_type_check_unavailable"),advisorProcedures:ie?.procedureProtections??[],agents:c,containers:u,env:R,flagKeys:Os,hasAccessFacade:p.access,hasAi:p.ai,hasAnalytics:p.analytics,hasBrowser:p.browser,hasFlags:T,hasHyperdrive:p.hyperdrive,hasImages:p.images,hasKv:p.kv,hasNotify:N,hasPayments:p.payments,hasPipelines:p.pipelines,hasR2sql:p.r2sql,hasVectors:ye,hasX402:p.x402,maskMetadata:He,mutators:re,queues:v,rlsMetadata:Fs,schema:a,schemaSnapshot:Ae,shapes:V,storageRules:j,studioFeatures:G,topics:te,useUmbrella:K,workflows:k}),Qe=Qn(V,h.has("@lunora/db"),K),Xe=Jn(u,a.jurisdiction),Ze=er(k),Je=tr(c),et=sr(v),tt=nr(d),Rs=rr(G.scheduler),Ls=ir(a.tables,K),st=or(a.vectorIndexes),oe=cr(a,K),nt=Xn(h.has("@lunora/seed")),ae=e.apiSpec??"openapi",be=ae==="openapi"||ae==="both",Ne=ae==="openrpc"||ae==="both",rt=jn({emailAgents:c.filter(f=>f.onEmail===!0).map(f=>({className:f.className,exportName:f.exportName})),hasAccess:h.has("@lunora/cloudflare-access"),hasAi:p.ai,hasAnalytics:p.analytics,hasAuth:h.has("@lunora/auth"),hasBrowser:p.browser,hasFramework:h.has("@lunora/astro")||h.has("@lunora/svelte")||h.has("@lunora/vue")||w(S(e.projectRoot,"src","worker.ts")),hasGlobal:a.tables.some(f=>Bt(f)),hasHyperdrive:p.hyperdrive,hasHyperdriveGlobal:a.tables.some(f=>qt(f)),hasImages:p.images,hasKv:p.kv,hasKvIntrospector:G.kv,hasNotify:N,hasPayments:p.payments,hasR2sql:p.r2sql,hasQueue:v.some(f=>f.mode==="push"),hasScheduler:G.scheduler,hasSourcedTables:a.tables.some(f=>f.externalSource!==void 0),hasStorage:G.storage,hasVectors:ye,hasWorkflow:k.length>0,hasX402:p.x402,identity:L,jurisdiction:a.jurisdiction,jurisdictionPinsAuth:a.jurisdictionPinsAuth===!0,tables:a.tables.map(f=>({name:f.name,shardMode:f.shardMode})),useUmbrella:K,vectorIndexCount:a.vectorIndexes.length,voiceAgents:c.filter(f=>f.voice===!0&&f.voiceBindingName!==void 0).map(f=>({bindingName:f.voiceBindingName,exportName:f.exportName})),wantsOpenApi:be,wantsOpenRpc:Ne}),it=Mu(e.projectRoot),ot=Vn({functions:W,httpRoutes:Cs,version:it}),at=Hn({functions:W,version:it}),ct=`${JSON.stringify(ot,void 0,2)}
|
|
8
|
-
`,lt=`${JSON.stringify(at,void 0,2)}
|
|
9
|
-
`,ut=Wn(ot),dt=Gn(at),Pe=S(n,Du),Ds=w(Pe),we=[];if(!e.dryRun){w(E)||ks(E,{recursive:!0});const f=(B,H)=>{Me(S(E,B),H),we.push(B)},I=(B,H)=>{ku(S(E,B),H),H!==""&&we.push(B)};f("app.ts",rt),f("dataModel.ts",g),f("api.ts",je),f("server.ts",q),f("functions.ts",Ve),f("shard.ts",Ye),f("crons.ts",tt),f("vectors.ts",st),f("drizzle.global.ts",oe.global),f("drizzle.shard.ts",oe.shard),I("containers.ts",Xe),I("workflows.ts",Ze),I("agents.ts",Je),I("queues.ts",et),I("scheduler.ts",Rs),I("shardRegistry.ts",Ls),I("seed.ts",nt),I("collections.ts",Qe),I("openapi.json",be?ct:""),I("openapi.ts",be?ut:""),I("openrpc.json",Ne?lt:""),I("openrpc.ts",Ne?dt:""),(!Ds||e.updateSchemaBaseline===!0)&&Me(Pe,$s(Ae))}if(t){const f=Ie.now(),I=Math.round(f-s),B=Math.round(Ge-s),H=Math.round(f-Ge);console.error(`@lunora/codegen: codegen took ${I.toString()}ms (discovery ${B.toString()}ms, emit ${H.toString()}ms)`)}return{advisories:We,advisorContext:ie,agents:c,containers:u,cronTriggers:[...new Set([...ar(d),...O])],generated:{agents:Je,api:je,app:rt,collections:Qe,containers:Xe,crons:tt,dataModel:g,drizzleGlobal:oe.global,drizzleShard:oe.shard,functions:Ve,openApi:ct,openApiModule:ut,openRpc:lt,openRpcModule:dt,queues:et,seed:nt,server:q,shard:Ye,vectors:st,workflows:Ze},migrations:ne,outputDirectory:E,platformDiagnostics:D.diagnostics,queues:v,schemaSnapshot:Ae,schemaSnapshotPath:Pe,workflows:k,writtenFiles:we}};export{Du as SCHEMA_SNAPSHOT_FILENAME,Bu as createCodegenProject,_u as findTsconfig,Hd as refreshCodegenProject,Gd as runCodegen};
|
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
import{r as S}from"./json-data-Chfs2Cz5.mjs";import{s as p}from"./paths-C-9fwEgQ.mjs";import{LUNORA_ERROR_CODES as O,objectSchema as h,validatorIrToJsonSchema as u}from"./LUNORA_ERROR_CODES-C2s0xWQD.mjs";import{G as E}from"./shared-DjUziztz.mjs";const A="/_lunora/rest",P=["authorization","cf-access-jwt-assertion","cookie","payment-signature","x-payment"],f=["x-d1-bookmark","x-lunora-shard-key"],T=e=>[...P,...(e.credentialHeaders??[]).map(t=>t.toLowerCase())],g=e=>Number.isFinite(e)?Math.max(0,Math.floor(e)):0,y=(...e)=>{const t=[];for(const r of e)for(const o of r?.split(",")??[]){const s=o.trim().toLowerCase();s!==""&&!t.includes(s)&&t.push(s)}return t.length===0?void 0:t.join(", ")},b=(e,t)=>{const r=[t,`max-age=${String(g(e.maxAge))}`];return e.staleWhileRevalidate!==void 0&&r.push(`stale-while-revalidate=${String(g(e.staleWhileRevalidate))}`),r.join(", ")},x=e=>e.scope==="public"?y(e.vary,...T(e),...f):y(e.vary,...f),k=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)}},N=e=>{const t=k(e);if(t!==void 0)return`${A}/${t.namespace}/${t.name}`},q=e=>e==="query"?"GET":"POST",m="#/components/responses/LunoraError",v=/:([A-Za-z_$][\w$]*)/gu,_=e=>[...e.matchAll(v)].map(t=>t[1]),j=e=>e.replaceAll(v,"{$1}"),l=e=>e.kind==="optional"?e.inner??e:e,C=e=>{const t=new Set(_(e.path)),r=[];for(const[o,s]of Object.entries(e.searchParams)){const c=l(s);r.push({description:`Query parameter \`${o}\``,in:"query",name:o,required:s.kind!=="optional",schema:u(c)})}for(const[o,s]of Object.entries(e.params)){const c=l(s);r.push({description:`Path parameter \`${o}\``,in:t.has(o)?"path":"query",name:o,required:t.has(o)?!0:s.kind!=="optional",schema:u(c)})}return r},$=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."},w=e=>{const t=p(e.filePath),r=C(e),o={description:`${e.stream?"Streaming (SSE) ":""}HTTP route handler \`${e.exportName}\` (${e.method} ${e.path}).`,operationId:`${e.method.toLowerCase()}_${p(e.path)}`,responses:{200:$(e.output),204:{description:"No content (handler returned `undefined`)."},default:{$ref:m}},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:h(e.body)}},required:!0}),e.stream&&(o["x-lunora-stream"]="text/event-stream"),o},D=e=>{const t=p(e.filePath),r=`${t}:${e.exportName}`,o={additionalProperties:!1,properties:{args:h(e.args),functionPath:{const:r,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}\` \`${r}\` over the Lunora RPC envelope (POST /_lunora/rpc).`,operationId:r,requestBody:{content:{"application/json":{schema:o}},required:!0},responses:{200:$(e.output),default:{$ref:m}},summary:`${e.kind}: ${r}`,tags:[t],"x-lunora-function-kind":e.kind},pathKey:`/_lunora/rpc#${r}`}},L=(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:b(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 s=x(r);return s!==void 0&&(o.Vary={description:"Request headers this response varies by. The endpoint's own negotiated headers are merged in at runtime.",schema:{example:s,type:"string"}}),{headers:o}},I=e=>{const t=p(e.filePath),r=`${t}:${e.exportName}`,o=N(r);if(o===void 0)return;const s=q(e.kind),c=s==="GET",d={description:`Public REST endpoint for the \`${e.kind}\` \`${r}\` (opt-in via \`.expose({ rest: true })\`). Routed through the procedure, so auth / RLS / validators are enforced.`,operationId:`rest_${p(o)}`,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).",...L(e.expose?.cache,c?"get":"post")},default:{$ref:m}},summary:`${s} ${o}`,tags:[t],"x-lunora-function-kind":e.kind};if(c){const n=Object.entries(e.args).map(([a,i])=>{const R=l(i);return{description:`Argument \`${a}\` (JSON-encoded for non-string values).`,in:"query",name:a,required:i.kind!=="optional",schema:u(R)}});return n.length>0&&(d.parameters=n),{method:"get",operation:d,path:o}}return d.requestBody={content:{"application/json":{schema:h(e.args)}},required:Object.keys(e.args).length>0},{method:"post",operation:d,path:o}},F=e=>{const t=e.version??"0.0.0",r={},o=new Set;for(const n of e.httpRoutes){const a=j(n.path),i=r[a]??{};i[n.method.toLowerCase()]=w(n),r[a]=i,o.add(p(n.filePath))}const s=e.functions.filter(n=>n.visibility!=="internal"&&n.kind!=="stream");for(const n of s){const{operation:a,pathKey:i}=D(n);r[i]={post:a},o.add(p(n.filePath))}for(const n of s){if(n.expose?.rest!==!0)continue;const a=I(n);if(a===void 0)continue;const i=r[a.path]??{};i[a.method]=a.operation,r[a.path]=i}const c=[...o].toSorted((n,a)=>n.localeCompare(a)).map(n=>({description:`Operations declared in \`lunora/${n}\`.`,name:n}));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:O,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:c}},B=e=>`${JSON.stringify(F(e),void 0,2)}
|
|
2
|
-
`,G=e=>`${E}export const openApiSpec = ${S(e,"Record<string, unknown>")};
|
|
3
|
-
`;export{F as buildOpenApiDocument,B as emitOpenApi,G as emitOpenApiModule};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{w as a}from"./classify-procedure-call-BztLe76A.mjs";const l=s=>a(s,"use","rls");export{l as r};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{d as o}from"./context-property-calls-CjDzLU8p.mjs";const t=(r,e)=>o(r,e,"sql");export{t as default};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import"./listLunoraSourceFiles-DP-5e-RE.mjs";import"./classify-procedure-call-BztLe76A.mjs";import{d as p}from"./index-BoaHhVtM.mjs";export{p as default};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{d as a}from"./queries-B-f4jO-x.mjs";import"./listLunoraSourceFiles-DP-5e-RE.mjs";export{a as default};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{d as r}from"./context-property-calls-CjDzLU8p.mjs";const t=(s,o)=>r(s,o,"r2sql");export{t as default};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as M}from"@lunora/errors";import{Node as i,SyntaxKind as R}from"ts-morph";import{diagnosticAt as d}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{createRequire as C}from"node:module";import{join as F}from"node:path";import{findObjectProperty as u,propertyKeyName as I}from"./listLunoraSourceFiles-DP-5e-RE.mjs";import{r as B,p as V}from"./parse-validator-C94Yiabo.mjs";const q=(e,n)=>`table "${e}" is .global() and declares vector index "${n}". Vector sync runs on the shard write path, which a global (D1/Hyperdrive) table's writes never take — the index would stay empty. Drop .global(), or keep the index yourself with ctx.vectors.upsert/deleteByIds.`,J=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}},U=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}:{}}),m=e=>{const n=e?._meta??{},t=e?.kind??"unknown",s={column:U(n.column),kind:t};switch(t){case"array":case"optional":{s.inner=m(n.inner);break}case"from":break;case"id":{s.tableName=n.tableName;break}case"literal":{s.literalValue=J(n.value);break}case"object":{const r=n.shape??{};s.shape=Object.fromEntries(Object.entries(r).map(([a,o])=>[a,m(o)]));break}case"record":{s.valueType=m(n.valueValidator),n.keyValidator!==void 0&&(s.keyType=m(n.keyValidator));break}case"storage":{typeof n.bucket=="string"&&(s.bucket=n.bucket);break}case"union":{const r=n.members??[];s.members=r.map(a=>m(a));break}}return s},K=e=>e?.kind==="global"?"global":e?.kind==="shardBy"&&typeof e.field=="string"?{field:e.field,kind:"shardBy"}:"root",Z=(e,n)=>{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 "${n}" declares ${t.join(" + ")}, which are not yet introspected from a node_modules extension — they will be absent from the generated types.`)},G=(e,n)=>{const t=e.shape??{},s=(e.indexes??[]).map(r=>({fields:r.fields,name:r.name,...r.unique?{unique:!0}:{}}));return Z(e,n),{...e.isExternallyManaged?{externallyManaged:!0}:{},geoIndexes:[],indexes:s,name:n,rankIndexes:[],relations:[],searchIndexes:(e.searchIndexes??[]).map(r=>({field:r.field,...r.filterFields?{filterFields:r.filterFields}:{},...r.language===void 0?{}:{language:r.language},...r.staged===void 0?{}:{staged:r.staged},...r.strategy===void 0?{}:{strategy:r.strategy},name:r.name})),shape:Object.fromEntries(Object.entries(t).map(([r,a])=>[r,m(a)])),shardMode:K(e.shardMode),vectorIndexes:[]}},W=e=>{const{key:n,tables:t}=e;if(typeof n!="string"||typeof t!="object"||t===null)return;const s=Object.entries(t).map(([o,l])=>G(l,o)),r=e.vectorIndexes??{},a=Object.entries(r??{}).map(([o,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:o,table:l.table??""}));return{bareTables:s,bareVectorIndexes:a,key:n}},X=e=>{if(i.isIdentifier(e))return e.getText();if(i.isPropertyAccessExpression(e)){const n=e.getExpression();return i.isIdentifier(n)?n.getText():void 0}},H=e=>{const n=X(e);if(n===void 0)return;const t=i.isPropertyAccessExpression(e)?e.getName():void 0,s=t===void 0?[]:[t];for(const r of e.getSourceFile().getImportDeclarations()){const a=r.getModuleSpecifierValue();for(const o of r.getNamedImports())if((o.getAliasNode()?.getText()??o.getName())===n)return{importedName:o.getName(),moduleSpecifier:a,propertyPath:s};if(r.getDefaultImport()?.getText()===n)return{importedName:"default",moduleSpecifier:a,propertyPath:s};if(r.getNamespaceImport()?.getText()===n&&t!==void 0)return{importedName:t,moduleSpecifier:a,propertyPath:[]}}},Q=(e,n)=>{let t=e[n.importedName];for(const s of n.propertyPath){if(typeof t!="object"||t===null)return;t=t[s]}return t},Y=(e,n)=>{const t=H(e);if(t)try{const s=C(F(n,"noop.cjs")),r=s.resolve(t.moduleSpecifier),a=s(r),o=Q(a,t);return typeof o!="object"||o===null?void 0:W(o)}catch{return}},ee=new Set(["cosine","dot-product","euclidean"]),b=(e,n)=>{const t=u(e,n);if(t&&i.isPropertyAssignment(t))return t.getInitializer()},f=(e,n)=>{const t=b(e,n);if(t&&i.isStringLiteral(t))return t.getLiteralText()},x=(e,n)=>{const t=b(e,n);if(t&&i.isNumericLiteral(t))return Number(t.getLiteralText())},L=(e,n)=>{const t=b(e,n);if(t&&(i.isTrueLiteral(t)||i.isFalseLiteral(t)))return t.getLiteralValue()},h=(e,n)=>{const t=b(e,n);if(t&&i.isArrayLiteralExpression(t))return t.getElements().filter(s=>i.isStringLiteral(s)).map(s=>s.getLiteralText())},O=e=>e&&ee.has(e)?e:void 0,y=e=>e&&i.isStringLiteral(e)?e.getLiteralText():"_unnamed_",te=(e,n)=>{const t=h(e,n);return t!==void 0&&t.length>0?t:void 0},A=(e,n,t,s,r)=>{let a=e;for(;;){const o=a.getParent();if(!o||!i.isPropertyAccessExpression(o))break;const l=o.getParent();if(!l||!i.isCallExpression(l))break;if(o.getName()===n){const c=l.getArguments()[0];if(!c||!i.isStringLiteral(c))throw d(l,`\`.${n}(...)\` expects a string literal (${r})`);const g=c.getLiteralText();if(!s.has(g))throw d(c,`unknown ${t} ${JSON.stringify(g)} — expected ${r}`);return g}a=l}},ne=e=>`table "${e}" is both .global() and .ttl(). The TTL sweep is a shard's alarm deleting from that shard's own SQLite, and a global (D1/Hyperdrive) table's rows live outside every shard — so expired rows would never be deleted. Drop .ttl() and expire the rows from a cron, or keep the table shard-local.`,re=/^(?:sqlite_|_cf_|__)/u,se=/__(?:agg|rank|geo|fts)_/u,ie=e=>re.test(e)||se.test(e),oe=new Set(["cascade","restrict","set null"]),ae=new Set(["aggregate","asId","cdcChangedTables","count","delete","deleteAll","deleteMany","deleteWhere","findFirst","findFirstOrThrow","findMany","get","groupBy","insert","insertMany","insertManyUnsafe","lookupById","normalizeId","patch","patchMany","patchWhere","query","rank","rankBefore","rankPage","rankPageRows","related","relationEdges","replace","restore","system","wipeShard"]),le=new Set(["arguments","await","break","case","catch","class","const","continue","debugger","default","delete","do","else","enum","eval","export","extends","false","finally","for","function","if","implements","import","in","instanceof","interface","let","new","null","package","private","protected","public","return","static","super","switch","this","throw","true","try","typeof","var","void","while","with","yield"]),N=/^[A-Za-z_$][\w$]*$/u,w=(e,n)=>{if(ae.has(e))throw d(n,`table name "${e}" is reserved — the generated shard binds each table's facade onto the same object that carries \`ctx.db\`'s own members, so this table would overwrite \`ctx.db.${e}\` and every use of it would break. Rename the table.`);if(le.has(e))throw d(n,`table name "${e}" is a reserved JavaScript word — codegen interpolates table names into a bare \`const ${e} = sqliteTable(...)\` binding in the generated Drizzle module, which is a syntax error for a keyword. Rename the table.`);if(!N.test(e))throw d(n,`table name ${JSON.stringify(e)} 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.`);if(ie(e))throw d(n,`table name ${JSON.stringify(e)} is reserved for framework tables — a leading \`__\` and the \`__agg_\`/\`__rank_\`/\`__geo_\`/\`__fts_\` infixes name Lunora's own bookkeeping and index companions, so the Studio and the admin API hide and refuse such a table. Rename the table.`)},ce=e=>e&&oe.has(e)?e:void 0,de=e=>{if(!i.isArrowFunction(e))return;let n=e.getBody();if(i.isParenthesizedExpression(n))n=n.getExpression();else if(i.isBlock(n)){const t=n.getStatements().find(s=>i.isReturnStatement(s));n=t&&i.isReturnStatement(t)?t.getExpression()??n:n}return i.isObjectLiteralExpression(n)?n:void 0},fe=e=>{if(!i.isPropertyAssignment(e))return;const n=e.getInitializer();if(!n||!i.isCallExpression(n))return;const t=n.getExpression();if(!i.isPropertyAccessExpression(t))return;const s=t.getName();if(s!=="one"&&s!=="many")return;const[r,a]=n.getArguments();if(!r||!i.isStringLiteral(r))throw d(r??n,`relation target table must be a string literal — codegen resolves relation targets statically. Got ${r?r.getText():"no argument"}.`);const o=r.getLiteralText();let l="_unknown_",c="_id",g;return a&&i.isObjectLiteralExpression(a)&&(l=f(a,"field")??l,c=f(a,"references")??c,g=s==="one"?ce(f(a,"onDelete")):void 0),{field:l,kind:s,name:I(e),onDelete:g,references:c,table:o}},ue=e=>{const n=de(e);if(!n)return[];const t=[];for(const s of n.getProperties()){const r=fe(s);r&&t.push(r)}return t},pe=(e,n,t)=>{if(!n.includes("."))return;const[s="",...r]=n.split("."),a=`${s}${r.map(o=>o.charAt(0).toUpperCase()+o.slice(1)).join("")}`;throw d(e,`index "${t}" indexes the nested path ${JSON.stringify(n)} — Lunora indexes only top-level columns. Denormalise the value into its own column (e.g. \`${a}\`), index that instead, and keep it in sync with a table \`.triggers()\` beforeInsert/beforeUpdate.`)},ge=e=>{if(!e||!i.isObjectLiteralExpression(e))return!1;const n=u(e,"unique");if(!n||!i.isPropertyAssignment(n))return!1;const t=n.getInitializer();if(t===void 0)return!1;if(!i.isTrueLiteral(t)&&!i.isFalseLiteral(t))throw d(t,`\`unique\` must be a literal \`true\` or \`false\`, got ${JSON.stringify(t.getText())}`);return i.isTrueLiteral(t)},me=e=>{const[n,t,s]=e,r=ge(s),a=y(n),o=t&&i.isArrayLiteralExpression(t)?t.getElements():[];for(const c of o)if(!i.isStringLiteral(c))throw d(c,`index "${a}" lists a non-literal field (${JSON.stringify(c.getText())}); codegen reads index fields statically, so every entry must be a string literal.`);const l=o.filter(c=>i.isStringLiteral(c));for(const c of l)pe(c,c.getLiteralText(),a);return{fields:l.map(c=>c.getLiteralText()),name:a,unique:r}},be=e=>{const[n,t]=e;let s="_unknown_",r,a,o,l;return t&&i.isObjectLiteralExpression(t)&&(s=f(t,"field")??s,r=h(t,"filterFields"),a=f(t,"language"),o=L(t,"staged"),l=f(t,"strategy")),{field:s,filterFields:r,language:a,name:y(n),staged:o,strategy:l}},xe=e=>{const[n,t]=e;let s="_unknown_",r;return t&&i.isObjectLiteralExpression(t)&&(s=f(t,"field")??s,r=x(t,"precision")),{field:s,name:y(n),precision:r}},he=e=>{const[n,t]=e,s=n&&i.isStringLiteral(n)?n.getLiteralText():"_unknown_";let r;return t&&i.isObjectLiteralExpression(t)&&(r=x(t,"after")),{after:r,field:s}},ye=e=>{if(!i.isObjectLiteralExpression(e))return;const n=f(e,"field");return n===void 0?void 0:{direction:f(e,"direction")==="desc"?"desc":"asc",field:n}},ve=e=>{const[n,t]=e;let s=[],r;if(t&&i.isObjectLiteralExpression(t)){const a=u(t,"sortBy");if(a&&i.isPropertyAssignment(a)){const o=a.getInitializer();o&&i.isArrayLiteralExpression(o)&&(s=o.getElements().map(l=>ye(l)).filter(l=>l!==void 0))}r=h(t,"partitionBy")}return{name:y(n),partitionBy:r,sortBy:s}},Ee=(e,n)=>{const[t,s]=e,r=t&&i.isStringLiteral(t)?t.getLiteralText():"_unknown_";if(!(!s||!i.isObjectLiteralExpression(s)))return{dimensions:x(s,"dimensions"),field:r,metadata:h(s,"metadata"),metric:O(f(s,"metric")),name:f(s,"index")??"_unnamed_",table:n}},Ie=e=>{const n=e[0];return n&&i.isObjectLiteralExpression(n)&&f(n,"backend")==="hyperdrive"?"hyperdrive":"d1"},we=e=>{if(e&&i.isObjectLiteralExpression(e)){const n=u(e,"field");if(n&&i.isPropertyAssignment(n)){const t=n.getInitializer();if(t&&i.isStringLiteral(t))return t.getLiteralText()}}return"deletedAt"},Se=e=>{const n=e[0];return!n||!i.isObjectLiteralExpression(n)?{binding:"",hasTenantBy:!1,unanalyzable:!0}:{binding:f(n,"binding")??"",columns:te(n,"columns"),hasReconcile:u(n,"reconcileEveryMs")!==void 0,hasSoftDelete:u(n,"softDeleteColumn")!==void 0,hasTenantBy:u(n,"tenantBy")!==void 0,idColumn:f(n,"idColumn"),mode:f(n,"mode"),query:f(n,"query")}},ke=(e,n,t,s)=>{switch(n){case"commitOrdered":{e.commitOrdered=!0;break}case"externallyManaged":{e.externallyManaged=!0;break}case"geoIndex":{e.geoIndexes.push(xe(t));break}case"global":{e.shardMode="global",e.globalBackend=Ie(t);break}case"index":{e.indexes.push(me(t));break}case"memory":{e.memory=!0;break}case"public":{e.isPublic=!0;break}case"rankIndex":{e.rankIndexes.push(ve(t));break}case"relations":{const r=t[0];r&&e.relations.push(...ue(r));break}case"searchIndex":{e.searchIndexes.push(be(t));break}case"shardBy":{const r=t[0];e.shardMode={field:r&&i.isStringLiteral(r)?r.getLiteralText():"_unknown_",kind:"shardBy"};break}case"softDelete":{e.softDelete={field:we(t[0])};break}case"source":{e.externalSource=Se(t),e.externallyManaged=!0;break}case"ttl":{e.ttl=he(t);break}case"vectorize":{const r=Ee(t,s);r&&e.vectorIndexes.push(r);break}}},_=["__vocab","_config","_content","_data","_docsize","_idx"],Te=(e,n,t)=>{const s=new Set(t.map(r=>r.name));for(const r of t)for(const a of _){const o=`${r.name}${a}`;if(!s.has(o))continue;const l=a==="__vocab"?`the \`fts5vocab\` companion for "${o}" is created \`IF NOT EXISTS\`, so it silently resolves to "${r.name}"'s — the second index then reads the wrong vocabulary and returns wrong results, with no error`:`creating "${o}" is rejected (\`object name reserved for internal use: SQLITE_ERROR\`), which aborts the shard migration and leaves every sharded table unreadable`;throw d(e,`table "${n}" declares search indexes "${r.name}" and "${o}", whose generated FTS5 tables collide: "${r.name}" already owns "${n}__fts_${o}" as its "${a}" companion, so ${l}. Rename one of them so neither ends with another's name plus ${_.join(", ")}.`)}},_e=(e,n,t)=>{if(t.ttl!==void 0&&t.shardMode==="global")throw d(e,ne(n))},P=(e,n)=>{const t={commitOrdered:!1,externallyManaged:!1,geoIndexes:[],indexes:[],isPublic:!1,memory:!1,rankIndexes:[],relations:[],searchIndexes:[],shardMode:"root",vectorIndexes:[]};let s={},r=e;for(;i.isCallExpression(r);){const a=r.getExpression(),o=r.getArguments();if(i.isPropertyAccessExpression(a))ke(t,a.getName(),o,n),r=a.getExpression();else if(i.isIdentifier(a)&&a.getText()==="defineTable"){const l=o[0];if(l&&i.isObjectLiteralExpression(l))s=V(l);else if(l)throw d(l,`table "${n}" 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_${n}\` / \`Insert_${n}\` type instead of sharing the runtime value.`);break}else break}return t.softDelete&&!(t.softDelete.field in s)&&(s={...s,[t.softDelete.field]:{inner:{column:{notNull:!1},kind:"number"},kind:"optional"}}),Te(e,n,t.searchIndexes),_e(e,n,t),{commitOrdered:t.commitOrdered,externallyManaged:t.externallyManaged,externalSource:t.externalSource,geoIndexes:t.geoIndexes,globalBackend:t.shardMode==="global"?t.globalBackend??"d1":void 0,indexes:t.indexes,isPublic:t.isPublic,memory:t.memory,name:n,rankIndexes:t.rankIndexes,relations:t.relations,searchIndexes:t.searchIndexes,shape:s,shardMode:t.shardMode,softDelete:t.softDelete,ttl:t.ttl,vectorIndexes:t.vectorIndexes}},j=(e,n=[],t=new Set,s=new Set)=>{s.add(e);for(const r of e.getProperties()){if(i.isSpreadAssignment(r)){const o=B(r.getExpression());o!==void 0&&!s.has(o)&&j(o,n,t,s);continue}if(!i.isPropertyAssignment(r))continue;const a=r.getInitializer();if(a){const o=I(r);if(w(o,r.getNameNode()),t.has(o))throw d(r.getNameNode(),`defineSchema({...}): table "${o}" is declared more than once — the earlier declaration would be silently discarded. Remove the duplicate.`);t.add(o),n.push(P(a,o))}}return n},Le=e=>{const n=u(e,"source");if(n&&i.isPropertyAssignment(n)){const t=n.getInitializer();if(t&&i.isObjectLiteralExpression(t))return f(t,"table")??"_unknown_"}return"_unknown_"},Oe=e=>{if(!i.isPropertyAssignment(e))return;const n=e.getInitializer();if(!n||!i.isCallExpression(n))return;const t=n.getExpression();if(!i.isIdentifier(t)||t.getText()!=="defineVectorIndex")return;const s=n.getArguments()[0];if(!s||!i.isObjectLiteralExpression(s))return;const r=e.getNameNode(),a=i.isStringLiteral(r)?r.getLiteralText():r.getText();return{dimensions:x(s,"dimensions"),metric:O(f(s,"metric")),name:a,table:Le(s)}},$=e=>{const n=[];for(const t of e.getProperties()){const s=Oe(t);s&&n.push(s)}return n},S=(e,n)=>`${e}_${n}`,Ae=(e,n)=>{if(!N.test(e))throw d(n,`defineSchemaExtension key ${JSON.stringify(e)} is not a valid JS identifier — it is prefixed onto every table the extension contributes (\`${e}_<table>\`), and table names are used in generated type names (Doc_<name>) and must match [A-Za-z_$][A-Za-z0-9_$]*. Rename the extension key.`)},E=(e,n,t)=>t.has(e)?S(n,e):e,Ne=(e,n,t)=>{const s=S(n,e.name);return{...e,extensionKey:n,name:s,relations:e.relations.map(r=>({...r,table:E(r.table,n,t)})),vectorIndexes:e.vectorIndexes.map(r=>({...r,table:E(r.table,n,t)}))}},Pe=e=>{if(i.isVariableDeclaration(e)||i.isPropertyAssignment(e))return e.getInitializer();if(i.isShorthandPropertyAssignment(e))return e.getNameNode()},je=e=>{if(!i.isCallExpression(e))return!1;const n=e.getExpression();return i.isIdentifier(n)&&n.getText()==="defineSchemaExtension"},$e=e=>{if(i.isIdentifier(e))return e;if(i.isPropertyAccessExpression(e)){const n=e.getExpression();return i.isIdentifier(n)?n:void 0}},De=e=>{if(i.isObjectLiteralExpression(e))return e;if(i.isCallExpression(e)){const n=e.getExpression();let t;if(i.isIdentifier(n)?t=n.getText():i.isPropertyAccessExpression(n)&&(t=n.getName()),t==="definePlugin"){const s=e.getArguments()[1];return s&&i.isObjectLiteralExpression(s)?s:void 0}}},ze=(e,n)=>{const t=Pe(e);if(t){if(i.isPropertyAccessExpression(n)){const s=De(t);return s?b(s,n.getName()):void 0}return t}},Me=e=>{let n=e,t=0;for(;n&&t<32;){if(t+=1,je(n))return n;const s=$e(n),r=s&&i.isIdentifier(s)?s.getSymbol():void 0,o=(r?.getAliasedSymbol()?.getDeclarations()??r?.getDeclarations()??[])[0];if(!o)return;const l=o.getSourceFile();if(l.isInNodeModules()||l.isDeclarationFile())return;n=ze(o,n)}},Re=e=>{const[n,t]=e.getArguments();if(!(!n||!i.isStringLiteral(n))&&!(!t||!i.isObjectLiteralExpression(t)))return{key:n.getLiteralText(),keyNode:n,options:t}},Ce=e=>{const n=u(e,"tables");if(!n||!i.isPropertyAssignment(n))return[];const t=n.getInitializer();if(!t||!i.isObjectLiteralExpression(t))return[];const s=[];for(const r of t.getProperties()){if(!i.isPropertyAssignment(r))continue;const a=r.getInitializer();if(!a)continue;const o=I(r);w(o,r.getNameNode()),s.push(P(a,o))}return s},Fe=e=>{const n=u(e,"vectorIndexes");if(!n||!i.isPropertyAssignment(n))return[];const t=n.getInitializer();return!t||!i.isObjectLiteralExpression(t)?[]:$(t)},D=(e,n,t,s)=>{Ae(e,s);const r=new Set(n.map(l=>l.name)),a=n.map(l=>Ne(l,e,r)),o=t.map(l=>({...l,name:S(e,l.name),table:E(l.table,e,r)}));return{tables:a,vectorIndexes:o}},Be=(e,n,t)=>D(e,Ce(t),Fe(t),n),Ve=(e,n)=>{const t=e.getArguments()[0];if(!t)return;const s=Me(t);if(!s){if(n!==void 0){const a=Y(t,n);if(a){for(const o of a.bareTables)w(o.name,t);return D(a.key,a.bareTables,a.bareVectorIndexes,t)}}console.warn(`@lunora/codegen: skipping \`.extend(${t.getText()})\` — its \`defineSchemaExtension(...)\` could not be resolved from local sources, and ${n===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 r=Re(s);if(!r){console.warn("@lunora/codegen: skipping `.extend(...)` — `defineSchemaExtension` requires a string `key` and an options object literal.");return}return Be(r.key,r.keyNode,r.options)},qe=e=>{const n=[];let t=e;for(;;){const s=t.getParent();if(!s||!i.isPropertyAccessExpression(s))break;const r=s.getParent();if(!r||!i.isCallExpression(r))break;s.getName()==="extend"&&n.push(r),t=r}return n},Je=(e,n,t)=>{const s=new Set(n.map(a=>a.name)),r=[];for(const a of qe(e)){const o=Ve(a,t);if(o){for(const l of o.tables){if(s.has(l.name))throw d(a,`defineSchema(...).extend(...): table "${l.name}" already exists — another extension with the same key already contributed it.`);s.add(l.name),n.push(l)}r.push(...o.vectorIndexes)}}return r},Ue=new Set(["eu","fedramp","us"]),Ke=e=>A(e,"jurisdiction","jurisdiction",Ue,'"eu", "us", or "fedramp"'),Ze=e=>{let n=e;for(;;){const t=n.getParent(),s=t?.getParent();if(!t||!i.isPropertyAccessExpression(t)||!s||!i.isCallExpression(s))return!1;if(t.getName()==="jurisdiction"){const r=s.getArguments()[1];return r!==void 0&&i.isObjectLiteralExpression(r)&&L(r,"pinAuth")===!0}n=s}},Ge=new Set(["required"]),We=e=>A(e,"rls","rls mode",Ge,'"required"'),rt=(e,n,t)=>{const r=e.addSourceFileAtPath(n).getDescendantsOfKind(R.CallExpression).find(p=>{const T=p.getExpression();return i.isIdentifier(T)&&T.getText()==="defineSchema"});if(!r)throw new M("INTERNAL",`defineSchema() not found in ${n}`);const a=r.getArguments()[0];if(!a||!i.isObjectLiteralExpression(a))throw d(r,"defineSchema() expects an object literal");const o=j(a),l=r.getArguments()[1],c=l&&i.isObjectLiteralExpression(l)?$(l):[],g=Je(r,o,t),k=[...o.flatMap(p=>p.vectorIndexes),...c,...g],z=new Set(o.filter(p=>p.shardMode==="global").map(p=>p.name)),v=k.find(p=>z.has(p.table));if(v)throw d(r,q(v.table,v.name));return{jurisdiction:Ke(r),...Ze(r)?{jurisdictionPinsAuth:!0}:{},rlsMode:We(r),tables:o,vectorIndexes:k}};export{rt as default};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import"./ir-DBSvhNa-.mjs";import"./json-data-Chfs2Cz5.mjs";import{w as i,p as r,A as n,n as o,B as g,q as F,l as p,D as u,u as l,m as f,o as w,C as d,t as k,s as A}from"./shard-runtime-oIXHEMU7.mjs";import"./shared-DjUziztz.mjs";export{i as buildDoTypeImports,r as emitAgentFragments,n as emitAgents,o as emitContainerFragments,g as emitContainers,F as emitPaymentFragments,p as emitQueueFragments,u as emitQueues,l as emitQueuesMetadataFragments,f as emitTopicFragments,w as emitWorkflowFragments,d as emitWorkflows,k as emitWorkflowsMetadataFragments,A as emitX402Fragments};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{readdirSync as x,realpathSync as P,lstatSync as A,statSync as O}from"node:fs";import{dirname as w,join as f,relative as N,sep as F,extname as E}from"node:path";import{Node as s,VariableDeclarationKind as T,SyntaxKind as S}from"ts-morph";import{diagnosticAt as R}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{findProjectConfigFile as D}from"./PROJECT_CONFIG_FILENAMES-DzOu-lSc.mjs";const I=/\.ts$/u,u=(t,e)=>N(t,e).split(F).join("/").replace(I,""),C=new Set(["_generated","node_modules"]),j=(t,e,i)=>t==="schema.ts"&&e===i,z=t=>{try{return O(t)}catch{console.warn(`@lunora/codegen: skipping ${t} — it is a symlink that does not resolve (or vanished mid-scan).`);return}},b=(t,e,i,r)=>{let o,n;try{o=x(t),n=P(t)}catch{return e}if(r.has(n))return e;r.add(n);for(const a of o){const l=f(t,a),c=z(l);c!==void 0&&(c.isDirectory()?C.has(a)||b(l,e,i,r):c.isFile()&&E(a)===".ts"&&!j(a,t,i)&&e.push(l))}return e},y=t=>b(t,[],t,new Set),V=["src/server","src/index.ts","src/worker.ts"],_=new Set([".ts",".tsx"]),v=(t,e=[])=>{let i;try{i=A(t)}catch{return e}if(i.isFile())return _.has(E(t))&&e.push(t),e;if(!i.isDirectory())return e;for(const r of x(t))r==="_generated"||r==="node_modules"||v(f(t,r),e);return e},K=t=>{const e=w(t),i=y(t).map(n=>({displayPath:u(t,n),filePath:n})),r=new Set(i.map(n=>n.filePath)),o=D(e);for(const n of[...V.flatMap(a=>v(f(e,a))),...o===void 0?[]:[o]])r.has(n)||(r.add(n),i.push({displayPath:u(e,n),filePath:n}));return i},L=(t,e,i)=>{const r=[];for(const{displayPath:o,filePath:n}of e){const a=t.getSourceFile(n)??t.addSourceFileAtPath(n);for(const l of a.getDescendantsOfKind(S.CallExpression)){const c=i(l,o);c!==void 0&&r.push(c)}}return r},J=(t,e,i)=>L(t,y(e).map(r=>({displayPath:u(e,r),filePath:r})),i),Q=(t,e,i)=>L(t,K(e),i),Z=t=>{for(const e of t.getAncestors())if(s.isVariableDeclaration(e)&&e.getVariableStatement()?.hasExportKeyword()===!0)return e.getName();return""},h=t=>{if(s.isStringLiteral(t)||s.isNoSubstitutionTemplateLiteral(t)||s.isNumericLiteral(t))return t.getLiteralText();if(s.isComputedPropertyName(t)){const e=t.getExpression();if(s.isStringLiteral(e)||s.isNoSubstitutionTemplateLiteral(e))return e.getLiteralText()}return t.getText()},k=t=>h(t.getNameNode()),tt=t=>h(t.getPropertyNameNode()??t.getNameNode()),p=(t,e)=>t?.getProperties().find(i=>!s.isSpreadAssignment(i)&&k(i)===e),et=(t,e)=>{if(e){const n=t.getArguments()[0];return n&&(s.isArrowFunction(n)||s.isFunctionExpression(n))?n:void 0}const i=t.getArguments()[0];if(!i||!s.isObjectLiteralExpression(i))return;const r=p(i,"handler");if(!r||!s.isPropertyAssignment(r))return;const o=r.getInitializer();return o&&(s.isArrowFunction(o)||s.isFunctionExpression(o))?o:void 0},it=(t,e)=>{if(!t||!s.isObjectLiteralExpression(t))return;const i=p(t,e);return i&&s.isPropertyAssignment(i)?i.getInitializer():void 0},$=t=>{const e=t?.getDeclarations().find(o=>s.isVariableDeclaration(o));if(e===void 0||!s.isVariableDeclaration(e))return;const i=e.getParent();if(!s.isVariableDeclarationList(i)||i.getDeclarationKind()!==T.Const)return;const r=i.getParent();return s.isVariableStatement(r)&&s.isSourceFile(r.getParent())?e.getInitializer():void 0},B=t=>$(t.getSymbol()),st=t=>{if(!t)return;if(s.isObjectLiteralExpression(t))return t;if(!s.isIdentifier(t))return;const e=B(t);return e!==void 0&&s.isObjectLiteralExpression(e)?e:void 0},g=t=>s.isPropertyAccessExpression(t)&&t.getName()==="db"||s.isIdentifier(t)&&t.getText()==="db",M=new Set(["findFirst","findFirstOrThrow","findMany","findUnique"]),rt=t=>{const e=t.getExpression();if(!s.isPropertyAccessExpression(e)||!M.has(e.getName()))return;const i=e.getExpression();if(g(i)){const r=t.getArguments()[0];return{options:t.getArguments()[1],table:r&&s.isStringLiteral(r)?r.getLiteralText():""}}if(s.isPropertyAccessExpression(i)){const r=i.getExpression();if(g(r))return{options:t.getArguments()[0],table:i.getName()}}},d=(t,e)=>{const i=t.getExpression();return!s.isPropertyAccessExpression(i)||!e.has(i.getName())?!1:g(i.getExpression())},m=t=>{const e=t.getArguments()[0];return e&&s.isStringLiteral(e)?e.getLiteralText():""},nt=(t,e,i)=>{const r=new Set,o=new Set;for(const n of t.getDescendantsOfKind(S.CallExpression))if(d(n,e)){const a=m(n);a!==""&&r.add(a)}else if(d(n,i)){const a=m(n);a!==""&&o.add(a)}return{tablesRead:[...r],tablesWritten:[...o]}},W=t=>{let e=t;for(;e&&(s.isAsExpression(e)||s.isSatisfiesExpression(e)||s.isParenthesizedExpression(e)||s.isNonNullExpression(e));)e=e.getExpression();return e},ot=t=>{const e=W(t);return e&&s.isCallExpression(e)?e:void 0},at=t=>{const e=t.getExportAssignment(o=>!o.isExportEquals());if(!e)return;const i=e.getExpression();if(!s.isIdentifier(i))return i;const r=i.getSymbol()?.getValueDeclaration();return r&&s.isVariableDeclaration(r)?r.getInitializer():i},ct=t=>{const e=t.getArguments()[1];return e&&s.isStringLiteral(e)?e.getLiteralValue():""},lt=(t,e)=>{if(!s.isObjectLiteralExpression(t))return;const i=p(t,e);if(!i||!s.isPropertyAssignment(i))return;const r=i.getInitializer();return r&&s.isStringLiteral(r)?r.getLiteralText():void 0},q=t=>{const e=t.getStatements(),[i]=e;if(e.length!==1||i===void 0||!s.isReturnStatement(i))return;const r=i.getExpression();return r!==void 0&&s.isObjectLiteralExpression(r)?r:void 0},ut=t=>{if(s.isObjectLiteralExpression(t))return t;if(s.isParenthesizedExpression(t)){const e=t.getExpression();return s.isObjectLiteralExpression(e)?e:void 0}return s.isBlock(t)?q(t):void 0},gt=t=>s.isIdentifier(t)&&t.getText()==="ctx",ft=t=>(e,i,r)=>{if(s.isStringLiteral(e)||s.isNoSubstitutionTemplateLiteral(e))return e.getLiteralValue();throw R(e,`${t} "${i}": \`${r}\` must be a static string literal — it is deploy configuration codegen writes into wrangler.jsonc`)};export{I as TS_EXTENSION_RE,tt as bindingKeyName,J as collectCallRows,Q as collectSecurityCallRows,at as defaultExportExpression,Z as enclosingExportName,p as findObjectProperty,et as handlerOf,gt as isContextIdentifier,g as isDatabaseAccessor,ct as limitNameOf,y as listLunoraSourceFiles,K as listSecurityScanFiles,u as lunoraRelativePath,ut as objectLiteralFromCallbackBody,st as optionsObjectLiteral,it as propertyInitializer,k as propertyKeyName,h as propertyNameText,rt as readTargetOf,ft as stringPropertyFor,lt as stringPropertyOf,$ as symbolConstInitializer,m as tableArgumentOf,nt as tablesAccessedIn,W as unwrapExpression,ot as unwrapToCallExpression};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{statSync as p,readFileSync as m}from"node:fs";import{basename as v}from"node:path";import{createJiti as E}from"jiti";import{Project as b,Node as r}from"ts-morph";import{propertyKeyName as u}from"./listLunoraSourceFiles-DP-5e-RE.mjs";import{findProjectConfigFile as f}from"./PROJECT_CONFIG_FILENAMES-DzOu-lSc.mjs";import{PROJECT_CONFIG_FILENAMES as I}from"./PROJECT_CONFIG_FILENAMES-DzOu-lSc.mjs";const g=new Map,N=async t=>{const i=f(t);if(i===void 0)return{};let e;try{const n=p(i);e=`${String(n.mtimeMs)}:${String(n.size)}`}catch{return{}}const s=g.get(i);if(s?.key===e)return s.value;const l=(async()=>{try{const o=(await E(i,{interopDefault:!1,moduleCache:!1}).import(i))?.default;return{config:o!==null&&typeof o=="object"?o:void 0}}catch(n){return{error:n instanceof Error?n.message:String(n)}}})();return g.set(i,{key:e,value:l}),l},x=t=>{let e=t.getExportAssignments().find(s=>!s.isExportEquals())?.getExpression();for(;e!==void 0&&(r.isSatisfiesExpression(e)||r.isAsExpression(e)||r.isParenthesizedExpression(e));)e=e.getExpression();if(e!==void 0&&r.isIdentifier(e))for(e=t.getVariableDeclaration(e.getText())?.getInitializer();e!==void 0&&(r.isSatisfiesExpression(e)||r.isAsExpression(e));)e=e.getExpression();return e!==void 0&&r.isObjectLiteralExpression(e)?e:void 0},c=(t,i)=>r.isPropertyAssignment(t)?t.getInitializer():i.getVariableDeclaration(u(t))?.getInitializer(),S=(t,i)=>{let e=t;for(;e!==void 0&&(r.isSatisfiesExpression(e)||r.isAsExpression(e)||r.isParenthesizedExpression(e));)e=e.getExpression();if(e===void 0||!r.isObjectLiteralExpression(e))return{advisor:{unreadable:!0}};const s=e.getProperties(),l=s.filter(a=>r.isPropertyAssignment(a)&&!r.isComputedPropertyName(a.getNameNode())||r.isShorthandPropertyAssignment(a));if(l.length!==s.length)return{advisor:{unreadable:!0}};const n=l.find(a=>u(a)==="minSeverity");if(n===void 0)return{advisor:{}};const o=c(n,i);return o!==void 0&&r.isStringLiteral(o)?{advisor:{minSeverity:o.getLiteralValue()}}:{advisor:{unreadable:!0}}},h=new Map([["advisor",{advisor:{unreadable:!0}}],["remote",{unreadable:!0}],["target",{unreadable:!0}]]),P=(t,i)=>{if(r.isGetAccessorDeclaration(t)||r.isMethodDeclaration(t))return h.get(u(t))??{};if(!r.isPropertyAssignment(t)&&!r.isShorthandPropertyAssignment(t))return{};const e=u(t);if(e==="advisor")return S(c(t,i),i);if(e!=="target"&&e!=="remote")return{};const s=c(t,i);return s===void 0?{unreadable:!0}:e==="target"?r.isStringLiteral(s)?{target:s.getLiteralValue()}:{unreadable:!0}:r.isTrueLiteral(s)||r.isFalseLiteral(s)?{remote:s.getLiteralValue()}:r.isObjectLiteralExpression(s)?{remote:!0}:{unreadable:!0}},O=t=>{const i=f(t);if(i===void 0)return{};let e;try{e=m(i,"utf8")}catch{return{unreadable:!0}}const l=new b({compilerOptions:{allowJs:!0},skipFileDependencyResolution:!0,skipLoadingLibFiles:!0,useInMemoryFileSystem:!0}).createSourceFile(v(i),e,{overwrite:!0}),n=x(l);if(n===void 0)return{unreadable:!0};if(n.getProperties().some(a=>r.isSpreadAssignment(a)))return n.getProperties().some(d=>!r.isSpreadAssignment(d)&&u(d)==="advisor")?{advisor:{unreadable:!0},unreadable:!0}:{unreadable:!0};let o={};for(const a of n.getProperties())o={...o,...P(a,l)};return o};export{I as PROJECT_CONFIG_FILENAMES,f as findProjectConfigFile,N as loadProjectConfig,O as readProjectConfigLiterals};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{Node as s,SyntaxKind as f}from"ts-morph";import{bindingKeyName as P,listLunoraSourceFiles as v,lunoraRelativePath as A,isDatabaseAccessor as h}from"./listLunoraSourceFiles-DP-5e-RE.mjs";const I=t=>{const e=t.getText(),n=r=>{const i=r.getNameNode();return s.isIdentifier(i)&&i.getText()===e};for(const r of t.getAncestors())if(!(!s.isArrowFunction(r)&&!s.isFunctionExpression(r)&&!s.isFunctionDeclaration(r)))for(const i of r.getParameters()){const a=i.getDescendantsOfKind(f.BindingElement).find(o=>n(o));if(a!==void 0)return a}},N=t=>{let e=t;for(;;){const n=e.getParent();if(!s.isObjectBindingPattern(n))return;const r=n.getParent();if(s.isBindingElement(r)){e=r;continue}return s.isParameterDeclaration(r)?P(e):void 0}},x=(t,e)=>{const n=t.getParent();if(s.isPropertyAccessExpression(n)&&n.getNameNode()===t||s.isPropertyAssignment(n)&&n.getNameNode()===t)return!1;if(t.getText()===e)return!0;const r=I(t);return r!==void 0&&N(r)===e},p=(t,e)=>s.isIdentifier(t)?x(t,e):t.getDescendantsOfKind(f.Identifier).some(n=>x(n,e)),g=t=>p(t,"ctx"),b=t=>{let e=t;for(;s.isPropertyAccessExpression(e)||s.isElementAccessExpression(e)||s.isNonNullExpression(e);)e=e.getExpression();return s.isIdentifier(e)?e:void 0},E=t=>p(t,"args"),u=t=>{if(!s.isIdentifier(t))return;const e=t.getText(),n=t.getFirstAncestor(o=>s.isArrowFunction(o)||s.isFunctionExpression(o)||s.isFunctionDeclaration(o));if(n===void 0)return;const r=t.getStart();let i,a=-1;for(const o of n.getDescendantsOfKind(f.VariableDeclaration)){if(o.getName()!==e)continue;const c=o.getInitializer(),l=o.getStart();c!==void 0&&l<r&&l>a&&(i=c,a=l)}return i},C=t=>{if(E(t))return!0;const e=u(t);return e!==void 0&&E(e)},_=t=>{if(s.isCallExpression(t)||s.isNewExpression(t))return!1;const e=u(t);return e===void 0||!(s.isCallExpression(e)||s.isNewExpression(e))},B=t=>{if(g(t))return!0;const e=u(t);if(e!==void 0&&g(e))return!0;const n=e??t;return(s.isIdentifier(n)?[n]:n.getDescendantsOfKind(f.Identifier)).some(i=>{const a=u(i);return a!==void 0&&g(a)})},m=(t,e)=>p(t,e),L=(t,e)=>{if(m(t,e))return!0;const n=u(t);if(n!==void 0&&m(n,e))return!0;const r=b(t);if(r!==void 0){const i=u(r);return i!==void 0&&m(i,e)}return!1},D=t=>{for(const e of t.getAncestors())if(s.isVariableDeclaration(e)&&e.getVariableStatement()?.hasExportKeyword()===!0)return e.getName();return"<module>"},y=new Set(["withGeoIndex","withIndex","withSearchIndex"]),S=new Set(["collect","collectWithScores","first","paginate","take","unique"]),F=t=>{const e=t.getExpression();if(!s.isPropertyAccessExpression(e)||e.getName()!=="query")return!1;const n=e.getExpression();return h(n)},w=t=>{const e=[];let n=t;for(;;){const r=n.getParent();if(!r||!s.isPropertyAccessExpression(r))break;const i=r.getParent();if(!i||!s.isCallExpression(i))break;e.push(r.getName()),n=i}return e},R=/\b[A-Za-z_$][\w$]*\._id\s*===?[^=]/u,K=t=>{let e=t;for(;;){const n=e.getParent();if(!n||!s.isPropertyAccessExpression(n))return!1;const r=n.getParent();if(!r||!s.isCallExpression(r))return!1;if(n.getName()==="filter"){const i=r.getArguments()[0];if(i&&R.test(i.getText()))return!0}e=r}},z=t=>{const e=t.getArguments()[0];return e&&s.isStringLiteral(e)?e.getLiteralText():""},M=(t,e)=>{const n=[];for(const r of v(e)){const i=t.getSourceFile(r)??t.addSourceFileAtPath(r),a=A(e,r);for(const o of i.getDescendantsOfKind(f.CallExpression)){if(!F(o))continue;const c=w(o),l=c.includes("filter");n.push({exportName:D(o),file:a,filtersPrimaryKey:l&&K(o),hasFilter:l,hasIndex:c.some(d=>y.has(d)),line:o.getStartLineNumber(),table:z(o),terminal:c.findLast(d=>S.has(d))})}}return n};export{B as a,_ as b,L as c,M as d,D as e,m as f,C as i,E as r,u as s};
|