effect-analyzer 0.1.2 → 0.1.3
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/{analyze-a8PswlPG.d.cts → analyze-BXCwo5MU.d.cts} +2 -0
- package/dist/{analyze-a8PswlPG.d.ts → analyze-BXCwo5MU.d.ts} +2 -0
- package/dist/cli.js +76 -76
- package/dist/effect-workflow.cjs +3 -3
- package/dist/effect-workflow.cjs.map +1 -1
- package/dist/effect-workflow.d.cts +2 -2
- package/dist/effect-workflow.d.ts +2 -2
- package/dist/effect-workflow.js +3 -3
- package/dist/effect-workflow.js.map +1 -1
- package/dist/index.cjs +79 -74
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +80 -75
- package/dist/index.js.map +1 -1
- package/dist/lsp/server.js +1366 -1186
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,69 +1,69 @@
|
|
|
1
|
-
import{Effect as G,Option as jt}from"effect";import{Option as O}from"effect";var pe=class extends Error{code;location;constructor(t,r,n){super(r),this.code=t,this.location=n,this.name="AnalysisError"}},je=e=>e.type==="effect",$t=e=>e.type==="generator",rn=e=>e.type==="pipe",on=e=>e.type==="parallel",Qs=e=>e.type==="race",pt=e=>e.type==="error-handler",Zs=e=>e.type==="retry",Xs=e=>e.type==="timeout",ei=e=>e.type==="resource",ti=e=>e.type==="conditional",ni=e=>e.type==="loop",ri=e=>e.type==="layer",oi=e=>e.type==="cause",si=e=>e.type==="exit",ii=e=>e.type==="schedule",ai=e=>e.type==="match",ci=e=>e.type==="transform",li=e=>e.type==="stream";var di=e=>e.type==="concurrency-primitive",ui=e=>e.type==="fiber";var sn=e=>e.type==="unknown";var v=e=>{switch(e.type){case"program":return O.some(e.children);case"generator":return O.some(e.yields.map(t=>t.effect));case"pipe":return O.some([e.initial,...e.transformations]);case"parallel":case"race":return O.some([...e.children]);case"error-handler":return O.some(e.handler?[e.source,e.handler]:[e.source]);case"retry":{let t=e,r=[t.source,t.scheduleNode].filter(n=>n!==void 0);return r.length>0?O.some(r):O.none()}case"timeout":{let t=e.source;return t?O.some([t]):O.none()}case"resource":return O.some(e.use?[e.acquire,e.release,e.use]:[e.acquire,e.release]);case"conditional":return O.some(e.onFalse?[e.onTrue,e.onFalse]:[e.onTrue]);case"loop":return O.some([e.body]);case"cause":return e.children&&e.children.length>0?O.some(e.children):O.none();case"exit":case"schedule":case"match":return O.none();case"transform":return e.source?O.some([e.source]):O.none();case"layer":return O.some([...e.operations]);case"stream":return O.some([e.source]);case"channel":return e.source?O.some([e.source]):O.none();case"sink":return e.source?O.some([e.source]):O.none();case"concurrency-primitive":return e.source?O.some([e.source]):O.none();case"fiber":return e.fiberSource?O.some([e.fiberSource]):O.none();case"interruption":{let t=[];return e.source&&t.push(e.source),e.handler&&t.push(e.handler),t.length>0?O.some(t):O.none()}case"effect":return e.callbackBody&&e.callbackBody.length>0?O.some([...e.callbackBody]):O.none();case"decision":return O.some([...e.onTrue,...e.onFalse??[]]);case"switch":return O.some(e.cases.flatMap(t=>[...t.body]));case"try-catch":return O.some([...e.tryBody,...e.catchBody??[],...e.finallyBody??[]]);case"terminal":return e.value?O.some([...e.value]):O.none();case"opaque":return O.none();default:return O.none()}};import{Effect as ke}from"effect";import{createRequire as fi}from"module";var an=null,ar=new Map,I=()=>{if(!an)try{an=fi(import.meta.url)("ts-morph")}catch{throw new Error("ts-morph is required but not installed. Please install it as a peer dependency: npm install ts-morph")}return an},cr=e=>{let t=e??"__default__",r=ar.get(t);if(r)return r;let{Project:n}=I(),o={};e&&(o.tsConfigFilePath=e);let s=new n(o);return ar.set(t,s),s};var lr=(e,t="temp.ts")=>{let{Project:r}=I();return new r({useInMemoryFileSystem:!0,compilerOptions:{strict:!0,esModuleInterop:!0}}).createSourceFile(t,e)};import{Option as pr}from"effect";var pi=/Effect(?:\.Effect)?<([^,]+),\s*([^,]+),\s*([^>]+)>/,gi=/Effect(?:\.Effect)?<([^,>]+),\s*([^,>]+)>/;function cn(e){let t=o=>o.replace(/import\([^)]+\)\./g,"").replace(/typeof\s+/g,"").trim().substring(0,200),r=pi.exec(e);if(r)return{successType:t(r[1]),errorType:t(r[2]),requirementsType:t(r[3]),isInferred:!1,typeConfidence:"inferred",rawTypeString:e};let n=gi.exec(e);if(n)return{successType:t(n[1]),errorType:t(n[2]),requirementsType:"never",isInferred:!1,typeConfidence:"inferred",rawTypeString:e}}var _e=(e,t)=>{let r;try{r=e.getType()}catch{return}if(!hi(r))return;let n=Dt(r);if(n){let[i,c,d]=n;return{successType:xe(i),errorType:xe(c),requirementsType:xe(d),isInferred:!0,typeConfidence:"declared",rawTypeString:r.getText()}}let o=r.getText(),s=cn(o);if(s)return s;let a=mi(e);return a||{successType:"unknown",errorType:"never",requirementsType:"never",isInferred:!1,typeConfidence:"unknown",rawTypeString:o}};function mi(e){try{if(!("getExpression"in e))return;let r=e.getExpression(),o=r.getType().getCallSignatures();if(o.length>0){let a=o[0].getReturnType(),i=Dt(a);if(i){let[l,f,u]=i;return{successType:xe(l),errorType:xe(f),requirementsType:xe(u),isInferred:!0,typeConfidence:"inferred",rawTypeString:a.getText()}}let c=a.getText(),d=cn(c);if(d)return d}let s=r.getSymbol();if(!s)return;for(let a of s.getDeclarations()){let i;if("getReturnType"in a)i=a.getReturnType().getText();else if("getType"in a){let d=a.getType().getCallSignatures();if(d.length>0){let l=d[0].getReturnType(),f=Dt(l);if(f){let[u,p,g]=f;return{successType:xe(u),errorType:xe(p),requirementsType:xe(g),isInferred:!0,typeConfidence:"inferred",rawTypeString:l.getText()}}i=l.getText()}}if(i){let c=cn(i);if(c)return{...c,typeConfidence:"inferred"}}}}catch{}}var hi=e=>{let t=e.getSymbol(),r=e.getText();if(t){let o=t.getName();if(o==="Effect"||o.includes("Effect"))return!0}if(r.includes("Effect<")||r.startsWith("Effect."))return!0;let n=e.getAliasSymbol();if(n){let o=n.getName();if(o==="Effect"||o.includes("Effect"))return!0}return!1},Dt=e=>{try{let t=e.getTypeArguments?.();if(!t||t.length<3){let r=e.getAliasTypeArguments?.();return r&&r.length>=3?[r[0],r[1],r[2]]:void 0}return[t[0],t[1],t[2]]}catch{return}},xe=e=>e.getText().replace(/import\([^)]+\)\./g,"").replace(/typeof\s+/g,"").substring(0,200),gt=(e,t)=>{let r=[],n=e.getType(),o=e,s;try{s=typeof n.getTypeArguments=="function"?n.getTypeArguments():void 0}catch{s=void 0}if(!s||s.length<3){let c=e.getParent();if(c?.getKindName()==="VariableDeclaration"){let d=c,l=d.getType();l&&(n=l,o=d)}}let a=yi(n);if(!a)return r;let i=Si(a);for(let c of i){let d=o.getSourceFile(),{line:l,column:f}=d.getLineAndColumnAtPos(o.getStart()),u={filePath:d.getFilePath(),line:l,column:f};r.push({serviceId:c.id,serviceType:c.typeName,requiredAt:u})}return r},yi=e=>{let t=Dt(e);if(t)return t[2]},Si=e=>{let t=[],r=e.getText(),n=/Context<([^>]+)>/.exec(r);if(n){let o=n[1];t.push({id:dr(o),typeName:o})}if(r.includes("|")){let o=we(r);for(let s of o){let a=/Context<([^>]+)>/.exec(s);a&&t.push({id:dr(a[1]),typeName:a[1]})}}return r==="never"||r==="{}"?[]:t},dr=e=>{let t=/Tag<["']([^"']+)["']/.exec(e);return t?t[1]:e.split("<")[0].trim()},xi=(e,t,r)=>{let n=[];return e.successType!==r.successType&&n.push(`${e.successType} \u2192 ${r.successType}`),e.errorType!==r.errorType&&n.push(`${e.errorType} \u2192 ${r.errorType}`),e.requirementsType!==r.requirementsType&&n.push(`${e.requirementsType} \u2192 ${r.requirementsType}`),{operation:t,typeChange:n.length>0?n.join(", "):"no change"}};function we(e){let t=[],r="",n=0,o=null;for(let a=0;a<e.length;a++){let i=e[a];if(o){r+=i,i===o&&e[a-1]!=="\\"&&(o=null);continue}if(i==='"'||i==="'"||i==="`"){o=i,r+=i;continue}if(i==="<"||i==="("){n++,r+=i;continue}if(i===">"||i===")"){n=Math.max(0,n-1),r+=i;continue}if(i==="|"&&n===0){t.push(r.trim()),r="";continue}r+=i}let s=r.trim();return s&&t.push(s),t.filter(Boolean)}var Ei=e=>`Effect<${e.successType}, ${e.errorType}, ${e.requirementsType}>`,Ce=e=>e.replace(/import\([^)]+\)\./g,"").replace(/typeof\s+/g,"").trim().substring(0,200),bi=/Stream<([^,]+),\s*([^,]+),\s*([^>]+)>/,Ci=/Layer<([^,]+),\s*([^,]+),\s*([^>]+)>/,Ni=/Schedule<([^,]+),\s*([^,]+),\s*([^>]+)>/,vi=/Cause<([^>]+)>/;function wi(e){let t=e.getType().getText(),r=bi.exec(t);if(r)return{successType:Ce(r[1]),errorType:Ce(r[2]),requirementsType:Ce(r[3]),rawTypeString:t}}function ln(e){let t=e.getType().getText(),r=Ci.exec(t);if(r)return{providedType:Ce(r[1]),errorType:Ce(r[2]),requiredType:Ce(r[3]),rawTypeString:t}}function Ti(e){let t=e.getType().getText(),r=Ni.exec(t);if(r)return{outputType:Ce(r[1]),inputType:Ce(r[2]),requirementsType:Ce(r[3]),rawTypeString:t}}function ki(e){let t=e.getType().getText(),r=vi.exec(t);if(r)return{errorType:Ce(r[1]),rawTypeString:t}}var ur=e=>{let t=e.getSymbol();if(t){let n=t.getName();return n==="Schema"||n.includes("Schema")}let r=e.getText();return r.includes("Schema<")||r.startsWith("Schema.")},Ii=e=>{if(!ur(e))return;let t=e.getTypeArguments();if(t.length>=2)return{encoded:xe(t[1]),decoded:xe(t[0])}};var dn={tsConfigPath:"./tsconfig.json",resolveReferences:!0,maxReferenceDepth:5,includeLocations:!0,assumeImported:!1,enableEffectWorkflow:!1,knownEffectInternalsRoot:void 0,minDiscoveryConfidence:"low",onlyExportedPrograms:!1,enableEffectFlow:!1},gr=0,ht=()=>{gr=0},T=()=>`effect-${++gr}`,fr=new WeakMap;function Pt(e){let t=fr.get(e);return t===void 0&&(t=e.getText(),fr.set(e,t)),t}function mr(e){let t=new Set,r=n=>{for(let o of n){if(o.type==="effect"){let a=o.typeSignature?.errorType?.trim();if(a&&a!=="never")for(let i of we(a))t.add(i)}let s=pr.getOrElse(v(o),()=>[]);s.length>0&&r(s)}};return r(e),Array.from(t).sort()}function hr(e){let t=new Map,r=n=>{for(let o of n){if(o.type==="effect"){let a=o.requiredServices;if(a)for(let i of a)t.has(i.serviceId)||t.set(i.serviceId,{name:i.serviceId,typeSignature:i.serviceType,isLayer:!1});if((o.semanticRole==="environment"||o.semanticRole==="side-effect")&&o.callee){let i=o.callee;/^[A-Z]/.test(i)&&!i.startsWith("Effect.")&&!i.startsWith("Schema.")&&!i.startsWith("Data.")&&!i.startsWith("Config.")&&!i.startsWith("Command.")&&!i.startsWith("Stream.")&&!i.startsWith("Option.")&&!i.startsWith("Either.")&&!i.startsWith("Cause.")&&!i.startsWith("Exit.")&&!t.has(i)&&t.set(i,{name:i,typeSignature:o.typeSignature?.requirementsType,isLayer:!1})}}let s=pr.getOrElse(v(o),()=>[]);s.length>0&&r(s)}};return r(e),Array.from(t.values())}var W=(e,t,r)=>{if(!r)return;let n=e.getSourceFile(),o=e.getStart(),{line:s,column:a}=n.getLineAndColumnAtPos(o),i=e.getEnd(),c=n.getLineAndColumnAtPos(i);return{filePath:t,line:s,column:a,endLine:c.line,endColumn:c.column}},ze=e=>{let t=e.getJsDocs?.();if(t&&t.length>0){let n=t[0];if(!n)return;let o=n.getComment?.();if(o){let i;if(typeof o=="string")i=o;else if(Array.isArray(o))i=o.map(d=>d.text).join(`
|
|
2
|
-
`);else return;let c=i.search(/\n\s*@/);return c!==-1&&(i=i.substring(0,c)),i.trim()||void 0}let s=
|
|
1
|
+
import{Effect as Q,Option as Qt}from"effect";import{Option as M}from"effect";var me=class extends Error{code;location;constructor(t,n,r){super(n),this.code=t,this.location=r,this.name="AnalysisError"}},He=e=>e.type==="effect",Kt=e=>e.type==="generator",pn=e=>e.type==="pipe",gn=e=>e.type==="parallel",si=e=>e.type==="race",Et=e=>e.type==="error-handler",ii=e=>e.type==="retry",ai=e=>e.type==="timeout",ci=e=>e.type==="resource",li=e=>e.type==="conditional",di=e=>e.type==="loop",ui=e=>e.type==="layer",fi=e=>e.type==="cause",pi=e=>e.type==="exit",gi=e=>e.type==="schedule",mi=e=>e.type==="match",hi=e=>e.type==="transform",yi=e=>e.type==="stream";var Si=e=>e.type==="concurrency-primitive",xi=e=>e.type==="fiber";var mn=e=>e.type==="unknown";var v=e=>{switch(e.type){case"program":return M.some(e.children);case"generator":return M.some(e.yields.map(t=>t.effect));case"pipe":return M.some([e.initial,...e.transformations]);case"parallel":case"race":return M.some([...e.children]);case"error-handler":return M.some(e.handler?[e.source,e.handler]:[e.source]);case"retry":{let t=e,n=[t.source,t.scheduleNode].filter(r=>r!==void 0);return n.length>0?M.some(n):M.none()}case"timeout":{let t=e.source;return t?M.some([t]):M.none()}case"resource":return M.some(e.use?[e.acquire,e.release,e.use]:[e.acquire,e.release]);case"conditional":return M.some(e.onFalse?[e.onTrue,e.onFalse]:[e.onTrue]);case"loop":return M.some([e.body]);case"cause":return e.children&&e.children.length>0?M.some(e.children):M.none();case"exit":case"schedule":case"match":return M.none();case"transform":return e.source?M.some([e.source]):M.none();case"layer":return M.some([...e.operations]);case"stream":return M.some([e.source]);case"channel":return e.source?M.some([e.source]):M.none();case"sink":return e.source?M.some([e.source]):M.none();case"concurrency-primitive":return e.source?M.some([e.source]):M.none();case"fiber":return e.fiberSource?M.some([e.fiberSource]):M.none();case"interruption":{let t=[];return e.source&&t.push(e.source),e.handler&&t.push(e.handler),t.length>0?M.some(t):M.none()}case"effect":return e.callbackBody&&e.callbackBody.length>0?M.some([...e.callbackBody]):M.none();case"decision":return M.some([...e.onTrue,...e.onFalse??[]]);case"switch":return M.some(e.cases.flatMap(t=>[...t.body]));case"try-catch":return M.some([...e.tryBody,...e.catchBody??[],...e.finallyBody??[]]);case"terminal":return e.value?M.some([...e.value]):M.none();case"opaque":return M.none();default:return M.none()}};import{Effect as $e}from"effect";import{createRequire as Ei}from"module";var hn=null,mr=new Map,I=()=>{if(!hn)try{hn=Ei(import.meta.url)("ts-morph")}catch{throw new Error("ts-morph is required but not installed. Please install it as a peer dependency: npm install ts-morph")}return hn},hr=e=>{let t=e??"__default__",n=mr.get(t);if(n)return n;let{Project:r}=I(),o={};e&&(o.tsConfigFilePath=e);let s=new r(o);return mr.set(t,s),s};var yr=(e,t="temp.ts")=>{let{Project:n}=I();return new n({useInMemoryFileSystem:!0,compilerOptions:{strict:!0,esModuleInterop:!0}}).createSourceFile(t,e)};import{Option as Mr}from"effect";var bi=/Effect(?:\.Effect)?<([^,]+),\s*([^,]+),\s*([^>]+)>/,Ci=/Effect(?:\.Effect)?<([^,>]+),\s*([^,>]+)>/;function yn(e){let t=o=>o.replace(/import\([^)]+\)\./g,"").replace(/typeof\s+/g,"").trim().substring(0,200),n=bi.exec(e);if(n)return{successType:t(n[1]),errorType:t(n[2]),requirementsType:t(n[3]),isInferred:!1,typeConfidence:"inferred",rawTypeString:e};let r=Ci.exec(e);if(r)return{successType:t(r[1]),errorType:t(r[2]),requirementsType:"never",isInferred:!1,typeConfidence:"inferred",rawTypeString:e}}function Sr(e,t){try{let{SyntaxKind:n}=I();if(e.getKind()===n.CallExpression){let r=e,o=r.getExpression();if(o.getKind()===n.PropertyAccessExpression){let a=o;if(a.getName()==="pipe"){let i=a.getExpression();if(i){let c=Ie(i,t);if(c&&!/^[A-Z]$/.test(c.errorType))return{errorType:c.errorType}}}}let s=r.getArguments();if(s.length>0)for(let a of s){let i=Ie(a,t);if(i&&!/^[A-Z]$/.test(i.errorType))return{errorType:i.errorType}}}}catch{}}var Ie=(e,t)=>{let n;try{n=e.getType()}catch{return}if(!Ti(n))return;let r=Bt(n);if(r){let[i,c,d]=r,l=pe(c);if(/^[A-Z]$/.test(l)){let f=Sr(e,t);if(f)return{successType:pe(i),errorType:f.errorType,requirementsType:pe(d),isInferred:!0,typeConfidence:"inferred",rawTypeString:n.getText()}}return{successType:pe(i),errorType:l,requirementsType:pe(d),isInferred:!0,typeConfidence:"declared",rawTypeString:n.getText()}}let o=n.getText(),s=yn(o);if(s){let i=s.errorType.trim();if(/^[A-Z]$/.test(i)){let c=Sr(e,t);if(c)return{...s,errorType:c.errorType,isInferred:!0,typeConfidence:"inferred",rawTypeString:n.getText()}}return s}let a=Ni(e);return a||{successType:"unknown",errorType:"never",requirementsType:"never",isInferred:!1,typeConfidence:"unknown",rawTypeString:o}};function Ni(e){try{if(!("getExpression"in e))return;let n=e.getExpression(),o=n.getType().getCallSignatures();if(o.length>0){let a=o[0].getReturnType(),i=Bt(a);if(i){let[l,f,u]=i;return{successType:pe(l),errorType:pe(f),requirementsType:pe(u),isInferred:!0,typeConfidence:"inferred",rawTypeString:a.getText()}}let c=a.getText(),d=yn(c);if(d)return d}let s=n.getSymbol();if(!s)return;for(let a of s.getDeclarations()){let i;if("getReturnType"in a)i=a.getReturnType().getText();else if("getType"in a){let d=a.getType().getCallSignatures();if(d.length>0){let l=d[0].getReturnType(),f=Bt(l);if(f){let[u,p,g]=f;return{successType:pe(u),errorType:pe(p),requirementsType:pe(g),isInferred:!0,typeConfidence:"inferred",rawTypeString:l.getText()}}i=l.getText()}}if(i){let c=yn(i);if(c)return{...c,typeConfidence:"inferred"}}}}catch{}}var Ti=e=>{let t=e.getSymbol(),n=e.getText();if(t){let o=t.getName();if(o==="Effect"||o.includes("Effect"))return!0}if(n.includes("Effect<")||n.startsWith("Effect."))return!0;let r=e.getAliasSymbol();if(r){let o=r.getName();if(o==="Effect"||o.includes("Effect"))return!0}return!1},Bt=e=>{try{let t=e.getTypeArguments?.();if(!t||t.length<3){let n=e.getAliasTypeArguments?.();return n&&n.length>=3?[n[0],n[1],n[2]]:void 0}return[t[0],t[1],t[2]]}catch{return}},pe=e=>e.getText().replace(/import\([^)]+\)\./g,"").replace(/typeof\s+/g,"").substring(0,200),bt=(e,t)=>{let n=[],r=e.getType(),o=e,s;try{s=typeof r.getTypeArguments=="function"?r.getTypeArguments():void 0}catch{s=void 0}if(!s||s.length<3){let c=e.getParent();if(c?.getKindName()==="VariableDeclaration"){let d=c,l=d.getType();l&&(r=l,o=d)}}let a=vi(r);if(!a)return n;let i=wi(a);for(let c of i){let d=o.getSourceFile(),{line:l,column:f}=d.getLineAndColumnAtPos(o.getStart()),u={filePath:d.getFilePath(),line:l,column:f};n.push({serviceId:c.id,serviceType:c.typeName,requiredAt:u})}return n},vi=e=>{let t=Bt(e);if(t)return t[2]},wi=e=>{let t=[],n=e.getText(),r=/Context<([^>]+)>/.exec(n);if(r){let o=r[1];t.push({id:xr(o),typeName:o})}if(n.includes("|")){let o=Ae(n);for(let s of o){let a=/Context<([^>]+)>/.exec(s);a&&t.push({id:xr(a[1]),typeName:a[1]})}}return n==="never"||n==="{}"?[]:t},xr=e=>{let t=/Tag<["']([^"']+)["']/.exec(e);return t?t[1]:e.split("<")[0].trim()},ki=(e,t,n)=>{let r=[];return e.successType!==n.successType&&r.push(`${e.successType} \u2192 ${n.successType}`),e.errorType!==n.errorType&&r.push(`${e.errorType} \u2192 ${n.errorType}`),e.requirementsType!==n.requirementsType&&r.push(`${e.requirementsType} \u2192 ${n.requirementsType}`),{operation:t,typeChange:r.length>0?r.join(", "):"no change"}};function Ae(e){let t=[],n="",r=0,o=null;for(let a=0;a<e.length;a++){let i=e[a];if(o){n+=i,i===o&&e[a-1]!=="\\"&&(o=null);continue}if(i==='"'||i==="'"||i==="`"){o=i,n+=i;continue}if(i==="<"||i==="("){r++,n+=i;continue}if(i===">"||i===")"){r=Math.max(0,r-1),n+=i;continue}if(i==="|"&&r===0){t.push(n.trim()),n="";continue}n+=i}let s=n.trim();return s&&t.push(s),t.filter(Boolean)}var Ii=e=>`Effect<${e.successType}, ${e.errorType}, ${e.requirementsType}>`,Te=e=>e.replace(/import\([^)]+\)\./g,"").replace(/typeof\s+/g,"").trim().substring(0,200),Ai=/Stream<([^,]+),\s*([^,]+),\s*([^>]+)>/,Fi=/Layer<([^,]+),\s*([^,]+),\s*([^>]+)>/,Ri=/Schedule<([^,]+),\s*([^,]+),\s*([^>]+)>/,$i=/Cause<([^>]+)>/;function Di(e){let t=e.getType().getText(),n=Ai.exec(t);if(n)return{successType:Te(n[1]),errorType:Te(n[2]),requirementsType:Te(n[3]),rawTypeString:t}}function Sn(e){let t=e.getType().getText(),n=Fi.exec(t);if(n)return{providedType:Te(n[1]),errorType:Te(n[2]),requiredType:Te(n[3]),rawTypeString:t}}function Pi(e){let t=e.getType().getText(),n=Ri.exec(t);if(n)return{outputType:Te(n[1]),inputType:Te(n[2]),requirementsType:Te(n[3]),rawTypeString:t}}function Li(e){let t=e.getType().getText(),n=$i.exec(t);if(n)return{errorType:Te(n[1]),rawTypeString:t}}var Er=e=>{let t=e.getSymbol();if(t){let r=t.getName();return r==="Schema"||r.includes("Schema")}let n=e.getText();return n.includes("Schema<")||n.startsWith("Schema.")},Mi=e=>{if(!Er(e))return;let t=e.getTypeArguments();if(t.length>=2)return{encoded:pe(t[1]),decoded:pe(t[0])}};var xn=[".catchAll",".catchTag",".catchAllCause",".catchIf",".catchSome",".catchSomeCause",".catchSomeDefect",".catchAllDefect",".catchTags",".orElse",".orElseFail",".orElseSucceed",".orDie",".orDieWith",".flip",".mapError",".mapErrorCause",".mapBoth",".sandbox",".unsandbox",".parallelErrors",".filterOrDie",".filterOrDieMessage",".filterOrElse",".filterOrFail",".match",".matchCause",".matchEffect",".matchCauseEffect",".firstSuccessOf",".ignore",".ignoreLogged",".eventually"],En=[".if",".when",".whenEffect",".whenFiberRef",".whenRef",".unless",".unlessEffect",".option",".either",".exit",".liftPredicate"],Oi=[".acquireRelease",".acquireUseRelease",".ensuring",".addFinalizer",".onExit",".onError",".parallelFinalizers",".sequentialFinalizers",".finalizersMask",".using",".withEarlyRelease"],bn=[".forEach",".loop",".filter",".filterMap",".partition",".reduce",".reduceRight",".reduceWhile",".reduceEffect",".dropUntil",".dropWhile",".takeUntil",".takeWhile",".every",".exists",".findFirst",".head",".mergeAll",".replicate",".replicateEffect",".validateAll",".validateFirst",".validate",".validateWith"],Cn=["Effect.fork",".fork",".forkAll",".forkIn",".forkWithErrorHandler","Fiber."],Nn={"Effect.map":"map","Effect.flatMap":"flatMap","Effect.andThen":"andThen","Effect.tap":"tap","Effect.tapBoth":"tapBoth","Effect.tapError":"tapError","Effect.tapErrorTag":"tapErrorTag","Effect.tapErrorCause":"tapErrorCause","Effect.tapDefect":"tapDefect","Effect.zipLeft":"zipLeft","Effect.zipRight":"zipRight","Effect.zipWith":"zipWith","Effect.zip":"zip","Effect.as":"as","Effect.asVoid":"asVoid","Effect.asSome":"asSome","Effect.asSomeError":"asSomeError","Effect.flatten":"flatten","Effect.ap":"ap","Effect.negate":"negate","Effect.merge":"merge"},Cr=new Set(["flatMap","andThen","tapBoth","tapError","tapErrorTag","tapErrorCause","tapDefect","zipWith","zipLeft","zipRight","zip","ap","flatten"]),Nr=e=>e in Nn,Tn={"Match.type":"type","Match.tag":"tag","Match.value":"value","Match.when":"when","Match.whenOr":"whenOr","Match.whenAnd":"whenAnd","Match.not":"not","Match.is":"is","Match.exhaustive":"exhaustive","Match.orElse":"orElse","Match.option":"option","Match.either":"either","Match.discriminator":"discriminator","Match.discriminatorsExhaustive":"discriminatorsExhaustive","Match.tags":"tags","Match.tagsExhaustive":"tagsExhaustive","Match.withReturnType":"withReturnType","Match.run":"run"},Tr=new Set(["exhaustive","discriminatorsExhaustive","tagsExhaustive"]),vr=e=>e.startsWith("Match.")&&e in Tn,vn={"Cause.fail":"fail","Cause.die":"die","Cause.interrupt":"interrupt","Cause.parallel":"parallel","Cause.sequential":"sequential","Cause.empty":"empty","Cause.failures":"failures","Cause.defects":"defects","Cause.interruptors":"interruptors","Cause.squash":"squash","Cause.squashWith":"squashWith","Cause.pretty":"pretty","Cause.flatten":"flatten","Cause.isDie":"isDie","Cause.isFailure":"isFailure","Cause.isInterrupted":"isInterrupted","Cause.isEmpty":"isEmpty","Cause.map":"map","Cause.filter":"filter"},wr=new Set(["fail","die","interrupt","parallel","sequential","empty"]),kr=e=>e.startsWith("Cause.")&&e in vn,wn={"Exit.succeed":"succeed","Exit.fail":"fail","Exit.die":"die","Exit.interrupt":"interrupt","Exit.void":"void","Exit.unit":"unit","Exit.match":"match","Exit.isSuccess":"isSuccess","Exit.isFailure":"isFailure","Exit.isInterrupted":"isInterrupted","Exit.when":"when","Exit.whenEffect":"whenEffect","Exit.exists":"exists","Exit.contains":"contains","Exit.flatten":"flatten","Exit.map":"map","Exit.mapBoth":"mapBoth","Exit.mapError":"mapError","Exit.flatMap":"flatMap","Exit.zipWith":"zipWith","Exit.tap":"tap","Exit.tapBoth":"tapBoth","Exit.tapError":"tapError"},Ir=new Set(["succeed","fail","die","interrupt","void","unit"]),Ar=e=>e.startsWith("Exit.")&&(e in wn||/^Exit\.\w+$/.test(e)),kn={"Schedule.exponential":"exponential","Schedule.fibonacci":"fibonacci","Schedule.spaced":"spaced","Schedule.fixed":"fixed","Schedule.linear":"linear","Schedule.cron":"cron","Schedule.windowed":"windowed","Schedule.duration":"duration","Schedule.elapsed":"elapsed","Schedule.delays":"delays","Schedule.once":"once","Schedule.stop":"stop","Schedule.count":"count","Schedule.forever":"forever","Schedule.jittered":"jittered","Schedule.andThen":"andThen","Schedule.intersect":"intersect","Schedule.union":"union","Schedule.compose":"compose","Schedule.zipWith":"zipWith","Schedule.addDelay":"addDelay","Schedule.modifyDelay":"modifyDelay","Schedule.check":"check","Schedule.resetAfter":"resetAfter","Schedule.resetWhen":"resetWhen","Schedule.ensure":"ensure","Schedule.driver":"driver","Schedule.mapInput":"mapInput"},Fr=e=>e.startsWith("Schedule.")&&(e in kn||/^Schedule\.\w+$/.test(e)),In=[".interruptible",".uninterruptible",".interruptibleMask",".uninterruptibleMask",".onInterrupt",".disconnect",".allowInterrupt","Effect.interrupt",".interruptWith"],Wi=[".Do",".bind",".bindAll",".bindTo"],Ki=[".cached",".cachedWithTTL",".cachedInvalidateWithTTL",".cachedFunction",".once","Cache.","ScopedCache."],An=["Effect.","Layer.","Schedule.","Stream.","Queue.","PubSub.","Deferred.","Semaphore.","Mailbox.","SubscriptionRef.","Scope.","Fiber.","Runtime.","ManagedRuntime.","NodeRuntime.","BunRuntime.","DenoRuntime.","Cause.","Exit.","Data.","Option.","Either.","Chunk.","HashMap.","HashSet.","List.","SortedMap.","SortedSet.","RedBlackTree.","Trie.","Graph.","Match.","Config.","Schema.","Cache.","ScopedCache.","RcRef.","RcMap.","Reloadable.","Cache.","ScopedCache.","RateLimiter.","PartitionedSemaphore.","FiberSet.","FiberMap.","FiberHandle.","Metric.","Logger.","Tracer.","Context.","HttpClient.","HttpRouter.","HttpApi.","FileSystem.","Command.","Socket.","SocketServer.","Worker.","Terminal.","KeyValueStore.","Multipart.","Ndjson.","MsgPack.","OpenApi.","OpenApiJsonSchema.","Brand.","Encoding.","Predicate.","DateTime.","Cron.","BigDecimal.","HashRing.","Redacted.","GlobalValue.","Channel.","Sink.","CliApp.","Args.","Options.","AiModel.","AiToolkit.","Completions.","AiInput.","AiResponse.","NodeSdk.","WebSdk.","Entity.","ClusterSchema.","MessageState.","Sharding.","RpcGroup.","RpcApi.","RpcClient.","RpcRouter.","SqlResolver.","SqlMigrator.","Printer.","Doc.","DocTree.","PageWidth.","Optimize."],qt=new Set(["Array","ReadonlyArray","String","Number","Boolean","Object","Function","Promise","Math","Date","RegExp","Error","Map","Set","WeakMap","WeakSet","Symbol","BigInt","JSON","Console","process","Buffer","EventEmitter","Window","Document","AbortController"]),Ct=new Set(["Effect","Layer","Stream","Queue","PubSub","Deferred","Semaphore","Mailbox","SubscriptionRef","Scope","Fiber","Runtime","ManagedRuntime","Cause","Exit","Data","Option","Either","Chunk","HashMap","HashSet","List","SortedMap","SortedSet","Match","Config","Schema","Schedule","Metric","Tracer","Logger","FiberRef","FiberHandle","FiberSet","FiberMap","Cache","ScopedCache","RateLimiter","Supervisor"]),Rr=e=>e.includes(".")||Ct.has(e)?!1:/^[A-Z][A-Za-z0-9]*$/.test(e),br=e=>{if(e.startsWith("Channel."))return"channel";if(e.startsWith("Sink."))return"sink";if(e.endsWith(".never"))return"never";if(e.endsWith(".void"))return"void-effect";if(e.endsWith(".fromNullable"))return"null-coalescing";if(e.endsWith(".fn")||e.endsWith(".fnUntraced"))return"function-lift";if(e.includes(".async")||e.includes(".asyncEffect")||e.includes(".promise")||e.includes(".sync")||e.includes(".suspend")||e.includes(".succeed")||e.includes(".fail")||e.includes(".try"))return"constructor";if(In.some(t=>e.includes(t)))return"interruption";if(Wi.some(t=>e.includes(t)))return"do-notation";if(Ki.some(t=>e.includes(t)||e.startsWith(t)))return"caching";if(xn.some(t=>e.includes(t)))return"error-handler";if(En.some(t=>e.includes(t)))return"conditional";if(Oi.some(t=>e.includes(t)))return"resource";if(bn.some(t=>e.includes(t)))return"collection";if(Cn.some(t=>e.includes(t)))return"fiber";if(e.startsWith("Stream."))return"stream";if(e.startsWith("Layer."))return"layer";if(e.startsWith("Schema."))return"schema";if(e.startsWith("Config."))return"config";if(e.startsWith("Cause."))return"cause";if(e.startsWith("Exit."))return"exit";if(e==="Data.tagged"||e==="Data.taggedEnum")return"tagged-enum";if(e.startsWith("Data."))return"data";if(e.startsWith("Option."))return"option";if(e.startsWith("Either."))return"either";if(e.startsWith("Match."))return"match";if(e.startsWith("ManagedRuntime.")||e.startsWith("Runtime.")||e.startsWith("NodeRuntime.")||e.startsWith("BunRuntime.")||e.startsWith("DenoRuntime."))return"runtime";if(e.startsWith("Scope."))return"scope";if(e.startsWith("ScopedRef.")||e.startsWith("RcRef.")||e.startsWith("RcMap."))return"resource-ref";if(e.startsWith("Reloadable.")||e.startsWith("Resource."))return"reloadable";if(e.startsWith("Micro."))return"micro";if(e.startsWith("Brand."))return"brand";if(e.startsWith("Encoding."))return"encoding";if(e.startsWith("Predicate."))return"predicate";if(e.startsWith("DateTime."))return"datetime";if(e.startsWith("Cron."))return"cron";if(e.startsWith("Redacted."))return"redacted";if(e.startsWith("GlobalValue."))return"global-value";if(e.startsWith("Supervisor."))return"supervisor";if(e.includes(".locally")||e.includes(".locallyWith")||e.includes(".locallyScoped")||e.includes(".getFiberRefs")||e.includes(".setFiberRefs")||e.includes(".inheritFiberRefs")||e.includes("FiberRef."))return"fiberref";if(e.includes(".withConcurrency")||e.includes(".withScheduler")||e.includes(".withSchedulingPriority")||e.includes(".daemonChildren")||e.includes(".awaitAllChildren")||e.includes(".supervised"))return"structured-concurrency";if(e.startsWith("Context.pick")||e.startsWith("Context.omit")||e==="Effect.provide"||e.startsWith("Effect.")&&e.includes(".provide")&&!e.includes("provideService"))return"context";if(e.includes(".serviceOption")||e.includes(".serviceOptional")||e.includes(".serviceFunction")||e.includes(".serviceFunctionEffect")||e.includes(".serviceFunctions")||e.includes(".serviceConstants")||e.includes(".serviceMembers")||e.includes(".updateService"))return"service";if(e.startsWith("CliApp.")||e.startsWith("Args.")||e.startsWith("Options."))return"cli";if(e.startsWith("AiModel.")||e.startsWith("AiToolkit.")||e.startsWith("Completions.")||e.startsWith("AiInput.")||e.startsWith("AiResponse."))return"ai";if(e.startsWith("NodeSdk.")||e.startsWith("WebSdk.")||e.startsWith("OtelMetrics."))return"opentelemetry";if(e.startsWith("Entity.")||e.startsWith("ClusterSchema.")||e.startsWith("MessageState.")||e.startsWith("Sharding."))return"cluster";if(e.startsWith("RpcGroup.")||e.startsWith("RpcApi.")||e.startsWith("RpcClient.")||e.startsWith("RpcRouter."))return"rpc";if(e.startsWith("SqlResolver.")||e.startsWith("SqlMigrator."))return"sql";if(e.startsWith("DevTools.")||e.startsWith("Server."))return"devtools";if(e.startsWith("BigDecimal."))return"big-decimal";if(e.startsWith("Graph."))return"graph";if(e.startsWith("HashRing."))return"hash-ring";if(e.startsWith("Chunk."))return"chunk";if(e.startsWith("HashMap.")||e.startsWith("HashSet.")||e.startsWith("List.")||e.startsWith("SortedMap.")||e.startsWith("SortedSet.")||e.startsWith("RedBlackTree.")||e.startsWith("Trie."))return"immutable-collection";if(e.includes(".map")||e.includes(".flatMap")||e.includes(".andThen")||e.includes(".tap")||e.includes(".tapBoth")||e.includes(".tapError")||e.includes(".tapErrorTag")||e.includes(".tapErrorCause")||e.includes(".tapDefect")||e.includes(".zip")||e.includes(".zipLeft")||e.includes(".zipRight")||e.includes(".zipWith")||e.includes(".as")||e.includes(".asVoid")||e.includes(".flatten")||e.includes(".merge")||e.includes(".ap")||e.includes(".validate")||e.includes(".negate"))return"transformation";if(e.startsWith("Printer.")||e.startsWith("Doc.")||e.startsWith("DocTree.")||e.startsWith("PageWidth.")||e.startsWith("Optimize."))return"printer";if(e.startsWith("Http")||e.startsWith("FileSystem.")||e.startsWith("Command.")||e.startsWith("Socket.")||e.startsWith("Worker."))return"platform";if(e.includes("channel.")&&!e.includes("Channel"))return"channel"},$r=(e,t)=>{let n=br(e);if(n)return n;if(t){let r=e.indexOf(".");if(r>0){let o=e.substring(0,r);if(t.has(o)){let s=e.substring(r+1);return br(`Effect.${s}`)}}}},ne=(e,t,n=new Set)=>{let{SyntaxKind:r}=I(),o=f=>n.has(f),s=f=>/\.run(?:Promise(?:Exit)?|Sync(?:Exit)?|Fork|Callback|Main)$/.test(f)||/^Runtime\.run(?:Promise|Sync|Fork)$/.test(f),a=f=>{if(s(f))return!1;let u=f==="pipe"||f.endsWith(".pipe"),p=f.indexOf(".");return p>0&&o(f.slice(0,p))?!1:u||[...t].some(g=>f.startsWith(`${g}.`))},i=f=>{let u=f.getExpression(),p=u.getText();if(s(p))return!1;let g=p==="pipe",m=u.getKind()===r.PropertyAccessExpression&&u.getName()==="pipe";if(g||m){if(f.getArguments().some(x=>ne(x,t,n)))return!0;if(m){let x=u.getExpression();return ne(x,t,n)}return!1}return u.getKind()===r.Identifier&&t.has(p)&&!o(p)||a(p)||u.getKind()===r.PropertyAccessExpression&&ne(u.getExpression(),t,n)?!0:f.getArguments().some(h=>ne(h,t,n))},c=(f,u)=>{let p=f.getParent();for(;p&&p!==u;){let g=p.getKind();if(g===r.FunctionDeclaration||g===r.FunctionExpression||g===r.ArrowFunction||g===r.MethodDeclaration||g===r.GetAccessor||g===r.SetAccessor||g===r.ClassDeclaration||g===r.ClassExpression||g===r.Constructor||g===r.ClassStaticBlockDeclaration)return!1;p=p.getParent()}return!0},d=f=>f.getDescendantsOfKind(r.CallExpression).some(m=>c(m,f)&&i(m))||f.getDescendantsOfKind(r.AwaitExpression).some(m=>c(m,f)&&ne(m,t,n))?!0:f.getDescendantsOfKind(r.PropertyAccessExpression).some(m=>c(m,f)&&ne(m,t,n)),l=f=>f.getDescendantsOfKind(r.CallExpression).some(u=>c(u,f)&&s(u.getExpression().getText()));if(e.getKind()===r.ObjectLiteralExpression)return e.getProperties().some(u=>{if(u.getKind()===r.PropertyAssignment||u.getKind()===r.ShorthandPropertyAssignment){let p=u.getKind()===r.PropertyAssignment?u.getInitializer():void 0;return p?ne(p,t,n):!1}if(u.getKind()===r.MethodDeclaration||u.getKind()===r.GetAccessor||u.getKind()===r.SetAccessor){let p=u.getBody();return p?d(p):!1}return!1});if(e.getKind()===r.ArrowFunction||e.getKind()===r.FunctionExpression){let u=e.getBody();if(u.getKind()===r.Block){let p=u;return p.getDescendantsOfKind(r.ReturnStatement).some(h=>{if(!c(h,p))return!1;let x=h.getExpression();return x!==void 0&&ne(x,t,n)})?!0:l(p)?!1:d(p)}return ne(u,t,n)}if(e.getKind()===r.CallExpression)return i(e);if(e.getKind()===r.AwaitExpression){let f=e.getExpression();return f.getKind()!==r.CallExpression?!1:i(f)}if(e.getKind()===r.ConditionalExpression){let f=e;return ne(f.getWhenTrue(),t,n)||ne(f.getWhenFalse(),t,n)}if(e.getKind()===r.PropertyAccessExpression){let f=e.getText(),u=f.indexOf(".");return u>0&&o(f.slice(0,u))?!1:[...t].some(p=>f.startsWith(`${p}.`))}return!1};function Fe(e){return e==="effect"||e.startsWith("effect/")||e.startsWith("@effect/")}var Fn=new Set(["Effect","Layer","Schedule","Stream","Queue","PubSub","Deferred","Semaphore","Mailbox","SubscriptionRef","Scope","Fiber","Runtime","ManagedRuntime","Cause","Exit","Data","Option","Either","Chunk","HashMap","HashSet","Match","Config","Schema","Cache","ScopedCache","Metric","Logger","Tracer","Context","Brand","Encoding","Predicate","DateTime","Cron","BigDecimal","Graph","HashRing","Redacted","GlobalValue","NodeRuntime","BunRuntime","DenoRuntime","Channel","Sink"]),Dr=new Set(["core","core-effect","core-stream","fiberRuntime","effectable","channel","sink","layer","schedule","mailbox","pubsub"]);function Pr(e){let t=new Set(["never","unknown","any","{}","object"]),n=e.trim();return!n||t.has(n)?[]:n.split(/[\s|&]+/).map(o=>o.trim().split("<")[0]?.trim()??"").filter(o=>o.length>0&&!t.has(o))}function Nt(e){let{SyntaxKind:t}=I(),n=e.getKind();if(n===t.NumericLiteral){let r=e.getText(),o=Number(r);return Number.isFinite(o)?o:void 0}if(n===t.PrefixUnaryExpression){let r=e;if(r.getOperatorToken()===t.MinusToken){let o=r.getOperand(),s=Nt(o);return s!==void 0?-s:void 0}}}var Rn={tsConfigPath:"./tsconfig.json",resolveReferences:!0,maxReferenceDepth:5,includeLocations:!0,assumeImported:!1,enableEffectWorkflow:!1,knownEffectInternalsRoot:void 0,minDiscoveryConfidence:"low",onlyExportedPrograms:!1,enableEffectFlow:!1},Or=0,Tt=()=>{Or=0},k=()=>`effect-${++Or}`,Lr=new WeakMap;function _t(e){let t=Lr.get(e);return t===void 0&&(t=e.getText(),Lr.set(e,t)),t}function Wr(e){let t=new Set,n=r=>{for(let o of r){if(o.type==="effect"){let a=o.typeSignature?.errorType?.trim();if(a&&a!=="never")for(let i of Ae(a))t.add(i)}let s=Mr.getOrElse(v(o),()=>[]);s.length>0&&n(s)}};return n(e),Array.from(t).sort()}function Kr(e){let t=new Map,n=r=>{for(let o of r){if(o.type==="effect"){let a=o.requiredServices;if(a)for(let i of a)t.has(i.serviceId)||t.set(i.serviceId,{name:i.serviceId,typeSignature:i.serviceType,isLayer:!1});if((o.semanticRole==="environment"||o.semanticRole==="side-effect")&&o.callee){let i=o.callee;/^[A-Z]/.test(i)&&!i.startsWith("Effect.")&&!i.startsWith("Schema.")&&!i.startsWith("Data.")&&!i.startsWith("Config.")&&!i.startsWith("Command.")&&!i.startsWith("Stream.")&&!i.startsWith("Option.")&&!i.startsWith("Either.")&&!i.startsWith("Cause.")&&!i.startsWith("Exit.")&&!t.has(i)&&t.set(i,{name:i,typeSignature:o.typeSignature?.requirementsType,isLayer:!1})}}let s=Mr.getOrElse(v(o),()=>[]);s.length>0&&n(s)}};return n(e),Array.from(t.values())}var K=(e,t,n)=>{if(!n)return;let r=e.getSourceFile(),o=e.getStart(),{line:s,column:a}=r.getLineAndColumnAtPos(o),i=e.getEnd(),c=r.getLineAndColumnAtPos(i);return{filePath:t,line:s,column:a,endLine:c.line,endColumn:c.column}},Ue=e=>{let t=e.getJsDocs?.();if(t&&t.length>0){let r=t[0];if(!r)return;let o=r.getComment?.();if(o){let i;if(typeof o=="string")i=o;else if(Array.isArray(o))i=o.map(d=>d.text).join(`
|
|
2
|
+
`);else return;let c=i.search(/\n\s*@/);return c!==-1&&(i=i.substring(0,c)),i.trim()||void 0}let s=r.getText(),a=/\/\*\*\s*\n?\s*\*\s*([^@]*?)(?=\n\s*\*\s*@|\*\/)/.exec(s);if(a?.[1])return a[1].replace(/\n\s*\*\s*/g," ").trim()||void 0}let n=e.getLeadingCommentRanges();if(n.length>0){let r=n[n.length-1];if(!r)return;let o=r.getText();if(o.startsWith("/**")){let s=o.replace(/^\/\*\*\s*/,"").replace(/\s*\*\/\s*$/,"").replace(/^\s*\*\s?/gm,"").trim(),a=s.search(/\n@/);return a!==-1?s.substring(0,a).trim()||void 0:s||void 0}}},ot=e=>{let t=r=>{let o=r.getJsDocs?.();if(o&&o.length>0)return o[0].getText();let s=r.getLeadingCommentRanges();if(s.length>0){let a=s[s.length-1];if(a){let i=a.getText();if(i.startsWith("/**"))return i}}},n=t(e);if(!n){let{SyntaxKind:r}=I(),o=e.getParent();for(;o&&!n;){let s=o.getKind();if(s===r.VariableStatement){n=t(o);break}if(s===r.VariableDeclarationList){let a=o.getParent();a&&(n=t(a));break}if(s===r.CallExpression||s===r.ArrowFunction||s===r.VariableDeclaration||s===r.ParenthesizedExpression)o=o.getParent();else break}}if(n)return Bi(n)};function Bi(e){let t=e.replace(/^\/\*\*/,"").replace(/\*\/$/,"").split(`
|
|
3
3
|
`).map(c=>c.replace(/^\s*\*\s?/,"")).join(`
|
|
4
|
-
`),r=[],n,o=[],s,a=/@(param|returns?|throws?|exception|example)\s*(.*)/gi,i;for(;(i=a.exec(t))!==null;){let c=i[1].toLowerCase(),d=i[2].trim();if(c==="param"){let l=/^(?:\{[^}]*\}\s*)?(\[?\w+(?:=[^\]]*)?]?)\s*(?:-\s*(.*))?$/.exec(d);if(l){let f=l[1].replace(/^\[|\]$/g,"").replace(/=.*/,""),u=l[2]?.trim();r.push(u?{name:f,description:u}:{name:f})}}else if(c==="returns"||c==="return")n=d.replace(/^\{[^}]*\}\s*/,"").trim()||void 0;else if(c==="throws"||c==="throw"||c==="exception"){let l=d.replace(/^\{[^}]*\}\s*/,"").trim();l&&o.push(l)}else if(c==="example"){let l=i.index+i[0].length,f=/\n\s*@\w/.exec(t.slice(l));f?s=t.slice(i.index+i[0].length-d.length,l+f.index).trim()||void 0:s=t.slice(i.index+i[0].length-d.length).trim()||void 0}}if(!(r.length===0&&!n&&o.length===0&&!s))return{params:r,returns:n,throws:o,example:s}}var yr=e=>{let t=e.getParent(),{SyntaxKind:r}=I();if(t){let n=t.getKind();if(n===r.VariableDeclaration)return ze(t);if(n===r.ArrowFunction){let o=t.getParent();if(o?.getKind()===r.VariableDeclaration)return ze(o)}}};function Sr(e){return e.endsWith(".js")||e.endsWith(".jsx")}var Mt=e=>{let t=e.getParent(),{SyntaxKind:r}=I();if(t?.getKind()===r.VariableDeclaration)return t.getName()},He=e=>{let{SyntaxKind:t}=I(),r=s=>{let a=s;for(;a!==void 0;){if(a.getKind()===t.VariableDeclaration)return a.getName();a=a.getParent()}},n=e.getParent();if(n){let s=n.getKind();if(s===t.VariableDeclaration)return n.getName();if(s===t.AwaitExpression){let a=n.getParent();if(a?.getKind()===t.VariableDeclaration)return a.getName()}if(s===t.PropertyAssignment){let i=n.getName(),c=r(n);return c?`${c}.${i}`:i}if(s===t.ArrowFunction){let a=n.getParent();if(a?.getKind()===t.VariableDeclaration)return a.getName();if(a?.getKind()===t.PropertyAssignment){let c=a.getName(),d=r(a);return d?`${d}.${c}`:c}}}let o=e;for(let s=0;o&&s<6&&(o=o.getParent(),!!o);s++){let a=o.getKind();if(a===t.VariableDeclaration)return o.getName();if(a===t.PropertyAssignment){let c=o.getName(),d=r(o);return d?`${d}.${c}`:c}if(a===t.Block||a===t.SourceFile)break}},xr=e=>{let{SyntaxKind:t}=I(),r=e.getParent();for(let n=0;r&&n<10;n++){if(r.getKind()===t.CallExpression){let o=r,s=o.getExpression().getText();if(s==="Effect.fn"||s.endsWith(".fn")){let a=o.getArguments();if(a.length>0){let i=a[0].getText(),c=/^["'](.+)["']$/.exec(i);if(c?.[1])return c[1]}}}r=r.getParent()}},Er=()=>({totalEffects:0,parallelCount:0,raceCount:0,errorHandlerCount:0,retryCount:0,timeoutCount:0,resourceCount:0,loopCount:0,conditionalCount:0,layerCount:0,interruptionCount:0,unknownCount:0,decisionCount:0,switchCount:0,tryCatchCount:0,terminalCount:0,opaqueCount:0}),mt=(e,t)=>e.length<=t?e:`${e.slice(0,t)}\u2026`;function j(e,t){switch(e.type){case"effect":{let r=t??e.name;return r?`${r} <- ${e.callee}`:e.callee}case"generator":return`Generator (${e.yields.length} yields)`;case"pipe":return`Pipe (${e.transformations.length} steps)`;case"parallel":return`${e.callee} (${e.children.length})`;case"race":return`${e.callee} (${e.children.length} racing)`;case"error-handler":return e.name?`${e.name}: ${e.handlerType}`:e.handlerType;case"retry":return e.schedule?`retry: ${e.schedule}`:"retry";case"timeout":return e.duration?`timeout: ${e.duration}`:"timeout";case"resource":return"Resource";case"conditional":return mt(e.condition,30);case"loop":return e.iterSource?`${e.loopType}(${e.iterSource})`:e.loopType;case"layer":return e.isMerged?"Layer (merged)":"Layer";case"stream":{let n=["Stream",...e.pipeline.map(o=>o.operation)];return e.sink&&n.push(e.sink),n.join(" \u2192 ")}case"concurrency-primitive":return`${e.primitive}.${e.operation}`;case"fiber":{let r=e.operation;return e.isDaemon?`${r} (daemon)`:e.isScoped?`${r} (scoped)`:r}case"transform":return e.transformType;case"match":return`Match.${e.matchOp}`;case"cause":return`Cause.${e.causeOp}`;case"exit":return`Exit.${e.exitOp}`;case"schedule":return`Schedule.${e.scheduleOp}`;case"interruption":return e.interruptionType;case"channel":{let r=e.pipeline.map(n=>n.operation);return r.length>0?`Channel: ${r.join(" \u2192 ")}`:"Channel"}case"sink":{let r=e.pipeline.map(n=>n.operation);return r.length>0?`Sink: ${r.join(" \u2192 ")}`:"Sink"}case"decision":return mt(e.condition,30);case"switch":return`switch(${mt(e.expression,25)})`;case"try-catch":return"try/catch";case"terminal":return e.label?`${e.terminalKind} ${e.label}`:e.terminalKind;case"opaque":return`Opaque: ${mt(e.reason,25)}`;case"unknown":return`Unknown: ${mt(e.reason,30)}`}}function U(e){switch(e.type){case"effect":{if(e.serviceCall||e.serviceMethod)return"service-call";let t=e.description?.toLowerCase()??"";if(t.includes("service"))return"service-call";if(t.includes("layer")||e.provideKind==="layer")return"layer";let r=e.callee.toLowerCase();return/^[A-Z][A-Za-z0-9_]*$/.test(e.callee)&&!e.constructorKind?"environment":r.includes("sync")||r.includes("promise")||r.includes("async")||r.includes("log")||r.includes("console")?"side-effect":r.includes("succeed")||r.includes("fail")||r.includes("die")||r.includes("void")||r.includes("never")||r.includes("gen")||r.includes("make")||e.constructorKind?"constructor":"side-effect"}case"generator":case"pipe":return"constructor";case"parallel":case"race":case"concurrency-primitive":return"concurrency";case"error-handler":case"cause":case"exit":return"error-handler";case"retry":case"timeout":case"schedule":return"scheduling";case"resource":return"resource";case"conditional":case"loop":case"match":case"decision":case"switch":case"terminal":return"control-flow";case"try-catch":return"error-handler";case"opaque":return"unknown";case"layer":return"layer";case"stream":case"channel":case"sink":return"stream";case"fiber":case"interruption":return"fiber";case"transform":return"transform";case"unknown":return"unknown"}}var un=[".catchAll",".catchTag",".catchAllCause",".catchIf",".catchSome",".catchSomeCause",".catchSomeDefect",".catchAllDefect",".catchTags",".orElse",".orElseFail",".orElseSucceed",".orDie",".orDieWith",".flip",".mapError",".mapErrorCause",".mapBoth",".sandbox",".unsandbox",".parallelErrors",".filterOrDie",".filterOrDieMessage",".filterOrElse",".filterOrFail",".match",".matchCause",".matchEffect",".matchCauseEffect",".firstSuccessOf",".ignore",".ignoreLogged",".eventually"],fn=[".if",".when",".whenEffect",".whenFiberRef",".whenRef",".unless",".unlessEffect",".option",".either",".exit",".liftPredicate"],Fi=[".acquireRelease",".acquireUseRelease",".ensuring",".addFinalizer",".onExit",".onError",".parallelFinalizers",".sequentialFinalizers",".finalizersMask",".using",".withEarlyRelease"],pn=[".forEach",".loop",".filter",".filterMap",".partition",".reduce",".reduceRight",".reduceWhile",".reduceEffect",".dropUntil",".dropWhile",".takeUntil",".takeWhile",".every",".exists",".findFirst",".head",".mergeAll",".replicate",".replicateEffect",".validateAll",".validateFirst",".validate",".validateWith"],gn=["Effect.fork",".fork",".forkAll",".forkIn",".forkWithErrorHandler","Fiber."],mn={"Effect.map":"map","Effect.flatMap":"flatMap","Effect.andThen":"andThen","Effect.tap":"tap","Effect.tapBoth":"tapBoth","Effect.tapError":"tapError","Effect.tapErrorTag":"tapErrorTag","Effect.tapErrorCause":"tapErrorCause","Effect.tapDefect":"tapDefect","Effect.zipLeft":"zipLeft","Effect.zipRight":"zipRight","Effect.zipWith":"zipWith","Effect.zip":"zip","Effect.as":"as","Effect.asVoid":"asVoid","Effect.asSome":"asSome","Effect.asSomeError":"asSomeError","Effect.flatten":"flatten","Effect.ap":"ap","Effect.negate":"negate","Effect.merge":"merge"},Cr=new Set(["flatMap","andThen","tapBoth","tapError","tapErrorTag","tapErrorCause","tapDefect","zipWith","zipLeft","zipRight","zip","ap","flatten"]),Nr=e=>e in mn,hn={"Match.type":"type","Match.tag":"tag","Match.value":"value","Match.when":"when","Match.whenOr":"whenOr","Match.whenAnd":"whenAnd","Match.not":"not","Match.is":"is","Match.exhaustive":"exhaustive","Match.orElse":"orElse","Match.option":"option","Match.either":"either","Match.discriminator":"discriminator","Match.discriminatorsExhaustive":"discriminatorsExhaustive","Match.tags":"tags","Match.tagsExhaustive":"tagsExhaustive","Match.withReturnType":"withReturnType","Match.run":"run"},vr=new Set(["exhaustive","discriminatorsExhaustive","tagsExhaustive"]),wr=e=>e.startsWith("Match.")&&e in hn,yn={"Cause.fail":"fail","Cause.die":"die","Cause.interrupt":"interrupt","Cause.parallel":"parallel","Cause.sequential":"sequential","Cause.empty":"empty","Cause.failures":"failures","Cause.defects":"defects","Cause.interruptors":"interruptors","Cause.squash":"squash","Cause.squashWith":"squashWith","Cause.pretty":"pretty","Cause.flatten":"flatten","Cause.isDie":"isDie","Cause.isFailure":"isFailure","Cause.isInterrupted":"isInterrupted","Cause.isEmpty":"isEmpty","Cause.map":"map","Cause.filter":"filter"},Tr=new Set(["fail","die","interrupt","parallel","sequential","empty"]),kr=e=>e.startsWith("Cause.")&&e in yn,Sn={"Exit.succeed":"succeed","Exit.fail":"fail","Exit.die":"die","Exit.interrupt":"interrupt","Exit.void":"void","Exit.unit":"unit","Exit.match":"match","Exit.isSuccess":"isSuccess","Exit.isFailure":"isFailure","Exit.isInterrupted":"isInterrupted","Exit.when":"when","Exit.whenEffect":"whenEffect","Exit.exists":"exists","Exit.contains":"contains","Exit.flatten":"flatten","Exit.map":"map","Exit.mapBoth":"mapBoth","Exit.mapError":"mapError","Exit.flatMap":"flatMap","Exit.zipWith":"zipWith","Exit.tap":"tap","Exit.tapBoth":"tapBoth","Exit.tapError":"tapError"},Ir=new Set(["succeed","fail","die","interrupt","void","unit"]),Ar=e=>e.startsWith("Exit.")&&(e in Sn||/^Exit\.\w+$/.test(e)),xn={"Schedule.exponential":"exponential","Schedule.fibonacci":"fibonacci","Schedule.spaced":"spaced","Schedule.fixed":"fixed","Schedule.linear":"linear","Schedule.cron":"cron","Schedule.windowed":"windowed","Schedule.duration":"duration","Schedule.elapsed":"elapsed","Schedule.delays":"delays","Schedule.once":"once","Schedule.stop":"stop","Schedule.count":"count","Schedule.forever":"forever","Schedule.jittered":"jittered","Schedule.andThen":"andThen","Schedule.intersect":"intersect","Schedule.union":"union","Schedule.compose":"compose","Schedule.zipWith":"zipWith","Schedule.addDelay":"addDelay","Schedule.modifyDelay":"modifyDelay","Schedule.check":"check","Schedule.resetAfter":"resetAfter","Schedule.resetWhen":"resetWhen","Schedule.ensure":"ensure","Schedule.driver":"driver","Schedule.mapInput":"mapInput"},Fr=e=>e.startsWith("Schedule.")&&(e in xn||/^Schedule\.\w+$/.test(e)),En=[".interruptible",".uninterruptible",".interruptibleMask",".uninterruptibleMask",".onInterrupt",".disconnect",".allowInterrupt","Effect.interrupt",".interruptWith"],Ri=[".Do",".bind",".bindAll",".bindTo"],$i=[".cached",".cachedWithTTL",".cachedInvalidateWithTTL",".cachedFunction",".once","Cache.","ScopedCache."],bn=["Effect.","Layer.","Schedule.","Stream.","Queue.","PubSub.","Deferred.","Semaphore.","Mailbox.","SubscriptionRef.","Scope.","Fiber.","Runtime.","ManagedRuntime.","NodeRuntime.","BunRuntime.","DenoRuntime.","Cause.","Exit.","Data.","Option.","Either.","Chunk.","HashMap.","HashSet.","List.","SortedMap.","SortedSet.","RedBlackTree.","Trie.","Graph.","Match.","Config.","Schema.","Cache.","ScopedCache.","RcRef.","RcMap.","Reloadable.","Cache.","ScopedCache.","RateLimiter.","PartitionedSemaphore.","FiberSet.","FiberMap.","FiberHandle.","Metric.","Logger.","Tracer.","Context.","HttpClient.","HttpRouter.","HttpApi.","FileSystem.","Command.","Socket.","SocketServer.","Worker.","Terminal.","KeyValueStore.","Multipart.","Ndjson.","MsgPack.","OpenApi.","OpenApiJsonSchema.","Brand.","Encoding.","Predicate.","DateTime.","Cron.","BigDecimal.","HashRing.","Redacted.","GlobalValue.","Channel.","Sink.","CliApp.","Args.","Options.","AiModel.","AiToolkit.","Completions.","AiInput.","AiResponse.","NodeSdk.","WebSdk.","Entity.","ClusterSchema.","MessageState.","Sharding.","RpcGroup.","RpcApi.","RpcClient.","RpcRouter.","SqlResolver.","SqlMigrator.","Printer.","Doc.","DocTree.","PageWidth.","Optimize."],Rr=new Set(["Array","ReadonlyArray","String","Number","Boolean","Object","Function","Promise","Math","Date","RegExp","Error","Map","Set","WeakMap","WeakSet","Symbol","BigInt","JSON","Console","process","Buffer","EventEmitter","Window","Document","AbortController"]),Cn=new Set(["Effect","Layer","Stream","Queue","PubSub","Deferred","Semaphore","Mailbox","SubscriptionRef","Scope","Fiber","Runtime","ManagedRuntime","Cause","Exit","Data","Option","Either","Chunk","HashMap","HashSet","List","SortedMap","SortedSet","Match","Config","Schema","Schedule","Metric","Tracer","Logger","FiberRef","FiberHandle","FiberSet","FiberMap","Cache","ScopedCache","RateLimiter","Supervisor"]),$r=e=>e.includes(".")||Cn.has(e)?!1:/^[A-Z][A-Za-z0-9]*$/.test(e),br=e=>{if(e.startsWith("Channel."))return"channel";if(e.startsWith("Sink."))return"sink";if(e.endsWith(".never"))return"never";if(e.endsWith(".void"))return"void-effect";if(e.endsWith(".fromNullable"))return"null-coalescing";if(e.endsWith(".fn")||e.endsWith(".fnUntraced"))return"function-lift";if(e.includes(".async")||e.includes(".asyncEffect")||e.includes(".promise")||e.includes(".sync")||e.includes(".suspend")||e.includes(".succeed")||e.includes(".fail")||e.includes(".try"))return"constructor";if(En.some(t=>e.includes(t)))return"interruption";if(Ri.some(t=>e.includes(t)))return"do-notation";if($i.some(t=>e.includes(t)||e.startsWith(t)))return"caching";if(un.some(t=>e.includes(t)))return"error-handler";if(fn.some(t=>e.includes(t)))return"conditional";if(Fi.some(t=>e.includes(t)))return"resource";if(pn.some(t=>e.includes(t)))return"collection";if(gn.some(t=>e.includes(t)))return"fiber";if(e.startsWith("Stream."))return"stream";if(e.startsWith("Layer."))return"layer";if(e.startsWith("Schema."))return"schema";if(e.startsWith("Config."))return"config";if(e.startsWith("Cause."))return"cause";if(e.startsWith("Exit."))return"exit";if(e==="Data.tagged"||e==="Data.taggedEnum")return"tagged-enum";if(e.startsWith("Data."))return"data";if(e.startsWith("Option."))return"option";if(e.startsWith("Either."))return"either";if(e.startsWith("Match."))return"match";if(e.startsWith("ManagedRuntime.")||e.startsWith("Runtime.")||e.startsWith("NodeRuntime.")||e.startsWith("BunRuntime.")||e.startsWith("DenoRuntime."))return"runtime";if(e.startsWith("Scope."))return"scope";if(e.startsWith("ScopedRef.")||e.startsWith("RcRef.")||e.startsWith("RcMap."))return"resource-ref";if(e.startsWith("Reloadable.")||e.startsWith("Resource."))return"reloadable";if(e.startsWith("Micro."))return"micro";if(e.startsWith("Brand."))return"brand";if(e.startsWith("Encoding."))return"encoding";if(e.startsWith("Predicate."))return"predicate";if(e.startsWith("DateTime."))return"datetime";if(e.startsWith("Cron."))return"cron";if(e.startsWith("Redacted."))return"redacted";if(e.startsWith("GlobalValue."))return"global-value";if(e.startsWith("Supervisor."))return"supervisor";if(e.includes(".locally")||e.includes(".locallyWith")||e.includes(".locallyScoped")||e.includes(".getFiberRefs")||e.includes(".setFiberRefs")||e.includes(".inheritFiberRefs")||e.includes("FiberRef."))return"fiberref";if(e.includes(".withConcurrency")||e.includes(".withScheduler")||e.includes(".withSchedulingPriority")||e.includes(".daemonChildren")||e.includes(".awaitAllChildren")||e.includes(".supervised"))return"structured-concurrency";if(e.startsWith("Context.pick")||e.startsWith("Context.omit")||e==="Effect.provide"||e.startsWith("Effect.")&&e.includes(".provide")&&!e.includes("provideService"))return"context";if(e.includes(".serviceOption")||e.includes(".serviceOptional")||e.includes(".serviceFunction")||e.includes(".serviceFunctionEffect")||e.includes(".serviceFunctions")||e.includes(".serviceConstants")||e.includes(".serviceMembers")||e.includes(".updateService"))return"service";if(e.startsWith("CliApp.")||e.startsWith("Args.")||e.startsWith("Options."))return"cli";if(e.startsWith("AiModel.")||e.startsWith("AiToolkit.")||e.startsWith("Completions.")||e.startsWith("AiInput.")||e.startsWith("AiResponse."))return"ai";if(e.startsWith("NodeSdk.")||e.startsWith("WebSdk.")||e.startsWith("OtelMetrics."))return"opentelemetry";if(e.startsWith("Entity.")||e.startsWith("ClusterSchema.")||e.startsWith("MessageState.")||e.startsWith("Sharding."))return"cluster";if(e.startsWith("RpcGroup.")||e.startsWith("RpcApi.")||e.startsWith("RpcClient.")||e.startsWith("RpcRouter."))return"rpc";if(e.startsWith("SqlResolver.")||e.startsWith("SqlMigrator."))return"sql";if(e.startsWith("DevTools.")||e.startsWith("Server."))return"devtools";if(e.startsWith("BigDecimal."))return"big-decimal";if(e.startsWith("Graph."))return"graph";if(e.startsWith("HashRing."))return"hash-ring";if(e.startsWith("Chunk."))return"chunk";if(e.startsWith("HashMap.")||e.startsWith("HashSet.")||e.startsWith("List.")||e.startsWith("SortedMap.")||e.startsWith("SortedSet.")||e.startsWith("RedBlackTree.")||e.startsWith("Trie."))return"immutable-collection";if(e.includes(".map")||e.includes(".flatMap")||e.includes(".andThen")||e.includes(".tap")||e.includes(".tapBoth")||e.includes(".tapError")||e.includes(".tapErrorTag")||e.includes(".tapErrorCause")||e.includes(".tapDefect")||e.includes(".zip")||e.includes(".zipLeft")||e.includes(".zipRight")||e.includes(".zipWith")||e.includes(".as")||e.includes(".asVoid")||e.includes(".flatten")||e.includes(".merge")||e.includes(".ap")||e.includes(".validate")||e.includes(".negate"))return"transformation";if(e.startsWith("Printer.")||e.startsWith("Doc.")||e.startsWith("DocTree.")||e.startsWith("PageWidth.")||e.startsWith("Optimize."))return"printer";if(e.startsWith("Http")||e.startsWith("FileSystem.")||e.startsWith("Command.")||e.startsWith("Socket.")||e.startsWith("Worker."))return"platform";if(e.includes("channel.")&&!e.includes("Channel"))return"channel"},Dr=(e,t)=>{let r=br(e);if(r)return r;if(t){let n=e.indexOf(".");if(n>0){let o=e.substring(0,n);if(t.has(o)){let s=e.substring(n+1);return br(`Effect.${s}`)}}}},te=(e,t,r=new Set)=>{let{SyntaxKind:n}=I(),o=f=>r.has(f),s=f=>/\.run(?:Promise(?:Exit)?|Sync(?:Exit)?|Fork|Callback|Main)$/.test(f)||/^Runtime\.run(?:Promise|Sync|Fork)$/.test(f),a=f=>{if(s(f))return!1;let u=f==="pipe"||f.endsWith(".pipe"),p=f.indexOf(".");return p>0&&o(f.slice(0,p))?!1:u||[...t].some(g=>f.startsWith(`${g}.`))},i=f=>{let u=f.getExpression(),p=u.getText();if(s(p))return!1;let g=p==="pipe",m=u.getKind()===n.PropertyAccessExpression&&u.getName()==="pipe";if(g||m){if(f.getArguments().some(h=>te(h,t,r)))return!0;if(m){let h=u.getExpression();return te(h,t,r)}return!1}return u.getKind()===n.Identifier&&t.has(p)&&!o(p)||a(p)||u.getKind()===n.PropertyAccessExpression&&te(u.getExpression(),t,r)?!0:f.getArguments().some(S=>te(S,t,r))},c=(f,u)=>{let p=f.getParent();for(;p&&p!==u;){let g=p.getKind();if(g===n.FunctionDeclaration||g===n.FunctionExpression||g===n.ArrowFunction||g===n.MethodDeclaration||g===n.GetAccessor||g===n.SetAccessor||g===n.ClassDeclaration||g===n.ClassExpression||g===n.Constructor||g===n.ClassStaticBlockDeclaration)return!1;p=p.getParent()}return!0},d=f=>f.getDescendantsOfKind(n.CallExpression).some(m=>c(m,f)&&i(m))||f.getDescendantsOfKind(n.AwaitExpression).some(m=>c(m,f)&&te(m,t,r))?!0:f.getDescendantsOfKind(n.PropertyAccessExpression).some(m=>c(m,f)&&te(m,t,r)),l=f=>f.getDescendantsOfKind(n.CallExpression).some(u=>c(u,f)&&s(u.getExpression().getText()));if(e.getKind()===n.ObjectLiteralExpression)return e.getProperties().some(u=>{if(u.getKind()===n.PropertyAssignment||u.getKind()===n.ShorthandPropertyAssignment){let p=u.getKind()===n.PropertyAssignment?u.getInitializer():void 0;return p?te(p,t,r):!1}if(u.getKind()===n.MethodDeclaration||u.getKind()===n.GetAccessor||u.getKind()===n.SetAccessor){let p=u.getBody();return p?d(p):!1}return!1});if(e.getKind()===n.ArrowFunction||e.getKind()===n.FunctionExpression){let u=e.getBody();if(u.getKind()===n.Block){let p=u;return p.getDescendantsOfKind(n.ReturnStatement).some(S=>{if(!c(S,p))return!1;let h=S.getExpression();return h!==void 0&&te(h,t,r)})?!0:l(p)?!1:d(p)}return te(u,t,r)}if(e.getKind()===n.CallExpression)return i(e);if(e.getKind()===n.AwaitExpression){let f=e.getExpression();return f.getKind()!==n.CallExpression?!1:i(f)}if(e.getKind()===n.ConditionalExpression){let f=e;return te(f.getWhenTrue(),t,r)||te(f.getWhenFalse(),t,r)}if(e.getKind()===n.PropertyAccessExpression){let f=e.getText(),u=f.indexOf(".");return u>0&&o(f.slice(0,u))?!1:[...t].some(p=>f.startsWith(`${p}.`))}return!1};function $e(e){return e==="effect"||e.startsWith("effect/")||e.startsWith("@effect/")}var Nn=new Set(["Effect","Layer","Schedule","Stream","Queue","PubSub","Deferred","Semaphore","Mailbox","SubscriptionRef","Scope","Fiber","Runtime","ManagedRuntime","Cause","Exit","Data","Option","Either","Chunk","HashMap","HashSet","Match","Config","Schema","Cache","ScopedCache","Metric","Logger","Tracer","Context","Brand","Encoding","Predicate","DateTime","Cron","BigDecimal","Graph","HashRing","Redacted","GlobalValue","NodeRuntime","BunRuntime","DenoRuntime","Channel","Sink"]),Pr=new Set(["core","core-effect","core-stream","fiberRuntime","effectable","channel","sink","layer","schedule","mailbox","pubsub"]);function Mr(e){let t=new Set(["never","unknown","any","{}","object"]),r=e.trim();return!r||t.has(r)?[]:r.split(/[\s|&]+/).map(o=>o.trim().split("<")[0]?.trim()??"").filter(o=>o.length>0&&!t.has(o))}function yt(e){let{SyntaxKind:t}=I(),r=e.getKind();if(r===t.NumericLiteral){let n=e.getText(),o=Number(n);return Number.isFinite(o)?o:void 0}if(r===t.PrefixUnaryExpression){let n=e;if(n.getOperatorToken()===t.MinusToken){let o=n.getOperand(),s=yt(o);return s!==void 0?-s:void 0}}}import{existsSync as Di}from"fs";import{dirname as vn,resolve as St,join as De,sep as Lr}from"path";var Or=new WeakMap,Wr=new WeakMap;function wn(e){let t=new Set;for(let r of e.getExportDeclarations()){let n=r.getModuleSpecifierValue();if(!(!n||!$e(n))){if(r.isNamespaceExport()){Nn.forEach(o=>t.add(o));continue}for(let o of r.getNamedExports()){t.add(o.getName());let s=o.getAliasNode()?.getText();s&&t.add(s)}}}return t}function Xe(e,t,r){if(!r.startsWith("."))return;let n=vn(t),o=St(n,r),s=[o,`${o}.ts`,`${o}.tsx`,`${o}.js`,`${o}.jsx`,De(o,"index.ts"),De(o,"index.tsx"),De(o,"index.js"),De(o,"index.jsx")];for(let a of s){let i=e.getSourceFile(a);if(i)return i}}function xt(e,t){if(!t.startsWith("."))return;let r=vn(e),n=St(r,t);return[n,`${n}.ts`,`${n}.tsx`,`${n}.js`,`${n}.jsx`,De(n,"index.ts"),De(n,"index.tsx"),De(n,"index.js"),De(n,"index.jsx")].find(s=>Di(s))}function Lt(e,t,r){if(!r||!t.startsWith("."))return!1;let n=t.replace(/\\/g,"/"),o=St(vn(e),t),s=St(o),a=St(r);return s===a||s.startsWith(a+Lr)?!0:e==="temp.ts"||e.endsWith(`${Lr}temp.ts`)?n.startsWith("./internal/")||n.startsWith("../internal/"):!1}function Pi(e){let t=new Set(Nn),r=e.getProject(),n=e.getFilePath();for(let o of e.getImportDeclarations()){let s=o.getModuleSpecifierValue();if($e(s)){let a=o.getDefaultImport();a&&t.add(a.getText());let i=o.getNamespaceImport();i&&t.add(i.getText());for(let c of o.getNamedImports()){let d=c.getAliasNode()?.getText();t.add(d??c.getName())}continue}if(s.startsWith(".")){let a=Xe(r,n,s);if(!a)continue;let i=wn(a);if(i.size===0)continue;let c=o.getDefaultImport();if(c){let l=c.getText();i.has(l)&&t.add(l)}let d=o.getNamespaceImport();if(d){let l=d.getText();i.has(l)&&t.add(l)}for(let l of o.getNamedImports())i.has(l.getName())&&t.add(l.getAliasNode()?.getText()??l.getName())}}return t}function Tn(e,t){let r=Pi(e);for(let n of e.getImportDeclarations()){let o=n.getModuleSpecifierValue(),s=n.getNamespaceImport();if(!s)continue;let a=s.getText();if(o.startsWith("effect")||o.startsWith("@effect/")){r.add(a);continue}if(Lt(e.getFilePath(),o,t)){r.add(a);continue}let i=o.replace(/\.(js|ts)$/,"").split("/").pop()??"";Pr.has(i)&&r.add(a)}return r}var Mi=new Set(["BigDecimal","BigInt","Brand","Cause","Chunk","Data","Exit","Option","Either","HashMap","HashSet","List","Redacted"]);function Br(e){let t=new Set;for(let r of e.getImportDeclarations()){let s=r.getModuleSpecifierValue().replace(/\\/g,"/").replace(/\.(js|ts|tsx|jsx)$/,"").split("/").pop()??"";if(!Mi.has(s))continue;let a=r.getDefaultImport();a&&t.add(a.getText());let i=r.getNamespaceImport();i&&t.add(i.getText());for(let c of r.getNamedImports())t.add(c.getAliasNode()?.getText()??c.getName())}return t}function Pe(e){let t=Or.get(e);return t||(t=Tn(e),Or.set(e,t)),t}var Kr=new WeakMap;function Li(e){let t=e.replace(/\\/g,"/").replace(/\.(js|ts|mts|cts)$/,"");return t==="effect"||t.endsWith("/Effect")?"Effect":(t.split("/").pop()??"")||"Effect"}function Oi(e){let t=Kr.get(e);if(t)return t;t=new Map;for(let r of e.getImportDeclarations()){let n=r.getModuleSpecifierValue();if(!n||!$e(n))continue;let o=r.getNamespaceImport();if(!o)continue;let s=o.getText(),a=Li(n);t.set(s,a)}return Kr.set(e,t),t}function kn(e,t){let r=e.indexOf(".");if(r<=0)return e;let n=e.slice(0,r),o=e.slice(r+1),a=Oi(t).get(n);return a?`${a}.${o}`:e}function Wi(e,t){let r=Wr.get(t);r||(r=new Map,Wr.set(t,r));let n=e.indexOf("."),o=n>0?e.slice(0,n):e,s=r.get(o);if(s!==void 0)return s;let a=!1;try{for(let i of t.getImportDeclarations()){let c=i.getModuleSpecifierValue();if(i.getNamespaceImport()?.getText()===o){a=$e(c);break}if(i.getDefaultImport()?.getText()===o){a=$e(c);break}for(let f of i.getNamedImports())if((f.getAliasNode()?.getText()??f.getName())===o){if($e(c))a=!0;else if(c.startsWith(".")){let g=Xe(t.getProject(),t.getFilePath(),c);g&&(a=wn(g).has(f.getName()))}break}if(a)break}}catch{a=!1}return r.set(o,a),a}function Ki(e,t){let n=e.getExpression().getText();for(let o of t.getImportDeclarations()){let s=o.getModuleSpecifierValue();if(o.getNamespaceImport()?.getText()===n||o.getDefaultImport()?.getText()===n)return s;for(let c of o.getNamedImports())if((c.getAliasNode()?.getText()??c.getName())===n)return s}}function et(e,t,r,n){let o=e.getExpression(),s=o.getText();if(bn.some(d=>s.startsWith(d))||s.startsWith("pipe("))return!0;for(let d of r)if(s.startsWith(`${d}.`))return!0;let{SyntaxKind:a}=I();if(o.getKind()!==a.PropertyAccessExpression)return!1;let i=o,c=Ki(i,t);if(!c)return!1;if($e(c))return!0;if(c.startsWith(".")){let d=Xe(t.getProject(),t.getFilePath(),c);if(d){let l=wn(d),f=i.getExpression().getText();for(let u of t.getImportDeclarations())if(u.getModuleSpecifierValue()===c){for(let p of u.getNamedImports())if((p.getAliasNode()?.getText()??p.getName())===f&&l.has(p.getName()))return!0}}if(Lt(t.getFilePath(),c,n))return!0}return!1}function Ot(e,t,r){if(bn.some(n=>e.startsWith(n))||e.startsWith("pipe("))return!0;if(t){for(let n of t)if(e.startsWith(`${n}.`))return!0}return r&&e.includes(".")?Wi(e,r):!1}var Bi=new Set(["createWorkflow","createSagaWorkflow","runSaga"]),qi=e=>Array.from(Bi).some(t=>e===t||e.endsWith(`.${t}`)),qr=e=>{let t=e.getExpression();if(t.getKind()!==I().SyntaxKind.PropertyAccessExpression)return!1;let r=t,n=e.getArguments();if(r.getName()!=="make"||n.length<3||!n[2])return!1;let o=n[2].getKind(),{SyntaxKind:s}=I();return o===s.ArrowFunction||o===s.FunctionExpression};function Hr(e,t){let r=e.replace(/\\/g,"/");return!!(r==="@effect/workflow"||r==="effect/workflow"||r.endsWith("/workflow")||r.includes("/workflow/")||r.endsWith("/Workflow.js")||r.endsWith("/Workflow.ts")||r.endsWith("/Activity.js")||r.endsWith("/Activity.ts")||r.startsWith(".")&&(r.endsWith("Workflow.js")||r.endsWith("Workflow.ts")||r.endsWith("Activity.js")||r.endsWith("Activity.ts")))}function ji(e,t,r){return e!=="Workflow"?!1:Hr(t,r)}function _i(e,t,r){return e!=="Activity"?!1:Hr(t,r)}function Ur(e,t){let{SyntaxKind:r}=I(),n=e.getArguments();if(n.length!==1||!n[0])return!1;let o=n[0];if(o.getKind()!==r.ObjectLiteralExpression)return!1;let a=o.getProperties(),i=new Set(t);for(let c of a)if(c.getKind()===r.PropertyAssignment){let d=c.getName();if(i.has(d))return!0}return!1}function zi(e,t,r){let{SyntaxKind:n}=I(),o=e.getExpression();if(o.getKind()!==n.PropertyAccessExpression)return!1;let s=o;if(s.getName()!=="make")return!1;let a=s.getExpression().getText(),i=t.get(a);return!i||!ji(a,i,r)?!1:Ur(e,["name","payload","idempotencyKey"])}function Hi(e,t,r){let{SyntaxKind:n}=I(),o=e.getExpression();if(o.getKind()!==n.PropertyAccessExpression)return!1;let s=o;if(s.getName()!=="make")return!1;let a=s.getExpression().getText(),i=t.get(a);return!i||!_i(a,i,r)?!1:Ur(e,["name","execute"])}var Vr=(e,t)=>{let r=e.getExpression();if(r.getKind()!==I().SyntaxKind.PropertyAccessExpression||r.getName()!=="run")return null;let o=e.getArguments();if(o.length<1||!o[0])return null;let s=o[0],{SyntaxKind:a}=I();if(s.getKind()===a.CallExpression){let l=s;return qr(l)?l.getArguments()[2]??null:null}if(s.getKind()!==a.Identifier)return null;let c=s.getText(),d=t.getDescendantsOfKind(a.VariableDeclaration);for(let l of d){if(l.getName()!==c)continue;let f=l.getInitializer();if(f?.getKind()===a.CallExpression&&qr(f))return f.getArguments()[2]??null}return null},Ui=e=>{let{SyntaxKind:t}=I(),r=e.getParent();for(;r;){if(r.getKind()===t.CallExpression){let o=r.getExpression().getText();if(o.includes(".gen")||o==="gen")return!0}r=r.getParent()}return!1},Vi=e=>{let{SyntaxKind:t}=I();return e.getFirstAncestorByKind(t.VariableStatement)?.getParent()?.getKind()===t.SourceFile},Gi=e=>{let{SyntaxKind:t}=I(),r=e.getInitializer();return r?r.getKind()===t.YieldExpression||r.getKind()===t.AwaitExpression&&r.getExpression().getKind()===t.YieldExpression:!1},jr=e=>{let{SyntaxKind:t}=I();if(e.getKind()===t.CallExpression)return e;if(e.getKind()===t.AwaitExpression){let r=e.getExpression();if(r.getKind()===t.CallExpression)return r}},_=(e,t)=>({discoveryConfidence:e,discoveryReason:t}),Ji=["Effect<","Layer<","Layer.Layer<","Stream<","Stream.Stream<","Channel<","Channel.Channel<","Sink<","Sink.Sink<","STM<","STM.STM<","Schedule<","Schedule.Schedule<"],Wt=e=>e!==void 0&&Ji.some(t=>e.includes(t)),_r={low:0,medium:1,high:2},In=e=>{let t=e.getExpression().getText();return t.includes(".runPromise")||t.includes(".runPromiseExit")||t.includes(".runSync")||t.includes(".runSyncExit")||t.includes(".runFork")||t.includes(".runCallback")||t.includes(".runMain")||t.includes("Runtime.runPromise")||t.includes("Runtime.runSync")||t.includes("Runtime.runFork")};function zr(e){let t=e.getBody?.();if(!t)return!1;let r=t.getText();return r.includes(".runMain")||r.includes(".runPromise")||r.includes(".runSync")||r.includes(".runFork")||r.includes("Runtime.runPromise")||r.includes("Runtime.runSync")||r.includes("NodeRuntime.runMain")||r.includes("BunRuntime.runMain")||r.includes("DenoRuntime.runMain")}function Yi(e,t){let r=e.getExpression();if(r.getKind()!==I().SyntaxKind.Identifier)return!1;let s=r.getSymbol()?.getValueDeclaration();if(!s)return!1;let a=s.getKind(),{SyntaxKind:i}=I();if(a===i.FunctionDeclaration||a===i.ArrowFunction||a===i.FunctionExpression)return zr(s);if(a===i.VariableDeclaration){let c=s.getInitializer();if(c&&(c.getKind()===i.ArrowFunction||c.getKind()===i.FunctionExpression))return zr(c)}return!1}function Qi(e){let t=e.getExpression();if(e.getArguments().length!==1)return!1;let{SyntaxKind:r}=I();if(t.getKind()!==r.CallExpression)return!1;let n=t;if(n.getArguments().length!==1)return!1;let o=n.getExpression().getText();return o.includes(".runPromise")||o.includes(".runSync")||o.includes(".runFork")||o.includes(".runCallback")||o.includes("Runtime.runPromise")||o.includes("Runtime.runSync")||o.includes("Runtime.runFork")}var An=(e,t)=>{let r=[],{SyntaxKind:n}=I(),o=new Set,s=new Set,a=Tn(e,t.knownEffectInternalsRoot),i=Br(e),c=new Map;for(let E of e.getImportDeclarations()){let y=E.getModuleSpecifierValue(),w=E.getDefaultImport();w&&c.set(w.getText(),y);let k=E.getNamespaceImport();k&&c.set(k.getText(),y);for(let b of E.getNamedImports())c.set(b.getAliasNode()?.getText()??b.getName(),y)}let d=E=>{let y=c.get(E);if(y){if(y.startsWith("effect")||y.startsWith("@effect/"))return _("high",`imported from ${y}`);if(Lt(e.getFilePath(),y,t.knownEffectInternalsRoot))return _("high","namespace import resolved under knownEffectInternalsRoot");if(y.startsWith(".")&&/(?:^|\/)Effect(?:\.[jt]sx?)?$/.test(y))return _("high",`relative Effect module namespace import (${y})`)}},l=E=>{let y=k=>{let b=k.getDescendantsOfKind(n.PropertyAccessExpression);for(let F of b){let L=F.getExpression().getText();if(a.has(L)&&!i.has(L))return d(L)?.discoveryConfidence==="high"?_("high",`function body uses ${L}.* from trusted Effect alias`):_("medium",`function body uses Effect-like alias ${L}.*`)}let M=k.getDescendantsOfKind(n.CallExpression);for(let F of M){let L=F.getExpression();if(L.getKind()===n.Identifier){let A=L.getText();if(a.has(A)&&!i.has(A))return d(A)?.discoveryConfidence==="high"?_("high",`function body calls trusted Effect import ${A}(...)`):_("medium",`function body calls Effect-like import ${A}(...)`)}}};if(E.getKind()===n.ArrowFunction||E.getKind()===n.FunctionExpression){let b=E.getBody();if(b.getKind()===n.Block){let M=y(b);if(M)return M}else{let M=y(b);if(M)return M}}let w=jr(E);if(w){let k=w.getExpression(),b=k.getText();if(k.getKind()===n.Identifier){let M=b;if(a.has(M)&&!i.has(M))return d(M)??_("high",`named import call (${M})`);if(M==="pipe")return _("medium","exact pipe() call detection")}if(k.getKind()===n.PropertyAccessExpression){let M=k,F=M.getExpression().getText();if(a.has(F)&&!i.has(F))return d(F)??_("medium",`Effect-like namespace prefix (${F}.*)`);if(M.getName()==="pipe")return _("medium","exact .pipe() call detection")}}if(E.getKind()===n.PropertyAccessExpression){let b=E.getExpression().getText();if(a.has(b)&&!i.has(b))return d(b)??_("medium",`Effect-like namespace property access (${b}.*)`)}if(E.getKind()===n.AwaitExpression){let k=E.getExpression();if(k.getKind()===n.CallExpression)return l(k)}return _("low","heuristic direct initializer match")},f=E=>{let w=(b=>b.getTypeNode?.()?.getText())(E);if(Wt(w))return _("high","explicit Effect-family type annotation");let k=E.getKind()===n.VariableDeclaration?E.getFirstAncestorByKind(n.VariableStatement)?.isExported()??!1:E.getKind()===n.PropertyDeclaration||E.getKind()===n.MethodDeclaration||E.getKind()===n.GetAccessor?E.getFirstAncestorByKind(n.ClassDeclaration)?.isExported()??!1:!1;if(E.getKind()===n.VariableDeclaration||E.getKind()===n.PropertyDeclaration){let b=E.getInitializer();if(b&&(b.getKind()===n.ArrowFunction||b.getKind()===n.FunctionExpression)){let F=b.getReturnTypeNode()?.getText();if(Wt(F))return _("high","function return type annotated as Effect-family");if(k&&w)return _("medium","explicit exported function API type signature")}if(b?.getKind()===n.CallExpression){let F=b.getTypeArguments().map(L=>L.getText()).join(" ");if(Wt(F))return _("high","call type arguments reference Effect-family types");if(k&&w)return _("medium","explicit exported call-based API type signature")}}if(E.getKind()===n.MethodDeclaration||E.getKind()===n.GetAccessor){let b=E.getReturnTypeNode?.()?.getText();if(Wt(b))return _("high","method/getter return type annotated as Effect-family");if(k&&w)return _("medium","explicit exported method/getter API type signature")}},u=E=>{let y=E.node,w=y.getKind();return w===n.CallExpression?!0:w===n.VariableDeclaration?y.getFirstAncestorByKind(n.VariableStatement)?.isExported()??!1:w===n.FunctionDeclaration||w===n.ClassDeclaration?y.isExported():w===n.PropertyDeclaration||w===n.MethodDeclaration||w===n.GetAccessor?y.getFirstAncestorByKind(n.ClassDeclaration)?.isExported()??!1:!0},p=E=>{for(let y of E){let w=y.getExpression();if(w&&te(w,a,i))return l(w)}return _("low","heuristic method return match")},g=e.getFilePath(),m=e.getDescendantsOfKind(n.VariableDeclaration);for(let E of m){let y=E.getInitializer();if(y?.getKind()===n.CallExpression&&qi(y.getExpression().getText())&&s.add(E.getName()),t.enableEffectWorkflow&&y?.getKind()===n.CallExpression){let w=y;(zi(w,c,g)||Hi(w,c,g))&&s.add(E.getName())}}let S=e.getDescendantsOfKind(n.CallExpression);for(let E of S){let y=E.getExpression(),w=y.getText(),k=E.getStart(),b=!1;if(y.getKind()===n.Identifier)b=s.has(w);else if(y.getKind()===n.PropertyAccessExpression){let F=y,L=F.getExpression().getText(),A=F.getName();if(b=s.has(L)&&A==="run",t.enableEffectWorkflow&&!b&&A==="run"&&E.getArguments().length===1&&!w.includes("runPromise")&&!w.includes("runSync")&&!w.includes("runFork")&&!w.includes("runCallback")&&!o.has(k)){let K=He(E)??`workflow-${r.length+1}`;r.push({name:K,node:E,type:"run",..._("low","workflow-like .run(...) shape heuristic")}),o.add(k);continue}}if(b&&!o.has(k)){let F=He(E)??`workflow-${r.length+1}`;r.push({name:F,node:E,type:"run",..._("medium","workflow builder invocation")}),o.add(k);continue}if(t.enableEffectWorkflow&&y.getKind()===n.PropertyAccessExpression){let F=y,L=F.getExpression().getText(),A=F.getName();if((A==="execute"||A==="executeEncoded")&&s.has(L)&&!o.has(k)){let q=He(E)??`${L}.${A}`;r.push({name:q,node:E,type:"workflow-execute",..._("medium","workflow/activity .execute entrypoint")}),o.add(k);continue}}if((w==="gen"||w.endsWith(".gen")&&et(E,e,a,t.knownEffectInternalsRoot))&&!o.has(k)){let F=He(E)??xr(E)??`program-${r.length+1}`;r.push({name:F,node:E,type:"generator",...w==="gen"?_("medium","unqualified gen(...) call"):_("high","Effect-like .gen(...) call")}),o.add(k)}let M=He(E);if(w.includes("pipe")&&Zi(E,a)&&!o.has(k)&&y.getKind()!==n.PropertyAccessExpression&&M!==void 0&&!Ui(E)&&(r.push({name:M,node:E,type:"pipe",..._("medium","exact pipe(...) call with Effect-like args")}),o.add(k)),(In(E)||Qi(E))&&!o.has(k)){let F=He(E)??`run-${r.length+1}`;r.push({name:F,node:E,type:"run",..._("high","recognized Runtime/Effect run* entrypoint")}),o.add(k)}}for(let E of m){if(!Vi(E)||Gi(E))continue;let y=E.getInitializer();if(y){let w=E.getName(),k=jr(y);if(k&&In(k)||y.getKind()===n.ObjectLiteralExpression)continue;te(y,a,i)&&!r.some(M=>M.name===w)&&r.push({name:w,node:E,type:"direct",...f(E)??l(y)})}}let h=e.getStatements();for(let E of h){if(E.getKind()!==n.ExpressionStatement)continue;let y=E.getExpression();if(y.getKind()!==n.CallExpression)continue;let w=y,k=w.getStart();if(o.has(k))continue;let b=w.getExpression(),M=b.getText();if(In(w)){let F=`run-${r.length+1}`;r.push({name:F,node:w,type:"run",..._("high","recognized top-level run* entrypoint")}),o.add(k);continue}if(M.endsWith(".pipe")||M==="pipe"){let F=w.getArguments(),L=F[F.length-1];if(!L)continue;let A=L.getText();if(A.includes(".runMain")||A.includes(".runPromise")||A.includes(".runSync")||A.includes(".runFork")){let q;b.getKind()===n.PropertyAccessExpression&&(q=b.getExpression().getText().split(".").pop());let Y=q&&!r.some(V=>V.name===q)?q:`entrypoint-${r.length+1}`;r.push({name:Y,node:w,type:"run",..._("medium","top-level pipe(...).run* terminator pattern")}),o.add(k)}}if(b.getKind()===n.Identifier&&w.getArguments().length>=1){let F=b.getText();Yi(w,e)&&!r.some(A=>A.name===F)&&(r.push({name:F,node:w,type:"run",..._("low","indirect run wrapper body heuristic")}),o.add(k))}}let N=["Data.TaggedError","Data.TaggedClass","Data.Class","Data.Error","Schema.Class","Schema.TaggedClass","Schema.TaggedError","Schema.TaggedRequest","Context.Tag","Context.Reference","Effect.Service"],x=e.getDescendantsOfKind(n.ClassDeclaration);for(let E of x){let y=E.getName();if(!y||r.some(b=>b.name===y))continue;E.getHeritageClauses().some(b=>{let M=b.getText();return N.some(F=>M.includes(F))})&&r.push({name:y,node:E,type:"class",..._("medium","known Data/Schema/Context class pattern")})}let C=x.filter(E=>{let y=E.getParent();return y===e||y?.getParent()===e});for(let E of C){let y=E.getName()??"Anonymous",w=E.getMembers(),k=w.filter(F=>F.getKind()===n.PropertyDeclaration);for(let F of k){let L=F.getInitializer();if(!L)continue;let A=F.getName(),K=`${y}.${A}`;r.some(q=>q.name===K)||te(L,a,i)&&r.push({name:K,node:F,type:"classProperty",...f(F)??l(L)})}let b=w.filter(F=>F.getKind()===n.MethodDeclaration);for(let F of b){let L=F.getName(),A=`${y}.${L}`;if(r.some(V=>V.name===A))continue;let K=F.getBody();if(!K)continue;let q=K.getDescendantsOfKind(n.ReturnStatement);q.some(V=>{let P=V.getExpression();return P?te(P,a,i):!1})&&r.push({name:A,node:F,type:"classMethod",...f(F)??p(q)})}let M=w.filter(F=>F.getKind()===n.GetAccessor);for(let F of M){let L=F.getName(),A=`${y}.${L}`;if(r.some(V=>V.name===A))continue;let K=F.getBody();if(!K)continue;let q=K.getDescendantsOfKind(n.ReturnStatement);q.some(V=>{let P=V.getExpression();return P?te(P,a,i):!1})&&r.push({name:A,node:F,type:"classMethod",...f(F)??p(q)})}}return r.filter(E=>{let y=t.minDiscoveryConfidence??"low",w=E.discoveryConfidence??"low";return!(_r[w]<_r[y]||t.onlyExportedPrograms&&!u(E))})},Zi=(e,t)=>e.getArguments().map(o=>o.getText()).some(o=>[...t].some(s=>o.includes(`${s}.`)));function Gr(e){let{SyntaxKind:t}=I(),r=[],n=e.getProject().getTypeChecker(),o=e.getDescendantsOfKind(t.ClassDeclaration);for(let s of o){let a=s.getName();if(!a)continue;let i=s.getExtends();if(!i)continue;let c=i.getText();if(!c.includes("Context.Tag")&&!c.includes("Effect.Service"))continue;let d=i.getTypeArguments();if(d.length<2){let f=i.getExpression();f&&"getTypeArguments"in f&&typeof f.getTypeArguments=="function"&&(d=f.getTypeArguments())}if(d.length<2)continue;let l=d[1];if(l)try{let f=n.getTypeAtLocation(l),u=[],p=[];for(let h of f.getProperties()){let N=h.getName();if(N.startsWith("_")||N==="constructor")continue;n.getTypeOfSymbolAtLocation(h,l).getCallSignatures().length>0?u.push(N):p.push(N)}let g=s.getText(),m=g.includes("Equal.symbol")||g.includes("[Equal")||g.includes("equal("),S=g.includes("Hash.symbol")||g.includes("[Hash")||g.includes("hash(");r.push({tagId:a,methods:u,properties:p,...m?{hasCustomEquality:m}:{},...S?{hasCustomHash:S}:{}})}catch{}}for(let s of o){let a=s.getName();if(!a)continue;let i=s.getExtends();if(!i)continue;let c=i.getText();if(!c.includes("Data.Class")&&!c.includes("Data.TaggedClass")||r.some(u=>u.tagId===a))continue;let d=s.getText(),l=d.includes("Equal.symbol")||d.includes("[Equal")||d.includes("equal("),f=d.includes("Hash.symbol")||d.includes("[Hash")||d.includes("hash(");(l||f)&&r.push({tagId:a,methods:[],properties:[],hasCustomEquality:l,hasCustomHash:f})}return r}import{Effect as ge,Option as Et}from"effect";import{Effect as J,Option as Xi}from"effect";var Bt=(e,t,r,n,o,s)=>J.gen(function*(){let{SyntaxKind:a}=I(),i=e.getArguments(),c=e.getExpression(),d=c.getKind()===a.PropertyAccessExpression&&c.getName()==="pipe",l=d?c.getExpression():i[0],f=d?i:i.slice(1);if(!l)return[];let u=Yr(l),p=u.getSourceFile(),g=p.getFilePath(),m=t.getProject();if(m.getSourceFile(g)){let E=m.getSourceFile(g);E&&(p=E)}else{let E=m.addSourceFileAtPath(g);E&&(p=E)}let S=yield*$(u,p,p.getFilePath(),n,o,s),h=[];for(let E of f)if(E){let y=yield*$(E,t,r,n,o,s);h.push(y)}let N;try{let E=t.getProject().getTypeChecker(),y=[],w=_e(l,E);w&&y.push(w);for(let k of f)if(k){let b=_e(k,E);b&&y.push(b)}y.length>0&&(N=y)}catch{}let x={id:T(),type:"pipe",initial:S,transformations:h,...N?{typeFlow:N}:{}};return[{...x,displayName:j(x),semanticRole:U(x)}]}),$=(e,t,r,n,o,s,a)=>J.gen(function*(){let{SyntaxKind:i}=I();if(e.getKind()===i.ArrowFunction||e.getKind()===i.FunctionExpression){let l=e.getBody();if(!l){let u={id:T(),type:"unknown",reason:"Function has no body",sourceCode:e.getText().slice(0,100),location:W(e,r,n.includeLocations??!1)};return s.unknownCount++,u}if(l.getKind()===i.Block){let g=l.getStatements().find(m=>m.getKind()===i.ReturnStatement)?.getExpression();if(g)return yield*$(g,t,r,n,o,s,a)}else return yield*$(l,t,r,n,o,s,a);let f={id:T(),type:"unknown",reason:"Function does not return an Effect expression",sourceCode:e.getText().slice(0,100),location:W(e,r,n.includeLocations??!1)};return s.unknownCount++,f}if(e.getKind()===i.CallExpression)return yield*Fn(e,t,r,n,o,s,a);if(e.getKind()===i.PropertyAccessExpression){let d=e.getText();if(d==="Fiber.roots"||d==="Fiber.getCurrentFiber"){let l=d==="Fiber.roots"?"roots":"getCurrentFiber";return{id:T(),type:"fiber",operation:l,isScoped:!1,isDaemon:!1,location:W(e,r,n.includeLocations??!1)}}if(Ot(d,Pe(t),t)){let l={id:T(),type:"effect",callee:d,location:W(e,r,n.includeLocations??!1)};return s.totalEffects++,l}}if(e.getKind()===i.Identifier){let d={id:T(),type:"effect",callee:e.getText(),location:W(e,r,n.includeLocations??!1)};return s.totalEffects++,d}if(e.getKind()===i.ObjectLiteralExpression){let d=e,l=new Set(["onNone","onSome","onFailure","onSuccess","onLeft","onRight"]),f=d.getProperties(),u=[],p=!1;for(let g of f){if(g.getKind()!==i.PropertyAssignment)continue;let m=g,S=m.getName();if(!l.has(S))continue;p=!0;let h=m.getInitializer();if(h){let N=yield*$(h,t,r,n,o,s,a);u.push(N)}}if(p&&u.length>0)return u.length===1?u[0]:{id:T(),type:"parallel",callee:"match-handlers",mode:"sequential",children:u,location:W(e,r,n.includeLocations??!1)}}let c={id:T(),type:"unknown",reason:"Could not determine effect type",sourceCode:e.getText().slice(0,100),location:W(e,r,n.includeLocations??!1)};return s.unknownCount++,c}),Fn=(e,t,r,n,o,s,a)=>J.gen(function*(){let{SyntaxKind:i}=I(),c=e.getExpression().getText(),d=kn(c,t),l=/([A-Za-z_$][\w$]*)$/.exec(d)?.[1]??d,f=W(e,r,n.includeLocations??!1);if(c==="pipe"&&e.getArguments().length>=1){let P=yield*Bt(e,t,r,n,o,s);if(P.length>0&&P[0])return P[0]}if(d==="Context.pick"||d==="Context.omit"){let P={id:T(),type:"effect",callee:d,description:"context",location:f};return s.totalEffects++,{...P,displayName:j(P),semanticRole:U(P)}}if(d.startsWith("Layer."))return yield*ra(e,d,t,r,n,o,s);if(d.startsWith("Stream."))return yield*oa(e,d,t,r,n,o,s);if(d.startsWith("Channel."))return yield*ia(e,d,t,r,n,o,s);if(c.startsWith("Sink."))return yield*ca(e,c,t,r,n,o,s);if(c.startsWith("Queue.")||c.startsWith("PubSub.")||c.startsWith("Deferred.")||c.startsWith("Semaphore.")||c.startsWith("Mailbox.")||c.startsWith("SubscriptionRef.")||c.startsWith("RateLimiter.")||c.startsWith("PartitionedSemaphore.")||c.startsWith("FiberHandle.")||c.startsWith("FiberSet.")||c.startsWith("FiberMap.")||c.startsWith("Cache.")||c.startsWith("ScopedCache.")||c.startsWith("RcRef.")||c.includes(".RcRef.")||c.startsWith("RcMap.")||c.includes(".RcMap.")||c.startsWith("Reloadable.")||c.includes(".Reloadable.")||c.includes("makeLatch")||c.includes("Latch."))return yield*la(e,c,t,r,n,o,s);if(gn.some(P=>c.includes(P)||c.startsWith(P)))return yield*da(e,c,t,r,n,o,s);if(En.some(P=>c.includes(P)))return yield*ua(e,c,t,r,n,o,s);if(c.includes(".all")||c==="all")return yield*pa(e,c,t,r,n,o,s);if(c.includes(".race")||c==="race")return yield*ga(e,c,t,r,n,o,s);if(un.some(P=>c.includes(P)))return yield*ma(e,c,t,r,n,o,s);if(c.includes(".retry"))return yield*ha(e,t,r,n,o,s);if(c.includes(".timeout"))return yield*ya(e,t,r,n,o,s);let p=new Set(["acquireRelease","acquireUseRelease","ensuring","addFinalizer","onExit","onError","parallelFinalizers","sequentialFinalizers","finalizersMask","using","withEarlyRelease"]),g=["acquireRelease","acquireUseRelease"],m=P=>p.has(P)||g.some(H=>P.startsWith(H));if(l==="pipe"&&e.getExpression().getKind()===i.PropertyAccessExpression){let H=e.getExpression().getExpression();if(H.getKind()===i.CallExpression){let fe=H,de=fe.getExpression().getText(),ee=/([A-Za-z_$][\w$]*)$/.exec(de)?.[1]??de;if(m(ee))return yield*Jr(fe,ee,t,r,n,o,s)}}if(m(l))return yield*Jr(e,l,t,r,n,o,s);if(fn.some(P=>c.includes(P)))return yield*Sa(e,c,t,r,n,o,s);if(pn.some(P=>c.includes(P)))return yield*xa(e,c,t,r,n,o,s);if(Nr(c))return yield*va(e,c,t,r,n,o,s);if(wr(c))return Ea(e,c,r,n);if(kr(c))return yield*ba(e,c,t,r,n,o,s);if(Ar(c))return Ca(e,c,r,n);if(Fr(c))return yield*Na(e,c,r,n);s.totalEffects++;let S,N=["Effect.sync","Effect.promise","Effect.async","Effect.asyncEffect","Effect.tryPromise","Effect.suspend"].some(P=>c.includes(P))&&e.getArguments().length>0&&e.getArguments()[0],x;if(N){let P=e.getArguments()[0],{SyntaxKind:H}=I();if(P.getKind()===H.ArrowFunction||P.getKind()===H.FunctionExpression){let de=P,ee=de.getBody(),Fe=[];if(ee){if(ee.getKind()===H.Block){let Re=ee;for(let Be of Re.getStatements())if(Be.getKind()===H.ReturnStatement){let be=Be.getExpression();if(be&&Ot(be.getText(),Pe(t),t)){let qe=yield*$(be,t,r,n,o,s,void 0);Fe.push(qe)}}else if(Be.getKind()===H.ExpressionStatement){let be=Be.getExpression();if(be.getKind()===H.CallExpression&&et(be,t,Pe(t),n.knownEffectInternalsRoot)){let qe=yield*$(be,t,r,n,o,s,void 0);Fe.push(qe)}}}else if(Ot(ee.getText(),Pe(t),t)){let Re=yield*$(ee,t,r,n,o,s,void 0);Fe.push(Re)}}if(Fe.length>0&&(S=Fe),c.includes("Effect.async")||c.includes("Effect.asyncEffect")){let Re=de.getParameters()[0]?.getName?.()??"resume",Be=0,be=ut=>{if(ut.getKind()===H.CallExpression){let ft=ut.getExpression();ft.getKind()===H.Identifier&&ft.getText()===Re&&Be++}ut.getChildren().forEach(be)};ee&&be(ee);let qe=!1;if(ee?.getKind()===H.Block){let ut=ee;for(let nn of ut.getStatements())if(nn.getKind()===H.ReturnStatement){let ft=nn.getExpression();if(ft){let ir=ft.getKind();if(ir===H.ArrowFunction||ir===H.FunctionExpression){qe=!0;break}}}}else ee&&(ee.getKind()===H.ArrowFunction||ee.getKind()===H.FunctionExpression)&&(qe=!0);x={resumeParamName:Re,resumeCallCount:Be,returnsCanceller:qe}}}}let C=ze(e),E=t.getProject().getTypeChecker(),y=_e(e,E),w=gt(e,E),k=ea(e,t),b,M=e.getExpression();if(M.getKind()===I().SyntaxKind.PropertyAccessExpression){let P=M,H=P.getExpression().getText(),fe=P.getName();if(a){let de=a.get(H);de&&(b={serviceId:de,methodName:fe})}!b&&w?.length===1&&w[0]&&(b={serviceId:w[0].serviceId,methodName:fe})}let F;if(c==="Effect.provide"||c.startsWith("Effect.")&&c.includes(".provide")&&!c.includes("provideService")){let P=e.getArguments(),H=(P.length>=2?P[1]:P[0])?.getText()??"";/Runtime\.|defaultRuntime|\.runSync|\.runPromise|\.runFork|\.runCallback/.test(H)||/^\s*runtime\s*$|^\s*rt\s*$/i.test(H.trim())?F="runtime":H.includes("Layer.")?F="layer":F="context"}let L;c.endsWith(".sync")||c.endsWith(".succeed")||c.endsWith(".fail")||c.endsWith(".try")||c.endsWith(".suspend")?L="sync":c.endsWith(".promise")?L="promise":c.endsWith(".async")||c.endsWith(".asyncEffect")?L="async":c.endsWith(".never")?L="never":c.endsWith(".void")?L="void":c.endsWith(".fromNullable")?L="fromNullable":c.endsWith(".fn")?L="fn":c.endsWith(".fnUntraced")&&(L="fnUntraced");let A,K=["currentConcurrency","currentLogLevel","currentScheduler","currentTracerEnabled","currentLogSpan","currentLogAnnotations","currentContext","currentRequestBatching","currentMaxOpsBeforeYield","currentSupervisor","currentMetricLabels","interruptedCause","unhandledLogLevel"];for(let P of K)if(c.includes(P)){A=P;break}let q;if(L==="fn"||L==="fnUntraced"){let P=e.getArguments();if(P.length>0){let H=P[0].getText(),fe=/^["'`](.+?)["'`]$/.exec(H);fe&&(q=fe[1])}}let Y={id:T(),type:"effect",callee:c,description:k?"service-call":Dr(c,Pe(t)),location:f,jsdocDescription:C,jsdocTags:Ze(e),typeSignature:y,requiredServices:w,serviceCall:k,serviceMethod:b,callbackBody:S,...x?{asyncCallback:x}:{},...F?{provideKind:F}:{},...L?{constructorKind:L}:{},...A?{fiberRefName:A}:{},...q?{tracedName:q}:{}};return{...Y,displayName:j(Y),semanticRole:U(Y)}}),ea=(e,t)=>{let{SyntaxKind:r}=I(),n=e.getExpression();if(n.getKind()!==r.PropertyAccessExpression)return;let o=n,s=o.getExpression(),a=o.getName(),i=s.getText(),c=i.split(".")[0]??i;if(!Cn.has(c))try{let d=s.getType(),l=d.getSymbol()??d.getAliasSymbol();if(!l)return;let f=l.getName();return!f||f==="__type"||f==="unknown"||f==="any"||Rr.has(f)?void 0:{serviceType:f,methodName:a,objectName:i}}catch{return}};function Kt(e){let t=e.getExpression().getText(),r=e.getSourceFile(),n=kn(t,r);return n.startsWith("Layer.")||n.startsWith("Effect.")||t==="pipe"||t.endsWith(".pipe")}function ta(e,t,r){let{SyntaxKind:n}=I(),o=e.getSourceFile(),s=o.getProject(),a=o.getFilePath(),c=t.getImportDeclaration().getModuleSpecifierValue();if(!c?.startsWith("."))return;let d=Xe(s,a,c);if(!d){let m=xt(a,c);if(m){let S=s.addSourceFileAtPath(m);S&&(d=S)}}if(!d)return;d=s.getSourceFile(d.getFilePath())??d;let l=m=>{if(m.getKind()===n.VariableDeclaration){let h=m.getInitializer();if(h?.getKind()===n.CallExpression&&r(h))return h}if(m.getKind()===n.VariableStatement){let S=m.getDeclarationList();for(let h of S.getDeclarations()){let N=h.getInitializer();if(N?.getKind()===n.CallExpression&&r(N))return N}}},f=t.getName(),u=d.getExportedDeclarations(),p=u.get(f)??[];for(let m of p){let S=l(m);if(S)return S}let g=t.getTargetName?.();if(g&&g!==f)for(let m of u.get(g)??[]){let S=l(m);if(S)return S}for(let[,m]of u)for(let S of m){let h=l(S);if(h)return h}}function na(e,t,r){let{SyntaxKind:n}=I(),o=e.getSourceFile(),s=o.getProject(),a=o.getFilePath(),i=t.getModuleSpecifierValue();if(!i?.startsWith("."))return;let c=Xe(s,a,i);if(!c){let l=xt(a,i);if(l){let f=s.addSourceFileAtPath(l);f&&(c=f)}}if(!c)return;c=s.getSourceFile(c.getFilePath())??c;let d=l=>{if(l.getKind()===n.VariableDeclaration){let u=l.getInitializer();if(u?.getKind()===n.CallExpression&&r(u))return u}if(l.getKind()===n.VariableStatement){let f=l.getDeclarationList();for(let u of f.getDeclarations()){let p=u.getInitializer();if(p?.getKind()===n.CallExpression&&r(p))return p}}};for(let l of c.getDefaultExportSymbol()?.getDeclarations()??[]){let f=d(l);if(f)return f}for(let l of c.getExportedDeclarations().get("default")??[]){let f=d(l);if(f)return f}}function Yr(e){let{SyntaxKind:t}=I();if(e.getKind()!==t.Identifier)return e;let r=e,n=r.getText(),o=r.getSymbol(),s=o?.getValueDeclaration(),a=s?.getKind()===t.ImportSpecifier?s:void 0;if(!a&&o){let i=o.getDeclarations().find(c=>c.getKind()===t.ImportSpecifier);i&&(a=i)}if(!a){let i=r.getSourceFile();for(let c of i.getImportDeclarations()){if(c.getDefaultImport()?.getText()===n){let f=na(r,c,Kt);if(f)return f}let l=c.getNamedImports().find(f=>f.getName()===n||f.getAliasNode()?.getText()===n);if(l){a=l;break}}}if(a){let i=ta(r,a,Kt);if(i)return i;o=o?.getImmediatelyAliasedSymbol()??o?.getAliasedSymbol(),s=o?.getValueDeclaration()}if(s?.getKind()===t.ExportSpecifier&&(o=o?.getImmediatelyAliasedSymbol()??o?.getAliasedSymbol(),s=o?.getValueDeclaration()),o&&s?.getKind()!==t.VariableDeclaration){for(let i of o.getDeclarations())if(i.getKind()===t.VariableDeclaration){let d=i.getInitializer();if(d?.getKind()===t.CallExpression&&Kt(d))return d}}if(s?.getKind()===t.VariableDeclaration){let c=s.getInitializer();if(c?.getKind()===t.CallExpression&&Kt(c))return c}return e}var ra=(e,t,r,n,o,s,a)=>J.gen(function*(){let i=e.getArguments(),c=[],{SyntaxKind:d}=I();if(i.length>0&&i[0]){let y=i[0];if(t.includes("mergeAll")&&y.getKind()===d.ArrayLiteralExpression){let k=y.getElements();for(let b of k){let M=yield*$(b,r,n,o,s,a);c.push(M)}}else for(let k of i){if(!k)continue;let b=Yr(k),M=b.getSourceFile(),F=yield*$(b,M,M.getFilePath(),o,s,a);c.push(F)}}let l=t.includes("merge")||t.includes("mergeAll"),f;t.includes("fresh")?f="fresh":t.includes("memoize")?f="memoized":t.includes("scoped")?f="scoped":f="default";let u=[],p=y=>{if(y.getKind()===d.Identifier)return y.getText();if(y.getKind()===d.PropertyAccessExpression){let w=y,k=w.getExpression();return k.getKind()===d.Identifier?k.getText():w.getText().split(".")[0]}};if((t.includes("succeed")||t.includes("sync")||t.includes("effect")||t.includes("scoped")||t.includes("scopedDiscard")||t.includes("effectDiscard"))&&i.length>0&&i[0]){let y=p(i[0]);y&&u.push(y)}let g=t.includes("provide")&&!t.includes("provideService"),m=new Set;if(g&&i.length>=1&&i[0]){let y=p(i[0]);y&&m.add(y)}if(g&&i.length>=2&&i[1]){let y=p(i[1]);y&&m.add(y);let w=p(i[0]);w&&u.push(w)}if(t.includes("provideService")&&i.length>0&&i[0]){let y=p(i[0]);y&&u.push(y)}let S=y=>{if(y.type==="effect"){let k=y;for(let M of k.requiredServices??[])m.add(M.serviceId);let b=k.callee??"";(/^[A-Z][A-Za-z0-9_]*(Service|Tag)$/.test(b)||b.endsWith(".Tag"))&&m.add(b)}else if(y.type==="layer"){let k=y;for(let b of k.requires??[])m.add(b)}Xi.getOrElse(v(y),()=>[]).forEach(S)};if(c.forEach(S),m.size===0)try{let y=ln(e);y?.requiredType&&y.requiredType!=="never"&&Mr(y.requiredType).forEach(k=>m.add(k))}catch{}let h=t.replace(/^Layer\./,"").replace(/^[a-zA-Z]+\./,""),x=new Set(["catchAll","catchAllCause","orDie","orElse","retry","tap","mapError","mapErrorCause","build","launch","toRuntime","passthrough","project","flatMap","flatten","annotateLogs","annotateSpans","setConfigProvider","setClock","setTracer","locally","withSpan","withLogger","withTracer","withClock","mock","suspend","unwrapEffect","unwrapScoped"]).has(h)?`Layer.${h}`:void 0,C=t.includes("MemoMap")||c.some(y=>y.type==="layer"&&y.isMemoMap===!0),E={id:T(),type:"layer",name:x,operations:c,isMerged:l,provides:u.length>0?u:void 0,requires:m.size>0?Array.from(m).sort():void 0,lifecycle:f,...C?{isMemoMap:!0}:{},location:W(e,n,o.includeLocations??!1)};return{...E,displayName:j(E),semanticRole:U(E)}});function oa(e,t,r,n,o,s,a){return J.gen(function*(){let i=e.getArguments(),c;i.length>0&&i[0]?c=yield*$(i[0],r,n,o,s,a):c={id:T(),type:"unknown",reason:"Stream source not determined"};let d=t.replace(/^Stream\./,"")||"unknown",l;t.startsWith("Stream.")&&(d==="fromIterable"||d==="fromChunk"||d==="fromChunkQueue"?l="fromIterable":d==="fromArray"?l="fromArray":d==="fromQueue"||d==="fromChunkQueue"?l="fromQueue":d==="fromPubSub"||d==="fromChunkPubSub"?l="fromPubSub":d==="fromEffect"||d==="unwrap"||d==="unwrapScoped"?l="fromEffect":d==="fromAsyncIterable"?l="fromAsyncIterable":d==="fromReadableStream"||d==="fromReadableStreamByob"?l="fromReadableStream":d==="fromEventListener"?l="fromEventListener":d==="fromSchedule"?l="fromSchedule":d==="range"?l="range":d==="tick"?l="tick":d==="iterate"||d==="iterateEffect"?l="iterate":d==="unfold"||d==="unfoldEffect"||d==="unfoldChunk"||d==="unfoldChunkEffect"?l="unfold":d==="make"?l="make":d==="empty"?l="empty":d==="never"?l="never":d==="succeed"||d==="sync"?l="succeed":(d==="fail"||d==="failSync"||d==="failCause"||d==="failCauseSync")&&(l="fail"));let f=b=>l!==void 0?"constructor":b.startsWith("run")?"sink":b==="toQueue"||b==="toPubSub"||b==="toReadableStream"||b==="toAsyncIterable"||b==="toChannel"?"conversion":b.includes("pipeThroughChannel")||b.includes("Channel")||b.includes("channel")||b.includes("duplex")?"channel":b.includes("grouped")||b.includes("sliding")||b.includes("groupBy")||b.includes("aggregate")||b.includes("window")?"windowing":b.includes("broadcast")||b==="share"?"broadcasting":b.includes("haltAfter")||b.includes("haltWhen")||b.includes("interruptAfter")?"halting":b.includes("decodeText")||b.includes("encodeText")||b.includes("splitLines")?"text":b.includes("merge")||b==="concat"||b.includes("interleave")||b.includes("zip")?"merge":b.includes("buffer")||b.includes("debounce")||b.includes("throttle")?"backpressure":b.includes("catchAll")||b.includes("catchTag")||b.includes("orElse")||b.includes("orDie")||b.includes("retry")?"error":b.includes("filter")||b.includes("take")||b.includes("drop")||b.includes("head")||b==="first"||b==="last"?"filter":b.includes("acquireRelease")||b.includes("scoped")||b.includes("ensuring")||b.includes("onDone")||b.includes("onError")?"resource":b.includes("provide")||b.includes("withSpan")||b.includes("annotate")?"context":b.includes("map")||b.includes("tap")||b.includes("flatMap")||b.includes("mapChunk")||b.includes("scan")||b.includes("transduce")?"transform":"other",u=d.includes("Effect")||d.startsWith("run")||d.includes("tap"),p=f(d),g=p==="filter"?"fewer":p==="merge"||p==="broadcasting"?"more":p==="halting"||p==="sink"||p==="windowing"?"fewer":"unknown",m,S;(d==="grouped"||d==="groupedWithin"||d.includes("sliding")||d.includes("Sliding"))&&i.length>0&&i[0]&&(m=yt(i[0]),(d.includes("sliding")||d.includes("Sliding"))&&i.length>1&&i[1]&&(S=yt(i[1])));let N={operation:d,isEffectful:u,estimatedCardinality:g,category:p,...m!==void 0?{windowSize:m}:{},...S!==void 0?{stride:S}:{}},x;d.startsWith("run")&&(x=d);let C;d.includes("buffer")?C="buffer":d.includes("drop")||d.includes("Drop")?C="drop":(d.includes("sliding")||d.includes("Sliding"))&&(C="sliding");let E=c,y=[N],w=l;if(c.type==="stream"){let b=c;y=[...b.pipeline,N],E=b.source,!w&&b.constructorType&&(w=b.constructorType),!x&&b.sink&&(x=b.sink),!C&&b.backpressureStrategy&&(C=b.backpressureStrategy)}let k={id:T(),type:"stream",source:E,pipeline:y,sink:x,backpressureStrategy:C,constructorType:w,location:W(e,n,o.includeLocations??!1)};return{...k,displayName:j(k),semanticRole:U(k)}})}function sa(e){return e==="fromReadableStream"||e==="fromWritableStream"||e==="fromDuplexStream"||e==="make"||e==="succeed"||e==="fail"||e==="empty"||e==="never"?"constructor":e.includes("map")||e.includes("flatMap")||e.includes("filter")||e.includes("concat")||e.includes("zip")?"transform":e.includes("pipe")||e==="pipeTo"||e==="pipeThrough"?"pipe":"other"}function ia(e,t,r,n,o,s,a){return J.gen(function*(){let i=e.getArguments(),c;i.length>0&&i[0]&&(c=yield*$(i[0],r,n,o,s,a));let d=t.replace(/^Channel\./,"")||"unknown",l=[{operation:d,category:sa(d)}];if(c?.type==="channel"){let u=c;l.unshift(...u.pipeline),c=u.source}let f={id:T(),type:"channel",source:c,pipeline:l,location:W(e,n,o.includeLocations??!1)};return{...f,displayName:j(f),semanticRole:U(f)}})}function aa(e){return e==="forEach"||e==="forEachWhile"||e==="run"||e==="runDrain"||e==="runFor"||e==="make"||e==="fromEffect"||e==="fromQueue"?"constructor":e.includes("map")||e.includes("contramap")||e.includes("filter")||e.includes("zip")?"transform":"other"}function ca(e,t,r,n,o,s,a){return J.gen(function*(){let i=e.getArguments(),c;i.length>0&&i[0]&&(c=yield*$(i[0],r,n,o,s,a));let d=t.replace(/^Sink\./,"")||"unknown",l=[{operation:d,category:aa(d)}];if(c?.type==="sink"){let u=c;l.unshift(...u.pipeline),c=u.source}let f={id:T(),type:"sink",source:c,pipeline:l,location:W(e,n,o.includeLocations??!1)};return{...f,displayName:j(f),semanticRole:U(f)}})}function la(e,t,r,n,o,s,a){let{SyntaxKind:i}=I(),c="queue",d="create",l,f,u;t.startsWith("Queue.")?(c="queue",t.includes("bounded")?l="bounded":t.includes("unbounded")?l="unbounded":t.includes("sliding")?l="sliding":t.includes("dropping")&&(l="dropping"),t.includes("offer")||t.includes("offerAll")?d="offer":t.includes("take")||t.includes("takeAll")||t.includes("poll")?d="take":d="create"):t.startsWith("PubSub.")?(c="pubsub",t.includes("bounded")?l="bounded":t.includes("unbounded")&&(l="unbounded"),t.includes("publish")?d="publish":t.includes("subscribe")?d="subscribe":d="create"):t.startsWith("Deferred.")?(c="deferred",t.includes("succeed")?d="succeed":t.includes("fail")?d="fail":t.includes("await")?d="await":d="create"):t.startsWith("Semaphore.")?(c="semaphore",t.includes("withPermit")?d="withPermit":t.includes("take")?d="take":t.includes("release")?d="release":t.includes("available")?d="available":d="create"):t.startsWith("Mailbox.")?(c="mailbox",t.includes("offer")?d="offer":t.includes("takeAll")?d="takeAll":t.includes("take")?d="take":t.includes("end")?d="end":t.includes("toStream")?d="toStream":d="create"):t.startsWith("SubscriptionRef.")?(c="subscriptionRef",t.includes("changes")?d="changes":t.includes("get")?d="get":t.includes("set")?d="set":t.includes("update")?d="update":d="create"):t.includes("makeLatch")||t.includes("Latch.")?(c="latch",t.includes("open")?d="open":t.includes("close")?d="close":t.includes("await")||t.includes("whenOpen")?d="await":d="create"):t.startsWith("FiberHandle.")?(c="fiberHandle",t.includes("run")?d="run":t.includes("await")?d="await":d="create"):t.startsWith("FiberSet.")?(c="fiberSet",t.includes("run")?d="run":t.includes("join")?d="await":d="create"):t.startsWith("FiberMap.")?(c="fiberMap",t.includes("run")?d="run":t.includes("join")?d="await":d="create"):t.startsWith("RateLimiter.")?(c="rateLimiter",t.includes("withCost")?d="withPermit":d="create"):t.startsWith("ScopedCache.")?(c="scopedCache",t.includes("make")||t.includes("Make")?d="create":t.includes("get")&&!t.includes("getOrElse")||t.includes("getOrElse")?d="get":t.includes("set")||t.includes("Set")?d="set":t.includes("invalidate")?d="invalidate":t.includes("contains")?d="contains":d="create"):t.startsWith("Cache.")?(c="cache",t.includes("make")||t.includes("Make")?d="create":t.includes("get")&&!t.includes("getOrElse")||t.includes("getOrElse")?d="get":t.includes("set")||t.includes("Set")?d="set":t.includes("invalidate")?d="invalidate":t.includes("contains")?d="contains":d="create"):t.startsWith("Reloadable.")||t.includes(".Reloadable.")?(c="reloadable",t.includes("make")||t.includes("Make")?d="create":t.includes("get")&&!t.includes("reload")?d="get":t.includes("reload")?d="reload":d="create"):t.startsWith("RcMap.")||t.includes(".RcMap.")?(c="rcMap",t.includes("make")||t.includes("Make")?d="create":t.includes("get")?d="get":t.includes("set")||t.includes("Set")?d="set":t.includes("update")?d="update":d="create"):(t.startsWith("RcRef.")||t.includes(".RcRef."))&&(c="rcRef",t.includes("make")||t.includes("Make")?d="create":t.includes("get")?d="get":t.includes("set")||t.includes("Set")?d="set":t.includes("update")?d="update":d="create");let p=e.getArguments();if(p.length>0&&l==="bounded"){let S=p[0];S?.getKind()===i.NumericLiteral&&(f=Number.parseInt(S.getText(),10))}c==="semaphore"&&(d==="take"||d==="release")&&p.length>0&&p[0]&&(u=yt(p[0]));let g;if(c==="fiberHandle"&&d==="run")for(let S of p){let h=S.getText();h.includes("onlyIfMissing")&&(g={onlyIfMissing:h.includes("true")})}if(c==="mailbox"&&d==="toStream"||c==="subscriptionRef"&&d==="changes"){let S=c==="mailbox"?"fromMailbox":"fromSubscriptionRef",h={id:T(),type:"concurrency-primitive",primitive:c,operation:d,location:W(e,n,o.includeLocations??!1)},N={id:T(),type:"stream",source:{...h,displayName:j(h),semanticRole:U(h)},pipeline:[],constructorType:S,location:W(e,n,o.includeLocations??!1)};return J.succeed({...N,displayName:j(N),semanticRole:U(N)})}let m={id:T(),type:"concurrency-primitive",primitive:c,operation:d,strategy:l,capacity:f,...u!==void 0?{permitCount:u}:{},...g?{lifecycleOptions:g}:{},location:W(e,n,o.includeLocations??!1)};return J.succeed({...m,displayName:j(m),semanticRole:U(m)})}function da(e,t,r,n,o,s,a){return J.gen(function*(){let i=e.getArguments(),c="fork",d=!1,l=!1,f;t.startsWith("Fiber.")?t.includes("awaitAll")?c="awaitAll":t.includes("join")?c="join":t.includes("await")?c="await":t.includes("interruptFork")?c="interruptFork":t.includes("interrupt")?c="interrupt":t.includes("poll")?c="poll":t.includes("status")?c="status":t.includes("all")?c="all":t.includes("children")?c="children":t.includes("dump")?c="dump":t.includes("scoped")?(c="scoped",d=!0):t.includes("inheritAll")?c="inheritAll":t.includes("mapFiber")?c="mapFiber":t.includes("mapEffect")?c="mapEffect":t.includes("map")?c="map":t.includes("roots")?c="roots":t.includes("getCurrentFiber")&&(c="getCurrentFiber"):t.includes("forkWithErrorHandler")?c="forkWithErrorHandler":t.includes("forkAll")?c="forkAll":t.includes("forkIn")?c="forkIn":t.includes("fork")&&(t.includes("forkDaemon")?(c="forkDaemon",l=!0):t.includes("forkScoped")?(c="forkScoped",d=!0):c="fork"),(c==="fork"||c==="forkScoped"||c==="forkDaemon"||c==="forkAll"||c==="forkIn"||c==="forkWithErrorHandler")&&i.length>0&&i[0]&&(f=yield*$(i[0],r,n,o,s,a));let u;if(d)u="safe";else{let g=e.getParent();for(;g;){let m=g.getText?.();if(m&&(m.includes("Effect.scoped")||m.includes("Scope.make"))){u="safe";break}if(g=g.getParent(),g&&g===r)break}}let p={id:T(),type:"fiber",operation:c,fiberSource:f,isScoped:d,isDaemon:l,...u?{scopeContext:u}:{},location:W(e,n,o.includeLocations??!1)};return{...p,displayName:j(p),semanticRole:U(p)}})}function ua(e,t,r,n,o,s,a){return J.gen(function*(){let i=e.getArguments(),{SyntaxKind:c}=I(),d;t.includes("uninterruptibleMask")?d="uninterruptibleMask":t.includes("interruptibleMask")?d="interruptibleMask":t.includes("uninterruptible")?d="uninterruptible":t.includes("interruptible")?d="interruptible":t.includes("onInterrupt")?d="onInterrupt":t.includes("disconnect")?d="disconnect":t.includes("allowInterrupt")?d="allowInterrupt":t.includes("interruptWith")?d="interruptWith":d="interrupt";let l,f,u=e.getExpression();u.getKind()===c.PropertyAccessExpression?(l=yield*$(u.getExpression(),r,n,o,s,a),i.length>0&&i[0]&&(f=yield*$(i[0],r,n,o,s,a))):i.length>0&&i[0]&&(l=yield*$(i[0],r,n,o,s,a),i.length>1&&i[1]&&(f=yield*$(i[1],r,n,o,s,a))),a.interruptionCount++;let p={id:T(),type:"interruption",interruptionType:d,source:l,handler:f,location:W(e,n,o.includeLocations??!1)};return{...p,displayName:j(p),semanticRole:U(p)}})}function fa(e){let{SyntaxKind:t}=I(),r,n,o;for(let s of e.getProperties()){if(s.getKind()!==t.PropertyAssignment)continue;let a=s.getNameNode().getText(),i=s.getInitializer();if(!i)continue;let c=i.getText();if(a==="concurrency")if(c==='"unbounded"'||c==="'unbounded'")r="unbounded";else if(c==='"sequential"'||c==="'sequential'")r="sequential";else if(c==='"inherit"'||c==="'inherit'")r="sequential";else{let d=Number.parseInt(c,10);!Number.isNaN(d)&&d>=0&&(r=d)}else a==="batching"&&(c==="true"||c==="false")?n=c==="true":a==="discard"&&(c==="true"||c==="false")&&(o=c==="true")}return{concurrency:r,batching:n,discard:o}}var pa=(e,t,r,n,o,s,a)=>J.gen(function*(){let i=e.getArguments(),c=[],{SyntaxKind:d}=I();if(i.length>0&&i[0]){let S=i[0];if(S.getKind()===d.ArrayLiteralExpression){let h=S.getElements();for(let N of h){let x=yield*$(N,r,n,o,s,a);c.push(x)}}else if(S.getKind()===d.ObjectLiteralExpression){let h=S.getProperties();for(let N of h)if(N.getKind()===d.PropertyAssignment){let x=N.getInitializer();if(x){let C=yield*$(x,r,n,o,s,a);c.push(C)}}}}let l,f,u;if(i.length>1&&i[1]?.getKind()===d.ObjectLiteralExpression){let S=fa(i[1]);l=S.concurrency,f=S.batching,u=S.discard}let p=t.includes("Par")?"parallel":"sequential";l===void 0&&(l=p==="parallel"?"unbounded":"sequential"),a.parallelCount++;let g=c.map(S=>j(S)),m={id:T(),type:"parallel",callee:t,mode:p,children:c,concurrency:l,batching:f,discard:u,branchLabels:g,location:W(e,n,o.includeLocations??!1)};return{...m,displayName:j(m),semanticRole:U(m)}}),ga=(e,t,r,n,o,s,a)=>J.gen(function*(){let i=e.getArguments(),c=[];for(let f of i)if(f){let u=yield*$(f,r,n,o,s,a);c.push(u)}a.raceCount++;let d=c.map(f=>j(f)),l={id:T(),type:"race",callee:t,children:c,raceLabels:d,location:W(e,n,o.includeLocations??!1)};return{...l,displayName:j(l),semanticRole:U(l)}}),ma=(e,t,r,n,o,s,a)=>J.gen(function*(){let i=e.getArguments(),c;t.includes("catchAllCause")?c="catchAllCause":t.includes("catchSomeCause")?c="catchSomeCause":t.includes("catchSomeDefect")?c="catchSomeDefect":t.includes("catchAllDefect")?c="catchAllDefect":t.includes("catchTags")?c="catchTags":t.includes("catchIf")?c="catchIf":t.includes("catchSome")?c="catchSome":t.includes("catchTag")?c="catchTag":t.includes("catchAll")?c="catchAll":t.includes("orElseFail")?c="orElseFail":t.includes("orElseSucceed")?c="orElseSucceed":t.includes("orElse")?c="orElse":t.includes("orDieWith")?c="orDieWith":t.includes("orDie")?c="orDie":t.includes("flip")?c="flip":t.includes("mapErrorCause")?c="mapErrorCause":t.includes("mapBoth")?c="mapBoth":t.includes("mapError")?c="mapError":t.includes("unsandbox")?c="unsandbox":t.includes("sandbox")?c="sandbox":t.includes("parallelErrors")?c="parallelErrors":t.includes("filterOrDieMessage")?c="filterOrDieMessage":t.includes("filterOrDie")?c="filterOrDie":t.includes("filterOrElse")?c="filterOrElse":t.includes("filterOrFail")?c="filterOrFail":t.includes("matchCauseEffect")?c="matchCauseEffect":t.includes("matchCause")?c="matchCause":t.includes("matchEffect")?c="matchEffect":t.includes("match")?c="match":t.includes("firstSuccessOf")?c="firstSuccessOf":t.includes("ignoreLogged")?c="ignoreLogged":t.includes("ignore")?c="ignore":t.includes("eventually")?c="eventually":c="catchAll";let d,l,f=e.getExpression();if(f.getKind()===I().SyntaxKind.PropertyAccessExpression){let S=f.getExpression();d=yield*$(S,r,n,o,s,a),i.length>0&&i[0]&&(l=yield*$(i[0],r,n,o,s,a))}else i.length>0&&i[0]?d=yield*$(i[0],r,n,o,s,a):d={id:T(),type:"unknown",reason:"Could not determine source effect"},i.length>1&&i[1]&&(l=yield*$(i[1],r,n,o,s,a));a.errorHandlerCount++;let u,p;if(c==="catchTag"){let m=i[0];m?.getKind()===I().SyntaxKind.StringLiteral&&(u=m.getLiteralValue())}else if(c==="catchTags"){let m=[...i].find(S=>S?.getKind()===I().SyntaxKind.ObjectLiteralExpression);m&&(p=m.getProperties().filter(h=>h.getKind()===I().SyntaxKind.PropertyAssignment||h.getKind()===I().SyntaxKind.MethodDeclaration).map(h=>(h.getKind()===I().SyntaxKind.PropertyAssignment,h.getName())))}let g={id:T(),type:"error-handler",handlerType:c,source:d,handler:l,errorTag:u,errorTags:p,errorEdgeLabel:u?`on ${u}`:p&&p.length>0?`on ${p.join(" | ")}`:"on error",location:W(e,n,o.includeLocations??!1)};return{...g,displayName:j(g),semanticRole:U(g)}}),ha=(e,t,r,n,o,s)=>J.gen(function*(){let a=e.getArguments(),i,c,d,l,f=e.getExpression();if(f.getKind()===I().SyntaxKind.PropertyAccessExpression){let m=f.getExpression();i=yield*$(m,t,r,n,o,s),a.length>0&&a[0]&&(c=a[0].getText(),d=yield*$(a[0],t,r,n,o,s)),l=f.getText().includes("retryOrElse")}else a.length>0&&a[0]?i=yield*$(a[0],t,r,n,o,s):i={id:T(),type:"unknown",reason:"Could not determine source effect"},a.length>1&&a[1]&&(c=a[1].getText(),d=yield*$(a[1],t,r,n,o,s)),l=a.length>2;s.retryCount++;let u=c?Qr(c):void 0,p={id:T(),type:"retry",source:i,schedule:c,...d!==void 0?{scheduleNode:d}:{},hasFallback:l,scheduleInfo:u,retryEdgeLabel:c?`retry: ${c}`:"retry",location:W(e,r,n.includeLocations??!1)};return{...p,displayName:j(p),semanticRole:U(p)}});function Qr(e){let t=e.replace(/\s+/g," "),r="custom";t.includes("Schedule.exponential")||t.includes("exponential(")?r="exponential":t.includes("Schedule.fibonacci")||t.includes("fibonacci(")?r="fibonacci":t.includes("Schedule.spaced")||t.includes("spaced(")?r="spaced":t.includes("Schedule.fixed")||t.includes("fixed(")?r="fixed":t.includes("Schedule.linear")||t.includes("linear(")?r="linear":t.includes("Schedule.cron")||t.includes("cron(")?r="cron":t.includes("Schedule.windowed")||t.includes("windowed(")?r="windowed":t.includes("Schedule.duration")||t.includes("duration(")?r="duration":t.includes("Schedule.elapsed")||t.includes("elapsed(")?r="elapsed":t.includes("Schedule.delays")||t.includes("delays(")?r="delays":t.includes("Schedule.once")||t.includes("once(")?r="once":t.includes("Schedule.stop")||t.includes("stop(")?r="stop":(t.includes("Schedule.count")||t.includes("count("))&&(r="count");let n,o=/recurs\s*\(\s*(\d+)\s*\)/.exec(t);o&&(n=Number.parseInt(o[1],10));let s=/recurUpTo\s*\(\s*(\d+)\s*\)/.exec(t);s?n=Number.parseInt(s[1],10):(t.includes("forever")||t.includes("Schedule.forever"))&&(n="unlimited");let a=t.includes("jittered")||t.includes("Schedule.jittered"),i=[];return t.includes("whileInput")&&i.push("whileInput"),t.includes("whileOutput")&&i.push("whileOutput"),t.includes("untilInput")&&i.push("untilInput"),t.includes("untilOutput")&&i.push("untilOutput"),t.includes("recurUntil")&&i.push("recurUntil"),t.includes("recurWhile")&&i.push("recurWhile"),t.includes("andThen")&&i.push("andThen"),t.includes("intersect")&&i.push("intersect"),t.includes("union")&&i.push("union"),t.includes("compose")&&i.push("compose"),t.includes("zipWith")&&i.push("zipWith"),t.includes("addDelay")&&i.push("addDelay"),t.includes("modifyDelay")&&i.push("modifyDelay"),t.includes("check")&&i.push("check"),t.includes("resetAfter")&&i.push("resetAfter"),t.includes("resetWhen")&&i.push("resetWhen"),t.includes("ensure")&&i.push("ensure"),t.includes("driver")&&i.push("driver"),t.includes("mapInput")&&i.push("mapInput"),{baseStrategy:r,maxRetries:n,jittered:a,conditions:i}}var ya=(e,t,r,n,o,s)=>J.gen(function*(){let a=e.getArguments(),i,c,d,l=e.getExpression();if(l.getKind()===I().SyntaxKind.PropertyAccessExpression){let p=l.getExpression();i=yield*$(p,t,r,n,o,s),a.length>0&&a[0]&&(c=Pt(a[0]));let g=Pt(l);d=g.includes("timeoutFail")||g.includes("timeoutTo")}else a.length>0&&a[0]?i=yield*$(a[0],t,r,n,o,s):i={id:T(),type:"unknown",reason:"Could not determine source effect"},a.length>1&&a[1]&&(c=Pt(a[1])),d=a.length>2;s.timeoutCount++;let f={id:T(),type:"timeout",source:i,duration:c,hasFallback:d,location:W(e,r,n.includeLocations??!1)};return{...f,displayName:j(f),semanticRole:U(f)}}),Jr=(e,t,r,n,o,s,a)=>J.gen(function*(){let i=e.getArguments(),c=/([A-Za-z_$][\w$]*)$/.exec(t)?.[1]??t,d,l,f;if(c.startsWith("acquireUseRelease"))i.length>=3&&i[0]&&i[2]?(d=yield*$(i[0],r,n,o,s,a),l=yield*$(i[2],r,n,o,s,a),i[1]&&(f=yield*$(i[1],r,n,o,s,a))):(d={id:T(),type:"unknown",reason:"Missing acquire"},l={id:T(),type:"unknown",reason:"Missing release"});else if(c.startsWith("acquireRelease"))i.length>=2&&i[0]&&i[1]?(d=yield*$(i[0],r,n,o,s,a),l=yield*$(i[1],r,n,o,s,a)):(d={id:T(),type:"unknown",reason:"Missing acquire"},l={id:T(),type:"unknown",reason:"Missing release"});else if(c==="addFinalizer"||c==="onExit"||c==="onError"||c==="parallelFinalizers"||c==="sequentialFinalizers"||c==="finalizersMask"||c==="using"||c==="withEarlyRelease"){let p=e.getExpression();p.getKind()===I().SyntaxKind.PropertyAccessExpression?d=yield*$(p.getExpression(),r,n,o,s,a):d={id:T(),type:"unknown",reason:"Scoped acquire"},l=i.length>0&&i[0]?yield*$(i[0],r,n,o,s,a):{id:T(),type:"unknown",reason:"Missing finalizer"}}else if(c==="ensuring"){let p=e.getExpression();if(p.getKind()===I().SyntaxKind.PropertyAccessExpression){let m=p.getExpression();d=yield*$(m,r,n,o,s,a),l=i.length>0&&i[0]?yield*$(i[0],r,n,o,s,a):{id:T(),type:"unknown",reason:"Missing cleanup"}}else d=i.length>0&&i[0]?yield*$(i[0],r,n,o,s,a):{id:T(),type:"unknown",reason:"Missing effect"},l=i.length>1&&i[1]?yield*$(i[1],r,n,o,s,a):{id:T(),type:"unknown",reason:"Missing cleanup"}}else d={id:T(),type:"unknown",reason:"Unknown resource pattern"},l={id:T(),type:"unknown",reason:"Unknown resource pattern"};a.resourceCount++;let u={id:T(),type:"resource",acquire:d,release:l,use:f,location:W(e,n,o.includeLocations??!1)};return{...u,displayName:j(u),semanticRole:U(u)}}),Sa=(e,t,r,n,o,s,a)=>J.gen(function*(){let i=e.getArguments(),c;t.includes(".if")||t==="if"?c="if":t.includes("whenEffect")?c="whenEffect":t.includes("whenFiberRef")?c="whenFiberRef":t.includes("whenRef")?c="whenRef":t.includes(".when")||t==="when"?c="when":t.includes("unlessEffect")?c="unlessEffect":t.includes(".unless")||t==="unless"?c="unless":t.includes(".option")||t==="option"?c="option":t.includes(".either")||t==="either"?c="either":t.includes(".exit")||t==="exit"?c="exit":t.includes("liftPredicate")?c="liftPredicate":c="unless";let d="<dynamic>",l,f;if(c==="if"){if(i.length>0&&i[0]&&(d=i[0].getText()),i.length>1&&i[1]){let g=i[1],{SyntaxKind:m}=I();if(g.getKind()===m.ObjectLiteralExpression){let S=g.getProperties();for(let h of S)if(h.getKind()===m.PropertyAssignment){let N=h,x=N.getName(),C=N.getInitializer();C&&(x==="onTrue"?l=yield*$(C,r,n,o,s,a):x==="onFalse"&&(f=yield*$(C,r,n,o,s,a)))}}}}else{let g=e.getExpression();if(g.getKind()===I().SyntaxKind.PropertyAccessExpression){let S=g.getExpression();l||(l=yield*$(S,r,n,o,s,a))}i.length>0&&i[0]&&(d=i[0].getText())}l||(l={id:T(),type:"unknown",reason:"Could not determine true branch"}),a.conditionalCount++;let u=d.length<=30?d:`${d.slice(0,30)}\u2026`,p={id:T(),type:"conditional",conditionalType:c,condition:d,onTrue:l,onFalse:f,conditionLabel:u,trueEdgeLabel:"true",falseEdgeLabel:"false",location:W(e,n,o.includeLocations??!1)};return{...p,displayName:j(p),semanticRole:U(p)}}),xa=(e,t,r,n,o,s,a)=>J.gen(function*(){let i=e.getArguments(),c=t.includes("forEach")?"forEach":t.includes("filterMap")?"filterMap":t.includes("filter")?"filter":t.includes("partition")?"partition":t.includes("reduce")?"reduce":t.includes("validateAll")||t.includes("validateFirst")||t.includes("validateWith")?"validate":t.includes("replicate")?"replicate":t.includes("dropUntil")?"dropUntil":t.includes("dropWhile")?"dropWhile":t.includes("takeUntil")?"takeUntil":t.includes("takeWhile")?"takeWhile":t.includes("every")?"every":t.includes("exists")?"exists":t.includes("findFirst")?"findFirst":t.includes("head")?"head":t.includes("mergeAll")?"mergeAll":"loop",d=c==="reduce"||t.includes("reduceRight")||t.includes("reduceWhile")||t.includes("reduceEffect")?2:1,l,f;i.length>0&&i[0]&&(l=i[0].getText()),i.length>d&&i[d]?f=yield*$(i[d],r,n,o,s,a):f={id:T(),type:"unknown",reason:"Could not determine loop body"},a.loopCount++;let u={id:T(),type:"loop",loopType:c,iterSource:l,body:f,location:W(e,n,o.includeLocations??!1)};return{...u,displayName:j(u),semanticRole:U(u)}}),Ea=(e,t,r,n)=>{let o=hn[t]??"other",s=vr.has(o),a=e.getArguments(),i=[];if((o==="when"||o==="tag")&&a[0]){let d=a[0].getText().replace(/["'`]/g,"").trim();/^[A-Za-z_][A-Za-z0-9_]*$/.test(d)&&i.push(d)}if(o==="tags"||o==="tagsExhaustive"){let{SyntaxKind:d}=I();for(let l of a)if(l.getKind()===d.ObjectLiteralExpression){let f=l;for(let u of f.getProperties()){let p=u.getKind()===d.PropertyAssignment?u.getName():void 0;p&&i.push(p.replace(/["'`]/g,""))}}}let c={id:T(),type:"match",matchOp:o,isExhaustive:s,...i.length>0?{matchedTags:i}:{},location:W(e,r,n.includeLocations??!1)};return{...c,displayName:j(c),semanticRole:U(c)}},ba=(e,t,r,n,o,s,a)=>J.gen(function*(){let i=yn[t]??"other",c=Tr.has(i),d;if(i==="parallel"||i==="sequential"){let u=e.getArguments(),p=[];for(let g of u)if(g){let m=yield*$(g,r,n,o,s,a);p.push(m)}p.length>0&&(d=p)}let l;if(i==="fail")l="fail";else if(i==="die")l="die";else if(i==="interrupt")l="interrupt";else if((i==="parallel"||i==="sequential")&&d&&d.length>0){let u=d.filter(p=>p.type==="cause").map(p=>p.causeKind).filter(p=>p!==void 0);u.length>0&&(l=u.every(p=>p===u[0])?u[0]:"mixed")}let f={id:T(),type:"cause",causeOp:i,isConstructor:c,...d?{children:d}:{},...l?{causeKind:l}:{},location:W(e,n,o.includeLocations??!1)};return{...f,displayName:j(f),semanticRole:U(f)}}),Ca=(e,t,r,n)=>{let o=Sn[t]??"other",s=Ir.has(o),a={id:T(),type:"exit",exitOp:o,isConstructor:s,location:W(e,r,n.includeLocations??!1)};return{...a,displayName:j(a),semanticRole:U(a)}},Na=(e,t,r,n)=>J.sync(()=>{let o=xn[t]??"other",s=e.getText(),a=Qr(s),i={id:T(),type:"schedule",scheduleOp:o,...a?{scheduleInfo:a}:{},location:W(e,r,n.includeLocations??!1)};return{...i,displayName:j(i),semanticRole:U(i)}}),va=(e,t,r,n,o,s,a)=>J.gen(function*(){let i=e.getArguments(),c=mn[t]??"other",d=Cr.has(c),l,f;if(i.length>=2&&i[0]){if(l=yield*$(i[0],r,n,o,s,a),i[1]){let p=i[1].getText();f=p.length<=120?p:p.slice(0,120)+"\u2026"}}else if(i.length===1&&i[0]){let p=i[0].getText();f=p.length<=120?p:p.slice(0,120)+"\u2026"}a.totalEffects++;let u={id:T(),type:"transform",transformType:c,isEffectful:d,...l!==void 0?{source:l}:{},...f!==void 0?{fn:f}:{},location:W(e,n,o.includeLocations??!1)};return{...u,displayName:j(u),semanticRole:U(u)}});var Rn=(e,t,r,n,o)=>ge.gen(function*(){let s=[],a=Er(),i=yield*wa(e.node,e.type,t,r,n,s,a),c=yr(e.node),d=t.getProject().getTypeChecker(),l=_e(e.node,d),f=gt(e.node,d),u={id:T(),type:"program",programName:e.name,source:e.type,...e.discoveryConfidence?{discoveryConfidence:e.discoveryConfidence}:{},...e.discoveryReason?{discoveryReason:e.discoveryReason}:{},children:i,dependencies:hr(i),errorTypes:mr(i),typeSignature:l,requiredServices:f,location:W(e.node,r,n.includeLocations??!1),jsdocDescription:c,jsdocTags:Ze(e.node)},p=Gr(t);return{root:u,metadata:{analyzedAt:Date.now(),filePath:r,tsVersion:o,warnings:s,stats:a,...p.length>0?{serviceDefinitions:p}:{}},references:new Map}}),wa=(e,t,r,n,o,s,a)=>ge.gen(function*(){switch(t){case"generator":{let i=e.getArguments();if(i.length>0&&i[0]){let c=i[0];return yield*Ra(c,r,n,o,s,a)}return[]}case"pipe":return yield*Bt(e,r,n,o,s,a);case"run":{let i=e,{SyntaxKind:c}=I(),d=yield*$a(i,r,n,o,s,a);if(Et.isSome(d))return d.value;let l=i.getArguments(),f=l.find(g=>g.getKind()===c.ArrowFunction||g.getKind()===c.FunctionExpression),u=o.enableEffectWorkflow&&f===void 0&&l.length===1?Vr(i,r):null,p=f??u??l[0];return p?[yield*$(p,r,n,o,s,a)]:[]}case"workflow-execute":{let i=e,c=i.getExpression().getText();return[{id:T(),type:"effect",callee:c,name:c,semanticRole:"side-effect",location:W(i,n,o.includeLocations??!1)}]}case"direct":{let i=e.getInitializer();return i?[yield*$(i,r,n,o,s,a)]:[]}case"class":{let i=e,c="Data.Class";for(let f of i.getHeritageClauses()){let u=f.getText();if(u.includes("Data.TaggedError")){c="Data.TaggedError";break}if(u.includes("Data.TaggedClass")){c="Data.TaggedClass";break}if(u.includes("Data.Error")){c="Data.Error";break}if(u.includes("Schema.TaggedRequest")){c="Schema.TaggedRequest";break}if(u.includes("Schema.TaggedError")){c="Schema.TaggedError";break}if(u.includes("Schema.TaggedClass")){c="Schema.TaggedClass";break}if(u.includes("Schema.Class")){c="Schema.Class";break}if(u.includes("Context.Tag")){c="Context.Tag";break}if(u.includes("Context.Reference")){c="Context.Reference";break}if(u.includes("Effect.Service")){c="Effect.Service";break}}let d=c.includes("Error")?"error-type":c.includes("Schema")?"schema":c==="Context.Tag"||c==="Context.Reference"||c==="Effect.Service"?"service-tag":"data",l={id:T(),type:"effect",callee:c,description:d,location:W(e,n,o.includeLocations??!1),jsdocDescription:ze(i),jsdocTags:Ze(i)};return a.totalEffects++,[l]}case"classProperty":{let c=e.getInitializer();return c?[yield*$(c,r,n,o,s,a)]:[]}case"classMethod":{let c=e.getBody();if(!c)return[];let{SyntaxKind:d}=I(),l=c.getDescendantsOfKind(d.ReturnStatement),f=[];for(let u of l){let p=u.getExpression();if(p){let g=yield*$(p,r,n,o,s,a);f.push(g)}}return f}default:return[]}});function $n(e){let{SyntaxKind:t}=I(),r=e.getKind();return r===t.FunctionDeclaration||r===t.FunctionExpression||r===t.ArrowFunction||r===t.MethodDeclaration||r===t.ClassDeclaration||r===t.ClassExpression||r===t.Constructor}function ne(e){let{SyntaxKind:t}=I();if(e.getKind()===t.YieldExpression)return!0;let r=!1;return e.forEachChild(n=>{if(!r&&!$n(n)){if(n.getKind()===t.YieldExpression){r=!0;return}if(ne(n)){r=!0;return}}}),r}function Ta(e){let{SyntaxKind:t}=I();switch(e.getKind()){case t.StringLiteral:return e.getLiteralValue();case t.NumericLiteral:return e.getLiteralValue().toString();case t.TrueKeyword:return"true";case t.FalseKeyword:return"false";case t.NullKeyword:return"null";case t.NoSubstitutionTemplateLiteral:return e.getText().replace(/^`|`$/g,"");default:return}}function nt(e,t){if(t.size===0)return e;let r=e;for(let[n,o]of t){let s=new RegExp(`\\b${n}\\b`,"g"),a=/^\d/.test(o)||o==="true"||o==="false"||o==="null"?o:`'${o}'`;r=r.replace(s,a)}return r}function bt(e){let t=e;return t=t.replace(/\btrue\b\s*&&\s*/g,""),t=t.replace(/\s*&&\s*\btrue\b/g,""),t=t.replace(/\bfalse\b\s*\|\|\s*/g,""),t=t.replace(/\s*\|\|\s*\bfalse\b/g,""),t=t.replace(/\bfalse\b\s*&&\s*[^|&]+/g,"false"),t=t.replace(/\btrue\b\s*\|\|\s*[^|&]+/g,"true"),t.trim()}function Dn(e){let{SyntaxKind:t}=I();switch(e.getKind()){case t.ParenthesizedExpression:case t.AsExpression:case t.TypeAssertionExpression:case t.NonNullExpression:case t.SatisfiesExpression:{let n=e.getExpression();return Dn(n)}default:return e}}function Zr(e){let{SyntaxKind:t}=I();if(e.length===0)return!1;let r=e[e.length-1];if(!r)return!1;let n=r.getKind();return n===t.ReturnStatement||n===t.ThrowStatement||n===t.BreakStatement||n===t.ContinueStatement}function eo(e){let{SyntaxKind:t}=I(),r=[];return e.forEachChild(n=>{$n(n)||(n.getKind()===t.YieldExpression?r.push(n):r.push(...eo(n)))}),r}var ka=new Set(["Step.run","Step.decide","Step.branch","Step.all","Step.forEach","Step.retry","Step.race","Step.sleep"]);function Ia(e){let{SyntaxKind:t}=I();if(e.getKind()!==t.CallExpression)return!1;let r=e.getExpression().getText();return ka.has(r)}function Te(e){if(!e)return;let{SyntaxKind:t}=I();if(e.getKind()===t.StringLiteral)return e.getLiteralText()}function Aa(e){if(!e)return[];let{SyntaxKind:t}=I();if(e.getKind()!==t.ObjectLiteralExpression)return[];let r=[],n=e;for(let o of n.getProperties())if(o.getKind()===t.PropertyAssignment){let s=o.getName();r.push({labels:[s],isDefault:s==="default",body:[]})}return r}function Fa(e,t){return ge.gen(function*(){let{SyntaxKind:r}=I(),n=e.getExpression().getText(),o=e.getArguments();switch(n){case"Step.run":{let s=Te(o[0]),a=o[1];if(!a){let c={id:T(),type:"effect",callee:"Step.run",name:s,displayName:s};return t.stats.totalEffects++,c}let i=yield*$(a,t.sourceFile,t.filePath,t.opts,t.warnings,t.stats,t.serviceScope);return{...i,displayName:s??i.displayName,name:s??i.name}}case"Step.decide":{let s=Te(o[0]),a=Te(o[1]);return t.stats.decisionCount++,{id:T(),type:"decision",decisionId:s??T(),label:a??s??"decision",condition:o[2]?.getText()??"unknown",source:"effect-flow",onTrue:[],onFalse:void 0}}case"Step.branch":{let s=Te(o[0]),a=o[1]?.getText()??"unknown",i=o[2],c=Aa(i);return t.stats.switchCount++,{id:T(),type:"switch",switchId:s,expression:a,cases:c,source:"effect-flow",hasDefault:c.some(l=>l.isDefault),hasFallthrough:!1}}case"Step.all":{let s=Te(o[0]),a=o[1],i=[];if(a?.getKind()===r.ArrayLiteralExpression){let d=a;for(let l of d.getElements()){let f=yield*$(l,t.sourceFile,t.filePath,t.opts,t.warnings,t.stats,t.serviceScope);i.push(f)}}return t.stats.parallelCount++,{id:T(),type:"parallel",name:s,displayName:s,children:i,mode:"parallel",callee:"Step.all"}}case"Step.forEach":{let s=Te(o[0]),a=o[1]?.getText(),i=o[2],c={id:T(),type:"effect",callee:"unknown"};return i&&(c=yield*$(i,t.sourceFile,t.filePath,t.opts,t.warnings,t.stats,t.serviceScope)),t.stats.loopCount++,{id:T(),type:"loop",name:s,displayName:s,loopType:"forEach",iterSource:a,body:c}}case"Step.retry":{let s=Te(o[0]),a=o[1];if(!a){let d={id:T(),type:"effect",callee:"Step.retry",name:s,displayName:s};return t.stats.totalEffects++,d}let i=yield*$(a,t.sourceFile,t.filePath,t.opts,t.warnings,t.stats,t.serviceScope);return t.stats.retryCount++,{id:T(),type:"retry",name:s,displayName:s,source:i,hasFallback:!1}}case"Step.race":{let s=Te(o[0]),a=o[1],i=[];if(a?.getKind()===r.ArrayLiteralExpression){let d=a;for(let l of d.getElements()){let f=yield*$(l,t.sourceFile,t.filePath,t.opts,t.warnings,t.stats,t.serviceScope);i.push(f)}}return t.stats.raceCount++,{id:T(),type:"race",name:s,displayName:s,children:i,callee:"Step.race"}}case"Step.sleep":{let s=Te(o[0]),a={id:T(),type:"effect",callee:"Step.sleep",name:s,displayName:s,semanticRole:"scheduling"};return t.stats.totalEffects++,a}default:{let s={id:T(),type:"effect",callee:n,name:n,displayName:n};return t.stats.totalEffects++,s}}})}function Xr(e,t){return ge.gen(function*(){let r=e,n=r.getText().startsWith("yield*"),o=r.getExpression();if(!n){let d={id:T(),type:"opaque",reason:"plain-yield",sourceText:e.getText().slice(0,80)};return t.stats.opaqueCount++,t.warnings.push({code:"PLAIN_YIELD",message:`Plain yield (not yield*) detected; this is unusual in Effect generators: ${e.getText().slice(0,60)}`,location:W(e,t.filePath,t.opts.includeLocations??!1)}),{variableName:Mt(e),effect:d}}if(!o){let d={id:T(),type:"opaque",reason:"yield-no-expression",sourceText:e.getText().slice(0,80)};return t.stats.opaqueCount++,{variableName:void 0,effect:d}}let s=Dn(o);if(t.opts.enableEffectFlow&&Ia(s)){let d=yield*Fa(s,t),l=Mt(e),f={...d,displayName:d.displayName??j(d,l),semanticRole:d.semanticRole??U(d)};return{variableName:l,effect:f}}let a=yield*$(o,t.sourceFile,t.filePath,t.opts,t.warnings,t.stats,t.serviceScope),i=Mt(e);i&&a.type==="effect"&&$r(a.callee)&&t.serviceScope.set(i,a.callee);let c={...a,displayName:j(a,i),semanticRole:a.semanticRole??U(a)};return{variableName:i,effect:c}})}function rt(e,t){return ge.gen(function*(){let r=e.getStatements(),n=[];for(let o of r){let s=yield*qt(o,t);n.push(...s)}return n})}function qt(e,t){return ge.gen(function*(){let{SyntaxKind:r}=I();switch(e.getKind()){case r.ExpressionStatement:{let s=e.getExpression();return yield*ce(s,t)}case r.VariableStatement:{let o=e,s=[],{VariableDeclarationKind:a}=I(),i=o.getDeclarationKind()===a.Const;for(let c of o.getDeclarations()){let d=c.getInitializer();if(i&&d){let l=Ta(d);l!==void 0&&t.constValues.set(c.getName(),l)}if(d&&!ne(d)&&d.getKind()===r.CallExpression){let l=d,f=l.getExpression().getText();if(f==="Context.pick"||f==="Context.omit"){let u=yield*$(l,t.sourceFile,t.filePath,t.opts,t.warnings,t.stats,t.serviceScope);u.type==="effect"&&u.description==="context"&&s.push({variableName:c.getName(),effect:u});continue}}if(d&&ne(d)){let l=yield*ce(d,t);if(l.length>0){let f=c.getName(),u=l[l.length-1];u&&(l[l.length-1]={...u,variableName:u.variableName??f})}s.push(...l)}}return s}case r.IfStatement:{if(!ne(e))return[];let o=e,s=o.getExpression().getText(),a=yield*ce(o.getExpression(),t),i=o.getThenStatement(),c=o.getElseStatement(),d=yield*Ue(i,t),l=c?yield*Ue(c,t):void 0,f=bt(nt(s,t.constValues)),u=f.length>40?f.slice(0,40)+"...":f,p={id:T(),type:"decision",decisionId:T(),label:u,condition:s,source:"raw-if",onTrue:d.map(g=>g.effect),onFalse:l&&l.length>0?l.map(g=>g.effect):void 0};return t.stats.decisionCount++,[...a,{effect:p}]}case r.SwitchStatement:{if(!ne(e))return[];let o=e,s=o.getExpression().getText(),a=o.getClauses(),i=[],c=!1,d=!1,l=[],f=[],u=!1;for(let m of a){if(m.getKind()===r.DefaultClause)d=!0,u=!0,l.push("default");else{let x=m;l.push(x.getExpression().getText())}let h=m.getStatements();if(h.length===0){c=!0;continue}for(let x of h){let C=yield*qt(x,t);f.push(...C)}Zr(h)||(c=!0),i.push({labels:l,isDefault:u,body:f.map(x=>x.effect)}),l=[],f=[],u=!1}l.length>0&&i.push({labels:l,isDefault:u,body:f.map(m=>m.effect)});let p=nt(s,t.constValues),g={id:T(),type:"switch",switchId:T(),expression:p,cases:i,source:"raw-js",hasDefault:d,hasFallthrough:c};return t.stats.switchCount++,[{effect:g}]}case r.ForStatement:{if(!ne(e))return[];let o=e,s=[],a=o.getInitializer();if(a&&ne(a)){let m=yield*ce(a,t);s.push(...m.map(S=>S.effect))}let i=o.getIncrementor();if(i&&ne(i)){let m=yield*ce(i,t);s.push(...m.map(S=>S.effect))}let c=o.getStatement(),d=yield*Ue(c,t),l=tt(c),f=o.getCondition(),u=f?f.getText():void 0,p=d.length===1&&d[0]?d[0].effect:{id:T(),type:"generator",yields:d},g={id:T(),type:"loop",loopType:"for",iterSource:u,body:p,...l?{hasEarlyExit:l}:{},...s.length>0?{headerYields:s}:{}};return t.stats.loopCount++,[{effect:g}]}case r.ForOfStatement:{if(!ne(e))return[];let o=e,s=o.getExpression(),a=s.getText(),i=[];if(ne(s)){let g=yield*ce(s,t);i.push(...g.map(m=>m.effect))}let c=o.getInitializer().getText(),d=o.getStatement(),l=yield*Ue(d,t),f=tt(d),u=l.length===1&&l[0]?l[0].effect:{id:T(),type:"generator",yields:l},p={id:T(),type:"loop",loopType:"forOf",iterSource:a,body:u,...f?{hasEarlyExit:f}:{},...i.length>0?{headerYields:i}:{},iterVariable:c};return t.stats.loopCount++,[{effect:p}]}case r.ForInStatement:{if(!ne(e))return[];let o=e,s=o.getExpression().getText(),a=o.getInitializer().getText(),i=o.getStatement(),c=yield*Ue(i,t),d=tt(i),l=c.length===1&&c[0]?c[0].effect:{id:T(),type:"generator",yields:c},f={id:T(),type:"loop",loopType:"forIn",iterSource:s,body:l,...d?{hasEarlyExit:d}:{},iterVariable:a};return t.stats.loopCount++,[{effect:f}]}case r.WhileStatement:{if(!ne(e))return[];let o=e,s=o.getExpression().getText(),a=o.getStatement(),i=yield*Ue(a,t),c=tt(a),d=i.length===1&&i[0]?i[0].effect:{id:T(),type:"generator",yields:i},l={id:T(),type:"loop",loopType:"while",iterSource:s,body:d,...c?{hasEarlyExit:c}:{}};return t.stats.loopCount++,[{effect:l}]}case r.DoStatement:{if(!ne(e))return[];let o=e,s=o.getExpression().getText(),a=o.getStatement(),i=yield*Ue(a,t),c=tt(a),d=i.length===1&&i[0]?i[0].effect:{id:T(),type:"generator",yields:i},l={id:T(),type:"loop",loopType:"doWhile",iterSource:s,body:d,...c?{hasEarlyExit:c}:{}};return t.stats.loopCount++,[{effect:l}]}case r.TryStatement:{if(!ne(e))return[];let o=e,s=o.getTryBlock(),a=yield*rt(s,t),i=o.getCatchClause(),c,d;if(i){c=i.getVariableDeclaration()?.getName();let m=i.getBlock();d=yield*rt(m,t)}let l=o.getFinallyBlock(),f;l&&(f=yield*rt(l,t));let u=Zr(s.getStatements()),p={id:T(),type:"try-catch",tryBody:a.map(g=>g.effect),...c?{catchVariable:c}:{},...d&&d.length>0?{catchBody:d.map(g=>g.effect)}:{},...f&&f.length>0?{finallyBody:f.map(g=>g.effect)}:{},hasTerminalInTry:u};return t.stats.tryCatchCount++,[{effect:p}]}case r.ReturnStatement:{let s=e.getExpression();if(!s||!ne(s))return[];let a=yield*ce(s,t),i={id:T(),type:"terminal",terminalKind:"return",value:a.map(c=>c.effect)};return t.stats.terminalCount++,[{effect:i}]}case r.ThrowStatement:{let s=e.getExpression();if(!ne(s))return[];let a=yield*ce(s,t),i={id:T(),type:"terminal",terminalKind:"throw",...a.length>0?{value:a.map(c=>c.effect)}:{}};return t.stats.terminalCount++,[{effect:i}]}case r.BreakStatement:return[];case r.ContinueStatement:return[];case r.LabeledStatement:return yield*qt(e.getStatement(),t);case r.Block:return yield*rt(e,t);default:return[]}})}function Ue(e,t){let{SyntaxKind:r}=I();return e.getKind()===r.Block?rt(e,t):qt(e,t)}function tt(e){let{SyntaxKind:t}=I(),r=!1;return e.forEachChild(n=>{if(r||$n(n))return;let o=n.getKind();if(o===t.BreakStatement||o===t.ReturnStatement){r=!0;return}if(tt(n)){r=!0;return}}),r}function ce(e,t){return ge.gen(function*(){let{SyntaxKind:r}=I();if(!ne(e))return[];let n=Dn(e),o=n.getKind();if(o===r.YieldExpression)return[yield*Xr(n,t)];if(o===r.ConditionalExpression){let i=n,c=i.getCondition().getText(),d=i.getWhenTrue(),l=i.getWhenFalse(),f=yield*ce(d,t),u=yield*ce(l,t);if(f.length>0||u.length>0){let p=bt(nt(c,t.constValues)),g={id:T(),type:"decision",decisionId:T(),label:p.length>40?p.slice(0,40)+"...":p,condition:c,source:"raw-ternary",onTrue:f.map(m=>m.effect),onFalse:u.length>0?u.map(m=>m.effect):void 0};return t.stats.decisionCount++,[{effect:g}]}}if(o===r.BinaryExpression){let i=n,c=i.getOperatorToken().getKind(),d=i.getLeft(),l=i.getRight();if(c===r.AmpersandAmpersandToken){let f=yield*ce(l,t);if(f.length>0){let u=d.getText(),p=bt(nt(u,t.constValues)),g={id:T(),type:"decision",decisionId:T(),label:p.length>40?p.slice(0,40)+"...":p,condition:u,source:"raw-short-circuit",onTrue:f.map(m=>m.effect),onFalse:[]};return t.stats.decisionCount++,[{effect:g}]}}if(c===r.BarBarToken){let f=yield*ce(l,t);if(f.length>0){let u=d.getText(),p=bt(nt(u,t.constValues)),g={id:T(),type:"decision",decisionId:T(),label:p.length>40?p.slice(0,40)+"...":p,condition:u,source:"raw-short-circuit",onTrue:[],onFalse:f.map(m=>m.effect)};return t.stats.decisionCount++,[{effect:g}]}}if(c===r.QuestionQuestionToken){let f=yield*ce(l,t);if(f.length>0){let u=`${d.getText()} != null`,p=bt(nt(u,t.constValues)),g={id:T(),type:"decision",decisionId:T(),label:p.length>40?p.slice(0,40)+"...":p,condition:u,source:"raw-short-circuit",onTrue:[],onFalse:f.map(m=>m.effect)};return t.stats.decisionCount++,[{effect:g}]}}}let s=eo(e),a=[];for(let i of s){let c=yield*Xr(i,t);a.push(c)}return a})}var Ra=(e,t,r,n,o,s)=>ge.gen(function*(){let{SyntaxKind:a}=I(),i;if((e.getKind()===a.ArrowFunction||e.getKind()===a.FunctionExpression||e.getKind()===a.FunctionDeclaration)&&(i=e.getBody()),!i)return[];let c=new Map,l={sourceFile:t,filePath:r,opts:n,warnings:o,stats:s,serviceScope:c,constValues:new Map},f;i.getKind()===a.Block?f=yield*rt(i,l):f=yield*ce(i,l);let u=i.getDescendantsOfKind(a.CallExpression);for(let S of u){let h=Pe(t);if(et(S,t,h,n.knownEffectInternalsRoot)){let N=yield*Fn(S,t,r,n,o,s,c);f.push({effect:N})}}let p=ze(e),g={id:T(),type:"generator",yields:f,jsdocDescription:p,jsdocTags:Ze(e)};return[{...g,displayName:j(g),semanticRole:U(g)}]});function $a(e,t,r,n,o,s){let i=e.getExpression().getText();if(!(i.endsWith(".pipe")||i==="pipe"))return ge.succeed(Et.none());let d=e.getArguments(),l=d[d.length-1];if(!l)return ge.succeed(Et.none());let f=l.getText();return f.includes(".runMain")||f.includes(".runPromise")||f.includes(".runSync")||f.includes(".runFork")?ge.map(Bt(e,t,r,n,o,s),p=>Et.some(p)):ge.succeed(Et.none())}var Pn=(e,t)=>ke.gen(function*(){let r={...dn,...t},{ts:n,Project:o}=I(),s=yield*ke.try({try:()=>Sr(e)?new o({skipAddingFilesFromTsConfig:!0,compilerOptions:{allowJs:!0}}):cr(r.tsConfigPath),catch:d=>new pe("PROJECT_CREATION_FAILED",`Failed to create project: ${String(d)}`)}),a=s.getSourceFile(e);a&&s.removeSourceFile(a);let i=yield*ke.try({try:()=>s.addSourceFileAtPath(e),catch:d=>new pe("FILE_NOT_FOUND",`Failed to load file ${e}: ${String(d)}`)}),c=An(i,r);return c.length===0?yield*ke.fail(new pe("NO_EFFECTS_FOUND",`No Effect programs found in ${e}`)):yield*ke.forEach(c,d=>Rn(d,i,e,r,n.version),{concurrency:"unbounded"})}),Mn=(e,t="temp.ts",r)=>ke.gen(function*(){let n={...dn,...r},{ts:o}=I(),s=yield*ke.try({try:()=>lr(e,t),catch:i=>new pe("SOURCE_PARSE_FAILED",`Failed to parse source: ${String(i)}`)}),a=An(s,n);return a.length===0?yield*ke.fail(new pe("NO_EFFECTS_FOUND","No Effect programs found in source")):yield*ke.forEach(a,i=>Rn(i,s,t,n,o.version),{concurrency:"unbounded"})});var Ne=e=>({single:()=>G.gen(function*(){if(e.length===1){let t=e[0];if(t)return t}return yield*G.fail(new pe("NOT_SINGLE_PROGRAM",`Expected exactly 1 program, found ${String(e.length)}`))}),singleOption:()=>G.gen(function*(){if(e.length===1){let t=e[0];if(t)return jt.some(t)}return jt.none()}),all:()=>G.succeed(e),named:t=>G.gen(function*(){let r=e.find(n=>n.root.programName===t);if(!r){let n=e.map(o=>o.root.programName).join(", ");return yield*G.fail(new pe("PROGRAM_NOT_FOUND",`Program "${t}" not found. Available: ${n||"(none)"}`))}return r}),first:()=>G.gen(function*(){let t=e[0];return t||(yield*G.fail(new pe("NO_PROGRAMS","No programs found")))}),firstOption:()=>G.gen(function*(){let t=e[0];return t?jt.some(t):jt.none()})}),Ct=(e,t)=>{ht();let r=Pn(e,t);return{single:()=>G.gen(function*(){let n=yield*r;return yield*Ne(n).single()}),singleOption:()=>G.gen(function*(){let n=yield*r;return yield*Ne(n).singleOption()}).pipe(G.orDie),all:()=>r,named:n=>G.gen(function*(){let o=yield*r;return yield*Ne(o).named(n)}),first:()=>G.gen(function*(){let n=yield*r;return yield*Ne(n).first()}),firstOption:()=>G.gen(function*(){let n=yield*r;return yield*Ne(n).firstOption()}).pipe(G.orDie)}};Ct.source=(e,t)=>{ht();let r=Mn(e,"temp.ts",t);return{single:()=>G.gen(function*(){let n=yield*r;return yield*Ne(n).single()}),singleOption:()=>G.gen(function*(){let n=yield*r;return yield*Ne(n).singleOption()}).pipe(G.orDie),all:()=>r,named:n=>G.gen(function*(){let o=yield*r;return yield*Ne(o).named(n)}),first:()=>G.gen(function*(){let n=yield*r;return yield*Ne(n).first()}),firstOption:()=>G.gen(function*(){let n=yield*r;return yield*Ne(n).firstOption()}).pipe(G.orDie)}};import{Effect as me,Option as io}from"effect";import{readdir as ao,readFile as Oa,stat as Wa}from"fs/promises";import{readFileSync as co}from"fs";import{join as Ut,extname as lo,resolve as so,basename as Ka}from"path";import{Option as to}from"effect";function Da(e,t){let{SyntaxKind:r}=I(),n=[],o=e.getProject().getTypeChecker(),s=e.getDescendantsOfKind(r.ClassDeclaration);for(let a of s){let i=a.getName();if(!i)continue;let c=a.getExtends();if(!c)continue;let d=c.getText();if(!d.includes("Context.Tag")&&!d.includes("Effect.Service"))continue;let l=i,f=/Context\.Tag\s*\(\s*['"]([^'"]+)['"]\s*\)/.exec(d);f?.[1]&&(l=f[1]);let u=c.getTypeArguments();if(u.length<2){let h=c.getExpression();h&&"getTypeArguments"in h&&typeof h.getTypeArguments=="function"&&(u=h.getTypeArguments())}let p={tagId:l,methods:[],properties:[]},g;if(u.length>=2){let h=u[1];if(h)try{g=h.getText();let N=o.getTypeAtLocation(h),x=[],C=[];for(let E of N.getProperties()){let y=E.getName();if(y.startsWith("_")||y==="constructor")continue;o.getTypeOfSymbolAtLocation(E,h).getCallSignatures().length>0?x.push(y):C.push(y)}p={tagId:l,methods:x,properties:C}}catch{}}let m=a.getStart(),S=e.getLineAndColumnAtPos(m);n.push({tagId:l,className:i,filePath:t,location:{filePath:t,line:S.line,column:S.column-1},definition:p,interfaceTypeText:g})}return n}function Pa(e,t,r){let{SyntaxKind:n}=I(),o=[],s=e.getDescendantsOfKind(n.VariableDeclaration);for(let a of s){let i=a.getInitializer();if(!i)continue;let c=i.getText(),d=/Layer\.(effect|succeed|sync|scoped)\s*\(\s*/.exec(c);if(!d)continue;let l=d[1],f=a.getName(),u;if(i.getKind()===n.CallExpression){let x=i.getArguments?.();if(x&&x.length>0){let C=x[0];if(!C)continue;let E=C.getText().trim();u=r.get(E)}}if(!u){for(let x of r.keys())if(c.includes(`Layer.${l}(${x}`)||c.includes(`Layer.${l}(
|
|
5
|
-
${x}`)){u=r.get(x);break}}if(!u)continue;let p=[],g=/Layer\.provide\s*\(([^)]+)\)/.exec(c);if(g?.[1]){let x=g[1].trim();for(let[C,E]of r.entries())E!==u&&x.includes(C)&&!p.includes(E)&&p.push(E)}let m=c.matchAll(/yield\*\s+(\w+)/g);for(let x of m){let C=x[1],E=C?r.get(C):void 0;E&&E!==u&&!p.includes(E)&&p.push(E)}let S=c.matchAll(/yield\s*\*\s*(\w+)/g);for(let x of S){let C=x[1],E=C?r.get(C):void 0;E&&E!==u&&!p.includes(E)&&p.push(E)}let h=a.getStart(),N=e.getLineAndColumnAtPos(h);o.push({providesServiceId:u,implementation:{name:f,filePath:t,location:{filePath:t,line:N.line,column:N.column-1},kind:l,requires:p}})}return o}function Ma(e){let t=new Map;for(let[r,n]of e)for(let o of n){let s=o.root.programName;if(o.root.requiredServices)for(let a of o.root.requiredServices){let i=t.get(a.serviceId)??[];i.push({programName:s,filePath:r,location:a.requiredAt}),t.set(a.serviceId,i)}no(o.root.children,s,r,t)}return t}function no(e,t,r,n){for(let o of e){if(o.type==="effect"&&o.serviceCall){let a=o.serviceCall.serviceType;if(a){let i=n.get(a)??[];i.some(c=>c.programName===t&&c.filePath===r)||(i.push({programName:t,filePath:r,location:o.location}),n.set(a,i))}}let s=to.getOrElse(v(o),()=>[]);s.length>0&&no(s,t,r,n)}}function La(e){let t=[],r=new Set,n=new Set;function o(s){if(r.has(s)||n.has(s))return;n.add(s);let a=e.get(s);if(a)for(let i of a.dependencies)o(i);n.delete(s),r.add(s),t.push(s)}for(let s of e.keys())o(s);return t}function ro(e,t,r,n=new Set){let o=[];if(n.has(e))return o;n.add(e);for(let s of t)for(let a of s.requires){o.includes(a)||o.push(a);let i=r.get(a);if(i)for(let c of ro(a,i,r,n))o.includes(c)||o.push(c)}return o}function _t(e,t){let r=new Map;if(t)for(let[u,p]of t){let g=Da(p,u);for(let m of g)r.has(m.tagId)||r.set(m.tagId,m)}for(let[u,p]of e)for(let g of p)if(g.metadata.serviceDefinitions)for(let m of g.metadata.serviceDefinitions)r.has(m.tagId)||r.set(m.tagId,{tagId:m.tagId,className:m.tagId,filePath:u,location:{filePath:u,line:1,column:0},definition:m});let n=new Set(r.keys()),o=new Map;for(let[u,p]of r)o.has(u)||o.set(u,u),o.has(p.className)||o.set(p.className,u);let s=new Set;for(let u of e.values())for(let p of u)if(p.root.requiredServices)for(let g of p.root.requiredServices)s.add(g.serviceId);let a=new Map;if(t)for(let[u,p]of t){let g=Pa(p,u,o);for(let m of g){if(!n.has(m.providesServiceId))continue;let S=a.get(m.providesServiceId)??[];S.push(m.implementation),a.set(m.providesServiceId,S)}}for(let[u,p]of e)for(let g of p)oo(g.root.children,u,n,o,a,g);let i=Ma(e),c=new Map,d=[];for(let[u,p]of r){let g=a.get(u)??[],m=i.get(u)??[],S=ro(u,g,a);c.set(u,{serviceId:u,className:p.className,definitionFilePath:p.filePath,definitionLocation:p.location,definition:p.definition,interfaceTypeText:p.interfaceTypeText,layerImplementations:g,consumers:m,dependencies:S})}let l=new Set(s);for(let u of i.keys())l.add(u);for(let u of l)c.has(u)||d.push(u);let f=La(c);return{services:c,unresolvedServices:d,topologicalOrder:f}}function oo(e,t,r,n,o,s){for(let a of e){if(a.type==="layer"&&a.provides)for(let c of a.provides){let d=n.get(c)??(r.has(c)?c:void 0);if(d&&r.has(d)){let l=o.get(d)??[],f=a.requires?a.requires.map(u=>n.get(u)??u).filter(u=>r.has(u)):[];l.some(u=>u.name===(a.name??s.root.programName)&&u.filePath===t)||(l.push({name:a.name??s.root.programName,filePath:t,location:a.location??{filePath:t,line:1,column:0},kind:"other",requires:f}),o.set(d,l))}}let i=to.getOrElse(v(a),()=>[]);i.length>0&&oo(i,t,r,n,o,s)}}var Ht={extensions:[".ts",".tsx"],maxDepth:10,knownEffectInternalsRoot:void 0,includePerFileTiming:!1,excludeFromSuspiciousZeros:[],buildServiceMap:!1};function Ba(e){let t=0,r=0,n=o=>{for(let s of o){t++,s.type==="unknown"&&r++;let a=io.getOrElse(v(s),()=>[]);a.length>0&&n(a)}};return n(e),{total:t,unknown:r}}function qa(e){let t=new Map,r=n=>{for(let o of n){if(sn(o)){let a=o.reason;t.set(a,(t.get(a)??0)+1)}let s=io.getOrElse(v(o),()=>[]);s.length>0&&r(s)}};return r(e),t}function ja(e){try{let t=co(e,"utf-8");return/from\s+["'](?:effect|effect\/|@effect\/)/.test(t)}catch{return!1}}function _a(e){try{let t=co(e,"utf-8");return/\bEffect\./.test(t)||/\bLayer\./.test(t)||/\bStream\./.test(t)||/\bSchema\./.test(t)||/\byield\*/.test(t)||/\bpipe\(/.test(t)||/\brunPromise\b/.test(t)||/\brunSync\b/.test(t)||/\brunFork\b/.test(t)||/\bacquireRelease\b/.test(t)?!1:/\binterface\b/.test(t)||/\btype\b/.test(t)||/\bdeclare\b/.test(t)||/^\s*import\s+type\b/m.test(t)||/^\s*export\s+type\b/m.test(t)}catch{return!1}}function za(e){let t=e.replace(/\\/g,"/"),r=Ka(t).toLowerCase();if(r==="index.ts"||r==="index.tsx"||/\/index\.[jt]sx?$/.test(t))return"barrel_or_index";if(/(^|\/)(__tests__|test|tests|dtslint)(\/|$)/.test(t)||/\.(test|spec|tst)\.[jt]sx?$/.test(t))return"test_or_dtslint";if(/(^|\/)(vitest|vite|jest|webpack|rollup|tsup|esbuild|eslint|prettier|babel|playwright|typedoc|karma)\.config\.[jt]s$/.test(t)||/(^|\/)vitest\.workspace\.[jt]s$/.test(t))return"config_or_build";if(_a(e))return"type_only"}async function Ln(e,t,r,n){if(n>=r)return[];let o=[];try{let s=await ao(e,{withFileTypes:!0});for(let a of s){let i=Ut(e,a.name);a.isDirectory()?a.name!=="node_modules"&&a.name!==".git"&&o.push(...await Ln(i,t,r,n+1)):a.isFile()&&t.includes(lo(a.name))&&o.push(i)}}catch{}return o}async function uo(e,t,r){if(r>=t)return[];let n=[];try{let o=await ao(e,{withFileTypes:!0});o.some(a=>a.isFile()&&a.name==="package.json")&&n.push(e);for(let a of o)a.isDirectory()&&a.name!=="node_modules"&&a.name!==".git"&&n.push(...await uo(Ut(e,a.name),t,r+1))}catch{}return n}function zt(e,t,r){if(!t||typeof t!="string")return[];let n=t.replace(/^\.\//,""),o=Ut(e,n);return lo(n)?[so(o)]:r.map(a=>so(o+a))}async function Ha(e){try{let{Project:t,SyntaxKind:r}=I(),s=new t({skipAddingFilesFromTsConfig:!0}).addSourceFileAtPath(e).getDescendantsOfKind(r.CallExpression),a=[r.FunctionDeclaration,r.FunctionExpression,r.ArrowFunction,r.MethodDeclaration];for(let i of s){let c=i.getParent();if(c?.getKind()!==r.ExpressionStatement)continue;let d=c;for(;d;){let f=d.getKind();if(f===r.SourceFile||a.includes(f))break;d=d.getParent()}if(d?.getKind()!==r.SourceFile)continue;let l=i.getExpression().getText();if(l.includes(".runPromise")||l.includes(".runSync")||l.includes(".runFork")||l.includes(".runCallback")||l.includes("NodeRuntime.runMain")||l.includes("BunRuntime.runMain")||l.includes("DenoRuntime.runMain")||l.includes("Runtime.runPromise")||l.includes("Runtime.runSync")||l.includes("Runtime.runFork"))return!0}}catch{}return!1}async function Ua(e,t){let r=await uo(e,10,0),n=[];for(let o of r)try{let s=await Oa(Ut(o,"package.json"),"utf-8"),a=JSON.parse(s),i=[zt(o,a.main,t),zt(o,a.module,t)];if(typeof a.bin=="string")i.push(zt(o,a.bin,t));else if(a.bin&&typeof a.bin=="object")for(let c of Object.values(a.bin))i.push(zt(o,typeof c=="string"?c:void 0,t));for(let c of i)for(let d of c)try{(await Wa(d).catch(()=>null))?.isFile()&&n.push(d)}catch{}}catch{}return[...new Set(n)]}function Va(e,t={}){let r=t.extensions??Ht.extensions,n=t.maxDepth??Ht.maxDepth;return me.gen(function*(){let o=yield*me.promise(()=>Ln(e,r,n,0)),s=new Map,a=[],i=[],c=[],d=[];for(let u of o){let p=yield*Ct(u,{tsConfigPath:t.tsconfig,knownEffectInternalsRoot:t.knownEffectInternalsRoot}).all().pipe(me.map(m=>({_tag:"ok",programs:m})),me.catchAll(m=>me.succeed({_tag:"fail",error:m instanceof Error?m.message:String(m)})));if(p._tag==="fail"){c.push({file:u,error:p.error});continue}let g=p.programs;if(g.length===0){d.push(u);continue}s.set(u,g),a.push(...g);for(let m of g){let S=m.root.programName==="main"||m.root.programName.includes("run"),h=m.root.source==="run";(S||h)&&(i.includes(u)||i.push(u))}}let l=yield*me.promise(()=>Ua(e,r));for(let u of l)o.includes(u)&&!i.includes(u)&&i.push(u);for(let u of s.keys()){if(i.includes(u))continue;(yield*me.promise(()=>Ha(u)))&&i.push(u)}let f;if(t.buildServiceMap)try{let{Project:u}=I(),p=new u({skipAddingFilesFromTsConfig:!0,compilerOptions:{allowJs:!0}}),g=new Map;for(let m of s.keys())try{let S=p.addSourceFileAtPath(m);g.set(m,S)}catch{}f=_t(s,g)}catch{f=_t(s)}return{byFile:s,allPrograms:a,entryPointFiles:i,fileCount:o.length,failedFiles:c,zeroProgramFiles:d,serviceMap:f}})}function Ga(e,t={}){let r=t.extensions??Ht.extensions,n=t.maxDepth??Ht.maxDepth;return me.gen(function*(){let o=Date.now(),s=yield*me.promise(()=>Ln(e,r,n,0)),a=[],i=0,c=0,d=[],l=new Map,f=t.includePerFileTiming===!0;for(let A of s){let K=f?Date.now():0,q=yield*Ct(A,{tsConfigPath:t.tsconfig,knownEffectInternalsRoot:t.knownEffectInternalsRoot}).all().pipe(me.map(V=>({_tag:"ok",programs:V})),me.catchAll(V=>me.succeed({_tag:"fail",error:V instanceof Error?V.message:String(V)}))),Y=f?Date.now()-K:void 0;if(q._tag==="ok"){let V=q.programs.length,P=0,H=0;for(let fe of q.programs){let de=Ba(fe.root.children);i+=de.total,c+=de.unknown,P+=de.total,H+=de.unknown;let ee=qa(fe.root.children);for(let[Fe,Re]of ee)l.set(Fe,(l.get(Fe)??0)+Re)}P>0&&d.push({file:A,total:P,unknown:H}),a.push(V>0?{file:A,status:"ok",programCount:V,...Y!==void 0?{durationMs:Y}:{}}:{file:A,status:"zero",programCount:0,...Y!==void 0?{durationMs:Y}:{}})}else{let V=q.error??"",P=V.includes("No Effect programs found")||V.includes("NO_EFFECTS_FOUND");a.push(P?{file:A,status:"zero",programCount:0,...Y!==void 0?{durationMs:Y}:{}}:{file:A,status:"fail",error:q.error,...Y!==void 0?{durationMs:Y}:{}})}}let u=s.length,p=a.filter(A=>A.status==="ok").length,g=a.filter(A=>A.status==="zero").length,m=a.filter(A=>A.status==="fail").length,S=u>0?p/u*100:0,h=p+m>0?p/(p+m)*100:100,N=t.excludeFromSuspiciousZeros??[],x=A=>{let K=A.replace(/\\/g,"/");return N.some(q=>K.includes(q.replace(/\\/g,"/"))||K.endsWith(q.replace(/\\/g,"/")))},C={barrel_or_index:0,config_or_build:0,test_or_dtslint:0,type_only:0,suspicious:0,other:0},E=[],y=[],w=a.filter(A=>A.status==="zero");for(let A of w){let K=ja(A.file),q=za(A.file),Y=K&&!x(A.file)&&q===void 0?"suspicious":q??"other";C[Y]++,y.push({file:A.file,category:Y,importsEffect:K}),Y==="suspicious"&&E.push(A.file)}let k=i>0?c/i:0,b=d.filter(A=>A.total>0).sort((A,K)=>K.unknown/K.total-A.unknown/A.total).slice(0,10).map(A=>A.file),M={};for(let[A,K]of l)M[A]=K;let F=[...l.entries()].sort((A,K)=>K[1]-A[1]).slice(0,20).map(([A,K])=>({reason:A,count:K})),L=Date.now()-o;return{discovered:u,analyzed:p,zeroPrograms:g,failed:m,outcomes:a,percentage:S,analyzableCoverage:h,unknownNodeRate:k,totalNodes:i,unknownNodes:c,suspiciousZeros:E,zeroProgramCategoryCounts:C,zeroProgramClassifications:y,topUnknownFiles:b,unknownReasonCounts:M,topUnknownReasons:F,durationMs:L}})}import{readdir as Ja}from"fs/promises";import{join as Ya,extname as Qa}from"path";import{Project as Za,SyntaxKind as D}from"ts-morph";function R(e,t,r,n,o,s,a){let{line:i,column:c}=n.getLineAndColumnAtPos(r.getStart());e.push({filePath:t,line:i+1,column:c,pattern:o,suggestion:s,codeSnippet:a??n.getText().slice(r.getStart(),r.getStart()+80).replace(/\n/g," ")})}function fo(e,t){let r=[],n=new Za({skipAddingFilesFromTsConfig:!0}),o=t?n.createSourceFile(e,t):n.addSourceFileAtPath(e);for(let l of o.getDescendantsOfKind(D.TryStatement))R(r,e,l,o,"try/catch","Effect.try or Effect.tryPromise with catch handler");for(let l of o.getDescendantsOfKind(D.CallExpression)){let u=l.getExpression().getText();(u==="Promise.all"||u.endsWith(".all")&&u.includes("Promise"))&&R(r,e,l,o,"Promise.all",'Effect.all([...], { concurrency: "unbounded" })'),(u==="Promise.race"||u.endsWith(".race")&&u.includes("Promise"))&&R(r,e,l,o,"Promise.race","Effect.race(first, second)")}for(let l of o.getDescendantsOfKind(D.CallExpression)){let u=l.getExpression().getText();(u==="setTimeout"||u==="setInterval")&&R(r,e,l,o,u,u==="setTimeout"?"Effect.sleep(Duration.millis(n))":"Schedule.spaced(Duration.millis(n))"),(u==="setImmediate"||u==="process.setImmediate")&&R(r,e,l,o,"setImmediate","Effect.sync + queueMicrotask or Effect.async")}for(let l of o.getDescendantsOfKind(D.NewExpression)){let u=l.getExpression().getText();(u==="XMLHttpRequest"||u.includes("XMLHttpRequest"))&&R(r,e,l,o,"new XMLHttpRequest()","HttpClient.request or @effect/platform HttpClient")}for(let l of o.getDescendantsOfKind(D.NewExpression)){let u=l.getExpression().getText();(u==="Worker"||u.includes("Worker"))&&R(r,e,l,o,"new Worker()","Worker.make or @effect/platform Worker")}for(let l of o.getDescendantsOfKind(D.CallExpression)){let u=l.getExpression().getText();(u==="fs.exists"||u.endsWith(".exists")&&u.startsWith("fs."))&&l.getArguments().length>=2&&R(r,e,l,o,"fs.exists (callback)","Effect.promise or fs.promises.access")}for(let l of o.getDescendantsOfKind(D.CallExpression)){let u=l.getExpression().getText();(u.endsWith(".request")&&(u.includes("http")||u.includes("https"))||u==="request"&&o.getText().includes("http"))&&R(r,e,l,o,"http.request / https.request","HttpClient.request or @effect/platform HttpClient")}for(let l of o.getDescendantsOfKind(D.CallExpression)){let u=l.getExpression().getText();(u.startsWith("dns.")||u.includes("dns."))&&(u.includes("lookup")||u.includes("resolve")||u.includes("reverse"))&&R(r,e,l,o,"dns (callback)","Effect.promise or dns.promises")}for(let l of o.getDescendantsOfKind(D.CallExpression))l.getExpression().getText()==="fetch"&&R(r,e,l,o,"fetch()","HttpClient.request or @effect/platform HttpClient");for(let l of o.getDescendantsOfKind(D.NewExpression)){let u=l.getExpression().getText();(u==="EventEmitter"||u.includes("EventEmitter"))&&R(r,e,l,o,"new EventEmitter()","PubSub.bounded<EventType>() or PubSub.unbounded<EventType>()")}for(let l of o.getDescendantsOfKind(D.CallExpression)){let u=l.getExpression().getText();(u.endsWith(".on(")||u.endsWith(".addListener("))&&(u.includes("Emitter")||u.includes("emitter"))&&R(r,e,l,o,"EventEmitter.on / addListener","PubSub.subscribe for PubSub"),u.endsWith(".emit(")&&(u.includes("Emitter")||u.includes("emitter"))&&R(r,e,l,o,"EventEmitter.emit","PubSub.publish for PubSub")}for(let l of o.getDescendantsOfKind(D.ClassDeclaration)){let f=l.getName(),u=l.getText();f&&(u.includes("new ")||u.includes("constructor"))&&(f.endsWith("Service")||f.endsWith("Repository")||f.endsWith("Client"))&&R(r,e,l,o,`class ${f} (manual DI)`,`Context.Tag<${f}>() + Layer.effect or Layer.succeed`)}for(let l of o.getDescendantsOfKind(D.NewExpression)){let u=l.getExpression().getText();(u.endsWith("Service")||u.endsWith("Repository")||u.endsWith("Client"))&&!u.includes("Context")&&!u.includes("Layer")&&R(r,e,l,o,`new ${u}()`,"Context.Tag + Layer.effect for dependency injection")}for(let l of o.getDescendantsOfKind(D.FunctionDeclaration))(l.getModifiers().some(f=>f.getText()==="async")||l.getText().startsWith("async"))&&R(r,e,l,o,"async function","Effect.gen or Effect.pipe with flatMap");for(let l of o.getDescendantsOfKind(D.ArrowFunction))l.getText().startsWith("async")&&R(r,e,l,o,"async arrow function","Effect.gen or Effect.pipe with flatMap");for(let l of o.getDescendantsOfKind(D.CallExpression)){let u=l.getExpression().getText();u.endsWith(".then")&&u.includes("Promise")&&R(r,e,l,o,"Promise.then","Effect.flatMap for sequential composition"),(u==="Promise.allSettled"||u.endsWith(".allSettled")&&u.includes("Promise"))&&R(r,e,l,o,"Promise.allSettled","Effect.all with merge or separate error handling"),u.endsWith(".catch")&&(u.includes("Promise")||u.includes(".then"))&&R(r,e,l,o,"Promise.catch","Effect.catchAll or Effect.catchTag for typed error handling"),u.endsWith(".finally")&&(u.includes("Promise")||u.includes(".then"))&&R(r,e,l,o,"Promise.finally","Effect.ensuring for cleanup")}for(let l of o.getDescendantsOfKind(D.CallExpression)){let u=l.getExpression().getText();(u==="addEventListener"||u.endsWith(".addEventListener"))&&R(r,e,l,o,"addEventListener","Effect.async or EventTarget + Effect.asyncInterrupt")}for(let l of o.getDescendantsOfKind(D.CallExpression)){let u=l.getExpression().getText();(u==="fs.readFile"||u==="fs.writeFile"||u==="readFile"||u==="writeFile"||u.endsWith(".readFile")&&u.startsWith("fs.")||u.endsWith(".writeFile")&&u.startsWith("fs."))&&l.getArguments().length>=2&&R(r,e,l,o,u.includes("write")?"fs.writeFile (callback)":"fs.readFile (callback)","Effect.promise or fs.promises + Effect.tryPromise")}for(let l of o.getDescendantsOfKind(D.ThrowStatement))R(r,e,l,o,"throw","Effect.fail(error) for typed error channel");for(let l of o.getDescendantsOfKind(D.CallExpression)){let u=l.getExpression().getText();(u==="promisify"||u.endsWith(".promisify"))&&R(r,e,l,o,"util.promisify","Effect.tryPromise or Effect.async for callback-style APIs")}for(let l of o.getDescendantsOfKind(D.NewExpression))l.getExpression().getText()==="Promise"&&R(r,e,l,o,"new Promise(...)","Effect.async or Effect.promise for callback-style");for(let l of o.getDescendantsOfKind(D.ForOfStatement))l.getAwaitKeyword()&&R(r,e,l,o,"for await...of","Stream.iterate or Effect.asyncIterable for async iteration");for(let l of o.getDescendantsOfKind(D.CallExpression)){let u=l.getExpression().getText();(u==="readFileSync"||u==="writeFileSync"||u==="existsSync"||u.endsWith(".readFileSync")||u.endsWith(".writeFileSync")||u.endsWith(".existsSync"))&&R(r,e,l,o,u,"Effect.promise or fs/promises + Effect.tryPromise")}for(let l of o.getDescendantsOfKind(D.CallExpression)){let u=l.getExpression().getText();(u==="process.nextTick"||u.endsWith(".nextTick")&&u.includes("process"))&&R(r,e,l,o,"process.nextTick","Effect.sync + queueMicrotask or Effect.async")}for(let l of o.getDescendantsOfKind(D.CallExpression)){let u=l.getExpression().getText();(u==="queueMicrotask"||u.endsWith(".queueMicrotask"))&&R(r,e,l,o,"queueMicrotask","Effect.sync for deferred execution")}for(let l of o.getDescendantsOfKind(D.NewExpression)){let u=l.getExpression().getText();(u==="WebSocket"||u.includes("WebSocket"))&&R(r,e,l,o,"new WebSocket()","Effect.async or @effect/platform WebSocket")}for(let l of o.getDescendantsOfKind(D.NewExpression)){let u=l.getExpression().getText();(u==="MessageChannel"||u.includes("MessageChannel"))&&R(r,e,l,o,"new MessageChannel()","Effect.async or Queue for cross-context messaging")}for(let l of o.getDescendantsOfKind(D.CallExpression)){let u=l.getExpression().getText();(u==="fs.appendFile"||u.endsWith(".appendFile")&&u.startsWith("fs."))&&l.getArguments().length>=2&&R(r,e,l,o,"fs.appendFile (callback)","Effect.promise or fs.promises.appendFile")}for(let l of o.getDescendantsOfKind(D.CallExpression)){let u=l.getExpression().getText();if((u==="fs.mkdir"||u==="fs.stat"||u==="fs.unlink"||u.endsWith(".mkdir")&&u.startsWith("fs.")||u.endsWith(".stat")&&u.startsWith("fs.")||u.endsWith(".unlink")&&u.startsWith("fs."))&&l.getArguments().length>=2){let g=u.includes("mkdir")?"fs.mkdir":u.includes("stat")?"fs.stat":"fs.unlink";R(r,e,l,o,`${g} (callback)`,"Effect.promise or fs.promises")}}for(let l of o.getDescendantsOfKind(D.NewExpression)){let u=l.getExpression().getText();(u==="MutationObserver"||u.includes("MutationObserver"))&&R(r,e,l,o,"new MutationObserver()","Effect.async or Effect.asyncInterrupt for DOM observation")}for(let l of o.getDescendantsOfKind(D.CallExpression)){let u=l.getExpression().getText();(u==="requestIdleCallback"||u.endsWith(".requestIdleCallback"))&&R(r,e,l,o,"requestIdleCallback","Effect.async or Effect.sync for idle-time work")}for(let l of o.getDescendantsOfKind(D.NewExpression)){let u=l.getExpression().getText();(u==="BroadcastChannel"||u.includes("BroadcastChannel"))&&R(r,e,l,o,"new BroadcastChannel()","PubSub or Effect.async for cross-tab messaging")}for(let l of o.getDescendantsOfKind(D.CallExpression)){let u=l.getExpression().getText();if((u==="fs.rename"||u==="fs.realpath"||u.endsWith(".rename")&&u.startsWith("fs.")||u.endsWith(".realpath")&&u.startsWith("fs."))&&l.getArguments().length>=2){let g=u.includes("realpath")?"fs.realpath":"fs.rename";R(r,e,l,o,`${g} (callback)`,"Effect.promise or fs.promises")}}for(let l of o.getDescendantsOfKind(D.CallExpression)){let u=l.getExpression().getText(),p=(u==="fs.readdir"||u.endsWith(".readdir")&&u.startsWith("fs."))&&l.getArguments().length>=2,g=(u==="fs.copyFile"||u.endsWith(".copyFile")&&u.startsWith("fs."))&&l.getArguments().length>=2;p&&R(r,e,l,o,"fs.readdir (callback)","Effect.promise or fs.promises.readdir"),g&&R(r,e,l,o,"fs.copyFile (callback)","Effect.promise or fs.promises.copyFile")}for(let l of o.getDescendantsOfKind(D.NewExpression)){let u=l.getExpression().getText();(u==="FileReader"||u.includes("FileReader"))&&R(r,e,l,o,"new FileReader()","Effect.async or FileReader + Effect.asyncInterrupt")}for(let l of o.getDescendantsOfKind(D.CallExpression)){let u=l.getExpression().getText(),p=(u==="fs.mkdtemp"||u.endsWith(".mkdtemp")&&u.startsWith("fs."))&&l.getArguments().length>=2,g=(u==="fs.symlink"||u.endsWith(".symlink")&&u.startsWith("fs."))&&l.getArguments().length>=2;p&&R(r,e,l,o,"fs.mkdtemp (callback)","Effect.promise or fs.promises.mkdtemp"),g&&R(r,e,l,o,"fs.symlink (callback)","Effect.promise or fs.promises.symlink")}for(let l of o.getDescendantsOfKind(D.NewExpression)){let u=l.getExpression().getText();(u==="ResizeObserver"||u==="IntersectionObserver"||u.includes("ResizeObserver")||u.includes("IntersectionObserver"))&&R(r,e,l,o,`new ${u}()`,"Effect.async or Effect.asyncInterrupt for DOM observation")}let s=o.getText().includes("child_process");for(let l of o.getDescendantsOfKind(D.CallExpression)){let u=l.getExpression().getText();(u.includes("child_process")&&u.endsWith(".fork")||s&&u==="fork")&&R(r,e,l,o,"child_process.fork","Worker.make or @effect/platform Worker")}for(let l of o.getDescendantsOfKind(D.NewExpression)){let u=l.getExpression().getText();(u==="AbortController"||u.includes("AbortController"))&&R(r,e,l,o,"new AbortController()","Effect.Scoped or Effect.interruptible for cancellation")}let a=o.getText(),i=a.includes("child_process");for(let l of o.getDescendantsOfKind(D.CallExpression)){let u=l.getExpression().getText();((u.endsWith(".exec")||u.endsWith(".execSync")||u.endsWith(".spawn"))&&u.includes("child_process")||i&&(u==="exec"||u==="execSync"||u==="spawn"))&&R(r,e,l,o,"child_process.exec/spawn","@effect/platform CommandExecutor or Effect.promise")}for(let l of o.getDescendantsOfKind(D.PropertyAccessExpression))l.getExpression().getText()==="process"&&l.getName()==="env"&&R(r,e,l,o,"process.env","Config.string or Config.forEffect for typed config");if(a.includes("rxjs")||a.includes("Observable"))for(let l of o.getDescendantsOfKind(D.CallExpression)){let u=l.getExpression().getText();(u.includes("Observable")||u.includes("of")&&u.includes("rxjs"))&&R(r,e,l,o,"RxJS Observable","Stream from @effect/platform or Effect Stream")}for(let l of o.getDescendantsOfKind(D.NewExpression)){let u=l.getExpression().getText();(u.includes("Observable")||u.includes("Subject"))&&R(r,e,l,o,"RxJS Observable/Subject","Stream or PubSub for Effect")}for(let l of o.getDescendantsOfKind(D.CallExpression)){let u=l.getExpression().getText();(u==="requestAnimationFrame"||u.endsWith(".requestAnimationFrame"))&&R(r,e,l,o,"requestAnimationFrame","Effect.async or Effect.sync + queueMicrotask for scheduling")}for(let l of o.getDescendantsOfKind(D.CallExpression)){let u=l.getExpression().getText();(u.includes("crypto.")||u.includes("randomBytes")||u.includes("scrypt")||u.includes("pbkdf2"))&&l.getArguments().length>=2&&R(r,e,l,o,"crypto (callback)","Effect.promise or crypto.webcrypto / node:crypto promises")}for(let l of o.getDescendantsOfKind(D.CallExpression)){let u=l.getExpression().getText();(u==="createReadStream"||u==="createWriteStream"||u.endsWith(".createReadStream")||u.endsWith(".createWriteStream"))&&R(r,e,l,o,u,"Stream.fromReadable or @effect/platform FileSystem/Stream")}for(let l of o.getDescendantsOfKind(D.CallExpression)){let u=l.getExpression().getText();u.includes("cluster")&&u.endsWith(".fork")&&R(r,e,l,o,"cluster.fork","Worker.make or @effect/platform Worker pool")}for(let l of o.getDescendantsOfKind(D.CallExpression)){let f=l.getExpression(),u=f.getText();if(u==="createServer"||u==="connect"||u.endsWith(".createServer")||u.endsWith(".connect")){let p=f.getText();(p.includes("net")||p.includes("tls"))&&R(r,e,l,o,p,"Effect.async or @effect/platform Socket/Server")}}for(let l of o.getDescendantsOfKind(D.CallExpression)){let u=l.getExpression().getText();u.includes("zlib.")&&(u.includes("deflate")||u.includes("inflate")||u.includes("gzip")||u.includes("gunzip"))&&R(r,e,l,o,"zlib (callback)","Effect.promise or zlib.promises")}for(let l of o.getDescendantsOfKind(D.CallExpression)){let u=l.getExpression().getText();(u==="createInterface"||u.endsWith(".createInterface"))&&u.includes("readline")&&R(r,e,l,o,"readline.createInterface","Effect.async or Stream for line-by-line reading")}let d=o.getText().includes("stream");for(let l of o.getDescendantsOfKind(D.CallExpression)){let u=l.getExpression().getText();(u.endsWith(".pipeline")&&u.includes("stream")||d&&u==="pipeline")&&R(r,e,l,o,"stream.pipeline (callback)","Effect.promise or stream.promises.pipeline")}for(let l of o.getDescendantsOfKind(D.CallExpression)){let u=l.getExpression().getText();(u==="once"||u.endsWith(".once"))&&(u.includes("events")||o.getText().includes("from 'events'"))&&R(r,e,l,o,"events.once","Effect.async for one-shot event")}for(let l of o.getDescendantsOfKind(D.CallExpression)){let f=l.getExpression(),u=f.getText();(u==="watch"||u==="watchFile"||u.endsWith(".watch")||u.endsWith(".watchFile"))&&(u.includes("fs")||f.getText().includes("fs."))&&R(r,e,l,o,"fs.watch / fs.watchFile","Effect.async or fs.watch with EventEmitter")}for(let l of o.getDescendantsOfKind(D.CallExpression)){let u=l.getExpression().getText();(u.includes("runInNewContext")||u.includes("runInContext")||u.includes("runInThisContext"))&&u.includes("vm")&&R(r,e,l,o,"vm.runIn*","Effect.sync for isolated code execution")}for(let l of o.getDescendantsOfKind(D.CallExpression)){let u=l.getExpression().getText();(u==="parse"||u.endsWith(".parse"))&&u.includes("url")&&R(r,e,l,o,"url.parse (deprecated)","new URL() or URL.parse for standard parsing")}for(let l of o.getDescendantsOfKind(D.CallExpression)){let u=l.getExpression().getText();(u.endsWith(".spawnSync")&&u.includes("child_process")||o.getText().includes("child_process")&&u==="spawnSync")&&R(r,e,l,o,"child_process.spawnSync","@effect/platform CommandExecutor or Effect.promise")}for(let l of o.getDescendantsOfKind(D.CallExpression)){let u=l.getExpression().getText();(u==="glob"||u.endsWith(".glob"))&&o.getText().includes("glob")&&l.getArguments().length>=2&&R(r,e,l,o,"glob (callback)","Effect.promise or glob promise API")}for(let l of o.getDescendantsOfKind(D.CallExpression)){let u=l.getExpression().getText(),p=u.includes("assert")&&u.endsWith(".throws"),g=u.endsWith(".rejects")&&u.includes("expect");(p||g)&&R(r,e,l,o,g?"expect().rejects":"assert.throws","Effect.runPromiseExit + Exit.match for testing Effect failures")}for(let l of o.getDescendantsOfKind(D.CallExpression)){let u=l.getExpression().getText();u.includes("tls")&&(u.endsWith(".connect")||u.endsWith(".createServer"))&&R(r,e,l,o,"tls.connect / tls.createServer","Effect.async or @effect/platform Socket/TLS")}return r}async function Xa(e,t){let r=t?.extensions??[".ts",".tsx"],n=[],o=0;async function s(a){let i=await Ja(a,{withFileTypes:!0}).catch(()=>[]);for(let c of i){let d=Ya(a,c.name);if(c.isDirectory())c.name!=="node_modules"&&c.name!==".git"&&c.name!=="dist"&&await s(d);else if(c.isFile()&&r.includes(Qa(c.name))){o++;try{n.push(...fo(d))}catch{}}}}return await s(e),{opportunities:n,fileCount:o}}function ec(e){let t=[];t.push("Migration Opportunities Found:"),t.push("");for(let r of e.opportunities)t.push(` ${r.filePath}:${r.line}:${r.column} ${r.pattern}`),t.push(` \u2192 ${r.suggestion}`),r.codeSnippet&&t.push(` Snippet: ${r.codeSnippet.slice(0,60)}...`),t.push("");return t.push(`Total: ${e.opportunities.length} opportunities in ${e.fileCount} files`),t.join(`
|
|
6
|
-
`)}import{Effect as
|
|
7
|
-
`)}import{Option as
|
|
8
|
-
`)}function
|
|
9
|
-
`)}var
|
|
10
|
-
<${o.successType}, ${o.errorType}, ${o.requirementsType}>`}e.semanticRole&&e.semanticRole!=="unknown"&&e.semanticRole!=="constructor"&&(
|
|
11
|
-
(${e.semanticRole})`)}return
|
|
12
|
-
`+
|
|
13
|
-
`)),
|
|
14
|
-
`)}var
|
|
15
|
-
`)}var
|
|
16
|
-
`)}var
|
|
4
|
+
`),n=[],r,o=[],s,a=/@(param|returns?|throws?|exception|example)\s*(.*)/gi,i;for(;(i=a.exec(t))!==null;){let c=i[1].toLowerCase(),d=i[2].trim();if(c==="param"){let l=/^(?:\{[^}]*\}\s*)?(\[?\w+(?:=[^\]]*)?]?)\s*(?:-\s*(.*))?$/.exec(d);if(l){let f=l[1].replace(/^\[|\]$/g,"").replace(/=.*/,""),u=l[2]?.trim();n.push(u?{name:f,description:u}:{name:f})}}else if(c==="returns"||c==="return")r=d.replace(/^\{[^}]*\}\s*/,"").trim()||void 0;else if(c==="throws"||c==="throw"||c==="exception"){let l=d.replace(/^\{[^}]*\}\s*/,"").trim();l&&o.push(l)}else if(c==="example"){let l=i.index+i[0].length,f=/\n\s*@\w/.exec(t.slice(l));f?s=t.slice(i.index+i[0].length-d.length,l+f.index).trim()||void 0:s=t.slice(i.index+i[0].length-d.length).trim()||void 0}}if(!(n.length===0&&!r&&o.length===0&&!s))return{params:n,returns:r,throws:o,example:s}}var Br=e=>{let t=e.getParent(),{SyntaxKind:n}=I();if(t){let r=t.getKind();if(r===n.VariableDeclaration)return Ue(t);if(r===n.ArrowFunction){let o=t.getParent();if(o?.getKind()===n.VariableDeclaration)return Ue(o)}}};function qr(e){return e.endsWith(".js")||e.endsWith(".jsx")}var jt=e=>{let t=e.getParent(),{SyntaxKind:n}=I();if(t?.getKind()===n.VariableDeclaration)return t.getName()},Ve=e=>{let{SyntaxKind:t}=I(),n=s=>{let a=s;for(;a!==void 0;){if(a.getKind()===t.VariableDeclaration)return a.getName();a=a.getParent()}},r=e.getParent();if(r){let s=r.getKind();if(s===t.VariableDeclaration)return r.getName();if(s===t.AwaitExpression){let a=r.getParent();if(a?.getKind()===t.VariableDeclaration)return a.getName()}if(s===t.PropertyAssignment){let i=r.getName(),c=n(r);return c?`${c}.${i}`:i}if(s===t.ArrowFunction){let a=r.getParent();if(a?.getKind()===t.VariableDeclaration)return a.getName();if(a?.getKind()===t.PropertyAssignment){let c=a.getName(),d=n(a);return d?`${d}.${c}`:c}}}let o=e;for(let s=0;o&&s<6&&(o=o.getParent(),!!o);s++){let a=o.getKind();if(a===t.VariableDeclaration)return o.getName();if(a===t.PropertyAssignment){let c=o.getName(),d=n(o);return d?`${d}.${c}`:c}if(a===t.Block||a===t.SourceFile)break}},_r=e=>{let{SyntaxKind:t}=I(),n=e.getParent();for(let r=0;n&&r<10;r++){if(n.getKind()===t.CallExpression){let o=n,s=o.getExpression().getText();if(s==="Effect.fn"||s.endsWith(".fn")){let a=o.getArguments();if(a.length>0){let i=a[0].getText(),c=/^["'](.+)["']$/.exec(i);if(c?.[1])return c[1]}}}n=n.getParent()}},jr=()=>({totalEffects:0,parallelCount:0,raceCount:0,errorHandlerCount:0,retryCount:0,timeoutCount:0,resourceCount:0,loopCount:0,conditionalCount:0,layerCount:0,interruptionCount:0,unknownCount:0,decisionCount:0,switchCount:0,tryCatchCount:0,terminalCount:0,opaqueCount:0}),_=60;function j(e,t=_){return e.length<=t?e:`${e.slice(0,t)}\u2026`}var ve=j;function qi(e){let t=e.replace(/\(.*$/,""),n=t.split(".");if(n.length<=1)return t;let r=n[0]??"";return Ct.has(r)||qt.has(r)?n[n.length-1]??t:t}function z(e,t){switch(e.type){case"effect":{let n=qi(e.callee);return t?ve(`${t} <- ${n}`,60):e.name?ve(`${e.name} <- ${n}`,60):ve(n,60)}case"generator":return`Generator (${e.yields.length} yields)`;case"pipe":return`Pipe (${e.transformations.length} steps)`;case"parallel":return`${e.callee} (${e.children.length})`;case"race":return`${e.callee} (${e.children.length} racing)`;case"error-handler":return e.name?`${e.name}: ${e.handlerType}`:e.handlerType;case"retry":return e.schedule?`retry: ${e.schedule}`:"retry";case"timeout":return e.duration?`timeout: ${e.duration}`:"timeout";case"resource":return"Resource";case"conditional":return ve(e.condition,30);case"loop":return e.iterSource?ve(`${e.loopType}(${e.iterSource})`,60):e.loopType;case"layer":return e.isMerged?"Layer (merged)":"Layer";case"stream":{let r=["Stream",...e.pipeline.map(o=>o.operation)];return e.sink&&r.push(e.sink),ve(r.join(" \u2192 "),60)}case"concurrency-primitive":return`${e.primitive}.${e.operation}`;case"fiber":{let n=e.operation;return e.isDaemon?`${n} (daemon)`:e.isScoped?`${n} (scoped)`:n}case"transform":return e.transformType;case"match":return`Match.${e.matchOp}`;case"cause":return`Cause.${e.causeOp}`;case"exit":return`Exit.${e.exitOp}`;case"schedule":return`Schedule.${e.scheduleOp}`;case"interruption":return e.interruptionType;case"channel":{let n=e.pipeline.map(r=>r.operation);return n.length>0?`Channel: ${n.join(" \u2192 ")}`:"Channel"}case"sink":{let n=e.pipeline.map(r=>r.operation);return n.length>0?`Sink: ${n.join(" \u2192 ")}`:"Sink"}case"decision":return ve(e.condition,30);case"switch":return`switch(${ve(e.expression,25)})`;case"try-catch":return"try/catch";case"terminal":return e.label?`${e.terminalKind} ${e.label}`:e.terminalKind;case"opaque":return`Opaque: ${ve(e.reason,25)}`;case"unknown":return`Unknown: ${ve(e.reason,30)}`}}function G(e){switch(e.type){case"effect":{if(e.serviceCall||e.serviceMethod)return"service-call";let t=e.description?.toLowerCase()??"";if(t.includes("service"))return"service-call";if(t.includes("layer")||e.provideKind==="layer")return"layer";let n=e.callee.toLowerCase();return/^[A-Z][A-Za-z0-9_]*$/.test(e.callee)&&!e.constructorKind?"environment":n.includes("sync")||n.includes("promise")||n.includes("async")||n.includes("log")||n.includes("console")?"side-effect":n.includes("succeed")||n.includes("fail")||n.includes("die")||n.includes("void")||n.includes("never")||n.includes("gen")||n.includes("make")||e.constructorKind?"constructor":"side-effect"}case"generator":case"pipe":return"constructor";case"parallel":case"race":case"concurrency-primitive":return"concurrency";case"error-handler":case"cause":case"exit":return"error-handler";case"retry":case"timeout":case"schedule":return"scheduling";case"resource":return"resource";case"conditional":case"loop":case"match":case"decision":case"switch":case"terminal":return"control-flow";case"try-catch":return"error-handler";case"opaque":return"unknown";case"layer":return"layer";case"stream":case"channel":case"sink":return"stream";case"fiber":case"interruption":return"fiber";case"transform":return"transform";case"unknown":return"unknown"}}import{existsSync as _i}from"fs";import{dirname as $n,resolve as vt,join as Me,sep as zr}from"path";var Hr=new WeakMap,Ur=new WeakMap;function zt(e){let t=new Set;for(let n of e.getExportDeclarations()){let r=n.getModuleSpecifierValue();if(!(!r||!Fe(r))){if(n.isNamespaceExport()){Fn.forEach(o=>t.add(o));continue}for(let o of n.getNamedExports()){t.add(o.getName());let s=o.getAliasNode()?.getText();s&&t.add(s)}}}return t}function Ge(e,t,n){if(!n.startsWith("."))return;let r=$n(t),o=vt(r,n),s=[o,`${o}.ts`,`${o}.tsx`,`${o}.js`,`${o}.jsx`,Me(o,"index.ts"),Me(o,"index.tsx"),Me(o,"index.js"),Me(o,"index.jsx")];for(let a of s){let i=e.getSourceFile(a);if(i)return i}}function wt(e,t){if(!t.startsWith("."))return;let n=$n(e),r=vt(n,t);return[r,`${r}.ts`,`${r}.tsx`,`${r}.js`,`${r}.jsx`,Me(r,"index.ts"),Me(r,"index.tsx"),Me(r,"index.js"),Me(r,"index.jsx")].find(s=>_i(s))}function Ht(e,t,n){if(!n||!t.startsWith("."))return!1;let r=t.replace(/\\/g,"/"),o=vt($n(e),t),s=vt(o),a=vt(n);return s===a||s.startsWith(a+zr)?!0:e==="temp.ts"||e.endsWith(`${zr}temp.ts`)?r.startsWith("./internal/")||r.startsWith("../internal/"):!1}function ji(e){let t=new Set(Fn),n=e.getProject(),r=e.getFilePath();for(let o of e.getImportDeclarations()){let s=o.getModuleSpecifierValue();if(Fe(s)){let a=o.getDefaultImport();a&&t.add(a.getText());let i=o.getNamespaceImport();i&&t.add(i.getText());for(let c of o.getNamedImports()){let d=c.getAliasNode()?.getText();t.add(d??c.getName())}continue}if(s.startsWith(".")){let a=Ge(n,r,s);if(!a)continue;let i=zt(a),c=[],d=o.getDefaultImport();if(d){let u=d.getText();c.push({name:u,localName:u})}let l=o.getNamespaceImport();if(l){let u=l.getText();c.push({name:u,localName:u})}for(let u of o.getNamedImports())c.push({name:u.getName(),localName:u.getAliasNode()?.getText()??u.getName()});let f=!1;for(let u of c)i.has(u.name)?t.add(u.localName):f=!0;if(f)for(let u of c)!i.has(u.name)&&Ln(a,u.name,n,3)&&t.add(u.localName)}}return t}function Dn(e,t){let n=ji(e);for(let r of e.getImportDeclarations()){let o=r.getModuleSpecifierValue(),s=r.getNamespaceImport();if(!s)continue;let a=s.getText();if(o.startsWith("effect")||o.startsWith("@effect/")){n.add(a);continue}if(Ht(e.getFilePath(),o,t)){n.add(a);continue}let i=o.replace(/\.(js|ts)$/,"").split("/").pop()??"";Dr.has(i)&&n.add(a)}return n}var zi=new Set(["BigDecimal","BigInt","Brand","Cause","Chunk","Data","Exit","Option","Either","HashMap","HashSet","List","Redacted"]);function Gr(e){let t=new Set;for(let n of e.getImportDeclarations()){let s=n.getModuleSpecifierValue().replace(/\\/g,"/").replace(/\.(js|ts|tsx|jsx)$/,"").split("/").pop()??"";if(!zi.has(s))continue;let a=n.getDefaultImport();a&&t.add(a.getText());let i=n.getNamespaceImport();i&&t.add(i.getText());for(let c of n.getNamedImports())t.add(c.getAliasNode()?.getText()??c.getName())}return t}function Oe(e){let t=Hr.get(e);return t||(t=Dn(e),Hr.set(e,t)),t}var Vr=new WeakMap;function Hi(e){let t=e.replace(/\\/g,"/").replace(/\.(js|ts|mts|cts)$/,"");return t==="effect"||t.endsWith("/Effect")?"Effect":(t.split("/").pop()??"")||"Effect"}function Ui(e){let t=Vr.get(e);if(t)return t;t=new Map;for(let n of e.getImportDeclarations()){let r=n.getModuleSpecifierValue();if(!r||!Fe(r))continue;let o=n.getNamespaceImport();if(!o)continue;let s=o.getText(),a=Hi(r);t.set(s,a)}return Vr.set(e,t),t}function Pn(e,t){let n=e.indexOf(".");if(n<=0)return e;let r=e.slice(0,n),o=e.slice(n+1),a=Ui(t).get(r);return a?`${a}.${o}`:e}function Ln(e,t,n,r){if(r<=0)return!1;for(let o of e.getExportDeclarations()){let s=o.getModuleSpecifierValue();if(!s)continue;let a;if(o.isNamespaceExport())a=t;else for(let i of o.getNamedExports()){if(i.getAliasNode()?.getText()===t){a=i.getName();break}if(i.getName()===t){a=t;break}}if(a!==void 0){if(Fe(s))return!0;if(s.startsWith(".")){let i=Ge(n,e.getFilePath(),s);if(i&&(zt(i).has(a)||Ln(i,a,n,r-1)))return!0}}}return!1}function Vi(e,t){let n=Ur.get(t);n||(n=new Map,Ur.set(t,n));let r=e.indexOf("."),o=r>0?e.slice(0,r):e,s=n.get(o);if(s!==void 0)return s;let a=!1;try{for(let i of t.getImportDeclarations()){let c=i.getModuleSpecifierValue();if(i.getNamespaceImport()?.getText()===o){a=Fe(c);break}if(i.getDefaultImport()?.getText()===o){a=Fe(c);break}for(let f of i.getNamedImports())if((f.getAliasNode()?.getText()??f.getName())===o){if(Fe(c))a=!0;else if(c.startsWith(".")){let g=Ge(t.getProject(),t.getFilePath(),c);g&&(zt(g).has(f.getName())?a=!0:a=Ln(g,f.getName(),t.getProject(),3))}break}if(a)break}}catch{a=!1}return n.set(o,a),a}function Gi(e,t){let r=e.getExpression().getText();for(let o of t.getImportDeclarations()){let s=o.getModuleSpecifierValue();if(o.getNamespaceImport()?.getText()===r||o.getDefaultImport()?.getText()===r)return s;for(let c of o.getNamedImports())if((c.getAliasNode()?.getText()??c.getName())===r)return s}}function st(e,t,n,r){let o=e.getExpression(),s=o.getText();if(An.some(d=>s.startsWith(d))||s.startsWith("pipe("))return!0;for(let d of n)if(s.startsWith(`${d}.`))return!0;let{SyntaxKind:a}=I();if(o.getKind()!==a.PropertyAccessExpression)return!1;let i=o,c=Gi(i,t);if(!c)return!1;if(Fe(c))return!0;if(c.startsWith(".")){let d=Ge(t.getProject(),t.getFilePath(),c);if(d){let l=zt(d),f=i.getExpression().getText();for(let u of t.getImportDeclarations())if(u.getModuleSpecifierValue()===c){for(let p of u.getNamedImports())if((p.getAliasNode()?.getText()??p.getName())===f&&l.has(p.getName()))return!0}}if(Ht(t.getFilePath(),c,r))return!0}return!1}function Ut(e,t,n){if(An.some(r=>e.startsWith(r))||e.startsWith("pipe("))return!0;if(t){for(let r of t)if(e.startsWith(`${r}.`))return!0}return n&&e.includes(".")?Vi(e,n):!1}var Ji=new Set(["createWorkflow","createSagaWorkflow","runSaga"]),Yi=e=>Array.from(Ji).some(t=>e===t||e.endsWith(`.${t}`)),Jr=e=>{let t=e.getExpression();if(t.getKind()!==I().SyntaxKind.PropertyAccessExpression)return!1;let n=t,r=e.getArguments();if(n.getName()!=="make"||r.length<3||!r[2])return!1;let o=r[2].getKind(),{SyntaxKind:s}=I();return o===s.ArrowFunction||o===s.FunctionExpression};function Xr(e,t){let n=e.replace(/\\/g,"/");return!!(n==="@effect/workflow"||n==="effect/workflow"||n.endsWith("/workflow")||n.includes("/workflow/")||n.endsWith("/Workflow.js")||n.endsWith("/Workflow.ts")||n.endsWith("/Activity.js")||n.endsWith("/Activity.ts")||n.startsWith(".")&&(n.endsWith("Workflow.js")||n.endsWith("Workflow.ts")||n.endsWith("Activity.js")||n.endsWith("Activity.ts")))}function Qi(e,t,n){return e!=="Workflow"?!1:Xr(t,n)}function Zi(e,t,n){return e!=="Activity"?!1:Xr(t,n)}function eo(e,t){let{SyntaxKind:n}=I(),r=e.getArguments();if(r.length!==1||!r[0])return!1;let o=r[0];if(o.getKind()!==n.ObjectLiteralExpression)return!1;let a=o.getProperties(),i=new Set(t);for(let c of a)if(c.getKind()===n.PropertyAssignment){let d=c.getName();if(i.has(d))return!0}return!1}function Xi(e,t,n){let{SyntaxKind:r}=I(),o=e.getExpression();if(o.getKind()!==r.PropertyAccessExpression)return!1;let s=o;if(s.getName()!=="make")return!1;let a=s.getExpression().getText(),i=t.get(a);return!i||!Qi(a,i,n)?!1:eo(e,["name","payload","idempotencyKey"])}function ea(e,t,n){let{SyntaxKind:r}=I(),o=e.getExpression();if(o.getKind()!==r.PropertyAccessExpression)return!1;let s=o;if(s.getName()!=="make")return!1;let a=s.getExpression().getText(),i=t.get(a);return!i||!Zi(a,i,n)?!1:eo(e,["name","execute"])}var to=(e,t)=>{let n=e.getExpression();if(n.getKind()!==I().SyntaxKind.PropertyAccessExpression||n.getName()!=="run")return null;let o=e.getArguments();if(o.length<1||!o[0])return null;let s=o[0],{SyntaxKind:a}=I();if(s.getKind()===a.CallExpression){let l=s;return Jr(l)?l.getArguments()[2]??null:null}if(s.getKind()!==a.Identifier)return null;let c=s.getText(),d=t.getDescendantsOfKind(a.VariableDeclaration);for(let l of d){if(l.getName()!==c)continue;let f=l.getInitializer();if(f?.getKind()===a.CallExpression&&Jr(f))return f.getArguments()[2]??null}return null},ta=e=>{let{SyntaxKind:t}=I(),n=e.getParent();for(;n;){if(n.getKind()===t.CallExpression){let o=n.getExpression().getText();if(o.includes(".gen")||o==="gen")return!0}n=n.getParent()}return!1},na=e=>{let{SyntaxKind:t}=I();return e.getFirstAncestorByKind(t.VariableStatement)?.getParent()?.getKind()===t.SourceFile},ra=e=>{let{SyntaxKind:t}=I(),n=e.getInitializer();return n?n.getKind()===t.YieldExpression||n.getKind()===t.AwaitExpression&&n.getExpression().getKind()===t.YieldExpression:!1},Yr=e=>{let{SyntaxKind:t}=I();if(e.getKind()===t.CallExpression)return e;if(e.getKind()===t.AwaitExpression){let n=e.getExpression();if(n.getKind()===t.CallExpression)return n}},H=(e,t)=>({discoveryConfidence:e,discoveryReason:t}),oa=["Effect<","Layer<","Layer.Layer<","Stream<","Stream.Stream<","Channel<","Channel.Channel<","Sink<","Sink.Sink<","STM<","STM.STM<","Schedule<","Schedule.Schedule<"],Vt=e=>e!==void 0&&oa.some(t=>e.includes(t)),Qr={low:0,medium:1,high:2},Mn=e=>{let t=e.getExpression().getText();return t.includes(".runPromise")||t.includes(".runPromiseExit")||t.includes(".runSync")||t.includes(".runSyncExit")||t.includes(".runFork")||t.includes(".runCallback")||t.includes(".runMain")||t.includes("Runtime.runPromise")||t.includes("Runtime.runSync")||t.includes("Runtime.runFork")};function Zr(e){let t=e.getBody?.();if(!t)return!1;let n=t.getText();return n.includes(".runMain")||n.includes(".runPromise")||n.includes(".runSync")||n.includes(".runFork")||n.includes("Runtime.runPromise")||n.includes("Runtime.runSync")||n.includes("NodeRuntime.runMain")||n.includes("BunRuntime.runMain")||n.includes("DenoRuntime.runMain")}function sa(e,t){let n=e.getExpression();if(n.getKind()!==I().SyntaxKind.Identifier)return!1;let s=n.getSymbol()?.getValueDeclaration();if(!s)return!1;let a=s.getKind(),{SyntaxKind:i}=I();if(a===i.FunctionDeclaration||a===i.ArrowFunction||a===i.FunctionExpression)return Zr(s);if(a===i.VariableDeclaration){let c=s.getInitializer();if(c&&(c.getKind()===i.ArrowFunction||c.getKind()===i.FunctionExpression))return Zr(c)}return!1}function ia(e){let t=e.getExpression();if(e.getArguments().length!==1)return!1;let{SyntaxKind:n}=I();if(t.getKind()!==n.CallExpression)return!1;let r=t;if(r.getArguments().length!==1)return!1;let o=r.getExpression().getText();return o.includes(".runPromise")||o.includes(".runSync")||o.includes(".runFork")||o.includes(".runCallback")||o.includes("Runtime.runPromise")||o.includes("Runtime.runSync")||o.includes("Runtime.runFork")}var On=(e,t)=>{let n=[],{SyntaxKind:r}=I(),o=new Set,s=new Set,a=Dn(e,t.knownEffectInternalsRoot),i=Gr(e),c=new Map;for(let E of e.getImportDeclarations()){let y=E.getModuleSpecifierValue(),C=E.getDefaultImport();C&&c.set(C.getText(),y);let w=E.getNamespaceImport();w&&c.set(w.getText(),y);for(let b of E.getNamedImports())c.set(b.getAliasNode()?.getText()??b.getName(),y)}let d=E=>{let y=c.get(E);if(y){if(y.startsWith("effect")||y.startsWith("@effect/"))return H("high",`imported from ${y}`);if(Ht(e.getFilePath(),y,t.knownEffectInternalsRoot))return H("high","namespace import resolved under knownEffectInternalsRoot");if(y.startsWith(".")&&/(?:^|\/)Effect(?:\.[jt]sx?)?$/.test(y))return H("high",`relative Effect module namespace import (${y})`)}},l=E=>{let y=w=>{let b=w.getDescendantsOfKind(r.PropertyAccessExpression);for(let F of b){let O=F.getExpression().getText();if(a.has(O)&&!i.has(O))return d(O)?.discoveryConfidence==="high"?H("high",`function body uses ${O}.* from trusted Effect alias`):H("medium",`function body uses Effect-like alias ${O}.*`)}let P=w.getDescendantsOfKind(r.CallExpression);for(let F of P){let O=F.getExpression();if(O.getKind()===r.Identifier){let A=O.getText();if(a.has(A)&&!i.has(A))return d(A)?.discoveryConfidence==="high"?H("high",`function body calls trusted Effect import ${A}(...)`):H("medium",`function body calls Effect-like import ${A}(...)`)}}};if(E.getKind()===r.ArrowFunction||E.getKind()===r.FunctionExpression){let b=E.getBody();if(b.getKind()===r.Block){let P=y(b);if(P)return P}else{let P=y(b);if(P)return P}}let C=Yr(E);if(C){let w=C.getExpression(),b=w.getText();if(w.getKind()===r.Identifier){let P=b;if(a.has(P)&&!i.has(P))return d(P)??H("high",`named import call (${P})`);if(P==="pipe")return H("medium","exact pipe() call detection")}if(w.getKind()===r.PropertyAccessExpression){let P=w,F=P.getExpression().getText();if(a.has(F)&&!i.has(F))return d(F)??H("medium",`Effect-like namespace prefix (${F}.*)`);if(P.getName()==="pipe")return H("medium","exact .pipe() call detection")}}if(E.getKind()===r.PropertyAccessExpression){let b=E.getExpression().getText();if(a.has(b)&&!i.has(b))return d(b)??H("medium",`Effect-like namespace property access (${b}.*)`)}if(E.getKind()===r.AwaitExpression){let w=E.getExpression();if(w.getKind()===r.CallExpression)return l(w)}return H("low","heuristic direct initializer match")},f=E=>{let C=(b=>b.getTypeNode?.()?.getText())(E);if(Vt(C))return H("high","explicit Effect-family type annotation");let w=E.getKind()===r.VariableDeclaration?E.getFirstAncestorByKind(r.VariableStatement)?.isExported()??!1:E.getKind()===r.PropertyDeclaration||E.getKind()===r.MethodDeclaration||E.getKind()===r.GetAccessor?E.getFirstAncestorByKind(r.ClassDeclaration)?.isExported()??!1:!1;if(E.getKind()===r.VariableDeclaration||E.getKind()===r.PropertyDeclaration){let b=E.getInitializer();if(b&&(b.getKind()===r.ArrowFunction||b.getKind()===r.FunctionExpression)){let F=b.getReturnTypeNode()?.getText();if(Vt(F))return H("high","function return type annotated as Effect-family");if(w&&C)return H("medium","explicit exported function API type signature")}if(b?.getKind()===r.CallExpression){let F=b.getTypeArguments().map(O=>O.getText()).join(" ");if(Vt(F))return H("high","call type arguments reference Effect-family types");if(w&&C)return H("medium","explicit exported call-based API type signature")}}if(E.getKind()===r.MethodDeclaration||E.getKind()===r.GetAccessor){let b=E.getReturnTypeNode?.()?.getText();if(Vt(b))return H("high","method/getter return type annotated as Effect-family");if(w&&C)return H("medium","explicit exported method/getter API type signature")}},u=E=>{let y=E.node,C=y.getKind();return C===r.CallExpression?!0:C===r.VariableDeclaration?y.getFirstAncestorByKind(r.VariableStatement)?.isExported()??!1:C===r.FunctionDeclaration||C===r.ClassDeclaration?y.isExported():C===r.PropertyDeclaration||C===r.MethodDeclaration||C===r.GetAccessor?y.getFirstAncestorByKind(r.ClassDeclaration)?.isExported()??!1:!0},p=E=>{for(let y of E){let C=y.getExpression();if(C&&ne(C,a,i))return l(C)}return H("low","heuristic method return match")},g=e.getFilePath(),m=e.getDescendantsOfKind(r.VariableDeclaration);for(let E of m){let y=E.getInitializer();if(y?.getKind()===r.CallExpression&&Yi(y.getExpression().getText())&&s.add(E.getName()),t.enableEffectWorkflow&&y?.getKind()===r.CallExpression){let C=y;(Xi(C,c,g)||ea(C,c,g))&&s.add(E.getName())}}let h=e.getDescendantsOfKind(r.CallExpression);for(let E of h){let y=E.getExpression(),C=y.getText(),w=E.getStart(),b=!1;if(y.getKind()===r.Identifier)b=s.has(C);else if(y.getKind()===r.PropertyAccessExpression){let F=y,O=F.getExpression().getText(),A=F.getName();if(b=s.has(O)&&A==="run",t.enableEffectWorkflow&&!b&&A==="run"&&E.getArguments().length===1&&!C.includes("runPromise")&&!C.includes("runSync")&&!C.includes("runFork")&&!C.includes("runCallback")&&!o.has(w)){let W=Ve(E)??`workflow-${n.length+1}`;n.push({name:W,node:E,type:"run",...H("low","workflow-like .run(...) shape heuristic")}),o.add(w);continue}}if(b&&!o.has(w)){let F=Ve(E)??`workflow-${n.length+1}`;n.push({name:F,node:E,type:"run",...H("medium","workflow builder invocation")}),o.add(w);continue}if(t.enableEffectWorkflow&&y.getKind()===r.PropertyAccessExpression){let F=y,O=F.getExpression().getText(),A=F.getName();if((A==="execute"||A==="executeEncoded")&&s.has(O)&&!o.has(w)){let B=Ve(E)??`${O}.${A}`;n.push({name:B,node:E,type:"workflow-execute",...H("medium","workflow/activity .execute entrypoint")}),o.add(w);continue}}if((C==="gen"||C.endsWith(".gen")&&st(E,e,a,t.knownEffectInternalsRoot))&&!o.has(w)){let F=Ve(E)??_r(E)??`program-${n.length+1}`;n.push({name:F,node:E,type:"generator",...C==="gen"?H("medium","unqualified gen(...) call"):H("high","Effect-like .gen(...) call")}),o.add(w)}let P=Ve(E);if(C.includes("pipe")&&aa(E,a)&&!o.has(w)&&y.getKind()!==r.PropertyAccessExpression&&P!==void 0&&!ta(E)&&(n.push({name:P,node:E,type:"pipe",...H("medium","exact pipe(...) call with Effect-like args")}),o.add(w)),(Mn(E)||ia(E))&&!o.has(w)){let F=Ve(E)??`run-${n.length+1}`;n.push({name:F,node:E,type:"run",...H("high","recognized Runtime/Effect run* entrypoint")}),o.add(w)}}for(let E of m){if(!na(E)||ra(E))continue;let y=E.getInitializer();if(y){let C=E.getName(),w=Yr(y);if(w&&Mn(w)||y.getKind()===r.ObjectLiteralExpression)continue;ne(y,a,i)&&!n.some(P=>P.name===C)&&n.push({name:C,node:E,type:"direct",...f(E)??l(y)})}}let x=e.getStatements();for(let E of x){if(E.getKind()!==r.ExpressionStatement)continue;let y=E.getExpression();if(y.getKind()!==r.CallExpression)continue;let C=y,w=C.getStart();if(o.has(w))continue;let b=C.getExpression(),P=b.getText();if(Mn(C)){let F=`run-${n.length+1}`;n.push({name:F,node:C,type:"run",...H("high","recognized top-level run* entrypoint")}),o.add(w);continue}if(P.endsWith(".pipe")||P==="pipe"){let F=C.getArguments(),O=F[F.length-1];if(!O)continue;let A=O.getText();if(A.includes(".runMain")||A.includes(".runPromise")||A.includes(".runSync")||A.includes(".runFork")){let B;b.getKind()===r.PropertyAccessExpression&&(B=b.getExpression().getText().split(".").pop());let J=B&&!n.some(Y=>Y.name===B)?B:`entrypoint-${n.length+1}`;n.push({name:J,node:C,type:"run",...H("medium","top-level pipe(...).run* terminator pattern")}),o.add(w)}}if(b.getKind()===r.Identifier&&C.getArguments().length>=1){let F=b.getText();sa(C,e)&&!n.some(A=>A.name===F)&&(n.push({name:F,node:C,type:"run",...H("low","indirect run wrapper body heuristic")}),o.add(w))}}let T=["Data.TaggedError","Data.TaggedClass","Data.Class","Data.Error","Schema.Class","Schema.TaggedClass","Schema.TaggedError","Schema.TaggedRequest","Context.Tag","Context.Reference","Effect.Service"],S=e.getDescendantsOfKind(r.ClassDeclaration);for(let E of S){let y=E.getName();if(!y||n.some(b=>b.name===y))continue;E.getHeritageClauses().some(b=>{let P=b.getText();return T.some(F=>P.includes(F))})&&n.push({name:y,node:E,type:"class",...H("medium","known Data/Schema/Context class pattern")})}let N=S.filter(E=>{let y=E.getParent();return y===e||y?.getParent()===e});for(let E of N){let y=E.getName()??"Anonymous",C=E.getMembers(),w=C.filter(F=>F.getKind()===r.PropertyDeclaration);for(let F of w){let O=F.getInitializer();if(!O)continue;let A=F.getName(),W=`${y}.${A}`;n.some(B=>B.name===W)||ne(O,a,i)&&n.push({name:W,node:F,type:"classProperty",...f(F)??l(O)})}let b=C.filter(F=>F.getKind()===r.MethodDeclaration);for(let F of b){let O=F.getName(),A=`${y}.${O}`;if(n.some(Y=>Y.name===A))continue;let W=F.getBody();if(!W)continue;let B=W.getDescendantsOfKind(r.ReturnStatement);B.some(Y=>{let de=Y.getExpression();return de?ne(de,a,i):!1})&&n.push({name:A,node:F,type:"classMethod",...f(F)??p(B)})}let P=C.filter(F=>F.getKind()===r.GetAccessor);for(let F of P){let O=F.getName(),A=`${y}.${O}`;if(n.some(Y=>Y.name===A))continue;let W=F.getBody();if(!W)continue;let B=W.getDescendantsOfKind(r.ReturnStatement);B.some(Y=>{let de=Y.getExpression();return de?ne(de,a,i):!1})&&n.push({name:A,node:F,type:"classMethod",...f(F)??p(B)})}}return n.filter(E=>{let y=t.minDiscoveryConfidence??"low",C=E.discoveryConfidence??"low";return!(Qr[C]<Qr[y]||t.onlyExportedPrograms&&!u(E))})},aa=(e,t)=>e.getArguments().map(o=>o.getText()).some(o=>[...t].some(s=>o.includes(`${s}.`)));function no(e){let{SyntaxKind:t}=I(),n=[],r=e.getProject().getTypeChecker(),o=e.getDescendantsOfKind(t.ClassDeclaration);for(let s of o){let a=s.getName();if(!a)continue;let i=s.getExtends();if(!i)continue;let c=i.getText();if(!c.includes("Context.Tag")&&!c.includes("Effect.Service"))continue;let d=i.getTypeArguments();if(d.length<2){let f=i.getExpression();f&&"getTypeArguments"in f&&typeof f.getTypeArguments=="function"&&(d=f.getTypeArguments())}if(d.length<2)continue;let l=d[1];if(l)try{let f=r.getTypeAtLocation(l),u=[],p=[];for(let x of f.getProperties()){let T=x.getName();if(T.startsWith("_")||T==="constructor")continue;r.getTypeOfSymbolAtLocation(x,l).getCallSignatures().length>0?u.push(T):p.push(T)}let g=s.getText(),m=g.includes("Equal.symbol")||g.includes("[Equal")||g.includes("equal("),h=g.includes("Hash.symbol")||g.includes("[Hash")||g.includes("hash(");n.push({tagId:a,methods:u,properties:p,...m?{hasCustomEquality:m}:{},...h?{hasCustomHash:h}:{}})}catch{}}for(let s of o){let a=s.getName();if(!a)continue;let i=s.getExtends();if(!i)continue;let c=i.getText();if(!c.includes("Data.Class")&&!c.includes("Data.TaggedClass")||n.some(u=>u.tagId===a))continue;let d=s.getText(),l=d.includes("Equal.symbol")||d.includes("[Equal")||d.includes("equal("),f=d.includes("Hash.symbol")||d.includes("[Hash")||d.includes("hash(");(l||f)&&n.push({tagId:a,methods:[],properties:[],hasCustomEquality:l,hasCustomHash:f})}return n}import{Effect as he,Option as kt}from"effect";import{Effect as Z,Option as ca}from"effect";var la=["Schema.decode","Schema.decodeUnknown","Schema.encode","Schema.validate","Schema.decodeOption","Schema.decodeEither","Schema.encodeUnknown","Schema.decodeSync","Schema.encodeSync","Schema.decodeUnknownSync","Schema.decodeUnknownOption","Schema.decodeUnknownEither","Schema.decodePromise","Schema.encodePromise","Schema.decodeUnknownPromise"],Jt=(e,t,n,r,o,s)=>Z.gen(function*(){let{SyntaxKind:a}=I(),i=e.getArguments(),c=e.getExpression(),d=c.getKind()===a.PropertyAccessExpression&&c.getName()==="pipe",l=d?c.getExpression():i[0],f=d?i:i.slice(1);if(!l)return[];let u=oo(l),p=u.getSourceFile(),g=p.getFilePath(),m=t.getProject();if(m.getSourceFile(g)){let C=m.getSourceFile(g);C&&(p=C)}else{let C=m.addSourceFileAtPath(g);C&&(p=C)}let h=yield*$(u,p,p.getFilePath(),r,o,s),x=[];for(let C of f)if(C){let w=yield*$(C,t,n,r,o,s);x.push(w)}let T,S=x.filter(C=>!(C.type==="effect"&&C.callee.includes("withSpan")));if(!T){for(let C of f)if(C){let w=C.getText();if(w.includes("withSpan")){let b=/withSpan\s*\(\s*["']([^"']+)["']/.exec(w);b?.[1]&&(T=b[1])}}}let N;try{let C=t.getProject().getTypeChecker(),w=[],b=Ie(l,C);b&&w.push(b);for(let P of f)if(P){let F=Ie(P,C);F&&w.push(F)}w.length>0&&(N=w)}catch{}let E={id:k(),type:"pipe",initial:h,transformations:S,...N?{typeFlow:N}:{},...T?{spanName:T}:{}};return[{...E,displayName:z(E),semanticRole:G(E)}]}),$=(e,t,n,r,o,s,a)=>Z.gen(function*(){let{SyntaxKind:i}=I();if(e.getKind()===i.ArrowFunction||e.getKind()===i.FunctionExpression){let l=e.getBody();if(!l){let u={id:k(),type:"unknown",reason:"Function has no body",sourceCode:e.getText().slice(0,100),location:K(e,n,r.includeLocations??!1)};return s.unknownCount++,u}if(l.getKind()===i.Block){let g=l.getStatements().find(m=>m.getKind()===i.ReturnStatement)?.getExpression();if(g)return yield*$(g,t,n,r,o,s,a)}else return yield*$(l,t,n,r,o,s,a);let f={id:k(),type:"unknown",reason:"Function does not return an Effect expression",sourceCode:e.getText().slice(0,100),location:K(e,n,r.includeLocations??!1)};return s.unknownCount++,f}if(e.getKind()===i.CallExpression)return yield*Wn(e,t,n,r,o,s,a);if(e.getKind()===i.PropertyAccessExpression){let d=e.getText();if(d==="Fiber.roots"||d==="Fiber.getCurrentFiber"){let l=d==="Fiber.roots"?"roots":"getCurrentFiber";return{id:k(),type:"fiber",operation:l,isScoped:!1,isDaemon:!1,location:K(e,n,r.includeLocations??!1)}}if(Ut(d,Oe(t),t)){let l={id:k(),type:"effect",callee:d,location:K(e,n,r.includeLocations??!1)};return s.totalEffects++,l}}if(e.getKind()===i.Identifier){let d={id:k(),type:"effect",callee:e.getText(),location:K(e,n,r.includeLocations??!1)};return s.totalEffects++,d}if(e.getKind()===i.ObjectLiteralExpression){let d=e,l=new Set(["onNone","onSome","onFailure","onSuccess","onLeft","onRight"]),f=d.getProperties(),u=[],p=!1;for(let g of f){if(g.getKind()!==i.PropertyAssignment)continue;let m=g,h=m.getName();if(!l.has(h))continue;p=!0;let x=m.getInitializer();if(x){let T=yield*$(x,t,n,r,o,s,a);u.push(T)}}if(p&&u.length>0)return u.length===1?u[0]:{id:k(),type:"parallel",callee:"match-handlers",mode:"sequential",children:u,location:K(e,n,r.includeLocations??!1)}}let c={id:k(),type:"unknown",reason:"Could not determine effect type",sourceCode:e.getText().slice(0,100),location:K(e,n,r.includeLocations??!1)};return s.unknownCount++,c}),Wn=(e,t,n,r,o,s,a)=>Z.gen(function*(){let{SyntaxKind:i}=I(),c=e.getExpression().getText(),d=Pn(c,t),l=/([A-Za-z_$][\w$]*)$/.exec(d)?.[1]??d,f=K(e,n,r.includeLocations??!1),u=c.endsWith(".pipe")&&c!=="pipe"&&c.startsWith("Effect.");if((c==="pipe"||u)&&e.getArguments().length>=1){let L=yield*Jt(e,t,n,r,o,s);if(L.length>0&&L[0])return L[0]}if(d==="Context.pick"||d==="Context.omit"){let L={id:k(),type:"effect",callee:d,description:"context",location:f};return s.totalEffects++,{...L,displayName:z(L),semanticRole:G(L)}}if(d.startsWith("Layer."))return yield*pa(e,d,t,n,r,o,s);if(d.startsWith("Stream."))return yield*ga(e,d,t,n,r,o,s);if(d.startsWith("Channel."))return yield*ha(e,d,t,n,r,o,s);if(c.startsWith("Sink."))return yield*Sa(e,c,t,n,r,o,s);if(c.startsWith("Queue.")||c.startsWith("PubSub.")||c.startsWith("Deferred.")||c.startsWith("Semaphore.")||c.startsWith("Mailbox.")||c.startsWith("SubscriptionRef.")||c.startsWith("RateLimiter.")||c.startsWith("PartitionedSemaphore.")||c.startsWith("FiberHandle.")||c.startsWith("FiberSet.")||c.startsWith("FiberMap.")||c.startsWith("Cache.")||c.startsWith("ScopedCache.")||c.startsWith("RcRef.")||c.includes(".RcRef.")||c.startsWith("RcMap.")||c.includes(".RcMap.")||c.startsWith("Reloadable.")||c.includes(".Reloadable.")||c.includes("makeLatch")||c.includes("Latch."))return yield*xa(e,c,t,n,r,o,s);if(Cn.some(L=>c.includes(L)||c.startsWith(L)))return yield*Ea(e,c,t,n,r,o,s);if(In.some(L=>c.includes(L)))return yield*ba(e,c,t,n,r,o,s);if(c.includes(".all")||c==="all")return yield*Na(e,c,t,n,r,o,s);if(c.includes(".race")||c==="race")return yield*Ta(e,c,t,n,r,o,s);if(xn.some(L=>c.includes(L)))return yield*va(e,c,t,n,r,o,s);if(c.includes(".retry"))return yield*wa(e,t,n,r,o,s);if(c.includes(".timeout"))return yield*ka(e,t,n,r,o,s);let g=new Set(["acquireRelease","acquireUseRelease","ensuring","addFinalizer","onExit","onError","parallelFinalizers","sequentialFinalizers","finalizersMask","using","withEarlyRelease"]),m=["acquireRelease","acquireUseRelease"],h=L=>g.has(L)||m.some(V=>L.startsWith(V));if(l==="pipe"&&e.getExpression().getKind()===i.PropertyAccessExpression){let V=e.getExpression().getExpression();if(V.getKind()===i.CallExpression){let be=V,Le=be.getExpression().getText(),ce=/([A-Za-z_$][\w$]*)$/.exec(Le)?.[1]??Le;if(h(ce))return yield*ro(be,ce,t,n,r,o,s)}}if(h(l))return yield*ro(e,l,t,n,r,o,s);let x=`.${l}`;if(En.some(L=>x===L||c.endsWith(L)))return yield*Ia(e,c,t,n,r,o,s);let T=la.some(L=>c.startsWith(L)||d.startsWith(L)),S=`.${l}`;if(!T&&bn.some(L=>S===L||c.endsWith(L)))return yield*Aa(e,c,t,n,r,o,s);if(Nr(c))return yield*Pa(e,c,t,n,r,o,s);if(vr(c))return Fa(e,c,n,r);if(kr(c))return yield*Ra(e,c,t,n,r,o,s);if(Ar(c))return $a(e,c,n,r);if(Fr(c))return yield*Da(e,c,n,r);s.totalEffects++;let N,y=["Effect.sync","Effect.promise","Effect.async","Effect.asyncEffect","Effect.tryPromise","Effect.suspend"].some(L=>c.includes(L))&&e.getArguments().length>0&&e.getArguments()[0],C;if(y){let L=e.getArguments()[0],{SyntaxKind:V}=I();if(L.getKind()===V.ArrowFunction||L.getKind()===V.FunctionExpression){let Le=L,ce=Le.getBody(),yt=[];if(ce){if(ce.getKind()===V.Block){let rt=ce;for(let je of rt.getStatements())if(je.getKind()===V.ReturnStatement){let Ne=je.getExpression();if(Ne&&Ut(Ne.getText(),Oe(t),t)){let ze=yield*$(Ne,t,n,r,o,s,void 0);yt.push(ze)}}else if(je.getKind()===V.ExpressionStatement){let Ne=je.getExpression();if(Ne.getKind()===V.CallExpression&&st(Ne,t,Oe(t),r.knownEffectInternalsRoot)){let ze=yield*$(Ne,t,n,r,o,s,void 0);yt.push(ze)}}}else if(Ut(ce.getText(),Oe(t),t)){let rt=yield*$(ce,t,n,r,o,s,void 0);yt.push(rt)}}if(yt.length>0&&(N=yt),c.includes("Effect.async")||c.includes("Effect.asyncEffect")){let rt=Le.getParameters()[0]?.getName?.()??"resume",je=0,Ne=St=>{if(St.getKind()===V.CallExpression){let xt=St.getExpression();xt.getKind()===V.Identifier&&xt.getText()===rt&&je++}St.getChildren().forEach(Ne)};ce&&Ne(ce);let ze=!1;if(ce?.getKind()===V.Block){let St=ce;for(let fn of St.getStatements())if(fn.getKind()===V.ReturnStatement){let xt=fn.getExpression();if(xt){let gr=xt.getKind();if(gr===V.ArrowFunction||gr===V.FunctionExpression){ze=!0;break}}}}else ce&&(ce.getKind()===V.ArrowFunction||ce.getKind()===V.FunctionExpression)&&(ze=!0);C={resumeParamName:rt,resumeCallCount:je,returnsCanceller:ze}}}}let w=Ue(e),b=t.getProject().getTypeChecker(),P=Ie(e,b),F=bt(e,b),O=da(e,t),A,W=e.getExpression();if(W.getKind()===I().SyntaxKind.PropertyAccessExpression){let L=W,V=L.getExpression().getText(),be=L.getName();if(a){let Le=a.get(V);Le&&(A={serviceId:Le,methodName:be})}!A&&F?.length===1&&F[0]&&(A={serviceId:F[0].serviceId,methodName:be})}let B;if(c==="Effect.provide"||c.startsWith("Effect.")&&c.includes(".provide")&&!c.includes("provideService")){let L=e.getArguments(),V=(L.length>=2?L[1]:L[0])?.getText()??"";/Runtime\.|defaultRuntime|\.runSync|\.runPromise|\.runFork|\.runCallback/.test(V)||/^\s*runtime\s*$|^\s*rt\s*$/i.test(V.trim())?B="runtime":V.includes("Layer.")?B="layer":B="context"}let J;c.endsWith(".sync")||c.endsWith(".succeed")||c.endsWith(".fail")||c.endsWith(".try")||c.endsWith(".suspend")?J="sync":c.endsWith(".promise")?J="promise":c.endsWith(".async")||c.endsWith(".asyncEffect")?J="async":c.endsWith(".never")?J="never":c.endsWith(".void")?J="void":c.endsWith(".fromNullable")?J="fromNullable":c.endsWith(".fn")?J="fn":c.endsWith(".fnUntraced")&&(J="fnUntraced");let Y,de=["currentConcurrency","currentLogLevel","currentScheduler","currentTracerEnabled","currentLogSpan","currentLogAnnotations","currentContext","currentRequestBatching","currentMaxOpsBeforeYield","currentSupervisor","currentMetricLabels","interruptedCause","unhandledLogLevel"];for(let L of de)if(c.includes(L)){Y=L;break}let tt;if(J==="fn"||J==="fnUntraced"){let L=e.getArguments();if(L.length>0){let V=L[0].getText(),be=/^["'`](.+?)["'`]$/.exec(V);be&&(tt=be[1])}}let nt={id:k(),type:"effect",callee:c,description:O?"service-call":$r(c,Oe(t)),location:f,jsdocDescription:w,jsdocTags:ot(e),typeSignature:P,requiredServices:F,serviceCall:O,serviceMethod:A,callbackBody:N,...C?{asyncCallback:C}:{},...B?{provideKind:B}:{},...J?{constructorKind:J}:{},...Y?{fiberRefName:Y}:{},...tt?{tracedName:tt}:{}};return{...nt,displayName:z(nt),semanticRole:G(nt)}}),da=(e,t)=>{let{SyntaxKind:n}=I(),r=e.getExpression();if(r.getKind()!==n.PropertyAccessExpression)return;let o=r,s=o.getExpression(),a=o.getName(),i=s.getText(),c=i.split(".")[0]??i;if(!Ct.has(c))try{let d=s.getType(),l=d.getSymbol()??d.getAliasSymbol();if(!l)return;let f=l.getName();return!f||f==="__type"||f==="unknown"||f==="any"||qt.has(f)?void 0:{serviceType:f,methodName:a,objectName:i}}catch{return}};function Gt(e){let t=e.getExpression().getText(),n=e.getSourceFile(),r=Pn(t,n);return r.startsWith("Layer.")||r.startsWith("Effect.")||t==="pipe"||t.endsWith(".pipe")}function ua(e,t,n){let{SyntaxKind:r}=I(),o=e.getSourceFile(),s=o.getProject(),a=o.getFilePath(),c=t.getImportDeclaration().getModuleSpecifierValue();if(!c?.startsWith("."))return;let d=Ge(s,a,c);if(!d){let m=wt(a,c);if(m){let h=s.addSourceFileAtPath(m);h&&(d=h)}}if(!d)return;d=s.getSourceFile(d.getFilePath())??d;let l=m=>{if(m.getKind()===r.VariableDeclaration){let x=m.getInitializer();if(x?.getKind()===r.CallExpression&&n(x))return x}if(m.getKind()===r.VariableStatement){let h=m.getDeclarationList();for(let x of h.getDeclarations()){let T=x.getInitializer();if(T?.getKind()===r.CallExpression&&n(T))return T}}},f=t.getName(),u=d.getExportedDeclarations(),p=u.get(f)??[];for(let m of p){let h=l(m);if(h)return h}let g=t.getTargetName?.();if(g&&g!==f)for(let m of u.get(g)??[]){let h=l(m);if(h)return h}for(let[,m]of u)for(let h of m){let x=l(h);if(x)return x}}function fa(e,t,n){let{SyntaxKind:r}=I(),o=e.getSourceFile(),s=o.getProject(),a=o.getFilePath(),i=t.getModuleSpecifierValue();if(!i?.startsWith("."))return;let c=Ge(s,a,i);if(!c){let l=wt(a,i);if(l){let f=s.addSourceFileAtPath(l);f&&(c=f)}}if(!c)return;c=s.getSourceFile(c.getFilePath())??c;let d=l=>{if(l.getKind()===r.VariableDeclaration){let u=l.getInitializer();if(u?.getKind()===r.CallExpression&&n(u))return u}if(l.getKind()===r.VariableStatement){let f=l.getDeclarationList();for(let u of f.getDeclarations()){let p=u.getInitializer();if(p?.getKind()===r.CallExpression&&n(p))return p}}};for(let l of c.getDefaultExportSymbol()?.getDeclarations()??[]){let f=d(l);if(f)return f}for(let l of c.getExportedDeclarations().get("default")??[]){let f=d(l);if(f)return f}}function oo(e){let{SyntaxKind:t}=I();if(e.getKind()!==t.Identifier)return e;let n=e,r=n.getText(),o=n.getSymbol(),s=o?.getValueDeclaration(),a=s?.getKind()===t.ImportSpecifier?s:void 0;if(!a&&o){let i=o.getDeclarations().find(c=>c.getKind()===t.ImportSpecifier);i&&(a=i)}if(!a){let i=n.getSourceFile();for(let c of i.getImportDeclarations()){if(c.getDefaultImport()?.getText()===r){let f=fa(n,c,Gt);if(f)return f}let l=c.getNamedImports().find(f=>f.getName()===r||f.getAliasNode()?.getText()===r);if(l){a=l;break}}}if(a){let i=ua(n,a,Gt);if(i)return i;o=o?.getImmediatelyAliasedSymbol()??o?.getAliasedSymbol(),s=o?.getValueDeclaration()}if(s?.getKind()===t.ExportSpecifier&&(o=o?.getImmediatelyAliasedSymbol()??o?.getAliasedSymbol(),s=o?.getValueDeclaration()),o&&s?.getKind()!==t.VariableDeclaration){for(let i of o.getDeclarations())if(i.getKind()===t.VariableDeclaration){let d=i.getInitializer();if(d?.getKind()===t.CallExpression&&Gt(d))return d}}if(s?.getKind()===t.VariableDeclaration){let c=s.getInitializer();if(c?.getKind()===t.CallExpression&&Gt(c))return c}return e}var pa=(e,t,n,r,o,s,a)=>Z.gen(function*(){let i=e.getArguments(),c=[],{SyntaxKind:d}=I();if(i.length>0&&i[0]){let y=i[0];if(t.includes("mergeAll")&&y.getKind()===d.ArrayLiteralExpression){let w=y.getElements();for(let b of w){let P=yield*$(b,n,r,o,s,a);c.push(P)}}else for(let w of i){if(!w)continue;let b=oo(w),P=b.getSourceFile(),F=yield*$(b,P,P.getFilePath(),o,s,a);c.push(F)}}let l=t.includes("merge")||t.includes("mergeAll"),f;t.includes("fresh")?f="fresh":t.includes("memoize")?f="memoized":t.includes("scoped")?f="scoped":f="default";let u=[],p=y=>{if(y.getKind()===d.Identifier)return y.getText();if(y.getKind()===d.PropertyAccessExpression){let C=y,w=C.getExpression();return w.getKind()===d.Identifier?w.getText():C.getText().split(".")[0]}};if((t.includes("succeed")||t.includes("sync")||t.includes("effect")||t.includes("scoped")||t.includes("scopedDiscard")||t.includes("effectDiscard"))&&i.length>0&&i[0]){let y=p(i[0]);y&&u.push(y)}let g=t.includes("provide")&&!t.includes("provideService"),m=new Set;if(g&&i.length>=1&&i[0]){let y=p(i[0]);y&&m.add(y)}if(g&&i.length>=2&&i[1]){let y=p(i[1]);y&&m.add(y);let C=p(i[0]);C&&u.push(C)}if(t.includes("provideService")&&i.length>0&&i[0]){let y=p(i[0]);y&&u.push(y)}let h=y=>{if(y.type==="effect"){let w=y;for(let P of w.requiredServices??[])m.add(P.serviceId);let b=w.callee??"";(/^[A-Z][A-Za-z0-9_]*(Service|Tag)$/.test(b)||b.endsWith(".Tag"))&&m.add(b)}else if(y.type==="layer"){let w=y;for(let b of w.requires??[])m.add(b)}ca.getOrElse(v(y),()=>[]).forEach(h)};if(c.forEach(h),m.size===0)try{let y=Sn(e);y?.requiredType&&y.requiredType!=="never"&&Pr(y.requiredType).forEach(w=>m.add(w))}catch{}let x=t.replace(/^Layer\./,"").replace(/^[a-zA-Z]+\./,""),S=new Set(["catchAll","catchAllCause","orDie","orElse","retry","tap","mapError","mapErrorCause","build","launch","toRuntime","passthrough","project","flatMap","flatten","annotateLogs","annotateSpans","setConfigProvider","setClock","setTracer","locally","withSpan","withLogger","withTracer","withClock","mock","suspend","unwrapEffect","unwrapScoped"]).has(x)?`Layer.${x}`:void 0,N=t.includes("MemoMap")||c.some(y=>y.type==="layer"&&y.isMemoMap===!0),E={id:k(),type:"layer",name:S,operations:c,isMerged:l,provides:u.length>0?u:void 0,requires:m.size>0?Array.from(m).sort():void 0,lifecycle:f,...N?{isMemoMap:!0}:{},location:K(e,r,o.includeLocations??!1)};return{...E,displayName:z(E),semanticRole:G(E)}});function ga(e,t,n,r,o,s,a){return Z.gen(function*(){let i=e.getArguments(),c;i.length>0&&i[0]?c=yield*$(i[0],n,r,o,s,a):c={id:k(),type:"unknown",reason:"Stream source not determined"};let d=t.replace(/^Stream\./,"")||"unknown",l;t.startsWith("Stream.")&&(d==="fromIterable"||d==="fromChunk"||d==="fromChunkQueue"?l="fromIterable":d==="fromArray"?l="fromArray":d==="fromQueue"||d==="fromChunkQueue"?l="fromQueue":d==="fromPubSub"||d==="fromChunkPubSub"?l="fromPubSub":d==="fromEffect"||d==="unwrap"||d==="unwrapScoped"?l="fromEffect":d==="fromAsyncIterable"?l="fromAsyncIterable":d==="fromReadableStream"||d==="fromReadableStreamByob"?l="fromReadableStream":d==="fromEventListener"?l="fromEventListener":d==="fromSchedule"?l="fromSchedule":d==="range"?l="range":d==="tick"?l="tick":d==="iterate"||d==="iterateEffect"?l="iterate":d==="unfold"||d==="unfoldEffect"||d==="unfoldChunk"||d==="unfoldChunkEffect"?l="unfold":d==="make"?l="make":d==="empty"?l="empty":d==="never"?l="never":d==="succeed"||d==="sync"?l="succeed":(d==="fail"||d==="failSync"||d==="failCause"||d==="failCauseSync")&&(l="fail"));let f=b=>l!==void 0?"constructor":b.startsWith("run")?"sink":b==="toQueue"||b==="toPubSub"||b==="toReadableStream"||b==="toAsyncIterable"||b==="toChannel"?"conversion":b.includes("pipeThroughChannel")||b.includes("Channel")||b.includes("channel")||b.includes("duplex")?"channel":b.includes("grouped")||b.includes("sliding")||b.includes("groupBy")||b.includes("aggregate")||b.includes("window")?"windowing":b.includes("broadcast")||b==="share"?"broadcasting":b.includes("haltAfter")||b.includes("haltWhen")||b.includes("interruptAfter")?"halting":b.includes("decodeText")||b.includes("encodeText")||b.includes("splitLines")?"text":b.includes("merge")||b==="concat"||b.includes("interleave")||b.includes("zip")?"merge":b.includes("buffer")||b.includes("debounce")||b.includes("throttle")?"backpressure":b.includes("catchAll")||b.includes("catchTag")||b.includes("orElse")||b.includes("orDie")||b.includes("retry")?"error":b.includes("filter")||b.includes("take")||b.includes("drop")||b.includes("head")||b==="first"||b==="last"?"filter":b.includes("acquireRelease")||b.includes("scoped")||b.includes("ensuring")||b.includes("onDone")||b.includes("onError")?"resource":b.includes("provide")||b.includes("withSpan")||b.includes("annotate")?"context":b.includes("map")||b.includes("tap")||b.includes("flatMap")||b.includes("mapChunk")||b.includes("scan")||b.includes("transduce")?"transform":"other",u=d.includes("Effect")||d.startsWith("run")||d.includes("tap"),p=f(d),g=p==="filter"?"fewer":p==="merge"||p==="broadcasting"?"more":p==="halting"||p==="sink"||p==="windowing"?"fewer":"unknown",m,h;(d==="grouped"||d==="groupedWithin"||d.includes("sliding")||d.includes("Sliding"))&&i.length>0&&i[0]&&(m=Nt(i[0]),(d.includes("sliding")||d.includes("Sliding"))&&i.length>1&&i[1]&&(h=Nt(i[1])));let T={operation:d,isEffectful:u,estimatedCardinality:g,category:p,...m!==void 0?{windowSize:m}:{},...h!==void 0?{stride:h}:{}},S;d.startsWith("run")&&(S=d);let N;d.includes("buffer")?N="buffer":d.includes("drop")||d.includes("Drop")?N="drop":(d.includes("sliding")||d.includes("Sliding"))&&(N="sliding");let E=c,y=[T],C=l;if(c.type==="stream"){let b=c;y=[...b.pipeline,T],E=b.source,!C&&b.constructorType&&(C=b.constructorType),!S&&b.sink&&(S=b.sink),!N&&b.backpressureStrategy&&(N=b.backpressureStrategy)}let w={id:k(),type:"stream",source:E,pipeline:y,sink:S,backpressureStrategy:N,constructorType:C,location:K(e,r,o.includeLocations??!1)};return{...w,displayName:z(w),semanticRole:G(w)}})}function ma(e){return e==="fromReadableStream"||e==="fromWritableStream"||e==="fromDuplexStream"||e==="make"||e==="succeed"||e==="fail"||e==="empty"||e==="never"?"constructor":e.includes("map")||e.includes("flatMap")||e.includes("filter")||e.includes("concat")||e.includes("zip")?"transform":e.includes("pipe")||e==="pipeTo"||e==="pipeThrough"?"pipe":"other"}function ha(e,t,n,r,o,s,a){return Z.gen(function*(){let i=e.getArguments(),c;i.length>0&&i[0]&&(c=yield*$(i[0],n,r,o,s,a));let d=t.replace(/^Channel\./,"")||"unknown",l=[{operation:d,category:ma(d)}];if(c?.type==="channel"){let u=c;l.unshift(...u.pipeline),c=u.source}let f={id:k(),type:"channel",source:c,pipeline:l,location:K(e,r,o.includeLocations??!1)};return{...f,displayName:z(f),semanticRole:G(f)}})}function ya(e){return e==="forEach"||e==="forEachWhile"||e==="run"||e==="runDrain"||e==="runFor"||e==="make"||e==="fromEffect"||e==="fromQueue"?"constructor":e.includes("map")||e.includes("contramap")||e.includes("filter")||e.includes("zip")?"transform":"other"}function Sa(e,t,n,r,o,s,a){return Z.gen(function*(){let i=e.getArguments(),c;i.length>0&&i[0]&&(c=yield*$(i[0],n,r,o,s,a));let d=t.replace(/^Sink\./,"")||"unknown",l=[{operation:d,category:ya(d)}];if(c?.type==="sink"){let u=c;l.unshift(...u.pipeline),c=u.source}let f={id:k(),type:"sink",source:c,pipeline:l,location:K(e,r,o.includeLocations??!1)};return{...f,displayName:z(f),semanticRole:G(f)}})}function xa(e,t,n,r,o,s,a){let{SyntaxKind:i}=I(),c="queue",d="create",l,f,u;t.startsWith("Queue.")?(c="queue",t.includes("bounded")?l="bounded":t.includes("unbounded")?l="unbounded":t.includes("sliding")?l="sliding":t.includes("dropping")&&(l="dropping"),t.includes("offer")||t.includes("offerAll")?d="offer":t.includes("take")||t.includes("takeAll")||t.includes("poll")?d="take":d="create"):t.startsWith("PubSub.")?(c="pubsub",t.includes("bounded")?l="bounded":t.includes("unbounded")&&(l="unbounded"),t.includes("publish")?d="publish":t.includes("subscribe")?d="subscribe":d="create"):t.startsWith("Deferred.")?(c="deferred",t.includes("succeed")?d="succeed":t.includes("fail")?d="fail":t.includes("await")?d="await":d="create"):t.startsWith("Semaphore.")?(c="semaphore",t.includes("withPermit")?d="withPermit":t.includes("take")?d="take":t.includes("release")?d="release":t.includes("available")?d="available":d="create"):t.startsWith("Mailbox.")?(c="mailbox",t.includes("offer")?d="offer":t.includes("takeAll")?d="takeAll":t.includes("take")?d="take":t.includes("end")?d="end":t.includes("toStream")?d="toStream":d="create"):t.startsWith("SubscriptionRef.")?(c="subscriptionRef",t.includes("changes")?d="changes":t.includes("get")?d="get":t.includes("set")?d="set":t.includes("update")?d="update":d="create"):t.includes("makeLatch")||t.includes("Latch.")?(c="latch",t.includes("open")?d="open":t.includes("close")?d="close":t.includes("await")||t.includes("whenOpen")?d="await":d="create"):t.startsWith("FiberHandle.")?(c="fiberHandle",t.includes("run")?d="run":t.includes("await")?d="await":d="create"):t.startsWith("FiberSet.")?(c="fiberSet",t.includes("run")?d="run":t.includes("join")?d="await":d="create"):t.startsWith("FiberMap.")?(c="fiberMap",t.includes("run")?d="run":t.includes("join")?d="await":d="create"):t.startsWith("RateLimiter.")?(c="rateLimiter",t.includes("withCost")?d="withPermit":d="create"):t.startsWith("ScopedCache.")?(c="scopedCache",t.includes("make")||t.includes("Make")?d="create":t.includes("get")&&!t.includes("getOrElse")||t.includes("getOrElse")?d="get":t.includes("set")||t.includes("Set")?d="set":t.includes("invalidate")?d="invalidate":t.includes("contains")?d="contains":d="create"):t.startsWith("Cache.")?(c="cache",t.includes("make")||t.includes("Make")?d="create":t.includes("get")&&!t.includes("getOrElse")||t.includes("getOrElse")?d="get":t.includes("set")||t.includes("Set")?d="set":t.includes("invalidate")?d="invalidate":t.includes("contains")?d="contains":d="create"):t.startsWith("Reloadable.")||t.includes(".Reloadable.")?(c="reloadable",t.includes("make")||t.includes("Make")?d="create":t.includes("get")&&!t.includes("reload")?d="get":t.includes("reload")?d="reload":d="create"):t.startsWith("RcMap.")||t.includes(".RcMap.")?(c="rcMap",t.includes("make")||t.includes("Make")?d="create":t.includes("get")?d="get":t.includes("set")||t.includes("Set")?d="set":t.includes("update")?d="update":d="create"):(t.startsWith("RcRef.")||t.includes(".RcRef."))&&(c="rcRef",t.includes("make")||t.includes("Make")?d="create":t.includes("get")?d="get":t.includes("set")||t.includes("Set")?d="set":t.includes("update")?d="update":d="create");let p=e.getArguments();if(p.length>0&&l==="bounded"){let h=p[0];h?.getKind()===i.NumericLiteral&&(f=Number.parseInt(h.getText(),10))}c==="semaphore"&&(d==="take"||d==="release")&&p.length>0&&p[0]&&(u=Nt(p[0]));let g;if(c==="fiberHandle"&&d==="run")for(let h of p){let x=h.getText();x.includes("onlyIfMissing")&&(g={onlyIfMissing:x.includes("true")})}if(c==="mailbox"&&d==="toStream"||c==="subscriptionRef"&&d==="changes"){let h=c==="mailbox"?"fromMailbox":"fromSubscriptionRef",x={id:k(),type:"concurrency-primitive",primitive:c,operation:d,location:K(e,r,o.includeLocations??!1)},T={id:k(),type:"stream",source:{...x,displayName:z(x),semanticRole:G(x)},pipeline:[],constructorType:h,location:K(e,r,o.includeLocations??!1)};return Z.succeed({...T,displayName:z(T),semanticRole:G(T)})}let m={id:k(),type:"concurrency-primitive",primitive:c,operation:d,strategy:l,capacity:f,...u!==void 0?{permitCount:u}:{},...g?{lifecycleOptions:g}:{},location:K(e,r,o.includeLocations??!1)};return Z.succeed({...m,displayName:z(m),semanticRole:G(m)})}function Ea(e,t,n,r,o,s,a){return Z.gen(function*(){let i=e.getArguments(),c="fork",d=!1,l=!1,f;t.startsWith("Fiber.")?t.includes("awaitAll")?c="awaitAll":t.includes("join")?c="join":t.includes("await")?c="await":t.includes("interruptFork")?c="interruptFork":t.includes("interrupt")?c="interrupt":t.includes("poll")?c="poll":t.includes("status")?c="status":t.includes("all")?c="all":t.includes("children")?c="children":t.includes("dump")?c="dump":t.includes("scoped")?(c="scoped",d=!0):t.includes("inheritAll")?c="inheritAll":t.includes("mapFiber")?c="mapFiber":t.includes("mapEffect")?c="mapEffect":t.includes("map")?c="map":t.includes("roots")?c="roots":t.includes("getCurrentFiber")&&(c="getCurrentFiber"):t.includes("forkWithErrorHandler")?c="forkWithErrorHandler":t.includes("forkAll")?c="forkAll":t.includes("forkIn")?c="forkIn":t.includes("fork")&&(t.includes("forkDaemon")?(c="forkDaemon",l=!0):t.includes("forkScoped")?(c="forkScoped",d=!0):c="fork"),(c==="fork"||c==="forkScoped"||c==="forkDaemon"||c==="forkAll"||c==="forkIn"||c==="forkWithErrorHandler")&&i.length>0&&i[0]&&(f=yield*$(i[0],n,r,o,s,a));let u;if(d)u="safe";else{let g=e.getParent();for(;g;){let m=g.getText?.();if(m&&(m.includes("Effect.scoped")||m.includes("Scope.make"))){u="safe";break}if(g=g.getParent(),g&&g===n)break}}let p={id:k(),type:"fiber",operation:c,fiberSource:f,isScoped:d,isDaemon:l,...u?{scopeContext:u}:{},location:K(e,r,o.includeLocations??!1)};return{...p,displayName:z(p),semanticRole:G(p)}})}function ba(e,t,n,r,o,s,a){return Z.gen(function*(){let i=e.getArguments(),{SyntaxKind:c}=I(),d;t.includes("uninterruptibleMask")?d="uninterruptibleMask":t.includes("interruptibleMask")?d="interruptibleMask":t.includes("uninterruptible")?d="uninterruptible":t.includes("interruptible")?d="interruptible":t.includes("onInterrupt")?d="onInterrupt":t.includes("disconnect")?d="disconnect":t.includes("allowInterrupt")?d="allowInterrupt":t.includes("interruptWith")?d="interruptWith":d="interrupt";let l,f,u=e.getExpression();u.getKind()===c.PropertyAccessExpression?(l=yield*$(u.getExpression(),n,r,o,s,a),i.length>0&&i[0]&&(f=yield*$(i[0],n,r,o,s,a))):i.length>0&&i[0]&&(l=yield*$(i[0],n,r,o,s,a),i.length>1&&i[1]&&(f=yield*$(i[1],n,r,o,s,a))),a.interruptionCount++;let p={id:k(),type:"interruption",interruptionType:d,source:l,handler:f,location:K(e,r,o.includeLocations??!1)};return{...p,displayName:z(p),semanticRole:G(p)}})}function Ca(e){let{SyntaxKind:t}=I(),n,r,o;for(let s of e.getProperties()){if(s.getKind()!==t.PropertyAssignment)continue;let a=s.getNameNode().getText(),i=s.getInitializer();if(!i)continue;let c=i.getText();if(a==="concurrency")if(c==='"unbounded"'||c==="'unbounded'")n="unbounded";else if(c==='"sequential"'||c==="'sequential'")n="sequential";else if(c==='"inherit"'||c==="'inherit'")n="sequential";else{let d=Number.parseInt(c,10);!Number.isNaN(d)&&d>=0&&(n=d)}else a==="batching"&&(c==="true"||c==="false")?r=c==="true":a==="discard"&&(c==="true"||c==="false")&&(o=c==="true")}return{concurrency:n,batching:r,discard:o}}var Na=(e,t,n,r,o,s,a)=>Z.gen(function*(){let i=e.getArguments(),c=[],{SyntaxKind:d}=I();if(i.length>0&&i[0]){let h=i[0];if(h.getKind()===d.ArrayLiteralExpression){let x=h.getElements();for(let T of x){let S=yield*$(T,n,r,o,s,a);c.push(S)}}else if(h.getKind()===d.ObjectLiteralExpression){let x=h.getProperties();for(let T of x)if(T.getKind()===d.PropertyAssignment){let S=T.getInitializer();if(S){let N=yield*$(S,n,r,o,s,a);c.push(N)}}}}let l,f,u;if(i.length>1&&i[1]?.getKind()===d.ObjectLiteralExpression){let h=Ca(i[1]);l=h.concurrency,f=h.batching,u=h.discard}let p=t.includes("Par")?"parallel":"sequential";l===void 0&&(l=p==="parallel"?"unbounded":"sequential"),a.parallelCount++;let g=c.map(h=>z(h)),m={id:k(),type:"parallel",callee:t,mode:p,children:c,concurrency:l,batching:f,discard:u,branchLabels:g,location:K(e,r,o.includeLocations??!1)};return{...m,displayName:z(m),semanticRole:G(m)}}),Ta=(e,t,n,r,o,s,a)=>Z.gen(function*(){let i=e.getArguments(),c=[];for(let f of i)if(f){let u=yield*$(f,n,r,o,s,a);c.push(u)}a.raceCount++;let d=c.map(f=>z(f)),l={id:k(),type:"race",callee:t,children:c,raceLabels:d,location:K(e,r,o.includeLocations??!1)};return{...l,displayName:z(l),semanticRole:G(l)}}),va=(e,t,n,r,o,s,a)=>Z.gen(function*(){let i=e.getArguments(),c;t.includes("catchAllCause")?c="catchAllCause":t.includes("catchSomeCause")?c="catchSomeCause":t.includes("catchSomeDefect")?c="catchSomeDefect":t.includes("catchAllDefect")?c="catchAllDefect":t.includes("catchTags")?c="catchTags":t.includes("catchIf")?c="catchIf":t.includes("catchSome")?c="catchSome":t.includes("catchTag")?c="catchTag":t.includes("catchAll")?c="catchAll":t.includes("orElseFail")?c="orElseFail":t.includes("orElseSucceed")?c="orElseSucceed":t.includes("orElse")?c="orElse":t.includes("orDieWith")?c="orDieWith":t.includes("orDie")?c="orDie":t.includes("flip")?c="flip":t.includes("mapErrorCause")?c="mapErrorCause":t.includes("mapBoth")?c="mapBoth":t.includes("mapError")?c="mapError":t.includes("unsandbox")?c="unsandbox":t.includes("sandbox")?c="sandbox":t.includes("parallelErrors")?c="parallelErrors":t.includes("filterOrDieMessage")?c="filterOrDieMessage":t.includes("filterOrDie")?c="filterOrDie":t.includes("filterOrElse")?c="filterOrElse":t.includes("filterOrFail")?c="filterOrFail":t.includes("matchCauseEffect")?c="matchCauseEffect":t.includes("matchCause")?c="matchCause":t.includes("matchEffect")?c="matchEffect":t.includes("match")?c="match":t.includes("firstSuccessOf")?c="firstSuccessOf":t.includes("ignoreLogged")?c="ignoreLogged":t.includes("ignore")?c="ignore":t.includes("eventually")?c="eventually":c="catchAll";let d,l,f=e.getExpression();if(f.getKind()===I().SyntaxKind.PropertyAccessExpression){let h=f.getExpression();d=yield*$(h,n,r,o,s,a),i.length>0&&i[0]&&(l=yield*$(i[0],n,r,o,s,a))}else i.length>0&&i[0]?d=yield*$(i[0],n,r,o,s,a):d={id:k(),type:"unknown",reason:"Could not determine source effect"},i.length>1&&i[1]&&(l=yield*$(i[1],n,r,o,s,a));a.errorHandlerCount++;let u,p;if(c==="catchTag"){let m=i[0];m?.getKind()===I().SyntaxKind.StringLiteral&&(u=m.getLiteralValue())}else if(c==="catchTags"){let m=[...i].find(h=>h?.getKind()===I().SyntaxKind.ObjectLiteralExpression);m&&(p=m.getProperties().filter(x=>x.getKind()===I().SyntaxKind.PropertyAssignment||x.getKind()===I().SyntaxKind.MethodDeclaration).map(x=>(x.getKind()===I().SyntaxKind.PropertyAssignment,x.getName())))}let g={id:k(),type:"error-handler",handlerType:c,source:d,handler:l,errorTag:u,errorTags:p,errorEdgeLabel:u?`on ${u}`:p&&p.length>0?`on ${p.join(" | ")}`:"on error",location:K(e,r,o.includeLocations??!1)};return{...g,displayName:z(g),semanticRole:G(g)}}),wa=(e,t,n,r,o,s)=>Z.gen(function*(){let a=e.getArguments(),i,c,d,l,f=e.getExpression();if(f.getKind()===I().SyntaxKind.PropertyAccessExpression){let m=f.getExpression();i=yield*$(m,t,n,r,o,s),a.length>0&&a[0]&&(c=a[0].getText(),d=yield*$(a[0],t,n,r,o,s)),l=f.getText().includes("retryOrElse")}else a.length>0&&a[0]?i=yield*$(a[0],t,n,r,o,s):i={id:k(),type:"unknown",reason:"Could not determine source effect"},a.length>1&&a[1]&&(c=a[1].getText(),d=yield*$(a[1],t,n,r,o,s)),l=a.length>2;s.retryCount++;let u=c?so(c):void 0,p={id:k(),type:"retry",source:i,schedule:c,...d!==void 0?{scheduleNode:d}:{},hasFallback:l,scheduleInfo:u,retryEdgeLabel:c?`retry: ${c}`:"retry",location:K(e,n,r.includeLocations??!1)};return{...p,displayName:z(p),semanticRole:G(p)}});function so(e){let t=e.replace(/\s+/g," "),n="custom";t.includes("Schedule.exponential")||t.includes("exponential(")?n="exponential":t.includes("Schedule.fibonacci")||t.includes("fibonacci(")?n="fibonacci":t.includes("Schedule.spaced")||t.includes("spaced(")?n="spaced":t.includes("Schedule.fixed")||t.includes("fixed(")?n="fixed":t.includes("Schedule.linear")||t.includes("linear(")?n="linear":t.includes("Schedule.cron")||t.includes("cron(")?n="cron":t.includes("Schedule.windowed")||t.includes("windowed(")?n="windowed":t.includes("Schedule.duration")||t.includes("duration(")?n="duration":t.includes("Schedule.elapsed")||t.includes("elapsed(")?n="elapsed":t.includes("Schedule.delays")||t.includes("delays(")?n="delays":t.includes("Schedule.once")||t.includes("once(")?n="once":t.includes("Schedule.stop")||t.includes("stop(")?n="stop":(t.includes("Schedule.count")||t.includes("count("))&&(n="count");let r,o=/recurs\s*\(\s*(\d+)\s*\)/.exec(t);o&&(r=Number.parseInt(o[1],10));let s=/recurUpTo\s*\(\s*(\d+)\s*\)/.exec(t);s?r=Number.parseInt(s[1],10):(t.includes("forever")||t.includes("Schedule.forever"))&&(r="unlimited");let a=t.includes("jittered")||t.includes("Schedule.jittered"),i=[];return t.includes("whileInput")&&i.push("whileInput"),t.includes("whileOutput")&&i.push("whileOutput"),t.includes("untilInput")&&i.push("untilInput"),t.includes("untilOutput")&&i.push("untilOutput"),t.includes("recurUntil")&&i.push("recurUntil"),t.includes("recurWhile")&&i.push("recurWhile"),t.includes("andThen")&&i.push("andThen"),t.includes("intersect")&&i.push("intersect"),t.includes("union")&&i.push("union"),t.includes("compose")&&i.push("compose"),t.includes("zipWith")&&i.push("zipWith"),t.includes("addDelay")&&i.push("addDelay"),t.includes("modifyDelay")&&i.push("modifyDelay"),t.includes("check")&&i.push("check"),t.includes("resetAfter")&&i.push("resetAfter"),t.includes("resetWhen")&&i.push("resetWhen"),t.includes("ensure")&&i.push("ensure"),t.includes("driver")&&i.push("driver"),t.includes("mapInput")&&i.push("mapInput"),{baseStrategy:n,maxRetries:r,jittered:a,conditions:i}}var ka=(e,t,n,r,o,s)=>Z.gen(function*(){let a=e.getArguments(),i,c,d,l=e.getExpression();if(l.getKind()===I().SyntaxKind.PropertyAccessExpression){let p=l.getExpression();i=yield*$(p,t,n,r,o,s),a.length>0&&a[0]&&(c=_t(a[0]));let g=_t(l);d=g.includes("timeoutFail")||g.includes("timeoutTo")}else a.length>0&&a[0]?i=yield*$(a[0],t,n,r,o,s):i={id:k(),type:"unknown",reason:"Could not determine source effect"},a.length>1&&a[1]&&(c=_t(a[1])),d=a.length>2;s.timeoutCount++;let f={id:k(),type:"timeout",source:i,duration:c,hasFallback:d,location:K(e,n,r.includeLocations??!1)};return{...f,displayName:z(f),semanticRole:G(f)}}),ro=(e,t,n,r,o,s,a)=>Z.gen(function*(){let i=e.getArguments(),c=/([A-Za-z_$][\w$]*)$/.exec(t)?.[1]??t,d,l,f;if(c.startsWith("acquireUseRelease"))i.length>=3&&i[0]&&i[2]?(d=yield*$(i[0],n,r,o,s,a),l=yield*$(i[2],n,r,o,s,a),i[1]&&(f=yield*$(i[1],n,r,o,s,a))):(d={id:k(),type:"unknown",reason:"Missing acquire"},l={id:k(),type:"unknown",reason:"Missing release"});else if(c.startsWith("acquireRelease"))i.length>=2&&i[0]&&i[1]?(d=yield*$(i[0],n,r,o,s,a),l=yield*$(i[1],n,r,o,s,a)):(d={id:k(),type:"unknown",reason:"Missing acquire"},l={id:k(),type:"unknown",reason:"Missing release"});else if(c==="addFinalizer"||c==="onExit"||c==="onError"||c==="parallelFinalizers"||c==="sequentialFinalizers"||c==="finalizersMask"||c==="using"||c==="withEarlyRelease"){let p=e.getExpression();p.getKind()===I().SyntaxKind.PropertyAccessExpression?d=yield*$(p.getExpression(),n,r,o,s,a):d={id:k(),type:"unknown",reason:"Scoped acquire"},l=i.length>0&&i[0]?yield*$(i[0],n,r,o,s,a):{id:k(),type:"unknown",reason:"Missing finalizer"}}else if(c==="ensuring"){let p=e.getExpression();if(p.getKind()===I().SyntaxKind.PropertyAccessExpression){let m=p.getExpression();d=yield*$(m,n,r,o,s,a),l=i.length>0&&i[0]?yield*$(i[0],n,r,o,s,a):{id:k(),type:"unknown",reason:"Missing cleanup"}}else d=i.length>0&&i[0]?yield*$(i[0],n,r,o,s,a):{id:k(),type:"unknown",reason:"Missing effect"},l=i.length>1&&i[1]?yield*$(i[1],n,r,o,s,a):{id:k(),type:"unknown",reason:"Missing cleanup"}}else d={id:k(),type:"unknown",reason:"Unknown resource pattern"},l={id:k(),type:"unknown",reason:"Unknown resource pattern"};a.resourceCount++;let u={id:k(),type:"resource",acquire:d,release:l,use:f,location:K(e,r,o.includeLocations??!1)};return{...u,displayName:z(u),semanticRole:G(u)}}),Ia=(e,t,n,r,o,s,a)=>Z.gen(function*(){let i=e.getArguments(),c;t.includes(".if")||t==="if"?c="if":t.includes("whenEffect")?c="whenEffect":t.includes("whenFiberRef")?c="whenFiberRef":t.includes("whenRef")?c="whenRef":t.includes(".when")||t==="when"?c="when":t.includes("unlessEffect")?c="unlessEffect":t.includes(".unless")||t==="unless"?c="unless":t.includes(".option")||t==="option"?c="option":t.includes(".either")||t==="either"?c="either":t.includes(".exit")||t==="exit"?c="exit":t.includes("liftPredicate")?c="liftPredicate":c="unless";let d="<dynamic>",l,f;if(c==="if"){if(i.length>0&&i[0]&&(d=i[0].getText()),i.length>1&&i[1]){let g=i[1],{SyntaxKind:m}=I();if(g.getKind()===m.ObjectLiteralExpression){let h=g.getProperties();for(let x of h)if(x.getKind()===m.PropertyAssignment){let T=x,S=T.getName(),N=T.getInitializer();N&&(S==="onTrue"?l=yield*$(N,n,r,o,s,a):S==="onFalse"&&(f=yield*$(N,n,r,o,s,a)))}}}}else{let g=e.getExpression();if(g.getKind()===I().SyntaxKind.PropertyAccessExpression){let h=g.getExpression();l||(l=yield*$(h,n,r,o,s,a))}i.length>0&&i[0]&&(d=i[0].getText())}l||(l={id:k(),type:"unknown",reason:"Could not determine true branch"}),a.conditionalCount++;let u=d.length<=30?d:`${d.slice(0,30)}\u2026`,p={id:k(),type:"conditional",conditionalType:c,condition:d,onTrue:l,onFalse:f,conditionLabel:u,trueEdgeLabel:"true",falseEdgeLabel:"false",location:K(e,r,o.includeLocations??!1)};return{...p,displayName:z(p),semanticRole:G(p)}}),Aa=(e,t,n,r,o,s,a)=>Z.gen(function*(){let i=e.getArguments(),c=t.includes("forEach")?"forEach":t.includes("filterMap")?"filterMap":t.includes("filter")?"filter":t.includes("partition")?"partition":t.includes("reduce")?"reduce":t.includes("validateAll")||t.includes("validateFirst")||t.includes("validateWith")?"validate":t.includes("replicate")?"replicate":t.includes("dropUntil")?"dropUntil":t.includes("dropWhile")?"dropWhile":t.includes("takeUntil")?"takeUntil":t.includes("takeWhile")?"takeWhile":t.includes("every")?"every":t.includes("exists")?"exists":t.includes("findFirst")?"findFirst":t.includes("head")?"head":t.includes("mergeAll")?"mergeAll":"loop",d=c==="reduce"||t.includes("reduceRight")||t.includes("reduceWhile")||t.includes("reduceEffect")?2:1,l,f;if(i.length>0&&i[0]){let p=i[0].getText();l=p.length>30?p.slice(0,30)+"\u2026":p}i.length>d&&i[d]?f=yield*$(i[d],n,r,o,s,a):f={id:k(),type:"unknown",reason:"Could not determine loop body"},a.loopCount++;let u={id:k(),type:"loop",loopType:c,iterSource:l,body:f,location:K(e,r,o.includeLocations??!1)};return{...u,displayName:z(u),semanticRole:G(u)}}),Fa=(e,t,n,r)=>{let o=Tn[t]??"other",s=Tr.has(o),a=e.getArguments(),i=[];if((o==="when"||o==="tag")&&a[0]){let d=a[0].getText().replace(/["'`]/g,"").trim();/^[A-Za-z_][A-Za-z0-9_]*$/.test(d)&&i.push(d)}if(o==="tags"||o==="tagsExhaustive"){let{SyntaxKind:d}=I();for(let l of a)if(l.getKind()===d.ObjectLiteralExpression){let f=l;for(let u of f.getProperties()){let p=u.getKind()===d.PropertyAssignment?u.getName():void 0;p&&i.push(p.replace(/["'`]/g,""))}}}let c={id:k(),type:"match",matchOp:o,isExhaustive:s,...i.length>0?{matchedTags:i}:{},location:K(e,n,r.includeLocations??!1)};return{...c,displayName:z(c),semanticRole:G(c)}},Ra=(e,t,n,r,o,s,a)=>Z.gen(function*(){let i=vn[t]??"other",c=wr.has(i),d;if(i==="parallel"||i==="sequential"){let u=e.getArguments(),p=[];for(let g of u)if(g){let m=yield*$(g,n,r,o,s,a);p.push(m)}p.length>0&&(d=p)}let l;if(i==="fail")l="fail";else if(i==="die")l="die";else if(i==="interrupt")l="interrupt";else if((i==="parallel"||i==="sequential")&&d&&d.length>0){let u=d.filter(p=>p.type==="cause").map(p=>p.causeKind).filter(p=>p!==void 0);u.length>0&&(l=u.every(p=>p===u[0])?u[0]:"mixed")}let f={id:k(),type:"cause",causeOp:i,isConstructor:c,...d?{children:d}:{},...l?{causeKind:l}:{},location:K(e,r,o.includeLocations??!1)};return{...f,displayName:z(f),semanticRole:G(f)}}),$a=(e,t,n,r)=>{let o=wn[t]??"other",s=Ir.has(o),a={id:k(),type:"exit",exitOp:o,isConstructor:s,location:K(e,n,r.includeLocations??!1)};return{...a,displayName:z(a),semanticRole:G(a)}},Da=(e,t,n,r)=>Z.sync(()=>{let o=kn[t]??"other",s=e.getText(),a=so(s),i={id:k(),type:"schedule",scheduleOp:o,...a?{scheduleInfo:a}:{},location:K(e,n,r.includeLocations??!1)};return{...i,displayName:z(i),semanticRole:G(i)}}),Pa=(e,t,n,r,o,s,a)=>Z.gen(function*(){let i=e.getArguments(),c=Nn[t]??"other",d=Cr.has(c),l,f;if(i.length>=2&&i[0]){if(l=yield*$(i[0],n,r,o,s,a),i[1]){let p=i[1].getText();f=p.length<=120?p:p.slice(0,120)+"\u2026"}}else if(i.length===1&&i[0]){let p=i[0].getText();f=p.length<=120?p:p.slice(0,120)+"\u2026"}a.totalEffects++;let u={id:k(),type:"transform",transformType:c,isEffectful:d,...l!==void 0?{source:l}:{},...f!==void 0?{fn:f}:{},location:K(e,r,o.includeLocations??!1)};return{...u,displayName:z(u),semanticRole:G(u)}});var Kn=(e,t,n,r,o)=>he.gen(function*(){let s=[],a=jr(),i=yield*La(e.node,e.type,t,n,r,s,a),c=Br(e.node),d=t.getProject().getTypeChecker(),l=Ie(e.node,d),f=bt(e.node,d),u={id:k(),type:"program",programName:e.name,source:e.type,...e.discoveryConfidence?{discoveryConfidence:e.discoveryConfidence}:{},...e.discoveryReason?{discoveryReason:e.discoveryReason}:{},children:i,dependencies:Kr(i),errorTypes:Wr(i),typeSignature:l,requiredServices:f,location:K(e.node,n,r.includeLocations??!1),jsdocDescription:c,jsdocTags:ot(e.node)},p=no(t);return{root:u,metadata:{analyzedAt:Date.now(),filePath:n,tsVersion:o,warnings:s,stats:a,...p.length>0?{serviceDefinitions:p}:{}},references:new Map}}),La=(e,t,n,r,o,s,a)=>he.gen(function*(){switch(t){case"generator":{let i=e.getArguments();if(i.length>0&&i[0]){let c=i[0];return yield*qa(c,n,r,o,s,a)}return[]}case"pipe":return yield*Jt(e,n,r,o,s,a);case"run":{let i=e,{SyntaxKind:c}=I(),d=yield*_a(i,n,r,o,s,a);if(kt.isSome(d))return d.value;let l=i.getArguments(),f=l.find(g=>g.getKind()===c.ArrowFunction||g.getKind()===c.FunctionExpression),u=o.enableEffectWorkflow&&f===void 0&&l.length===1?to(i,n):null,p=f??u??l[0];return p?[yield*$(p,n,r,o,s,a)]:[]}case"workflow-execute":{let i=e,c=i.getExpression().getText();return[{id:k(),type:"effect",callee:c,name:c,semanticRole:"side-effect",location:K(i,r,o.includeLocations??!1)}]}case"direct":{let i=e.getInitializer();return i?[yield*$(i,n,r,o,s,a)]:[]}case"class":{let i=e,c="Data.Class";for(let f of i.getHeritageClauses()){let u=f.getText();if(u.includes("Data.TaggedError")){c="Data.TaggedError";break}if(u.includes("Data.TaggedClass")){c="Data.TaggedClass";break}if(u.includes("Data.Error")){c="Data.Error";break}if(u.includes("Schema.TaggedRequest")){c="Schema.TaggedRequest";break}if(u.includes("Schema.TaggedError")){c="Schema.TaggedError";break}if(u.includes("Schema.TaggedClass")){c="Schema.TaggedClass";break}if(u.includes("Schema.Class")){c="Schema.Class";break}if(u.includes("Context.Tag")){c="Context.Tag";break}if(u.includes("Context.Reference")){c="Context.Reference";break}if(u.includes("Effect.Service")){c="Effect.Service";break}}let d=c.includes("Error")?"error-type":c.includes("Schema")?"schema":c==="Context.Tag"||c==="Context.Reference"||c==="Effect.Service"?"service-tag":"data",l={id:k(),type:"effect",callee:c,description:d,location:K(e,r,o.includeLocations??!1),jsdocDescription:Ue(i),jsdocTags:ot(i)};return a.totalEffects++,[l]}case"classProperty":{let c=e.getInitializer();return c?[yield*$(c,n,r,o,s,a)]:[]}case"classMethod":{let c=e.getBody();if(!c)return[];let{SyntaxKind:d}=I(),l=c.getDescendantsOfKind(d.ReturnStatement),f=[];for(let u of l){let p=u.getExpression();if(p){let g=yield*$(p,n,r,o,s,a);f.push(g)}}return f}default:return[]}});function Bn(e){let{SyntaxKind:t}=I(),n=e.getKind();return n===t.FunctionDeclaration||n===t.FunctionExpression||n===t.ArrowFunction||n===t.MethodDeclaration||n===t.ClassDeclaration||n===t.ClassExpression||n===t.Constructor}function re(e){let{SyntaxKind:t}=I();if(e.getKind()===t.YieldExpression)return!0;let n=!1;return e.forEachChild(r=>{if(!n&&!Bn(r)){if(r.getKind()===t.YieldExpression){n=!0;return}if(re(r)){n=!0;return}}}),n}function Ma(e){let{SyntaxKind:t}=I();switch(e.getKind()){case t.StringLiteral:return e.getLiteralValue();case t.NumericLiteral:return e.getLiteralValue().toString();case t.TrueKeyword:return"true";case t.FalseKeyword:return"false";case t.NullKeyword:return"null";case t.NoSubstitutionTemplateLiteral:return e.getText().replace(/^`|`$/g,"");default:return}}function at(e,t){if(t.size===0)return e;let n=e;for(let[r,o]of t){let s=new RegExp(`\\b${r}\\b`,"g"),a=/^\d/.test(o)||o==="true"||o==="false"||o==="null"?o:`'${o}'`;n=n.replace(s,a)}return n}function It(e){let t=e;return t=t.replace(/\btrue\b\s*&&\s*/g,""),t=t.replace(/\s*&&\s*\btrue\b/g,""),t=t.replace(/\bfalse\b\s*\|\|\s*/g,""),t=t.replace(/\s*\|\|\s*\bfalse\b/g,""),t=t.replace(/\bfalse\b\s*&&\s*[^|&]+/g,"false"),t=t.replace(/\btrue\b\s*\|\|\s*[^|&]+/g,"true"),t.trim()}function qn(e){let{SyntaxKind:t}=I();switch(e.getKind()){case t.ParenthesizedExpression:case t.AsExpression:case t.TypeAssertionExpression:case t.NonNullExpression:case t.SatisfiesExpression:{let r=e.getExpression();return qn(r)}default:return e}}function io(e){let{SyntaxKind:t}=I();if(e.length===0)return!1;let n=e[e.length-1];if(!n)return!1;let r=n.getKind();return r===t.ReturnStatement||r===t.ThrowStatement||r===t.BreakStatement||r===t.ContinueStatement}function co(e){let{SyntaxKind:t}=I(),n=[];return e.forEachChild(r=>{Bn(r)||(r.getKind()===t.YieldExpression?n.push(r):n.push(...co(r)))}),n}var Oa=new Set(["Step.run","Step.decide","Step.branch","Step.all","Step.forEach","Step.retry","Step.race","Step.sleep"]);function Wa(e){let{SyntaxKind:t}=I();if(e.getKind()!==t.CallExpression)return!1;let n=e.getExpression().getText();return Oa.has(n)}function Re(e){if(!e)return;let{SyntaxKind:t}=I();if(e.getKind()===t.StringLiteral)return e.getLiteralText()}function Ka(e){if(!e)return[];let{SyntaxKind:t}=I();if(e.getKind()!==t.ObjectLiteralExpression)return[];let n=[],r=e;for(let o of r.getProperties())if(o.getKind()===t.PropertyAssignment){let s=o.getName();n.push({labels:[s],isDefault:s==="default",body:[]})}return n}function Ba(e,t){return he.gen(function*(){let{SyntaxKind:n}=I(),r=e.getExpression().getText(),o=e.getArguments();switch(r){case"Step.run":{let s=Re(o[0]),a=o[1];if(!a){let c={id:k(),type:"effect",callee:"Step.run",name:s,displayName:s};return t.stats.totalEffects++,c}let i=yield*$(a,t.sourceFile,t.filePath,t.opts,t.warnings,t.stats,t.serviceScope);return{...i,displayName:s??i.displayName,name:s??i.name}}case"Step.decide":{let s=Re(o[0]),a=Re(o[1]);return t.stats.decisionCount++,{id:k(),type:"decision",decisionId:s??k(),label:a??s??"decision",condition:o[2]?.getText()??"unknown",source:"effect-flow",onTrue:[],onFalse:void 0}}case"Step.branch":{let s=Re(o[0]),a=o[1]?.getText()??"unknown",i=o[2],c=Ka(i);return t.stats.switchCount++,{id:k(),type:"switch",switchId:s,expression:a,cases:c,source:"effect-flow",hasDefault:c.some(l=>l.isDefault),hasFallthrough:!1}}case"Step.all":{let s=Re(o[0]),a=o[1],i=[];if(a?.getKind()===n.ArrayLiteralExpression){let d=a;for(let l of d.getElements()){let f=yield*$(l,t.sourceFile,t.filePath,t.opts,t.warnings,t.stats,t.serviceScope);i.push(f)}}return t.stats.parallelCount++,{id:k(),type:"parallel",name:s,displayName:s,children:i,mode:"parallel",callee:"Step.all"}}case"Step.forEach":{let s=Re(o[0]),a=o[1]?.getText(),i=o[2],c={id:k(),type:"effect",callee:"unknown"};return i&&(c=yield*$(i,t.sourceFile,t.filePath,t.opts,t.warnings,t.stats,t.serviceScope)),t.stats.loopCount++,{id:k(),type:"loop",name:s,displayName:s,loopType:"forEach",iterSource:a,body:c}}case"Step.retry":{let s=Re(o[0]),a=o[1];if(!a){let d={id:k(),type:"effect",callee:"Step.retry",name:s,displayName:s};return t.stats.totalEffects++,d}let i=yield*$(a,t.sourceFile,t.filePath,t.opts,t.warnings,t.stats,t.serviceScope);return t.stats.retryCount++,{id:k(),type:"retry",name:s,displayName:s,source:i,hasFallback:!1}}case"Step.race":{let s=Re(o[0]),a=o[1],i=[];if(a?.getKind()===n.ArrayLiteralExpression){let d=a;for(let l of d.getElements()){let f=yield*$(l,t.sourceFile,t.filePath,t.opts,t.warnings,t.stats,t.serviceScope);i.push(f)}}return t.stats.raceCount++,{id:k(),type:"race",name:s,displayName:s,children:i,callee:"Step.race"}}case"Step.sleep":{let s=Re(o[0]),a={id:k(),type:"effect",callee:"Step.sleep",name:s,displayName:s,semanticRole:"scheduling"};return t.stats.totalEffects++,a}default:{let s={id:k(),type:"effect",callee:r,name:r,displayName:r};return t.stats.totalEffects++,s}}})}function ao(e,t){return he.gen(function*(){let n=e,r=n.getText().startsWith("yield*"),o=n.getExpression();if(!r){let d={id:k(),type:"opaque",reason:"plain-yield",sourceText:e.getText().slice(0,80)};return t.stats.opaqueCount++,t.warnings.push({code:"PLAIN_YIELD",message:`Plain yield (not yield*) detected; this is unusual in Effect generators: ${e.getText().slice(0,60)}`,location:K(e,t.filePath,t.opts.includeLocations??!1)}),{variableName:jt(e),effect:d}}if(!o){let d={id:k(),type:"opaque",reason:"yield-no-expression",sourceText:e.getText().slice(0,80)};return t.stats.opaqueCount++,{variableName:void 0,effect:d}}let s=qn(o);if(t.opts.enableEffectFlow&&Wa(s)){let d=yield*Ba(s,t),l=jt(e),f={...d,displayName:d.displayName??z(d,l),semanticRole:d.semanticRole??G(d)};return{variableName:l,effect:f}}let a=yield*$(o,t.sourceFile,t.filePath,t.opts,t.warnings,t.stats,t.serviceScope),i=jt(e);i&&a.type==="effect"&&Rr(a.callee)&&t.serviceScope.set(i,a.callee);let c={...a,displayName:z(a,i),semanticRole:a.semanticRole??G(a)};return{variableName:i,effect:c}})}function ct(e,t){return he.gen(function*(){let n=e.getStatements(),r=[];for(let o of n){let s=yield*Yt(o,t);r.push(...s)}return r})}function Yt(e,t){return he.gen(function*(){let{SyntaxKind:n}=I();switch(e.getKind()){case n.ExpressionStatement:{let s=e.getExpression();return yield*ue(s,t)}case n.VariableStatement:{let o=e,s=[],{VariableDeclarationKind:a}=I(),i=o.getDeclarationKind()===a.Const;for(let c of o.getDeclarations()){let d=c.getInitializer();if(i&&d){let l=Ma(d);l!==void 0&&t.constValues.set(c.getName(),l)}if(d&&!re(d)&&d.getKind()===n.CallExpression){let l=d,f=l.getExpression().getText();if(f==="Context.pick"||f==="Context.omit"){let u=yield*$(l,t.sourceFile,t.filePath,t.opts,t.warnings,t.stats,t.serviceScope);u.type==="effect"&&u.description==="context"&&s.push({variableName:c.getName(),effect:u});continue}}if(d&&re(d)){let l=yield*ue(d,t);if(l.length>0){let f=c.getName(),u=l[l.length-1];u&&(l[l.length-1]={...u,variableName:u.variableName??f})}s.push(...l)}}return s}case n.IfStatement:{if(!re(e))return[];let o=e,s=o.getExpression().getText(),a=yield*ue(o.getExpression(),t),i=o.getThenStatement(),c=o.getElseStatement(),d=yield*Je(i,t),l=c?yield*Je(c,t):void 0,f=It(at(s,t.constValues)),u=f.length>40?f.slice(0,40)+"...":f,p={id:k(),type:"decision",decisionId:k(),label:u,condition:s,source:"raw-if",onTrue:d.map(g=>g.effect),onFalse:l&&l.length>0?l.map(g=>g.effect):void 0};return t.stats.decisionCount++,[...a,{effect:p}]}case n.SwitchStatement:{if(!re(e))return[];let o=e,s=o.getExpression().getText(),a=o.getClauses(),i=[],c=!1,d=!1,l=[],f=[],u=!1;for(let m of a){if(m.getKind()===n.DefaultClause)d=!0,u=!0,l.push("default");else{let S=m;l.push(S.getExpression().getText())}let x=m.getStatements();if(x.length===0){c=!0;continue}for(let S of x){let N=yield*Yt(S,t);f.push(...N)}io(x)||(c=!0),i.push({labels:l,isDefault:u,body:f.map(S=>S.effect)}),l=[],f=[],u=!1}l.length>0&&i.push({labels:l,isDefault:u,body:f.map(m=>m.effect)});let p=at(s,t.constValues),g={id:k(),type:"switch",switchId:k(),expression:p,cases:i,source:"raw-js",hasDefault:d,hasFallthrough:c};return t.stats.switchCount++,[{effect:g}]}case n.ForStatement:{if(!re(e))return[];let o=e,s=[],a=o.getInitializer();if(a&&re(a)){let m=yield*ue(a,t);s.push(...m.map(h=>h.effect))}let i=o.getIncrementor();if(i&&re(i)){let m=yield*ue(i,t);s.push(...m.map(h=>h.effect))}let c=o.getStatement(),d=yield*Je(c,t),l=it(c),f=o.getCondition(),u=f?f.getText():void 0,p=d.length===1&&d[0]?d[0].effect:{id:k(),type:"generator",yields:d},g={id:k(),type:"loop",loopType:"for",iterSource:u,body:p,...l?{hasEarlyExit:l}:{},...s.length>0?{headerYields:s}:{}};return t.stats.loopCount++,[{effect:g}]}case n.ForOfStatement:{if(!re(e))return[];let o=e,s=o.getExpression(),a=s.getText(),i=[];if(re(s)){let g=yield*ue(s,t);i.push(...g.map(m=>m.effect))}let c=o.getInitializer().getText(),d=o.getStatement(),l=yield*Je(d,t),f=it(d),u=l.length===1&&l[0]?l[0].effect:{id:k(),type:"generator",yields:l},p={id:k(),type:"loop",loopType:"forOf",iterSource:a,body:u,...f?{hasEarlyExit:f}:{},...i.length>0?{headerYields:i}:{},iterVariable:c};return t.stats.loopCount++,[{effect:p}]}case n.ForInStatement:{if(!re(e))return[];let o=e,s=o.getExpression().getText(),a=o.getInitializer().getText(),i=o.getStatement(),c=yield*Je(i,t),d=it(i),l=c.length===1&&c[0]?c[0].effect:{id:k(),type:"generator",yields:c},f={id:k(),type:"loop",loopType:"forIn",iterSource:s,body:l,...d?{hasEarlyExit:d}:{},iterVariable:a};return t.stats.loopCount++,[{effect:f}]}case n.WhileStatement:{if(!re(e))return[];let o=e,s=o.getExpression().getText(),a=o.getStatement(),i=yield*Je(a,t),c=it(a),d=i.length===1&&i[0]?i[0].effect:{id:k(),type:"generator",yields:i},l={id:k(),type:"loop",loopType:"while",iterSource:s,body:d,...c?{hasEarlyExit:c}:{}};return t.stats.loopCount++,[{effect:l}]}case n.DoStatement:{if(!re(e))return[];let o=e,s=o.getExpression().getText(),a=o.getStatement(),i=yield*Je(a,t),c=it(a),d=i.length===1&&i[0]?i[0].effect:{id:k(),type:"generator",yields:i},l={id:k(),type:"loop",loopType:"doWhile",iterSource:s,body:d,...c?{hasEarlyExit:c}:{}};return t.stats.loopCount++,[{effect:l}]}case n.TryStatement:{if(!re(e))return[];let o=e,s=o.getTryBlock(),a=yield*ct(s,t),i=o.getCatchClause(),c,d;if(i){c=i.getVariableDeclaration()?.getName();let m=i.getBlock();d=yield*ct(m,t)}let l=o.getFinallyBlock(),f;l&&(f=yield*ct(l,t));let u=io(s.getStatements()),p={id:k(),type:"try-catch",tryBody:a.map(g=>g.effect),...c?{catchVariable:c}:{},...d&&d.length>0?{catchBody:d.map(g=>g.effect)}:{},...f&&f.length>0?{finallyBody:f.map(g=>g.effect)}:{},hasTerminalInTry:u};return t.stats.tryCatchCount++,[{effect:p}]}case n.ReturnStatement:{let s=e.getExpression();if(!s||!re(s))return[];let a=yield*ue(s,t),i={id:k(),type:"terminal",terminalKind:"return",value:a.map(c=>c.effect)};return t.stats.terminalCount++,[{effect:i}]}case n.ThrowStatement:{let s=e.getExpression();if(!re(s))return[];let a=yield*ue(s,t),i={id:k(),type:"terminal",terminalKind:"throw",...a.length>0?{value:a.map(c=>c.effect)}:{}};return t.stats.terminalCount++,[{effect:i}]}case n.BreakStatement:return[];case n.ContinueStatement:return[];case n.LabeledStatement:return yield*Yt(e.getStatement(),t);case n.Block:return yield*ct(e,t);default:return[]}})}function Je(e,t){let{SyntaxKind:n}=I();return e.getKind()===n.Block?ct(e,t):Yt(e,t)}function it(e){let{SyntaxKind:t}=I(),n=!1;return e.forEachChild(r=>{if(n||Bn(r))return;let o=r.getKind();if(o===t.BreakStatement||o===t.ReturnStatement){n=!0;return}if(it(r)){n=!0;return}}),n}function ue(e,t){return he.gen(function*(){let{SyntaxKind:n}=I();if(!re(e))return[];let r=qn(e),o=r.getKind();if(o===n.YieldExpression)return[yield*ao(r,t)];if(o===n.ConditionalExpression){let i=r,c=i.getCondition().getText(),d=i.getWhenTrue(),l=i.getWhenFalse(),f=yield*ue(d,t),u=yield*ue(l,t);if(f.length>0||u.length>0){let p=It(at(c,t.constValues)),g={id:k(),type:"decision",decisionId:k(),label:p.length>40?p.slice(0,40)+"...":p,condition:c,source:"raw-ternary",onTrue:f.map(m=>m.effect),onFalse:u.length>0?u.map(m=>m.effect):void 0};return t.stats.decisionCount++,[{effect:g}]}}if(o===n.BinaryExpression){let i=r,c=i.getOperatorToken().getKind(),d=i.getLeft(),l=i.getRight();if(c===n.AmpersandAmpersandToken){let f=yield*ue(l,t);if(f.length>0){let u=d.getText(),p=It(at(u,t.constValues)),g={id:k(),type:"decision",decisionId:k(),label:p.length>40?p.slice(0,40)+"...":p,condition:u,source:"raw-short-circuit",onTrue:f.map(m=>m.effect),onFalse:[]};return t.stats.decisionCount++,[{effect:g}]}}if(c===n.BarBarToken){let f=yield*ue(l,t);if(f.length>0){let u=d.getText(),p=It(at(u,t.constValues)),g={id:k(),type:"decision",decisionId:k(),label:p.length>40?p.slice(0,40)+"...":p,condition:u,source:"raw-short-circuit",onTrue:[],onFalse:f.map(m=>m.effect)};return t.stats.decisionCount++,[{effect:g}]}}if(c===n.QuestionQuestionToken){let f=yield*ue(l,t);if(f.length>0){let u=`${d.getText()} != null`,p=It(at(u,t.constValues)),g={id:k(),type:"decision",decisionId:k(),label:p.length>40?p.slice(0,40)+"...":p,condition:u,source:"raw-short-circuit",onTrue:[],onFalse:f.map(m=>m.effect)};return t.stats.decisionCount++,[{effect:g}]}}}let s=co(e),a=[];for(let i of s){let c=yield*ao(i,t);a.push(c)}return a})}var qa=(e,t,n,r,o,s)=>he.gen(function*(){let{SyntaxKind:a}=I(),i;if((e.getKind()===a.ArrowFunction||e.getKind()===a.FunctionExpression||e.getKind()===a.FunctionDeclaration)&&(i=e.getBody()),!i)return[];let c=new Map,l={sourceFile:t,filePath:n,opts:r,warnings:o,stats:s,serviceScope:c,constValues:new Map},f;i.getKind()===a.Block?f=yield*ct(i,l):f=yield*ue(i,l);let u=i.getDescendantsOfKind(a.CallExpression);for(let h of u){if(h.getExpression().getText().includes("withSpan"))continue;let T=Oe(t);if(st(h,t,T,r.knownEffectInternalsRoot)){let S=yield*Wn(h,t,n,r,o,s,c);f.push({effect:S})}}let p=Ue(e),g={id:k(),type:"generator",yields:f,jsdocDescription:p,jsdocTags:ot(e)};return[{...g,displayName:z(g),semanticRole:G(g)}]});function _a(e,t,n,r,o,s){let i=e.getExpression().getText();if(!(i.endsWith(".pipe")||i==="pipe"))return he.succeed(kt.none());let d=e.getArguments(),l=d[d.length-1];if(!l)return he.succeed(kt.none());let f=l.getText();return f.includes(".runMain")||f.includes(".runPromise")||f.includes(".runSync")||f.includes(".runFork")?he.map(Jt(e,t,n,r,o,s),p=>kt.some(p)):he.succeed(kt.none())}var _n=(e,t)=>$e.gen(function*(){let n={...Rn,...t},{ts:r,Project:o}=I(),s=yield*$e.try({try:()=>qr(e)?new o({skipAddingFilesFromTsConfig:!0,compilerOptions:{allowJs:!0}}):hr(n.tsConfigPath),catch:d=>new me("PROJECT_CREATION_FAILED",`Failed to create project: ${String(d)}`)}),a=s.getSourceFile(e);a&&s.removeSourceFile(a);let i=yield*$e.try({try:()=>s.addSourceFileAtPath(e),catch:d=>new me("FILE_NOT_FOUND",`Failed to load file ${e}: ${String(d)}`)}),c=On(i,n);return c.length===0?yield*$e.fail(new me("NO_EFFECTS_FOUND",`No Effect programs found in ${e}`)):yield*$e.forEach(c,d=>Kn(d,i,e,n,r.version),{concurrency:"unbounded"})}),jn=(e,t="temp.ts",n)=>$e.gen(function*(){let r={...Rn,...n},{ts:o}=I(),s=yield*$e.try({try:()=>yr(e,t),catch:i=>new me("SOURCE_PARSE_FAILED",`Failed to parse source: ${String(i)}`)}),a=On(s,r);return a.length===0?yield*$e.fail(new me("NO_EFFECTS_FOUND","No Effect programs found in source")):yield*$e.forEach(a,i=>Kn(i,s,t,r,o.version),{concurrency:"unbounded"})});var we=e=>({single:()=>Q.gen(function*(){if(e.length===1){let t=e[0];if(t)return t}return yield*Q.fail(new me("NOT_SINGLE_PROGRAM",`Expected exactly 1 program, found ${String(e.length)}`))}),singleOption:()=>Q.gen(function*(){if(e.length===1){let t=e[0];if(t)return Qt.some(t)}return Qt.none()}),all:()=>Q.succeed(e),named:t=>Q.gen(function*(){let n=e.find(r=>r.root.programName===t);if(!n){let r=e.map(o=>o.root.programName).join(", ");return yield*Q.fail(new me("PROGRAM_NOT_FOUND",`Program "${t}" not found. Available: ${r||"(none)"}`))}return n}),first:()=>Q.gen(function*(){let t=e[0];return t||(yield*Q.fail(new me("NO_PROGRAMS","No programs found")))}),firstOption:()=>Q.gen(function*(){let t=e[0];return t?Qt.some(t):Qt.none()})}),At=(e,t)=>{Tt();let n=_n(e,t);return{single:()=>Q.gen(function*(){let r=yield*n;return yield*we(r).single()}),singleOption:()=>Q.gen(function*(){let r=yield*n;return yield*we(r).singleOption()}).pipe(Q.orDie),all:()=>n,named:r=>Q.gen(function*(){let o=yield*n;return yield*we(o).named(r)}),first:()=>Q.gen(function*(){let r=yield*n;return yield*we(r).first()}),firstOption:()=>Q.gen(function*(){let r=yield*n;return yield*we(r).firstOption()}).pipe(Q.orDie)}};At.source=(e,t)=>{Tt();let n=jn(e,"temp.ts",t);return{single:()=>Q.gen(function*(){let r=yield*n;return yield*we(r).single()}),singleOption:()=>Q.gen(function*(){let r=yield*n;return yield*we(r).singleOption()}).pipe(Q.orDie),all:()=>n,named:r=>Q.gen(function*(){let o=yield*n;return yield*we(o).named(r)}),first:()=>Q.gen(function*(){let r=yield*n;return yield*we(r).first()}),firstOption:()=>Q.gen(function*(){let r=yield*n;return yield*we(r).firstOption()}).pipe(Q.orDie)}};import{Effect as ye,Option as mo}from"effect";import{readdir as ho,readFile as Va,stat as Ga}from"fs/promises";import{readFileSync as yo}from"fs";import{join as tn,extname as So,resolve as go,basename as Ja}from"path";import{Option as lo}from"effect";function ja(e,t){let{SyntaxKind:n}=I(),r=[],o=e.getProject().getTypeChecker(),s=e.getDescendantsOfKind(n.ClassDeclaration);for(let a of s){let i=a.getName();if(!i)continue;let c=a.getExtends();if(!c)continue;let d=c.getText();if(!d.includes("Context.Tag")&&!d.includes("Effect.Service"))continue;let l=i,f=/Context\.Tag\s*\(\s*['"]([^'"]+)['"]\s*\)/.exec(d);f?.[1]&&(l=f[1]);let u=c.getTypeArguments();if(u.length<2){let x=c.getExpression();x&&"getTypeArguments"in x&&typeof x.getTypeArguments=="function"&&(u=x.getTypeArguments())}let p={tagId:l,methods:[],properties:[]},g;if(u.length>=2){let x=u[1];if(x)try{g=x.getText();let T=o.getTypeAtLocation(x),S=[],N=[];for(let E of T.getProperties()){let y=E.getName();if(y.startsWith("_")||y==="constructor")continue;o.getTypeOfSymbolAtLocation(E,x).getCallSignatures().length>0?S.push(y):N.push(y)}p={tagId:l,methods:S,properties:N}}catch{}}let m=a.getStart(),h=e.getLineAndColumnAtPos(m);r.push({tagId:l,className:i,filePath:t,location:{filePath:t,line:h.line,column:h.column-1},definition:p,interfaceTypeText:g})}return r}function za(e,t,n){let{SyntaxKind:r}=I(),o=[],s=e.getDescendantsOfKind(r.VariableDeclaration);for(let a of s){let i=a.getInitializer();if(!i)continue;let c=i.getText(),d=/Layer\.(effect|succeed|sync|scoped)\s*\(\s*/.exec(c);if(!d)continue;let l=d[1],f=a.getName(),u;if(i.getKind()===r.CallExpression){let S=i.getArguments?.();if(S&&S.length>0){let N=S[0];if(!N)continue;let E=N.getText().trim();u=n.get(E)}}if(!u){for(let S of n.keys())if(c.includes(`Layer.${l}(${S}`)||c.includes(`Layer.${l}(
|
|
5
|
+
${S}`)){u=n.get(S);break}}if(!u)continue;let p=[],g=/Layer\.provide\s*\(([^)]+)\)/.exec(c);if(g?.[1]){let S=g[1].trim();for(let[N,E]of n.entries())E!==u&&S.includes(N)&&!p.includes(E)&&p.push(E)}let m=c.matchAll(/yield\*\s+(\w+)/g);for(let S of m){let N=S[1],E=N?n.get(N):void 0;E&&E!==u&&!p.includes(E)&&p.push(E)}let h=c.matchAll(/yield\s*\*\s*(\w+)/g);for(let S of h){let N=S[1],E=N?n.get(N):void 0;E&&E!==u&&!p.includes(E)&&p.push(E)}let x=a.getStart(),T=e.getLineAndColumnAtPos(x);o.push({providesServiceId:u,implementation:{name:f,filePath:t,location:{filePath:t,line:T.line,column:T.column-1},kind:l,requires:p}})}return o}function Ha(e){let t=new Map;for(let[n,r]of e)for(let o of r){let s=o.root.programName;if(o.root.requiredServices)for(let a of o.root.requiredServices){let i=t.get(a.serviceId)??[];i.push({programName:s,filePath:n,location:a.requiredAt}),t.set(a.serviceId,i)}uo(o.root.children,s,n,t)}return t}function uo(e,t,n,r){for(let o of e){if(o.type==="effect"&&o.serviceCall){let a=o.serviceCall.serviceType;if(a){let i=r.get(a)??[];i.some(c=>c.programName===t&&c.filePath===n)||(i.push({programName:t,filePath:n,location:o.location}),r.set(a,i))}}let s=lo.getOrElse(v(o),()=>[]);s.length>0&&uo(s,t,n,r)}}function Ua(e){let t=[],n=new Set,r=new Set;function o(s){if(n.has(s)||r.has(s))return;r.add(s);let a=e.get(s);if(a)for(let i of a.dependencies)o(i);r.delete(s),n.add(s),t.push(s)}for(let s of e.keys())o(s);return t}function fo(e,t,n,r=new Set){let o=[];if(r.has(e))return o;r.add(e);for(let s of t)for(let a of s.requires){o.includes(a)||o.push(a);let i=n.get(a);if(i)for(let c of fo(a,i,n,r))o.includes(c)||o.push(c)}return o}function Zt(e,t){let n=new Map;if(t)for(let[u,p]of t){let g=ja(p,u);for(let m of g)n.has(m.tagId)||n.set(m.tagId,m)}for(let[u,p]of e)for(let g of p)if(g.metadata.serviceDefinitions)for(let m of g.metadata.serviceDefinitions)n.has(m.tagId)||n.set(m.tagId,{tagId:m.tagId,className:m.tagId,filePath:u,location:{filePath:u,line:1,column:0},definition:m});let r=new Set(n.keys()),o=new Map;for(let[u,p]of n)o.has(u)||o.set(u,u),o.has(p.className)||o.set(p.className,u);let s=new Set;for(let u of e.values())for(let p of u)if(p.root.requiredServices)for(let g of p.root.requiredServices)s.add(g.serviceId);let a=new Map;if(t)for(let[u,p]of t){let g=za(p,u,o);for(let m of g){if(!r.has(m.providesServiceId))continue;let h=a.get(m.providesServiceId)??[];h.push(m.implementation),a.set(m.providesServiceId,h)}}for(let[u,p]of e)for(let g of p)po(g.root.children,u,r,o,a,g);let i=Ha(e),c=new Map,d=[];for(let[u,p]of n){let g=a.get(u)??[],m=i.get(u)??[],h=fo(u,g,a);c.set(u,{serviceId:u,className:p.className,definitionFilePath:p.filePath,definitionLocation:p.location,definition:p.definition,interfaceTypeText:p.interfaceTypeText,layerImplementations:g,consumers:m,dependencies:h})}let l=new Set(s);for(let u of i.keys())l.add(u);for(let u of l)c.has(u)||d.push(u);let f=Ua(c);return{services:c,unresolvedServices:d,topologicalOrder:f}}function po(e,t,n,r,o,s){for(let a of e){if(a.type==="layer"&&a.provides)for(let c of a.provides){let d=r.get(c)??(n.has(c)?c:void 0);if(d&&n.has(d)){let l=o.get(d)??[],f=a.requires?a.requires.map(u=>r.get(u)??u).filter(u=>n.has(u)):[];l.some(u=>u.name===(a.name??s.root.programName)&&u.filePath===t)||(l.push({name:a.name??s.root.programName,filePath:t,location:a.location??{filePath:t,line:1,column:0},kind:"other",requires:f}),o.set(d,l))}}let i=lo.getOrElse(v(a),()=>[]);i.length>0&&po(i,t,n,r,o,s)}}var en={extensions:[".ts",".tsx"],maxDepth:10,knownEffectInternalsRoot:void 0,includePerFileTiming:!1,excludeFromSuspiciousZeros:[],buildServiceMap:!1};function Ya(e){let t=0,n=0,r=o=>{for(let s of o){t++,s.type==="unknown"&&n++;let a=mo.getOrElse(v(s),()=>[]);a.length>0&&r(a)}};return r(e),{total:t,unknown:n}}function Qa(e){let t=new Map,n=r=>{for(let o of r){if(mn(o)){let a=o.reason;t.set(a,(t.get(a)??0)+1)}let s=mo.getOrElse(v(o),()=>[]);s.length>0&&n(s)}};return n(e),t}function Za(e){try{let t=yo(e,"utf-8");return/from\s+["'](?:effect|effect\/|@effect\/)/.test(t)}catch{return!1}}function Xa(e){try{let t=yo(e,"utf-8");return/\bEffect\./.test(t)||/\bLayer\./.test(t)||/\bStream\./.test(t)||/\bSchema\./.test(t)||/\byield\*/.test(t)||/\bpipe\(/.test(t)||/\brunPromise\b/.test(t)||/\brunSync\b/.test(t)||/\brunFork\b/.test(t)||/\bacquireRelease\b/.test(t)?!1:/\binterface\b/.test(t)||/\btype\b/.test(t)||/\bdeclare\b/.test(t)||/^\s*import\s+type\b/m.test(t)||/^\s*export\s+type\b/m.test(t)}catch{return!1}}function ec(e){let t=e.replace(/\\/g,"/"),n=Ja(t).toLowerCase();if(n==="index.ts"||n==="index.tsx"||/\/index\.[jt]sx?$/.test(t))return"barrel_or_index";if(/(^|\/)(__tests__|test|tests|dtslint)(\/|$)/.test(t)||/\.(test|spec|tst)\.[jt]sx?$/.test(t))return"test_or_dtslint";if(/(^|\/)(vitest|vite|jest|webpack|rollup|tsup|esbuild|eslint|prettier|babel|playwright|typedoc|karma)\.config\.[jt]s$/.test(t)||/(^|\/)vitest\.workspace\.[jt]s$/.test(t))return"config_or_build";if(Xa(e))return"type_only"}async function zn(e,t,n,r){if(r>=n)return[];let o=[];try{let s=await ho(e,{withFileTypes:!0});for(let a of s){let i=tn(e,a.name);a.isDirectory()?a.name!=="node_modules"&&a.name!==".git"&&o.push(...await zn(i,t,n,r+1)):a.isFile()&&t.includes(So(a.name))&&o.push(i)}}catch{}return o}async function xo(e,t,n){if(n>=t)return[];let r=[];try{let o=await ho(e,{withFileTypes:!0});o.some(a=>a.isFile()&&a.name==="package.json")&&r.push(e);for(let a of o)a.isDirectory()&&a.name!=="node_modules"&&a.name!==".git"&&r.push(...await xo(tn(e,a.name),t,n+1))}catch{}return r}function Xt(e,t,n){if(!t||typeof t!="string")return[];let r=t.replace(/^\.\//,""),o=tn(e,r);return So(r)?[go(o)]:n.map(a=>go(o+a))}async function tc(e){try{let{Project:t,SyntaxKind:n}=I(),s=new t({skipAddingFilesFromTsConfig:!0}).addSourceFileAtPath(e).getDescendantsOfKind(n.CallExpression),a=[n.FunctionDeclaration,n.FunctionExpression,n.ArrowFunction,n.MethodDeclaration];for(let i of s){let c=i.getParent();if(c?.getKind()!==n.ExpressionStatement)continue;let d=c;for(;d;){let f=d.getKind();if(f===n.SourceFile||a.includes(f))break;d=d.getParent()}if(d?.getKind()!==n.SourceFile)continue;let l=i.getExpression().getText();if(l.includes(".runPromise")||l.includes(".runSync")||l.includes(".runFork")||l.includes(".runCallback")||l.includes("NodeRuntime.runMain")||l.includes("BunRuntime.runMain")||l.includes("DenoRuntime.runMain")||l.includes("Runtime.runPromise")||l.includes("Runtime.runSync")||l.includes("Runtime.runFork"))return!0}}catch{}return!1}async function nc(e,t){let n=await xo(e,10,0),r=[];for(let o of n)try{let s=await Va(tn(o,"package.json"),"utf-8"),a=JSON.parse(s),i=[Xt(o,a.main,t),Xt(o,a.module,t)];if(typeof a.bin=="string")i.push(Xt(o,a.bin,t));else if(a.bin&&typeof a.bin=="object")for(let c of Object.values(a.bin))i.push(Xt(o,typeof c=="string"?c:void 0,t));for(let c of i)for(let d of c)try{(await Ga(d).catch(()=>null))?.isFile()&&r.push(d)}catch{}}catch{}return[...new Set(r)]}function rc(e,t={}){let n=t.extensions??en.extensions,r=t.maxDepth??en.maxDepth;return ye.gen(function*(){let o=yield*ye.promise(()=>zn(e,n,r,0)),s=new Map,a=[],i=[],c=[],d=[];for(let u of o){let p=yield*At(u,{tsConfigPath:t.tsconfig,knownEffectInternalsRoot:t.knownEffectInternalsRoot}).all().pipe(ye.map(m=>({_tag:"ok",programs:m})),ye.catchAll(m=>ye.succeed({_tag:"fail",error:m instanceof Error?m.message:String(m)})));if(p._tag==="fail"){c.push({file:u,error:p.error});continue}let g=p.programs;if(g.length===0){d.push(u);continue}s.set(u,g),a.push(...g);for(let m of g){let h=m.root.programName==="main"||m.root.programName.includes("run"),x=m.root.source==="run";(h||x)&&(i.includes(u)||i.push(u))}}let l=yield*ye.promise(()=>nc(e,n));for(let u of l)o.includes(u)&&!i.includes(u)&&i.push(u);for(let u of s.keys()){if(i.includes(u))continue;(yield*ye.promise(()=>tc(u)))&&i.push(u)}let f;if(t.buildServiceMap)try{let{Project:u}=I(),p=new u({skipAddingFilesFromTsConfig:!0,compilerOptions:{allowJs:!0}}),g=new Map;for(let m of s.keys())try{let h=p.addSourceFileAtPath(m);g.set(m,h)}catch{}f=Zt(s,g)}catch{f=Zt(s)}return{byFile:s,allPrograms:a,entryPointFiles:i,fileCount:o.length,failedFiles:c,zeroProgramFiles:d,serviceMap:f}})}function oc(e,t={}){let n=t.extensions??en.extensions,r=t.maxDepth??en.maxDepth;return ye.gen(function*(){let o=Date.now(),s=yield*ye.promise(()=>zn(e,n,r,0)),a=[],i=0,c=0,d=[],l=new Map,f=t.includePerFileTiming===!0;for(let A of s){let W=f?Date.now():0,B=yield*At(A,{tsConfigPath:t.tsconfig,knownEffectInternalsRoot:t.knownEffectInternalsRoot}).all().pipe(ye.map(Y=>({_tag:"ok",programs:Y})),ye.catchAll(Y=>ye.succeed({_tag:"fail",error:Y instanceof Error?Y.message:String(Y)}))),J=f?Date.now()-W:void 0;if(B._tag==="ok"){let Y=B.programs.length,de=0,tt=0;for(let nt of B.programs){let ht=Ya(nt.root.children);i+=ht.total,c+=ht.unknown,de+=ht.total,tt+=ht.unknown;let L=Qa(nt.root.children);for(let[V,be]of L)l.set(V,(l.get(V)??0)+be)}de>0&&d.push({file:A,total:de,unknown:tt}),a.push(Y>0?{file:A,status:"ok",programCount:Y,...J!==void 0?{durationMs:J}:{}}:{file:A,status:"zero",programCount:0,...J!==void 0?{durationMs:J}:{}})}else{let Y=B.error??"",de=Y.includes("No Effect programs found")||Y.includes("NO_EFFECTS_FOUND");a.push(de?{file:A,status:"zero",programCount:0,...J!==void 0?{durationMs:J}:{}}:{file:A,status:"fail",error:B.error,...J!==void 0?{durationMs:J}:{}})}}let u=s.length,p=a.filter(A=>A.status==="ok").length,g=a.filter(A=>A.status==="zero").length,m=a.filter(A=>A.status==="fail").length,h=u>0?p/u*100:0,x=p+m>0?p/(p+m)*100:100,T=t.excludeFromSuspiciousZeros??[],S=A=>{let W=A.replace(/\\/g,"/");return T.some(B=>W.includes(B.replace(/\\/g,"/"))||W.endsWith(B.replace(/\\/g,"/")))},N={barrel_or_index:0,config_or_build:0,test_or_dtslint:0,type_only:0,suspicious:0,other:0},E=[],y=[],C=a.filter(A=>A.status==="zero");for(let A of C){let W=Za(A.file),B=ec(A.file),J=W&&!S(A.file)&&B===void 0?"suspicious":B??"other";N[J]++,y.push({file:A.file,category:J,importsEffect:W}),J==="suspicious"&&E.push(A.file)}let w=i>0?c/i:0,b=d.filter(A=>A.total>0).sort((A,W)=>W.unknown/W.total-A.unknown/A.total).slice(0,10).map(A=>A.file),P={};for(let[A,W]of l)P[A]=W;let F=[...l.entries()].sort((A,W)=>W[1]-A[1]).slice(0,20).map(([A,W])=>({reason:A,count:W})),O=Date.now()-o;return{discovered:u,analyzed:p,zeroPrograms:g,failed:m,outcomes:a,percentage:h,analyzableCoverage:x,unknownNodeRate:w,totalNodes:i,unknownNodes:c,suspiciousZeros:E,zeroProgramCategoryCounts:N,zeroProgramClassifications:y,topUnknownFiles:b,unknownReasonCounts:P,topUnknownReasons:F,durationMs:O}})}import{readdir as sc}from"fs/promises";import{join as ic,extname as ac}from"path";import{Project as cc,SyntaxKind as D}from"ts-morph";function R(e,t,n,r,o,s,a){let{line:i,column:c}=r.getLineAndColumnAtPos(n.getStart());e.push({filePath:t,line:i+1,column:c,pattern:o,suggestion:s,codeSnippet:a??r.getText().slice(n.getStart(),n.getStart()+80).replace(/\n/g," ")})}function Eo(e,t){let n=[],r=new cc({skipAddingFilesFromTsConfig:!0}),o=t?r.createSourceFile(e,t):r.addSourceFileAtPath(e);for(let l of o.getDescendantsOfKind(D.TryStatement))R(n,e,l,o,"try/catch","Effect.try or Effect.tryPromise with catch handler");for(let l of o.getDescendantsOfKind(D.CallExpression)){let u=l.getExpression().getText();(u==="Promise.all"||u.endsWith(".all")&&u.includes("Promise"))&&R(n,e,l,o,"Promise.all",'Effect.all([...], { concurrency: "unbounded" })'),(u==="Promise.race"||u.endsWith(".race")&&u.includes("Promise"))&&R(n,e,l,o,"Promise.race","Effect.race(first, second)")}for(let l of o.getDescendantsOfKind(D.CallExpression)){let u=l.getExpression().getText();(u==="setTimeout"||u==="setInterval")&&R(n,e,l,o,u,u==="setTimeout"?"Effect.sleep(Duration.millis(n))":"Schedule.spaced(Duration.millis(n))"),(u==="setImmediate"||u==="process.setImmediate")&&R(n,e,l,o,"setImmediate","Effect.sync + queueMicrotask or Effect.async")}for(let l of o.getDescendantsOfKind(D.NewExpression)){let u=l.getExpression().getText();(u==="XMLHttpRequest"||u.includes("XMLHttpRequest"))&&R(n,e,l,o,"new XMLHttpRequest()","HttpClient.request or @effect/platform HttpClient")}for(let l of o.getDescendantsOfKind(D.NewExpression)){let u=l.getExpression().getText();(u==="Worker"||u.includes("Worker"))&&R(n,e,l,o,"new Worker()","Worker.make or @effect/platform Worker")}for(let l of o.getDescendantsOfKind(D.CallExpression)){let u=l.getExpression().getText();(u==="fs.exists"||u.endsWith(".exists")&&u.startsWith("fs."))&&l.getArguments().length>=2&&R(n,e,l,o,"fs.exists (callback)","Effect.promise or fs.promises.access")}for(let l of o.getDescendantsOfKind(D.CallExpression)){let u=l.getExpression().getText();(u.endsWith(".request")&&(u.includes("http")||u.includes("https"))||u==="request"&&o.getText().includes("http"))&&R(n,e,l,o,"http.request / https.request","HttpClient.request or @effect/platform HttpClient")}for(let l of o.getDescendantsOfKind(D.CallExpression)){let u=l.getExpression().getText();(u.startsWith("dns.")||u.includes("dns."))&&(u.includes("lookup")||u.includes("resolve")||u.includes("reverse"))&&R(n,e,l,o,"dns (callback)","Effect.promise or dns.promises")}for(let l of o.getDescendantsOfKind(D.CallExpression))l.getExpression().getText()==="fetch"&&R(n,e,l,o,"fetch()","HttpClient.request or @effect/platform HttpClient");for(let l of o.getDescendantsOfKind(D.NewExpression)){let u=l.getExpression().getText();(u==="EventEmitter"||u.includes("EventEmitter"))&&R(n,e,l,o,"new EventEmitter()","PubSub.bounded<EventType>() or PubSub.unbounded<EventType>()")}for(let l of o.getDescendantsOfKind(D.CallExpression)){let u=l.getExpression().getText();(u.endsWith(".on(")||u.endsWith(".addListener("))&&(u.includes("Emitter")||u.includes("emitter"))&&R(n,e,l,o,"EventEmitter.on / addListener","PubSub.subscribe for PubSub"),u.endsWith(".emit(")&&(u.includes("Emitter")||u.includes("emitter"))&&R(n,e,l,o,"EventEmitter.emit","PubSub.publish for PubSub")}for(let l of o.getDescendantsOfKind(D.ClassDeclaration)){let f=l.getName(),u=l.getText();f&&(u.includes("new ")||u.includes("constructor"))&&(f.endsWith("Service")||f.endsWith("Repository")||f.endsWith("Client"))&&R(n,e,l,o,`class ${f} (manual DI)`,`Context.Tag<${f}>() + Layer.effect or Layer.succeed`)}for(let l of o.getDescendantsOfKind(D.NewExpression)){let u=l.getExpression().getText();(u.endsWith("Service")||u.endsWith("Repository")||u.endsWith("Client"))&&!u.includes("Context")&&!u.includes("Layer")&&R(n,e,l,o,`new ${u}()`,"Context.Tag + Layer.effect for dependency injection")}for(let l of o.getDescendantsOfKind(D.FunctionDeclaration))(l.getModifiers().some(f=>f.getText()==="async")||l.getText().startsWith("async"))&&R(n,e,l,o,"async function","Effect.gen or Effect.pipe with flatMap");for(let l of o.getDescendantsOfKind(D.ArrowFunction))l.getText().startsWith("async")&&R(n,e,l,o,"async arrow function","Effect.gen or Effect.pipe with flatMap");for(let l of o.getDescendantsOfKind(D.CallExpression)){let u=l.getExpression().getText();u.endsWith(".then")&&u.includes("Promise")&&R(n,e,l,o,"Promise.then","Effect.flatMap for sequential composition"),(u==="Promise.allSettled"||u.endsWith(".allSettled")&&u.includes("Promise"))&&R(n,e,l,o,"Promise.allSettled","Effect.all with merge or separate error handling"),u.endsWith(".catch")&&(u.includes("Promise")||u.includes(".then"))&&R(n,e,l,o,"Promise.catch","Effect.catchAll or Effect.catchTag for typed error handling"),u.endsWith(".finally")&&(u.includes("Promise")||u.includes(".then"))&&R(n,e,l,o,"Promise.finally","Effect.ensuring for cleanup")}for(let l of o.getDescendantsOfKind(D.CallExpression)){let u=l.getExpression().getText();(u==="addEventListener"||u.endsWith(".addEventListener"))&&R(n,e,l,o,"addEventListener","Effect.async or EventTarget + Effect.asyncInterrupt")}for(let l of o.getDescendantsOfKind(D.CallExpression)){let u=l.getExpression().getText();(u==="fs.readFile"||u==="fs.writeFile"||u==="readFile"||u==="writeFile"||u.endsWith(".readFile")&&u.startsWith("fs.")||u.endsWith(".writeFile")&&u.startsWith("fs."))&&l.getArguments().length>=2&&R(n,e,l,o,u.includes("write")?"fs.writeFile (callback)":"fs.readFile (callback)","Effect.promise or fs.promises + Effect.tryPromise")}for(let l of o.getDescendantsOfKind(D.ThrowStatement))R(n,e,l,o,"throw","Effect.fail(error) for typed error channel");for(let l of o.getDescendantsOfKind(D.CallExpression)){let u=l.getExpression().getText();(u==="promisify"||u.endsWith(".promisify"))&&R(n,e,l,o,"util.promisify","Effect.tryPromise or Effect.async for callback-style APIs")}for(let l of o.getDescendantsOfKind(D.NewExpression))l.getExpression().getText()==="Promise"&&R(n,e,l,o,"new Promise(...)","Effect.async or Effect.promise for callback-style");for(let l of o.getDescendantsOfKind(D.ForOfStatement))l.getAwaitKeyword()&&R(n,e,l,o,"for await...of","Stream.iterate or Effect.asyncIterable for async iteration");for(let l of o.getDescendantsOfKind(D.CallExpression)){let u=l.getExpression().getText();(u==="readFileSync"||u==="writeFileSync"||u==="existsSync"||u.endsWith(".readFileSync")||u.endsWith(".writeFileSync")||u.endsWith(".existsSync"))&&R(n,e,l,o,u,"Effect.promise or fs/promises + Effect.tryPromise")}for(let l of o.getDescendantsOfKind(D.CallExpression)){let u=l.getExpression().getText();(u==="process.nextTick"||u.endsWith(".nextTick")&&u.includes("process"))&&R(n,e,l,o,"process.nextTick","Effect.sync + queueMicrotask or Effect.async")}for(let l of o.getDescendantsOfKind(D.CallExpression)){let u=l.getExpression().getText();(u==="queueMicrotask"||u.endsWith(".queueMicrotask"))&&R(n,e,l,o,"queueMicrotask","Effect.sync for deferred execution")}for(let l of o.getDescendantsOfKind(D.NewExpression)){let u=l.getExpression().getText();(u==="WebSocket"||u.includes("WebSocket"))&&R(n,e,l,o,"new WebSocket()","Effect.async or @effect/platform WebSocket")}for(let l of o.getDescendantsOfKind(D.NewExpression)){let u=l.getExpression().getText();(u==="MessageChannel"||u.includes("MessageChannel"))&&R(n,e,l,o,"new MessageChannel()","Effect.async or Queue for cross-context messaging")}for(let l of o.getDescendantsOfKind(D.CallExpression)){let u=l.getExpression().getText();(u==="fs.appendFile"||u.endsWith(".appendFile")&&u.startsWith("fs."))&&l.getArguments().length>=2&&R(n,e,l,o,"fs.appendFile (callback)","Effect.promise or fs.promises.appendFile")}for(let l of o.getDescendantsOfKind(D.CallExpression)){let u=l.getExpression().getText();if((u==="fs.mkdir"||u==="fs.stat"||u==="fs.unlink"||u.endsWith(".mkdir")&&u.startsWith("fs.")||u.endsWith(".stat")&&u.startsWith("fs.")||u.endsWith(".unlink")&&u.startsWith("fs."))&&l.getArguments().length>=2){let g=u.includes("mkdir")?"fs.mkdir":u.includes("stat")?"fs.stat":"fs.unlink";R(n,e,l,o,`${g} (callback)`,"Effect.promise or fs.promises")}}for(let l of o.getDescendantsOfKind(D.NewExpression)){let u=l.getExpression().getText();(u==="MutationObserver"||u.includes("MutationObserver"))&&R(n,e,l,o,"new MutationObserver()","Effect.async or Effect.asyncInterrupt for DOM observation")}for(let l of o.getDescendantsOfKind(D.CallExpression)){let u=l.getExpression().getText();(u==="requestIdleCallback"||u.endsWith(".requestIdleCallback"))&&R(n,e,l,o,"requestIdleCallback","Effect.async or Effect.sync for idle-time work")}for(let l of o.getDescendantsOfKind(D.NewExpression)){let u=l.getExpression().getText();(u==="BroadcastChannel"||u.includes("BroadcastChannel"))&&R(n,e,l,o,"new BroadcastChannel()","PubSub or Effect.async for cross-tab messaging")}for(let l of o.getDescendantsOfKind(D.CallExpression)){let u=l.getExpression().getText();if((u==="fs.rename"||u==="fs.realpath"||u.endsWith(".rename")&&u.startsWith("fs.")||u.endsWith(".realpath")&&u.startsWith("fs."))&&l.getArguments().length>=2){let g=u.includes("realpath")?"fs.realpath":"fs.rename";R(n,e,l,o,`${g} (callback)`,"Effect.promise or fs.promises")}}for(let l of o.getDescendantsOfKind(D.CallExpression)){let u=l.getExpression().getText(),p=(u==="fs.readdir"||u.endsWith(".readdir")&&u.startsWith("fs."))&&l.getArguments().length>=2,g=(u==="fs.copyFile"||u.endsWith(".copyFile")&&u.startsWith("fs."))&&l.getArguments().length>=2;p&&R(n,e,l,o,"fs.readdir (callback)","Effect.promise or fs.promises.readdir"),g&&R(n,e,l,o,"fs.copyFile (callback)","Effect.promise or fs.promises.copyFile")}for(let l of o.getDescendantsOfKind(D.NewExpression)){let u=l.getExpression().getText();(u==="FileReader"||u.includes("FileReader"))&&R(n,e,l,o,"new FileReader()","Effect.async or FileReader + Effect.asyncInterrupt")}for(let l of o.getDescendantsOfKind(D.CallExpression)){let u=l.getExpression().getText(),p=(u==="fs.mkdtemp"||u.endsWith(".mkdtemp")&&u.startsWith("fs."))&&l.getArguments().length>=2,g=(u==="fs.symlink"||u.endsWith(".symlink")&&u.startsWith("fs."))&&l.getArguments().length>=2;p&&R(n,e,l,o,"fs.mkdtemp (callback)","Effect.promise or fs.promises.mkdtemp"),g&&R(n,e,l,o,"fs.symlink (callback)","Effect.promise or fs.promises.symlink")}for(let l of o.getDescendantsOfKind(D.NewExpression)){let u=l.getExpression().getText();(u==="ResizeObserver"||u==="IntersectionObserver"||u.includes("ResizeObserver")||u.includes("IntersectionObserver"))&&R(n,e,l,o,`new ${u}()`,"Effect.async or Effect.asyncInterrupt for DOM observation")}let s=o.getText().includes("child_process");for(let l of o.getDescendantsOfKind(D.CallExpression)){let u=l.getExpression().getText();(u.includes("child_process")&&u.endsWith(".fork")||s&&u==="fork")&&R(n,e,l,o,"child_process.fork","Worker.make or @effect/platform Worker")}for(let l of o.getDescendantsOfKind(D.NewExpression)){let u=l.getExpression().getText();(u==="AbortController"||u.includes("AbortController"))&&R(n,e,l,o,"new AbortController()","Effect.Scoped or Effect.interruptible for cancellation")}let a=o.getText(),i=a.includes("child_process");for(let l of o.getDescendantsOfKind(D.CallExpression)){let u=l.getExpression().getText();((u.endsWith(".exec")||u.endsWith(".execSync")||u.endsWith(".spawn"))&&u.includes("child_process")||i&&(u==="exec"||u==="execSync"||u==="spawn"))&&R(n,e,l,o,"child_process.exec/spawn","@effect/platform CommandExecutor or Effect.promise")}for(let l of o.getDescendantsOfKind(D.PropertyAccessExpression))l.getExpression().getText()==="process"&&l.getName()==="env"&&R(n,e,l,o,"process.env","Config.string or Config.forEffect for typed config");if(a.includes("rxjs")||a.includes("Observable"))for(let l of o.getDescendantsOfKind(D.CallExpression)){let u=l.getExpression().getText();(u.includes("Observable")||u.includes("of")&&u.includes("rxjs"))&&R(n,e,l,o,"RxJS Observable","Stream from @effect/platform or Effect Stream")}for(let l of o.getDescendantsOfKind(D.NewExpression)){let u=l.getExpression().getText();(u.includes("Observable")||u.includes("Subject"))&&R(n,e,l,o,"RxJS Observable/Subject","Stream or PubSub for Effect")}for(let l of o.getDescendantsOfKind(D.CallExpression)){let u=l.getExpression().getText();(u==="requestAnimationFrame"||u.endsWith(".requestAnimationFrame"))&&R(n,e,l,o,"requestAnimationFrame","Effect.async or Effect.sync + queueMicrotask for scheduling")}for(let l of o.getDescendantsOfKind(D.CallExpression)){let u=l.getExpression().getText();(u.includes("crypto.")||u.includes("randomBytes")||u.includes("scrypt")||u.includes("pbkdf2"))&&l.getArguments().length>=2&&R(n,e,l,o,"crypto (callback)","Effect.promise or crypto.webcrypto / node:crypto promises")}for(let l of o.getDescendantsOfKind(D.CallExpression)){let u=l.getExpression().getText();(u==="createReadStream"||u==="createWriteStream"||u.endsWith(".createReadStream")||u.endsWith(".createWriteStream"))&&R(n,e,l,o,u,"Stream.fromReadable or @effect/platform FileSystem/Stream")}for(let l of o.getDescendantsOfKind(D.CallExpression)){let u=l.getExpression().getText();u.includes("cluster")&&u.endsWith(".fork")&&R(n,e,l,o,"cluster.fork","Worker.make or @effect/platform Worker pool")}for(let l of o.getDescendantsOfKind(D.CallExpression)){let f=l.getExpression(),u=f.getText();if(u==="createServer"||u==="connect"||u.endsWith(".createServer")||u.endsWith(".connect")){let p=f.getText();(p.includes("net")||p.includes("tls"))&&R(n,e,l,o,p,"Effect.async or @effect/platform Socket/Server")}}for(let l of o.getDescendantsOfKind(D.CallExpression)){let u=l.getExpression().getText();u.includes("zlib.")&&(u.includes("deflate")||u.includes("inflate")||u.includes("gzip")||u.includes("gunzip"))&&R(n,e,l,o,"zlib (callback)","Effect.promise or zlib.promises")}for(let l of o.getDescendantsOfKind(D.CallExpression)){let u=l.getExpression().getText();(u==="createInterface"||u.endsWith(".createInterface"))&&u.includes("readline")&&R(n,e,l,o,"readline.createInterface","Effect.async or Stream for line-by-line reading")}let d=o.getText().includes("stream");for(let l of o.getDescendantsOfKind(D.CallExpression)){let u=l.getExpression().getText();(u.endsWith(".pipeline")&&u.includes("stream")||d&&u==="pipeline")&&R(n,e,l,o,"stream.pipeline (callback)","Effect.promise or stream.promises.pipeline")}for(let l of o.getDescendantsOfKind(D.CallExpression)){let u=l.getExpression().getText();(u==="once"||u.endsWith(".once"))&&(u.includes("events")||o.getText().includes("from 'events'"))&&R(n,e,l,o,"events.once","Effect.async for one-shot event")}for(let l of o.getDescendantsOfKind(D.CallExpression)){let f=l.getExpression(),u=f.getText();(u==="watch"||u==="watchFile"||u.endsWith(".watch")||u.endsWith(".watchFile"))&&(u.includes("fs")||f.getText().includes("fs."))&&R(n,e,l,o,"fs.watch / fs.watchFile","Effect.async or fs.watch with EventEmitter")}for(let l of o.getDescendantsOfKind(D.CallExpression)){let u=l.getExpression().getText();(u.includes("runInNewContext")||u.includes("runInContext")||u.includes("runInThisContext"))&&u.includes("vm")&&R(n,e,l,o,"vm.runIn*","Effect.sync for isolated code execution")}for(let l of o.getDescendantsOfKind(D.CallExpression)){let u=l.getExpression().getText();(u==="parse"||u.endsWith(".parse"))&&u.includes("url")&&R(n,e,l,o,"url.parse (deprecated)","new URL() or URL.parse for standard parsing")}for(let l of o.getDescendantsOfKind(D.CallExpression)){let u=l.getExpression().getText();(u.endsWith(".spawnSync")&&u.includes("child_process")||o.getText().includes("child_process")&&u==="spawnSync")&&R(n,e,l,o,"child_process.spawnSync","@effect/platform CommandExecutor or Effect.promise")}for(let l of o.getDescendantsOfKind(D.CallExpression)){let u=l.getExpression().getText();(u==="glob"||u.endsWith(".glob"))&&o.getText().includes("glob")&&l.getArguments().length>=2&&R(n,e,l,o,"glob (callback)","Effect.promise or glob promise API")}for(let l of o.getDescendantsOfKind(D.CallExpression)){let u=l.getExpression().getText(),p=u.includes("assert")&&u.endsWith(".throws"),g=u.endsWith(".rejects")&&u.includes("expect");(p||g)&&R(n,e,l,o,g?"expect().rejects":"assert.throws","Effect.runPromiseExit + Exit.match for testing Effect failures")}for(let l of o.getDescendantsOfKind(D.CallExpression)){let u=l.getExpression().getText();u.includes("tls")&&(u.endsWith(".connect")||u.endsWith(".createServer"))&&R(n,e,l,o,"tls.connect / tls.createServer","Effect.async or @effect/platform Socket/TLS")}return n}async function lc(e,t){let n=t?.extensions??[".ts",".tsx"],r=[],o=0;async function s(a){let i=await sc(a,{withFileTypes:!0}).catch(()=>[]);for(let c of i){let d=ic(a,c.name);if(c.isDirectory())c.name!=="node_modules"&&c.name!==".git"&&c.name!=="dist"&&await s(d);else if(c.isFile()&&n.includes(ac(c.name))){o++;try{r.push(...Eo(d))}catch{}}}}return await s(e),{opportunities:r,fileCount:o}}function dc(e){let t=[];t.push("Migration Opportunities Found:"),t.push("");for(let n of e.opportunities)t.push(` ${n.filePath}:${n.line}:${n.column} ${n.pattern}`),t.push(` \u2192 ${n.suggestion}`),n.codeSnippet&&t.push(` Snippet: ${n.codeSnippet.slice(0,60)}...`),t.push("");return t.push(`Total: ${e.opportunities.length} opportunities in ${e.fileCount} files`),t.join(`
|
|
6
|
+
`)}import{Effect as Io,Option as Ao}from"effect";import{Option as uc}from"effect";function bo(e,t){for(let n of e){n.type==="effect"&&t.push(n);let r=uc.getOrElse(v(n),()=>[]);r.length>0&&bo(r,t)}}function Ft(e){let t=[],n=[],r=new Set,o=new Map,s=[];bo(e.root.children,s);for(let d of s){let l=d.typeSignature?.successType,f=(d.requiredServices??[]).map(u=>u.serviceId);if(l){r.add(l);let u=o.get(l)??[];u.push(d.id),o.set(l,u)}t.push({id:d.id,name:d.callee,writes:l,reads:f,location:d.location?{line:d.location.line,column:d.location.column}:void 0})}for(let d=0;d<s.length-1;d++){let l=s[d],f=s[d+1];if(l===void 0||f===void 0)continue;let u=l.typeSignature?.successType??"value";n.push({from:l.id,to:f.id,key:u})}let a="__context__";for(let d of t)for(let l of d.reads)n.push({from:a,to:d.id,key:l});let i=[];for(let d of t)for(let l of d.reads)!r.has(l)&&l!==a&&i.push({key:l,readerId:d.id,readerName:d.name});let c=[];for(let[d,l]of o)l.length>1&&c.push({key:d,writerIds:l});return{nodes:t,edges:n,producedKeys:r,undefinedReads:i,duplicateWrites:c}}function fc(e){let t=new Map,n=new Map;for(let s of e.nodes)t.set(s.id,0),n.set(s.id,[]);for(let s of e.edges){if(s.from==="__context__")continue;let a=n.get(s.from)??[];a.push(s.to),n.set(s.from,a),t.set(s.to,(t.get(s.to)??0)+1)}let r=[];for(let[s,a]of t)s!=="__context__"&&a===0&&r.push(s);let o=[];for(;r.length>0;){let s=r.shift();if(s===void 0)break;o.push(s);for(let a of n.get(s)??[]){let i=(t.get(a)??0)-1;t.set(a,i),i===0&&r.push(a)}}if(o.length===e.nodes.length)return o}function pc(e,t){let n=new Set;for(let r of e.edges)r.to===t&&r.from!=="__context__"&&n.add(r.from);return e.nodes.filter(r=>n.has(r.id))}function gc(e,t){let n=new Set;for(let r of e.edges)r.from===t&&n.add(r.to);return e.nodes.filter(r=>n.has(r.id))}function mc(e,t){let n=new Set,r=[];function o(s){if(!(n.has(s)||s==="__context__")){n.add(s);for(let a of e.edges)a.to===s&&(r.push(a.from),o(a.from))}}return o(t),r}function Co(e){let t=[],n=new Set,r=new Set,o=new Map;for(let a of e.nodes)o.set(a.id,[]);for(let a of e.edges){if(a.from==="__context__")continue;let i=o.get(a.from)??[];i.push(a.to),o.set(a.from,i)}function s(a,i){n.add(a),r.add(a),i.push(a);for(let c of o.get(a)??[])if(!n.has(c))s(c,i);else if(r.has(c)){let d=i.indexOf(c);t.push(i.slice(d))}i.pop(),r.delete(a)}for(let a of e.nodes)n.has(a.id)||s(a.id,[]);return t}function hc(e){let t=[];for(let r of e.undefinedReads)t.push({severity:"warning",type:"undefined-read",message:`Effect "${r.readerName??r.readerId}" reads "${r.key}" which is never produced`,stepIds:[r.readerId],key:r.key});for(let r of e.duplicateWrites)t.push({severity:"warning",type:"duplicate-write",message:`Key "${r.key}" is written by multiple effects: ${r.writerIds.join(", ")}`,stepIds:r.writerIds,key:r.key});let n=Co(e);for(let r of n)t.push({severity:"error",type:"cycle",message:`Circular data dependency: ${r.join(" -> ")}`,stepIds:r});return{valid:t.length===0,issues:t}}function lt(e){return e.replace(/[^a-zA-Z0-9_]/g,"_")}function yc(e){let t=[];t.push("flowchart LR"),t.push(""),t.push(" %% Data Flow Graph"),t.push("");for(let n of e.nodes){let r=n.name??n.id,o=n.writes?` [out: ${n.writes}]`:"";t.push(` ${lt(n.id)}["${r}${o}"]`)}t.push("");for(let n of e.edges)n.from!=="__context__"&&t.push(` ${lt(n.from)} -->|${n.key}| ${lt(n.to)}`);if(e.undefinedReads.length>0){t.push(""),t.push(" %% Undefined Reads (warnings)");for(let n of e.undefinedReads){let r=`undefined_${lt(n.key)}`;t.push(` ${r}[/"${n.key} (undefined)"/]`),t.push(` ${r} -.-> ${lt(n.readerId)}`)}t.push(""),t.push(" classDef warning fill:#fff3cd,stroke:#856404");for(let n of e.undefinedReads)t.push(` class undefined_${lt(n.key)} warning`)}return t.join(`
|
|
7
|
+
`)}import{Option as ft}from"effect";function Hn(e){let t=e.trim();return t==="never"||t==="unknown"?[]:Ae(t)}function No(e,t){for(let n of e){if(n.type==="effect"){let o=n,s=o.typeSignature?.errorType?Hn(o.typeSignature.errorType):[];t.push({stepId:o.id,stepName:o.callee,errors:s,location:o.location?{line:o.location.line,column:o.location.column}:void 0})}let r=ft.getOrElse(v(n),()=>[]);r.length>0&&No(r,t)}}function Ye(e){let t=[],n=new Set,r=new Map,o=[];No(e.root.children,t);for(let s of t){s.errors.length===0&&o.push(s.stepId);for(let a of s.errors){n.add(a);let i=r.get(a)??[];i.push(s.stepId),r.set(a,i)}}return{allErrors:Array.from(n).sort(),stepErrors:t,errorToSteps:r,stepsWithoutErrors:o,allStepsDeclareErrors:o.length===0&&t.length>0}}function nn(e,t){return Array.from(new Set([...e,...t])).sort()}function Sc(e,t){let n=new Set(t);return e.filter(r=>!n.has(r))}function xc(e){let t=[],n=r=>{if(r.type==="effect"){let s=r.typeSignature?.errorType;s&&t.push(...Hn(s))}ft.getOrElse(v(r),()=>[]).forEach(n)};return n(e),nn([],t)}function To(e){if(e.type==="cause")return e.causeKind;let t=ft.getOrElse(v(e),()=>[]);for(let n of t){let r=To(n);if(r)return r}}function ut(e,t,n){let r=[...t];for(let o of e)if(o.type==="effect"){let s=o,a=s.typeSignature?.errorType?Hn(s.typeSignature.errorType):[];r=nn(r,a),n.push({atNode:s.id,possibleErrors:[...r],defects:[],interruptible:!1});let i=ft.getOrElse(v(o),()=>[]);i.length>0&&(r=ut(i,r,n))}else if(o.type==="error-handler"){let s=o;r=ut([s.source],r,n);let a=[...r],i=[];s.handlerType==="catchTag"&&s.errorTag?i.push(s.errorTag):s.handlerType==="catchTags"?s.errorTags&&s.errorTags.length>0?i.push(...a.filter(l=>s.errorTags?s.errorTags.includes(l):!1)):i.push(...a.filter(l=>/Error$|^[A-Z]/.test(l))):s.handlerType==="catchIf"||s.handlerType==="catchSome"||s.handlerType==="catchSomeCause"||s.handlerType==="catchSomeDefect"?i.push(...a.slice(0,Math.ceil(a.length/2))):s.handlerType==="catchAll"||s.handlerType==="catchAllCause"||s.handlerType==="catchAllDefect"||s.handlerType==="orElse"||s.handlerType==="orDie"||s.handlerType==="orDieWith"?i.push(...a):s.handlerType==="mapError"||s.handlerType==="mapErrorCause"||s.handlerType==="mapBoth"?i.push(...a):s.handlerType==="sandbox"?i.push(...a):s.handlerType==="ignore"||s.handlerType==="ignoreLogged"?i.push(...a):s.handlerType==="orElseFail"||s.handlerType==="orElseSucceed"?i.push(...a):(s.handlerType==="filterOrDie"||s.handlerType==="filterOrDieMessage")&&i.push(...a);let c=Sc(r,i),d=s.handler?xc(s.handler):[];if((s.handlerType==="mapError"||s.handlerType==="mapErrorCause"||s.handlerType==="mapBoth")&&i.length>0&&d.length===0){let l=To(s.source);l==="fail"?d=["<mapped-fail>"]:l==="die"?d=["<mapped-defect>"]:d=["<mapped-error>"]}r=nn(c,d),n.push({atNode:s.id,possibleErrors:[...r],narrowedBy:{handler:s.handlerType,removedErrors:i,addedErrors:d},defects:[],interruptible:!1}),s.handler&&(r=ut([s.handler],r,n))}else if(o.type==="parallel"||o.type==="race"){let s=ft.getOrElse(v(o),()=>[]),a=[];for(let i of s){let c=ut([i],r,n);a=nn(a,c)}r=a}else{let s=ft.getOrElse(v(o),()=>[]);s.length>0&&(r=ut(s,r,n))}return r}function Rt(e){let t=[];ut(e.root.children,[],t);let n=new Map;for(let r of t)n.set(r.atNode,r);return{propagation:t,byNodeId:n}}function Ec(e,t){let n=new Set,r=!1;for(let o of e.stepErrors){for(let s of o.errors)n.add(s);if(o.stepId===t){r=!0;break}}return r?Array.from(n).sort():e.allErrors}function bc(e,t){let n=e.errorToSteps.get(t)??[];return e.stepErrors.filter(r=>n.includes(r.stepId))}function Cc(e,t){let n=new Set(t),r=new Set(e.allErrors),o=t.filter(a=>!r.has(a)),s=e.allErrors.filter(a=>!n.has(a));return{valid:o.length===0&&s.length===0,unusedDeclared:o,undeclaredErrors:s,computedErrors:e.allErrors}}function dt(e){return e.replace(/[^a-zA-Z0-9_]/g,"_")}function Nc(e){let t=[];t.push("flowchart LR"),t.push(""),t.push(" %% Error Flow Graph"),t.push(""),t.push(" subgraph Steps");for(let n of e.stepErrors){let r=n.stepName??n.stepId;t.push(` ${dt(n.stepId)}["${r}"]`)}if(t.push(" end"),t.push(""),e.allErrors.length>0){t.push(" subgraph Errors");for(let n of e.allErrors)t.push(` err_${dt(n)}(["${n}"])`);t.push(" end"),t.push("");for(let n of e.stepErrors)for(let r of n.errors)t.push(` ${dt(n.stepId)} -.->|throws| err_${dt(r)}`)}t.push(""),t.push(" classDef error fill:#ffcdd2,stroke:#c62828");for(let n of e.allErrors)t.push(` class err_${dt(n)} error`);if(e.stepsWithoutErrors.length>0){t.push(""),t.push(" classDef noErrors fill:#fff3cd,stroke:#856404");for(let n of e.stepsWithoutErrors)t.push(` class ${dt(n)} noErrors`)}return t.join(`
|
|
8
|
+
`)}function Tc(e){let t=[];if(t.push("## Error Flow Summary"),t.push(""),t.push(`**Total Effects:** ${e.stepErrors.length}`),t.push(`**Total Error Types:** ${e.allErrors.length}`),t.push(`**Effects Without Declared Errors:** ${e.stepsWithoutErrors.length}`),t.push(""),e.allErrors.length>0){t.push("### Error Types"),t.push("");for(let n of e.allErrors){let r=e.errorToSteps.get(n)??[];t.push(`- \`${n}\` - produced by: ${r.join(", ")}`)}t.push("")}if(e.stepsWithoutErrors.length>0){t.push("### Effects Without Declared Errors"),t.push(""),t.push("The following effects do not declare their error type (typeSignature.errorType):"),t.push("");for(let n of e.stepsWithoutErrors)t.push(`- ${n}`);t.push("")}t.push("### Effect Error Details"),t.push(""),t.push("| Effect | Errors |"),t.push("|--------|--------|");for(let n of e.stepErrors){let r=n.stepName??n.stepId,o=n.errors.length>0?n.errors.map(s=>`\`${s}\``).join(", "):"_none_";t.push(`| ${r} | ${o} |`)}return t.join(`
|
|
9
|
+
`)}var Fo={effect:"fill:#90EE90,stroke:#333,stroke-width:2px",generator:"fill:#FFB6C1,stroke:#333,stroke-width:2px",pipe:"fill:#ADD8E6,stroke:#333,stroke-width:2px",parallel:"fill:#FFA500,stroke:#333,stroke-width:2px",race:"fill:#FF6347,stroke:#333,stroke-width:2px",errorHandler:"fill:#FFD700,stroke:#333,stroke-width:2px",retry:"fill:#EE82EE,stroke:#333,stroke-width:2px",timeout:"fill:#87CEEB,stroke:#333,stroke-width:2px",resource:"fill:#98FB98,stroke:#333,stroke-width:2px",conditional:"fill:#DDA0DD,stroke:#333,stroke-width:2px",loop:"fill:#F0E68C,stroke:#333,stroke-width:2px",layer:"fill:#E6E6FA,stroke:#333,stroke-width:2px",stream:"fill:#E0F7FA,stroke:#333,stroke-width:2px",concurrencyPrimitive:"fill:#B0E0E6,stroke:#333,stroke-width:2px",fiber:"fill:#DDA0DD,stroke:#333,stroke-width:2px",decision:"fill:#DDA0DD,stroke:#333,stroke-width:2px",switch:"fill:#FFD700,stroke:#333,stroke-width:2px",tryCatch:"fill:#FFE4B5,stroke:#333,stroke-width:2px",terminal:"fill:#FF6B6B,stroke:#333,stroke-width:2px",opaque:"fill:#FF9800,stroke:#333,stroke-width:2px",unknown:"fill:#D3D3D3,stroke:#333,stroke-width:1px",start:"fill:#c8e6c9,stroke:#2e7d32",end:"fill:#ffcdd2,stroke:#c62828",cause:"fill:#FF8A80,stroke:#D32F2F,stroke-width:2px",exit:"fill:#B39DDB,stroke:#512DA8,stroke-width:2px",schedule:"fill:#80DEEA,stroke:#00838F,stroke-width:2px",match:"fill:#FFE082,stroke:#F57F17,stroke-width:2px",transform:"fill:#A5D6A7,stroke:#388E3C,stroke-width:2px",channel:"fill:#90CAF9,stroke:#1565C0,stroke-width:2px",sink:"fill:#CE93D8,stroke:#7B1FA2,stroke-width:2px",interruption:"fill:#FFAB91,stroke:#BF360C,stroke-width:2px"},Un={direction:"TB",includeIds:!1,includeDescriptions:!0,styles:Fo,compact:!1,includeTypeSignatures:!0,useSubgraphs:!0,showConditions:!0,detail:"verbose"};function te(e){return e.replace(/\r?\n/g," ").replace(/"/g,"'").replace(/\[/g,"(").replace(/\]/g,")").replace(/\{/g,"(").replace(/\}/g,")").replace(/#/g,"#").replace(/\|/g,"|")}function pt(e,t){return e.length<=t?e:e.slice(0,t-3)+"..."}function vc(e){return e.replace(/[^a-zA-Z0-9_]/g,"_")}function Ro(e,t,n){let r={...Un,...t,useSubgraphs:t?.useSubgraphs??!0,showConditions:t?.showConditions??!0,detail:t?.detail??"verbose"},o={opts:r,nodeCounter:0,edges:[],subgraphs:[],styleClasses:new Map,nodeIdMap:new Map,nodeLabelAnnotations:n},s=[];s.push(`flowchart ${r.direction}`),s.push(""),s.push(` %% Program: ${e.root.programName}`),s.push("");let a="start",i="end_node";s.push(` ${a}((Start))`),s.push(` ${i}((End))`),s.push("");let{firstNodeId:c,lastNodeIds:d}=Se(e.root.children,o,s);c&&o.edges.push({from:a,to:c});for(let f of d)o.edges.push({from:f,to:i});for(let f of o.subgraphs){s.push(""),s.push(` subgraph ${f.id}["${f.label}"]`);for(let u of f.content)s.push(` ${u}`);s.push(" end")}s.push(""),s.push(" %% Edges");for(let f of o.edges)f.label&&r.showConditions?s.push(` ${f.from} -->|${te(f.label)}| ${f.to}`):s.push(` ${f.from} --> ${f.to}`);let l={...Fo,...r.styles};s.push(""),s.push(" %% Styles"),l.start&&s.push(` classDef startStyle ${l.start}`),l.end&&s.push(` classDef endStyle ${l.end}`);for(let[f,u]of Object.entries(l))u&&f!=="start"&&f!=="end"&&s.push(` classDef ${f}Style ${u}`);s.push(` class ${a} startStyle`),s.push(` class ${i} endStyle`);for(let[f,u]of o.styleClasses)s.push(` class ${f} ${u}`);if(t?.dataFlowOverlay){let f=Ft(e),u=o.nodeIdMap;s.push(""),s.push(" %% Data-flow variable annotations"),s.push(" linkStyle default stroke:#999");for(let p of f.edges){if(p.from==="__context__")continue;let g=u.get(p.from),m=u.get(p.to);g&&m&&p.key&&p.key!=="value"&&s.push(` ${g} -.->|${p.key}| ${m}`)}if(f.undefinedReads.length>0){s.push(""),s.push(" %% Data-flow warnings"),s.push(" classDef dataFlowWarning fill:#fff3cd,stroke:#856404,stroke-width:2px");for(let p of f.undefinedReads){let g=u.get(p.readerId);g&&s.push(` class ${g} dataFlowWarning`)}}if(f.duplicateWrites.length>0){s.push(" classDef duplicateWrite fill:#f8d7da,stroke:#721c24,stroke-width:2px");for(let p of f.duplicateWrites)for(let g of p.writerIds){let m=u.get(g);m&&s.push(` class ${m} duplicateWrite`)}}}if(t?.errorFlowOverlay){let f=Ye(e),u=Rt(e),p=o.nodeIdMap;s.push(""),s.push(" %% Error-flow overlay"),s.push(" classDef canFail fill:#FFECB3,stroke:#F57F17,stroke-width:2px"),s.push(" classDef unhandledError fill:#FFCDD2,stroke:#C62828,stroke-width:3px");for(let g of f.stepErrors)if(g.errors.length>0){let m=p.get(g.stepId);m&&s.push(` class ${m} canFail`)}for(let g of u.propagation)if(g.possibleErrors.length>0&&!g.narrowedBy){let m=p.get(g.atNode);m&&s.push(` class ${m} unhandledError`)}for(let g of u.propagation)if(g.narrowedBy&&g.narrowedBy.removedErrors.length>0){let m=p.get(g.narrowedBy.handler),h=p.get(g.atNode);if(m&&h){let x=g.narrowedBy.removedErrors.join(", ");s.push(` ${h} -.->|catches ${x}| ${m}`)}}}return{lines:s,context:o}}function Se(e,t,n){if(e.length===0)return{firstNodeId:null,lastNodeIds:[]};let r=null,o=[];for(let s of e){let a=ee(s,t,n);if(r===null&&a.firstNodeId&&(r=a.firstNodeId),a.firstNodeId)for(let i of o)t.edges.push({from:i,to:a.firstNodeId});o=a.lastNodeIds}return{firstNodeId:r,lastNodeIds:o}}function wc(e,t){let n=t.opts.includeIds&&"id"in e?e.id:`n${String(++t.nodeCounter)}`;return vc(n)}function kc(e,t,n){if(!t.includeDescriptions)return e.type;let r;switch(e.type){case"effect":r=j(e.callee||"Effect",_);break;case"generator":r=`Generator (${e.yields.length} yields)`;break;case"pipe":r=`Pipe (${e.transformations.length+1} steps)`;break;case"parallel":r=j(`${e.callee} (${e.children.length} effects)`,_);break;case"race":r=j(`${e.callee} (${e.children.length} racing)`,_);break;case"error-handler":r=e.handlerType;break;case"retry":r=`Retry${e.schedule?`(${e.schedule})`:""}`;break;case"timeout":r=`Timeout${e.duration?`(${e.duration})`:""}`;break;case"resource":r="Resource";break;case"conditional":r=`${e.conditionalType} (${pt(e.condition,20)})`;break;case"loop":r=e.iterSource?j(`${e.loopType}(${e.iterSource})`,_):e.loopType;break;case"layer":r=`Layer${e.isMerged?" (merged)":""}`;break;case"stream":r=j(`Stream${e.pipeline.length>0?`.${e.pipeline.map(o=>o.operation).join(" \u2192 ")}`:""}${e.sink?` \u2192 ${e.sink}`:""}`,_);break;case"concurrency-primitive":r=`${e.primitive}.${e.operation}${e.strategy?` (${e.strategy})`:""}`;break;case"fiber":r=`${e.operation}${e.isDaemon?" (daemon)":""}${e.isScoped?" (scoped)":""}`;break;case"decision":r=e.label||pt(e.condition,30);break;case"switch":r=`Switch: ${pt(e.expression,25)}`;break;case"try-catch":r="Try/Catch";break;case"terminal":r=e.terminalKind;break;case"opaque":r=`\u26A0 ${e.reason}`;break;case"cause":r=`Cause: ${e.causeOp}`;break;case"exit":r=`Exit: ${e.exitOp}`;break;case"schedule":r=`Schedule: ${e.scheduleOp}`;break;case"match":r=`Match: ${e.matchOp}${e.matchedTags?.length?` (${e.matchedTags.join(", ")})`:""}`;break;case"transform":r=`${e.transformType}${e.isEffectful?" (effectful)":""}`;break;case"channel":r=`Channel${e.pipeline.length>0?`.${e.pipeline.map(o=>o.operation).join(" \u2192 ")}`:""}`;break;case"sink":r=`Sink${e.pipeline.length>0?`.${e.pipeline.map(o=>o.operation).join(" \u2192 ")}`:""}`;break;case"interruption":r=e.interruptionType;break;case"unknown":r=`Unknown: ${e.reason}`;break;default:{r=e.type??"unknown";break}}if(t.detail!=="compact"&&e.displayName&&(r=e.displayName),t.detail==="verbose"){if(e.type==="effect"&&t.includeTypeSignatures&&e.typeSignature){let o=e.typeSignature;r+=`
|
|
10
|
+
<${o.successType}, ${o.errorType}, ${o.requirementsType}>`}e.semanticRole&&e.semanticRole!=="unknown"&&e.semanticRole!=="constructor"&&(r+=`
|
|
11
|
+
(${e.semanticRole})`)}return n?.length&&(r+=`
|
|
12
|
+
`+n.join(`
|
|
13
|
+
`)),r}function Ic(e){return e.type==="concurrency-primitive"?"concurrencyPrimitiveStyle":e.type==="try-catch"?"tryCatchStyle":e.type==="error-handler"?"errorHandlerStyle":`${e.type}Style`}function ee(e,t,n){let r=wc(e,t),o=t.nodeLabelAnnotations?.get(e.id),s=kc(e,t.opts,o),a=Ic(e);switch(e.type!=="generator"&&(n.push(` ${r}["${te(s)}"]`),t.styleClasses.set(r,a),t.nodeIdMap.set(e.id,r)),e.type){case"effect":case"unknown":return{firstNodeId:r,lastNodeIds:[r]};case"stream":{let i=ee(e.source,t,n);return i.firstNodeId&&t.edges.push({from:r,to:i.firstNodeId}),{firstNodeId:r,lastNodeIds:i.lastNodeIds}}case"concurrency-primitive":{if(e.source){let i=ee(e.source,t,n);return i.firstNodeId&&t.edges.push({from:r,to:i.firstNodeId}),{firstNodeId:r,lastNodeIds:i.lastNodeIds}}return{firstNodeId:r,lastNodeIds:[r]}}case"fiber":{if(e.fiberSource){let i=ee(e.fiberSource,t,n);return i.firstNodeId&&t.edges.push({from:r,to:i.firstNodeId}),{firstNodeId:r,lastNodeIds:i.lastNodeIds}}return{firstNodeId:r,lastNodeIds:[r]}}case"generator":{let i=e.yields.map(d=>d.effect),c=Se(i,t,n);return c.firstNodeId?{firstNodeId:c.firstNodeId,lastNodeIds:c.lastNodeIds.length>0?c.lastNodeIds:[c.firstNodeId]}:(n.push(` ${r}["${te(s)}"]`),t.styleClasses.set(r,a),t.nodeIdMap.set(e.id,r),{firstNodeId:r,lastNodeIds:[r]})}case"pipe":{let i=[e.initial,...e.transformations],c=Se(i,t,n);return c.firstNodeId&&t.edges.push({from:r,to:c.firstNodeId}),{firstNodeId:r,lastNodeIds:c.lastNodeIds.length>0?c.lastNodeIds:[r]}}case"parallel":{let i=`parallel_fork_${++t.nodeCounter}`,c=`parallel_join_${t.nodeCounter}`,d=e.mode==="parallel"?"Parallel":"All";n.push(` ${i}{{"${d} (${e.children.length})"}}`),n.push(` ${c}{{"Join"}}`),t.styleClasses.set(i,"parallelStyle"),t.styleClasses.set(c,"parallelStyle"),t.edges.push({from:r,to:i});for(let l=0;l<e.children.length;l++){let f=e.children[l];if(!f)continue;let u=ee(f,t,n);u.firstNodeId&&t.edges.push({from:i,to:u.firstNodeId,label:e.branchLabels?.[l]??`branch ${l+1}`});for(let p of u.lastNodeIds)t.edges.push({from:p,to:c})}return{firstNodeId:r,lastNodeIds:[c]}}case"race":{let i=`race_fork_${++t.nodeCounter}`,c=`race_join_${t.nodeCounter}`;n.push(` ${i}{{{"Race (${e.children.length})"}}}`),n.push(` ${c}{{{"Winner"}}}`),t.styleClasses.set(i,"raceStyle"),t.styleClasses.set(c,"raceStyle"),t.edges.push({from:r,to:i});for(let d=0;d<e.children.length;d++){let l=e.children[d];if(!l)continue;let f=ee(l,t,n);f.firstNodeId&&t.edges.push({from:i,to:f.firstNodeId,label:e.raceLabels?.[d]??`racer ${d+1}`});for(let u of f.lastNodeIds)t.edges.push({from:u,to:c})}return{firstNodeId:r,lastNodeIds:[c]}}case"error-handler":{let i=ee(e.source,t,n),c=`err_handler_${++t.nodeCounter}`;n.push(` ${c}["${e.handlerType}"]`),t.styleClasses.set(c,"errorHandlerStyle"),i.lastNodeIds.length>0&&t.edges.push({from:i.lastNodeIds[0],to:c,label:e.errorEdgeLabel??"on error"});let d=[c];if(e.handler){let l=ee(e.handler,t,n);l.firstNodeId&&t.edges.push({from:c,to:l.firstNodeId}),d=l.lastNodeIds}return{firstNodeId:i.firstNodeId??r,lastNodeIds:d}}case"retry":case"timeout":{let i=ee(e.source,t,n),c=`${e.type}_${++t.nodeCounter}`,d=e.type==="retry"?`Retry${e.schedule?`(${e.schedule})`:""}`:`Timeout${e.duration?`(${e.duration})`:""}`;return n.push(` ${c}["${d}"]`),t.styleClasses.set(c,`${e.type}Style`),i.lastNodeIds.length>0&&t.edges.push({from:i.lastNodeIds[0],to:c}),{firstNodeId:i.firstNodeId??r,lastNodeIds:[c]}}case"resource":{let i=ee(e.acquire,t,n),c=`resource_${++t.nodeCounter}`;n.push(` ${c}["Resource"]`),t.styleClasses.set(c,"resourceStyle"),i.lastNodeIds.length>0&&t.edges.push({from:i.lastNodeIds[0],to:c});let d=[c];if(e.use){let l=ee(e.use,t,n);l.firstNodeId&&t.edges.push({from:c,to:l.firstNodeId}),d=l.lastNodeIds}return{firstNodeId:i.firstNodeId??r,lastNodeIds:d}}case"conditional":{let i=`cond_${++t.nodeCounter}`,c=e.conditionLabel??pt(e.condition,25);n.push(` ${i}{"${te(c)}"}`),t.styleClasses.set(i,"conditionalStyle"),t.edges.push({from:r,to:i});let d=ee(e.onTrue,t,n);d.firstNodeId&&t.edges.push({from:i,to:d.firstNodeId,label:e.trueEdgeLabel??"true"});let l=[...d.lastNodeIds];if(e.onFalse){let f=ee(e.onFalse,t,n);f.firstNodeId&&t.edges.push({from:i,to:f.firstNodeId,label:e.falseEdgeLabel??"false"}),l.push(...f.lastNodeIds)}else l.push(i);return{firstNodeId:r,lastNodeIds:l}}case"loop":{let i=`loop_${++t.nodeCounter}`,c=e.iterSource?j(`${e.loopType}(${e.iterSource})`,_):e.loopType;n.push(` ${i}(["${te(c)}"])`),t.styleClasses.set(i,"loopStyle"),t.edges.push({from:r,to:i});let d=ee(e.body,t,n);d.firstNodeId&&t.edges.push({from:i,to:d.firstNodeId,label:"iterate"});for(let l of d.lastNodeIds)t.edges.push({from:l,to:i,label:"next"});return{firstNodeId:r,lastNodeIds:[i]}}case"layer":{let i=Se(e.operations,t,n);return i.firstNodeId&&t.edges.push({from:r,to:i.firstNodeId}),{firstNodeId:r,lastNodeIds:i.lastNodeIds.length>0?i.lastNodeIds:[r]}}case"decision":{let i=`decision_${++t.nodeCounter}`,c=e.label||pt(e.condition,25);n.push(` ${i}{"${te(c)}"}`),t.styleClasses.set(i,"decisionStyle");let d=Se(e.onTrue,t,n);d.firstNodeId&&t.edges.push({from:i,to:d.firstNodeId,label:"yes"});let l=[...d.lastNodeIds];if(e.onFalse&&e.onFalse.length>0){let f=Se(e.onFalse,t,n);f.firstNodeId&&t.edges.push({from:i,to:f.firstNodeId,label:"no"}),l.push(...f.lastNodeIds)}else l.push(i);return{firstNodeId:i,lastNodeIds:l}}case"switch":{let i=`switch_${++t.nodeCounter}`,c=`Switch: ${pt(e.expression,20)}`;n.push(` ${i}{"${te(c)}"}`),t.styleClasses.set(i,"switchStyle");let d=[];for(let l of e.cases){let f=l.labels.join(" / "),u=Se(l.body,t,n);u.firstNodeId&&t.edges.push({from:i,to:u.firstNodeId,label:f}),d.push(...u.lastNodeIds)}if(e.hasFallthrough){let l=`switchWarn_${++t.nodeCounter}`;n.push(` ${l}{{"\u26A0 fallthrough"}}`),t.styleClasses.set(l,"opaqueStyle"),t.edges.push({from:i,to:l,label:"note"})}return d.length===0&&d.push(i),{firstNodeId:i,lastNodeIds:d}}case"try-catch":{let i=Se(e.tryBody,t,n),c=[...i.lastNodeIds];if(e.catchBody&&e.catchBody.length>0){let d=`catch_${++t.nodeCounter}`,l=e.catchVariable?`Catch(${e.catchVariable})`:"Catch";n.push(` ${d}["${te(l)}"]`),t.styleClasses.set(d,"tryCatchStyle");for(let u of i.lastNodeIds)t.edges.push({from:u,to:d,label:"on error"});let f=Se(e.catchBody,t,n);f.firstNodeId&&t.edges.push({from:d,to:f.firstNodeId}),c.push(...f.lastNodeIds)}if(e.finallyBody&&e.finallyBody.length>0){let d=Se(e.finallyBody,t,n);if(d.firstNodeId)for(let l of c)t.edges.push({from:l,to:d.firstNodeId,label:"finally"});return{firstNodeId:i.firstNodeId??r,lastNodeIds:d.lastNodeIds}}return{firstNodeId:i.firstNodeId??r,lastNodeIds:c.length>0?c:[r]}}case"terminal":{let i=`term_${++t.nodeCounter}`,c=e.terminalKind;if(n.push(` ${i}(["${te(c)}"])`),t.styleClasses.set(i,"terminalStyle"),e.value&&e.value.length>0){let d=Se(e.value,t,n);d.firstNodeId&&t.edges.push({from:r,to:d.firstNodeId});for(let l of d.lastNodeIds)t.edges.push({from:l,to:i})}return{firstNodeId:e.value?.length?r:i,lastNodeIds:[]}}case"opaque":{let i=`opaque_${++t.nodeCounter}`;return n.push(` ${i}{{"${te(`\u26A0 ${e.reason}`)}"}}`),t.styleClasses.set(i,"opaqueStyle"),{firstNodeId:i,lastNodeIds:[i]}}case"cause":{let i=`cause_${++t.nodeCounter}`;if(n.push(` ${i}{{"${te(s)}"}}`),t.styleClasses.set(i,"causeStyle"),t.nodeIdMap.set(e.id,i),e.children&&e.children.length>0){let c=Se([...e.children],t,n);return c.firstNodeId&&t.edges.push({from:i,to:c.firstNodeId}),{firstNodeId:i,lastNodeIds:c.lastNodeIds.length>0?c.lastNodeIds:[i]}}return{firstNodeId:i,lastNodeIds:[i]}}case"exit":{let i=`exit_${++t.nodeCounter}`;return n.push(` ${i}(["${te(s)}"])`),t.styleClasses.set(i,"exitStyle"),t.nodeIdMap.set(e.id,i),{firstNodeId:i,lastNodeIds:[i]}}case"schedule":{let i=`schedule_${++t.nodeCounter}`;return n.push(` ${i}[/"${te(s)}"/]`),t.styleClasses.set(i,"scheduleStyle"),t.nodeIdMap.set(e.id,i),{firstNodeId:i,lastNodeIds:[i]}}case"match":{let i=`match_${++t.nodeCounter}`;if(n.push(` ${i}{"${te(s)}"}`),t.styleClasses.set(i,"matchStyle"),t.nodeIdMap.set(e.id,i),e.matchedTags&&e.matchedTags.length>0){let c=[];for(let d of e.matchedTags){let l=`match_tag_${++t.nodeCounter}`;n.push(` ${l}["${te(d)}"]`),t.styleClasses.set(l,"matchStyle"),t.edges.push({from:i,to:l,label:d}),c.push(l)}return c.length===0&&c.push(i),{firstNodeId:i,lastNodeIds:c}}return{firstNodeId:i,lastNodeIds:[i]}}case"transform":{if(e.source){let i=ee(e.source,t,n);return i.lastNodeIds.length>0&&t.edges.push({from:i.lastNodeIds[0],to:r}),{firstNodeId:i.firstNodeId??r,lastNodeIds:[r]}}return{firstNodeId:r,lastNodeIds:[r]}}case"channel":{let i=`channel_${++t.nodeCounter}`;if(n.push(` ${i}[["${te(s)}"]]`),t.styleClasses.set(i,"channelStyle"),t.nodeIdMap.set(e.id,i),e.source){let c=ee(e.source,t,n);return c.lastNodeIds.length>0&&t.edges.push({from:c.lastNodeIds[0],to:i}),{firstNodeId:c.firstNodeId??i,lastNodeIds:[i]}}return{firstNodeId:i,lastNodeIds:[i]}}case"sink":{let i=`sink_${++t.nodeCounter}`;if(n.push(` ${i}[("${te(s)}")]`),t.styleClasses.set(i,"sinkStyle"),t.nodeIdMap.set(e.id,i),e.source){let c=ee(e.source,t,n);return c.lastNodeIds.length>0&&t.edges.push({from:c.lastNodeIds[0],to:i}),{firstNodeId:c.firstNodeId??i,lastNodeIds:[i]}}return{firstNodeId:i,lastNodeIds:[i]}}case"interruption":{let i=`interruption_${++t.nodeCounter}`;if(n.push(` ${i}{{"${te(s)}"}}`),t.styleClasses.set(i,"interruptionStyle"),t.nodeIdMap.set(e.id,i),e.source){let c=ee(e.source,t,n);c.firstNodeId&&t.edges.push({from:i,to:c.firstNodeId});let d=[...c.lastNodeIds];if(e.handler){let l=ee(e.handler,t,n);c.lastNodeIds.length>0&&l.firstNodeId&&t.edges.push({from:c.lastNodeIds[0],to:l.firstNodeId,label:"on interrupt"}),d.push(...l.lastNodeIds)}return{firstNodeId:i,lastNodeIds:d.length>0?d:[i]}}return{firstNodeId:i,lastNodeIds:[i]}}default:return{firstNodeId:r,lastNodeIds:[r]}}}function fe(e,t){let n={...Un,...t},{lines:r}=Ro(e,n);return r.join(`
|
|
14
|
+
`)}var Ac=(e,t)=>Io.sync(()=>fe(e,t));function vo(e){let t=e.toLowerCase();return t.includes("log")||t.includes("loginfo")||t.includes("logdebug")||t.includes("logwarning")||t.includes("logerror")||t.includes("taperror")}function wo(e){let t=e.toLowerCase();return t.includes("map")||t.includes("flatmap")||t.includes("filter")||t.includes("transform")||t.includes("tap(")||t==="tap"||t.includes("annotate")||t.includes("hsep")||t.includes("ansidoc.text")}function ko(e){let t=e.trim();return!!(/\(environment\)/i.test(t)||/^[A-Z][A-Za-z0-9_]+$/.test(t)||/^(Context\.Tag|GenericTag|Effect\.serviceOption|Effect\.service)\b/.test(t))}function Fc(e){let t=e.trim();return/^[A-Za-z_$][\w$]*\.[A-Za-z_$][\w$]*/.test(t)?!["Effect.","Layer.","Stream.","Schema.","Schedule.","Option.","Either.","Duration.","Console.","Array.","String.","Number.","Boolean.","Math.","Object.","JSON.","Promise.","Date."].some(r=>t.startsWith(r)):!1}function Rc(e,t){if(!(t.prefixServiceBoundaries??t.styleGuide??!1))return[...e];let r=[...e],o=0;for(let s=0;s<r.length&&!(o>=2);s++){let a=r[s];a&&Fc(a.name)&&!a.name.startsWith("svc: ")&&(r[s]={...a,name:`svc: ${a.name}`},o++)}return r}function rn(e,t){let n=t.collapseRepeatedLogs??!0,r=t.collapsePureTransforms??!0,o=t.collapseEnvironmentRuns??t.styleGuide??!1,s=[],a=0,i=0;for(;i<e.steps.length;){let c=e.steps[i];if(!c)break;let d=c.name??c.nodeId;if(n&&vo(d)){let l=i+1;for(;l<e.steps.length;){let u=e.steps[l];if(!u)break;let p=u.name??u.nodeId;if(!vo(p))break;l++}let f=l-i;if(f>1){s.push({key:`${e.id}:logs:${i}`,name:`log steps \xD7${String(f)}`}),a++,i=l;continue}}if(r&&wo(d)){let l=i+1;for(;l<e.steps.length;){let u=e.steps[l];if(!u)break;let p=u.name??u.nodeId;if(!wo(p))break;l++}let f=l-i;if(f>1){s.push({key:`${e.id}:transforms:${i}`,name:`transform steps \xD7${String(f)}`}),a++,i=l;continue}}if(o&&ko(d)){let l=i+1;for(;l<e.steps.length;){let u=e.steps[l];if(!u)break;let p=u.name??u.nodeId;if(!ko(p))break;l++}let f=l-i;if(f>1){s.push({key:`${e.id}:env:${i}`,name:`environment \xD7${String(f)}`}),a++,i=l;continue}}s.push({key:c.nodeId,name:d}),i++}return{steps:Rc(s,t),collapsedGroups:a}}function $c(e,t={}){let n=t.direction??"TB",r=[];r.push(`flowchart ${n}`),r.push("");let o=new Map,s=0,a=e.map(c=>rn(c,t).steps);for(let c of a)for(let d of c){let l=d.key;o.has(l)||o.set(l,{id:`step_${++s}`,name:d.name})}r.push(" start((Start))"),r.push(" end_node((End))"),r.push("");for(let[,c]of o)r.push(` ${c.id}["${te(c.name)}"]`);r.push("");let i=new Set;for(let c of a){if(c.length===0)continue;let d=c[0],l=o.get(d.key);i.add(`start --> ${l.id}`);for(let p=0;p<c.length-1;p++){let g=c[p],m=c[p+1],h=o.get(g.key),x=o.get(m.key);i.add(`${h.id} --> ${x.id}`)}let f=c[c.length-1],u=o.get(f.key);i.add(`${u.id} --> end_node`)}r.push(" %% Edges");for(let c of i)r.push(` ${c}`);return r.join(`
|
|
15
|
+
`)}var Dc={...Un,showTypeSignatures:!0,showRequiredServices:!0,showErrorNodes:!1};function Pc(e,t){let n=new Map,r=t.showTypeSignatures!==!1,o=t.showRequiredServices===!0;function s(a){if(a.type==="effect"){let i=[];if(r&&a.typeSignature&&i.push(`<${a.typeSignature.successType}, ${a.typeSignature.errorType}, ${a.typeSignature.requirementsType}>`),o&&a.requiredServices&&a.requiredServices.length>0){let c=a.requiredServices.map(d=>d.serviceId).join(", ");i.push(`R: ${c}`)}i.length>0&&n.set(a.id,i)}switch(a.type){case"generator":for(let i of a.yields)s(i.effect);break;case"pipe":s(a.initial);for(let i of a.transformations)s(i);break;case"parallel":case"race":for(let i of a.children)s(i);break;case"error-handler":s(a.source),a.handler&&s(a.handler);break;case"retry":case"timeout":s(a.source);break;case"resource":s(a.acquire),s(a.release),a.use&&s(a.use);break;case"conditional":s(a.onTrue),a.onFalse&&s(a.onFalse);break;case"loop":s(a.body);break;case"layer":for(let i of a.operations)s(i);break;case"decision":for(let i of a.onTrue)s(i);if(a.onFalse)for(let i of a.onFalse)s(i);break;case"switch":for(let i of a.cases)for(let c of i.body)s(c);break;case"try-catch":for(let i of a.tryBody)s(i);if(a.catchBody)for(let i of a.catchBody)s(i);if(a.finallyBody)for(let i of a.finallyBody)s(i);break;case"terminal":if(a.value)for(let i of a.value)s(i);break;case"opaque":break;default:break}}for(let a of e.root.children)s(a);return n}function $o(e,t){let n={...Dc,...t},r=Pc(e,n),{lines:o}=Ro(e,n,r);return o.join(`
|
|
16
|
+
`)}var Lc=(e,t)=>Io.sync(()=>$o(e,t));function Do(e,t){for(let n of e){n.type==="fiber"&&t.push(n);let r=Ao.getOrElse(v(n),()=>[]);r.length>0&&Do(r,t)}}function Mc(e){let t=[];Do(e.root.children,t);let n=t.filter(s=>s.operation==="fork"||s.operation==="forkScoped"||s.operation==="forkDaemon"),r=t.filter(s=>s.operation==="join"||s.operation==="await");if(n.length===0&&r.length===0)return`sequenceDiagram
|
|
17
17
|
participant Main
|
|
18
|
-
note over Main: No fiber operations detected`;let o=["sequenceDiagram"," participant Main"];return
|
|
19
|
-
`)}function
|
|
18
|
+
note over Main: No fiber operations detected`;let o=["sequenceDiagram"," participant Main"];return n.forEach((s,a)=>{o.push(` participant Fiber${a+1}`)}),o.push(""),n.forEach((s,a)=>{let i=s.fiberSource?s.fiberSource.callee??"effect":"effect",c=j(i,_);o.push(` Main->>Fiber${a+1}: fork(${c})`)}),r.forEach((s,a)=>{let i=Math.min(a+1,n.length);o.push(` Fiber${i}-->>Main: join`)}),o.join(`
|
|
19
|
+
`)}function Po(e,t){for(let n of e){n.type==="retry"&&t.push(n);let r=Ao.getOrElse(v(n),()=>[]);r.length>0&&Po(r,t)}}function Oc(e){let t=[];Po(e.root.children,t);let n=t.filter(o=>o.scheduleInfo);if(n.length===0)return`gantt
|
|
20
20
|
title Retry Schedule
|
|
21
21
|
section Retries
|
|
22
|
-
No retry schedules detected`;let
|
|
23
|
-
`)}function
|
|
24
|
-
`)}import{Option as
|
|
25
|
-
Empty((No steps))`;let s=[`flowchart ${
|
|
26
|
-
`)}import{Option as
|
|
27
|
-
NoServices((No services))`;let i=[`flowchart ${
|
|
28
|
-
`)}function
|
|
29
|
-
`)}function
|
|
30
|
-
NoErrors((No errors))`;let s=[`flowchart ${
|
|
31
|
-
`)}import{Option as
|
|
32
|
-
NoDec((No decisions))`;let o=[`flowchart ${
|
|
33
|
-
`)}import{Option as
|
|
34
|
-
NoCauses((No failure causes))`;let o=[`flowchart ${
|
|
35
|
-
`)}import{Option as
|
|
36
|
-
NoConcurrency((No concurrency))`;let o=[`flowchart ${
|
|
37
|
-
`)}import{Option as
|
|
22
|
+
No retry schedules detected`;let r=["gantt"," title Retry Schedule"," section Attempts"];return n.forEach((o,s)=>{let a=o.scheduleInfo,i=a.maxRetries==="unlimited"?5:Math.min(typeof a.maxRetries=="string"?Number(a.maxRetries):a.maxRetries??3,5);for(let c=0;c<i;c++)r.push(` Attempt ${c+1}: a${s}_${c}, ${c===0?"0":`after a${s}_${c-1}`}, 100ms`),c<i-1&&r.push(` Wait: w${s}_${c}, after a${s}_${c}, 200ms`)}),r.join(`
|
|
23
|
+
`)}function Wc(e,t={}){let n=t.direction??"TB",r=[],o=a=>a.replace(/[^a-zA-Z0-9_]/g,"_");r.push(`flowchart ${n}`),r.push(""),r.push(" %% Service Dependency Graph"),r.push("");for(let[a,i]of e.services){let c=o(a),d=i.definition.methods.length,l=d>0?`${a}\\n(${d} method${d===1?"":"s"})`:a;r.push(` ${c}{{{"${l}"}}}`)}for(let a of e.unresolvedServices){let i=`unresolved_${o(a)}`;r.push(` ${i}["? ${a}"]`)}r.push("");let s=new Set;for(let[a,i]of e.services)for(let c of i.layerImplementations)for(let d of c.requires){let l=`${a}->${d}`;if(s.has(l))continue;s.add(l);let f=o(a),u=e.services.has(d)?o(d):`unresolved_${o(d)}`;r.push(` ${f} -->|"${c.name}"| ${u}`)}r.push(""),r.push(" classDef service fill:#E3F2FD,stroke:#1565C0,stroke-width:2px"),r.push(" classDef unresolved fill:#FFF3CD,stroke:#856404,stroke-dasharray:5");for(let a of e.services.keys())r.push(` class ${o(a)} service`);for(let a of e.unresolvedServices)r.push(` class unresolved_${o(a)} unresolved`);return r.join(`
|
|
24
|
+
`)}import{Option as Mo}from"effect";function on(e){let t=String.fromCharCode(65+e%26),n=Math.floor(e/26);return n===0?t:`${t}${n}`}function sn(e){return e.replace(/"/g,"#quot;").replace(/</g,"#lt;").replace(/>/g,"#gt;").replace(/\(/g,"#lpar;").replace(/\)/g,"#rpar;")}function Lo(e){return e.replace(/(Error|Exception)$/,"")}function Kc(e){let t;return e.type==="effect"?t=e.typeSignature?.errorType??e.errorType:"typeSignature"in e&&e.typeSignature&&(t=e.typeSignature.errorType),!t||t==="never"||t.trim()===""?[]:Ae(t).filter(n=>n!=="never")}function Bc(e){let t=new Set,n=[],r=o=>{for(let a of Kc(o))t.has(a)||(t.add(a),n.push(a));let s=Mo.getOrElse(v(o),()=>[]);for(let a of s)r(a)};return r(e),n}function qc(e){let t=(()=>{if(e.displayName)return e.displayName;if(e.type==="effect"){if(e.name){let n=e.name.replace(/^Effect\./,"");return n.charAt(0).toUpperCase()+n.slice(1)}return e.callee.replace(/^Effect\./,"")}return e.name?e.name:e.type==="parallel"?"Effect.all":e.type==="race"?"Effect.race":e.type==="error-handler"?"Error Handler":e.type==="retry"?"Retry":e.type==="conditional"?"Conditional":e.type})();return j(t,_)}function _c(e){switch(e.type){case"generator":case"pipe":return!0;default:return!1}}function jc(e){switch(e.type){case"loop":case"conditional":case"decision":case"switch":case"parallel":case"race":case"retry":case"timeout":case"resource":return!0;default:return!1}}function zc(e){switch(e.type){case"error-handler":case"transform":case"stream":case"channel":case"sink":case"concurrency-primitive":case"fiber":case"interruption":case"try-catch":case"terminal":return!0;default:return!1}}function Hc(e){if(e.type!=="effect")return!1;let t=e.callee??"";if(t==="Effect.fn"||t.startsWith("Effect.fn("))return!0;let n=e.displayName??"";return!!(!(n&&n!==t&&n!==e.type)||t.startsWith("Schema.")||t.startsWith("Data."))}function Uc(e){let t=[],n=r=>{if(_c(r)){let o=Mo.getOrElse(v(r),()=>[]);for(let s of o)n(s);return}if(!zc(r)){if(jc(r)){t.push(r);return}Hc(r)||t.push(r)}};for(let r of e)n(r);return t}function Vc(e){return e.map(t=>({label:qc(t),errorTypes:Bc(t)}))}function Gc(e,t={}){let n=t.direction??"LR",r=Uc(e.root.children),o=Vc(r);if(o.length===0)return`flowchart ${n}
|
|
25
|
+
Empty((No steps))`;let s=[`flowchart ${n}`],a=[],i=o.some(c=>c.errorTypes.length>0);for(let c=0;c<o.length;c++){let d=o[c];if(!d)continue;let l=on(c),f=sn(d.label);if(c<o.length-1){let u=o[c+1];if(!u)continue;let p=on(c+1),g=sn(u.label);c===0?s.push(` ${l}[${f}] -->|ok| ${p}[${g}]`):s.push(` ${l} -->|ok| ${p}[${g}]`)}else c===0?s.push(` ${l}[${f}] -->|ok| Done((Success))`):s.push(` ${l} -->|ok| Done((Success))`)}if(i)for(let c=0;c<o.length;c++){let d=o[c];if(!d)continue;let{errorTypes:l}=d;if(l.length===0)continue;let f=on(c),u=`${f}E`,p=sn(l.map(Lo).join(" / "));a.push(` ${f} -->|err| ${u}[${p}]`)}else if(e.root.errorTypes.length>0){let c=on(o.length-1),d=sn(e.root.errorTypes.map(Lo).join(" / "));a.push(` ${c} -->|err| Errors[${d}]`)}return[...s,...a].join(`
|
|
26
|
+
`)}import{Option as Oo}from"effect";function Wo(e,t){if(e.type==="effect"){let o=e.requiredServices??[];for(let s of o)t.some(a=>a.serviceId===s.serviceId)||t.push(s)}let n=Oo.getOrElse(v(e),()=>[]);for(let r of n)Wo(r,t)}function Jc(e,t){let n=e.callee;if(n.includes("provideService")||n.includes("provide"))return t(e)}function $t(e,t){let n=[];for(let f of e.root.children)Wo(f,n);let r=Array.from(new Map(n.map(f=>[f.serviceId,f])).values()),o=[],s=[],a=new Map,i=new Set,c=t?.getFirstArgText;function d(f){for(let u of f){if(u.type==="effect"){let g=u,m=c?Jc(g,c):void 0;if(m){i.add(m);let x={nodeId:g.id,serviceId:m};g.location&&(x.location=g.location),o.push(x)}let h=g.requiredServices??[];for(let x of h){let T=a.get(x.serviceId)??[];if(T.push(g.id),a.set(x.serviceId,T),!i.has(x.serviceId)){let S={nodeId:g.id,serviceId:x.serviceId};x.serviceType!==void 0&&(S.serviceType=x.serviceType),x.requiredAt!==void 0&&(S.location=x.requiredAt),s.push(S)}}}let p=Oo.getOrElse(v(u),()=>[]);p.length>0&&d(p)}}d(e.root.children);let l=new Map;for(let f of o)l.set(f.serviceId,{createdAt:f.nodeId,consumedAt:a.get(f.serviceId)??[]});for(let f of r)l.has(f.serviceId)||l.set(f.serviceId,{createdAt:"",consumedAt:a.get(f.serviceId)??[]});return{requiredServices:r,providedServices:o,unsatisfiedAt:s,serviceLifecycle:l}}function Vn(e){return e.replace(/"/g,"#quot;").replace(/</g,"#lt;").replace(/>/g,"#gt;").replace(/\(/g,"#lpar;").replace(/\)/g,"#rpar;")}function Ce(e){return e.replace(/[^a-zA-Z0-9_]/g,"_")}function Yc(e,t={}){let n=t.direction??"LR",{requiredServices:r,providedServices:o}=$t(e),s=e.root.dependencies,a=new Set;for(let d of r)a.add(d.serviceId);for(let d of s)a.add(d.name);if(a.size===0&&o.length===0)return`flowchart ${n}
|
|
27
|
+
NoServices((No services))`;let i=[`flowchart ${n}`],c=Vn(e.root.programName);i.push(` prog["${c}"]`),i.push("");for(let d of a){let l=`svc_${Ce(d)}`,f=Vn(d);i.push(` ${l}{{"${f}"}}`),i.push(` prog -->|requires| ${l}`)}for(let d of o){let l=`prov_${Ce(d.serviceId)}`,f=Vn(d.serviceId);i.push(` ${l}{{"${f}"}}`),i.push(` ${l} -->|provides| prog`)}i.push(""),i.push(" classDef required fill:#E3F2FD,stroke:#1565C0,stroke-width:2px"),i.push(" classDef provided fill:#E8F5E9,stroke:#2E7D32,stroke-width:2px");for(let d of r)i.push(` class svc_${Ce(d.serviceId)} required`);for(let d of o)i.push(` class prov_${Ce(d.serviceId)} provided`);return i.join(`
|
|
28
|
+
`)}function Qc(e,t={}){let r=[`flowchart ${t.direction??"TB"}`];r.push(""),r.push(" %% Service Dependency Graph"),r.push("");for(let[s,a]of e.services){let i=Ce(s),c=a.definition.methods.length,d=c>0?`${s}\\n(${c} method${c===1?"":"s"})`:s;r.push(` ${i}{{"${d}"}}`)}for(let s of e.unresolvedServices){let a=`unresolved_${Ce(s)}`;r.push(` ${a}["? ${s}"]`)}r.push("");let o=new Set;for(let[s,a]of e.services)for(let i of a.layerImplementations)for(let c of i.requires){let d=`${s}->${c}`;if(o.has(d))continue;o.add(d);let l=Ce(s),f=e.services.has(c)?Ce(c):`unresolved_${Ce(c)}`;r.push(` ${l} -->|"${i.name}"| ${f}`)}r.push(""),r.push(" classDef service fill:#E3F2FD,stroke:#1565C0,stroke-width:2px"),r.push(" classDef unresolved fill:#FFF3CD,stroke:#856404,stroke-dasharray:5");for(let s of e.services.keys())r.push(` class ${Ce(s)} service`);for(let s of e.unresolvedServices)r.push(` class unresolved_${Ce(s)} unresolved`);return r.join(`
|
|
29
|
+
`)}function Gn(e){return e.replace(/"/g,"#quot;").replace(/</g,"#lt;").replace(/>/g,"#gt;").replace(/\(/g,"#lpar;").replace(/\)/g,"#rpar;")}function De(e){return e.replace(/[^a-zA-Z0-9_]/g,"_")}function Zc(e){return e.replace(/(Error|Exception)$/,"")}function Xc(e,t={}){let n=t.direction??"LR",r=Ye(e),o=Rt(e);if(r.allErrors.length===0)return`flowchart ${n}
|
|
30
|
+
NoErrors((No errors))`;let s=[`flowchart ${n}`],a=[],i=new Set;for(let l of o.propagation)if(l.narrowedBy&&l.narrowedBy.removedErrors.length>0){let f=`handler_${De(l.atNode)}`;a.push({id:f,label:l.narrowedBy.handler,removedErrors:l.narrowedBy.removedErrors});for(let u of l.narrowedBy.removedErrors)i.add(u)}let c=r.allErrors.filter(l=>!i.has(l)),d=r.stepErrors.filter(l=>l.errors.length>0);if(d.length>0){s.push(""),s.push(" subgraph Steps");for(let l of d){let f=Gn(l.stepName??l.stepId);s.push(` step_${De(l.stepId)}["${f}"]`)}s.push(" end")}s.push(""),s.push(" subgraph Errors");for(let l of r.allErrors){let f=Gn(Zc(l));s.push(` err_${De(l)}("${f}")`)}if(s.push(" end"),a.length>0){s.push(""),s.push(" subgraph Handlers");for(let l of a){let f=Gn(l.label);s.push(` ${l.id}["${f}"]`)}s.push(" end")}c.length>0&&(s.push(""),s.push(' UNHANDLED["UNHANDLED"]')),s.push("");for(let l of d)for(let f of l.errors)s.push(` step_${De(l.stepId)} --produces--> err_${De(f)}`);for(let l of a)for(let f of l.removedErrors)r.allErrors.includes(f)&&s.push(` err_${De(f)} --caught by--> ${l.id}`);for(let l of c)s.push(` err_${De(l)} --unhandled--> UNHANDLED`);s.push(""),s.push(" classDef stepStyle fill:#BBDEFB"),s.push(" classDef errorStyle fill:#FFE0B2"),s.push(" classDef handlerStyle fill:#C8E6C9"),s.push(" classDef unhandledStyle fill:#FFCDD2");for(let l of d)s.push(` class step_${De(l.stepId)} stepStyle`);for(let l of r.allErrors)s.push(` class err_${De(l)} errorStyle`);for(let l of a)s.push(` class ${l.id} handlerStyle`);return c.length>0&&s.push(" class UNHANDLED unhandledStyle"),s.join(`
|
|
31
|
+
`)}import{Option as el}from"effect";var tl=new Set(["conditional","decision","switch","match"]);function We(e){return e.replace(/"/g,"#quot;").replace(/</g,"#lt;").replace(/>/g,"#gt;").replace(/\(/g,"#lpar;").replace(/\)/g,"#rpar;")}function Jn(e,t=40){return e.length>t?e.slice(0,t-3)+"...":e}function Bo(e){return e.displayName?e.displayName:e.name?e.name:e.type==="effect"?e.callee:e.type}function nl(e){let t=[],n=0,r=o=>{tl.has(o.type)&&t.push({node:o,nodeId:`D${n++}`});let s=el.getOrElse(v(o),()=>[]);for(let a of s)r(a);if(o.type==="conditional"){let a=o;r(a.onTrue),a.onFalse&&r(a.onFalse)}else if(o.type==="decision"){let a=o;for(let i of a.onTrue)r(i);if(a.onFalse)for(let i of a.onFalse)r(i)}else if(o.type==="switch"){let a=o;for(let i of a.cases)for(let c of i.body)r(c)}};for(let o of e)r(o);return t}function qo(e,t){return e.find(n=>n.node===t)}function rl(e,t){for(let n of t){let r=qo(e,n);if(r)return r}}function Ko(e,t,n){if(!e){let a=`T${n.value++}`;return{targetId:a,extraLine:` ${a}["..."]`}}let r=qo(t,e);if(r)return{targetId:r.nodeId};let o=We(Bo(e)),s=`T${n.value++}`;return{targetId:s,extraLine:` ${s}["${o}"]`}}function Yn(e,t,n){if(!e||e.length===0){let i=`T${n.value++}`;return{targetId:i,extraLine:` ${i}["..."]`}}let r=rl(t,e);if(r)return{targetId:r.nodeId};let o=e[0];if(!o){let i=`T${n.value++}`;return{targetId:i,extraLine:` ${i}["..."]`}}let s=We(Bo(o)),a=`T${n.value++}`;return{targetId:a,extraLine:` ${a}["${s}"]`}}function ol(e,t={}){let n=t.direction??"TB",r=nl(e.root.children);if(r.length===0)return`flowchart ${n}
|
|
32
|
+
NoDec((No decisions))`;let o=[`flowchart ${n}`],s={value:0};for(let{node:a,nodeId:i}of r)switch(a.type){case"conditional":{let c=a,d=We(Jn(c.condition));o.push(` ${i}{${d}}`);let l=c.trueEdgeLabel??"true",f=c.falseEdgeLabel??"false",u=Ko(c.onTrue,r,s);if(u.extraLine&&o.push(u.extraLine),o.push(` ${i} -->|${l}| ${u.targetId}`),c.onFalse){let p=Ko(c.onFalse,r,s);p.extraLine&&o.push(p.extraLine),o.push(` ${i} -->|${f}| ${p.targetId}`)}break}case"decision":{let c=a,d=We(Jn(c.condition));o.push(` ${i}{${d}}`);let l=Yn(c.onTrue,r,s);if(l.extraLine&&o.push(l.extraLine),o.push(` ${i} -->|true| ${l.targetId}`),c.onFalse){let f=Yn(c.onFalse,r,s);f.extraLine&&o.push(f.extraLine),o.push(` ${i} -->|false| ${f.targetId}`)}break}case"switch":{let c=a,d=We(Jn(c.expression));o.push(` ${i}{${d}}`);for(let l of c.cases){let f=l.isDefault?"default":l.labels.join(", "),u=Yn(l.body,r,s);u.extraLine&&o.push(u.extraLine),o.push(` ${i} -->|${f}| ${u.targetId}`)}break}case"match":{let c=a,d=We(`Match.${c.matchOp}`);if(o.push(` ${i}{${d}}`),c.matchedTags&&c.matchedTags.length>0)for(let l of c.matchedTags){let f=`T${s.value++}`;o.push(` ${f}["${We(l)}"]`),o.push(` ${i} -->|${We(l)}| ${f}`)}else{let l=`T${s.value++}`;o.push(` ${l}["..."]`),o.push(` ${i} -->|match| ${l}`)}break}}return o.join(`
|
|
33
|
+
`)}import{Option as sl}from"effect";function _o(e){return e.replace(/"/g,"#quot;").replace(/</g,"#lt;").replace(/>/g,"#gt;").replace(/\(/g,"#lpar;").replace(/\)/g,"#rpar;")}function an(e){return e.replace(/[^a-zA-Z0-9]/g,"_")}var il=new Set(["Effect.fail","Effect.die","Effect.interrupt"]);function al(e){if(e.type==="effect"){let t=e.typeSignature?.errorType??e.errorType;if(t&&t!=="never"&&t.trim()!=="")return t}}function cl(e){return e==="Effect.die"?"die":e==="Effect.interrupt"?"interrupt":"fail"}function Qn(e){let t=[];if(e.type==="cause"&&e.isConstructor){let r=e.causeOp;if(r==="parallel"||r==="sequential"){let o=[],s=e.children??[];for(let a of s)o.push(...Qn(a));return t.push({id:an(e.id),kind:r,label:`Cause.${r}`,children:o}),t}if(r==="fail"||r==="die"||r==="interrupt")return t.push({id:an(e.id),kind:r,label:`Cause.${r}`,children:[]}),t}if(e.type==="exit"&&e.isConstructor){let r=e.exitOp;if(r==="fail"||r==="die"||r==="interrupt")return t.push({id:an(e.id),kind:r==="fail"?"fail":r==="die"?"die":"interrupt",label:`Exit.${r}`,children:[]}),t}if(e.type==="effect"&&il.has(e.callee)){let r=cl(e.callee),o=al(e),s=j(o?`${e.callee}: ${o}`:e.callee,_);return t.push({id:an(e.id),kind:r,label:s,children:[]}),t}let n=sl.getOrElse(v(e),()=>[]);for(let r of n)t.push(...Qn(r));return t}function jo(e,t,n,r,o,s){let a=`N${s.value++}`,i=_o(e.label);if(e.kind==="parallel"||e.kind==="sequential"){if(r.push(` ${a}[${i}]`),o.set(a,"composite"),t){let d=n?` -->|${n}| `:" --> ";r.push(` ${t}${d}${a}`)}let c=e.kind==="parallel"?"parallel":"then";for(let d of e.children)jo(d,a,c,r,o,s)}else if(e.kind==="die"?(r.push(` ${a}[${i}]`),o.set(a,"die")):e.kind==="interrupt"?(r.push(` ${a}[${i}]`),o.set(a,"interrupt")):(r.push(` ${a}(${i})`),o.set(a,"fail")),t){let c=n?` -->|${n}| `:" --> ";r.push(` ${t}${c}${a}`)}}function ll(e,t={}){let n=t.direction??"TB",r=[];for(let l of e.root.children)r.push(...Qn(l));if(r.length===0)return`flowchart ${n}
|
|
34
|
+
NoCauses((No failure causes))`;let o=[`flowchart ${n}`],s=new Map,a={value:0},i="Root",c=_o(e.root.programName);o.push(` ${i}((${c}))`);for(let l of r)jo(l,i,void 0,o,s,a);o.push(""),o.push(" classDef failStyle fill:#FFCDD2,stroke:#C62828"),o.push(" classDef dieStyle fill:#B71C1C,color:#fff"),o.push(" classDef interruptStyle fill:#FFE0B2,stroke:#E65100"),o.push(" classDef compositeStyle fill:#E3F2FD");let d={failStyle:[],dieStyle:[],interruptStyle:[],compositeStyle:[]};for(let[l,f]of s)f==="fail"?d.failStyle.push(l):f==="die"?d.dieStyle.push(l):f==="interrupt"?d.interruptStyle.push(l):d.compositeStyle.push(l);for(let[l,f]of Object.entries(d))f.length>0&&o.push(` class ${f.join(",")} ${l}`);return o.join(`
|
|
35
|
+
`)}import{Option as dl}from"effect";function Ke(e){return e.replace(/"/g,"#quot;").replace(/</g,"#lt;").replace(/>/g,"#gt;").replace(/\(/g,"#lpar;").replace(/\)/g,"#rpar;")}function Be(e,t){return`${e}${t}`}function zo(e,t){let n=r=>j(r,_);return e.displayName?n(e.displayName):e.name?n(e.name):e.type==="effect"?n(e.callee):`child_${t}`}function ul(e){return e.charAt(0).toUpperCase()+e.slice(1)}function fl(e){let t=[],n=r=>{switch(r.type){case"parallel":t.push({kind:"parallel",node:r});break;case"race":t.push({kind:"race",node:r});break;case"fiber":t.push({kind:"fiber",node:r});break;case"concurrency-primitive":t.push({kind:"primitive",node:r});break}let o=dl.getOrElse(v(r),()=>[]);for(let s of o)n(s)};for(let r of e)n(r);return t}function pl(e,t={}){let n=t.direction??"TB",r=fl(e.root.children);if(r.length===0)return`flowchart ${n}
|
|
36
|
+
NoConcurrency((No concurrency))`;let o=[`flowchart ${n}`],s=[],a=0,i=[];for(let c of r)switch(c.kind){case"parallel":{let d=c.node,l=Be("P",a++),f=d.children.length,u=d.mode==="parallel"?"parallel":"sequential",p=Ke(j(`${d.callee} #lpar;${f} effects, ${u}#rpar;`,_));o.push(` ${l}[${p}]`),s.push(` style ${l} fill:#E3F2FD`);let g=Be("PJ",a++);for(let m=0;m<d.children.length;m++){let h=d.children[m];if(!h)continue;let x=Be("PC",a++),T=Ke(d.branchLabels?.[m]??zo(h,m)),S=d.branchLabels?.[m],N=S?Ke(S):void 0;o.push(` ${x}[${T}]`),N?o.push(` ${l} -->|${N}| ${x}`):o.push(` ${l} --> ${x}`),o.push(` ${x} --> ${g}`)}o.push(` ${g}([Join])`),s.push(` style ${g} fill:#E3F2FD`),i.push(l),i.push(g);break}case"race":{let d=c.node,l=Be("R",a++);o.push(` ${l}{Race}`),s.push(` style ${l} fill:#FFF3E0`);let f=Be("RW",a++);for(let u=0;u<d.children.length;u++){let p=d.children[u];if(!p)continue;let g=Be("RC",a++),m=Ke(d.raceLabels?.[u]??zo(p,u));o.push(` ${g}[${m}]`),o.push(` ${l} -->|competes| ${g}`),o.push(` ${g} -.->|winner?| ${f}`)}o.push(` ${f}([First to complete])`),s.push(` style ${f} fill:#FFF3E0`),i.push(l),i.push(f);break}case"fiber":{let d=c.node,l=Be("F",a++),f=d.operation;if(f==="fork"||f==="forkScoped"||f==="forkDaemon"||f==="forkAll"||f==="forkIn"||f==="forkWithErrorHandler"){let u=d.fiberSource?.displayName??d.fiberSource?.name??"effect",p=Ke(`${f}#lpar;${u}#rpar;`);o.push(` ${l}[${p}]`),f==="forkScoped"?s.push(` style ${l} fill:#C8E6C9`):f==="forkDaemon"?s.push(` style ${l} fill:#FFE0B2`):s.push(` style ${l} fill:#FFF9C4`)}else if(f==="join"||f==="await"){let u=Ke(f);o.push(` ${l}[${u}]`),s.push(` style ${l} fill:#BBDEFB`)}else{let u=Ke(`Fiber.${f}`);o.push(` ${l}[${u}]`),s.push(` style ${l} fill:#BBDEFB`)}i.push(l);break}case"primitive":{let d=c.node,l=Be("CP",a++),f=ul(d.primitive),u=Ke(`${f}.${d.operation}`);o.push(` ${l}{{${u}}}`),s.push(` style ${l} fill:#F3E5F5`),i.push(l);break}}for(let c=0;c<i.length-1;c++){let d=i[c],l=i[c+1];!d||!l||o.push(` ${d} --> ${l}`)}return[...o,...s].join(`
|
|
37
|
+
`)}import{Option as Zn}from"effect";function gl(e){let t=[],n=r=>{if(r.type==="parallel"){t.push({kind:"parallel",node:r});return}if(r.type==="retry"){t.push({kind:"retry",node:r}),n(r.source);return}if(r.type==="timeout"){t.push({kind:"timeout",node:r}),n(r.source);return}if(r.type==="effect"){let s=r.callee;if(s==="Effect.fn"||s.startsWith("Effect.fn(")||s.startsWith("Schema.")||s.startsWith("Data."))return;let a=r.displayName??"";if(!(a&&a!==s&&a!==r.type)&&(s.startsWith("Effect.")||s==="Effect"))return;r.serviceCall?t.push({kind:"service-call",node:r}):t.push({kind:"effect-constructor",node:r});return}let o=Zn.getOrElse(v(r),()=>[]);for(let s of o)n(s)};for(let r of e)n(r);return t}function ml(e){let t=new Set,n=[],r=o=>{if(o.kind==="service-call"&&o.node.type==="effect"&&o.node.serviceCall){let s=o.node.serviceCall.serviceType;t.has(s)||(t.add(s),n.push(s))}else if(o.kind==="parallel"){let s=Zn.getOrElse(v(o.node),()=>[]);for(let a of s)if(a.type==="effect"&&a.serviceCall){let i=a.serviceCall.serviceType;t.has(i)||(t.add(i),n.push(i))}}};for(let o of e)r(o);return n}function hl(e,t,n){let r=Zn.getOrElse(v(e),()=>[]);if(r.length!==0){t.push(`${n}par Parallel`);for(let o=0;o<r.length;o++){o>0&&t.push(`${n}and`);let s=r[o];if(s)if(s.type==="effect"&&s.serviceCall)t.push(`${n} Program->>${s.serviceCall.serviceType}: ${s.serviceCall.methodName}()`),t.push(`${n} ${s.serviceCall.serviceType}-->>Program: result`);else if(s.type==="effect")t.push(`${n} Note over Program: ${j(s.callee,_)}`);else{let a=s.displayName??s.name??(typeof s.type=="string"?s.type:"node"),i=j(a,_);t.push(`${n} Note over Program: ${i}`)}}t.push(`${n}end`)}}function yl(e){let t=gl(e.root.children);if(t.length===0)return`sequenceDiagram
|
|
38
38
|
participant Program
|
|
39
|
-
Note over Program: Empty program`;let
|
|
40
|
-
`)}import{Option as
|
|
41
|
-
`)}function
|
|
42
|
-
NoLayers((No layers))`;let o=[`flowchart ${
|
|
43
|
-
`)}import{Option as
|
|
44
|
-
NoRetry((No retry/timeout patterns))`;let o=[`flowchart ${
|
|
45
|
-
`)}function
|
|
46
|
-
NoMocks((No services to mock - pure computation))`;let s=new Set(o.filter(l=>l.isLayer).map(l=>l.name)),a=[`flowchart ${
|
|
47
|
-
`)}import{Option as
|
|
48
|
-
NoData((No data transformations))`;let o=[`flowchart ${
|
|
49
|
-
`)}import{Option as
|
|
50
|
-
`)}function Vn(e){let t=e.root.children;if(Ye(t,"parallel")||Ye(t,"race")||Ye(t,"switch")||Ye(t,"loop")||Ye(t,"conditional")||Ye(t,"decision"))return"mermaid";let r=e.metadata.stats;if(r.decisionCount>2||r.switchCount>0||r.conditionalCount>2)return"mermaid";let n=Se(e);return n.cyclomaticComplexity<=3&&n.decisionPoints<=1&&n.maxDepth<=2?"railway":"mermaid"}function Ye(e,t){for(let r of e){if(r.type===t)return!0;let n=Al.getOrElse(v(r),()=>[]);if(n.length>0&&Ye(n,t))return!0}return!1}import{Option as od}from"effect";var Fl={maxPaths:1e3,expandLoops:!1,maxLoopIterations:3};function kt(e,t={}){return Ho(e,t).paths}function Ho(e,t={}){let n={opts:{...Fl,...t},pathCount:0,hasHitLimit:!1,controlStack:[]},o={steps:[],conditions:[],hasLoops:!1,hasUnresolvedRefs:!1};return{paths:ue(e.root.children,o,n).map((i,c)=>({id:`path-${c+1}`,description:td(i),steps:i.steps,conditions:i.conditions,hasLoops:i.hasLoops,hasUnresolvedRefs:i.hasUnresolvedRefs})),limitHit:n.hasHitLimit}}function ue(e,t,r){if(e.length===0)return[t];let n=[t];for(let o of e){let s=[];for(let a of n)s.push(...oe(o,a,r));if(n=s,o.type==="terminal"){let a=o;if(a.terminalKind==="return"||a.terminalKind==="throw")return n}}return n}function oe(e,t,r){switch(e.type){case"effect":return Rl(e,t);case"generator":return $l(e,t,r);case"pipe":return Dl(e,t,r);case"parallel":return Pl(e,t,r);case"race":return Ml(e,t,r);case"error-handler":return Ll(e,t,r);case"retry":case"timeout":return Ol(e,t,r);case"resource":return Wl(e,t,r);case"conditional":return Kl(e,t,r);case"loop":return Bl(e,t,r);case"layer":return ql(e,t,r);case"stream":return jl(e,t,r);case"concurrency-primitive":case"fiber":return _l(e,t,r);case"decision":return zl(e,t,r);case"switch":return Hl(e,t,r);case"try-catch":return Ul(e,t,r);case"terminal":return Vl(e,t,r);case"cause":return Jl(e,t,r);case"exit":case"schedule":return Gl(e,t);case"match":return Yl(e,t,r);case"transform":return Ql(e,t,r);case"channel":return Zl(e,t,r);case"sink":return Xl(e,t,r);case"interruption":return ed(e,t,r);case"opaque":return[t];case"unknown":return[t];default:return[t]}}function Rl(e,t){let r={nodeId:e.id,name:e.name??e.callee,repeated:!1};return[{...t,steps:[...t.steps,r]}]}function $l(e,t,r){let n=e.yields.map(o=>o.effect);return ue(n,t,r)}function Dl(e,t,r){let n=[e.initial,...e.transformations];return ue(n,t,r)}function Pl(e,t,r){let n=[t];for(let o of e.children){let s=[];for(let a of n){let i=oe(o,a,r);for(let c of i)s.push({steps:c.steps,conditions:c.conditions,hasLoops:a.hasLoops||c.hasLoops,hasUnresolvedRefs:a.hasUnresolvedRefs||c.hasUnresolvedRefs})}n=s}return n}function Ml(e,t,r){if(e.children.length===0)return[t];if(r.hasHitLimit||r.pathCount+e.children.length>=r.opts.maxPaths){r.hasHitLimit=!0;let a=e.children[0];return a?oe(a,t,r):[t]}let o=[],s=r.opts.maxPaths;for(let a of e.children){if(o.length>=s){r.hasHitLimit=!0;break}let i=oe(a,t,r),c=s-o.length,d=i.slice(0,c);o.push(...d),d.length<i.length&&(r.hasHitLimit=!0)}return r.pathCount+=Math.max(0,o.length-1),o.length>0?o:[t]}function Ll(e,t,r){let n=oe(e.source,t,r);if(!e.handler)return n;let o=oe(e.handler,t,r);return[...n,...o]}function Ol(e,t,r){return oe(e.source,t,r)}function Wl(e,t,r){let n=[e.acquire,e.release];return e.use&&n.push(e.use),ue(n,t,r)}function Kl(e,t,r){let n={expression:e.condition,mustBe:e.conditionalType!=="unless",location:e.location},o={...t,conditions:[...t.conditions,n]},s=oe(e.onTrue,o,r),a={expression:e.condition,mustBe:e.conditionalType==="unless",location:e.location},i={...t,conditions:[...t.conditions,a]};if(e.onFalse){let c=oe(e.onFalse,i,r);return[...s,...c]}return[...s,i]}function Bl(e,t,r){return oe(e.body,t,r).map(o=>({...o,steps:o.steps.map((s,a)=>a>=t.steps.length?{...s,repeated:!0}:s),hasLoops:!0}))}function ql(e,t,r){return ue(e.operations,t,r)}function jl(e,t,r){let n={nodeId:e.id,name:e.pipeline.length>0?`Stream.${e.pipeline.map(s=>s.operation).join(" \u2192 ")}`:"Stream",repeated:!1},o={...t,steps:[...t.steps,n]};return oe(e.source,o,r)}function _l(e,t,r){let n={nodeId:e.id,name:e.type==="concurrency-primitive"?`${e.primitive}.${e.operation}`:e.operation,repeated:!1},o={...t,steps:[...t.steps,n]},s=e.type==="concurrency-primitive"?e.source:e.fiberSource;return s?oe(s,o,r):[o]}function zl(e,t,r){let n={expression:e.condition,mustBe:!0,location:e.location},o={...t,conditions:[...t.conditions,n]},s=ue(e.onTrue,o,r);if(e.onFalse&&e.onFalse.length>0){let c={expression:e.condition,mustBe:!1,location:e.location},d={...t,conditions:[...t.conditions,c]},l=ue(e.onFalse,d,r);return[...s,...l]}let a={expression:e.condition,mustBe:!1,location:e.location},i={...t,conditions:[...t.conditions,a]};return[...s,i]}function Hl(e,t,r){let n=[];for(let o of e.cases){let s=o.labels.join(" / "),a={expression:`${e.expression} === ${s}`,mustBe:!0,location:e.location},i={...t,conditions:[...t.conditions,a]},c=ue(o.body,i,r);n.push(...c)}return n.length>0?n:[t]}function Ul(e,t,r){let n=ue(e.tryBody,t,r),o=[];if(e.catchBody&&e.catchBody.length>0){let a={expression:"throws",mustBe:!0,location:e.location},i={...t,conditions:[...t.conditions,a]};o.push(...ue(e.catchBody,i,r))}let s=[...n,...o];if(e.finallyBody&&e.finallyBody.length>0){let a=[];for(let i of s)a.push(...ue(e.finallyBody,i,r));return a}return s}function Vl(e,t,r){let n=t;switch(e.value&&e.value.length>0&&(n=ue(e.value,t,r)[0]??t),e.terminalKind){case"return":case"throw":return[{...n,steps:[...n.steps,{nodeId:e.id,name:e.terminalKind,repeated:!1}]}];case"break":case"continue":return[n]}}function Gl(e,t){let r={nodeId:e.id,name:e.name??e.type,repeated:!1};return[{...t,steps:[...t.steps,r]}]}function Jl(e,t,r){let n={nodeId:e.id,name:e.name??`Cause.${e.causeOp}`,repeated:!1},o={...t,steps:[...t.steps,n]};return e.children&&e.children.length>0?ue([...e.children],o,r):[o]}function Yl(e,t,r){let n={nodeId:e.id,name:e.name??`Match.${e.matchOp}`,repeated:!1};return[{...t,steps:[...t.steps,n]}]}function Ql(e,t,r){let n=t;e.source&&(n=oe(e.source,t,r)[0]??t);let o={nodeId:e.id,name:e.name??e.transformType,repeated:!1};return[{...n,steps:[...n.steps,o]}]}function Zl(e,t,r){let n=t;e.source&&(n=oe(e.source,t,r)[0]??t);let o={nodeId:e.id,name:e.name??`Channel${e.pipeline.length>0?`.${e.pipeline.map(s=>s.operation).join(".")}`:""}`,repeated:!1};return[{...n,steps:[...n.steps,o]}]}function Xl(e,t,r){let n=t;e.source&&(n=oe(e.source,t,r)[0]??t);let o={nodeId:e.id,name:e.name??`Sink${e.pipeline.length>0?`.${e.pipeline.map(s=>s.operation).join(".")}`:""}`,repeated:!1};return[{...n,steps:[...n.steps,o]}]}function ed(e,t,r){let n={nodeId:e.id,name:e.name??e.interruptionType,repeated:!1},o={...t,steps:[...t.steps,n]};if(e.source){let s=oe(e.source,o,r);if(e.handler){let a=oe(e.handler,o,r);return[...s,...a]}return s}return[o]}function td(e){let t=[];if(e.conditions.length>0){let n=e.conditions.map(o=>{let s=o.mustBe?"is true":"is false";return`${o.expression.length>30?o.expression.slice(0,30)+"...":o.expression} ${s}`});t.push(`When ${n.join(" AND ")}`)}let r=e.steps.map(n=>{let o=n.name??n.nodeId;return n.repeated?`${o} (repeated)`:o}).join(" \u2192 ");return r&&t.push(`Steps: ${r}`),e.hasLoops&&t.push("[contains loops]"),e.hasUnresolvedRefs&&t.push("[has unresolved refs]"),t.join(". ")||"Empty path"}function nd(e,t){if(e.length===0)return{totalPaths:0,pathLimitHit:!1,pathsWithLoops:0,pathsWithUnresolvedRefs:0,uniqueConditions:[],maxPathLength:0,minPathLength:0,avgPathLength:0};let r=new Set,n=0,o=0,s=0,a=0,i=1/0;for(let c of e){c.hasLoops&&n++,c.hasUnresolvedRefs&&o++;let d=c.steps.length;s+=d,a=Math.max(a,d),i=Math.min(i,d);for(let l of c.conditions)r.add(l.expression)}return{totalPaths:e.length,pathLimitHit:t?.limitHit??!1,pathsWithLoops:n,pathsWithUnresolvedRefs:o,uniqueConditions:Array.from(r),maxPathLength:a,minPathLength:i===1/0?0:i,avgPathLength:s/e.length}}function rd(e,t){return e.filter(r=>!(t.mustIncludeStep&&!r.steps.some(o=>o.name===t.mustIncludeStep||o.nodeId===t.mustIncludeStep)||t.mustExcludeStep&&r.steps.some(o=>o.name===t.mustExcludeStep||o.nodeId===t.mustExcludeStep)||t.conditionTrue&&!r.conditions.some(o=>o.expression===t.conditionTrue&&o.mustBe)||t.conditionFalse&&!r.conditions.some(o=>o.expression===t.conditionFalse&&!o.mustBe)||t.noLoops&&r.hasLoops||t.maxLength!==void 0&&r.steps.length>t.maxLength))}var Uo=3,sd=5;function Vo(e,t,r){return Math.max(t,Math.min(r,e))}function It(e,t){return[...new Set(e)].slice(0,t)}function Go(e){return e.startsWith("Consider")||e.startsWith("If you want clearer diagrams")||e.startsWith("For larger programs")}function tn(e){return Go(e)?e:`Consider ${e.charAt(0).toLowerCase()}${e.slice(1)}`}function id(e){let t=[],r=n=>{for(let o of n){t.push(o);let s=od.getOrElse(v(o),()=>[]);s.length>0&&r(s)}};return r(e),t}function ad(e){let t=e.toLowerCase();return t.includes("log")||t.includes("logger")||t.includes("taperror")}function cd(e){let t=e.callee.trim();return!!(t===""||t==="_"||t==="Effect"||/call expression/i.test(t)||/^program-\d+$/i.test(e.name??""))}function ld(e){return e.type==="effect"&&(e.semanticRole==="service-call"||e.serviceCall!==void 0||e.serviceMethod!==void 0)}function dd(e){let t=e.callee.trim();return!(t===""||t==="_"||t==="Effect"||/unknown/i.test(t)||/call expression/i.test(t))}function ud(e,t={}){let r=id(e.root.children),n=r.length,o=r.filter(x=>x.type==="effect"),s=o.filter(x=>x.semanticRole==="side-effect"),a=o.filter(x=>ad(x.displayName??x.name??x.callee)),i=r.filter(x=>x.type==="unknown").length,c=r.filter(x=>x.type==="unknown"||x.type==="pipe"?!0:x.type==="effect"?cd(x):!1).length,d=r.filter(x=>ld(x)),l=d.filter(x=>dd(x)),f=r.filter(x=>x.type==="pipe"),u=f.length,p=f.length>0?Math.max(...f.map(x=>1+x.transformations.length)):0,m=[...kt(e)].sort((x,C)=>C.steps.length-x.steps.length)[0],S=m?Gt(m,{collapseRepeatedLogs:!0,collapsePureTransforms:!0,styleGuide:t.styleGuideSummary??!1}):{steps:[],collapsedGroups:0},h=n>0?n:1,N=d.length>0?d.length:1;return{stepCountDetailed:n,stepCountSummary:S.steps.length,collapsedGroupsSummary:S.collapsedGroups,logRatio:a.length/h,sideEffectRatio:s.length/h,anonymousNodeCount:c,anonymousRatio:c/h,unknownNodeCount:i,serviceCallCount:d.length,namedServiceCallRatio:l.length/N,pipeChainCount:u,maxPipeChainLength:p}}function fd(e){let t=Math.min(35,e.unknownNodeCount*8),r=Math.min(25,Math.round(e.anonymousRatio*40)),n=e.stepCountDetailed>24?Math.min(22,Math.round((e.stepCountDetailed-24)*.6)):0,o=Math.min(12,Math.round(e.logRatio*30)),s=e.sideEffectRatio>.75?Math.min(8,Math.round((e.sideEffectRatio-.75)*40)):0,a=Vo(Math.round(100-t-r-n-o-s),0,100),i=a>=75?"good":a>=50?"ok":"noisy";return{score:a,band:i}}function Jo(e){let t=[],r=Math.round(e.logRatio*Math.max(e.stepCountDetailed,1));return e.stepCountDetailed>=60?t.push(`High step count (${String(e.stepCountDetailed)}). Consider summary mode.`):e.stepCountDetailed>=35&&t.push(`Moderate step count (${String(e.stepCountDetailed)}). Summary mode may improve readability.`),(r>=12||e.logRatio>=.35)&&t.push(`Many log steps (${String(r)}). Consider collapsing logs or summary mode.`),e.anonymousNodeCount>=5&&t.push(`${String(e.anonymousNodeCount)} anonymous nodes from pipe chains or unnamed calls.`),e.unknownNodeCount>0&&t.push(`${String(e.unknownNodeCount)} unresolved nodes may reduce diagram clarity.`),e.serviceCallCount>=3&&e.namedServiceCallRatio<.7&&t.push(`Service call naming clarity is ${(e.namedServiceCallRatio*100).toFixed(0)}% (${String(e.serviceCallCount)} calls).`),t}function Yo(e){let t=[],r=Math.round(e.logRatio*Math.max(e.stepCountDetailed,1));return e.stepCountDetailed>=35&&t.push("For larger programs, consider summary mode."),(r>=12||e.logRatio>=.35)&&t.push("For larger programs, consider grouping logs or using summary mode."),e.anonymousNodeCount>=5&&t.push("Consider naming intermediate values or extracting named helpers."),(e.pipeChainCount>=4||e.maxPipeChainLength>=6)&&t.push("If you want clearer diagrams, consider splitting long pipe chains into named steps."),e.serviceCallCount>=3&&e.namedServiceCallRatio<.7&&t.push("Consider naming service-call intermediates to make boundaries explicit."),It(t.map(tn),Uo)}function Qo(e,t={}){let r=ud(e,t),{score:n,band:o}=fd(r),s=Jo(r),a=Yo(r),i=t.hints?.reasons??[],c=(t.hints?.tips??[]).map(tn);return{score:n,band:o,metrics:r,reasons:It([...s,...i],8),tips:It([...a,...c],Uo)}}function pd(e){if(e.length===0)return{stepCountDetailed:0,stepCountSummary:0,collapsedGroupsSummary:0,logRatio:0,sideEffectRatio:0,anonymousNodeCount:0,anonymousRatio:0,unknownNodeCount:0,serviceCallCount:0,namedServiceCallRatio:0,pipeChainCount:0,maxPipeChainLength:0};let t=e.map(s=>Math.max(1,s.metrics.stepCountDetailed)),r=t.reduce((s,a)=>s+a,0),n=s=>e.reduce((a,i,c)=>a+s(i)*(t[c]??1),0)/r,o=s=>e.reduce((a,i)=>a+s(i),0);return{stepCountDetailed:Math.round(n(s=>s.metrics.stepCountDetailed)),stepCountSummary:Math.round(n(s=>s.metrics.stepCountSummary)),collapsedGroupsSummary:Math.round(n(s=>s.metrics.collapsedGroupsSummary)),logRatio:n(s=>s.metrics.logRatio),sideEffectRatio:n(s=>s.metrics.sideEffectRatio),anonymousNodeCount:Math.round(o(s=>s.metrics.anonymousNodeCount)),anonymousRatio:n(s=>s.metrics.anonymousRatio),unknownNodeCount:Math.round(o(s=>s.metrics.unknownNodeCount)),serviceCallCount:Math.round(o(s=>s.metrics.serviceCallCount)),namedServiceCallRatio:n(s=>s.metrics.namedServiceCallRatio),pipeChainCount:Math.round(o(s=>s.metrics.pipeChainCount)),maxPipeChainLength:Math.max(...e.map(s=>s.metrics.maxPipeChainLength))}}function gd(e,t,r={}){let n=t.map(d=>Qo(d,r)),o=pd(n),s=n.length>0?Math.round(n.reduce((d,l)=>d+l.score*Math.max(1,l.metrics.stepCountDetailed),0)/n.reduce((d,l)=>d+Math.max(1,l.metrics.stepCountDetailed),0)):100,a=s>=75?"good":s>=50?"ok":"noisy",i=It([...Jo(o),...r.hints?.reasons??[]],10),c=It([...Yo(o),...(r.hints?.tips??[]).map(tn)].filter(Go),sd);return{filePath:e,quality:{score:s,band:a,metrics:o,reasons:i,tips:c}}}function md(e,t,r){return{filePath:e,metricValue:t,tip:tn(r)}}function en(e,t,r,n){return[...e].sort((o,s)=>{let a=t(s)-t(o);return a!==0?a:o.filePath.localeCompare(s.filePath)}).slice(0,n).map(o=>md(o.filePath,t(o),r(o)))}function hd(e,t=10){let r=Vo(t,1,50);return{largestPrograms:en(e,n=>n.quality.metrics.stepCountDetailed,()=>"For larger programs, consider summary mode.",r),mostAnonymousNodes:en(e,n=>n.quality.metrics.anonymousNodeCount,()=>"Consider naming intermediate values or extracting named helpers.",r),mostUnknownNodes:en(e,n=>n.quality.metrics.unknownNodeCount,()=>"If you want clearer diagrams, consider extracting helpers to reduce unresolved nodes.",r),highestLogRatio:en(e,n=>n.quality.metrics.logRatio,()=>"For larger programs, consider grouping logs or using summary mode.",r)}}import{readFile as yd}from"fs/promises";import{resolve as Sd}from"path";function xd(e){return e?/effect/i.test(e):!1}function Ed(e){let t=`${e.ruleId??""} ${e.message??""}`.toLowerCase();if(t.includes("yield")||t.includes("untagged"))return"Consider binding yielded values with meaningful names.";if(t.includes("error")||t.includes("catch")||t.includes("handle"))return"If you want clearer diagrams, consider making error boundaries explicit.";if(t.includes("service")||t.includes("layer")||t.includes("provide"))return"Consider acquiring services near the top of the workflow.";if(t.includes("pipe")||t.includes("nested")||t.includes("lambda"))return"If you want clearer diagrams, consider extracting nested pipe lambdas into named helpers."}function bd(e){let t=e.ruleId??"eslint",r=(e.message??"").trim();if(r)return`ESLint (${t}): ${r}`}function Cd(e){if(Array.isArray(e))return e;if(e&&typeof e=="object"&&"results"in e){let t=e.results;if(Array.isArray(t))return t}return[]}async function Nd(e){let t=await yd(e,"utf-8"),r=JSON.parse(t),n=Cd(r),o=new Map;for(let a of n){let i=a.filePath?Sd(a.filePath):void 0;if(!i)continue;let c=a.messages??[];for(let d of c){if(!xd(d.ruleId))continue;let l=o.get(i)??{reasons:[],tips:[]},f=bd(d);f&&l.reasons.push(f);let u=Ed(d);u&&l.tips.push(u),o.set(i,l)}}let s=new Map;for(let[a,i]of o)s.set(a,{reasons:[...new Set(i.reasons)].slice(0,8),tips:[...new Set(i.tips)].slice(0,5)});return s}var vd=e=>" ".repeat(e);function Zo(e){switch(e.type){case"effect":return e.serviceCall?`${e.serviceCall.serviceType}.${e.serviceCall.methodName}`:e.displayName??e.callee;case"generator":return"Effect.gen block";case"pipe":return`pipe(${Zo(e.initial)})`;case"parallel":return`${e.callee}(${e.children.length} effects)`;case"race":return`${e.callee}(${e.children.length} effects)`;case"error-handler":return e.handlerType;case"retry":return"retry";case"timeout":return e.duration?`timeout(${e.duration})`:"timeout";case"resource":return"acquireRelease";case"conditional":return`if ${e.conditionLabel??e.condition}`;case"loop":return`${e.loopType}${e.iterSource?`(${e.iterSource})`:""}`;case"layer":return e.provides?`Layer(${e.provides.join(", ")})`:"Layer";case"stream":return"Stream";case"fiber":return`Fiber.${e.operation}`;case"concurrency-primitive":return`${e.primitive}.${e.operation}`;case"decision":return`if ${e.condition}`;case"switch":return`switch(${e.expression})`;case"try-catch":return"try/catch";case"terminal":return e.terminalKind;case"match":return e.matchedTags?`Match(${e.matchedTags.join(", ")})`:"Match";case"transform":return e.transformType;case"channel":return"Channel";case"sink":return"Sink";case"cause":return`Cause.${e.causeOp}`;case"exit":return`Exit.${e.exitOp}`;case"schedule":return`Schedule.${e.scheduleOp}`;case"interruption":return e.interruptionType;case"opaque":return`(opaque: ${e.reason})`;case"unknown":return`(unknown: ${e.reason})`}}function B(e,t,r={hasParallelism:!1,serviceCallsSeen:new Set}){let n=vd(t),o=[];switch(e.type){case"effect":{if(e.serviceCall)if(r.serviceCallsSeen.add(e.serviceCall.serviceType),e.callee.includes("Tag")||e.callee.includes("Context")||e.callee===e.serviceCall.serviceType)o.push(`${n}Acquires ${e.serviceCall.serviceType} service`);else{let s=e.description?` \u2014 ${e.description}`:"";o.push(`${n}Calls ${e.serviceCall.serviceType}.${e.serviceCall.methodName}${s}`)}else{let s=e.displayName??e.callee,a=e.description?` \u2014 ${e.description}`:"";s.includes(" <- ")?o.push(`${n}Yields ${s}`):o.push(`${n}Calls ${s}${a}`)}break}case"generator":{for(let s of e.yields){let a=B(s.effect,t,r),i=a[0];if(s.variableName&&i!==void 0){let c=i.trimStart();c.includes(`${s.variableName} <-`)||c.includes(`${s.variableName} =`)||(a[0]=`${n}${s.variableName} = ${c.replace(/^Calls /,"")}`)}o.push(...a)}if(e.returnNode){let s=B(e.returnNode,t,r),a=s[0];if(a!==void 0){let i=a.trimStart();s[0]=`${n}Returns ${i.replace(/^Calls /,"")}`,o.push(...s)}}break}case"pipe":{o.push(`${n}Pipes ${Zo(e.initial)} through:`);let s=B(e.initial,t+1,r);o.push(...s);for(let a of e.transformations){let i=B(a,t+1,r);o.push(...i)}break}case"parallel":{r.hasParallelism=!0;let s=e.concurrency!==void 0&&e.concurrency!=="sequential"?` (concurrency: ${e.concurrency})`:"";o.push(`${n}Runs ${e.children.length} effects in ${e.mode}${s}:`);for(let a of e.children)o.push(...B(a,t+1,r));break}case"race":{r.hasParallelism=!0,o.push(`${n}Races ${e.children.length} effects:`);for(let s of e.children)o.push(...B(s,t+1,r));break}case"error-handler":{let s=e.errorTag?` "${e.errorTag}"`:e.errorTags&&e.errorTags.length>0?` [${e.errorTags.join(", ")}]`:"";switch(e.handlerType){case"catchAll":o.push(`${n}Catches all errors on:`);break;case"catchTag":o.push(`${n}Catches tag${s} on:`);break;case"catchTags":o.push(`${n}Catches tags${s} on:`);break;case"orElse":o.push(`${n}Falls back (orElse) on error:`);break;case"orDie":o.push(`${n}Converts errors to defects (orDie):`);break;case"mapError":o.push(`${n}Maps error on:`);break;case"ignore":o.push(`${n}Ignores errors on:`);break;default:o.push(`${n}Handles errors (${e.handlerType})${s}:`)}o.push(...B(e.source,t+1,r)),e.handler&&(o.push(`${n} Handler:`),o.push(...B(e.handler,t+2,r)));break}case"retry":{if(e.scheduleInfo){let s=e.scheduleInfo.maxRetries!==void 0?`max ${e.scheduleInfo.maxRetries}`:"",a=e.scheduleInfo.baseStrategy,i=[s,a].filter(Boolean).join(", ");o.push(`${n}Retries (${i}):`)}else e.schedule?o.push(`${n}Retries with ${e.schedule}:`):o.push(`${n}Retries:`);o.push(...B(e.source,t+1,r)),e.hasFallback&&o.push(`${n} (with fallback on exhaustion)`);break}case"timeout":{let s=e.duration?` after ${e.duration}`:"";o.push(`${n}Times out${s}:`),o.push(...B(e.source,t+1,r)),e.hasFallback&&o.push(`${n} (with fallback on timeout)`);break}case"resource":{o.push(`${n}Acquires resource:`),o.push(...B(e.acquire,t+1,r)),e.use&&(o.push(`${n} Uses:`),o.push(...B(e.use,t+2,r))),o.push(`${n} Then releases:`),o.push(...B(e.release,t+2,r));break}case"conditional":{let s=e.conditionLabel??e.condition;o.push(`${n}If ${s}:`),o.push(...B(e.onTrue,t+1,r)),e.onFalse&&(o.push(`${n}Else:`),o.push(...B(e.onFalse,t+1,r)));break}case"decision":{o.push(`${n}If ${e.condition}:`);for(let s of e.onTrue)o.push(...B(s,t+1,r));if(e.onFalse&&e.onFalse.length>0){o.push(`${n}Else:`);for(let s of e.onFalse)o.push(...B(s,t+1,r))}break}case"switch":{o.push(`${n}Switch on ${e.expression}:`);for(let s of e.cases){let a=s.isDefault?"default":s.labels.join(", ");o.push(`${n} Case ${a}:`);for(let i of s.body)o.push(...B(i,t+2,r))}break}case"try-catch":{o.push(`${n}Try:`);for(let s of e.tryBody)o.push(...B(s,t+1,r));if(e.catchBody&&e.catchBody.length>0){o.push(`${n}Catch:`);for(let s of e.catchBody)o.push(...B(s,t+1,r))}if(e.finallyBody&&e.finallyBody.length>0){o.push(`${n}Finally:`);for(let s of e.finallyBody)o.push(...B(s,t+1,r))}break}case"terminal":{switch(e.terminalKind){case"return":{if(e.value&&e.value.length>0){o.push(`${n}Returns:`);for(let s of e.value)o.push(...B(s,t+1,r))}else o.push(`${n}Returns`);break}case"throw":o.push(`${n}Throws`);break;case"break":o.push(`${n}Breaks`);break;case"continue":o.push(`${n}Continues`);break}break}case"loop":{let s=e.iterSource?` over ${e.iterSource}`:"";o.push(`${n}Iterates (${e.loopType})${s}:`),o.push(...B(e.body,t+1,r));break}case"layer":{let s=e.provides&&e.provides.length>0?` providing ${e.provides.join(", ")}`:"",a=e.requires&&e.requires.length>0?` (requires ${e.requires.join(", ")})`:"";o.push(`${n}Provides layer${s}${a}:`);for(let i of e.operations)o.push(...B(i,t+1,r));break}case"stream":{let s=e.pipeline.map(i=>i.operation).join(" -> "),a=e.sink?` -> ${e.sink}`:"";o.push(`${n}Stream: ${s}${a}`),o.push(...B(e.source,t+1,r));break}case"fiber":{let s=e.isDaemon?" (daemon)":e.isScoped?" (scoped)":"";o.push(`${n}Fiber ${e.operation}${s}:`),e.fiberSource&&o.push(...B(e.fiberSource,t+1,r));break}case"concurrency-primitive":{let s=e.capacity!==void 0?` (capacity: ${e.capacity})`:"";o.push(`${n}${e.primitive}.${e.operation}${s}`),e.source&&o.push(...B(e.source,t+1,r));break}case"match":{e.matchedTags&&e.matchedTags.length>0?o.push(`${n}Matches tags: ${e.matchedTags.join(", ")}`):o.push(`${n}Match (${e.matchOp})`);break}case"transform":{o.push(`${n}Transforms via ${e.transformType}`),e.source&&o.push(...B(e.source,t+1,r));break}case"cause":{if(o.push(`${n}Cause.${e.causeOp}`),e.children)for(let s of e.children)o.push(...B(s,t+1,r));break}case"exit":{o.push(`${n}Exit.${e.exitOp}`);break}case"schedule":{o.push(`${n}Schedule.${e.scheduleOp}`);break}case"channel":{let s=e.pipeline.map(a=>a.operation).join(" -> ");o.push(`${n}Channel${s?`: ${s}`:""}`),e.source&&o.push(...B(e.source,t+1,r));break}case"sink":{let s=e.pipeline.map(a=>a.operation).join(" -> ");o.push(`${n}Sink${s?`: ${s}`:""}`),e.source&&o.push(...B(e.source,t+1,r));break}case"interruption":{o.push(`${n}${e.interruptionType}`),e.source&&o.push(...B(e.source,t+1,r)),e.handler&&(o.push(`${n} On interrupt:`),o.push(...B(e.handler,t+2,r)));break}case"opaque":{o.push(`${n}(opaque: ${e.reason})`);break}case"unknown":{o.push(`${n}(unknown: ${e.reason})`);break}}return o}function wd(e,t){let r={hasParallelism:!1,serviceCallsSeen:new Set},n=[];for(let d of e.children)n.push(...B(d,1,r));let o=Td(n),s=`${e.programName} (${e.source}):`,a=[],i=new Set;for(let d of e.dependencies)i.add(d.name);Array.from(r.serviceCallsSeen).forEach(d=>{i.add(d)}),i.size>0&&a.push(` Services required: ${Array.from(i).join(", ")}`),e.errorTypes.length>0&&a.push(` Error paths: ${e.errorTypes.join(", ")}`),r.hasParallelism?a.push(" Concurrency: uses parallelism / racing"):a.push(" Concurrency: sequential (no parallelism)");let c=[s,o.join(`
|
|
39
|
+
Note over Program: Empty program`;let n=ml(t),r=["sequenceDiagram"];r.push(" participant Program");for(let o of n)r.push(` participant ${o}`);for(let o of t)switch(o.kind){case"service-call":{let s=o.node;if(s.type==="effect"&&s.serviceCall){let a=s.serviceCall.serviceType,i=s.serviceCall.methodName;r.push(` Program->>${a}: ${i}()`),r.push(` ${a}-->>Program: result`)}break}case"effect-constructor":{let s=o.node;s.type==="effect"&&r.push(` Note over Program: ${j(s.callee,_)}`);break}case"retry":{let s=o.node;if(s.type==="retry"){let a=s.scheduleInfo;if(a){let i=a.maxRetries!==void 0?`${a.maxRetries}x`:"unlimited";r.push(` Note over Program: ${j(`retry (${i}, ${a.baseStrategy})`,_)}`)}else s.schedule?r.push(` Note over Program: ${j(`retry (${s.schedule})`,_)}`):r.push(" Note over Program: retry")}break}case"timeout":{let s=o.node;if(s.type==="timeout"){let a=s.duration??"unknown";r.push(` Note over Program: timeout(${a})`)}break}case"parallel":{hl(o.node,r," ");break}}return r.join(`
|
|
40
|
+
`)}import{Option as Sl}from"effect";function Ho(e,t){for(let n of e){if(n.type==="layer"){let o=n,s={id:o.id,provides:[...o.provides??[]],requires:[...o.requires??[]],lifecycle:o.lifecycle??"default",isMerged:o.isMerged,operationLayerIds:o.operations.filter(a=>a.type==="layer").map(a=>a.id)};o.name!==void 0&&(s.name=o.name),t.push(s)}let r=Sl.getOrElse(v(n),()=>[]);r.length>0&&Ho(r,t)}}function Qe(e){let t=[];Ho(e.root.children,t);let n=[],r=new Map;for(let o of t){for(let s of o.operationLayerIds)n.push({from:o.id,to:s,kind:"merge"});for(let s of o.provides){let a=r.get(s)??[];a.push(o.id),r.set(s,a),n.push({from:o.id,to:s,kind:"provides"})}for(let s of o.requires)n.push({from:o.id,to:s,kind:"requires"})}return{layers:t,edges:n,serviceToLayers:r}}function Uo(e){let t=new Map;for(let i of e.layers)for(let c of i.provides){let d=t.get(c)??[];d.push(i.id),t.set(c,d)}let n=new Map;for(let i of e.layers){let c=[];for(let d of i.requires)for(let l of t.get(d)??[])l!==i.id&&c.push(l);n.set(i.id,c)}let r=[],o=new Set,s=new Set;function a(i,c){if(!s.has(i)){if(o.has(i)){let d=c.indexOf(i);d>=0&&r.push({path:[...c.slice(d),i]});return}o.add(i),c.push(i);for(let d of n.get(i)??[])a(d,c);c.pop(),o.delete(i),s.add(i)}}for(let i of n.keys())a(i,[]);return r}function xl(e){let t=[];for(let[n,r]of e.serviceToLayers)r.length>1&&t.push({serviceId:n,providers:[...r]});return t}function El(e){let t=new Set;for(let r of e.layers)for(let o of r.provides)t.add(o);let n=new Map;for(let r of e.layers)for(let o of r.requires)if(!t.has(o)){let s=n.get(o)??[];s.push(r.id),n.set(o,s)}return Array.from(n.entries()).map(([r,o])=>({serviceId:r,requiredBy:o}))}function bl(e){let t=new Map;for(let s of e.layers)for(let a of s.provides){let i=t.get(a)??[];i.push(s.id),t.set(a,i)}let n=new Map,r=new Set;function o(s){let a=n.get(s);if(a!==void 0)return a;if(r.has(s))return 0;r.add(s);let i=e.layers.find(d=>d.id===s);if(!i)return 0;let c=0;for(let d of i.requires)for(let l of t.get(d)??[])l!==s&&(c=Math.max(c,o(l)+1));return n.set(s,c),c}for(let s of e.layers)o(s.id);return n}function xe(e){return e.replace(/[^a-zA-Z0-9_]/g,"_")}var Xn=["#C8E6C9","#A5D6A7","#81C784","#66BB6A","#4CAF50","#43A047","#388E3C","#2E7D32","#1B5E20"];function Cl(e){let t=[];t.push("graph TD"),t.push("");let n=Uo(e),r=new Set;for(let i of n)for(let c=0;c<i.path.length-1;c++)r.add(`${i.path[c]}\u2192${i.path[c+1]}`);let o=bl(e);for(let i of e.layers){let c=i.name??i.id;t.push(` ${xe(i.id)}["${c}"]`)}t.push("");let s=new Set;for(let i of e.edges)i.kind==="provides"&&s.add(i.to);for(let i of s)t.push(` ${xe(i)}["${i}"]`);t.push("");for(let i of e.edges){let c=r.has(`${i.from}\u2192${i.to}`);i.kind==="provides"?t.push(` ${xe(i.from)} -.->|provides| ${xe(i.to)}`):i.kind==="requires"?c?t.push(` ${xe(i.from)} -->|\u26A0 CYCLE| ${xe(i.to)}`):t.push(` ${xe(i.from)} --> ${xe(i.to)}`):t.push(` ${xe(i.from)} -->|merge| ${xe(i.to)}`)}t.push(""),t.push(" %% Depth-based styling");let a=Math.max(...Array.from(o.values()),0);for(let i=0;i<=a&&i<Xn.length;i++)t.push(` classDef depth${i} fill:${Xn[i]},stroke:#333`);for(let i of e.layers){let c=Math.min(o.get(i.id)??0,Xn.length-1);t.push(` class ${xe(i.id)} depth${c}`)}if(n.length>0){t.push(" classDef cycleNode fill:#FFCDD2,stroke:#C62828,stroke-width:3px");let i=new Set;for(let c of n)for(let d of c.path)i.add(d);for(let c of i)t.push(` class ${xe(c)} cycleNode`)}return t.join(`
|
|
41
|
+
`)}function gt(e){return e.replace(/[^a-zA-Z0-9_]/g,"_")}function Nl(e,t={}){let n=t.direction??"TB",r=Qe(e);if(r.layers.length===0)return`flowchart ${n}
|
|
42
|
+
NoLayers((No layers))`;let o=[`flowchart ${n}`],s=new Set;for(let i of r.layers){for(let c of i.provides)s.add(c);for(let c of i.requires)s.add(c)}let a=new Set;for(let i of r.layers){let c=i.name??i.id,d=i.lifecycle!=="default"?` (${i.lifecycle})`:"",l=gt(i.id);o.push(` ${l}["${c}${d}"]`),i.isMerged&&a.add(l)}for(let i of s)o.push(` ${gt(i)}{{"${i}"}}`);for(let i of r.edges){let c=gt(i.from),d=gt(i.to);i.kind==="provides"?o.push(` ${c} -->|provides| ${d}`):i.kind==="requires"?o.push(` ${c} -.->|requires| ${d}`):o.push(` ${c} -->|merge| ${d}`)}o.push(""),o.push(" classDef layerStyle fill:#E8EAF6,stroke:#3F51B5"),o.push(" classDef serviceStyle fill:#E3F2FD,stroke:#1E88E5"),o.push(" classDef mergedStyle fill:#F3E5F5,stroke:#8E24AA");for(let i of r.layers){let c=gt(i.id);a.has(c)?o.push(` class ${c} mergedStyle`):o.push(` class ${c} layerStyle`)}for(let i of s)o.push(` class ${gt(i)} serviceStyle`);return o.join(`
|
|
43
|
+
`)}import{Option as Tl}from"effect";function er(e){return e.replace(/"/g,"#quot;").replace(/</g,"#lt;").replace(/>/g,"#gt;").replace(/\(/g,"#lpar;").replace(/\)/g,"#rpar;")}function Vo(e,t){for(let n of e){(n.type==="retry"||n.type==="timeout")&&t.push({node:n,index:t.length});let r=Tl.getOrElse(v(n),()=>[]);r.length>0&&Vo(r,t)}}function vl(e){if(e.type!=="retry")return"";let t=e.scheduleInfo;if(!t)return"retry";let n=[t.baseStrategy];return t.maxRetries!==void 0&&t.maxRetries!=="unlimited"&&n.push(`${t.maxRetries}x`),t.initialDelay&&n.push(t.initialDelay),t.maxDelay&&n.push(`max ${t.maxDelay}`),t.jittered&&n.push("+jitter"),n.join(" ")}function wl(e){let t=e.source;return t===void 0?"Operation":t.displayName?t.displayName:t.name?t.name:"Operation"}function kl(e,t={}){let n=t.direction??"LR",r=[];if(Vo(e.root.children,r),r.length===0)return`flowchart ${n}
|
|
44
|
+
NoRetry((No retry/timeout patterns))`;let o=[`flowchart ${n}`];for(let{node:s,index:a}of r){let i=`N${a}`,c=er(wl(s));if(s.type==="retry"){let d=s,l=er(vl(s));o.push(` ${i}_Op[${c}] -->|fail| ${i}_R{Retry}`),o.push(` ${i}_R -->|"${l}"| ${i}_Op`),d.hasFallback?o.push(` ${i}_R -->|exhausted| ${i}_F[Fallback]`):o.push(` ${i}_R -->|exhausted| ${i}_Fail((Failure))`),o.push(` style ${i}_R fill:#9b59b6,stroke:#8e44ad,color:#fff`),d.hasFallback?o.push(` style ${i}_F fill:#2ecc71,stroke:#27ae60,color:#fff`):o.push(` style ${i}_Fail fill:#e74c3c,stroke:#c0392b,color:#fff`)}else if(s.type==="timeout"){let d=s,l=d.duration??"?",f=er(`timeout: ${l}ms`);o.push(` ${i}_Op[${c}] -->|within| ${i}_T[${f}]`),d.hasFallback?o.push(` ${i}_T -->|exceeded| ${i}_F[Fallback]`):o.push(` ${i}_T -->|exceeded| ${i}_Fail((Timeout))`),o.push(` style ${i}_T fill:#e67e22,stroke:#d35400,color:#fff`),d.hasFallback?o.push(` style ${i}_F fill:#2ecc71,stroke:#27ae60,color:#fff`):o.push(` style ${i}_Fail fill:#e74c3c,stroke:#c0392b,color:#fff`)}}return o.join(`
|
|
45
|
+
`)}function Il(e,t={}){let n=t.direction??"LR",r=e.root.requiredServices??[],o=e.root.dependencies;if(r.length===0)return`flowchart ${n}
|
|
46
|
+
NoMocks((No services to mock - pure computation))`;let s=new Set(o.filter(l=>l.isLayer).map(l=>l.name)),a=[`flowchart ${n}`],i=[],c=[];for(let l=0;l<r.length;l++){let f=`S${l}`,u=r[l];u&&(a.push(` Prog[${e.root.programName}] -->|needs mock| ${f}{{"${u.serviceId}"}}`),s.has(u.serviceId)?c.push(f):i.push(f))}a.push(""),a.push(" classDef easy fill:#C8E6C9"),a.push(" classDef hard fill:#FFE0B2"),i.length>0&&a.push(` class ${i.join(",")} easy`),c.length>0&&a.push(` class ${c.join(",")} hard`);let d=r.length===1?"mock":"mocks";return a.push(""),a.push(` Note[Requires ${r.length} service ${d}]`),a.join(`
|
|
47
|
+
`)}import{Option as Jo}from"effect";function Go(e){return`S${e}`}function cn(e){return e.replace(/"/g,"#quot;").replace(/</g,"#lt;").replace(/>/g,"#gt;").replace(/\(/g,"#lpar;").replace(/\)/g,"#rpar;")}function Yo(e){let t=[];if(e.type==="pipe"){let r=e,o=[],s=r.typeFlow?.[0]??("typeSignature"in r.initial?r.initial.typeSignature:void 0);s&&o.push({successType:s.successType,errorType:s.errorType,isEffectful:!1});for(let a=0;a<r.transformations.length;a++){let i=r.transformations[a];if(!i)continue;let c=i.type==="transform"?i.transformType:i.name??i.type,d=i.type==="transform"?i.isEffectful:!1,l=r.typeFlow?.[a+1]??(i.type==="transform"?i.outputType:void 0);l?o.push({successType:l.successType,errorType:l.errorType,transformLabel:c,isEffectful:d}):o.push({successType:"unknown",errorType:"unknown",transformLabel:c,isEffectful:d})}o.length>0&&t.push(o)}let n=Jo.getOrElse(v(e),()=>[]);for(let r of n)t.push(...Yo(r));return t}function Qo(e){let t=[];if(e.type==="generator"){let r=e,o=[];for(let s of r.yields){let a="typeSignature"in s.effect?s.effect.typeSignature:void 0;a?o.push({successType:a.successType,errorType:a.errorType,transformLabel:s.variableName??s.effect.name,isEffectful:!0}):o.push({successType:"unknown",errorType:"unknown",transformLabel:s.variableName??s.effect.name,isEffectful:!0})}o.length>0&&t.push(o)}let n=Jo.getOrElse(v(e),()=>[]);for(let r of n)t.push(...Qo(r));return t}function Al(e,t={}){let n=t.direction??"LR",r=[];for(let i of e.root.children)r.push(...Yo(i)),r.push(...Qo(i));if(r.length===0)return`flowchart ${n}
|
|
48
|
+
NoData((No data transformations))`;let o=[`flowchart ${n}`],s=[],a=0;for(let i of r){let c=a;for(let d=0;d<i.length;d++){let l=i[d];if(!l)continue;let f=Go(c+d),u=cn(l.successType);if(l.successType==="unknown"?s.push(` style ${f} fill:#EEEEEE`):s.push(` style ${f} fill:#E8F5E9`),d<i.length-1){let p=i[d+1];if(!p)continue;let g=Go(c+d+1),m=cn(p.successType),h=p.transformLabel??"",x=l.errorType,T=p.errorType;T!==x&&T!=="never"&&T!=="unknown"&&(h=h?`${h}<br/>E: ${cn(T)}`:`E: ${cn(T)}`);let S=p.isEffectful?"==>":"-->";d===0?o.push(` ${f}["${u}"] ${S}|${h}| ${g}["${m}"]`):o.push(` ${f} ${S}|${h}| ${g}["${m}"]`)}else d===0&&o.push(` ${f}["${u}"]`)}a+=i.length}return[...o,...s].join(`
|
|
49
|
+
`)}import{Option as Kl}from"effect";import{Option as Dt}from"effect";var Zo={cyclomaticWarning:10,cyclomaticError:20,pathCountWarning:50,maxDepthWarning:5};function Ee(e){let t=e.root.children,n=Fl(t),r=Rl(t),o=Dl(t),s=Pl(t),a=Ll(t),i=Ml(t);return{cyclomaticComplexity:n,cognitiveComplexity:r,pathCount:o,maxDepth:s,maxParallelBreadth:a,decisionPoints:i}}function Fl(e){let t=1;for(let n of e)t+=le(n);return t}function le(e){let t=v(e),n=Dt.getOrElse(t,()=>[]),r=0;switch(e.type){case"conditional":r+=1;for(let o of n)r+=le(o);break;case"race":r+=Math.max(0,e.children.length-1);for(let o of e.children)r+=le(o);break;case"loop":r+=1,r+=le(e.body);break;case"generator":case"pipe":case"parallel":case"error-handler":case"retry":case"timeout":case"resource":case"layer":for(let o of n)r+=le(o);break;case"decision":r+=1;for(let o of n)r+=le(o);break;case"switch":r+=Math.max(0,e.cases.length-1);for(let o of n)r+=le(o);break;case"try-catch":r+=1;for(let o of n)r+=le(o);break;case"terminal":case"opaque":for(let o of n)r+=le(o);break;case"match":e.matchedTags&&e.matchedTags.length>1&&(r+=e.matchedTags.length-1);break;case"interruption":e.handler&&(r+=1,r+=le(e.handler)),e.source&&(r+=le(e.source));break;case"cause":if(e.children)for(let o of e.children)r+=le(o);break;case"transform":e.source&&(r+=le(e.source));break;case"channel":case"sink":e.source&&(r+=le(e.source));break;case"exit":case"schedule":case"effect":case"unknown":break}return r}function Rl(e){return $l(e,0)}function $l(e,t){let n=0;for(let r of e)n+=oe(r,t);return n}function oe(e,t){let n=v(e),r=Dt.getOrElse(n,()=>[]),o=0;switch(e.type){case"conditional":o+=1+t,o+=oe(e.onTrue,t+1),e.onFalse&&(o+=oe(e.onFalse,t+1));break;case"loop":o+=1+t,o+=oe(e.body,t+1);break;case"race":o+=e.children.length;for(let s of e.children)o+=oe(s,t+1);break;case"parallel":o+=Math.max(0,e.children.length-1);for(let s of e.children)o+=oe(s,t);break;case"generator":case"pipe":case"error-handler":case"retry":case"timeout":case"resource":case"layer":for(let s of r)o+=oe(s,t);break;case"decision":o+=1+t;for(let s of e.onTrue)o+=oe(s,t+1);if(e.onFalse)for(let s of e.onFalse)o+=oe(s,t+1);break;case"switch":o+=1+t;for(let s of e.cases)for(let a of s.body)o+=oe(a,t+1);break;case"try-catch":o+=1+t;for(let s of r)o+=oe(s,t+1);break;case"terminal":if(e.value)for(let s of e.value)o+=oe(s,t);break;case"opaque":break;case"match":e.matchedTags&&e.matchedTags.length>0&&(o+=1+t);break;case"interruption":e.handler&&(o+=1+t,o+=oe(e.handler,t+1)),e.source&&(o+=oe(e.source,t));break;case"cause":if(e.children)for(let s of e.children)o+=oe(s,t);break;case"transform":e.source&&(o+=oe(e.source,t));break;case"channel":case"sink":e.source&&(o+=oe(e.source,t));break;case"exit":case"schedule":case"effect":case"unknown":break}return o}function Dl(e){let t=1,n=!1;for(let r of e){let o=ln(r);o==="unbounded"?n=!0:t*=o}return n?"unbounded":t}function ln(e){let t=v(e),n=Dt.getOrElse(t,()=>[]);switch(e.type){case"conditional":{let r=Ze([e.onTrue]),o=e.onFalse?Ze([e.onFalse]):1;return r==="unbounded"||o==="unbounded"?"unbounded":r+o}case"race":{let r=0;for(let o of e.children){let s=ln(o);if(s==="unbounded")return"unbounded";r+=s}return Math.max(1,r)}case"parallel":{let r=1;for(let o of e.children){let s=ln(o);if(s==="unbounded")return"unbounded";r*=s}return r}case"loop":return"unbounded";case"generator":case"pipe":case"error-handler":case"retry":case"timeout":case"resource":case"layer":return Ze(n);case"effect":case"unknown":case"opaque":return 1;case"decision":{let r=Ze([...e.onTrue]),o=e.onFalse?Ze([...e.onFalse]):1;return r==="unbounded"||o==="unbounded"?"unbounded":r+o}case"switch":{let r=0;for(let o of e.cases){let s=Ze([...o.body]);if(s==="unbounded")return"unbounded";r+=s}return Math.max(1,r)}case"try-catch":case"terminal":case"stream":case"concurrency-primitive":case"fiber":case"interruption":case"transform":case"match":case"cause":case"exit":case"schedule":case"channel":case"sink":return Ze(n)}}function Ze(e){let t=1;for(let n of e){let r=ln(n);if(r==="unbounded")return"unbounded";t*=r}return t}function Pl(e){let t=0;for(let n of e)t=Math.max(t,ie(n,0));return t}function ie(e,t){let n=v(e),r=Dt.getOrElse(n,()=>[]),o=t;switch(e.type){case"conditional":o=Math.max(o,ie(e.onTrue,t+1)),e.onFalse&&(o=Math.max(o,ie(e.onFalse,t+1)));break;case"loop":o=Math.max(o,ie(e.body,t+1));break;case"parallel":case"race":for(let s of e.children)o=Math.max(o,ie(s,t+1));break;case"generator":case"pipe":case"error-handler":case"retry":case"timeout":case"resource":case"layer":for(let s of r)o=Math.max(o,ie(s,t));break;case"decision":for(let s of e.onTrue)o=Math.max(o,ie(s,t+1));if(e.onFalse)for(let s of e.onFalse)o=Math.max(o,ie(s,t+1));break;case"switch":for(let s of e.cases)for(let a of s.body)o=Math.max(o,ie(a,t+1));break;case"try-catch":for(let s of r)o=Math.max(o,ie(s,t+1));break;case"terminal":if(e.value)for(let s of e.value)o=Math.max(o,ie(s,t));break;case"opaque":break;case"match":break;case"interruption":e.source&&(o=Math.max(o,ie(e.source,t+1))),e.handler&&(o=Math.max(o,ie(e.handler,t+1)));break;case"cause":if(e.children)for(let s of e.children)o=Math.max(o,ie(s,t));break;case"transform":e.source&&(o=Math.max(o,ie(e.source,t)));break;case"channel":case"sink":e.source&&(o=Math.max(o,ie(e.source,t)));break;case"exit":case"schedule":case"effect":case"unknown":break}return o}function Ll(e){let t=0;for(let n of e)t=Math.max(t,ae(n));return t}function ae(e){let t=v(e),n=Dt.getOrElse(t,()=>[]),r=0;switch(e.type){case"parallel":case"race":r=e.children.length;for(let o of e.children)r=Math.max(r,ae(o));break;case"conditional":r=Math.max(ae(e.onTrue),e.onFalse?ae(e.onFalse):0);break;case"loop":r=ae(e.body);break;case"generator":case"pipe":case"error-handler":case"retry":case"timeout":case"resource":case"layer":for(let o of n)r=Math.max(r,ae(o));break;case"decision":for(let o of e.onTrue)r=Math.max(r,ae(o));if(e.onFalse)for(let o of e.onFalse)r=Math.max(r,ae(o));break;case"switch":for(let o of e.cases)for(let s of o.body)r=Math.max(r,ae(s));break;case"try-catch":for(let o of n)r=Math.max(r,ae(o));break;case"terminal":if(e.value)for(let o of e.value)r=Math.max(r,ae(o));break;case"opaque":break;case"interruption":e.source&&(r=Math.max(r,ae(e.source))),e.handler&&(r=Math.max(r,ae(e.handler)));break;case"cause":if(e.children)for(let o of e.children)r=Math.max(r,ae(o));break;case"transform":e.source&&(r=Math.max(r,ae(e.source)));break;case"channel":case"sink":e.source&&(r=Math.max(r,ae(e.source)));break;case"match":case"exit":case"schedule":case"effect":case"unknown":break}return r}function Ml(e){let t=0;for(let n of e)t+=le(n);return t}function Ol(e,t=Zo){let n=[],r=[];e.cyclomaticComplexity>=t.cyclomaticError?(n.push({type:"cyclomatic",message:`Cyclomatic complexity (${e.cyclomaticComplexity}) exceeds error threshold (${t.cyclomaticError})`,severity:"error"}),r.push("Consider breaking this program into smaller effects")):e.cyclomaticComplexity>=t.cyclomaticWarning&&(n.push({type:"cyclomatic",message:`Cyclomatic complexity (${e.cyclomaticComplexity}) exceeds warning threshold (${t.cyclomaticWarning})`,severity:"warning"}),r.push("Consider simplifying conditional logic or extracting sub-effects")),e.pathCount==="unbounded"?(n.push({type:"paths",message:"Program has unbounded paths due to loops",severity:"warning"}),r.push("Ensure loop termination conditions are well-tested")):e.pathCount>=t.pathCountWarning&&(n.push({type:"paths",message:`Path count (${e.pathCount}) exceeds threshold (${t.pathCountWarning})`,severity:"warning"}),r.push("High path count makes exhaustive testing difficult - consider simplifying")),e.maxDepth>=t.maxDepthWarning&&(n.push({type:"depth",message:`Nesting depth (${e.maxDepth}) exceeds threshold (${t.maxDepthWarning})`,severity:"warning"}),r.push("Deep nesting reduces readability - consider flattening or extracting"));let o="low",s=n.some(i=>i.severity==="error"),a=n.some(i=>i.severity==="warning");return s?o="very-high":a&&(o=n.length>=2?"high":"medium"),{level:o,warnings:n,recommendations:r}}function Wl(e,t){let n=[];if(n.push("## Effect Program Complexity Report"),n.push(""),n.push(`**Overall Complexity:** ${t.level.toUpperCase()}`),n.push(""),n.push("### Metrics"),n.push(""),n.push("| Metric | Value |"),n.push("|--------|-------|"),n.push(`| Cyclomatic Complexity | ${e.cyclomaticComplexity} |`),n.push(`| Cognitive Complexity | ${e.cognitiveComplexity} |`),n.push(`| Unique Paths | ${e.pathCount} |`),n.push(`| Max Nesting Depth | ${e.maxDepth} |`),n.push(`| Max Parallel Breadth | ${e.maxParallelBreadth} |`),n.push(`| Decision Points | ${e.decisionPoints} |`),n.push(""),t.warnings.length>0){n.push("### Warnings"),n.push("");for(let r of t.warnings){let o=r.severity==="error"?"ERROR":"WARNING";n.push(`- **${o}:** ${r.message}`)}n.push("")}if(t.recommendations.length>0){n.push("### Recommendations"),n.push("");for(let r of t.recommendations)n.push(`- ${r}`);n.push("")}return n.join(`
|
|
50
|
+
`)}function tr(e){let t=e.root.children;if(Xe(t,"parallel")||Xe(t,"race")||Xe(t,"switch")||Xe(t,"loop")||Xe(t,"conditional")||Xe(t,"decision"))return"mermaid";let n=e.metadata.stats;if(n.decisionCount>2||n.switchCount>0||n.conditionalCount>2)return"mermaid";let r=Ee(e);return r.cyclomaticComplexity<=3&&r.decisionPoints<=1&&r.maxDepth<=2?"railway":"mermaid"}function Xe(e,t){for(let n of e){if(n.type===t)return!0;let r=Kl.getOrElse(v(n),()=>[]);if(r.length>0&&Xe(r,t))return!0}return!1}import{Option as gd}from"effect";var Bl={maxPaths:1e3,expandLoops:!1,maxLoopIterations:3};function Pt(e,t={}){return Xo(e,t).paths}function Xo(e,t={}){let r={opts:{...Bl,...t},pathCount:0,hasHitLimit:!1,controlStack:[]},o={steps:[],conditions:[],hasLoops:!1,hasUnresolvedRefs:!1};return{paths:ge(e.root.children,o,r).map((i,c)=>({id:`path-${c+1}`,description:ud(i),steps:i.steps,conditions:i.conditions,hasLoops:i.hasLoops,hasUnresolvedRefs:i.hasUnresolvedRefs})),limitHit:r.hasHitLimit}}function ge(e,t,n){if(e.length===0)return[t];let r=[t];for(let o of e){let s=[];for(let a of r)s.push(...se(o,a,n));if(r=s,o.type==="terminal"){let a=o;if(a.terminalKind==="return"||a.terminalKind==="throw")return r}}return r}function se(e,t,n){switch(e.type){case"effect":return ql(e,t);case"generator":return _l(e,t,n);case"pipe":return jl(e,t,n);case"parallel":return zl(e,t,n);case"race":return Hl(e,t,n);case"error-handler":return Ul(e,t,n);case"retry":case"timeout":return Vl(e,t,n);case"resource":return Gl(e,t,n);case"conditional":return Jl(e,t,n);case"loop":return Yl(e,t,n);case"layer":return Ql(e,t,n);case"stream":return Zl(e,t,n);case"concurrency-primitive":case"fiber":return Xl(e,t,n);case"decision":return ed(e,t,n);case"switch":return td(e,t,n);case"try-catch":return nd(e,t,n);case"terminal":return rd(e,t,n);case"cause":return sd(e,t,n);case"exit":case"schedule":return od(e,t);case"match":return id(e,t,n);case"transform":return ad(e,t,n);case"channel":return cd(e,t,n);case"sink":return ld(e,t,n);case"interruption":return dd(e,t,n);case"opaque":return[t];case"unknown":return[t];default:return[t]}}function ql(e,t){let n={nodeId:e.id,name:e.name??e.callee,repeated:!1};return[{...t,steps:[...t.steps,n]}]}function _l(e,t,n){let r=e.yields.map(o=>o.effect);return ge(r,t,n)}function jl(e,t,n){let r=[e.initial,...e.transformations];return ge(r,t,n)}function zl(e,t,n){let r=[t];for(let o of e.children){let s=[];for(let a of r){let i=se(o,a,n);for(let c of i)s.push({steps:c.steps,conditions:c.conditions,hasLoops:a.hasLoops||c.hasLoops,hasUnresolvedRefs:a.hasUnresolvedRefs||c.hasUnresolvedRefs})}r=s}return r}function Hl(e,t,n){if(e.children.length===0)return[t];if(n.hasHitLimit||n.pathCount+e.children.length>=n.opts.maxPaths){n.hasHitLimit=!0;let a=e.children[0];return a?se(a,t,n):[t]}let o=[],s=n.opts.maxPaths;for(let a of e.children){if(o.length>=s){n.hasHitLimit=!0;break}let i=se(a,t,n),c=s-o.length,d=i.slice(0,c);o.push(...d),d.length<i.length&&(n.hasHitLimit=!0)}return n.pathCount+=Math.max(0,o.length-1),o.length>0?o:[t]}function Ul(e,t,n){let r=se(e.source,t,n);if(!e.handler)return r;let o=se(e.handler,t,n);return[...r,...o]}function Vl(e,t,n){return se(e.source,t,n)}function Gl(e,t,n){let r=[e.acquire,e.release];return e.use&&r.push(e.use),ge(r,t,n)}function Jl(e,t,n){let r={expression:e.condition,mustBe:e.conditionalType!=="unless",location:e.location},o={...t,conditions:[...t.conditions,r]},s=se(e.onTrue,o,n),a={expression:e.condition,mustBe:e.conditionalType==="unless",location:e.location},i={...t,conditions:[...t.conditions,a]};if(e.onFalse){let c=se(e.onFalse,i,n);return[...s,...c]}return[...s,i]}function Yl(e,t,n){return se(e.body,t,n).map(o=>({...o,steps:o.steps.map((s,a)=>a>=t.steps.length?{...s,repeated:!0}:s),hasLoops:!0}))}function Ql(e,t,n){return ge(e.operations,t,n)}function Zl(e,t,n){let r={nodeId:e.id,name:e.pipeline.length>0?`Stream.${e.pipeline.map(s=>s.operation).join(" \u2192 ")}`:"Stream",repeated:!1},o={...t,steps:[...t.steps,r]};return se(e.source,o,n)}function Xl(e,t,n){let r={nodeId:e.id,name:e.type==="concurrency-primitive"?`${e.primitive}.${e.operation}`:e.operation,repeated:!1},o={...t,steps:[...t.steps,r]},s=e.type==="concurrency-primitive"?e.source:e.fiberSource;return s?se(s,o,n):[o]}function ed(e,t,n){let r={expression:e.condition,mustBe:!0,location:e.location},o={...t,conditions:[...t.conditions,r]},s=ge(e.onTrue,o,n);if(e.onFalse&&e.onFalse.length>0){let c={expression:e.condition,mustBe:!1,location:e.location},d={...t,conditions:[...t.conditions,c]},l=ge(e.onFalse,d,n);return[...s,...l]}let a={expression:e.condition,mustBe:!1,location:e.location},i={...t,conditions:[...t.conditions,a]};return[...s,i]}function td(e,t,n){let r=[];for(let o of e.cases){let s=o.labels.join(" / "),a={expression:`${e.expression} === ${s}`,mustBe:!0,location:e.location},i={...t,conditions:[...t.conditions,a]},c=ge(o.body,i,n);r.push(...c)}return r.length>0?r:[t]}function nd(e,t,n){let r=ge(e.tryBody,t,n),o=[];if(e.catchBody&&e.catchBody.length>0){let a={expression:"throws",mustBe:!0,location:e.location},i={...t,conditions:[...t.conditions,a]};o.push(...ge(e.catchBody,i,n))}let s=[...r,...o];if(e.finallyBody&&e.finallyBody.length>0){let a=[];for(let i of s)a.push(...ge(e.finallyBody,i,n));return a}return s}function rd(e,t,n){let r=t;switch(e.value&&e.value.length>0&&(r=ge(e.value,t,n)[0]??t),e.terminalKind){case"return":case"throw":return[{...r,steps:[...r.steps,{nodeId:e.id,name:e.terminalKind,repeated:!1}]}];case"break":case"continue":return[r]}}function od(e,t){let n={nodeId:e.id,name:e.name??e.type,repeated:!1};return[{...t,steps:[...t.steps,n]}]}function sd(e,t,n){let r={nodeId:e.id,name:e.name??`Cause.${e.causeOp}`,repeated:!1},o={...t,steps:[...t.steps,r]};return e.children&&e.children.length>0?ge([...e.children],o,n):[o]}function id(e,t,n){let r={nodeId:e.id,name:e.name??`Match.${e.matchOp}`,repeated:!1};return[{...t,steps:[...t.steps,r]}]}function ad(e,t,n){let r=t;e.source&&(r=se(e.source,t,n)[0]??t);let o={nodeId:e.id,name:e.name??e.transformType,repeated:!1};return[{...r,steps:[...r.steps,o]}]}function cd(e,t,n){let r=t;e.source&&(r=se(e.source,t,n)[0]??t);let o={nodeId:e.id,name:e.name??`Channel${e.pipeline.length>0?`.${e.pipeline.map(s=>s.operation).join(".")}`:""}`,repeated:!1};return[{...r,steps:[...r.steps,o]}]}function ld(e,t,n){let r=t;e.source&&(r=se(e.source,t,n)[0]??t);let o={nodeId:e.id,name:e.name??`Sink${e.pipeline.length>0?`.${e.pipeline.map(s=>s.operation).join(".")}`:""}`,repeated:!1};return[{...r,steps:[...r.steps,o]}]}function dd(e,t,n){let r={nodeId:e.id,name:e.name??e.interruptionType,repeated:!1},o={...t,steps:[...t.steps,r]};if(e.source){let s=se(e.source,o,n);if(e.handler){let a=se(e.handler,o,n);return[...s,...a]}return s}return[o]}function ud(e){let t=[];if(e.conditions.length>0){let r=e.conditions.map(o=>{let s=o.mustBe?"is true":"is false";return`${o.expression.length>30?o.expression.slice(0,30)+"...":o.expression} ${s}`});t.push(`When ${r.join(" AND ")}`)}let n=e.steps.map(r=>{let o=r.name??r.nodeId;return r.repeated?`${o} (repeated)`:o}).join(" \u2192 ");return n&&t.push(`Steps: ${n}`),e.hasLoops&&t.push("[contains loops]"),e.hasUnresolvedRefs&&t.push("[has unresolved refs]"),t.join(". ")||"Empty path"}function fd(e,t){if(e.length===0)return{totalPaths:0,pathLimitHit:!1,pathsWithLoops:0,pathsWithUnresolvedRefs:0,uniqueConditions:[],maxPathLength:0,minPathLength:0,avgPathLength:0};let n=new Set,r=0,o=0,s=0,a=0,i=1/0;for(let c of e){c.hasLoops&&r++,c.hasUnresolvedRefs&&o++;let d=c.steps.length;s+=d,a=Math.max(a,d),i=Math.min(i,d);for(let l of c.conditions)n.add(l.expression)}return{totalPaths:e.length,pathLimitHit:t?.limitHit??!1,pathsWithLoops:r,pathsWithUnresolvedRefs:o,uniqueConditions:Array.from(n),maxPathLength:a,minPathLength:i===1/0?0:i,avgPathLength:s/e.length}}function pd(e,t){return e.filter(n=>!(t.mustIncludeStep&&!n.steps.some(o=>o.name===t.mustIncludeStep||o.nodeId===t.mustIncludeStep)||t.mustExcludeStep&&n.steps.some(o=>o.name===t.mustExcludeStep||o.nodeId===t.mustExcludeStep)||t.conditionTrue&&!n.conditions.some(o=>o.expression===t.conditionTrue&&o.mustBe)||t.conditionFalse&&!n.conditions.some(o=>o.expression===t.conditionFalse&&!o.mustBe)||t.noLoops&&n.hasLoops||t.maxLength!==void 0&&n.steps.length>t.maxLength))}var es=3,md=5;function ts(e,t,n){return Math.max(t,Math.min(n,e))}function Lt(e,t){return[...new Set(e)].slice(0,t)}function ns(e){return e.startsWith("Consider")||e.startsWith("If you want clearer diagrams")||e.startsWith("For larger programs")}function un(e){return ns(e)?e:`Consider ${e.charAt(0).toLowerCase()}${e.slice(1)}`}function hd(e){let t=[],n=r=>{for(let o of r){t.push(o);let s=gd.getOrElse(v(o),()=>[]);s.length>0&&n(s)}};return n(e),t}function yd(e){let t=e.toLowerCase();return t.includes("log")||t.includes("logger")||t.includes("taperror")}function Sd(e){let t=e.callee.trim();return!!(t===""||t==="_"||t==="Effect"||/call expression/i.test(t)||/^program-\d+$/i.test(e.name??""))}function xd(e){return e.type==="effect"&&(e.semanticRole==="service-call"||e.serviceCall!==void 0||e.serviceMethod!==void 0)}function Ed(e){let t=e.callee.trim();return!(t===""||t==="_"||t==="Effect"||/unknown/i.test(t)||/call expression/i.test(t))}function bd(e,t={}){let n=hd(e.root.children),r=n.length,o=n.filter(S=>S.type==="effect"),s=o.filter(S=>S.semanticRole==="side-effect"),a=o.filter(S=>yd(S.displayName??S.name??S.callee)),i=n.filter(S=>S.type==="unknown").length,c=n.filter(S=>S.type==="unknown"||S.type==="pipe"?!0:S.type==="effect"?Sd(S):!1).length,d=n.filter(S=>xd(S)),l=d.filter(S=>Ed(S)),f=n.filter(S=>S.type==="pipe"),u=f.length,p=f.length>0?Math.max(...f.map(S=>1+S.transformations.length)):0,m=[...Pt(e)].sort((S,N)=>N.steps.length-S.steps.length)[0],h=m?rn(m,{collapseRepeatedLogs:!0,collapsePureTransforms:!0,styleGuide:t.styleGuideSummary??!1}):{steps:[],collapsedGroups:0},x=r>0?r:1,T=d.length>0?d.length:1;return{stepCountDetailed:r,stepCountSummary:h.steps.length,collapsedGroupsSummary:h.collapsedGroups,logRatio:a.length/x,sideEffectRatio:s.length/x,anonymousNodeCount:c,anonymousRatio:c/x,unknownNodeCount:i,serviceCallCount:d.length,namedServiceCallRatio:l.length/T,pipeChainCount:u,maxPipeChainLength:p}}function Cd(e){let t=Math.min(35,e.unknownNodeCount*8),n=Math.min(25,Math.round(e.anonymousRatio*40)),r=e.stepCountDetailed>24?Math.min(22,Math.round((e.stepCountDetailed-24)*.6)):0,o=Math.min(12,Math.round(e.logRatio*30)),s=e.sideEffectRatio>.75?Math.min(8,Math.round((e.sideEffectRatio-.75)*40)):0,a=ts(Math.round(100-t-n-r-o-s),0,100),i=a>=75?"good":a>=50?"ok":"noisy";return{score:a,band:i}}function rs(e){let t=[],n=Math.round(e.logRatio*Math.max(e.stepCountDetailed,1));return e.stepCountDetailed>=60?t.push(`High step count (${String(e.stepCountDetailed)}). Consider summary mode.`):e.stepCountDetailed>=35&&t.push(`Moderate step count (${String(e.stepCountDetailed)}). Summary mode may improve readability.`),(n>=12||e.logRatio>=.35)&&t.push(`Many log steps (${String(n)}). Consider collapsing logs or summary mode.`),e.anonymousNodeCount>=5&&t.push(`${String(e.anonymousNodeCount)} anonymous nodes from pipe chains or unnamed calls.`),e.unknownNodeCount>0&&t.push(`${String(e.unknownNodeCount)} unresolved nodes may reduce diagram clarity.`),e.serviceCallCount>=3&&e.namedServiceCallRatio<.7&&t.push(`Service call naming clarity is ${(e.namedServiceCallRatio*100).toFixed(0)}% (${String(e.serviceCallCount)} calls).`),t}function os(e){let t=[],n=Math.round(e.logRatio*Math.max(e.stepCountDetailed,1));return e.stepCountDetailed>=35&&t.push("For larger programs, consider summary mode."),(n>=12||e.logRatio>=.35)&&t.push("For larger programs, consider grouping logs or using summary mode."),e.anonymousNodeCount>=5&&t.push("Consider naming intermediate values or extracting named helpers."),(e.pipeChainCount>=4||e.maxPipeChainLength>=6)&&t.push("If you want clearer diagrams, consider splitting long pipe chains into named steps."),e.serviceCallCount>=3&&e.namedServiceCallRatio<.7&&t.push("Consider naming service-call intermediates to make boundaries explicit."),Lt(t.map(un),es)}function ss(e,t={}){let n=bd(e,t),{score:r,band:o}=Cd(n),s=rs(n),a=os(n),i=t.hints?.reasons??[],c=(t.hints?.tips??[]).map(un);return{score:r,band:o,metrics:n,reasons:Lt([...s,...i],8),tips:Lt([...a,...c],es)}}function Nd(e){if(e.length===0)return{stepCountDetailed:0,stepCountSummary:0,collapsedGroupsSummary:0,logRatio:0,sideEffectRatio:0,anonymousNodeCount:0,anonymousRatio:0,unknownNodeCount:0,serviceCallCount:0,namedServiceCallRatio:0,pipeChainCount:0,maxPipeChainLength:0};let t=e.map(s=>Math.max(1,s.metrics.stepCountDetailed)),n=t.reduce((s,a)=>s+a,0),r=s=>e.reduce((a,i,c)=>a+s(i)*(t[c]??1),0)/n,o=s=>e.reduce((a,i)=>a+s(i),0);return{stepCountDetailed:Math.round(r(s=>s.metrics.stepCountDetailed)),stepCountSummary:Math.round(r(s=>s.metrics.stepCountSummary)),collapsedGroupsSummary:Math.round(r(s=>s.metrics.collapsedGroupsSummary)),logRatio:r(s=>s.metrics.logRatio),sideEffectRatio:r(s=>s.metrics.sideEffectRatio),anonymousNodeCount:Math.round(o(s=>s.metrics.anonymousNodeCount)),anonymousRatio:r(s=>s.metrics.anonymousRatio),unknownNodeCount:Math.round(o(s=>s.metrics.unknownNodeCount)),serviceCallCount:Math.round(o(s=>s.metrics.serviceCallCount)),namedServiceCallRatio:r(s=>s.metrics.namedServiceCallRatio),pipeChainCount:Math.round(o(s=>s.metrics.pipeChainCount)),maxPipeChainLength:Math.max(...e.map(s=>s.metrics.maxPipeChainLength))}}function Td(e,t,n={}){let r=t.map(d=>ss(d,n)),o=Nd(r),s=r.length>0?Math.round(r.reduce((d,l)=>d+l.score*Math.max(1,l.metrics.stepCountDetailed),0)/r.reduce((d,l)=>d+Math.max(1,l.metrics.stepCountDetailed),0)):100,a=s>=75?"good":s>=50?"ok":"noisy",i=Lt([...rs(o),...n.hints?.reasons??[]],10),c=Lt([...os(o),...(n.hints?.tips??[]).map(un)].filter(ns),md);return{filePath:e,quality:{score:s,band:a,metrics:o,reasons:i,tips:c}}}function vd(e,t,n){return{filePath:e,metricValue:t,tip:un(n)}}function dn(e,t,n,r){return[...e].sort((o,s)=>{let a=t(s)-t(o);return a!==0?a:o.filePath.localeCompare(s.filePath)}).slice(0,r).map(o=>vd(o.filePath,t(o),n(o)))}function wd(e,t=10){let n=ts(t,1,50);return{largestPrograms:dn(e,r=>r.quality.metrics.stepCountDetailed,()=>"For larger programs, consider summary mode.",n),mostAnonymousNodes:dn(e,r=>r.quality.metrics.anonymousNodeCount,()=>"Consider naming intermediate values or extracting named helpers.",n),mostUnknownNodes:dn(e,r=>r.quality.metrics.unknownNodeCount,()=>"If you want clearer diagrams, consider extracting helpers to reduce unresolved nodes.",n),highestLogRatio:dn(e,r=>r.quality.metrics.logRatio,()=>"For larger programs, consider grouping logs or using summary mode.",n)}}import{readFile as kd}from"fs/promises";import{resolve as Id}from"path";function Ad(e){return e?/effect/i.test(e):!1}function Fd(e){let t=`${e.ruleId??""} ${e.message??""}`.toLowerCase();if(t.includes("yield")||t.includes("untagged"))return"Consider binding yielded values with meaningful names.";if(t.includes("error")||t.includes("catch")||t.includes("handle"))return"If you want clearer diagrams, consider making error boundaries explicit.";if(t.includes("service")||t.includes("layer")||t.includes("provide"))return"Consider acquiring services near the top of the workflow.";if(t.includes("pipe")||t.includes("nested")||t.includes("lambda"))return"If you want clearer diagrams, consider extracting nested pipe lambdas into named helpers."}function Rd(e){let t=e.ruleId??"eslint",n=(e.message??"").trim();if(n)return`ESLint (${t}): ${n}`}function $d(e){if(Array.isArray(e))return e;if(e&&typeof e=="object"&&"results"in e){let t=e.results;if(Array.isArray(t))return t}return[]}async function Dd(e){let t=await kd(e,"utf-8"),n=JSON.parse(t),r=$d(n),o=new Map;for(let a of r){let i=a.filePath?Id(a.filePath):void 0;if(!i)continue;let c=a.messages??[];for(let d of c){if(!Ad(d.ruleId))continue;let l=o.get(i)??{reasons:[],tips:[]},f=Rd(d);f&&l.reasons.push(f);let u=Fd(d);u&&l.tips.push(u),o.set(i,l)}}let s=new Map;for(let[a,i]of o)s.set(a,{reasons:[...new Set(i.reasons)].slice(0,8),tips:[...new Set(i.tips)].slice(0,5)});return s}var Pd=e=>" ".repeat(e);function is(e){let t=(n,r=_)=>j(n,r);switch(e.type){case"effect":return e.serviceCall?t(`${e.serviceCall.serviceType}.${e.serviceCall.methodName}`):t(e.displayName??e.callee);case"generator":return"Effect.gen block";case"pipe":return t(`pipe(${is(e.initial)})`);case"parallel":return t(`${e.callee}(${e.children.length} effects)`);case"race":return t(`${e.callee}(${e.children.length} effects)`);case"error-handler":return e.handlerType;case"retry":return"retry";case"timeout":return e.duration?`timeout(${e.duration})`:"timeout";case"resource":return"acquireRelease";case"conditional":return`if ${e.conditionLabel??e.condition}`;case"loop":return t(`${e.loopType}${e.iterSource?`(${e.iterSource})`:""}`);case"layer":return e.provides?`Layer(${e.provides.join(", ")})`:"Layer";case"stream":return"Stream";case"fiber":return`Fiber.${e.operation}`;case"concurrency-primitive":return`${e.primitive}.${e.operation}`;case"decision":return`if ${e.condition}`;case"switch":return`switch(${e.expression})`;case"try-catch":return"try/catch";case"terminal":return e.terminalKind;case"match":return e.matchedTags?`Match(${e.matchedTags.join(", ")})`:"Match";case"transform":return e.transformType;case"channel":return"Channel";case"sink":return"Sink";case"cause":return`Cause.${e.causeOp}`;case"exit":return`Exit.${e.exitOp}`;case"schedule":return`Schedule.${e.scheduleOp}`;case"interruption":return e.interruptionType;case"opaque":return`(opaque: ${e.reason})`;case"unknown":return`(unknown: ${e.reason})`}}function q(e,t,n={hasParallelism:!1,serviceCallsSeen:new Set}){let r=Pd(t),o=[];switch(e.type){case"effect":{if(e.serviceCall)if(n.serviceCallsSeen.add(e.serviceCall.serviceType),e.callee.includes("Tag")||e.callee.includes("Context")||e.callee===e.serviceCall.serviceType)o.push(`${r}Acquires ${e.serviceCall.serviceType} service`);else{let s=e.description?` \u2014 ${e.description}`:"";o.push(`${r}Calls ${e.serviceCall.serviceType}.${e.serviceCall.methodName}${s}`)}else{let s=j(e.displayName??e.callee,_),a=e.description?` \u2014 ${e.description}`:"";s.includes(" <- ")?o.push(`${r}Yields ${s}`):o.push(`${r}Calls ${s}${a}`)}break}case"generator":{for(let s of e.yields){let a=q(s.effect,t,n),i=a[0];if(s.variableName&&i!==void 0){let c=i.trimStart();c.includes(`${s.variableName} <-`)||c.includes(`${s.variableName} =`)||(a[0]=`${r}${s.variableName} = ${c.replace(/^Calls /,"")}`)}o.push(...a)}if(e.returnNode){let s=q(e.returnNode,t,n),a=s[0];if(a!==void 0){let i=a.trimStart();s[0]=`${r}Returns ${i.replace(/^Calls /,"")}`,o.push(...s)}}break}case"pipe":{o.push(`${r}Pipes ${is(e.initial)} through:`);let s=q(e.initial,t+1,n);o.push(...s);for(let a of e.transformations){let i=q(a,t+1,n);o.push(...i)}break}case"parallel":{n.hasParallelism=!0;let s=e.concurrency!==void 0&&e.concurrency!=="sequential"?` (concurrency: ${e.concurrency})`:"";o.push(`${r}Runs ${e.children.length} effects in ${e.mode}${s}:`);for(let a of e.children)o.push(...q(a,t+1,n));break}case"race":{n.hasParallelism=!0,o.push(`${r}Races ${e.children.length} effects:`);for(let s of e.children)o.push(...q(s,t+1,n));break}case"error-handler":{let s=e.errorTag?` "${e.errorTag}"`:e.errorTags&&e.errorTags.length>0?` [${e.errorTags.join(", ")}]`:"";switch(e.handlerType){case"catchAll":o.push(`${r}Catches all errors on:`);break;case"catchTag":o.push(`${r}Catches tag${s} on:`);break;case"catchTags":o.push(`${r}Catches tags${s} on:`);break;case"orElse":o.push(`${r}Falls back (orElse) on error:`);break;case"orDie":o.push(`${r}Converts errors to defects (orDie):`);break;case"mapError":o.push(`${r}Maps error on:`);break;case"ignore":o.push(`${r}Ignores errors on:`);break;default:o.push(`${r}Handles errors (${e.handlerType})${s}:`)}o.push(...q(e.source,t+1,n)),e.handler&&(o.push(`${r} Handler:`),o.push(...q(e.handler,t+2,n)));break}case"retry":{if(e.scheduleInfo){let s=e.scheduleInfo.maxRetries!==void 0?`max ${e.scheduleInfo.maxRetries}`:"",a=e.scheduleInfo.baseStrategy,i=[s,a].filter(Boolean).join(", ");o.push(`${r}Retries (${i}):`)}else e.schedule?o.push(`${r}Retries with ${e.schedule}:`):o.push(`${r}Retries:`);o.push(...q(e.source,t+1,n)),e.hasFallback&&o.push(`${r} (with fallback on exhaustion)`);break}case"timeout":{let s=e.duration?` after ${e.duration}`:"";o.push(`${r}Times out${s}:`),o.push(...q(e.source,t+1,n)),e.hasFallback&&o.push(`${r} (with fallback on timeout)`);break}case"resource":{o.push(`${r}Acquires resource:`),o.push(...q(e.acquire,t+1,n)),e.use&&(o.push(`${r} Uses:`),o.push(...q(e.use,t+2,n))),o.push(`${r} Then releases:`),o.push(...q(e.release,t+2,n));break}case"conditional":{let s=e.conditionLabel??e.condition;o.push(`${r}If ${s}:`),o.push(...q(e.onTrue,t+1,n)),e.onFalse&&(o.push(`${r}Else:`),o.push(...q(e.onFalse,t+1,n)));break}case"decision":{o.push(`${r}If ${e.condition}:`);for(let s of e.onTrue)o.push(...q(s,t+1,n));if(e.onFalse&&e.onFalse.length>0){o.push(`${r}Else:`);for(let s of e.onFalse)o.push(...q(s,t+1,n))}break}case"switch":{o.push(`${r}Switch on ${e.expression}:`);for(let s of e.cases){let a=s.isDefault?"default":s.labels.join(", ");o.push(`${r} Case ${a}:`);for(let i of s.body)o.push(...q(i,t+2,n))}break}case"try-catch":{o.push(`${r}Try:`);for(let s of e.tryBody)o.push(...q(s,t+1,n));if(e.catchBody&&e.catchBody.length>0){o.push(`${r}Catch:`);for(let s of e.catchBody)o.push(...q(s,t+1,n))}if(e.finallyBody&&e.finallyBody.length>0){o.push(`${r}Finally:`);for(let s of e.finallyBody)o.push(...q(s,t+1,n))}break}case"terminal":{switch(e.terminalKind){case"return":{if(e.value&&e.value.length>0){o.push(`${r}Returns:`);for(let s of e.value)o.push(...q(s,t+1,n))}else o.push(`${r}Returns`);break}case"throw":o.push(`${r}Throws`);break;case"break":o.push(`${r}Breaks`);break;case"continue":o.push(`${r}Continues`);break}break}case"loop":{let s=e.iterSource?` over ${j(e.iterSource,_)}`:"";o.push(`${r}Iterates (${e.loopType})${s}:`),o.push(...q(e.body,t+1,n));break}case"layer":{let s=e.provides&&e.provides.length>0?` providing ${e.provides.join(", ")}`:"",a=e.requires&&e.requires.length>0?` (requires ${e.requires.join(", ")})`:"";o.push(`${r}Provides layer${s}${a}:`);for(let i of e.operations)o.push(...q(i,t+1,n));break}case"stream":{let s=e.pipeline.map(i=>i.operation).join(" -> "),a=e.sink?` -> ${e.sink}`:"";o.push(`${r}Stream: ${s}${a}`),o.push(...q(e.source,t+1,n));break}case"fiber":{let s=e.isDaemon?" (daemon)":e.isScoped?" (scoped)":"";o.push(`${r}Fiber ${e.operation}${s}:`),e.fiberSource&&o.push(...q(e.fiberSource,t+1,n));break}case"concurrency-primitive":{let s=e.capacity!==void 0?` (capacity: ${e.capacity})`:"";o.push(`${r}${e.primitive}.${e.operation}${s}`),e.source&&o.push(...q(e.source,t+1,n));break}case"match":{e.matchedTags&&e.matchedTags.length>0?o.push(`${r}Matches tags: ${e.matchedTags.join(", ")}`):o.push(`${r}Match (${e.matchOp})`);break}case"transform":{o.push(`${r}Transforms via ${e.transformType}`),e.source&&o.push(...q(e.source,t+1,n));break}case"cause":{if(o.push(`${r}Cause.${e.causeOp}`),e.children)for(let s of e.children)o.push(...q(s,t+1,n));break}case"exit":{o.push(`${r}Exit.${e.exitOp}`);break}case"schedule":{o.push(`${r}Schedule.${e.scheduleOp}`);break}case"channel":{let s=e.pipeline.map(a=>a.operation).join(" -> ");o.push(`${r}Channel${s?`: ${s}`:""}`),e.source&&o.push(...q(e.source,t+1,n));break}case"sink":{let s=e.pipeline.map(a=>a.operation).join(" -> ");o.push(`${r}Sink${s?`: ${s}`:""}`),e.source&&o.push(...q(e.source,t+1,n));break}case"interruption":{o.push(`${r}${e.interruptionType}`),e.source&&o.push(...q(e.source,t+1,n)),e.handler&&(o.push(`${r} On interrupt:`),o.push(...q(e.handler,t+2,n)));break}case"opaque":{o.push(`${r}(opaque: ${e.reason})`);break}case"unknown":{o.push(`${r}(unknown: ${e.reason})`);break}}return o}function Ld(e,t){let n={hasParallelism:!1,serviceCallsSeen:new Set},r=[];for(let d of e.children)r.push(...q(d,1,n));let o=Md(r),s=`${e.programName} (${e.source}):`,a=[],i=new Set;for(let d of e.dependencies)i.add(d.name);Array.from(n.serviceCallsSeen).forEach(d=>{i.add(d)}),i.size>0&&a.push(` Services required: ${Array.from(i).join(", ")}`),e.errorTypes.length>0&&a.push(` Error paths: ${e.errorTypes.join(", ")}`),n.hasParallelism?a.push(" Concurrency: uses parallelism / racing"):a.push(" Concurrency: sequential (no parallelism)");let c=[s,o.join(`
|
|
51
51
|
`)];return a.length>0&&(c.push(""),c.push(a.join(`
|
|
52
52
|
`))),c.join(`
|
|
53
|
-
`)}function
|
|
53
|
+
`)}function Md(e){let t=0;return e.map(n=>/^ {2}\S/.test(n)?(t++,` ${t}. ${n.trimStart()}`):n)}function as(e){return Ld(e.root,e)}function Od(e){return e.map(t=>as(t)).join(`
|
|
54
54
|
|
|
55
55
|
---
|
|
56
56
|
|
|
57
|
-
`)}var
|
|
58
|
-
`)}function
|
|
57
|
+
`)}var Wd={generator:"gen",direct:"direct",pipe:"pipe",run:"run","workflow-execute":"wf-exec",class:"class",classProperty:"classProp",classMethod:"classMeth"};function cs(e){return Wd[e]}function Kd(e){let t=e.root.programName,n=cs(e.root.source),r=e.metadata.stats.totalEffects,o=e.root.dependencies.length,s=e.root.errorTypes.length,a=e.metadata.stats.errorHandlerCount,i=Ee(e).cyclomaticComplexity;return[t,n,`${r} steps`,`${o} services`,`${s} errors`,`${a} ${a===1?"handler":"handlers"}`,`complexity: ${i}`].join(" | ")}function Bd(e){return{program:e.root.programName,kind:cs(e.root.source),steps:e.metadata.stats.totalEffects,services:e.root.dependencies.length,errors:e.root.errorTypes.length,handlers:e.metadata.stats.errorHandlerCount,complexity:Ee(e).cyclomaticComplexity}}function qd(e){if(e.length===0)return"(no programs)";let t=e.map(Bd),n={program:"Program",kind:"Kind",steps:"Steps",services:"Services",errors:"Errors",handlers:"Handlers",complexity:"Complexity"},r={program:Math.max(n.program.length,...t.map(d=>d.program.length)),kind:Math.max(n.kind.length,...t.map(d=>d.kind.length)),steps:Math.max(n.steps.length,...t.map(d=>String(d.steps).length)),services:Math.max(n.services.length,...t.map(d=>String(d.services).length)),errors:Math.max(n.errors.length,...t.map(d=>String(d.errors).length)),handlers:Math.max(n.handlers.length,...t.map(d=>String(d.handlers).length)),complexity:Math.max(n.complexity.length,...t.map(d=>String(d.complexity).length))},o=(d,l)=>d+" ".repeat(Math.max(0,l-d.length)),s=(d,l)=>" ".repeat(Math.max(0,l-d.length))+d,a=[o(n.program,r.program),o(n.kind,r.kind),o(n.steps,r.steps),o(n.services,r.services),o(n.errors,r.errors),o(n.handlers,r.handlers),o(n.complexity,r.complexity)].join(" | "),i=["-".repeat(r.program),"-".repeat(r.kind),"-".repeat(r.steps),"-".repeat(r.services),"-".repeat(r.errors),"-".repeat(r.handlers),"-".repeat(r.complexity)].join("-+-"),c=t.map(d=>[o(d.program,r.program),o(d.kind,r.kind),s(String(d.steps),r.steps),s(String(d.services),r.services),s(String(d.errors),r.errors),s(String(d.handlers),r.handlers),s(String(d.complexity),r.complexity)].join(" | "));return[a,i,...c].join(`
|
|
58
|
+
`)}function _d(e){let t=new Set,n=new Map;for(let s of e){let a=s.root.programName,i=n.get(a)??new Set;for(let c of s.root.dependencies)t.add(c.name),i.add(c.name);n.set(a,i)}let r=[...t].sort((s,a)=>s.localeCompare(a)),o=[...n.keys()].sort((s,a)=>s.localeCompare(a));return ls(o,r,(s,a)=>{let i=n.get(s);return i?i.has(a):!1},{programs:e.length,services:r.length})}function jd(e){let t=[],n=new Set,r=new Set,o=new Map;for(let[a,i]of e.services){t.push(a);let c=new Set;for(let d of i.consumers)c.add(d.programName),n.add(d.programName),r.add(`${d.filePath}::${d.programName}`);o.set(a,c)}t.sort((a,i)=>a.localeCompare(i));let s=[...n].sort((a,i)=>a.localeCompare(i));return ls(s,t,(a,i)=>{let c=o.get(i);return c?c.has(a):!1},{programs:r.size,services:t.length})}function ls(e,t,n,r){let o=r?.programs??e.length,s=r?.services??t.length;if(e.length===0||t.length===0)return`_No dependencies found._
|
|
59
59
|
|
|
60
|
-
${o} programs \xD7 ${s} services`;let a=[];a.push(`| Program | ${t.join(" | ")} |`);let i=t.map(c=>`:${"-".repeat(Math.max(c.length-2,1))}:`);a.push(`|${"-".repeat(9)}|${i.join("|")}|`);for(let c of e){let d=t.map(l=>
|
|
61
|
-
`)}import{Effect as
|
|
60
|
+
${o} programs \xD7 ${s} services`;let a=[];a.push(`| Program | ${t.join(" | ")} |`);let i=t.map(c=>`:${"-".repeat(Math.max(c.length-2,1))}:`);a.push(`|${"-".repeat(9)}|${i.join("|")}|`);for(let c of e){let d=t.map(l=>n(c,l)?"\u2713":"");a.push(`| ${c} | ${d.join(" | ")} |`)}return a.push(""),a.push(`${o} programs \xD7 ${s} services`),a.join(`
|
|
61
|
+
`)}import{Effect as ds}from"effect";var us={pretty:!0,includeMetadata:!0,compact:!1},zd=(e,t)=>ds.gen(function*(){let n={...us,...t},r=n.pretty?2:void 0,o=n.includeMetadata?{root:e.root,metadata:e.metadata,references:e.references instanceof Map?Object.fromEntries(e.references):e.references}:{root:e.root};return JSON.stringify(o,fs,r)}),Hd=(e,t)=>ds.gen(function*(){let n={...us,...t},r=n.pretty?2:void 0,o=e.map(s=>n.includeMetadata?{root:s.root,metadata:s.metadata,references:s.references instanceof Map?Object.fromEntries(s.references):s.references}:{root:s.root});return JSON.stringify(o,fs,r)}),fs=(e,t)=>t instanceof Map?Object.fromEntries(t):t instanceof Set?Array.from(t):typeof t=="bigint"?t.toString():(t&&typeof t=="object"&&"_tag"in t,t);function Ud(e){return e==="light"?"daylight":e==="dark"?"midnight":e}function Vd(e,t={}){let n=t.title??`${e.root.programName} - Effect Analysis`,r=Ud(t.theme),o=fe(e).replace(/<\/script>/gi,"<\\/script>"),s=Pt(e),a=Ee(e),i=fe(e,{dataFlowOverlay:!0}).replace(/<\/script>/gi,"<\\/script>"),c=fe(e,{errorFlowOverlay:!0}).replace(/<\/script>/gi,"<\\/script>"),d=JSON.stringify(e,null,2).replace(/</g,"\\u003c").replace(/>/g,"\\u003e"),l=JSON.stringify(s,null,2).replace(/</g,"\\u003c").replace(/>/g,"\\u003e"),f=JSON.stringify(a,null,2).replace(/</g,"\\u003c").replace(/>/g,"\\u003e"),u=r?`"${r}"`:"null";return`<!DOCTYPE html>
|
|
62
62
|
<html lang="en" data-theme="midnight">
|
|
63
63
|
<head>
|
|
64
64
|
<meta charset="UTF-8">
|
|
65
65
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
66
|
-
<title>${
|
|
66
|
+
<title>${nr(n)}</title>
|
|
67
67
|
<script src="https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js"></script>
|
|
68
68
|
<style>
|
|
69
69
|
/* Theme definitions */
|
|
@@ -153,7 +153,7 @@ ${o} programs \xD7 ${s} services`;let a=[];a.push(`| Program | ${t.join(" | ")}
|
|
|
153
153
|
</head>
|
|
154
154
|
<body>
|
|
155
155
|
<div class="header">
|
|
156
|
-
<h1>${
|
|
156
|
+
<h1>${nr(n)}</h1>
|
|
157
157
|
<span class="stats" id="complexity-stats"></span>
|
|
158
158
|
<div class="theme-picker">
|
|
159
159
|
<button onclick="toggleThemeMenu()" id="theme-btn">Theme</button>
|
|
@@ -182,7 +182,7 @@ ${o} programs \xD7 ${s} services`;let a=[];a.push(`| Program | ${t.join(" | ")}
|
|
|
182
182
|
</div>
|
|
183
183
|
<div class="layout">
|
|
184
184
|
<div class="diagram-pane">
|
|
185
|
-
<pre class="mermaid" id="mermaid-diagram">${
|
|
185
|
+
<pre class="mermaid" id="mermaid-diagram">${nr(o)}</pre>
|
|
186
186
|
</div>
|
|
187
187
|
<div class="sidebar">
|
|
188
188
|
<div class="sidebar-tabs">
|
|
@@ -474,6 +474,11 @@ ${o} programs \xD7 ${s} services`;let a=[];a.push(`| Program | ${t.join(" | ")}
|
|
|
474
474
|
}
|
|
475
475
|
|
|
476
476
|
// Click-to-navigate: show node details when clicking on diagram nodes
|
|
477
|
+
function truncLabel(s, max) {
|
|
478
|
+
if (!s || s.length <= max) return s;
|
|
479
|
+
return s.slice(0, max) + '\u2026';
|
|
480
|
+
}
|
|
481
|
+
var LABEL_MAX = 60;
|
|
477
482
|
function showNodeDetails(nodeId) {
|
|
478
483
|
var node = nodeIndex[nodeId];
|
|
479
484
|
if (!node) return;
|
|
@@ -483,8 +488,8 @@ ${o} programs \xD7 ${s} services`;let a=[];a.push(`| Program | ${t.join(" | ")}
|
|
|
483
488
|
html += '<table>';
|
|
484
489
|
html += '<tr><td>ID</td><td><code>' + node.id + '</code></td></tr>';
|
|
485
490
|
html += '<tr><td>Type</td><td><b>' + node.type + '</b></td></tr>';
|
|
486
|
-
if (node.callee) html += '<tr><td>Callee</td><td>' + node.callee + '</td></tr>';
|
|
487
|
-
if (node.displayName) html += '<tr><td>Display</td><td>' + node.displayName + '</td></tr>';
|
|
491
|
+
if (node.callee) html += '<tr><td>Callee</td><td>' + truncLabel(node.callee, LABEL_MAX) + '</td></tr>';
|
|
492
|
+
if (node.displayName) html += '<tr><td>Display</td><td>' + truncLabel(node.displayName, LABEL_MAX) + '</td></tr>';
|
|
488
493
|
if (node.semanticRole) html += '<tr><td>Role</td><td>' + node.semanticRole + '</td></tr>';
|
|
489
494
|
html += '<tr><td>Location</td><td><code>' + loc + '</code></td></tr>';
|
|
490
495
|
if (node.typeSignature) {
|
|
@@ -523,26 +528,26 @@ ${o} programs \xD7 ${s} services`;let a=[];a.push(`| Program | ${t.join(" | ")}
|
|
|
523
528
|
});
|
|
524
529
|
</script>
|
|
525
530
|
</body>
|
|
526
|
-
</html>`}function
|
|
527
|
-
`)}function
|
|
528
|
-
`)}import{Option as
|
|
529
|
-
`:` ${r
|
|
530
|
-
`)}function
|
|
531
|
-
`)}function
|
|
532
|
-
`)}import{Option as
|
|
533
|
-
`)}import{Option as
|
|
534
|
-
`)}function
|
|
535
|
-
`)}function
|
|
536
|
-
`)}function
|
|
537
|
-
`)}import{Project as
|
|
538
|
-
`)}import{Project as ju,SyntaxKind as _u}from"ts-morph";function Zn(e,t,r){let{line:n,column:o}=r.getLineAndColumnAtPos(t.getStart());return{filePath:e,line:n+1,column:o}}function zu(e,t){let r=new ju({useInMemoryFileSystem:!0}),n=t?r.createSourceFile(e,t):r.addSourceFileAtPath(e),o=[],s=[];for(let a of n.getDescendantsOfKind(_u.CallExpression)){let c=a.getExpression().getText();if(c.includes("Match")&&(c.includes("Match.type")||c.includes("Match.tag")||c.includes("Match.value"))){let l=a.getParent()?.getText()??"",f=[],u=l.includes(".exhaustive("),p=l.includes(".orElse(");if(l.includes("Match.tag(")){let m=/Match\.tag\s*\(\s*["'](\w+)["']/.exec(l);if(m){let S=m[1],h=S!==void 0?{kind:"tag",tag:S,location:Zn(e,a,n)}:{kind:"tag",location:Zn(e,a,n)};f.push(h)}}u&&f.push({kind:"exhaustive"}),p&&f.push({kind:"orElse"});let g={location:Zn(e,a,n),arms:f,hasExhaustive:u,hasOrElse:p};o.push(g),!u&&!p&&s.push(g)}}return{matchSites:o,nonExhaustive:s}}import{Project as Hu,SyntaxKind as Xn}from"ts-morph";function Qe(e,t,r){let{line:n,column:o}=r.getLineAndColumnAtPos(t.getStart());return{filePath:e,line:n+1,column:o}}function Uu(e){let n=e.getText().replace(/\$\{HttpApiSchema\.param\s*\(\s*["'](\w+)["'][^}]*\)\}/g,":$1").replace(/\$\{[^}]*\}/g,":param").replace(/^`|`$/g,"").trim();return n.startsWith("/")?n:`/${n}`}function Vu(e){let t,r,n=e;for(let s=0;s<20;s++){let a=n.getParent();if(!a)break;if(a.getKind()===Xn.CallExpression){let i=a,c=i.getExpression().getText();if(c.endsWith(".add")&&i.getArguments().length>0){let l=c.slice(0,-4),f=/HttpApi\.make\s*\(\s*["']([^"']+)["']/.exec(l);f&&(t=f[1]);let u=/HttpApiGroup\.make\s*\(\s*["']([^"']+)["']/.exec(l);u&&(r=u[1])}}n=a}let o={};return t!==void 0&&(o.apiId=t),r!==void 0&&(o.groupName=r),o}function Gu(e,t){let r=new Hu({useInMemoryFileSystem:!0}),n=t?r.createSourceFile(e,t):r.addSourceFileAtPath(e),o=new Map,s={client:!1,server:!1,routes:[],api:!1,apiBuilder:!1,endpoint:!1,security:!1,middleware:!1},a={reads:[],writes:[]},i=!1,c=!1,d=!1,l=[],f=!1,u=!1,p=[],g=!1,m=[],S=[],h=[],N=[],x=[],C=[];for(let E of n.getDescendantsOfKind(Xn.CallExpression)){let y=E.getExpression().getText();if((y.includes("HttpClient")||y.includes("HttpServer")||y.includes("HttpRouter")||y.includes("HttpApi")||y.includes("HttpApiBuilder")||y.includes("HttpApiEndpoint")||y.includes("HttpApiGroup")||y.includes("HttpApiSecurity")||y.includes("HttpApiClient"))&&((y.includes("HttpClient")||y.includes("HttpApiClient"))&&(s.client=!0),s.server=s.server||y.includes("HttpServer")||y.includes("HttpRouter"),s.api=s.api||y.includes("HttpApi")&&!y.includes("HttpApiBuilder")&&!y.includes("HttpApiEndpoint")&&!y.includes("HttpApiGroup")&&!y.includes("HttpApiSecurity")&&!y.includes("HttpApiClient"),s.apiBuilder=s.apiBuilder||y.includes("HttpApiBuilder"),s.endpoint=s.endpoint||y.includes("HttpApiEndpoint")||y.includes("HttpApiGroup"),s.security=s.security||y.includes("HttpApiSecurity"),s.middleware=s.middleware||y.includes("middleware")||y.includes("Middleware"),(y.includes("route")||y.includes(".get")||y.includes(".post")||y.includes(".put")||y.includes(".delete")||y.includes(".patch"))&&s.routes.push(y),o.set("http",Qe(e,E,n))),y.includes("FileSystem")){y.includes("read")&&a.reads.push(y),y.includes("write")&&a.writes.push(y),o.set("filesystem",Qe(e,E,n));let w={readFile:"read",readFileString:"read",writeFile:"write",writeFileString:"write",remove:"delete",mkdir:"mkdir",stat:"stat",copy:"copy",rename:"rename",readDirectory:"readDir"};for(let[k,b]of Object.entries(w))if(y.includes(k)){S.push({op:b,location:Qe(e,E,n)});break}}if((y.includes("Socket")||y.includes("fromNetServer"))&&(i=!0),y.includes("Terminal")&&(c=!0),y.includes("Worker")&&(d=!0),y.includes("Command.")){l.push(y);let w={make:"make",start:"start",stdin:"stdin",stdout:"stdout",stderr:"stderr",exitCode:"exitCode"};for(let[k,b]of Object.entries(w))if(y.includes(k)){h.push({op:b,location:Qe(e,E,n)});break}}if(y.includes("KeyValueStore")&&(f=!0),y.includes("Multipart")&&(u=!0),(y.includes("Ndjson")||y.includes("MsgPack")||y.includes("Effectify"))&&p.push(y),(y.includes("OpenApi")||y.includes("OpenApiJsonSchema"))&&(g=!0),y.includes("HttpApiEndpoint")){let w=["get","post","put","delete","patch","head","options"];for(let k of w)if(y.includes(`.${k}`)){let b=E.getArguments(),F=(b.length>0?b[0]?.getText().replace(/["'`]/g,""):"unnamed")??"unnamed",L="/";if(b.length>=2)L=b[1]?.getText().replace(/["'`]/g,"")??"/";else{let K=E.getParent();if(K?.getKind()===Xn.TaggedTemplateExpression){let q=K.getTemplate();L=Uu(q)}}let A=Vu(E);N.push({method:k.toUpperCase(),name:F,path:L||"/",location:Qe(e,E,n),...A.apiId!==void 0?{apiId:A.apiId}:{},...A.groupName!==void 0?{groupName:A.groupName}:{}});break}}if(y.includes("middleware")||y.includes("Middleware")){let w=y.replace(/.*\./,"").replace(/\(.*/,"");w&&x.push({name:w,location:Qe(e,E,n)})}if(y.includes("Command.make")||y.includes("Prompt.")){let w=E.getArguments(),k=w.length>0?w[0]?.getText().replace(/["'`]/g,""):"unnamed",b=w.some(M=>M.getText().includes("Schema"));C.push({name:k??"unnamed",hasSchema:b,location:Qe(e,E,n)})}}return(s.client||s.server||s.api||a.reads.length>0||a.writes.length>0)&&(m.includes("node")||m.push("node")),(d||u)&&(m.includes("browser")||m.push("browser")),{platforms:m,modules:{http:{...s,routes:[...new Set(s.routes)]},filesystem:{reads:[...new Set(a.reads)],writes:[...new Set(a.writes)]},sockets:i,terminal:c,workers:d,commands:[...new Set(l)],keyValueStore:f,multipart:u,codecs:[...new Set(p)],openApi:g},locations:o,...S.length>0?{fileSystemOps:S}:{},...h.length>0?{commandOps:h}:{},...N.length>0?{routeDefinitions:N}:{},...x.length>0?{middlewareChain:x}:{},...C.length>0?{cliCommands:C}:{}}}import{SyntaxKind as z}from"ts-morph";import{SyntaxKind as Q}from"ts-morph";function Ju(e,t,r){if(e.getText().includes("Schema."))return e;if(e.getKind()===Q.Identifier){let o=e,s=o.getSymbol(),i=(s?.getAliasedSymbol()??s)?.getDeclarations()??[];for(let l of i){if(l.getKind()===Q.VariableDeclaration){let f=l.getInitializer();if(f?.getText().includes("Schema."))return f}if(l.getKind()===Q.ImportSpecifier){let f=l.getName(),u=l.getFirstAncestorByKind(Q.ImportDeclaration);if(u){let p=u.getModuleSpecifierValue(),g=t.getFilePath(),m=p.startsWith(".")?xt(g,p):void 0,S=m?r.getSourceFile(m):void 0;if(S){let h=S.getExportedDeclarations().get(f)??[];for(let N of h)if(N.getKind()===Q.VariableDeclaration){let x=N.getInitializer();if(x?.getText().includes("Schema."))return x}}}}}let c=o.getText(),d=t.getVariableDeclarations();for(let l of d)if(l.getName()===c){let f=l.getInitializer();if(f?.getText().includes("Schema."))return f}}return e.getText().includes("Schema.")?e:void 0}function Ft(e,t,r,n){let o=Ju(e,t,r);if(o)return We(o,t,r,n??new Map)}function We(e,t,r,n){let o=e.getText();if(o.includes("Schema.Array")){let c=e.getKind()===Q.CallExpression?e:e.getFirstDescendantByKind(Q.CallExpression);if(c){let d=c.getArguments();return{type:"array",items:(d[0]?We(d[0],t,r,n):void 0)??{}}}}if(o.includes("Schema.Struct")){let c=e.getKind()===Q.CallExpression?e:e.getFirstDescendantByKind(Q.CallExpression);if(!c)return{type:"object"};let l=c.getArguments()[0];if(l?.getKind()!==Q.ObjectLiteralExpression)return{type:"object"};let f=l,u={},p=[];for(let m of f.getProperties()){if(m.getKind()!==Q.PropertyAssignment)continue;let S=m,h=S.getNameNode().getText(),N=S.getInitializer();if(!N)continue;let x=N.getText();x.includes("Schema.optional")||x.includes(".optional")||p.push(h);let E=We(N,t,r,n);E&&(u[h]=E)}let g={type:"object",properties:Object.keys(u).length?u:void 0,additionalProperties:!1};return p.length&&(g.required=p),g}if(o.includes("Schema.Union")){let c=e.getKind()===Q.CallExpression?e:e.getFirstDescendantByKind(Q.CallExpression);if(c){let l=c.getArguments().map(f=>We(f,t,r,n)).filter(f=>f!==void 0);if(l.length)return{oneOf:l}}}if(o.includes("Schema.optional")||o.includes(".pipe(Schema.optional")){let c=e.getKind()===Q.CallExpression?e:e.getFirstDescendantByKind(Q.CallExpression);if(c){let d=c.getArguments(),l=d[0]?We(d[0],t,r,n):void 0;if(l)return{...l,nullable:!0}}}if(o.includes("Schema.Record")){let c=e.getKind()===Q.CallExpression?e:e.getFirstDescendantByKind(Q.CallExpression);if(c){let d=c.getArguments();return{type:"object",additionalProperties:(d[1]?We(d[1],t,r,n):void 0)??!0}}}if(o.includes("Schema.Tuple")){let c=e.getKind()===Q.CallExpression?e:e.getFirstDescendantByKind(Q.CallExpression);if(c)return{type:"array",items:c.getArguments().map(f=>We(f,t,r,n)).filter(Boolean)}}if(o.includes("Schema.Date")||o.includes("Schema.DateTimeUtc")||o.includes("Schema.Instant"))return{type:"string",format:"date-time"};if(o.includes("Schema.String")&&!o.includes("Schema.Struct"))return{type:"string"};if(o.includes("Schema.Number")||o.includes("Schema.Int")||o.includes("Schema.Positive")||o.includes("Schema.NonNegative")||o.includes("Schema.Finite"))return{type:"number"};if(o.includes("Schema.Boolean"))return{type:"boolean"};if(o.includes("Schema.Null"))return{type:"null"};let s=/Schema\.Literal\s*\(\s*(["'])([^"']*)\1\s*\)/.exec(o);if(s)return{type:"string",enum:[s[2]]};let a=/Schema\.Literal\s*\(\s*(\d+)\s*\)/.exec(o);if(a)return{type:"number",enum:[Number(a[1])]};let i=/Schema\.Literal\s*\(\s*(true|false)\s*\)/.exec(o);if(i)return{type:"boolean",enum:[i[1]==="true"]};if(e.getKind()===Q.Identifier){let l=(e.getSymbol()?.getDeclarations()[0]).getInitializer();if(l)return We(l,t,r,n)}}function Yu(e,t,r){let{line:n,column:o}=r.getLineAndColumnAtPos(t.getStart());return{filePath:e,line:n+1,column:o}}function Qu(e){let n=e.getText().replace(/\$\{HttpApiSchema\.param\s*\(\s*["'](\w+)["'][^}]*\)\}/g,":$1").replace(/\$\{[^}]*\}/g,":param").replace(/^`|`$/g,"").trim();return n.startsWith("/")?n:`/${n}`}function Es(e,t,r){let n={},o=e;for(let s=0;s<30&&o;s++){let a=o.getParent();if(a?.getKind()!==z.CallExpression){o=a;continue}let i=a,c=i.getExpression().getText(),d=i.getArguments();if(d.length<2){o=a;continue}let l=d[0]?.getText(),f=d[1]?.getText();if(c.endsWith(".annotate")||c.endsWith(".annotateContext"))if(l?.includes("OpenApi.Description")||l?.includes("Description")){let u=f?.replace(/^["']|["']$/g,"");u&&(n.description=u)}else if(l?.includes("OpenApi.Summary")||l?.includes("Summary")){let u=f?.replace(/^["']|["']$/g,"");u&&(n.summary=u)}else l?.includes("OpenApi.Deprecated")||l?.includes("Deprecated")?n.deprecated=f==="true":(l?.includes("OpenApi.Exclude")||l?.includes("Exclude"))&&(n.excluded=f==="true");o=a}return n}function Zu(e,t){let r={},n=t.getProject(),o=e;for(let s=0;s<40&&o;s++){let a=o.getParent();if(a?.getKind()!==z.CallExpression){o=a;continue}let i=a,c=i.getExpression().getText(),d=i.getArguments();if(d.length<1){o=a;continue}let l=d[0];if(c.endsWith(".addSuccess")&&l&&!r.responseSchema){let f=Ft(l,t,n);f&&(r.responseSchema=f)}else if(c.endsWith(".setPayload")&&l&&!r.requestSchema){let f=Ft(l,t,n);f&&(r.requestSchema=f)}else if((c.endsWith(".setUrlParams")||c.endsWith(".setQueryParams"))&&l&&!r.urlParamsSchema){let f=Ft(l,t,n);f&&(r.urlParamsSchema=f)}o=a}return r}function Xu(e,t,r,n){let o=e.getArguments(),a=(o.length>0?o[0]?.getText().replace(/["'`]/g,""):"unnamed")??"unnamed",i="/";if(o.length>=2)i=o[1]?.getText().replace(/["'`]/g,"")??"/";else{let l=e.getParent();if(l?.getKind()===z.TaggedTemplateExpression){let f=l.getTemplate();i=Qu(f)}}let c=Es(e,r,n);if(c.excluded)return null;let d=Zu(e,r);return{name:a,method:t.toUpperCase(),path:i||"/",location:Yu(n,e,r),...c.description?{description:c.description}:{},...c.summary?{summary:c.summary}:{},...c.deprecated?{deprecated:!0}:{},...d.requestSchema?{requestSchema:d.requestSchema}:{},...d.responseSchema?{responseSchema:d.responseSchema}:{},...d.urlParamsSchema?{urlParamsSchema:d.urlParamsSchema}:{}}}function ef(e,t,r){let n=[],o=["get","post","put","delete","patch","head","options"],s=new Set,a=er(e);function i(l){let f=l,u=[".annotate",".addSuccess",".setPayload",".setUrlParams",".setQueryParams",".addFailure"];for(let p=0;p<15;p++){if(f.getKind()!==z.CallExpression)return;let g=f,m=g.getExpression().getText();for(let h of o){let N=m.includes(`HttpApiEndpoint.${h}`)||m.includes(`HttpApiEndpoint.${h}(`),x=!u.some(C=>m.endsWith(C)||m.includes(C));if(N&&!m.includes(".annotate")&&x)return g}if(u.some(h=>m.endsWith(h)||m.includes(h))){let h=g.getExpression();h.getKind()===z.CallExpression?f=h:f=h.getExpression();continue}return}}function c(l){if(l.getKind()===z.CallExpression)return l;if(l.getKind()===z.Identifier){let f=l.getText(),u=l.getSymbol(),p=u?.getDeclarations()??u?.getAliasedSymbol()?.getDeclarations()??[];for(let m of p)if(m.getKind()===z.VariableDeclaration){let S=m.getInitializer();if(S)return S}let g=t.getVariableDeclarations();for(let m of g)if(m.getName()===f){let S=m.getInitializer();if(S)return S}}}function d(l){let f=c(l);if(f?.getKind()!==z.CallExpression)return;let u=f,p=i(u);if(p){let m=p.getExpression().getText();for(let S of o)if(m.includes(`HttpApiEndpoint.${S}`)){let h=Xu(p,S,t,r);h&&!s.has(`${h.method}:${h.path}:${h.name}`)&&(s.add(`${h.method}:${h.path}:${h.name}`),n.push(h));return}}if(u.getExpression().getText().endsWith(".add"))for(let m of u.getArguments())d(m)}for(let l of a)d(l);return n}function tf(e,t,r,n){let o=e.getArguments(),a=(o.length>0?o[0]?.getText().replace(/["'`]/g,""):"group")??"group",i=o[1],c=!1;if(i?.getKind()===z.ObjectLiteralExpression){let u=i.getProperty("topLevel");u?.getKind()===z.PropertyAssignment&&(c=u.getInitializer()?.getText()==="true")}let d=ef(e,t,r),l=Es(e,t,r);return{name:a,endpoints:d,...l.description?{description:l.description}:{},...c?{topLevel:!0}:{},...n?{prefix:n}:{}}}function nf(e){let t=e;for(let r=0;r<25&&t.getKind()===z.CallExpression;r++){let n=t;if(n.getExpression().getText().endsWith(".prefix")){let a=n.getArguments();if(a.length>=1){let i=a[0]?.getText().replace(/["'`]/g,"");if(i)return i.startsWith("/")?i:`/${i}`}break}let s=n.getExpression();if(s.getKind()===z.PropertyAccessExpression)t=s.getExpression();else break}}function er(e){let t=[],r,n=e,o=e.getExpression().getText(),s=o.includes("HttpApi.make"),a=o.includes("HttpApiGroup.make");for(let i=0;i<20;i++){let c=n.getParent();if(!c||(c.getKind()===z.PropertyAccessExpression&&(c=c.getParent()),c?.getKind()!==z.CallExpression))break;let d=c,l=d.getExpression().getText();if(l.endsWith(".add")){if(s&&l.includes("HttpApiGroup.make")||a&&l.includes("HttpApi.make")&&!l.includes("HttpApiGroup"))break;r=d,n=c;continue}break}if(!r)return t;n=r;for(let i=0;i<50;i++){if(n.getKind()===z.CallExpression){let c=n;if(c.getExpression().getText().endsWith(".add")){for(let f of c.getArguments())t.push(f);let l=c.getExpression();if(l.getKind()===z.CallExpression){n=l;continue}if(l.getKind()===z.PropertyAccessExpression){let f=l.getExpression();if(f.getKind()===z.CallExpression){n=f;continue}}}}break}return t}function rf(e,t,r){let n=[],o=new Set,s=er(e),a=[".add",".prefix",".annotate"];function i(l){let f=l;for(let u=0;u<20;u++){if(f.getKind()!==z.CallExpression)return;let p=f,g=p.getExpression().getText();if(g.includes("HttpApiGroup.make")&&!a.some(m=>g.endsWith(m))||g.includes("HttpApi.make")&&!a.some(m=>g.endsWith(m)))return p;if(a.some(m=>g.endsWith(m))){let m=p.getExpression();if(m.getKind()===z.CallExpression){f=m;continue}if(m.getKind()===z.PropertyAccessExpression){let S=m.getExpression();if(S.getKind()===z.CallExpression){f=S;continue}}return}return}}function c(l){if(l.getKind()===z.CallExpression)return l;if(l.getKind()===z.Identifier){let f=l.getText(),u=l.getSymbol(),p=u?.getDeclarations()??u?.getAliasedSymbol()?.getDeclarations()??[];for(let m of p)if(m.getKind()===z.VariableDeclaration){let S=m.getInitializer();if(S?.getKind()===z.CallExpression)return S}let g=t.getVariableDeclarations();for(let m of g)if(m.getName()===f){let S=m.getInitializer();if(S?.getKind()===z.CallExpression)return S}}}function d(l){let f=c(l);if(!f)return;let u=f.getExpression().getText();if(u.includes("HttpApiGroup.make")){let p=i(f);if(p){let g=nf(f),m=tf(p,t,r,g);m&&!o.has(m.name)&&(o.add(m.name),n.push(m))}return}if(u.includes("HttpApi.make")){let p=i(f);if(p)for(let g of er(p))d(g)}}for(let l of s)d(l);return n}function of(e){let t=e;for(let r=0;r<50;r++){let n=t.getParent();if(n?.getKind()!==z.CallExpression)return e;let o=n;if(o.getExpression().getText().endsWith(".add")){let a=o.getExpression();if(a.getKind()===z.CallExpression){let i=a;if(i.getExpression().getText().includes("HttpApi.make")){t=i;continue}}}break}return t}function sf(e,t){let r=[],n=t||e.getFilePath(),o=new Set;for(let s of e.getDescendantsOfKind(z.CallExpression)){let a=s.getExpression().getText();if(!a.includes("HttpApi.make")||a.includes("HttpApiBuilder")||a.includes(".add"))continue;let i=s.getArguments(),c=i.length>0?i[0]?.getText().replace(/["'`]/g,""):void 0;if(!c||o.has(c))continue;let d=of(s),l=rf(d,e,n);o.add(c),r.push({apiId:c,filePath:n,groups:l})}return r}function af(e){let t=[];for(let r of e){t.push(`# API: ${r.apiId}`),t.push("");let n=r.prefix??"";for(let o of r.groups){t.push(`## ${o.name}`),o.description&&(t.push(""),t.push(o.description),t.push("")),t.push(""),t.push("| Method | Path | Name | Description |"),t.push("|--------|------|------|-------------|");let s=o.prefix??"";for(let a of o.endpoints){let i=n+s+a.path,c=a.description??a.summary??"-",d=a.deprecated?" (deprecated)":"";t.push(`| ${a.method} | ${i} | ${a.name}${d} | ${c} |`)}t.push("")}t.push("")}return t.join(`
|
|
539
|
-
`).trim()}function
|
|
540
|
-
`)}function lf(e){let t={};for(let r of e){let n=r.prefix??"";for(let o of r.groups){let s=o.prefix??"";for(let a of o.endpoints){let i=n+s+a.path;t[i]??={};let c=a.method.toLowerCase(),d={operationId:`${o.name}.${a.name}`,...a.summary?{summary:a.summary}:{},...a.deprecated?{deprecated:!0}:{}};if(a.requestSchema&&(d.requestBody={content:{"application/json":{schema:a.requestSchema}}}),a.responseSchema&&(d.responses={200:{description:a.summary??a.description??"Success",content:{"application/json":{schema:a.responseSchema}}}}),a.urlParamsSchema?.properties){let l=Object.entries(a.urlParamsSchema.properties).map(([f,u])=>({name:f,in:"path",schema:u}));l.length&&(d.parameters=l)}t[i][c]=d}}}return{paths:t}}import{Project as df,SyntaxKind as uf}from"ts-morph";function tr(e,t,r){let{line:n,column:o}=r.getLineAndColumnAtPos(t.getStart());return{filePath:e,line:n+1,column:o}}function ff(e,t){let r=new df({useInMemoryFileSystem:!0}),n=t?r.createSourceFile(e,t):r.addSourceFileAtPath(e),o=new Map,s=!1,a=!1,i=[],c=!1,d=!1,l=!1,f=!1,u=!1,p=!1,g=!1,m=!1,S=!1,h=!1;for(let N of n.getImportDeclarations()){let x=N.getModuleSpecifierValue();(x==="@effect/vitest"||x.includes("@effect/vitest"))&&(l=!0),(x==="fast-check"||x==="fc"||x.includes("fast-check"))&&(S=!0,o.set("fast-check",{filePath:e,line:1,column:0}))}for(let N of n.getDescendantsOfKind(uf.CallExpression)){let x=N.getExpression().getText(),C=tr(e,N,n);(x.includes("TestClock")||x.includes("TestContext"))&&(x.includes("TestClock")&&(s=!0),x.includes("TestContext")&&(a=!0),o.set("test-context",tr(e,N,n))),(x.includes("Layer.succeed")||x.includes("Layer.mock"))&&(N.getParent()?.getText().includes("test")||n.getFilePath().includes(".test."))&&(i.push(x.slice(0,60)),o.set("mock-layer",tr(e,N,n))),(x.includes("Effect.runPromise")||x.includes("Effect.runSync")||x.includes("Effect.runPromiseExit")||x.includes("Effect.runSyncExit")||x.includes("runPromise")||x.includes("runSync"))&&(n.getFilePath().includes(".test.")||n.getFilePath().includes("spec."))&&(c=!0),(x.includes("it.effect")||x.includes("it.scoped")||x.includes("it.live")||x.includes("it.scopedLive")||x.includes("it.prop"))&&(d=!0,x.includes("it.prop")&&(h=!0),o.set("effect-vitest",C)),x.includes("TestAnnotations")&&(u=!0,o.set("test-annotations",C)),x.includes("flakyTest")&&(p=!0,o.set("flaky-test",C)),(x.includes("Exit.match")||x.includes("Exit.isSuccess")||x.includes("Exit.isFailure")||x.includes("Exit.isInterrupted"))&&(g=!0,o.set("exit-assertions",C)),(x==="layer"||x.endsWith(".layer"))&&N.getParent()?.getText().includes("(")&&(f=!0,o.set("shared-layer",C)),(x.includes("TestServices")||x.includes("TestSized")||x.includes("TestLive"))&&(m=!0,o.set("test-services",C)),(x.includes("fc.")||x.includes("FastCheck")||x.includes("Arbitrary.make")||x.includes("Arbitrary.filter")||x.includes("Arbitrary.from"))&&(S=!0,o.set("fast-check",C)),(x.includes("fc.property")||x.includes("fc.asyncProperty"))&&(h=!0,o.set("property-test",C))}return{testClockUsed:s,testContextUsed:a,mockLayers:[...new Set(i)],runInTests:c,effectVitestUsed:d,effectVitestImported:l,sharedLayerUsed:f,testAnnotationsUsed:u,flakyTestUsed:p,exitAssertionsUsed:g,testServicesUsed:m,fastCheckUsed:S,propertyTestUsed:h,locations:o}}import{readFile as pf}from"fs/promises";import{join as gf}from"path";var mf=/^(\d+)\.(\d+)\.(\d+)(?:-(.+))?$/;function hf(e){let t=mf.exec(e);return t?.[1]===void 0||t[2]===void 0||t[3]===void 0?null:{version:e,major:parseInt(t[1],10),minor:parseInt(t[2],10),patch:parseInt(t[3],10),isPrerelease:!!t[4]}}async function bs(e=process.cwd()){try{let t=gf(e,"package.json"),r=await pf(t,"utf-8"),n=JSON.parse(r),s={...n.dependencies,...n.devDependencies}.effect;if(typeof s!="string")return null;let a=s.replace(/^[\^~]/,"");return hf(a)}catch{return null}}async function yf(e=process.cwd()){let t=await bs(e),r=[],n=null;return t?t.major<3&&(r.push("Effect v2 is deprecated; upgrade to Effect v3"),n="pnpm add effect@^3"):n='Add "effect" to dependencies to enable version checks',{effectVersion:t,deprecationWarnings:r,suggestion:n}}import{Option as Cs}from"effect";function nr(e,t,r,n){for(let o of e)if(o.type==="generator"){let s=o;for(let i of s.yields){let c=i.effect.type==="effect"?i.effect.callee:void 0,d={yieldIndex:n.current++,nodeId:i.effect.id,...i.variableName!==void 0&&{variableName:i.variableName},...c!==void 0&&{effectCallee:c}};t.push(d),(c?.includes("service")||c?.includes("Context"))&&r.push(c)}let a=Cs.getOrElse(v(o),()=>[]);nr(a,t,r,n)}else{let s=Cs.getOrElse(v(o),()=>[]);nr(s,t,r,n)}}function Sf(e){let t=[],r=[];nr(e.root.children,t,r,{current:0});let n=new Set;for(let s of t)s.variableName&&!s.variableName.startsWith("_")&&n.add(s.yieldIndex);let o=t.map(s=>s.yieldIndex).filter(s=>!n.has(s));return{bindings:t,unusedYieldIndices:o,serviceYields:[...new Set(r)]}}import{Project as xf,SyntaxKind as Rt}from"ts-morph";function Ns(e,t,r){let{line:n,column:o}=r.getLineAndColumnAtPos(t.getStart());return{filePath:e,line:n+1,column:o}}function Ef(e,t){let r=new xf({useInMemoryFileSystem:!0}),n=t?r.createSourceFile(e,t):r.addSourceFileAtPath(e),o=new Map,s=!1,a=!1,i=[],c=!1,d=[],l=[],f=[];for(let p of n.getDescendantsOfKind(Rt.CallExpression)){let g=p.getExpression().getText(),m=Ns(e,p,n);if((g.includes("SqlClient")||g.includes("sqlClient")||g.includes("Sql"))&&(s=!0,o.set("sql",m)),g.includes("withTransaction")&&(a=!0,o.set("transaction",m)),(g.includes("SqlSchema")||g.includes("sqlSchema"))&&(i.push(g.slice(0,80)),o.set("schema",m)),g.includes("SqlResolver.make")||g.includes("SqlResolver.grouped")||g.includes("SqlResolver.void")){let S=p.getArguments(),h=S.length>0?S[0]?.getText().replace(/["'`]/g,""):"unnamed";d.push({name:h??"unnamed",location:m})}if(g.includes("SqlMigrator")){let S=p.getArguments(),h=S.length>0?S[0]?.getText().replace(/["'`]/g,""):"unnamed";l.push({name:h??"unnamed",location:m})}}let u=[Rt.ForStatement,Rt.ForOfStatement,Rt.WhileStatement];for(let p of u)for(let g of n.getDescendantsOfKind(p)){let S=g.getFirstChildByKind(Rt.Block)?.getText()??"";if(S.includes("Sql")||S.includes("execute")||S.includes("query")){c=!0;let h=Ns(e,g,n);o.set("sql-in-loop",h),f.push({query:S.slice(0,80),location:h})}}return{sqlClientUsed:s,withTransaction:a,schemaDefs:[...new Set(i)],queryInLoop:c,locations:o,...d.length>0?{resolvers:d}:{},...l.length>0?{migrations:l}:{},...f.length>0?{queriesInLoops:f}:{}}}import{Project as bf,SyntaxKind as Cf}from"ts-morph";function Nf(e,t,r){let{line:n,column:o}=r.getLineAndColumnAtPos(t.getStart());return{filePath:e,line:n+1,column:o}}function vf(e,t){let r=new bf({useInMemoryFileSystem:!0}),n=t?r.createSourceFile(e,t):r.addSourceFileAtPath(e),o=new Map,s=!1,a=[],i=[],c=[];for(let d of n.getDescendantsOfKind(Cf.CallExpression)){let l=d.getExpression().getText(),f=Nf(e,d,n);if((l.includes("Rpc.make")||l.includes("Rpc.router"))&&(s=!0,a.push(l.slice(0,60)),o.set("rpc",f)),(l.includes("RpcClient")||l.includes("Rpc.call"))&&(i.push(l.slice(0,60)),o.set("rpc-client",f)),l.includes("Rpc.make")||l.includes("RpcGroup")){let u=d.getArguments(),p=u.length>0?u[0]?.getText().replace(/["'`]/g,""):"unnamed",g=d.getText(),m=g.includes("Stream")||g.includes("stream");c.push({name:p??"unnamed",isStreaming:m,location:f})}}return{rpcDefined:s,routers:[...new Set(a)],clientCalls:[...new Set(i)],locations:o,...c.length>0?{rpcDefinitions:c}:{}}}import{Project as wf,SyntaxKind as Tf}from"ts-morph";function kf(e,t,r){let{line:n,column:o}=r.getLineAndColumnAtPos(t.getStart());return{filePath:e,line:n+1,column:o}}function If(e,t){let r=new wf({useInMemoryFileSystem:!0}),n=t?r.createSourceFile(e,t):r.addSourceFileAtPath(e),o=new Map,s=!1,a=!1,i=!1,c=!1;for(let d of n.getDescendantsOfKind(Tf.CallExpression)){let l=d.getExpression().getText(),f=kf(e,d,n);(l.includes("Request.tagged")||l.includes("Request.of"))&&(s=!0,o.set("request",f)),(l.includes("RequestResolver.makeBatched")||l.includes("RequestResolver.fromEffect"))&&(a=!0,o.set("resolver",f)),l.includes("withRequestBatching")&&(i=!0,o.set("batching",f)),l.includes("withRequestCaching")&&(c=!0,o.set("caching",f))}return{requestTagged:s,resolverBatched:a,withBatching:i,withCaching:c,locations:o}}import{Project as Af,SyntaxKind as Ff}from"ts-morph";function Rf(e,t,r){let{line:n,column:o}=r.getLineAndColumnAtPos(t.getStart());return{filePath:e,line:n+1,column:o}}function $f(e,t){let r=new Af({useInMemoryFileSystem:!0}),n=t?r.createSourceFile(e,t):r.addSourceFileAtPath(e),o=new Map,s=[],a=[],i=[],c=[],d=!1;for(let l of n.getDescendantsOfKind(Ff.CallExpression)){let f=l.getExpression().getText(),u=Rf(e,l,n);(f.includes("STM.commit")||f==="STM.commit")&&(s.push(u),o.set("commit",u)),(f.includes("TRef.make")||f.includes("TRef.unsafeMake"))&&(a.push(f.slice(0,50)),o.set("tref",u)),(f.includes("TMap.make")||f.includes("TMap.empty"))&&(i.push(f.slice(0,50)),o.set("tmap",u)),(f.includes("TQueue.make")||f.includes("TQueue.bounded"))&&(c.push(f.slice(0,50)),o.set("tqueue",u)),(f.includes("STM.retry")||f==="STM.retry")&&(d=!0)}return{commitSites:s,tRefs:[...new Set(a)],tMaps:[...new Set(i)],tQueues:[...new Set(c)],retryUsed:d,locations:o}}function Df(e){let t=le(e);return{version:1,ir:e,mermaid:t,programName:e.root.programName,exportedAt:new Date().toISOString()}}function Pf(e){return Buffer.from(JSON.stringify(e),"utf-8").toString("base64url")}function Mf(e){let t=Buffer.from(e,"base64url").toString("utf-8");return JSON.parse(t)}import{createHash as Lf}from"crypto";import{readFile as Of,writeFile as Wf,mkdir as Kf}from"fs/promises";import{stat as Bf}from"fs/promises";import{join as vs}from"path";var ws=".effect-analyzer-cache",Ts=1;function ks(e){return Lf("sha256").update(e,"utf-8").digest("hex").slice(0,16)}function Is(e,t){let r=t.replace(/[^a-zA-Z0-9._-]/g,"_");return vs(e,ws,`${r}.json`)}async function qf(e,t,r=process.cwd()){try{let n=Is(r,e),o=ks(t),s=await Of(n,"utf-8"),a=JSON.parse(s);if(a.version===Ts&&a.contentHash===o)return a.irs}catch{}return null}async function jf(e,t,r,n=process.cwd()){try{let o=vs(n,ws);await Kf(o,{recursive:!0});let s=await Bf(e).catch(()=>null),a={version:Ts,contentHash:ks(t),mtimeMs:s?.mtimeMs??0,irs:r};await Wf(Is(n,e),JSON.stringify(a),"utf-8")}catch{}}import{VariableDeclarationKind as _f}from"ts-morph";function zf(e){return{values:new Map,sourceFile:e}}function rr(e,t){let r=t.values.get(e);if(r!==void 0)return r;let o=t.sourceFile.getVariableDeclarations();for(let a of o)if(a.getName()===e){let i={resolved:!1,reason:`Cyclic reference detected for "${e}"`};if(t.values.set(e,i),a.getVariableStatement()?.getDeclarationKind()!==_f.Const){let f={resolved:!1,reason:`"${e}" is not a const declaration`};return t.values.set(e,f),f}let d=a.getInitializer();if(!d){let f={resolved:!1,reason:`"${e}" has no initializer`};return t.values.set(e,f),f}let l=Ke(d,t);return t.values.set(e,l),l}let s={resolved:!1,reason:`"${e}" not found in current file`};return t.values.set(e,s),s}function Ke(e,t){let{Node:r}=I();if(r.isStringLiteral(e))return{resolved:!0,value:{type:"string",value:e.getLiteralValue()}};if(r.isNumericLiteral(e))return{resolved:!0,value:{type:"number",value:e.getLiteralValue()}};if(r.isTrueLiteral(e))return{resolved:!0,value:{type:"boolean",value:!0}};if(r.isFalseLiteral(e))return{resolved:!0,value:{type:"boolean",value:!1}};if(r.isNullLiteral(e))return{resolved:!0,value:{type:"null",value:null}};if(r.isArrayLiteralExpression(e)){let n=e.getElements(),o=[];for(let s of n){if(r.isSpreadElement(s))return{resolved:!1,reason:"Array contains spread element"};let a=Ke(s,t);if(!a.resolved||!a.value)return{resolved:!1,reason:`Could not resolve array element: ${a.reason}`};o.push(a.value)}return{resolved:!0,value:{type:"array",value:o}}}if(r.isObjectLiteralExpression(e)){let n=e.getProperties(),o={};for(let s of n){if(r.isSpreadAssignment(s))return{resolved:!1,reason:"Object contains spread assignment"};if(r.isShorthandPropertyAssignment(s)){let l=s.getName(),f=rr(l,t);if(!f.resolved||!f.value)return{resolved:!1,reason:`Could not resolve shorthand property "${l}"`};o[l]=f.value;continue}if(!r.isPropertyAssignment(s))return{resolved:!1,reason:"Object contains unsupported property type"};let a=s.getNameNode();if(r.isComputedPropertyName(a))return{resolved:!1,reason:"Object contains computed property name"};let i=s.getName(),c=s.getInitializer();if(!c)return{resolved:!1,reason:`Property "${i}" has no initializer`};let d=Ke(c,t);if(!d.resolved||!d.value)return{resolved:!1,reason:`Could not resolve property "${i}": ${d.reason}`};o[i]=d.value}return{resolved:!0,value:{type:"object",value:o}}}if(r.isIdentifier(e)){let n=e.getText();return n==="undefined"?{resolved:!0,value:{type:"undefined",value:void 0}}:rr(n,t)}if(r.isCallExpression(e)){let n=e.getExpression(),o=r.isIdentifier(n)?n.getText():null;if(o==="tags"||o==="err"){let s=e.getArguments(),a=[];for(let i of s){let c=Ke(i,t);if(!c.resolved||!c.value)return{resolved:!1,reason:`Could not resolve ${o}() argument: ${c.reason}`};a.push(c.value)}return{resolved:!0,value:{type:"array",value:a}}}return{resolved:!1,reason:`Cannot inline function call: ${o??"unknown"}`}}return r.isNoSubstitutionTemplateLiteral(e)?{resolved:!0,value:{type:"string",value:e.getLiteralValue()}}:r.isTemplateExpression(e)?{resolved:!1,reason:"Cannot inline template literal with expressions"}:r.isAsExpression(e)||r.isSatisfiesExpression(e)||r.isParenthesizedExpression(e)?Ke(e.getExpression(),t):{resolved:!1,reason:`Unsupported node type: ${e.getKindName()}`}}function or(e){switch(e.type){case"string":case"number":case"boolean":case"null":case"undefined":return e.value;case"array":return e.value.map(or);case"object":{let t={};for(let[r,n]of Object.entries(e.value))t[r]=or(n);return t}}}function Hf(e){if(e.type!=="array")return;let t=[];for(let r of e.value){if(r.type!=="string")return;t.push(r.value)}return t}function Uf(e){if(e.type==="string")return e.value}import{Option as Fs}from"effect";var Rs=new Set(["parallel","race","conditional","decision","switch","loop","error-handler","retry","generator","pipe","stream","fiber"]);function sr(e,t="root",r=0){let n=[];e.type==="effect"&&n.push({stepId:e.id,callee:e.callee,containerType:t,index:r});let o=Fs.getOrElse(v(e),()=>[]),s=Rs.has(e.type)?e.type:t,a=0;for(let i of o){let c=sr(i,s,a);n.push(...c),a++}return n}function As(e){let t=new Map;function r(n){Rs.has(n.type)&&t.set(n.type,(t.get(n.type)??0)+1);let o=Fs.getOrElse(v(n),()=>[]);for(let s of o)r(s)}return r(e),t}function $s(e,t,r){let n=r?.detectRenames??!0,o=r?.regressionMode??!1,s=sr(e.root),a=sr(t.root),i=new Map;for(let h of s)i.set(h.stepId,h);let c=new Map;for(let h of a)c.set(h.stepId,h);let d=new Set,l=new Set,f=[];for(let h of a){let N=i.get(h.stepId);N&&(d.add(N.stepId),l.add(h.stepId),N.containerType!==h.containerType?f.push({kind:"moved",stepId:h.stepId,callee:h.callee,containerBefore:N.containerType,containerAfter:h.containerType}):f.push({kind:"unchanged",stepId:h.stepId,callee:h.callee}))}if(n){let h=s.filter(x=>!d.has(x.stepId)),N=a.filter(x=>!l.has(x.stepId));for(let x of N){let C=h.find(E=>!d.has(E.stepId)&&E.callee===x.callee&&E.index===x.index);C&&(d.add(C.stepId),l.add(x.stepId),f.push({kind:"renamed",stepId:x.stepId,previousStepId:C.stepId,callee:x.callee}))}}for(let h of s)d.has(h.stepId)||f.push({kind:"removed",stepId:h.stepId,callee:h.callee});for(let h of a)l.has(h.stepId)||f.push({kind:"added",stepId:h.stepId,callee:h.callee});let u=[],p=As(e.root),g=As(t.root),m=new Set([...p.keys(),...g.keys()]);for(let h of m){let N=p.get(h)??0,x=g.get(h)??0;if(x>N)for(let C=0;C<x-N;C++)u.push({kind:"added",nodeType:h,description:`${h} block added`});else if(N>x)for(let C=0;C<N-x;C++)u.push({kind:"removed",nodeType:h,description:`${h} block removed`})}let S={stepsAdded:f.filter(h=>h.kind==="added").length,stepsRemoved:f.filter(h=>h.kind==="removed").length,stepsRenamed:f.filter(h=>h.kind==="renamed").length,stepsMoved:f.filter(h=>h.kind==="moved").length,stepsUnchanged:f.filter(h=>h.kind==="unchanged").length,structuralChanges:u.length,hasRegressions:o?f.some(h=>h.kind==="removed")||u.some(h=>h.kind==="removed"):!1};return{beforeName:e.root.programName,afterName:t.root.programName,diffedAt:Date.now(),steps:f,structuralChanges:u,summary:S}}var Vf={added:"+",removed:"-",unchanged:" ",renamed:"~",moved:">"};function Gf(e){let t=Vf[e.kind]??"?",r=e.callee??e.stepId;switch(e.kind){case"renamed":return`${t} **${r}** (renamed from \`${e.previousStepId}\` \u2192 \`${e.stepId}\`)`;case"moved":return`${t} **${r}** (moved from \`${e.containerBefore}\` \u2192 \`${e.containerAfter}\`)`;case"added":return`${t} **${r}** (added, id: \`${e.stepId}\`)`;case"removed":return`${t} **${r}** (removed, id: \`${e.stepId}\`)`;default:return`${t} ${r}`}}function Ds(e,t){let r=t?.showUnchanged??!1,n=t?.title??`Effect Program Diff: ${e.beforeName} \u2192 ${e.afterName}`,o=[];o.push(`# ${n}`),o.push(""),o.push("## Summary"),o.push(""),o.push("| Metric | Count |"),o.push("|--------|-------|"),o.push(`| Added | ${e.summary.stepsAdded} |`),o.push(`| Removed | ${e.summary.stepsRemoved} |`),o.push(`| Renamed | ${e.summary.stepsRenamed} |`),o.push(`| Moved | ${e.summary.stepsMoved} |`),o.push(`| Unchanged | ${e.summary.stepsUnchanged} |`),o.push(`| Structural changes | ${e.summary.structuralChanges} |`),e.summary.hasRegressions&&o.push("| **Regressions** | **Yes** |"),o.push("");let s=r?e.steps:e.steps.filter(a=>a.kind!=="unchanged");if(s.length>0){o.push("## Step Changes"),o.push(""),o.push("```diff");for(let a of s)o.push(Gf(a));o.push("```"),o.push("")}if(e.structuralChanges.length>0){o.push("## Structural Changes"),o.push("");for(let a of e.structuralChanges){let i=a.kind==="added"?"+":"-";o.push(`- ${i} ${a.description}`)}o.push("")}return o.join(`
|
|
541
|
-
`)}function
|
|
542
|
-
`),p=[];for(let g of u){let m=/^\s*(n\d+)\["([^"]*)"\]/.exec(g);if(!m)continue;let
|
|
531
|
+
</html>`}function nr(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}import{Option as Gd}from"effect";var Jd={includeDiagram:!0,includeComplexity:!0,includeServiceDeps:!0,includeErrors:!0,includeDataFlow:!0};function ps(e,t,n){for(let r of e){let o=Yd(r,n);o&&t.push(o);let s=Gd.getOrElse(v(r),()=>[]);s.length>0&&ps(s,t,n+1)}}function Yd(e,t){switch(e.type){case"effect":return{name:j(e.callee||"Effect",_),type:"effect",description:j(e.displayName??e.callee,_),depth:t};case"error-handler":return{name:e.handlerType,type:"error-handler",description:`Error handler: ${e.handlerType}${e.errorTag?` (catches ${e.errorTag})`:""}`,depth:t};case"parallel":return{name:e.callee||"parallel",type:"parallel",description:`Parallel execution of ${e.children.length} effects`,depth:t};case"race":return{name:e.callee||"race",type:"race",description:`Race between ${e.children.length} effects`,depth:t};case"retry":return{name:"Retry",type:"retry",description:`Retry${e.schedule?` with schedule: ${e.schedule}`:""}`,depth:t};case"timeout":return{name:"Timeout",type:"timeout",description:`Timeout${e.duration?` after ${e.duration}`:""}`,depth:t};case"resource":return{name:"Resource",type:"resource",description:"Acquire/Release resource lifecycle",depth:t};case"conditional":return{name:e.conditionalType,type:"conditional",description:j(`Conditional: ${e.condition}`,_),depth:t};case"decision":return{name:e.label||"decision",type:"decision",description:`Decision: ${e.label||e.condition}`,depth:t};case"loop":return{name:e.loopType,type:"loop",description:j(`Loop: ${e.loopType}${e.iterSource?` over ${e.iterSource}`:""}`,_),depth:t};case"layer":return{name:"Layer",type:"layer",description:`Layer${e.provides?.length?` providing: ${e.provides.join(", ")}`:""}`,depth:t};case"stream":return{name:"Stream",type:"stream",description:j(`Stream pipeline${e.pipeline.length>0?`: ${e.pipeline.map(n=>n.operation).join(" \u2192 ")}`:""}`,_),depth:t};case"fiber":return{name:e.operation,type:"fiber",description:`Fiber: ${e.operation}${e.isDaemon?" (daemon)":""}${e.isScoped?" (scoped)":""}`,depth:t};default:return null}}function gs(e,t){let n={...Jd,...t},r=[];if(r.push(`# ${e.root.programName}`),r.push(""),e.root.jsdocDescription&&(r.push(e.root.jsdocDescription),r.push("")),r.push("## Overview"),r.push(""),r.push(`- **Source**: \`${e.metadata.filePath}\``),r.push(`- **Entry**: ${e.root.source}`),e.root.typeSignature){let s=e.root.typeSignature;r.push(`- **Type**: \`Effect<${s.successType}, ${s.errorType}, ${s.requirementsType}>\``)}r.push("");let o=[];if(ps(e.root.children,o,0),o.length>0){r.push("## Workflow Steps"),r.push("");for(let s of o){let a=" ".repeat(s.depth);r.push(`${a}- **${s.name}** _(${s.type})_: ${s.description}`)}r.push("")}if(n.includeServiceDeps&&e.root.dependencies.length>0){r.push("## Service Dependencies"),r.push(""),r.push("| Service | Type | Layer |"),r.push("|---------|------|-------|");for(let s of e.root.dependencies)r.push(`| ${s.name} | ${s.typeSignature??"-"} | ${s.isLayer?"Yes":"No"} |`);r.push("")}if(n.includeErrors){let s=Ye(e);if(s.allErrors.length>0){r.push("## Error Types"),r.push("");for(let a of s.allErrors){let i=s.errorToSteps.get(a)??[];r.push(`- **${a}**: produced by ${i.length} step(s)`)}r.push("")}}if(n.includeComplexity){let s=Ee(e);r.push("## Complexity Metrics"),r.push(""),r.push("| Metric | Value |"),r.push("|--------|-------|"),r.push(`| Cyclomatic Complexity | ${s.cyclomaticComplexity} |`),r.push(`| Cognitive Complexity | ${s.cognitiveComplexity} |`),r.push(`| Max Depth | ${s.maxDepth} |`),r.push(`| Decision Points | ${s.decisionPoints} |`),r.push(`| Max Parallel Breadth | ${s.maxParallelBreadth} |`),r.push("")}if(n.includeDataFlow){let s=Ft(e);if(s.undefinedReads.length>0||s.duplicateWrites.length>0){r.push("## Data Flow Warnings"),r.push("");for(let a of s.undefinedReads)r.push(`- **Undefined read**: \`${a.key}\` read by ${a.readerName??a.readerId}`);for(let a of s.duplicateWrites)r.push(`- **Duplicate write**: \`${a.key}\` written by ${a.writerIds.join(", ")}`);r.push("")}}return n.includeDiagram&&(r.push("## Flow Diagram"),r.push(""),r.push("```mermaid"),r.push(fe(e)),r.push("```"),r.push("")),r.join(`
|
|
532
|
+
`)}function Qd(e,t){let n=[];n.push("# Effect Program Documentation"),n.push(""),n.push(`Generated: ${new Date().toISOString()}`),n.push(""),n.push("## Programs"),n.push("");for(let r of e)n.push(`- [${r.root.programName}](#${r.root.programName.toLowerCase().replace(/[^a-z0-9]/g,"-")})`);n.push("");for(let r of e)n.push("---"),n.push(""),n.push(gs(r,t)),n.push("");return n.join(`
|
|
533
|
+
`)}import{Option as Zd}from"effect";function Xd(e){return e?e.typeConfidence:"unknown"}function eu(e){return!e||e==="never"?"never":e}function tu(e){return!e||e==="never"?[]:Ae(e).filter(t=>t!=="never")}function rr(e){switch(e.type){case"effect":return e.displayName??e.callee;case"generator":return e.name??"generator";case"pipe":return e.name??"pipe";default:return e.name??e.type}}function Pe(e,t,n){for(let r of e){let o=nu(r,n);o&&t.push(o);let s=n;if(r.type==="loop"){s={...s,inLoop:!0,loopType:r.loopType,iterationSource:r.iterSource},Pe([r.body],t,s);continue}if(r.type==="retry"){let i=r.scheduleInfo?{attempts:r.scheduleInfo.maxRetries??"unlimited",backoff:r.scheduleInfo.baseStrategy}:{attempts:"unlimited",backoff:r.schedule??"unknown"};s={...s,inRetry:i},Pe([r.source],t,s);continue}if(r.type==="timeout"){s={...s,inTimeout:{ms:r.duration??"unknown"}},Pe([r.source],t,s);continue}if(r.type==="resource"){r.use&&Pe([r.use],t,n);continue}if(r.type==="error-handler"){Pe([r.source],t,n),r.handler&&Pe([r.handler],t,n);continue}if(r.type==="generator"){let i=r.yields.map(c=>c.effect);Pe(i,t,s);continue}let a=Zd.getOrElse(v(r),()=>[]);a.length>0&&Pe(a,t,s)}}function nu(e,t){switch(e.type){case"effect":{let n=e.typeSignature,r=n?.successType??"unknown",o=n?.errorType??"never";return{stepId:e.id,name:e.displayName??e.callee,callee:e.callee,outputType:r,outputTypeKind:Xd(n),outputTypeDisplay:r,outputTypeText:n?`Effect<${n.successType}, ${n.errorType}, ${n.requirementsType}>`:`Effect<${r}>`,errorTypeDisplay:eu(o),errors:tu(o),depSource:e.serviceCall?.serviceType,stepKind:"effect",...t.inRetry?{retry:t.inRetry}:{},...t.inTimeout?{timeout:t.inTimeout}:{},...t.inLoop?{repeats:"loop",loopType:t.loopType,iterationSource:t.iterationSource}:{}}}case"retry":{let n=e.scheduleInfo?{attempts:e.scheduleInfo.maxRetries??"unlimited",backoff:e.scheduleInfo.baseStrategy}:{attempts:"unlimited",backoff:e.schedule??"unknown"};return{stepId:e.id,name:e.name??"Retry",callee:"Effect.retry",outputType:"void",outputTypeKind:"unknown",outputTypeDisplay:"void",outputTypeText:"retry wrapper",errorTypeDisplay:"never",errors:[],stepKind:"retry",retry:n}}case"timeout":return{stepId:e.id,name:e.name??"Timeout",callee:"Effect.timeout",outputType:"void",outputTypeKind:"unknown",outputTypeDisplay:"void",outputTypeText:"timeout wrapper",errorTypeDisplay:"TimeoutException",errors:["TimeoutException"],stepKind:"timeout",timeout:{ms:e.duration??"unknown"}};case"resource":return{stepId:e.id,name:e.name??"Resource",callee:"Effect.acquireRelease",outputType:"void",outputTypeKind:"unknown",outputTypeDisplay:"void",outputTypeText:"resource lifecycle",errorTypeDisplay:"never",errors:[],stepKind:"resource",kind:"resource",acquire:rr(e.acquire),use:e.use?rr(e.use):void 0,release:rr(e.release)};case"error-handler":{if(e.handlerType==="catchTag"||e.handlerType==="catchTags"){let n=e.errorTags?[...e.errorTags]:e.errorTag?[e.errorTag]:[];return{stepId:e.id,name:e.name??e.handlerType,callee:`Effect.${e.handlerType}`,outputType:"void",outputTypeKind:"unknown",outputTypeDisplay:"void",outputTypeText:`error handler (${e.handlerType})`,errorTypeDisplay:n.join(" | ")||"unknown",errors:n,stepKind:"error-handler"}}return null}default:return null}}function ms(e,t,n){let r=fe(e,{direction:t?.direction??"TB"}),o=[];return Pe(e.root.children,o,{}),{title:e.root.programName,code:n??"",mermaid:r,stepDetails:o}}function ru(e,t,n){return e.map(r=>ms(r,t,n))}import{Option as hs}from"effect";function Mt(e,t){for(let n of e){if(n.type==="effect"){let o=n,s=o.callee.trim();if(s&&!s.startsWith("Effect.")&&!s.includes(".")){let a=o.location?{line:o.location.line,column:o.location.column}:void 0;a?t.push({callee:s,location:a}):t.push({callee:s})}}let r=hs.getOrElse(v(n),()=>[]);r.length>0&&Mt(r,t)}}function or(e,t){for(let n of e){if(n.type==="generator"){for(let o of n.yields)if(o.effect.type==="effect"){let s=o.effect.callee.trim();if(s&&!s.startsWith("Effect.")&&!s.includes(".")){let a=o.effect.location?{line:o.effect.location.line,column:o.effect.location.column}:void 0;t.push({callee:s,isYieldStar:!0,location:a})}}}let r=hs.getOrElse(v(n),()=>[]);r.length>0&&or(r,t)}}function ou(e,t,n={}){let r=new Set(e.map(l=>l.root.programName)),o=e.length>0?e[0]:void 0,s=n.entryProgramName??(o?o.root.programName:""),a={programs:new Map,entryProgram:s,circularDependencies:[],unresolvedReferences:[]};for(let l of e){let f=l.root.programName,u=[];Mt(l.root.children,u);let p=u.filter(m=>r.has(m.callee)&&m.callee!==f).map(m=>m.location?{targetProgram:m.callee,callSite:m.location,resolved:!0}:{targetProgram:m.callee,resolved:!0});for(let m of u)r.has(m.callee)&&m.callee!==f||m.callee.startsWith("Effect.")||m.callee.includes(".")||a.unresolvedReferences.push({programName:m.callee,referencedFrom:f,reason:"Program not found in graph"});let g=[];for(let m of e){if(m.root.programName===f)continue;let h=[];Mt(m.root.children,h),h.some(x=>x.callee===f)&&g.push(m.root.programName)}a.programs.set(f,{name:f,filePath:t,ir:l,calls:p,calledBy:g})}let i=[],c=new Set;function d(l){if(i.includes(l)){let u=i.indexOf(l);a.circularDependencies.push([...i.slice(u),l]);return}if(c.has(l))return;c.add(l),i.push(l);let f=a.programs.get(l);if(f)for(let u of f.calls)u.resolved&&d(u.targetProgram);i.pop()}for(let l of a.programs.keys())d(l);return a}function ys(e){let t=[],n=new Set,r=new Set;function o(s){if(n.has(s)||r.has(s))return;r.add(s);let a=e.programs.get(s);if(a)for(let i of a.calls)i.resolved&&o(i.targetProgram);r.delete(s),n.add(s),t.push(s)}for(let s of e.programs.keys())o(s);return t}function su(e,t){let n=new Set,r=new Set;function o(s){if(r.has(s))return;r.add(s);let a=e.programs.get(s);if(a)for(let i of a.calls)i.resolved&&(n.add(i.targetProgram),o(i.targetProgram))}return o(t),Array.from(n)}function iu(e,t){let n=new Set,r=new Set;function o(s){if(r.has(s))return;r.add(s);let a=e.programs.get(s);if(a)for(let i of a.calledBy)n.add(i),o(i)}return o(t),Array.from(n)}function au(e){let t=0,n=0;for(let s of e.programs.values())t+=Ee(s.ir).cyclomaticComplexity;let r=ys(e),o=new Map;for(let s of r){let a=e.programs.get(s);if(!a)continue;let i=0;for(let c of a.calls)c.resolved&&(i=Math.max(i,(o.get(c.targetProgram)??0)+1));o.set(s,i),n=Math.max(n,i)}return{totalCyclomaticComplexity:t,totalPrograms:e.programs.size,maxDepth:n,hasCircularDependencies:e.circularDependencies.length>0}}function cu(e){let t=[],n=r=>r.replace(/[^a-zA-Z0-9_]/g,"_");t.push("flowchart TD"),t.push(""),t.push(" %% Program Composition Graph"),t.push("");for(let[r]of e.programs){let s=r===e.entryProgram?`${n(r)}[["${r}"]]
|
|
534
|
+
`:` ${n(r)}["${r}"]`;t.push(s.startsWith(" ")?s:` ${s}`)}t.push("");for(let[,r]of e.programs)for(let o of r.calls)if(o.resolved){let s=o.callSite?`L${o.callSite.line}`:"";s?t.push(` ${n(r.name)} -->|${s}| ${n(o.targetProgram)}`):t.push(` ${n(r.name)} --> ${n(o.targetProgram)}`)}if(t.push(""),t.push(" classDef entryPoint fill:#C8E6C9,stroke:#2E7D32,stroke-width:3px"),t.push(` class ${n(e.entryProgram)} entryPoint`),e.circularDependencies.length>0){t.push(" classDef cyclic fill:#FFCDD2,stroke:#C62828,stroke-width:2px");let r=new Set;for(let o of e.circularDependencies)for(let s of o)r.add(s);for(let o of r)t.push(` class ${n(o)} cyclic`)}return t.join(`
|
|
535
|
+
`)}function lu(e){let t=[],n=s=>s.replace(/[^a-zA-Z0-9_]/g,"_");t.push("flowchart TD"),t.push("");let r=new Map;for(let[,s]of e.programs){let a=r.get(s.filePath)??[];a.push(s),r.set(s.filePath,a)}let o=0;for(let[s,a]of r){let i=s.split("/").pop()??s;t.push(` subgraph file${o}["${i}"]`);for(let c of a)c.name===e.entryProgram?t.push(` ${n(c.name)}[["${c.name}"]]`):t.push(` ${n(c.name)}["${c.name}"]`);t.push(" end"),t.push(""),o++}for(let[,s]of e.programs)for(let a of s.calls)if(a.resolved){let i=a.callSite?`yield* L${a.callSite.line}`:"yield*";t.push(` ${n(s.name)} -->|${i}| ${n(a.targetProgram)}`)}if(e.unresolvedReferences.length>0){t.push(""),t.push(" %% Unresolved references");for(let s of e.unresolvedReferences){let a=`unresolved_${n(s.programName)}`;t.push(` ${a}["? ${s.programName}"]`),t.push(` ${n(s.referencedFrom)} -.-> ${a}`)}t.push(" classDef unresolved fill:#FFF3CD,stroke:#856404,stroke-dasharray:5");for(let s of e.unresolvedReferences)t.push(` class unresolved_${n(s.programName)} unresolved`)}return t.join(`
|
|
536
|
+
`)}function du(e,t={},n){let r=new Set,o=new Map,s=new Map;for(let[u,p]of e)for(let g of p){let m=g.root.programName;r.add(m),o.set(m,u),s.set(m,g)}let a=r.values().next().value,i=t.entryProgramName??a??"",c={programs:new Map,entryProgram:i,circularDependencies:[],unresolvedReferences:[]};for(let[u,p]of s){let g=o.get(u)??"",m=[];Mt(p.root.children,m);let h=[];or(p.root.children,h);for(let N of h)if(!m.some(E=>E.callee===N.callee)){let E={callee:N.callee};N.location&&(E.location=N.location),m.push(E)}let x=m.filter(N=>r.has(N.callee)&&N.callee!==u).map(N=>N.location?{targetProgram:N.callee,callSite:N.location,resolved:!0}:{targetProgram:N.callee,resolved:!0}),T=n?new Set(n.services.keys()):new Set;for(let N of m)r.has(N.callee)&&N.callee!==u||N.callee.startsWith("Effect.")||N.callee.includes(".")||N.callee!==u&&(T.has(N.callee)||c.unresolvedReferences.push({programName:N.callee,referencedFrom:u,reason:"Program not found in project"}));let S=[];for(let[N,E]of s){if(N===u)continue;let y=[];Mt(E.root.children,y);let C=[];or(E.root.children,C),(y.some(w=>w.callee===u)||C.some(w=>w.callee===u))&&S.push(N)}c.programs.set(u,{name:u,filePath:g,ir:p,calls:x,calledBy:S})}let d=[],l=new Set;function f(u){if(d.includes(u)){let g=d.indexOf(u);c.circularDependencies.push([...d.slice(g),u]);return}if(l.has(u))return;l.add(u),d.push(u);let p=c.programs.get(u);if(p)for(let g of p.calls)g.resolved&&f(g.targetProgram);d.pop()}for(let u of c.programs.keys())f(u);return c}function uu(e,t){let n=[],r=o=>o.replace(/[^a-zA-Z0-9_]/g,"_");n.push("flowchart TD"),n.push(""),n.push(" %% Programs");for(let[o]of e.programs)o===e.entryProgram?n.push(` ${r(o)}[["${o}"]]`):n.push(` ${r(o)}["${o}"]`);n.push(""),n.push(" %% Services");for(let[o]of t.services)n.push(` svc_${r(o)}{{{"${o}"}}}`);n.push(""),n.push(" %% Program calls");for(let[,o]of e.programs)for(let s of o.calls)if(s.resolved){let a=s.callSite?`yield* L${s.callSite.line}`:"yield*";n.push(` ${r(o.name)} -->|${a}| ${r(s.targetProgram)}`)}n.push(""),n.push(" %% Service dependencies");for(let[o,s]of t.services)for(let a of s.consumers)e.programs.has(a.programName)&&n.push(` ${r(a.programName)} -.->|yield*| svc_${r(o)}`);n.push(""),n.push(" %% Service layer dependencies");for(let[o,s]of t.services)for(let a of s.dependencies)t.services.has(a)&&n.push(` svc_${r(o)} -.-> svc_${r(a)}`);n.push(""),n.push(" classDef entryPoint fill:#C8E6C9,stroke:#2E7D32,stroke-width:3px"),n.push(" classDef service fill:#E3F2FD,stroke:#1565C0,stroke-width:2px"),n.push(` class ${r(e.entryProgram)} entryPoint`);for(let o of t.services.keys())n.push(` class svc_${r(o)} service`);return n.join(`
|
|
537
|
+
`)}import{Option as fu}from"effect";function pu(e){return e.startsWith("Ref.")||e.startsWith("FiberRef.")||e.startsWith("SynchronizedRef.")}function gu(e){return e.includes("getAndUpdate")?"getAndUpdate":e.includes("getAndSet")?"getAndSet":e.includes("modify")?"modify":e.includes("update")?"update":e.includes(".set")?"set":e.includes(".get")?"get":e.includes("make")||e.includes("unsafeMake")?"make":"get"}function mu(e){return e.startsWith("Ref.")?"Ref":e.startsWith("FiberRef.")?"FiberRef":e.startsWith("SynchronizedRef.")?"SynchronizedRef":"Ref"}var hu=new Set(["set","update","modify","getAndSet","getAndUpdate"]);function yu(e){let t=[],n=[],r=new Map,o=new Map;function s(c){for(let d of c){if(d.type==="effect"){let f=d,u=f.callee;if(pu(u)){let p=mu(u),g=gu(u),m={refId:p,operation:g,nodeId:f.id};if(f.location&&(m.location={line:f.location.line,column:f.location.column}),t.push(m),hu.has(g)){n.push({refId:p,nodeId:f.id,operation:g});let h=o.get(p)??[];h.push(f.id),o.set(p,h)}else if(g==="get"){let h=r.get(p)??[];h.push(f.id),r.set(p,h)}}}let l=fu.getOrElse(v(d),()=>[]);l.length>0&&s(l)}}s(e.root.children);let a=Array.from(new Set([...r.keys(),...o.keys()])).map(c=>({refId:c,readers:r.get(c)??[],writers:o.get(c)??[]})),i=[];for(let{refId:c,readers:d,writers:l}of a)d.length>0&&l.length>0&&i.push({refId:c,readerIds:d,writerIds:l,message:`Ref "${c}" has concurrent readers and writers - consider Ref.modify for atomic updates`});return{refs:t,mutations:n,potentialRaces:i,stateGraph:a}}import{Option as Su}from"effect";function xu(e){let t=[],n=[],r=[],o=[];function s(a){for(let i of a){if(i.type==="effect"){let d=i,l=d.callee;if(l.includes("acquireRelease")||l.includes("acquireUseRelease")){let f={nodeId:d.id,type:l.includes("acquireUseRelease")?"acquireUseRelease":"acquireRelease"};d.location&&(f.location={line:d.location.line,column:d.location.column}),t.push(f)}else if(l.includes("Effect.scoped")){let f={nodeId:d.id,type:"scoped"};d.location&&(f.location={line:d.location.line,column:d.location.column}),n.push(f)}else if(l.startsWith("Scope.")){if(l.includes("make")){let f={nodeId:d.id,type:"scopeMake"};d.location&&(f.location={line:d.location.line,column:d.location.column}),n.push(f)}else if(l.includes("use")){let f={nodeId:d.id,type:"scopeUse"};d.location&&(f.location={line:d.location.line,column:d.location.column}),n.push(f)}else if(l.includes("fork")){let f={nodeId:d.id,type:"scopeFork"};d.location&&(f.location={line:d.location.line,column:d.location.column}),n.push(f)}else if(l.includes("addFinalizer")){let f={nodeId:d.id,type:"scopeAddFinalizer"};d.location&&(f.location={line:d.location.line,column:d.location.column}),n.push(f)}else if(l.includes("extend")){let f={nodeId:d.id,type:"scopeExtend"};d.location&&(f.location={line:d.location.line,column:d.location.column}),n.push(f)}}else(l.startsWith("Pool.")||l.startsWith("KeyedPool."))&&r.push(d.id)}else if(i.type==="resource"){let d=i,l={nodeId:i.id,type:"acquireRelease",acquireNodeId:d.acquire.id,releaseNodeId:d.release.id};i.location&&(l.location={line:i.location.line,column:i.location.column}),t.push(l)}let c=Su.getOrElse(v(i),()=>[]);c.length>0&&s(c)}}return s(e.root.children),{acquisitions:t,scopeBoundaries:n,poolCreations:r,potentialLeaks:o}}import{Option as Ss}from"effect";function xs(e){return e.includes("withSpan")||e.includes("Tracer.span")||e.includes("annotateCurrentSpan")||e.includes("annotateSpans")||e.includes("makeSpan")||e.includes("makeSpanScoped")||e.includes("useSpan")||e.includes("withParentSpan")||e.includes("linkSpans")||e.includes("linkSpanCurrent")||e.includes("functionWithSpan")||e.includes("currentSpan")||e.includes("currentParentSpan")||e.includes("withTracerEnabled")||e.includes("withTracerTiming")||e.includes("span(")}function Es(e){return e.includes("Effect.log")||e.includes("Logger.add")||e.includes("Logger.replace")||e.includes("Logger.batched")||e.includes("Logger.withLeveledConsole")||e.includes("Logger.json")||e.includes("Logger.logFmt")||e.includes("Logger.pretty")||e.includes("Logger.structured")}function Eu(e){return e.includes("logDebug")||e.includes("Debug")?"debug":e.includes("logWarning")||e.includes("Warning")?"warning":e.includes("logError")||e.includes("Error")?"error":"info"}function bs(e){return e.startsWith("Metric.")||e.includes(".track")}function bu(e){return e.includes("counter")||e.includes("increment")||e.includes("frequency")?"counter":e.includes("gauge")||e.includes(".set")?"gauge":e.includes("histogram")?"histogram":e.includes("summary")?"summary":e.includes("timer")||e.includes("trackDuration")?"timer":"counter"}function Cu(e){let t=[],n=[],r=[],o=0,s=0,a=0,i=0,c=0;function d(l,f,u){for(let p of l){if(p.type==="effect"){let S=p,N=S.callee??"";if(o++,xs(N)){let E={nodeId:S.id};S.location&&(E.location={line:S.location.line,column:S.location.column}),t.push(E)}if(f&&s++,Es(N)){let E={nodeId:S.id,level:Eu(N)};S.location&&(E.location={line:S.location.line,column:S.location.column}),n.push(E)}if(bs(N)){let E=N.includes("tagged")||N.includes("taggedWith"),y={nodeId:S.id,type:bu(N),...E?{isTagged:!0}:{}};S.location&&(y.location={line:S.location.line,column:S.location.column}),r.push(y)}u&&a++}if(p.type==="error-handler"){c++;let S=p;if(S.handler){let N=!1,E=y=>{if(y.type==="effect"){let w=y.callee??"";Es(w)&&(N=!0)}Ss.getOrElse(v(y),()=>[]).forEach(E)};E(S.handler),N&&i++}}let g=Ss.getOrElse(v(p),()=>[]),m=p.type==="effect"&&xs(p.callee??""),h=p.type==="effect"&&bs(p.callee??""),x=f||m,T=u||h;g.length>0&&d(g,x,T)}}return d(e.root.children,!1,!1),{spans:t,logPoints:n,metrics:r,coverage:{effectCount:o,effectsWithSpans:s,effectsWithMetrics:a,errorHandlersWithLogging:i,errorHandlerCount:c}}}import{Option as Nu}from"effect";function Tu(e){let t=new Map,n=new Map;for(let a of e.layers)for(let i of a.provides){let c=n.get(i)??[];c.push(a.id),n.set(i,c)}for(let a of e.layers){let i=[];for(let c of a.requires)for(let d of n.get(c)??[])d!==a.id&&i.push(d);t.set(a.id,i)}let r=new Set,o=new Set,s=a=>{if(r.has(a))return!0;if(o.has(a))return!1;r.add(a);for(let i of t.get(a)??[])if(s(i))return!0;return r.delete(a),o.add(a),!1};for(let a of t.keys())if(s(a))return!1;return!0}function vu(e){let t=$t(e),n=Qe(e),r=new Map;for(let u of n.layers)for(let p of u.provides)r.set(p,u.id);let o=t.requiredServices.map(u=>u.serviceId),s=[],a=!0;for(let u of o){let p=r.get(u);p?s.push({serviceId:u,status:"ok",providedBy:p,message:`provided by ${p}`}):(a=!1,s.push({serviceId:u,status:"missing",message:"NO PROVIDER FOUND"}))}let i=Tu(n),c=new Map;for(let u of n.layers)for(let p of u.provides){let g=c.get(p)??[];g.push(u.id),c.set(p,g)}let d=new Map,l=u=>{for(let p of u){p.type==="layer"&&p.location&&d.set(p.id,p.location);let g=Nu.getOrElse(v(p),()=>[]);g.length>0&&l(g)}};l(e.root.children);let f=[];for(let[u,p]of c)if(p.length>1){let g=p.map(m=>d.get(m)).filter(m=>m!==void 0);f.push({serviceId:u,providers:g})}return{programName:e.root.programName,requiredServices:o,providedByLayer:r,entries:s,layerGraphAcyclic:i,valid:a,...f.length>0?{layerConflicts:f}:{}}}function wu(e){let t=[];t.push(`Service Completeness Report for ${e.programName}:`);for(let n of e.entries){let r=n.status==="ok"?"\u2713":"\u2717",o=n.providedBy?` \u2192 provided by ${n.providedBy}`:"";t.push(` ${r} ${n.serviceId}${o} ${n.status==="missing"?n.message:""}`)}return t.push(""),t.push(e.valid?"All required services have providers.":"Some required services have no provider."),t.join(`
|
|
538
|
+
`)}import{Option as mt}from"effect";var ku={requireErrors:!0,requireParallelErrors:!0,warningsAsErrors:!1};function Iu(e,t={}){let n={...ku,...t,requireErrors:t.requireErrors??!0,requireParallelErrors:t.requireParallelErrors??!0,warningsAsErrors:t.warningsAsErrors??!1},r=[];Cs(e.root.children,n,r,!1),Ns(e.root.children,r,new Set),Ts(e.root.children,r,!1),vs(e.root.children,r),ws(e.root.children,r),Au(e,r);let o=r.filter(a=>a.severity==="error"||n.warningsAsErrors&&a.severity==="warning"),s=r.filter(a=>a.severity==="warning"&&!n.warningsAsErrors);return{valid:o.length===0,diagnostics:r,errors:o,warnings:s}}function Cs(e,t,n,r=!1){for(let o of e){let s=r||o.type==="error-handler";if(o.type==="effect"){let i=o;Fu(i,t,n);let c=i.typeSignature?.errorType?.trim();c&&c!=="never"&&!r&&n.push({rule:"effect-without-handler",severity:"warning",message:`Effect "${i.callee}" can fail with "${c}" but has no error handler (catchAll/catchTag/orElse) on this path`,fix:"Wrap in .pipe(Effect.catchAll(...)) or handle errors before this point",location:i.location,nodeId:i.id})}if(o.type==="parallel"&&t.requireParallelErrors){for(let i of o.children)if(i.type==="effect"){let c=i,d=c.typeSignature?.errorType;(!d||d==="unknown"||d.trim()==="")&&n.push({rule:"parallel-missing-errors",severity:"warning",message:`Parallel branch effect "${c.callee}" does not declare error type`,fix:"Add type signature or use Effect.mapError/catchTag to narrow errors",location:c.location,nodeId:c.id})}}if(o.type==="race"&&t.requireParallelErrors){for(let i of o.children)if(i.type==="effect"){let c=i,d=c.typeSignature?.errorType;(!d||d==="unknown"||d.trim()==="")&&n.push({rule:"race-missing-errors",severity:"warning",message:`Race branch effect "${c.callee}" does not declare error type`,fix:"Add type signature or use Effect.mapError/catchTag to narrow errors",location:c.location,nodeId:c.id})}}let a=mt.getOrElse(v(o),()=>[]);a.length>0&&Cs(a,t,n,s)}}function Ns(e,t,n){for(let r of e){if(r.type==="fiber"){let s=r;(s.operation==="fork"||s.operation==="forkAll")&&!s.isScoped&&!s.isDaemon&&!n.has("join")&&!n.has("interrupt")&&!n.has("await")&&t.push({rule:"fiber-potential-leak",severity:"warning",message:`Fiber.${s.operation} without join/interrupt in scope \u2014 potential fiber leak`,fix:"Use Fiber.join, Fiber.interrupt, or forkScoped instead",location:s.location,nodeId:s.id}),(s.operation==="join"||s.operation==="interrupt"||s.operation==="await")&&n.add(s.operation)}let o=mt.getOrElse(v(r),()=>[]);o.length>0&&Ns(o,t,n)}}function Ts(e,t,n){for(let r of e){r.type==="resource"&&!n&&t.push({rule:"resource-missing-scope",severity:"warning",message:"acquireRelease without visible Effect.scoped in scope",fix:"Wrap resource usage in Effect.scoped",location:r.location,nodeId:r.id});let o=r.type==="effect"&&r.callee==="Effect.scoped",s=mt.getOrElse(v(r),()=>[]);s.length>0&&Ts(s,t,n||o)}}function vs(e,t){for(let n of e){if(n.type==="parallel"&&n.children.length>5){let o=n.callee||"";(o.includes("all")||o.includes("forEach"))&&t.push({rule:"unbounded-concurrency",severity:"warning",message:`${o} with ${n.children.length} children \u2014 consider adding { concurrency } option`,fix:"Add { concurrency: N } to limit concurrent execution",location:n.location,nodeId:n.id})}n.type==="loop"&&(n.loopType==="forEach"||n.loopType==="validate")&&t.push({rule:"unbounded-concurrency",severity:"warning",message:`Effect.${n.loopType} may run unbounded \u2014 consider concurrency control`,fix:"Add { concurrency: N } option",location:n.location,nodeId:n.id});let r=mt.getOrElse(v(n),()=>[]);r.length>0&&vs(r,t)}}function ws(e,t){for(let n of e){if(n.type==="decision"){let o=n.label.trim();(o==="true"||o==="false")&&t.push({rule:"dead-code-path",severity:"warning",message:`Decision "${n.condition}" always resolves to ${o} \u2014 ${o==="true"?"false":"true"} branch is dead code`,fix:"Remove the dead branch or fix the condition",location:n.location,nodeId:n.id})}let r=mt.getOrElse(v(n),()=>[]);r.length>0&&ws(r,t)}}function Au(e,t){let n=Qe(e);if(n.layers.length===0)return;let r=new Set;for(let o of n.layers)for(let s of o.requires)r.add(s);ks(e.root.children,r);for(let o of n.layers)for(let s of o.provides)r.has(s)||t.push({rule:"unused-service",severity:"warning",message:`Service "${s}" is provided by layer "${o.name??o.id}" but never consumed`,fix:"Remove unused service provision or add a consumer",nodeId:o.id})}function ks(e,t){for(let n of e){if(n.type==="effect"){let o=n.requiredServices??[];for(let s of o)t.add(s.serviceId)}let r=mt.getOrElse(v(n),()=>[]);r.length>0&&ks(r,t)}}function Fu(e,t,n){if(!t.requireErrors)return;let r=e.typeSignature?.errorType;if(!r){n.push({rule:"missing-error-type",severity:"warning",message:`Effect "${e.callee}" has no extracted error type`,fix:"Ensure type checker can infer Effect<A, E, R> or add explicit type",location:e.location,nodeId:e.id});return}r.trim()==="unknown"&&n.push({rule:"unknown-error-type",severity:"warning",message:`Effect "${e.callee}" has error type "unknown"`,fix:"Use a concrete error type or branded errors for better validation",location:e.location,nodeId:e.id})}function Ru(e){let t=[];e.valid?(t.push("All strict mode checks passed"),e.warnings.length>0&&t.push(` (${e.warnings.length} warning${e.warnings.length===1?"":"s"})`)):t.push(`Strict validation failed: ${e.errors.length} error(s)`),t.push("");for(let n of e.diagnostics){let r=n.severity==="error"?"x":"!",o=n.location?`:${n.location.line}:${n.location.column}`:"";t.push(`[${r}] [${n.rule}]${o}`),t.push(` ${n.message}`),n.fix&&t.push(` Fix: ${n.fix}`),t.push("")}return t.join(`
|
|
539
|
+
`)}function $u(e){return JSON.stringify({valid:e.valid,errorCount:e.errors.length,warningCount:e.warnings.length,diagnostics:e.diagnostics.map(t=>({rule:t.rule,severity:t.severity,message:t.message,fix:t.fix,location:t.location?{line:t.location.line,column:t.location.column}:void 0,nodeId:t.nodeId}))},null,2)}function Du(e){return e.valid&&e.warnings.length===0?"All strict mode checks passed":e.valid?`Passed with ${e.warnings.length} warning(s)`:`${e.errors.length} error(s), ${e.warnings.length} warning(s)`}var Pu={testNamePrefix:"should",testNameGenerator:Wu,includeLoopPaths:!0};function Lu(e,t={}){let n={...Pu,...t},r=e;n.includeLoopPaths||(r=e.filter(i=>!i.hasLoops));let o=r.map(i=>Mu(i,n)),s=qu(r),a=_u(o,s);return{paths:o,conditions:s,summary:a}}function Mu(e,t){let n=t.testNameGenerator(e),r=Ou(e),o=e.conditions.map(a=>{let i=a.mustBe?"be truthy":"be falsy";return`Set up ${a.expression} to ${i}`}),s=e.steps.map(a=>{let i=a.name??a.nodeId;return a.repeated?`${i} (may repeat)`:i});return{id:e.id,suggestedTestName:n,description:e.description,setupConditions:o,expectedSteps:s,priority:r}}function Ou(e){return e.conditions.length===0&&!e.hasLoops?"high":e.hasLoops&&e.conditions.length>2?"low":"medium"}function Wu(e){let t=["should"];if(e.steps.length>0){let n=e.steps.filter(r=>!r.repeated).slice(0,3);if(n.length>0){let r=n.map(o=>Ku(o.name??o.nodeId));t.push(r.join(" then "))}}if(e.conditions.length>0){t.push("when");let n=e.conditions.slice(0,2).map(r=>{let o=Bu(r.expression);return r.mustBe?o:`not ${o}`});t.push(n.join(" and "))}return e.hasLoops&&t.push("(with iteration)"),t.join(" ")}function Ku(e){return e.replace(/([a-z])([A-Z])/g,"$1 $2").replace(/([A-Z])([A-Z][a-z])/g,"$1 $2").toLowerCase()}function Bu(e){return e.replace(/\s*===\s*true/g,"").replace(/\s*===\s*false/g," is false").replace(/\s*===\s*/g," is ").replace(/\s*!==\s*/g," is not ").replace(/\s*>\s*/g," greater than ").replace(/\s*<\s*/g," less than ").replace(/\s*>=\s*/g," at least ").replace(/\s*<=\s*/g," at most ").replace(/&&/g," and ").replace(/\|\|/g," or ").trim()}function qu(e){let t=new Map;for(let n of e)for(let r of n.conditions){let o=r.expression;t.has(o)||t.set(o,{whenTrue:[],whenFalse:[]});let s=t.get(o);s&&(r.mustBe?s.whenTrue.push(n.id):s.whenFalse.push(n.id))}return Array.from(t.entries()).map(([n,r])=>({expression:n,affectedPathsWhenTrue:r.whenTrue,affectedPathsWhenFalse:r.whenFalse}))}function _u(e,t){let n=e.filter(o=>o.priority==="high").length,r=Math.max(1,t.length*2);return{totalPaths:e.length,highPriorityPaths:n,totalConditions:t.length,minTestsForCoverage:r}}function ju(e){let t=[];t.push("# Test Coverage Matrix"),t.push(""),t.push("## Summary"),t.push(""),t.push(`- **Total Paths:** ${e.summary.totalPaths}`),t.push(`- **High Priority Paths:** ${e.summary.highPriorityPaths}`),t.push(`- **Conditions to Test:** ${e.summary.totalConditions}`),t.push(`- **Minimum Tests for Coverage:** ${e.summary.minTestsForCoverage}`),t.push(""),t.push("## Test Cases"),t.push("");let n=e.paths.filter(s=>s.priority==="high"),r=e.paths.filter(s=>s.priority==="medium"),o=e.paths.filter(s=>s.priority==="low");if(n.length>0){t.push("### High Priority"),t.push("");for(let s of n)t.push(...sr(s));t.push("")}if(r.length>0){t.push("### Medium Priority"),t.push("");for(let s of r)t.push(...sr(s));t.push("")}if(o.length>0){t.push("### Low Priority"),t.push("");for(let s of o)t.push(...sr(s));t.push("")}if(e.conditions.length>0){t.push("## Conditions Coverage"),t.push(""),t.push("| Condition | Paths When True | Paths When False |"),t.push("|-----------|-----------------|------------------|");for(let s of e.conditions){let a=s.expression.length>40?s.expression.slice(0,40)+"...":s.expression,i=s.affectedPathsWhenTrue.length,c=s.affectedPathsWhenFalse.length;t.push(`| \`${a}\` | ${i} | ${c} |`)}t.push("")}t.push("## Test Checklist"),t.push("");for(let s of e.paths){let a=s.priority==="high"?"HIGH":s.priority==="medium"?"MED":"LOW";t.push(`- [ ] [${a}] ${s.suggestedTestName}`)}return t.push(""),t.join(`
|
|
540
|
+
`)}function sr(e){let t=[];if(t.push(`#### ${e.suggestedTestName}`),t.push(""),e.setupConditions.length>0){t.push("**Setup:**");for(let n of e.setupConditions)t.push(`- ${n}`);t.push("")}t.push("**Expected Steps:**");for(let n=0;n<e.expectedSteps.length;n++)t.push(`${n+1}. ${e.expectedSteps[n]}`);return t.push(""),t}function zu(e,t={}){let n=t.testRunner??"vitest",r=t.programName??"program",o=[];n==="vitest"?o.push("import { describe, it, expect } from 'vitest';"):n==="jest"?o.push("// Jest test file"):(o.push("import { describe, it } from 'mocha';"),o.push("import { expect } from 'chai';")),o.push(""),o.push(`describe('${r}', () => {`);for(let s of e.paths){o.push(""),o.push(` it('${Hu(s.suggestedTestName)}', async () => {`),o.push(" // Setup");for(let a of s.setupConditions)o.push(` // TODO: ${a}`);o.push(""),o.push(" // Execute effect program"),o.push(` // const result = await Effect.runPromise(${r});`),o.push(""),o.push(" // Verify expected steps executed");for(let a of s.expectedSteps)o.push(` // TODO: Verify ${a} was executed`);o.push(" });")}return o.push("});"),o.push(""),o.join(`
|
|
541
|
+
`)}function Hu(e){return e.replace(/'/g,"\\'").replace(/"/g,'\\"')}function Uu(e){let t=[];t.push("Test Coverage Checklist"),t.push("======================="),t.push(""),t.push(`Total: ${e.summary.totalPaths} tests needed`),t.push(`High Priority: ${e.summary.highPriorityPaths}`),t.push("");for(let n of e.paths){let r=n.priority==="high"?"***":n.priority==="medium"?"**":"*";t.push(`[ ] ${r} ${n.suggestedTestName}`),n.setupConditions.length>0&&t.push(` Conditions: ${n.setupConditions.join(", ")}`)}return t.join(`
|
|
542
|
+
`)}import{Project as Vu,SyntaxKind as Gu}from"ts-morph";function Ju(e,t,n){let{line:r,column:o}=n.getLineAndColumnAtPos(t.getStart());return{filePath:e,line:r+1,column:o}}function Yu(e,t){let n=new Vu({useInMemoryFileSystem:!0}),r=t?n.createSourceFile(e,t):n.addSourceFileAtPath(e),o=[],s=[],a=[],i=[],c=new Map,d=[];for(let l of r.getDescendantsOfKind(Gu.CallExpression)){let u=l.getExpression().getText(),p=Ju(e,l,r),h=l.getArguments()[0]?.getText().replace(/["'`]/g,"").trim()??"unknown",x=l.getParent()?.getText()??"",T=x.includes("withDefault"),S=h.toUpperCase().replace(/[^A-Z0-9]/g,"_");c.set(h,S);let N=u.includes("Config.nonEmptyString")||u.includes("Config.string")?"string":u.includes("Config.integer")?"integer":u.includes("Config.number")?"number":u.includes("Config.boolean")?"boolean":u.includes("Config.date")?"date":u.includes("Config.duration")?"duration":u.includes("Config.url")?"url":u.includes("Config.port")?"port":u.includes("Config.logLevel")?"logLevel":u.includes("Config.literal")?"literal":u.includes("Config.array")||u.includes("Config.chunk")?"array":u.includes("Config.hashSet")||u.includes("Config.hashMap")?"map":u.includes("Config.nested")||u.includes("Config.all")?"nested":void 0;if(N!==void 0){let y={key:h,type:N,required:!T,hasDefault:T,location:p};T||x.includes("Config.option")?s.push(y):o.push(y)}else(u==="Config.secret"||u==="Config.redacted"||u.includes("Config.secret")||u.includes("Config.redacted"))&&a.push({key:h,type:"secret",required:!0,hasDefault:!1,location:p});(u.includes("Effect.withConfigProvider")||u.includes("Layer.setConfigProvider"))&&i.push(u);let E=[["Config.mapOrFail","mapOrFail"],["Config.mapAttempt","mapAttempt"],["Config.map","map"],["Config.orElseIf","orElseIf"],["Config.orElse","orElse"],["Config.withDefault","withDefault"],["Config.withDescription","withDescription"],["Config.validate","validate"],["Config.repeat","repeat"],["Config.option","option"]];for(let[y,C]of E)if(u===y||u.startsWith(y+"(")||u.startsWith(y+"<")){d.push({kind:C,location:p});break}}return{requiredConfigs:o,optionalConfigs:s,secretConfigs:a,providerOverrides:[...new Set(i)],envVarHints:c,combinators:d}}function Qu(e){let t=["| Config Key | Type | Required | Default | Secret |","|------------|------|----------|---------|--------|"],n=[...e.requiredConfigs,...e.optionalConfigs,...e.secretConfigs],r=new Set;for(let o of n){if(r.has(o.key))continue;r.add(o.key);let s=o.required?"yes":"no",a=o.hasDefault?"yes":"-",i=e.secretConfigs.some(c=>c.key===o.key)?"yes":"no";t.push(`| ${o.key} | ${o.type} | ${s} | ${a} | ${i} |`)}if(t.push(""),t.push(`Total: ${r.size} config key(s)`),e.providerOverrides.length>0&&t.push(`Config providers: ${e.providerOverrides.length}`),e.combinators.length>0){let o=new Map;for(let a of e.combinators)o.set(a.kind,(o.get(a.kind)??0)+1);let s=Array.from(o.entries()).map(([a,i])=>`${a}(\xD7${i})`).join(", ");t.push(`Config combinators: ${s}`)}return t.join(`
|
|
543
|
+
`)}import{Project as Zu,SyntaxKind as Xu}from"ts-morph";function ir(e,t,n){let{line:r,column:o}=n.getLineAndColumnAtPos(t.getStart());return{filePath:e,line:r+1,column:o}}function ef(e,t){let n=new Zu({useInMemoryFileSystem:!0}),r=t?n.createSourceFile(e,t):n.addSourceFileAtPath(e),o=[],s=[];for(let a of r.getDescendantsOfKind(Xu.CallExpression)){let c=a.getExpression().getText();if(c.includes("Match")&&(c.includes("Match.type")||c.includes("Match.tag")||c.includes("Match.value"))){let l=a.getParent()?.getText()??"",f=[],u=l.includes(".exhaustive("),p=l.includes(".orElse(");if(l.includes("Match.tag(")){let m=/Match\.tag\s*\(\s*["'](\w+)["']/.exec(l);if(m){let h=m[1],x=h!==void 0?{kind:"tag",tag:h,location:ir(e,a,r)}:{kind:"tag",location:ir(e,a,r)};f.push(x)}}u&&f.push({kind:"exhaustive"}),p&&f.push({kind:"orElse"});let g={location:ir(e,a,r),arms:f,hasExhaustive:u,hasOrElse:p};o.push(g),!u&&!p&&s.push(g)}}return{matchSites:o,nonExhaustive:s}}import{Project as tf,SyntaxKind as ar}from"ts-morph";function et(e,t,n){let{line:r,column:o}=n.getLineAndColumnAtPos(t.getStart());return{filePath:e,line:r+1,column:o}}function nf(e){let r=e.getText().replace(/\$\{HttpApiSchema\.param\s*\(\s*["'](\w+)["'][^}]*\)\}/g,":$1").replace(/\$\{[^}]*\}/g,":param").replace(/^`|`$/g,"").trim();return r.startsWith("/")?r:`/${r}`}function rf(e){let t,n,r=e;for(let s=0;s<20;s++){let a=r.getParent();if(!a)break;if(a.getKind()===ar.CallExpression){let i=a,c=i.getExpression().getText();if(c.endsWith(".add")&&i.getArguments().length>0){let l=c.slice(0,-4),f=/HttpApi\.make\s*\(\s*["']([^"']+)["']/.exec(l);f&&(t=f[1]);let u=/HttpApiGroup\.make\s*\(\s*["']([^"']+)["']/.exec(l);u&&(n=u[1])}}r=a}let o={};return t!==void 0&&(o.apiId=t),n!==void 0&&(o.groupName=n),o}function of(e,t){let n=new tf({useInMemoryFileSystem:!0}),r=t?n.createSourceFile(e,t):n.addSourceFileAtPath(e),o=new Map,s={client:!1,server:!1,routes:[],api:!1,apiBuilder:!1,endpoint:!1,security:!1,middleware:!1},a={reads:[],writes:[]},i=!1,c=!1,d=!1,l=[],f=!1,u=!1,p=[],g=!1,m=[],h=[],x=[],T=[],S=[],N=[];for(let E of r.getDescendantsOfKind(ar.CallExpression)){let y=E.getExpression().getText();if((y.includes("HttpClient")||y.includes("HttpServer")||y.includes("HttpRouter")||y.includes("HttpApi")||y.includes("HttpApiBuilder")||y.includes("HttpApiEndpoint")||y.includes("HttpApiGroup")||y.includes("HttpApiSecurity")||y.includes("HttpApiClient"))&&((y.includes("HttpClient")||y.includes("HttpApiClient"))&&(s.client=!0),s.server=s.server||y.includes("HttpServer")||y.includes("HttpRouter"),s.api=s.api||y.includes("HttpApi")&&!y.includes("HttpApiBuilder")&&!y.includes("HttpApiEndpoint")&&!y.includes("HttpApiGroup")&&!y.includes("HttpApiSecurity")&&!y.includes("HttpApiClient"),s.apiBuilder=s.apiBuilder||y.includes("HttpApiBuilder"),s.endpoint=s.endpoint||y.includes("HttpApiEndpoint")||y.includes("HttpApiGroup"),s.security=s.security||y.includes("HttpApiSecurity"),s.middleware=s.middleware||y.includes("middleware")||y.includes("Middleware"),(y.includes("route")||y.includes(".get")||y.includes(".post")||y.includes(".put")||y.includes(".delete")||y.includes(".patch"))&&s.routes.push(y),o.set("http",et(e,E,r))),y.includes("FileSystem")){y.includes("read")&&a.reads.push(y),y.includes("write")&&a.writes.push(y),o.set("filesystem",et(e,E,r));let C={readFile:"read",readFileString:"read",writeFile:"write",writeFileString:"write",remove:"delete",mkdir:"mkdir",stat:"stat",copy:"copy",rename:"rename",readDirectory:"readDir"};for(let[w,b]of Object.entries(C))if(y.includes(w)){h.push({op:b,location:et(e,E,r)});break}}if((y.includes("Socket")||y.includes("fromNetServer"))&&(i=!0),y.includes("Terminal")&&(c=!0),y.includes("Worker")&&(d=!0),y.includes("Command.")){l.push(y);let C={make:"make",start:"start",stdin:"stdin",stdout:"stdout",stderr:"stderr",exitCode:"exitCode"};for(let[w,b]of Object.entries(C))if(y.includes(w)){x.push({op:b,location:et(e,E,r)});break}}if(y.includes("KeyValueStore")&&(f=!0),y.includes("Multipart")&&(u=!0),(y.includes("Ndjson")||y.includes("MsgPack")||y.includes("Effectify"))&&p.push(y),(y.includes("OpenApi")||y.includes("OpenApiJsonSchema"))&&(g=!0),y.includes("HttpApiEndpoint")){let C=["get","post","put","delete","patch","head","options"];for(let w of C)if(y.includes(`.${w}`)){let b=E.getArguments(),F=(b.length>0?b[0]?.getText().replace(/["'`]/g,""):"unnamed")??"unnamed",O="/";if(b.length>=2)O=b[1]?.getText().replace(/["'`]/g,"")??"/";else{let W=E.getParent();if(W?.getKind()===ar.TaggedTemplateExpression){let B=W.getTemplate();O=nf(B)}}let A=rf(E);T.push({method:w.toUpperCase(),name:F,path:O||"/",location:et(e,E,r),...A.apiId!==void 0?{apiId:A.apiId}:{},...A.groupName!==void 0?{groupName:A.groupName}:{}});break}}if(y.includes("middleware")||y.includes("Middleware")){let C=y.replace(/.*\./,"").replace(/\(.*/,"");C&&S.push({name:C,location:et(e,E,r)})}if(y.includes("Command.make")||y.includes("Prompt.")){let C=E.getArguments(),w=C.length>0?C[0]?.getText().replace(/["'`]/g,""):"unnamed",b=C.some(P=>P.getText().includes("Schema"));N.push({name:w??"unnamed",hasSchema:b,location:et(e,E,r)})}}return(s.client||s.server||s.api||a.reads.length>0||a.writes.length>0)&&(m.includes("node")||m.push("node")),(d||u)&&(m.includes("browser")||m.push("browser")),{platforms:m,modules:{http:{...s,routes:[...new Set(s.routes)]},filesystem:{reads:[...new Set(a.reads)],writes:[...new Set(a.writes)]},sockets:i,terminal:c,workers:d,commands:[...new Set(l)],keyValueStore:f,multipart:u,codecs:[...new Set(p)],openApi:g},locations:o,...h.length>0?{fileSystemOps:h}:{},...x.length>0?{commandOps:x}:{},...T.length>0?{routeDefinitions:T}:{},...S.length>0?{middlewareChain:S}:{},...N.length>0?{cliCommands:N}:{}}}import{SyntaxKind as U}from"ts-morph";import{SyntaxKind as X}from"ts-morph";function sf(e,t,n){if(e.getText().includes("Schema."))return e;if(e.getKind()===X.Identifier){let o=e,s=o.getSymbol(),i=(s?.getAliasedSymbol()??s)?.getDeclarations()??[];for(let l of i){if(l.getKind()===X.VariableDeclaration){let f=l.getInitializer();if(f?.getText().includes("Schema."))return f}if(l.getKind()===X.ImportSpecifier){let f=l.getName(),u=l.getFirstAncestorByKind(X.ImportDeclaration);if(u){let p=u.getModuleSpecifierValue(),g=t.getFilePath(),m=p.startsWith(".")?wt(g,p):void 0,h=m?n.getSourceFile(m):void 0;if(h){let x=h.getExportedDeclarations().get(f)??[];for(let T of x)if(T.getKind()===X.VariableDeclaration){let S=T.getInitializer();if(S?.getText().includes("Schema."))return S}}}}}let c=o.getText(),d=t.getVariableDeclarations();for(let l of d)if(l.getName()===c){let f=l.getInitializer();if(f?.getText().includes("Schema."))return f}}return e.getText().includes("Schema.")?e:void 0}function Ot(e,t,n,r){let o=sf(e,t,n);if(o)return qe(o,t,n,r??new Map)}function qe(e,t,n,r){let o=e.getText();if(o.includes("Schema.Array")){let c=e.getKind()===X.CallExpression?e:e.getFirstDescendantByKind(X.CallExpression);if(c){let d=c.getArguments();return{type:"array",items:(d[0]?qe(d[0],t,n,r):void 0)??{}}}}if(o.includes("Schema.Struct")){let c=e.getKind()===X.CallExpression?e:e.getFirstDescendantByKind(X.CallExpression);if(!c)return{type:"object"};let l=c.getArguments()[0];if(l?.getKind()!==X.ObjectLiteralExpression)return{type:"object"};let f=l,u={},p=[];for(let m of f.getProperties()){if(m.getKind()!==X.PropertyAssignment)continue;let h=m,x=h.getNameNode().getText(),T=h.getInitializer();if(!T)continue;let S=T.getText();S.includes("Schema.optional")||S.includes(".optional")||p.push(x);let E=qe(T,t,n,r);E&&(u[x]=E)}let g={type:"object",properties:Object.keys(u).length?u:void 0,additionalProperties:!1};return p.length&&(g.required=p),g}if(o.includes("Schema.Union")){let c=e.getKind()===X.CallExpression?e:e.getFirstDescendantByKind(X.CallExpression);if(c){let l=c.getArguments().map(f=>qe(f,t,n,r)).filter(f=>f!==void 0);if(l.length)return{oneOf:l}}}if(o.includes("Schema.optional")||o.includes(".pipe(Schema.optional")){let c=e.getKind()===X.CallExpression?e:e.getFirstDescendantByKind(X.CallExpression);if(c){let d=c.getArguments(),l=d[0]?qe(d[0],t,n,r):void 0;if(l)return{...l,nullable:!0}}}if(o.includes("Schema.Record")){let c=e.getKind()===X.CallExpression?e:e.getFirstDescendantByKind(X.CallExpression);if(c){let d=c.getArguments();return{type:"object",additionalProperties:(d[1]?qe(d[1],t,n,r):void 0)??!0}}}if(o.includes("Schema.Tuple")){let c=e.getKind()===X.CallExpression?e:e.getFirstDescendantByKind(X.CallExpression);if(c)return{type:"array",items:c.getArguments().map(f=>qe(f,t,n,r)).filter(Boolean)}}if(o.includes("Schema.Date")||o.includes("Schema.DateTimeUtc")||o.includes("Schema.Instant"))return{type:"string",format:"date-time"};if(o.includes("Schema.String")&&!o.includes("Schema.Struct"))return{type:"string"};if(o.includes("Schema.Number")||o.includes("Schema.Int")||o.includes("Schema.Positive")||o.includes("Schema.NonNegative")||o.includes("Schema.Finite"))return{type:"number"};if(o.includes("Schema.Boolean"))return{type:"boolean"};if(o.includes("Schema.Null"))return{type:"null"};let s=/Schema\.Literal\s*\(\s*(["'])([^"']*)\1\s*\)/.exec(o);if(s)return{type:"string",enum:[s[2]]};let a=/Schema\.Literal\s*\(\s*(\d+)\s*\)/.exec(o);if(a)return{type:"number",enum:[Number(a[1])]};let i=/Schema\.Literal\s*\(\s*(true|false)\s*\)/.exec(o);if(i)return{type:"boolean",enum:[i[1]==="true"]};if(e.getKind()===X.Identifier){let l=(e.getSymbol()?.getDeclarations()[0]).getInitializer();if(l)return qe(l,t,n,r)}}function af(e,t,n){let{line:r,column:o}=n.getLineAndColumnAtPos(t.getStart());return{filePath:e,line:r+1,column:o}}function cf(e){let r=e.getText().replace(/\$\{HttpApiSchema\.param\s*\(\s*["'](\w+)["'][^}]*\)\}/g,":$1").replace(/\$\{[^}]*\}/g,":param").replace(/^`|`$/g,"").trim();return r.startsWith("/")?r:`/${r}`}function Is(e,t,n){let r={},o=e;for(let s=0;s<30&&o;s++){let a=o.getParent();if(a?.getKind()!==U.CallExpression){o=a;continue}let i=a,c=i.getExpression().getText(),d=i.getArguments();if(d.length<2){o=a;continue}let l=d[0]?.getText(),f=d[1]?.getText();if(c.endsWith(".annotate")||c.endsWith(".annotateContext"))if(l?.includes("OpenApi.Description")||l?.includes("Description")){let u=f?.replace(/^["']|["']$/g,"");u&&(r.description=u)}else if(l?.includes("OpenApi.Summary")||l?.includes("Summary")){let u=f?.replace(/^["']|["']$/g,"");u&&(r.summary=u)}else l?.includes("OpenApi.Deprecated")||l?.includes("Deprecated")?r.deprecated=f==="true":(l?.includes("OpenApi.Exclude")||l?.includes("Exclude"))&&(r.excluded=f==="true");o=a}return r}function lf(e,t){let n={},r=t.getProject(),o=e;for(let s=0;s<40&&o;s++){let a=o.getParent();if(a?.getKind()!==U.CallExpression){o=a;continue}let i=a,c=i.getExpression().getText(),d=i.getArguments();if(d.length<1){o=a;continue}let l=d[0];if(c.endsWith(".addSuccess")&&l&&!n.responseSchema){let f=Ot(l,t,r);f&&(n.responseSchema=f)}else if(c.endsWith(".setPayload")&&l&&!n.requestSchema){let f=Ot(l,t,r);f&&(n.requestSchema=f)}else if((c.endsWith(".setUrlParams")||c.endsWith(".setQueryParams"))&&l&&!n.urlParamsSchema){let f=Ot(l,t,r);f&&(n.urlParamsSchema=f)}o=a}return n}function df(e,t,n,r){let o=e.getArguments(),a=(o.length>0?o[0]?.getText().replace(/["'`]/g,""):"unnamed")??"unnamed",i="/";if(o.length>=2)i=o[1]?.getText().replace(/["'`]/g,"")??"/";else{let l=e.getParent();if(l?.getKind()===U.TaggedTemplateExpression){let f=l.getTemplate();i=cf(f)}}let c=Is(e,n,r);if(c.excluded)return null;let d=lf(e,n);return{name:a,method:t.toUpperCase(),path:i||"/",location:af(r,e,n),...c.description?{description:c.description}:{},...c.summary?{summary:c.summary}:{},...c.deprecated?{deprecated:!0}:{},...d.requestSchema?{requestSchema:d.requestSchema}:{},...d.responseSchema?{responseSchema:d.responseSchema}:{},...d.urlParamsSchema?{urlParamsSchema:d.urlParamsSchema}:{}}}function uf(e,t,n){let r=[],o=["get","post","put","delete","patch","head","options"],s=new Set,a=cr(e);function i(l){let f=l,u=[".annotate",".addSuccess",".setPayload",".setUrlParams",".setQueryParams",".addFailure"];for(let p=0;p<15;p++){if(f.getKind()!==U.CallExpression)return;let g=f,m=g.getExpression().getText();for(let x of o){let T=m.includes(`HttpApiEndpoint.${x}`)||m.includes(`HttpApiEndpoint.${x}(`),S=!u.some(N=>m.endsWith(N)||m.includes(N));if(T&&!m.includes(".annotate")&&S)return g}if(u.some(x=>m.endsWith(x)||m.includes(x))){let x=g.getExpression();x.getKind()===U.CallExpression?f=x:f=x.getExpression();continue}return}}function c(l){if(l.getKind()===U.CallExpression)return l;if(l.getKind()===U.Identifier){let f=l.getText(),u=l.getSymbol(),p=u?.getDeclarations()??u?.getAliasedSymbol()?.getDeclarations()??[];for(let m of p)if(m.getKind()===U.VariableDeclaration){let h=m.getInitializer();if(h)return h}let g=t.getVariableDeclarations();for(let m of g)if(m.getName()===f){let h=m.getInitializer();if(h)return h}}}function d(l){let f=c(l);if(f?.getKind()!==U.CallExpression)return;let u=f,p=i(u);if(p){let m=p.getExpression().getText();for(let h of o)if(m.includes(`HttpApiEndpoint.${h}`)){let x=df(p,h,t,n);x&&!s.has(`${x.method}:${x.path}:${x.name}`)&&(s.add(`${x.method}:${x.path}:${x.name}`),r.push(x));return}}if(u.getExpression().getText().endsWith(".add"))for(let m of u.getArguments())d(m)}for(let l of a)d(l);return r}function ff(e,t,n,r){let o=e.getArguments(),a=(o.length>0?o[0]?.getText().replace(/["'`]/g,""):"group")??"group",i=o[1],c=!1;if(i?.getKind()===U.ObjectLiteralExpression){let u=i.getProperty("topLevel");u?.getKind()===U.PropertyAssignment&&(c=u.getInitializer()?.getText()==="true")}let d=uf(e,t,n),l=Is(e,t,n);return{name:a,endpoints:d,...l.description?{description:l.description}:{},...c?{topLevel:!0}:{},...r?{prefix:r}:{}}}function pf(e){let t=e;for(let n=0;n<25&&t.getKind()===U.CallExpression;n++){let r=t;if(r.getExpression().getText().endsWith(".prefix")){let a=r.getArguments();if(a.length>=1){let i=a[0]?.getText().replace(/["'`]/g,"");if(i)return i.startsWith("/")?i:`/${i}`}break}let s=r.getExpression();if(s.getKind()===U.PropertyAccessExpression)t=s.getExpression();else break}}function cr(e){let t=[],n,r=e,o=e.getExpression().getText(),s=o.includes("HttpApi.make"),a=o.includes("HttpApiGroup.make");for(let i=0;i<20;i++){let c=r.getParent();if(!c||(c.getKind()===U.PropertyAccessExpression&&(c=c.getParent()),c?.getKind()!==U.CallExpression))break;let d=c,l=d.getExpression().getText();if(l.endsWith(".add")){if(s&&l.includes("HttpApiGroup.make")||a&&l.includes("HttpApi.make")&&!l.includes("HttpApiGroup"))break;n=d,r=c;continue}break}if(!n)return t;r=n;for(let i=0;i<50;i++){if(r.getKind()===U.CallExpression){let c=r;if(c.getExpression().getText().endsWith(".add")){for(let f of c.getArguments())t.push(f);let l=c.getExpression();if(l.getKind()===U.CallExpression){r=l;continue}if(l.getKind()===U.PropertyAccessExpression){let f=l.getExpression();if(f.getKind()===U.CallExpression){r=f;continue}}}}break}return t}function gf(e,t,n){let r=[],o=new Set,s=cr(e),a=[".add",".prefix",".annotate"];function i(l){let f=l;for(let u=0;u<20;u++){if(f.getKind()!==U.CallExpression)return;let p=f,g=p.getExpression().getText();if(g.includes("HttpApiGroup.make")&&!a.some(m=>g.endsWith(m))||g.includes("HttpApi.make")&&!a.some(m=>g.endsWith(m)))return p;if(a.some(m=>g.endsWith(m))){let m=p.getExpression();if(m.getKind()===U.CallExpression){f=m;continue}if(m.getKind()===U.PropertyAccessExpression){let h=m.getExpression();if(h.getKind()===U.CallExpression){f=h;continue}}return}return}}function c(l){if(l.getKind()===U.CallExpression)return l;if(l.getKind()===U.Identifier){let f=l.getText(),u=l.getSymbol(),p=u?.getDeclarations()??u?.getAliasedSymbol()?.getDeclarations()??[];for(let m of p)if(m.getKind()===U.VariableDeclaration){let h=m.getInitializer();if(h?.getKind()===U.CallExpression)return h}let g=t.getVariableDeclarations();for(let m of g)if(m.getName()===f){let h=m.getInitializer();if(h?.getKind()===U.CallExpression)return h}}}function d(l){let f=c(l);if(!f)return;let u=f.getExpression().getText();if(u.includes("HttpApiGroup.make")){let p=i(f);if(p){let g=pf(f),m=ff(p,t,n,g);m&&!o.has(m.name)&&(o.add(m.name),r.push(m))}return}if(u.includes("HttpApi.make")){let p=i(f);if(p)for(let g of cr(p))d(g)}}for(let l of s)d(l);return r}function mf(e){let t=e;for(let n=0;n<50;n++){let r=t.getParent();if(r?.getKind()!==U.CallExpression)return e;let o=r;if(o.getExpression().getText().endsWith(".add")){let a=o.getExpression();if(a.getKind()===U.CallExpression){let i=a;if(i.getExpression().getText().includes("HttpApi.make")){t=i;continue}}}break}return t}function hf(e,t){let n=[],r=t||e.getFilePath(),o=new Set;for(let s of e.getDescendantsOfKind(U.CallExpression)){let a=s.getExpression().getText();if(!a.includes("HttpApi.make")||a.includes("HttpApiBuilder")||a.includes(".add"))continue;let i=s.getArguments(),c=i.length>0?i[0]?.getText().replace(/["'`]/g,""):void 0;if(!c||o.has(c))continue;let d=mf(s),l=gf(d,e,r);o.add(c),n.push({apiId:c,filePath:r,groups:l})}return n}function yf(e){let t=[];for(let n of e){t.push(`# API: ${n.apiId}`),t.push("");let r=n.prefix??"";for(let o of n.groups){t.push(`## ${o.name}`),o.description&&(t.push(""),t.push(o.description),t.push("")),t.push(""),t.push("| Method | Path | Name | Description |"),t.push("|--------|------|------|-------------|");let s=o.prefix??"";for(let a of o.endpoints){let i=r+s+a.path,c=a.description??a.summary??"-",d=a.deprecated?" (deprecated)":"";t.push(`| ${a.method} | ${i} | ${a.name}${d} | ${c} |`)}t.push("")}t.push("")}return t.join(`
|
|
544
|
+
`).trim()}function Sf(e){let t=["flowchart TB"],n=0,r=new Map,o=s=>{let a=`${s}${n++}`;return r.set(a,a),a};for(let s of e){let a=o("api");t.push(` ${a}["${s.apiId}"]`);for(let i of s.groups){let c=o("group");t.push(` ${c}["${i.name}"]`),t.push(` ${a} --> ${c}`);let d=s.prefix??"",l=i.prefix??"";for(let f of i.endpoints){let u=o("ep"),p=d+l+f.path;t.push(` ${u}["${f.method} ${p}"]`),t.push(` ${c} --> ${u}`)}}}return t.join(`
|
|
545
|
+
`)}function xf(e){let t={};for(let n of e){let r=n.prefix??"";for(let o of n.groups){let s=o.prefix??"";for(let a of o.endpoints){let i=r+s+a.path;t[i]??={};let c=a.method.toLowerCase(),d={operationId:`${o.name}.${a.name}`,...a.summary?{summary:a.summary}:{},...a.deprecated?{deprecated:!0}:{}};if(a.requestSchema&&(d.requestBody={content:{"application/json":{schema:a.requestSchema}}}),a.responseSchema&&(d.responses={200:{description:a.summary??a.description??"Success",content:{"application/json":{schema:a.responseSchema}}}}),a.urlParamsSchema?.properties){let l=Object.entries(a.urlParamsSchema.properties).map(([f,u])=>({name:f,in:"path",schema:u}));l.length&&(d.parameters=l)}t[i][c]=d}}}return{paths:t}}import{Project as Ef,SyntaxKind as bf}from"ts-morph";function lr(e,t,n){let{line:r,column:o}=n.getLineAndColumnAtPos(t.getStart());return{filePath:e,line:r+1,column:o}}function Cf(e,t){let n=new Ef({useInMemoryFileSystem:!0}),r=t?n.createSourceFile(e,t):n.addSourceFileAtPath(e),o=new Map,s=!1,a=!1,i=[],c=!1,d=!1,l=!1,f=!1,u=!1,p=!1,g=!1,m=!1,h=!1,x=!1;for(let T of r.getImportDeclarations()){let S=T.getModuleSpecifierValue();(S==="@effect/vitest"||S.includes("@effect/vitest"))&&(l=!0),(S==="fast-check"||S==="fc"||S.includes("fast-check"))&&(h=!0,o.set("fast-check",{filePath:e,line:1,column:0}))}for(let T of r.getDescendantsOfKind(bf.CallExpression)){let S=T.getExpression().getText(),N=lr(e,T,r);(S.includes("TestClock")||S.includes("TestContext"))&&(S.includes("TestClock")&&(s=!0),S.includes("TestContext")&&(a=!0),o.set("test-context",lr(e,T,r))),(S.includes("Layer.succeed")||S.includes("Layer.mock"))&&(T.getParent()?.getText().includes("test")||r.getFilePath().includes(".test."))&&(i.push(S.slice(0,60)),o.set("mock-layer",lr(e,T,r))),(S.includes("Effect.runPromise")||S.includes("Effect.runSync")||S.includes("Effect.runPromiseExit")||S.includes("Effect.runSyncExit")||S.includes("runPromise")||S.includes("runSync"))&&(r.getFilePath().includes(".test.")||r.getFilePath().includes("spec."))&&(c=!0),(S.includes("it.effect")||S.includes("it.scoped")||S.includes("it.live")||S.includes("it.scopedLive")||S.includes("it.prop"))&&(d=!0,S.includes("it.prop")&&(x=!0),o.set("effect-vitest",N)),S.includes("TestAnnotations")&&(u=!0,o.set("test-annotations",N)),S.includes("flakyTest")&&(p=!0,o.set("flaky-test",N)),(S.includes("Exit.match")||S.includes("Exit.isSuccess")||S.includes("Exit.isFailure")||S.includes("Exit.isInterrupted"))&&(g=!0,o.set("exit-assertions",N)),(S==="layer"||S.endsWith(".layer"))&&T.getParent()?.getText().includes("(")&&(f=!0,o.set("shared-layer",N)),(S.includes("TestServices")||S.includes("TestSized")||S.includes("TestLive"))&&(m=!0,o.set("test-services",N)),(S.includes("fc.")||S.includes("FastCheck")||S.includes("Arbitrary.make")||S.includes("Arbitrary.filter")||S.includes("Arbitrary.from"))&&(h=!0,o.set("fast-check",N)),(S.includes("fc.property")||S.includes("fc.asyncProperty"))&&(x=!0,o.set("property-test",N))}return{testClockUsed:s,testContextUsed:a,mockLayers:[...new Set(i)],runInTests:c,effectVitestUsed:d,effectVitestImported:l,sharedLayerUsed:f,testAnnotationsUsed:u,flakyTestUsed:p,exitAssertionsUsed:g,testServicesUsed:m,fastCheckUsed:h,propertyTestUsed:x,locations:o}}import{readFile as Nf}from"fs/promises";import{join as Tf}from"path";var vf=/^(\d+)\.(\d+)\.(\d+)(?:-(.+))?$/;function wf(e){let t=vf.exec(e);return t?.[1]===void 0||t[2]===void 0||t[3]===void 0?null:{version:e,major:parseInt(t[1],10),minor:parseInt(t[2],10),patch:parseInt(t[3],10),isPrerelease:!!t[4]}}async function As(e=process.cwd()){try{let t=Tf(e,"package.json"),n=await Nf(t,"utf-8"),r=JSON.parse(n),s={...r.dependencies,...r.devDependencies}.effect;if(typeof s!="string")return null;let a=s.replace(/^[\^~]/,"");return wf(a)}catch{return null}}async function kf(e=process.cwd()){let t=await As(e),n=[],r=null;return t?t.major<3&&(n.push("Effect v2 is deprecated; upgrade to Effect v3"),r="pnpm add effect@^3"):r='Add "effect" to dependencies to enable version checks',{effectVersion:t,deprecationWarnings:n,suggestion:r}}import{Option as Fs}from"effect";function dr(e,t,n,r){for(let o of e)if(o.type==="generator"){let s=o;for(let i of s.yields){let c=i.effect.type==="effect"?i.effect.callee:void 0,d={yieldIndex:r.current++,nodeId:i.effect.id,...i.variableName!==void 0&&{variableName:i.variableName},...c!==void 0&&{effectCallee:c}};t.push(d),(c?.includes("service")||c?.includes("Context"))&&n.push(c)}let a=Fs.getOrElse(v(o),()=>[]);dr(a,t,n,r)}else{let s=Fs.getOrElse(v(o),()=>[]);dr(s,t,n,r)}}function If(e){let t=[],n=[];dr(e.root.children,t,n,{current:0});let r=new Set;for(let s of t)s.variableName&&!s.variableName.startsWith("_")&&r.add(s.yieldIndex);let o=t.map(s=>s.yieldIndex).filter(s=>!r.has(s));return{bindings:t,unusedYieldIndices:o,serviceYields:[...new Set(n)]}}import{Project as Af,SyntaxKind as Wt}from"ts-morph";function Rs(e,t,n){let{line:r,column:o}=n.getLineAndColumnAtPos(t.getStart());return{filePath:e,line:r+1,column:o}}function Ff(e,t){let n=new Af({useInMemoryFileSystem:!0}),r=t?n.createSourceFile(e,t):n.addSourceFileAtPath(e),o=new Map,s=!1,a=!1,i=[],c=!1,d=[],l=[],f=[];for(let p of r.getDescendantsOfKind(Wt.CallExpression)){let g=p.getExpression().getText(),m=Rs(e,p,r);if((g.includes("SqlClient")||g.includes("sqlClient")||g.includes("Sql"))&&(s=!0,o.set("sql",m)),g.includes("withTransaction")&&(a=!0,o.set("transaction",m)),(g.includes("SqlSchema")||g.includes("sqlSchema"))&&(i.push(g.slice(0,80)),o.set("schema",m)),g.includes("SqlResolver.make")||g.includes("SqlResolver.grouped")||g.includes("SqlResolver.void")){let h=p.getArguments(),x=h.length>0?h[0]?.getText().replace(/["'`]/g,""):"unnamed";d.push({name:x??"unnamed",location:m})}if(g.includes("SqlMigrator")){let h=p.getArguments(),x=h.length>0?h[0]?.getText().replace(/["'`]/g,""):"unnamed";l.push({name:x??"unnamed",location:m})}}let u=[Wt.ForStatement,Wt.ForOfStatement,Wt.WhileStatement];for(let p of u)for(let g of r.getDescendantsOfKind(p)){let h=g.getFirstChildByKind(Wt.Block)?.getText()??"";if(h.includes("Sql")||h.includes("execute")||h.includes("query")){c=!0;let x=Rs(e,g,r);o.set("sql-in-loop",x),f.push({query:h.slice(0,80),location:x})}}return{sqlClientUsed:s,withTransaction:a,schemaDefs:[...new Set(i)],queryInLoop:c,locations:o,...d.length>0?{resolvers:d}:{},...l.length>0?{migrations:l}:{},...f.length>0?{queriesInLoops:f}:{}}}import{Project as Rf,SyntaxKind as $f}from"ts-morph";function Df(e,t,n){let{line:r,column:o}=n.getLineAndColumnAtPos(t.getStart());return{filePath:e,line:r+1,column:o}}function Pf(e,t){let n=new Rf({useInMemoryFileSystem:!0}),r=t?n.createSourceFile(e,t):n.addSourceFileAtPath(e),o=new Map,s=!1,a=[],i=[],c=[];for(let d of r.getDescendantsOfKind($f.CallExpression)){let l=d.getExpression().getText(),f=Df(e,d,r);if((l.includes("Rpc.make")||l.includes("Rpc.router"))&&(s=!0,a.push(l.slice(0,60)),o.set("rpc",f)),(l.includes("RpcClient")||l.includes("Rpc.call"))&&(i.push(l.slice(0,60)),o.set("rpc-client",f)),l.includes("Rpc.make")||l.includes("RpcGroup")){let u=d.getArguments(),p=u.length>0?u[0]?.getText().replace(/["'`]/g,""):"unnamed",g=d.getText(),m=g.includes("Stream")||g.includes("stream");c.push({name:p??"unnamed",isStreaming:m,location:f})}}return{rpcDefined:s,routers:[...new Set(a)],clientCalls:[...new Set(i)],locations:o,...c.length>0?{rpcDefinitions:c}:{}}}import{Project as Lf,SyntaxKind as Mf}from"ts-morph";function Of(e,t,n){let{line:r,column:o}=n.getLineAndColumnAtPos(t.getStart());return{filePath:e,line:r+1,column:o}}function Wf(e,t){let n=new Lf({useInMemoryFileSystem:!0}),r=t?n.createSourceFile(e,t):n.addSourceFileAtPath(e),o=new Map,s=!1,a=!1,i=!1,c=!1;for(let d of r.getDescendantsOfKind(Mf.CallExpression)){let l=d.getExpression().getText(),f=Of(e,d,r);(l.includes("Request.tagged")||l.includes("Request.of"))&&(s=!0,o.set("request",f)),(l.includes("RequestResolver.makeBatched")||l.includes("RequestResolver.fromEffect"))&&(a=!0,o.set("resolver",f)),l.includes("withRequestBatching")&&(i=!0,o.set("batching",f)),l.includes("withRequestCaching")&&(c=!0,o.set("caching",f))}return{requestTagged:s,resolverBatched:a,withBatching:i,withCaching:c,locations:o}}import{Project as Kf,SyntaxKind as Bf}from"ts-morph";function qf(e,t,n){let{line:r,column:o}=n.getLineAndColumnAtPos(t.getStart());return{filePath:e,line:r+1,column:o}}function _f(e,t){let n=new Kf({useInMemoryFileSystem:!0}),r=t?n.createSourceFile(e,t):n.addSourceFileAtPath(e),o=new Map,s=[],a=[],i=[],c=[],d=!1;for(let l of r.getDescendantsOfKind(Bf.CallExpression)){let f=l.getExpression().getText(),u=qf(e,l,r);(f.includes("STM.commit")||f==="STM.commit")&&(s.push(u),o.set("commit",u)),(f.includes("TRef.make")||f.includes("TRef.unsafeMake"))&&(a.push(f.slice(0,50)),o.set("tref",u)),(f.includes("TMap.make")||f.includes("TMap.empty"))&&(i.push(f.slice(0,50)),o.set("tmap",u)),(f.includes("TQueue.make")||f.includes("TQueue.bounded"))&&(c.push(f.slice(0,50)),o.set("tqueue",u)),(f.includes("STM.retry")||f==="STM.retry")&&(d=!0)}return{commitSites:s,tRefs:[...new Set(a)],tMaps:[...new Set(i)],tQueues:[...new Set(c)],retryUsed:d,locations:o}}function jf(e){let t=fe(e);return{version:1,ir:e,mermaid:t,programName:e.root.programName,exportedAt:new Date().toISOString()}}function zf(e){return Buffer.from(JSON.stringify(e),"utf-8").toString("base64url")}function Hf(e){let t=Buffer.from(e,"base64url").toString("utf-8");return JSON.parse(t)}import{createHash as Uf}from"crypto";import{readFile as Vf,writeFile as Gf,mkdir as Jf}from"fs/promises";import{stat as Yf}from"fs/promises";import{join as $s}from"path";var Ds=".effect-analyzer-cache",Ps=1;function Ls(e){return Uf("sha256").update(e,"utf-8").digest("hex").slice(0,16)}function Ms(e,t){let n=t.replace(/[^a-zA-Z0-9._-]/g,"_");return $s(e,Ds,`${n}.json`)}async function Qf(e,t,n=process.cwd()){try{let r=Ms(n,e),o=Ls(t),s=await Vf(r,"utf-8"),a=JSON.parse(s);if(a.version===Ps&&a.contentHash===o)return a.irs}catch{}return null}async function Zf(e,t,n,r=process.cwd()){try{let o=$s(r,Ds);await Jf(o,{recursive:!0});let s=await Yf(e).catch(()=>null),a={version:Ps,contentHash:Ls(t),mtimeMs:s?.mtimeMs??0,irs:n};await Gf(Ms(r,e),JSON.stringify(a),"utf-8")}catch{}}import{VariableDeclarationKind as Xf}from"ts-morph";function ep(e){return{values:new Map,sourceFile:e}}function ur(e,t){let n=t.values.get(e);if(n!==void 0)return n;let o=t.sourceFile.getVariableDeclarations();for(let a of o)if(a.getName()===e){let i={resolved:!1,reason:`Cyclic reference detected for "${e}"`};if(t.values.set(e,i),a.getVariableStatement()?.getDeclarationKind()!==Xf.Const){let f={resolved:!1,reason:`"${e}" is not a const declaration`};return t.values.set(e,f),f}let d=a.getInitializer();if(!d){let f={resolved:!1,reason:`"${e}" has no initializer`};return t.values.set(e,f),f}let l=_e(d,t);return t.values.set(e,l),l}let s={resolved:!1,reason:`"${e}" not found in current file`};return t.values.set(e,s),s}function _e(e,t){let{Node:n}=I();if(n.isStringLiteral(e))return{resolved:!0,value:{type:"string",value:e.getLiteralValue()}};if(n.isNumericLiteral(e))return{resolved:!0,value:{type:"number",value:e.getLiteralValue()}};if(n.isTrueLiteral(e))return{resolved:!0,value:{type:"boolean",value:!0}};if(n.isFalseLiteral(e))return{resolved:!0,value:{type:"boolean",value:!1}};if(n.isNullLiteral(e))return{resolved:!0,value:{type:"null",value:null}};if(n.isArrayLiteralExpression(e)){let r=e.getElements(),o=[];for(let s of r){if(n.isSpreadElement(s))return{resolved:!1,reason:"Array contains spread element"};let a=_e(s,t);if(!a.resolved||!a.value)return{resolved:!1,reason:`Could not resolve array element: ${a.reason}`};o.push(a.value)}return{resolved:!0,value:{type:"array",value:o}}}if(n.isObjectLiteralExpression(e)){let r=e.getProperties(),o={};for(let s of r){if(n.isSpreadAssignment(s))return{resolved:!1,reason:"Object contains spread assignment"};if(n.isShorthandPropertyAssignment(s)){let l=s.getName(),f=ur(l,t);if(!f.resolved||!f.value)return{resolved:!1,reason:`Could not resolve shorthand property "${l}"`};o[l]=f.value;continue}if(!n.isPropertyAssignment(s))return{resolved:!1,reason:"Object contains unsupported property type"};let a=s.getNameNode();if(n.isComputedPropertyName(a))return{resolved:!1,reason:"Object contains computed property name"};let i=s.getName(),c=s.getInitializer();if(!c)return{resolved:!1,reason:`Property "${i}" has no initializer`};let d=_e(c,t);if(!d.resolved||!d.value)return{resolved:!1,reason:`Could not resolve property "${i}": ${d.reason}`};o[i]=d.value}return{resolved:!0,value:{type:"object",value:o}}}if(n.isIdentifier(e)){let r=e.getText();return r==="undefined"?{resolved:!0,value:{type:"undefined",value:void 0}}:ur(r,t)}if(n.isCallExpression(e)){let r=e.getExpression(),o=n.isIdentifier(r)?r.getText():null;if(o==="tags"||o==="err"){let s=e.getArguments(),a=[];for(let i of s){let c=_e(i,t);if(!c.resolved||!c.value)return{resolved:!1,reason:`Could not resolve ${o}() argument: ${c.reason}`};a.push(c.value)}return{resolved:!0,value:{type:"array",value:a}}}return{resolved:!1,reason:`Cannot inline function call: ${o??"unknown"}`}}return n.isNoSubstitutionTemplateLiteral(e)?{resolved:!0,value:{type:"string",value:e.getLiteralValue()}}:n.isTemplateExpression(e)?{resolved:!1,reason:"Cannot inline template literal with expressions"}:n.isAsExpression(e)||n.isSatisfiesExpression(e)||n.isParenthesizedExpression(e)?_e(e.getExpression(),t):{resolved:!1,reason:`Unsupported node type: ${e.getKindName()}`}}function fr(e){switch(e.type){case"string":case"number":case"boolean":case"null":case"undefined":return e.value;case"array":return e.value.map(fr);case"object":{let t={};for(let[n,r]of Object.entries(e.value))t[n]=fr(r);return t}}}function tp(e){if(e.type!=="array")return;let t=[];for(let n of e.value){if(n.type!=="string")return;t.push(n.value)}return t}function np(e){if(e.type==="string")return e.value}import{Option as Ws}from"effect";var Ks=new Set(["parallel","race","conditional","decision","switch","loop","error-handler","retry","generator","pipe","stream","fiber"]);function rp(e){return e.type==="effect"?e.displayName??e.callee:`${e.type}:${e.displayName??e.id}`}function pr(e,t="root",n=0){let r=[];e.type==="effect"&&r.push({stepId:e.id,callee:e.callee,containerType:t,index:n,fingerprint:rp(e)});let o=Ws.getOrElse(v(e),()=>[]),s=Ks.has(e.type)?e.type:t,a=0;for(let i of o){let c=pr(i,s,a);r.push(...c),a++}return r}function Os(e){let t=new Map;function n(r){Ks.has(r.type)&&t.set(r.type,(t.get(r.type)??0)+1);let o=Ws.getOrElse(v(r),()=>[]);for(let s of o)n(s)}return n(e),t}function Bs(e,t,n){let r=n?.detectRenames??!0,o=n?.regressionMode??!1,s=pr(e.root),a=pr(t.root),i=new Set,c=new Set,d=[];function l(h){for(let x=0;x<s.length;x++){if(i.has(x))continue;let T=s[x];if(!T)continue;let S=[];for(let C=0;C<a.length;C++)if(!c.has(C)&&a[C]?.fingerprint===T.fingerprint){if(h&&a[C].containerType!==T.containerType)continue;S.push(C)}if(S.length===0)continue;let N=S[0],E=Math.abs(a[N].index-T.index);for(let C=1;C<S.length;C++){let w=S[C],b=Math.abs(a[w].index-T.index);b<E&&(N=w,E=b)}let y=a[N];i.add(x),c.add(N),T.containerType!==y.containerType?d.push({kind:"moved",stepId:y.stepId,callee:y.callee,containerBefore:T.containerType,containerAfter:y.containerType}):d.push({kind:"unchanged",stepId:y.stepId,callee:y.callee})}}if(l(!0),l(!1),r)for(let h=0;h<a.length;h++){if(c.has(h))continue;let x=a[h];if(!x)continue;let T=s.findIndex((S,N)=>!i.has(N)&&S.callee===x.callee);if(T>=0){let S=s[T];if(!S)continue;i.add(T),c.add(h),d.push({kind:"renamed",stepId:x.stepId,previousStepId:S.stepId,callee:x.callee})}}for(let h=0;h<s.length;h++)if(!i.has(h)){let x=s[h];if(!x)continue;d.push({kind:"removed",stepId:x.stepId,callee:x.callee})}for(let h=0;h<a.length;h++)if(!c.has(h)){let x=a[h];if(!x)continue;d.push({kind:"added",stepId:x.stepId,callee:x.callee})}let f=[],u=Os(e.root),p=Os(t.root),g=new Set([...u.keys(),...p.keys()]);for(let h of g){let x=u.get(h)??0,T=p.get(h)??0;if(T>x)for(let S=0;S<T-x;S++)f.push({kind:"added",nodeType:h,description:`${h} block added`});else if(x>T)for(let S=0;S<x-T;S++)f.push({kind:"removed",nodeType:h,description:`${h} block removed`})}let m={stepsAdded:d.filter(h=>h.kind==="added").length,stepsRemoved:d.filter(h=>h.kind==="removed").length,stepsRenamed:d.filter(h=>h.kind==="renamed").length,stepsMoved:d.filter(h=>h.kind==="moved").length,stepsUnchanged:d.filter(h=>h.kind==="unchanged").length,structuralChanges:f.length,hasRegressions:o?d.some(h=>h.kind==="removed")||f.some(h=>h.kind==="removed"):!1};return{beforeName:e.root.programName,afterName:t.root.programName,diffedAt:Date.now(),steps:d,structuralChanges:f,summary:m}}var op={added:"+",removed:"-",unchanged:" ",renamed:"~",moved:">"};function sp(e){let t=op[e.kind]??"?",n=e.callee??e.stepId;switch(e.kind){case"renamed":return`${t} **${n}** (renamed from \`${e.previousStepId}\` \u2192 \`${e.stepId}\`)`;case"moved":return`${t} **${n}** (moved from \`${e.containerBefore}\` \u2192 \`${e.containerAfter}\`)`;case"added":return`${t} **${n}** (added, id: \`${e.stepId}\`)`;case"removed":return`${t} **${n}** (removed, id: \`${e.stepId}\`)`;default:return`${t} ${n}`}}function qs(e,t){let n=t?.showUnchanged??!1,r=t?.title??`Effect Program Diff: ${e.beforeName} \u2192 ${e.afterName}`,o=[];o.push(`# ${r}`),o.push(""),o.push("## Summary"),o.push(""),o.push("| Metric | Count |"),o.push("|--------|-------|"),o.push(`| Added | ${e.summary.stepsAdded} |`),o.push(`| Removed | ${e.summary.stepsRemoved} |`),o.push(`| Renamed | ${e.summary.stepsRenamed} |`),o.push(`| Moved | ${e.summary.stepsMoved} |`),o.push(`| Unchanged | ${e.summary.stepsUnchanged} |`),o.push(`| Structural changes | ${e.summary.structuralChanges} |`),e.summary.hasRegressions&&o.push("| **Regressions** | **Yes** |"),o.push("");let s=n?e.steps:e.steps.filter(a=>a.kind!=="unchanged");if(s.length>0){o.push("## Step Changes"),o.push(""),o.push("```diff");for(let a of s)o.push(sp(a));o.push("```"),o.push("")}if(e.structuralChanges.length>0){o.push("## Structural Changes"),o.push("");for(let a of e.structuralChanges){let i=a.kind==="added"?"+":"-";o.push(`- ${i} ${a.description}`)}o.push("")}return o.join(`
|
|
546
|
+
`)}function _s(e,t){return t?.pretty??!0?JSON.stringify(e,null,2):JSON.stringify(e)}function ip(e){let t=new Map,n=/^\s*(n\d+)\["[^"]*"\]/gm,r;for(;(r=n.exec(e))!==null;){let o=r[1]??"";t.set(o,o)}return t}function js(e,t,n){let r=n?.direction??"TB",o=n?.showRemovedSteps??!1,s=fe(e,{direction:r}),a=ip(s),i=new Set(t.steps.filter(g=>g.kind==="added").map(g=>g.stepId)),c=new Set(t.steps.filter(g=>g.kind==="removed").map(g=>g.stepId)),d=new Set(t.steps.filter(g=>g.kind==="moved").map(g=>g.stepId)),l=new Set(t.steps.filter(g=>g.kind==="renamed").map(g=>g.stepId)),f=new Map,u=s.split(`
|
|
547
|
+
`),p=[];for(let g of u){let m=/^\s*(n\d+)\["([^"]*)"\]/.exec(g);if(!m)continue;let h=m[1]??"",x=m[2]??"";for(let T of t.steps)if(T.callee&&x.includes(T.callee)){f.set(T.stepId,h);break}}for(let[g,m]of f)i.has(g)?p.push(` style ${m} fill:#d4edda,stroke:#28a745,stroke-width:2px`):d.has(g)?p.push(` style ${m} fill:#fff3cd,stroke:#ffc107,stroke-width:2px`):l.has(g)&&p.push(` style ${m} fill:#cce5ff,stroke:#007bff,stroke-width:2px`);if(o){for(let g of t.steps)if(g.kind==="removed"){let m=`removed_${g.stepId.replace(/[^a-zA-Z0-9]/g,"_")}`;p.push(` ${m}["\u274C ${g.callee??g.stepId}"]`),p.push(` style ${m} fill:#f8d7da,stroke:#dc3545,stroke-width:2px,stroke-dasharray: 5 5`)}}return p.length===0?s:s.trimEnd()+`
|
|
543
548
|
`+p.join(`
|
|
544
549
|
`)+`
|
|
545
|
-
`}import{execSync as
|
|
546
|
-
`)}import{Option as
|
|
547
|
-
`)};export{
|
|
550
|
+
`}import{execSync as ap}from"child_process";function zs(e){if(/^https?:\/\/github\.com\/.+\/pull\/\d+/.test(e))return{kind:"github-pr",prUrl:e};let t=/^([^:]+):(.+)$/.exec(e);return t?.[1]&&t[2]&&!e.startsWith("/")&&!e.startsWith(".")&&!(/^[A-Za-z]$/.test(t[1])&&t[2].startsWith("\\"))?{kind:"git-ref",ref:t[1],filePath:t[2]}:{kind:"file",filePath:e}}function Hs(e,t,n){try{return ap(`git show ${e}:${t}`,{cwd:n??process.cwd(),encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch(r){let o=r instanceof Error?r.message:String(r);throw new Error(`Failed to resolve git source ${e}:${t}: ${o}`,{cause:r})}}import{Option as cp}from"effect";function Us(e){return e.type==="cause"||e.type==="exit"||e.type==="effect"&&(e.callee==="Effect.cause"||e.callee==="Effect.exit")?!0:cp.getOrElse(v(e),()=>[]).some(Us)}function lp(e){let t=e.metadata.stats,n=e.root,o=[{format:"mermaid-services",score:n.dependencies.length*2+(n.requiredServices?.length??0)},{format:"mermaid-concurrency",score:t.parallelCount*3+t.raceCount*3},{format:"mermaid-errors",score:n.errorTypes.length>0?n.errorTypes.length*2+t.errorHandlerCount*2:0},{format:"mermaid-retry",score:t.retryCount*4+t.timeoutCount*3},{format:"mermaid-decisions",score:t.conditionalCount+t.decisionCount+t.switchCount},{format:"mermaid-layers",score:t.layerCount*3},{format:"mermaid-dataflow",score:n.source==="pipe"?5:0},{format:"mermaid-causes",score:n.children.some(Us)?4:0},{format:"mermaid-timeline",score:n.dependencies.length>2?3:0},{format:"mermaid-testability",score:(n.requiredServices?.length??0)*2}].filter(a=>a.score>0).sort((a,i)=>i.score-a.score).slice(0,2).map(a=>a.format);return[tr(e)==="railway"?"mermaid-railway":"mermaid",...o]}import{Option as dp}from"effect";function Vs(e,t,n){for(let r of e){if(r.type==="fiber"){let s=r;(s.operation==="fork"||s.operation==="forkScoped"||s.operation==="forkDaemon"||s.operation==="forkAll"||s.operation==="forkIn"||s.operation==="forkWithErrorHandler")&&t.push(s),(s.operation==="join"||s.operation==="await"||s.operation==="awaitAll"||s.operation==="interrupt"||s.operation==="interruptFork")&&(s.joinPoint&&n.add(s.joinPoint),n.add(s.id))}let o=dp.getOrElse(v(r),()=>[]);o.length>0&&Vs(o,t,n)}}function up(e,t){return e.isScoped?"safe":e.isDaemon?"daemon":t?"safe":e.operation==="forkAll"?"uncertain":e.operation==="forkIn"?"safe":"potential-leak"}function fp(e){let t=[],n=new Set;Vs(e.root.children,t,n);let r=t.map(c=>{let d=n.size>0,l=up(c,d),f={nodeId:c.id,operation:c.operation,isScoped:c.isScoped,isDaemon:c.isDaemon,hasJoin:d,risk:l};return c.location&&(f.location=c.location),f}),o=r.filter(c=>c.risk==="potential-leak"),s=r.filter(c=>c.risk==="daemon"),a=r.filter(c=>c.risk==="safe"),i=r.filter(c=>c.risk==="uncertain");return{forks:r,potentialLeaks:o,daemonForks:s,safeForks:a,summary:{total:r.length,safe:a.length,daemon:s.length,potentialLeaks:o.length,uncertain:i.length}}}function pp(e){let t=[];if(t.push("# Fiber Lifecycle Analysis"),t.push(""),t.push(`Total forks: ${e.summary.total}`),t.push(` Safe (scoped/joined): ${e.summary.safe}`),t.push(` Daemon (intentional): ${e.summary.daemon}`),t.push(` Uncertain: ${e.summary.uncertain}`),t.push(` Potential leaks: ${e.summary.potentialLeaks}`),e.potentialLeaks.length>0){t.push(""),t.push("## \u26A0\uFE0F Potential Fiber Leaks"),t.push(""),t.push("These forks are not scoped, not daemon, and no join/await was found in the same program:"),t.push("");for(let n of e.potentialLeaks){let r=n.location?` at ${n.location.filePath}:${n.location.line}`:"";t.push(`- \`${n.operation}\` (id: ${n.nodeId})${r}`)}t.push(""),t.push("\u{1F4A1} **Suggestions**:"),t.push(" - Use `Effect.forkScoped` to tie fiber lifetime to a scope"),t.push(" - Use `Effect.forkDaemon` if fire-and-forget is intentional"),t.push(" - Add `Fiber.join(fiber)` / `Fiber.await(fiber)` to properly await the fiber")}if(e.daemonForks.length>0){t.push(""),t.push("## \u2139\uFE0F Daemon Forks (fire-and-forget)"),t.push("");for(let n of e.daemonForks){let r=n.location?` at ${n.location.filePath}:${n.location.line}`:"";t.push(`- \`${n.operation}\` (id: ${n.nodeId})${r}`)}}return t.join(`
|
|
551
|
+
`)}import{Option as ke}from"effect";var Js={name:"untagged-yield",description:"Detects yields in Effect.gen that are not assigned to a variable",severity:"warning",check:e=>{let t=[],n=(r,o)=>{if(Kt(r))for(let a of r.yields)!a.variableName&&a.effect.type!=="unknown"&&t.push({rule:"untagged-yield",message:`Untagged yield detected: ${He(a.effect)?a.effect.callee:"Effect"}`,severity:"warning",location:a.effect.location,nodeId:a.effect.id,suggestion:"Assign yield result to a variable or use Effect.tap for side effects"});let s=v(r);if(ke.isSome(s))for(let a of s.value)n(a,r.id)};for(let r of e.root.children)n(r);return t}},Ys={name:"missing-error-handler",description:"Detects Effect operations that can fail but have no error handling",severity:"error",check:e=>{let t=[],n=(r,o=!1)=>{let s=o||Et(r);He(r)&&r.typeSignature&&r.typeSignature.errorType!=="never"&&!s&&(["Effect.try","Effect.tryPromise","Effect.fail","Effect.catchAll"].some(l=>r.callee.includes(l))||r.typeSignature.errorType!=="unknown")&&t.push({rule:"missing-error-handler",message:`Effect "${r.callee}" can fail with error type "${r.typeSignature.errorType}" but has no error handler`,severity:"error",location:r.location,nodeId:r.id,suggestion:"Add .pipe(Effect.catchAll(...)) or handle the error appropriately"});let a=v(r);if(ke.isSome(a))for(let i of a.value)n(i,s)};for(let r of e.root.children)n(r);return t}};function Gs(e){let t=new Set,n=r=>{if(He(r)){let s=r.callee;s&&!/\.|\(/.test(s)&&/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(s)&&t.add(s),r.name&&t.add(r.name)}let o=v(r);if(ke.isSome(o))for(let s of o.value)n(s)};return n(e),t}var Qs={name:"dead-code",description:"Detects yields whose results are never used",severity:"warning",check:e=>{let t=[],n=r=>{if(Kt(r)){let s=r.yields;for(let a=0;a<s.length;a++){let i=s[a];if(!i)continue;let c=i.variableName;if(!c)continue;let d=new Set;for(let l=a+1;l<s.length;l++){let f=s[l];if(f)for(let u of Gs(f.effect))d.add(u)}if(r.returnNode)for(let l of Gs(r.returnNode))d.add(l);d.has(c)||t.push({rule:"dead-code",message:`Yield result "${c}" is never used in later steps or return`,severity:"warning",location:i.effect.location,nodeId:i.effect.id,suggestion:"Remove the variable assignment if not needed, or use the result in a subsequent step"})}}let o=v(r);if(ke.isSome(o))for(let s of o.value)n(s)};for(let r of e.root.children)n(r);return t}},Zs={name:"complex-layer",description:"Detects Layer compositions that might be overly complex",severity:"warning",check:e=>{let t=[],n=0,r=0,o=s=>{He(s)&&(s.callee.includes("Layer.")||s.callee.includes(".provide"))&&(n++,(s.callee.includes("provide")||s.callee.includes("provideService"))&&r++);let a=v(s);if(ke.isSome(a))for(let i of a.value)o(i)};for(let s of e.root.children)o(s);return n>10&&t.push({rule:"complex-layer",message:`Program has ${n} Layer operations, which may be overly complex`,severity:"warning",suggestion:"Consider grouping related services into a single AppLayer, or using Layer.mergeAll for parallel composition"}),r>5&&t.push({rule:"complex-layer",message:`Program has ${r} Layer.provide calls, suggesting deep dependency nesting`,severity:"warning",suggestion:"Consider flattening your Layer hierarchy or using Layer.mergeAll instead of nested provides"}),t}},Xs={name:"catchAll-vs-catchTag",description:"Suggests using catchTag instead of catchAll when error type is tagged",severity:"info",check:e=>{let t=[],n=r=>{Et(r)&&r.handlerType==="catchAll"&&t.push({rule:"catchAll-vs-catchTag",message:"Using catchAll - consider catchTag if error type has _tag discriminator",severity:"info",location:r.location,nodeId:r.id,suggestion:'Use Effect.catchTag("ErrorTag", handler) for better type safety'});let o=v(r);if(ke.isSome(o))for(let s of o.value)n(s)};for(let r of e.root.children)n(r);return t}},ei={name:"error-type-too-wide",description:"Warns when error type is unknown or Error instead of tagged errors",severity:"warning",check:e=>{let t=[],n=r=>{if(He(r)){let s=r.typeSignature?.errorType.trim();(s==="unknown"||s==="Error")&&t.push({rule:"error-type-too-wide",message:`Effect "${r.callee}" has wide error type "${s}"`,severity:"warning",location:r.location,nodeId:r.id,suggestion:'Use branded/tagged errors (e.g. { _tag: "NotFound" }) for better handling'})}let o=v(r);if(ke.isSome(o))for(let s of o.value)n(s)};for(let r of e.root.children)n(r);return t}},ti={name:"unbounded-parallelism",description:"Warns when Effect.all uses unbounded concurrency",severity:"warning",check:e=>{let t=[],n=r=>{gn(r)&&r.concurrency==="unbounded"&&t.push({rule:"unbounded-parallelism",message:`Parallel effect uses unbounded concurrency (${r.children.length} branches)`,severity:"warning",location:r.location,nodeId:r.id,suggestion:"Consider { concurrency: N } to limit parallelism"});let o=v(r);if(ke.isSome(o))for(let s of o.value)n(s)};for(let r of e.root.children)n(r);return t}},ni={name:"redundant-pipe",description:"pipe() with single transformation could be inlined",severity:"info",check:e=>{let t=[],n=r=>{pn(r)&&r.transformations.length===0&&t.push({rule:"redundant-pipe",message:"Pipe has no transformations (only initial effect)",severity:"info",location:r.location,nodeId:r.id,suggestion:"Use the effect directly or add transformations"});let o=v(r);if(ke.isSome(o))for(let s of o.value)n(s)};for(let r of e.root.children)n(r);return t}},ri={name:"ordie-on-recoverable",description:"orDie converts errors to defects; ensure only used for unrecoverable cases",severity:"info",check:e=>{let t=[],n=r=>{Et(r)&&r.handlerType==="orDie"&&t.push({rule:"ordie-on-recoverable",message:"orDie used - typed errors become defects",severity:"info",location:r.location,nodeId:r.id,suggestion:"Reserve orDie for truly unrecoverable cases; handle recoverable errors with catchTag/catchAll"});let o=v(r);if(ke.isSome(o))for(let s of o.value)n(s)};for(let r of e.root.children)n(r);return t}},oi=[Js,Ys,Qs,Zs,Xs,ei,ti,ni,ri],gp=(e,t=oi)=>{let n=[];for(let a of t){let i=a.check(e);n.push(...i)}let r=n.filter(a=>a.severity==="error").length,o=n.filter(a=>a.severity==="warning").length,s=n.filter(a=>a.severity==="info").length;return{issues:n,summary:{errors:r,warnings:o,infos:s,total:n.length}}},mp=(e,t)=>{let n=[];if(n.push(`# Lint Report: ${t}`),n.push(""),n.push("## Summary"),n.push(`- **Errors**: ${e.summary.errors}`),n.push(`- **Warnings**: ${e.summary.warnings}`),n.push(`- **Info**: ${e.summary.infos}`),n.push(`- **Total Issues**: ${e.summary.total}`),n.push(""),e.issues.length>0){n.push("## Issues"),n.push("");for(let r of e.issues){let o=r.severity==="error"?"\u274C":r.severity==="warning"?"\u26A0\uFE0F":"\u2139\uFE0F";n.push(`${o} **${r.rule}** (${r.severity})`),n.push(` ${r.message}`),r.location&&n.push(` at ${r.location.filePath}:${r.location.line}`),r.suggestion&&n.push(` \u{1F4A1} ${r.suggestion}`),n.push("")}}else n.push("## \u2705 No Issues Found"),n.push("");return n.join(`
|
|
552
|
+
`)};export{oi as DEFAULT_LINT_RULES,Zo as DEFAULT_THRESHOLDS,At as analyze,Yu as analyzeConfig,_n as analyzeEffectFile,jn as analyzeEffectSource,Ye as analyzeErrorFlow,Rt as analyzeErrorPropagation,fp as analyzeFiberLeaks,If as analyzeGenYields,ef as analyzeMatch,Cu as analyzeObservability,of as analyzePlatformUsage,ou as analyzeProgramGraph,rc as analyzeProject,du as analyzeProjectComposition,Wf as analyzeRequestBatching,Pf as analyzeRpcPatterns,xu as analyzeScopeResource,$t as analyzeServiceFlow,Ff as analyzeSqlPatterns,yu as analyzeStateFlow,_f as analyzeStm,Cf as analyzeTestingPatterns,Ol as assessComplexity,Ft as buildDataFlowGraph,Qe as buildLayerDependencyGraph,Zt as buildProjectServiceMap,wd as buildTopOffendersReport,Ee as calculateComplexity,au as calculateGraphComplexity,fd as calculatePathStatistics,Xs as catchAllVsCatchTagRule,vu as checkDICompleteness,kf as checkVersionCompat,Zs as complexLayerRule,Td as computeFileDiagramQuality,ss as computeProgramDiagramQuality,fr as constValueToJS,ep as createConstCache,Qs as deadCodeRule,Hf as decodePlaygroundPayload,xl as detectDiamondDependencies,Uo as detectLayerCycles,Bs as diffPrograms,zf as encodePlaygroundPayload,ei as errorTypeTooWideRule,jf as exportForPlayground,Li as extractCauseTypeSignature,Ie as extractEffectTypeSignature,hf as extractHttpApiStructure,Sn as extractLayerTypeSignature,Pi as extractScheduleTypeSignature,Mi as extractSchemaInfo,bt as extractServiceRequirements,Di as extractStreamTypeSignature,np as extractString,tp as extractStringArray,pd as filterPaths,Co as findCycles,Eo as findMigrationOpportunities,lc as findMigrationOpportunitiesInProject,El as findUnsatisfiedServices,Wl as formatComplexitySummary,Qu as formatConfigReport,wu as formatDICompletenessReport,Ru as formatDiagnostics,$u as formatDiagnosticsJSON,Tc as formatErrorSummary,pp as formatFiberLeakReport,mp as formatLintReport,dc as formatMigrationReport,Uu as formatTestChecklist,zu as formatTestMatrixAsCode,ju as formatTestMatrixMarkdown,Ii as formatTypeSignature,ru as generateMultipleShowcase,Pt as generatePaths,Xo as generatePathsWithMetadata,ms as generateShowcase,Lu as generateTestMatrix,Qf as getCached,gc as getConsumers,fc as getDataFlowOrder,su as getDependencies,iu as getDependents,As as getEffectVersion,bc as getErrorProducers,Ec as getErrorsAtPoint,pc as getProducers,v as getStaticChildren,Du as getSummary,ys as getTopologicalOrder,mc as getTransitiveDependencies,tr as inferBestDiagramType,Er as isSchemaType,fi as isStaticCauseNode,Si as isStaticConcurrencyPrimitiveNode,li as isStaticConditionalNode,He as isStaticEffectNode,Et as isStaticErrorHandlerNode,pi as isStaticExitNode,xi as isStaticFiberNode,Kt as isStaticGeneratorNode,ui as isStaticLayerNode,di as isStaticLoopNode,mi as isStaticMatchNode,gn as isStaticParallelNode,pn as isStaticPipeNode,si as isStaticRaceNode,ci as isStaticResourceNode,ii as isStaticRetryNode,gi as isStaticScheduleNode,yi as isStaticStreamNode,ai as isStaticTimeoutNode,hi as isStaticTransformNode,mn as isStaticUnknownNode,gp as lintEffectProgram,Dd as loadDiagramQualityHintsFromEslintJson,Ys as missingErrorHandlerRule,ri as orDieWarningRule,zs as parseSourceArg,ni as redundantPipeRule,yf as renderApiDocsMarkdown,Sf as renderApiDocsMermaid,ll as renderCausesMermaid,lu as renderCompositionMermaid,uu as renderCompositionWithServicesMermaid,pl as renderConcurrencyMermaid,yc as renderDataFlowMermaid,Al as renderDataflowMermaid,ol as renderDecisionsMermaid,_d as renderDependencyMatrix,jd as renderDependencyMatrixFromServiceMap,_s as renderDiffJSON,qs as renderDiffMarkdown,js as renderDiffMermaid,gs as renderDocumentation,$o as renderEnhancedMermaid,Lc as renderEnhancedMermaidEffect,Nc as renderErrorFlowMermaid,Xc as renderErrorsMermaid,as as renderExplanation,cu as renderGraphMermaid,Vd as renderInteractiveHTML,zd as renderJSON,Cl as renderLayerGraphMermaid,Nl as renderLayersMermaid,Ac as renderMermaid,Qd as renderMultiProgramDocs,Od as renderMultipleExplanations,Hd as renderMultipleJSON,qd as renderMultipleSummaries,xf as renderOpenApiPaths,$c as renderPathsMermaid,Gc as renderRailwayMermaid,Oc as renderRetryGanttMermaid,kl as renderRetryMermaid,Mc as renderSequenceMermaid,Wc as renderServiceGraphMermaid,Yc as renderServicesMermaid,Qc as renderServicesMermaidFromMap,fe as renderStaticMermaid,Kd as renderSummary,Il as renderTestabilityMermaid,yl as renderTimelineMermaid,Tt as resetIdCounter,ur as resolveConst,Hs as resolveGitSource,_e as resolveNode,oc as runCoverageAudit,Ot as schemaToJsonSchema,lp as selectFormats,Zf as setCached,rn as summarizePathSteps,ki as trackTypeTransformation,ti as unboundedParallelismRule,Js as untaggedYieldRule,hc as validateDataFlow,Iu as validateStrict,Cc as validateWorkflowErrors};
|
|
548
553
|
//# sourceMappingURL=index.js.map
|