@lunora/codegen 1.0.0-alpha.32 → 1.0.0-alpha.320
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/LICENSE.md +6 -0
- package/README.md +1 -1
- package/dist/index.d.mts +4230 -2183
- package/dist/index.d.ts +4230 -2183
- package/dist/index.mjs +1 -35
- package/dist/packem_shared/AGENTS_FILENAME-B6-kjzM3.mjs +1 -0
- package/dist/packem_shared/CAPABILITY_PROBES-brcmKenl.mjs +25 -0
- package/dist/packem_shared/CONTAINERS_FILENAME-dFRtAyIe.mjs +1 -0
- package/dist/packem_shared/CodegenDiagnosticError-BUXlG3P-.mjs +1 -0
- package/dist/packem_shared/DEFAULT_TARGET-B0FkdiZq.mjs +1 -0
- package/dist/packem_shared/FLAGS_FILENAME-Bf0MSlHH.mjs +1 -0
- package/dist/packem_shared/GENERATED_HEADER-Ck_WOHzE.mjs +1 -0
- package/dist/packem_shared/LUNORA_ERROR_CODES-C2s0xWQD.mjs +1 -0
- package/dist/packem_shared/MUTATORS_FILENAME-Jkk8Zgkb.mjs +1 -0
- package/dist/packem_shared/NOTIFY_FILENAME-bAt7J3cs.mjs +1 -0
- package/dist/packem_shared/OPENRPC_VERSION-CCY7xqSL.mjs +3 -0
- package/dist/packem_shared/PROJECT_CONFIG_FILENAMES-DzOu-lSc.mjs +1 -0
- package/dist/packem_shared/QUEUES_FILENAME-CsRy4VTF.mjs +1 -0
- package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-Bo67h-3B.mjs +11 -0
- package/dist/packem_shared/SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs +2 -0
- package/dist/packem_shared/SHAPES_FILENAME-DkBUN9dK.mjs +1 -0
- package/dist/packem_shared/SchemaSnapshotParseError-BRJT7c2k.mjs +18 -0
- package/dist/packem_shared/WORKFLOWS_FILENAME-CdeS224T.mjs +1 -0
- package/dist/packem_shared/attribution-hVBriwzy.mjs +1 -0
- package/dist/packem_shared/buildOpenApiDocument-DFv-RYZU.mjs +3 -0
- package/dist/packem_shared/capabilitiesUsedBy-QgSZyE0T.mjs +1 -0
- package/dist/packem_shared/chain-Cm6BMT8g.mjs +1 -0
- package/dist/packem_shared/classify-procedure-call-DVxdUhZt.mjs +1 -0
- package/dist/packem_shared/context-property-calls-Cn3upNgZ.mjs +1 -0
- package/dist/packem_shared/context-root-BdxINX-T.mjs +1 -0
- package/dist/packem_shared/createCodegenProject-V51_yBw3.mjs +1 -0
- package/dist/packem_shared/database-calls-BKozZUEW.mjs +1 -0
- package/dist/packem_shared/declared-output-Iaar469J.mjs +1 -0
- package/dist/packem_shared/describeErrorLevelFindings-vzaGS9KL.mjs +1 -0
- package/dist/packem_shared/discoverAuthApiCalls-xs0ONfI-.mjs +1 -0
- package/dist/packem_shared/discoverCrons-DBnCama4.mjs +1 -0
- package/dist/packem_shared/discoverFunctions-CZgLhsMn.mjs +1 -0
- package/dist/packem_shared/discoverHttpRoutes-WBAqBcfK.mjs +1 -0
- package/dist/packem_shared/discoverHyperdriveCalls-DV4IglLE.mjs +1 -0
- package/dist/packem_shared/discoverInserts-BjxXCACZ.mjs +1 -0
- package/dist/packem_shared/discoverMaskProcedures-DE-8CDen.mjs +1 -0
- package/dist/packem_shared/discoverMigrations-C9mLIhGZ.mjs +1 -0
- package/dist/packem_shared/discoverNondeterministicCalls-DvhyKM-f.mjs +1 -0
- package/dist/packem_shared/discoverQueries-C8E7TeRT.mjs +1 -0
- package/dist/packem_shared/discoverR2sqlCalls-DVcfMO6-.mjs +1 -0
- package/dist/packem_shared/discoverRlsMetadata-QRsWRQbM.mjs +1 -0
- package/dist/packem_shared/discoverRlsProcedures-Du7ITNTQ.mjs +1 -0
- package/dist/packem_shared/discoverSandboxUsage-w6Q3RvxZ.mjs +1 -0
- package/dist/packem_shared/discoverSchema-BtsX-CN9.mjs +1 -0
- package/dist/packem_shared/discoverStorageRulesMetadata-ClzKLdCV.mjs +1 -0
- package/dist/packem_shared/dispatch-namespace-DwTjD7BU.mjs +1 -0
- package/dist/packem_shared/emitAgents-CR2_X_ov.mjs +1 -0
- package/dist/packem_shared/emitApi-CDgIPAG2.mjs +147 -0
- package/dist/packem_shared/emitApp-BEe4wd3R.mjs +985 -0
- package/dist/packem_shared/emitCrons-BQW2lviZ.mjs +96 -0
- package/dist/packem_shared/emitDataModel-BskFt9Wv.mjs +114 -0
- package/dist/packem_shared/emitDrizzleSchema-DitcRZ1a.mjs +15 -0
- package/dist/packem_shared/emitFunctions-rjyb7h7k.mjs +422 -0
- package/dist/packem_shared/emitServer-D1vA5_X1.mjs +1 -0
- package/dist/packem_shared/emitShard-D3Po46nf.mjs +1 -0
- package/dist/packem_shared/exported-procedure-chains-BNBUkXui.mjs +1 -0
- package/dist/packem_shared/fingerprintSchemaSources-eVG9aVt0.mjs +1 -0
- package/dist/packem_shared/formatAdvisories-BCVASH7N.mjs +2 -0
- package/dist/packem_shared/handler-reference-vIeqkhV_.mjs +1 -0
- package/dist/packem_shared/index-JnqBWRYO.mjs +1 -0
- package/dist/packem_shared/isD1GlobalTable-udvHAAzD.mjs +1 -0
- package/dist/packem_shared/isTestPath-B81lOULB.mjs +1 -0
- package/dist/packem_shared/isTypedSchema-CKzc3ioR.mjs +4 -0
- package/dist/packem_shared/json-data-Chfs2Cz5.mjs +1 -0
- package/dist/packem_shared/loadProjectConfig-NO0dVJSl.mjs +1 -0
- package/dist/packem_shared/module-specifiers-WF8iAydP.mjs +1 -0
- package/dist/packem_shared/modules-CjOcuQnK.mjs +1 -0
- package/dist/packem_shared/parse-validator-IDBKIT7M.mjs +1 -0
- package/dist/packem_shared/platform-8oj7iXQy.mjs +1 -0
- package/dist/packem_shared/project-config-file-BV7RR-l6.mjs +1 -0
- package/dist/packem_shared/qualifiers-DEdXn5wP.mjs +1 -0
- package/dist/packem_shared/readPackageDependencies-RHhGiz0k.mjs +1 -0
- package/dist/packem_shared/readServiceBindings-DvqIThzd.mjs +1 -0
- package/dist/packem_shared/redact-Cy14LEnc.mjs +1 -0
- package/dist/packem_shared/reserved-words-CW1QFbTd.mjs +1 -0
- package/dist/packem_shared/schema-BgM8A3XV.mjs +1 -0
- package/dist/packem_shared/schemaFromIr-BWFnvCVg.mjs +1 -0
- package/dist/packem_shared/server-DAvi_bv_.mjs +368 -0
- package/dist/packem_shared/shard-CsOnD3Na.mjs +1601 -0
- package/dist/packem_shared/shard-runtime-BpoCV-aM.mjs +331 -0
- package/dist/packem_shared/shared-DnCokNcE.mjs +13 -0
- package/dist/packem_shared/unwrap-handler-return-CeaOifqX.mjs +1 -0
- package/dist/sdk/index.d.mts +288 -0
- package/dist/sdk/index.d.ts +288 -0
- package/dist/sdk/index.mjs +372 -0
- package/package.json +21 -8
- package/dist/packem_shared/CONTAINERS_FILENAME-DjpXMqhp.mjs +0 -224
- package/dist/packem_shared/CodegenDiagnosticError-DyQ5FwkM.mjs +0 -24
- package/dist/packem_shared/FLAGS_FILENAME-BjpS5w08.mjs +0 -139
- package/dist/packem_shared/GENERATED_HEADER-CLwPlCQe.mjs +0 -3
- package/dist/packem_shared/LUNORA_ERROR_CODES-CySpQPD3.mjs +0 -61
- package/dist/packem_shared/MUTATORS_FILENAME-BZOfUhlY.mjs +0 -81
- package/dist/packem_shared/OPENRPC_VERSION-4YIeMkOI.mjs +0 -60
- package/dist/packem_shared/QUEUES_FILENAME-BF0iUmx7.mjs +0 -119
- package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-OBXQBJV0.mjs +0 -3520
- package/dist/packem_shared/SCHEMA_SNAPSHOT_VERSION-D0ARY6rL.mjs +0 -249
- package/dist/packem_shared/SHAPES_FILENAME-DOhPGi-6.mjs +0 -94
- package/dist/packem_shared/WORKFLOWS_FILENAME-CCC_42o3.mjs +0 -124
- package/dist/packem_shared/buildOpenApiDocument-bp1pYSV6.mjs +0 -183
- package/dist/packem_shared/discover-ast-CT6BgBr4.mjs +0 -13
- package/dist/packem_shared/discoverAuthApiCalls-URDoTADN.mjs +0 -62
- package/dist/packem_shared/discoverCrons-DdZOeroL.mjs +0 -257
- package/dist/packem_shared/discoverFunctions-BJdF7lRs.mjs +0 -514
- package/dist/packem_shared/discoverHttpRoutes-CcwP-Rkr.mjs +0 -131
- package/dist/packem_shared/discoverInserts-BpFhM32L.mjs +0 -61
- package/dist/packem_shared/discoverMaskProcedures-DT-v8wvj.mjs +0 -273
- package/dist/packem_shared/discoverMigrations-cG1idBVM.mjs +0 -97
- package/dist/packem_shared/discoverNondeterministicCalls-CEOjmfk4.mjs +0 -122
- package/dist/packem_shared/discoverQueries-DeVBQVAG.mjs +0 -62
- package/dist/packem_shared/discoverR2sqlCalls-CWCAU-xJ.mjs +0 -80
- package/dist/packem_shared/discoverRlsMetadata-BL0oukaK.mjs +0 -280
- package/dist/packem_shared/discoverSchema-CeXJWVKV.mjs +0 -874
- package/dist/packem_shared/discoverStorageRulesMetadata-CFHByjIl.mjs +0 -97
- package/dist/packem_shared/emit-CBwEvCXQ.mjs +0 -3451
- package/dist/packem_shared/emitApp-nQ2oC-8G.mjs +0 -668
- package/dist/packem_shared/formatAdvisories-C9wNBNvL.mjs +0 -113
- package/dist/packem_shared/parse-validator-D6zI2i85.mjs +0 -134
- package/dist/packem_shared/paths-BRd6JHuF.mjs +0 -11
- package/dist/packem_shared/redact-oTmsol5A.mjs +0 -33
- package/dist/packem_shared/schemaFromIr-DTYsLBaA.mjs +0 -57
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import{existsSync as D,mkdirSync as Lt,readFileSync as Qi,writeFileSync as Xi,rmSync as Ae,readdirSync as mn}from"node:fs";import{dirname as Dt,join as v,relative as hn}from"node:path";import{performance as dt}from"node:perf_hooks";import{runAdvisor as Ji}from"@lunora/advisor";import{LunoraError as G}from"@lunora/errors";import{serializeSchemaSnapshot as Zi}from"./SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs";import{toAdvisorContext as er}from"./formatAdvisories-BCVASH7N.mjs";import{Node as r,SyntaxKind as d,ts as tr,VariableDeclarationKind as sr}from"ts-morph";import{listLunoraSourceFiles as A,lunoraRelativePath as P,bindingKeyName as ce,collectCallRows as w,findObjectProperty as z,collectSecurityCallRows as nr,propertyInitializer as C,listSecurityScanFiles as He,objectLiteralFromCallbackBody as vn,limitNameOf as En,optionsObjectLiteral as xn,handlerOf as ir,collectNodeRows as ne,chainRootOf as Mt,outermostValueWrapper as N,isWriteTarget as Ge,isSameNode as S,unwrapExpression as h,isConstDeclaration as ie,memberAccessOf as Sn,returningFunctionOf as St,walkChain as rr,RUN_METHODS as An,functionReferenceSegments as or,isTestPath as ar,isFunctionLike as re,functionKeyOf as yn}from"./isTestPath-B81lOULB.mjs";import{b as X,d as q,f as k,g as _t,c as x,a as bn,w as Kt,k as cr,l as lr,h as dr,m as ur,j as At,i as fr}from"./attribution-hVBriwzy.mjs";import{a as bs,r as ut,i as Y,b as gr,m as Nn,c as Ye,e as zt,E as Pn,C as wn,d as pr,f as mr,g as hr}from"./context-root-BdxINX-T.mjs";import{a as b,i as vr,c as te,d as In,e as Er,f as xr}from"./classify-procedure-call-DVxdUhZt.mjs";import{a as y,r as Cn,s as Sr,b as Ar}from"./project-config-file-BV7RR-l6.mjs";import{a as yr,b as Qe}from"./module-specifiers-WF8iAydP.mjs";import{r as Xe,s as br}from"./parse-validator-IDBKIT7M.mjs";import Nr from"./discoverAuthApiCalls-xs0ONfI-.mjs";import{i as _,r as Tn}from"./database-calls-BKozZUEW.mjs";import Pr from"./discoverHyperdriveCalls-DV4IglLE.mjs";import{diagnosticAt as Pe}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{m as Bt,a as Be,s as On,d as wr}from"./index-JnqBWRYO.mjs";import{MUTATORS_FILENAME as Ir,isDefineMutatorCallee as Cr,mutatorServerImplOf as Tr,discoverMutators as Or}from"./MUTATORS_FILENAME-Jkk8Zgkb.mjs";import kr from"./discoverNondeterministicCalls-DvhyKM-f.mjs";import{discoverNotifyConfig as Rr,discoverNotifyCalls as Fr}from"./NOTIFY_FILENAME-bAt7J3cs.mjs";import Lr from"./discoverR2sqlCalls-DVcfMO6-.mjs";import Dr from"./discoverRlsProcedures-Du7ITNTQ.mjs";import{s as $t,n as Mr}from"./dispatch-namespace-DwTjD7BU.mjs";import{secretKindOf as _r,redact as Kr,isHeuristicSecretKind as zr,isSecretishName as Br}from"./redact-Cy14LEnc.mjs";import{a as Fe,d as $r,r as Vr}from"./modules-CjOcuQnK.mjs";import{WORKFLOWS_FILENAME as Ur,discoverWorkflows as Wr}from"./WORKFLOWS_FILENAME-CdeS224T.mjs";import{r as qr}from"./json-data-Chfs2Cz5.mjs";import{G as jr}from"./shared-DnCokNcE.mjs";import{createCodegenProject as Hr}from"./createCodegenProject-V51_yBw3.mjs";import{findTsconfig as Fv,refreshCodegenProject as Lv}from"./createCodegenProject-V51_yBw3.mjs";import{CAPABILITIES as Gr,usedCapabilities as Yr}from"./CAPABILITY_PROBES-brcmKenl.mjs";import{isD1GlobalTable as kn,isHyperdriveGlobalTable as Rn}from"./isD1GlobalTable-udvHAAzD.mjs";import{discoverAgents as Qr}from"./AGENTS_FILENAME-B6-kjzM3.mjs";import{discoverContainers as Xr}from"./CONTAINERS_FILENAME-dFRtAyIe.mjs";import Jr from"./discoverCrons-DBnCama4.mjs";import{contextPropertiesRead as Zr,discoverFeatureUsage as eo}from"./capabilitiesUsedBy-QgSZyE0T.mjs";import Fn from"./readPackageDependencies-RHhGiz0k.mjs";import{discoverQueueDeclarations as to}from"./QUEUES_FILENAME-CsRy4VTF.mjs";import{discoverSandboxUsage as so}from"./discoverSandboxUsage-w6Q3RvxZ.mjs";import{resolveServiceBindings as no}from"./readServiceBindings-DvqIThzd.mjs";import io from"./discoverStorageRulesMetadata-ClzKLdCV.mjs";import{resolveCodegenTarget as Ln,gatePlatformFeatures as ro,readTargetDiagnostics as oo,vectorizeDimensionDiagnostics as ao,studioPlatformFor as co}from"./DEFAULT_TARGET-B0FkdiZq.mjs";import{i as lo}from"./schema-BgM8A3XV.mjs";import{b as Dn,e as uo}from"./shard-CsOnD3Na.mjs";import{e as fo,a as go}from"./server-DAvi_bv_.mjs";import{emitDataModel as po}from"./emitDataModel-BskFt9Wv.mjs";import{i as mo,a as ho,e as vo,b as Eo,d as xo,c as So}from"./unwrap-handler-return-CeaOifqX.mjs";import Ao from"./discoverFunctions-CZgLhsMn.mjs";import yo from"./discoverHttpRoutes-WBAqBcfK.mjs";import bo from"./discoverInserts-BjxXCACZ.mjs";import{e as Mn}from"./exported-procedure-chains-BNBUkXui.mjs";import No from"./discoverMigrations-C9mLIhGZ.mjs";import Po from"./discoverQueries-C8E7TeRT.mjs";import wo from"./discoverRlsMetadata-QRsWRQbM.mjs";import Io from"./discoverSchema-BtsX-CN9.mjs";import{discoverShapes as Co}from"./SHAPES_FILENAME-DkBUN9dK.mjs";import{i as To}from"./reserved-words-CW1QFbTd.mjs";import{emitApp as Oo}from"./emitApp-BEe4wd3R.mjs";import{readJsonSync as ko}from"@visulima/fs";import{buildSchemaSnapshot as Ro}from"./SchemaSnapshotParseError-BRJT7c2k.mjs";import{buildOpenApiDocument as Fo,emitOpenApiModule as Lo}from"./buildOpenApiDocument-DFv-RYZU.mjs";import{buildOpenRpcDocument as Do,emitOpenRpcModule as Mo}from"./OPENRPC_VERSION-CCY7xqSL.mjs";import{v as _o,t as Ko,u as zo,s as Bo,w as $o}from"./shard-runtime-BpoCV-aM.mjs";import{emitCollections as Vo,emitSeed as Uo,emitApi as Wo,emitInternalApi as qo}from"./emitApi-CDgIPAG2.mjs";import{emitCrons as jo,emitScheduler as Ho,emitShardRegistry as Go,emitDurableObjects as Yo,emitVectors as Qo,emitWranglerCronTriggers as Xo}from"./emitCrons-BQW2lviZ.mjs";import Jo from"./emitDrizzleSchema-DitcRZ1a.mjs";import{emitFunctions as Zo,emitLazyFunctionModules as ea}from"./emitFunctions-rjyb7h7k.mjs";const _n=new Set(["delete","get","head","options","patch","post","put"]),ta=new Set(["handler","stream"]),sa=/\/(?:_|admin|internal|superuser|sudo|root|debug)/iu,Ns=new Set(["ADMIN_TOKEN","adminToken","assertAdmin","assertAuth","auth","Authorization","getSession","identity","isAdmin","requireAdmin","requireAuth","requireRole","verifyAdmin"]),na=e=>{if(!r.isCallExpression(e))return;const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!_n.has(t.getName()))return;const s=t.getExpression();if(!r.isIdentifier(s)||s.getText()!=="httpRoute")return;const n=e.getArguments()[0];if(!(!n||!r.isStringLiteral(n)))return{method:t.getName().toUpperCase(),path:n.getLiteralValue()}},ia=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;let s=t.getExpression();for(;r.isCallExpression(s);){const n=s.getExpression();if(!r.isPropertyAccessExpression(n)||_n.has(n.getName()))break;s=n.getExpression()}return na(s)},ra=e=>{for(const t of e.getDescendantsOfKind(d.PropertyAccessExpression))if(Ns.has(t.getName()))return!0;for(const t of e.getDescendantsOfKind(d.CallExpression)){const s=t.getExpression();if(r.isIdentifier(s)&&Ns.has(s.getText()))return!0}return!1},oa=(e,t)=>{const s=e.getInitializer();if(!s||!r.isCallExpression(s))return;const n=s.getExpression();if(!r.isPropertyAccessExpression(n)||!ta.has(n.getName()))return;const i=ia(s);if(!i||!sa.test(i.path))return;const o=s.getArguments()[0],a=o!==void 0&&(r.isArrowFunction(o)||r.isFunctionExpression(o))&&ra(o);return{exportName:q(e)??e.getName(),file:t,method:i.method,path:i.path,usesGuard:a}},aa=(e,t)=>{const s=[];for(const n of X(e)){const i=oa(n,t);i&&s.push(i)}return s},ca=(e,t)=>{const s=[];for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...aa(i,P(t,n)))}return s},la=e=>{const t=e.getText(),s=n=>{const i=n.getNameNode();return r.isIdentifier(i)&&i.getText()===t};for(const n of e.getAncestors())if(!(!r.isArrowFunction(n)&&!r.isFunctionExpression(n)&&!r.isFunctionDeclaration(n)))for(const i of n.getParameters()){const o=i.getDescendantsOfKind(d.BindingElement).find(a=>s(a));if(o!==void 0)return o}},da=e=>{let t=e;for(;;){const s=t.getParent();if(!r.isObjectBindingPattern(s))return;const n=s.getParent();if(r.isBindingElement(n)){t=n;continue}return r.isParameterDeclaration(n)?ce(t):void 0}},ua=e=>{const t=e.getText();if(!e.getAncestors().some(o=>{const a=r.isFunctionLikeDeclaration(o)||r.isArrowFunction(o)?o.getParameters()[1]:void 0,c=a?.getNameNode();return a!==void 0&&(r.isIdentifier(c)?c.getText()===t:a.getDescendantsOfKind(d.BindingElement).some(l=>l.getName()===t))&&bs(a)}))return!1;const n=k(e),i=r.isParameterDeclaration(n)?n:n?.getFirstAncestorByKind(d.Parameter);return i!==void 0&&(r.isParameterDeclaration(n)||r.isBindingElement(n))&&bs(i)},Ps=(e,t)=>{const s=e.getParent();if(r.isPropertyAccessExpression(s)&&s.getNameNode()===e||r.isPropertyAssignment(s)&&s.getNameNode()===e)return!1;if(e.getText()===t)return!0;const n=la(e);return n!==void 0&&da(n)===t?!0:t==="args"&&ua(e)},Kn=(e,t)=>r.isIdentifier(e)?Ps(e,t):e.getDescendantsOfKind(d.Identifier).some(s=>Ps(s,t)),fa=e=>{let t=e;for(;r.isPropertyAccessExpression(t)||r.isElementAccessExpression(t)||r.isNonNullExpression(t);)t=t.getExpression();return r.isIdentifier(t)?t:void 0},ws=e=>{const t=r.isIdentifier(e)?k(e):void 0;return r.isVariableDeclaration(t)&&r.isIdentifier(t.getNameNode())&&!_t(t)?t.getInitializer():void 0},yt=e=>Kn(e,"args"),Q=e=>{if(!r.isIdentifier(e))return;const t=e.getText(),s=e.getFirstAncestor(a=>r.isArrowFunction(a)||r.isFunctionExpression(a)||r.isFunctionDeclaration(a));if(s===void 0)return;const n=e.getStart();let i,o=-1;for(const a of s.getDescendantsOfKind(d.VariableDeclaration)){if(a.getName()!==t)continue;const c=a.getInitializer(),l=a.getStart();c!==void 0&&l<n&&l>o&&(i=c,o=l)}return i},W=e=>{if(yt(e))return!0;const t=Q(e);return t!==void 0&&yt(t)},ga=e=>{if(r.isCallExpression(e)||r.isNewExpression(e))return!1;const t=Q(e);return t===void 0||!(r.isCallExpression(t)||r.isNewExpression(t))},le=e=>{if(ut(e))return!0;const t=ws(e);if(t!==void 0&&ut(t))return!0;const s=t??e;return(r.isIdentifier(s)?[s]:s.getDescendantsOfKind(d.Identifier)).some(i=>{const o=ws(i);return o!==void 0&&ut(o)})},De=(e,t)=>Kn(e,t),pa=(e,t)=>{if(De(e,t))return!0;const s=Q(e);if(s!==void 0&&De(s,t))return!0;const n=fa(e);if(n!==void 0){const i=Q(n);return i!==void 0&&De(i,t)}return!1},ma=e=>!r.isPropertyAccessExpression(e)||e.getName()!=="run"?!1:Y(e.getExpression(),["ai"]),ha=(e,t)=>{if(!ma(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!W(s)||le(s)))return{scope:x(e),file:t,line:e.getStartLineNumber()}},va=(e,t)=>w(e,t,ha),Ea=new Set(["generateText","streamText"]),xa=new Set(["messages","prompt","system"]),Sa=[{methods:new Set(["delete","insert","insertManyUnsafe","patch","patchIf","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"]}],Aa=(e,t)=>Sa.some(s=>s.methods.has(t)&&s.prefixes.some(n=>e===n||e.startsWith(`${n}.`))),ya=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;const s=t.getName(),n=[gr(t.getExpression()),t.getExpression().getText()].find(i=>i!==void 0&&Aa(i,s));return n===void 0?void 0:`${n}.${s}`},ba=e=>{for(const t of e.getDescendantsOfKind(d.CallExpression)){const s=ya(t);if(s!==void 0)return s}},Na=e=>{const t=new Set,s=e.getFirstAncestor(o=>r.isArrowFunction(o)||r.isFunctionExpression(o)||r.isFunctionDeclaration(o)),[n]=s?.getParameters()??[],i=n?.getNameNode();if(i===void 0||!r.isObjectBindingPattern(i))return t;for(const o of i.getElements()){const a=ce(o),c=o.getNameNode();if(a==="args"&&r.isObjectBindingPattern(c))for(const l of c.getElements())t.add(l.getName())}return t},Pa=e=>{if(yt(e))return!0;const t=Na(e);return t.size===0?!1:e.getDescendantsOfKind(d.Identifier).some(s=>t.has(s.getText()))},wa=e=>{for(const t of e.getProperties()){if(!r.isPropertyAssignment(t)||!xa.has(y(t)))continue;const s=t.getInitializer();if(s!==void 0&&Pa(s))return!0}return!1},Ia=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(d.CallExpression)){const i=b(n.getExpression());if(i===void 0||!Ea.has(i))continue;const[o]=n.getArguments();if(o===void 0||!r.isObjectLiteralExpression(o))continue;let a;for(const c of o.getDescendantsOfKind(d.CallExpression))if(b(c.getExpression())==="tool"&&(a=ba(c),a!==void 0))break;a!==void 0&&s.push({scope:x(n),file:t,line:n.getStartLineNumber(),method:i,sideEffect:a,userInputDerived:wa(o)})}return s},Ca=(e,t)=>{const s=[];for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Ia(i,P(t,n)))}return s},Ta=e=>Y(e,["fetch"]),Oa=(e,t)=>{if(!Ta(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!W(s)))return{scope:x(e),file:t,line:e.getStartLineNumber()}},ka=(e,t)=>w(e,t,Oa),Vt=(e,t=new Set)=>{if(t.has(e))return!0;t.add(e);try{return e.getProperties().some(s=>{if(!r.isSpreadAssignment(s))return!1;const n=Xe(s.getExpression());return n===void 0||Vt(n,t)})}finally{t.delete(e)}},Ra=e=>{const t=e.getArguments()[0];if(!t||!r.isObjectLiteralExpression(t))return{objects:[],opaque:!0};const s=z(t,"args");if(!s)return{objects:[],opaque:!1};if(!r.isPropertyAssignment(s))return{objects:[],opaque:!0};const n=s.getInitializer(),i=n===void 0?void 0:Xe(n);return i===void 0?{objects:[],opaque:!0}:{objects:[i],opaque:Vt(i)}},Fa=e=>{const t=[];let s=!1,n=e;for(;r.isCallExpression(n);){const i=n.getExpression();if(!r.isPropertyAccessExpression(i))break;if(i.getName()==="input"){const o=n.getArguments()[0],a=o!==void 0&&r.isExpression(o)?Xe(o):void 0;a===void 0?s=!0:(t.push(a),s||=Vt(a))}n=i.getExpression()}return{objects:t,opaque:s}},Ut=(e,t)=>t?Fa(t):Ra(e),zn=(e,t)=>{if(t.has(e))return[];t.add(e);try{return e.getProperties().flatMap(s=>{if(r.isSpreadAssignment(s)){const n=Xe(s.getExpression());return n===void 0?[]:zn(n,t)}return r.isPropertyAssignment(s)||r.isShorthandPropertyAssignment(s)?[y(s)]:[]})}finally{t.delete(e)}},La=e=>e.flatMap(t=>zn(t,new Set)),Da=new Set(["check","length","max"]),bt=e=>{let t=e;for(;;){const s=t.getParent();if(!s||!r.isPropertyAccessExpression(s)||s.getExpression()!==t)return!1;const n=s.getParent();if(!n||!r.isCallExpression(n)||n.getExpression()!==s)return!1;if(Da.has(s.getName()))return!0;t=n}},Nt=e=>yr(e)||e==="@lunora/values",Ma=e=>{const t=new Set(["v"]);for(const s of vr(e,"v",Nt))t.add(s);for(const s of e.getImportDeclarations()){const n=s.getNamespaceImport();n&&Nt(s.getModuleSpecifierValue())&&t.add(`${n.getText()}.v`)}return t},_a=(e,t)=>{const s=new Map;for(const n of e.getVariableStatements())for(const i of n.getDeclarations()){const o=i.getNameNode(),a=i.getInitializer();if(!(!r.isObjectBindingPattern(o)||!a||!t.has(a.getText())))for(const c of o.getElements())c.getDotDotDotToken()||s.set(c.getName(),c.getPropertyNameNode()?.getText()??c.getName())}return s},Ka=e=>(e.getSymbol()?.getDeclarations()??[]).some(t=>!t.getSourceFile().isDeclarationFile()&&!r.isImportSpecifier(t)&&!r.isNamespaceImport(t)&&!r.isImportClause(t)),za=e=>(e.getSymbol()?.getDeclarations()??[]).some(t=>r.isNamespaceImport(t)&&Nt(t.getFirstAncestorByKindOrThrow(d.ImportDeclaration).getModuleSpecifierValue())),Wt=(e,t)=>{if(!r.isCallExpression(e))return;const s=e.getExpression();if(r.isPropertyAccessExpression(s)){const n=s.getExpression();if(!t.namespaces.has(n.getText()))return;if(r.isIdentifier(n))return Ka(n)?void 0:s.getName();const i=r.isPropertyAccessExpression(n)?n.getExpression():void 0;return r.isIdentifier(i)&&za(i)?s.getName():void 0}if(r.isIdentifier(s))return t.destructured.get(s.getText())},Ba=(e,t)=>{if(!r.isIdentifier(e))return;const s=e.getText(),n=t.getVariableDeclaration(s)?.getInitializer();return n&&(r.isArrowFunction(n)||r.isFunctionExpression(n))?n:t.getFunction(s)},$a=e=>{let t=e.getParent();for(;t&&!r.isFunctionLikeDeclaration(t);)t=t.getParent();return t},Va=e=>r.isReturnStatement(e)?e.getExpression():void 0,Ua=e=>r.isArrowFunction(e)&&!r.isBlock(e.getBody())?[e.getBody()]:e.getDescendantsOfKind(d.ReturnStatement).filter(t=>$a(t)?.compilerNode===e.compilerNode).flatMap(t=>{const s=Va(t);return s?[s]:[]}),Bn=(e,t)=>{if(Wt(e,t)!==void 0)return e;if(r.isCallExpression(e)||r.isPropertyAccessExpression(e))return Bn(e.getExpression(),t)},Wa=(e,t)=>{const s=Ba(e.getExpression(),e.getSourceFile());if(!s)return[];const n=bt(e),i=new Set(Ua(s).map(o=>Bn(o,t)).filter(o=>o!==void 0));return[s,...s.getDescendants()].flatMap(o=>{const a=Wt(o,t);return a===void 0?[]:[{bounded:bt(o)||n&&i.has(o),factory:a}]})},qa=(e,t)=>[e,...e.getDescendants()].flatMap(s=>{const n=Wt(s,t),i=n===void 0?[]:[{bounded:bt(s),factory:n}];return r.isCallExpression(s)?[...i,...Wa(s,t)]:i}),ja=(e,t)=>{const s=[],n=[];for(const i of e)for(const o of i.getProperties()){if(!r.isPropertyAssignment(o))continue;const a=o.getInitializer();if(!a)continue;const c=qa(a,t),l=y(o);c.some(u=>u.factory==="any")?s.push(l):c.some(u=>u.factory==="string"&&!u.bounded)&&n.push(l)}return{anyArgs:s,unboundedStringArgs:n}},Ha=(e,t,s)=>{const n=e.getInitializer();if(!n||!r.isCallExpression(n))return;const i=te(n);if(i?.visibility!=="public")return;const{objects:o}=Ut(n,i.receiver),{anyArgs:a,unboundedStringArgs:c}=ja(o,s);if(!(a.length===0&&c.length===0))return{anyArgs:a,exportName:q(e)??e.getName(),file:t,line:n.getStartLineNumber(),unboundedStringArgs:c}},Ga=(e,t)=>{const s=[],n=Ma(e),i={destructured:_a(e,n),namespaces:n};for(const o of X(e)){const a=Ha(o,t,i);a&&s.push(a)}return s},Ya=(e,t)=>{const s=[];for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Ga(i,P(t,n)))}return s},ft=e=>e?.getKind()===d.TrueKeyword,Qa=e=>e?.getKind()===d.FalseKeyword,Xa=e=>e!==void 0&&r.isNumericLiteral(e)&&e.getLiteralValue()===0,Ja=new Set(["lunoraAuthAdapter","lunoraD1Adapter"]),Za=e=>!e||!r.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>r.isCallExpression(t)&&b(t.getExpression())==="scim"),ec=e=>e!==void 0&&r.isCallExpression(e)&&Ja.has(b(e.getExpression())??""),tc=e=>!e||!r.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>r.isStringLiteral(t)&&t.getLiteralText()==="*"),sc=e=>{const t=C(e,"advanced"),s=C(e,"emailAndPassword"),n=C(e,"session");return{analyzable:!0,disableCsrfCheck:ft(C(t,"disableCSRFCheck")),emailPasswordEnabled:ft(C(s,"enabled")),requireEmailVerification:ft(C(s,"requireEmailVerification")),scimOnNonTransactionalAdapter:Za(C(e,"plugins"))&&ec(C(e,"database")),secureCookiesDisabled:Qa(C(t,"useSecureCookies")),sessionFreshAgeZero:Xa(C(n,"freshAge")),trustedOriginsWildcard:tc(C(e,"trustedOrigins"))}},nc=()=>({analyzable:!1,disableCsrfCheck:!1,emailPasswordEnabled:!1,requireEmailVerification:!1,scimOnNonTransactionalAdapter:!1,secureCookiesDisabled:!1,sessionFreshAgeZero:!1,trustedOriginsWildcard:!1}),ic=(e,t)=>{if(b(e.getExpression())!=="createAuth")return;const s=e.getArguments()[0],n=s!==void 0&&r.isObjectLiteralExpression(s)&&s.getProperties().some(o=>r.isSpreadAssignment(o)),i=s!==void 0&&r.isObjectLiteralExpression(s)&&!n?sc(s):nc();return{scope:x(e),file:t,line:e.getStartLineNumber(),...i}},rc=(e,t)=>nr(e,t,ic),oc=(e,t)=>{if(!r.isPropertyAccessExpression(e))return;const s=e.getName();if(t.methods.has(s))return Nn(e.getExpression(),t.matchReceiver)?s:void 0},ac=(e,t,s)=>{const n=oc(e.getExpression(),s);if(n===void 0)return;const i=e.getArguments()[s.argIndex];if(!(!i||!W(i)||le(i))&&!(s.requireUnmodifiedReach===!0&&!ga(i)))return{scope:x(e),file:t,line:e.getStartLineNumber(),method:n}},Je=(e,t,s)=>w(e,t,(n,i)=>ac(n,i,s)),cc=new Set(["content","pdf","scrape","screenshot"]),lc=(e,t)=>Je(e,t,{argIndex:0,matchReceiver:s=>s==="ctx.browser",methods:cc}),dc=new Set(["createBrowser","createInboundEmailHandler","createPayment"]),uc=new Set(["RateLimiter"]),fc=new Set(["extend"]),Is="lunora",gc=["vite.config.ts","vite.config.mts","vite.config.js","vite.config.mjs"],$n=e=>{const t=[],s=[];let n=!1;for(const i of e.getProperties()){if(r.isSpreadAssignment(i)){n=!0;continue}if(r.isPropertyAssignment(i)){const o=y(i);t.push(o),i.getInitializer()?.getKind()===d.TrueKeyword&&s.push(o);continue}(r.isShorthandPropertyAssignment(i)||r.isMethodDeclaration(i))&&t.push(y(i))}return{analyzable:!n,presentKeys:t,trueKeys:s}},Pt=e=>e&&r.isObjectLiteralExpression(e)?$n(e):{analyzable:!1,presentKeys:[],trueKeys:[]},pc=e=>{const t=e&&(r.isArrowFunction(e)||r.isFunctionExpression(e))?e:void 0,s=t&&vn(t.getBody());return s?$n(s):{analyzable:!1,presentKeys:[],trueKeys:[]}},mc=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(d.CallExpression)){const i=b(n.getExpression());i!==void 0&&(dc.has(i)?s.push({callee:i,file:t,line:n.getStartLineNumber(),...Pt(n.getArguments()[0])}):fc.has(i)&&s.push({callee:i,file:t,line:n.getStartLineNumber(),...pc(n.getArguments()[0])}))}for(const n of e.getDescendantsOfKind(d.NewExpression)){const i=b(n.getExpression());i===void 0||!uc.has(i)||s.push({callee:i,file:t,line:n.getStartLineNumber(),...Pt(n.getArguments()[0])})}return s},hc=(e,t)=>{for(const s of gc){const n=v(t,s);if(!D(n))continue;const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=[];for(const a of i.getDescendantsOfKind(d.CallExpression))b(a.getExpression())===Is&&o.push({callee:Is,file:s,line:a.getStartLineNumber(),...Pt(a.getArguments()[0])});return o}return[]},vc=(e,t)=>{const s=[];for(const{displayPath:n,filePath:i}of He(t)){const o=e.getSourceFile(i)??e.addSourceFileAtPath(i);s.push(...mc(o,n))}return s.push(...hc(e,Dt(t))),s},Cs="ctx.containers.",Ec=e=>{if(!e.startsWith(Cs))return!1;const t=e.slice(Cs.length);return t.length>0&&!t.includes(".")},xc=(e,t)=>Je(e,t,{argIndex:0,matchReceiver:Ec,methods:new Set(["get"])}),Sc=new Set(["allow","deny","setAllowed"]),Ac=e=>{const t=e.getArguments()[0];if(!t||!r.isObjectLiteralExpression(t))return!1;const s=z(t,"enableInternet");return s!==void 0&&r.isPropertyAssignment(s)&&r.isTrueLiteral(s.getInitializerOrThrow())},yc=(e,t)=>{const s=e.getExpression();if(!(!r.isPropertyAccessExpression(s)||s.getName()!=="start"||!Ac(e)))return{detail:"enableInternet: true",scope:x(e),file:t,kind:"enable_internet",line:e.getStartLineNumber()}},bc=(e,t)=>{const s=e.getExpression();if(!r.isPropertyAccessExpression(s)||!Sc.has(s.getName()))return;const n=s.getExpression();if(!(!r.isPropertyAccessExpression(n)||n.getName()!=="egress"))return{detail:s.getName(),scope:x(e),file:t,kind:"egress_relaxation",line:e.getStartLineNumber()}},Nc=(e,t)=>yc(e,t)??bc(e,t),Pc=(e,t)=>w(e,t,Nc),wc=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||t.getName()!=="count")return;const s=t.getExpression();if(_(s)){const n=e.getArguments()[0];return n&&r.isStringLiteral(n)?n.getLiteralText():""}return r.isPropertyAccessExpression(s)&&_(s.getExpression())?s.getName():void 0},Ic=e=>{const t=e.getExpression(),s=r.isPropertyAccessExpression(t)?t.getExpression():void 0;return e.getArguments()[s!==void 0&&_(s)?1:0]},Cc=new Set(["baseWhere","relationBaseWhere","restrictsCounts","where"]),Tc=e=>{if(e===void 0||!r.isObjectLiteralExpression(e))return;const t=[];for(const n of e.getProperties()){if(!r.isPropertyAssignment(n)&&!r.isShorthandPropertyAssignment(n))return;t.push(n.getName())}return t.length>0&&t.every(n=>Cc.has(n))||t.some(n=>n==="AND"||n==="OR"||n==="NOT")?void 0:t},Oc=(e,t,s)=>{const n=new Map(s.map(i=>[i.name,i.aggregateIndexed===!0]));return w(e,t,(i,o)=>{const a=wc(i);if(a===void 0)return;const c=Tc(Ic(i));return{file:o,indexed:n.get(a)!==!1,...c===void 0?{}:{filterFields:c},line:i.getStartLineNumber(),scope:x(i),table:a}})},kc=new Set(["defineExportSink","r2Sink","webhookExportSink"]),Rc=e=>{const t=e.getExpression();if(!r.isIdentifier(t))return;const s=t.getText();return kc.has(s)?s:void 0},Fc=e=>{const t=[],s=[];for(const n of e.getProperties()){if(r.isSpreadAssignment(n))return{analyzable:!1,emptyKeys:[],presentKeys:[]};if(r.isPropertyAssignment(n)){const i=y(n);t.push(i);const o=n.getInitializer();o&&r.isStringLiteral(o)&&o.getLiteralText()===""&&s.push(i);continue}(r.isShorthandPropertyAssignment(n)||r.isMethodDeclaration(n)||r.isGetAccessorDeclaration(n))&&t.push(y(n))}return{analyzable:!0,emptyKeys:s,presentKeys:t}},Lc=(e,t)=>{const s=[];for(const{displayPath:n,filePath:i}of He(t)){const o=e.getSourceFile(i)??e.addSourceFileAtPath(i);for(const a of o.getDescendantsOfKind(d.CallExpression)){const c=Rc(a);if(c===void 0)continue;const l=a.getArguments()[0],u=l&&r.isObjectLiteralExpression(l)?Fc(l):{analyzable:!1,emptyKeys:[],presentKeys:[]};s.push({analyzable:u.analyzable,emptyKeys:u.emptyKeys,factory:c,file:n,line:a.getStartLineNumber(),presentKeys:u.presentKeys})}}return s},Dc=new Map([["dbRateLimit",2],["rateLimit",2],["verifyTurnstileMiddleware",0]]),Mc=new Set(["dbRateLimit","rateLimit"]),_c=e=>{const t=xn(e);if(!t)return!1;const s=z(t,"failOpen");return s!==void 0&&r.isPropertyAssignment(s)&&s.getInitializer()?.getKind()===d.TrueKeyword},Kc=(e,t)=>{const s=b(e.getExpression());if(s===void 0)return;const n=Dc.get(s);if(n!==void 0)return{callee:s,scope:x(e),failOpen:_c(e.getArguments()[n]),file:t,limitName:Mc.has(s)?En(e):"",line:e.getStartLineNumber()}},zc=(e,t)=>w(e,t,Kc),Bc=e=>{const t=e.getInitializer();if(!t||!r.isCallExpression(t))return;const s=te(t);if(s?.kind!=="query")return;const n=ir(t,s.receiver);return n?{exportName:q(e)??e.getName(),handler:n}:void 0},Ts=e=>{const t=e.getParent();return t&&r.isPropertyAccessExpression(t)&&t.getExpression()===e?t:void 0},$c=e=>{const t=Ts(e);if(!t)return"ctx.flags";if(t.getName()==="details"){const s=Ts(t);return s?`ctx.flags.details.${s.getName()}`:"ctx.flags.details"}return`ctx.flags.${t.getName()}`},Vc=(e,t)=>{const s=[];for(const n of Ye(e.handler,"flags"))s.push({callee:$c(n),exportName:e.exportName,file:t,line:n.getStartLineNumber()});return s},Uc=(e,t)=>{const s=[];for(const n of X(e)){const i=Bc(n);i&&s.push(...Vc(i,t))}return s},Wc=(e,t)=>{const s=[];for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Uc(i,P(t,n)))}return s},qc=e=>!r.isPropertyAccessExpression(e)||e.getName()!=="boolean"?!1:Y(e.getExpression(),["flags"]),jc=e=>{if(e?.getKind()===d.TrueKeyword)return!0;if(e?.getKind()===d.FalseKeyword)return!1},Hc=(e,t)=>{if(!qc(e.getExpression()))return;const[s,n]=e.getArguments();if(!s||!(r.isStringLiteral(s)||r.isNoSubstitutionTemplateLiteral(s)))return;const i=s.getLiteralValue(),o=jc(n);if(!(i.length===0||o===void 0))return{defaultValue:o,scope:x(e),file:t,key:i,line:e.getStartLineNumber()}},Gc=(e,t)=>w(e,t,Hc),Yc=e=>{const t=e.getExpression();return r.isPropertyAccessExpression(t)&&t.getName()==="withGeoIndex"},Qc=e=>{const t=e.getArguments()[0];return t&&r.isStringLiteral(t)?t.getLiteralText():""},Xc=(e,t)=>{const s=[];for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=P(t,n);for(const a of i.getDescendantsOfKind(d.CallExpression))Yc(a)&&s.push({file:o,indexName:Qc(a),line:a.getStartLineNumber()})}return s},ye=e=>e!==void 0&&(r.isArrowFunction(e)||r.isFunctionExpression(e))?e:void 0,Vn=e=>{const t=e.getArguments()[0],s=ye(t);if(s!==void 0)return s;if(t===void 0||!r.isObjectLiteralExpression(t))return;const n=z(t,"handler");return n!==void 0&&r.isPropertyAssignment(n)?ye(n.getInitializer()):void 0},Jc=new Set(["delete","get","head","options","patch","post","put"]),Zc=new Set(["handler","stream"]),el=new Set(["runAction","runMutation"]),tl=new Set(["delete","insert","insertManyUnsafe","patch","patchIf","replace"]),be=(e,t)=>e!==void 0&&r.isIdentifier(e)&&e.getText()===t,Un=(e,t)=>{if(!(e===void 0||!r.isObjectBindingPattern(e))){for(const s of e.getElements())if(ce(s)===t){const i=s.getNameNode();return r.isIdentifier(i)?i.getText():void 0}}},Os=(e,t)=>{const s=e.getParameters()[0]?.getNameNode();if(s!==void 0)return t?r.isIdentifier(s)?s.getText():void 0:Un(s,"ctx")},ks=(e,t)=>{const s=e.getParameters()[t?1:0]?.getNameNode();return t?s!==void 0&&r.isIdentifier(s)?s.getText():void 0:Un(s,"request")},Rs=(e,t)=>{const s=e.getBody(),n=s.getDescendantsOfKind(d.CallExpression);r.isCallExpression(s)&&n.unshift(s);for(const i of n){const o=i.getExpression();if(!r.isPropertyAccessExpression(o))continue;const a=o.getName(),c=o.getExpression();if(el.has(a)&&be(c,t))return a;if(tl.has(a)&&r.isPropertyAccessExpression(c)&&c.getName()==="db"&&be(c.getExpression(),t))return`db.${a}`}},Fs=(e,t)=>{const s=e.getBody();for(const n of s.getDescendantsOfKind(d.PropertyAccessExpression))if(n.getName()==="auth"&&be(n.getExpression(),t))return!0;for(const n of s.getDescendantsOfKind(d.VariableDeclaration)){const i=n.getNameNode();if(!(!r.isObjectBindingPattern(i)||!be(n.getInitializer(),t))){for(const o of i.getElements())if(ce(o)==="auth")return!0}}return!1},sl=/signature|hmac|digest|(?:^|[_-])sig(?:[_-]|$)/i,nl=(e,t)=>{const s=e.getExpression();if(!r.isPropertyAccessExpression(s)||s.getName()!=="get"&&s.getName()!=="has")return!1;const n=s.getExpression();return r.isPropertyAccessExpression(n)&&n.getName()==="headers"&&be(n.getExpression(),t)},il=e=>[...r.isStringLiteral(e)?[e.getLiteralText()]:[],...e.getDescendantsOfKind(d.StringLiteral).map(t=>t.getLiteralText())],Wn=(e,t)=>{const s=e.getVariableDeclaration(t)?.getInitializer();return s===void 0?[]:il(s)},rl=(e,t)=>{const s=e.getText();for(let n=e.getParent();n!==void 0;n=n.getParent()){if(!r.isArrowFunction(n)&&!r.isFunctionExpression(n)||!n.getParameters().some(c=>c.getName()===s))continue;const i=n.getParent();if(!r.isCallExpression(i))return[];const o=i.getExpression();if(!r.isPropertyAccessExpression(o))return[];const a=o.getExpression();return r.isIdentifier(a)?Wn(t,a.getText()):[]}return[]},ol=e=>{const t=e.getArguments()[0];if(t===void 0)return[];if(r.isStringLiteral(t))return[t.getLiteralText()];if(!r.isIdentifier(t))return[];const s=e.getSourceFile(),n=Wn(s,t.getText());return n.length>0?n:rl(t,s)},Ls=(e,t)=>{if(t===void 0)return!1;const s=e.getBody(),n=s.getDescendantsOfKind(d.CallExpression);return r.isCallExpression(s)&&n.unshift(s),n.some(i=>nl(i,t)&&ol(i).some(o=>sl.test(o)))},al=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!Zc.has(t.getName()))return;let s=t.getExpression();for(;r.isCallExpression(s);){const n=s.getExpression();if(!r.isPropertyAccessExpression(n))return;const i=n.getName();if(Jc.has(i)){const o=n.getExpression();return r.isIdentifier(o)&&o.getText()==="httpRoute"?i.toUpperCase():void 0}s=n.getExpression()}},cl=(e,t)=>{const s=e.getExpression();if(r.isIdentifier(s)&&s.getText()==="httpAction"){const c=ye(e.getArguments()[0]),l=c&&Os(c,!0);if(!c||l===void 0||Ls(c,ks(c,!0)))return;const u=Rs(c,l);return u===void 0?void 0:{scope:x(e),file:t,kind:"httpAction",line:e.getStartLineNumber(),readsAuth:Fs(c,l),sideEffect:u}}const n=al(e);if(n===void 0)return;const i=ye(e.getArguments()[0]),o=i&&Os(i,!1);if(!i||o===void 0||Ls(i,ks(i,!1)))return;const a=Rs(i,o);return a===void 0?void 0:{scope:x(e),file:t,kind:"httpRoute",line:e.getStartLineNumber(),method:n,readsAuth:Fs(i,o),sideEffect:a}},ll=(e,t)=>w(e,t,cl),dl=new Set(["btoa","encodeURI","encodeURIComponent","isSafeHeaderValue","Number","parseFloat","parseInt"]),ul=new Set(["append","set"]),qn=e=>e!==void 0&&(r.isStringLiteral(e)||r.isNoSubstitutionTemplateLiteral(e))?e.getLiteralText():"",Ds=(e,t)=>(r.isCallExpression(e)?[e,...e.getDescendantsOfKind(d.CallExpression)]:e.getDescendantsOfKind(d.CallExpression)).some(n=>dl.has(b(n.getExpression())??"")&&De(n,t)),fl=(e,t)=>{if(Ds(e,t))return!0;const s=Q(e);return s!==void 0&&Ds(s,t)},wt=(e,t)=>pa(e,t)&&!fl(e,t),gl=e=>{if(r.isPropertyAccessExpression(e)&&e.getName()==="headers")return!0;const t=Q(e);return t!==void 0&&r.isNewExpression(t)&&b(t.getExpression())==="Headers"},$e=e=>{if(e===void 0)return;if(r.isObjectLiteralExpression(e))return e;const t=Q(e);return t!==void 0&&r.isObjectLiteralExpression(t)?t:void 0},qt=(e,t,s)=>{for(const n of e.getProperties())if(r.isPropertyAssignment(n)){const i=n.getInitializer();i!==void 0&&wt(i,s.requestName)&&s.rows.push({scope:s.scope,file:s.relativePath,headerName:qn(n.getNameNode()),line:i.getStartLineNumber(),via:t})}else if(r.isShorthandPropertyAssignment(n)){const i=n.getNameNode();wt(i,s.requestName)&&s.rows.push({scope:s.scope,file:s.relativePath,headerName:y(n),line:i.getStartLineNumber(),via:t})}else if(r.isSpreadAssignment(n)){const i=$e(n.getExpression());i!==void 0&&qt(i,t,s)}},jn=(e,t)=>{const s=$e(e);if(s===void 0)return;const n=z(s,"headers");if(n===void 0||!r.isPropertyAssignment(n))return;const i=$e(n.getInitializer());i!==void 0&&qt(i,"response-init",t)},pl=(e,t)=>{const s=b(e.getExpression());if(s==="Response")jn(e.getArguments()[1],t);else if(s==="Headers"){const n=$e(e.getArguments()[0]);n!==void 0&&qt(n,"headers-ctor",t)}},ml=(e,t)=>{const s=e.getExpression();if(!r.isPropertyAccessExpression(s))return;const n=s.getName(),i=s.getExpression();if(n==="json"&&r.isIdentifier(i)&&i.getText()==="Response"){jn(e.getArguments()[1],t);return}if(ul.has(n)&&gl(i)){const o=e.getArguments()[1];o!==void 0&&wt(o,t.requestName)&&t.rows.push({scope:t.scope,file:t.relativePath,headerName:qn(e.getArguments()[0]),line:o.getStartLineNumber(),via:n==="set"?"headers-set":"headers-append"})}},hl=(e,t)=>{for(const s of e.getDescendantsOfKind(d.NewExpression))pl(s,t);for(const s of e.getDescendantsOfKind(d.CallExpression))ml(s,t)},vl=(e,t)=>{const s=e.getExpression();if(!r.isIdentifier(s)||s.getText()!=="httpAction")return[];const n=ye(e.getArguments()[0]);if(n===void 0)return[];const i=n.getParameters()[1];if(i===void 0)return[];const o=i.getNameNode();if(!r.isIdentifier(o))return[];const a=[];return hl(n,{scope:x(e),relativePath:t,requestName:o.getText(),rows:a}),a},El=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(d.CallExpression))s.push(...vl(n,t));return s},xl=(e,t)=>{const s=[];for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...El(i,P(t,n)))}return s},Hn="identity.ts",Sl=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineIdentity";for(const s of t.getDeclarations())if(r.isImportSpecifier(s))return Qe(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineIdentity":!1;return!1},Al=e=>{const t=e.getSymbol();if(!t)return!1;for(const s of t.getDeclarations()){if(!r.isNamespaceImport(s))continue;const n=s.getFirstAncestorByKind(d.ImportDeclaration);return n!==void 0&&Qe(n.getModuleSpecifierValue())}return!1},yl=e=>{if(r.isIdentifier(e))return Sl(e);if(r.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineIdentity"&&r.isIdentifier(t)&&Al(t)}return!1},bl=e=>{const t=[];for(const s of e.getVariableDeclarations()){const n=s.getInitializer();if(n?.getKind()!==d.CallExpression||!yl(n.getExpression()))continue;const o=s.getNameNode();if(!r.isIdentifier(o)){if(s.getVariableStatement()?.hasExportKeyword()!==!0)continue;throw Pe(o,"defineIdentity exports must be plain named exports (no destructuring)")}const a=bn(s,"member");a!==void 0&&t.push({exportName:a})}return t},Nl=(e,t)=>{const s=v(t,Hn);if(!D(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s),i=bl(n);if(i.length!==0){if(i.length>1)throw Pe(n,`lunora/identity.ts declares ${i.length.toString()} defineIdentity() contracts (${i.map(o=>o.exportName).join(", ")}); exactly one is allowed`);return i[0]}},Pl=new Set(["auth","context.auth"]),wl="userId",Il=e=>{const t=new Set;for(const s of e.getProperties()){if(r.isSpreadAssignment(s))return;(r.isPropertyAssignment(s)||r.isShorthandPropertyAssignment(s)||r.isMethodDeclaration(s))&&t.add(y(s))}return t},Cl=(e,t)=>{const s=v(t,Hn);if(!D(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const i of n.getDescendantsOfKind(d.CallExpression)){if(b(i.getExpression())!=="defineIdentity")continue;const[o]=i.getArguments();return o&&r.isObjectLiteralExpression(o)?Il(o):void 0}},Ms=e=>{if(e===void 0||!r.isPropertyAccessExpression(e)||e.getName()!=="identity")return;const t=e.getExpression();return Pl.has(t.getText())||Y(t,["auth"])?e:void 0},Tl=e=>{if(r.isPropertyAccessExpression(e)&&Ms(e.getExpression())!==void 0)return e.getName();if(r.isElementAccessExpression(e)&&Ms(e.getExpression())!==void 0){const t=e.getArgumentExpression();return t&&r.isStringLiteral(t)?t.getLiteralValue():void 0}},_s=(e,t,s)=>{const n=Tl(e);return n===void 0?void 0:{declared:n===wl||s.has(n),file:t,key:n,line:e.getStartLineNumber(),scope:x(e)}},Ol=(e,t)=>{const s=Cl(e,t);return s===void 0?[]:[...ne(e,t,d.PropertyAccessExpression,(n,i)=>_s(n,i,s)),...ne(e,t,d.ElementAccessExpression,(n,i)=>_s(n,i,s))]},kl=(e,t)=>{if(b(e.getExpression())!=="buildImageDeliveryUrl")return;const s=e.getArguments()[0];if(!s)return;const n=C(s,"key");if(!(!n||!W(n)||le(n)))return{scope:x(e),file:t,line:e.getStartLineNumber()}},Rl=(e,t)=>w(e,t,kl),Fl=new Set(["delete","get","getRaw","getWithMetadata","put"]),Ll=(e,t,s=[])=>{const n=Je(e,t,{argIndex:0,matchReceiver:i=>i==="ctx.kv"||i.startsWith("ctx.kv."),methods:Fl});return Kt(n,s)},Dl=new Set(["queue","send"]),Ks=new Set(["bcc","cc","to"]),Ml=e=>{if(!r.isPropertyAccessExpression(e))return;const t=e.getName();if(!Dl.has(t))return;const s=e.getExpression();return Y(s,["mail"])||Y(s,["email"])?t:void 0},_l=e=>r.isObjectLiteralExpression(e)?e.getProperties().some(t=>{if(r.isShorthandPropertyAssignment(t)){const n=t.getNameNode();return Ks.has(y(t))&&W(n)&&!le(n)}if(!r.isPropertyAssignment(t)||!Ks.has(y(t)))return!1;const s=t.getInitializer();return s!==void 0&&W(s)&&!le(s)}):!1,Kl=(e,t)=>{const s=Ml(e.getExpression());if(s===void 0)return;const n=e.getArguments()[0];if(!(!n||!_l(n)))return{scope:x(e),file:t,line:e.getStartLineNumber(),method:s}},zl=(e,t)=>w(e,t,Kl),Bl=(e,t,s)=>{const n=e.getArguments()[0];if(!n||!r.isObjectLiteralExpression(n))return[];const i=[];for(const o of n.getProperties()){const a=Be(o);if(a===void 0||!r.isPropertyAssignment(o))continue;const c=o.getInitializer();if(!(!c||!r.isObjectLiteralExpression(c)))for(const l of c.getProperties()){const u=Be(l);if(u===void 0)continue;const f=On(l);f!=="custom"&&i.push({column:u,exportName:t,file:s,line:l.getStartLineNumber(),strategy:f,table:a})}}return i},$l=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&r.isCallExpression(s)?te(s):void 0;return n?.receiver?Bt(n.receiver).flatMap(i=>Bl(i,q(e)??e.getName(),t)):[]},Vl=(e,t)=>{const s=[];for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=P(t,n);for(const a of X(i))s.push(...$l(a,o))}return s},Ul=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||t.getName()!=="replace")return!1;const s=t.getExpression();return _(s)},Wl=e=>{const t=e.getArguments()[0];if(t===void 0||!r.isObjectLiteralExpression(t))return;const s=z(t,"server");if(s!==void 0)return r.isPropertyAssignment(s)?s.getInitializer():s},ql=e=>{if(!e.isExported())return;const t=e.getInitializer();if(t?.getKind()!==d.CallExpression)return;const s=t;return Cr(s.getExpression())?s:void 0},jl=e=>{const t=ql(e),s=t===void 0?void 0:Wl(t);if(s===void 0)return[];const n=e.getNameNode(),i=r.isIdentifier(n)?q(e)??n.getText():"";return s.getDescendantsOfKind(d.CallExpression).filter(o=>Ul(o)).map(o=>({exportName:i,file:"lunora/mutators.ts",line:o.getStartLineNumber()}))},Hl=e=>e.getVariableDeclarations().flatMap(t=>jl(t)),Gl=(e,t)=>{const s=v(t,Ir);if(!D(s))return[];const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);return Hl(n)},Yl=new Set(["delete","get","patch"]),Ql=new Set(["accountId","authorId","companyId","createdBy","createdById","customerId","groupId","memberId","organizationId","orgId","ownerId","projectId","teamId","tenantId","userId","workspaceId"]),Xl=new Set(["auth","identity","session","user"]),Jl=new Set([d.EqualsEqualsEqualsToken,d.EqualsEqualsToken,d.ExclamationEqualsEqualsToken,d.ExclamationEqualsToken]),Zl=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||t.getName()!=="normalizeId"||!_(t.getExpression()))return;const s=e.getArguments()[0];return s&&r.isStringLiteral(s)?s.getLiteralText():""},ed=e=>{let t=e,s=t.getParent();for(;s!==void 0&&(r.isAsExpression(s)||r.isParenthesizedExpression(s)||r.isNonNullExpression(s));)t=s,s=t.getParent();if(s===void 0||!r.isVariableDeclaration(s))return;const n=s.getNameNode();return r.isIdentifier(n)?n.getText():void 0},td=(e,t)=>e.getDescendantsOfKind(d.Identifier).some(s=>s.getText()===t),sd=e=>r.isThrowStatement(e)||r.isReturnStatement(e)||e.getDescendantsOfKind(d.ThrowStatement).length>0||e.getDescendantsOfKind(d.ReturnStatement).length>0,nd=(e,t)=>e.getDescendantsOfKind(d.IfStatement).some(s=>td(s.getExpression(),t)&&sd(s.getThenStatement())),id=(e,t)=>{for(const s of e.getDescendantsOfKind(d.CallExpression)){const n=s.getExpression();if(!r.isPropertyAccessExpression(n))continue;const i=n.getName();if(!Yl.has(i))continue;const o=n.getExpression();if(!(_(o)||r.isPropertyAccessExpression(o)&&_(o.getExpression())))continue;const c=s.getArguments()[0];if(c!==void 0&&r.isIdentifier(c)&&c.getText()===t)return i}},rd=e=>e.getDescendantsOfKind(d.CallExpression).some(t=>t.getArguments().some(s=>zt(Mt(s))!==void 0)),od=e=>e.getDescendantsOfKind(d.BinaryExpression).some(t=>Jl.has(t.getOperatorToken().getKind())?r.isPropertyAccessExpression(t.getLeft())||r.isPropertyAccessExpression(t.getRight()):!1),ad=e=>{for(const t of e.getDescendantsOfKind(d.Identifier))if(Ql.has(t.getText()))return!0;return[...Xl].some(t=>Ye(e,t).length>0)?!0:rd(e)||od(e)},cd=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!r.isCallExpression(s))return[];const n=te(s);if(n?.kind!=="query"&&n?.kind!=="mutation")return[];const i=Vn(s);if(i===void 0)return[];const o=n.receiver!==void 0&&In(n.receiver,"use","rls"),a=ad(i),c=new Set,l=[];for(const u of i.getDescendantsOfKind(d.CallExpression)){const f=Zl(u);if(f===void 0)continue;const g=ed(u);if(g===void 0||c.has(g)||!nd(i,g))continue;const m=id(i,g);m!==void 0&&(c.add(g),l.push({exportName:q(e)??e.getName(),file:t,line:u.getStartLineNumber(),mentionsOwnership:a,sinkMethod:m,table:f,usesRls:o,visibility:n.visibility}))}return l},ld=(e,t)=>{const s=[];for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=P(t,n);for(const a of X(i))s.push(...cd(a,o))}return s},Gn=(e,t)=>{const s=r.isIdentifier(e)&&t!==void 0?k(e):void 0;return s===void 0||t===void 0?!1:s.compilerNode===t.compilerNode?r.isIdentifier(t.getNameNode()):r.isBindingElement(s)&&s.getFirstAncestorByKind(d.Parameter)?.compilerNode===t.compilerNode},dd=e=>{const t=N(e),s=t.getParent();return(r.isPropertyAccessExpression(s)||r.isElementAccessExpression(s))&&s.getExpression()===t&&!Ge(s)},ud=e=>{const t=N(e).getParent();return r.isVariableDeclaration(t)&&r.isObjectBindingPattern(t.getNameNode())},fd=e=>{const s=N(e).getParent();if(r.isSpreadAssignment(s)||r.isSpreadElement(s)){const n=s.getParent();return(r.isObjectLiteralExpression(n)||r.isArrayLiteralExpression(n))&&!Ge(n)}return r.isTemplateSpan(s)&&!r.isTaggedTemplateExpression(s.getParent().getParent())},Ve=e=>{const t=k(e);return t===void 0||lr(t.getSourceFile())},It=(e,t)=>{const s=N(e),n=s.getParent();if(!r.isCallExpression(n))return!1;const i=n.getArguments().indexOf(s),o=h(n.getExpression());if(i===-1||o===void 0)return!1;if(r.isIdentifier(o))return o.getText()==="structuredClone"&&Ve(o);if(Gn(Mt(o),t))return!(r.isPropertyAccessExpression(o)&&Pn.has(o.getName()))||r.isExpressionStatement(N(r.isAwaitExpression(n.getParent())?n.getParentOrThrow():n).getParent());if(!r.isPropertyAccessExpression(o))return!1;const a=o.getExpression();if(!r.isIdentifier(a)||!Ve(a))return!1;const c=a.getText(),l=o.getName();switch(c){case"console":return!0;case"JSON":return l==="stringify";case"Object":return["entries","freeze","isFrozen","keys","values"].includes(l)||l==="assign"&&i>0;default:return!1}},Me={kind:"opaque"},gd={kind:"unreached"},pd=e=>{const t=e.getSymbol()?.getDeclarations()??[],s=t.filter(o=>r.isFunctionDeclaration(o)&&o.hasBody()),[n]=s;return t.every(o=>r.isFunctionDeclaration(o)&&o.getSourceFile()===e.getSourceFile())&&s.length===1&&r.isFunctionDeclaration(n)?n:void 0},Ct=e=>{const t=h(e);if(r.isArrowFunction(t)||r.isFunctionExpression(t))return t;const s=r.isIdentifier(t)?k(t):void 0;if(s?.getSourceFile()!==e.getSourceFile())return;if(r.isFunctionDeclaration(s)){const i=pd(s);return i===void 0||_t(i)?void 0:i}const n=ie(s)?h(s.getInitializer()):void 0;return r.isArrowFunction(n)||r.isFunctionExpression(n)?n:void 0},Yn=(e,t,s)=>{const n=t.getArguments(),i=n.indexOf(s),o=i===-1||n.slice(0,i+1).some(l=>r.isSpreadElement(l))||e.getDescendantsOfKind(d.Identifier).some(l=>l.getText()==="arguments"),a=e.getParameters(),c=a[i];return o?Me:c===void 0?a.some(l=>l.isRestParameter())?Me:gd:c.isRestParameter()?Me:{kind:"parameter",parameter:c}},md=e=>{const t=N(e),s=t.getParent();if(!r.isCallExpression(s)||s.getExpression()===t)return;const n=Ct(s.getExpression());return n===void 0?Me:Yn(n,s,t)},hd=new Set(["__defineGetter__","__defineSetter__","__proto__"]),vd=e=>r.isForInStatement(e)?e.getExpression():r.isConditionalExpression(e)?e.getCondition():r.isElementAccessExpression(e)?e.getArgumentExpression():void 0,Qn=e=>{const t=N(e),s=t.getParent();if(r.isIfStatement(s)||r.isWhileStatement(s)||r.isDoStatement(s)||r.isSwitchStatement(s)||r.isCaseClause(s)||r.isTypeOfExpression(s)||r.isVoidExpression(s)||r.isComputedPropertyName(s))return!0;if(r.isTemplateSpan(s))return!r.isTaggedTemplateExpression(s.getParent().getParent());const n=vd(s);if(n!==void 0)return S(n,t);if(r.isPrefixUnaryExpression(s))return s.getOperatorToken()!==d.PlusPlusToken&&s.getOperatorToken()!==d.MinusMinusToken;if(!r.isBinaryExpression(s))return!1;const i=s.getOperatorToken().getKind(),o=i>=d.FirstAssignment&&i<=d.LastAssignment,a=i===d.QuestionQuestionToken||i===d.BarBarToken||i===d.AmpersandAmpersandToken;return!o&&!a},Ed=4,Xn=(e,t,s=0)=>{if(cr(e))return!0;if(dd(e)){const i=N(e).getParent(),o=r.isElementAccessExpression(i)?i.getArgumentExpression():void 0,a=r.isStringLiteral(o)?o.getLiteralValue():void 0,c=r.isPropertyAccessExpression(i)?i.getName():a;return c===void 0||!hd.has(c)}if(ud(e)||fd(e)||Qn(e)||It(e,t))return!0;const n=md(e);return n?.kind==="unreached"||n?.kind==="parameter"&&xd(n.parameter,s+1)},zs=new WeakMap,xd=(e,t=0)=>{const s=e.getNameNode();if(!r.isIdentifier(s))return!0;const n=zs.get(e.compilerNode);if(n!==void 0)return n;if(t>Ed)return!1;const o=(s.getSymbol()?.getDeclarations().length??0)===1&&e.getParentOrThrow().getDescendantsOfKind(d.Identifier).every(a=>a===s||a.getText()!==s.getText()||k(a)?.compilerNode!==e.compilerNode||Xn(a,void 0,t));return(o||t===0)&&zs.set(e.compilerNode,o),o},Bs=new WeakMap,Sd=(e,t)=>{const s=r.isFunctionExpression(e)?e.getNameNode():void 0;if(!r.isArrowFunction(e)&&e.getFirstDescendantByKind(d.ThisKeyword)!==void 0)return!0;const n=new Set([t.getName(),...s===void 0?[]:[s.getText()]]);return e.getDescendantsOfKind(d.Identifier).some(i=>{if(i===s||!n.has(i.getText()))return!1;const o=k(i)?.compilerNode;return o!==void 0&&(o===t.compilerNode||s!==void 0&&o===e.compilerNode)})},Ad=(e,t,s)=>{const{context:n,impl:i}=e,o=Bs.get(i.compilerNode);if(o!==void 0)return o;const a=t.getNameNode(),c=r.isIdentifier(a)?[a]:a.getDescendantsOfKind(d.BindingElement).flatMap(g=>{const m=g.getNameNode();return r.isIdentifier(m)?[m]:[]}),l=new Map(c.map(g=>[g.getText(),g.getParentOrThrow().compilerNode])),u=g=>r.isIdentifier(a)?Xn(g,n):!Ge(g),f=!Sd(i,s)&&c.every(g=>(g.getSymbol()?.getDeclarations().length??0)===1)&&i.getDescendantsOfKind(d.Identifier).every(g=>{const m=g.getText();if(m==="arguments")return!1;const E=l.get(m);return E===void 0||c.includes(g)||k(g)?.compilerNode!==E?!0:u(g)});return Bs.set(i.compilerNode,f),f},$s=new WeakMap,yd=e=>{let t=$s.get(e.compilerNode);return t===void 0&&(t=new Map(e.getVariableDeclarations().flatMap(s=>{const n=Tr(s);return n===void 0?[]:[[n.compilerNode,s]]})),$s.set(e.compilerNode,t)),t},bd=e=>{const t=yd(e.getSourceFile()),s=e.getAncestors().find(l=>t.has(l.compilerNode)),n=s===void 0?void 0:t.get(s.compilerNode);if(s===void 0||n===void 0)return;const[i,o]=s.getParameters(),a=o===void 0||o.isRestParameter()?void 0:o,c={context:i,impl:s,mutatorName:q(n)??n.getName()};return a!==void 0&&Ad(c,a,n)?{...c,parameter:a,pristine:!0}:{...c,parameter:a,pristine:!1}},gt="args",Ee=e=>{const t=Sn(e);if(t!==void 0){const c=h(t.object);return r.isIdentifier(c)&&c.getText()===gt?t.member:void 0}if(!r.isIdentifier(e))return;const s=k(e);if(!r.isBindingElement(s)||s.getDotDotDotToken()!==void 0)return;const n=s.getParent();if(!r.isObjectBindingPattern(n))return;const i=n.getParent(),o=ie(i)?h(i.getInitializer()):void 0;return r.isBindingElement(i)&&ce(i)===gt||r.isIdentifier(o)&&o.getText()===gt?ce(s):void 0},Nd=new Set(["auth","identity","user"]),Tt=e=>{const t=i=>{const o=zt(i);return o!==void 0&&o.length>0&&Nd.has(o[0]??"")},s=h(e)??e;if(t(s))return!0;const n=Q(s);return n!==void 0&&t(n)},Jn=(e,t=2)=>{const s=new Set;for(const n of[e,...e.getDescendants()]){const i=Ee(n);i!==void 0&&s.add(i);const o=t>0&&r.isIdentifier(n)?Q(n):void 0;if(o!==void 0)for(const a of Jn(o,t-1))s.add(a)}return s},_e=e=>{const t=h(e)??e;if(!r.isBinaryExpression(t))return[];const s=t.getOperatorToken().getKind(),n=t.getLeft(),i=t.getRight();if(s===d.BarBarToken)return[..._e(n),..._e(i)];if(s===d.AmpersandAmpersandToken){const l=(u,f)=>{const g=Ee(h(u)??u);return g===void 0?[]:_e(f).filter(m=>m===g)};return[...l(n,i),...l(i,n)]}if(s!==d.ExclamationEqualsEqualsToken&&s!==d.ExclamationEqualsToken)return[];const o=[],a=Ee(h(n)??n),c=Ee(h(i)??i);return a!==void 0&&Tt(i)&&o.push(a),c!==void 0&&Tt(n)&&o.push(c),o},Pd=e=>{const t=h(e)??e;if(!r.isIdentifier(t))return!1;const s=t.getSymbol(),n=s?.getAliasedSymbol()?.getValueDeclaration()??s?.getValueDeclaration();if(!r.isVariableDeclaration(n))return!1;const i=h(n.getInitializer());return r.isCallExpression(i)&&Er(i.getExpression(),"defineIdentityGuard")},wd=e=>{if(!Pd(e.getExpression()))return[];const t=e.getArguments();return t.flatMap((s,n)=>{const i=Ee(h(s)??s),o=t.some((a,c)=>c!==n&&Tt(a));return i!==void 0&&o?[i]:[]})},Id=e=>{if(r.isThrowStatement(e))return!0;if(!r.isBlock(e))return!1;const t=e.getStatements().at(-1);return t!==void 0&&r.isThrowStatement(t)},Cd=e=>r.isArrowFunction(e)||r.isFunctionExpression(e)||r.isFunctionDeclaration(e)||r.isMethodDeclaration(e),Vs=(e,t)=>{for(let s=e.getParent();s!==void 0;s=s.getParent()){if(s===t||s.compilerNode===t.compilerNode)return!0;if(!(r.isBlock(s)||r.isExpressionStatement(s)||r.isAwaitExpression(s)||r.isParenthesizedExpression(s)||r.isVariableStatement(s)||r.isVariableDeclarationList(s)||r.isVariableDeclaration(s)))return!1}return!1},Td=e=>r.isAwaitExpression(e.getParent())||e.getType().isVoid(),Od=(e,t)=>{const s=new Set;for(const n of e.getDescendantsOfKind(d.IfStatement))if(n.getEnd()<=t&&Vs(n,e)&&Id(n.getThenStatement()))for(const i of _e(n.getExpression()))s.add(i);for(const n of e.getDescendantsOfKind(d.CallExpression))if(n.getEnd()<=t&&Td(n)&&Vs(n,e))for(const i of wd(n))s.add(i);return s},kd=(e,t)=>{const s=Jn(t);if(s.size===0)return!1;const n=e.getFirstAncestor(Cd);if(n===void 0)return!1;const i=Od(n,e.getStart());return[...s].every(o=>i.has(o))},Rd=new Set(["at","concat","filter","find","findLast","flat","reverse","slice","sort","toReversed","toSorted"]),Fd=new Map([["Array",new Set(["from","of"])],["Object",new Set(["entries","values"])]]),Ot=new Set(["catch","every","filter","finally","find","findIndex","findLast","findLastIndex","flatMap","forEach","map","reduce","reduceRight","some","sort","then"]),Zn=e=>e.getNameNode().getDescendantsOfKind(d.BindingElement).filter(t=>r.isIdentifier(t.getNameNode())),Ld=e=>{const t=N(e),s=t.getParent();if(r.isVariableDeclaration(s))return S(s.getInitializer(),t)?s:void 0;const n=r.isForOfStatement(s)&&s.getExpression()===t?s.getInitializer():void 0;return r.isVariableDeclarationList(n)?n.getDeclarations()[0]:void 0},Dd=e=>{const t=Ld(e);return t===void 0?void 0:r.isIdentifier(t.getNameNode())?r.isForOfStatement(t.getParent().getParent())||ie(t)?[t]:void 0:Zn(t)},xe=e=>e.isUnion()?e.getUnionTypes().every(t=>xe(t)):e.isIntersection()?e.getIntersectionTypes().some(t=>xe(t)):!e.isAny()&&!e.isUnknown()&&!e.isObject()&&!e.isTypeParameter(),Ue=(e,t,s)=>{const n=r.isCallExpression(e)?h(e.getExpression()):void 0;return r.isPropertyAccessExpression(n)&&t.has(n.getName())&&(s===void 0||n.getExpression()===s)},Ke=e=>{const t=h(e);if(!r.isArrowFunction(t)&&!r.isFunctionExpression(t))return;const s=t.getBody();return r.isBlock(s)?s.getDescendantsOfKind(d.ReturnStatement).filter(n=>n.getFirstAncestor(i=>r.isFunctionLikeDeclaration(i))===t).map(n=>n.getExpression()):[s]},Md=e=>{const t=r.isCallExpression(e)?h(e.getExpression()):void 0,s=r.isPropertyAccessExpression(t)?t.getExpression():void 0;return r.isPropertyAccessExpression(t)&&r.isIdentifier(s)&&Fd.get(s.getText())?.has(t.getName())===!0&&Ve(s)},_d=e=>{const t=St(e);if(!r.isArrowFunction(t)&&!r.isFunctionExpression(t))return;const s=N(t),n=s.getParent();return r.isCallExpression(n)&&n.getArguments().includes(s)&&Ue(n,wn)?n:void 0},Kd=(e,t)=>{if(!(r.isPropertyAccessExpression(e)||r.isElementAccessExpression(e))||e.getExpression()!==t)return;const s=N(e),n=s.getParent();return!r.isCallExpression(n)||n.getExpression()!==s?e:Ue(n,Rd,t)?n:void 0},zd=(e,t)=>{if(r.isAwaitExpression(e))return e;if(r.isConditionalExpression(e))return e.getCondition()===t?void 0:e;const s=r.isBinaryExpression(e)?e.getOperatorToken().getKind():void 0;return s===d.QuestionQuestionToken||s===d.BarBarToken||s===d.AmpersandAmpersandToken?e:void 0},Bd=(e,t)=>{if(r.isArrayLiteralExpression(e))return e;const n=r.isSpreadElement(e)||r.isSpreadAssignment(e)||r.isShorthandPropertyAssignment(e)||r.isPropertyAssignment(e)&&S(e.getInitializer(),t)?e.getParent():void 0;return r.isArrayLiteralExpression(n)||r.isObjectLiteralExpression(n)?n:void 0},Us=e=>{const t=N(e),s=t.getParent();if(s===void 0)return;const n=r.isCallExpression(s)&&s.getArguments().includes(t)&&Md(s);return Kd(s,t)??zd(s,t)??Bd(s,t)??(n?s:_d(t))},$d=5e4,ei=()=>({inProgress:new Set,verdicts:new Map});class Vd{cuts=0;work=0;reset(){this.work=0}cut(){return this.cuts+=1,!0}spend(){return this.work+=1,this.work>$d&&this.cut()}memoized(t,s,n){const i=n.verdicts.get(t);if(i!==void 0)return i;if(n.inProgress.has(t))return this.cuts+=1,!1;if(this.spend())return!0;const o=this.cuts;n.inProgress.add(t);let a;try{a=s()}finally{n.inProgress.delete(t)}return this.cuts===o&&n.verdicts.set(t,a),a}}const Ud=8,Wd=8;class qd{budget;scope;taint;verdicts=ei();constructor(t,s,n){this.scope=t,this.budget=s,this.taint=n}isCompromised(t){return this.flowHasCompromisingUse(t)&&!xe(t.getType())}flowHasCompromisingUse(t){return this.budget.memoized(t.compilerNode,()=>{const s=this.budget.cuts,n=[],i=new Set,o=(c,l)=>{i.has(c.compilerNode)||(i.add(c.compilerNode),n.push({binding:c,hops:l}))};let a=!1;o(t,0);for(const c of n)if(a=(c.binding===t?void 0:this.verdicts.verdicts.get(c.binding.compilerNode))??this.visitBinding(c,t,o),a)break;if(!a&&this.budget.cuts===s)for(const c of i)this.verdicts.verdicts.set(c,!1);return a},this.verdicts)}visitBinding({binding:t,hops:s},n,i){const o=t.getNameNode();if(!r.isIdentifier(o)){for(const l of r.isParameterDeclaration(t)?Zn(t):[])i(l,s);return!1}if(this.budget.spend())return!0;const a=(l,u)=>u&&s>=Ud?this.budget.cut():(i(l,u?s+1:s),!1);return this.taint.referencesTo(t,o.getText()).some(l=>this.valueCompromises(N(l),!0,a,0))&&(t===n||!xe(t.getType()))}valueCompromises(t,s,n,i){let o=t;for(let m=Us(o);m!==void 0;m=Us(o)){if(r.isCallExpression(m)&&this.callbackCompromises(m,n))return!0;o=N(m)}const a=o.getParent(),c=o===t&&s,l=()=>!c&&xe(o.getType());if(Ge(o))return!c&&(!r.isBinaryExpression(a)||this.taint.isTaintedValue(a.getRight(),!1));const u=Dd(o);if(u!==void 0)return u.some(m=>n(m,!0));const f=r.isPropertyAccessExpression(a)&&a.getExpression()===o?a.getParent():void 0;if(r.isCallExpression(f)&&f.getExpression()===a)return this.methodCallCompromises(f,n);const g=this.nestedReturningFunctionOf(o);return g!==void 0?this.resultCompromises(g,n,i)&&!l():this.positionCompromises(o,n)&&!l()}resultCompromises(t,s,n){const i=N(t).getParent();if(n>=Wd)return this.budget.cut();if(r.isCallExpression(i))return i.getExpression()===N(t)?this.valueCompromises(i,!1,s,n+1):!Ue(i,Ot);const o=r.isFunctionDeclaration(t)?t:i,a=r.isFunctionDeclaration(o)||ie(o)?o.getNameNode():void 0;return o===void 0||!r.isIdentifier(a)?!0:this.taint.referencesTo(o,a.getText()).some(c=>{const l=N(c),u=l.getParent();return!r.isCallExpression(u)||u.getExpression()!==l||this.valueCompromises(u,!1,s,n+1)})}methodCallCompromises(t,s){return t.getArguments().filter(i=>Ke(i)===void 0).some(i=>this.taint.isTaintedValue(i,!1))||this.callbackCompromises(t,s)}callbackCompromises(t,s){const n=Ue(t,Ot)?t.getArguments()[0]:void 0;if(n===void 0)return!1;const i=Ct(n);return i!==void 0&&this.taint.isInImpl(i)?i.getParameters().some(o=>s(o,!1)):this.taint.isTaintedValue(n,!1)}positionCompromises(t,s){const n=t.getParent();if(r.isCallExpression(n)&&n.getArguments().includes(t))return this.argumentCompromises(n,t,s);const i=r.isSpreadElement(n)?n.getParent():void 0;if(n!==void 0&&r.isCallExpression(i))return!It(n,this.scope.context)&&this.isOpaqueCallTainted(i.getExpression(),i.getArguments(),n);if(r.isNewExpression(n))return this.isOpaqueCallTainted(n.getExpression(),n.getArguments(),t);if(r.isTemplateSpan(n)){const o=n.getParent(),a=o.getParent(),c=o.getTemplateSpans().map(l=>l.getExpression());return r.isTaggedTemplateExpression(a)&&this.isOpaqueCallTainted(a.getTag(),c,t)}return!this.isReadPosition(t)}argumentCompromises(t,s,n){if(It(s,this.scope.context))return!1;const i=Ct(t.getExpression()),o=i===void 0?void 0:Yn(i,t,s);return o?.kind==="unreached"?!1:o?.kind==="parameter"&&i!==void 0&&this.taint.isInImpl(i)?n(o.parameter,!1):this.isOpaqueCallTainted(t.getExpression(),t.getArguments(),s)}isReadPosition(t){const s=t.getParent();return s===void 0||r.isExpressionStatement(s)||r.isForStatement(s)||r.isElementAccessExpression(s)||Qn(t)||S(St(t),this.scope.impl)}isOpaqueCallTainted(t,s,n){const i=!r.isIdentifier(h(n));return this.taint.isTaintedValue(t,!1)||s.some(o=>(o!==n||i)&&this.taint.isTaintedValue(o,!1))}nestedReturningFunctionOf(t){const s=St(t);return S(s,this.scope.impl)?void 0:s}}const jd=new Set(["at","every","filter","finally","find","findIndex","findLast","findLastIndex","forEach","order","slice","some","sort","withIndex","withSearchIndex"]),Hd=e=>{const t=h(e);if(!r.isIdentifier(t))return r.isPropertyAccessExpression(t)||r.isElementAccessExpression(t);const s=k(t),n=r.isVariableDeclaration(s)?h(s.getInitializer()):void 0;return s===void 0||r.isFunctionDeclaration(s)||r.isParameterDeclaration(s)||r.isArrowFunction(n)||r.isFunctionExpression(n)},Gd=new Set(["all","allSettled","any","race"]),Ws=e=>r.isParameterDeclaration(e)?e:r.isBindingElement(e)?e.getFirstAncestorByKind(d.Parameter):void 0,pt=8;class Yd{budget=new Vd;referencesByDeclaration=new Map;referencesByName=new Map;scope;verdicts=ei();walk;variableDepth=0;queryDepth=0;constructor(t){this.scope=t,this.walk=new qd(t,this.budget,this);for(const s of t.impl.getDescendantsOfKind(d.Identifier)){const n=s.getText();this.referencesByName.set(n,[...this.referencesByName.get(n)??[],s])}}isTaintedValue(t,s){this.queryDepth===0&&this.budget.reset(),this.queryDepth+=1;try{return s&&this.isRootedInContext(t,pt)?!1:(r.isIdentifier(t)?[t]:t.getDescendantsOfKind(d.Identifier)).some(i=>dr(i)&&this.isIdentifierTainted(i))}finally{this.queryDepth-=1}}isInImpl(t){const{impl:s}=this.scope;return t!==s&&s.getPos()<=t.getPos()&&t.getEnd()<=s.getEnd()}referencesTo(t,s){let n=this.referencesByDeclaration.get(s);if(n===void 0){n=new Map;for(const i of this.referencesByName.get(s)??[]){const o=k(i)?.compilerNode;o!==void 0&&n.set(o,[...n.get(o)??[],i])}this.referencesByDeclaration.set(s,n)}return(n.get(t.compilerNode)??[]).filter(i=>i.getParent()!==t)}flowsIntoTainted(t){if([t.getInitializer(),...t.getDescendantsOfKind(d.BindingElement).map(g=>g.getInitializer())].some(g=>g!==void 0&&this.isTaintedValue(g,!1)))return!0;const n=t.getParentOrThrow(),i=r.isFunctionLikeDeclaration(n)?n.getParameters().findIndex(g=>g.compilerNode===t.compilerNode):-1,o=N(n),a=o.getParent();if(i===-1)return!0;if(r.isCallExpression(a)){if(a.getExpression()===o)return this.isCallSiteTainted(a,i,t.isRestParameter());const g=h(a.getExpression());if(!r.isPropertyAccessExpression(g)||!Ot.has(g.getName()))return!0;const m=a.getArguments().filter(E=>E!==o);return this.isTaintedValue(g.getExpression(),!0)||m.some(E=>this.isTaintedValue(E,!1))}const c=r.isVariableDeclaration(a)&&ie(a)?a:void 0,l=r.isFunctionDeclaration(n)?n:c,u=l?.getNameNode();if(l===void 0||!r.isIdentifier(u))return!0;const f=this.referencesTo(l,u.getText());return f.length===0||f.some(g=>{const m=N(g),E=m.getParent();return!r.isCallExpression(E)||E.getExpression()!==m||this.isCallSiteTainted(E,i,t.isRestParameter())})}isCallSiteTainted(t,s,n){const i=t.getArguments(),o=i.findIndex(c=>r.isSpreadElement(c)),a=c=>c===s||n&&c>s||o!==-1&&o<=s&&c>=o;return i.some((c,l)=>a(l)&&this.isTaintedValue(c,!1))}isContextRootedCombinator(t,s){const n=h(t.getExpression()),i=r.isPropertyAccessExpression(n)?n.getExpression():void 0,a=r.isPropertyAccessExpression(n)&&r.isIdentifier(i)&&i.getText()==="Promise"&&Ve(i)&&Gd.has(n.getName())?h(t.getArguments()[0]):void 0;if(r.isArrayLiteralExpression(a)){const f=a.getElements();return f.length>0&&f.every(g=>!r.isSpreadElement(g)&&this.isRootedInContext(g,s))}const c=r.isCallExpression(a)?h(a.getExpression()):void 0,l=r.isCallExpression(a)&&r.isPropertyAccessExpression(c)&&c.getName()==="map"?h(a.getArguments()[0]):void 0,u=l===void 0?void 0:Ke(l);return u!==void 0&&u.length>0&&u.every(f=>f!==void 0&&this.isRootedInContext(f,s))}isIdentifierTainted(t){const s=t.getText();if(s==="arguments")return!0;const n=k(t),i=Ws(n);if(i!==void 0)return this.isSource(i);if(s==="args")return!0;if(n===void 0||!this.isInImpl(n))return!1;if(r.isFunctionDeclaration(n))return this.budget.memoized(n.compilerNode,()=>this.isTaintedValue(n,!1),this.verdicts);if(r.isBindingElement(n)&&this.walk.isCompromised(n))return!0;const o=r.isBindingElement(n)?n.getFirstAncestorByKind(d.VariableDeclaration):n;return r.isVariableDeclaration(o)&&this.isVariableTainted(o)}callChainVerdict(t,s){if(this.isContextRootedCombinator(t,s))return!0;const n=h(t.getExpression()),i=r.isPropertyAccessExpression(n)?n.getName():void 0;return i!==void 0&&Pn.has(i)?!1:i!==void 0&&wn.has(i)?this.isCallbackResultServerScoped(t,s)?void 0:!1:t.getArguments().some(a=>Ke(a)!==void 0)&&(i===void 0||!jd.has(i))?!1:void 0}isCallbackResultServerScoped(t,s){const n=(i,o=[])=>{const a=Mt(i),c=r.isIdentifier(a)?Ws(k(a)):void 0;return c!==void 0&&o.includes(c)?!0:this.isRootedInContext(i,s)||!this.isTaintedValue(i,!1)};return t.getArguments().every(i=>{const o=Ke(i);if(o===void 0)return!Hd(i)&&n(i);const a=h(i),c=r.isArrowFunction(a)||r.isFunctionExpression(a)?a.getParameters():[];return o.every(l=>l===void 0||n(l,c))})}isRootedInContext(t,s){const n=rr(t,u=>this.callChainVerdict(u,s)),i=n.root;if(n.verdict!==void 0)return n.verdict;if(Gn(i,this.scope.context))return!0;const o=r.isIdentifier(i)?k(i):void 0,a=r.isBindingElement(o)?o.getFirstAncestorByKind(d.VariableDeclaration):o,c=ie(a)&&this.isInImpl(a)?a.getInitializer():void 0,l=r.isBindingElement(o)?o:a;return s>0&&c!==void 0&&(r.isBindingElement(l)||r.isVariableDeclaration(l))&&!this.walk.isCompromised(l)&&this.isRootedInContext(c,s-1)}isSource(t){const{impl:s,parameter:n}=this.scope;return t.compilerNode===n?.compilerNode?!0:t.getParent()!==s&&this.isInImpl(t)&&(this.budget.memoized(t.compilerNode,()=>this.flowsIntoTainted(t),this.verdicts)||this.walk.isCompromised(t))}isVariableTainted(t){return this.budget.memoized(t.compilerNode,()=>{const s=t.getParent().getParent();if(r.isCatchClause(t.getParent())||this.walk.isCompromised(t))return!0;if(r.isForOfStatement(s)||r.isForInStatement(s))return this.isTaintedValue(s.getExpression(),!0);const n=t.getInitializer(),i=_t(t);if(n===void 0||i)return!0;if(this.isRootedInContext(n,pt))return!1;if(this.variableDepth>=pt)return this.budget.cut();this.variableDepth+=1;try{return this.isTaintedValue(n,!1)}finally{this.variableDepth-=1}},this.verdicts)}}const qs=new WeakMap,Qd=e=>{const t=qs.get(e.impl.compilerNode);if(t!==void 0)return t;const s=new Yd(e);return qs.set(e.impl.compilerNode,s),s},Xd=new Set(["accountId","authorId","createdBy","createdById","organizationId","orgId","ownerId","tenantId","updatedBy","userId","workspaceId"]),Jd=new Set(["insert","insertManyUnsafe","patch","replace"]),Zd=e=>{if(!r.isPropertyAccessExpression(e))return;const t=e.getName();return Jd.has(t)&&pr(e.getExpression())?t:void 0},eu=(e,t)=>{if(t!=="insertManyUnsafe")return r.isObjectLiteralExpression(e)?[e]:[];if(!r.isArrayLiteralExpression(e))return[];const s=[];for(const n of e.getElements())r.isObjectLiteralExpression(n)&&s.push(n);return s},tu=(e,t)=>{const s=Sn(e);return s?.member===t?h(s.object):void 0},js=(e,t)=>r.isIdentifier(e)&&k(e)?.compilerNode===t.compilerNode,ti=(e,t,s,n=1)=>{const i=tu(e,s);if(i!==void 0)return js(i,t);const o=r.isIdentifier(e)?k(e):void 0;if(r.isBindingElement(o)){const c=o.getParent(),l=c.getParent();return o.getDotDotDotToken()===void 0&&ce(o)===s&&r.isObjectBindingPattern(c)&&(l.compilerNode===t.compilerNode||ie(l)&&js(h(l.getInitializer()),t))}const a=ie(o)?o.getInitializer():void 0;return n>0&&a!==void 0&&ti(a,t,s,n-1)},kt=e=>{const t=h(e)??e;return r.isConditionalExpression(t)?[...kt(t.getWhenTrue()),...kt(t.getWhenFalse())]:[t]},su=(e,t,s)=>{const n=[],i=s===void 0?void 0:Qd(s);for(const o of e.getProperties()){let a,c;if(r.isPropertyAssignment(o)?(a=y(o),c=o.getInitializer()):r.isShorthandPropertyAssignment(o)&&(a=y(o),c=o.getNameNode()),a===void 0||c===void 0||!Xd.has(a))continue;const l=kt(c).filter(f=>i===void 0?W(f)&&!mr(f):i.isTaintedValue(f,!0));if(l.length>0){const f=t.ownerField===a&&s?.pristine===!0&&ti(c,s.parameter,a),g=l.every(m=>kd(t.call,m));n.push({field:a,file:t.relativePath,line:t.call.getStartLineNumber(),method:t.method,scope:t.scope,...f&&{ownerScoped:!0},...g&&{guarded:!0}})}}return n},nu=(e,t,s)=>{const n=Zd(e.getExpression()),i=n===void 0?void 0:e.getArguments()[1];if(n===void 0||i===void 0)return[];const o=eu(i,n);if(o.length===0)return[];const a=x(e),c=bd(e),l={call:e,method:n,ownerField:c===void 0?void 0:s(c.mutatorName),relativePath:t,scope:a};return o.flatMap(u=>su(u,l,c))},iu=(e,t,s=[],n=[])=>{const i=new Map(n.map(c=>[`${c.filePath}:${c.exportName}`,c.owner])),o=w(e,t,(c,l)=>nu(c,l,u=>i.get(`${l}:${u}`))),a=new Map(s.map(c=>[`${c.filePath}:${c.exportName}`,c.adminOnly===!0]));return Kt(o,s).map(c=>ur(c.scope)?.every(f=>a.get(`${c.file}:${f}`)===!0)===!0?{...c,adminOnly:!0}:c)},ru=new Set(["createAutumnAdapter","createDodoPaymentsAdapter","createPolarAdapter","createStripeAdapter"]),ou=e=>e&&r.isNumericLiteral(e)?Number(e.getText()):void 0,au=e=>{const t=z(e,"webhookToleranceSeconds");return t&&r.isPropertyAssignment(t)?ou(t.getInitializer()):void 0},cu=(e,t)=>{const s=b(e.getExpression());if(s===void 0||!ru.has(s))return;const[n]=e.getArguments(),i=n&&r.isObjectLiteralExpression(n)?au(n):void 0;return{callee:s,scope:x(e),file:t,line:e.getStartLineNumber(),...i===void 0?{}:{toleranceSeconds:i}}},lu=(e,t)=>w(e,t,cu),du=new Map([["defineQueue",0],["defineSubscription",1],["defineWorkflow",0]]),uu=e=>{const t=e.getExpression();return r.isIdentifier(t)?t.getText():void 0},fu=(e,t)=>{const s=e.getArguments()[t];if(!s||!r.isObjectLiteralExpression(s))return;const n=z(s,"handler");if(n===void 0||!r.isPropertyAssignment(n))return;const i=n.getInitializer();if(i&&(r.isArrowFunction(i)||r.isFunctionExpression(i)))return i},si=(e,t)=>{const s=e.getParameters()[t]?.getNameNode();return s&&r.isIdentifier(s)?s.getText():void 0},ni=(e,t)=>e===t||e.startsWith(`${t}.`),ii=e=>{const t=e.getDescendantsOfKind(d.PropertyAccessExpression);return r.isPropertyAccessExpression(e)&&t.push(e),t},Hs=e=>{const t=e.getParent();return r.isPropertyAccessExpression(t)&&t.getNameNode()===e||r.isPropertyAssignment(t)&&t.getNameNode()===e?!1:!(r.isBindingElement(t)&&t.getNameNode()===e)},ri=e=>{const t=e.getDescendantsOfKind(d.Identifier).filter(s=>Hs(s));return r.isIdentifier(e)&&Hs(e)&&t.push(e),t},gu=e=>{if(!r.isVariableDeclaration(e))return[];const t=e.getNameNode();return r.isIdentifier(t)?[t.getText()]:t.getDescendantsOfKind(d.BindingElement).map(s=>s.getName())},pu=e=>{const t=si(e,1);if(t===void 0)return[];const s=[`${t}.messages`];for(const n of e.getDescendantsOfKind(d.ForOfStatement)){if(n.getExpression().getText()!==`${t}.messages`)continue;const i=n.getInitializer(),o=r.isVariableDeclarationList(i)?i.getDeclarations()[0]?.getNameNode():void 0;o&&r.isIdentifier(o)&&s.push(`${o.getText()}.body`)}return s},mu=(e,t,s)=>{const n=t==="workflow"?[`${s}.params`]:pu(e),i=new Set,o=a=>ii(a).some(c=>n.some(l=>ni(c.getText(),l)))?!0:ri(a).some(c=>i.has(c.getText()));for(const a of e.getDescendantsOfKind(d.VariableDeclaration)){const c=a.getInitializer();if(c&&o(c))for(const l of gu(a))i.add(l)}return{names:i,prefixes:n}},hu=(e,t)=>ii(e).some(s=>t.prefixes.some(n=>ni(s.getText(),n)))?!0:ri(e).some(s=>t.names.has(s.getText())),vu=e=>{const t=or(e);return t===void 0?void 0:{exportName:String(t.at(-1)),file:t.slice(0,-1).join("/")}},Eu=(e,t,s)=>{const n=si(e,0);if(n===void 0)return[];const i=mu(e,t,n),o=new Set([n,...i.prefixes.filter(c=>c.endsWith(".body")).map(c=>c.slice(0,-5))]),a=[];for(const c of e.getDescendantsOfKind(d.CallExpression)){const l=c.getExpression();if(!r.isPropertyAccessExpression(l)||!An.has(l.getName())||!o.has(l.getExpression().getText()))continue;const u=c.getArguments()[1];if(!u||!hu(u,i))continue;const f=vu(c.getArguments()[0]);f!==void 0&&a.push({dispatchKind:t,file:s,scope:x(c),line:c.getStartLineNumber(),targetExport:f.exportName,targetFile:f.file})}return a},xu=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(d.CallExpression)){const i=uu(n),o=i===void 0?void 0:du.get(i);if(o===void 0)continue;const a=fu(n,o);a!==void 0&&s.push(...Eu(a,i==="defineWorkflow"?"workflow":"queue",t))}return s},Su=(e,t)=>{const s=[];for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...xu(i,P(t,n)))}return s},Gs={dbRateLimit:"usesRateLimit",emailGateMiddleware:"usesEmailGate",mask:"usesMask",rateLimit:"usesRateLimit",rls:"usesRls",verifyTurnstileMiddleware:"usesCaptcha"},Ys=new Set(["account","credential","member","passkey","session","user"]),Au=e=>e.replaceAll(/[-_]/gu," ").replaceAll(/([a-z0-9])([A-Z])/gu,"$1 $2").split(" ").filter(Boolean).map(t=>t.toLowerCase()),yu=e=>{const s=Au(e).at(-1);if(!s)return!1;const n=s.endsWith("s")?s.slice(0,-1):s;return Ys.has(s)||Ys.has(n)},bu=e=>{const t=e.replaceAll(/[^a-z0-9]/giu,"").toLowerCase();return t.endsWith("email")||t.endsWith("emailaddress")},Nu=(e,t)=>{const{objects:s,opaque:n}=Ut(e,t);return La(s).some(i=>bu(i))?!0:n?void 0:!1},Pu=e=>{const t=e.getArguments()[0];return!t||!r.isObjectLiteralExpression(t)?{usesCaptcha:!1,usesRateLimit:!1}:{usesCaptcha:!!z(t,"captcha"),usesRateLimit:!!z(t,"rateLimit")}},wu=e=>{if(r.isCallExpression(e))return e;if(!r.isIdentifier(e))return;const s=e.getSourceFile().getVariableDeclaration(e.getText())?.getInitializer();return s&&r.isCallExpression(s)?s:void 0},ze={usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},Iu=e=>{const t=wu(e),s=t?b(t.getExpression()):void 0;if(t&&s==="protectPublic"){const n=Pu(t);return{...ze,usesCaptcha:n.usesCaptcha,usesRateLimit:n.usesRateLimit}}return s!==void 0&&s in Gs?{...ze,[Gs[s]]:!0}:ze},Cu=e=>{const t={...ze};let s=e;for(;r.isCallExpression(s);){const n=s.getExpression();if(!r.isPropertyAccessExpression(n))break;const i=n.getName()==="use"?s.getArguments()[0]:void 0;if(i){const o=Iu(i);t.usesCaptcha||=o.usesCaptcha,t.usesEmailGate||=o.usesEmailGate,t.usesMask||=o.usesMask,t.usesRateLimit||=o.usesRateLimit,t.usesRls||=o.usesRls}s=n.getExpression()}return t},Tu=new Set(["insert","insertMany","insertManyUnsafe","replace"]),Ou=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!Tu.has(t.getName()))return!1;const s=t.getExpression();if(!_(s))return!1;const i=e.getArguments()[0];return!i||!(r.isStringLiteral(i)||r.isNoSubstitutionTemplateLiteral(i))?!1:yu(i.getLiteralText())},ku=new Set(["create","publish","publishBatch","runAfter","runAt","send","sendBatch"]),Qs=new Set(["queues","scheduler","topics","workflows"]),Ru=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!ku.has(t.getName()))return!1;let s=t.getExpression();for(;r.isCallExpression(s)||r.isElementAccessExpression(s)||r.isPropertyAccessExpression(s);){if(r.isPropertyAccessExpression(s)&&Qs.has(s.getName())&&hr(s.getExpression()))return!0;s=s.getExpression()}const n=zt(s);return n?.length===1&&Qs.has(n[0]??"")},Fu=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||t.getName()!=="insertManyUnsafe")return!1;const s=t.getExpression();return _(s)},oi=new Set(["generateObject","generateText","streamObject","streamText"]),Lu=e=>{const t=b(e.getExpression());return t!==void 0&&oi.has(t)},Du=e=>{const t=b(e.getExpression());if(t===void 0||!oi.has(t))return!1;const s=e.getArguments()[0];return!s||!r.isObjectLiteralExpression(s)||s.getProperties().some(n=>r.isSpreadAssignment(n))?!1:!z(s,"maxOutputTokens")},Mu=new Set(["log","span","trace"]),_u=new Set(["ai"]),Ku=new Set(["email","mail"]),zu=new Set(["ai","browser","fetch","mail","notify","queues","sql","storage","topics","workflows"]),mt=(e,t)=>[...t].some(s=>Ye(e,s).length>0),ai=new Set([d.ArrowFunction,d.FunctionDeclaration,d.FunctionExpression,d.GetAccessor,d.MethodDeclaration,d.SetAccessor]),Bu=new Set(["every","filter","flatMap","forEach","map","some"]),$u=new Set(["all","allSettled","race"]),ci=e=>{const t=e.getParent();if(!t||!r.isCallExpression(t)||!t.getArguments().includes(e))return;const s=t.getExpression();if(!r.isPropertyAccessExpression(s))return;const n=s.getName();if(Bu.has(n))return t;const i=s.getExpression();if(r.isIdentifier(i)&&i.getText()==="Promise"&&$u.has(n))return t},Vu=e=>{let t=e.getParent();for(;t;){if(r.isTryStatement(t)){const s=t.getTryBlock();if(e.getPos()>=s.getPos()&&e.getEnd()<=s.getEnd())return!0}if(ai.has(t.getKind())){const s=ci(t);if(!s)return!1;t=s;continue}t=t.getParent()}return!1},Uu=e=>{let t=e.getParent();for(;t!==void 0;){if(r.isCallExpression(t)&&t.getExpression().getText()==="Promise.allSettled")return!0;if(ai.has(t.getKind())){if(t=ci(t),t===void 0)return!1;continue}t=t.getParent()}return!1},Wu=e=>{const t=e.getFirstAncestor(u=>r.isArrowFunction(u)||r.isFunctionExpression(u)),s=t?.getParent();if(!t||!r.isCallExpression(s)||!s.getArguments().includes(t))return!1;const n=s.getExpression();if(!r.isIdentifier(n))return!1;const i=n.getSymbol(),o=i?.getAliasedSymbol()?.getValueDeclaration()??i?.getValueDeclaration(),a=r.isVariableDeclaration(o)?o.getInitializer():o;if(!r.isArrowFunction(a)&&!r.isFunctionExpression(a)&&!r.isFunctionDeclaration(a))return!1;const c=s.getArguments().indexOf(t),l=a.getParameters()[c]?.getName();return l===void 0?!1:a.getDescendantsOfKind(d.TryStatement).some(u=>{const f=u.getTryBlock().getDescendantsOfKind(d.CallExpression).some(m=>{const E=m.getExpression();return r.isIdentifier(E)&&E.getText()===l&&r.isAwaitExpression(m.getParent())}),g=u.getCatchClause();return f&&g!==void 0&&g.getDescendantsOfKind(d.ThrowStatement).length>0})},qu=e=>{let t=e;for(;;){const s=t.getParent();if(!r.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(!r.isCallExpression(n)||n.getExpression()!==s)return!1;t=n}},ju=e=>{let t=e;for(;;){const s=t.getParent();if(r.isPropertyAccessExpression(s)&&s.getExpression()===t){t=s;continue}return r.isCallExpression(s)&&s.getExpression()===t?s:void 0}},Hu=e=>{let t=!1,s=!0;for(const n of[...zu].flatMap(i=>Ye(e,i))){const i=ju(n);i&&(t=!0,!Vu(i)&&!qu(i)&&!Wu(i)&&!Uu(i)&&(s=!1))}return{handlesErrors:t&&s,reachesOutbound:t}},Gu=e=>e.getDescendantsOfKind(d.ThrowStatement).some(t=>{const s=t.getExpression();if(!r.isNewExpression(s))return!1;const n=s.getExpression();return r.isIdentifier(n)&&n.getText()==="Error"}),Xs="lunora-advisor-exempt",Yu=/^[\s*/]+/u,Qu=/[\w-]/u,Xu=e=>{const s=(e.getFirstAncestorByKind(d.VariableStatement)??e).getLeadingCommentRanges().map(n=>n.getText()).join(`
|
|
2
|
+
`);for(const n of s.split(`
|
|
3
|
+
`)){const i=n.replace(Yu,"");if(!i.startsWith(Xs))continue;const o=i.slice(Xs.length);if(Qu.test(o.charAt(0)))continue;const a=o.indexOf("--");return{exempt:!0,exemptReason:(a===-1?"":o.slice(a+2).split("*")[0]??"").trim()}}return{exempt:!1,exemptReason:""}},Ju=e=>{const[t]=e.getArguments();if(t){if(r.isObjectLiteralExpression(t)){const s=z(t,"handler");return s?r.isPropertyAssignment(s)?s.getInitializer():r.isShorthandPropertyAssignment(s)?s.getNameNode():r.isMethodDeclaration(s)?s:void 0:void 0}return t}},Zu=(e,t)=>{const s=Ju(t);if(!s)return;if(r.isArrowFunction(s)||r.isFunctionExpression(s)||r.isMethodDeclaration(s))return e;if(!r.isIdentifier(s))return;const n=s.getSourceFile(),i=s.getText(),o=n.getVariableDeclaration(i)?.getInitializer();return o&&(r.isArrowFunction(o)||r.isFunctionExpression(o))?o:n.getFunction(i)},ef=e=>{let t=!1,s=!1,n=!1,i=!1,o=!1;for(const l of e.getDescendantsOfKind(d.CallExpression))if(Ou(l)&&(o=!0),Ru(l)&&(t=!0),Fu(l)&&(i=!0),Lu(l)&&(s=!0),Du(l)&&(n=!0),o&&t&&i&&n)break;const{handlesErrors:a,reachesOutbound:c}=Hu(e);return{callsMail:mt(e,Ku),emitsEvent:mt(e,Mu),fanOut:t,handlesErrors:a,reachesOutbound:c,runsAiGeneration:s||mt(e,_u),throwsBareError:Gu(e),unboundedAiGeneration:n,usesInsertManyUnsafe:i,writesUserTable:o}},tf=(e,t)=>{const s=e.getInitializer();if(!s||!r.isCallExpression(s))return;const n=te(s);if(!n||n.kind!=="query"&&n.kind!=="mutation"&&n.kind!=="action")return;const i=n.receiver?Cu(n.receiver):{usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},o=Zu(e,s);return{...o?ef(o):{},...Xu(e),...i,analyzableBody:o!==void 0,exportName:q(e)??e.getName(),file:t,hasEmailArg:Nu(s,n.receiver),kind:n.kind,visibility:n.visibility}},sf=(e,t)=>{const s=[];for(const n of X(e)){const i=tf(n,t);i&&s.push(i)}return s},nf=(e,t)=>{const s=[];for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...sf(i,P(t,n)))}return s},rf=new Set(["dbRateLimit","rateLimit"]),of=e=>r.isArrowFunction(e)?e.getBody():e,af=e=>{if(!r.isArrowFunction(e))return;const t=e.getParameters()[0]?.getNameNode();return t!==void 0&&r.isIdentifier(t)?t:void 0},li=e=>{const t=e.getParent();return r.isPropertyAccessExpression(t)&&t.getExpression()===e&&t.getName()==="args"},di=(e,t)=>{const s=t.getSymbol();return s===void 0?[]:e.getDescendantsOfKind(d.Identifier).filter(n=>{if(n.getSymbol()!==s)return!1;const i=n.getParent();return!(r.isPropertyAccessExpression(i)&&i.getNameNode()===n)})},cf=(e,t)=>W(e)||t!==void 0&&di(e,t).some(s=>li(s)),lf=(e,t)=>t===void 0?le(e):di(e,t).some(s=>!li(s)),df=(e,t)=>{const s=b(e.getExpression());if(s===void 0||!rf.has(s))return;const n=C(xn(e.getArguments()[2]),"key");if(!n)return;const i=of(n),o=af(n);if(!(!cf(i,o)||lf(i,o)))return{callee:s,scope:x(e),file:t,limitName:En(e),line:e.getStartLineNumber()}},uf=(e,t)=>w(e,t,df),ff=new Set(["findFirst","findFirstOrThrow","findMany","findUnique","get"]),gf=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!ff.has(t.getName()))return;const s=t.getExpression();if(_(s)){const n=e.getArguments()[0];return n&&r.isStringLiteral(n)?n.getLiteralText():""}if(r.isPropertyAccessExpression(s)&&_(s.getExpression()))return s.getName()},pf=e=>{let t=e;for(;r.isCallExpression(t);){const s=t.getExpression();if(!r.isPropertyAccessExpression(s))return;if(s.getName()==="query"&&_(s.getExpression())){const n=t.getArguments()[0];return n&&r.isStringLiteral(n)?n.getLiteralText():""}t=s.getExpression()}},mf=e=>{let t=h(e)??e;for(;r.isAwaitExpression(t);)t=h(t.getExpression())??t.getExpression();return t},ui=(e,t=!1)=>{const s=mf(e);if(r.isIdentifier(s)){if(t)return;const n=Q(s);return n===void 0?void 0:ui(n,!0)}if(r.isCallExpression(s))return gf(s)??pf(s)},hf=e=>{const t=e.getBody();if(!r.isBlock(t))return[t];const s=[];for(const n of e.getDescendantsOfKind(d.ReturnStatement)){const i=n.getFirstAncestor(a=>r.isArrowFunction(a)||r.isFunctionExpression(a)||r.isFunctionDeclaration(a)),o=n.getExpression();i===e&&o!==void 0&&s.push(o)}return s},vf=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!r.isCallExpression(s))return[];const n=te(s);if(n?.kind!=="query")return[];const i=Vn(s);if(i===void 0)return[];const o=n.receiver!==void 0&&xr(n.receiver,"output"),a=n.receiver!==void 0&&In(n.receiver,"use","mask"),c=new Set,l=[];for(const u of hf(i)){const f=ui(u);f===void 0||c.has(f)||(c.add(f),l.push({exportName:q(e)??e.getName(),file:t,line:u.getStartLineNumber(),table:f,usesMask:a,usesOutput:o,visibility:n.visibility}))}return l},Ef=(e,t)=>{const s=[];for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=P(t,n);for(const a of X(i))s.push(...vf(a,o))}return s},xf=e=>{if(!e||!r.isObjectLiteralExpression(e))return[];const t=[];for(const s of e.getProperties())(r.isPropertyAssignment(s)||r.isShorthandPropertyAssignment(s)||r.isMethodDeclaration(s)||r.isGetAccessorDeclaration(s))&&t.push(y(s));return t},Sf=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&r.isCallExpression(s)?te(s):void 0;if(!n)return[];const i=[];for(const o of e.getDescendantsOfKind(d.CallExpression)){const a=Tn(o);if(a===void 0)continue;const c=xf(C(a.options,"with"));c.length!==0&&i.push({exportName:q(e)??e.getName(),file:t,line:o.getStartLineNumber(),parentTable:a.table,relations:c,visibility:n.visibility})}return i},Af=(e,t)=>{const s=[];for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=P(t,n);for(const a of X(i))s.push(...Sf(a,o))}return s},U=(e,t)=>`${e}:${t}`,Js=(e,t,s,n)=>s===void 0?void 0:{endLine:e.getEndLineNumber(),exported:n,file:t,name:s,node:e,startLine:e.getStartLineNumber()},yf=(e,t)=>[...ne(e,t,d.FunctionDeclaration,(s,n)=>s.getParent().getKind()===d.SourceFile?Js(s,n,s.getName(),s.isExported()):void 0),...ne(e,t,d.VariableDeclaration,(s,n)=>{const i=s.getVariableStatement();return i?.getParent().getKind()===d.SourceFile?Js(i,n,s.getName(),i.isExported()):void 0})],bf=(e,t,s)=>{const n=e.getExpression();if(!r.isIdentifier(n))return;const i=n.getSymbol(),o=(i?.getAliasedSymbol()??i)?.getDeclarations()[0];if(o===void 0||!(r.isFunctionDeclaration(o)||r.isVariableDeclaration(o)))return;const a=o.getName(),c=P(s,o.getSourceFile().getFilePath());return a===void 0?void 0:t.get(U(c,a))},Nf=e=>`${e.table}|${e.method}|${e.fields?.join(",")??"*"}`,Pf=(e,t)=>{const s=new Map(e.map(n=>[U(n.file,n.name),new Map]));for(const n of t){const i=e.find(o=>o.file===n.file&&o.startLine<=n.line&&n.line<=o.endLine);i!==void 0&&n.table!==""&&s.get(U(i.file,i.name))?.set(Nf(n),{fields:n.fields,method:n.method,table:n.table})}return s},wf=(e,t,s)=>e.node.getDescendantsOfKind(d.CallExpression).map(n=>bf(n,t,s)).filter(n=>n!==void 0),If=(e,t,s,n)=>{for(const i of e){const o=i.scope.kind==="module"?void 0:t.get(U(i.file,i.scope.name)),a=i.target===void 0?void 0:s.get(i.target);i.kind==="call"&&o!==void 0&&a!==void 0&&n.get(U(o.file,o.name))?.push(a)}},Cf=(e,t,s)=>{const n=new Map(e.map(a=>[U(a.file,a.name),a])),i=new Map(e.map(a=>[`${$t(a.file)}:${a.name}`,a])),o=new Map(e.map(a=>[U(a.file,a.name),wf(a,n,t)]));return If(s,n,i,o),o},Tf=(e,t)=>{let s=!1;for(const[n,i]of t??[])e!==void 0&&!e.has(n)&&(e.set(n,i),s=!0);return s},Of=(e,t,s)=>{let n=!0;for(;n;){n=!1;for(const i of e)for(const o of s.get(U(i.file,i.name))??[])Tf(t.get(U(i.file,i.name)),t.get(U(o.file,o.name)))&&(n=!0)}},kf=(e,t,s,n)=>{const i=yf(e,t),o=Pf(i,s);return Of(i,o,Cf(i,t,n)),i.filter(a=>a.exported).flatMap(a=>[...o.get(U(a.file,a.name))?.values()??[]].map(c=>({...c,exportName:a.name,file:a.file})))},We=e=>{if(r.isStringLiteral(e)||r.isNoSubstitutionTemplateLiteral(e))return e.getLiteralText();if(r.isBinaryExpression(e)&&e.getOperatorToken().getKind()===d.PlusToken){const t=We(e.getLeft()),s=We(e.getRight());return t!==void 0&&s!==void 0?t+s:void 0}},Rf=e=>{let t=e,s=t.getParent();for(;s!==void 0&&r.isBinaryExpression(s)&&s.getOperatorToken().getKind()===d.PlusToken;)t=s,s=t.getParent();return t!==e&&We(t)!==void 0},Ff=e=>{const t=e.getParent();if(t!==void 0){if(r.isVariableDeclaration(t)||r.isPropertyAssignment(t)||r.isPropertySignature(t))return y(t);if(r.isBinaryExpression(t)&&t.getOperatorToken().getKind()===d.EqualsToken)return t.getLeft().getText()}},Lf=(e,t,s)=>zr(e)?!ar(s)&&Br(Ff(t)):!0,Df=(e,t)=>{const s=[],n=[...e.getDescendantsOfKind(d.BinaryExpression),...e.getDescendantsOfKind(d.StringLiteral),...e.getDescendantsOfKind(d.NoSubstitutionTemplateLiteral)],i=new Set;for(const o of n){if(Rf(o))continue;const a=We(o);if(a===void 0)continue;const c=_r(a);if(c===void 0||!Lf(c,o,t))continue;const l=o.getStartLineNumber(),u=`${String(l)}:${c}`;i.has(u)||(i.add(u),s.push({file:t,kind:c,line:l,preview:Kr(a)}))}return s},Mf=(e,t)=>{const s=[];for(const n of A(t,{includeSkipped:!0})){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Df(i,P(t,n)))}return s},_f=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&r.isCallExpression(s)?te(s):void 0;if(!n)return[];const i=[];for(const o of e.getDescendantsOfKind(d.CallExpression)){const a=Tn(o);if(a===void 0)continue;const c=C(a.options,"includeDeleted");if(c===void 0)continue;const l=r.isTrueLiteral(c),u=!l&&W(c);!l&&!u||i.push({exportName:q(e)??e.getName(),file:t,fromArgs:u,hardcodedTrue:l,line:o.getStartLineNumber(),table:a.table,visibility:n.visibility})}return i},Kf=(e,t)=>{const s=[];for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=P(t,n);for(const a of X(i))s.push(..._f(a,o))}return s},zf=new Set(["query","unsafe"]),Bf=e=>!r.isPropertyAccessExpression(e)||!zf.has(e.getName())?!1:Y(e.getExpression(),["sql"]),$f=e=>r.isBinaryExpression(e)||r.isTemplateExpression(e),Vf=(e,t)=>{if(!Bf(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!$f(s)))return{file:t,line:s.getStartLineNumber(),scope:x(e)}},Uf=(e,t)=>w(e,t,Vf),Wf=[["convex",["convex","@convex-dev/"]],["supabase",["@supabase/"]],["firebase",["firebase","@firebase/","firebase-admin"]]],qf=e=>{for(const[t,s]of Wf)for(const n of s)if(e===n||e.startsWith(n.endsWith("/")?n:`${n}/`))return t},jf=(e,t)=>{const s=[];for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const o of i.getImportDeclarations()){const a=o.getModuleSpecifierValue(),c=qf(a);c!==void 0&&s.push({file:P(t,n),line:o.getStartLineNumber(),moduleSpecifier:a,platform:c})}}return s},Hf=new Set(["createMultipartUpload","delete","download","generateUploadUrl","get","getMetadata","getPresignedUrl","getSignedUrl","getUrl","head","put","resumeMultipartUpload","store","upload"]),Gf=(e,t,s=[])=>{const n=Je(e,t,{argIndex:0,matchReceiver:i=>i==="ctx.storage"||i.startsWith("ctx.storage."),methods:Hf,requireUnmodifiedReach:!0});return Kt(n,s)},Yf=new Map([["generateUploadUrl",1],["getPresignedUrl",1],["getSignedUrl",1],["store",2],["upload",2]]),Qf=e=>e&&r.isNumericLiteral(e)?Number(e.getText()):void 0,Xf=e=>{if(e===void 0)return{analyzable:!0,presentKeys:[]};if(!r.isObjectLiteralExpression(e))return{analyzable:!1,presentKeys:[]};const t=[];let s,n=!1;for(const i of e.getProperties()){if(r.isSpreadAssignment(i)){n=!0;continue}if(r.isPropertyAssignment(i)){const o=y(i);t.push(o),o==="expiresInSeconds"&&(s=Qf(i.getInitializer()));continue}(r.isShorthandPropertyAssignment(i)||r.isMethodDeclaration(i))&&t.push(y(i))}return{analyzable:!n,expiresInSeconds:s,presentKeys:t}},Jf=e=>{if(!r.isPropertyAccessExpression(e))return;const t=e.getName(),s=Yf.get(t);return s===void 0?void 0:Nn(e.getExpression(),i=>i==="ctx.storage"||i.startsWith("ctx.storage."))?{method:t,optionsIndex:s}:void 0},Zf=(e,t)=>{const s=Jf(e.getExpression());if(s!==void 0)return{scope:x(e),file:t,line:e.getStartLineNumber(),method:s.method,...Xf(e.getArguments()[s.optionsIndex])}},eg=(e,t)=>w(e,t,Zf),tg=e=>r.isDoStatement(e)||r.isForInStatement(e)||r.isForOfStatement(e)||r.isForStatement(e)||r.isWhileStatement(e),fi=e=>{const t=e.getLabel()?.getText(),s=i=>t!==void 0?r.isLabeledStatement(i)&&i.getLabel().getText()===t:tg(i)||r.isBreakStatement(e)&&r.isSwitchStatement(i);let n=e.getFirstAncestor(i=>re(i)||s(i));if(!(n===void 0||re(n))){for(;r.isContinueStatement(e)&&r.isLabeledStatement(n);)n=n.getStatement();return n}},jt=(e,t)=>S(e.getFirstAncestor(s=>S(s,t)||re(s)),t),sg=(e,t)=>S(e,t)||e.getFirstAncestor(s=>S(s,t))!==void 0,gi=(e,t)=>{if(r.isReturnStatement(e)||r.isThrowStatement(e))return S(e,t)||jt(e,t);if(r.isBreakStatement(e)||r.isContinueStatement(e)){const s=fi(e);return s!==void 0&&!sg(s,t)}return!1},pi=e=>[...r.isBreakStatement(e)||r.isContinueStatement(e)||r.isReturnStatement(e)||r.isThrowStatement(e)?[e]:[],...e.getDescendantsOfKind(d.BreakStatement),...e.getDescendantsOfKind(d.ContinueStatement),...e.getDescendantsOfKind(d.ReturnStatement),...e.getDescendantsOfKind(d.ThrowStatement)],ng=e=>pi(e).some(t=>gi(t,e)),ig=e=>{const t=r.isCallExpression(e)?e.getExpression():void 0;return r.isPropertyAccessExpression(t)&&t.getName()==="throwIfAborted"},rg=e=>pi(e).some(t=>gi(t,e)||r.isBreakStatement(t)&&S(fi(t),e))||e.getDescendantsOfKind(d.CallExpression).some(t=>ig(t)&&jt(t,e)),og=e=>e.getDescendantsOfKind(d.YieldExpression).some(t=>jt(t,e)),ag=e=>r.isDoStatement(e)||r.isWhileStatement(e)?e.getExpression():e.getCondition(),cg=e=>r.isDoStatement(e)?"do":r.isWhileStatement(e)?"while":"for",ht=(e,t)=>{const s=ag(e);if(!(s===void 0||r.isTrueLiteral(h(s)))||rg(e)||og(e))return;const i=x(e);if(!(i.kind==="module"&&e.getFirstAncestor(re)!==void 0))return{file:t,kind:cg(e),line:e.getStartLineNumber(),scope:i}},lg=(e,t)=>[...ne(e,t,d.WhileStatement,ht),...ne(e,t,d.ForStatement,ht),...ne(e,t,d.DoStatement,ht)].toSorted((s,n)=>s.file.localeCompare(n.file)||s.line-n.line),dg=new Set(["when","where"]),vt=new Set(["definePolicy","defineShape"]),ug=e=>{if(!r.isCallExpression(e))return;const t=e.getExpression();if(r.isPropertyAccessExpression(t)){const n=t.getName();return vt.has(n)?n:void 0}if(!r.isIdentifier(t))return;for(const n of t.getSymbol()?.getDeclarations()??[])if(r.isImportSpecifier(n)){const i=n.getNameNode().getText();return vt.has(i)?i:void 0}const s=t.getText();return vt.has(s)?s:void 0},fg=e=>r.isObjectLiteralExpression(e)&&e.getProperties().length===0,mi=e=>{if(e!==void 0){if(r.isReturnStatement(e)&&e.getExpression()===void 0||e.getKind()===d.UndefinedKeyword||e.getText()==="undefined")return"undefined";if(fg(e))return"empty-object";if(r.isParenthesizedExpression(e))return mi(e.getExpression())}},Ht=e=>e.getAncestors().find(t=>r.isArrowFunction(t)||r.isFunctionExpression(t)||r.isFunctionDeclaration(t)),gg=e=>e.getDescendantsOfKind(d.ReturnStatement).filter(t=>Ht(t)===e),hi=e=>e.getDescendantsOfKind(d.ConditionalExpression).filter(t=>Ht(t)===e),pg=e=>{const t=gg(e);return t.length>1?!0:t.some(s=>s.getFirstAncestorByKind(d.IfStatement)!==void 0)||hi(e).length>0},mg=e=>e.getDescendantsOfKind(d.IfStatement).filter(t=>Ht(t)===e),Rt=e=>e.getKind()===d.NullKeyword||e.getKind()===d.FalseKeyword||r.isIdentifier(e)&&e.getText()==="undefined"?!0:r.isNumericLiteral(e)?e.getLiteralValue()===0:r.isStringLiteral(e)&&e.getLiteralValue()==="",hg=(e,t)=>Rt(e)||Rt(t),vg=new Map([[d.EqualsEqualsEqualsToken,"positive"],[d.EqualsEqualsToken,"positive"],[d.ExclamationEqualsEqualsToken,"negative"],[d.ExclamationEqualsToken,"negative"]]),Zs=e=>!Rt(e)&&(r.isLiteralExpression(e)||e.getKind()===d.TrueKeyword),Eg=(e,t,s)=>{const n=vg.get(e);if(n!==void 0)return hg(t,s)?n==="positive"?"negative":"positive":Zs(t)||Zs(s)?void 0:n},Se=e=>{if(r.isParenthesizedExpression(e))return Se(e.getExpression());if(r.isPrefixUnaryExpression(e)&&e.getOperatorToken()===d.ExclamationToken)return"negative";if(r.isBinaryExpression(e)){const t=e.getOperatorToken().getKind(),s=Eg(t,e.getLeft(),e.getRight());if(s!==void 0)return s;if(t===d.AmpersandAmpersandToken||t===d.BarBarToken){const n=Se(e.getLeft()),i=Se(e.getRight());return n===i?n:"indeterminate"}}return r.isIdentifier(e)||r.isPropertyAccessExpression(e)||r.isElementAccessExpression(e)||r.isCallExpression(e)?"positive":"indeterminate"},en=e=>{if(e!==void 0){if(r.isReturnStatement(e))return e;if(r.isBlock(e)){const t=e.getStatements().at(-1);return t!==void 0&&r.isReturnStatement(t)?t:void 0}}},xg=e=>{if(e.getElseStatement()!==void 0)return;const t=e.getNextSiblingIfKind(d.ReturnStatement);return t!==void 0&&t.getNextSibling()===void 0?t:void 0},Sg=e=>r.isReturnStatement(e)?e.getExpression()??e:e,Ag=e=>{const t=[];for(const s of hi(e)){const n=Se(s.getCondition());n==="positive"?t.push(s.getWhenFalse()):n==="negative"&&t.push(s.getWhenTrue())}for(const s of mg(e)){const n=Se(s.getExpression());if(n==="indeterminate")continue;const i=n==="negative"?en(s.getThenStatement()):en(s.getElseStatement())??xg(s);i!==void 0&&t.push(Sg(i))}return t},yg=e=>{for(const t of e.getAncestors())if(r.isVariableDeclaration(t)){const s=t.getNameNode();if(r.isIdentifier(s))return s.getText()}return"<anonymous>"},bg=(e,t,s)=>{if(!r.isCallExpression(e))return[];const[n]=e.getArguments();if(!n||!r.isObjectLiteralExpression(n))return[];const i=[];for(const o of n.getProperties()){if(!r.isPropertyAssignment(o)||!dg.has(y(o)))continue;const a=o.getInitializer();if(!(!a||!(r.isArrowFunction(a)||r.isFunctionExpression(a)))&&pg(a))for(const c of Ag(a)){const l=mi(c);l!==void 0&&i.push({exportName:yg(e),file:s,form:l,key:y(o),line:c.getStartLineNumber(),owner:t})}}return i},Ng=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(d.CallExpression)){const i=ug(n);i!==void 0&&s.push(...bg(n,i,t))}return s},Pg=(e,t)=>{const s=[];for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Ng(i,P(t,n)))}return s},wg=new Set(["query","upsert","upsertMany","upsertNow"]),ge=new Set,Ig=e=>{if(!r.isPropertyAccessExpression(e))return;const t=e.getName();if(wg.has(t))return Y(e.getExpression(),["vectors"])?t:void 0},Gt=e=>{let t=e;for(;r.isParenthesizedExpression(t)||r.isAsExpression(t)||r.isSatisfiesExpression(t)||r.isNonNullExpression(t)||r.isTypeAssertion(t);)t=t.getExpression();return t},vi=e=>{const t=e.getParent();return r.isShorthandPropertyAssignment(t)&&t.getNameNode()===e?t.getValueSymbol():e.getSymbol()},Ei=e=>vi(e)?.getDeclarations()[0],Cg=e=>{const t=e.getParent();return r.isBindingElement(t)||(r.isPropertyAccessExpression(t)||r.isPropertyAssignment(t)||r.isVariableDeclaration(t)||r.isParameterDeclaration(t)||r.isMethodDeclaration(t))&&t.getNameNode()===e?!1:!r.isQualifiedName(t)||t.getLeft()===e},xi=e=>{let t=e;for(;t!==void 0&&(r.isBindingElement(t)||r.isObjectBindingPattern(t)||r.isArrayBindingPattern(t));)t=t.getParent();return t!==void 0&&r.isVariableDeclaration(t)?t:void 0},tn=(e,t,s)=>{const n=vi(e)?.compilerSymbol;if(n!==void 0&&t.has(n))return!0;if(s>0){const i=xi(Ei(e)),o=i!==void 0&&r.isVariableDeclaration(i)?i.getInitializer():void 0;if(o!==void 0)return Yt(o,t,s-1)}return W(e)},Yt=(e,t,s)=>{const n=Gt(e);return le(n)?!1:r.isIdentifier(n)?tn(n,t,s):W(n)?!0:n.getDescendantsOfKind(d.Identifier).some(i=>Cg(i)&&tn(i,t,s))},Si=e=>{const t=xi(Ei(e));return t!==void 0&&r.isVariableDeclaration(t)?t.getInitializer():void 0},ee=(e,t)=>{const s=Gt(e);if(r.isObjectLiteralExpression(s))return[s];if(r.isConditionalExpression(s))return[...ee(s.getWhenTrue(),t),...ee(s.getWhenFalse(),t)];if(r.isBinaryExpression(s)){const n=s.getOperatorToken().getKind();if(n===d.BarBarToken||n===d.QuestionQuestionToken||n===d.AmpersandAmpersandToken)return[...ee(s.getLeft(),t),...ee(s.getRight(),t)]}if(r.isIdentifier(s)&&t){const n=Si(s);return n===void 0?[]:ee(n,!1)}return[]},Tg=(e,t)=>{const s=ee(e,t);if(s.length===0)return{replaces:!0,sources:[e]};const n=s.map(o=>qe(o,!1)),i=n.flat();if(i.length!==0)return{replaces:n.every(o=>o.length>0),sources:i}},Og=e=>(r.isPropertyAssignment(e)||r.isShorthandPropertyAssignment(e))&&e.getName()==="namespace",kg=e=>r.isShorthandPropertyAssignment(e)?e.getNameNode():e.getInitializer()??e.getNameNode(),qe=(e,t)=>{let s=[];for(const n of e.getProperties())if(r.isSpreadAssignment(n)){const i=Tg(n.getExpression(),t);i!==void 0&&(s=i.replaces?i.sources:[...s,...i.sources])}else Og(n)&&(s=[kg(n)]);return s},Rg=e=>{if(!e||!(r.isArrowFunction(e)||r.isFunctionExpression(e)))return[];const t=e.getBody();return r.isBlock(t)?t.getDescendantsOfKind(d.ReturnStatement).filter(s=>s.getFirstAncestor(n=>r.isFunctionLikeDeclaration(n))===e).flatMap(s=>s.getExpression()??[]):[t]},Fg=e=>{if(!e||!(r.isArrowFunction(e)||r.isFunctionExpression(e)))return ge;const t=e.getParameters()[0]?.getNameNode();if(t===void 0)return ge;const s=r.isIdentifier(t)?[t]:t.getDescendantsOfKind(d.BindingElement).map(n=>n.getNameNode());return new Set(s.flatMap(n=>r.isIdentifier(n)?n.getSymbol()?.compilerSymbol??[]:[]))},Ft=(e,t=!0,s=ge)=>{const n=Gt(e);if(r.isIdentifier(n)){const o=t?Si(n):void 0;return o===void 0?[{node:n,parameters:s}]:Ft(o,!1,s)}if(r.isArrayLiteralExpression(n))return n.getElements().flatMap(o=>r.isSpreadElement(o)?Ft(o.getExpression(),t,s):ee(o,!0).flatMap(a=>qe(a,!0).map(c=>({node:c,parameters:s}))));const i=r.isCallExpression(n)?n.getExpression():void 0;if(r.isCallExpression(n)&&r.isPropertyAccessExpression(i)&&i.getName()==="map"){const o=n.getArguments()[0],a=Yt(i.getExpression(),ge,1)?Fg(o):ge;return Rg(o).flatMap(c=>ee(c,!0).flatMap(l=>qe(l,!0).map(u=>({node:u,parameters:a}))))}return[{node:n,parameters:s}]},Lg=(e,t)=>{const s=Ig(e.getExpression());if(s===void 0)return;const n=e.getArguments()[1];if(!(!n||!(s==="upsertMany"?Ft(n):ee(n,!0).flatMap(o=>qe(o,!0).map(a=>({node:a,parameters:ge})))).some(({node:o,parameters:a})=>Yt(o,a,1))))return{scope:x(e),file:t,line:e.getStartLineNumber(),method:s}},Dg=(e,t)=>w(e,t,Lg),Mg=(e,t,s)=>{const{callSites:n,containers:i,crons:o,functions:a,modules:c,mutators:l,queues:u,schema:f,shapes:g,wranglerVariables:m,workflows:E}=s;return er({adminRoutes:ca(e,t),aiRawRuns:va(e,t),aiToolSideEffects:Ca(e,t),argumentDerivedFetches:ka(e,t),argumentValidators:Ya(e,t),authApiCalls:Nr(e,t),authConfigs:rc(e,t),browserUrlAccesses:lc(e,t),callEdges:n.callEdges,configCalls:vc(e,t),containerKeyAccesses:xc(e,t),containerOverrides:Pc(e,t),containers:i,countReads:Oc(e,t,f.tables),cronTargets:o.flatMap(V=>V.functionPath===void 0?[]:[V.functionPath]),exportSinks:Lc(e,t),staleMigrationImports:jf(e,t),failOpenGuards:zc(e,t),flagReads:Wc(e,t),flagSecurityDefaults:Gc(e,t),geoIndexUsages:Xc(e,t),httpActionGuards:ll(e,t),httpHeaderWrites:xl(e,t),hyperdriveCalls:Pr(e,t),identityClaimReads:Ol(e,t),imageDeliveryUrlAccesses:Rl(e,t),inserts:n.inserts,kvKeyAccesses:Ll(e,t,a),mailRecipientAccesses:zl(e,t),maskProcedures:wr(e,t),maskStrategies:Vl(e,t),mutatorWrites:Gl(e,t),nondeterministicCalls:kr(e,t),normalizeIdAuthorizations:ld(e,t),notifyCalls:Fr(e,t),notifyConfig:Rr(e,t),mutators:l,ownerFieldWrites:iu(e,t,a,l),unrestrictedWhereBranches:Pg(e,t),paymentWebhooks:lu(e,t),privilegedDispatches:Su(e,t),procedureProtections:nf(e,t),queries:n.queries,queues:u,r2sqlCalls:Lr(e,t),ratelimitKeySelectors:uf(e,t),rawRowReturns:Ef(e,t),relationLoads:Af(e,t),rlsProcedures:Dr(e,t),schema:f,secretLiterals:Mf(e,t),modules:c,shapes:g,softDeleteReads:Kf(e,t),sqlInterpolations:Uf(e,t),storageKeyAccesses:Gf(e,t,a),storageUploads:eg(e,t),tableWrites:n.tableWrites,rowEffects:kf(e,t,n.tableWrites,n.callEdges),unboundedLoops:lg(e,t),vectorNamespaceAccesses:Dg(e,t),workflowCalls:n.workflowCalls,workflows:E,wranglerVariables:m})},_g=e=>({cacheKey:`advisor_accept_unused:${e.rule}:${e.file}:${e.exportName}`,categories:["SCHEMA"],description:"`advisor.accept` in `lunora.config.*` accepts a finding the advisor does not report as an error.",detail:`No ERROR \`${e.rule}\` in \`${e.file}\` for \`${e.exportName}\` — the acceptance no longer applies.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:e.exportName,file:e.file,rule:e.rule},name:"advisor_accept_unused",remediation:"Remove the entry, or correct the rule, file and export name it names.",title:"An accepted advisor finding matches no error"}),Kg=(e,t)=>{const s=new Set;return[...e.map(i=>{if(i.level!=="ERROR")return i;const o=t.find(a=>a.rule===i.name&&a.file===i.metadata.file&&a.exportName===i.metadata.exportName);return o===void 0?i:(s.add(o),{...i,detail:`Accepted: ${o.reason}. ${i.detail}`,level:"INFO",metadata:{...i.metadata,accepted:o.reason}})}),...t.filter(i=>!s.has(i)).map(i=>_g(i))]},zg=()=>({cacheKey:"advisor_accept_invalid",categories:["SCHEMA"],description:"`advisor.accept` in `lunora.config.*` is read by parsing the file, so every entry must be a literal.",detail:"`advisor.accept` is not an array of literal `{ rule, file, exportName, reason }` objects with non-empty strings, so codegen ignored all of it and every ERROR still fails the gate.",facing:"INTERNAL",level:"WARN",metadata:{},name:"advisor_accept_invalid",remediation:'Write `advisor: { accept: [{ rule: "owner_field_from_args_not_auth", file: "lunora/auth/team.ts", exportName: "addTeamMember", reason: "…" }] }` as literals on the config\'s default export.',title:"`advisor.accept` is not a list codegen can read, so no acceptance applies"}),Bg=e=>e.metadata.accepted!==void 0||e.name==="advisor_accept_unused"||e.name==="advisor_accept_invalid",sn={error:"ERROR",info:"INFO",warn:"WARN"},nn={ERROR:2,INFO:0,WARN:1},$g=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"}),Vg=(e,t)=>{const{advisor:s}=Cn(e);if(s===void 0||s.minSeverity===void 0&&s.unreadable!==!0)return[...t];const{minSeverity:n}=s,i=n!==void 0&&Object.hasOwn(sn,n)?sn[n]:void 0;return i===void 0?[...t,$g(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(o=>Bg(o)||nn[o.level]>=nn[i])},Ug=(e,t)=>{const{advisor:s}=Cn(e),n=Kg(t,s?.accept??[]);return Vg(e,s?.acceptUnreadable===!0?[...n,zg()]:n)},Wg={call:"function",enqueue:"queue",invoke:"service",publish:"topic",schedule:"function"},qg="crons",jg=Ur.replace(/\.ts$/u,""),fe=(e,t)=>`${$t(e)}:${t}`,Et=(e,t,s)=>t===""?{reason:`the ${s} is not a string literal`}:{to:`${e}:${t}`},Hg=e=>[...e.callEdges.map(t=>{const s=t.target===void 0?{reason:t.reason??"unreadable target"}:{to:`${Wg[t.kind]}:${t.target}`};return{file:t.file,kind:t.kind,line:t.line,scope:t.scope,...s}}),...e.queries.map(t=>({file:t.file,kind:"read",line:t.line,scope:t.scope,...Et("table",t.table,"table name")})),...[...e.inserts,...e.tableWrites].map(t=>({file:t.file,kind:"write",line:t.line,scope:t.scope,...Et("table",t.table,"written table")})),...e.workflowCalls.map(t=>({file:t.file,kind:"start",line:t.line,scope:t.scope,...Et("workflow",t.workflow,"workflow name")}))],Gg=e=>e.untracked===!0?"inside a helper only code outside any export calls":"inside a non-exported helper",Yg=e=>{const{scope:t}=e;switch(t.kind){case"export":return[{...e,exportName:t.name}];case"helper":return t.callers.length===0?[{...e,unattributed:Gg(t)}]:t.callers.map(s=>({...e,exportName:s}));default:return[{...e,unattributed:"at module scope"}]}},Qg=e=>Hg(e).flatMap(t=>Yg(t)),Xg=e=>[...e.queues.flatMap(t=>t.topic===void 0?[]:[{file:t.filePath,from:`topic:${t.topic}`,kind:"subscribe",line:0,to:`queue:${t.exportName}`}]),...e.crons.map(t=>{const s=t.workflow===void 0?void 0:`workflow:${t.workflow.exportName}`,n=t.functionPath===void 0?void 0:`function:${t.functionPath}`,i=s??n;return{file:qg,from:`cron:${t.name}`,kind:"trigger",line:0,...i===void 0?{reason:"the cron has no target"}:{to:i}}})],Jg=e=>new Map(e.flatMap(t=>t.tables.map(s=>[s,t.name]))),ve=(e,t)=>t===void 0?e:{...e,module:t},Zg=e=>{const t=new Map,s=new Map,n=Jg(e.modules),i=(c,l)=>{s.set(c,[...s.get(c)??[],l])},o=(c,l)=>{t.set(c.id,c),l!==void 0&&i(l,c.id)},a=(c,l)=>{c!==void 0&&i(fe(c.file,c.exportName),l)};for(const c of e.functions){const l=fe(c.filePath,c.exportName),u=[...Mr(c.filePath),c.exportName].join(".");o(ve({detail:c.kind,id:`function:${l}`,kind:"function",name:u},Fe(e.modules,c.filePath)),l)}for(const c of e.httpRoutes){const l=fe(c.filePath,c.exportName);o(ve({id:`http:${l}`,kind:"http",name:`${c.method} ${c.path}`},Fe(e.modules,c.filePath)),l)}for(const c of e.schema.tables)o(ve({id:`table:${c.name}`,kind:"table",name:c.name},n.get(c.name)));for(const c of e.queues){const l=c.topic===void 0?{}:{detail:"subscription"};o(ve({...l,id:`queue:${c.exportName}`,kind:"queue",name:c.exportName},Fe(e.modules,c.filePath)),fe(c.filePath,c.exportName)),a(c.handlerSite,`queue:${c.exportName}`)}for(const c of e.topics)o(ve({id:`topic:${c.exportName}`,kind:"topic",name:c.exportName},Fe(e.modules,c.filePath)));for(const c of e.workflows)o({id:`workflow:${c.exportName}`,kind:"workflow",name:c.exportName},fe(jg,c.exportName)),a(c.handlerSite,`workflow:${c.exportName}`);for(const c of e.crons)o({detail:c.cron,id:`cron:${c.name}`,kind:"cron",name:c.name});for(const c of e.services){const l=c.rpcEntrypoint===void 0?"fetch":"rpc";o({detail:c.entrypoint===void 0?l:`${l} · ${c.entrypoint}`,id:`service:${c.name}`,kind:"service",name:c.worker})}return{nodes:t,sites:s}},ep=e=>e==="default"?"the default export is not a registered function":`"${e}" is not a registered function`,tp=(e,t)=>"from"in e?[e.from]:"unattributed"in e?{reason:e.unattributed}:t.get(fe(e.file,e.exportName))??{reason:ep(e.exportName)},sp=(e,t,s)=>{if("reason"in e)return{reason:e.reason};const n=tp(e,t);if("reason"in n)return n;const{to:i}=e;return s.has(i)?{drawn:n.map(o=>({from:o,kind:e.kind,to:i}))}:{reason:`${i} is not declared`}},xt=e=>`${e.from}|${e.kind}|${e.to}`,np=e=>`${e.file}|${String(e.line)}|${e.kind}|${e.reason}`,ip=e=>{const{nodes:t,sites:s}=Zg(e),n=new Map,i=new Map;for(const o of[...Xg(e),...Qg(e)]){const a=sp(o,s,t);if("drawn"in a)for(const c of a.drawn)n.set(xt(c),c);else{const c={file:o.file,kind:o.kind,line:o.line,reason:a.reason};i.set(np(c),c)}}return{edges:[...n.values()].toSorted((o,a)=>xt(o).localeCompare(xt(a))),nodes:[...t.values()].toSorted((o,a)=>o.id.localeCompare(a.id)),modules:e.modules.map(o=>({...o.description===void 0?{}:{description:o.description},...o.installed===!0?{installed:!0}:{},...o.ownsFolder===!1?{ownsFolder:!1}:{},name:o.name,tables:[...o.tables]})),unresolved:[...i.values()].toSorted((o,a)=>o.file.localeCompare(a.file)||o.line-a.line),version:1}},rp=e=>`${jr}export const architecture = ${qr(e,"Record<string, unknown>")};
|
|
4
|
+
`,rn=(e,t="api")=>{const s=new Map;for(const n of e){const i=$t(n),o=s.get(i);if(o===void 0){s.set(i,n);continue}if(o!==n){const a=t==="api"?`the generated api.ts would declare "${i}" twice and the dispatch key "${i}:<fn>" would be ambiguous`:`the generated api.ts would declare "${i}" twice in HttpStreamsRef and again in the httpStreams object literal`;throw new G("INTERNAL",`@lunora/codegen: "${o}" and "${n}" both map to the ${t} namespace "${i}" — ${a}. Rename one file so the two differ by more than a non-identifier character (\`-\`, \`.\`, \`/\` and \`_\` all sanitize to \`_\`).`,{status:500})}}},op=(e,t={})=>{const{hasVectors:s=!0,scheduler:n=!1,storage:i=!1,usage:o}=t,a=[];e.tables.some(c=>kn(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=>Rn(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`"}),i&&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 o===void 0?[]:Gr)c.requiredPackage!==void 0&&o?.[c.key]===!0&&a.push({name:c.requiredPackage,reason:`\`ctx.${c.contextProperty??c.key}\` usage makes \`_generated/\` import \`${c.moduleSpecifier}\``});return a.filter((c,l)=>a.findIndex(u=>u.name===c.name)===l)},ap=(e,t,s={})=>{if(t===void 0)return;const n=op(e,s).filter(o=>!t.has(o.name));if(n.length===0)return;const i=n.map(o=>` - ${o.name} — ${o.reason}`).join(`
|
|
5
|
+
`);throw new G("INTERNAL",`@lunora/codegen: this schema's generated code imports packages the project does not declare:
|
|
6
|
+
${i}
|
|
7
|
+
|
|
8
|
+
Install them with your package manager, then re-run codegen.`)},cp="env.ts",lp=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineEnv";for(const s of t.getDeclarations())if(r.isImportSpecifier(s))return Qe(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineEnv":!1;return!1},dp=e=>{const t=e.getSymbol();if(!t)return!1;for(const s of t.getDeclarations()){if(!r.isNamespaceImport(s))continue;const n=s.getFirstAncestorByKind(d.ImportDeclaration);return n!==void 0&&Qe(n.getModuleSpecifierValue())}return!1},up=e=>{if(r.isIdentifier(e))return lp(e);if(r.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineEnv"&&r.isIdentifier(t)&&dp(t)}return!1},fp=e=>{const t=[];for(const s of e.getVariableDeclarations()){const n=s.getInitializer();if(n?.getKind()!==d.CallExpression||!up(n.getExpression()))continue;const o=s.getNameNode();if(!r.isIdentifier(o)){if(s.getVariableStatement()?.hasExportKeyword()!==!0)continue;throw Pe(o,"defineEnv exports must be plain named exports (no destructuring)")}const a=bn(s,"member");a!==void 0&&t.push({exportName:a})}return t},gp=(e,t)=>{const s=v(t,cp);if(!D(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s),i=fp(n);if(i.length!==0){if(i.length>1)throw Pe(n,`lunora/env.ts declares ${i.length.toString()} defineEnv() contracts (${i.map(o=>o.exportName).join(", ")}); exactly one is allowed`);return i[0]}},pp={defineLiveStream:"liveStreams",defineRoom:"typedWebSockets",defineWebSocket:"typedWebSockets"},mp=new Set(["allowedHosts","deniedHosts","interceptHttps"]),hp=(e,t)=>{const s=h(t);if(s===void 0||!r.isIdentifier(s))return s;const n=s.getText();return h(e.getDescendantsOfKind(d.VariableDeclaration).find(i=>i.getName()===n)?.getInitializer())},vp=(e,t)=>e!==void 0&&r.isObjectLiteralExpression(e)&&e.getProperties().some(s=>{if(r.isShorthandPropertyAssignment(s))return t.has(y(s));if(!r.isPropertyAssignment(s)||!t.has(y(s)))return!1;const n=h(s.getInitializer())?.getText();return n!=="false"&&n!=="undefined"}),Ep=new Set(["durable"]),xp=new Set(["rollback"]),Ai=e=>{const t=e.getExpression();return r.isPropertyAccessExpression(t)?t.getName():t.getText()},Sp=new Map([["defineContainer",{keys:mp,signal:"containerEgressPolicy"}],["defineStep",{keys:xp,signal:"workflowRollback"}],["stream",{keys:Ep,signal:"durableStreams"}]]),Ap=(e,t)=>{const s=Sp.get(Ai(t));if(s!==void 0)return t.getArguments().some(n=>vp(hp(e,n),s.keys))?s.signal:void 0},yp=(e,t)=>{const s={containerEgressPolicy:!1,durableStreams:!1,liveStreams:!1,secrets:!1,typedWebSockets:!1,workflowRollback:!1};for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.secrets||(s.secrets=Zr(i).has("secrets"));for(const o of i.getDescendantsOfKind(d.CallExpression)){const a=Ap(i,o);a!==void 0&&(s[a]=!0);const c=pp[Ai(o)];c!==void 0&&(s[c]=!0)}if(Object.values(s).every(Boolean))break}return s},bp="createWorker",Np="extend",on=e=>e!==void 0&&(r.isStringLiteral(e)||r.isNoSubstitutionTemplateLiteral(e))?e.getLiteralValue():void 0,an=e=>{const t=[],s=on(C(e,"backupCron"));s!==void 0&&t.push(s);const n=C(e,"crons");if(n===void 0||!r.isObjectLiteralExpression(n))return t;for(const i of n.getProperties()){if(!r.isPropertyAssignment(i)&&!r.isMethodDeclaration(i))continue;const o=on(i.getNameNode());o!==void 0&&t.push(o)}return t},Pp=e=>{const t=b(e.getExpression()),[s]=e.getArguments();if(s===void 0)return[];if(t===bp)return r.isObjectLiteralExpression(s)?an(s):[];if(t!==Np||!(r.isArrowFunction(s)||r.isFunctionExpression(s)))return[];const n=vn(s.getBody());return n===void 0?[]:an(n)},wp=(e,t)=>{const s=[];for(const{filePath:n}of He(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const o of i.getDescendantsOfKind(d.CallExpression))s.push(...Pp(o))}return[...new Set(s)]},yi=e=>{if(e.kind==="id")return e.tableName;if(!(e.kind!=="array"&&e.kind!=="optional"))return e.inner===void 0?void 0:yi(e.inner)},Ip=e=>{const t=new Set(e.tables.map(s=>s.name));return e.tables.some(s=>Object.values(s.shape).some(n=>{const i=yi(n);return i!==void 0&&t.has(i)}))},Cp=(e,t)=>{const s=new Map,n=new Map;for(const i of e)s.set(i.name,`workflow "${i.exportName}"`),n.set(i.className,`workflow "${i.exportName}"`);for(const i of t){const o=s.get(i.name);if(o!==void 0)throw new G("DUPLICATE_WORKFLOW_NAME",`Duplicate deployed name "${i.name}": produced by both ${o} and agent "${i.exportName}". Workflow and agent names share one account-wide namespace and must be unique together.`,{status:500});const a=n.get(i.className);if(a!==void 0)throw new G("DUPLICATE_WORKFLOW_CLASS",`Duplicate generated class "${i.className}": produced by both ${a} and agent "${i.exportName}". Workflow and agent export names must yield unique generated class names.`,{status:500})}},Tp=e=>{const{lunoraDirectory:t,project:s,projectRoot:n,schema:i}=e,o=Nl(s,t),a=gp(s,t),c=Wr(s,t),{queues:l,topics:u}=to(s,t),f=no(n),g=Qr(s,t);Cp(c,g);const m=Xr(s,t),E=io(s,t),V=Jr(s,t,c,g),de=wp(s,t),R=yp(s,t),K=so(s,t),B=eo(s,t);B.browser=B.browser||K.usesSandboxBrowser;const F=Ln(n,e.target),M=ro(B,F,{agents:g.length>0,commitOrderedTables:i.tables.some(L=>L.commitOrdered===!0),cronTriggers:V.length>0,crossShardFanout:i.tables.some(L=>lo(L)),containerEgressPolicy:R.containerEgressPolicy,containerRuntimeScheduling:m.some(L=>L.schedulingPolicy==="durable_object"),containerSandboxTools:m.some(L=>L.sandbox===!0),durableStreams:R.durableStreams,globalTables:i.tables.some(L=>L.shardMode==="global"),liveStreams:R.liveStreams,typedWebSockets:R.typedWebSockets,queues:l.length>0,relationGraph:Ip(i),secrets:R.secrets,services:f.length>0,topics:u.length>0,vectorStore:i.vectorIndexes.length>0,workerLoaders:K.usesSandboxLoader,workflowRollback:R.workflowRollback,workflowSchedules:c.some(L=>L.schedules!==void 0)}),I=M.usage,j=Yr(I),J=M.signals.vectorStore!==!1,Z=M.signals.services===!1?[]:f,H=Fn(n),se=H??new Set,T=se.has("lunorash");ap(i,H,{hasVectors:J,scheduler:I.scheduler||V.length>0,storage:I.storage||E.rules.length>0||Object.keys(Dn(i)).length>0,usage:I});const O=D(v(t,"flags.ts")),$=D(v(t,"notify.ts"));return{agents:g,capabilities:j,containers:m,crons:V,dataModelContent:po(i),declaredDependencies:H,dependencies:se,entryCronTriggers:de,env:a,featureUsage:I,hasFlags:O,hasNotify:$,identity:o,platformGate:{...M,diagnostics:[...oo(n,e.target),...M.diagnostics,...ao(F,i.vectorIndexes)]},queues:l,serverContent:fo({agents:g,capabilities:j,containers:m,env:a,hasVectors:J,hasFlags:O,hasNotify:$,identity:o,queues:l,schema:i,services:Z,storageRuleBuckets:E.rules.map(L=>L.bucket),topics:u,useUmbrella:T,workflows:c}),services:Z,storageRulesMetadata:E,topics:u,usesSandbox:K.usesSandboxBrowser||K.usesSandboxContainer||K.usesSandboxFs,useUmbrella:T,workflows:c}},bi=(e,t)=>{if(!r.isPropertyAccessExpression(e))return;const s=e.getExpression();if(!r.isPropertyAccessExpression(s))return;const n=s.getExpression();return r.isPropertyAccessExpression(n)&&n.getName()===t?s.getName():void 0},Op=e=>{if(!r.isPropertyAccessExpression(e))return!1;const t=e.getExpression();return r.isPropertyAccessExpression(t)&&t.getName()==="scheduler"||r.isIdentifier(t)&&t.getText()==="scheduler"},kp=new Map([["publish",{kind:"publish",surface:"topics"}],["publishBatch",{kind:"publish",surface:"topics"}],["send",{kind:"enqueue",surface:"queues"}],["sendBatch",{kind:"enqueue",surface:"queues"}]]),Rp=/^[\w$]+:[\w$]+$/u,Fp=(e,t)=>{const s=yn(t);return s!==void 0?{kind:"call",target:s}:e!=="run"&&t!==void 0?{kind:"call",reason:'the function reference is not a static api.* / internal.* chain or a "namespace:export" key'}:void 0},cn=e=>{const t=[];for(const s of e.getProperties()){if(!r.isPropertyAssignment(s)&&!r.isShorthandPropertyAssignment(s))return;t.push(s.getName())}return t},Lp=e=>{if(e===void 0)return[];if(r.isObjectLiteralExpression(e))return cn(e);if(r.isIdentifier(e)){const t=e.getSymbol()?.getDeclarations()[0];if(r.isVariableDeclaration(t)&&t.getVariableStatement()?.getDeclarationKind()===sr.Const){const s=t.getInitializer();return r.isObjectLiteralExpression(s)?cn(s):void 0}}},Dp=(e,t,s)=>({schedule:{argKeys:Lp(s),...e==="runAfter"&&t!==void 0&&r.isNumericLiteral(t)?{delayMs:t.getLiteralValue()}:{}}}),Mp=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;const s=t.getName(),[n,i,o]=e.getArguments();if(An.has(s))return Fp(s,n);if((s==="runAfter"||s==="runAt")&&Op(t)){const l=yn(i)??(r.isStringLiteral(i)&&Rp.test(i.getLiteralText())?i.getLiteralText():void 0);return l===void 0?{kind:"schedule",reason:'the scheduled function is not a static api.* / internal.* chain or a "namespace:export" key'}:{kind:"schedule",target:l,...Dp(s,n,o)}}const a=kp.get(s),c=a===void 0?void 0:bi(t,a.surface);return a===void 0||c===void 0?void 0:{kind:a.kind,target:c}},_p=new Set([d.AmpersandAmpersandEqualsToken,d.AmpersandAmpersandToken,d.BarBarEqualsToken,d.BarBarToken,d.QuestionQuestionEqualsToken,d.QuestionQuestionToken]),Ni=e=>tr.isOptionalChain(e.compilerNode),Kp=(e,t)=>r.isIfStatement(t)?!S(e,t.getExpression()):r.isWhileStatement(t)||r.isForInStatement(t)||r.isForOfStatement(t)?S(e,t.getStatement()):r.isForStatement(t)?S(e,t.getStatement())||S(t.getIncrementor(),e):r.isCaseClause(t)||r.isDefaultClause(t)||r.isCatchClause(t)?!0:re(t)?t.getFirstAncestor(re)!==void 0:r.isConditionalExpression(t)?!S(e,t.getCondition()):r.isBinaryExpression(t)?!S(e,t.getLeft())&&_p.has(t.getOperatorToken().getKind()):(r.isCallExpression(t)||r.isElementAccessExpression(t))&&Ni(t)?!S(e,t.getExpression()):r.isBlock(t)&&t.getStatements().some(s=>s.getEnd()<=e.getStart()&&ng(s)),zp=e=>{let t=e,s=e.getParent();for(;s!==void 0&&(r.isAwaitExpression(s)||r.isParenthesizedExpression(s));)t=s,s=s.getParent();const n=r.isVariableDeclaration(s)||r.isBinaryExpression(s)&&S(t,s.getRight())&&s.getOperatorToken().getKind()===d.EqualsToken,i=e.getFirstAncestor(re);return n||i?.getDescendantsOfKind(d.ThrowStatement).some(o=>o.getStart()>=e.getEnd()&&S(o.getFirstAncestor(re),i))===!0},Bp=(e,t)=>(r.isWhileStatement(t)||r.isForInStatement(t)||r.isForOfStatement(t))&&S(e,t.getStatement())||r.isForStatement(t)&&(S(e,t.getStatement())||S(t.getIncrementor(),e)),$p=(e,t)=>{if(Ni(e)||t==="schedule"&&zp(e))return"guard";let s=e,n=!1;for(let i=s.getParent();i!==void 0&&!r.isSourceFile(i);i=i.getParent()){if(Kp(s,i)){if(!Bp(s,i))return"guard";n=!0}s=i}return n?"loop":void 0},ln=(e,t,s)=>{if(s===void 0)return;const n=$p(e,s.kind);return{...s,...n===void 0?{}:{conditional:!0},...n==="loop"?{loopOnly:!0}:{},file:t,line:e.getStartLineNumber(),scope:x(e)}},Vp=(e,t)=>[...w(e,t,(s,n)=>ln(s,n,Mp(s))),...ne(e,t,d.PropertyAccessExpression,(s,n)=>{const i=bi(s,"services");return ln(s,n,i===void 0?void 0:{kind:"invoke",target:i})})],Up=new Set(["boolean","number","object","string"]),Wp=e=>{const t=e.getName();if(!Up.has(t))return;const s=e.getExpression();return Y(s,["flags"])||Y(s,["flags","details"])?t:void 0},qp=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;const s=Wp(t);if(s===void 0)return;const n=e.getArguments()[0];if(!n||!(r.isStringLiteral(n)||r.isNoSubstitutionTemplateLiteral(n)))return;const i=n.getLiteralValue();return i.length>0?{key:i,type:s}:void 0},jp=(e,t)=>{const s=new Map;for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const o of i.getDescendantsOfKind(d.CallExpression)){const a=qp(o);a&&!s.has(a.key)&&s.set(a.key,a.type)}}return[...s.entries()].map(([n,i])=>({key:n,type:i})).toSorted((n,i)=>n.key.localeCompare(i.key))},Hp=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 i=n.getTypeAtLocation(e),o=i.getText(e);if(!o||o==="any"||o==="never"||mo(o))return;const a=e.getSourceFile().getFilePath();if(ho(i,e,a)){const c=vo(i,e,a,0,new Set);return c===void 0&&Eo(o),c}return o},Gp=e=>e.getProperties().some(t=>{if(r.isSpreadAssignment(t))return!0;const s=Sr(t.getNameNode());return s===void 0||s==="namespace"}),Yp=(e,t)=>{for(const{filePath:s}of He(t)){const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const i of n.getDescendantsOfKind(d.CallExpression)){const o=i.getExpression(),[a]=i.getArguments();if(!(!r.isPropertyAccessExpression(o)||o.getName()!=="auth"||a===void 0)&&(!r.isObjectLiteralExpression(a)||Gp(a)))return i}}},Qp="https://lunora.sh/docs/concepts/data-residency#pinning-auth-and-voice",Xp=(e,t)=>{if(!(e.jurisdiction===void 0||e.jurisdictionPinsAuth===!0||t===void 0))throw Pe(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 (${Qp}). 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})},Jp=e=>r.isPropertyAssignment(e)||r.isMethodDeclaration(e)||r.isGetAccessorDeclaration(e)?r.isComputedPropertyName(e.getNameNode()):!1,Zp=e=>r.isPropertyAssignment(e)||r.isShorthandPropertyAssignment(e)||r.isMethodDeclaration(e)||r.isGetAccessorDeclaration(e)?Jp(e):!0,Pi=(e,t=!1)=>{for(const s of e.getProperties()){if(Zp(s))return!0;if(t)continue;if(!r.isPropertyAssignment(s))return!0;const n=s.getInitializer();if(!n||!r.isObjectLiteralExpression(n)||Pi(n,!0))return!0}return!1},em=(e,t)=>{for(const s of A(t)){const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const{receiver:i}of Mn(n))for(const o of Bt(i)){const a=o.getArguments()[0];if(a!==void 0&&(!r.isObjectLiteralExpression(a)||Pi(a)))return!0}}return!1},tm=e=>{const t=e.getArguments()[0];if(!t||!r.isObjectLiteralExpression(t))return[];const s=[];for(const n of t.getProperties()){const i=Be(n);if(i===void 0||!r.isPropertyAssignment(n))continue;const o=n.getInitializer();if(!(!o||!r.isObjectLiteralExpression(o)))for(const a of o.getProperties()){const c=Be(a);c!==void 0&&s.push({column:c,strategy:On(a),table:i})}}return s},sm=(e,t)=>{const s=new Map;for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const{receiver:o}of Mn(i))for(const a of Bt(o))for(const c of tm(a)){const l=`${c.table}\0${c.column}`;s.has(l)||s.set(l,c)}}return{columns:[...s.values()]}},nm=["providerSubscriptionId","state"],im=["providerEventId","processedAt"],dn=(e,t)=>t.every(s=>s in e.shape),rm=e=>{const t=e.find(n=>n.name==="payment_subscriptions"),s=e.find(n=>n.name==="payment_events");return t!==void 0&&s!==void 0&&dn(t,nm)&&dn(s,im)},om=["account","apikey","member","passkey","session","teamMember","twoFactor","user"],am=(e,t)=>{const s={};for(const[n,i]of e)s[n]={dataset:i};for(const[n,i]of t)s[n]={excluded:i};return s},cm=(e,t)=>{const s=[];for(const n of e){const i=t[n];i===void 0?s.push({code:"unclassified",table:n}):"excluded"in i&&i.excluded.trim()===""&&s.push({code:"excluded_without_reason",table:n})}return s},lm="@lunora/privacy",wi="userId",dm=e=>e.replaceAll("\\","/"),um="privacy",fm=new Set(["actionCacheDataset","authDataset","documentHistoryDataset"]),Ze=e=>e!==void 0&&(r.isStringLiteral(e)||r.isNoSubstitutionTemplateLiteral(e))?e.getLiteralText():void 0,et=e=>r.isPropertyAssignment(e)?e.getName().replaceAll(/^["']|["']$/gu,""):"",Qt=e=>e.getProperties().filter(t=>r.isPropertyAssignment(t)),gm=(e,t)=>{const s=e.getProperty(t),n=r.isPropertyAssignment(s)?s.getInitializer():void 0;return n!==void 0&&r.isObjectLiteralExpression(n)?n:void 0},tt=e=>{const t=e.getExpression();return r.isIdentifier(t)?t.getText():void 0},pm=(e,t)=>{const s=e.getArguments()[1];if(s===void 0||!r.isObjectLiteralExpression(s))return;const n=gm(s,"tables"),i=Ze(e.getArguments()[0])??"defineDataset";for(const o of n===void 0?[]:Qt(n).map(a=>et(a)))t.datasets.set(o,i)},mm=(e,t)=>{const s=e.getArguments()[0],n=s!==void 0&&r.isObjectLiteralExpression(s)?Qt(s):[],i=new Set(n.map(o=>et(o)));for(const o of om)i.has(o)||t.datasets.set(o,"authDataset");for(const o of n){const a=r.isPropertyAssignment(o)?Ze(o.getInitializer()):void 0;a!==void 0&&t.datasets.set(a,"authDataset")}},un=(e,t,s)=>{t.datasets.set(Ze(e.getArguments()[0])??s,s)},Xt=8,Ne=(e,t=0)=>{if(t>Xt)return;if(r.isAsExpression(e)||r.isSatisfiesExpression(e)||r.isParenthesizedExpression(e))return Ne(e.getExpression(),t+1);if(!r.isIdentifier(e))return e;const s=e.getSymbol(),n=(s?.isAlias()===!0?s.getAliasedSymbol():s)?.getValueDeclaration(),i=r.isVariableDeclaration(n)?n.getInitializer():void 0;return i===void 0?void 0:Ne(i,t+1)},hm=e=>{if(r.isPropertyAssignment(e)){const t=e.getInitializer();return t===void 0?void 0:[et(e),t]}if(r.isShorthandPropertyAssignment(e)){const t=e.getValueSymbol(),s=(t?.isAlias()===!0?t.getAliasedSymbol():t)?.getValueDeclaration(),n=r.isVariableDeclaration(s)?s.getInitializer():void 0;return[e.getName(),n??e.getNameNode()]}},Ii=(e,t=0)=>{const s=Ne(e,t);if(s===void 0||!r.isObjectLiteralExpression(s)||t>Xt)return;const n=new Map;for(const i of s.getProperties()){const o=r.isSpreadAssignment(i)?Ii(i.getExpression(),t+1):[hm(i)];if(o===void 0)return;for(const a of o)a!==void 0&&n.set(a[0],a[1])}return n},vm=e=>{const t=e.getArguments()[0];return t===void 0?void 0:Ii(t)},Em=(e,t)=>{const s=e?.get("exclude"),n=s===void 0?void 0:Ne(s);for(const i of n!==void 0&&r.isObjectLiteralExpression(n)?Qt(n):[])t.excluded.set(et(i),r.isPropertyAssignment(i)?Ze(i.getInitializer())??"":"")},xm=(e,t)=>{switch(tt(e)){case"actionCacheDataset":{un(e,t,"actionCache");break}case"authDataset":{mm(e,t);break}case"defineDataset":{pm(e,t);break}case"documentHistoryDataset":{un(e,t,"documentHistory");break}}},Jt=e=>e!==void 0&&r.isCallExpression(e)&&tt(e)==="defineDataset",Ci=e=>e!==void 0&&r.isCallExpression(e)&&fm.has(tt(e)??""),Sm=e=>{const t=e.getSymbol(),n=(t?.isAlias()===!0?t.getAliasedSymbol():t)?.getValueDeclaration(),i=r.isVariableDeclaration(n)?n.getInitializer():void 0;return r.isVariableDeclaration(n)&&(Jt(i)||Ci(i))?n:void 0},Ti=(e,t,s=0)=>{const n=Ne(e,s);if(n===void 0||!r.isArrayLiteralExpression(n)||s>Xt)return!1;for(const i of n.getElements())if(r.isSpreadElement(i)){if(!Ti(i.getExpression(),t,s+1))return!1}else if(!Jt(i)&&!Ci(i)){const o=r.isIdentifier(i)?Sm(i):void 0;if(o===void 0)return!1;t.add(o)}return!0},Am=e=>{if(e===void 0)return;const t=e.get("datasets"),s=new Set;return t===void 0||Ti(t,s)?s:void 0},ym=(e,t)=>{const s=[];for(const i of e.getDescendantsOfKind(d.CallExpression))if(xm(i,t),tt(i)==="definePrivacy"){const o=vm(i);Em(o,t),s.push({location:`${e.getFilePath()}:${String(i.getStartLineNumber())}`,passed:Am(o)})}return{declared:e.getDescendantsOfKind(d.VariableDeclaration).filter(i=>Jt(i.getInitializer())).map(i=>({declaration:i,name:i.getName()})),privacyCalls:s}},bm=(e,t)=>{const s=v(t,"schema.ts"),n=[...A(t),...D(s)?[s]:[]];for(const o of n)e.getSourceFile(o)===void 0&&e.addSourceFileAtPath(o);const i=new Set(n.map(o=>dm(o)));return e.getSourceFiles().filter(o=>i.has(o.getFilePath()))},Nm=(e,t,s)=>{if(s?.has(lm)!==!0)return{classifications:{},enabled:!1,unusedDatasets:[]};const n={datasets:new Map,excluded:new Map},i=[],o=[];for(const f of bm(e,t)){const g=ym(f,n);i.push(...g.declared),o.push(...g.privacyCalls)}const a=new Set;for(const f of o){for(const g of f.passed??[])a.add(g);f.passed===void 0&&console.warn(`@lunora/codegen: privacy_datasets_unresolved: the definePrivacy call at ${f.location} passes datasets codegen cannot read, so a defineDataset it leaves out is not reported. Pass an array of dataset constants, directly or through a spread of a config object literal.`)}const l=o.every(f=>f.passed!==void 0)?i.filter(f=>!a.has(f.declaration)).map(f=>f.name):[];return{classifications:am(n.datasets,n.excluded),enabled:o.length>0,unusedDatasets:l}},Pm=e=>e.extensionKey!==um&&wi in e.shape,wm=e=>e.code==="excluded_without_reason"?`privacy_exclusion_unexplained: "${e.table}" is excluded without a reason. Give one in definePrivacy({ exclude }).`:`privacy_table_unclassified: "${e.table}" holds user data (it has a "${wi}" column) but no dataset exports it. Add it to a defineDataset, or exclude it in definePrivacy({ exclude }) with a reason.`,Im=(e,t)=>{if(!t.enabled)return;const s=e.filter(o=>Pm(o)).map(o=>o.name),[n]=cm(s,t.classifications);if(n!==void 0)throw new G("PRIVACY_COVERAGE",wm(n));const[i]=t.unusedDatasets;if(i!==void 0)throw new G("PRIVACY_COVERAGE",`privacy_dataset_unused: "${i}" is declared with defineDataset but never passed to definePrivacy({ datasets }). Pass it, or delete it.`)},Cm=(e,t)=>{const s=co(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,privacy:t.dependencies.has("@lunora/privacy"),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")}},Tm=new Set(["delete","hardDelete","patch","replace","restore"]),Om=new Set(["insertMany","insertManyUnsafe","patchIf","patchWhere"]),km=new Set(["delete","deleteMany","hardDelete","insert","insertMany","patch","patchMany","replace","restore","upsert","upsertMany"]),fn=(e,t)=>{const s=e.getNonNullableType().getProperty("__table")?.getTypeAtLocation(t);if(s===void 0)return[];const n=s.isUnion()?s.getUnionTypes():[s],i=n.map(o=>o.getLiteralValue()).filter(o=>typeof o=="string");return i.length===n.length?i:[]},Rm=(e,t)=>{const s=e.getType();if(t==="deleteMany"||t==="patchMany"){const n=s.getArrayElementType();if(n===void 0)return[];const i=t==="patchMany"?n.getProperty("id")?.getTypeAtLocation(e):n;return i===void 0?[]:fn(i,e)}return fn(s,e)},gn="",Fm=(e,t)=>{if(t!=="patch"&&t!=="patchMany")return;const s=e.getArguments()[1];if(s===void 0||!r.isObjectLiteralExpression(s))return;const n=[];for(const i of s.getProperties()){if(!r.isPropertyAssignment(i)&&!r.isShorthandPropertyAssignment(i))return;n.push(i.getName())}return n},Lm=(e,t)=>{if(Om.has(e))return{method:e,tables:[t!==void 0&&r.isStringLiteral(t)?t.getLiteralText():gn]};if(Tm.has(e)||e==="deleteMany"||e==="patchMany"){const s=t===void 0?[]:Rm(t,e);return{method:e,tables:s.length===0?[gn]:s}}},pn=(e,t)=>e===void 0?void 0:{...e,fields:Fm(t,e.method)},Dm=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;const s=t.getName(),n=t.getExpression();if(_(n))return pn(Lm(s,e.getArguments()[0]),e);if(km.has(s)&&r.isPropertyAccessExpression(n)&&_(n.getExpression()))return pn({method:s,tables:[n.getName()]},e)},Mm=(e,t)=>w(e,t,(s,n)=>{const i=Dm(s);if(i===void 0)return;const o=x(s),a=s.getStartLineNumber();return i.tables.map(c=>({...i.fields===void 0?{}:{fields:i.fields},file:n,line:a,method:i.method,scope:o,table:c}))}),_m=(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"}),Km=(e,t)=>{if(t===void 0){const s=e.getArguments()[0];if(s===void 0||!r.isObjectLiteralExpression(s)||z(s,"args")===void 0)return!1}return Ut(e,t).opaque},zm=(e,t)=>{const s=[],n=(i,o)=>{const a=i.getInitializer();if(a===void 0||!r.isCallExpression(a))return;const c=te(a);c!==void 0&&Km(a,c.receiver)&&s.push(_m(t,o,a.getStartLineNumber()))};for(const i of e.getVariableStatements().filter(o=>o.isExported()))for(const o of i.getDeclarations())n(o,o.getName());return s},Bm=(e,t)=>{const s=[];for(const n of A(t)){const i=e.getSourceFile(n);i!==void 0&&s.push(...zm(i,P(t,n)))}return s.toSorted((n,i)=>n.cacheKey.localeCompare(i.cacheKey))},$m=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."}],["RegisteredRoom",{call:"defineRoom({ … })",note:"A dropped room has no caller to fail — its whisper topic is never wired to a handler, so joins, messages and broadcasts are silently ignored."}],["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"}]]),je=({byName:e,byPath:t},s,n)=>t.has(`${s}:${n}`)||e.has(n),Oi=e=>!e.isAny(),ki=e=>{const t=e.getType();if(!Oi(t))return;const s=t.getAliasSymbol()?.getName()??t.getSymbol()?.getName(),n=s===void 0?void 0:$m.get(s);return n===void 0||s===void 0?void 0:{...n,typeName:s}},Vm=e=>{const t=e.getInitializer();return t===void 0?!1:r.isCallExpression(t)||r.isIdentifier(t)||r.isPropertyAccessExpression(t)},Ri={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."},Um=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.`}),Wm={cause:"it is exported only under a string name that is not an identifier, which the generated `api.ts` and dispatch table cannot address as `<module>.<name>`",remediation:"Export it under an identifier name as well (or instead)."},qm=new Set(["AgentDefinition","ContainerDefinition","QueueDefinition","RegisteredShape","SubscriptionDefinition","WorkflowDefinition"]),jm={cause:"it is exported only as `default` or under a reserved word, and this kind's name becomes an import binding and a generated class / binding name, where that is a syntax error",remediation:"Export it under a plain identifier: `export const <name> = …` (an extra `export default <name>` is fine)."},Hm=(e,t,s)=>{if(!t.some(i=>fr(i)))return Wm;const n=e.getVariableStatement()?.hasExportKeyword()===!0;return qm.has(s.typeName)&&!n&&!t.some(i=>To(i))?jm:Ri},Fi=(e,t,s,n,i)=>{const{call:o,file:a,note:c,typeName:l}=s,u=a!==void 0&&e!==a?a:void 0,f=u===void 0?i:Um(u),g=c===void 0?f.remediation:`${c} ${f.remediation}`;return{cacheKey:`procedure_not_registered:${e}:${t}`,categories:["SCHEMA"],description:"Codegen registers an export only when its initializer is literally the registering call and the module exports it under an identifier name — by the `export` keyword, a local `export { … }`, or `export default`. 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 \`${l}\` but was not registered — ${f.cause}.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:t,filePath:e,line:n,typeName:l},name:"procedure_not_registered",remediation:u===void 0?`Assign the registration directly: \`export const ${t} = ${o};\`. ${g}`:g,title:"Procedure exists at runtime but is missing from the generated API"}},Gm=(e,t,s)=>{const n=[];for(const i of X(e)){const o=r.isIdentifier(i.getNameNode())?At(i):[i.getName()],c=o.some(u=>je(s,t,u))||!Vm(i)?void 0:ki(i),[l=i.getName()]=o;c!==void 0&&n.push(Fi(t,l,c,i.getStartLineNumber(),Hm(i,o,c)))}return n},Ym=(e,t,s)=>{if(je(s,t,"default"))return[];const n=[];for(const i of e.getExportAssignments().filter(o=>!o.isExportEquals()&&!r.isIdentifier(o.getExpression()))){const o=ki(i.getExpression());o!==void 0&&n.push(Fi(t,"default",o,i.getStartLineNumber(),Ri))}return n},Qm=(e,t,s)=>[...Gm(e,t,s),...Ym(e,t,s)],Xm=(e,t,s)=>e.getVariableStatements().flatMap(n=>n.getDeclarations()).filter(n=>r.isIdentifier(n.getNameNode())).filter(n=>At(n).some(i=>je(s,t,i))).filter(n=>{const i=n.getInitializer();return i!==void 0&&r.isCallExpression(i)&&r.isPropertyAccessExpression(i.getExpression())}).map(n=>{const i=At(n).find(o=>je(s,t,o))??n.getName();return{declaration:n,exportName:i,relativePath:t}}),Jm=({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"}),Zm=(e,t,s)=>{const n=[],i=[];for(const a of A(t)){const c=e.getSourceFile(a);if(c===void 0)continue;const l=P(t,a);n.push(...Qm(c,l,s)),i.push(...Xm(c,l,s))}const[o]=i;return o!==void 0&&i.every(({declaration:a})=>!Oi(a.getType()))&&n.push(Jm(o)),n.toSorted((a,c)=>a.cacheKey.localeCompare(c.cacheKey))},eh=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||t.getName()!=="get")return!1;const s=t.getExpression();return r.isPropertyAccessExpression(s)?s.getName()==="workflows":r.isIdentifier(s)&&s.getText()==="workflows"},th=e=>{const t=e.getArguments()[0];return t&&r.isStringLiteral(t)?t.getLiteralText():""},sh=(e,t)=>w(e,t,(s,n)=>eh(s)?{file:n,line:s.getStartLineNumber(),scope:x(s),workflow:th(s)}:void 0),we=(e,t)=>{D(e)&&Qi(e,"utf8")===t||Xi(e,t,"utf8")},nh=(e,t)=>{if(t===""){Ae(e,{force:!0});return}we(e,t)},ih=(e,t)=>{const s=v(e,"services");if(Object.keys(t).length===0){Ae(s,{force:!0,recursive:!0});return}if(D(s))for(const n of mn(s,{recursive:!0,withFileTypes:!0})){const i=v(n.parentPath,n.name);n.isFile()&&t[hn(e,i)]===void 0&&Ae(i)}for(const[n,i]of Object.entries(t))Lt(Dt(v(e,n)),{recursive:!0}),we(v(e,n),i)},rh=(e,t,s)=>{const n=v(e,t);if(Object.keys(s).length===0){Ae(n,{force:!0,recursive:!0});return}if(D(n))for(const i of mn(n,{recursive:!0,withFileTypes:!0})){const o=v(i.parentPath,i.name);i.isFile()&&s[hn(n,o)]===void 0&&Ae(o)}for(const[i,o]of Object.entries(s)){const a=v(n,i);Lt(Dt(a),{recursive:!0}),we(a,o)}},oh=e=>{try{const t=ko(v(e,"package.json"));return typeof t.version=="string"&&t.version!==""?t.version:void 0}catch{return}},ae=(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)},Le=(e,t,s)=>e.getSourceFile(t)?.getFullText()===s,ah=(e,t)=>{D(e)||Lt(e,{recursive:!0});const s=[];for(const n of t)switch(n.kind){case"always":{we(v(e,n.name),n.content),s.push(n.name);break}case"directory":{rh(e,n.name,n.files),s.push(...Object.keys(n.files).map(i=>v(n.name,i)));break}case"services":{ih(e,n.files),s.push(...Object.keys(n.files));break}default:nh(v(e,n.name),n.content),n.content!==""&&s.push(n.name)}return s},ch=e=>{const t=oh(e.projectRoot),s=e.wantsArchitecture?e.modules:[],n=Fo({functions:e.functions,httpRoutes:e.httpRoutes,modules:s,version:t}),i=Do({functions:e.functions,modules:s,version:t});return{openApiContent:`${JSON.stringify(n,void 0,2)}
|
|
9
|
+
`,openApiModuleContent:Lo(n),openRpcContent:`${JSON.stringify(i,void 0,2)}
|
|
10
|
+
`,openRpcModuleContent:Mo(i)}},lh=".lunora-schema.json",dh=/^fn\//u,uh=()=>{const e=process.env.LUNORA_CODEGEN_TIMING;return e!==void 0&&e!==""},fh=(e,t,s)=>{if(s&&e.length>0){const o=e.map(a=>`"${a.exportName}"`).join(", ");throw new G("MASK_UNSUPPORTED",`This project declares a \`mask(...)\` policy whose argument isn't a plain object literal (e.g. \`mask(sharedPolicies)\` referencing a hoisted variable), or contains a spread (\`...shared\`) or computed key (\`[name]:\`) codegen can't enumerate, so codegen can't tell which columns it masks. Because the project also declares replication shape(s) (${o}), codegen can't verify none of them replicate a table that policy masks — inline every table and column as literal keys so codegen can verify it, or remove the affected shape(s).`,{status:422})}const n=new Map;for(const o of t.columns){const a=n.get(o.table)??[];a.push(o.column),n.set(o.table,a)}const i=t.columns.length>0;for(const o of e){if(o.table===void 0){if(i)throw new G("MASK_UNSUPPORTED",`defineShape "${o.exportName}" has a non-literal \`table\` (a variable or expression, not a string literal), so codegen can't statically verify it doesn't replicate a table that masks a column. This project masks at least one column elsewhere, so the combination can't be proven safe — change "${o.exportName}"'s \`table\` to a plain string literal so codegen can verify it, or remove the mask(s) on the table it targets.`,{status:422});continue}const a=n.get(o.table);if(a===void 0)continue;const c=a.map(l=>`"${l}"`).join(", ");throw new G("MASK_UNSUPPORTED",`defineShape "${o.exportName}" replicates table "${o.table}", which masks column(s) ${c} on at least one procedure. A shape runs no procedure, so \`.use(mask(...))\` never applies to its replicated rows — remove the shape, unmask the table, or wait for shape-masking support.`,{status:422})}},gh=8,ph=e=>{const{agents:t,apiPath:s,generatedFunctionsPath:n,internalPath:i,lazyFunctions:o,lunoraDirectory:a,migrations:c,project:l,roomsSupported:u,shapes:f,usesSandbox:g,useUmbrella:m,workflows:E}=e,V=()=>So(()=>{const F=Ao(l,a,{lazyFunctions:o===!0}),M=Or(l,a);return{functions:F,httpRoutes:yo(l,a),mutators:M}});let{erased:de,value:{functions:R,httpRoutes:K,mutators:B}}=V();rn([...R,...B].map(F=>F.filePath)),rn(K.filter(F=>F.stream).map(F=>F.filePath),"http-stream");for(let F=1;;F+=1){const M=u?R:R.filter(T=>T.channel?.kind!=="room"),I=o===!0,j=Wo({agents:t,functions:M,httpRoutes:K,mutators:B,useUmbrella:m,workflows:E}),J={agents:t,functions:M,lazyFunctions:I,migrations:c,mutators:B,shapes:f,useUmbrella:m,usesSandbox:g},Z=Zo(J),H=ea(J),se=qo({functions:R,useUmbrella:m});if(F>=gh||Le(l,s,j)&&Le(l,i,se)&&Le(l,n,Z)&&Object.entries(H).every(([T,O])=>Le(l,v(a,"_generated",T),O)))return{apiContent:j,erased:de,functions:R,functionModulesContent:H,functionsContent:Z,httpRoutes:K,internalContent:se,lazyFunctions:I,mutators:B};ae(l,s,j),ae(l,i,se),ae(l,n,Z);for(const[T,O]of Object.entries(H))ae(l,v(a,"_generated",T),O);({erased:de,value:{functions:R,httpRoutes:K,mutators:B}}=V())}},Ov=e=>{const t=uh(),s=t?dt.now():0,n=v(e.projectRoot,e.lunoraDirectory??"lunora"),i=e.lazyFunctions===!0,o=v(n,"schema.ts");if(!D(o))throw new G("INTERNAL",`schema.ts not found at ${o}`);const a=e.project??Hr(n);br(Hp);const c=Io(a,o,e.projectRoot);Im(c.tables,Nm(a,n,Fn(e.projectRoot)));const{agents:l,capabilities:u,containers:f,crons:g,dataModelContent:m,dependencies:E,entryCronTriggers:V,env:de,featureUsage:R,hasFlags:K,hasNotify:B,identity:F,platformGate:M,queues:I,serverContent:j,services:J,storageRulesMetadata:Z,topics:H,usesSandbox:se,useUmbrella:T,workflows:O}=Tp({lunoraDirectory:n,project:a,projectRoot:e.projectRoot,schema:c,target:e.target});Xp(c,c.jurisdiction===void 0?void 0:Yp(a,n));const $=v(n,"_generated"),L=v($,"dataModel.ts"),Li=v($,"server.ts"),Di=v($,"api.ts"),Mi=v($,"internal.ts"),_i=v($,"functions.ts");ae(a,L,m),ae(a,Li,j);const Zt=Object.fromEntries(J.filter(p=>p.rpcEntrypoint!==void 0).flatMap(p=>Object.entries(go(p,$))));for(const[p,he]of Object.entries(Zt))ae(a,v($,p),he);const Ie=No(a,n),ue=Co(a,n),es=M.signals.typedWebSockets!==!1,{apiContent:ts,erased:Ki,functions:oe,functionModulesContent:ss,functionsContent:ns,httpRoutes:st,internalContent:is,lazyFunctions:zi,mutators:nt}=ph({agents:l,apiPath:Di,generatedFunctionsPath:_i,internalPath:Mi,lazyFunctions:i,roomsSupported:es,lunoraDirectory:n,migrations:Ie,project:a,shapes:ue,useUmbrella:T,usesSandbox:se,workflows:O}),rs=$r(a,n),it=Vr(rs,c,[...oe,...st].map(p=>p.filePath)),Ce=rs.length>0,Te=e.lint===!1&&!Ce?void 0:{callEdges:Vp(a,n),inserts:bo(a,n),queries:Po(a,n,oe),tableWrites:Mm(a,n),workflowCalls:sh(a,n)},Oe=e.lint===!1||Te===void 0?void 0:Mg(a,n,{callSites:Te,containers:f,crons:g,functions:oe,modules:it,mutators:nt,queues:I,schema:c,shapes:ue,workflows:O,wranglerVariables:e.wranglerVariables}),os=Oe===void 0?[]:Ug(e.projectRoot,[...Ji(Oe,{source:"static"}),...Zm(a,n,{byName:new Set([...O,...I,...l,...f].map(p=>p.exportName)),byPath:new Set([...oe,...nt,...ue,...Ie].map(p=>`${p.filePath}:${p.exportName}`))}),...Bm(a,n),...xo(Ki,n),..._o(I,e.wranglerQueueProducers)]),Bi=wo(a,n),as=sm(a,n);fh(ue,as,em(a,n));const $i=K?jp(a,n):[],rt=M.signals.vectorStore!==!1,pe=Cm(R,{containerCount:f.length,cronCount:g.length,dependencies:E,hasPaymentTables:rm(c.tables),queueCount:I.length,storageColumnCount:Object.keys(Dn(c)).length,storageRuleCount:Z.rules.length,vectorIndexCount:c.vectorIndexes.length,target:Ln(e.projectRoot,e.target),vectorStoreSupported:rt,workflowCount:O.length}),cs=t?dt.now():0,ot=Ro(c,Ie.map(p=>p.id)),ls=uo({advisories:os.filter(p=>p.name!=="procedure_type_check_unavailable"),advisorProcedures:Oe?.procedureProtections??[],agents:l,capabilities:u,containers:f,env:de,flagKeys:$i,hasFlags:K,hasNotify:B,hasRooms:es&&oe.some(p=>p.channel?.kind==="room"),lazyFunctions:zi,hasVectors:rt,maskMetadata:as,mutators:nt,queues:I,rlsMetadata:Bi,schema:c,schemaSnapshot:ot,shapes:ue,services:J,storageRules:Z,studioFeatures:pe,topics:H,useUmbrella:T,workflows:O}),ds=Vo(ue,E.has("@lunora/db"),T),us=Ko(f,c.jurisdiction),fs=zo(O),gs=Bo(l),ps=$o(I,e.wranglerQueueProducers),ms=jo(g),Vi=Ho(pe.scheduler),Ui=Go(c.tables,T),Wi=Ar(e.projectRoot)?Yo(T):"",hs=Qo(c.vectorIndexes),ke=Jo(c,T),vs=Uo(E.has("@lunora/seed")),Re=e.apiSpec??"openapi",at=Re==="openapi"||Re==="both",ct=Re==="openrpc"||Re==="both",Es=Oo({capabilities:u,emailAgents:l.filter(p=>p.onEmail===!0).map(p=>({className:p.className,exportName:p.exportName})),hasAccess:E.has("@lunora/cloudflare-access"),hasAuth:E.has("@lunora/auth"),hasFramework:E.has("@lunora/astro")||E.has("@lunora/svelte")||E.has("@lunora/vue")||D(v(e.projectRoot,"src","worker.ts")),hasGlobal:c.tables.some(p=>kn(p)),hasHyperdriveGlobal:c.tables.some(p=>Rn(p)),hasKvIntrospector:pe.kv,hasNotify:B,hasQueue:I.some(p=>p.mode==="push"),hasScheduler:pe.scheduler,hasSourcedTables:c.tables.some(p=>p.externalSource!==void 0),hasStorage:pe.storage,hasVectors:rt,hasWorkflow:O.length>0,identity:F,jurisdiction:c.jurisdiction,jurisdictionPinsAuth:c.jurisdictionPinsAuth===!0,tables:c.tables.map(p=>({name:p.name,shardMode:p.shardMode})),useUmbrella:T,vectorIndexCount:c.vectorIndexes.length,voiceAgents:l.filter(p=>p.voice===!0&&p.voiceBindingName!==void 0).map(p=>({bindingName:p.voiceBindingName,exportName:p.exportName})),wantsArchitecture:Ce,wantsOpenApi:at,wantsOpenRpc:ct}),{openApiContent:xs,openApiModuleContent:Ss,openRpcContent:As,openRpcModuleContent:ys}=ch({functions:oe,httpRoutes:st,modules:it,projectRoot:e.projectRoot,wantsArchitecture:Ce}),me=Ce&&Te!==void 0?ip({...Te,crons:g,functions:oe,httpRoutes:st,modules:it,queues:I,schema:c,services:J,topics:H,workflows:O}):void 0,lt=v(n,lh),qi=D(lt),ji=Object.fromEntries(Object.entries(ss).map(([p,he])=>[p.replace(dh,""),he])),Hi=e.dryRun?[]:ah($,[{content:Es,kind:"always",name:"app.ts"},{content:m,kind:"always",name:"dataModel.ts"},{content:ts,kind:"always",name:"api.ts"},{content:is,kind:"always",name:"internal.ts"},{content:j,kind:"always",name:"server.ts"},{content:ns,kind:"always",name:"functions.ts"},{files:ji,kind:"directory",name:"fn"},{content:ls,kind:"always",name:"shard.ts"},{content:ms,kind:"always",name:"crons.ts"},{content:hs,kind:"always",name:"vectors.ts"},{content:ke.global,kind:"always",name:"drizzle.global.ts"},{content:ke.shard,kind:"always",name:"drizzle.shard.ts"},{content:us,kind:"optional",name:"containers.ts"},{content:fs,kind:"optional",name:"workflows.ts"},{content:gs,kind:"optional",name:"agents.ts"},{content:ps,kind:"optional",name:"queues.ts"},{content:Vi,kind:"optional",name:"scheduler.ts"},{content:Ui,kind:"optional",name:"shardRegistry.ts"},{content:Wi,kind:"optional",name:"durableObjects.ts"},{content:vs,kind:"optional",name:"seed.ts"},{content:ds,kind:"optional",name:"collections.ts"},{files:Zt,kind:"services"},{content:at?xs:"",kind:"optional",name:"openapi.json"},{content:at?Ss:"",kind:"optional",name:"openapi.ts"},{content:ct?As:"",kind:"optional",name:"openrpc.json"},{content:ct?ys:"",kind:"optional",name:"openrpc.ts"},{content:me===void 0?"":`${JSON.stringify(me,void 0,2)}
|
|
11
|
+
`,kind:"optional",name:"architecture.json"},{content:me===void 0?"":rp(me),kind:"optional",name:"architecture.ts"}]);if(!e.dryRun&&(!qi||e.updateSchemaBaseline===!0)&&we(lt,Zi(ot)),t){const p=dt.now(),he=Math.round(p-s),Gi=Math.round(cs-s),Yi=Math.round(p-cs);console.error(`@lunora/codegen: codegen took ${he.toString()}ms (discovery ${Gi.toString()}ms, emit ${Yi.toString()}ms)`)}return{advisories:os,advisorContext:Oe,agents:l,architecture:me,containers:f,cronTriggers:[...new Set([...Xo(g),...V])],generated:{agents:gs,api:ts,app:Es,collections:ds,containers:us,crons:ms,dataModel:m,drizzleGlobal:ke.global,drizzleShard:ke.shard,functionModules:ss,functions:ns,internal:is,openApi:xs,openApiModule:Ss,openRpc:As,openRpcModule:ys,queues:ps,seed:vs,server:j,shard:ls,vectors:hs,workflows:fs},migrations:Ie,outputDirectory:$,platformDiagnostics:M.diagnostics,queues:I,schemaSnapshot:ot,schemaSnapshotPath:lt,workflows:O,writtenFiles:Hi}};export{lh as SCHEMA_SNAPSHOT_FILENAME,Hr as createCodegenProject,Fv as findTsconfig,Lv as refreshCodegenProject,Ov as runCodegen};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const m=(e,t=2166136261)=>{let i=t;for(let o=0;o<e.length;o+=1)i^=e.charCodeAt(o),i=Math.imul(i,16777619);return(i>>>0).toString(16).padStart(8,"0")},S=e=>`${m(e,2166136261)}${m(e,16777619)}`,H=1;function w(e){const t={},i=Object.keys(e);i.sort();for(const o of i)t[o]=e[o];return t}const O=e=>`${JSON.stringify(e,void 0,2)}
|
|
2
|
+
`,P=e=>S(O(e)),c=e=>typeof e=="object"&&e!==null,x=e=>c(e)&&c(e.fields)&&c(e.indexes)&&c(e.relations)&&typeof e.shardMode=="string",J=e=>{if(e===void 0||e.trim()==="")return{status:"absent"};let t;try{t=JSON.parse(e)}catch(o){return{error:`baseline is not valid JSON: ${o instanceof Error?o.message:String(o)}`,status:"invalid"}}if(!c(t)||t.version!==1||!c(t.tables))return{error:`baseline is malformed or written by an incompatible version (expected version ${String(1)})`,status:"invalid"};for(const[o,r]of Object.entries(t.tables))if(!x(r))return{error:`baseline table "${o}" has an invalid structure`,status:"invalid"};return{snapshot:{jurisdiction:typeof t.jurisdiction=="string"?t.jurisdiction:void 0,migrationIds:Array.isArray(t.migrationIds)?t.migrationIds:[],tables:t.tables,version:1},status:"ok"}},F=(e,t)=>e.unique===t.unique&&e.fields.length===t.fields.length&&e.fields.every((i,o)=>i===t.fields[o]),y=e=>e.unique!==void 0,p=({nullable:e,optional:t,refined:i,unique:o,...r})=>JSON.stringify(w(r)),g=e=>({form:JSON.stringify([p(e),e.optional===!0,e.nullable===!0]),refined:e.refined===!0}),v=e=>e.kind==="union"&&e.members?e.members.map(t=>g(t)):[g({...e,nullable:!1,optional:!1})],T=(e,t)=>{if(t.kind!=="union")return!1;const i=v(t);return v(e).every(o=>i.some(r=>r.form===o.form&&(o.refined||!r.refined)))},a=e=>{switch(e.kind){case"array":return`array(${e.of?a(e.of):"?"})`;case"id":return`id(${e.ref??"?"})`;case"literal":return`literal(${e.literal??"?"})`;case"object":return`object({ ${Object.keys(e.fields??{}).join(", ")} })`;case"record":return`record(${e.key?a(e.key):"?"}, ${e.of?a(e.of):"?"})`;case"union":return(e.members??[]).map(t=>a(t)).join(" | ");default:return e.kind}},l=(e,t,i)=>({remediation:"backfill",scope:"table",severity:"breaking",summary:i,table:e,type:t}),f=(e,t,i)=>({remediation:"none",scope:"table",severity:"safe",summary:i,table:e,type:t}),_=(e,t,i,o,r)=>{if(!(i.kind===o.kind&&(!r||p(i)===p(o))))return r&&T(i,o)?f(e,"widenedFieldShape",`field ${e}.${t} widened: ${a(i)} → ${a(o)} — every stored value stays valid`):i.kind!==o.kind?l(e,"changedFieldKind",`field ${e}.${t} changed type: ${i.kind} → ${o.kind} — add a data migration to convert existing values`):l(e,"changedFieldShape",`field ${e}.${t} changed shape: ${a(i)} → ${a(o)} — stored values were written against the old shape; add a data migration to convert them`)},j=(e,t,i,o)=>{const r=[];return i.unique!==o.unique&&r.push(o.unique===!0?l(e,"addedFieldConstraint",`field ${e}.${t} became unique — existing duplicates would violate it; add a data migration to de-duplicate first`):f(e,"relaxedFieldConstraint",`field ${e}.${t} is no longer unique`)),i.nullable!==o.nullable&&r.push(o.nullable===!0?f(e,"relaxedFieldConstraint",`field ${e}.${t} became nullable`):l(e,"addedFieldConstraint",`field ${e}.${t} is no longer nullable — rows holding NULL would be invalid; add a data migration to backfill them`)),i.refined!==o.refined&&r.push(o.refined===!0?l(e,"addedFieldConstraint",`field ${e}.${t} gained a validation refinement — stored values were never checked against it; add a data migration if any could fail`):f(e,"relaxedFieldConstraint",`field ${e}.${t} dropped its validation refinement`)),r},q=(e,t,i,o)=>{const r=[],n=y(i)&&y(o),s=_(e,t,i,o,n);return s&&r.push(s),n&&r.push(...j(e,t,i,o)),i.optional&&!o.optional?r.push({remediation:"backfill",severity:"breaking",summary:`field ${e}.${t} became required — rows missing it would be invalid; add a data migration to backfill it`,table:e,scope:"table",type:"fieldOptionalToRequired"}):!i.optional&&o.optional&&r.push({remediation:"none",scope:"table",severity:"safe",summary:`field ${e}.${t} became optional`,table:e,type:"fieldRequiredToOptional"}),r},E=(e,t,i)=>i.optional?{remediation:"none",scope:"table",severity:"safe",summary:`added optional field ${e}.${t}`,table:e,type:"addedOptionalField"}:{remediation:"backfill",severity:"breaking",summary:`added required field ${e}.${t} — existing rows have no value; add a data migration to backfill it`,table:e,scope:"table",type:"addedRequiredField"},A=(e,t,i,o)=>{for(const[r,n]of Object.entries(i.fields)){const s=t.fields[r];s===void 0?o.push(E(e,r,n)):o.push(...q(e,r,s,n))}for(const r of Object.keys(t.fields))i.fields[r]===void 0&&o.push({remediation:"backfill",severity:"breaking",summary:`removed field ${e}.${r} — add a data migration if stored data must be cleaned up`,table:e,scope:"table",type:"removedField"})},M=(e,t,i,o)=>{for(const[r,n]of Object.entries(i.indexes)){const s=t.indexes[r];if(s===void 0){o.push(n.unique?{remediation:"backfill",scope:"table",severity:"breaking",summary:`added unique index ${r} on ${e} — existing duplicates would violate it; add a data migration to de-duplicate first`,table:e,type:"addedIndex"}:{remediation:"none",scope:"table",severity:"safe",summary:`added index ${r} on ${e}`,table:e,type:"addedIndex"});continue}F(s,n)||o.push({remediation:"code",severity:"breaking",summary:`index ${r} on ${e} changed shape — a query may have relied on the old index`,table:e,scope:"table",type:"changedIndex"})}for(const r of Object.keys(t.indexes))i.indexes[r]===void 0&&o.push({remediation:"code",severity:"breaking",summary:`removed index ${r} on ${e} — a query that used \`.withIndex("${r}")\` would break`,table:e,scope:"table",type:"removedIndex"})},C=(e,t,i,o)=>{for(const r of Object.keys(i.relations))t.relations[r]===void 0&&o.push({remediation:"none",scope:"schema",severity:"safe",summary:`added relation ${e}.${r}`,table:e,type:"addedRelation"});for(const r of Object.keys(t.relations))i.relations[r]===void 0&&o.push({remediation:"code",scope:"schema",severity:"breaking",summary:`removed relation ${e}.${r}`,table:e,type:"removedRelation"})},$="shardBy:_unknown_",u="global",I=(e,t)=>e===u&&t.startsWith(`${u}:`)||t===u&&e.startsWith(`${u}:`),R=(e,t,i)=>{if(t===i)return i!==$?void 0:{remediation:"rehome",scope:"table",severity:"breaking",summary:`table ${e} declares a non-literal .shardBy(...) key, so codegen cannot read which column partitions it — every such key records as "${$}" and two DIFFERENT keys would compare equal. Pass the shard key as a string literal; until then this is reported on every run, because the alternative is a silent pass on a re-home that strands every row (export/import is the only way back).`,table:e,type:"changedShardMode"};if(!I(t,i))return{remediation:"rehome",severity:"breaking",summary:`table ${e} changed shard mode: ${t} → ${i} — its physical storage moves, and existing rows do NOT follow the schema; re-home them with an export/import round trip (https://lunora.sh/docs/concepts/sharding#migrating-a-populated-table)`,table:e,scope:"table",type:"changedShardMode"}},b=e=>e.memory!==void 0,k=e=>e.after??0,d=e=>e.after===void 0?`.ttl("${e.field}")`:`.ttl("${e.field}", { after: ${String(e.after)} })`,V=(e,t,i)=>{if(t===void 0&&i===void 0)return;const o=h=>({remediation:"backfill",scope:"table",severity:"breaking",summary:h,table:e,type:"changedTtlPolicy"}),r=h=>({remediation:"none",scope:"table",severity:"safe",summary:h,table:e,type:"changedTtlPolicy"});if(i===void 0)return r(`table ${e} dropped its TTL policy — its rows are no longer swept`);if(t===void 0)return o(`table ${e} gained a TTL policy ${d(i)} — every row already past the cutoff is deleted on the next alarm sweep; add a data migration to refresh or clear "${i.field}" on the rows written before it`);if(t.field!==i.field)return o(`table ${e} moved its TTL to a different column: ${d(t)} → ${d(i)} — rows are now expired by a column they were never written against; add a data migration to populate "${i.field}"`);const n=k(t),s=k(i);return s<n?o(`table ${e} shortened its TTL: ${d(t)} → ${d(i)} — rows that were not expired under the old offset are deleted on the next alarm sweep; add a data migration to refresh "${i.field}" on the rows that must survive`):s>n?r(`table ${e} lengthened its TTL: ${d(t)} → ${d(i)}`):void 0},L=(e,t,i)=>{const o=[];return t.memory!==i.memory&&o.push(i.memory===!0?{remediation:"rehome",scope:"table",severity:"breaking",summary:`table ${e} became a .memory() table — every row is deleted in every shard on the next Durable Object cold start, and no data migration survives that; export the rows first if they must be kept, or revert`,table:e,type:"changedMemoryMode"}:{remediation:"none",scope:"table",severity:"safe",summary:`table ${e} is no longer a .memory() table — its rows now survive a cold start`,table:e,type:"changedMemoryMode"}),t.commitOrdered!==i.commitOrdered&&o.push(i.commitOrdered===!0?{remediation:"backfill",scope:"table",severity:"breaking",summary:`table ${e} became .commitOrdered() — rows written before it carry no _commitSeq, so a \`_commitSeq > cursor\` changefeed never offers them; add a data migration over the table to stamp them (the rewrite allocates a sequence)`,table:e,type:"changedCommitOrdering"}:{remediation:"code",scope:"table",severity:"breaking",summary:`table ${e} is no longer .commitOrdered() — new rows carry no _commitSeq, so a \`_commitSeq > cursor\` changefeed stops advancing without erroring; update the consumers before deploying`,table:e,type:"changedCommitOrdering"}),o},D=(e,t,i,o)=>{const r=R(e,t.shardMode,i.shardMode);if(r&&o.push(r),b(t)&&b(i)){o.push(...L(e,t,i));const n=V(e,t.ttl,i.ttl);n&&o.push(n)}A(e,t,i,o),M(e,t,i,o),C(e,t,i,o)},B=(e,t)=>{const i=[],o=e?.tables??{};for(const[r,n]of Object.entries(t.tables)){const s=o[r];if(s===void 0){i.push({remediation:"none",scope:"table",severity:"safe",summary:`added table ${r}`,table:r,type:"addedTable"});continue}D(r,s,n,i)}for(const r of Object.keys(o))t.tables[r]===void 0&&i.push({remediation:"rehome",scope:"table",severity:"breaking",summary:`removed table ${r} — its rows stay in each shard's SQLite, unreachable through the schema; export the shard first if the data must be kept`,table:r,type:"removedTable"});if(e!==void 0&&e.jurisdiction!==t.jurisdiction){const r=e.jurisdiction??"(none)",n=t.jurisdiction??"(none)";i.push({remediation:"rehome",scope:"schema",severity:"breaking",summary:`Durable Object jurisdiction changed from ${r} to ${n} — this re-homes every DO and strands all existing shard, scheduler, and session-DO data in the old region (no in-place migration; export then import to move it). Revert the change, or override the gate to proceed intentionally.`,type:"changedJurisdiction"})}return{changes:i}};export{H as SCHEMA_SNAPSHOT_VERSION,a as describeShape,q as diffExistingField,B as diffSchemaSnapshots,P as hashSchemaSnapshot,x as isValidTableSnapshot,J as parseSnapshotJson,O as serializeSchemaSnapshot,w as sortKeys};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{existsSync as m}from"node:fs";import{join as u}from"node:path";import{SyntaxKind as p,Node as o}from"ts-morph";import{diagnosticAt as g}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{b as f}from"./module-specifiers-WF8iAydP.mjs";import{p as d}from"./parse-validator-IDBKIT7M.mjs";import{findObjectProperty as l}from"./isTestPath-B81lOULB.mjs";import{a as S}from"./attribution-hVBriwzy.mjs";const h="shapes.ts",b=r=>{const t=r.getSymbol();if(!t)return r.getText()==="defineShape";for(const e of t.getDeclarations())if(o.isImportSpecifier(e))return f(e.getImportDeclaration().getModuleSpecifierValue())?e.getNameNode().getText()==="defineShape":!1;return!1},x=r=>{const t=r.getSymbol();if(!t)return!1;for(const e of t.getDeclarations()){if(!o.isNamespaceImport(e))continue;const i=e.getFirstAncestorByKind(p.ImportDeclaration);return i!==void 0&&f(i.getModuleSpecifierValue())}return!1},y=r=>{if(o.isIdentifier(r))return b(r);if(o.isPropertyAccessExpression(r)){const t=r.getExpression();return r.getName()==="defineShape"&&o.isIdentifier(t)&&x(t)}return!1},N=r=>{const[t]=r.getArguments();if(!t||!o.isObjectLiteralExpression(t))return;const e=l(t,"table");if(!e||!o.isPropertyAssignment(e))return;const i=e.getInitializer();return i&&o.isStringLiteral(i)?i.getLiteralValue():void 0},E=r=>{const[t]=r.getArguments();if(!t||!o.isObjectLiteralExpression(t))return{};const e=l(t,"args");if(!e||!o.isPropertyAssignment(e))return{};const i=e.getInitializer();return!i||!o.isObjectLiteralExpression(i)?{}:d(i)},I=r=>{const t=[];for(const e of r.getVariableDeclarations()){const i=e.getInitializer();if(i?.getKind()!==p.CallExpression)continue;const s=i,a=s.getExpression();if(!y(a))continue;const n=e.getNameNode();if(!o.isIdentifier(n)){if(e.getVariableStatement()?.hasExportKeyword()!==!0)continue;throw g(n,"defineShape exports must be plain named exports (no destructuring)")}const c=S(e,"binding");c!==void 0&&t.push({args:E(s),exportName:c,filePath:"shapes",table:N(s)})}return t},z=(r,t)=>{const e=u(t,h);if(!m(e))return[];const i=r.getSourceFile(e)??r.addSourceFileAtPath(e),s=I(i);return s.sort((a,n)=>a.exportName.localeCompare(n.exportName)),s};export{h as SHAPES_FILENAME,z as discoverShapes};
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import{LunoraError as v}from"@lunora/errors";import{SCHEMA_SNAPSHOT_VERSION as E,sortKeys as f,diffSchemaSnapshots as I,parseSnapshotJson as A}from"./SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs";import{isHyperdriveGlobalTable as L}from"./isD1GlobalTable-udvHAAzD.mjs";const O=e=>{const t=e.shardMode;return t==="global"?`global:${L(e)?"hyperdrive":"d1"}`:t==="root"?t:`shardBy:${t.field}`},_=(e,t)=>{const s=JSON.stringify(e),i=JSON.stringify(t);return s===i?0:s<i?-1:1},l=e=>{const t=e.kind==="optional",s=t?e.inner:void 0,i=s??e,r={kind:t?s?.kind??"unknown":e.kind,nullable:i.column?.notNull===!1||e.column?.notNull===!1,optional:t,unique:i.column?.unique===!0||e.column?.unique===!0,...j[i.kind]?.(i)};return(i.hasRefinement===!0||e.hasRefinement===!0)&&(r.refined=!0),r},N=e=>{const t={};for(const[s,i]of Object.entries(e))t[s]=l(i);return f(t)},j={array:e=>e.inner?{of:l(e.inner)}:{},id:e=>e.tableName===void 0?{}:{ref:e.tableName},literal:e=>e.literalValue===void 0?{}:{literal:e.literalValue},object:e=>e.shape?{fields:N(e.shape)}:{},record:e=>({...e.keyType?{key:l(e.keyType)}:{},...e.valueType?{of:l(e.valueType)}:{}}),union:e=>e.members?{members:e.members.map(t=>l(t)).toSorted(_)}:{}},D=e=>{const t={};for(const[n,a]of Object.entries(e.shape))t[n]=l(a);const s={};for(const n of e.indexes)s[n.name]={fields:[...n.fields],unique:n.unique??!1};const i={};for(const n of e.relations)i[n.name]=n.through===void 0?{field:n.field,kind:n.kind,table:n.table}:{kind:n.kind,table:n.table,through:{...n.through}};const r={commitOrdered:e.commitOrdered===!0,fields:f(t),indexes:f(s),memory:e.memory===!0,relations:f(i),shardMode:O(e)};return e.ttl&&(r.ttl=e.ttl.after===void 0?{field:e.ttl.field}:{after:e.ttl.after,field:e.ttl.field}),r},C=(e,t)=>{const s={};for(const r of e.tables)s[r.name]=D(r);const i=[...t].sort();return{jurisdiction:e.jurisdiction,migrationIds:i,tables:f(s),version:E}};class R extends v{constructor(t){super("SCHEMA_SNAPSHOT_PARSE",t,{name:"SchemaSnapshotParseError"})}}const J=e=>{const t=A(e);if(t.status==="invalid")throw new R(t.error);return t.status==="ok"?t.snapshot:void 0},M={build:{allowDrift:!0,updateBaseline:!1},deploy:{allowDrift:!0,updateBaseline:!0},prepare:{allowDrift:!0,updateBaseline:!0},verify:{allowDrift:!0,updateBaseline:!1}},y=" • For backward-compatible changes (e.g. adding an optional field): pass `--allow-schema-drift` to skip the block.",k=" • To accept the new shape without a migration (you know data is compatible): pass `--update-schema-baseline`.",B=e=>{const t=e===void 0?void 0:M[e];if(e===void 0||t===void 0)return`${y}
|
|
2
|
+
${k}
|
|
3
|
+
`;const s=t.updateBaseline?k:` • To accept the new shape without a migration, run \`lunora prepare --update-schema-baseline\` — \`lunora ${e}\` does not take that flag.`;return`${y}
|
|
4
|
+
${s}
|
|
5
|
+
`},p=e=>e.map(t=>` - ${t.summary}`).join(`
|
|
6
|
+
`),w=e=>e.remediation==="backfill"&&e.table!==void 0,x=/^[A-Za-z_]\w*$/u,F=e=>` lunora migrate create backfill_${e} --table ${e}`,P=(e,t,s)=>{const i=[...new Set(e.filter(n=>w(n)).map(n=>n.table))],r=[];if(i.length>0){r.push(" • Add a `defineMigration({ id, table, up })` in lunora/ for each affected table, then re-run this command — the baseline is re-blessed on a successful deploy, not by `lunora migrate` itself.\n");const n=i.filter(a=>x.test(a));n.length>0&&r.push(`
|
|
7
|
+
Scaffold the missing migration(s) — the generated \`up\` is an identity placeholder you must fill in:
|
|
8
|
+
${n.map(a=>F(a)).join(`
|
|
9
|
+
`)}
|
|
10
|
+
|
|
11
|
+
`)}return t.length>0&&r.push(` • Migration(s) ${t.join(", ")} declare a non-literal \`table\`, so codegen cannot tell which table they visit and they cover nothing. Use a string literal.
|
|
12
|
+
`),r.push(B(s)),[`${s??"deploy"} blocked: ${String(e.length)} unresolved breaking schema change(s) since the last blessed schema baseline:`,p(e),"",`To fix:
|
|
13
|
+
${r.join("")}Docs: https://lunora.dev/docs/migrations`].join(`
|
|
14
|
+
`)},V=e=>{const{allowDrift:t=!1,baseline:s,command:i,current:r,migrations:n}=e,a=I(s,r),u=a.changes.filter(o=>o.severity==="breaking"),b=r.migrationIds.filter(o=>!(s?.migrationIds??[]).includes(o)),m=n.filter(o=>b.includes(o.id)),c=(o,h)=>({blocked:o,changes:a.changes,newMigrationIds:b,reason:h}),T=new Set(m.filter(o=>o.table!=="").map(o=>o.table)),$=m.filter(o=>o.table==="").map(o=>o.id);if(a.changes.length===0||s===void 0)return c(!1,"");if(u.length===0)return c(!1,`schema drift detected (all additive/safe):
|
|
15
|
+
${p(a.changes)}`);const g=u.filter(o=>!w(o)||!T.has(o.table));if(g.length===0){const o=new Set(u.map(d=>d.table)),h=m.filter(d=>o.has(d.table)).map(d=>d.id);return c(!1,`breaking schema drift detected, covered by ${String(h.length)} new migration(s) (${h.join(", ")}):
|
|
16
|
+
${p(u)}`)}const S=P(g,$,i);return t?c(!1,`${S}
|
|
17
|
+
|
|
18
|
+
(overridden by --allow-schema-drift)`):c(!0,S)};export{R as SchemaSnapshotParseError,C as buildSchemaSnapshot,V as evaluateSchemaDrift,J as parseSchemaSnapshot};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{existsSync as b}from"node:fs";import{join as y}from"node:path";import{LunoraError as w}from"@lunora/errors";import k from"@lunora/scheduler/validate";import{workflowDefaultName as E,workflowClassName as v}from"@lunora/workflow";import{Node as n,VariableDeclarationKind as S,SyntaxKind as x}from"ts-morph";import{diagnosticAt as c}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{unwrapToCallExpression as N,findObjectProperty as d,stringPropertyFor as L}from"./isTestPath-B81lOULB.mjs";import{a as P}from"./attribution-hVBriwzy.mjs";import{r as $}from"./handler-reference-vIeqkhV_.mjs";const A="workflows.ts",W=new Set(["do","sleep","sleepUntil","waitForEvent"]),C=o=>{const e=o.getSymbol();if(!e)return o.getText()==="defineWorkflow";for(const t of e.getDeclarations())if(n.isImportSpecifier(t))return t.getImportDeclaration().getModuleSpecifierValue()!=="@lunora/workflow"?!1:t.getNameNode().getText()==="defineWorkflow";return!1},m=L("workflow"),O=(o,e,t)=>{if(n.isNumericLiteral(o))return o.getLiteralValue();throw c(o,`workflow "${e}": \`${t}\` must be a static number literal — it is deploy configuration codegen writes into wrangler.jsonc`)},f=(o,e)=>{const t=d(o,e);return t&&n.isPropertyAssignment(t)?t.getInitializerOrThrow():void 0},g=(o,e,t)=>{if(n.isObjectLiteralExpression(o))return o;throw c(o,`workflow "${e}": \`${t}\` must be an inline object literal — it is deploy configuration codegen writes into wrangler.jsonc`)},D=(o,e)=>{if(!n.isArrayLiteralExpression(o)||o.getElements().length===0)throw c(o,`workflow "${e}": \`schedules\` must be a non-empty inline array of cron expression string literals`);return o.getElements().map(t=>{const r=m(t,e,"schedules[]");if(!k(r))throw c(t,`workflow "${e}": schedule "${r}" is not a valid cron expression`);return r})},I=(o,e)=>{const t={},r=f(o,"schedules");r!==void 0&&(t.schedules=D(r,e));const s=f(o,"limits");if(s!==void 0){const i=f(g(s,e,"limits"),"steps");if(i===void 0)t.limits={};else{const l=O(i,e,"limits.steps");if(!Number.isInteger(l)||l<=0)throw c(i,`workflow "${e}": \`limits.steps\` must be a positive integer (got ${String(l)})`);t.limits={steps:l}}}const a=f(o,"defaultRetention");if(a!==void 0){const i=g(a,e,"defaultRetention"),l={};for(const u of["errorRetention","successRetention"]){const p=f(i,u);p!==void 0&&(l[u]=m(p,e,`defaultRetention.${u}`))}t.defaultRetention=l}return t},F=o=>{const e=o.getExpression();if(!n.isPropertyAccessExpression(e)||!W.has(e.getName()))return!1;const t=e.getExpression();return n.isPropertyAccessExpression(t)&&t.getName()==="step"?!0:n.isIdentifier(t)&&t.getText()==="step"},T=o=>{if(!o)return[];const e=[];for(const t of o.getDescendantsOfKind(x.CallExpression)){if(!F(t))continue;const r=t.getArguments()[0];!r||!(n.isStringLiteral(r)||n.isNoSubstitutionTemplateLiteral(r))||e.push({line:t.getStartLineNumber(),method:t.getExpression().getName(),name:r.getLiteralValue()})}return e},h=o=>{let e=o;for(;e&&(n.isAsExpression(e)||n.isSatisfiesExpression(e)||n.isParenthesizedExpression(e));)e=e.getExpression();return e},R=o=>{const e=h(o);if(e&&n.isObjectLiteralExpression(e))return e;if(!(!e||!n.isIdentifier(e)))for(const t of e.getSymbol()?.getDeclarations()??[]){const s=n.isVariableDeclaration(t)&&t.getVariableStatement()?.getDeclarationKind()===S.Const?h(t.getInitializer()):void 0;if(s&&n.isObjectLiteralExpression(s))return s}},j=(o,e)=>{const t=d(o,"handler"),r=$(t,e);return r!==void 0?r:{body:t!==void 0&&n.isPropertyAssignment(t)?t.getInitializer():t}},K=(o,e,t)=>{const r=R(o.getArguments()[0]);if(!r)throw c(o,`workflow "${e}": defineWorkflow's argument must be an object literal, or a local \`const\` holding one — codegen reads \`name\` and the \`ctx.step.*\` calls out of it statically. Keep the handler wherever you like and pass it through: \`const config = { handler: myHandler }; export const ${e} = defineWorkflow(config);\`.`);const s=j(r,t),a={className:v(e),exportName:e,name:E(e),steps:T(s.body),...s.file===void 0?{}:{handlerFile:s.file},...s.site===void 0?{}:{handlerSite:s.site}},i=d(r,"name");return i&&n.isPropertyAssignment(i)&&(a.name=m(i.getInitializerOrThrow(),e,"name")),{...a,...I(r,e)}},V=(o,e)=>{const t=[];for(const r of o.getVariableDeclarations()){const s=N(r.getInitializer());if(!s)continue;const a=s.getExpression();if(!n.isIdentifier(a)||!C(a))continue;const i=r.getNameNode();if(!n.isIdentifier(i)){if(r.getVariableStatement()?.hasExportKeyword()!==!0)continue;throw c(i,"defineWorkflow exports must be plain named exports (no destructuring)")}const l=P(r,"binding");l!==void 0&&t.push(K(s,l,e))}return t},z=o=>{const e=new Map,t=new Map;for(const r of o){const s=e.get(r.name);if(s!==void 0)throw new w("DUPLICATE_WORKFLOW_NAME",`Duplicate workflow name "${r.name}": produced by both "${s}" and "${r.exportName}". Deployed workflow names must be unique across the project.`,{status:500});e.set(r.name,r.exportName);const a=t.get(r.className);if(a!==void 0)throw new w("DUPLICATE_WORKFLOW_CLASS",`Duplicate workflow class "${r.className}": produced by both "${a}" and "${r.exportName}". Workflow export names must yield unique generated class names.`,{status:500});t.set(r.className,r.exportName)}},Y=(o,e)=>{const t=y(e,A);if(!b(t))return[];const r=o.getSourceFile(t)??o.addSourceFileAtPath(t),s=V(r,e);return s.sort((a,i)=>a.exportName.localeCompare(i.exportName)),z(s),s};export{A as WORKFLOWS_FILENAME,Y as discoverWorkflows};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{callSiteCallers as y,byCodepoint as k}from"@lunora/advisor";import{Node as r,SyntaxKind as p,VariableDeclarationKind as F,ts as O}from"ts-morph";import{i as M}from"./reserved-words-CW1QFbTd.mjs";import{isWriteTarget as A,unwrapExpression as T}from"./isTestPath-B81lOULB.mjs";const N=new WeakMap,V=e=>e.getStatements().flatMap(t=>r.isFunctionDeclaration(t)?[t]:r.isVariableStatement(t)?t.getDeclarations().filter(o=>r.isIdentifier(o.getNameNode())):[]),x=e=>r.isStringLiteral(e)?e.getLiteralValue():e.getText(),C=e=>{if(r.isFunctionDeclaration(e)||r.isClassDeclaration(e)){const t=e.getName();return e.hasExportKeyword()?[[t??"default",e.hasDefaultKeyword()?"default":t??"default"]]:[]}return!r.isVariableStatement(e)||!e.hasExportKeyword()?[]:e.getDeclarations().flatMap(t=>{const o=t.getNameNode();return r.isIdentifier(o)?[[o.getText(),o.getText()]]:o.getDescendantsOfKind(p.BindingElement).flatMap(n=>r.isIdentifier(n.getNameNode())?[[n.getName(),n.getName()]]:[])})},I=e=>{if(r.isExportDeclaration(e))return e.hasModuleSpecifier()||e.isTypeOnly()?[]:e.getNamedExports().filter(o=>!o.isTypeOnly()).map(o=>{const n=x(o.getNameNode()),s=o.getAliasNode();return[n,s===void 0?n:x(s)]});const t=r.isExportAssignment(e)&&!e.isExportEquals()?e.getExpression():void 0;return r.isIdentifier(t)?[[t.getText(),"default"]]:C(e)},h=new WeakMap,P=e=>{const t=h.get(e.compilerNode);if(t!==void 0)return t;const o=new Map;for(const[s,c]of e.getStatements().flatMap(i=>I(i)))o.set(s,(o.get(s)??new Set).add(c));const n=new Map([...o].map(([s,c])=>[s,[...c].toSorted(G)]));return h.set(e.compilerNode,n),n},g=e=>{const t=r.isBindingElement(e)?e.getFirstAncestorByKind(p.VariableStatement):void 0,o=r.isVariableDeclaration(e)?e.getVariableStatement():void 0,n=r.isFunctionDeclaration(e)?e:t??o;if(n===void 0||!r.isSourceFile(n.getParent()))return[];const s=r.isFunctionDeclaration(e)?e.getName()??"default":e.getName();return P(e.getSourceFile()).get(s)??[]},K=e=>new Map(e.flatMap(t=>{const o=g(t);return o.length===0?[]:[[t.compilerNode,o]]})),L=e=>{const t=T(e);return t!==void 0&&(r.isArrowFunction(t)||r.isFunctionExpression(t))},b=(e,t)=>{for(const o of e.getAncestors()){if(r.isExportAssignment(o)&&!o.isExportEquals())return{kind:"export",name:"default"};if((r.isFunctionDeclaration(o)&&r.isSourceFile(o.getParent())||r.isVariableDeclaration(o)&&r.isSourceFile(o.getVariableStatement()?.getParent())&&r.isIdentifier(o.getNameNode()))&&(r.isFunctionDeclaration(o)||r.isVariableDeclaration(o))){const s=t.get(o.compilerNode)?.[0];return s!==void 0?{kind:"export",name:s}:r.isFunctionDeclaration(o)||L(o.getInitializer())?{declaration:o,kind:"helper"}:{kind:"untracked"}}}return{kind:"untracked"}},E=e=>{for(const t of e.getAncestors()){if(r.isExpressionWithTypeArguments(t)){const o=t.getParent();return!(r.isHeritageClause(o)&&o.getToken()===p.ExtendsKeyword&&(r.isClassDeclaration(o.getParent())||r.isClassExpression(o.getParent())))}if(O.isTypeNode(t.compilerNode))return!0}return!1},U=e=>{const t=e.getParent(),o=r.isPropertyAccessExpression(t)&&t.getNameNode()===e,n=(r.isPropertyAssignment(t)||r.isMethodDeclaration(t))&&t.getNameNode()===e;return!o&&!n&&!E(e)},v=e=>{const t=e.getParent();return r.isShorthandPropertyAssignment(t)&&t.getNameNode()===e?t.getValueSymbol():e.getSymbol()},B=e=>{const t=v(e);return t?.getValueDeclaration()??t?.getDeclarations()[0]},S=new WeakMap,R=/\/typescript\/lib\/lib\.[^/]+\.d\.ts$/u,$=e=>{const t=e.getFilePath();return e.isDeclarationFile()&&(R.test(t)||t.includes("/@types/node/"))},ee=e=>{const t=e.getNameNode(),o=r.isFunctionDeclaration(e)?void 0:e.getFirstAncestorByKind(p.VariableDeclarationList);if(!r.isIdentifier(t)||o?.getDeclarationKind()===F.Const||$(e.getSourceFile()))return!1;let n=S.get(e.compilerNode);if(n===void 0){const s=r.isFunctionDeclaration(e)?e.getSourceFile():e.getFirstAncestor(i=>r.isFunctionLikeDeclaration(i)||r.isArrowFunction(i))??e.getSourceFile(),c=t.getText();n=s.getDescendantsOfKind(p.Identifier).some(i=>i!==t&&i.getText()===c&&A(i)&&B(i)?.compilerNode===e.compilerNode),S.set(e.compilerNode,n)}return n},_=e=>{const t=new Map,o=new Set,n=new Set;for(const s of e){const c=s.getNameNode(),i=c?.getSymbol()?.compilerSymbol;c!==void 0&&i!==void 0&&(t.set(i,s.compilerNode),o.add(c.compilerNode),n.add(c.getText()))}return{bySymbol:t,nameNodes:o,spellings:n}},W=(e,t,o)=>{const{bySymbol:n,nameNodes:s,spellings:c}=_(t),i=new Map;for(const a of e.getDescendantsOfKind(p.Identifier)){if(!c.has(a.getText())||s.has(a.compilerNode)||E(a))continue;const l=v(a)?.compilerSymbol,d=l===void 0?void 0:n.get(l);d!==void 0&&i.set(d,[...i.get(d)??[],b(a,o)])}return i},z=(e,t)=>{const o=new Map(e.map(a=>[a.compilerNode,new Set])),n=new Set,s=a=>(o.get(a)?.size??0)+(n.has(a)?1:0),c=(a,l)=>{const d=s(a),u=o.get(a),m=l.kind==="helper"?l.declaration.compilerNode:void 0;l.kind==="export"&&u?.add(l.name);for(const w of m===void 0?[]:o.get(m)??[])u?.add(w);return(l.kind==="untracked"||m!==void 0&&n.has(m))&&n.add(a),s(a)!==d};let i=!0;for(;i;){i=!1;for(const[a,l]of t)for(const d of l)i=c(a,d)||i}return new Map([...o].map(([a,l])=>[a,{callers:[...l].toSorted((d,u)=>d.localeCompare(u)),untracked:n.has(a)}]))},H=e=>{const t=N.get(e.compilerNode);if(t!==void 0)return t;const o=V(e),n=K(o),s=o.filter(i=>!n.has(i.compilerNode)),c={exportNames:n,helperReach:s.length===0?new Map:z(s,W(e,s,n))};return N.set(e.compilerNode,c),c},te=e=>{const t=H(e.getSourceFile()),o=b(e,t.exportNames);switch(o.kind){case"export":return{kind:"export",name:o.name};case"helper":{const n=o.declaration.getName(),s=t.helperReach.get(o.declaration.compilerNode);if(n===void 0||s===void 0)throw new Error(`call-site attribution: helper at ${o.declaration.getSourceFile().getFilePath()} is not indexed`);return{callers:s.callers,kind:"helper",name:n,...s.untracked?{untracked:!0}:{}}}default:return{kind:"module"}}},q=e=>{if(e.kind==="helper"&&e.untracked===!0)return;const t=y(e);return t.length===0?void 0:t},X=(e,t)=>{const o=new Set(y(e).map(n=>t(n)));return o.has("public")?"public":q(e)===void 0||o.has(void 0)?void 0:"internal"},oe=(e,t)=>{const o=new Map(t.map(n=>[`${n.filePath}:${n.exportName}`,n.visibility]));return e.map(n=>{const s=X(n.scope,c=>o.get(`${n.file}:${c}`));return s===void 0?n:{...n,visibility:s}})},f=/^[$A-Z_a-z][\w$]*$/u,D=e=>f.test(e),j=e=>{const t=g(e);return t.length===0?r.isVariableDeclaration(e)&&e.getVariableStatement()?.hasExportKeyword()===!0?e.getName():void 0:t.find(o=>D(o))??e.getName()},ne=e=>e.getVariableStatements().flatMap(t=>t.getDeclarations()).filter(t=>j(t)!==void 0),re=(e,t)=>{if(r.isIdentifier(e.getNameNode()))return e.getVariableStatement()?.hasExportKeyword()===!0?e.getName():g(e).find(o=>t==="binding"?M(o):D(o))},G=(e,t)=>Number(f.test(t))-Number(f.test(e))||k(e,t);export{re as a,ne as b,te as c,j as d,P as e,B as f,ee as g,U as h,D as i,g as j,E as k,$ as l,q as m,v as r,oe as w};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{m as b}from"./modules-CjOcuQnK.mjs";import{r as E}from"./json-data-Chfs2Cz5.mjs";import{LUNORA_ERROR_CODES as P,objectSchema as g,validatorIrToJsonSchema as l}from"./LUNORA_ERROR_CODES-C2s0xWQD.mjs";import{G as A}from"./shared-DnCokNcE.mjs";import{s as m}from"./dispatch-namespace-DwTjD7BU.mjs";const T="/_lunora/rest",x=["authorization","cf-access-jwt-assertion","cookie","payment-signature","x-payment"],v=["x-d1-bookmark","x-lunora-shard-key"],j=e=>[...x,...(e.credentialHeaders??[]).map(t=>t.toLowerCase())],O=e=>Number.isFinite(e)?Math.max(0,Math.floor(e)):0,$=(...e)=>{const t=[];for(const r of e)for(const n of r?.split(",")??[]){const s=n.trim().toLowerCase();s!==""&&!t.includes(s)&&t.push(s)}return t.length===0?void 0:t.join(", ")},k=(e,t)=>{const r=[t,`max-age=${String(O(e.maxAge))}`];return e.staleWhileRevalidate!==void 0&&r.push(`stale-while-revalidate=${String(O(e.staleWhileRevalidate))}`),r.join(", ")},N=e=>e.scope==="public"?$(e.vary,...j(e),...v):$(e.vary,...v),q=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)}},_=e=>{const t=q(e);if(t!==void 0)return`${T}/${t.namespace}/${t.name}`},C=e=>e==="query"?"GET":"POST",y="#/components/responses/LunoraError",R=/:([A-Za-z_$][\w$]*)/gu,w=e=>[...e.matchAll(R)].map(t=>t[1]),D=e=>e.replaceAll(R,"{$1}"),f=e=>e.kind==="optional"?e.inner??e:e,I=e=>{const t=new Set(w(e.path)),r=[];for(const[n,s]of Object.entries(e.searchParams)){const c=f(s);r.push({description:`Query parameter \`${n}\``,in:"query",name:n,required:s.kind!=="optional",schema:l(c)})}for(const[n,s]of Object.entries(e.params)){const c=f(s);r.push({description:`Path parameter \`${n}\``,in:t.has(n)?"path":"query",name:n,required:t.has(n)?!0:s.kind!=="optional",schema:l(c)})}return r},S=e=>e?{content:{"application/json":{schema:l(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."},L=(e,t)=>{const r=I(e),n={description:`${e.stream?"Streaming (SSE) ":""}HTTP route handler \`${e.exportName}\` (${e.method} ${e.path}).`,operationId:`${e.method.toLowerCase()}_${m(e.path)}`,responses:{200:S(e.output),204:{description:"No content (handler returned `undefined`)."},default:{$ref:y}},summary:`${e.method} ${e.path}`,tags:[t]};return r.length>0&&(n.parameters=r),Object.keys(e.body).length>0&&(n.requestBody={content:{"application/json":{schema:g(e.body)}},required:!0}),e.stream&&(n["x-lunora-stream"]="text/event-stream"),n},F=(e,t)=>{const r=`${m(e.filePath)}:${e.exportName}`,n={additionalProperties:!1,properties:{args:g(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:n}},required:!0},responses:{200:S(e.output),default:{$ref:y}},summary:`${e.kind}: ${r}`,tags:[t],"x-lunora-function-kind":e.kind},pathKey:`/_lunora/rpc#${r}`}},H=(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}},n={"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:k(r,r.scope),type:"string"}}};r.tag!==void 0&&(n["Cache-Tag"]={description:"Purge tag for `ctx.cache.purge({ tags: [...] })`.",schema:{example:r.tag,type:"string"}});const s=N(r);return s!==void 0&&(n.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:n}},M=(e,t)=>{const r=`${m(e.filePath)}:${e.exportName}`,n=_(r);if(n===void 0)return;const s=C(e.kind),c=s==="GET",i={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_${m(n)}`,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).",...H(e.expose?.cache,c?"get":"post")},default:{$ref:y}},summary:`${s} ${n}`,tags:[t],"x-lunora-function-kind":e.kind};if(c){const d=Object.entries(e.args).map(([u,h])=>{const o=f(h);return{description:`Argument \`${u}\` (JSON-encoded for non-string values).`,in:"query",name:u,required:h.kind!=="optional",schema:l(o)}});return d.length>0&&(i.parameters=d),{method:"get",operation:i,path:n}}return i.requestBody={content:{"application/json":{schema:g(e.args)}},required:Object.keys(e.args).length>0},{method:"post",operation:i,path:n}},J=e=>{const t=e.version??"0.0.0",r=Object.create(null),n=o=>r[o]??Object.create(null),s=new Set,c=e.modules??[],i=o=>b(c,o);for(const o of e.httpRoutes){const a=D(o.path),p=n(a);p[o.method.toLowerCase()]=L(o,i(o.filePath)),r[a]=p,s.add(i(o.filePath))}const d=e.functions.filter(o=>o.visibility!=="internal"&&o.kind!=="stream");for(const o of d){const{operation:a,pathKey:p}=F(o,i(o.filePath));r[p]={post:a},s.add(i(o.filePath))}for(const o of d){if(o.expose?.rest!==!0)continue;const a=M(o,i(o.filePath));if(a===void 0)continue;const p=n(a.path);p[a.method]=a.operation,r[a.path]=p}const u=[...s].toSorted((o,a)=>o.localeCompare(a)).map(o=>({description:c.find(p=>p.name===o)?.description??`Operations declared in \`lunora/${o}\`.`,name:o}));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:P,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:Object.fromEntries(Object.entries(r).map(([o,a])=>[o,{...a}])),tags:u}},z=e=>`${JSON.stringify(J(e),void 0,2)}
|
|
2
|
+
`,K=e=>`${A}export const openApiSpec = ${E(e,"Record<string, unknown>")};
|
|
3
|
+
`;export{J as buildOpenApiDocument,z as emitOpenApi,K as emitOpenApiModule};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{SyntaxKind as c,Node as r}from"ts-morph";import{CAPABILITIES as m}from"./CAPABILITY_PROBES-brcmKenl.mjs";import{bindingKeyName as p,listLunoraSourceFiles as g}from"./isTestPath-B81lOULB.mjs";import{scanImportDeclaration as u,noSandboxUsage as l}from"./discoverSandboxUsage-w6Q3RvxZ.mjs";const d="ctx",x=e=>{const t=new Set,o=new Set([d]),n=s=>{if(r.isObjectBindingPattern(s))for(const i of s.getElements()){const f=p(i);f&&t.add(f)}};for(const s of e.getDescendantsOfKind(c.BindingElement)){if(p(s)!==d)continue;const i=s.getNameNode();r.isIdentifier(i)?o.add(i.getText()):n(i)}const a=s=>r.isIdentifier(s)&&o.has(s.getText());for(const s of e.getDescendantsOfKind(c.PropertyAccessExpression))a(s.getExpression())&&t.add(s.getName());for(const s of e.getDescendantsOfKind(c.VariableDeclaration)){const i=s.getInitializer();i!==void 0&&a(i)&&n(s.getNameNode())}return t},E=e=>{if(e.isTypeOnly())return!0;if(r.isExportDeclaration(e)){const o=e.getNamedExports();return!e.isNamespaceExport()&&o.length>0&&o.every(n=>n.isTypeOnly())}const t=e.getNamedImports();return e.getDefaultImport()===void 0&&e.getNamespaceImport()===void 0&&t.length>0&&t.every(o=>o.isTypeOnly())},I=new Map(m.flatMap(({bindingFreeExports:e,moduleSpecifier:t})=>e===void 0?[]:[[t,new Set(e)]])),N=(e,t)=>{const o=I.get(t);if(o===void 0||r.isImportDeclaration(e)&&(e.getDefaultImport()!==void 0||e.getNamespaceImport()!==void 0))return!1;const n=r.isExportDeclaration(e)?e.getNamedExports():e.getNamedImports();return n.length>0&&n.every(a=>a.isTypeOnly()||o.has(a.getName()))},y=e=>{const t=new Set;for(const o of e.getDescendantsOfKind(c.CallExpression)){const[n]=o.getArguments();o.getExpression().getKind()===c.ImportKeyword&&(r.isStringLiteral(n)||r.isNoSubstitutionTemplateLiteral(n))&&t.add(n.getLiteralValue())}return t},S=e=>{const t=e.getImportDeclarations(),o=l();for(const n of t){const a=u(n);for(const s of Object.keys(o))o[s]||=a[s]}return{contextReads:x(e),dynamicImports:y(e),sandboxTools:o,valueImports:new Set([...t,...e.getExportDeclarations()].flatMap(n=>{const a=n.getModuleSpecifierValue();return a===void 0||E(n)||N(n,a)?[]:[a]}))}},T=e=>{const t=new Set,o=new Set,n=l(),a=new Set;for(const s of e){for(const i of s.contextReads)t.add(i);for(const i of s.dynamicImports)o.add(i);for(const i of s.valueImports)a.add(i);for(const i of Object.keys(n))n[i]||=s.sandboxTools[i]}return{contextReads:t,dynamicImports:o,sandboxTools:n,valueImports:a}},b=e=>new Set(m.filter(({contextProperty:t,moduleSpecifier:o})=>e.valueImports.has(o)||t!==void 0&&e.contextReads.has(t)).map(({key:t})=>t)),O=new RegExp(String.raw`\b${d}\b`,"u"),v=new RegExp(String.raw`\b(?:${m.flatMap(({contextProperty:e})=>e===void 0?[]:[e]).join("|")})\b`,"u"),h=e=>O.test(e)&&v.test(e),P=(e,t)=>{const o=T(g(t).map(a=>S(e.getSourceFile(a)??e.addSourceFileAtPath(a)))),n=b(o);return Object.fromEntries(m.map(({key:a})=>[a,n.has(a)]))};export{b as capabilitiesUsedBy,x as contextPropertiesRead,P as discoverFeatureUsage,T as foldCapabilitySignals,h as mayReadCapabilityContext,S as sourceCapabilitySignals};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{w as a}from"./classify-procedure-call-DVxdUhZt.mjs";const l=s=>a(s,"use","rls");export{l as r};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Node as o,VariableDeclarationKind as v,SyntaxKind as I}from"ts-morph";import{a as l}from"./module-specifiers-WF8iAydP.mjs";import{unwrapExpression as d}from"./isTestPath-B81lOULB.mjs";const Q=e=>o.isIdentifier(e)?e.getText():o.isPropertyAccessExpression(e)?e.getName():void 0,w=(e,i,r=l)=>{const t=new Set;for(const n of e.getImportDeclarations())if(r(n.getModuleSpecifierValue()))for(const s of n.getNamedImports())s.getNameNode().getText()===i&&t.add(s.getAliasNode()?.getText()??s.getName());return t},P=(e,i)=>{if(o.isPropertyAccessExpression(e))return e.getName()===i;if(!o.isIdentifier(e))return!1;const r=e.getText();return r===i||w(e.getSourceFile(),i).has(r)},S=e=>{for(const i of e.getSymbol()?.getDeclarations()??[])if(o.isImportSpecifier(i)&&l(i.getImportDeclaration().getModuleSpecifierValue()))return i.getNameNode().getText()},b=e=>e.getSymbol()?S(e):e.getText(),k=(e,i)=>o.isIdentifier(e)&&S(e)===i,m=e=>{const i=[];let r=d(e);for(;r&&o.isCallExpression(r);){const t=d(r.getExpression());if(!t||!o.isPropertyAccessExpression(t))return{root:void 0,steps:i};i.push({call:r,name:t.getName()}),r=d(t.getExpression())}return{root:r,steps:i}},N=e=>m(e).steps,h=(e,i,r)=>N(e).filter(t=>t.name===i).map(t=>t.call.getArguments()[0]).filter(t=>t!==void 0&&o.isCallExpression(t)&&r(t.getExpression())),K=(e,i,r)=>h(e,i,t=>P(t,r)),H=(e,i)=>N(e).some(r=>r.name===i),U=(e,i,r)=>K(e,i,r).length>0,x=new Set(["action","internalAction","internalMutation","internalQuery","mutation","query","stream"]),A=e=>{if(o.isIdentifier(e)){for(const i of e.getSymbol()?.getDeclarations()??[])if(o.isImportSpecifier(i)&&l(i.getImportDeclaration().getModuleSpecifierValue()))return i.getName()}if(o.isPropertyAccessExpression(e)){const i=e.getExpression();if(o.isIdentifier(i))return i.getSymbol()?.getDeclarations().some(t=>o.isNamespaceImport(t)&&l(t.getFirstAncestorByKindOrThrow(I.ImportDeclaration).getModuleSpecifierValue()))?e.getName():void 0}},F=e=>{const i=e.getParent(),r=i.getParent(),t=e.getPropertyNameNode()??e.getNameNode();if(!o.isObjectBindingPattern(i)||!o.isVariableDeclaration(r)||r.getVariableStatement()?.getDeclarationKind()!==v.Const||e.getDotDotDotToken()||e.getInitializer()||!o.isIdentifier(t)||!x.has(t.getText())||t.getText()==="stream")return;const n=r.getInitializer();if(!n)return;const{root:s,steps:a}=m(n);return s&&A(s)==="initLunora"&&a.length===2&&a[0]?.name==="create"&&a[1]?.name==="dataModel"?t.getText():void 0},z=e=>{const i=A(e);if(i)return x.has(i)?{factory:i}:{};if(!o.isIdentifier(e))return{};const r=e.getSymbol(),t=(r?.isAlias()?r.getAliasedSymbol():r)?.getValueDeclaration();return t&&o.isBindingElement(t)?{factory:F(t)}:t&&o.isVariableDeclaration(t)&&t.getVariableStatement()?.getDeclarationKind()===v.Const?{initializer:t.getInitializer()}:{}},M=e=>{const i=[],r=new Set;let t=e;for(;t!==void 0&&!r.has(t);){r.add(t);const n=m(t);if(i.push(...n.steps),!n.root)break;const{factory:s,initializer:a}=z(n.root);if(s)return{factory:s,steps:i};t=a}return{steps:i}},g=new Set(["action","mutation","query","stream"]),C={internalAction:"action",internalMutation:"mutation",internalQuery:"query"},O={onConnect:"connect",onDisconnect:"disconnect",onQueryChange:"reactor",onShardInit:"init",onWhisper:"whisper"},p={defineRoom:"room"},R=e=>e==="whisper"?"query":"mutation",D=e=>{const{root:i}=m(e);return i&&o.isIdentifier(i)?i:void 0},E=(e,i=!1)=>{const r=D(e);if(!r)return;const t=b(r);if(t===void 0){if(i)return;const n=r.getSymbol()?.getValueDeclaration();if(n&&o.isVariableDeclaration(n)){const s=n.getInitializer();return s?E(s,!0):void 0}return}return g.has(t)?"public":C[t]?"internal":void 0},T=(e,i=!1)=>{if(h(e,"use",s=>k(s,"platformAdmin")).length>0)return!0;if(i)return!1;const r=D(e)?.getSymbol(),t=(r?.isAlias()?r.getAliasedSymbol():r)?.getValueDeclaration(),n=t&&o.isVariableDeclaration(t)?t.getInitializer():void 0;return n!==void 0&&T(n,!0)},y=e=>T(e)?{adminOnly:!0}:{},B=(e,i)=>{const r=e.getName();if(!g.has(r))return;const t=e.getExpression(),n=d(t)??t,s=t===n?[n]:[t,n];if(s.some(f=>f.getType().getProperty("__lunoraProcedure"))){const f=s.some(V=>V.getType().getProperty("__lunoraVisibility"));return{kind:r,receiver:n,visibility:f?"internal":"public",...y(n)}}const a=i?M(n).factory:void 0,u=a?.startsWith("internal")?"internal":"public",c=a?u:E(n);if(c)return{kind:r,receiver:n,visibility:c,...y(n)}},_=e=>(e.getSymbol()?.getDeclarations()??[]).some(i=>o.isNamespaceImport(i)&&l(i.getFirstAncestorByKind(I.ImportDeclaration)?.getModuleSpecifierValue()??"")),j=(e,i=!1)=>{const r=e.getExpression();if(o.isPropertyAccessExpression(r)){const u=r.getExpression(),c=p[r.getName()]&&o.isIdentifier(u)&&_(u)?p[r.getName()]:void 0;return c?{channel:c,kind:"mutation",visibility:"internal"}:B(r,i)}if(!o.isIdentifier(r))return;const t=b(r);if(!t)return;if(g.has(t))return{kind:t,visibility:"public"};const n=C[t];if(n)return{kind:n,visibility:"internal"};const s=p[t];if(s)return{channel:s,kind:"mutation",visibility:"internal"};const a=O[t];if(a)return{kind:R(a),lifecycle:a,visibility:"internal"}};export{Q as a,N as b,j as c,U as d,k as e,H as f,w as i,M as s,K as w};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Node as i}from"ts-morph";import{listLunoraSourceFiles as a,lunoraRelativePath as c,handlerOf as l}from"./isTestPath-B81lOULB.mjs";import{b as d,d as f}from"./attribution-hVBriwzy.mjs";import{c as u}from"./context-root-BdxINX-T.mjs";import{c as m}from"./classify-procedure-call-DVxdUhZt.mjs";const p=t=>{const r=t.getInitializer();if(!r||!i.isCallExpression(r))return;const e=m(r);if(!e||e.kind!=="query"&&e.kind!=="mutation")return;const o=l(r,e.receiver);return o?{exportName:f(t)??t.getName(),handler:o,kind:e.kind}:void 0},x=(t,r)=>{const e=t.getParent();return e&&i.isPropertyAccessExpression(e)&&e.getExpression()===t?`ctx.${r}.${e.getName()}`:`ctx.${r}`},h=(t,r,e)=>{const o=[];for(const n of u(t.handler,e))o.push({callee:x(n,e),exportName:t.exportName,file:r,kind:t.kind,line:n.getStartLineNumber()});return o},N=(t,r,e)=>{const o=[];for(const n of d(t)){const s=p(n);s&&o.push(...h(s,r,e))}return o},F=(t,r,e)=>{const o=[];for(const n of a(r)){const s=t.getSourceFile(n)??t.addSourceFileAtPath(n);o.push(...N(s,c(r,n),e))}return o};export{F as d};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Node as s,SyntaxKind as d}from"ts-morph";import{unwrapExpression as l,memberAccessOf as P,bindingKeyName as C,findObjectProperty as p,isConstDeclaration as D,walkChain as A}from"./isTestPath-B81lOULB.mjs";import{f as v,g as I,h as M}from"./attribution-hVBriwzy.mjs";import{c as F}from"./classify-procedure-call-DVxdUhZt.mjs";import{isDefineMutatorCallee as b}from"./MUTATORS_FILENAME-Jkk8Zgkb.mjs";const x=8,E=t=>{if(s.isMethodDeclaration(t))return t;const e=s.isPropertyAssignment(t)?l(t.getInitializer()):void 0,o=s.isShorthandPropertyAssignment(t)?t.getNameNode():e;if(s.isArrowFunction(o)||s.isFunctionExpression(o))return o;const i=s.isIdentifier(o)?v(o):void 0;if(s.isFunctionDeclaration(i))return i;const n=D(i)?l(i.getInitializer()):void 0;return s.isArrowFunction(n)||s.isFunctionExpression(n)?n:void 0},w=t=>{const e=l(t.getArguments()[0]),o=s.isObjectLiteralExpression(e)?e:void 0,i=p(o,"server"),n=p(o,"handler"),r=i!==void 0&&b(t.getExpression()),a=n===void 0?void 0:F(t),u=a!==void 0&&a.receiver===void 0;return[r?E(i):void 0,u?E(n):void 0].filter(f=>f!==void 0)},h=new WeakMap,O=t=>{const e=t.getSourceFile(),o=h.get(e.compilerNode);if(o!==void 0)return o;const i=new Set(e.getDescendantsOfKind(d.CallExpression).flatMap(n=>w(n)).map(n=>n.compilerNode));return h.set(e.compilerNode,i),i},S=t=>{const e=t.getParent();return(s.isArrowFunction(e)||s.isFunctionExpression(e)||s.isFunctionDeclaration(e)||s.isMethodDeclaration(e))&&e.getParameters()[0]===t&&O(t).has(e.compilerNode)},G=t=>{const e=t.getParent();return(s.isArrowFunction(e)||s.isFunctionExpression(e)||s.isFunctionDeclaration(e)||s.isMethodDeclaration(e))&&e.getParameters()[1]===t&&O(t).has(e.compilerNode)},T=t=>t.getNameNode().getDescendantsOfKind(d.BindingElement).some(e=>e.getParent().getParent()===t&&["args","ctx"].includes(C(e))),g=(t,e,o)=>{const i=t.getParent().getParent(),n=C(t);if(t.getDotDotDotToken()!==void 0||e==="trust"&&I(t))return;let r;if(s.isParameterDeclaration(i)){if(!S(i)||T(i))return n==="ctx"?[]:void 0;r=[]}else s.isBindingElement(i)?r=g(i,e,o):s.isVariableDeclaration(i)&&o>0&&(r=c(i.getInitializer(),e,o-1));return r===void 0?void 0:[...r,n]},c=(t,e="discover",o=x)=>{const i=l(t),n=P(i);if(n!==void 0){const r=c(n.object,e,o);return r===void 0?void 0:[...r,n.member]}return s.isIdentifier(i)?B(i,e,o):void 0},B=(t,e,o)=>{const i=t.getText()==="ctx",n=e==="trust"||!i?v(t):void 0;return i&&!s.isVariableDeclaration(n)?s.isBindingElement(n)?g(n,e,o):[]:s.isParameterDeclaration(n)?s.isIdentifier(n.getNameNode())&&S(n)?[]:void 0:s.isBindingElement(n)?g(n,e,o):!(s.isVariableDeclaration(n)&&s.isIdentifier(n.getNameNode())&&o>0)||e==="trust"&&I(n)?void 0:c(n.getInitializer(),e,o-1)},Q=t=>c(t,"discover"),H=t=>{const e=c(t);return e===void 0?void 0:["ctx",...e].join(".")},q=(t,e)=>{if(e(t.getText()))return!0;const o=H(t);return o!==void 0&&e(o)},J=(t,e)=>{const o=l(t),i=P(o);if(i!==void 0&&i.member!==e.at(-1))return!1;const n=o===void 0?void 0:c(o);return n?.length===e.length&&n.every((r,a)=>r===e[a])},Y=(t,e)=>U(t).get(e)??[],K=t=>{const e=new Map;for(const i of t.getDescendantsOfKind(d.BindingElement)){const n=s.isIdentifier(i.getNameNode())?g(i,"discover",x):void 0;n?.length===1&&n[0]!==void 0&&e.set(i.compilerNode,n[0])}const o=new Set([...e.keys()].map(i=>i.name.getText()));return t.getDescendantsOfKind(d.Identifier).flatMap(i=>{const r=o.has(i.getText())&&!s.isBindingElement(i.getParent())?v(i):void 0,a=r===void 0?void 0:e.get(r.compilerNode);return a===void 0?[]:[[a,i]]})},N=new WeakMap,U=t=>{const e=N.get(t.compilerNode);if(e!==void 0)return e;const o=new Map;for(const[n,r]of[...y(t),...K(t)])o.set(n,[...o.get(n)??[],r]);const i=new Map([...o].map(([n,r])=>[n,r.toSorted((a,u)=>a.getPos()-u.getPos())]));return N.set(t.compilerNode,i),i},y=t=>t.getDescendantsOfKind(d.PropertyAccessExpression).flatMap(e=>z(e.getExpression())?[[e.getName(),e]]:[]),z=t=>s.isIdentifier(t)&&c(t)?.length===0,Z=t=>{const e=c(t);return e?.length===1&&e[0]==="db"},_=new Set(["asId","createMultipartUpload","fetch","generateUploadUrl","getPresignedUrl","getSignedUrl","getUrl","normalizeId","resumeMultipartUpload","runAction","runMutation","runQuery","store","upload"]),R=new Set(["catch","flatMap","map","reduce","reduceRight","then"]),k=(t,e=x)=>{const o=A(t,u=>{const f=l(u.getExpression()),m=s.isPropertyAccessExpression(f)?f.getName():void 0;return m!==void 0&&(_.has(m)||R.has(m))?!1:void 0}),i=o.root;if(o.verdict!==void 0||!s.isIdentifier(i))return o.verdict??!1;if(c(i,"trust")!==void 0)return!0;const n=v(i),r=s.isBindingElement(n)?n.getFirstAncestorByKind(d.VariableDeclaration):n,a=D(r)&&e>0?r.getInitializer():void 0;return a!==void 0&&k(a,e-1)},$=t=>(s.isIdentifier(t)?[t]:t.getDescendantsOfKind(d.Identifier)).some(o=>M(o)&&c(o,"trust")!==void 0);export{R as C,_ as E,G as a,H as b,Y as c,Z as d,Q as e,k as f,z as g,J as i,q as m,$ as r};
|