@lunora/codegen 1.0.0-alpha.241 → 1.0.0-alpha.243
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +108 -58
- package/dist/index.d.ts +108 -58
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/AGENTS_FILENAME-Bb2jxbOa.mjs +1 -0
- package/dist/packem_shared/CONTAINERS_FILENAME-CGB4bqUr.mjs +1 -0
- package/dist/packem_shared/DEFAULT_TARGET-wK6-Tado.mjs +1 -0
- package/dist/packem_shared/QUEUES_FILENAME-BzOl92QK.mjs +1 -0
- package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-DX6sZtLG.mjs +9 -0
- package/dist/packem_shared/WORKFLOWS_FILENAME-DNaUHGS8.mjs +1 -0
- package/dist/packem_shared/{discoverCrons-MfKw7IFf.mjs → discoverCrons-0lNudk0S.mjs} +1 -1
- package/dist/packem_shared/emitAgents-C3ygr0M8.mjs +1 -0
- package/dist/packem_shared/{emitApi-CJ9ziZnP.mjs → emitApi-DdW9RyGG.mjs} +22 -22
- package/dist/packem_shared/{emitApp-CgXCWBms.mjs → emitApp-D_9NVcvv.mjs} +2 -2
- package/dist/packem_shared/{emitCrons-BP2xBXDJ.mjs → emitCrons-BRKXFGFu.mjs} +11 -11
- package/dist/packem_shared/{emitFunctions-BqAz1ssY.mjs → emitFunctions-BgNeOZt_.mjs} +1 -1
- package/dist/packem_shared/{emitServer-BEo_fCY8.mjs → emitServer-pF_fhA82.mjs} +54 -52
- package/dist/packem_shared/emitShard-DID_s1FK.mjs +1 -0
- package/dist/packem_shared/ir-DBSvhNa-.mjs +1 -0
- package/dist/packem_shared/{shard-BaHiawkc.mjs → shard-BVzXMtWg.mjs} +67 -67
- package/dist/packem_shared/{shard-runtime-B5SUfdZB.mjs → shard-runtime-oIXHEMU7.mjs} +53 -44
- package/package.json +10 -10
- package/dist/packem_shared/AGENTS_FILENAME-DoPI92Wu.mjs +0 -1
- package/dist/packem_shared/CONTAINERS_FILENAME-B6TFs82W.mjs +0 -1
- package/dist/packem_shared/DEFAULT_TARGET-DCpDuuUM.mjs +0 -1
- package/dist/packem_shared/QUEUES_FILENAME-CxkPcMH1.mjs +0 -1
- package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-CtkD-vQu.mjs +0 -9
- package/dist/packem_shared/WORKFLOWS_FILENAME-B_ZJxRSx.mjs +0 -1
- package/dist/packem_shared/emitAgents-CoNw0AKK.mjs +0 -1
- package/dist/packem_shared/emitShard-DFgzghbs.mjs +0 -1
- package/dist/packem_shared/ir-BgM8A3XV.mjs +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{existsSync as p}from"node:fs";import{join as f}from"node:path";import{agentDefaultName as d,agentClassName as b,voiceBindingName as N,voiceClassName as y}from"@lunora/agent/naming";import{LunoraError as m}from"@lunora/errors";import{Node as s,SyntaxKind as u}from"ts-morph";import{diagnosticAt as l}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{unwrapToCallExpression as A,findObjectProperty as c,stringPropertyFor as w}from"./listLunoraSourceFiles-DP-5e-RE.mjs";const h="agents.ts",E=o=>{const n=o.getSymbol();if(!n)return o.getText()==="defineAgent";for(const t of n.getDeclarations())if(s.isImportSpecifier(t))return t.getImportDeclaration().getModuleSpecifierValue()!=="@lunora/agent"?!1:t.getNameNode().getText()==="defineAgent";return!1},P=w("agent"),v=(o,n,t)=>{if(o.getKind()===u.TrueKeyword)return!0;if(o.getKind()===u.FalseKeyword)return!1;throw l(o,`agent "${n}": \`${t}\` must be a static boolean literal — it is deploy configuration codegen writes into the ctx.agents wiring spec`)},T=(o,n)=>{const t=o.getArguments()[0];if(!t||!s.isObjectLiteralExpression(t))throw l(o,`agent "${n}": defineAgent must be passed an inline object literal`);const e={className:b(n),exportName:n,name:d(n)},i=c(t,"name");i&&s.isPropertyAssignment(i)&&(e.name=P(i.getInitializerOrThrow(),n,"name"));const r=c(t,"publicRun");r&&s.isPropertyAssignment(r)&&v(r.getInitializerOrThrow(),n,"publicRun")&&(e.publicRun=!0);const a=c(t,"voice");if(a&&s.isPropertyAssignment(a)){const g=a.getInitializerOrThrow();if(!s.isObjectLiteralExpression(g))throw l(g,`agent "${n}": \`voice\` must be an inline object literal — its presence tells codegen to emit the voice-session Durable Object`);e.voice=!0,e.voiceBindingName=N(n),e.voiceClassName=y(n)}return c(t,"onEmail")&&(e.onEmail=!0),e},I=o=>{const n=[];for(const t of o.getVariableDeclarations()){if(!t.isExported())continue;const e=A(t.getInitializer());if(!e)continue;const i=e.getExpression();if(!s.isIdentifier(i)||!E(i))continue;const r=t.getNameNode();if(!s.isIdentifier(r))throw l(r,"defineAgent exports must be plain named exports (no destructuring)");n.push(T(e,r.getText()))}return n},x=o=>{const n=new Map,t=new Map;for(const e of o){const i=n.get(e.name);if(i!==void 0)throw new m("DUPLICATE_AGENT_NAME",`Duplicate agent name "${e.name}": produced by both "${i}" and "${e.exportName}". Deployed agent names must be unique across the project.`,{status:500});n.set(e.name,e.exportName);const r=t.get(e.className);if(r!==void 0)throw new m("DUPLICATE_AGENT_CLASS",`Duplicate agent class "${e.className}": produced by both "${r}" and "${e.exportName}". Agent export names must yield unique generated class names.`,{status:500});t.set(e.className,e.exportName)}},O=(o,n)=>{const t=f(n,h);if(!p(t))return[];const e=o.getSourceFile(t)??o.addSourceFileAtPath(t),i=I(e);return i.sort((r,a)=>r.exportName.localeCompare(a.exportName)),x(i),i};export{h as AGENTS_FILENAME,O as discoverAgents};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{existsSync as $}from"node:fs";import{join as S}from"node:path";import{containerClassName as P,containerBindingName as T,DURABLE_OBJECT_POLICY_FORBIDDEN_KEYS as A,isManagedImage as j,isCloudflareRegistryDigest as O,normalizeContainerImage as b}from"@lunora/container";import{SyntaxKind as d,Node as o}from"ts-morph";import{diagnosticAt as a}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{propertyKeyName as y,stringPropertyFor as I,findObjectProperty as p,symbolConstInitializer as k}from"./listLunoraSourceFiles-DP-5e-RE.mjs";const C="containers.ts",D=t=>{const e=t.getSymbol();if(!e)return t.getText()==="defineContainer";for(const r of e.getDeclarations())if(o.isImportSpecifier(r))return r.getImportDeclaration().getModuleSpecifierValue()!=="@lunora/container"?!1:r.getNameNode().getText()==="defineContainer";return!1},f=I("container"),h=(t,e,r)=>{if(o.isNumericLiteral(t))return t.getLiteralValue();throw a(t,`container "${e}": \`${r}\` must be a static number literal — it is deploy configuration codegen writes into wrangler.jsonc`)},w=(t,e)=>{if(o.isStringLiteral(t)||o.isNoSubstitutionTemplateLiteral(t))return b(t.getLiteralValue());if(o.isObjectLiteralExpression(t)){const r=p(t,"registry");if(r&&o.isPropertyAssignment(r)){const i=r.getInitializerOrThrow();return b({registry:f(i,e,"image.registry")})}const n=p(t,"build");if(n&&o.isPropertyAssignment(n)){const i=n.getInitializerOrThrow();return b({build:f(i,e,"image.build")})}}throw a(t,`container "${e}": \`image\` must be a static string path, { registry: "…" }, or { build: "…" } literal`)},M=new Set(["buildArgs","image","images","instanceType","maxInstances","name","rollout","schedulingPolicy"]),_=new Set(["gracePeriodSeconds","stepPercentage"]),E=t=>{let e=t;for(;o.isAsExpression(e)||o.isSatisfiesExpression(e)||o.isTypeAssertion(e)||o.isParenthesizedExpression(e);)e=e.getExpression();return e},F=(t,e)=>{const r=i=>{let s=i;for(;o.isPropertyAccessExpression(s)||o.isElementAccessExpression(s)||o.isParenthesizedExpression(s);)s=s.getExpression();return s===i?void 0:s},n=i=>i!==void 0&&o.isIdentifier(i)&&i.getSymbol()===t;return e.getDescendants().some(i=>{if(o.isBinaryExpression(i)){const s=i.getOperatorToken().getKind();return s>=d.FirstAssignment&&s<=d.LastAssignment&&n(r(i.getLeft()))}if(o.isPrefixUnaryExpression(i)||o.isPostfixUnaryExpression(i)){const s=i.getOperatorToken();return(s===d.PlusPlusToken||s===d.MinusMinusToken)&&n(r(i.getOperand()))}return o.isDeleteExpression(i)?n(r(i.getExpression())):o.isCallExpression(i)&&i.getExpression().getText()==="Object.assign"&&n(i.getArguments()[0])})},B=16,v=(t,e,r,n)=>{let i={name:r,symbol:t},s;for(let l=0;l<B;l+=1){const c=k(i.symbol);if(c===void 0||!o.isExpression(c))return s;if(s=E(c),o.isObjectLiteralExpression(s)&&i.symbol!==void 0&&F(i.symbol,e.getSourceFile()))throw a(e,`${n}: \`${i.name}\` is a const object that is written to elsewhere in this file, so its initializer is not the value the container runs with. Declare the settings where they are final.`);if(!o.isIdentifier(s))return s;i={name:s.getText(),symbol:s.getSymbol()}}return s},L=(t,e)=>{const r=E(t);return o.isIdentifier(r)?v(r.getSymbol(),r,r.getText(),e)??r:r},R=t=>{const e=t.getNonNullableType();return(e.isUnion()?e.getUnionTypes():[e]).flatMap(n=>n.getApparentType().getProperties().map(i=>i.getName()))},V=(t,e,r)=>{const n=t.getExpression().getType(),i=e==="every"||n.isAny()||n.isUnknown()?["its keys"]:[...new Set(R(n))].filter(s=>e.has(s)).map(s=>`\`${s}\``);if(i.length>0)throw a(t,`${r}: this spread can set ${i.join(", ")}, which codegen writes into wrangler.jsonc and so must read statically. Spread a module-scope \`const\` object literal, or write the keys inline.`)},z=(t,e,r)=>{const n=y(t),i=o.isShorthandPropertyAssignment(t)?v(t.getValueSymbol(),t,n,r):void 0;if(i!==void 0)return[n,i];if(e==="every"||e.has(n))throw a(t,`${r}: \`${n}\` is deploy configuration codegen writes into wrangler.jsonc, so it must be a static literal — inline it, or name a module-scope \`const\` initialized with one.`)},m=(t,e,r,n=new Set)=>{const i=[],s=new Set(n).add(t);for(const l of t.getProperties())if(o.isPropertyAssignment(l))i.push([y(l),L(l.getInitializerOrThrow(),r)]);else if(o.isSpreadAssignment(l))i.push(...K(l,e,r,s));else{const c=z(l,e,r);c!==void 0&&i.push(c)}return i},K=(t,e,r,n)=>{const i=L(t.getExpression(),r);if(!o.isObjectLiteralExpression(i))return V(t,e,r),[];if(n.has(i))throw a(t,`${r}: this spread refers back to an object it is part of, so it has no static value.`);return m(i,e,r,n)},U=(t,e)=>{if(!o.isObjectLiteralExpression(t))throw a(t,`container "${e}": \`buildArgs\` must be a static object literal — it is deploy configuration codegen writes into wrangler.jsonc`);const r={};for(const[n,i]of m(t,"every",`container "${e}" buildArgs`))r[n]=f(i,e,`buildArgs.${n}`);return Object.keys(r).length>0?r:void 0},x=(t,e)=>{if(!o.isObjectLiteralExpression(t))throw a(t,`container "${e}": \`rollout\` must be a static object literal — it is deploy configuration codegen writes into wrangler.jsonc`);const r={};for(const[n,i]of m(t,_,`container "${e}" rollout`))(n==="gracePeriodSeconds"||n==="stepPercentage")&&(r[n]=h(i,e,`rollout.${n}`));return r.gracePeriodSeconds===void 0&&r.stepPercentage===void 0?void 0:r},N=t=>{if(o.isTrueLiteral(t))return!0;if(o.isFalseLiteral(t))return!1},Y=t=>{if(o.isStringLiteral(t)||o.isNoSubstitutionTemplateLiteral(t)||o.isNumericLiteral(t))return t.getLiteralValue()},q=(t,e)=>{if(o.isStringLiteral(t))return t.getLiteralValue();if(o.isObjectLiteralExpression(t)){const r={};for(const n of t.getProperties()){if(!o.isPropertyAssignment(n))throw a(n,`container "${e}": \`instanceType\` must be an object of static number literals`);const i=y(n);if(i!=="diskMb"&&i!=="memoryMib"&&i!=="vcpu")throw a(n,`container "${e}": unknown \`instanceType\` field "${i}" — expected vcpu, memoryMib, or diskMb`);r[i]=h(n.getInitializerOrThrow(),e,`instanceType.${i}`)}return r}throw a(t,`container "${e}": \`instanceType\` must be a static string or { vcpu, memoryMib, diskMb } literal`)},W=(t,e)=>{if(!o.isObjectLiteralExpression(t))throw a(t,`container "${e}": \`images\` must be a static object literal — codegen writes it into wrangler.jsonc`);const r={};for(const[n,i]of m(t,"every",`container "${e}" images`)){const s=w(i,e);if(s.kind==="build")throw a(i,`container "${e}": \`images["${n}"]\` cannot be a Railpack { build } source — use a Dockerfile path or a { registry } reference`);if(s.kind==="registry"&&!O(s.reference))throw a(i,`container "${e}": \`images["${n}"].registry\` must be a digest-pinned (@sha256) reference under registry.cloudflare.com — push other registries' images there first`);r[n]=s}return r},G=(t,e)=>{const r=t.findLast(([i])=>i==="schedulingPolicy");if(r===void 0)return;const n=f(r[1],e,"schedulingPolicy");if(n!=="default"&&n!=="durable_object")throw a(r[1],`container "${e}": unknown \`schedulingPolicy\` "${n}" — use "default" or "durable_object"`);return n==="durable_object"?n:void 0},H=(t,e,r,n)=>{if(r!==void 0&&A.includes(t))throw a(e,`container "${n}": \`${t}\` is not supported with schedulingPolicy "durable_object"`);if(r===void 0&&t==="images")throw a(e,`container "${n}": \`images\` needs schedulingPolicy "durable_object"`)},J=(t,e,r,n)=>{const{base:i,policy:s}=r;switch(t){case"buildArgs":{i.buildArgs=U(e,n);break}case"enableInternet":{i.enableInternet=N(e);break}case"image":{r.scheduled||(s.image=w(e,n));break}case"images":{s.images=W(e,n);break}case"instanceType":{i.instanceType=q(e,n);break}case"maxInstances":{s.maxInstances=h(e,n,"maxInstances");break}case"name":{i.name=f(e,n,"name");break}case"rollout":{s.rollout=x(e,n);break}case"sleepAfter":{i.sleepAfter=Y(e);break}}},X=(t,e,r)=>{const n=t.findLast(([s])=>s==="image")?.[1];if(n===void 0||!(o.isStringLiteral(n)||o.isNoSubstitutionTemplateLiteral(n)))return;const i=n.getLiteralValue();if(!Object.hasOwn(e??{},i)&&!j(i))throw a(n,`container "${r}": \`image\` "${i}" must name an entry of \`images\` or a Cloudflare-managed "cloudflare/…" image`)},Q=(t,e)=>{const r=t.getArguments()[0];if(!r||!o.isObjectLiteralExpression(r))throw a(t,`container "${e}": defineContainer must be passed an inline object literal`);const n=m(r,M,`container "${e}"`),i=G(n,e),s={base:{bindingName:T(e),className:P(e),exportName:e},policy:{},scheduled:i!==void 0};for(const[u,g]of n)H(u,g,i,e),J(u,g,s,e);const{base:l,policy:c}=s;if(i==="durable_object")return X(n,c.images,e),{...l,...c.images===void 0?{}:{images:c.images},schedulingPolicy:i};if(c.image===void 0)throw a(r,`container "${e}": defineContainer requires a static \`image\` property`);return{...l,image:c.image,...c.maxInstances===void 0?{}:{maxInstances:c.maxInstances},...c.rollout===void 0?{}:{rollout:c.rollout}}},Z=t=>{const e=[],r=new Map;for(const n of t.getVariableDeclarations()){if(!n.isExported())continue;const i=n.getInitializer();if(i?.getKind()!==d.CallExpression)continue;const s=i,l=s.getExpression();if(!o.isIdentifier(l)||!D(l))continue;const c=n.getNameNode();if(!o.isIdentifier(c))throw a(c,"defineContainer exports must be plain named exports (no destructuring)");const u=Q(s,c.getText()),g=r.get(u.bindingName);if(g!==void 0)throw a(c,`containers "${g}" and "${u.exportName}" both map to the binding ${u.bindingName} — rename one so each container gets its own Durable Object binding`);r.set(u.bindingName,u.exportName),e.push(u)}return e},oe=(t,e)=>{const r=S(e,C);if(!$(r))return[];const n=t.getSourceFile(r)??t.addSourceFileAtPath(r),i=Z(n);return i.sort((s,l)=>s.exportName.localeCompare(l.exportName)),i};export{C as CONTAINERS_FILENAME,oe as discoverContainers};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{NODE_CAPABILITIES as f,CLOUDFLARE_CAPABILITIES as h,CELLD_CAPABILITIES as v}from"@lunora/platform";import{readProjectConfigLiterals as m}from"./loadProjectConfig-CKsFNgn3.mjs";const c="cloudflare",b=t=>{const{target:e}=m(t);return e!==void 0&&e.length>0?e:void 0},L=(t,e)=>e??b(t)??c,x=(t,e)=>{if(e!==void 0)return[];const{target:a,unreadable:r}=m(t);return r!==!0||a!==void 0?[]:[{level:"warn",message:`lunora.config declares a \`target\` that codegen cannot read without evaluating it, so the "${c}" surface was emitted. \`runCodegen\` resolves the target synchronously, which means it reads literals only.`,name:"platform_unreadable_target",remediation:`Write \`target\` as a string literal on the config's default export (\`export default { target: "${c}" }\`), or pass \`--target\`.`,target:c}]},u={celld:v,cloudflare:h,node:f},C=()=>Object.keys(u).toSorted((t,e)=>t.localeCompare(e)),w={access:null,ai:"ai",analytics:"analytics",browser:"browser",container:"containers",flags:null,hyperdrive:"hyperdrive",images:"images",kv:"keyValueStore",mail:"mail",notify:null,payments:null,pipelines:"pipelines",r2sql:null,scheduler:"scheduler",storage:"objectStorage",vectors:"vectorStore",workflows:"workflows",x402:null},S=["agents","commitOrderedTables","containerEgressPolicy","containerRuntimeScheduling","cronTriggers","crossShardFanout","durableStreams","globalTables","queues","relationGraph","secrets","topics","vectorStore","workerLoaders","workflowRollback","workflowSchedules"],g={agents:"durable agents (`defineAgent`)",commitOrderedTables:"commit-ordered tables (`.commitOrdered()`)",containerEgressPolicy:"container egress policies (`defineContainer({ allowedHosts | deniedHosts | interceptHttps })`)",containerRuntimeScheduling:'per-instance container images and snapshots (`defineContainer({ schedulingPolicy: "durable_object" })`)',cronTriggers:"declared cron triggers (`cronJobs()`)",crossShardFanout:"cross-shard fan-out queries (a `.shardBy(...)` schema)",durableStreams:"durable streams (`.stream(handler, { durable: true })`)",globalTables:"global tables (`.global()`)",queues:"queues (`defineQueue`)",relationGraph:"relation-graph traversal (`ctx.db.related`, derived from `v.id(...)` columns)",secrets:"the secrets store (`ctx.secrets`)",topics:"pub/sub topics (`defineTopic` / `defineSubscription`)",vectorStore:"vector indexes (`.vectorize()`)",workerLoaders:"sandboxed agent scripts (`jsCodeTool`, on Worker Loaders)",workflowRollback:"workflow step rollback (`defineStep({ rollback })`)",workflowSchedules:"scheduled workflow instances (`defineWorkflow({ schedules })`)"},y=(t,e,a)=>({level:"error",message:`${e.name} does not support ${g[t]}, which this app declares.`,name:"platform_unsupported_feature",remediation:`Remove the declaration, or deploy to a target whose capability matrix marks "${t}" as native or emulated.`,target:a}),T=(t,e,a)=>({level:"error",message:`${e.name}'s capability matrix does not declare a support level for ${g[t]}, which this app declares. Treated as unsupported.`,name:"platform_undeclared_feature",remediation:`Rate "${t}" in the ${e.name} capability matrix as "native", "emulated", or "unsupported" — an undeclared feature fails closed rather than letting the app deploy onto a primitive the host may not provide.`,target:a}),k=t=>{const{diagnostics:e,gatedSignals:a,matrix:r,reported:n,signals:d,target:i}=t;for(const s of S){if(d[s]!==!0)continue;const o=r.features[s]?.level;o!=="unsupported"&&o!==void 0||(a[s]=!1,!n.has(s)&&e.push(o==="unsupported"?y(s,r,i):T(s,r,i)))}},_=(t,e,a,r={})=>{const n={...t},d={...r},i=[],s=new Set;for(const[o,l]of Object.entries(w)){if(l===null||!t[o])continue;const p=e.features[l]?.level;p==="unsupported"?(n[o]=!1,s.add(l),i.push({feature:o,level:"error",message:`${e.name} does not support "${o}" (ctx.${o}).`,name:"platform_unsupported_feature",remediation:`Remove the ctx.${o} usage, or deploy to a target whose capability matrix marks "${l}" as native or emulated.`,target:a})):p===void 0&&(n[o]=!1,s.add(l),i.push({feature:o,level:"error",message:`${e.name}'s capability matrix does not declare a support level for "${o}" (ctx.${o}). Treated as unsupported.`,name:"platform_undeclared_feature",remediation:`Rate "${l}" in the ${e.name} capability matrix as "native", "emulated", or "unsupported" — an undeclared feature fails closed rather than shipping a surface the host may not provide.`,target:a}))}return k({diagnostics:i,gatedSignals:d,matrix:e,reported:s,signals:r,target:a}),{diagnostics:i,signals:d,usage:n}},E=(t,e,a={})=>{const r=u[e];return r===void 0?{diagnostics:[{level:"error",message:`Unknown deploy target "${e}" — no capability matrix is registered for it. Codegen emitted the full Cloudflare surface un-gated.`,name:"platform_unknown_target",remediation:`Use a registered target (${Object.keys(u).join(", ")}) or install the target's @lunora/platform-${e} package.`,target:e}],signals:{...a},usage:{...t}}:_(t,r,e,a)},I=t=>{const e=u[t];if(e===void 0)return;const a=Object.entries(e.features).filter(([,r])=>r.level==="unsupported").map(([r])=>r).toSorted((r,n)=>r.localeCompare(n));return{id:e.id,name:e.name,unsupported:a}};export{w as CAPABILITY_TO_FEATURE,c as DEFAULT_TARGET,_ as gateAgainstMatrix,E as gatePlatformFeatures,C as platformMatrixIds,b as readProjectTarget,x as readTargetDiagnostics,L as resolveCodegenTarget,I as studioPlatformFor};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{existsSync as g}from"node:fs";import{join as b}from"node:path";import{LunoraError as f}from"@lunora/errors";import{queueDefaultName as y,queueBindingName as h}from"@lunora/queue";import{SyntaxKind as q,Node as a}from"ts-morph";import{diagnosticAt as c}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{findObjectProperty as d,stringPropertyFor as w}from"./listLunoraSourceFiles-DP-5e-RE.mjs";const N="queues.ts",x=i=>{const t=e=>e==="defineQueue"||e==="defineSubscription"||e==="defineTopic",o=i.getSymbol();if(!o){const e=i.getText();return t(e)?e:void 0}for(const e of o.getDeclarations()){if(!a.isImportSpecifier(e))continue;if(e.getImportDeclaration().getModuleSpecifierValue()!=="@lunora/queue")return;const r=e.getNameNode().getText();return t(r)?r:void 0}},p=w("queue"),E=(i,t,o)=>{if(a.isNumericLiteral(i))return i.getLiteralValue();throw c(i,`queue "${t}": \`${o}\` must be a static numeric literal — it is deploy configuration codegen writes into wrangler.jsonc`)},S=(i,t)=>{const o=d(i,"name");if(!o||!a.isPropertyAssignment(o))return;const e=p(o.getInitializerOrThrow(),t,"name");if(e.length===0)throw c(o,`queue "${t}": \`name\` must be a non-empty string when provided`);return e},l=(i,t,o)=>{const e={bindingName:h(t),exportName:t,mode:"push",name:S(i,t)??y(t),...o===void 0?{}:{topic:o},tuning:{}},r=d(i,"mode");if(r&&a.isPropertyAssignment(r)){if(o!==void 0)throw c(r,`subscription "${t}": \`mode\` is not allowed — a subscription is always a push consumer`);const s=p(r.getInitializerOrThrow(),t,"mode");if(s!=="push"&&s!=="pull")throw c(r,`queue "${t}": \`mode\` must be "push" or "pull" (got ${JSON.stringify(s)})`);e.mode=s}const n=d(i,"deadLetterQueue");n&&a.isPropertyAssignment(n)&&(e.tuning.deadLetterQueue=p(n.getInitializerOrThrow(),t,"deadLetterQueue"));for(const s of["maxBatchSize","maxBatchTimeout","maxRetries","retryDelay"]){const u=d(i,s);u&&a.isPropertyAssignment(u)&&(e.tuning[s]=E(u.getInitializerOrThrow(),t,s))}return e},v=(i,t)=>{const o=i.getArguments()[0];if(!o||!a.isObjectLiteralExpression(o))throw c(i,`queue "${t}": defineQueue must be passed an inline object literal`);return l(o,t,void 0)},$=(i,t,o)=>{const[e,r]=i.getArguments();if(!e||!a.isIdentifier(e)||!o.has(e.getText()))throw c(e??i,`subscription "${t}": the first argument must name a \`defineTopic()\` export of lunora/queues.ts`);if(!r||!a.isObjectLiteralExpression(r))throw c(i,`subscription "${t}": defineSubscription must be passed an inline object literal`);return l(r,t,e.getText())},I=i=>{const t=[];for(const o of i.getVariableDeclarations()){if(!o.isExported())continue;const e=o.getInitializer();if(e?.getKind()!==q.CallExpression)continue;const r=e,n=r.getExpression(),s=a.isIdentifier(n)?x(n):void 0;if(s===void 0)continue;const u=o.getNameNode();if(!a.isIdentifier(u))throw c(u,`${s} exports must be plain named exports (no destructuring)`);t.push({call:r,exportName:u.getText(),factory:s})}return t},P=i=>{const t=I(i),o=new Set(t.filter(n=>n.factory==="defineTopic").map(n=>n.exportName)),e=[];for(const n of t)n.factory==="defineQueue"?e.push(v(n.call,n.exportName)):n.factory==="defineSubscription"&&e.push($(n.call,n.exportName,o));const r=[...o].map(n=>({exportName:n}));return{queues:e,topics:r}},T=i=>{const t=new Map,o=new Map;for(const e of i){const r=t.get(e.name);if(r!==void 0)throw new f("DUPLICATE_QUEUE_NAME",`Duplicate queue name "${e.name}": produced by both "${r}" and "${e.exportName}". Deployed queue names must be unique across the project.`,{status:500});t.set(e.name,e.exportName);const n=o.get(e.bindingName);if(n!==void 0)throw new f("DUPLICATE_QUEUE_BINDING",`Duplicate queue binding "${e.bindingName}": produced by both "${n}" and "${e.exportName}". Queue export names must yield unique binding names.`,{status:500});o.set(e.bindingName,e.exportName)}},A=(i,t)=>{const o=b(t,N);if(!g(o))return{queues:[],topics:[]};const e=i.getSourceFile(o)??i.addSourceFileAtPath(o),{queues:r,topics:n}=P(e),s=r.toSorted((u,m)=>u.exportName.localeCompare(m.exportName));return T(s),{queues:s,topics:n.toSorted((u,m)=>u.exportName.localeCompare(m.exportName))}},j=(i,t)=>A(i,t).queues;export{N as QUEUES_FILENAME,A as discoverQueueDeclarations,j as discoverQueues};
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import{existsSync as w,mkdirSync as ks,readFileSync as Ut,writeFileSync as Ms,rmSync as Ks}from"node:fs";import{join as S,dirname as ce}from"node:path";import{performance as Ie}from"node:perf_hooks";import{runAdvisor as _s}from"@lunora/advisor";import{LunoraError as $}from"@lunora/errors";import{SyntaxKind as l,Node as o,VariableDeclarationKind as zs,Project as ft}from"ts-morph";import{serializeSchemaSnapshot as $s}from"./SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs";import{toAdvisorContext as Us}from"./formatAdvisories-DwmUKYuc.mjs";import{readProjectConfigLiterals as Bs}from"./loadProjectConfig-CKsFNgn3.mjs";import{s as qs}from"./paths-C-9fwEgQ.mjs";import{C as le}from"./capabilities-DJJWVEtk.mjs";import{isD1GlobalTable as Bt,isHyperdriveGlobalTable as qt}from"./isD1GlobalTable-udvHAAzD.mjs";import{discoverAgents as js}from"./AGENTS_FILENAME-Bb2jxbOa.mjs";import{discoverContainers as Vs}from"./CONTAINERS_FILENAME-CGB4bqUr.mjs";import Ws from"./discoverCrons-0lNudk0S.mjs";import{diagnosticAt as ee}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{b as me}from"./module-specifiers-WF8iAydP.mjs";import{listLunoraSourceFiles as m,bindingKeyName as Q,propertyKeyName as y,unwrapExpression as X,listSecurityScanFiles as he,objectLiteralFromCallbackBody as jt,propertyInitializer as P,lunoraRelativePath as x,collectCallRows as F,findObjectProperty as C,collectSecurityCallRows as Hs,limitNameOf as Vt,optionsObjectLiteral as Wt,isContextIdentifier as Oe,handlerOf as Gs,isDatabaseAccessor as _,readTargetOf as Ht,enclosingExportName as Ys}from"./listLunoraSourceFiles-DP-5e-RE.mjs";import Qs from"./readPackageDependencies-C6h6FZuP.mjs";import{discoverQueueDeclarations as Xs}from"./QUEUES_FILENAME-BzOl92QK.mjs";import{discoverSandboxUsage as Zs}from"./discoverSandboxUsage-CrjZ6yNg.mjs";import Js from"./discoverStorageRulesMetadata-D8VYflWt.mjs";import{a as b,c as z,d as Gt,e as en}from"./classify-procedure-call-BztLe76A.mjs";import{discoverWorkflows as tn}from"./WORKFLOWS_FILENAME-DNaUHGS8.mjs";import{i as sn}from"./ir-DBSvhNa-.mjs";import{gatePlatformFeatures as nn,resolveCodegenTarget as Yt,readTargetDiagnostics as rn,studioPlatformFor as on}from"./DEFAULT_TARGET-wK6-Tado.mjs";import{b as Qt,e as an}from"./shard-BVzXMtWg.mjs";import cn from"./emitServer-pF_fhA82.mjs";import{emitDataModel as ln}from"./emitDataModel-D3WuEZ4b.mjs";import{i as M,a as U,e as A,r as un,b as dn,s as ve,c as fn,f as gn,d as pn}from"./queries-B-f4jO-x.mjs";import{r as xe,s as mn}from"./parse-validator-C94Yiabo.mjs";import hn from"./discoverAuthApiCalls-FxrdBeVt.mjs";import{i as vn,a as xn,e as En,b as Sn,d as yn,c as An}from"./unwrap-handler-return-CoV_GK33.mjs";import bn from"./discoverFunctions-BsmX-sEq.mjs";import Nn from"./discoverHttpRoutes-BcXI9CNt.mjs";import Pn from"./discoverHyperdriveCalls-D9qXqTq3.mjs";import wn from"./discoverInserts-CFJ3IVeI.mjs";import{m as Ke,a as de,s as Xt,d as In}from"./index-BoaHhVtM.mjs";import{e as Zt}from"./exported-procedure-chains-CmCDiPBV.mjs";import Tn from"./discoverMigrations-DbrHwcGE.mjs";import{MUTATORS_FILENAME as Cn,isDefineMutatorCallee as Fn,discoverMutators as On}from"./MUTATORS_FILENAME-B6cKrN_m.mjs";import Rn from"./discoverNondeterministicCalls-CSQ_GDcA.mjs";import{discoverNotifyConfig as Ln,discoverNotifyCalls as Dn}from"./NOTIFY_FILENAME-Cri3NT5U.mjs";import kn from"./discoverR2sqlCalls-fu7fC0i_.mjs";import Mn from"./discoverRlsProcedures-BO4qC77y.mjs";import Kn from"./discoverRlsMetadata-CPmAGL0W.mjs";import _n from"./discoverSchema-D8DBDHEg.mjs";import{secretKindOf as zn,redact as $n,isHeuristicSecretKind as Un,isSecretishName as Bn}from"./redact-Cy14LEnc.mjs";import{discoverShapes as qn}from"./SHAPES_FILENAME-zJgzynXR.mjs";import{emitApp as jn}from"./emitApp-D_9NVcvv.mjs";import{buildOpenApiDocument as Vn,emitOpenApiModule as Wn}from"./buildOpenApiDocument-nYvBhjxu.mjs";import{buildOpenRpcDocument as Hn,emitOpenRpcModule as Gn}from"./OPENRPC_VERSION-Cl6P9WGv.mjs";import{buildSchemaSnapshot as Yn}from"./SchemaSnapshotParseError-CPOXlFhI.mjs";import{emitCollections as Qn,emitSeed as Xn,emitApi as Zn}from"./emitApi-DdW9RyGG.mjs";import{B as Jn,C as er,A as tr,D as sr}from"./shard-runtime-oIXHEMU7.mjs";import{emitCrons as nr,emitScheduler as rr,emitShardRegistry as ir,emitVectors as or,emitWranglerCronTriggers as ar}from"./emitCrons-BRKXFGFu.mjs";import cr from"./emitDrizzleSchema-Cv0HtLR3.mjs";import lr from"./emitFunctions-BgNeOZt_.mjs";const gt={error:"ERROR",info:"INFO",warn:"WARN"},pt={ERROR:2,INFO:0,WARN:1},ur=e=>({cacheKey:"advisor_min_severity_invalid",categories:["SCHEMA"],description:"`advisor.minSeverity` in `lunora.config.*` sets the lowest advisory level codegen reports and writes into `_generated/shard.ts`. Codegen reads it by parsing the file, so it has to be a string literal.",detail:e,facing:"INTERNAL",level:"WARN",metadata:{},name:"advisor_min_severity_invalid",remediation:'Set `advisor: { minSeverity: "info" | "warn" | "error" }` as a literal on the config\'s default export.',title:"`advisor.minSeverity` is not a level codegen can read, so every advisory was reported"}),dr=(e,t)=>{const{advisor:s}=Bs(e);if(s===void 0||s.minSeverity===void 0&&s.unreadable!==!0)return[...t];const{minSeverity:n}=s,r=n!==void 0&&Object.hasOwn(gt,n)?gt[n]:void 0;return r===void 0?[...t,ur(n===void 0?"`advisor.minSeverity` is not a string literal codegen can read without evaluating the config: a computed value or key, or a spread that could set or override it.":`\`advisor.minSeverity\` is "${n}", which is not one of "info", "warn" or "error".`)]:t.filter(i=>pt[i.level]>=pt[r])},mt=(e,t="api")=>{const s=new Map;for(const n of e){const r=qs(n),i=s.get(r);if(i===void 0){s.set(r,n);continue}if(i!==n){const a=t==="api"?`the generated api.ts would declare "${r}" twice and the dispatch key "${r}:<fn>" would be ambiguous`:`the generated api.ts would declare "${r}" twice in HttpStreamsRef and again in the httpStreams object literal`;throw new $("INTERNAL",`@lunora/codegen: "${i}" and "${n}" both map to the ${t} namespace "${r}" — ${a}. Rename one file so the two differ by more than a non-identifier character (\`-\`, \`.\`, \`/\` and \`_\` all sanitize to \`_\`).`,{status:500})}}},fr=(e,t={})=>{const{hasVectors:s=!0,scheduler:n=!1,storage:r=!1,usage:i}=t,a=[];e.tables.some(c=>Bt(c))&&a.push({name:"@lunora/d1",reason:"`.global()` tables are D1-backed, so `_generated/app.ts` imports the D1 `ctx.db` adapter"}),e.tables.some(c=>qt(c))&&a.push({name:"@lunora/hyperdrive",reason:'`.global({ backend: "hyperdrive" })` tables route through `@lunora/hyperdrive/global`'},{name:"@lunora/sql-store",reason:'`.global({ backend: "hyperdrive" })` makes `_generated/app.ts` import the `SqlCtxDbOptions` / `SqlExec` types'}),n&&a.push({name:"@lunora/scheduler",reason:"a declared cron (or `ctx.scheduler` use) makes `_generated/app.ts` import `createScheduler`"}),r&&a.push({name:"@lunora/storage",reason:"a `v.storage()` column, a storage access rule (or `ctx.storage` use) makes `_generated/app.ts` import `createStorage`"}),e.vectorIndexes.length>0&&s&&a.push({name:"@lunora/bindings",reason:"`.vectorize()` indexes make `_generated/shard.ts` import `@lunora/bindings/vectors`"});for(const c of i===void 0?[]:le)c.requiredPackage!==void 0&&i?.[c.key]===!0&&a.push({name:c.requiredPackage,reason:`\`ctx.${c.contextProperty??c.key}\` usage makes \`_generated/\` import \`${c.moduleSpecifier}\``});return a.filter((c,u)=>a.findIndex(d=>d.name===c.name)===u)},gr=(e,t,s={})=>{if(t===void 0)return;const n=fr(e,s).filter(i=>!t.has(i.name));if(n.length===0)return;const r=n.map(i=>` - ${i.name} — ${i.reason}`).join(`
|
|
2
|
+
`);throw new $("INTERNAL",`@lunora/codegen: this schema's generated code imports packages the project does not declare:
|
|
3
|
+
${r}
|
|
4
|
+
|
|
5
|
+
Install them with your package manager, then re-run codegen.`)},pr="env.ts",mr=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineEnv";for(const s of t.getDeclarations())if(o.isImportSpecifier(s))return me(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineEnv":!1;return!1},hr=e=>{const t=e.getSymbol();if(!t)return!1;for(const s of t.getDeclarations()){if(!o.isNamespaceImport(s))continue;const n=s.getFirstAncestorByKind(l.ImportDeclaration);return n!==void 0&&me(n.getModuleSpecifierValue())}return!1},vr=e=>{if(o.isIdentifier(e))return mr(e);if(o.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineEnv"&&o.isIdentifier(t)&&hr(t)}return!1},xr=e=>{const t=[];for(const s of e.getVariableDeclarations()){if(!s.isExported())continue;const n=s.getInitializer();if(n?.getKind()!==l.CallExpression||!vr(n.getExpression()))continue;const i=s.getNameNode();if(!o.isIdentifier(i))throw ee(i,"defineEnv exports must be plain named exports (no destructuring)");t.push({exportName:i.getText()})}return t},Er=(e,t)=>{const s=S(t,pr);if(!w(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s),r=xr(n);if(r.length!==0){if(r.length>1)throw ee(n,`lunora/env.ts declares ${r.length.toString()} defineEnv() contracts (${r.map(i=>i.exportName).join(", ")}); exactly one is allowed`);return r[0]}},ht="ctx",Jt=e=>{const t=new Set,s=new Set([ht]),n=i=>{if(o.isObjectBindingPattern(i))for(const a of i.getElements()){const c=Q(a);c&&t.add(c)}};for(const i of e.getDescendantsOfKind(l.BindingElement)){if(Q(i)!==ht)continue;const a=i.getNameNode();o.isIdentifier(a)?s.add(a.getText()):n(a)}const r=i=>o.isIdentifier(i)&&s.has(i.getText());for(const i of e.getDescendantsOfKind(l.PropertyAccessExpression))r(i.getExpression())&&t.add(i.getName());for(const i of e.getDescendantsOfKind(l.VariableDeclaration)){const a=i.getInitializer();a!==void 0&&r(a)&&n(i.getNameNode())}return t},Sr=(e,t)=>{const s=Object.fromEntries(le.map(n=>[n.key,!1]));for(const n of m(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n),i=new Set(r.getImportDeclarations().map(c=>c.getModuleSpecifierValue())),a=Jt(r);for(const c of le)if(!s[c.key]){if(i.has(c.moduleSpecifier)){s[c.key]=!0;continue}c.contextProperty!==void 0&&a.has(c.contextProperty)&&(s[c.key]=!0)}if(le.every(c=>s[c.key]))break}return s},es="identity.ts",yr=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineIdentity";for(const s of t.getDeclarations())if(o.isImportSpecifier(s))return me(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineIdentity":!1;return!1},Ar=e=>{const t=e.getSymbol();if(!t)return!1;for(const s of t.getDeclarations()){if(!o.isNamespaceImport(s))continue;const n=s.getFirstAncestorByKind(l.ImportDeclaration);return n!==void 0&&me(n.getModuleSpecifierValue())}return!1},br=e=>{if(o.isIdentifier(e))return yr(e);if(o.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineIdentity"&&o.isIdentifier(t)&&Ar(t)}return!1},Nr=e=>{const t=[];for(const s of e.getVariableDeclarations()){if(!s.isExported())continue;const n=s.getInitializer();if(n?.getKind()!==l.CallExpression||!br(n.getExpression()))continue;const i=s.getNameNode();if(!o.isIdentifier(i))throw ee(i,"defineIdentity exports must be plain named exports (no destructuring)");t.push({exportName:i.getText()})}return t},Pr=(e,t)=>{const s=S(t,es);if(!w(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s),r=Nr(n);if(r.length!==0){if(r.length>1)throw ee(n,`lunora/identity.ts declares ${r.length.toString()} defineIdentity() contracts (${r.map(i=>i.exportName).join(", ")}); exactly one is allowed`);return r[0]}},wr=new Set(["allowedHosts","deniedHosts","interceptHttps"]),Ir=(e,t)=>{const s=X(t);if(s===void 0||!o.isIdentifier(s))return s;const n=s.getText();return X(e.getDescendantsOfKind(l.VariableDeclaration).find(r=>r.getName()===n)?.getInitializer())},Tr=(e,t)=>e!==void 0&&o.isObjectLiteralExpression(e)&&e.getProperties().some(s=>{if(o.isShorthandPropertyAssignment(s))return t.has(y(s));if(!o.isPropertyAssignment(s)||!t.has(y(s)))return!1;const n=X(s.getInitializer())?.getText();return n!=="false"&&n!=="undefined"}),Cr=new Set(["durable"]),Fr=new Set(["rollback"]),Or=e=>{const t=e.getExpression();return o.isPropertyAccessExpression(t)?t.getName():t.getText()},Rr=new Map([["defineContainer",{keys:wr,signal:"containerEgressPolicy"}],["defineStep",{keys:Fr,signal:"workflowRollback"}],["stream",{keys:Cr,signal:"durableStreams"}]]),Lr=(e,t)=>{const s=Rr.get(Or(t));if(s!==void 0)return t.getArguments().some(n=>Tr(Ir(e,n),s.keys))?s.signal:void 0},Dr=(e,t)=>{const s={containerEgressPolicy:!1,durableStreams:!1,secrets:!1,workflowRollback:!1};for(const n of m(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.secrets||(s.secrets=Jt(r).has("secrets"));for(const i of r.getDescendantsOfKind(l.CallExpression)){const a=Lr(r,i);a!==void 0&&(s[a]=!0)}if(Object.values(s).every(Boolean))break}return s},kr="createWorker",Mr="extend",vt=e=>e!==void 0&&(o.isStringLiteral(e)||o.isNoSubstitutionTemplateLiteral(e))?e.getLiteralValue():void 0,xt=e=>{const t=[],s=vt(P(e,"backupCron"));s!==void 0&&t.push(s);const n=P(e,"crons");if(n===void 0||!o.isObjectLiteralExpression(n))return t;for(const r of n.getProperties()){if(!o.isPropertyAssignment(r)&&!o.isMethodDeclaration(r))continue;const i=vt(r.getNameNode());i!==void 0&&t.push(i)}return t},Kr=e=>{const t=b(e.getExpression()),[s]=e.getArguments();if(s===void 0)return[];if(t===kr)return o.isObjectLiteralExpression(s)?xt(s):[];if(t!==Mr||!(o.isArrowFunction(s)||o.isFunctionExpression(s)))return[];const n=jt(s.getBody());return n===void 0?[]:xt(n)},_r=(e,t)=>{const s=[];for(const{filePath:n}of he(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const i of r.getDescendantsOfKind(l.CallExpression))s.push(...Kr(i))}return[...new Set(s)]},ts=e=>{if(e.kind==="id")return e.tableName;if(!(e.kind!=="array"&&e.kind!=="optional"))return e.inner===void 0?void 0:ts(e.inner)},zr=e=>{const t=new Set(e.tables.map(s=>s.name));return e.tables.some(s=>Object.values(s.shape).some(n=>{const r=ts(n);return r!==void 0&&t.has(r)}))},$r=(e,t)=>{const s=new Map,n=new Map;for(const r of e)s.set(r.name,`workflow "${r.exportName}"`),n.set(r.className,`workflow "${r.exportName}"`);for(const r of t){const i=s.get(r.name);if(i!==void 0)throw new $("DUPLICATE_WORKFLOW_NAME",`Duplicate deployed name "${r.name}": produced by both ${i} and agent "${r.exportName}". Workflow and agent names share one account-wide namespace and must be unique together.`,{status:500});const a=n.get(r.className);if(a!==void 0)throw new $("DUPLICATE_WORKFLOW_CLASS",`Duplicate generated class "${r.className}": produced by both ${a} and agent "${r.exportName}". Workflow and agent export names must yield unique generated class names.`,{status:500})}},Ur=e=>{const{lunoraDirectory:t,project:s,projectRoot:n,schema:r}=e,i=Pr(s,t),a=Er(s,t),c=tn(s,t),{queues:u,topics:d}=Xs(s,t),g=js(s,t);$r(c,g);const h=Vs(s,t),O=Js(s,t),R=Ws(s,t,c,g),p=_r(s,t),T=Dr(s,t),N=Zs(s,t),L=Sr(s,t);L.browser=L.browser||N.usesSandboxBrowser;const D=nn(L,Yt(n,e.target),{agents:g.length>0,commitOrderedTables:r.tables.some(E=>E.commitOrdered===!0),cronTriggers:R.length>0,crossShardFanout:r.tables.some(E=>sn(E)),containerEgressPolicy:T.containerEgressPolicy,containerRuntimeScheduling:h.some(E=>E.schedulingPolicy==="durable_object"),durableStreams:T.durableStreams,globalTables:r.tables.some(E=>E.shardMode==="global"),queues:u.length>0,relationGraph:zr(r),secrets:T.secrets,topics:d.length>0,vectorStore:r.vectorIndexes.length>0,workerLoaders:N.usesSandboxLoader,workflowRollback:T.workflowRollback,workflowSchedules:c.some(E=>E.schedules!==void 0)}),v=D.usage,q=D.signals.vectorStore!==!1,j=Qs(n),te=j??new Set,se=te.has("lunorash");gr(r,j,{hasVectors:q,scheduler:v.scheduler||R.length>0,storage:v.storage||O.rules.length>0||Object.keys(Qt(r)).length>0,usage:v});const K=w(S(t,"flags.ts")),k=w(S(t,"notify.ts"));return{agents:g,containers:h,crons:R,dataModelContent:ln(r),declaredDependencies:j,dependencies:te,entryCronTriggers:p,env:a,featureUsage:v,hasFlags:K,hasNotify:k,identity:i,platformGate:{...D,diagnostics:[...rn(n,e.target),...D.diagnostics]},queues:u,serverContent:cn({agents:g,containers:h,env:a,hasAccessFacade:v.access,hasAi:v.ai,hasAnalytics:v.analytics,hasBrowser:v.browser,hasVectors:q,hasFlags:K,hasHyperdrive:v.hyperdrive,hasImages:v.images,hasKv:v.kv,hasNotify:k,hasPayments:v.payments,hasPipelines:v.pipelines,hasR2sql:v.r2sql,hasX402:v.x402,identity:i,queues:u,schema:r,storageRuleBuckets:O.rules.map(E=>E.bucket),topics:d,useUmbrella:se,workflows:c}),storageRulesMetadata:O,topics:d,usesSandbox:N.usesSandboxBrowser||N.usesSandboxContainer||N.usesSandboxFs,useUmbrella:se,workflows:c}},ss=new Set(["delete","get","head","options","patch","post","put"]),Br=new Set(["handler","stream"]),qr=/\/(?:_|admin|internal|superuser|sudo|root|debug)/iu,Et=new Set(["ADMIN_TOKEN","adminToken","assertAdmin","assertAuth","auth","Authorization","getSession","identity","isAdmin","requireAdmin","requireAuth","requireRole","verifyAdmin"]),jr=e=>{if(!o.isCallExpression(e))return;const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||!ss.has(t.getName()))return;const s=t.getExpression();if(!o.isIdentifier(s)||s.getText()!=="httpRoute")return;const n=e.getArguments()[0];if(!(!n||!o.isStringLiteral(n)))return{method:t.getName().toUpperCase(),path:n.getLiteralValue()}},Vr=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t))return;let s=t.getExpression();for(;o.isCallExpression(s);){const n=s.getExpression();if(!o.isPropertyAccessExpression(n)||ss.has(n.getName()))break;s=n.getExpression()}return jr(s)},Wr=e=>{for(const t of e.getDescendantsOfKind(l.PropertyAccessExpression))if(Et.has(t.getName()))return!0;for(const t of e.getDescendantsOfKind(l.CallExpression)){const s=t.getExpression();if(o.isIdentifier(s)&&Et.has(s.getText()))return!0}return!1},Hr=(e,t)=>{const s=e.getInitializer();if(!s||!o.isCallExpression(s))return;const n=s.getExpression();if(!o.isPropertyAccessExpression(n)||!Br.has(n.getName()))return;const r=Vr(s);if(!r||!qr.test(r.path))return;const i=s.getArguments()[0],a=i!==void 0&&(o.isArrowFunction(i)||o.isFunctionExpression(i))&&Wr(i);return{exportName:e.getName(),file:t,method:r.method,path:r.path,usesGuard:a}},Gr=(e,t)=>{const s=[];for(const n of e.getVariableStatements())if(n.isExported())for(const r of n.getDeclarations()){const i=Hr(r,t);i&&s.push(i)}return s},Yr=(e,t)=>{const s=[];for(const n of m(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Gr(r,x(t,n)))}return s},Qr=e=>!o.isPropertyAccessExpression(e)||e.getName()!=="run"?!1:e.getExpression().getText()==="ctx.ai",Xr=(e,t)=>{if(!Qr(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!M(s)||U(s)))return{exportName:A(e),file:t,line:e.getStartLineNumber()}},Zr=(e,t)=>F(e,t,Xr),Jr=new Set(["generateText","streamText"]),ei=new Set(["messages","prompt","system"]),ti=[{methods:new Set(["delete","insert","insertManyUnsafe","patch","replace"]),prefixes:["context.db","ctx.db"]},{methods:new Set(["run","runAction","runMutation"]),prefixes:["context","ctx"]},{methods:new Set(["fetch"]),prefixes:["context","ctx"]},{methods:new Set(["queue","send"]),prefixes:["context.email","context.mail","ctx.email","ctx.mail"]}],si=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t))return;const s=t.getName(),n=t.getExpression().getText();for(const r of ti)if(r.methods.has(s)&&r.prefixes.some(i=>n===i||n.startsWith(`${i}.`)))return`${n}.${s}`},ni=e=>{for(const t of e.getDescendantsOfKind(l.CallExpression)){const s=si(t);if(s!==void 0)return s}},ri=e=>{const t=new Set,s=e.getFirstAncestor(i=>o.isArrowFunction(i)||o.isFunctionExpression(i)||o.isFunctionDeclaration(i)),[n]=s?.getParameters()??[],r=n?.getNameNode();if(r===void 0||!o.isObjectBindingPattern(r))return t;for(const i of r.getElements()){const a=Q(i),c=i.getNameNode();if(a==="args"&&o.isObjectBindingPattern(c))for(const u of c.getElements())t.add(u.getName())}return t},ii=e=>{if(un(e))return!0;const t=ri(e);return t.size===0?!1:e.getDescendantsOfKind(l.Identifier).some(s=>t.has(s.getText()))},oi=e=>{for(const t of e.getProperties()){if(!o.isPropertyAssignment(t)||!ei.has(y(t)))continue;const s=t.getInitializer();if(s!==void 0&&ii(s))return!0}return!1},ai=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression)){const r=b(n.getExpression());if(r===void 0||!Jr.has(r))continue;const[i]=n.getArguments();if(i===void 0||!o.isObjectLiteralExpression(i))continue;let a;for(const c of i.getDescendantsOfKind(l.CallExpression))if(b(c.getExpression())==="tool"&&(a=ni(c),a!==void 0))break;a!==void 0&&s.push({exportName:A(n),file:t,line:n.getStartLineNumber(),method:r,sideEffect:a,userInputDerived:oi(i)})}return s},ci=(e,t)=>{const s=[];for(const n of m(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...ai(r,x(t,n)))}return s},li=e=>{if(!o.isPropertyAccessExpression(e)||e.getName()!=="fetch")return!1;const t=e.getExpression();return o.isIdentifier(t)&&t.getText()==="ctx"},ui=(e,t)=>{if(!li(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!M(s)))return{exportName:A(e),file:t,line:e.getStartLineNumber()}},di=(e,t)=>F(e,t,ui),_e=(e,t=new Set)=>{if(t.has(e))return!0;t.add(e);try{return e.getProperties().some(s=>{if(!o.isSpreadAssignment(s))return!1;const n=xe(s.getExpression());return n===void 0||_e(n,t)})}finally{t.delete(e)}},fi=e=>{const t=e.getArguments()[0];if(!t||!o.isObjectLiteralExpression(t))return{objects:[],opaque:!0};const s=C(t,"args");if(!s)return{objects:[],opaque:!1};if(!o.isPropertyAssignment(s))return{objects:[],opaque:!0};const n=s.getInitializer(),r=n===void 0?void 0:xe(n);return r===void 0?{objects:[],opaque:!0}:{objects:[r],opaque:_e(r)}},gi=e=>{const t=[];let s=!1,n=e;for(;o.isCallExpression(n);){const r=n.getExpression();if(!o.isPropertyAccessExpression(r))break;if(r.getName()==="input"){const i=n.getArguments()[0],a=i!==void 0&&o.isExpression(i)?xe(i):void 0;a===void 0?s=!0:(t.push(a),s||=_e(a))}n=r.getExpression()}return{objects:t,opaque:s}},ze=(e,t)=>t?gi(t):fi(e),ns=(e,t)=>{if(t.has(e))return[];t.add(e);try{return e.getProperties().flatMap(s=>{if(o.isSpreadAssignment(s)){const n=xe(s.getExpression());return n===void 0?[]:ns(n,t)}return o.isPropertyAssignment(s)||o.isShorthandPropertyAssignment(s)?[y(s)]:[]})}finally{t.delete(e)}},pi=e=>e.flatMap(t=>ns(t,new Set)),mi=new Set(["check","length","max"]),Re=e=>{if(!o.isCallExpression(e))return;const t=e.getExpression();if(!(!o.isPropertyAccessExpression(t)||t.getExpression().getText()!=="v"))return t.getName()},hi=e=>[e,...e.getDescendants()].filter(t=>Re(t)!==void 0),vi=e=>{let t=e;for(;;){const s=t.getParent();if(!s||!o.isPropertyAccessExpression(s)||s.getExpression()!==t)return!1;const n=s.getParent();if(!n||!o.isCallExpression(n)||n.getExpression()!==s)return!1;if(mi.has(s.getName()))return!0;t=n}},xi=e=>{const t=[],s=[];for(const n of e)for(const r of n.getProperties()){if(!o.isPropertyAssignment(r))continue;const i=r.getInitializer();if(!i)continue;const a=hi(i),c=y(r);a.some(u=>Re(u)==="any")?t.push(c):a.some(u=>Re(u)==="string"&&!vi(u))&&s.push(c)}return{anyArgs:t,unboundedStringArgs:s}},Ei=(e,t)=>{const s=e.getInitializer();if(!s||!o.isCallExpression(s))return;const n=z(s);if(n?.visibility!=="public")return;const{objects:r}=ze(s,n.receiver),{anyArgs:i,unboundedStringArgs:a}=xi(r);if(!(i.length===0&&a.length===0))return{anyArgs:i,exportName:e.getName(),file:t,line:s.getStartLineNumber(),unboundedStringArgs:a}},Si=(e,t)=>{const s=[];for(const n of e.getVariableStatements())if(n.isExported())for(const r of n.getDeclarations()){const i=Ei(r,t);i&&s.push(i)}return s},yi=(e,t)=>{const s=[];for(const n of m(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Si(r,x(t,n)))}return s},Te=e=>e?.getKind()===l.TrueKeyword,Ai=e=>e?.getKind()===l.FalseKeyword,bi=e=>e!==void 0&&o.isNumericLiteral(e)&&e.getLiteralValue()===0,Ni=new Set(["lunoraAuthAdapter","lunoraD1Adapter"]),Pi=e=>!e||!o.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>o.isCallExpression(t)&&b(t.getExpression())==="scim"),wi=e=>e!==void 0&&o.isCallExpression(e)&&Ni.has(b(e.getExpression())??""),Ii=e=>!e||!o.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>o.isStringLiteral(t)&&t.getLiteralText()==="*"),Ti=e=>{const t=P(e,"advanced"),s=P(e,"emailAndPassword"),n=P(e,"session");return{analyzable:!0,disableCsrfCheck:Te(P(t,"disableCSRFCheck")),emailPasswordEnabled:Te(P(s,"enabled")),requireEmailVerification:Te(P(s,"requireEmailVerification")),scimOnNonTransactionalAdapter:Pi(P(e,"plugins"))&&wi(P(e,"database")),secureCookiesDisabled:Ai(P(t,"useSecureCookies")),sessionFreshAgeZero:bi(P(n,"freshAge")),trustedOriginsWildcard:Ii(P(e,"trustedOrigins"))}},Ci=()=>({analyzable:!1,disableCsrfCheck:!1,emailPasswordEnabled:!1,requireEmailVerification:!1,scimOnNonTransactionalAdapter:!1,secureCookiesDisabled:!1,sessionFreshAgeZero:!1,trustedOriginsWildcard:!1}),Fi=(e,t)=>{if(b(e.getExpression())!=="createAuth")return;const s=e.getArguments()[0],n=s!==void 0&&o.isObjectLiteralExpression(s)&&s.getProperties().some(i=>o.isSpreadAssignment(i)),r=s!==void 0&&o.isObjectLiteralExpression(s)&&!n?Ti(s):Ci();return{exportName:A(e),file:t,line:e.getStartLineNumber(),...r}},Oi=(e,t)=>Hs(e,t,Fi),Ri=(e,t)=>{if(!o.isPropertyAccessExpression(e))return;const s=e.getName();if(t.methods.has(s))return t.matchReceiver(e.getExpression().getText())?s:void 0},Li=(e,t,s)=>{const n=Ri(e.getExpression(),s);if(n===void 0)return;const r=e.getArguments()[s.argIndex];if(!(!r||!M(r)||U(r))&&!(s.requireUnmodifiedReach===!0&&!dn(r)))return{exportName:A(e),file:t,line:e.getStartLineNumber(),method:n}},Di=(e,t,s)=>{const n=[];for(const r of e.getDescendantsOfKind(l.CallExpression)){const i=Li(r,t,s);i&&n.push(i)}return n},Ee=(e,t,s)=>{const n=[];for(const r of m(t)){const i=e.getSourceFile(r)??e.addSourceFileAtPath(r);n.push(...Di(i,x(t,r),s))}return n},ki=new Set(["content","pdf","scrape","screenshot"]),Mi=(e,t)=>Ee(e,t,{argIndex:0,matchReceiver:s=>s==="ctx.browser",methods:ki}),Ki=new Set(["createBrowser","createInboundEmailHandler","createPayment"]),_i=new Set(["RateLimiter"]),zi=new Set(["extend"]),St="lunora",$i=["vite.config.ts","vite.config.mts","vite.config.js","vite.config.mjs"],rs=e=>{const t=[],s=[];let n=!1;for(const r of e.getProperties()){if(o.isSpreadAssignment(r)){n=!0;continue}if(o.isPropertyAssignment(r)){const i=y(r);t.push(i),r.getInitializer()?.getKind()===l.TrueKeyword&&s.push(i);continue}(o.isShorthandPropertyAssignment(r)||o.isMethodDeclaration(r))&&t.push(y(r))}return{analyzable:!n,presentKeys:t,trueKeys:s}},Le=e=>e&&o.isObjectLiteralExpression(e)?rs(e):{analyzable:!1,presentKeys:[],trueKeys:[]},Ui=e=>{const t=e&&(o.isArrowFunction(e)||o.isFunctionExpression(e))?e:void 0,s=t&&jt(t.getBody());return s?rs(s):{analyzable:!1,presentKeys:[],trueKeys:[]}},Bi=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression)){const r=b(n.getExpression());r!==void 0&&(Ki.has(r)?s.push({callee:r,file:t,line:n.getStartLineNumber(),...Le(n.getArguments()[0])}):zi.has(r)&&s.push({callee:r,file:t,line:n.getStartLineNumber(),...Ui(n.getArguments()[0])}))}for(const n of e.getDescendantsOfKind(l.NewExpression)){const r=b(n.getExpression());r===void 0||!_i.has(r)||s.push({callee:r,file:t,line:n.getStartLineNumber(),...Le(n.getArguments()[0])})}return s},qi=(e,t)=>{for(const s of $i){const n=S(t,s);if(!w(n))continue;const r=e.getSourceFile(n)??e.addSourceFileAtPath(n),i=[];for(const a of r.getDescendantsOfKind(l.CallExpression))b(a.getExpression())===St&&i.push({callee:St,file:s,line:a.getStartLineNumber(),...Le(a.getArguments()[0])});return i}return[]},ji=(e,t)=>{const s=[];for(const{displayPath:n,filePath:r}of he(t)){const i=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Bi(i,n))}return s.push(...qi(e,ce(t))),s},yt="ctx.containers.",Vi=e=>{if(!e.startsWith(yt))return!1;const t=e.slice(yt.length);return t.length>0&&!t.includes(".")},Wi=(e,t)=>Ee(e,t,{argIndex:0,matchReceiver:Vi,methods:new Set(["get"])}),Hi=new Set(["allow","deny","setAllowed"]),Gi=e=>{const t=e.getArguments()[0];if(!t||!o.isObjectLiteralExpression(t))return!1;const s=C(t,"enableInternet");return s!==void 0&&o.isPropertyAssignment(s)&&o.isTrueLiteral(s.getInitializerOrThrow())},Yi=(e,t)=>{const s=e.getExpression();if(!(!o.isPropertyAccessExpression(s)||s.getName()!=="start"||!Gi(e)))return{detail:"enableInternet: true",exportName:A(e),file:t,kind:"enable_internet",line:e.getStartLineNumber()}},Qi=(e,t)=>{const s=e.getExpression();if(!o.isPropertyAccessExpression(s)||!Hi.has(s.getName()))return;const n=s.getExpression();if(!(!o.isPropertyAccessExpression(n)||n.getName()!=="egress"))return{detail:s.getName(),exportName:A(e),file:t,kind:"egress_relaxation",line:e.getStartLineNumber()}},Xi=(e,t)=>Yi(e,t)??Qi(e,t),Zi=(e,t)=>F(e,t,Xi),Ji=new Set(["defineExportSink","r2Sink","webhookExportSink"]),eo=e=>{const t=e.getExpression();if(!o.isIdentifier(t))return;const s=t.getText();return Ji.has(s)?s:void 0},to=e=>{const t=[],s=[];for(const n of e.getProperties()){if(o.isSpreadAssignment(n))return{analyzable:!1,emptyKeys:[],presentKeys:[]};if(o.isPropertyAssignment(n)){const r=y(n);t.push(r);const i=n.getInitializer();i&&o.isStringLiteral(i)&&i.getLiteralText()===""&&s.push(r);continue}(o.isShorthandPropertyAssignment(n)||o.isMethodDeclaration(n)||o.isGetAccessorDeclaration(n))&&t.push(y(n))}return{analyzable:!0,emptyKeys:s,presentKeys:t}},so=(e,t)=>{const s=[];for(const{displayPath:n,filePath:r}of he(t)){const i=e.getSourceFile(r)??e.addSourceFileAtPath(r);for(const a of i.getDescendantsOfKind(l.CallExpression)){const c=eo(a);if(c===void 0)continue;const u=a.getArguments()[0],d=u&&o.isObjectLiteralExpression(u)?to(u):{analyzable:!1,emptyKeys:[],presentKeys:[]};s.push({analyzable:d.analyzable,emptyKeys:d.emptyKeys,factory:c,file:n,line:a.getStartLineNumber(),presentKeys:d.presentKeys})}}return s},no=new Map([["dbRateLimit",2],["rateLimit",2],["verifyTurnstileMiddleware",0]]),ro=new Set(["dbRateLimit","rateLimit"]),io=e=>{const t=Wt(e);if(!t)return!1;const s=C(t,"failOpen");return s!==void 0&&o.isPropertyAssignment(s)&&s.getInitializer()?.getKind()===l.TrueKeyword},oo=(e,t)=>{const s=b(e.getExpression());if(s===void 0)return;const n=no.get(s);if(n!==void 0)return{callee:s,exportName:A(e),failOpen:io(e.getArguments()[n]),file:t,limitName:ro.has(s)?Vt(e):"",line:e.getStartLineNumber()}},ao=(e,t)=>F(e,t,oo),co=new Set(["boolean","number","object","string"]),lo=e=>{const t=e.getName();if(!co.has(t))return;const s=e.getExpression();if(!o.isPropertyAccessExpression(s))return;if(s.getName()==="flags"&&Oe(s.getExpression()))return t;const n=s.getExpression();if(s.getName()==="details"&&o.isPropertyAccessExpression(n)&&n.getName()==="flags"&&Oe(n.getExpression()))return t},uo=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t))return;const s=lo(t);if(s===void 0)return;const n=e.getArguments()[0];if(!n||!(o.isStringLiteral(n)||o.isNoSubstitutionTemplateLiteral(n)))return;const r=n.getLiteralValue();return r.length>0?{key:r,type:s}:void 0},fo=(e,t)=>{const s=new Map;for(const n of m(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const i of r.getDescendantsOfKind(l.CallExpression)){const a=uo(i);a&&!s.has(a.key)&&s.set(a.key,a.type)}}return[...s.entries()].map(([n,r])=>({key:n,type:r})).toSorted((n,r)=>n.key.localeCompare(r.key))},go=e=>{const t=e.getInitializer();if(!t||!o.isCallExpression(t))return;const s=z(t);if(s?.kind!=="query")return;const n=Gs(t,s.receiver);return n?{exportName:e.getName(),handler:n}:void 0},At=e=>{const t=e.getParent();return t&&o.isPropertyAccessExpression(t)&&t.getExpression()===e?t:void 0},po=e=>{if(!o.isPropertyAccessExpression(e)||e.getName()!=="flags")return;const t=e.getExpression();if(!o.isIdentifier(t)||t.getText()!=="ctx")return;const s=At(e);if(!s)return"ctx.flags";if(s.getName()==="details"){const n=At(s);return n?`ctx.flags.details.${n.getName()}`:"ctx.flags.details"}return`ctx.flags.${s.getName()}`},mo=(e,t)=>{const s=[];for(const n of e.handler.getDescendantsOfKind(l.PropertyAccessExpression)){const r=po(n);r!==void 0&&s.push({callee:r,exportName:e.exportName,file:t,line:n.getStartLineNumber()})}return s},ho=(e,t)=>{const s=[];for(const n of e.getVariableStatements())if(n.isExported())for(const r of n.getDeclarations()){const i=go(r);i&&s.push(...mo(i,t))}return s},vo=(e,t)=>{const s=[];for(const n of m(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...ho(r,x(t,n)))}return s},xo=e=>{if(!o.isPropertyAccessExpression(e)||e.getName()!=="boolean")return!1;const t=e.getExpression();return o.isPropertyAccessExpression(t)&&t.getName()==="flags"&&Oe(t.getExpression())},Eo=e=>{if(e?.getKind()===l.TrueKeyword)return!0;if(e?.getKind()===l.FalseKeyword)return!1},So=(e,t)=>{if(!xo(e.getExpression()))return;const[s,n]=e.getArguments();if(!s||!(o.isStringLiteral(s)||o.isNoSubstitutionTemplateLiteral(s)))return;const r=s.getLiteralValue(),i=Eo(n);if(!(r.length===0||i===void 0))return{defaultValue:i,exportName:A(e),file:t,key:r,line:e.getStartLineNumber()}},yo=(e,t)=>F(e,t,So),Ao=e=>{const t=e.getType().getProperty("~standard");if(!t)return;const s=t.getTypeAtLocation(e).getProperty("types");if(!s)return;const n=s.getTypeAtLocation(e).getNonNullableType().getProperty("output");if(!n)return;const r=n.getTypeAtLocation(e),i=r.getText(e);if(!i||i==="any"||i==="never"||vn(i))return;const a=e.getSourceFile().getFilePath();if(xn(r,e,a)){const c=En(r,e,a,0,new Set);return c===void 0&&Sn(i),c}return i},bo=e=>{const t=e.getExpression();return o.isPropertyAccessExpression(t)&&t.getName()==="withGeoIndex"},No=e=>{const t=e.getArguments()[0];return t&&o.isStringLiteral(t)?t.getLiteralText():""},Po=(e,t)=>{const s=[];for(const n of m(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n),i=x(t,n);for(const a of r.getDescendantsOfKind(l.CallExpression))bo(a)&&s.push({file:i,indexName:No(a),line:a.getStartLineNumber()})}return s},Z=e=>e!==void 0&&(o.isArrowFunction(e)||o.isFunctionExpression(e))?e:void 0,is=e=>{const t=e.getArguments()[0],s=Z(t);if(s!==void 0)return s;if(t===void 0||!o.isObjectLiteralExpression(t))return;const n=C(t,"handler");return n!==void 0&&o.isPropertyAssignment(n)?Z(n.getInitializer()):void 0},wo=new Set(["delete","get","head","options","patch","post","put"]),Io=new Set(["handler","stream"]),To=new Set(["runAction","runMutation"]),Co=new Set(["delete","insert","insertManyUnsafe","patch","replace"]),J=(e,t)=>e!==void 0&&o.isIdentifier(e)&&e.getText()===t,os=(e,t)=>{if(!(e===void 0||!o.isObjectBindingPattern(e))){for(const s of e.getElements())if(Q(s)===t){const r=s.getNameNode();return o.isIdentifier(r)?r.getText():void 0}}},bt=(e,t)=>{const s=e.getParameters()[0]?.getNameNode();if(s!==void 0)return t?o.isIdentifier(s)?s.getText():void 0:os(s,"ctx")},Nt=(e,t)=>{const s=e.getParameters()[t?1:0]?.getNameNode();return t?s!==void 0&&o.isIdentifier(s)?s.getText():void 0:os(s,"request")},Pt=(e,t)=>{const s=e.getBody(),n=s.getDescendantsOfKind(l.CallExpression);o.isCallExpression(s)&&n.unshift(s);for(const r of n){const i=r.getExpression();if(!o.isPropertyAccessExpression(i))continue;const a=i.getName(),c=i.getExpression();if(To.has(a)&&J(c,t))return a;if(Co.has(a)&&o.isPropertyAccessExpression(c)&&c.getName()==="db"&&J(c.getExpression(),t))return`db.${a}`}},wt=(e,t)=>{const s=e.getBody();for(const n of s.getDescendantsOfKind(l.PropertyAccessExpression))if(n.getName()==="auth"&&J(n.getExpression(),t))return!0;for(const n of s.getDescendantsOfKind(l.VariableDeclaration)){const r=n.getNameNode();if(!(!o.isObjectBindingPattern(r)||!J(n.getInitializer(),t))){for(const i of r.getElements())if(Q(i)==="auth")return!0}}return!1},Fo=/signature|hmac|digest|(?:^|[_-])sig(?:[_-]|$)/i,Oo=(e,t)=>{const s=e.getExpression();if(!o.isPropertyAccessExpression(s)||s.getName()!=="get"&&s.getName()!=="has")return!1;const n=s.getExpression();return o.isPropertyAccessExpression(n)&&n.getName()==="headers"&&J(n.getExpression(),t)},Ro=e=>[...o.isStringLiteral(e)?[e.getLiteralText()]:[],...e.getDescendantsOfKind(l.StringLiteral).map(t=>t.getLiteralText())],as=(e,t)=>{const s=e.getVariableDeclaration(t)?.getInitializer();return s===void 0?[]:Ro(s)},Lo=(e,t)=>{const s=e.getText();for(let n=e.getParent();n!==void 0;n=n.getParent()){if(!o.isArrowFunction(n)&&!o.isFunctionExpression(n)||!n.getParameters().some(c=>c.getName()===s))continue;const r=n.getParent();if(!o.isCallExpression(r))return[];const i=r.getExpression();if(!o.isPropertyAccessExpression(i))return[];const a=i.getExpression();return o.isIdentifier(a)?as(t,a.getText()):[]}return[]},Do=e=>{const t=e.getArguments()[0];if(t===void 0)return[];if(o.isStringLiteral(t))return[t.getLiteralText()];if(!o.isIdentifier(t))return[];const s=e.getSourceFile(),n=as(s,t.getText());return n.length>0?n:Lo(t,s)},It=(e,t)=>{if(t===void 0)return!1;const s=e.getBody(),n=s.getDescendantsOfKind(l.CallExpression);return o.isCallExpression(s)&&n.unshift(s),n.some(r=>Oo(r,t)&&Do(r).some(i=>Fo.test(i)))},ko=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||!Io.has(t.getName()))return;let s=t.getExpression();for(;o.isCallExpression(s);){const n=s.getExpression();if(!o.isPropertyAccessExpression(n))return;const r=n.getName();if(wo.has(r)){const i=n.getExpression();return o.isIdentifier(i)&&i.getText()==="httpRoute"?r.toUpperCase():void 0}s=n.getExpression()}},Mo=(e,t)=>{const s=e.getExpression();if(o.isIdentifier(s)&&s.getText()==="httpAction"){const c=Z(e.getArguments()[0]),u=c&&bt(c,!0);if(!c||u===void 0||It(c,Nt(c,!0)))return;const d=Pt(c,u);return d===void 0?void 0:{exportName:A(e),file:t,kind:"httpAction",line:e.getStartLineNumber(),readsAuth:wt(c,u),sideEffect:d}}const n=ko(e);if(n===void 0)return;const r=Z(e.getArguments()[0]),i=r&&bt(r,!1);if(!r||i===void 0||It(r,Nt(r,!1)))return;const a=Pt(r,i);return a===void 0?void 0:{exportName:A(e),file:t,kind:"httpRoute",line:e.getStartLineNumber(),method:n,readsAuth:wt(r,i),sideEffect:a}},Ko=(e,t)=>F(e,t,Mo),_o=new Set(["btoa","encodeURI","encodeURIComponent","isSafeHeaderValue","Number","parseFloat","parseInt"]),zo=new Set(["append","set"]),cs=e=>e!==void 0&&(o.isStringLiteral(e)||o.isNoSubstitutionTemplateLiteral(e))?e.getLiteralText():"",Tt=(e,t)=>(o.isCallExpression(e)?[e,...e.getDescendantsOfKind(l.CallExpression)]:e.getDescendantsOfKind(l.CallExpression)).some(n=>_o.has(b(n.getExpression())??"")&&gn(n,t)),$o=(e,t)=>{if(Tt(e,t))return!0;const s=ve(e);return s!==void 0&&Tt(s,t)},De=(e,t)=>fn(e,t)&&!$o(e,t),Uo=e=>{if(o.isPropertyAccessExpression(e)&&e.getName()==="headers")return!0;const t=ve(e);return t!==void 0&&o.isNewExpression(t)&&b(t.getExpression())==="Headers"},fe=e=>{if(e===void 0)return;if(o.isObjectLiteralExpression(e))return e;const t=ve(e);return t!==void 0&&o.isObjectLiteralExpression(t)?t:void 0},$e=(e,t,s)=>{for(const n of e.getProperties())if(o.isPropertyAssignment(n)){const r=n.getInitializer();r!==void 0&&De(r,s.requestName)&&s.rows.push({exportName:s.exportName,file:s.relativePath,headerName:cs(n.getNameNode()),line:r.getStartLineNumber(),via:t})}else if(o.isShorthandPropertyAssignment(n)){const r=n.getNameNode();De(r,s.requestName)&&s.rows.push({exportName:s.exportName,file:s.relativePath,headerName:y(n),line:r.getStartLineNumber(),via:t})}else if(o.isSpreadAssignment(n)){const r=fe(n.getExpression());r!==void 0&&$e(r,t,s)}},ls=(e,t)=>{const s=fe(e);if(s===void 0)return;const n=C(s,"headers");if(n===void 0||!o.isPropertyAssignment(n))return;const r=fe(n.getInitializer());r!==void 0&&$e(r,"response-init",t)},Bo=(e,t)=>{const s=b(e.getExpression());if(s==="Response")ls(e.getArguments()[1],t);else if(s==="Headers"){const n=fe(e.getArguments()[0]);n!==void 0&&$e(n,"headers-ctor",t)}},qo=(e,t)=>{const s=e.getExpression();if(!o.isPropertyAccessExpression(s))return;const n=s.getName(),r=s.getExpression();if(n==="json"&&o.isIdentifier(r)&&r.getText()==="Response"){ls(e.getArguments()[1],t);return}if(zo.has(n)&&Uo(r)){const i=e.getArguments()[1];i!==void 0&&De(i,t.requestName)&&t.rows.push({exportName:t.exportName,file:t.relativePath,headerName:cs(e.getArguments()[0]),line:i.getStartLineNumber(),via:n==="set"?"headers-set":"headers-append"})}},jo=(e,t)=>{for(const s of e.getDescendantsOfKind(l.NewExpression))Bo(s,t);for(const s of e.getDescendantsOfKind(l.CallExpression))qo(s,t)},Vo=(e,t)=>{const s=e.getExpression();if(!o.isIdentifier(s)||s.getText()!=="httpAction")return[];const n=Z(e.getArguments()[0]);if(n===void 0)return[];const r=n.getParameters()[1];if(r===void 0)return[];const i=r.getNameNode();if(!o.isIdentifier(i))return[];const a=[];return jo(n,{exportName:A(e),relativePath:t,requestName:i.getText(),rows:a}),a},Wo=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression))s.push(...Vo(n,t));return s},Ho=(e,t)=>{const s=[];for(const n of m(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Wo(r,x(t,n)))}return s},Go=new Set(["auth","context.auth","ctx.auth"]),Yo="userId",Qo=e=>{const t=new Set;for(const s of e.getProperties()){if(o.isSpreadAssignment(s))return;(o.isPropertyAssignment(s)||o.isShorthandPropertyAssignment(s)||o.isMethodDeclaration(s))&&t.add(y(s))}return t},Xo=(e,t)=>{const s=S(t,es);if(!w(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const r of n.getDescendantsOfKind(l.CallExpression)){if(b(r.getExpression())!=="defineIdentity")continue;const[i]=r.getArguments();return i&&o.isObjectLiteralExpression(i)?Qo(i):void 0}},Ct=e=>{if(!(e===void 0||!o.isPropertyAccessExpression(e)||e.getName()!=="identity"))return Go.has(e.getExpression().getText())?e:void 0},Zo=e=>{if(o.isPropertyAccessExpression(e)&&Ct(e.getExpression())!==void 0)return e.getName();if(o.isElementAccessExpression(e)&&Ct(e.getExpression())!==void 0){const t=e.getArgumentExpression();return t&&o.isStringLiteral(t)?t.getLiteralValue():void 0}},Jo=(e,t,s)=>{const n=[];for(const r of e.getDescendants()){const i=Zo(r);i!==void 0&&n.push({declared:i===Yo||s.has(i),exportName:A(r),file:t,key:i,line:r.getStartLineNumber()})}return n},ea=(e,t)=>{const s=Xo(e,t);if(s===void 0)return[];const n=[];for(const r of m(t)){const i=e.getSourceFile(r)??e.addSourceFileAtPath(r);n.push(...Jo(i,x(t,r),s))}return n},ta=(e,t)=>{if(b(e.getExpression())!=="buildImageDeliveryUrl")return;const s=e.getArguments()[0];if(!s)return;const n=P(s,"key");if(!(!n||!M(n)||U(n)))return{exportName:A(e),file:t,line:e.getStartLineNumber()}},sa=(e,t)=>F(e,t,ta),na=e=>{if(o.isComputedPropertyName(e)){const t=e.getExpression();return o.isStringLiteral(t)||o.isNoSubstitutionTemplateLiteral(t)?t.getLiteralValue():void 0}return o.isStringLiteral(e)?e.getLiteralValue():e.getText()},ra=e=>e.getProperties().some(t=>{if(o.isSpreadAssignment(t))return!0;const s=na(t.getNameNode());return s===void 0||s==="namespace"}),ia=(e,t)=>{for(const{filePath:s}of he(t)){const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const r of n.getDescendantsOfKind(l.CallExpression)){const i=r.getExpression(),[a]=r.getArguments();if(!(!o.isPropertyAccessExpression(i)||i.getName()!=="auth"||a===void 0)&&(!o.isObjectLiteralExpression(a)||ra(a)))return r}}},oa="https://lunora.sh/docs/concepts/data-residency#pinning-auth-and-voice",aa=(e,t)=>{if(!(e.jurisdiction===void 0||e.jurisdictionPinsAuth===!0||t===void 0))throw ee(t,`the schema pins Durable Objects to the "${e.jurisdiction}" jurisdiction, and this project also has DO-backed auth (users, sessions, accounts, credentials). Pinning the auth object resolves it to a NEW, EMPTY object: existing users stay in the unpinned one until you copy them across (${oa}). Acknowledge with \`.jurisdiction("${e.jurisdiction}", { pinAuth: true })\`, deploy, then run the copy. For D1-mode auth the acknowledgement changes nothing.`,{code:"JURISDICTION_MOVE",status:422})},ca=new Set(["delete","get","getRaw","getWithMetadata","put"]),la=(e,t,s=[])=>{const n=new Map(s.map(i=>[`${i.filePath}:${i.exportName}`,i.visibility]));return Ee(e,t,{argIndex:0,matchReceiver:i=>i==="ctx.kv"||i.startsWith("ctx.kv."),methods:ca}).map(i=>{const a=n.get(`${i.file}:${i.exportName}`);return a===void 0?i:{...i,visibility:a}})},ua=new Set(["queue","send"]),Ft=new Set(["bcc","cc","to"]),da=e=>{if(!o.isPropertyAccessExpression(e))return;const t=e.getName();if(!ua.has(t))return;const s=e.getExpression().getText();return s==="ctx.mail"||s==="ctx.email"?t:void 0},fa=e=>o.isObjectLiteralExpression(e)?e.getProperties().some(t=>{if(o.isShorthandPropertyAssignment(t)){const n=t.getNameNode();return Ft.has(y(t))&&M(n)&&!U(n)}if(!o.isPropertyAssignment(t)||!Ft.has(y(t)))return!1;const s=t.getInitializer();return s!==void 0&&M(s)&&!U(s)}):!1,ga=(e,t)=>{const s=da(e.getExpression());if(s===void 0)return;const n=e.getArguments()[0];if(!(!n||!fa(n)))return{exportName:A(e),file:t,line:e.getStartLineNumber(),method:s}},pa=(e,t)=>F(e,t,ga),ma=e=>o.isPropertyAssignment(e)||o.isMethodDeclaration(e)||o.isGetAccessorDeclaration(e)?o.isComputedPropertyName(e.getNameNode()):!1,ha=e=>o.isPropertyAssignment(e)||o.isShorthandPropertyAssignment(e)||o.isMethodDeclaration(e)||o.isGetAccessorDeclaration(e)?ma(e):!0,us=(e,t=!1)=>{for(const s of e.getProperties()){if(ha(s))return!0;if(t)continue;if(!o.isPropertyAssignment(s))return!0;const n=s.getInitializer();if(!n||!o.isObjectLiteralExpression(n)||us(n,!0))return!0}return!1},va=(e,t)=>{for(const s of m(t)){const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const{receiver:r}of Zt(n))for(const i of Ke(r)){const a=i.getArguments()[0];if(a!==void 0&&(!o.isObjectLiteralExpression(a)||us(a)))return!0}}return!1},xa=e=>{const t=e.getArguments()[0];if(!t||!o.isObjectLiteralExpression(t))return[];const s=[];for(const n of t.getProperties()){const r=de(n);if(r===void 0||!o.isPropertyAssignment(n))continue;const i=n.getInitializer();if(!(!i||!o.isObjectLiteralExpression(i)))for(const a of i.getProperties()){const c=de(a);c!==void 0&&s.push({column:c,strategy:Xt(a),table:r})}}return s},Ea=(e,t)=>{const s=new Map;for(const n of m(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const{receiver:i}of Zt(r))for(const a of Ke(i))for(const c of xa(a)){const u=`${c.table}\0${c.column}`;s.has(u)||s.set(u,c)}}return{columns:[...s.values()]}},Sa=(e,t,s)=>{const n=e.getArguments()[0];if(!n||!o.isObjectLiteralExpression(n))return[];const r=[];for(const i of n.getProperties()){const a=de(i);if(a===void 0||!o.isPropertyAssignment(i))continue;const c=i.getInitializer();if(!(!c||!o.isObjectLiteralExpression(c)))for(const u of c.getProperties()){const d=de(u);if(d===void 0)continue;const g=Xt(u);g!=="custom"&&r.push({column:d,exportName:t,file:s,line:u.getStartLineNumber(),strategy:g,table:a})}}return r},ya=(e,t)=>{if(!o.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&o.isCallExpression(s)?z(s):void 0;return n?.receiver?Ke(n.receiver).flatMap(r=>Sa(r,e.getName(),t)):[]},Aa=(e,t)=>{const s=[];for(const n of m(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n),i=x(t,n);for(const a of r.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...ya(c,i))}return s},ba=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||t.getName()!=="replace")return!1;const s=t.getExpression();return _(s)},Na=e=>{const t=e.getArguments()[0];if(t===void 0||!o.isObjectLiteralExpression(t))return;const s=C(t,"server");if(s!==void 0)return o.isPropertyAssignment(s)?s.getInitializer():s},Pa=e=>{if(!e.isExported())return;const t=e.getInitializer();if(t?.getKind()!==l.CallExpression)return;const s=t;return Fn(s.getExpression())?s:void 0},wa=e=>{const t=Pa(e),s=t===void 0?void 0:Na(t);if(s===void 0)return[];const n=e.getNameNode(),r=o.isIdentifier(n)?n.getText():"";return s.getDescendantsOfKind(l.CallExpression).filter(i=>ba(i)).map(i=>({exportName:r,file:"lunora/mutators.ts",line:i.getStartLineNumber()}))},Ia=e=>e.getVariableDeclarations().flatMap(t=>wa(t)),Ta=(e,t)=>{const s=S(t,Cn);if(!w(s))return[];const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);return Ia(n)},Ca=new Set(["delete","get","patch"]),Fa=new Set(["accountId","authorId","companyId","createdBy","createdById","customerId","groupId","memberId","organizationId","orgId","ownerId","projectId","teamId","tenantId","userId","workspaceId"]),Oa=new Set(["auth","identity","session","user"]),Ra=new Set([l.EqualsEqualsEqualsToken,l.EqualsEqualsToken,l.ExclamationEqualsEqualsToken,l.ExclamationEqualsToken]),La=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||t.getName()!=="normalizeId"||!_(t.getExpression()))return;const s=e.getArguments()[0];return s&&o.isStringLiteral(s)?s.getLiteralText():""},Da=e=>{let t=e,s=t.getParent();for(;s!==void 0&&(o.isAsExpression(s)||o.isParenthesizedExpression(s)||o.isNonNullExpression(s));)t=s,s=t.getParent();if(s===void 0||!o.isVariableDeclaration(s))return;const n=s.getNameNode();return o.isIdentifier(n)?n.getText():void 0},ka=(e,t)=>e.getDescendantsOfKind(l.Identifier).some(s=>s.getText()===t),Ma=e=>o.isThrowStatement(e)||o.isReturnStatement(e)||e.getDescendantsOfKind(l.ThrowStatement).length>0||e.getDescendantsOfKind(l.ReturnStatement).length>0,Ka=(e,t)=>e.getDescendantsOfKind(l.IfStatement).some(s=>ka(s.getExpression(),t)&&Ma(s.getThenStatement())),_a=(e,t)=>{for(const s of e.getDescendantsOfKind(l.CallExpression)){const n=s.getExpression();if(!o.isPropertyAccessExpression(n))continue;const r=n.getName();if(!Ca.has(r))continue;const i=n.getExpression();if(!(_(i)||o.isPropertyAccessExpression(i)&&_(i.getExpression())))continue;const c=s.getArguments()[0];if(c!==void 0&&o.isIdentifier(c)&&c.getText()===t)return r}},za=e=>{let t=e;for(;o.isPropertyAccessExpression(t)||o.isElementAccessExpression(t)||o.isNonNullExpression(t)||o.isParenthesizedExpression(t)||o.isAsExpression(t)||o.isAwaitExpression(t);)t=t.getExpression();return o.isIdentifier(t)?t.getText():void 0},$a=e=>e.getDescendantsOfKind(l.CallExpression).some(t=>t.getArguments().some(s=>za(s)==="ctx")),Ua=e=>e.getDescendantsOfKind(l.BinaryExpression).some(t=>Ra.has(t.getOperatorToken().getKind())?o.isPropertyAccessExpression(t.getLeft())||o.isPropertyAccessExpression(t.getRight()):!1),Ba=e=>{for(const t of e.getDescendantsOfKind(l.Identifier))if(Fa.has(t.getText()))return!0;for(const t of e.getDescendantsOfKind(l.PropertyAccessExpression)){const s=t.getExpression();if(o.isIdentifier(s)&&s.getText()==="ctx"&&Oa.has(t.getName()))return!0}return $a(e)||Ua(e)},qa=(e,t)=>{if(!o.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!o.isCallExpression(s))return[];const n=z(s);if(n?.kind!=="query"&&n?.kind!=="mutation")return[];const r=is(s);if(r===void 0)return[];const i=n.receiver!==void 0&&Gt(n.receiver,"use","rls"),a=Ba(r),c=new Set,u=[];for(const d of r.getDescendantsOfKind(l.CallExpression)){const g=La(d);if(g===void 0)continue;const h=Da(d);if(h===void 0||c.has(h)||!Ka(r,h))continue;const O=_a(r,h);O!==void 0&&(c.add(h),u.push({exportName:e.getName(),file:t,line:d.getStartLineNumber(),mentionsOwnership:a,sinkMethod:O,table:g,usesRls:i,visibility:n.visibility}))}return u},ja=(e,t)=>{const s=[];for(const n of m(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n),i=x(t,n);for(const a of r.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...qa(c,i))}return s},Va=new Set(["accountId","authorId","createdBy","createdById","organizationId","orgId","ownerId","tenantId","updatedBy","userId","workspaceId"]),Wa=new Set(["insert","insertManyUnsafe","patch","replace"]),Ha=e=>{if(!o.isPropertyAccessExpression(e))return;const t=e.getName();if(!Wa.has(t))return;const s=e.getExpression();if(!o.isPropertyAccessExpression(s)||s.getName()!=="db")return;const n=s.getExpression();return o.isIdentifier(n)&&n.getText()==="ctx"?t:void 0},Ga=(e,t)=>{if(t!=="insertManyUnsafe")return o.isObjectLiteralExpression(e)?[e]:[];if(!o.isArrayLiteralExpression(e))return[];const s=[];for(const n of e.getElements())o.isObjectLiteralExpression(n)&&s.push(n);return s},Ot=(e,t)=>{if(o.isPropertyAccessExpression(e)){const s=e.getExpression();return o.isIdentifier(s)&&s.getText()==="args"&&e.getName()===t}if(o.isElementAccessExpression(e)){const s=e.getExpression(),n=e.getArgumentExpression();return o.isIdentifier(s)&&s.getText()==="args"&&n!==void 0&&o.isStringLiteral(n)&&n.getLiteralValue()===t}return!1},Ya=e=>{if(!o.isIdentifier(e))return;const t=e.getText(),s=e.getFirstAncestor(a=>o.isArrowFunction(a)||o.isFunctionExpression(a)||o.isFunctionDeclaration(a));if(s===void 0)return;for(const a of s.getDescendantsOfKind(l.BinaryExpression)){const c=a.getLeft();if(o.isIdentifier(c)&&c.getText()===t&&a.getOperatorToken().getText().endsWith("="))return}const n=e.getStart();let r,i=-1;for(const a of s.getDescendantsOfKind(l.VariableDeclaration)){if(a.getName()!==t)continue;const c=a.getParent();if(!o.isVariableDeclarationList(c)||c.getDeclarationKind()!==zs.Const)continue;const u=a.getInitializer(),d=a.getStart();u!==void 0&&d<n&&d>i&&(r=u,i=d)}return r},Qa=(e,t)=>{if(Ot(e,t))return!0;const s=Ya(e);return s!==void 0&&Ot(s,t)},Xa=(e,t,s,n,r)=>{const i=[];for(const a of e.getProperties()){let c,u;if(o.isPropertyAssignment(a)?(c=y(a),u=a.getInitializer()):o.isShorthandPropertyAssignment(a)&&(c=y(a),u=a.getNameNode()),!(c===void 0||u===void 0||!Va.has(c))&&M(u)&&!U(u)){const d=A(s),g=r(d)===c&&Qa(u,c);i.push({exportName:d,field:c,file:n,line:s.getStartLineNumber(),method:t,...g&&{ownerScoped:!0}})}}return i},Za=(e,t,s)=>{const n=Ha(e.getExpression());if(n===void 0)return[];const r=e.getArguments()[1];return r?Ga(r,n).flatMap(i=>Xa(i,n,e,t,s)):[]},Ja=(e,t,s)=>{const n=[];for(const r of e.getDescendantsOfKind(l.CallExpression))for(const i of Za(r,t,a=>s(a).owner)){const{visibility:a}=s(i.exportName);n.push(a===void 0?i:{...i,visibility:a})}return n},ec=(e,t,s=[],n=[])=>{const r=[],i=new Map;for(const a of s)i.set(`${a.filePath}:${a.exportName}`,{visibility:a.visibility});for(const a of n){const c=`${a.filePath}:${a.exportName}`;i.set(c,{...i.get(c),owner:a.owner})}for(const a of m(t)){const c=e.getSourceFile(a)??e.addSourceFileAtPath(a),u=x(t,a);r.push(...Ja(c,u,d=>i.get(`${u}:${d}`)??{}))}return r},tc=["providerSubscriptionId","state"],sc=["providerEventId","processedAt"],Rt=(e,t)=>t.every(s=>s in e.shape),nc=e=>{const t=e.find(n=>n.name==="subscriptions"),s=e.find(n=>n.name==="events");return t!==void 0&&s!==void 0&&Rt(t,tc)&&Rt(s,sc)},rc=new Set(["createAutumnAdapter","createDodoPaymentsAdapter","createPolarAdapter","createStripeAdapter"]),ic=e=>e&&o.isNumericLiteral(e)?Number(e.getText()):void 0,oc=e=>{const t=C(e,"webhookToleranceSeconds");return t&&o.isPropertyAssignment(t)?ic(t.getInitializer()):void 0},ac=(e,t)=>{const s=b(e.getExpression());if(s===void 0||!rc.has(s))return;const[n]=e.getArguments(),r=n&&o.isObjectLiteralExpression(n)?oc(n):void 0;return{callee:s,exportName:A(e),file:t,line:e.getStartLineNumber(),...r===void 0?{}:{toleranceSeconds:r}}},cc=(e,t)=>F(e,t,ac),lc=new Map([["defineQueue",0],["defineSubscription",1],["defineWorkflow",0]]),uc=new Set(["run","runAction","runMutation","runQuery"]),dc=new Set(["api","internal"]),fc=e=>{const t=e.getExpression();return o.isIdentifier(t)?t.getText():void 0},gc=(e,t)=>{const s=e.getArguments()[t];if(!s||!o.isObjectLiteralExpression(s))return;const n=C(s,"handler");if(n===void 0||!o.isPropertyAssignment(n))return;const r=n.getInitializer();if(r&&(o.isArrowFunction(r)||o.isFunctionExpression(r)))return r},ds=(e,t)=>{const s=e.getParameters()[t]?.getNameNode();return s&&o.isIdentifier(s)?s.getText():void 0},fs=(e,t)=>e===t||e.startsWith(`${t}.`),gs=e=>{const t=e.getDescendantsOfKind(l.PropertyAccessExpression);return o.isPropertyAccessExpression(e)&&t.push(e),t},Lt=e=>{const t=e.getParent();return o.isPropertyAccessExpression(t)&&t.getNameNode()===e||o.isPropertyAssignment(t)&&t.getNameNode()===e?!1:!(o.isBindingElement(t)&&t.getNameNode()===e)},ps=e=>{const t=e.getDescendantsOfKind(l.Identifier).filter(s=>Lt(s));return o.isIdentifier(e)&&Lt(e)&&t.push(e),t},pc=e=>{if(!o.isVariableDeclaration(e))return[];const t=e.getNameNode();return o.isIdentifier(t)?[t.getText()]:t.getDescendantsOfKind(l.BindingElement).map(s=>s.getName())},mc=e=>{const t=ds(e,1);if(t===void 0)return[];const s=[`${t}.messages`];for(const n of e.getDescendantsOfKind(l.ForOfStatement)){if(n.getExpression().getText()!==`${t}.messages`)continue;const r=n.getInitializer(),i=o.isVariableDeclarationList(r)?r.getDeclarations()[0]?.getNameNode():void 0;i&&o.isIdentifier(i)&&s.push(`${i.getText()}.body`)}return s},hc=(e,t,s)=>{const n=t==="workflow"?[`${s}.params`]:mc(e),r=new Set,i=a=>gs(a).some(c=>n.some(u=>fs(c.getText(),u)))?!0:ps(a).some(c=>r.has(c.getText()));for(const a of e.getDescendantsOfKind(l.VariableDeclaration)){const c=a.getInitializer();if(c&&i(c))for(const u of pc(a))r.add(u)}return{names:r,prefixes:n}},vc=(e,t)=>gs(e).some(s=>t.prefixes.some(n=>fs(s.getText(),n)))?!0:ps(e).some(s=>t.names.has(s.getText())),xc=e=>{if(e===void 0||!o.isPropertyAccessExpression(e))return;const t=[];let s=e;for(;o.isPropertyAccessExpression(s);)t.unshift(s.getName()),s=s.getExpression();const n=t.at(-1);if(!(n===void 0||!o.isIdentifier(s)||!dc.has(s.getText())||t.length<2))return{exportName:n,file:t.slice(0,-1).join("/")}},Ec=(e,t,s)=>{const n=ds(e,0);if(n===void 0)return[];const r=hc(e,t,n),i=new Set([n,...r.prefixes.filter(c=>c.endsWith(".body")).map(c=>c.slice(0,-5))]),a=[];for(const c of e.getDescendantsOfKind(l.CallExpression)){const u=c.getExpression();if(!o.isPropertyAccessExpression(u)||!uc.has(u.getName())||!i.has(u.getExpression().getText()))continue;const d=c.getArguments()[1];if(!d||!vc(d,r))continue;const g=xc(c.getArguments()[0]);g!==void 0&&a.push({dispatchKind:t,file:s,handlerExport:A(c),line:c.getStartLineNumber(),targetExport:g.exportName,targetFile:g.file})}return a},Sc=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression)){const r=fc(n),i=r===void 0?void 0:lc.get(r);if(i===void 0)continue;const a=gc(n,i);a!==void 0&&s.push(...Ec(a,r==="defineWorkflow"?"workflow":"queue",t))}return s},yc=(e,t)=>{const s=[];for(const n of m(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Sc(r,x(t,n)))}return s},Dt={dbRateLimit:"usesRateLimit",emailGateMiddleware:"usesEmailGate",mask:"usesMask",rateLimit:"usesRateLimit",rls:"usesRls",verifyTurnstileMiddleware:"usesCaptcha"},kt=new Set(["account","credential","member","passkey","session","user"]),Ac=e=>e.replaceAll(/[-_]/gu," ").replaceAll(/([a-z0-9])([A-Z])/gu,"$1 $2").split(" ").filter(Boolean).map(t=>t.toLowerCase()),bc=e=>{const s=Ac(e).at(-1);if(!s)return!1;const n=s.endsWith("s")?s.slice(0,-1):s;return kt.has(s)||kt.has(n)},Nc=e=>{const t=e.replaceAll(/[^a-z0-9]/giu,"").toLowerCase();return t.endsWith("email")||t.endsWith("emailaddress")},Pc=(e,t)=>{const{objects:s,opaque:n}=ze(e,t);return pi(s).some(r=>Nc(r))?!0:n?void 0:!1},wc=e=>{const t=e.getArguments()[0];return!t||!o.isObjectLiteralExpression(t)?{usesCaptcha:!1,usesRateLimit:!1}:{usesCaptcha:!!C(t,"captcha"),usesRateLimit:!!C(t,"rateLimit")}},Ic=e=>{if(o.isCallExpression(e))return e;if(!o.isIdentifier(e))return;const s=e.getSourceFile().getVariableDeclaration(e.getText())?.getInitializer();return s&&o.isCallExpression(s)?s:void 0},ue={usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},Tc=e=>{const t=Ic(e),s=t?b(t.getExpression()):void 0;if(t&&s==="protectPublic"){const n=wc(t);return{...ue,usesCaptcha:n.usesCaptcha,usesRateLimit:n.usesRateLimit}}return s!==void 0&&s in Dt?{...ue,[Dt[s]]:!0}:ue},Cc=e=>{const t={...ue};let s=e;for(;o.isCallExpression(s);){const n=s.getExpression();if(!o.isPropertyAccessExpression(n))break;const r=n.getName()==="use"?s.getArguments()[0]:void 0;if(r){const i=Tc(r);t.usesCaptcha||=i.usesCaptcha,t.usesEmailGate||=i.usesEmailGate,t.usesMask||=i.usesMask,t.usesRateLimit||=i.usesRateLimit,t.usesRls||=i.usesRls}s=n.getExpression()}return t},Fc=new Set(["insert","insertMany","insertManyUnsafe","replace"]),Oc=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||!Fc.has(t.getName()))return!1;const s=t.getExpression();if(!_(s))return!1;const r=e.getArguments()[0];return!r||!(o.isStringLiteral(r)||o.isNoSubstitutionTemplateLiteral(r))?!1:bc(r.getLiteralText())},Rc=new Set(["create","publish","publishBatch","runAfter","runAt","send","sendBatch"]),Lc=new Set(["queues","scheduler","topics","workflows"]),Dc=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||!Rc.has(t.getName()))return!1;let s=t.getExpression();for(;o.isCallExpression(s)||o.isElementAccessExpression(s)||o.isPropertyAccessExpression(s);){if(o.isPropertyAccessExpression(s)&&Lc.has(s.getName())){const n=s.getExpression();if(o.isIdentifier(n)&&n.getText()==="ctx")return!0}s=s.getExpression()}return!1},kc=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||t.getName()!=="insertManyUnsafe")return!1;const s=t.getExpression();return _(s)},ms=new Set(["generateObject","generateText","streamObject","streamText"]),Mc=e=>{const t=b(e.getExpression());return t!==void 0&&ms.has(t)},Kc=e=>{const t=b(e.getExpression());if(t===void 0||!ms.has(t))return!1;const s=e.getArguments()[0];return!s||!o.isObjectLiteralExpression(s)||s.getProperties().some(n=>o.isSpreadAssignment(n))?!1:!C(s,"maxOutputTokens")},_c=new Set(["log","span","trace"]),zc=new Set(["ai"]),$c=new Set(["email","mail"]),Uc=new Set(["ai","browser","fetch","mail","notify","queues","sql","storage","topics","workflows"]),Ce=(e,t)=>e.getDescendantsOfKind(l.PropertyAccessExpression).some(s=>{if(!t.has(s.getName()))return!1;const n=s.getExpression();return o.isIdentifier(n)&&n.getText()==="ctx"}),Bc=new Set([l.ArrowFunction,l.FunctionDeclaration,l.FunctionExpression,l.GetAccessor,l.MethodDeclaration,l.SetAccessor]),qc=new Set(["every","filter","flatMap","forEach","map","some"]),jc=new Set(["all","allSettled","race"]),Vc=e=>{const t=e.getParent();if(!t||!o.isCallExpression(t)||!t.getArguments().includes(e))return;const s=t.getExpression();if(!o.isPropertyAccessExpression(s))return;const n=s.getName();if(qc.has(n))return t;const r=s.getExpression();if(o.isIdentifier(r)&&r.getText()==="Promise"&&jc.has(n))return t},Wc=e=>{let t=e.getParent();for(;t;){if(o.isTryStatement(t)){const s=t.getTryBlock();if(e.getPos()>=s.getPos()&&e.getEnd()<=s.getEnd())return!0}if(Bc.has(t.getKind())){const s=Vc(t);if(!s)return!1;t=s;continue}t=t.getParent()}return!1},Hc=e=>{let t=e;for(;;){const s=t.getParent();if(!o.isPropertyAccessExpression(s)||s.getExpression()!==t)return!1;if(s.getName()==="catch")return!0;if(s.getName()!=="then"&&s.getName()!=="finally")return!1;const n=s.getParent();if(!o.isCallExpression(n)||n.getExpression()!==s)return!1;t=n}},Gc=e=>{let t=e;for(;;){const s=t.getParent();if(o.isPropertyAccessExpression(s)&&s.getExpression()===t){t=s;continue}return o.isCallExpression(s)&&s.getExpression()===t?s:void 0}},Yc=e=>{let t=!1,s=!0;for(const n of e.getDescendantsOfKind(l.PropertyAccessExpression)){if(!Uc.has(n.getName()))continue;const r=n.getExpression();if(!o.isIdentifier(r)||r.getText()!=="ctx")continue;const i=Gc(n);i&&(t=!0,!Wc(i)&&!Hc(i)&&(s=!1))}return{handlesErrors:t&&s,reachesOutbound:t}},Qc=e=>e.getDescendantsOfKind(l.ThrowStatement).some(t=>{const s=t.getExpression();if(!o.isNewExpression(s))return!1;const n=s.getExpression();return o.isIdentifier(n)&&n.getText()==="Error"}),Mt="lunora-advisor-exempt",Xc=/^[\s*/]+/u,Zc=/[\w-]/u,Jc=e=>{const s=(e.getFirstAncestorByKind(l.VariableStatement)??e).getLeadingCommentRanges().map(n=>n.getText()).join(`
|
|
6
|
+
`);for(const n of s.split(`
|
|
7
|
+
`)){const r=n.replace(Xc,"");if(!r.startsWith(Mt))continue;const i=r.slice(Mt.length);if(Zc.test(i.charAt(0)))continue;const a=i.indexOf("--");return{exempt:!0,exemptReason:(a===-1?"":i.slice(a+2).split("*")[0]??"").trim()}}return{exempt:!1,exemptReason:""}},el=e=>{const[t]=e.getArguments();if(t){if(o.isObjectLiteralExpression(t)){const s=C(t,"handler");return s?o.isPropertyAssignment(s)?s.getInitializer():o.isShorthandPropertyAssignment(s)?s.getNameNode():o.isMethodDeclaration(s)?s:void 0:void 0}return t}},tl=(e,t)=>{const s=el(t);if(!s)return;if(o.isArrowFunction(s)||o.isFunctionExpression(s)||o.isMethodDeclaration(s))return e;if(!o.isIdentifier(s))return;const n=s.getSourceFile(),r=s.getText(),i=n.getVariableDeclaration(r)?.getInitializer();return i&&(o.isArrowFunction(i)||o.isFunctionExpression(i))?i:n.getFunction(r)},sl=e=>{let t=!1,s=!1,n=!1,r=!1,i=!1;for(const u of e.getDescendantsOfKind(l.CallExpression))if(Oc(u)&&(i=!0),Dc(u)&&(t=!0),kc(u)&&(r=!0),Mc(u)&&(s=!0),Kc(u)&&(n=!0),i&&t&&r&&n)break;const{handlesErrors:a,reachesOutbound:c}=Yc(e);return{callsMail:Ce(e,$c),emitsEvent:Ce(e,_c),fanOut:t,handlesErrors:a,reachesOutbound:c,runsAiGeneration:s||Ce(e,zc),throwsBareError:Qc(e),unboundedAiGeneration:n,usesInsertManyUnsafe:r,writesUserTable:i}},nl=(e,t)=>{const s=e.getInitializer();if(!s||!o.isCallExpression(s))return;const n=z(s);if(!n||n.kind!=="query"&&n.kind!=="mutation"&&n.kind!=="action")return;const r=n.receiver?Cc(n.receiver):{usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},i=tl(e,s);return{...i?sl(i):{},...Jc(e),...r,analyzableBody:i!==void 0,exportName:e.getName(),file:t,hasEmailArg:Pc(s,n.receiver),kind:n.kind,visibility:n.visibility}},rl=(e,t)=>{const s=[];for(const n of e.getVariableStatements())if(n.isExported())for(const r of n.getDeclarations()){const i=nl(r,t);i&&s.push(i)}return s},il=(e,t)=>{const s=[];for(const n of m(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...rl(r,x(t,n)))}return s},ol=new Set(["dbRateLimit","rateLimit"]),al=e=>o.isArrowFunction(e)?e.getBody():e,cl=e=>{if(!o.isArrowFunction(e))return;const t=e.getParameters()[0]?.getNameNode();return t!==void 0&&o.isIdentifier(t)?t:void 0},hs=e=>{const t=e.getParent();return o.isPropertyAccessExpression(t)&&t.getExpression()===e&&t.getName()==="args"},vs=(e,t)=>{const s=t.getSymbol();return s===void 0?[]:e.getDescendantsOfKind(l.Identifier).filter(n=>{if(n.getSymbol()!==s)return!1;const r=n.getParent();return!(o.isPropertyAccessExpression(r)&&r.getNameNode()===n)})},ll=(e,t)=>M(e)||t!==void 0&&vs(e,t).some(s=>hs(s)),ul=(e,t)=>t===void 0?U(e):vs(e,t).some(s=>!hs(s)),dl=(e,t)=>{const s=b(e.getExpression());if(s===void 0||!ol.has(s))return;const n=P(Wt(e.getArguments()[2]),"key");if(!n)return;const r=al(n),i=cl(n);if(!(!ll(r,i)||ul(r,i)))return{callee:s,exportName:A(e),file:t,limitName:Vt(e),line:e.getStartLineNumber()}},fl=(e,t)=>F(e,t,dl),gl=new Set(["findFirst","findFirstOrThrow","findMany","findUnique","get"]),pl=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||!gl.has(t.getName()))return;const s=t.getExpression();if(_(s)){const n=e.getArguments()[0];return n&&o.isStringLiteral(n)?n.getLiteralText():""}if(o.isPropertyAccessExpression(s)&&_(s.getExpression()))return s.getName()},ml=e=>{let t=e;for(;o.isCallExpression(t);){const s=t.getExpression();if(!o.isPropertyAccessExpression(s))return;if(s.getName()==="query"&&_(s.getExpression())){const n=t.getArguments()[0];return n&&o.isStringLiteral(n)?n.getLiteralText():""}t=s.getExpression()}},hl=e=>{let t=X(e)??e;for(;o.isAwaitExpression(t);)t=X(t.getExpression())??t.getExpression();return t},xs=(e,t=!1)=>{const s=hl(e);if(o.isIdentifier(s)){if(t)return;const n=ve(s);return n===void 0?void 0:xs(n,!0)}if(o.isCallExpression(s))return pl(s)??ml(s)},vl=e=>{const t=e.getBody();if(!o.isBlock(t))return[t];const s=[];for(const n of e.getDescendantsOfKind(l.ReturnStatement)){const r=n.getFirstAncestor(a=>o.isArrowFunction(a)||o.isFunctionExpression(a)||o.isFunctionDeclaration(a)),i=n.getExpression();r===e&&i!==void 0&&s.push(i)}return s},xl=(e,t)=>{if(!o.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!o.isCallExpression(s))return[];const n=z(s);if(n?.kind!=="query")return[];const r=is(s);if(r===void 0)return[];const i=n.receiver!==void 0&&en(n.receiver,"output"),a=n.receiver!==void 0&&Gt(n.receiver,"use","mask"),c=new Set,u=[];for(const d of vl(r)){const g=xs(d);g===void 0||c.has(g)||(c.add(g),u.push({exportName:e.getName(),file:t,line:d.getStartLineNumber(),table:g,usesMask:a,usesOutput:i,visibility:n.visibility}))}return u},El=(e,t)=>{const s=[];for(const n of m(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n),i=x(t,n);for(const a of r.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...xl(c,i))}return s},Sl=e=>{if(!e||!o.isObjectLiteralExpression(e))return[];const t=[];for(const s of e.getProperties())(o.isPropertyAssignment(s)||o.isShorthandPropertyAssignment(s)||o.isMethodDeclaration(s)||o.isGetAccessorDeclaration(s))&&t.push(y(s));return t},yl=(e,t)=>{if(!o.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&o.isCallExpression(s)?z(s):void 0;if(!n)return[];const r=[];for(const i of e.getDescendantsOfKind(l.CallExpression)){const a=Ht(i);if(a===void 0)continue;const c=Sl(P(a.options,"with"));c.length!==0&&r.push({exportName:e.getName(),file:t,line:i.getStartLineNumber(),parentTable:a.table,relations:c,visibility:n.visibility})}return r},Al=(e,t)=>{const s=[];for(const n of m(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n),i=x(t,n);for(const a of r.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...yl(c,i))}return s},ge=e=>{if(o.isStringLiteral(e)||o.isNoSubstitutionTemplateLiteral(e))return e.getLiteralText();if(o.isBinaryExpression(e)&&e.getOperatorToken().getKind()===l.PlusToken){const t=ge(e.getLeft()),s=ge(e.getRight());return t!==void 0&&s!==void 0?t+s:void 0}},bl=e=>{let t=e,s=t.getParent();for(;s!==void 0&&o.isBinaryExpression(s)&&s.getOperatorToken().getKind()===l.PlusToken;)t=s,s=t.getParent();return t!==e&&ge(t)!==void 0},Nl=/(?:^|\/)__tests__\//u,Pl=/\.(?:spec|test)$/u,wl=e=>Nl.test(e)||Pl.test(e),Il=e=>{const t=e.getParent();if(t!==void 0){if(o.isVariableDeclaration(t)||o.isPropertyAssignment(t)||o.isPropertySignature(t))return y(t);if(o.isBinaryExpression(t)&&t.getOperatorToken().getKind()===l.EqualsToken)return t.getLeft().getText()}},Tl=(e,t,s)=>Un(e)?!wl(s)&&Bn(Il(t)):!0,Cl=(e,t)=>{const s=[],n=[...e.getDescendantsOfKind(l.BinaryExpression),...e.getDescendantsOfKind(l.StringLiteral),...e.getDescendantsOfKind(l.NoSubstitutionTemplateLiteral)],r=new Set;for(const i of n){if(bl(i))continue;const a=ge(i);if(a===void 0)continue;const c=zn(a);if(c===void 0||!Tl(c,i,t))continue;const u=i.getStartLineNumber(),d=`${String(u)}:${c}`;r.has(d)||(r.add(d),s.push({file:t,kind:c,line:u,preview:$n(a)}))}return s},Fl=(e,t)=>{const s=[];for(const n of m(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Cl(r,x(t,n)))}return s},Ol=(e,t)=>{if(!o.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&o.isCallExpression(s)?z(s):void 0;if(!n)return[];const r=[];for(const i of e.getDescendantsOfKind(l.CallExpression)){const a=Ht(i);if(a===void 0)continue;const c=P(a.options,"includeDeleted");if(c===void 0)continue;const u=o.isTrueLiteral(c),d=!u&&M(c);!u&&!d||r.push({exportName:e.getName(),file:t,fromArgs:d,hardcodedTrue:u,line:i.getStartLineNumber(),table:a.table,visibility:n.visibility})}return r},Rl=(e,t)=>{const s=[];for(const n of m(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n),i=x(t,n);for(const a of r.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...Ol(c,i))}return s},Ll=new Set(["query","unsafe"]),Dl=e=>{if(!o.isPropertyAccessExpression(e)||!Ll.has(e.getName()))return!1;const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||t.getName()!=="sql")return!1;const s=t.getExpression();return o.isIdentifier(s)&&s.getText()==="ctx"},kl=e=>o.isBinaryExpression(e)||o.isTemplateExpression(e),Ml=e=>e.getFirstAncestorByKind(l.VariableDeclaration)?.getName()??"<module>",Kl=(e,t)=>{if(!Dl(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!kl(s)))return{exportName:Ml(e),file:t,line:s.getStartLineNumber()}},_l=(e,t)=>F(e,t,Kl),zl=[["convex",["convex","@convex-dev/"]],["supabase",["@supabase/"]],["firebase",["firebase","@firebase/","firebase-admin"]]],$l=e=>{for(const[t,s]of zl)for(const n of s)if(e===n||e.startsWith(n.endsWith("/")?n:`${n}/`))return t},Ul=(e,t)=>{const s=[];for(const n of m(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const i of r.getImportDeclarations()){const a=i.getModuleSpecifierValue(),c=$l(a);c!==void 0&&s.push({file:x(t,n),line:i.getStartLineNumber(),moduleSpecifier:a,platform:c})}}return s},Bl=new Set(["createMultipartUpload","delete","download","generateUploadUrl","get","getMetadata","getPresignedUrl","getSignedUrl","getUrl","head","put","resumeMultipartUpload","store","upload"]),ql=(e,t,s=[])=>{const n=new Map(s.map(i=>[`${i.filePath}:${i.exportName}`,i.visibility]));return Ee(e,t,{argIndex:0,matchReceiver:i=>i==="ctx.storage"||i.startsWith("ctx.storage."),methods:Bl,requireUnmodifiedReach:!0}).map(i=>{const a=n.get(`${i.file}:${i.exportName}`);return a===void 0?i:{...i,visibility:a}})},jl=new Map([["generateUploadUrl",1],["getPresignedUrl",1],["getSignedUrl",1],["store",2],["upload",2]]),Vl=e=>e&&o.isNumericLiteral(e)?Number(e.getText()):void 0,Wl=e=>{if(e===void 0)return{analyzable:!0,presentKeys:[]};if(!o.isObjectLiteralExpression(e))return{analyzable:!1,presentKeys:[]};const t=[];let s,n=!1;for(const r of e.getProperties()){if(o.isSpreadAssignment(r)){n=!0;continue}if(o.isPropertyAssignment(r)){const i=y(r);t.push(i),i==="expiresInSeconds"&&(s=Vl(r.getInitializer()));continue}(o.isShorthandPropertyAssignment(r)||o.isMethodDeclaration(r))&&t.push(y(r))}return{analyzable:!n,expiresInSeconds:s,presentKeys:t}},Hl=e=>{if(!o.isPropertyAccessExpression(e))return;const t=e.getName(),s=jl.get(t);if(s===void 0)return;const n=e.getExpression().getText();return n==="ctx.storage"||n.startsWith("ctx.storage.")?{method:t,optionsIndex:s}:void 0},Gl=(e,t)=>{const s=Hl(e.getExpression());if(s!==void 0)return{exportName:A(e),file:t,line:e.getStartLineNumber(),method:s.method,...Wl(e.getArguments()[s.optionsIndex])}},Yl=(e,t)=>F(e,t,Gl),Ql=(e,t)=>{const s=on(t.target);return{...s===void 0?{}:{platform:s},analytics:e.analytics||t.dependencies.has("@lunora/bindings"),auth:t.dependencies.has("@lunora/auth"),containers:e.container||t.containerCount>0||t.dependencies.has("@lunora/container"),flags:e.flags||t.dependencies.has("@lunora/flags"),kv:e.kv||t.dependencies.has("@lunora/bindings"),mail:e.mail||t.dependencies.has("@lunora/mail"),notifications:e.notify||t.dependencies.has("@lunora/notify"),payments:e.payments||t.hasPaymentTables,queues:t.queueCount>0||t.dependencies.has("@lunora/queue"),scheduler:e.scheduler||t.cronCount>0||t.dependencies.has("@lunora/scheduler"),storage:e.storage||t.storageRuleCount>0||t.storageColumnCount>0||t.dependencies.has("@lunora/storage"),vectors:t.vectorStoreSupported&&t.vectorIndexCount>0,workflows:e.workflows||t.workflowCount>0||t.dependencies.has("@lunora/workflow")}},Xl=(e,t,s)=>({cacheKey:`procedure_arguments_unreadable:${e}:${t}`,categories:["SCHEMA"],description:"Codegen reads an argument record statically. One built at runtime — a factory call, or a property off a value it cannot follow — has no literal to read, so the generated `FunctionReference` carries only the arguments it could see while the runtime validator still enforces all of them.",detail:`\`${t}\` in \`${e}\` (line ${s.toString()}) declares arguments codegen could not read, so its generated type is missing some of them.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:t,filePath:e,line:s},name:"procedure_arguments_unreadable",remediation:`Declare the arguments as an object literal, or as a \`const\` object literal the chain names — \`const ${t}Args = { … };\` then \`.input(${t}Args)\`. Both resolve; a record returned by a call does not.`,title:"Procedure arguments are missing from the generated type"}),Zl=(e,t)=>{if(t===void 0){const s=e.getArguments()[0];if(s===void 0||!o.isObjectLiteralExpression(s)||C(s,"args")===void 0)return!1}return ze(e,t).opaque},Jl=(e,t)=>{const s=[],n=(r,i)=>{const a=r.getInitializer();if(a===void 0||!o.isCallExpression(a))return;const c=z(a);c!==void 0&&Zl(a,c.receiver)&&s.push(Xl(t,i,a.getStartLineNumber()))};for(const r of e.getVariableStatements().filter(i=>i.isExported()))for(const i of r.getDeclarations())n(i,i.getName());return s},eu=(e,t)=>{const s=[];for(const n of m(t)){const r=e.getSourceFile(n);r!==void 0&&s.push(...Jl(r,x(t,n)))}return s.toSorted((n,r)=>n.cacheKey.localeCompare(r.cacheKey))},tu=new Map([["AgentDefinition",{call:"defineAgent({ … })",file:"agents"}],["ContainerDefinition",{call:"defineContainer({ … })",file:"containers"}],["QueueDefinition",{call:"defineQueue({ … })",file:"queues",note:"A dropped queue has no caller to fail — its consumer is simply never wired."}],["RegisteredAction",{call:"action.input({ … }).action(handler)"}],["RegisteredLifecycleHook",{call:"onConnect(handler)",note:"Substitute the hook you called: `onConnect`, `onDisconnect` and `onShardInit` share one type, so codegen cannot tell which you wrote. A dropped hook has no caller to fail — it silently never fires."}],["RegisteredMigration",{call:"defineMigration({ … })",note:"A dropped migration never runs, so `lunora migrate up` reports nothing to do."}],["RegisteredMutation",{call:"mutation.input({ … }).mutation(handler)"}],["RegisteredMutator",{call:"defineMutator({ … })",file:"mutators"}],["RegisteredQuery",{call:"query.input({ … }).query(handler)"}],["RegisteredReactor",{call:"onQueryChange(select, handler)",note:"A dropped reactor has no caller to fail — it silently never runs."}],["RegisteredShape",{call:"defineShape({ … })",file:"shapes"}],["RegisteredStream",{call:"query.input({ … }).stream(handler)"}],["RegisteredWhisperAuthorizer",{call:"onWhisper(handler)",note:"A dropped authorizer has no caller to fail — the whisper topics it was meant to gate silently stay open to every socket on the shard."}],["SubscriptionDefinition",{call:"defineSubscription(topic, { … })",file:"queues",note:"A dropped subscription is never published to — its topic's messages simply never reach it."}],["WorkflowDefinition",{call:"defineWorkflow({ … })",file:"workflows"}]]),Se=({byName:e,byPath:t},s,n)=>t.has(`${s}:${n}`)||e.has(n),Es=e=>!e.isAny(),Ue=e=>{const t=e.getType();if(!Es(t))return;const s=t.getAliasSymbol()?.getName()??t.getSymbol()?.getName(),n=s===void 0?void 0:tu.get(s);return n===void 0||s===void 0?void 0:{...n,typeName:s}},Ss=e=>{const t=e.getInitializer();return t===void 0?!1:o.isCallExpression(t)||o.isIdentifier(t)||o.isPropertyAccessExpression(t)},ys={cause:"codegen recognises a registration only when the initializer is the registering call itself, and this one comes from a factory or an alias",remediation:"A factory that returns a registration cannot be read statically — inline it, or export what the factory builds."},su=e=>({cause:`codegen reads this kind of registration only from \`lunora/${e}.ts\`, and this is a different module`,remediation:`Move it into \`lunora/${e}.ts\` — the declaration itself is fine.`}),nu={cause:"the binding is exported by a separate `export { … }` statement, and codegen reads the `export` keyword on the declaration itself",remediation:"Move the keyword onto the declaration and drop the separate export statement."},Be=(e,t,s,n,r)=>{const{call:i,file:a,note:c,typeName:u}=s,d=a!==void 0&&e!==a?a:void 0,g=d===void 0?r:su(d),h=c===void 0?g.remediation:`${c} ${g.remediation}`;return{cacheKey:`procedure_not_registered:${e}:${t}`,categories:["SCHEMA"],description:"Codegen registers an export only when the declaration carries `export` and its initializer is literally the registering call. Written any other way it exists at runtime but never reaches the generated output — `_generated/api.ts` for a procedure, the lifecycle manifest for a hook or reactor — so a caller cannot address it and a hook never fires.",detail:`\`${t}\` in \`${e}\` (line ${n.toString()}) has type \`${u}\` but was not registered — ${g.cause}.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:t,filePath:e,line:n,typeName:u},name:"procedure_not_registered",remediation:d===void 0?`Assign the registration directly: \`export const ${t} = ${i};\`. ${h}`:h,title:"Procedure exists at runtime but is missing from the generated API"}},ru=(e,t,s)=>{const n=[];for(const r of e.getVariableStatements().filter(i=>i.isExported()))for(const i of r.getDeclarations()){const a=i.getName();if(Se(s,t,a)||!Ss(i))continue;const c=Ue(i);c!==void 0&&n.push(Be(t,a,c,i.getStartLineNumber(),ys))}return n},iu=(e,t,s)=>{if(Se(s,t,"default"))return[];const n=[];for(const r of e.getExportAssignments().filter(i=>!i.isExportEquals())){const i=Ue(r.getExpression());i!==void 0&&n.push(Be(t,"default",i,r.getStartLineNumber(),ys))}return n},ou=(e,t,s)=>{const n=[];for(const r of e.getExportDeclarations().filter(i=>i.getModuleSpecifier()===void 0))for(const i of r.getNamedExports()){const a=i.getAliasNode()?.getText()??i.getName();if(Se(s,t,a))continue;const c=i.getLocalTargetDeclarations().find(d=>o.isVariableDeclaration(d));if(c===void 0||!Ss(c))continue;const u=Ue(c);u!==void 0&&n.push(Be(t,a,u,i.getStartLineNumber(),nu))}return n},au=(e,t,s)=>[...ru(e,t,s),...iu(e,t,s),...ou(e,t,s)],cu=(e,t,s)=>e.getVariableStatements().filter(n=>n.isExported()).flatMap(n=>n.getDeclarations()).filter(n=>Se(s,t,n.getName())).filter(n=>{const r=n.getInitializer();return r!==void 0&&o.isCallExpression(r)&&o.isPropertyAccessExpression(r.getExpression())}).map(n=>({declaration:n,exportName:n.getName(),relativePath:t})),lu=({exportName:e,relativePath:t})=>({cacheKey:"procedure_type_check_unavailable",categories:["SCHEMA"],description:"Codegen cross-checks every export in `lunora/` against its TYPE to catch a procedure the syntactic scan dropped — a factory-assigned export, an alias, a separate `export { … }`. That check needs the type checker to resolve `@lunora/server`; when it cannot, the check reports nothing regardless of what the code does.",detail:`Type resolution for \`lunora/\` is unavailable — the registered procedure \`${e}\` in \`${t}\` types as \`any\`, as does every other one — so codegen cannot tell you when an export is dropped from \`_generated/api.ts\`. A dropped procedure will surface as \`Property '<name>' does not exist\` at its call site instead.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:e,filePath:t},name:"procedure_type_check_unavailable",remediation:`Check what codegen sees: \`${e}\` should have a procedure type, not \`any\`. It needs a \`tsconfig.json\` at or above \`lunora/\` — the one codegen finds walking up from there, which is not necessarily the one your editor uses — resolving \`lunorash\` / \`@lunora/server\` to declarations that exist on disk (a workspace dependency has to be built first).`,title:"Codegen cannot type-check `lunora/`, so dropped procedures go unreported"}),uu=(e,t,s)=>{const n=[],r=[];for(const a of m(t)){const c=e.getSourceFile(a);if(c===void 0)continue;const u=x(t,a);n.push(...au(c,u,s)),r.push(...cu(c,u,s))}const[i]=r;return i!==void 0&&r.every(({declaration:a})=>!Es(a.getType()))&&n.push(lu(i)),n.toSorted((a,c)=>a.cacheKey.localeCompare(c.cacheKey))},du=new Set(["when","where"]),Fe=new Set(["definePolicy","defineShape"]),fu=e=>{if(!o.isCallExpression(e))return;const t=e.getExpression();if(o.isPropertyAccessExpression(t)){const n=t.getName();return Fe.has(n)?n:void 0}if(!o.isIdentifier(t))return;for(const n of t.getSymbol()?.getDeclarations()??[])if(o.isImportSpecifier(n)){const r=n.getNameNode().getText();return Fe.has(r)?r:void 0}const s=t.getText();return Fe.has(s)?s:void 0},gu=e=>o.isObjectLiteralExpression(e)&&e.getProperties().length===0,As=e=>{if(e!==void 0){if(o.isReturnStatement(e)&&e.getExpression()===void 0||e.getKind()===l.UndefinedKeyword||e.getText()==="undefined")return"undefined";if(gu(e))return"empty-object";if(o.isParenthesizedExpression(e))return As(e.getExpression())}},qe=e=>e.getAncestors().find(t=>o.isArrowFunction(t)||o.isFunctionExpression(t)||o.isFunctionDeclaration(t)),pu=e=>e.getDescendantsOfKind(l.ReturnStatement).filter(t=>qe(t)===e),bs=e=>e.getDescendantsOfKind(l.ConditionalExpression).filter(t=>qe(t)===e),mu=e=>{const t=pu(e);return t.length>1?!0:t.some(s=>s.getFirstAncestorByKind(l.IfStatement)!==void 0)||bs(e).length>0},hu=e=>e.getDescendantsOfKind(l.IfStatement).filter(t=>qe(t)===e),ke=e=>e.getKind()===l.NullKeyword||e.getKind()===l.FalseKeyword||o.isIdentifier(e)&&e.getText()==="undefined"?!0:o.isNumericLiteral(e)?e.getLiteralValue()===0:o.isStringLiteral(e)&&e.getLiteralValue()==="",vu=(e,t)=>ke(e)||ke(t),xu=new Map([[l.EqualsEqualsEqualsToken,"positive"],[l.EqualsEqualsToken,"positive"],[l.ExclamationEqualsEqualsToken,"negative"],[l.ExclamationEqualsToken,"negative"]]),Kt=e=>!ke(e)&&(o.isLiteralExpression(e)||e.getKind()===l.TrueKeyword),Eu=(e,t,s)=>{const n=xu.get(e);if(n!==void 0)return vu(t,s)?n==="positive"?"negative":"positive":Kt(t)||Kt(s)?void 0:n},Y=e=>{if(o.isParenthesizedExpression(e))return Y(e.getExpression());if(o.isPrefixUnaryExpression(e)&&e.getOperatorToken()===l.ExclamationToken)return"negative";if(o.isBinaryExpression(e)){const t=e.getOperatorToken().getKind(),s=Eu(t,e.getLeft(),e.getRight());if(s!==void 0)return s;if(t===l.AmpersandAmpersandToken||t===l.BarBarToken){const n=Y(e.getLeft()),r=Y(e.getRight());return n===r?n:"indeterminate"}}return o.isIdentifier(e)||o.isPropertyAccessExpression(e)||o.isElementAccessExpression(e)||o.isCallExpression(e)?"positive":"indeterminate"},_t=e=>{if(e!==void 0){if(o.isReturnStatement(e))return e;if(o.isBlock(e)){const t=e.getStatements().at(-1);return t!==void 0&&o.isReturnStatement(t)?t:void 0}}},Su=e=>{if(e.getElseStatement()!==void 0)return;const t=e.getNextSiblingIfKind(l.ReturnStatement);return t!==void 0&&t.getNextSibling()===void 0?t:void 0},yu=e=>o.isReturnStatement(e)?e.getExpression()??e:e,Au=e=>{const t=[];for(const s of bs(e)){const n=Y(s.getCondition());n==="positive"?t.push(s.getWhenFalse()):n==="negative"&&t.push(s.getWhenTrue())}for(const s of hu(e)){const n=Y(s.getExpression());if(n==="indeterminate")continue;const r=n==="negative"?_t(s.getThenStatement()):_t(s.getElseStatement())??Su(s);r!==void 0&&t.push(yu(r))}return t},bu=e=>{for(const t of e.getAncestors())if(o.isVariableDeclaration(t)){const s=t.getNameNode();if(o.isIdentifier(s))return s.getText()}return"<anonymous>"},Nu=(e,t,s)=>{if(!o.isCallExpression(e))return[];const[n]=e.getArguments();if(!n||!o.isObjectLiteralExpression(n))return[];const r=[];for(const i of n.getProperties()){if(!o.isPropertyAssignment(i)||!du.has(y(i)))continue;const a=i.getInitializer();if(!(!a||!(o.isArrowFunction(a)||o.isFunctionExpression(a)))&&mu(a))for(const c of Au(a)){const u=As(c);u!==void 0&&r.push({exportName:bu(e),file:s,form:u,key:y(i),line:c.getStartLineNumber(),owner:t})}}return r},Pu=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression)){const r=fu(n);r!==void 0&&s.push(...Nu(n,r,t))}return s},wu=(e,t)=>{const s=[];for(const n of m(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Pu(r,x(t,n)))}return s},Iu=new Set(["query","upsert","upsertNow"]),Tu=e=>{if(!o.isPropertyAccessExpression(e))return;const t=e.getName();if(Iu.has(t))return e.getExpression().getText()==="ctx.vectors"?t:void 0},Cu=(e,t)=>{const s=Tu(e.getExpression());if(s===void 0)return;const n=e.getArguments()[1];if(!n)return;const r=P(n,"namespace");if(!(!r||!M(r)||U(r)))return{exportName:A(e),file:t,line:e.getStartLineNumber(),method:s}},Fu=(e,t)=>F(e,t,Cu),Ou=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||t.getName()!=="get")return!1;const s=t.getExpression();return o.isPropertyAccessExpression(s)?s.getName()==="workflows":o.isIdentifier(s)&&s.getText()==="workflows"},Ru=e=>{const t=e.getArguments()[0];return t&&o.isStringLiteral(t)?t.getLiteralText():""},Lu=(e,t)=>{const s=[];for(const n of m(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n),i=x(t,n);for(const a of r.getDescendantsOfKind(l.CallExpression)){if(!Ou(a))continue;const c=Ys(a);c!==""&&s.push({exportName:c,file:i,line:a.getStartLineNumber(),workflow:Ru(a)})}}return s},Du=".lunora-schema.json",Me=(e,t)=>{w(e)&&Ut(e,"utf8")===t||Ms(e,t,"utf8")},ku=(e,t)=>{if(t===""){Ks(e,{force:!0});return}Me(e,t)},Mu=e=>{const t=S(e,"package.json");if(w(t))try{const s=JSON.parse(Ut(t,"utf8"));return typeof s.version=="string"&&s.version!==""?s.version:void 0}catch{return}},Ku=()=>{const e=process.env.LUNORA_CODEGEN_TIMING;return e!==void 0&&e!==""},_u=e=>{let t=w(e)?e:ce(e);for(;t&&t!==ce(t);){const s=S(t,"tsconfig.json");if(w(s))return s;t=ce(t)}},zt=e=>e.replaceAll("\\","/"),zu=(e,t,s)=>{if(s&&e.length>0){const i=e.map(a=>`"${a.exportName}"`).join(", ");throw new $("MASK_UNSUPPORTED",`This project declares a \`mask(...)\` policy whose argument isn't a plain object literal (e.g. \`mask(sharedPolicies)\` referencing a hoisted variable), or contains a spread (\`...shared\`) or computed key (\`[name]:\`) codegen can't enumerate, so codegen can't tell which columns it masks. Because the project also declares replication shape(s) (${i}), codegen can't verify none of them replicate a table that policy masks — inline every table and column as literal keys so codegen can verify it, or remove the affected shape(s).`,{status:422})}const n=new Map;for(const i of t.columns){const a=n.get(i.table)??[];a.push(i.column),n.set(i.table,a)}const r=t.columns.length>0;for(const i of e){if(i.table===void 0){if(r)throw new $("MASK_UNSUPPORTED",`defineShape "${i.exportName}" has a non-literal \`table\` (a variable or expression, not a string literal), so codegen can't statically verify it doesn't replicate a table that masks a column. This project masks at least one column elsewhere, so the combination can't be proven safe — change "${i.exportName}"'s \`table\` to a plain string literal so codegen can verify it, or remove the mask(s) on the table it targets.`,{status:422});continue}const a=n.get(i.table);if(a===void 0)continue;const c=a.map(u=>`"${u}"`).join(", ");throw new $("MASK_UNSUPPORTED",`defineShape "${i.exportName}" replicates table "${i.table}", which masks column(s) ${c} on at least one procedure. A shape runs no procedure, so \`.use(mask(...))\` never applies to its replicated rows — remove the shape, unmask the table, or wait for shape-masking support.`,{status:422})}},pe=(e,t,s)=>{const n=e.getSourceFile(t);if(n===void 0){e.createSourceFile(t,s,{overwrite:!0});return}n.getFullText()!==s&&n.replaceWithText(s)},$t=(e,t,s)=>e.getSourceFile(t)?.getFullText()===s,$u=8,Uu=e=>{const{agents:t,apiPath:s,generatedFunctionsPath:n,lunoraDirectory:r,migrations:i,project:a,shapes:c,usesSandbox:u,useUmbrella:d,workflows:g}=e,h=()=>An(()=>{const N=bn(a,r),L=On(a,r);return{functions:N,httpRoutes:Nn(a,r),mutators:L}});let{erased:O,value:{functions:R,httpRoutes:p,mutators:T}}=h();mt([...R,...T].map(N=>N.filePath)),mt(p.filter(N=>N.stream).map(N=>N.filePath),"http-stream");for(let N=1;;N+=1){const L=Zn({agents:t,functions:R,httpRoutes:p,mutators:T,useUmbrella:d,workflows:g}),D=lr({agents:t,functions:R,migrations:i,mutators:T,shapes:c,useUmbrella:d,usesSandbox:u});if(N>=$u||$t(a,s,L)&&$t(a,n,D))return{apiContent:L,erased:O,functions:R,functionsContent:D,httpRoutes:p,mutators:T};pe(a,s,L),pe(a,n,D),{erased:O,value:{functions:R,httpRoutes:p,mutators:T}}=h()}},Bu=e=>{const t=_u(e);return t?new ft({skipAddingFilesFromTsConfig:!1,tsConfigFilePath:t,useInMemoryFileSystem:!1}):new ft({skipAddingFilesFromTsConfig:!0,useInMemoryFileSystem:!1})},Hd=(e,t)=>{const s=m(t),n=S(t,"schema.ts");w(n)&&s.push(n);for(const c of s){const u=e.getSourceFile(c);u===void 0?e.addSourceFileAtPath(c):u.refreshFromFileSystemSync()}const r=new Set(s.map(c=>zt(c))),i=zt(t),a=`${i}/`;for(const c of e.getSourceFiles()){const u=c.getFilePath();(u===i||u.startsWith(a))&&!r.has(u)&&e.removeSourceFile(c)}for(const c of e.getSourceFiles()){const u=c.getFilePath();if(!(u===i||u.startsWith(a)||u.includes("/node_modules/")))try{c.refreshFromFileSystemSync()}catch{e.removeSourceFile(c)}}},Gd=e=>{const t=Ku(),s=t?Ie.now():0,n=S(e.projectRoot,e.lunoraDirectory??"lunora"),r=S(n,"schema.ts");if(!w(r))throw new $("INTERNAL",`schema.ts not found at ${r}`);const i=e.project??Bu(n);mn(Ao);const a=_n(i,r,e.projectRoot),{agents:c,containers:u,crons:d,dataModelContent:g,dependencies:h,entryCronTriggers:O,env:R,featureUsage:p,hasFlags:T,hasNotify:N,identity:L,platformGate:D,queues:v,serverContent:q,storageRulesMetadata:j,topics:te,usesSandbox:se,useUmbrella:K,workflows:k}=Ur({lunoraDirectory:n,project:i,projectRoot:e.projectRoot,schema:a,target:e.target});aa(a,a.jurisdiction===void 0?void 0:ia(i,n));const E=S(n,"_generated"),Ns=S(E,"dataModel.ts"),Ps=S(E,"server.ts"),ws=S(E,"api.ts"),Is=S(E,"functions.ts");pe(i,Ns,g),pe(i,Ps,q);const ne=Tn(i,n),V=qn(i,n),{apiContent:je,erased:Ts,functions:W,functionsContent:Ve,httpRoutes:Cs,mutators:re}=Uu({agents:c,apiPath:ws,generatedFunctionsPath:Is,lunoraDirectory:n,migrations:ne,project:i,shapes:V,useUmbrella:K,usesSandbox:se,workflows:k}),ie=e.lint===!1?void 0:Us({adminRoutes:Yr(i,n),aiRawRuns:Zr(i,n),aiToolSideEffects:ci(i,n),argumentDerivedFetches:di(i,n),argumentValidators:yi(i,n),authApiCalls:hn(i,n),authConfigs:Oi(i,n),browserUrlAccesses:Mi(i,n),configCalls:ji(i,n),containerKeyAccesses:Wi(i,n),containerOverrides:Zi(i,n),containers:u,exportSinks:so(i,n),staleMigrationImports:Ul(i,n),failOpenGuards:ao(i,n),flagReads:vo(i,n),flagSecurityDefaults:yo(i,n),geoIndexUsages:Po(i,n),httpActionGuards:Ko(i,n),httpHeaderWrites:Ho(i,n),hyperdriveCalls:Pn(i,n),identityClaimReads:ea(i,n),imageDeliveryUrlAccesses:sa(i,n),inserts:wn(i,n),kvKeyAccesses:la(i,n,W),mailRecipientAccesses:pa(i,n),maskProcedures:In(i,n),maskStrategies:Aa(i,n),mutatorWrites:Ta(i,n),nondeterministicCalls:Rn(i,n),normalizeIdAuthorizations:ja(i,n),notifyCalls:Dn(i,n),notifyConfig:Ln(i,n),mutators:re,ownerFieldWrites:ec(i,n,W,re),unrestrictedWhereBranches:wu(i,n),paymentWebhooks:cc(i,n),privilegedDispatches:yc(i,n),procedureProtections:il(i,n),queries:pn(i,n),queues:v,r2sqlCalls:kn(i,n),ratelimitKeySelectors:fl(i,n),rawRowReturns:El(i,n),relationLoads:Al(i,n),rlsProcedures:Mn(i,n),schema:a,secretLiterals:Fl(i,n),shapes:V,softDeleteReads:Rl(i,n),sqlInterpolations:_l(i,n),storageKeyAccesses:ql(i,n,W),storageUploads:Yl(i,n),vectorNamespaceAccesses:Fu(i,n),workflowCalls:Lu(i,n),workflows:k,wranglerVariables:e.wranglerVariables}),We=ie===void 0?[]:dr(e.projectRoot,[..._s(ie,{source:"static"}),...uu(i,n,{byName:new Set([...k,...v,...c,...u].map(f=>f.exportName)),byPath:new Set([...W,...re,...V,...ne].map(f=>`${f.filePath}:${f.exportName}`))}),...eu(i,n),...yn(Ts,n)]),Fs=Kn(i,n),He=Ea(i,n);zu(V,He,va(i,n));const Os=T?fo(i,n):[],ye=D.signals.vectorStore!==!1,G=Ql(p,{containerCount:u.length,cronCount:d.length,dependencies:h,hasPaymentTables:nc(a.tables),queueCount:v.length,storageColumnCount:Object.keys(Qt(a)).length,storageRuleCount:j.rules.length,vectorIndexCount:a.vectorIndexes.length,target:Yt(e.projectRoot,e.target),vectorStoreSupported:ye,workflowCount:k.length}),Ge=t?Ie.now():0,Ae=Yn(a,ne.map(f=>f.id)),Ye=an({advisories:We.filter(f=>f.name!=="procedure_type_check_unavailable"),advisorProcedures:ie?.procedureProtections??[],agents:c,containers:u,env:R,flagKeys:Os,hasAccessFacade:p.access,hasAi:p.ai,hasAnalytics:p.analytics,hasBrowser:p.browser,hasFlags:T,hasHyperdrive:p.hyperdrive,hasImages:p.images,hasKv:p.kv,hasNotify:N,hasPayments:p.payments,hasPipelines:p.pipelines,hasR2sql:p.r2sql,hasVectors:ye,hasX402:p.x402,maskMetadata:He,mutators:re,queues:v,rlsMetadata:Fs,schema:a,schemaSnapshot:Ae,shapes:V,storageRules:j,studioFeatures:G,topics:te,useUmbrella:K,workflows:k}),Qe=Qn(V,h.has("@lunora/db"),K),Xe=Jn(u,a.jurisdiction),Ze=er(k),Je=tr(c),et=sr(v),tt=nr(d),Rs=rr(G.scheduler),Ls=ir(a.tables,K),st=or(a.vectorIndexes),oe=cr(a,K),nt=Xn(h.has("@lunora/seed")),ae=e.apiSpec??"openapi",be=ae==="openapi"||ae==="both",Ne=ae==="openrpc"||ae==="both",rt=jn({emailAgents:c.filter(f=>f.onEmail===!0).map(f=>({className:f.className,exportName:f.exportName})),hasAccess:h.has("@lunora/cloudflare-access"),hasAi:p.ai,hasAnalytics:p.analytics,hasAuth:h.has("@lunora/auth"),hasBrowser:p.browser,hasFramework:h.has("@lunora/astro")||h.has("@lunora/svelte")||h.has("@lunora/vue")||w(S(e.projectRoot,"src","worker.ts")),hasGlobal:a.tables.some(f=>Bt(f)),hasHyperdrive:p.hyperdrive,hasHyperdriveGlobal:a.tables.some(f=>qt(f)),hasImages:p.images,hasKv:p.kv,hasKvIntrospector:G.kv,hasNotify:N,hasPayments:p.payments,hasR2sql:p.r2sql,hasQueue:v.some(f=>f.mode==="push"),hasScheduler:G.scheduler,hasSourcedTables:a.tables.some(f=>f.externalSource!==void 0),hasStorage:G.storage,hasVectors:ye,hasWorkflow:k.length>0,hasX402:p.x402,identity:L,jurisdiction:a.jurisdiction,jurisdictionPinsAuth:a.jurisdictionPinsAuth===!0,tables:a.tables.map(f=>({name:f.name,shardMode:f.shardMode})),useUmbrella:K,vectorIndexCount:a.vectorIndexes.length,voiceAgents:c.filter(f=>f.voice===!0&&f.voiceBindingName!==void 0).map(f=>({bindingName:f.voiceBindingName,exportName:f.exportName})),wantsOpenApi:be,wantsOpenRpc:Ne}),it=Mu(e.projectRoot),ot=Vn({functions:W,httpRoutes:Cs,version:it}),at=Hn({functions:W,version:it}),ct=`${JSON.stringify(ot,void 0,2)}
|
|
8
|
+
`,lt=`${JSON.stringify(at,void 0,2)}
|
|
9
|
+
`,ut=Wn(ot),dt=Gn(at),Pe=S(n,Du),Ds=w(Pe),we=[];if(!e.dryRun){w(E)||ks(E,{recursive:!0});const f=(B,H)=>{Me(S(E,B),H),we.push(B)},I=(B,H)=>{ku(S(E,B),H),H!==""&&we.push(B)};f("app.ts",rt),f("dataModel.ts",g),f("api.ts",je),f("server.ts",q),f("functions.ts",Ve),f("shard.ts",Ye),f("crons.ts",tt),f("vectors.ts",st),f("drizzle.global.ts",oe.global),f("drizzle.shard.ts",oe.shard),I("containers.ts",Xe),I("workflows.ts",Ze),I("agents.ts",Je),I("queues.ts",et),I("scheduler.ts",Rs),I("shardRegistry.ts",Ls),I("seed.ts",nt),I("collections.ts",Qe),I("openapi.json",be?ct:""),I("openapi.ts",be?ut:""),I("openrpc.json",Ne?lt:""),I("openrpc.ts",Ne?dt:""),(!Ds||e.updateSchemaBaseline===!0)&&Me(Pe,$s(Ae))}if(t){const f=Ie.now(),I=Math.round(f-s),B=Math.round(Ge-s),H=Math.round(f-Ge);console.error(`@lunora/codegen: codegen took ${I.toString()}ms (discovery ${B.toString()}ms, emit ${H.toString()}ms)`)}return{advisories:We,advisorContext:ie,agents:c,containers:u,cronTriggers:[...new Set([...ar(d),...O])],generated:{agents:Je,api:je,app:rt,collections:Qe,containers:Xe,crons:tt,dataModel:g,drizzleGlobal:oe.global,drizzleShard:oe.shard,functions:Ve,openApi:ct,openApiModule:ut,openRpc:lt,openRpcModule:dt,queues:et,seed:nt,server:q,shard:Ye,vectors:st,workflows:Ze},migrations:ne,outputDirectory:E,platformDiagnostics:D.diagnostics,queues:v,schemaSnapshot:Ae,schemaSnapshotPath:Pe,workflows:k,writtenFiles:we}};export{Du as SCHEMA_SNAPSHOT_FILENAME,Bu as createCodegenProject,_u as findTsconfig,Hd as refreshCodegenProject,Gd as runCodegen};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{existsSync as y}from"node:fs";import{join as b}from"node:path";import{LunoraError as w}from"@lunora/errors";import{isValidCronExpression as k}from"@lunora/scheduler";import{workflowDefaultName as E,workflowClassName as S}from"@lunora/workflow";import{Node as n,VariableDeclarationKind as v,SyntaxKind as P}from"ts-morph";import{diagnosticAt as c}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{unwrapToCallExpression as x,findObjectProperty as d,stringPropertyFor as L}from"./listLunoraSourceFiles-DP-5e-RE.mjs";const $="workflows.ts",A=new Set(["do","sleep","sleepUntil","waitForEvent"]),N=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"),C=(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})},W=(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 a=f(g(s,e,"limits"),"steps");if(a===void 0)t.limits={};else{const l=C(a,e,"limits.steps");if(!Number.isInteger(l)||l<=0)throw c(a,`workflow "${e}": \`limits.steps\` must be a positive integer (got ${String(l)})`);t.limits={steps:l}}}const i=f(o,"defaultRetention");if(i!==void 0){const a=g(i,e,"defaultRetention"),l={};for(const u of["errorRetention","successRetention"]){const p=f(a,u);p!==void 0&&(l[u]=m(p,e,`defaultRetention.${u}`))}t.defaultRetention=l}return t},I=o=>{const e=o.getExpression();if(!n.isPropertyAccessExpression(e)||!A.has(e.getName()))return!1;const t=e.getExpression();return n.isPropertyAccessExpression(t)&&t.getName()==="step"?!0:n.isIdentifier(t)&&t.getText()==="step"},O=o=>{const e=d(o,"handler");if(!e)return[];const t=n.isPropertyAssignment(e)?e.getInitializer():e;if(!t)return[];const r=[];for(const s of t.getDescendantsOfKind(P.CallExpression)){if(!I(s))continue;const i=s.getArguments()[0];!i||!(n.isStringLiteral(i)||n.isNoSubstitutionTemplateLiteral(i))||r.push({line:s.getStartLineNumber(),method:s.getExpression().getName(),name:i.getLiteralValue()})}return r},h=o=>{let e=o;for(;e&&(n.isAsExpression(e)||n.isSatisfiesExpression(e)||n.isParenthesizedExpression(e));)e=e.getExpression();return e},F=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()===v.Const?h(t.getInitializer()):void 0;if(s&&n.isObjectLiteralExpression(s))return s}},T=(o,e)=>{const t=F(o.getArguments()[0]);if(!t)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 r={className:S(e),exportName:e,name:E(e),steps:O(t)},s=d(t,"name");return s&&n.isPropertyAssignment(s)&&(r.name=m(s.getInitializerOrThrow(),e,"name")),{...r,...W(t,e)}},j=o=>{const e=[];for(const t of o.getVariableDeclarations()){if(!t.isExported())continue;const r=x(t.getInitializer());if(!r)continue;const s=r.getExpression();if(!n.isIdentifier(s)||!N(s))continue;const i=t.getNameNode();if(!n.isIdentifier(i))throw c(i,"defineWorkflow exports must be plain named exports (no destructuring)");e.push(T(r,i.getText()))}return e},R=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 i=t.get(r.className);if(i!==void 0)throw new w("DUPLICATE_WORKFLOW_CLASS",`Duplicate workflow class "${r.className}": produced by both "${i}" and "${r.exportName}". Workflow export names must yield unique generated class names.`,{status:500});t.set(r.className,r.exportName)}},B=(o,e)=>{const t=b(e,$);if(!y(t))return[];const r=o.getSourceFile(t)??o.addSourceFileAtPath(t),s=j(r);return s.sort((i,a)=>i.exportName.localeCompare(a.exportName)),R(s),s};export{$ as WORKFLOWS_FILENAME,B as discoverWorkflows};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as L}from"@lunora/errors";import{CRON_SCHEDULE_KINDS as A,isValidCronExpression as O,warnIfSecondsLeading as S,compileCronSchedule as
|
|
1
|
+
import{LunoraError as L}from"@lunora/errors";import{CRON_SCHEDULE_KINDS as A,isValidCronExpression as O,warnIfSecondsLeading as S,compileCronSchedule as I}from"@lunora/scheduler";import{SyntaxKind as m,Node as n}from"ts-morph";import{diagnosticAt as f,CodegenDiagnosticError as R}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{i as b}from"./module-specifiers-WF8iAydP.mjs";import{s as $}from"./paths-C-9fwEgQ.mjs";import{listLunoraSourceFiles as y,propertyKeyName as P}from"./listLunoraSourceFiles-DP-5e-RE.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(n.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 s=r.getInitializer();if(s?.getKind()!==m.CallExpression)continue;const i=s.getExpression();n.isIdentifier(i)&&v(i)&&t.add(r.getName())}return t},V=e=>{let t=e;for(;n.isCallExpression(t)||n.isPropertyAccessExpression(t);)t=t.getExpression();return n.isIdentifier(t)?t.getText():void 0},x=(e,t)=>{const r=e.getArguments()[t];return r&&(n.isStringLiteral(r)||n.isNoSubstitutionTemplateLiteral(r))?r.getLiteralValue():void 0},_=(e,t)=>{if(n.isStringLiteral(e)||n.isNoSubstitutionTemplateLiteral(e)||n.isNumericLiteral(e))return e.getLiteralValue();if(n.isTrueLiteral(e))return!0;if(n.isFalseLiteral(e))return!1;if(n.isPrefixUnaryExpression(e)&&e.getOperatorToken()===m.MinusToken){const r=e.getOperand();if(n.isNumericLiteral(r))return-r.getLiteralValue()}if(n.isObjectLiteralExpression(e))return p(e,t);if(n.isArrayLiteralExpression(e))return e.getElements().map(r=>_(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 s of e.getProperties()){if(!n.isPropertyAssignment(s))throw f(s,`Cron job "${t}" uses an unsupported object property (shorthand/spread/method) where a static literal is required.`,{code:"CRON_NON_STATIC_VALUE",name:"LunoraError",status:500});const i=s.getInitializer();i&&(r[P(s)]=_(i,t))}return r},C=(e,t,r)=>{const s=e.getArguments()[t];if(!s||!n.isPropertyAccessExpression(s))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 i=s.getName(),o=s.getExpression();if(!n.isPropertyAccessExpression(o))throw f(s,`Cron job "${r}" function reference must be of the form internal.file.fn (two property accesses).`,{code:"CRON_NON_STATIC_FN",name:"LunoraError",status:500});const a=o.getName();return`${$(a)}:${i}`},h=e=>({workflow:{className:e.className,exportName:e.exportName}}),w=e=>({workflow:{className:e.className,exportName:e.exportName}}),T=(e,t,r,s,i,o)=>{const a=e.getExpression();if(!n.isIdentifier(a)||a.getText()!==t)return;const c=r.get(e.getName());if(c)return o(c);throw f(e,`Cron job "${s}" targets ${t}.${e.getName()}, but no such ${i} is declared in lunora/${i}s.ts.`,{code:"CRON_NON_STATIC_FN",name:"LunoraError",status:500})},j=(e,t,r,s,i)=>{const o=e.getArguments()[t];if(o&&n.isPropertyAccessExpression(o)){const a=T(o,"workflows",s,r,"workflow",h);if(a)return a;const c=T(o,"agents",i,r,"agent",w);return c||{functionPath:C(e,t,r)}}if(o&&n.isIdentifier(o)){const a=s.get(o.getText()),c=i.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)}},k=/^@lunora\/scheduler:\s*/u,U=(e,t)=>{const r=x(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(!O(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 S(r,`cron expression for job "${t}"`),r},M=(e,t,r)=>{const s=e.getArguments()[1];if(!s||!n.isObjectLiteralExpression(s))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 I(t,p(s,r),r)}catch(i){if(i instanceof R)throw i;const o=i instanceof Error?i.message.replace(k,""):String(i);throw f(e,o,{code:"CRON_SCHEDULE_INVALID",name:"LunoraError",status:500})}},z=(e,t,r,s,i)=>{const o=t.getName();if(!D.has(o)||!r.has(V(t.getExpression())??""))return;const a=x(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=j(e,2,a,s,i),l=e.getArguments()[3];return{args:l&&n.isObjectLiteralExpression(l)?p(l,a):{},cron:c,name:a,...u}},H=e=>{const t=new Set;for(const r of e){if(t.has(r.name))throw new L("DUPLICATE_CRON_NAME",`Duplicate cron job name "${r.name}": cron names must be unique across the project.`,{status:500});t.add(r.name)}},W=(e,t,r=[],s=[])=>{const i=y(t),o=[],a=new Map(r.map(u=>[u.exportName,u])),c=new Map(s.map(u=>[u.exportName,u]));for(const u of i){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(!n.isPropertyAccessExpression(N))continue;const E=z(d,N,g,a,c);E&&o.push(E)}}return o.sort((u,l)=>u.name.localeCompare(l.name)),H(o),o};export{W as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"./ir-DBSvhNa-.mjs";import"./json-data-Chfs2Cz5.mjs";import{w as i,p as r,A as n,n as o,B as g,q as F,l as p,D as u,u as l,m as f,o as w,C as d,t as k,s as A}from"./shard-runtime-oIXHEMU7.mjs";import"./shared-DjUziztz.mjs";export{i as buildDoTypeImports,r as emitAgentFragments,n as emitAgents,o as emitContainerFragments,g as emitContainers,F as emitPaymentFragments,p as emitQueueFragments,u as emitQueues,l as emitQueuesMetadataFragments,f as emitTopicFragments,w as emitWorkflowFragments,d as emitWorkflows,k as emitWorkflowsMetadataFragments,A as emitX402Fragments};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{agentComponent as T}from"@lunora/agent/component";import{LunoraError as P}from"@lunora/errors";import{s as u}from"./paths-C-9fwEgQ.mjs";import{r as j,a as K,b as
|
|
1
|
+
import{agentComponent as T}from"@lunora/agent/component";import{LunoraError as P}from"@lunora/errors";import{s as u}from"./paths-C-9fwEgQ.mjs";import{r as j,a as K,b as h,c as E}from"./qualifiers-BhOL15WZ.mjs";import{G as w,a as B,r as g,p as $,b as x,c as y,d as v}from"./shared-DjUziztz.mjs";const A=t=>{const r=new Map;for(const o of t){const e=r.get(o.filePath)??[];e.push(o),r.set(o.filePath,e)}return[...r.entries()].toSorted(([o],[e])=>o.localeCompare(e))},C=t=>{const r=([o,e])=>{const c=e.toSorted((a,i)=>a.exportName.localeCompare(i.exportName)).map(a=>{const i=h(g(a.args),a.filePath),n=h(E(a),a.filePath);return` ${a.exportName}: FunctionReference<"${a.kind}", ${i}, ${n}>;`}).join(`
|
|
2
2
|
`);return` ${x(u(o))}: {
|
|
3
3
|
${c}
|
|
4
4
|
};`};return A(t).map(o=>r(o)).join(`
|
|
@@ -7,35 +7,35 @@ ${c}
|
|
|
7
7
|
export interface WorkflowReference<Params = Record<string, unknown>> {
|
|
8
8
|
readonly isLunoraWorkflow: true;
|
|
9
9
|
readonly __params?: Params;
|
|
10
|
-
readonly
|
|
10
|
+
readonly className: string;
|
|
11
11
|
readonly name: string;
|
|
12
12
|
}
|
|
13
|
-
`,t.length>0){const c=[...t].toSorted((n,s)=>n.exportName.localeCompare(s.exportName)),
|
|
14
|
-
`),
|
|
13
|
+
`,t.length>0){const c=[...t].toSorted((n,s)=>n.exportName.localeCompare(s.exportName)),a=c.map(n=>` ${n.exportName}: WorkflowReference<WorkflowParamsOf<typeof lunoraWorkflowDefinitions.${n.exportName}>>;`).join(`
|
|
14
|
+
`),i=c.map(n=>` ${y(n.exportName)}: { isLunoraWorkflow: true, className: ${JSON.stringify(n.className)}, name: ${JSON.stringify(n.exportName)} },`).join(`
|
|
15
15
|
`);e+=`
|
|
16
16
|
/** This project's durable workflows, addressable as typed references (e.g. \`crons.daily("digest", …, workflows.digestPipeline, params)\`). */
|
|
17
17
|
export interface WorkflowsRef {
|
|
18
|
-
${
|
|
18
|
+
${a}
|
|
19
19
|
}
|
|
20
20
|
|
|
21
21
|
export const workflows: WorkflowsRef = {
|
|
22
|
-
${
|
|
22
|
+
${i}
|
|
23
23
|
};
|
|
24
24
|
`,o.push(`import type * as lunoraWorkflowDefinitions from "../workflows.js";
|
|
25
|
-
`)}if(r.length>0){const c=[...r].toSorted((n,s)=>n.exportName.localeCompare(s.exportName)),
|
|
26
|
-
`),
|
|
25
|
+
`)}if(r.length>0){const c=[...r].toSorted((n,s)=>n.exportName.localeCompare(s.exportName)),a=c.map(n=>` ${n.exportName}: WorkflowReference<AgentRunInput>;`).join(`
|
|
26
|
+
`),i=c.map(n=>` ${y(n.exportName)}: { isLunoraWorkflow: true, className: ${JSON.stringify(n.className)}, name: ${JSON.stringify(n.name)} },`).join(`
|
|
27
27
|
`);e+=`
|
|
28
28
|
/** This project's durable agents, addressable as typed references for \`cronJobs()\` — each fire starts a fresh agent run (e.g. \`crons.daily("sweep", …, agents.support, { input, threadKey })\`). */
|
|
29
29
|
export interface AgentsRef {
|
|
30
|
-
${
|
|
30
|
+
${a}
|
|
31
31
|
}
|
|
32
32
|
|
|
33
33
|
export const agents: AgentsRef = {
|
|
34
|
-
${
|
|
34
|
+
${i}
|
|
35
35
|
};
|
|
36
36
|
`,o.push(`import type { AgentRunInput } from "@lunora/agent";
|
|
37
|
-
`)}return{block:e,importLine:o.join("")}},D=()=>Object.keys(T().functions).toSorted((t,r)=>t.localeCompare(r)),O=t=>new Set(t.filter(r=>u(r.filePath)==="agents").map(r=>r.exportName)),J=()=>new Set(Object.entries(T().functions).filter(([,t])=>t.visibility==="internal").map(([t])=>t)),X=(t,r)=>{const o={importLine:"",lines:"",prelude:""};if(t.length===0)return o;const e=O(r),c=J(),
|
|
38
|
-
`,lines:
|
|
37
|
+
`)}return{block:e,importLine:o.join("")}},D=()=>Object.keys(T().functions).toSorted((t,r)=>t.localeCompare(r)),O=t=>new Set(t.filter(r=>u(r.filePath)==="agents").map(r=>r.exportName)),J=()=>new Set(Object.entries(T().functions).filter(([,t])=>t.visibility==="internal").map(([t])=>t)),X=(t,r)=>{const o={importLine:"",lines:"",prelude:""};if(t.length===0)return o;const e=O(r),c=J(),a=r.find(n=>u(n.filePath)==="agents"&&c.has(n.exportName));if(a)throw new P("INTERNAL",`@lunora/codegen: "agents:${a.exportName}" is reserved for the durable agent loop's internal dispatch — rename the "${a.exportName}" export in ${a.filePath}`);const i=D().filter(n=>!e.has(n));return i.length===0?o:{importLine:`import { agentComponent } from "@lunora/agent/component";
|
|
38
|
+
`,lines:i.map(n=>` "agents:${n}": lunoraAgentRuntimeFunctions.${n} as unknown as RegisteredLunoraFunction,`).join(`
|
|
39
39
|
`),prelude:`
|
|
40
40
|
/**
|
|
41
41
|
* The \`@lunora/agent\` runtime component — auto-registered because \`lunora/agents.ts\`
|
|
@@ -44,12 +44,12 @@ ${a}
|
|
|
44
44
|
*/
|
|
45
45
|
const lunoraAgentRuntimeFunctions = agentComponent().functions;
|
|
46
46
|
`}},Y=(t,r)=>{if(!t)return{importLine:"",lines:"",prelude:""};const o=r.find(e=>u(e.filePath)==="sandbox"&&e.exportName==="invoke");if(o)throw new P("INTERNAL",`@lunora/codegen: "sandbox:invoke" is reserved for the batteries-included sandbox tool dispatcher (browserTool/containerTool) — rename the "invoke" export in ${o.filePath}`);return{importLine:`import { sandboxComponent } from "@lunora/agent/component";
|
|
47
|
-
`,lines:' "sandbox:invoke": lunoraSandbox.invoke as unknown as RegisteredLunoraFunction,',prelude:"\n/**\n * The `@lunora/agent` sandbox dispatcher — auto-registered because `lunora/`\n * imports a sandbox tool (`browserTool`/`containerTool`). The batteries-included\n * tools dispatch to this internal action, which runs on an action ctx carrying\n * `ctx.browser` + `ctx.containers` (the durable tool step itself has neither).\n */\nconst lunoraSandbox = sandboxComponent();\n"}},H=(t,r)=>{if(t.length===0)return[];const o=O(r),e=[{args:{key:{kind:"string"},limit:{inner:{kind:"number"},kind:"optional"}},exportName:"agentMessages",filePath:"agents",kind:"query",returnType:"Record<string, unknown>[]"},{args:{decision:{kind:"union",members:[{kind:"literal",literalValue:'"approve"'},{kind:"literal",literalValue:'"reject"'}]},instanceId:{kind:"string"},note:{inner:{kind:"string"},kind:"optional"},threadKey:{kind:"string"},toolCallId:{kind:"string"}},exportName:"agentResolveApproval",filePath:"agents",kind:"mutation",returnType:"{ resolved: boolean }"},{args:{agent:{kind:"string"},input:{kind:"string"},threadKey:{kind:"string"},title:{inner:{kind:"string"},kind:"optional"}},exportName:"agentRun",filePath:"agents",kind:"mutation",returnType:"{ id: string; threadKey: string }"},{args:{key:{kind:"string"}},exportName:"agentState",filePath:"agents",kind:"query",returnType:"Record<string, unknown> | undefined"},{args:{key:{kind:"string"}},exportName:"agentThread",filePath:"agents",kind:"query",returnType:"Record<string, unknown> | undefined"}];for(const c of t)c.voice&&e.push({args:{threadKey:{kind:"string"}},exportName:`${c.exportName}Voice`,filePath:"agents",kind:"stream",returnType:"Record<string, unknown>"});return e.filter(c=>!o.has(c.exportName))},_=(t,r)=>{if(t.length===0)return[];const o=new Set(r.filter(e=>u(e.filePath)==="mutators").map(e=>e.exportName));return t.filter(e=>!o.has(e.exportName)).map(e=>({args:e.args,exportName:e.exportName,filePath:e.filePath,kind:"mutation",returnType:e.returnType}))},q=t=>{const r=t.filter(
|
|
48
|
-
`);return` ${x(u(
|
|
47
|
+
`,lines:' "sandbox:invoke": lunoraSandbox.invoke as unknown as RegisteredLunoraFunction,',prelude:"\n/**\n * The `@lunora/agent` sandbox dispatcher — auto-registered because `lunora/`\n * imports a sandbox tool (`browserTool`/`containerTool`). The batteries-included\n * tools dispatch to this internal action, which runs on an action ctx carrying\n * `ctx.browser` + `ctx.containers` (the durable tool step itself has neither).\n */\nconst lunoraSandbox = sandboxComponent();\n"}},H=(t,r)=>{if(t.length===0)return[];const o=O(r),e=[{args:{key:{kind:"string"},limit:{inner:{kind:"number"},kind:"optional"}},exportName:"agentMessages",filePath:"agents",kind:"query",returnType:"Record<string, unknown>[]"},{args:{decision:{kind:"union",members:[{kind:"literal",literalValue:'"approve"'},{kind:"literal",literalValue:'"reject"'}]},instanceId:{kind:"string"},note:{inner:{kind:"string"},kind:"optional"},threadKey:{kind:"string"},toolCallId:{kind:"string"}},exportName:"agentResolveApproval",filePath:"agents",kind:"mutation",returnType:"{ resolved: boolean }"},{args:{agent:{kind:"string"},input:{kind:"string"},threadKey:{kind:"string"},title:{inner:{kind:"string"},kind:"optional"}},exportName:"agentRun",filePath:"agents",kind:"mutation",returnType:"{ id: string; threadKey: string }"},{args:{key:{kind:"string"}},exportName:"agentState",filePath:"agents",kind:"query",returnType:"Record<string, unknown> | undefined"},{args:{key:{kind:"string"}},exportName:"agentThread",filePath:"agents",kind:"query",returnType:"Record<string, unknown> | undefined"}];for(const c of t)c.voice&&e.push({args:{threadKey:{kind:"string"}},exportName:`${c.exportName}Voice`,filePath:"agents",kind:"stream",returnType:"Record<string, unknown>"});return e.filter(c=>!o.has(c.exportName))},_=(t,r)=>{if(t.length===0)return[];const o=new Set(r.filter(e=>u(e.filePath)==="mutators").map(e=>e.exportName));return t.filter(e=>!o.has(e.exportName)).map(e=>({args:e.args,exportName:e.exportName,filePath:e.filePath,kind:"mutation",returnType:e.returnType}))},q=t=>{const r=t.filter(i=>i.stream);if(r.length===0)return{block:"",body:""};const o=A(r),e=o.map(([i,n])=>{const s=n.map(l=>{const p=h(l.chunkType??"unknown",l.filePath),d=h(g(l.searchParams),l.filePath),m=h(g(l.params),l.filePath);return` ${x(l.exportName)}: HttpStreamRef<${p}, ${d}, ${m}>;`}).join(`
|
|
48
|
+
`);return` ${x(u(i))}: {
|
|
49
49
|
${s}
|
|
50
50
|
};`}).join(`
|
|
51
|
-
`),c=o.map(([
|
|
52
|
-
`);return` ${y(u(
|
|
51
|
+
`),c=o.map(([i,n])=>{const s=n.map(l=>` ${y(l.exportName)}: { method: ${JSON.stringify(l.method)}, path: ${JSON.stringify(l.path)} },`).join(`
|
|
52
|
+
`);return` ${y(u(i))}: {
|
|
53
53
|
${s}
|
|
54
54
|
},`}).join(`
|
|
55
55
|
`);return{block:`
|
|
@@ -61,7 +61,7 @@ ${e}
|
|
|
61
61
|
export const httpStreams: HttpStreamsRef = {
|
|
62
62
|
${c}
|
|
63
63
|
};
|
|
64
|
-
`,body:e}},Z=t=>{const{agents:r=[],functions:o,httpRoutes:e=[],mutators:c=[],useUmbrella:
|
|
64
|
+
`,body:e}},Z=t=>{const{agents:r=[],functions:o,httpRoutes:e=[],mutators:c=[],useUmbrella:a=!1,workflows:i=[]}=t,n=v(a),s=[...o.filter(k=>k.visibility!=="internal"),...H(r,o),..._(c,o)],l=o.filter(k=>k.visibility==="internal"),p=C(s),d=C(l),m=q(e),b=`${p}
|
|
65
65
|
${d}
|
|
66
66
|
${m.body}`,f=j(b),L=f.length>0?`
|
|
67
67
|
import type { ${f.join(", ")} } from "./dataModel.js";
|
|
@@ -69,7 +69,7 @@ import type { ${f.join(", ")} } from "./dataModel.js";
|
|
|
69
69
|
${p}
|
|
70
70
|
`:"",M=d?`
|
|
71
71
|
${d}
|
|
72
|
-
`:"",N=W(
|
|
72
|
+
`:"",N=W(i,r),R=`export interface ApiTypes {${I}}
|
|
73
73
|
|
|
74
74
|
export const api = anyApi as unknown as ApiTypes;
|
|
75
75
|
|
|
@@ -80,7 +80,7 @@ export const internal = anyApi as unknown as InternalApiTypes;
|
|
|
80
80
|
${N.block}${m.block}`,S=[...R.includes("FunctionReference<")?["FunctionReference"]:[],...m.block===""?[]:["HttpStreamRef"]],F=S.length>0?`import type { ${S.join(", ")} } from "${n.client}";
|
|
81
81
|
`:"";return K(`${w}import { anyApi } from "${n.client}";
|
|
82
82
|
${F}${N.importLine}${L}
|
|
83
|
-
${R}`,
|
|
83
|
+
${R}`,a)},ee=t=>t?`${w}import { createSeedClient as createSeedClientBase } from "@lunora/seed";
|
|
84
84
|
import type { SeedClient, SeedClientOptions } from "@lunora/seed";
|
|
85
85
|
|
|
86
86
|
import schema from "../schema.js";
|
|
@@ -97,7 +97,7 @@ import type { InsertModel } from "./dataModel.js";
|
|
|
97
97
|
* const { posts } = await seed.posts((x) => x([10, 20]));
|
|
98
98
|
*/
|
|
99
99
|
export const createSeedClient = (options?: SeedClientOptions): SeedClient<InsertModel> => createSeedClientBase<InsertModel>(schema, options);
|
|
100
|
-
`:"",te=(t,r,o=!1)=>{if(t.length===0||!r)return"";const e=v(o),c=s=>s.table===void 0?"Row":`Doc<${JSON.stringify(s.table)}> & Row`,
|
|
100
|
+
`:"",te=(t,r,o=!1)=>{if(t.length===0||!r)return"";const e=v(o),c=s=>s.table===void 0?"Row":`Doc<${JSON.stringify(s.table)}> & Row`,a=t.map(s=>{B(s.exportName,"shape export name");const l=c(s),p=h(g(s.args),s.filePath),d=Object.keys(s.args).length>0,m=d?` args: ${p};`:` args?: ${p};`,b=d?`(args: ${p}) => void`:`(args?: ${p}) => void`,f=`${s.exportName}CollectionOptions`;return`/** Options for the \`${s.exportName}\` shape binding. */
|
|
101
101
|
export interface ${$(f)} {
|
|
102
102
|
${m}
|
|
103
103
|
/**
|
|
@@ -143,12 +143,12 @@ export const ${s.exportName}Collection = (
|
|
|
143
143
|
return { checkpoints, collection: createCollection(config), scope };
|
|
144
144
|
};`}).join(`
|
|
145
145
|
|
|
146
|
-
`),
|
|
146
|
+
`),i=j(a),n=i.length>0?`import type { ${i.join(", ")} } from "./dataModel.js";
|
|
147
147
|
`:"";return`${w}import type { LunoraClient, SubscriptionError } from "${e.client}";
|
|
148
148
|
import { lunoraCollectionOptions } from "@lunora/db/collections";
|
|
149
149
|
import type { CheckpointRegistry, LunoraCollectionOptions, Row } from "@lunora/db";
|
|
150
150
|
import type { Collection } from "@tanstack/db";
|
|
151
151
|
import { createCollection } from "@tanstack/db";
|
|
152
152
|
${n}
|
|
153
|
-
${
|
|
153
|
+
${a}
|
|
154
154
|
`};export{Z as emitApi,te as emitCollections,ee as emitSeed,A as groupByFileSorted,X as renderAgentFunctionRegistry,Y as renderSandboxFunctionRegistry};
|