@lunora/codegen 1.0.0-alpha.412 → 1.0.0-alpha.414

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.
Files changed (64) hide show
  1. package/dist/index.d.mts +55 -0
  2. package/dist/index.d.ts +55 -0
  3. package/dist/index.mjs +1 -1
  4. package/dist/packem_shared/{AGENTS_FILENAME-QRUqRvf6.mjs → AGENTS_FILENAME-C4tHmiZZ.mjs} +1 -1
  5. package/dist/packem_shared/{ALL_NOTIFY_CHANNELS-B7iq8Uiy.mjs → ALL_NOTIFY_CHANNELS-uYuQQpdn.mjs} +1 -1
  6. package/dist/packem_shared/CONTAINERS_FILENAME-d3XTFcqV.mjs +1 -0
  7. package/dist/packem_shared/{ENV_FILENAME-BoyByQTI.mjs → ENV_FILENAME-DJ11PXN5.mjs} +1 -1
  8. package/dist/packem_shared/{FLAGS_FILENAME-BB1QI_aN.mjs → FLAGS_FILENAME-DeSjFBWq.mjs} +1 -1
  9. package/dist/packem_shared/{MUTATORS_FILENAME-DkFBc4AU.mjs → MUTATORS_FILENAME-C0ZV0hh6.mjs} +1 -1
  10. package/dist/packem_shared/{OPENRPC_VERSION-47R9GrAx.mjs → OPENRPC_VERSION-BOBo0zdQ.mjs} +1 -1
  11. package/dist/packem_shared/QUEUES_FILENAME-DbuJZnrY.mjs +1 -0
  12. package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-DhpeJoSr.mjs +54 -0
  13. package/dist/packem_shared/SHAPES_FILENAME-BvRkrFtN.mjs +1 -0
  14. package/dist/packem_shared/WORKFLOWS_FILENAME-7FysJsMZ.mjs +1 -0
  15. package/dist/packem_shared/{attribution-C3R6vQrY.mjs → attribution-Cwt30DDJ.mjs} +1 -1
  16. package/dist/packem_shared/{buildOpenApiDocument-Bfgtz-IM.mjs → buildOpenApiDocument-DmV_PBFv.mjs} +1 -1
  17. package/dist/packem_shared/{capabilitiesUsedBy-Bx1C3HqI.mjs → capabilitiesUsedBy-BNvoiCu1.mjs} +1 -1
  18. package/dist/packem_shared/{classify-procedure-call-C6ajvyGA.mjs → classify-procedure-call-BmEirzc_.mjs} +1 -1
  19. package/dist/packem_shared/{context-property-calls-CCMzhSdz.mjs → context-property-calls-BQyyS_B0.mjs} +1 -1
  20. package/dist/packem_shared/{context-root-B5xiDINx.mjs → context-root-hthkpwQe.mjs} +1 -1
  21. package/dist/packem_shared/{createCodegenProject-CIWmoq01.mjs → createCodegenProject-dC6oJh5H.mjs} +1 -1
  22. package/dist/packem_shared/{database-calls-B8H7kkzY.mjs → database-calls-B8l9USAr.mjs} +1 -1
  23. package/dist/packem_shared/{discoverAuthApiCalls-Db2Px0BS.mjs → discoverAuthApiCalls-CuqaLRa0.mjs} +1 -1
  24. package/dist/packem_shared/discoverCrons-bT8F5GyL.mjs +1 -0
  25. package/dist/packem_shared/discoverFunctions-Dn6_nfhC.mjs +1 -0
  26. package/dist/packem_shared/{discoverHttpRoutes-1ebHL9DX.mjs → discoverHttpRoutes-CesuhqW1.mjs} +1 -1
  27. package/dist/packem_shared/discoverHyperdriveCalls-DoZqnpRp.mjs +1 -0
  28. package/dist/packem_shared/{discoverInserts-BXAKSCk0.mjs → discoverInserts-fL7eh_Q_.mjs} +1 -1
  29. package/dist/packem_shared/discoverMaskProcedures-0XApH-Nk.mjs +1 -0
  30. package/dist/packem_shared/{discoverMigrations-bY4FcGu3.mjs → discoverMigrations-C9AlZYFi.mjs} +1 -1
  31. package/dist/packem_shared/{discoverNondeterministicCalls-CSaz-HlP.mjs → discoverNondeterministicCalls-ZeZDQJAI.mjs} +1 -1
  32. package/dist/packem_shared/{discoverQueries-B53HkUIt.mjs → discoverQueries-DPqTWmBp.mjs} +1 -1
  33. package/dist/packem_shared/discoverR2sqlCalls-cS1hM24s.mjs +1 -0
  34. package/dist/packem_shared/{discoverRlsMetadata-x48NLw6f.mjs → discoverRlsMetadata-C0UkQkWd.mjs} +1 -1
  35. package/dist/packem_shared/discoverRlsProcedures-BY04NWTT.mjs +1 -0
  36. package/dist/packem_shared/{discoverSandboxUsage-BWV_Ebxg.mjs → discoverSandboxUsage-Dgvv6F_7.mjs} +1 -1
  37. package/dist/packem_shared/discoverSchema-BLTROO8Z.mjs +1 -0
  38. package/dist/packem_shared/{discoverStorageRulesMetadata-BYyL1oLc.mjs → discoverStorageRulesMetadata-DeBgC7po.mjs} +1 -1
  39. package/dist/packem_shared/{exported-procedure-chains-CHh7fXfL.mjs → exported-procedure-chains-CfH5jrzD.mjs} +1 -1
  40. package/dist/packem_shared/{fingerprintSchemaSources-BlBMjIrI.mjs → fingerprintSchemaSources-TN-rU6Of.mjs} +1 -1
  41. package/dist/packem_shared/formatAdvisories-Bue5tbp6.mjs +2 -0
  42. package/dist/packem_shared/{handler-reference-DOIBV2VQ.mjs → handler-reference-BkOkxxg8.mjs} +1 -1
  43. package/dist/packem_shared/{index-DTwKeiZr.mjs → index-BAkOcSfE.mjs} +1 -1
  44. package/dist/packem_shared/{index-D2i1mfys.mjs → index-s_NKnjVj.mjs} +1 -1
  45. package/dist/packem_shared/{ip-reads-DUVCi6k9.mjs → ip-reads-JFFYo4vb.mjs} +1 -1
  46. package/dist/packem_shared/isTestPath-Uwb5a6Kq.mjs +1 -0
  47. package/dist/packem_shared/{modules-5z0rLSZk.mjs → modules-DdOd-7Wp.mjs} +1 -1
  48. package/dist/packem_shared/{policies-DhRzjZZw.mjs → policies-Dn_tuTZd.mjs} +1 -1
  49. package/dist/packem_shared/{unwrap-handler-return-DhdSnAfS.mjs → unwrap-handler-return-DvbyiLjc.mjs} +1 -1
  50. package/package.json +3 -3
  51. package/dist/packem_shared/CONTAINERS_FILENAME-Cr7hB6eW.mjs +0 -1
  52. package/dist/packem_shared/QUEUES_FILENAME-g99T1hJ6.mjs +0 -1
  53. package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-CKGYZChO.mjs +0 -54
  54. package/dist/packem_shared/SHAPES_FILENAME-C51eXfND.mjs +0 -1
  55. package/dist/packem_shared/WORKFLOWS_FILENAME-WcVbEHuM.mjs +0 -1
  56. package/dist/packem_shared/discoverCrons-DaBAMqU6.mjs +0 -1
  57. package/dist/packem_shared/discoverFunctions-DdR5Uh1X.mjs +0 -1
  58. package/dist/packem_shared/discoverHyperdriveCalls-BHtXShva.mjs +0 -1
  59. package/dist/packem_shared/discoverMaskProcedures-DhcC6cfM.mjs +0 -1
  60. package/dist/packem_shared/discoverR2sqlCalls-B8K69UVy.mjs +0 -1
  61. package/dist/packem_shared/discoverRlsProcedures-DDulecui.mjs +0 -1
  62. package/dist/packem_shared/discoverSchema-DJ-YxkP2.mjs +0 -1
  63. package/dist/packem_shared/formatAdvisories-BCVASH7N.mjs +0 -2
  64. package/dist/packem_shared/isTestPath-6GN3Bkus.mjs +0 -1
@@ -1,54 +0,0 @@
1
- import{existsSync as $,readFileSync as ft,mkdirSync as ds,writeFileSync as go,rmSync as Ee,readdirSync as us}from"node:fs";import{dirname as gt,join as E,basename as po,relative as fs}from"node:path";import{performance as Dt}from"node:perf_hooks";import{runAdvisor as mo}from"@lunora/advisor";import{LunoraError as F}from"@lunora/errors";import{serializeSchemaSnapshot as ho}from"./SCHEMA_SNAPSHOT_VERSION-DTLoSaNn.mjs";import{toAdvisorContext as vo}from"./formatAdvisories-BCVASH7N.mjs";import{Node as r,SyntaxKind as d,VariableDeclarationKind as pt,Project as gs,ts as Eo}from"ts-morph";import{listLunoraSourceFiles as y,lunoraRelativePath as P,descendantsOfKind as x,bindingKeyName as fe,unwrapExpression as h,collectCallRows as O,findObjectProperty as B,collectSecurityCallRows as xo,propertyInitializer as M,listSecurityScanFiles as Be,objectLiteralFromCallbackBody as ii,limitNameOf as ri,optionsObjectLiteral as oi,handlerOf as So,memberAccessOf as ps,chainRootOf as mt,collectNodeRows as oe,isConstDeclaration as G,outermostValueWrapper as T,isWriteTarget as Pe,isSameNode as b,returningFunctionOf as jt,walkChain as Ao,staticNumberValue as ai,RUN_METHODS as ms,functionReferenceSegments as yo,isTestPath as bo,isFunctionLike as ge,functionKeyOf as ci,withSourceListMemo as No}from"./isTestPath-6GN3Bkus.mjs";import{j as Z,h as Q,d as _,b as hs,c as A,a as vs,w as Es,k as Po,l as wo,f as Io,m as To,g as Ht,i as Co}from"./attribution-C3R6vQrY.mjs";import{b as ln,r as Mt,a as Y,e as Oo,m as li,c as ht,f as xs,E as di,C as ui,d as fi,g as ko,h as Ro,i as Fo}from"./context-root-B5xiDINx.mjs";import{a as C,i as gi,c as ae,d as pi,e as mi,f as Lo,b as Do,g as Mo,h as _o}from"./classify-procedure-call-C6ajvyGA.mjs";import{a as S,s as Ss}from"./property-name-7cBlgK_O.mjs";import{b as zo,a as hi}from"./module-specifiers-BctA0m_p.mjs";import{r as vt,s as $o}from"./parse-validator-BisfC8bR.mjs";import Ko from"./discoverAuthApiCalls-Db2Px0BS.mjs";import{i as K,r as vi}from"./database-calls-B8H7kkzY.mjs";import{i as Gt,p as Ei,w as Bo,d as Vo}from"./index-D2i1mfys.mjs";import Uo from"./discoverHyperdriveCalls-BHtXShva.mjs";import{PROJECT_CONFIG_FILENAMES as Wo,findProjectConfigFile as xi,findCodegenConfigFile as qo}from"./PROJECT_CONFIG_FILENAMES-CLfsyvjA.mjs";import{contextPropertiesRead as jo,createTargetScope as Ho,fileWiresRequestSecretTool as Go,discoverFeatureUsage as Yo}from"./capabilitiesUsedBy-Bx1C3HqI.mjs";import{diagnosticAt as we}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{m as As,a as rt,s as Si,d as Qo}from"./index-DTwKeiZr.mjs";import{MUTATORS_FILENAME as Xo,isDefineMutatorCallee as Jo,mutatorServerImplOf as Zo,discoverMutators as ea}from"./MUTATORS_FILENAME-DkFBc4AU.mjs";import ta from"./discoverNondeterministicCalls-CSaz-HlP.mjs";import{discoverNotifyConfig as sa,discoverNotifyCalls as na}from"./ALL_NOTIFY_CHANNELS-B7iq8Uiy.mjs";import ia from"./discoverR2sqlCalls-B8K69UVy.mjs";import ra from"./discoverRlsProcedures-DDulecui.mjs";import{s as ys,n as oa}from"./dispatch-namespace-DwTjD7BU.mjs";import{secretKindOf as aa,redact as ca,isHeuristicSecretKind as la,isSecretishName as da}from"./redact-Cy14LEnc.mjs";import{r as Ai,p as ua,c as fa,a as ga,e as pa,d as ma}from"./project-config-file-DR7xrrNB.mjs";import{a as Ge,d as ha,r as va}from"./modules-5z0rLSZk.mjs";import{WORKFLOWS_FILENAME as Ea,discoverWorkflows as xa}from"./WORKFLOWS_FILENAME-WcVbEHuM.mjs";import{r as Sa}from"./json-data-Chfs2Cz5.mjs";import{a as Aa,I as ya,g as ba,G as yi,d as Na,i as Pa}from"./shared-Cn7dMQ_u.mjs";import{createCodegenProject as wa}from"./createCodegenProject-CIWmoq01.mjs";import{findTsconfig as E0,refreshCodegenProject as x0,tsconfigFingerprint as S0}from"./createCodegenProject-CIWmoq01.mjs";import{wranglerString as Ia,wranglerValue as Ta,companionName as Ca,COMPANION_FILES as Oa}from"./COMPANION_BINDING-Da_v9XpC.mjs";import{CAPABILITIES as ka,usedCapabilities as Ra}from"./CAPABILITY_PROBES-DCzOjTN7.mjs";import{isD1GlobalTable as bi,isHyperdriveGlobalTable as Ni}from"./isD1GlobalTable-udvHAAzD.mjs";import{discoverAgents as Fa}from"./AGENTS_FILENAME-QRUqRvf6.mjs";import{discoverContainers as La}from"./CONTAINERS_FILENAME-Cr7hB6eW.mjs";import Da from"./discoverCrons-DaBAMqU6.mjs";import{discoverEnv as Ma}from"./ENV_FILENAME-BoyByQTI.mjs";import Pi from"./readPackageDependencies-RHhGiz0k.mjs";import{discoverQueueDeclarations as _a}from"./QUEUES_FILENAME-g99T1hJ6.mjs";import{discoverSandboxUsage as za}from"./discoverSandboxUsage-BWV_Ebxg.mjs";import{resolveServiceBindings as $a}from"./companionServiceBinding-BZjm486n.mjs";import Ka from"./discoverStorageRulesMetadata-BYyL1oLc.mjs";import{resolveCodegenTarget as Xe,gatePlatformFeatures as Ba,readTargetDiagnostics as Va,vectorizeDimensionDiagnostics as Ua,liveStreamsDeliveryAuthorizationDiagnostic as Wa,socketRoutesDeliveryAuthorizationDiagnostic as qa,studioPlatformFor as ja,platformFeatureAvailable as Ha,gateAdminTokenRevocation as Ga}from"./DEFAULT_TARGET-CVYzxQ0y.mjs";import{i as Ya}from"./schema-BgM8A3XV.mjs";import{b as wi,e as Qa}from"./shard-CWAD5mYy.mjs";import{e as Xa,a as Ja}from"./server-Dfxmm5Zw.mjs";import{emitDataModel as Za}from"./emitDataModel-BvCZS4Yq.mjs";import{i as ec,b as tc,e as sc,d as nc,f as ic,c as rc}from"./unwrap-handler-return-DhdSnAfS.mjs";import oc from"./discoverHttpRoutes-1ebHL9DX.mjs";import ac from"./discoverInserts-BXAKSCk0.mjs";import{e as Ii}from"./exported-procedure-chains-CHh7fXfL.mjs";import cc from"./discoverMigrations-bY4FcGu3.mjs";import dn from"./discoverQueries-B53HkUIt.mjs";import lc from"./discoverRlsMetadata-x48NLw6f.mjs";import dc from"./discoverSchema-DJ-YxkP2.mjs";import{discoverShapes as uc}from"./SHAPES_FILENAME-C51eXfND.mjs";import{i as fc}from"./reserved-words-CW1QFbTd.mjs";import{emitAuthModule as gc,emitApp as pc}from"./emitApp-CBE_wZAT.mjs";import{readJsonSync as mc}from"@visulima/fs";import{indexReferencesOf as hc,buildSchemaSnapshot as vc}from"./SchemaSnapshotParseError-CV7mmuPi.mjs";import{buildOpenApiDocument as Ec,emitOpenApiModule as xc}from"./buildOpenApiDocument-Bfgtz-IM.mjs";import{buildOpenRpcDocument as Sc,emitOpenRpcModule as Ac}from"./OPENRPC_VERSION-47R9GrAx.mjs";import{w as yc,u as bc,v as Nc,t as Pc,x as wc}from"./shard-runtime-G5mZQjY0.mjs";import{emitCollections as Ic,emitSeed as Tc,emitApi as Cc,emitInternalApi as Oc}from"./emitApi-lwadq5G7.mjs";import{emitCrons as kc,emitScheduler as Rc,emitAdminRevocations as Fc,emitShardRegistry as Lc,emitDurableObjects as Dc,emitVectors as Mc,emitWranglerCronTriggers as _c}from"./emitCrons-CCRKs482.mjs";import zc from"./emitDrizzleSchema-BzOChEYW.mjs";import{LAZY_FUNCTION_DIRECTORY as Ti,emitFunctions as $c,emitLazyFunctionModules as Kc}from"./emitFunctions-ppMX7E3X.mjs";const Bc=(e,t=!1)=>{if(e.length===0)return"";const s=Na(t),n=e.map(c=>{if(Aa(c.exportName,"live stream export name"),!ya.test(c.filePath))throw new Error(`@lunora/codegen: live stream file path is not safe to import: ${JSON.stringify(c.filePath)}`);return`import type { ${c.exportName} as ${c.exportName}Stream } from "../${c.filePath}.js";`}),i=e.map(c=>{const l=c.topics.map(u=>{ba(u.name,"live topic name");const f=`(typeof ${c.exportName}Stream)["topics"]["${u.name}"]`,g=`LiveTopicRef<LiveTopicPayload<${f}>>`,m=JSON.stringify(c.id);if(u.fields.length===0)return` ${u.name}: (): ${g} => ({ __lunoraLive: ${m}, topic: ${JSON.stringify(u.name)} }),`;const v=u.fields.map(k=>`\${encodeURIComponent(key.${k})}`).join(":");return` ${u.name}: (key: LiveTopicKey<${f}>): ${g} => ({
2
- __lunoraLive: ${m},
3
- topic: \`${u.name}:${v}\`,
4
- }),`});return` ${c.exportName}: {
5
- ${l.join(`
6
- `)}
7
- },`}),a=e.some(c=>c.topics.some(l=>l.fields.length>0))?"LiveTopicKey, LiveTopicPayload, LiveTopicRef":"LiveTopicPayload, LiveTopicRef";return`${yi}import type { ${a} } from "${s.server}";
8
-
9
- ${n.join(`
10
- `)}
11
-
12
- /**
13
- * A typed reference to each declared live topic, grouped by the stream's export name:
14
- * \`live.posts.post({ postId })\`. Pass one to \`ctx.live.publish(ref, payload)\` on the server, or to a
15
- * live-topic hook in the browser. A reference is plain data and carries no server code.
16
- */
17
- export const live = {
18
- ${i.join(`
19
- `)}
20
- };
21
- `},Ci=new Set(["delete","get","head","options","patch","post","put"]),Vc=new Set(["handler","stream"]),Uc=/\/(?:_|admin|internal|superuser|sudo|root|debug)/iu,un=new Set(["ADMIN_TOKEN","adminToken","assertAdmin","assertAuth","auth","Authorization","getSession","identity","isAdmin","requireAdmin","requireAuth","requireRole","verifyAdmin"]),Wc=e=>{if(!r.isCallExpression(e))return;const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!Ci.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()}},qc=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)||Ci.has(n.getName()))break;s=n.getExpression()}return Wc(s)},jc=e=>{for(const t of e.getDescendantsOfKind(d.PropertyAccessExpression))if(un.has(t.getName()))return!0;for(const t of e.getDescendantsOfKind(d.CallExpression)){const s=t.getExpression();if(r.isIdentifier(s)&&un.has(s.getText()))return!0}return!1},Hc=(e,t)=>{const s=e.getInitializer();if(!s||!r.isCallExpression(s))return;const n=s.getExpression();if(!r.isPropertyAccessExpression(n)||!Vc.has(n.getName()))return;const i=qc(s);if(!i||!Uc.test(i.path))return;const o=s.getArguments()[0],a=o!==void 0&&(r.isArrowFunction(o)||r.isFunctionExpression(o))&&jc(o);return{exportName:Q(e)??e.getName(),file:t,method:i.method,path:i.path,usesGuard:a}},Gc=(e,t)=>{const s=[];for(const n of Z(e)){const i=Hc(n,t);i&&s.push(i)}return s},Yc=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Gc(i,P(t,n)))}return s},Qc=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}},Xc=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)?fe(t):void 0}},Jc=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))&&ln(a)}))return!1;const n=_(e),i=r.isParameterDeclaration(n)?n:n?.getFirstAncestorByKind(d.Parameter);return i!==void 0&&(r.isParameterDeclaration(n)||r.isBindingElement(n))&&ln(i)},fn=(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=Qc(e);return n!==void 0&&Xc(n)===t?!0:t==="args"&&Jc(e)},Oi=(e,t)=>r.isIdentifier(e)?fn(e,t):e.getDescendantsOfKind(d.Identifier).some(s=>fn(s,t)),Zc=e=>{let t=e;for(;r.isPropertyAccessExpression(t)||r.isElementAccessExpression(t)||r.isNonNullExpression(t);)t=t.getExpression();return r.isIdentifier(t)?t:void 0},gn=e=>{const t=r.isIdentifier(e)?_(e):void 0;return r.isVariableDeclaration(t)&&r.isIdentifier(t.getNameNode())&&!hs(t)?t.getInitializer():void 0},el=(e,t)=>{const s=e.getParent();if(r.isVariableDeclarationList(s)&&s.getDeclarationKind()===pt.Var)return t;const n=s.getParent();return r.isVariableStatement(n)?n.getParent():n},tl=(e,t)=>{const s=e.getNameNode();return r.isIdentifier(s)?s.getText()===t:s.getDescendantsOfKind(d.BindingElement).some(n=>{const i=n.getNameNode();return r.isIdentifier(i)&&i.getText()===t})},ki=e=>e.getDescendantsOfKind(d.Identifier).filter(t=>{const s=t.getParent();return!(r.isPropertyAccessExpression(s)&&s.getNameNode()===t)&&!(r.isPropertyAssignment(s)&&s.getNameNode()===t)}),Ye=e=>{let t=h(e)??e;for(;r.isAwaitExpression(t);)t=h(t.getExpression())??t.getExpression();return r.isCallExpression(t)||r.isNewExpression(t)},Yt=(e,t)=>{const s=e?.getNameNode().getDescendantsOfKind(d.BindingElement).find(n=>r.isIdentifier(n.getNameNode())&&n.getNameNode().getText()===t);return s===void 0?[]:[s,...s.getAncestors().filter(n=>r.isBindingElement(n))].map(n=>r.isBindingElement(n)?n.getInitializer():void 0).filter(n=>n!==void 0)},he=e=>Oi(e,"args"),Me=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 x(s,d.VariableDeclaration)){if(!tl(a,t))continue;const c=el(a,s);if(c===void 0||n<c.getStart()||n>=c.getEnd())continue;const l=a.getInitializer(),u=a.getStart();l!==void 0&&u<n&&u>o&&(i=a,o=u)}return i},pe=e=>Me(e)?.getInitializer(),q=e=>{if(he(e))return!0;const t=s=>{const n=Me(s),i=n?.getInitializer();return i!==void 0&&he(i)||Yt(n,s.getText()).some(o=>he(o))};return t(e)||ki(e).some(s=>t(s))},sl=e=>{if(Ye(e))return!1;if(Yt(Me(e),e.getText()).some(n=>he(n)&&!Ye(n)))return!0;const t=pe(e);if(t!==void 0&&Ye(t))return!1;const s=t??e;return he(s)?!0:ki(s).some(n=>{if(n.getFirstAncestor(c=>c===s||r.isCallExpression(c)||r.isNewExpression(c))!==s)return!1;const o=Me(n),a=c=>c!==void 0&&he(c)&&!Ye(c);return a(o?.getInitializer())||Yt(o,n.getText()).some(c=>a(c))})},xe=e=>{if(Mt(e))return!0;const t=gn(e);if(t!==void 0&&Mt(t))return!0;const s=t??e;return(r.isIdentifier(s)?[s]:s.getDescendantsOfKind(d.Identifier)).some(i=>{const o=gn(i);return o!==void 0&&Mt(o)})},Je=(e,t)=>Oi(e,t),nl=(e,t)=>{if(Je(e,t))return!0;const s=pe(e);if(s!==void 0&&Je(s,t))return!0;const n=Zc(e);if(n!==void 0){const i=pe(n);return i!==void 0&&Je(i,t)}return!1},il=e=>!r.isPropertyAccessExpression(e)||e.getName()!=="run"?!1:Y(e.getExpression(),["ai"]),rl=(e,t)=>{if(!il(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!q(s)||xe(s)))return{scope:A(e),file:t,line:e.getStartLineNumber()}},ol=(e,t)=>O(e,t,rl),al=new Set(["generateText","streamText"]),cl=new Set(["messages","prompt","system"]),ll=[{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"]}],dl=(e,t)=>ll.some(s=>s.methods.has(t)&&s.prefixes.some(n=>e===n||e.startsWith(`${n}.`))),ul=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;const s=t.getName(),n=[Oo(t.getExpression()),t.getExpression().getText()].find(i=>i!==void 0&&dl(i,s));return n===void 0?void 0:`${n}.${s}`},fl=e=>{for(const t of e.getDescendantsOfKind(d.CallExpression)){const s=ul(t);if(s!==void 0)return s}},gl=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=fe(o),c=o.getNameNode();if(a==="args"&&r.isObjectBindingPattern(c))for(const l of c.getElements())t.add(l.getName())}return t},pl=e=>{if(he(e))return!0;const t=gl(e);return t.size===0?!1:e.getDescendantsOfKind(d.Identifier).some(s=>t.has(s.getText()))},ml=e=>{for(const t of e.getProperties()){if(!r.isPropertyAssignment(t)||!cl.has(S(t)))continue;const s=t.getInitializer();if(s!==void 0&&pl(s))return!0}return!1},hl=(e,t)=>{const s=[];for(const n of x(e,d.CallExpression)){const i=C(n.getExpression());if(i===void 0||!al.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(C(c.getExpression())==="tool"&&(a=fl(c),a!==void 0))break;a!==void 0&&s.push({scope:A(n),file:t,line:n.getStartLineNumber(),method:i,sideEffect:a,userInputDerived:ml(o)})}return s},vl=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...hl(i,P(t,n)))}return s},El=e=>Y(e,["fetch"]),xl=(e,t)=>{if(!El(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!q(s)))return{scope:A(e),file:t,line:e.getStartLineNumber()}},Sl=(e,t)=>O(e,t,xl),bs=(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=vt(s.getExpression());return n===void 0||bs(n,t)})}finally{t.delete(e)}},Al=e=>{const t=e.getArguments()[0];if(!t||!r.isObjectLiteralExpression(t))return{objects:[],opaque:!0};const s=B(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:vt(n);return i===void 0?{objects:[],opaque:!0}:{objects:[i],opaque:bs(i)}},yl=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)?vt(o):void 0;a===void 0?s=!0:(t.push(a),s||=bs(a))}n=i.getExpression()}return{objects:t,opaque:s}},Ns=(e,t)=>t?yl(t):Al(e),Ri=(e,t)=>{if(t.has(e))return[];t.add(e);try{return e.getProperties().flatMap(s=>{if(r.isSpreadAssignment(s)){const n=vt(s.getExpression());return n===void 0?[]:Ri(n,t)}return r.isPropertyAssignment(s)||r.isShorthandPropertyAssignment(s)?[S(s)]:[]})}finally{t.delete(e)}},bl=e=>e.flatMap(t=>Ri(t,new Set)),Nl=new Set(["check","length","max"]),Qt=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(Nl.has(s.getName()))return!0;t=n}},Xt=e=>zo(e)||e==="@lunora/values",Pl=e=>{const t=new Set(["v"]);for(const s of gi(e,"v",Xt))t.add(s);for(const s of e.getImportDeclarations()){const n=s.getNamespaceImport();n&&Xt(s.getModuleSpecifierValue())&&t.add(`${n.getText()}.v`)}return t},wl=(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},Il=e=>(e.getSymbol()?.getDeclarations()??[]).some(t=>!t.getSourceFile().isDeclarationFile()&&!r.isImportSpecifier(t)&&!r.isNamespaceImport(t)&&!r.isImportClause(t)),Tl=e=>(e.getSymbol()?.getDeclarations()??[]).some(t=>r.isNamespaceImport(t)&&Xt(t.getFirstAncestorByKindOrThrow(d.ImportDeclaration).getModuleSpecifierValue())),Ps=(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 Il(n)?void 0:s.getName();const i=r.isPropertyAccessExpression(n)?n.getExpression():void 0;return r.isIdentifier(i)&&Tl(i)?s.getName():void 0}if(r.isIdentifier(s))return t.destructured.get(s.getText())},Cl=(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)},Ol=e=>{let t=e.getParent();for(;t&&!r.isFunctionLikeDeclaration(t);)t=t.getParent();return t},kl=e=>r.isReturnStatement(e)?e.getExpression():void 0,Rl=e=>r.isArrowFunction(e)&&!r.isBlock(e.getBody())?[e.getBody()]:e.getDescendantsOfKind(d.ReturnStatement).filter(t=>Ol(t)?.compilerNode===e.compilerNode).flatMap(t=>{const s=kl(t);return s?[s]:[]}),Fi=(e,t)=>{if(Ps(e,t)!==void 0)return e;if(r.isCallExpression(e)||r.isPropertyAccessExpression(e))return Fi(e.getExpression(),t)},Fl=(e,t)=>{const s=Cl(e.getExpression(),e.getSourceFile());if(!s)return[];const n=Qt(e),i=new Set(Rl(s).map(o=>Fi(o,t)).filter(o=>o!==void 0));return[s,...s.getDescendants()].flatMap(o=>{const a=Ps(o,t);return a===void 0?[]:[{bounded:Qt(o)||n&&i.has(o),factory:a}]})},Ll=(e,t)=>[e,...e.getDescendants()].flatMap(s=>{const n=Ps(s,t),i=n===void 0?[]:[{bounded:Qt(s),factory:n}];return r.isCallExpression(s)?[...i,...Fl(s,t)]:i}),Dl=(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=Ll(a,t),l=S(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}},Ml=(e,t,s)=>{const n=e.getInitializer();if(!n||!r.isCallExpression(n))return;const i=ae(n);if(i?.visibility!=="public")return;const{objects:o}=Ns(n,i.receiver),{anyArgs:a,unboundedStringArgs:c}=Dl(o,s);if(!(a.length===0&&c.length===0))return{anyArgs:a,exportName:Q(e)??e.getName(),file:t,line:n.getStartLineNumber(),unboundedStringArgs:c}},_l=(e,t)=>{const s=[],n=Pl(e),i={destructured:wl(e,n),namespaces:n};for(const o of Z(e)){const a=Ml(o,t,i);a&&s.push(a)}return s},zl=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(..._l(i,P(t,n)))}return s},_t=e=>e?.getKind()===d.TrueKeyword,$l=e=>e?.getKind()===d.FalseKeyword,Kl=e=>e!==void 0&&r.isNumericLiteral(e)&&e.getLiteralValue()===0,Bl=new Set(["lunoraAuthAdapter","lunoraD1Adapter"]),Vl=e=>!e||!r.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>r.isCallExpression(t)&&C(t.getExpression())==="scim"),Ul=e=>e!==void 0&&r.isCallExpression(e)&&Bl.has(C(e.getExpression())??""),Wl=e=>!e||!r.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>r.isStringLiteral(t)&&t.getLiteralText()==="*"),ql=e=>{const t=M(e,"advanced"),s=M(e,"emailAndPassword"),n=M(e,"session");return{analyzable:!0,disableCsrfCheck:_t(M(t,"disableCSRFCheck")),emailPasswordEnabled:_t(M(s,"enabled")),requireEmailVerification:_t(M(s,"requireEmailVerification")),scimOnNonTransactionalAdapter:Vl(M(e,"plugins"))&&Ul(M(e,"database")),secureCookiesDisabled:$l(M(t,"useSecureCookies")),sessionFreshAgeZero:Kl(M(n,"freshAge")),trustedOriginsWildcard:Wl(M(e,"trustedOrigins"))}},jl=()=>({analyzable:!1,disableCsrfCheck:!1,emailPasswordEnabled:!1,requireEmailVerification:!1,scimOnNonTransactionalAdapter:!1,secureCookiesDisabled:!1,sessionFreshAgeZero:!1,trustedOriginsWildcard:!1}),Hl=(e,t)=>{if(C(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?ql(s):jl();return{scope:A(e),file:t,line:e.getStartLineNumber(),...i}},Gl=(e,t)=>xo(e,t,Hl),Yl=(e,t)=>{if(!r.isPropertyAccessExpression(e))return;const s=e.getName();if(t.methods.has(s))return li(e.getExpression(),t.matchReceiver)?s:void 0},Ql=(e,t,s)=>{const n=Yl(e.getExpression(),s);if(n===void 0)return;const i=e.getArguments()[s.argIndex];if(!(!i||!q(i)||xe(i))&&!(s.requireUnmodifiedReach===!0&&!sl(i)))return{scope:A(e),file:t,line:e.getStartLineNumber(),method:n}},Et=(e,t,s)=>O(e,t,(n,i)=>Ql(n,i,s)),Xl=new Set(["content","pdf","scrape","screenshot"]),Jl=(e,t)=>Et(e,t,{argIndex:0,matchReceiver:s=>s==="ctx.browser",methods:Xl}),Zl=new Set(["createBrowser","createInboundEmailHandler","createPayment"]),ed=new Set(["RateLimiter"]),td=new Set(["extend"]),pn="lunora",sd=["vite.config.ts","vite.config.mts","vite.config.js","vite.config.mjs"],Li=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=S(i);t.push(o),i.getInitializer()?.getKind()===d.TrueKeyword&&s.push(o);continue}(r.isShorthandPropertyAssignment(i)||r.isMethodDeclaration(i))&&t.push(S(i))}return{analyzable:!n,presentKeys:t,trueKeys:s}},Jt=e=>e&&r.isObjectLiteralExpression(e)?Li(e):{analyzable:!1,presentKeys:[],trueKeys:[]},nd=e=>{const t=e&&(r.isArrowFunction(e)||r.isFunctionExpression(e))?e:void 0,s=t&&ii(t.getBody());return s?Li(s):{analyzable:!1,presentKeys:[],trueKeys:[]}},id=(e,t)=>{const s=[];for(const n of x(e,d.CallExpression)){const i=C(n.getExpression());i!==void 0&&(Zl.has(i)?s.push({callee:i,file:t,line:n.getStartLineNumber(),...Jt(n.getArguments()[0])}):td.has(i)&&s.push({callee:i,file:t,line:n.getStartLineNumber(),...nd(n.getArguments()[0])}))}for(const n of x(e,d.NewExpression)){const i=C(n.getExpression());i===void 0||!ed.has(i)||s.push({callee:i,file:t,line:n.getStartLineNumber(),...Jt(n.getArguments()[0])})}return s},rd=e=>{for(const t of sd){const s=E(e,t);if(!$(s))continue;const n=new gs({compilerOptions:{allowJs:!0},skipFileDependencyResolution:!0,skipLoadingLibFiles:!0,useInMemoryFileSystem:!0}).createSourceFile(t,ft(s,"utf8")),i=[];for(const o of x(n,d.CallExpression))C(o.getExpression())===pn&&i.push({callee:pn,file:t,line:o.getStartLineNumber(),...Jt(o.getArguments()[0])});return i}return[]},od=(e,t)=>{const s=[];for(const{displayPath:n,filePath:i}of Be(t)){const o=e.getSourceFile(i)??e.addSourceFileAtPath(i);s.push(...id(o,n))}return s.push(...rd(gt(t))),s},mn="ctx.containers.",ad=e=>{if(!e.startsWith(mn))return!1;const t=e.slice(mn.length);return t.length>0&&!t.includes(".")},cd=(e,t)=>Et(e,t,{argIndex:0,matchReceiver:ad,methods:new Set(["get"])}),ld=new Set(["allow","deny","setAllowed"]),dd=e=>{const t=e.getArguments()[0];if(!t||!r.isObjectLiteralExpression(t))return!1;const s=B(t,"enableInternet");return s!==void 0&&r.isPropertyAssignment(s)&&r.isTrueLiteral(s.getInitializerOrThrow())},ud=(e,t)=>{const s=e.getExpression();if(!(!r.isPropertyAccessExpression(s)||s.getName()!=="start"||!dd(e)))return{detail:"enableInternet: true",scope:A(e),file:t,kind:"enable_internet",line:e.getStartLineNumber()}},fd=(e,t)=>{const s=e.getExpression();if(!r.isPropertyAccessExpression(s)||!ld.has(s.getName()))return;const n=s.getExpression();if(!(!r.isPropertyAccessExpression(n)||n.getName()!=="egress"))return{detail:s.getName(),scope:A(e),file:t,kind:"egress_relaxation",line:e.getStartLineNumber()}},gd=(e,t)=>ud(e,t)??fd(e,t),pd=(e,t)=>O(e,t,gd),md=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||t.getName()!=="count")return;const s=t.getExpression();if(K(s)){const n=e.getArguments()[0];return n&&r.isStringLiteral(n)?n.getLiteralText():""}return r.isPropertyAccessExpression(s)&&K(s.getExpression())?s.getName():void 0},hd=e=>{const t=e.getExpression(),s=r.isPropertyAccessExpression(t)?t.getExpression():void 0;return e.getArguments()[s!==void 0&&K(s)?1:0]},vd=new Set(["baseWhere","relationBaseWhere","restrictsCounts","where"]),Ed=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=>vd.has(n))||t.some(n=>n==="AND"||n==="OR"||n==="NOT")?void 0:t},xd=(e,t,s)=>{const n=new Map(s.map(i=>[i.name,i.aggregateIndexed===!0]));return O(e,t,(i,o)=>{const a=md(i);if(a===void 0)return;const c=Ed(hd(i));return{file:o,indexed:n.get(a)!==!1,...c===void 0?{}:{filterFields:c},line:i.getStartLineNumber(),scope:A(i),table:a}})},Sd=new Set(["defineExportSink","r2Sink","webhookExportSink"]),Ad=e=>{const t=e.getExpression();if(!r.isIdentifier(t))return;const s=t.getText();return Sd.has(s)?s:void 0},yd=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=S(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(S(n))}return{analyzable:!0,emptyKeys:s,presentKeys:t}},bd=(e,t)=>{const s=[];for(const{displayPath:n,filePath:i}of Be(t)){const o=e.getSourceFile(i)??e.addSourceFileAtPath(i);for(const a of x(o,d.CallExpression)){const c=Ad(a);if(c===void 0)continue;const l=a.getArguments()[0],u=l&&r.isObjectLiteralExpression(l)?yd(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},Nd=new Map([["dbRateLimit",2],["rateLimit",2],["verifyTurnstileMiddleware",0]]),Pd=new Set(["dbRateLimit","rateLimit"]),wd=e=>{const t=oi(e);if(!t)return!1;const s=B(t,"failOpen");return s!==void 0&&r.isPropertyAssignment(s)&&s.getInitializer()?.getKind()===d.TrueKeyword},Id=(e,t)=>{const s=C(e.getExpression());if(s===void 0)return;const n=Nd.get(s);if(n!==void 0)return{callee:s,scope:A(e),failOpen:wd(e.getArguments()[n]),file:t,limitName:Pd.has(s)?ri(e):"",line:e.getStartLineNumber()}},Td=(e,t)=>O(e,t,Id),Cd=e=>{const t=e.getInitializer();if(!t||!r.isCallExpression(t))return;const s=ae(t);if(s?.kind!=="query")return;const n=So(t,s.receiver);return n?{exportName:Q(e)??e.getName(),handler:n}:void 0},hn=e=>{const t=e.getParent();return t&&r.isPropertyAccessExpression(t)&&t.getExpression()===e?t:void 0},Od=e=>{const t=hn(e);if(!t)return"ctx.flags";if(t.getName()==="details"){const s=hn(t);return s?`ctx.flags.details.${s.getName()}`:"ctx.flags.details"}return`ctx.flags.${t.getName()}`},kd=(e,t)=>{const s=[];for(const n of ht(e.handler,"flags"))s.push({callee:Od(n),exportName:e.exportName,file:t,line:n.getStartLineNumber()});return s},Rd=(e,t)=>{const s=[];for(const n of Z(e)){const i=Cd(n);i&&s.push(...kd(i,t))}return s},Fd=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Rd(i,P(t,n)))}return s},Ld=e=>!r.isPropertyAccessExpression(e)||e.getName()!=="boolean"?!1:Y(e.getExpression(),["flags"]),Dd=e=>{if(e?.getKind()===d.TrueKeyword)return!0;if(e?.getKind()===d.FalseKeyword)return!1},Md=(e,t)=>{if(!Ld(e.getExpression()))return;const[s,n]=e.getArguments();if(!s||!(r.isStringLiteral(s)||r.isNoSubstitutionTemplateLiteral(s)))return;const i=s.getLiteralValue(),o=Dd(n);if(!(i.length===0||o===void 0))return{defaultValue:o,scope:A(e),file:t,key:i,line:e.getStartLineNumber()}},_d=(e,t)=>O(e,t,Md),zd=e=>{const t=e.getExpression();return r.isPropertyAccessExpression(t)&&t.getName()==="withGeoIndex"},$d=e=>{const t=e.getArguments()[0];return t&&r.isStringLiteral(t)?t.getLiteralText():""},Kd=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=P(t,n);for(const a of x(i,d.CallExpression))zd(a)&&s.push({file:o,indexName:$d(a),line:a.getStartLineNumber()})}return s},Bd=new Set(["delete","get","head","options","patch","post","put"]),Vd=new Set(["handler","stream"]),Ud=new Set(["runAction","runMutation"]),Wd=new Set(["delete","insert","insertManyUnsafe","patch","patchIf","replace"]),_e=(e,t)=>e!==void 0&&r.isIdentifier(e)&&e.getText()===t,Di=(e,t)=>{if(!(e===void 0||!r.isObjectBindingPattern(e))){for(const s of e.getElements())if(fe(s)===t){const i=s.getNameNode();return r.isIdentifier(i)?i.getText():void 0}}},vn=(e,t)=>{const s=e.getParameters()[0]?.getNameNode();if(s!==void 0)return t?r.isIdentifier(s)?s.getText():void 0:Di(s,"ctx")},En=(e,t)=>{const s=e.getParameters()[t?1:0]?.getNameNode();return t?s!==void 0&&r.isIdentifier(s)?s.getText():void 0:Di(s,"request")},xn=(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(Ud.has(a)&&_e(c,t))return a;if(Wd.has(a)&&r.isPropertyAccessExpression(c)&&c.getName()==="db"&&_e(c.getExpression(),t))return`db.${a}`}},Sn=(e,t)=>{const s=e.getBody();for(const n of s.getDescendantsOfKind(d.PropertyAccessExpression))if(n.getName()==="auth"&&_e(n.getExpression(),t))return!0;for(const n of s.getDescendantsOfKind(d.VariableDeclaration)){const i=n.getNameNode();if(!(!r.isObjectBindingPattern(i)||!_e(n.getInitializer(),t))){for(const o of i.getElements())if(fe(o)==="auth")return!0}}return!1},qd=/signature|hmac|digest|(?:^|[_-])sig(?:[_-]|$)/i,jd=(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"&&_e(n.getExpression(),t)},Hd=e=>[...r.isStringLiteral(e)?[e.getLiteralText()]:[],...e.getDescendantsOfKind(d.StringLiteral).map(t=>t.getLiteralText())],Mi=(e,t)=>{const s=e.getVariableDeclaration(t)?.getInitializer();return s===void 0?[]:Hd(s)},Gd=(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)?Mi(t,a.getText()):[]}return[]},Yd=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=Mi(s,t.getText());return n.length>0?n:Gd(t,s)},An=(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=>jd(i,t)&&Yd(i).some(o=>qd.test(o)))},Qd=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!Vd.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(Bd.has(i)){const o=n.getExpression();return r.isIdentifier(o)&&o.getText()==="httpRoute"?i.toUpperCase():void 0}s=n.getExpression()}},Xd=(e,t)=>{const s=e.getExpression();if(r.isIdentifier(s)&&s.getText()==="httpAction"){const c=Gt(e.getArguments()[0]),l=c&&vn(c,!0);if(!c||l===void 0||An(c,En(c,!0)))return;const u=xn(c,l);return u===void 0?void 0:{scope:A(e),file:t,kind:"httpAction",line:e.getStartLineNumber(),readsAuth:Sn(c,l),sideEffect:u}}const n=Qd(e);if(n===void 0)return;const i=Gt(e.getArguments()[0]),o=i&&vn(i,!1);if(!i||o===void 0||An(i,En(i,!1)))return;const a=xn(i,o);return a===void 0?void 0:{scope:A(e),file:t,kind:"httpRoute",line:e.getStartLineNumber(),method:n,readsAuth:Sn(i,o),sideEffect:a}},Jd=(e,t)=>O(e,t,Xd),Zd=new Set(["btoa","encodeURI","encodeURIComponent","isSafeHeaderValue","Number","parseFloat","parseInt"]),eu=new Set(["append","set"]),_i=e=>e!==void 0&&(r.isStringLiteral(e)||r.isNoSubstitutionTemplateLiteral(e))?e.getLiteralText():"",yn=(e,t)=>(r.isCallExpression(e)?[e,...e.getDescendantsOfKind(d.CallExpression)]:e.getDescendantsOfKind(d.CallExpression)).some(n=>Zd.has(C(n.getExpression())??"")&&Je(n,t)),tu=(e,t)=>{if(yn(e,t))return!0;const s=pe(e);return s!==void 0&&yn(s,t)},Zt=(e,t)=>nl(e,t)&&!tu(e,t),su=e=>{if(r.isPropertyAccessExpression(e)&&e.getName()==="headers")return!0;const t=pe(e);return t!==void 0&&r.isNewExpression(t)&&C(t.getExpression())==="Headers"},ot=e=>{if(e===void 0)return;if(r.isObjectLiteralExpression(e))return e;const t=pe(e);return t!==void 0&&r.isObjectLiteralExpression(t)?t:void 0},ws=(e,t,s)=>{for(const n of e.getProperties())if(r.isPropertyAssignment(n)){const i=n.getInitializer();i!==void 0&&Zt(i,s.requestName)&&s.rows.push({scope:s.scope,file:s.relativePath,headerName:_i(n.getNameNode()),line:i.getStartLineNumber(),via:t})}else if(r.isShorthandPropertyAssignment(n)){const i=n.getNameNode();Zt(i,s.requestName)&&s.rows.push({scope:s.scope,file:s.relativePath,headerName:S(n),line:i.getStartLineNumber(),via:t})}else if(r.isSpreadAssignment(n)){const i=ot(n.getExpression());i!==void 0&&ws(i,t,s)}},zi=(e,t)=>{const s=ot(e);if(s===void 0)return;const n=B(s,"headers");if(n===void 0||!r.isPropertyAssignment(n))return;const i=ot(n.getInitializer());i!==void 0&&ws(i,"response-init",t)},nu=(e,t)=>{const s=C(e.getExpression());if(s==="Response")zi(e.getArguments()[1],t);else if(s==="Headers"){const n=ot(e.getArguments()[0]);n!==void 0&&ws(n,"headers-ctor",t)}},iu=(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"){zi(e.getArguments()[1],t);return}if(eu.has(n)&&su(i)){const o=e.getArguments()[1];o!==void 0&&Zt(o,t.requestName)&&t.rows.push({scope:t.scope,file:t.relativePath,headerName:_i(e.getArguments()[0]),line:o.getStartLineNumber(),via:n==="set"?"headers-set":"headers-append"})}},ru=(e,t)=>{for(const s of e.getDescendantsOfKind(d.NewExpression))nu(s,t);for(const s of e.getDescendantsOfKind(d.CallExpression))iu(s,t)},ou=(e,t)=>{const s=e.getExpression();if(!r.isIdentifier(s)||s.getText()!=="httpAction")return[];const n=Gt(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 ru(n,{scope:A(e),relativePath:t,requestName:o.getText(),rows:a}),a},au=(e,t)=>{const s=[];for(const n of x(e,d.CallExpression))s.push(...ou(n,t));return s},cu=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...au(i,P(t,n)))}return s},lu=new Set(["accessToken","backupCodes","idToken","password","publicKey","refreshToken","secret","token","tokenHash"]),du=new Set(["__proto__","email","exp","expiresAtMs","iat","name","nbf","orgId","role","roles","sub","teamId","userId"]),zt=32,uu=/^[A-Z_]\w{0,63}$/i,fu={defineLiveStream:"liveStreams",defineRoom:"typedWebSockets",defineWebSocket:"socketRoutes"},gu=new Set(["allowedHosts","deniedHosts","interceptHttps"]),pu=(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())},mu=(e,t)=>e!==void 0&&r.isObjectLiteralExpression(e)&&e.getProperties().some(s=>{if(r.isShorthandPropertyAssignment(s))return t.has(S(s));if(!r.isPropertyAssignment(s)||!t.has(S(s)))return!1;const n=h(s.getInitializer())?.getText();return n!=="false"&&n!=="undefined"}),hu=new Set(["durable"]),vu=new Set(["rollback"]),$i=e=>{const t=e.getExpression();return r.isPropertyAccessExpression(t)?t.getName():t.getText()},Eu="defineApp",Re="app",bn=(e,t)=>e.getDescendantsOfKind(d.PropertyAssignment).some(s=>S(s)===Re&&s.getInitializer()?.getText()===t)||t===Re&&e.getDescendantsOfKind(d.ShorthandPropertyAssignment).some(s=>S(s)===Re),xu=e=>{if(e===void 0||!Wo.includes(e.getSourceFile().getBaseName()))return!1;if(r.isMethodDeclaration(e))return r.isObjectLiteralExpression(e.getParent())&&S(e)===Re;if(!(r.isArrowFunction(e)||r.isFunctionExpression(e)||r.isFunctionDeclaration(e)))return!1;const t=e.getParent();if(r.isPropertyAssignment(t))return S(t)===Re;if(r.isVariableDeclaration(t))return bn(e.getSourceFile(),t.getName());const s=r.isFunctionDeclaration(e)?e.getName():void 0;return s!==void 0&&bn(e.getSourceFile(),s)},Su="AppBuilder",Ki=e=>{const t=e.getSourceFile();return t.getBaseNameWithoutExtension()==="app"&&t.getDirectory().getBaseName()==="_generated"},Bi=e=>{const t=e.getType(),s=(t.getConstraint()??t).getSymbol();return s?.getName()===Su&&s.getDeclarations().some(n=>Ki(n))},Au=e=>e.getText()===Eu&&(e.getSymbol()?.getDeclarations()??[]).every(t=>r.isImportSpecifier(t)||r.isImportClause(t)||Ki(t)),Is=(e,t,s=new Set)=>{const n=mt(t);if(n===void 0||!r.isIdentifier(n))return!1;if(Au(n))return!0;const i=n.getText();if(s.has(i))return!1;s.add(i);for(const o of n.getAncestors()){if(r.isParametered(o)&&o.getParameters().some(a=>a.getName()===i))return xu(o);if(r.isBlock(o)||r.isSourceFile(o)){const a=o.getVariableStatements().flatMap(c=>c.getDeclarations()).find(c=>c.getName()===i);if(a!==void 0)return Is(e,a.getInitializer(),s)}}return!1},Vi=(e,t)=>{const s=ps(t.getExpression());return s?.member==="deliveryAuthorization"&&(Is(e,s.object)||Bi(s.object))},yu=new Map([["defineContainer",{keys:gu,signal:"containerEgressPolicy"}],["defineStep",{keys:vu,signal:"workflowRollback"}],["stream",{keys:hu,signal:"durableStreams"}]]),bu=(e,t)=>{const s=yu.get($i(t));if(s!==void 0)return t.getArguments().some(n=>mu(pu(e,n),s.keys))?s.signal:void 0},Nu=(e,t)=>fu[$i(t)]??(Vi(e,t)?"deliveryAuthorization":void 0),Pu=(e,t,s)=>{const n={containerEgressPolicy:!1,deliveryAuthorization:!1,durableStreams:!1,liveContext:!1,liveStreams:!1,secrets:!1,socketRoutes:!1,typedWebSockets:!1,workflowRollback:!1};for(const i of y(t)){const o=e.getSourceFile(i)??e.addSourceFileAtPath(i);if(!n.secrets||!n.liveContext){const c=jo(o);n.secrets=n.secrets||c.has("secrets"),n.liveContext=n.liveContext||c.has("live")}const a=x(o,d.CallExpression);for(const c of a){const l=bu(o,c)??Nu(o,c);l!==void 0&&(n[l]=!0)}if(n.liveStreams=n.liveStreams||o.getFullText().includes("defineLiveStream")&&a.some(c=>pi(c,"defineLiveStream")),Object.values(n).every(Boolean))break}if(n.typedWebSockets=n.typedWebSockets||n.socketRoutes,!n.deliveryAuthorization&&s!==void 0){const i=e.getSourceFile(s)??new gs({compilerOptions:{allowJs:!0},skipFileDependencyResolution:!0,skipLoadingLibFiles:!0,useInMemoryFileSystem:!0}).createSourceFile(s,ft(s,"utf8"),{overwrite:!0});n.deliveryAuthorization=i.getDescendantsOfKind(d.CallExpression).some(o=>Vi(i,o))}return n},ze={claims:[],diagnostics:[]},re=e=>({claims:[],diagnostics:[e]}),xt=e=>r.isParenthesizedExpression(e)||r.isAsExpression(e)||r.isSatisfiesExpression(e)?xt(e.getExpression()):e,Ui=e=>{if(r.isSpreadAssignment(e))return!0;const t=e.getNameNode();return r.isComputedPropertyName(t)&&Ss(t)===void 0},be=e=>e.getProperties().some(t=>Ui(t)),Wi=(e,t)=>e.getProperties().findLast(s=>!r.isSpreadAssignment(s)&&S(s)===t),qi=(e,t)=>{const s=Wi(e,t);return r.isPropertyAssignment(s)?s.getInitializer():void 0},ji=(e,t)=>{const s=qi(e,t);return s!==void 0&&xt(s).getKind()===d.FalseKeyword},$e="unreadable",Ts=(e,t)=>{const s=Wi(e,t);if(s!==void 0)return r.isPropertyAssignment(s)?s.getInitializer()??$e:r.isShorthandPropertyAssignment(s)?s.getNameNode():$e},Nn=e=>{if(e===void 0||!r.isBlock(e))return e;const t=e.getStatements().filter(s=>r.isReturnStatement(s));return t.length===1?t[0]?.getExpression():void 0},ue=(e,t=0)=>{if(t>4)return;const s=xt(e);if(r.isObjectLiteralExpression(s))return s;if(r.isArrowFunction(s)||r.isFunctionExpression(s)){const c=Nn(s.getBody());return c===void 0?void 0:ue(c,t+1)}if(!r.isIdentifier(s))return;const n=s.getParent(),i=r.isShorthandPropertyAssignment(n)?n.getValueSymbol():s.getSymbol(),o=i?.isAlias()?i.getAliasedSymbol():i,[a]=o?.getDeclarations()??[];if(r.isVariableDeclaration(a)){const c=a.getInitializer();return c===void 0?void 0:ue(c,t+1)}if(r.isFunctionDeclaration(a)){const c=Nn(a.getBody());return c===void 0?void 0:ue(c,t+1)}},wu=e=>{if(e===void 0)return;const t=xt(e);if(r.isArrayLiteralExpression(t))return"string";if(!(!r.isStringLiteral(t)&&!r.isNoSubstitutionTemplateLiteral(t)))switch(t.getLiteralValue()){case"boolean":return"boolean";case"date":case"string":return"string";case"number":return"number";default:return}},Iu=e=>ji(e,"returned"),Tu=(e,t)=>{if(!uu.test(e))return{reason:`\`${e}\` is not an identifier of at most 64 characters`};if(du.has(e)||lu.has(e))return{reason:`\`${e}\` is reserved or secret-bearing, so the session never forwards it`};const s=ue(t);if(s===void 0||be(s))return{reason:`\`${e}\` is not a literal field definition`};const n=wu(qi(s,"type"));return n===void 0?{reason:`\`${e}\` is not a scalar (string, number, boolean or date) column`}:{claim:{name:e,type:n,writable:!ji(s,"input")}}},Cu=e=>{if(r.isSpreadAssignment(e))return;if(!r.isPropertyAssignment(e)&&!r.isShorthandPropertyAssignment(e))return{reason:`\`${e.getName()}\` is a method or accessor, not a field definition`};const t=r.isPropertyAssignment(e)?S(e):e.getName(),s=r.isPropertyAssignment(e)?e.getInitializer():e.getNameNode(),n=s===void 0?void 0:ue(s);if(!(n!==void 0&&!be(n)&&Iu(n)))return s===void 0?{reason:`\`${t}\` has no initializer`}:Tu(t,s)},Ou=e=>{const t=[],s=[];for(const n of e.getProperties()){const i=Cu(n);i?.claim!==void 0?t.push(i.claim):i!==void 0&&s.push(`${i.reason??"the entry cannot be a claim"}; it is not added to ctx.auth`)}return t.length>zt&&s.push(`${t.length.toString()} claims declared; the first ${zt.toString()} are forwarded, the rest are not`),{claims:t.slice(0,zt),diagnostics:s}},ku=e=>{if(be(e))return re("`user` has a spread or a computed key, so the user columns cannot be read");const t=Ts(e,"additionalFields");if(t===void 0)return ze;const s=t===$e?void 0:ue(t);return s===void 0||be(s)?re("`user.additionalFields` is not an object literal, so the user columns cannot be read"):Ou(s)},Ru=e=>{if(be(e))return re("the auth options contain a spread or a computed key, so the user columns cannot be read");const t=Ts(e,"user");if(t===void 0)return ze;const s=t===$e?void 0:ue(t);return s===void 0?re("`user` is not an object literal, so the user columns cannot be read"):ku(s)},Fu=(e,t)=>{const s=t.getExpression();if(!r.isPropertyAccessExpression(s)||s.getName()!=="auth")return!1;const n=s.getExpression();return Is(e,n)||Bi(n)},Lu=e=>{const t=e.getProperties(),s=t.findLastIndex(n=>!r.isSpreadAssignment(n)&&S(n)==="options");return t.some((n,i)=>i>s&&Ui(n))},Du=e=>{const[t]=e.getArguments();if(t===void 0)return ze;if(!r.isObjectLiteralExpression(t))return re(".auth() is not called with an object literal, so its user columns cannot be read");const s=Ts(t,"options");if(s===void 0)return be(t)?re("the .auth() argument has a spread or a computed key, so its options cannot be read"):ze;if(Lu(t))return re("a spread or computed key after `options` in .auth() may replace it, so the user columns cannot be read");const n=s===$e?void 0:ue(s);return n===void 0?re("`.auth({ options })` does not resolve to an object literal, so the user columns cannot be read"):Ru(n)},Hi=(e,t)=>{const s=[];for(const{filePath:o}of Be(t)){const a=e.getSourceFile(o)??e.addSourceFileAtPath(o);s.push(...x(a,d.CallExpression).filter(c=>Fu(a,c)))}const[n,...i]=s;return n===void 0?ze:i.length===0?Du(n):re(`the app builder's .auth() is called ${s.length.toString()} times, so which declaration applies cannot be read`)},Gi="identity.ts",Mu=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineIdentity";for(const s of t.getDeclarations())if(r.isImportSpecifier(s))return hi(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineIdentity":!1;return!1},_u=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&&hi(n.getModuleSpecifierValue())}return!1},zu=e=>{if(r.isIdentifier(e))return Mu(e);if(r.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineIdentity"&&r.isIdentifier(t)&&_u(t)}return!1},$u=e=>{const t=[];for(const s of e.getVariableDeclarations()){const n=s.getInitializer();if(n?.getKind()!==d.CallExpression||!zu(n.getExpression()))continue;const o=s.getNameNode();if(!r.isIdentifier(o)){if(s.getVariableStatement()?.hasExportKeyword()!==!0)continue;throw we(o,"defineIdentity exports must be plain named exports (no destructuring)")}const a=vs(s,"member");a!==void 0&&t.push({exportName:a})}return t},Ku=(e,t)=>{const s=E(t,Gi);if(!$(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s),i=$u(n);if(i.length!==0){if(i.length>1)throw we(n,`lunora/identity.ts declares ${i.length.toString()} defineIdentity() contracts (${i.map(o=>o.exportName).join(", ")}); exactly one is allowed`);return i[0]}},Yi=new Set(["auth","context.auth"]),Bu="userId",Vu=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(S(s))}return t},Uu=(e,t)=>{const s=E(t,Gi);if(!$(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const i of n.getDescendantsOfKind(d.CallExpression)){if(C(i.getExpression())!=="defineIdentity")continue;const[o]=i.getArguments();return o&&r.isObjectLiteralExpression(o)?Vu(o):void 0}},Wu=e=>{if(e===void 0||!r.isPropertyAccessExpression(e)||e.getName()!=="identity")return;const t=e.getExpression();return Yi.has(t.getText())||Y(t,["auth"])?e:void 0},es=(e,t=!1)=>r.isAwaitExpression(e)?es(e.getExpression(),!0):r.isParenthesizedExpression(e)||r.isAsExpression(e)||r.isSatisfiesExpression(e)||r.isTypeAssertion(e)||r.isNonNullExpression(e)?es(e.getExpression(),t):{awaited:t,value:e},Qi=e=>{if(e===void 0)return;const{awaited:t,value:s}=es(e);if(!t||!r.isCallExpression(s))return;const n=s.getExpression();if(!r.isPropertyAccessExpression(n)||n.getName()!=="getIdentity")return;const i=n.getExpression();return Yi.has(i.getText())||Y(i,["auth"])?s:void 0},Xi=e=>{if(r.isPropertyAccessExpression(e))return e.getName();const t=h(e.getArgumentExpression());return r.isStringLiteral(t)||r.isNoSubstitutionTemplateLiteral(t)?t.getLiteralValue():void 0},qu=e=>{if(!r.isPropertyAccessExpression(e)&&!r.isElementAccessExpression(e)||Pe(e))return;const t=e.getExpression();return Wu(t)!==void 0||Qi(t)!==void 0?Xi(e):void 0},ts=(e,t,s,n)=>({declared:t===Bu||n.has(t),file:s,key:t,line:e.getStartLineNumber(),scope:A(e)}),Pn=(e,t,s)=>{const n=qu(e);return n===void 0?void 0:ts(e,n,t,s)},ju=(e,t,s)=>{if(Qi(e.getInitializer())===void 0)return[];const n=e.getNameNode();return r.isObjectBindingPattern(n)?n.getElements().filter(i=>i.getDotDotDotToken()===void 0).flatMap(i=>{const o=Ss(i.getPropertyNameNode()??i.getNameNode());return o===void 0?[]:[ts(i,o,t,s)]}):!r.isIdentifier(n)||!G(e)?[]:n.findReferencesAsNodes().filter(i=>i!==n).flatMap(i=>{const o=T(i),a=o.getParent();if(!r.isPropertyAccessExpression(a)&&!r.isElementAccessExpression(a)||Pe(a))return[];const c=a.getExpression()===o?Xi(a):void 0;return c===void 0?[]:[ts(a,c,t,s)]})},Hu=(e,t)=>{const s=Uu(e,t);if(s===void 0)return[];const n=Hi(e,t).claims.filter(o=>!o.writable).map(o=>o.name),i=new Set([...s,...n]);return[...oe(e,t,d.PropertyAccessExpression,(o,a)=>Pn(o,a,i)),...oe(e,t,d.ElementAccessExpression,(o,a)=>Pn(o,a,i)),...oe(e,t,d.VariableDeclaration,(o,a)=>ju(o,a,i))]},Gu=(e,t)=>{if(C(e.getExpression())!=="buildImageDeliveryUrl")return;const s=e.getArguments()[0];if(!s)return;const n=M(s,"key");if(!(!n||!q(n)||xe(n)))return{scope:A(e),file:t,line:e.getStartLineNumber()}},Yu=(e,t)=>O(e,t,Gu),Qu=new Set(["delete","get","getRaw","getWithMetadata","put"]),Xu=(e,t,s=[])=>{const n=Et(e,t,{argIndex:0,matchReceiver:i=>i==="ctx.kv"||i.startsWith("ctx.kv."),methods:Qu});return Es(n,s)},Ju=new Set(["queue","send"]),wn=new Set(["bcc","cc","to"]),Zu=e=>{if(!r.isPropertyAccessExpression(e))return;const t=e.getName();if(!Ju.has(t))return;const s=e.getExpression();return Y(s,["mail"])||Y(s,["email"])?t:void 0},ef=e=>r.isObjectLiteralExpression(e)?e.getProperties().some(t=>{if(r.isShorthandPropertyAssignment(t)){const n=t.getNameNode();return wn.has(S(t))&&q(n)&&!xe(n)}if(!r.isPropertyAssignment(t)||!wn.has(S(t)))return!1;const s=t.getInitializer();return s!==void 0&&q(s)&&!xe(s)}):!1,tf=(e,t)=>{const s=Zu(e.getExpression());if(s===void 0)return;const n=e.getArguments()[0];if(!(!n||!ef(n)))return{scope:A(e),file:t,line:e.getStartLineNumber(),method:s}},sf=(e,t)=>O(e,t,tf),nf=(e,t,s)=>{const n=e.getArguments()[0];if(!n||!r.isObjectLiteralExpression(n))return[];const i=[];for(const o of n.getProperties()){const a=rt(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=rt(l);if(u===void 0)continue;const f=Si(l);f!=="custom"&&i.push({column:u,exportName:t,file:s,line:l.getStartLineNumber(),strategy:f,table:a})}}return i},rf=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&r.isCallExpression(s)?ae(s):void 0;return n?.receiver?As(n.receiver).flatMap(i=>nf(i,Q(e)??e.getName(),t)):[]},of=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=P(t,n);for(const a of Z(i))s.push(...rf(a,o))}return s},af=new Set(["delete","deleteMany","hardDelete","insert","insertMany","patch","patchMany","replace","restore","upsert","upsertMany"]),Ji=e=>{if(!r.isIdentifier(e))return;const t=e.getSymbol()?.getDeclarations()[0];if(t===void 0||!r.isVariableDeclaration(t))return;const s=t.getInitializer();if(!(!(t.getVariableStatement()?.getDeclarationKind()===pt.Const)||s===void 0||!r.isPropertyAccessExpression(s)||!K(s.getExpression())))return{database:s.getExpression(),table:s.getName()}},St=(e,t)=>{const s=e.getExpression();if(!r.isPropertyAccessExpression(s)||!t.has(s.getName()))return;const n=s.getName(),i=s.getExpression(),o=Ji(i);if(o!==void 0)return{database:o.database,method:n,table:o.table};if(r.isPropertyAccessExpression(i)&&K(i.getExpression()))return{database:i.getExpression(),method:n,table:i.getName()}},cf=new Set(["replace"]),lf=e=>{const t=e.getExpression();return r.isPropertyAccessExpression(t)&&t.getName()==="replace"&&K(t.getExpression())?!0:St(e,cf)!==void 0},df=e=>{const t=e.getArguments()[0];if(t===void 0||!r.isObjectLiteralExpression(t))return;const s=B(t,"server");if(s!==void 0)return r.isPropertyAssignment(s)?s.getInitializer():s},uf=e=>{if(!e.isExported())return;const t=e.getInitializer();if(t?.getKind()!==d.CallExpression)return;const s=t;return Jo(s.getExpression())?s:void 0},ff=e=>{const t=uf(e),s=t===void 0?void 0:df(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=>lf(o)).map(o=>({exportName:i,file:"lunora/mutators.ts",line:o.getStartLineNumber()}))},gf=e=>e.getVariableDeclarations().flatMap(t=>ff(t)),pf=(e,t)=>{const s=E(t,Xo);if(!$(s))return[];const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);return gf(n)},mf=new Set(["delete","get","patch"]),hf=new Set(["accountId","authorId","companyId","createdBy","createdById","customerId","groupId","memberId","organizationId","orgId","ownerId","projectId","teamId","tenantId","userId","workspaceId"]),vf=new Set(["auth","identity","session","user"]),Ef=new Set([d.EqualsEqualsEqualsToken,d.EqualsEqualsToken,d.ExclamationEqualsEqualsToken,d.ExclamationEqualsToken]),xf=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||t.getName()!=="normalizeId"||!K(t.getExpression()))return;const s=e.getArguments()[0];return s&&r.isStringLiteral(s)?s.getLiteralText():""},Sf=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},Af=(e,t)=>e.getDescendantsOfKind(d.Identifier).some(s=>s.getText()===t),yf=e=>r.isThrowStatement(e)||r.isReturnStatement(e)||e.getDescendantsOfKind(d.ThrowStatement).length>0||e.getDescendantsOfKind(d.ReturnStatement).length>0,bf=(e,t)=>e.getDescendantsOfKind(d.IfStatement).some(s=>Af(s.getExpression(),t)&&yf(s.getThenStatement())),Nf=(e,t)=>{for(const s of x(e,d.CallExpression)){const n=s.getExpression();if(!r.isPropertyAccessExpression(n))continue;const i=n.getName();if(!mf.has(i))continue;const o=n.getExpression(),a=K(o);if(!(a||r.isPropertyAccessExpression(o)&&K(o.getExpression())))continue;const l=a?2:1;if(s.getArguments().slice(0,l).some(f=>r.isIdentifier(f)&&f.getText()===t))return i}},Pf=e=>e.getDescendantsOfKind(d.CallExpression).some(t=>t.getArguments().some(s=>xs(mt(s))!==void 0)),wf=e=>e.getDescendantsOfKind(d.BinaryExpression).some(t=>Ef.has(t.getOperatorToken().getKind())?r.isPropertyAccessExpression(t.getLeft())||r.isPropertyAccessExpression(t.getRight()):!1),If=e=>{for(const t of x(e,d.Identifier))if(hf.has(t.getText()))return!0;return[...vf].some(t=>ht(e,t).length>0)?!0:Pf(e)||wf(e)},Tf=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!r.isCallExpression(s))return[];const n=ae(s);if(n?.kind!=="query"&&n?.kind!=="mutation")return[];const i=Ei(s);if(i===void 0)return[];const o=n.receiver!==void 0&&mi(n.receiver,"use","rls"),a=If(i),c=new Set,l=[];for(const u of x(i,d.CallExpression)){const f=xf(u);if(f===void 0)continue;const g=Sf(u);if(g===void 0||c.has(g)||!bf(i,g))continue;const m=Nf(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},Cf=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=P(t,n);for(const a of Z(i))s.push(...Tf(a,o))}return s},Zi=(e,t)=>{const s=r.isIdentifier(e)&&t!==void 0?_(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},Of=e=>{const t=T(e),s=t.getParent();return(r.isPropertyAccessExpression(s)||r.isElementAccessExpression(s))&&s.getExpression()===t&&!Pe(s)},kf=e=>{const t=T(e).getParent();return r.isVariableDeclaration(t)&&r.isObjectBindingPattern(t.getNameNode())},Rf=e=>{const s=T(e).getParent();if(r.isSpreadAssignment(s)||r.isSpreadElement(s)){const n=s.getParent();return(r.isObjectLiteralExpression(n)||r.isArrayLiteralExpression(n))&&!Pe(n)}return r.isTemplateSpan(s)&&!r.isTaggedTemplateExpression(s.getParent().getParent())},at=e=>{const t=_(e);return t===void 0||wo(t.getSourceFile())},ss=(e,t)=>{const s=T(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"&&at(o);if(Zi(mt(o),t))return!(r.isPropertyAccessExpression(o)&&di.has(o.getName()))||r.isExpressionStatement(T(r.isAwaitExpression(n.getParent())?n.getParentOrThrow():n).getParent());if(!r.isPropertyAccessExpression(o))return!1;const a=o.getExpression();if(!r.isIdentifier(a)||!at(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}},Ze={kind:"opaque"},Ff={kind:"unreached"},Lf=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},ns=e=>{const t=h(e);if(r.isArrowFunction(t)||r.isFunctionExpression(t))return t;const s=r.isIdentifier(t)?_(t):void 0;if(s?.getSourceFile()!==e.getSourceFile())return;if(r.isFunctionDeclaration(s)){const i=Lf(s);return i===void 0||hs(i)?void 0:i}const n=G(s)?h(s.getInitializer()):void 0;return r.isArrowFunction(n)||r.isFunctionExpression(n)?n:void 0},er=(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?Ze:c===void 0?a.some(l=>l.isRestParameter())?Ze:Ff:c.isRestParameter()?Ze:{kind:"parameter",parameter:c}},Df=e=>{const t=T(e),s=t.getParent();if(!r.isCallExpression(s)||s.getExpression()===t)return;const n=ns(s.getExpression());return n===void 0?Ze:er(n,s,t)},Mf=new Set(["__defineGetter__","__defineSetter__","__proto__"]),_f=e=>r.isForInStatement(e)?e.getExpression():r.isConditionalExpression(e)?e.getCondition():r.isElementAccessExpression(e)?e.getArgumentExpression():void 0,tr=e=>{const t=T(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=_f(s);if(n!==void 0)return b(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},zf=4,sr=(e,t,s=0)=>{if(Po(e))return!0;if(Of(e)){const i=T(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||!Mf.has(c)}if(kf(e)||Rf(e)||tr(e)||ss(e,t))return!0;const n=Df(e);return n?.kind==="unreached"||n?.kind==="parameter"&&$f(n.parameter,s+1)},In=new WeakMap,$f=(e,t=0)=>{const s=e.getNameNode();if(!r.isIdentifier(s))return!0;const n=In.get(e.compilerNode);if(n!==void 0)return n;if(t>zf)return!1;const o=(s.getSymbol()?.getDeclarations().length??0)===1&&e.getParentOrThrow().getDescendantsOfKind(d.Identifier).every(a=>a===s||a.getText()!==s.getText()||_(a)?.compilerNode!==e.compilerNode||sr(a,void 0,t));return(o||t===0)&&In.set(e.compilerNode,o),o},Tn=new WeakMap,Kf=(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=_(i)?.compilerNode;return o!==void 0&&(o===t.compilerNode||s!==void 0&&o===e.compilerNode)})},Bf=(e,t,s)=>{const{context:n,impl:i}=e,o=Tn.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)?sr(g,n):!Pe(g),f=!Kf(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 v=l.get(m);return v===void 0||c.includes(g)||_(g)?.compilerNode!==v?!0:u(g)});return Tn.set(i.compilerNode,f),f},Cn=new WeakMap,Vf=e=>{let t=Cn.get(e.compilerNode);return t===void 0&&(t=new Map(e.getVariableDeclarations().flatMap(s=>{const n=Zo(s);return n===void 0?[]:[[n.compilerNode,s]]})),Cn.set(e.compilerNode,t)),t},Uf=e=>{const t=Vf(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&&Bf(c,a,n)?{...c,parameter:a,pristine:!0}:{...c,parameter:a,pristine:!1}},$t="args",Fe=e=>{const t=ps(e);if(t!==void 0){const c=h(t.object);return r.isIdentifier(c)&&c.getText()===$t?t.member:void 0}if(!r.isIdentifier(e))return;const s=_(e);if(!r.isBindingElement(s)||s.getDotDotDotToken()!==void 0)return;const n=s.getParent();if(!r.isObjectBindingPattern(n))return;const i=n.getParent(),o=G(i)?h(i.getInitializer()):void 0;return r.isBindingElement(i)&&fe(i)===$t||r.isIdentifier(o)&&o.getText()===$t?fe(s):void 0},Wf=new Set(["auth","identity","user"]),is=e=>{const t=i=>{const o=xs(i);return o!==void 0&&o.length>0&&Wf.has(o[0]??"")},s=h(e)??e;if(t(s))return!0;const n=pe(s);return n!==void 0&&t(n)},nr=(e,t=2)=>{const s=new Set;for(const n of[e,...e.getDescendants()]){const i=Fe(n);i!==void 0&&s.add(i);const o=t>0&&r.isIdentifier(n)?pe(n):void 0;if(o!==void 0)for(const a of nr(o,t-1))s.add(a)}return s},et=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[...et(n),...et(i)];if(s===d.AmpersandAmpersandToken){const l=(u,f)=>{const g=Fe(h(u)??u);return g===void 0?[]:et(f).filter(m=>m===g)};return[...l(n,i),...l(i,n)]}if(s!==d.ExclamationEqualsEqualsToken&&s!==d.ExclamationEqualsToken)return[];const o=[],a=Fe(h(n)??n),c=Fe(h(i)??i);return a!==void 0&&is(i)&&o.push(a),c!==void 0&&is(n)&&o.push(c),o},qf=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)&&Lo(i.getExpression(),"defineIdentityGuard")},jf=e=>{if(!qf(e.getExpression()))return[];const t=e.getArguments();return t.flatMap((s,n)=>{const i=Fe(h(s)??s),o=t.some((a,c)=>c!==n&&is(a));return i!==void 0&&o?[i]:[]})},Hf=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)},Gf=e=>r.isArrowFunction(e)||r.isFunctionExpression(e)||r.isFunctionDeclaration(e)||r.isMethodDeclaration(e),On=(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},Yf=e=>r.isAwaitExpression(e.getParent())||e.getType().isVoid(),Qf=(e,t)=>{const s=new Set;for(const n of x(e,d.IfStatement))if(n.getEnd()<=t&&On(n,e)&&Hf(n.getThenStatement()))for(const i of et(n.getExpression()))s.add(i);for(const n of x(e,d.CallExpression))if(n.getEnd()<=t&&Yf(n)&&On(n,e))for(const i of jf(n))s.add(i);return s},Xf=(e,t)=>{const s=nr(t);if(s.size===0)return!1;const n=e.getFirstAncestor(Gf);if(n===void 0)return!1;const i=Qf(n,e.getStart());return[...s].every(o=>i.has(o))},Jf=new Set(["at","concat","filter","find","findLast","flat","reverse","slice","sort","toReversed","toSorted"]),Zf=new Map([["Array",new Set(["from","of"])],["Object",new Set(["entries","values"])]]),rs=new Set(["catch","every","filter","finally","find","findIndex","findLast","findLastIndex","flatMap","forEach","map","reduce","reduceRight","some","sort","then"]),ir=e=>e.getNameNode().getDescendantsOfKind(d.BindingElement).filter(t=>r.isIdentifier(t.getNameNode())),eg=e=>{const t=T(e),s=t.getParent();if(r.isVariableDeclaration(s))return b(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},tg=e=>{const t=eg(e);return t===void 0?void 0:r.isIdentifier(t.getNameNode())?r.isForOfStatement(t.getParent().getParent())||G(t)?[t]:void 0:ir(t)},Le=e=>e.isUnion()?e.getUnionTypes().every(t=>Le(t)):e.isIntersection()?e.getIntersectionTypes().some(t=>Le(t)):!e.isAny()&&!e.isUnknown()&&!e.isObject()&&!e.isTypeParameter(),ct=(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)},tt=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]},sg=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)&&Zf.get(s.getText())?.has(t.getName())===!0&&at(s)},ng=e=>{const t=jt(e);if(!r.isArrowFunction(t)&&!r.isFunctionExpression(t))return;const s=T(t),n=s.getParent();return r.isCallExpression(n)&&n.getArguments().includes(s)&&ct(n,ui)?n:void 0},ig=(e,t)=>{if(!(r.isPropertyAccessExpression(e)||r.isElementAccessExpression(e))||e.getExpression()!==t)return;const s=T(e),n=s.getParent();return!r.isCallExpression(n)||n.getExpression()!==s?e:ct(n,Jf,t)?n:void 0},rg=(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},og=(e,t)=>{if(r.isArrayLiteralExpression(e))return e;const n=r.isSpreadElement(e)||r.isSpreadAssignment(e)||r.isShorthandPropertyAssignment(e)||r.isPropertyAssignment(e)&&b(e.getInitializer(),t)?e.getParent():void 0;return r.isArrayLiteralExpression(n)||r.isObjectLiteralExpression(n)?n:void 0},kn=e=>{const t=T(e),s=t.getParent();if(s===void 0)return;const n=r.isCallExpression(s)&&s.getArguments().includes(t)&&sg(s);return ig(s,t)??rg(s,t)??og(s,t)??(n?s:ng(t))},ag=5e4,rr=()=>({inProgress:new Set,verdicts:new Map});class cg{cuts=0;work=0;reset(){this.work=0}cut(){return this.cuts+=1,!0}spend(){return this.work+=1,this.work>ag&&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 lg=8,dg=8;class ug{budget;scope;taint;verdicts=rr();constructor(t,s,n){this.scope=t,this.budget=s,this.taint=n}isCompromised(t){return this.flowHasCompromisingUse(t)&&!Le(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)?ir(t):[])i(l,s);return!1}if(this.budget.spend())return!0;const a=(l,u)=>u&&s>=lg?this.budget.cut():(i(l,u?s+1:s),!1);return this.taint.referencesTo(t,o.getText()).some(l=>this.valueCompromises(T(l),!0,a,0))&&(t===n||!Le(t.getType()))}valueCompromises(t,s,n,i){let o=t;for(let m=kn(o);m!==void 0;m=kn(o)){if(r.isCallExpression(m)&&this.callbackCompromises(m,n))return!0;o=T(m)}const a=o.getParent(),c=o===t&&s,l=()=>!c&&Le(o.getType());if(Pe(o))return!c&&(!r.isBinaryExpression(a)||this.taint.isTaintedValue(a.getRight(),!1));const u=tg(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=T(t).getParent();if(n>=dg)return this.budget.cut();if(r.isCallExpression(i))return i.getExpression()===T(t)?this.valueCompromises(i,!1,s,n+1):!ct(i,rs);const o=r.isFunctionDeclaration(t)?t:i,a=r.isFunctionDeclaration(o)||G(o)?o.getNameNode():void 0;return o===void 0||!r.isIdentifier(a)?!0:this.taint.referencesTo(o,a.getText()).some(c=>{const l=T(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=>tt(i)===void 0).some(i=>this.taint.isTaintedValue(i,!1))||this.callbackCompromises(t,s)}callbackCompromises(t,s){const n=ct(t,rs)?t.getArguments()[0]:void 0;if(n===void 0)return!1;const i=ns(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!ss(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(ss(s,this.scope.context))return!1;const i=ns(t.getExpression()),o=i===void 0?void 0:er(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)||tr(t)||b(jt(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=jt(t);return b(s,this.scope.impl)?void 0:s}}const fg=new Set(["at","every","filter","finally","find","findIndex","findLast","findLastIndex","forEach","order","slice","some","sort","withIndex","withSearchIndex"]),gg=e=>{const t=h(e);if(!r.isIdentifier(t))return r.isPropertyAccessExpression(t)||r.isElementAccessExpression(t);const s=_(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)},pg=new Set(["all","allSettled","any","race"]),Rn=e=>r.isParameterDeclaration(e)?e:r.isBindingElement(e)?e.getFirstAncestorByKind(d.Parameter):void 0,Kt=8;class mg{budget=new cg;referencesByDeclaration=new Map;referencesByName=new Map;scope;verdicts=rr();walk;variableDepth=0;queryDepth=0;constructor(t){this.scope=t,this.walk=new ug(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,Kt)?!1:(r.isIdentifier(t)?[t]:t.getDescendantsOfKind(d.Identifier)).some(i=>Io(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=_(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=T(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)||!rs.has(g.getName()))return!0;const m=a.getArguments().filter(v=>v!==o);return this.isTaintedValue(g.getExpression(),!0)||m.some(v=>this.isTaintedValue(v,!1))}const c=r.isVariableDeclaration(a)&&G(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=T(g),v=m.getParent();return!r.isCallExpression(v)||v.getExpression()!==m||this.isCallSiteTainted(v,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"&&at(i)&&pg.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:tt(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=_(t),i=Rn(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&&di.has(i)?!1:i!==void 0&&ui.has(i)?this.isCallbackResultServerScoped(t,s)?void 0:!1:t.getArguments().some(a=>tt(a)!==void 0)&&(i===void 0||!fg.has(i))?!1:void 0}isCallbackResultServerScoped(t,s){const n=(i,o=[])=>{const a=mt(i),c=r.isIdentifier(a)?Rn(_(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=tt(i);if(o===void 0)return!gg(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=Ao(t,u=>this.callChainVerdict(u,s)),i=n.root;if(n.verdict!==void 0)return n.verdict;if(Zi(i,this.scope.context))return!0;const o=r.isIdentifier(i)?_(i):void 0,a=r.isBindingElement(o)?o.getFirstAncestorByKind(d.VariableDeclaration):o,c=G(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=hs(t);if(n===void 0||i)return!0;if(this.isRootedInContext(n,Kt))return!1;if(this.variableDepth>=Kt)return this.budget.cut();this.variableDepth+=1;try{return this.isTaintedValue(n,!1)}finally{this.variableDepth-=1}},this.verdicts)}}const Fn=new WeakMap,hg=e=>{const t=Fn.get(e.impl.compilerNode);if(t!==void 0)return t;const s=new mg(e);return Fn.set(e.impl.compilerNode,s),s},vg=new Set(["accountId","authorId","createdBy","createdById","organizationId","orgId","ownerId","tenantId","updatedBy","userId","workspaceId"]),Eg=new Set(["insert","insertMany","insertManyUnsafe","patch","replace"]),xg=new Set(["insert","insertMany","patch","patchMany","replace","upsert","upsertMany"]),Qe=(e,t)=>e===void 0||!r.isObjectLiteralExpression(e)?[]:t.flatMap(s=>{const n=B(e,s),i=r.isPropertyAssignment(n)?n.getInitializer():void 0;return i===void 0?[]:[i]}),Ln=e=>e!==void 0&&r.isArrayLiteralExpression(e)?e.getElements():[],Sg=e=>{if(!r.isPropertyAccessExpression(e))return;const t=e.getName();return Eg.has(t)&&fi(e.getExpression())?t:void 0},Ag=(e,t)=>{const[s]=t.getArguments();if(e==="upsert")return Qe(s,["create","update"]);if(e==="upsertMany")return Qe(s,["rows"]).flatMap(i=>Ln(i).flatMap(o=>Qe(o,["create","update"])));if(e==="patchMany")return(s!==void 0&&r.isArrayLiteralExpression(s)?Ln(s):[s]).flatMap(o=>Qe(o,["values"]));const n=e==="patch"||e==="replace"?t.getArguments()[1]:s;return n===void 0?[]:[n]},yg=e=>{const t=e.getExpression(),s=Sg(t);if(s!==void 0){const i=s==="patch"||s==="replace"?2:1,o=e.getArguments()[i];return o===void 0?void 0:{documentArguments:[o],method:s}}const n=St(e,xg);if(!(n===void 0||!fi(n.database)))return{documentArguments:Ag(n.method,e),method:n.method}},bg=(e,t)=>{if(t!=="insertManyUnsafe"&&t!=="insertMany")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},Ng=(e,t)=>{const s=ps(e);return s?.member===t?h(s.object):void 0},Dn=(e,t)=>r.isIdentifier(e)&&_(e)?.compilerNode===t.compilerNode,or=(e,t,s,n=1)=>{const i=Ng(e,s);if(i!==void 0)return Dn(i,t);const o=r.isIdentifier(e)?_(e):void 0;if(r.isBindingElement(o)){const c=o.getParent(),l=c.getParent();return o.getDotDotDotToken()===void 0&&fe(o)===s&&r.isObjectBindingPattern(c)&&(l.compilerNode===t.compilerNode||G(l)&&Dn(h(l.getInitializer()),t))}const a=G(o)?o.getInitializer():void 0;return n>0&&a!==void 0&&or(a,t,s,n-1)},os=e=>{const t=h(e)??e;return r.isConditionalExpression(t)?[...os(t.getWhenTrue()),...os(t.getWhenFalse())]:[t]},Pg=(e,t,s)=>{const n=[],i=s===void 0?void 0:hg(s);for(const o of e.getProperties()){let a,c;if(r.isPropertyAssignment(o)?(a=S(o),c=o.getInitializer()):r.isShorthandPropertyAssignment(o)&&(a=S(o),c=o.getNameNode()),a===void 0||c===void 0||!vg.has(a))continue;const l=os(c).filter(f=>i===void 0?q(f)&&!ko(f):i.isTaintedValue(f,!0));if(l.length>0){const f=t.ownerField===a&&s?.pristine===!0&&or(c,s.parameter,a),g=l.every(m=>Xf(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},wg=e=>{const t=new Map;for(const s of e){const n=t.get(s.field);if(n===void 0)t.set(s.field,s);else{const i={...n};s.ownerScoped!==!0&&delete i.ownerScoped,s.guarded!==!0&&delete i.guarded,t.set(s.field,i)}}return[...t.values()]},Ig=(e,t,s)=>{const n=yg(e);if(n===void 0)return[];const{method:i}=n,o=n.documentArguments.flatMap(f=>bg(f,i));if(o.length===0)return[];const a=A(e),c=Uf(e),l={call:e,method:i,ownerField:c===void 0?void 0:s(c.mutatorName),relativePath:t,scope:a},u=o.flatMap(f=>Pg(f,l,c));return i==="upsert"?wg(u):u},Tg=(e,t,s=[],n=[])=>{const i=new Map(n.map(c=>[`${c.filePath}:${c.exportName}`,c.owner])),o=O(e,t,(c,l)=>Ig(c,l,u=>i.get(`${l}:${u}`))),a=new Map(s.map(c=>[`${c.filePath}:${c.exportName}`,c.adminOnly===!0]));return Es(o,s).map(c=>To(c.scope)?.every(f=>a.get(`${c.file}:${f}`)===!0)===!0?{...c,adminOnly:!0}:c)},Cg=new Set(["createAutumnAdapter","createDodoPaymentsAdapter","createPolarAdapter","createStripeAdapter"]),Og=e=>{const t=B(e,"webhookToleranceSeconds");return t&&r.isPropertyAssignment(t)?ai(t.getInitializer()):void 0},kg=(e,t)=>{const s=C(e.getExpression());if(s===void 0||!Cg.has(s))return;const[n]=e.getArguments(),i=n&&r.isObjectLiteralExpression(n)?Og(n):void 0;return{callee:s,scope:A(e),file:t,line:e.getStartLineNumber(),...i===void 0?{}:{toleranceSeconds:i}}},Rg=(e,t)=>O(e,t,kg),Fg=new Map([["defineQueue",0],["defineSubscription",1],["defineWorkflow",0]]),Lg=e=>{const t=e.getExpression();return r.isIdentifier(t)?t.getText():void 0},Dg=(e,t)=>{const s=e.getArguments()[t];if(!(!s||!r.isObjectLiteralExpression(s)))return Ro(B(s,"handler"))},ar=(e,t)=>e.getParameters()[t]?.getNameNode(),cr=e=>{const t=new Map;for(const s of e){const n=s.getNameNode();r.isIdentifier(n)&&t.set(s.getPropertyNameNode()?.getText()??n.getText(),n.getText())}return t},lr=(e,t)=>e===t||e.startsWith(`${t}.`),dr=e=>{const t=e.getDescendantsOfKind(d.PropertyAccessExpression);return r.isPropertyAccessExpression(e)&&t.push(e),t},Mn=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)},ur=e=>{const t=e.getDescendantsOfKind(d.Identifier).filter(s=>Mn(s));return r.isIdentifier(e)&&Mn(e)&&t.push(e),t},Mg=e=>{if(!r.isVariableDeclaration(e))return[];const t=e.getNameNode();return r.isIdentifier(t)?[t.getText()]:t.getDescendantsOfKind(d.BindingElement).map(s=>s.getName())},_g=new Set(["every","filter","flatMap","forEach","map","some"]),zg=e=>{const t=ar(e,1);return t&&r.isIdentifier(t)?`${t.getText()}.messages`:t&&r.isObjectBindingPattern(t)?cr(t.getElements()).get("messages"):void 0},$g=(e,t)=>{const s=e.getExpression();if(!r.isPropertyAccessExpression(s)||!_g.has(s.getName())||s.getExpression().getText()!==t)return;const n=e.getArguments()[0];if(!n||!(r.isArrowFunction(n)||r.isFunctionExpression(n)))return;const i=n.getParameters()[0]?.getNameNode();return i&&r.isIdentifier(i)?i.getText():void 0},Kg=e=>{const t=zg(e);if(t===void 0)return[];const s=[t];for(const n of e.getDescendantsOfKind(d.ForOfStatement)){if(n.getExpression().getText()!==t)continue;const i=n.getInitializer(),o=r.isVariableDeclarationList(i)?i.getDeclarations()[0]?.getNameNode():void 0;o&&r.isIdentifier(o)&&s.push(`${o.getText()}.body`)}for(const n of e.getDescendantsOfKind(d.CallExpression)){const i=$g(n,t);i!==void 0&&s.push(`${i}.body`)}return s},Bg=e=>{const t=ar(e,0);if(t&&r.isIdentifier(t))return{params:void 0,receiver:t.getText(),runCallees:[]};if(!t||!r.isObjectBindingPattern(t))return{params:void 0,receiver:void 0,runCallees:[]};const s=cr(t.getElements());return{params:s.get("params"),receiver:void 0,runCallees:[...s].filter(([n])=>ms.has(n)).map(([,n])=>n)}},Vg=(e,t,s)=>{const n=s.receiver===void 0?[]:[`${s.receiver}.params`],i=t==="workflow"?n:Kg(e),o=new Set(t==="workflow"&&s.params!==void 0?[s.params]:[]),a=c=>dr(c).some(l=>i.some(u=>lr(l.getText(),u)))?!0:ur(c).some(l=>o.has(l.getText()));for(const c of e.getDescendantsOfKind(d.VariableDeclaration)){const l=c.getInitializer();if(l&&a(l))for(const u of Mg(c))o.add(u)}return{names:o,prefixes:i}},Ug=(e,t)=>dr(e).some(s=>t.prefixes.some(n=>lr(s.getText(),n)))?!0:ur(e).some(s=>t.names.has(s.getText())),Wg=e=>{const t=yo(e);return t===void 0?void 0:{exportName:String(t.at(-1)),file:t.slice(0,-1).join("/")}},qg=(e,t,s)=>{const n=Bg(e),i=Vg(e,t,n),o=new Set([...n.receiver===void 0?[]:[n.receiver],...i.prefixes.filter(l=>l.endsWith(".body")).map(l=>l.slice(0,-5))]),a=new Set(n.runCallees),c=[];for(const l of e.getDescendantsOfKind(d.CallExpression)){const u=l.getExpression(),f=r.isPropertyAccessExpression(u)&&ms.has(u.getName())&&o.has(u.getExpression().getText()),g=r.isIdentifier(u)&&a.has(u.getText());if(!f&&!g)continue;const m=l.getArguments()[1];if(!m||!Ug(m,i))continue;const v=Wg(l.getArguments()[0]);v!==void 0&&c.push({dispatchKind:t,file:s,scope:A(l),line:l.getStartLineNumber(),targetExport:v.exportName,targetFile:v.file})}return c},jg=(e,t)=>{const s=[];for(const n of x(e,d.CallExpression)){const i=Lg(n),o=i===void 0?void 0:Fg.get(i);if(o===void 0)continue;const a=Dg(n,o);a!==void 0&&s.push(...qg(a,i==="defineWorkflow"?"workflow":"queue",t))}return s},Hg=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...jg(i,P(t,n)))}return s},_n={dbRateLimit:"usesRateLimit",emailGateMiddleware:"usesEmailGate",mask:"usesMask",rateLimit:"usesRateLimit",rls:"usesRls",verifyTurnstileMiddleware:"usesCaptcha"},zn=new Set(["account","credential","member","passkey","session","user"]),Gg=e=>e.replaceAll(/[-_]/gu," ").replaceAll(/([a-z0-9])([A-Z])/gu,"$1 $2").split(" ").filter(Boolean).map(t=>t.toLowerCase()),fr=e=>{const s=Gg(e).at(-1);if(!s)return!1;const n=s.endsWith("s")?s.slice(0,-1):s;return zn.has(s)||zn.has(n)},Yg=e=>{const t=e.replaceAll(/[^a-z0-9]/giu,"").toLowerCase();return t.endsWith("email")||t.endsWith("emailaddress")},Qg=(e,t)=>{const{objects:s,opaque:n}=Ns(e,t);return bl(s).some(i=>Yg(i))?!0:n?void 0:!1},Xg=e=>{const t=e.getArguments()[0];return!t||!r.isObjectLiteralExpression(t)?{usesCaptcha:!1,usesRateLimit:!1}:{usesCaptcha:!!B(t,"captcha"),usesRateLimit:!!B(t,"rateLimit")}},st={usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},Jg=e=>{const t=Mo(e),s=t?C(t.getExpression()):void 0;if(t&&s==="protectPublic"){const n=Xg(t);return{...st,usesCaptcha:n.usesCaptcha,usesRateLimit:n.usesRateLimit}}return s!==void 0&&s in _n?{...st,[_n[s]]:!0}:st},Zg=e=>{const t={...st};for(const s of Do(e)){const n=s.name==="use"?s.call.getArguments()[0]:void 0;if(!n)continue;const i=Jg(n);t.usesCaptcha||=i.usesCaptcha,t.usesEmailGate||=i.usesEmailGate,t.usesMask||=i.usesMask,t.usesRateLimit||=i.usesRateLimit,t.usesRls||=i.usesRls}return t},ep=new Set(["insert","insertMany","insertManyUnsafe","replace"]),tp=new Set(["insert","insertMany","replace","upsert","upsertMany"]),sp=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!ep.has(t.getName()))return!1;const s=t.getExpression();if(!K(s))return!1;const i=e.getArguments()[0];return!i||!(r.isStringLiteral(i)||r.isNoSubstitutionTemplateLiteral(i))?!1:fr(i.getLiteralText())},np=e=>{if(sp(e))return!0;const t=St(e,tp);return t!==void 0&&fr(t.table)},ip=new Set(["create","publish","publishBatch","runAfter","runAt","send","sendBatch"]),$n=new Set(["queues","scheduler","topics","workflows"]),rp=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!ip.has(t.getName()))return!1;let s=t.getExpression();for(;r.isCallExpression(s)||r.isElementAccessExpression(s)||r.isPropertyAccessExpression(s);){if(r.isPropertyAccessExpression(s)&&$n.has(s.getName())&&Fo(s.getExpression()))return!0;s=s.getExpression()}const n=xs(s);return n?.length===1&&$n.has(n[0]??"")},op=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||t.getName()!=="insertManyUnsafe")return!1;const s=t.getExpression();return K(s)},gr=new Set(["generateObject","generateText","streamObject","streamText"]),ap=e=>{const t=C(e.getExpression());return t!==void 0&&gr.has(t)},cp=e=>{const t=C(e.getExpression());if(t===void 0||!gr.has(t))return!1;const s=e.getArguments()[0];return!s||!r.isObjectLiteralExpression(s)||s.getProperties().some(n=>r.isSpreadAssignment(n))?!1:!B(s,"maxOutputTokens")},lp=new Set(["log","span","trace"]),dp=new Set(["ai"]),up=new Set(["email","mail"]),fp=new Set(["ai","browser","fetch","mail","notify","queues","sql","storage","topics","workflows"]),Bt=(e,t)=>[...t].some(s=>ht(e,s).length>0),pr=new Set([d.ArrowFunction,d.FunctionDeclaration,d.FunctionExpression,d.GetAccessor,d.MethodDeclaration,d.SetAccessor]),gp=new Set(["every","filter","flatMap","forEach","map","some"]),pp=new Set(["all","allSettled","race"]),mr=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(gp.has(n))return t;const i=s.getExpression();if(r.isIdentifier(i)&&i.getText()==="Promise"&&pp.has(n))return t},mp=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(pr.has(t.getKind())){const s=mr(t);if(!s)return!1;t=s;continue}t=t.getParent()}return!1},hp=e=>{let t=e.getParent();for(;t!==void 0;){if(r.isCallExpression(t)&&t.getExpression().getText()==="Promise.allSettled")return!0;if(pr.has(t.getKind())){if(t=mr(t),t===void 0)return!1;continue}t=t.getParent()}return!1},vp=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 v=m.getExpression();return r.isIdentifier(v)&&v.getText()===l&&r.isAwaitExpression(m.getParent())}),g=u.getCatchClause();return f&&g!==void 0&&g.getDescendantsOfKind(d.ThrowStatement).length>0})},Ep=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}},xp=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}},Sp=e=>{let t=!1,s=!0;for(const n of[...fp].flatMap(i=>ht(e,i))){const i=xp(n);i&&(t=!0,!mp(i)&&!Ep(i)&&!vp(i)&&!hp(i)&&(s=!1))}return{handlesErrors:t&&s,reachesOutbound:t}},Ap=e=>x(e,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"}),Kn="lunora-advisor-exempt",yp=/^[\s*/]+/u,bp=/[\w-]/u,Np=e=>{const s=(e.getFirstAncestorByKind(d.VariableStatement)??e).getLeadingCommentRanges().map(n=>n.getText()).join(`
22
- `);for(const n of s.split(`
23
- `)){const i=n.replace(yp,"");if(!i.startsWith(Kn))continue;const o=i.slice(Kn.length);if(bp.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:""}},Pp=e=>{const[t]=e.getArguments();if(t){if(r.isObjectLiteralExpression(t)){const s=B(t,"handler");return s?r.isPropertyAssignment(s)?s.getInitializer():r.isShorthandPropertyAssignment(s)?s.getNameNode():r.isMethodDeclaration(s)?s:void 0:void 0}return t}},wp=(e,t)=>{const s=Pp(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)},Ip=e=>{let t=!1,s=!1,n=!1,i=!1,o=!1;for(const l of x(e,d.CallExpression))if(np(l)&&(o=!0),rp(l)&&(t=!0),op(l)&&(i=!0),ap(l)&&(s=!0),cp(l)&&(n=!0),o&&t&&i&&n)break;const{handlesErrors:a,reachesOutbound:c}=Sp(e);return{callsMail:Bt(e,up),emitsEvent:Bt(e,lp),fanOut:t,handlesErrors:a,reachesOutbound:c,runsAiGeneration:s||Bt(e,dp),throwsBareError:Ap(e),unboundedAiGeneration:n,usesInsertManyUnsafe:i,writesUserTable:o}},Tp=(e,t)=>{const s=e.getInitializer();if(!s||!r.isCallExpression(s))return;const n=ae(s);if(!n||n.kind!=="query"&&n.kind!=="mutation"&&n.kind!=="action")return;const i=n.receiver?Zg(n.receiver):{usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},o=wp(e,s);return{...o?Ip(o):{},...Np(e),...i,analyzableBody:o!==void 0,exportName:Q(e)??e.getName(),file:t,hasEmailArg:Qg(s,n.receiver),kind:n.kind,visibility:n.visibility}},Cp=(e,t)=>{const s=[];for(const n of Z(e)){const i=Tp(n,t);i&&s.push(i)}return s},Op=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Cp(i,P(t,n)))}return s},kp=new Set(["dbRateLimit","rateLimit"]),Rp=e=>r.isArrowFunction(e)?e.getBody():e,Fp=e=>{if(!r.isArrowFunction(e))return;const t=e.getParameters()[0]?.getNameNode();return t!==void 0&&r.isIdentifier(t)?t:void 0},hr=e=>{const t=e.getParent();return r.isPropertyAccessExpression(t)&&t.getExpression()===e&&t.getName()==="args"},vr=(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)})},Lp=(e,t)=>q(e)||t!==void 0&&vr(e,t).some(s=>hr(s)),Dp=(e,t)=>t===void 0?xe(e):vr(e,t).some(s=>!hr(s)),Mp=(e,t)=>{const s=C(e.getExpression());if(s===void 0||!kp.has(s))return;const n=M(oi(e.getArguments()[2]),"key");if(!n)return;const i=Rp(n),o=Fp(n);if(!(!Lp(i,o)||Dp(i,o)))return{callee:s,scope:A(e),file:t,limitName:ri(e),line:e.getStartLineNumber()}},_p=(e,t)=>O(e,t,Mp),zp=new Set(["findFirst","findFirstOrThrow","findMany","findUnique","get"]),$p=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!zp.has(t.getName()))return;const s=t.getExpression();if(K(s)){const n=e.getArguments()[0];return n&&r.isStringLiteral(n)?n.getLiteralText():""}if(r.isPropertyAccessExpression(s)&&K(s.getExpression()))return s.getName()},Kp=e=>{let t=e;for(;r.isCallExpression(t);){const s=t.getExpression();if(!r.isPropertyAccessExpression(s))return;if(s.getName()==="query"&&K(s.getExpression())){const n=t.getArguments()[0];return n&&r.isStringLiteral(n)?n.getLiteralText():""}t=s.getExpression()}},Bp=e=>{let t=h(e)??e;for(;r.isAwaitExpression(t);)t=h(t.getExpression())??t.getExpression();return t},Er=(e,t=!1)=>{const s=Bp(e);if(r.isIdentifier(s)){if(t)return;const n=Me(s),i=n?.getInitializer();return i===void 0||!r.isIdentifier(n?.getNameNode())?void 0:Er(i,!0)}if(r.isCallExpression(s))return $p(s)??Kp(s)},Vp=e=>{const t=e.getBody();if(!r.isBlock(t))return[t];const s=[];for(const n of x(e,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},Up=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!r.isCallExpression(s))return[];const n=ae(s);if(n?.kind!=="query")return[];const i=Ei(s);if(i===void 0)return[];const o=n.receiver!==void 0&&_o(n.receiver,"output"),a=n.receiver!==void 0&&mi(n.receiver,"use","mask"),c=new Set,l=[];for(const u of Vp(i)){const f=Er(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},Wp=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=P(t,n);for(const a of Z(i))s.push(...Up(a,o))}return s},qp=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(S(s));return t},jp=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&r.isCallExpression(s)?ae(s):void 0;if(!n)return[];const i=[];for(const o of x(e,d.CallExpression)){const a=vi(o);if(a===void 0)continue;const c=qp(M(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},Hp=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=P(t,n);for(const a of Z(i))s.push(...jp(a,o))}return s},H=(e,t)=>`${e}:${t}`,Bn=(e,t,s,n)=>s===void 0?void 0:{endLine:e.getEndLineNumber(),exported:n,file:t,name:s,node:e,startLine:e.getStartLineNumber()},Gp=(e,t)=>[...oe(e,t,d.FunctionDeclaration,(s,n)=>s.getParent().getKind()===d.SourceFile?Bn(s,n,s.getName(),s.isExported()):void 0),...oe(e,t,d.VariableDeclaration,(s,n)=>{const i=s.getVariableStatement();return i?.getParent().getKind()===d.SourceFile?Bn(i,n,s.getName(),i.isExported()):void 0})],Yp=(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(H(c,a))},Qp=e=>`${e.table}|${e.method}|${e.fields?.join(",")??"*"}`,Xp=(e,t)=>{const s=new Map(e.map(n=>[H(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(H(i.file,i.name))?.set(Qp(n),{fields:n.fields,method:n.method,table:n.table})}return s},Jp=(e,t,s)=>x(e.node,d.CallExpression).map(n=>Yp(n,t,s)).filter(n=>n!==void 0),Zp=(e,t,s,n)=>{for(const i of e){const o=i.scope.kind==="module"?void 0:t.get(H(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(H(o.file,o.name))?.push(a)}},em=(e,t,s)=>{const n=new Map(e.map(a=>[H(a.file,a.name),a])),i=new Map(e.map(a=>[`${ys(a.file)}:${a.name}`,a])),o=new Map(e.map(a=>[H(a.file,a.name),Jp(a,n,t)]));return Zp(s,n,i,o),o},tm=(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},sm=(e,t,s)=>{let n=!0;for(;n;){n=!1;for(const i of e)for(const o of s.get(H(i.file,i.name))??[])tm(t.get(H(i.file,i.name)),t.get(H(o.file,o.name)))&&(n=!0)}},nm=(e,t,s,n)=>{const i=Gp(e,t),o=Xp(i,s);return sm(i,o,em(i,t,n)),i.filter(a=>a.exported).flatMap(a=>[...o.get(H(a.file,a.name))?.values()??[]].map(c=>({...c,exportName:a.name,file:a.file})))},lt=e=>{if(r.isStringLiteral(e)||r.isNoSubstitutionTemplateLiteral(e))return e.getLiteralText();if(r.isBinaryExpression(e)&&e.getOperatorToken().getKind()===d.PlusToken){const t=lt(e.getLeft()),s=lt(e.getRight());return t!==void 0&&s!==void 0?t+s:void 0}},im=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&&lt(t)!==void 0},rm=e=>{const t=e.getParent();if(t!==void 0){if(r.isVariableDeclaration(t)||r.isPropertyAssignment(t)||r.isPropertySignature(t))return S(t);if(r.isBinaryExpression(t)&&t.getOperatorToken().getKind()===d.EqualsToken)return t.getLeft().getText()}},om=(e,t,s)=>la(e)?!bo(s)&&da(rm(t)):!0,am=(e,t)=>{const s=[],n=[...x(e,d.BinaryExpression),...x(e,d.StringLiteral),...x(e,d.NoSubstitutionTemplateLiteral)],i=new Set;for(const o of n){if(im(o))continue;const a=lt(o);if(a===void 0)continue;const c=aa(a);if(c===void 0||!om(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:ca(a)}))}return s},cm=(e,t)=>{const s=[],n=new gs({compilerOptions:{allowJs:!0},skipFileDependencyResolution:!0,skipLoadingLibFiles:!0,useInMemoryFileSystem:!0});for(const i of y(t,{includeSkipped:!0})){const o=e.getSourceFile(i)??n.createSourceFile(i,ft(i,"utf8"),{overwrite:!0});s.push(...am(o,P(t,i)))}return s},lm=e=>{const t=M(e,"includeDeleted");if(t!==void 0||!r.isObjectLiteralExpression(e))return t;const s=B(e,"includeDeleted");return r.isShorthandPropertyAssignment(s)?s.getNameNode():void 0},dm=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&r.isCallExpression(s)?ae(s):void 0;if(!n)return[];const i=[];for(const o of x(e,d.CallExpression)){const a=vi(o);if(a===void 0)continue;const c=lm(a.options);if(c===void 0)continue;const l=r.isTrueLiteral(c),u=!l&&q(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},um=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=P(t,n);for(const a of Z(i))s.push(...dm(a,o))}return s},fm=new Set(["query","unsafe"]),xr=3,gm=e=>!r.isPropertyAccessExpression(e)||!fm.has(e.getName())?!1:Y(e.getExpression(),["sql"]),as=e=>{if(!r.isIdentifier(e))return;const t=e.getSymbol()?.getDeclarations()[0];if(!(!G(t)||!r.isIdentifier(t.getNameNode())))return t.getInitializer()},pm=e=>{const t=as(e);if(t!==void 0||!r.isIdentifier(e))return t;const s=e.getSymbol()?.getDeclarations()[0],n=r.isBindingElement(s)?s.getParent().getParent():void 0;if(!r.isBindingElement(s)||!G(n))return;const i=n.getInitializer(),o=h(i),a=h(o!==void 0&&r.isIdentifier(o)?as(o):o),c=u=>r.isSpreadAssignment(u)||r.isPropertyAssignment(u)&&r.isComputedPropertyName(u.getNameNode()),l=r.isObjectLiteralExpression(a)&&!a.getProperties().some(u=>c(u))?a.getProperty(fe(s)):void 0;return r.isShorthandPropertyAssignment(l)?l.getNameNode():r.isPropertyAssignment(l)?l.getInitializer():i},mm=e=>{const t=h(e);if(!t)return!1;if(r.isTemplateExpression(t))return!0;if(r.isBinaryExpression(t))return t.getOperatorToken().getKind()===d.PlusToken;if(!r.isCallExpression(t))return!1;const s=t.getExpression();return r.isPropertyAccessExpression(s)&&["concat","join"].includes(s.getName())},hm=(e,t)=>{const s=e.getExpression();if(!r.isPropertyAccessExpression(s))return!1;const n=e.getArguments().every(o=>t(o));if(s.getName()==="concat")return n&&t(s.getExpression());const i=h(s.getExpression());return s.getName()==="join"&&n&&r.isArrayLiteralExpression(i)&&i.getElements().every(o=>t(o))},Se=(e,t=xr)=>{const s=h(e);return s?r.isStringLiteral(s)||r.isNoSubstitutionTemplateLiteral(s)||r.isNumericLiteral(s)?!0:r.isTemplateExpression(s)?s.getTemplateSpans().every(n=>Se(n.getExpression(),t)):r.isBinaryExpression(s)?s.getOperatorToken().getKind()===d.PlusToken&&Se(s.getLeft(),t)&&Se(s.getRight(),t):r.isIdentifier(s)?t>0&&Se(as(s),t-1):r.isCallExpression(s)?hm(s,n=>Se(n,t)):!1:!1},vm=e=>{const t=h(e);if(!t||Se(t))return!1;let s=t;for(let n=0;s!==void 0&&n<=xr;n+=1){if(mm(s)||q(s))return!0;const i=pm(s);s=i===void 0?void 0:h(i)}return!1},Em=(e,t)=>{if(!gm(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!vm(s)))return{file:t,line:s.getStartLineNumber(),scope:A(e)}},xm=(e,t)=>O(e,t,Em),Sm=[["convex",["convex","@convex-dev/"]],["supabase",["@supabase/"]],["firebase",["firebase","@firebase/","firebase-admin"]]],Am=e=>{for(const[t,s]of Sm)for(const n of s)if(e===n||e.startsWith(n.endsWith("/")?n:`${n}/`))return t},ym=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const o of i.getImportDeclarations()){const a=o.getModuleSpecifierValue(),c=Am(a);c!==void 0&&s.push({file:P(t,n),line:o.getStartLineNumber(),moduleSpecifier:a,platform:c})}}return s},bm=new Set(["createMultipartUpload","delete","download","generateUploadUrl","get","getMetadata","getPresignedUrl","getSignedUrl","getUrl","head","put","resumeMultipartUpload","store","upload"]),Nm=(e,t,s=[])=>{const n=Et(e,t,{argIndex:0,matchReceiver:i=>i==="ctx.storage"||i.startsWith("ctx.storage."),methods:bm,requireUnmodifiedReach:!0});return Es(n,s)},Pm=new Map([["generateUploadUrl",1],["getPresignedUrl",1],["getSignedUrl",1],["store",2],["upload",2]]),wm=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=S(i);t.push(o),o==="expiresInSeconds"&&(s=ai(i.getInitializer()));continue}(r.isShorthandPropertyAssignment(i)||r.isMethodDeclaration(i))&&t.push(S(i))}return{analyzable:!n,expiresInSeconds:s,presentKeys:t}},Im=e=>{if(!r.isPropertyAccessExpression(e))return;const t=e.getName(),s=Pm.get(t);return s===void 0?void 0:li(e.getExpression(),i=>i==="ctx.storage"||i.startsWith("ctx.storage."))?{method:t,optionsIndex:s}:void 0},Tm=(e,t)=>{const s=Im(e.getExpression());if(s!==void 0)return{scope:A(e),file:t,line:e.getStartLineNumber(),method:s.method,...wm(e.getArguments()[s.optionsIndex])}},Cm=(e,t)=>O(e,t,Tm),Om=e=>r.isDoStatement(e)||r.isForInStatement(e)||r.isForOfStatement(e)||r.isForStatement(e)||r.isWhileStatement(e),Sr=e=>{const t=e.getLabel()?.getText(),s=i=>t!==void 0?r.isLabeledStatement(i)&&i.getLabel().getText()===t:Om(i)||r.isBreakStatement(e)&&r.isSwitchStatement(i);let n=e.getFirstAncestor(i=>ge(i)||s(i));if(!(n===void 0||ge(n))){for(;r.isContinueStatement(e)&&r.isLabeledStatement(n);)n=n.getStatement();return n}},Cs=(e,t)=>b(e.getFirstAncestor(s=>b(s,t)||ge(s)),t),km=(e,t)=>b(e,t)||e.getFirstAncestor(s=>b(s,t))!==void 0,Ar=(e,t)=>{if(r.isReturnStatement(e)||r.isThrowStatement(e))return b(e,t)||Cs(e,t);if(r.isBreakStatement(e)||r.isContinueStatement(e)){const s=Sr(e);return s!==void 0&&!km(s,t)}return!1},yr=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)],Rm=e=>yr(e).some(t=>Ar(t,e)),Fm=e=>{const t=r.isCallExpression(e)?e.getExpression():void 0;return r.isPropertyAccessExpression(t)&&t.getName()==="throwIfAborted"},Lm=e=>yr(e).some(t=>Ar(t,e)||r.isBreakStatement(t)&&b(Sr(t),e))||e.getDescendantsOfKind(d.CallExpression).some(t=>Fm(t)&&Cs(t,e)),Dm=e=>e.getDescendantsOfKind(d.YieldExpression).some(t=>Cs(t,e)),Mm=e=>r.isDoStatement(e)||r.isWhileStatement(e)?e.getExpression():e.getCondition(),_m=e=>r.isDoStatement(e)?"do":r.isWhileStatement(e)?"while":"for",Vt=(e,t)=>{const s=Mm(e);if(!(s===void 0||r.isTrueLiteral(h(s)))||Lm(e)||Dm(e))return;const i=A(e);if(!(i.kind==="module"&&e.getFirstAncestor(ge)!==void 0))return{file:t,kind:_m(e),line:e.getStartLineNumber(),scope:i}},zm=(e,t)=>[...oe(e,t,d.WhileStatement,Vt),...oe(e,t,d.ForStatement,Vt),...oe(e,t,d.DoStatement,Vt)].toSorted((s,n)=>s.file.localeCompare(n.file)||s.line-n.line),$m=new Set(["when","where"]),Ut=new Set(["definePolicy","defineShape"]),Km=e=>{if(!r.isCallExpression(e))return;const t=e.getExpression();if(r.isPropertyAccessExpression(t)){const n=t.getName();return Ut.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 Ut.has(i)?i:void 0}const s=t.getText();return Ut.has(s)?s:void 0},Bm=e=>r.isObjectLiteralExpression(e)&&e.getProperties().length===0,br=e=>{if(e!==void 0){if(r.isReturnStatement(e)&&e.getExpression()===void 0||e.getKind()===d.UndefinedKeyword||e.getText()==="undefined")return"undefined";if(Bm(e))return"empty-object";if(r.isParenthesizedExpression(e))return br(e.getExpression())}},Os=e=>e.getAncestors().find(t=>r.isArrowFunction(t)||r.isFunctionExpression(t)||r.isFunctionDeclaration(t)),Vm=e=>e.getDescendantsOfKind(d.ReturnStatement).filter(t=>Os(t)===e),Nr=e=>e.getDescendantsOfKind(d.ConditionalExpression).filter(t=>Os(t)===e),Um=e=>{const t=Vm(e);return t.length>1?!0:t.some(s=>s.getFirstAncestorByKind(d.IfStatement)!==void 0)||Nr(e).length>0},Wm=e=>e.getDescendantsOfKind(d.IfStatement).filter(t=>Os(t)===e),cs=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()==="",qm=(e,t)=>cs(e)||cs(t),jm=new Map([[d.EqualsEqualsEqualsToken,"positive"],[d.EqualsEqualsToken,"positive"],[d.ExclamationEqualsEqualsToken,"negative"],[d.ExclamationEqualsToken,"negative"]]),Vn=e=>!cs(e)&&(r.isLiteralExpression(e)||e.getKind()===d.TrueKeyword),Hm=(e,t,s)=>{const n=jm.get(e);if(n!==void 0)return qm(t,s)?n==="positive"?"negative":"positive":Vn(t)||Vn(s)?void 0:n},De=e=>{if(r.isParenthesizedExpression(e))return De(e.getExpression());if(r.isPrefixUnaryExpression(e)&&e.getOperatorToken()===d.ExclamationToken)return"negative";if(r.isBinaryExpression(e)){const t=e.getOperatorToken().getKind(),s=Hm(t,e.getLeft(),e.getRight());if(s!==void 0)return s;if(t===d.AmpersandAmpersandToken||t===d.BarBarToken){const n=De(e.getLeft()),i=De(e.getRight());return n===i?n:"indeterminate"}}return r.isIdentifier(e)||r.isPropertyAccessExpression(e)||r.isElementAccessExpression(e)||r.isCallExpression(e)?"positive":"indeterminate"},Un=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}}},Gm=e=>{if(e.getElseStatement()!==void 0)return;const t=e.getNextSiblingIfKind(d.ReturnStatement);return t!==void 0&&t.getNextSibling()===void 0?t:void 0},Ym=e=>r.isReturnStatement(e)?e.getExpression()??e:e,Qm=e=>{const t=[];for(const s of Nr(e)){const n=De(s.getCondition());n==="positive"?t.push(s.getWhenFalse()):n==="negative"&&t.push(s.getWhenTrue())}for(const s of Wm(e)){const n=De(s.getExpression());if(n==="indeterminate")continue;const i=n==="negative"?Un(s.getThenStatement()):Un(s.getElseStatement())??Gm(s);i!==void 0&&t.push(Ym(i))}return t},Xm=e=>{for(const t of e.getAncestors())if(r.isVariableDeclaration(t)){const s=t.getNameNode();if(r.isIdentifier(s))return s.getText()}return"<anonymous>"},Jm=(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)||!$m.has(S(o)))continue;const a=o.getInitializer();if(!(!a||!(r.isArrowFunction(a)||r.isFunctionExpression(a)))&&Um(a))for(const c of Qm(a)){const l=br(c);l!==void 0&&i.push({exportName:Xm(e),file:s,form:l,key:S(o),line:c.getStartLineNumber(),owner:t})}}return i},Zm=(e,t)=>{const s=[];for(const n of x(e,d.CallExpression)){const i=Km(n);i!==void 0&&s.push(...Jm(n,i,t))}return s},eh=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Zm(i,P(t,n)))}return s},th=new Set(["query","upsert","upsertMany","upsertNow"]),ye=new Set,sh=e=>{if(!r.isPropertyAccessExpression(e))return;const t=e.getName();if(th.has(t))return Y(e.getExpression(),["vectors"])?t:void 0},ks=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},Pr=e=>{const t=e.getParent();return r.isShorthandPropertyAssignment(t)&&t.getNameNode()===e?t.getValueSymbol():e.getSymbol()},wr=e=>Pr(e)?.getDeclarations()[0],nh=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},Ir=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},Wn=(e,t,s)=>{const n=Pr(e)?.compilerSymbol;if(n!==void 0&&t.has(n))return!0;if(s>0){const i=Ir(wr(e)),o=i!==void 0&&r.isVariableDeclaration(i)?i.getInitializer():void 0;if(o!==void 0)return Rs(o,t,s-1)}return q(e)},Rs=(e,t,s)=>{const n=ks(e);return xe(n)?!1:r.isIdentifier(n)?Wn(n,t,s):q(n)?!0:n.getDescendantsOfKind(d.Identifier).some(i=>nh(i)&&Wn(i,t,s))},Tr=e=>{const t=Ir(wr(e));return t!==void 0&&r.isVariableDeclaration(t)?t.getInitializer():void 0},ie=(e,t)=>{const s=ks(e);if(r.isObjectLiteralExpression(s))return[s];if(r.isConditionalExpression(s))return[...ie(s.getWhenTrue(),t),...ie(s.getWhenFalse(),t)];if(r.isBinaryExpression(s)){const n=s.getOperatorToken().getKind();if(n===d.BarBarToken||n===d.QuestionQuestionToken||n===d.AmpersandAmpersandToken)return[...ie(s.getLeft(),t),...ie(s.getRight(),t)]}if(r.isIdentifier(s)&&t){const n=Tr(s);return n===void 0?[]:ie(n,!1)}return[]},ih=(e,t)=>{const s=ie(e,t);if(s.length===0)return{replaces:!0,sources:[e]};const n=s.map(o=>dt(o,!1)),i=n.flat();if(i.length!==0)return{replaces:n.every(o=>o.length>0),sources:i}},rh=e=>(r.isPropertyAssignment(e)||r.isShorthandPropertyAssignment(e))&&e.getName()==="namespace",oh=e=>r.isShorthandPropertyAssignment(e)?e.getNameNode():e.getInitializer()??e.getNameNode(),dt=(e,t)=>{let s=[];for(const n of e.getProperties())if(r.isSpreadAssignment(n)){const i=ih(n.getExpression(),t);i!==void 0&&(s=i.replaces?i.sources:[...s,...i.sources])}else rh(n)&&(s=[oh(n)]);return s},ah=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]},ch=e=>{if(!e||!(r.isArrowFunction(e)||r.isFunctionExpression(e)))return ye;const t=e.getParameters()[0]?.getNameNode();if(t===void 0)return ye;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??[]:[]))},ls=(e,t=!0,s=ye)=>{const n=ks(e);if(r.isIdentifier(n)){const o=t?Tr(n):void 0;return o===void 0?[{node:n,parameters:s}]:ls(o,!1,s)}if(r.isArrayLiteralExpression(n))return n.getElements().flatMap(o=>r.isSpreadElement(o)?ls(o.getExpression(),t,s):ie(o,!0).flatMap(a=>dt(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=Rs(i.getExpression(),ye,1)?ch(o):ye;return ah(o).flatMap(c=>ie(c,!0).flatMap(l=>dt(l,!0).map(u=>({node:u,parameters:a}))))}return[{node:n,parameters:s}]},lh=(e,t)=>{const s=sh(e.getExpression());if(s===void 0)return;const n=e.getArguments()[1];if(!(!n||!(s==="upsertMany"?ls(n):ie(n,!0).flatMap(o=>dt(o,!0).map(a=>({node:a,parameters:ye})))).some(({node:o,parameters:a})=>Rs(o,a,1))))return{scope:A(e),file:t,line:e.getStartLineNumber(),method:s}},dh=(e,t)=>O(e,t,lh),uh=(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:v}=s;return vo({adminRoutes:Yc(e,t),aiRawRuns:ol(e,t),aiToolSideEffects:vl(e,t),argumentDerivedFetches:Sl(e,t),argumentValidators:zl(e,t),authApiCalls:Ko(e,t),authConfigs:Gl(e,t),browserUrlAccesses:Jl(e,t),callEdges:n.callEdges,configCalls:od(e,t),containerKeyAccesses:cd(e,t),containerOverrides:pd(e,t),containers:i,countReads:xd(e,t,f.tables),crons:o,cronTargets:o.flatMap(k=>k.functionPath===void 0?[]:[k.functionPath]),exportSinks:bd(e,t),staleMigrationImports:ym(e,t),failOpenGuards:Td(e,t),flagReads:Fd(e,t),flagSecurityDefaults:_d(e,t),geoIndexUsages:Kd(e,t),httpActionGuards:Jd(e,t),httpHeaderWrites:cu(e,t),hyperdriveCalls:Uo(e,t),identityClaimReads:Hu(e,t),imageDeliveryUrlAccesses:Yu(e,t),inserts:n.inserts,kvKeyAccesses:Xu(e,t,a),mailRecipientAccesses:sf(e,t),maskProcedures:Qo(e,t),maskStrategies:of(e,t),mutatorWrites:pf(e,t),nondeterministicCalls:ta(e,t),normalizeIdAuthorizations:Cf(e,t),notifyCalls:na(e,t),notifyConfig:sa(e,t),mutators:l,ownerFieldWrites:Tg(e,t,a,l),unrestrictedWhereBranches:eh(e,t),paymentWebhooks:Rg(e,t),privilegedDispatches:Hg(e,t),procedureProtections:Op(e,t),queries:n.queries,queues:u,r2sqlCalls:ia(e,t),ratelimitKeySelectors:_p(e,t),rawRowReturns:Wp(e,t),relationLoads:Hp(e,t),rlsProcedures:ra(e,t),schema:f,secretLiterals:cm(e,t),modules:c,shapes:g,softDeleteReads:um(e,t),sqlInterpolations:xm(e,t),storageKeyAccesses:Nm(e,t,a),storageUploads:Cm(e,t),tableWrites:n.tableWrites,rowEffects:nm(e,t,n.tableWrites,n.callEdges),unboundedLoops:zm(e,t),vectorNamespaceAccesses:dh(e,t),workflowCalls:n.workflowCalls,workflows:v,wranglerVariables:m})},fh=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"}),gh=(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=>fh(i))]},ph=()=>({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"}),mh=e=>e.metadata.accepted!==void 0||e.name==="advisor_accept_unused"||e.name==="advisor_accept_invalid",qn={error:"ERROR",info:"INFO",warn:"WARN"},jn={ERROR:2,INFO:0,WARN:1},hh=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"}),vh=(e,t)=>{const{advisor:s}=Ai(e);if(s===void 0||s.minSeverity===void 0&&s.unreadable!==!0)return[...t];const{minSeverity:n}=s,i=n!==void 0&&Object.hasOwn(qn,n)?qn[n]:void 0;return i===void 0?[...t,hh(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=>mh(o)||jn[o.level]>=jn[i])},Eh=(e,t)=>{const{advisor:s}=Ai(e),n=gh(t,s?.accept??[]);return vh(e,s?.acceptUnreadable===!0?[...n,ph()]:n)},xh={call:"function",enqueue:"queue",invoke:"service",publish:"topic",schedule:"function"},Sh="crons",Ah=Ea.replace(/\.ts$/u,""),Ae=(e,t)=>`${ys(e)}:${t}`,Wt=(e,t,s)=>t===""?{reason:`the ${s} is not a string literal`}:{to:`${e}:${t}`},yh=e=>[...e.callEdges.map(t=>{const s=t.target===void 0?{reason:t.reason??"unreadable target"}:{to:`${xh[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,...Wt("table",t.table,"table name")})),...[...e.inserts,...e.tableWrites].map(t=>({file:t.file,kind:"write",line:t.line,scope:t.scope,...Wt("table",t.table,"written table")})),...e.workflowCalls.map(t=>({file:t.file,kind:"start",line:t.line,scope:t.scope,...Wt("workflow",t.workflow,"workflow name")}))],bh=e=>e.untracked===!0?"inside a helper only code outside any export calls":"inside a non-exported helper",Nh=e=>{const{scope:t}=e;switch(t.kind){case"export":return[{...e,exportName:t.name}];case"helper":return t.callers.length===0?[{...e,unattributed:bh(t)}]:t.callers.map(s=>({...e,exportName:s}));default:return[{...e,unattributed:"at module scope"}]}},Ph=e=>yh(e).flatMap(t=>Nh(t)),wh=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:Sh,from:`cron:${t.name}`,kind:"trigger",line:0,...i===void 0?{reason:"the cron has no target"}:{to:i}}})],Ih=e=>new Map(e.flatMap(t=>t.tables.map(s=>[s,t.name]))),ke=(e,t)=>t===void 0?e:{...e,module:t},Th=e=>{const t=new Map,s=new Map,n=Ih(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(Ae(c.file,c.exportName),l)};for(const c of e.functions){const l=Ae(c.filePath,c.exportName),u=[...oa(c.filePath),c.exportName].join(".");o(ke({detail:c.kind,id:`function:${l}`,kind:"function",name:u},Ge(e.modules,c.filePath)),l)}for(const c of e.httpRoutes){const l=Ae(c.filePath,c.exportName);o(ke({id:`http:${l}`,kind:"http",name:`${c.method} ${c.path}`},Ge(e.modules,c.filePath)),l)}for(const c of e.schema.tables)o(ke({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(ke({...l,id:`queue:${c.exportName}`,kind:"queue",name:c.exportName},Ge(e.modules,c.filePath)),Ae(c.filePath,c.exportName)),a(c.handlerSite,`queue:${c.exportName}`)}for(const c of e.topics)o(ke({id:`topic:${c.exportName}`,kind:"topic",name:c.exportName},Ge(e.modules,c.filePath)));for(const c of e.workflows)o({id:`workflow:${c.exportName}`,kind:"workflow",name:c.exportName},Ae(Ah,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}},Ch=e=>e==="default"?"the default export is not a registered function":`"${e}" is not a registered function`,Oh=(e,t)=>"from"in e?[e.from]:"unattributed"in e?{reason:e.unattributed}:t.get(Ae(e.file,e.exportName))??{reason:Ch(e.exportName)},kh=(e,t,s)=>{if("reason"in e)return{reason:e.reason};const n=Oh(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`}},qt=e=>`${e.from}|${e.kind}|${e.to}`,Rh=e=>`${e.file}|${String(e.line)}|${e.kind}|${e.reason}`,Fh=e=>{const{nodes:t,sites:s}=Th(e),n=new Map,i=new Map;for(const o of[...wh(e),...Ph(e)]){const a=kh(o,s,t);if("drawn"in a)for(const c of a.drawn)n.set(qt(c),c);else{const c={file:o.file,kind:o.kind,line:o.line,reason:a.reason};i.set(Rh(c),c)}}return{edges:[...n.values()].toSorted((o,a)=>qt(o).localeCompare(qt(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}},Lh=e=>`${yi}export const architecture = ${Sa(e,"Record<string, unknown>")};
24
- `,Hn=(e,t="api")=>{const s=new Map;for(const n of e){const i=ys(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 F("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})}}},Dh=(e,t={})=>{const{hasVectors:s=!0,scheduler:n=!1,storage:i=!1,usage:o}=t,a=[];e.tables.some(c=>bi(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=>Ni(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?[]:ka)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)},Mh=(e,t,s={})=>{if(t===void 0)return;const n=Dh(e,s).filter(o=>!t.has(o.name));if(n.length===0)return;const i=n.map(o=>` - ${o.name} — ${o.reason}`).join(`
25
- `);throw new F("INTERNAL",`@lunora/codegen: this schema's generated code imports packages the project does not declare:
26
- ${i}
27
-
28
- Install them with your package manager, then re-run codegen.`)},_h=(e,t)=>{const s=Ho();for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);if(Go(i,s))return!0}return!1},zh="createWorker",$h="extend",Gn=e=>e!==void 0&&(r.isStringLiteral(e)||r.isNoSubstitutionTemplateLiteral(e))?e.getLiteralValue():void 0,Yn=e=>{const t=[],s=Gn(M(e,"backupCron"));s!==void 0&&t.push(s);const n=M(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=Gn(i.getNameNode());o!==void 0&&t.push(o)}return t},Kh=e=>{const t=C(e.getExpression()),[s]=e.getArguments();if(s===void 0)return[];if(t===zh)return r.isObjectLiteralExpression(s)?Yn(s):[];if(t!==$h||!(r.isArrowFunction(s)||r.isFunctionExpression(s)))return[];const n=ii(s.getBody());return n===void 0?[]:Yn(n)},Bh=(e,t)=>{const s=[];for(const{filePath:n}of Be(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const o of x(i,d.CallExpression))s.push(...Kh(o))}return[...new Set(s)]},Cr=e=>{if(e.kind==="id")return e.tableName;if(!(e.kind!=="array"&&e.kind!=="optional"))return e.inner===void 0?void 0:Cr(e.inner)},Vh=e=>{const t=new Set(e.tables.map(s=>s.name));return e.tables.some(s=>Object.values(s.shape).some(n=>{const i=Cr(n);return i!==void 0&&t.has(i)}))},Uh=(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 F("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 F("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})}},Wh=e=>{const{lunoraDirectory:t,project:s,projectRoot:n,schema:i}=e,o=Ku(s,t),a=Hi(s,t),c=a.claims;for(const D of a.diagnostics)console.warn(`@lunora/codegen: ${D}.`);const l=Ma(s,t),u=xa(s,t),{queues:f,topics:g}=_a(s,t),m=$a(n),v=Fa(s,t);Uh(u,v);const k=La(s,t),X=Ka(s,t),w=Da(s,t,u,v),ce=Bh(s,t),I=Pu(s,t,xi(n)),N=za(s,t),ee=_h(s,t),te=Yo(s,t);te.browser=te.browser||N.usesSandboxBrowser;const se=Xe(n,e.target),L=Ba(te,se,{agents:v.length>0,commitOrderedTables:i.tables.some(D=>D.commitOrdered===!0),cronTriggers:w.length>0,crossShardFanout:i.tables.some(D=>Ya(D)),containerEgressPolicy:I.containerEgressPolicy,containerRuntimeScheduling:k.some(D=>D.schedulingPolicy==="durable_object"),containerSandboxTools:k.some(D=>D.sandbox===!0),deliveryAuthorization:I.deliveryAuthorization,durableStreams:I.durableStreams,globalTables:i.tables.some(D=>D.shardMode==="global"),liveContext:I.liveContext,liveStreams:I.liveStreams,typedWebSockets:I.typedWebSockets,queues:f.length>0,relationGraph:Vh(i),secretValues:ee,secrets:I.secrets,services:m.length>0,topics:g.length>0,vectorStore:i.vectorIndexes.length>0,workerLoaders:N.usesSandboxLoader,workflowRollback:I.workflowRollback,workflowSchedules:u.some(D=>D.schedules!==void 0)}),R=L.usage,ne=Ra(R),le=L.signals.vectorStore!==!1,de=L.signals.services===!1?[]:m,z=Pi(n),J=z??new Set,V=J.has("lunorash");Mh(i,z,{hasVectors:le,scheduler:R.scheduler||w.length>0,storage:R.storage||X.rules.length>0||Object.keys(wi(i)).length>0,usage:R});const U=$(E(t,"flags.ts")),W=$(E(t,"notify.ts"));return{agents:v,capabilities:ne,containers:k,crons:w,dataModelContent:Za(i),declaredDependencies:z,dependencies:J,entryCronTriggers:ce,env:l,featureUsage:R,hasFlags:U,hasNotify:W,authClaims:c,identity:o,platformGate:{...L,diagnostics:[...Va(n,e.target),...L.diagnostics,...Ua(se,i.vectorIndexes),...I.liveStreams&&I.deliveryAuthorization?[Wa(se)]:[],...I.socketRoutes&&I.deliveryAuthorization?[qa(se)]:[]]},queues:f,serverContent:Xa({agents:v,capabilities:ne,containers:k,env:l,hasVectors:le,hasFlags:U,authClaims:c,hasNotify:W,identity:o,queues:f,schema:i,services:de,storageRuleBuckets:X.rules.map(D=>D.bucket),topics:g,useUmbrella:V,workflows:u}),services:de,storageRulesMetadata:X,topics:g,usesSandbox:N.usesSandboxBrowser||N.usesSandboxContainer||N.usesSandboxFs,useUmbrella:V,workflows:u}},Or=(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},qh=e=>{if(!r.isPropertyAccessExpression(e))return!1;const t=e.getExpression();return r.isPropertyAccessExpression(t)&&t.getName()==="scheduler"||r.isIdentifier(t)&&t.getText()==="scheduler"},jh=new Map([["publish",{kind:"publish",surface:"topics"}],["publishBatch",{kind:"publish",surface:"topics"}],["send",{kind:"enqueue",surface:"queues"}],["sendBatch",{kind:"enqueue",surface:"queues"}]]),Hh=/^[\w$]+:[\w$]+$/u,Gh=(e,t)=>{const s=ci(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},Qn=e=>{const t=[];for(const s of e.getProperties()){if(!r.isPropertyAssignment(s)&&!r.isShorthandPropertyAssignment(s))return;t.push(s.getName())}return t},Yh=e=>{if(e===void 0)return[];if(r.isObjectLiteralExpression(e))return Qn(e);if(r.isIdentifier(e)){const t=e.getSymbol()?.getDeclarations()[0];if(r.isVariableDeclaration(t)&&t.getVariableStatement()?.getDeclarationKind()===pt.Const){const s=t.getInitializer();return r.isObjectLiteralExpression(s)?Qn(s):void 0}}},Qh=(e,t,s)=>({schedule:{argKeys:Yh(s),...e==="runAfter"&&t!==void 0&&r.isNumericLiteral(t)?{delayMs:t.getLiteralValue()}:{}}}),Xh=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;const s=t.getName(),[n,i,o]=e.getArguments();if(ms.has(s))return Gh(s,n);if((s==="runAfter"||s==="runAt")&&qh(t)){const l=ci(i)??(r.isStringLiteral(i)&&Hh.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,...Qh(s,n,o)}}const a=jh.get(s),c=a===void 0?void 0:Or(t,a.surface);return a===void 0||c===void 0?void 0:{kind:a.kind,target:c}},Jh=new Set([d.AmpersandAmpersandEqualsToken,d.AmpersandAmpersandToken,d.BarBarEqualsToken,d.BarBarToken,d.QuestionQuestionEqualsToken,d.QuestionQuestionToken]),kr=e=>Eo.isOptionalChain(e.compilerNode),Zh=(e,t)=>r.isIfStatement(t)?!b(e,t.getExpression()):r.isWhileStatement(t)||r.isForInStatement(t)||r.isForOfStatement(t)?b(e,t.getStatement()):r.isForStatement(t)?b(e,t.getStatement())||b(t.getIncrementor(),e):r.isCaseClause(t)||r.isDefaultClause(t)||r.isCatchClause(t)?!0:ge(t)?t.getFirstAncestor(ge)!==void 0:r.isConditionalExpression(t)?!b(e,t.getCondition()):r.isBinaryExpression(t)?!b(e,t.getLeft())&&Jh.has(t.getOperatorToken().getKind()):(r.isCallExpression(t)||r.isElementAccessExpression(t))&&kr(t)?!b(e,t.getExpression()):r.isBlock(t)&&t.getStatements().some(s=>s.getEnd()<=e.getStart()&&Rm(s)),ev=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)&&b(t,s.getRight())&&s.getOperatorToken().getKind()===d.EqualsToken,i=e.getFirstAncestor(ge);return n||i?.getDescendantsOfKind(d.ThrowStatement).some(o=>o.getStart()>=e.getEnd()&&b(o.getFirstAncestor(ge),i))===!0},tv=(e,t)=>(r.isWhileStatement(t)||r.isForInStatement(t)||r.isForOfStatement(t))&&b(e,t.getStatement())||r.isForStatement(t)&&(b(e,t.getStatement())||b(t.getIncrementor(),e)),sv=(e,t)=>{if(kr(e)||t==="schedule"&&ev(e))return"guard";let s=e,n=!1;for(let i=s.getParent();i!==void 0&&!r.isSourceFile(i);i=i.getParent()){if(Zh(s,i)){if(!tv(s,i))return"guard";n=!0}s=i}return n?"loop":void 0},Xn=(e,t,s)=>{if(s===void 0)return;const n=sv(e,s.kind);return{...s,...n===void 0?{}:{conditional:!0},...n==="loop"?{loopOnly:!0}:{},file:t,line:e.getStartLineNumber(),scope:A(e)}},nv=(e,t)=>[...O(e,t,(s,n)=>Xn(s,n,Xh(s))),...oe(e,t,d.PropertyAccessExpression,(s,n)=>{const i=Or(s,"services");return Xn(s,n,i===void 0?void 0:{kind:"invoke",target:i})})],iv=new Set(["boolean","number","object","string"]),rv=e=>{const t=e.getName();if(!iv.has(t))return;const s=e.getExpression();return Y(s,["flags"])||Y(s,["flags","details"])?t:void 0},ov=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;const s=rv(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},av=(e,t)=>{const s=new Map;for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const o of x(i,d.CallExpression)){const a=ov(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))},cv=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"||ec(o))return;const a=e.getSourceFile().getFilePath();if(tc(i,e,a)){const c=sc(i,e,a,0,new Set);return c===void 0&&nc(o),c}return o},lv=e=>e.getProperties().some(t=>{if(r.isSpreadAssignment(t))return!0;const s=Ss(t.getNameNode());return s===void 0||s==="namespace"}),dv=(e,t)=>{for(const{filePath:s}of Be(t)){const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const i of x(n,d.CallExpression)){const o=i.getExpression(),[a]=i.getArguments();if(!(!r.isPropertyAccessExpression(o)||o.getName()!=="auth"||a===void 0)&&(!r.isObjectLiteralExpression(a)||lv(a)))return i}}},uv="https://lunora.sh/docs/concepts/data-residency#pinning-auth-and-voice",fv=(e,t)=>{if(!(e.jurisdiction===void 0||e.jurisdictionPinsAuth===!0||t===void 0))throw we(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 (${uv}). 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})},gv="room:",pv="__lunora_socket__:",mv=/^[A-Za-z]\w*$/u,Jn=e=>mv.test(e),hv=e=>`${e}:`.startsWith(gv)||`${e}:`.startsWith(pv),Rr=e=>e.getProperties().some(t=>r.isSpreadAssignment(t)||r.isComputedPropertyName(t.getNameNode())),Fr=e=>Rr(e)||e.getProperties().some(t=>r.isMethodDeclaration(t)||r.isGetAccessorDeclaration(t)||r.isSetAccessorDeclaration(t)),Zn=e=>S(e),Fs=(e,t)=>e.getProperties().find(s=>(r.isPropertyAssignment(s)||r.isShorthandPropertyAssignment(s))&&S(s)===t),ve=(e,t)=>{const s=we(e,`defineLiveStream ${t}`);return new F("LIVE_STREAM_NOT_LITERAL",s.message)},Lr=(e,t,s)=>{const n=Fs(e,t),i=r.isPropertyAssignment(n)?n.getInitializer():void 0;if(i===void 0||!r.isObjectLiteralExpression(i))throw ve(n??e,`needs ${s} so codegen can read its topics`);if(Fr(i))throw ve(i,`cannot spread into or compute the keys of \`${t}\`: codegen must read every name as a literal`);return i},vv=(e,t)=>{const s=Zn(t),n=r.isPropertyAssignment(t)?t.getInitializer():void 0;if(n===void 0||!r.isObjectLiteralExpression(n))throw ve(t,`needs an object literal for topic "${s}" ({ key?, payload }), not a reference to one`);if(Fr(n))throw ve(n,`cannot spread into or compute the keys of topic "${s}"`);if(!Jn(s)||hv(s))throw new F("LIVE_TOPIC_INVALID",`live stream "${e}": topic name "${s}" must be a plain identifier (letters, digits and "_", starting with a letter) that does not encode into the "room:" or socket topic prefix.`);if(Fs(n,"key")===void 0)return{fields:[],name:s};const a=Lr(n,"key",`an object literal \`key\` for topic "${s}"`).getProperties().map(l=>Zn(l)),c=a.find(l=>!Jn(l));if(c!==void 0)throw new F("LIVE_TOPIC_INVALID",`live stream "${e}": key field "${s}.${c}" must be a plain identifier (letters, digits and "_", starting with a letter).`);return{fields:a,name:s}},Ev=(e,t,s)=>{const n=e.getArguments()[0];if(n===void 0||!r.isObjectLiteralExpression(n))throw ve(e,"needs an object-literal options argument so codegen can read its `id` and `topics`");if(Rr(n))throw ve(n,"cannot spread its options or use a computed key: codegen must read `id` and `topics` as literals");const i=Fs(n,"id"),o=r.isPropertyAssignment(i)?i.getInitializer():void 0;if(o===void 0||!r.isStringLiteral(o))throw ve(i??n,'needs a string-literal `id` (e.g. `defineLiveStream({ id: "posts", … })`) so codegen can type its references');const a=o.getLiteralValue(),c=Lr(n,"topics","an object-literal `topics` map");return{exportName:t,filePath:P(s,e.getSourceFile().getFilePath()),id:a,topics:c.getProperties().map(l=>vv(a,l))}},xv=e=>{const t=new Map;for(const s of e)for(const[n,i]of[["id",s.id],["export",s.exportName]]){const o=`${n}:${i}`,a=t.get(o);if(a!==void 0)throw new F("LIVE_STREAM_DUPLICATE",`live stream ${n} "${i}" is declared by both lunora/${a}.ts and lunora/${s.filePath}.ts; it must be unique across the app.`);t.set(o,s.filePath)}},Sv=e=>{let t=e.getParent();for(;r.isAsExpression(t)||r.isSatisfiesExpression(t)||r.isNonNullExpression(t)||r.isParenthesizedExpression(t);)t=t.getParent();return t},Av=(e,t)=>x(e,d.CallExpression).filter(s=>pi(s,"defineLiveStream")).map(s=>{const n=Sv(s),i=r.isVariableDeclaration(n)?vs(n,"binding"):void 0;if(i===void 0)throw new F("LIVE_STREAM_NOT_EXPORTED",we(s,"defineLiveStream must be assigned to a named export (`export const posts = defineLiveStream({ … })`), not a default export, a local, or an inline call, so codegen can type its references").message);return Ev(s,i,t)}),yv=(e,t)=>{const s=y(t).flatMap(n=>Av(e.getSourceFile(n)??e.addSourceFileAtPath(n),t));return xv(s),s},bv=e=>r.isPropertyAssignment(e)||r.isMethodDeclaration(e)||r.isGetAccessorDeclaration(e)?r.isComputedPropertyName(e.getNameNode()):!1,Nv=e=>r.isPropertyAssignment(e)||r.isShorthandPropertyAssignment(e)||r.isMethodDeclaration(e)||r.isGetAccessorDeclaration(e)?bv(e):!0,Dr=(e,t=!1)=>{for(const s of e.getProperties()){if(Nv(s))return!0;if(t)continue;if(!r.isPropertyAssignment(s))return!0;const n=s.getInitializer();if(!n||!r.isObjectLiteralExpression(n)||Dr(n,!0))return!0}return!1},Pv=(e,t)=>{for(const s of y(t)){const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const{receiver:i}of Ii(n))for(const o of As(i)){const a=o.getArguments()[0];if(a!==void 0&&(!r.isObjectLiteralExpression(a)||Dr(a)))return!0}}return!1},wv=e=>{const t=e.getArguments()[0];if(!t||!r.isObjectLiteralExpression(t))return[];const s=[];for(const n of t.getProperties()){const i=rt(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=rt(a);c!==void 0&&s.push({column:c,strategy:Si(a),table:i})}}return s},Iv=(e,t)=>{const s=new Map;for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const{receiver:o}of Ii(i))for(const a of As(o))for(const c of wv(a)){const l=`${c.table}\0${c.column}`;s.has(l)||s.set(l,c)}}return{columns:[...s.values()]}},Tv=["providerSubscriptionId","state"],Cv=["providerEventId","processedAt"],ei=(e,t)=>t.every(s=>s in e.shape),Ov=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&&ei(t,Tv)&&ei(s,Cv)},kv=["account","apikey","member","passkey","session","teamMember","twoFactor","user"],Rv=(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},Fv=(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},Lv="@lunora/privacy",Mr="userId",ti=new Set(["user","users"]),Dv=e=>e.replaceAll("\\","/"),Mv="privacy",_v=new Set(["actionCacheDataset","authDataset","documentHistoryDataset"]),At=e=>e!==void 0&&(r.isStringLiteral(e)||r.isNoSubstitutionTemplateLiteral(e))?e.getLiteralText():void 0,Ke=e=>r.isPropertyAssignment(e)?e.getName().replaceAll(/^["']|["']$/gu,""):"",Ls=e=>e.getProperties().filter(t=>r.isPropertyAssignment(t)),zv=(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},yt=e=>{const t=e.getExpression();return r.isIdentifier(t)?t.getText():void 0},$v=(e,t)=>{const s=e.getArguments()[1];if(s===void 0||!r.isObjectLiteralExpression(s))return;const n=zv(s,"tables"),i=At(e.getArguments()[0])??"defineDataset";for(const o of n===void 0?[]:Ls(n).map(a=>Ke(a)))t.datasets.set(o,i)},Ds=8,Ne=(e,t=0)=>{if(t>Ds)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)},Kv=(e,t)=>{const s=e.getArguments()[0],n=s===void 0?void 0:Ne(s),i=n!==void 0&&r.isObjectLiteralExpression(n)?Ls(n):[],o=new Set(i.map(a=>Ke(a)));for(const a of kv)o.has(a)||t.datasets.set(a,"authDataset");for(const a of i){const c=r.isPropertyAssignment(a)?At(a.getInitializer()):void 0;c!==void 0&&(t.datasets.set(c,"authDataset"),Ke(a)==="user"&&t.userTables.add(c))}},si=(e,t,s)=>{t.datasets.set(At(e.getArguments()[0])??s,s)},Bv=e=>{if(r.isPropertyAssignment(e)){const t=e.getInitializer();return t===void 0?void 0:[Ke(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()]}},_r=(e,t=0)=>{const s=Ne(e,t);if(s===void 0||!r.isObjectLiteralExpression(s)||t>Ds)return;const n=new Map;for(const i of s.getProperties()){const o=r.isSpreadAssignment(i)?_r(i.getExpression(),t+1):[Bv(i)];if(o===void 0)return;for(const a of o)a!==void 0&&n.set(a[0],a[1])}return n},Vv=e=>{const t=e.getArguments()[0];return t===void 0?void 0:_r(t)},Uv=(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)?Ls(n):[])t.excluded.set(Ke(i),r.isPropertyAssignment(i)?At(i.getInitializer())??"":"")},Wv=(e,t)=>{switch(yt(e)){case"actionCacheDataset":{si(e,t,"actionCache");break}case"authDataset":{Kv(e,t);break}case"defineDataset":{$v(e,t);break}case"documentHistoryDataset":{si(e,t,"documentHistory");break}}},Ms=e=>e!==void 0&&r.isCallExpression(e)&&yt(e)==="defineDataset",zr=e=>e!==void 0&&r.isCallExpression(e)&&_v.has(yt(e)??""),qv=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)&&(Ms(i)||zr(i))?n:void 0},$r=(e,t,s=0)=>{const n=Ne(e,s);if(n===void 0||!r.isArrayLiteralExpression(n)||s>Ds)return!1;for(const i of n.getElements())if(r.isSpreadElement(i)){if(!$r(i.getExpression(),t,s+1))return!1}else if(!Ms(i)&&!zr(i)){const o=r.isIdentifier(i)?qv(i):void 0;if(o===void 0)return!1;t.add(o)}return!0},jv=e=>{if(e===void 0)return;const t=e.get("datasets"),s=new Set;return t===void 0||$r(t,s)?s:void 0},Hv=(e,t)=>{const s=[];for(const i of x(e,d.CallExpression))if(Wv(i,t),yt(i)==="definePrivacy"){const o=Vv(i);Uv(o,t),s.push({location:`${e.getFilePath()}:${String(i.getStartLineNumber())}`,passed:jv(o)})}return{declared:x(e,d.VariableDeclaration).filter(i=>Ms(i.getInitializer())).map(i=>({declaration:i,name:i.getName()})),privacyCalls:s}},Gv=(e,t)=>{const s=E(t,"schema.ts"),n=[...y(t),...$(s)?[s]:[]];for(const o of n)e.getSourceFile(o)===void 0&&e.addSourceFileAtPath(o);const i=new Set(n.map(o=>Dv(o)));return e.getSourceFiles().filter(o=>i.has(o.getFilePath()))},Yv=(e,t,s)=>{if(s?.has(Lv)!==!0)return{classifications:{},enabled:!1,unusedDatasets:[],userTables:ti};const n={datasets:new Map,excluded:new Map,userTables:new Set(ti)},i=[],o=[];for(const f of Gv(e,t)){const g=Hv(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:Rv(n.datasets,n.excluded),enabled:o.length>0,unusedDatasets:l,userTables:n.userTables}},Kr=(e,t)=>e.kind==="id"?t.has(e.tableName??""):[e.inner,e.keyType,e.valueType,...e.members??[],...Object.values(e.shape??{})].some(n=>n!==void 0&&Kr(n,t)),Qv=(e,t)=>e.extensionKey!==Mv&&(Mr in e.shape||Object.values(e.shape).some(s=>Kr(s,t))),Xv=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 (a "${Mr}" column or a v.id of a user table) but no dataset exports it. Add it to a defineDataset, or exclude it in definePrivacy({ exclude }) with a reason.`,Jv=(e,t)=>{if(!t.enabled)return;const s=e.filter(o=>Qv(o,t.userTables)).map(o=>o.name),[n]=Fv(s,t.classifications);if(n!==void 0)throw new F("PRIVACY_COVERAGE",Xv(n));const[i]=t.unusedDatasets;if(i!==void 0)throw new F("PRIVACY_COVERAGE",`privacy_dataset_unused: "${i}" is declared with defineDataset but never passed to definePrivacy({ datasets }). Pass it, or delete it.`)},Zv=(e,t)=>{const s=ja(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")}},eE=new Set(["delete","deleteMany","hardDelete","insertMany","insertManyUnsafe","patch","patchIf","patchMany","patchWhere","replace","restore"]),tE="",sE=(e,t,s)=>{if(t!=="patch")return;const n=e.getArguments()[s];if(n===void 0||!r.isObjectLiteralExpression(n))return;const i=[];for(const o of n.getProperties()){if(!r.isPropertyAssignment(o)&&!r.isShorthandPropertyAssignment(o))return;i.push(o.getName())}return i},nE=e=>{const t=e.getSymbol()?.getDeclarations()[0];if(!(t===void 0||!r.isVariableDeclaration(t)))return t.getVariableStatement()?.getDeclarationKind()===pt.Const?t.getInitializer():void 0},nt=e=>{if(e===void 0)return;if(r.isAsExpression(e)&&e.getTypeNode()?.getText()==="const"||r.isSatisfiesExpression(e))return nt(e.getExpression());if(r.isAsExpression(e)||r.isTypeAssertion(e))return;if(r.isStringLiteral(e))return[e.getLiteralText()];if(r.isIdentifier(e)){const n=nE(e);if(n!==void 0)return nt(n)}if(!r.isExpression(e))return;const t=e.getType(),s=(t.isUnion()?t.getUnionTypes():[t]).map(n=>n.getLiteralValue());return s.every(n=>typeof n=="string")?s:void 0},iE=(e,t)=>{if(eE.has(e))return{method:e,tables:nt(t)??[tE]}},Br=(e,t,s)=>e===void 0?void 0:{...e,fields:sE(t,e.method,s)},ni=e=>{const t=St(e,af);return t===void 0?void 0:Br({method:t.method,tables:[t.table]},e,1)},rE=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;const s=t.getName(),n=t.getExpression();return Ji(n)!==void 0?ni(e):K(n)?Br(iE(s,e.getArguments()[0]),e,2):ni(e)},oE=(e,t)=>O(e,t,(s,n)=>{const i=rE(s);if(i===void 0)return;const o=A(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}))}),aE=(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"}),cE=(e,t)=>{if(t===void 0){const s=e.getArguments()[0];if(s===void 0||!r.isObjectLiteralExpression(s)||B(s,"args")===void 0)return!1}return Ns(e,t).opaque},lE=(e,t)=>{const s=[],n=(i,o)=>{const a=i.getInitializer();if(a===void 0||!r.isCallExpression(a))return;const c=ae(a);c!==void 0&&cE(a,c.receiver)&&s.push(aE(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},dE=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n);i!==void 0&&s.push(...lE(i,P(t,n)))}return s.toSorted((n,i)=>n.cacheKey.localeCompare(i.cacheKey))},uE=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)"}],["RegisteredInternalAction",{call:"internalAction.input({ … }).action(handler)"}],["RegisteredInternalMutation",{call:"internalMutation.input({ … }).mutation(handler)"}],["RegisteredInternalQuery",{call:"internalQuery.input({ … }).query(handler)"}],["RegisteredInternalStream",{call:"internalQuery.input({ … }).stream(handler)"}],["RegisteredLifecycleHook",{call:"onConnect(handler)",note:"Substitute the hook you called: `onConnect`, `onDisconnect` or `onShardInit`. 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)"}],["RegisteredWebSocket",{call:"defineWebSocket({ … })",note:"A dropped socket route has no caller to fail — its path is never recognised as an upgrade route, so connections fall through to the app router and the handler never runs."}],["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"}]]),ut=({byName:e,byPath:t},s,n)=>t.has(`${s}:${n}`)||e.has(n),Vr=e=>!e.isAny(),Ur=e=>{const t=e.getType();if(!Vr(t))return;const s=t.getAliasSymbol()?.getName()??t.getSymbol()?.getName(),n=s===void 0?void 0:uE.get(s);return n===void 0||s===void 0?void 0:{...n,typeName:s}},fE=e=>{const t=e.getInitializer();return t===void 0?!1:r.isCallExpression(t)||r.isIdentifier(t)||r.isPropertyAccessExpression(t)},Wr={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."},gE=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.`}),pE={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)."},mE=new Set(["AgentDefinition","ContainerDefinition","QueueDefinition","RegisteredShape","SubscriptionDefinition","WorkflowDefinition"]),hE={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)."},vE=(e,t,s)=>{if(!t.some(i=>Co(i)))return pE;const n=e.getVariableStatement()?.hasExportKeyword()===!0;return mE.has(s.typeName)&&!n&&!t.some(i=>fc(i))?hE:Wr},qr=(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:gE(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"}},EE=(e,t,s)=>{const n=[];for(const i of Z(e)){const o=r.isIdentifier(i.getNameNode())?Ht(i):[i.getName()],c=o.some(u=>ut(s,t,u))||!fE(i)?void 0:Ur(i),[l=i.getName()]=o;c!==void 0&&n.push(qr(t,l,c,i.getStartLineNumber(),vE(i,o,c)))}return n},xE=(e,t,s)=>{if(ut(s,t,"default"))return[];const n=[];for(const i of e.getExportAssignments().filter(o=>!o.isExportEquals()&&!r.isIdentifier(o.getExpression()))){const o=Ur(i.getExpression());o!==void 0&&n.push(qr(t,"default",o,i.getStartLineNumber(),Wr))}return n},SE=(e,t,s)=>[...EE(e,t,s),...xE(e,t,s)],AE=(e,t,s)=>e.getVariableStatements().flatMap(n=>n.getDeclarations()).filter(n=>r.isIdentifier(n.getNameNode())).filter(n=>Ht(n).some(i=>ut(s,t,i))).filter(n=>{const i=n.getInitializer();return i!==void 0&&r.isCallExpression(i)&&r.isPropertyAccessExpression(i.getExpression())}).map(n=>{const i=Ht(n).find(o=>ut(s,t,o))??n.getName();return{declaration:n,exportName:i,relativePath:t}}),yE=({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"}),bE=(e,t,s)=>{const n=[],i=[];for(const a of y(t)){const c=e.getSourceFile(a);if(c===void 0)continue;const l=P(t,a);n.push(...SE(c,l,s)),i.push(...AE(c,l,s))}const[o]=i;return o!==void 0&&i.every(({declaration:a})=>!Vr(a.getType()))&&n.push(yE(o)),n.toSorted((a,c)=>a.cacheKey.localeCompare(c.cacheKey))},NE=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"},PE=e=>{const t=e.getArguments()[0];return t&&r.isStringLiteral(t)?t.getLiteralText():""},wE=(e,t)=>O(e,t,(s,n)=>NE(s)?{file:n,line:s.getStartLineNumber(),scope:A(s),workflow:PE(s)}:void 0),jr=e=>e==="@lunora/workflow",IE=e=>new Set(e.getImportDeclarations().filter(t=>jr(t.getModuleSpecifierValue())).map(t=>t.getNamespaceImport()?.getText()).filter(t=>t!==void 0)),TE=(e,t,s)=>r.isIdentifier(e)?t.has(e.getText()):r.isPropertyAccessExpression(e)&&e.getName()==="defineWorkflowEvent"&&s.has(e.getExpression().getText()),CE=(e,t)=>{const s=gi(e,"defineWorkflowEvent",jr),n=IE(e);if(s.size===0&&n.size===0)return[];const i=[];for(const o of x(e,d.CallExpression)){if(!TE(o.getExpression(),s,n))continue;let a=o.getParent();for(;r.isAsExpression(a)||r.isSatisfiesExpression(a)||r.isParenthesizedExpression(a)||r.isNonNullExpression(a);)a=a.getParent();const c=r.isVariableDeclaration(a)?vs(a,"binding"):void 0;if(c===void 0)continue;const l=o.getArguments()[0];if(l===void 0||!(r.isStringLiteral(l)||r.isNoSubstitutionTemplateLiteral(l)))throw new F("WORKFLOW_EVENT_NOT_LITERAL",we(l??o,`workflow event "${c}": defineWorkflowEvent's \`type\` must be a string literal so codegen can register it for admin sends`).message);i.push({exportName:c,filePath:P(t,e.getFilePath()),type:l.getLiteralValue()})}return i},OE=(e,t)=>{const s=y(t).flatMap(i=>CE(e.getSourceFile(i)??e.addSourceFileAtPath(i),t)),n=new Map;for(const i of s){const o=n.get(i.type);if(o!==void 0)throw new F("WORKFLOW_EVENT_DUPLICATE",`workflow event type ${JSON.stringify(i.type)} is declared by both lunora/${o.filePath}.ts (${o.exportName}) and lunora/${i.filePath}.ts (${i.exportName}); it must be unique across the app.`);n.set(i.type,i)}return s.toSorted((i,o)=>i.type.localeCompare(o.type))},kE=e=>{const t=Ia(e,"compatibility_date"),s=Ta(e,"observability"),n=typeof s=="object"&&s!==null?s:{enabled:!0};return`${JSON.stringify({$schema:"node_modules/wrangler/config-schema.json",...t===void 0?{}:{compatibility_date:t},main:"src/worker.ts",name:Ca(e),observability:n,preview_urls:!1,workers_dev:!1},void 0,4)}
29
- `},RE=e=>`// Generated by @lunora/codegen. Do not edit.
30
- // Serves the advisor procedure list to the app's Worker, which forwards it to a hosted Studio after the admin check.
31
- const PROCEDURES = ${JSON.stringify(e)};
32
-
33
- const ADVISOR_PROCEDURES_PATH = "/__lunora/advisor-procedures";
34
-
35
- export default {
36
- fetch(request: Request): Response {
37
- if (new URL(request.url).pathname !== ADVISOR_PROCEDURES_PATH) {
38
- return Response.json({ error: "not found" }, { status: 404 });
39
- }
40
-
41
- if (request.method !== "GET") {
42
- return Response.json({ error: "GET only" }, { status: 405 });
43
- }
44
-
45
- return new Response(PROCEDURES, { headers: { "Content-Type": "application/json" }, status: 200 });
46
- },
47
- };
48
- `,FE=(e,t,s)=>s?{"advisor-procedures.json":t,"src/worker.ts":RE(t),"wrangler.jsonc":kE(e)}:{},LE=(e,t)=>{for(const s of new Set([qo(t),xi(e)])){const n=s===void 0?[]:ua(s);if(s!==void 0&&n.length>0)throw new F("PROJECT_CONFIG_INVALID",`${po(s)} is invalid:
49
- ${n.map(i=>` - ${i}`).join(`
50
- `)}`)}},DE=(e,t,s)=>{for(const n of s)t[n]===void 0&&Ee(E(e,n),{force:!0});for(const n of[...new Set(s.map(i=>gt(E(e,i))))].toSorted((i,o)=>o.length-i.length))$(n)&&us(n).length===0&&Ee(n,{recursive:!0})},ME=(e,t)=>{for(const s of us(e,{recursive:!0,withFileTypes:!0})){const n=E(s.parentPath,s.name);s.isFile()&&t[fs(e,n)]===void 0&&Ee(n)}},Ve=(e,t)=>{$(e)&&ft(e,"utf8")===t||go(e,t,"utf8")},_E=(e,t)=>{if(t===""){Ee(e,{force:!0});return}Ve(e,t)},zE=(e,t)=>{const s=E(e,"services");if(Object.keys(t).length===0){Ee(s,{force:!0,recursive:!0});return}if($(s))for(const n of us(s,{recursive:!0,withFileTypes:!0})){const i=E(n.parentPath,n.name);n.isFile()&&t[fs(e,i)]===void 0&&Ee(i)}for(const[n,i]of Object.entries(t))ds(gt(E(e,n)),{recursive:!0}),Ve(E(e,n),i)},$E=(e,t,s,n)=>{const i=E(e,t);if(n!==void 0)DE(i,s,n);else if(Object.keys(s).length===0){Ee(i,{force:!0,recursive:!0});return}else $(i)&&ME(i,s);for(const[o,a]of Object.entries(s)){const c=E(i,o);ds(gt(c),{recursive:!0}),Ve(c,a)}},KE=e=>{try{const t=mc(E(e,"package.json"));return typeof t.version=="string"&&t.version!==""?t.version:void 0}catch{return}},it=(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)},BE=(e,t,s)=>e.getSourceFile(t)?.getFullText()===s,VE=(e,t)=>{$(e)||ds(e,{recursive:!0});const s=[];for(const n of t)switch(n.kind){case"always":{Ve(E(e,n.name),n.content),s.push(n.name);break}case"directory":{$E(e,n.name,n.files,n.owned),s.push(...Object.keys(n.files).map(i=>E(n.name,i)));break}case"services":{zE(e,n.files),s.push(...Object.keys(n.files));break}default:_E(E(e,n.name),n.content),n.content!==""&&s.push(n.name)}return s},UE=e=>{const t=KE(e.projectRoot),s=e.wantsArchitecture?e.modules:[],n=Ec({functions:e.functions,httpRoutes:e.httpRoutes,modules:s,version:t}),i=Sc({functions:e.functions,modules:s,version:t});return{openApiContent:`${JSON.stringify(n,void 0,2)}
51
- `,openApiModuleContent:xc(n),openRpcContent:`${JSON.stringify(i,void 0,2)}
52
- `,openRpcModuleContent:Ac(i)}},WE=".lunora-schema.json",qE=()=>{const e=process.env.LUNORA_CODEGEN_TIMING;return e!==void 0&&e!==""},jE=(e,t,s)=>{if(s&&e.length>0){const o=e.map(a=>`"${a.exportName}"`).join(", ");throw new F("MASK_UNSUPPORTED",`This project declares a \`mask(...)\` policy whose argument isn't a plain object literal (e.g. \`mask(sharedPolicies)\` referencing a hoisted variable), or contains a spread (\`...shared\`) or computed key (\`[name]:\`) codegen can't enumerate, so codegen can't tell which columns it masks. Because the project also declares replication shape(s) (${o}), codegen can't verify none of them replicate a table that policy masks — inline every table and column as literal keys so codegen can verify it, or remove the affected shape(s).`,{status:422})}const 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 F("MASK_UNSUPPORTED",`defineShape "${o.exportName}" has a non-literal \`table\` (a variable or expression, not a string literal), so codegen can't statically verify it doesn't replicate a table that masks a column. This project masks at least one column elsewhere, so the combination can't be proven safe — change "${o.exportName}"'s \`table\` to a plain string literal so codegen can verify it, or remove the mask(s) on the table it targets.`,{status:422});continue}const a=n.get(o.table);if(a===void 0)continue;const c=a.map(l=>`"${l}"`).join(", ");throw new F("MASK_UNSUPPORTED",`defineShape "${o.exportName}" replicates table "${o.table}", which masks column(s) ${c} on at least one procedure. A shape runs no procedure, so \`.use(mask(...))\` never applies to its replicated rows — remove the shape, unmask the table, or wait for shape-masking support.`,{status:422})}},HE=8,GE=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:v}=e,k=()=>rc(()=>{const N=Vo(l,a,{lazyFunctions:o}),ee=ea(l,a);return{functions:N,httpRoutes:oc(l,a),mutators:ee}});let{erased:X,value:{functions:w,httpRoutes:ce,mutators:I}}=k();Bo(y(a).map(N=>l.getSourceFileOrThrow(N)),N=>fs(a,N.getFilePath())),Hn([...w,...I].map(N=>N.filePath)),Hn(ce.filter(N=>N.stream).map(N=>N.filePath),"http-stream");for(let N=1;;N+=1){const ee=u?w:w.filter(z=>z.channel?.kind!=="room"&&z.lifecycle!=="socket"),te=Cc({agents:t,functions:ee,httpRoutes:ce,mutators:I,useUmbrella:m,workflows:v}),se={agents:t,functions:ee,lazyFunctions:o,migrations:c,mutators:I,shapes:f,useUmbrella:m,usesSandbox:g},L=$c(se),R=Kc(se),ne=Oc({functions:w,useUmbrella:m}),le=E(a,"_generated",Ti),de=[[s,te],[i,ne],[n,L],...Object.entries(R).map(([z,J])=>[E(le,z),J])];if(N>=HE||de.every(([z,J])=>BE(l,z,J)))return{apiContent:te,erased:X,functions:w,functionModulesContent:R,functionsContent:L,httpRoutes:ce,internalContent:ne,mutators:I};for(const[z,J]of de)it(l,z,J);({erased:X,value:{functions:w,httpRoutes:ce,mutators:I}}=k())}},YE=e=>{const t=qE(),s=t?Dt.now():0,n=E(e.projectRoot,e.lunoraDirectory??"lunora");LE(e.projectRoot,n);const i=fa(n),o=e.lazyFunctions===!0||i,a=ga(n),c=E(n,"schema.ts");if(!$(c))throw new F("INTERNAL",`schema.ts not found at ${c}`);const l=e.project??wa(n);$o(cv);const u=dc(l,c,e.projectRoot);Jv(u.tables,Yv(l,n,Pi(e.projectRoot)));const{agents:f,authClaims:g,capabilities:m,containers:v,crons:k,dataModelContent:X,dependencies:w,entryCronTriggers:ce,env:I,featureUsage:N,hasFlags:ee,hasNotify:te,identity:se,platformGate:L,queues:R,serverContent:ne,services:le,storageRulesMetadata:de,topics:z,usesSandbox:J,useUmbrella:V,workflows:U}=Wh({lunoraDirectory:n,project:l,projectRoot:e.projectRoot,schema:u,target:e.target});fv(u,u.jurisdiction===void 0?void 0:dv(l,n));const W=E(n,"_generated"),D=E(W,"dataModel.ts"),Hr=E(W,"server.ts"),Gr=E(W,"api.ts"),Yr=E(W,"internal.ts"),Qr=E(W,"functions.ts");it(l,D,X),it(l,Hr,ne);const _s=Object.fromEntries(le.filter(p=>p.rpcEntrypoint!==void 0).flatMap(p=>Object.entries(Ja(p,W))));for(const[p,Lt]of Object.entries(_s))it(l,E(W,p),Lt);const Ue=cc(l,n),me=uc(l,n),bt=L.signals.typedWebSockets!==!1,{apiContent:zs,erased:Xr,functions:j,functionModulesContent:$s,functionsContent:Ks,httpRoutes:Nt,internalContent:Bs,mutators:Pt}=GE({agents:f,apiPath:Gr,generatedFunctionsPath:Qr,internalPath:Yr,lazyFunctions:o,roomsSupported:bt,lunoraDirectory:n,migrations:Ue,project:l,shapes:me,useUmbrella:V,usesSandbox:J,workflows:U}),Vs=ha(l,n),wt=va(Vs,u,[...j,...Nt].map(p=>p.filePath)),We=Vs.length>0,Ie=e.lint===!1&&!We?void 0:{callEdges:nv(l,n),inserts:ac(l,n),queries:dn(l,n,j),tableWrites:oE(l,n),workflowCalls:wE(l,n)},Jr=hc(Ie?.queries??dn(l,n,j)),Te=e.lint===!1||Ie===void 0?void 0:uh(l,n,{callSites:Ie,containers:v,crons:k,functions:j,modules:wt,mutators:Pt,queues:R,schema:u,shapes:me,workflows:U,wranglerVariables:e.wranglerVariables}),Us=Te===void 0?[]:Eh(e.projectRoot,[...mo(Te,{source:"static"}),...bE(l,n,{byName:new Set([...U,...R,...f,...v].map(p=>p.exportName)),byPath:new Set([...j,...Pt,...me,...Ue].map(p=>`${p.filePath}:${p.exportName}`))}),...dE(l,n),...ic(Xr,n),...yc(R,e.wranglerQueueProducers)]),Zr=lc(l,n),Ws=Iv(l,n);jE(me,Ws,Pv(l,n));const eo=ee?av(l,n):[],It=L.signals.vectorStore!==!1,to=Ha(Xe(e.projectRoot,e.target),"deliveryAuthorization"),Ce=Zv(N,{containerCount:v.length,cronCount:k.length,dependencies:w,hasPaymentTables:Ov(u.tables),queueCount:R.length,storageColumnCount:Object.keys(wi(u)).length,storageRuleCount:de.rules.length,vectorIndexCount:u.vectorIndexes.length,target:Xe(e.projectRoot,e.target),vectorStoreSupported:It,workflowCount:U.length}),qs=t?Dt.now():0,Tt=vc(u,Ue.map(p=>p.id)),Ct=yv(l,n),js=Qa({advisories:Us.filter(p=>p.name!=="procedure_type_check_unavailable"),agents:f,capabilities:m,containers:v,env:I,flagKeys:eo,hasFlags:ee,hasNotify:te,hasIpReaders:j.some(p=>p.readsIp===!0)||me.some(p=>p.readsIp===!0),hasRooms:bt&&j.some(p=>p.channel?.kind==="room"),hasSensitiveArgs:f.length>0||j.some(p=>Pa(p)),hasSecretValues:L.signals.secretValues===!0,hasSockets:bt&&j.some(p=>p.lifecycle==="socket"),lazyFunctions:o,hasVectors:It,liveStreamDeclarations:Ct,liveStreams:L.signals.liveStreams===!0,maskMetadata:Ws,mutators:Pt,queues:R,rlsMetadata:Zr,schema:u,schemaSnapshot:Tt,shapes:me,services:le,storageRules:de,studioFeatures:Ce,topics:z,useUmbrella:V,workflowEvents:OE(l,n),workflows:U}),Hs=Ic(me,w.has("@lunora/db"),V),Gs=bc(v,u.jurisdiction),Ys=Nc(U,{lazy:o}),Qs=Pc(f,{lazy:o}),Xs=wc(R,e.wranglerQueueProducers),Js=Bc(Ct,V),Zs=kc(k),so=Rc(Ce.scheduler),qe=Ga(Xe(e.projectRoot,e.target)),no=qe.supported?Fc(V):"",io=Lc(u.tables,V,u.jurisdiction),ro=pa(e.projectRoot)?Dc(V):"",en=Mc(u.vectorIndexes),je=zc(u,V),tn=Tc(w.has("@lunora/seed")),He=e.apiSpec??"openapi",Ot=He==="openapi"||He==="both",oo=Te?.procedureProtections??[],ao=Te===void 0?{analysis:"disabled",procedures:[]}:{procedures:[...oo]},kt=`${JSON.stringify(ao,void 0,2)}
53
- `,Rt=He==="openrpc"||He==="both",sn=gc(w.has("@lunora/auth")),nn=pc({agentWorkflows:f.map(p=>p.className),authClaims:g.map(p=>p.name),capabilities:m,emailAgents:f.filter(p=>p.onEmail===!0).map(p=>({className:p.className,exportName:p.exportName})),hasAccess:w.has("@lunora/cloudflare-access"),hasAuth:w.has("@lunora/auth"),hasFramework:w.has("@lunora/astro")||w.has("@lunora/svelte")||w.has("@lunora/vue")||$(E(e.projectRoot,"src","worker.ts")),hasGlobal:u.tables.some(p=>bi(p)),hasHyperdriveGlobal:u.tables.some(p=>Ni(p)),hasKvIntrospector:Ce.kv,hasNotify:te,hasQueue:R.some(p=>p.mode==="push"),liveStreams:L.signals.liveStreams===!0,liveStreamsWithheld:L.liveStreamsWithheld,liveStreamDeclarations:Ct,hasAdminRevocations:qe.supported,hasScheduler:Ce.scheduler,hasSourcedTables:u.tables.some(p=>p.externalSource!==void 0),hasStorage:Ce.storage,hasDeliveryAuthorization:to,hasVectors:It,hasWorkflow:U.length>0,identity:se,jurisdiction:u.jurisdiction,jurisdictionPinsAuth:u.jurisdictionPinsAuth===!0,lazyFunctions:o,tables:u.tables.map(p=>({name:p.name,shardMode:p.shardMode})),securityHeaders:ma(n),spaAssetsBindings:e.spaAssetsBindings,useUmbrella:V,vectorIndexCount:u.vectorIndexes.length,voiceAgents:f.filter(p=>p.voice===!0&&p.voiceBindingName!==void 0).map(p=>({bindingName:p.voiceBindingName,exportName:p.exportName})),wantsArchitecture:We,wantsOpenApi:Ot,wantsOpenRpc:Rt}),{openApiContent:rn,openApiModuleContent:on,openRpcContent:an,openRpcModuleContent:cn}=UE({functions:j,httpRoutes:Nt,modules:wt,projectRoot:e.projectRoot,wantsArchitecture:We}),Oe=We&&Ie!==void 0?Fh({...Ie,crons:k,functions:j,httpRoutes:Nt,modules:wt,queues:R,schema:u,services:le,topics:z,workflows:U}):void 0,Ft=E(n,WE),co=$(Ft),lo=e.dryRun?[]:VE(W,[{content:nn,kind:"always",name:"app.ts"},{content:X,kind:"always",name:"dataModel.ts"},{content:zs,kind:"always",name:"api.ts"},{content:Bs,kind:"always",name:"internal.ts"},{content:ne,kind:"always",name:"server.ts"},{content:Ks,kind:"always",name:"functions.ts"},{files:$s,kind:"directory",name:Ti},{content:js,kind:"always",name:"shard.ts"},{content:Zs,kind:"always",name:"crons.ts"},{content:en,kind:"always",name:"vectors.ts"},{content:je.global,kind:"always",name:"drizzle.global.ts"},{content:je.shard,kind:"always",name:"drizzle.shard.ts"},{content:Gs,kind:"optional",name:"containers.ts"},{content:Ys,kind:"optional",name:"workflows.ts"},{content:Qs,kind:"optional",name:"agents.ts"},{content:Xs,kind:"optional",name:"queues.ts"},{content:Js,kind:"optional",name:"live.ts"},{content:so,kind:"optional",name:"scheduler.ts"},{content:io,kind:"optional",name:"shardRegistry.ts"},{content:no,kind:"optional",name:"adminRevocations.ts"},{content:ro,kind:"optional",name:"durableObjects.ts"},{content:tn,kind:"optional",name:"seed.ts"},{content:sn,kind:"optional",name:"authModule.ts"},{content:Hs,kind:"optional",name:"collections.ts"},{files:_s,kind:"services"},{files:FE(e.projectRoot,kt,a),kind:"directory",name:"companion",owned:Oa},{content:Ot?rn:"",kind:"optional",name:"openapi.json"},{content:Ot?on:"",kind:"optional",name:"openapi.ts"},{content:Rt?an:"",kind:"optional",name:"openrpc.json"},{content:Rt?cn:"",kind:"optional",name:"openrpc.ts"},{content:kt,kind:"optional",name:"advisor-procedures.json"},{content:Oe===void 0?"":`${JSON.stringify(Oe,void 0,2)}
54
- `,kind:"optional",name:"architecture.json"},{content:Oe===void 0?"":Lh(Oe),kind:"optional",name:"architecture.ts"}]);if(!e.dryRun&&!co&&Ve(Ft,ho(Tt)),t){const p=Dt.now(),Lt=Math.round(p-s),uo=Math.round(qs-s),fo=Math.round(p-qs);console.error(`@lunora/codegen: codegen took ${Lt.toString()}ms (discovery ${uo.toString()}ms, emit ${fo.toString()}ms)`)}return{advisories:Us,advisorContext:Te,agents:f,architecture:Oe,containers:v,cronTriggers:[...new Set([..._c(k),...ce])],generated:{advisorProceduresJson:kt,agents:Qs,api:zs,app:nn,authModule:sn,collections:Hs,containers:Gs,crons:Zs,dataModel:X,drizzleGlobal:je.global,drizzleShard:je.shard,functionModules:$s,functions:Ks,internal:Bs,live:Js,openApi:rn,openApiModule:on,openRpc:an,openRpcModule:cn,queues:Xs,seed:tn,server:ne,shard:js,vectors:en,workflows:Ys},migrations:Ue,outputDirectory:W,platformDiagnostics:qe.diagnostic===void 0?L.diagnostics:[...L.diagnostics,qe.diagnostic],queues:R,indexReferences:Jr,schemaSnapshot:Tt,schemaSnapshotPath:Ft,schemaTables:u.tables,workflows:U,writtenFiles:lo}},m0=e=>No(()=>YE(e));export{WE as SCHEMA_SNAPSHOT_FILENAME,wa as createCodegenProject,E0 as findTsconfig,x0 as refreshCodegenProject,m0 as runCodegen,S0 as tsconfigFingerprint};
@@ -1 +0,0 @@
1
- import{existsSync as d}from"node:fs";import{join as g}from"node:path";import{SyntaxKind as m,Node as o}from"ts-morph";import{diagnosticAt as l}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{a as u}from"./module-specifiers-BctA0m_p.mjs";import{p as h}from"./parse-validator-BisfC8bR.mjs";import{findObjectProperty as c}from"./isTestPath-6GN3Bkus.mjs";import{a as x}from"./attribution-C3R6vQrY.mjs";import{m as f}from"./ip-reads-DUVCi6k9.mjs";const S="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 u(e.getImportDeclaration().getModuleSpecifierValue())?e.getNameNode().getText()==="defineShape":!1;return!1},y=r=>{const t=r.getSymbol();if(!t)return!1;for(const e of t.getDeclarations()){if(!o.isNamespaceImport(e))continue;const i=e.getFirstAncestorByKind(m.ImportDeclaration);return i!==void 0&&u(i.getModuleSpecifierValue())}return!1},I=r=>{if(o.isIdentifier(r))return b(r);if(o.isPropertyAccessExpression(r)){const t=r.getExpression();return r.getName()==="defineShape"&&o.isIdentifier(t)&&y(t)}return!1},N=r=>{const[t]=r.getArguments();if(!t||!o.isObjectLiteralExpression(t))return;const e=c(t,"table");if(!e||!o.isPropertyAssignment(e))return;const i=e.getInitializer();return i&&o.isStringLiteral(i)?i.getLiteralValue():void 0},A=r=>{const[t]=r.getArguments();if(!t||!o.isObjectLiteralExpression(t))return{};const e=c(t,"args");if(!e||!o.isPropertyAssignment(e))return{};const i=e.getInitializer();return!i||!o.isObjectLiteralExpression(i)?{}:h(i)},E=r=>{const[t]=r.getArguments(),e=o.isObjectLiteralExpression(t)?c(t,"where"):void 0,i=o.isPropertyAssignment(e)?e.getInitializer():void 0;if(e===void 0)return f(r);if(!o.isArrowFunction(i)&&!o.isFunctionExpression(i))return!0;const n=i.getParameters()[0]?.getNameNode();return o.isIdentifier(n)&&n.getText()!=="ctx"&&n.findReferencesAsNodes().length>0||f(r)},P=r=>{const t=[];for(const e of r.getVariableDeclarations()){const i=e.getInitializer();if(i?.getKind()!==m.CallExpression)continue;const n=i,s=n.getExpression();if(!I(s))continue;const a=e.getNameNode();if(!o.isIdentifier(a)){if(e.getVariableStatement()?.hasExportKeyword()!==!0)continue;throw l(a,"defineShape exports must be plain named exports (no destructuring)")}const p=x(e,"binding");p!==void 0&&t.push({args:A(n),exportName:p,filePath:"shapes",...E(n)?{readsIp:!0}:{},table:N(n)})}return t},V=(r,t)=>{const e=g(t,S);if(!d(e))return[];const i=r.getSourceFile(e)??r.addSourceFileAtPath(e),n=P(i);return n.sort((s,a)=>s.exportName.localeCompare(a.exportName)),n};export{S as SHAPES_FILENAME,V as discoverShapes};
@@ -1 +0,0 @@
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-6GN3Bkus.mjs";import{a as P}from"./attribution-C3R6vQrY.mjs";import{r as $}from"./handler-reference-DOIBV2VQ.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};
@@ -1 +0,0 @@
1
- import{LunoraError as x}from"@lunora/errors";import{CRON_SCHEDULE_KINDS as A,warnIfSecondsLeading as O,compileCronSchedule as S}from"@lunora/scheduler";import I from"@lunora/scheduler/validate";import{SyntaxKind as m,Node as i}from"ts-morph";import{diagnosticAt as f,CodegenDiagnosticError as R}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{i as b}from"./module-specifiers-BctA0m_p.mjs";import{listLunoraSourceFiles as y,functionKeyOf as $}from"./isTestPath-6GN3Bkus.mjs";import{a as P}from"./property-name-7cBlgK_O.mjs";const D=new Set([...A,"cron"]),v=e=>{const t=e.getSymbol();if(!t)return e.getText()==="cronJobs";for(const r of t.getDeclarations())if(i.isImportSpecifier(r))return b(r.getImportDeclaration().getModuleSpecifierValue())?r.getNameNode().getText()==="cronJobs":!1;return!1},F=e=>{const t=new Set;for(const r of e.getVariableDeclarations()){const n=r.getInitializer();if(n?.getKind()!==m.CallExpression)continue;const s=n.getExpression();i.isIdentifier(s)&&v(s)&&t.add(r.getName())}return t},V=e=>{let t=e;for(;i.isCallExpression(t)||i.isPropertyAccessExpression(t);)t=t.getExpression();return i.isIdentifier(t)?t.getText():void 0},_=(e,t)=>{const r=e.getArguments()[t];return r&&(i.isStringLiteral(r)||i.isNoSubstitutionTemplateLiteral(r))?r.getLiteralValue():void 0},L=(e,t)=>{if(i.isStringLiteral(e)||i.isNoSubstitutionTemplateLiteral(e)||i.isNumericLiteral(e))return e.getLiteralValue();if(i.isTrueLiteral(e))return!0;if(i.isFalseLiteral(e))return!1;if(i.isPrefixUnaryExpression(e)&&e.getOperatorToken()===m.MinusToken){const r=e.getOperand();if(i.isNumericLiteral(r))return-r.getLiteralValue()}if(i.isObjectLiteralExpression(e))return p(e,t);if(i.isArrayLiteralExpression(e))return e.getElements().map(r=>L(r,t));throw f(e,`Cron job "${t}" passes a non-static value where a literal is required; codegen can only read literals.`,{code:"CRON_NON_STATIC_VALUE",name:"LunoraError",status:500})},p=(e,t)=>{const r={};for(const n of e.getProperties()){if(!i.isPropertyAssignment(n))throw f(n,`Cron job "${t}" uses an unsupported object property (shorthand/spread/method) where a static literal is required.`,{code:"CRON_NON_STATIC_VALUE",name:"LunoraError",status:500});const s=n.getInitializer();s&&(r[P(n)]=L(s,t))}return r},C=(e,t,r)=>{const n=e.getArguments()[t];if(!n||!i.isPropertyAccessExpression(n))throw f(e,`Cron job "${r}" must reference a function statically (e.g. internal.email.digest); codegen cannot resolve a dynamic reference.`,{code:"CRON_NON_STATIC_FN",name:"LunoraError",status:500});const s=$(n);if(s===void 0)throw f(n,`Cron job "${r}" function reference must be of the form internal.<…path>.fn (or api.<…path>.fn).`,{code:"CRON_NON_STATIC_FN",name:"LunoraError",status:500});return s},h=e=>({workflow:{className:e.className,exportName:e.exportName}}),w=e=>({workflow:{className:e.className,exportName:e.exportName}}),T=(e,t,r,n,s,o)=>{const a=e.getExpression();if(!i.isIdentifier(a)||a.getText()!==t)return;const c=r.get(e.getName());if(c)return o(c);throw f(e,`Cron job "${n}" targets ${t}.${e.getName()}, but no such ${s} is declared in lunora/${s}s.ts.`,{code:"CRON_NON_STATIC_FN",name:"LunoraError",status:500})},k=(e,t,r,n,s)=>{const o=e.getArguments()[t];if(o&&i.isPropertyAccessExpression(o)){const a=T(o,"workflows",n,r,"workflow",h);if(a)return a;const c=T(o,"agents",s,r,"agent",w);return c||{functionPath:C(e,t,r)}}if(o&&i.isIdentifier(o)){const a=n.get(o.getText()),c=s.get(o.getText());if(a&&c)throw f(o,`Cron job "${r}" references "${o.getText()}", which is ambiguous: a workflow and an agent are both declared under that name.`,{code:"CRON_NON_STATIC_FN",name:"LunoraError",status:500});if(a)return h(a);if(c)return w(c);throw f(o,`Cron job "${r}" references "${o.getText()}", which is neither a function (internal.file.fn / api.file.fn) nor a declared workflow in lunora/workflows.ts nor a declared agent in lunora/agents.ts.`,{code:"CRON_NON_STATIC_FN",name:"LunoraError",status:500})}return{functionPath:C(e,t,r)}},j=/^@lunora\/scheduler:\s*/u,U=(e,t)=>{const r=_(e,1);if(r===void 0)throw f(e,`Cron job "${t}" must pass a string-literal cron expression to ".cron(...)".`,{code:"CRON_EXPR_NOT_STATIC",name:"LunoraError",status:500});if(!I(r))throw f(e,`Cron job "${t}" has an invalid cron expression "${r}" — expected 5 or 6 space-separated fields.`,{code:"CRON_EXPR_INVALID",name:"LunoraError",status:500});return O(r,`cron expression for job "${t}"`),r},M=(e,t,r)=>{const n=e.getArguments()[1];if(!n||!i.isObjectLiteralExpression(n))throw f(e,`Cron job "${r}" must pass an object-literal schedule to ".${t}(...)".`,{code:"CRON_SCHEDULE_NOT_STATIC",name:"LunoraError",status:500});try{return S(t,p(n,r),r)}catch(s){if(s instanceof R)throw s;const o=s instanceof Error?s.message.replace(j,""):String(s);throw f(e,o,{code:"CRON_SCHEDULE_INVALID",name:"LunoraError",status:500})}},K=(e,t,r,n,s)=>{const o=t.getName();if(!D.has(o)||!r.has(V(t.getExpression())??""))return;const a=_(e,0);if(a===void 0||a.trim()==="")throw f(e,`A cron ".${o}(...)" registration must pass a non-empty string-literal name as its first argument.`,{code:"CRON_NAME_NOT_STATIC",name:"LunoraError",status:500});const c=o==="cron"?U(e,a):M(e,o,a),u=k(e,2,a,n,s),l=e.getArguments()[3];return{args:l&&i.isObjectLiteralExpression(l)?p(l,a):{},cron:c,name:a,...u}},z=e=>{const t=new Set;for(const r of e){if(t.has(r.name))throw new x("DUPLICATE_CRON_NAME",`Duplicate cron job name "${r.name}": cron names must be unique across the project.`,{status:500});t.add(r.name)}},Y=(e,t,r=[],n=[])=>{const s=y(t),o=[],a=new Map(r.map(u=>[u.exportName,u])),c=new Map(n.map(u=>[u.exportName,u]));for(const u of s){const l=e.getSourceFile(u)??e.addSourceFileAtPath(u),g=F(l);if(g.size!==0)for(const d of l.getDescendantsOfKind(m.CallExpression)){const N=d.getExpression();if(!i.isPropertyAccessExpression(N))continue;const E=K(d,N,g,a,c);E&&o.push(E)}}return o.sort((u,l)=>u.name.localeCompare(l.name)),z(o),o};export{Y as default};
@@ -1 +0,0 @@
1
- import"./declared-output-Iaar469J.mjs";import"./isTestPath-6GN3Bkus.mjs";import"./attribution-C3R6vQrY.mjs";import"./unwrap-handler-return-DhdSnAfS.mjs";import"./ip-reads-DUVCi6k9.mjs";import"./classify-procedure-call-C6ajvyGA.mjs";import{d as f}from"./index-D2i1mfys.mjs";import"./dispatch-namespace-DwTjD7BU.mjs";export{f as default};
@@ -1 +0,0 @@
1
- import{d as o}from"./context-property-calls-CCMzhSdz.mjs";const t=(r,e)=>o(r,e,"sql");export{t as default};
@@ -1 +0,0 @@
1
- import"./isTestPath-6GN3Bkus.mjs";import"./attribution-C3R6vQrY.mjs";import"./database-calls-B8H7kkzY.mjs";import"./classify-procedure-call-C6ajvyGA.mjs";import{d as a}from"./index-DTwKeiZr.mjs";export{a as default};
@@ -1 +0,0 @@
1
- import{d as r}from"./context-property-calls-CCMzhSdz.mjs";const t=(s,o)=>r(s,o,"r2sql");export{t as default};
@@ -1 +0,0 @@
1
- import{Node as o}from"ts-morph";import{listLunoraSourceFiles as c,lunoraRelativePath as f,findObjectProperty as u}from"./isTestPath-6GN3Bkus.mjs";import{j as p,h as d}from"./attribution-C3R6vQrY.mjs";import{t as m}from"./database-calls-B8H7kkzY.mjs";import{c as b}from"./classify-procedure-call-C6ajvyGA.mjs";import{r as h,p as y}from"./policies-DhRzjZZw.mjs";const v=e=>{const s=[];for(const r of y(e)){const t=u(r,"table");if(!t||!o.isPropertyAssignment(t))continue;const i=t.getInitializer();i&&o.isStringLiteral(i)&&s.push(i.getLiteralText())}return s},P=e=>{const s=h(e);return{rlsTables:s.flatMap(r=>v(r)),usesRls:s.length>0}},T=new Set(["explain","findFirst","findFirstOrThrow","findMany","get","query"]),g=new Set(["delete","deleteMany","insert","insertMany","patch","patchIf","patchMany","replace"]),R=(e,s)=>{if(!o.isVariableDeclaration(e))return;const r=e.getInitializer();if(!r||!o.isCallExpression(r))return;const t=b(r);if(!t)return;const i=t.receiver?P(t.receiver):{rlsTables:[],usesRls:!1},{tablesRead:a,tablesWritten:l}=m(e,T,g);return{exportName:d(e)??e.getName(),file:s,rlsTables:i.rlsTables,tablesRead:a,tablesWritten:l,usesRls:i.usesRls,visibility:t.visibility}},C=(e,s)=>{const r=[];for(const t of c(s)){const i=e.getSourceFile(t)??e.addSourceFileAtPath(t),a=f(s,t);for(const l of p(i)){const n=R(l,a);n&&r.push(n)}}return r};export{C as default};