effect-analyzer 0.1.0
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/README.md +202 -0
- package/dist/analyze-a8PswlPG.d.cts +1152 -0
- package/dist/analyze-a8PswlPG.d.ts +1152 -0
- package/dist/cli.js +198 -0
- package/dist/effect-workflow.cjs +5 -0
- package/dist/effect-workflow.cjs.map +1 -0
- package/dist/effect-workflow.d.cts +31 -0
- package/dist/effect-workflow.d.ts +31 -0
- package/dist/effect-workflow.js +5 -0
- package/dist/effect-workflow.js.map +1 -0
- package/dist/index.cjs +548 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +1895 -0
- package/dist/index.d.ts +1895 -0
- package/dist/index.js +548 -0
- package/dist/index.js.map +1 -0
- package/dist/lsp/server.js +8827 -0
- package/package.json +76 -0
- package/scripts/analyze-public-repos.ts +130 -0
- package/scripts/audit-ci.ts +213 -0
- package/scripts/audit-public-effect-modules.ts +111 -0
- package/scripts/baselines/effect-audit-baseline.json +14 -0
- package/scripts/benchmark.ts +107 -0
- package/scripts/diff-effect-scans.ts +87 -0
- package/scripts/effect-scan-utils.ts +275 -0
- package/scripts/eslint-rules/no-inline-type-import.js +39 -0
- package/scripts/fetch-effect-repo.ts +52 -0
- package/scripts/openapi-runtime-runner.mjs +66 -0
- package/scripts/scan-effect-internals.ts +53 -0
- package/scripts/scan-effect-top-level.ts +52 -0
- package/scripts/summarize-scan.ts +47 -0
- package/scripts/triage-effect-scan.ts +85 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,548 @@
|
|
|
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=n.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 r=e.getLeadingCommentRanges();if(r.length>0){let n=r[r.length-1];if(!n)return;let o=n.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}}},Ze=e=>{let t=n=>{let o=n.getJsDocs?.();if(o&&o.length>0)return o[0].getText();let s=n.getLeadingCommentRanges();if(s.length>0){let a=s[s.length-1];if(a){let i=a.getText();if(i.startsWith("/**"))return i}}},r=t(e);if(!r){let{SyntaxKind:n}=I(),o=e.getParent();for(;o&&!r;){let s=o.getKind();if(s===n.VariableStatement){r=t(o);break}if(s===n.VariableDeclarationList){let a=o.getParent();a&&(r=t(a));break}if(s===n.CallExpression||s===n.ArrowFunction||s===n.VariableDeclaration||s===n.ParenthesizedExpression)o=o.getParent();else break}}if(r)return Ai(r)};function Ai(e){let t=e.replace(/^\/\*\*/,"").replace(/\*\/$/,"").split(`
|
|
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.includes(".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 Eo,Option as bo}from"effect";import{Option as tc}from"effect";function po(e,t){for(let r of e){r.type==="effect"&&t.push(r);let n=tc.getOrElse(v(r),()=>[]);n.length>0&&po(n,t)}}function Nt(e){let t=[],r=[],n=new Set,o=new Map,s=[];po(e.root.children,s);for(let d of s){let l=d.typeSignature?.successType,f=(d.requiredServices??[]).map(u=>u.serviceId);if(l){n.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";r.push({from:l.id,to:f.id,key:u})}let a="__context__";for(let d of t)for(let l of d.reads)r.push({from:a,to:d.id,key:l});let i=[];for(let d of t)for(let l of d.reads)!n.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:r,producedKeys:n,undefinedReads:i,duplicateWrites:c}}function nc(e){let t=new Map,r=new Map;for(let s of e.nodes)t.set(s.id,0),r.set(s.id,[]);for(let s of e.edges){if(s.from==="__context__")continue;let a=r.get(s.from)??[];a.push(s.to),r.set(s.from,a),t.set(s.to,(t.get(s.to)??0)+1)}let n=[];for(let[s,a]of t)s!=="__context__"&&a===0&&n.push(s);let o=[];for(;n.length>0;){let s=n.shift();if(s===void 0)break;o.push(s);for(let a of r.get(s)??[]){let i=(t.get(a)??0)-1;t.set(a,i),i===0&&n.push(a)}}if(o.length===e.nodes.length)return o}function rc(e,t){let r=new Set;for(let n of e.edges)n.to===t&&n.from!=="__context__"&&r.add(n.from);return e.nodes.filter(n=>r.has(n.id))}function oc(e,t){let r=new Set;for(let n of e.edges)n.from===t&&r.add(n.to);return e.nodes.filter(n=>r.has(n.id))}function sc(e,t){let r=new Set,n=[];function o(s){if(!(r.has(s)||s==="__context__")){r.add(s);for(let a of e.edges)a.to===s&&(n.push(a.from),o(a.from))}}return o(t),n}function go(e){let t=[],r=new Set,n=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){r.add(a),n.add(a),i.push(a);for(let c of o.get(a)??[])if(!r.has(c))s(c,i);else if(n.has(c)){let d=i.indexOf(c);t.push(i.slice(d))}i.pop(),n.delete(a)}for(let a of e.nodes)r.has(a.id)||s(a.id,[]);return t}function ic(e){let t=[];for(let n of e.undefinedReads)t.push({severity:"warning",type:"undefined-read",message:`Effect "${n.readerName??n.readerId}" reads "${n.key}" which is never produced`,stepIds:[n.readerId],key:n.key});for(let n of e.duplicateWrites)t.push({severity:"warning",type:"duplicate-write",message:`Key "${n.key}" is written by multiple effects: ${n.writerIds.join(", ")}`,stepIds:n.writerIds,key:n.key});let r=go(e);for(let n of r)t.push({severity:"error",type:"cycle",message:`Circular data dependency: ${n.join(" -> ")}`,stepIds:n});return{valid:t.length===0,issues:t}}function ot(e){return e.replace(/[^a-zA-Z0-9_]/g,"_")}function ac(e){let t=[];t.push("flowchart LR"),t.push(""),t.push(" %% Data Flow Graph"),t.push("");for(let r of e.nodes){let n=r.name??r.id,o=r.writes?` [out: ${r.writes}]`:"";t.push(` ${ot(r.id)}["${n}${o}"]`)}t.push("");for(let r of e.edges)r.from!=="__context__"&&t.push(` ${ot(r.from)} -->|${r.key}| ${ot(r.to)}`);if(e.undefinedReads.length>0){t.push(""),t.push(" %% Undefined Reads (warnings)");for(let r of e.undefinedReads){let n=`undefined_${ot(r.key)}`;t.push(` ${n}[/"${r.key} (undefined)"/]`),t.push(` ${n} -.-> ${ot(r.readerId)}`)}t.push(""),t.push(" classDef warning fill:#fff3cd,stroke:#856404");for(let r of e.undefinedReads)t.push(` class undefined_${ot(r.key)} warning`)}return t.join(`
|
|
7
|
+
`)}import{Option as at}from"effect";function On(e){let t=e.trim();return t==="never"||t==="unknown"?[]:we(t)}function mo(e,t){for(let r of e){if(r.type==="effect"){let o=r,s=o.typeSignature?.errorType?On(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 n=at.getOrElse(v(r),()=>[]);n.length>0&&mo(n,t)}}function Ve(e){let t=[],r=new Set,n=new Map,o=[];mo(e.root.children,t);for(let s of t){s.errors.length===0&&o.push(s.stepId);for(let a of s.errors){r.add(a);let i=n.get(a)??[];i.push(s.stepId),n.set(a,i)}}return{allErrors:Array.from(r).sort(),stepErrors:t,errorToSteps:n,stepsWithoutErrors:o,allStepsDeclareErrors:o.length===0&&t.length>0}}function Vt(e,t){return Array.from(new Set([...e,...t])).sort()}function cc(e,t){let r=new Set(t);return e.filter(n=>!r.has(n))}function lc(e){let t=[],r=n=>{if(n.type==="effect"){let s=n.typeSignature?.errorType;s&&t.push(...On(s))}at.getOrElse(v(n),()=>[]).forEach(r)};return r(e),Vt([],t)}function ho(e){if(e.type==="cause")return e.causeKind;let t=at.getOrElse(v(e),()=>[]);for(let r of t){let n=ho(r);if(n)return n}}function it(e,t,r){let n=[...t];for(let o of e)if(o.type==="effect"){let s=o,a=s.typeSignature?.errorType?On(s.typeSignature.errorType):[];n=Vt(n,a),r.push({atNode:s.id,possibleErrors:[...n],defects:[],interruptible:!1});let i=at.getOrElse(v(o),()=>[]);i.length>0&&(n=it(i,n,r))}else if(o.type==="error-handler"){let s=o;n=it([s.source],n,r);let a=[...n],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=cc(n,i),d=s.handler?lc(s.handler):[];if((s.handlerType==="mapError"||s.handlerType==="mapErrorCause"||s.handlerType==="mapBoth")&&i.length>0&&d.length===0){let l=ho(s.source);l==="fail"?d=["<mapped-fail>"]:l==="die"?d=["<mapped-defect>"]:d=["<mapped-error>"]}n=Vt(c,d),r.push({atNode:s.id,possibleErrors:[...n],narrowedBy:{handler:s.handlerType,removedErrors:i,addedErrors:d},defects:[],interruptible:!1}),s.handler&&(n=it([s.handler],n,r))}else if(o.type==="parallel"||o.type==="race"){let s=at.getOrElse(v(o),()=>[]),a=[];for(let i of s){let c=it([i],n,r);a=Vt(a,c)}n=a}else{let s=at.getOrElse(v(o),()=>[]);s.length>0&&(n=it(s,n,r))}return n}function vt(e){let t=[];it(e.root.children,[],t);let r=new Map;for(let n of t)r.set(n.atNode,n);return{propagation:t,byNodeId:r}}function dc(e,t){let r=new Set,n=!1;for(let o of e.stepErrors){for(let s of o.errors)r.add(s);if(o.stepId===t){n=!0;break}}return n?Array.from(r).sort():e.allErrors}function uc(e,t){let r=e.errorToSteps.get(t)??[];return e.stepErrors.filter(n=>r.includes(n.stepId))}function fc(e,t){let r=new Set(t),n=new Set(e.allErrors),o=t.filter(a=>!n.has(a)),s=e.allErrors.filter(a=>!r.has(a));return{valid:o.length===0&&s.length===0,unusedDeclared:o,undeclaredErrors:s,computedErrors:e.allErrors}}function st(e){return e.replace(/[^a-zA-Z0-9_]/g,"_")}function pc(e){let t=[];t.push("flowchart LR"),t.push(""),t.push(" %% Error Flow Graph"),t.push(""),t.push(" subgraph Steps");for(let r of e.stepErrors){let n=r.stepName??r.stepId;t.push(` ${st(r.stepId)}["${n}"]`)}if(t.push(" end"),t.push(""),e.allErrors.length>0){t.push(" subgraph Errors");for(let r of e.allErrors)t.push(` err_${st(r)}(["${r}"])`);t.push(" end"),t.push("");for(let r of e.stepErrors)for(let n of r.errors)t.push(` ${st(r.stepId)} -.->|throws| err_${st(n)}`)}t.push(""),t.push(" classDef error fill:#ffcdd2,stroke:#c62828");for(let r of e.allErrors)t.push(` class err_${st(r)} error`);if(e.stepsWithoutErrors.length>0){t.push(""),t.push(" classDef noErrors fill:#fff3cd,stroke:#856404");for(let r of e.stepsWithoutErrors)t.push(` class ${st(r)} noErrors`)}return t.join(`
|
|
8
|
+
`)}function gc(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 r of e.allErrors){let n=e.errorToSteps.get(r)??[];t.push(`- \`${r}\` - produced by: ${n.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 r of e.stepsWithoutErrors)t.push(`- ${r}`);t.push("")}t.push("### Effect Error Details"),t.push(""),t.push("| Effect | Errors |"),t.push("|--------|--------|");for(let r of e.stepErrors){let n=r.stepName??r.stepId,o=r.errors.length>0?r.errors.map(s=>`\`${s}\``).join(", "):"_none_";t.push(`| ${n} | ${o} |`)}return t.join(`
|
|
9
|
+
`)}var Co={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"},Wn={direction:"TB",includeIds:!1,includeDescriptions:!0,styles:Co,compact:!1,includeTypeSignatures:!0,useSubgraphs:!0,showConditions:!0,detail:"verbose"};function X(e){return e.replace(/\r?\n/g," ").replace(/"/g,"'").replace(/\[/g,"(").replace(/\]/g,")").replace(/\{/g,"(").replace(/\}/g,")").replace(/#/g,"#").replace(/\|/g,"|")}function ct(e,t){return e.length<=t?e:e.slice(0,t-3)+"..."}function mc(e){return e.replace(/[^a-zA-Z0-9_]/g,"_")}function No(e,t,r){let n={...Wn,...t,useSubgraphs:t?.useSubgraphs??!0,showConditions:t?.showConditions??!0,detail:t?.detail??"verbose"},o={opts:n,nodeCounter:0,edges:[],subgraphs:[],styleClasses:new Map,nodeIdMap:new Map,nodeLabelAnnotations:r},s=[];s.push(`flowchart ${n.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}=he(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&&n.showConditions?s.push(` ${f.from} -->|${X(f.label)}| ${f.to}`):s.push(` ${f.from} --> ${f.to}`);let l={...Co,...n.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=Nt(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=Ve(e),u=vt(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),S=p.get(g.atNode);if(m&&S){let h=g.narrowedBy.removedErrors.join(", ");s.push(` ${S} -.->|catches ${h}| ${m}`)}}}return{lines:s,context:o}}function he(e,t,r){if(e.length===0)return{firstNodeId:null,lastNodeIds:[]};let n=null,o=[];for(let s of e){let a=Z(s,t,r);if(n===null&&a.firstNodeId&&(n=a.firstNodeId),a.firstNodeId)for(let i of o)t.edges.push({from:i,to:a.firstNodeId});o=a.lastNodeIds}return{firstNodeId:n,lastNodeIds:o}}function hc(e,t){let r=t.opts.includeIds&&"id"in e?e.id:`n${String(++t.nodeCounter)}`;return mc(r)}function yc(e,t,r){if(!t.includeDescriptions)return e.type;let n;switch(e.type){case"effect":n=e.callee||"Effect";break;case"generator":n=`Generator (${e.yields.length} yields)`;break;case"pipe":n=`Pipe (${e.transformations.length+1} steps)`;break;case"parallel":n=`${e.callee} (${e.children.length} effects)`;break;case"race":n=`${e.callee} (${e.children.length} racing)`;break;case"error-handler":n=e.handlerType;break;case"retry":n=`Retry${e.schedule?`(${e.schedule})`:""}`;break;case"timeout":n=`Timeout${e.duration?`(${e.duration})`:""}`;break;case"resource":n="Resource";break;case"conditional":n=`${e.conditionalType} (${ct(e.condition,20)})`;break;case"loop":n=`${e.loopType}${e.iterSource?`(${e.iterSource})`:""}`;break;case"layer":n=`Layer${e.isMerged?" (merged)":""}`;break;case"stream":n=`Stream${e.pipeline.length>0?`.${e.pipeline.map(o=>o.operation).join(" \u2192 ")}`:""}${e.sink?` \u2192 ${e.sink}`:""}`;break;case"concurrency-primitive":n=`${e.primitive}.${e.operation}${e.strategy?` (${e.strategy})`:""}`;break;case"fiber":n=`${e.operation}${e.isDaemon?" (daemon)":""}${e.isScoped?" (scoped)":""}`;break;case"decision":n=e.label||ct(e.condition,30);break;case"switch":n=`Switch: ${ct(e.expression,25)}`;break;case"try-catch":n="Try/Catch";break;case"terminal":n=e.terminalKind;break;case"opaque":n=`\u26A0 ${e.reason}`;break;case"cause":n=`Cause: ${e.causeOp}`;break;case"exit":n=`Exit: ${e.exitOp}`;break;case"schedule":n=`Schedule: ${e.scheduleOp}`;break;case"match":n=`Match: ${e.matchOp}${e.matchedTags?.length?` (${e.matchedTags.join(", ")})`:""}`;break;case"transform":n=`${e.transformType}${e.isEffectful?" (effectful)":""}`;break;case"channel":n=`Channel${e.pipeline.length>0?`.${e.pipeline.map(o=>o.operation).join(" \u2192 ")}`:""}`;break;case"sink":n=`Sink${e.pipeline.length>0?`.${e.pipeline.map(o=>o.operation).join(" \u2192 ")}`:""}`;break;case"interruption":n=e.interruptionType;break;case"unknown":n=`Unknown: ${e.reason}`;break;default:{n=e.type??"unknown";break}}if(t.detail!=="compact"&&e.displayName&&(n=e.displayName),t.detail==="verbose"){if(e.type==="effect"&&t.includeTypeSignatures&&e.typeSignature){let o=e.typeSignature;n+=`
|
|
10
|
+
<${o.successType}, ${o.errorType}, ${o.requirementsType}>`}e.semanticRole&&e.semanticRole!=="unknown"&&e.semanticRole!=="constructor"&&(n+=`
|
|
11
|
+
(${e.semanticRole})`)}return r?.length&&(n+=`
|
|
12
|
+
`+r.join(`
|
|
13
|
+
`)),n}function Sc(e){return e.type==="concurrency-primitive"?"concurrencyPrimitiveStyle":e.type==="try-catch"?"tryCatchStyle":e.type==="error-handler"?"errorHandlerStyle":`${e.type}Style`}function Z(e,t,r){let n=hc(e,t),o=t.nodeLabelAnnotations?.get(e.id),s=yc(e,t.opts,o),a=Sc(e);switch(e.type!=="generator"&&(r.push(` ${n}["${X(s)}"]`),t.styleClasses.set(n,a),t.nodeIdMap.set(e.id,n)),e.type){case"effect":case"unknown":return{firstNodeId:n,lastNodeIds:[n]};case"stream":{let i=Z(e.source,t,r);return i.firstNodeId&&t.edges.push({from:n,to:i.firstNodeId}),{firstNodeId:n,lastNodeIds:i.lastNodeIds}}case"concurrency-primitive":{if(e.source){let i=Z(e.source,t,r);return i.firstNodeId&&t.edges.push({from:n,to:i.firstNodeId}),{firstNodeId:n,lastNodeIds:i.lastNodeIds}}return{firstNodeId:n,lastNodeIds:[n]}}case"fiber":{if(e.fiberSource){let i=Z(e.fiberSource,t,r);return i.firstNodeId&&t.edges.push({from:n,to:i.firstNodeId}),{firstNodeId:n,lastNodeIds:i.lastNodeIds}}return{firstNodeId:n,lastNodeIds:[n]}}case"generator":{let i=e.yields.map(d=>d.effect),c=he(i,t,r);return c.firstNodeId?{firstNodeId:c.firstNodeId,lastNodeIds:c.lastNodeIds.length>0?c.lastNodeIds:[c.firstNodeId]}:(r.push(` ${n}["${X(s)}"]`),t.styleClasses.set(n,a),t.nodeIdMap.set(e.id,n),{firstNodeId:n,lastNodeIds:[n]})}case"pipe":{let i=[e.initial,...e.transformations],c=he(i,t,r);return c.firstNodeId&&t.edges.push({from:n,to:c.firstNodeId}),{firstNodeId:n,lastNodeIds:c.lastNodeIds.length>0?c.lastNodeIds:[n]}}case"parallel":{let i=`parallel_fork_${++t.nodeCounter}`,c=`parallel_join_${t.nodeCounter}`,d=e.mode==="parallel"?"Parallel":"All";r.push(` ${i}{{"${d} (${e.children.length})"}}`),r.push(` ${c}{{"Join"}}`),t.styleClasses.set(i,"parallelStyle"),t.styleClasses.set(c,"parallelStyle"),t.edges.push({from:n,to:i});for(let l=0;l<e.children.length;l++){let f=e.children[l];if(!f)continue;let u=Z(f,t,r);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:n,lastNodeIds:[c]}}case"race":{let i=`race_fork_${++t.nodeCounter}`,c=`race_join_${t.nodeCounter}`;r.push(` ${i}{{{"Race (${e.children.length})"}}}`),r.push(` ${c}{{{"Winner"}}}`),t.styleClasses.set(i,"raceStyle"),t.styleClasses.set(c,"raceStyle"),t.edges.push({from:n,to:i});for(let d=0;d<e.children.length;d++){let l=e.children[d];if(!l)continue;let f=Z(l,t,r);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:n,lastNodeIds:[c]}}case"error-handler":{let i=Z(e.source,t,r),c=`err_handler_${++t.nodeCounter}`;r.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=Z(e.handler,t,r);l.firstNodeId&&t.edges.push({from:c,to:l.firstNodeId}),d=l.lastNodeIds}return{firstNodeId:i.firstNodeId??n,lastNodeIds:d}}case"retry":case"timeout":{let i=Z(e.source,t,r),c=`${e.type}_${++t.nodeCounter}`,d=e.type==="retry"?`Retry${e.schedule?`(${e.schedule})`:""}`:`Timeout${e.duration?`(${e.duration})`:""}`;return r.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??n,lastNodeIds:[c]}}case"resource":{let i=Z(e.acquire,t,r),c=`resource_${++t.nodeCounter}`;r.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=Z(e.use,t,r);l.firstNodeId&&t.edges.push({from:c,to:l.firstNodeId}),d=l.lastNodeIds}return{firstNodeId:i.firstNodeId??n,lastNodeIds:d}}case"conditional":{let i=`cond_${++t.nodeCounter}`,c=e.conditionLabel??ct(e.condition,25);r.push(` ${i}{"${X(c)}"}`),t.styleClasses.set(i,"conditionalStyle"),t.edges.push({from:n,to:i});let d=Z(e.onTrue,t,r);d.firstNodeId&&t.edges.push({from:i,to:d.firstNodeId,label:e.trueEdgeLabel??"true"});let l=[...d.lastNodeIds];if(e.onFalse){let f=Z(e.onFalse,t,r);f.firstNodeId&&t.edges.push({from:i,to:f.firstNodeId,label:e.falseEdgeLabel??"false"}),l.push(...f.lastNodeIds)}else l.push(i);return{firstNodeId:n,lastNodeIds:l}}case"loop":{let i=`loop_${++t.nodeCounter}`,c=`${e.loopType}${e.iterSource?`(${e.iterSource})`:""}`;r.push(` ${i}(["${X(c)}"])`),t.styleClasses.set(i,"loopStyle"),t.edges.push({from:n,to:i});let d=Z(e.body,t,r);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:n,lastNodeIds:[i]}}case"layer":{let i=he(e.operations,t,r);return i.firstNodeId&&t.edges.push({from:n,to:i.firstNodeId}),{firstNodeId:n,lastNodeIds:i.lastNodeIds.length>0?i.lastNodeIds:[n]}}case"decision":{let i=`decision_${++t.nodeCounter}`,c=e.label||ct(e.condition,25);r.push(` ${i}{"${X(c)}"}`),t.styleClasses.set(i,"decisionStyle");let d=he(e.onTrue,t,r);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=he(e.onFalse,t,r);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: ${ct(e.expression,20)}`;r.push(` ${i}{"${X(c)}"}`),t.styleClasses.set(i,"switchStyle");let d=[];for(let l of e.cases){let f=l.labels.join(" / "),u=he(l.body,t,r);u.firstNodeId&&t.edges.push({from:i,to:u.firstNodeId,label:f}),d.push(...u.lastNodeIds)}if(e.hasFallthrough){let l=`switchWarn_${++t.nodeCounter}`;r.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=he(e.tryBody,t,r),c=[...i.lastNodeIds];if(e.catchBody&&e.catchBody.length>0){let d=`catch_${++t.nodeCounter}`,l=e.catchVariable?`Catch(${e.catchVariable})`:"Catch";r.push(` ${d}["${X(l)}"]`),t.styleClasses.set(d,"tryCatchStyle");for(let u of i.lastNodeIds)t.edges.push({from:u,to:d,label:"on error"});let f=he(e.catchBody,t,r);f.firstNodeId&&t.edges.push({from:d,to:f.firstNodeId}),c.push(...f.lastNodeIds)}if(e.finallyBody&&e.finallyBody.length>0){let d=he(e.finallyBody,t,r);if(d.firstNodeId)for(let l of c)t.edges.push({from:l,to:d.firstNodeId,label:"finally"});return{firstNodeId:i.firstNodeId??n,lastNodeIds:d.lastNodeIds}}return{firstNodeId:i.firstNodeId??n,lastNodeIds:c.length>0?c:[n]}}case"terminal":{let i=`term_${++t.nodeCounter}`,c=e.terminalKind;if(r.push(` ${i}(["${X(c)}"])`),t.styleClasses.set(i,"terminalStyle"),e.value&&e.value.length>0){let d=he(e.value,t,r);d.firstNodeId&&t.edges.push({from:n,to:d.firstNodeId});for(let l of d.lastNodeIds)t.edges.push({from:l,to:i})}return{firstNodeId:e.value?.length?n:i,lastNodeIds:[]}}case"opaque":{let i=`opaque_${++t.nodeCounter}`;return r.push(` ${i}{{"${X(`\u26A0 ${e.reason}`)}"}}`),t.styleClasses.set(i,"opaqueStyle"),{firstNodeId:i,lastNodeIds:[i]}}case"cause":{let i=`cause_${++t.nodeCounter}`;if(r.push(` ${i}{{"${X(s)}"}}`),t.styleClasses.set(i,"causeStyle"),t.nodeIdMap.set(e.id,i),e.children&&e.children.length>0){let c=he([...e.children],t,r);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 r.push(` ${i}(["${X(s)}"])`),t.styleClasses.set(i,"exitStyle"),t.nodeIdMap.set(e.id,i),{firstNodeId:i,lastNodeIds:[i]}}case"schedule":{let i=`schedule_${++t.nodeCounter}`;return r.push(` ${i}[/"${X(s)}"/]`),t.styleClasses.set(i,"scheduleStyle"),t.nodeIdMap.set(e.id,i),{firstNodeId:i,lastNodeIds:[i]}}case"match":{let i=`match_${++t.nodeCounter}`;if(r.push(` ${i}{"${X(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}`;r.push(` ${l}["${X(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=Z(e.source,t,r);return i.lastNodeIds.length>0&&t.edges.push({from:i.lastNodeIds[0],to:n}),{firstNodeId:i.firstNodeId??n,lastNodeIds:[n]}}return{firstNodeId:n,lastNodeIds:[n]}}case"channel":{let i=`channel_${++t.nodeCounter}`;if(r.push(` ${i}[["${X(s)}"]]`),t.styleClasses.set(i,"channelStyle"),t.nodeIdMap.set(e.id,i),e.source){let c=Z(e.source,t,r);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(r.push(` ${i}[("${X(s)}")]`),t.styleClasses.set(i,"sinkStyle"),t.nodeIdMap.set(e.id,i),e.source){let c=Z(e.source,t,r);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(r.push(` ${i}{{"${X(s)}"}}`),t.styleClasses.set(i,"interruptionStyle"),t.nodeIdMap.set(e.id,i),e.source){let c=Z(e.source,t,r);c.firstNodeId&&t.edges.push({from:i,to:c.firstNodeId});let d=[...c.lastNodeIds];if(e.handler){let l=Z(e.handler,t,r);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:n,lastNodeIds:[n]}}}function le(e,t){let r={...Wn,...t},{lines:n}=No(e,r);return n.join(`
|
|
14
|
+
`)}var xc=(e,t)=>Eo.sync(()=>le(e,t));function yo(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 So(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 xo(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 Ec(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(n=>t.startsWith(n)):!1}function bc(e,t){if(!(t.prefixServiceBoundaries??t.styleGuide??!1))return[...e];let n=[...e],o=0;for(let s=0;s<n.length&&!(o>=2);s++){let a=n[s];a&&Ec(a.name)&&!a.name.startsWith("svc: ")&&(n[s]={...a,name:`svc: ${a.name}`},o++)}return n}function Gt(e,t){let r=t.collapseRepeatedLogs??!0,n=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(r&&yo(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(!yo(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(n&&So(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(!So(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&&xo(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(!xo(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:bc(s,t),collapsedGroups:a}}function Cc(e,t={}){let r=t.direction??"TB",n=[];n.push(`flowchart ${r}`),n.push("");let o=new Map,s=0,a=e.map(c=>Gt(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})}n.push(" start((Start))"),n.push(" end_node((End))"),n.push("");for(let[,c]of o)n.push(` ${c.id}["${X(c.name)}"]`);n.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],S=o.get(g.key),h=o.get(m.key);i.add(`${S.id} --> ${h.id}`)}let f=c[c.length-1],u=o.get(f.key);i.add(`${u.id} --> end_node`)}n.push(" %% Edges");for(let c of i)n.push(` ${c}`);return n.join(`
|
|
15
|
+
`)}var Nc={...Wn,showTypeSignatures:!0,showRequiredServices:!0,showErrorNodes:!1};function vc(e,t){let r=new Map,n=t.showTypeSignatures!==!1,o=t.showRequiredServices===!0;function s(a){if(a.type==="effect"){let i=[];if(n&&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&&r.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 r}function vo(e,t){let r={...Nc,...t},n=vc(e,r),{lines:o}=No(e,r,n);return o.join(`
|
|
16
|
+
`)}var wc=(e,t)=>Eo.sync(()=>vo(e,t));function wo(e,t){for(let r of e){r.type==="fiber"&&t.push(r);let n=bo.getOrElse(v(r),()=>[]);n.length>0&&wo(n,t)}}function Tc(e){let t=[];wo(e.root.children,t);let r=t.filter(s=>s.operation==="fork"||s.operation==="forkScoped"||s.operation==="forkDaemon"),n=t.filter(s=>s.operation==="join"||s.operation==="await");if(r.length===0&&n.length===0)return`sequenceDiagram
|
|
17
|
+
participant Main
|
|
18
|
+
note over Main: No fiber operations detected`;let o=["sequenceDiagram"," participant Main"];return r.forEach((s,a)=>{o.push(` participant Fiber${a+1}`)}),o.push(""),r.forEach((s,a)=>{let i=s.fiberSource?s.fiberSource.callee??"effect":"effect";o.push(` Main->>Fiber${a+1}: fork(${i})`)}),n.forEach((s,a)=>{let i=Math.min(a+1,r.length);o.push(` Fiber${i}-->>Main: join`)}),o.join(`
|
|
19
|
+
`)}function To(e,t){for(let r of e){r.type==="retry"&&t.push(r);let n=bo.getOrElse(v(r),()=>[]);n.length>0&&To(n,t)}}function kc(e){let t=[];To(e.root.children,t);let r=t.filter(o=>o.scheduleInfo);if(r.length===0)return`gantt
|
|
20
|
+
title Retry Schedule
|
|
21
|
+
section Retries
|
|
22
|
+
No retry schedules detected`;let n=["gantt"," title Retry Schedule"," section Attempts"];return r.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++)n.push(` Attempt ${c+1}: a${s}_${c}, ${c===0?"0":`after a${s}_${c-1}`}, 100ms`),c<i-1&&n.push(` Wait: w${s}_${c}, after a${s}_${c}, 200ms`)}),n.join(`
|
|
23
|
+
`)}function Ic(e,t={}){let r=t.direction??"TB",n=[],o=a=>a.replace(/[^a-zA-Z0-9_]/g,"_");n.push(`flowchart ${r}`),n.push(""),n.push(" %% Service Dependency Graph"),n.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;n.push(` ${c}{{{"${l}"}}}`)}for(let a of e.unresolvedServices){let i=`unresolved_${o(a)}`;n.push(` ${i}["? ${a}"]`)}n.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)}`;n.push(` ${f} -->|"${c.name}"| ${u}`)}n.push(""),n.push(" classDef service fill:#E3F2FD,stroke:#1565C0,stroke-width:2px"),n.push(" classDef unresolved fill:#FFF3CD,stroke:#856404,stroke-dasharray:5");for(let a of e.services.keys())n.push(` class ${o(a)} service`);for(let a of e.unresolvedServices)n.push(` class unresolved_${o(a)} unresolved`);return n.join(`
|
|
24
|
+
`)}import{Option as Io}from"effect";function Jt(e){let t=String.fromCharCode(65+e%26),r=Math.floor(e/26);return r===0?t:`${t}${r}`}function Yt(e){return e.replace(/"/g,"#quot;").replace(/</g,"#lt;").replace(/>/g,"#gt;").replace(/\(/g,"#lpar;").replace(/\)/g,"#rpar;")}function ko(e){return e.replace(/(Error|Exception)$/,"")}function Ac(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()===""?[]:we(t).filter(r=>r!=="never")}function Fc(e){let t=new Set,r=[],n=o=>{for(let a of Ac(o))t.has(a)||(t.add(a),r.push(a));let s=Io.getOrElse(v(o),()=>[]);for(let a of s)n(a)};return n(e),r}function Rc(e){if(e.displayName)return e.displayName;if(e.type==="effect"){if(e.name){let t=e.name.replace(/^Effect\./,"");return t.charAt(0).toUpperCase()+t.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}function $c(e){switch(e.type){case"generator":case"pipe":return!0;default:return!1}}function Dc(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 Pc(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 Mc(e){if(e.type!=="effect")return!1;let t=e.callee??"";if(t==="Effect.fn"||t.startsWith("Effect.fn("))return!0;let r=e.displayName??"";return!!(!(r&&r!==t&&r!==e.type)||t.startsWith("Schema.")||t.startsWith("Data."))}function Lc(e){let t=[],r=n=>{if($c(n)){let o=Io.getOrElse(v(n),()=>[]);for(let s of o)r(s);return}if(!Pc(n)){if(Dc(n)){t.push(n);return}Mc(n)||t.push(n)}};for(let n of e)r(n);return t}function Oc(e){return e.map(t=>({label:Rc(t),errorTypes:Fc(t)}))}function Wc(e,t={}){let r=t.direction??"LR",n=Lc(e.root.children),o=Oc(n);if(o.length===0)return`flowchart ${r}
|
|
25
|
+
Empty((No steps))`;let s=[`flowchart ${r}`],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=Jt(c),f=Yt(d.label);if(c<o.length-1){let u=o[c+1];if(!u)continue;let p=Jt(c+1),g=Yt(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=Jt(c),u=`${f}E`,p=Yt(l.map(ko).join(" / "));a.push(` ${f} -->|err| ${u}[${p}]`)}else if(e.root.errorTypes.length>0){let c=Jt(o.length-1),d=Yt(e.root.errorTypes.map(ko).join(" / "));a.push(` ${c} -->|err| Errors[${d}]`)}return[...s,...a].join(`
|
|
26
|
+
`)}import{Option as Ao}from"effect";function Fo(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 r=Ao.getOrElse(v(e),()=>[]);for(let n of r)Fo(n,t)}function Kc(e,t){let r=e.callee;if(r.includes("provideService")||r.includes("provide"))return t(e)}function wt(e,t){let r=[];for(let f of e.root.children)Fo(f,r);let n=Array.from(new Map(r.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?Kc(g,c):void 0;if(m){i.add(m);let h={nodeId:g.id,serviceId:m};g.location&&(h.location=g.location),o.push(h)}let S=g.requiredServices??[];for(let h of S){let N=a.get(h.serviceId)??[];if(N.push(g.id),a.set(h.serviceId,N),!i.has(h.serviceId)){let x={nodeId:g.id,serviceId:h.serviceId};h.serviceType!==void 0&&(x.serviceType=h.serviceType),h.requiredAt!==void 0&&(x.location=h.requiredAt),s.push(x)}}}let p=Ao.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 n)l.has(f.serviceId)||l.set(f.serviceId,{createdAt:"",consumedAt:a.get(f.serviceId)??[]});return{requiredServices:n,providedServices:o,unsatisfiedAt:s,serviceLifecycle:l}}function Kn(e){return e.replace(/"/g,"#quot;").replace(/</g,"#lt;").replace(/>/g,"#gt;").replace(/\(/g,"#lpar;").replace(/\)/g,"#rpar;")}function Ee(e){return e.replace(/[^a-zA-Z0-9_]/g,"_")}function Bc(e,t={}){let r=t.direction??"LR",{requiredServices:n,providedServices:o}=wt(e),s=e.root.dependencies,a=new Set;for(let d of n)a.add(d.serviceId);for(let d of s)a.add(d.name);if(a.size===0&&o.length===0)return`flowchart ${r}
|
|
27
|
+
NoServices((No services))`;let i=[`flowchart ${r}`],c=Kn(e.root.programName);i.push(` prog["${c}"]`),i.push("");for(let d of a){let l=`svc_${Ee(d)}`,f=Kn(d);i.push(` ${l}{{"${f}"}}`),i.push(` prog -->|requires| ${l}`)}for(let d of o){let l=`prov_${Ee(d.serviceId)}`,f=Kn(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 n)i.push(` class svc_${Ee(d.serviceId)} required`);for(let d of o)i.push(` class prov_${Ee(d.serviceId)} provided`);return i.join(`
|
|
28
|
+
`)}function qc(e,t={}){let n=[`flowchart ${t.direction??"TB"}`];n.push(""),n.push(" %% Service Dependency Graph"),n.push("");for(let[s,a]of e.services){let i=Ee(s),c=a.definition.methods.length,d=c>0?`${s}\\n(${c} method${c===1?"":"s"})`:s;n.push(` ${i}{{"${d}"}}`)}for(let s of e.unresolvedServices){let a=`unresolved_${Ee(s)}`;n.push(` ${a}["? ${s}"]`)}n.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=Ee(s),f=e.services.has(c)?Ee(c):`unresolved_${Ee(c)}`;n.push(` ${l} -->|"${i.name}"| ${f}`)}n.push(""),n.push(" classDef service fill:#E3F2FD,stroke:#1565C0,stroke-width:2px"),n.push(" classDef unresolved fill:#FFF3CD,stroke:#856404,stroke-dasharray:5");for(let s of e.services.keys())n.push(` class ${Ee(s)} service`);for(let s of e.unresolvedServices)n.push(` class unresolved_${Ee(s)} unresolved`);return n.join(`
|
|
29
|
+
`)}function Bn(e){return e.replace(/"/g,"#quot;").replace(/</g,"#lt;").replace(/>/g,"#gt;").replace(/\(/g,"#lpar;").replace(/\)/g,"#rpar;")}function Ie(e){return e.replace(/[^a-zA-Z0-9_]/g,"_")}function jc(e){return e.replace(/(Error|Exception)$/,"")}function _c(e,t={}){let r=t.direction??"LR",n=Ve(e),o=vt(e);if(n.allErrors.length===0)return`flowchart ${r}
|
|
30
|
+
NoErrors((No errors))`;let s=[`flowchart ${r}`],a=[],i=new Set;for(let l of o.propagation)if(l.narrowedBy&&l.narrowedBy.removedErrors.length>0){let f=`handler_${Ie(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=n.allErrors.filter(l=>!i.has(l)),d=n.stepErrors.filter(l=>l.errors.length>0);if(d.length>0){s.push(""),s.push(" subgraph Steps");for(let l of d){let f=Bn(l.stepName??l.stepId);s.push(` step_${Ie(l.stepId)}["${f}"]`)}s.push(" end")}s.push(""),s.push(" subgraph Errors");for(let l of n.allErrors){let f=Bn(jc(l));s.push(` err_${Ie(l)}("${f}")`)}if(s.push(" end"),a.length>0){s.push(""),s.push(" subgraph Handlers");for(let l of a){let f=Bn(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_${Ie(l.stepId)} --produces--> err_${Ie(f)}`);for(let l of a)for(let f of l.removedErrors)n.allErrors.includes(f)&&s.push(` err_${Ie(f)} --caught by--> ${l.id}`);for(let l of c)s.push(` err_${Ie(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_${Ie(l.stepId)} stepStyle`);for(let l of n.allErrors)s.push(` class err_${Ie(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 zc}from"effect";var Hc=new Set(["conditional","decision","switch","match"]);function Me(e){return e.replace(/"/g,"#quot;").replace(/</g,"#lt;").replace(/>/g,"#gt;").replace(/\(/g,"#lpar;").replace(/\)/g,"#rpar;")}function qn(e,t=40){return e.length>t?e.slice(0,t-3)+"...":e}function $o(e){return e.displayName?e.displayName:e.name?e.name:e.type==="effect"?e.callee:e.type}function Uc(e){let t=[],r=0,n=o=>{Hc.has(o.type)&&t.push({node:o,nodeId:`D${r++}`});let s=zc.getOrElse(v(o),()=>[]);for(let a of s)n(a);if(o.type==="conditional"){let a=o;n(a.onTrue),a.onFalse&&n(a.onFalse)}else if(o.type==="decision"){let a=o;for(let i of a.onTrue)n(i);if(a.onFalse)for(let i of a.onFalse)n(i)}else if(o.type==="switch"){let a=o;for(let i of a.cases)for(let c of i.body)n(c)}};for(let o of e)n(o);return t}function Do(e,t){return e.find(r=>r.node===t)}function Vc(e,t){for(let r of t){let n=Do(e,r);if(n)return n}}function Ro(e,t,r){if(!e){let a=`T${r.value++}`;return{targetId:a,extraLine:` ${a}["..."]`}}let n=Do(t,e);if(n)return{targetId:n.nodeId};let o=Me($o(e)),s=`T${r.value++}`;return{targetId:s,extraLine:` ${s}["${o}"]`}}function jn(e,t,r){if(!e||e.length===0){let i=`T${r.value++}`;return{targetId:i,extraLine:` ${i}["..."]`}}let n=Vc(t,e);if(n)return{targetId:n.nodeId};let o=e[0];if(!o){let i=`T${r.value++}`;return{targetId:i,extraLine:` ${i}["..."]`}}let s=Me($o(o)),a=`T${r.value++}`;return{targetId:a,extraLine:` ${a}["${s}"]`}}function Gc(e,t={}){let r=t.direction??"TB",n=Uc(e.root.children);if(n.length===0)return`flowchart ${r}
|
|
32
|
+
NoDec((No decisions))`;let o=[`flowchart ${r}`],s={value:0};for(let{node:a,nodeId:i}of n)switch(a.type){case"conditional":{let c=a,d=Me(qn(c.condition));o.push(` ${i}{${d}}`);let l=c.trueEdgeLabel??"true",f=c.falseEdgeLabel??"false",u=Ro(c.onTrue,n,s);if(u.extraLine&&o.push(u.extraLine),o.push(` ${i} -->|${l}| ${u.targetId}`),c.onFalse){let p=Ro(c.onFalse,n,s);p.extraLine&&o.push(p.extraLine),o.push(` ${i} -->|${f}| ${p.targetId}`)}break}case"decision":{let c=a,d=Me(qn(c.condition));o.push(` ${i}{${d}}`);let l=jn(c.onTrue,n,s);if(l.extraLine&&o.push(l.extraLine),o.push(` ${i} -->|true| ${l.targetId}`),c.onFalse){let f=jn(c.onFalse,n,s);f.extraLine&&o.push(f.extraLine),o.push(` ${i} -->|false| ${f.targetId}`)}break}case"switch":{let c=a,d=Me(qn(c.expression));o.push(` ${i}{${d}}`);for(let l of c.cases){let f=l.isDefault?"default":l.labels.join(", "),u=jn(l.body,n,s);u.extraLine&&o.push(u.extraLine),o.push(` ${i} -->|${f}| ${u.targetId}`)}break}case"match":{let c=a,d=Me(`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}["${Me(l)}"]`),o.push(` ${i} -->|${Me(l)}| ${f}`)}else{let l=`T${s.value++}`;o.push(` ${l}["..."]`),o.push(` ${i} -->|match| ${l}`)}break}}return o.join(`
|
|
33
|
+
`)}import{Option as Jc}from"effect";function Po(e){return e.replace(/"/g,"#quot;").replace(/</g,"#lt;").replace(/>/g,"#gt;").replace(/\(/g,"#lpar;").replace(/\)/g,"#rpar;")}function Qt(e){return e.replace(/[^a-zA-Z0-9]/g,"_")}var Yc=new Set(["Effect.fail","Effect.die","Effect.interrupt"]);function Qc(e){if(e.type==="effect"){let t=e.typeSignature?.errorType??e.errorType;if(t&&t!=="never"&&t.trim()!=="")return t}}function Zc(e){return e==="Effect.die"?"die":e==="Effect.interrupt"?"interrupt":"fail"}function _n(e){let t=[];if(e.type==="cause"&&e.isConstructor){let n=e.causeOp;if(n==="parallel"||n==="sequential"){let o=[],s=e.children??[];for(let a of s)o.push(..._n(a));return t.push({id:Qt(e.id),kind:n,label:`Cause.${n}`,children:o}),t}if(n==="fail"||n==="die"||n==="interrupt")return t.push({id:Qt(e.id),kind:n,label:`Cause.${n}`,children:[]}),t}if(e.type==="exit"&&e.isConstructor){let n=e.exitOp;if(n==="fail"||n==="die"||n==="interrupt")return t.push({id:Qt(e.id),kind:n==="fail"?"fail":n==="die"?"die":"interrupt",label:`Exit.${n}`,children:[]}),t}if(e.type==="effect"&&Yc.has(e.callee)){let n=Zc(e.callee),o=Qc(e),s=o?`${e.callee}: ${o}`:e.callee;return t.push({id:Qt(e.id),kind:n,label:s,children:[]}),t}let r=Jc.getOrElse(v(e),()=>[]);for(let n of r)t.push(..._n(n));return t}function Mo(e,t,r,n,o,s){let a=`N${s.value++}`,i=Po(e.label);if(e.kind==="parallel"||e.kind==="sequential"){if(n.push(` ${a}[${i}]`),o.set(a,"composite"),t){let d=r?` -->|${r}| `:" --> ";n.push(` ${t}${d}${a}`)}let c=e.kind==="parallel"?"parallel":"then";for(let d of e.children)Mo(d,a,c,n,o,s)}else if(e.kind==="die"?(n.push(` ${a}[${i}]`),o.set(a,"die")):e.kind==="interrupt"?(n.push(` ${a}[${i}]`),o.set(a,"interrupt")):(n.push(` ${a}(${i})`),o.set(a,"fail")),t){let c=r?` -->|${r}| `:" --> ";n.push(` ${t}${c}${a}`)}}function Xc(e,t={}){let r=t.direction??"TB",n=[];for(let l of e.root.children)n.push(..._n(l));if(n.length===0)return`flowchart ${r}
|
|
34
|
+
NoCauses((No failure causes))`;let o=[`flowchart ${r}`],s=new Map,a={value:0},i="Root",c=Po(e.root.programName);o.push(` ${i}((${c}))`);for(let l of n)Mo(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 el}from"effect";function Le(e){return e.replace(/"/g,"#quot;").replace(/</g,"#lt;").replace(/>/g,"#gt;").replace(/\(/g,"#lpar;").replace(/\)/g,"#rpar;")}function Oe(e,t){return`${e}${t}`}function Lo(e,t){return e.displayName?e.displayName:e.name?e.name:e.type==="effect"?e.callee:`child_${t}`}function tl(e){return e.charAt(0).toUpperCase()+e.slice(1)}function nl(e){let t=[],r=n=>{switch(n.type){case"parallel":t.push({kind:"parallel",node:n});break;case"race":t.push({kind:"race",node:n});break;case"fiber":t.push({kind:"fiber",node:n});break;case"concurrency-primitive":t.push({kind:"primitive",node:n});break}let o=el.getOrElse(v(n),()=>[]);for(let s of o)r(s)};for(let n of e)r(n);return t}function rl(e,t={}){let r=t.direction??"TB",n=nl(e.root.children);if(n.length===0)return`flowchart ${r}
|
|
36
|
+
NoConcurrency((No concurrency))`;let o=[`flowchart ${r}`],s=[],a=0,i=[];for(let c of n)switch(c.kind){case"parallel":{let d=c.node,l=Oe("P",a++),f=d.children.length,u=d.mode==="parallel"?"parallel":"sequential",p=Le(`${d.callee} #lpar;${f} effects, ${u}#rpar;`);o.push(` ${l}[${p}]`),s.push(` style ${l} fill:#E3F2FD`);let g=Oe("PJ",a++);for(let m=0;m<d.children.length;m++){let S=d.children[m];if(!S)continue;let h=Oe("PC",a++),N=Le(d.branchLabels?.[m]??Lo(S,m)),x=d.branchLabels?.[m],C=x?Le(x):void 0;o.push(` ${h}[${N}]`),C?o.push(` ${l} -->|${C}| ${h}`):o.push(` ${l} --> ${h}`),o.push(` ${h} --> ${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=Oe("R",a++);o.push(` ${l}{Race}`),s.push(` style ${l} fill:#FFF3E0`);let f=Oe("RW",a++);for(let u=0;u<d.children.length;u++){let p=d.children[u];if(!p)continue;let g=Oe("RC",a++),m=Le(d.raceLabels?.[u]??Lo(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=Oe("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=Le(`${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=Le(f);o.push(` ${l}[${u}]`),s.push(` style ${l} fill:#BBDEFB`)}else{let u=Le(`Fiber.${f}`);o.push(` ${l}[${u}]`),s.push(` style ${l} fill:#BBDEFB`)}i.push(l);break}case"primitive":{let d=c.node,l=Oe("CP",a++),f=tl(d.primitive),u=Le(`${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 ol(e){let t=[],r=n=>{if(n.type==="parallel"){t.push({kind:"parallel",node:n});return}if(n.type==="retry"){t.push({kind:"retry",node:n}),r(n.source);return}if(n.type==="timeout"){t.push({kind:"timeout",node:n}),r(n.source);return}if(n.type==="effect"){let s=n.callee;if(s==="Effect.fn"||s.startsWith("Effect.fn(")||s.startsWith("Schema.")||s.startsWith("Data."))return;let a=n.displayName??"";if(!(a&&a!==s&&a!==n.type)&&(s.startsWith("Effect.")||s==="Effect"))return;n.serviceCall?t.push({kind:"service-call",node:n}):t.push({kind:"effect-constructor",node:n});return}let o=zn.getOrElse(v(n),()=>[]);for(let s of o)r(s)};for(let n of e)r(n);return t}function sl(e){let t=new Set,r=[],n=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),r.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),r.push(i))}}};for(let o of e)n(o);return r}function il(e,t,r){let n=zn.getOrElse(v(e),()=>[]);if(n.length!==0){t.push(`${r}par Parallel`);for(let o=0;o<n.length;o++){o>0&&t.push(`${r}and`);let s=n[o];if(s)if(s.type==="effect"&&s.serviceCall)t.push(`${r} Program->>${s.serviceCall.serviceType}: ${s.serviceCall.methodName}()`),t.push(`${r} ${s.serviceCall.serviceType}-->>Program: result`);else if(s.type==="effect")t.push(`${r} Note over Program: ${s.callee}`);else{let a=s.displayName??s.name??s.type;t.push(`${r} Note over Program: ${a}`)}}t.push(`${r}end`)}}function al(e){let t=ol(e.root.children);if(t.length===0)return`sequenceDiagram
|
|
38
|
+
participant Program
|
|
39
|
+
Note over Program: Empty program`;let r=sl(t),n=["sequenceDiagram"];n.push(" participant Program");for(let o of r)n.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;n.push(` Program->>${a}: ${i}()`),n.push(` ${a}-->>Program: result`)}break}case"effect-constructor":{let s=o.node;s.type==="effect"&&n.push(` Note over Program: ${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";n.push(` Note over Program: retry (${i}, ${a.baseStrategy})`)}else s.schedule?n.push(` Note over Program: retry (${s.schedule})`):n.push(" Note over Program: retry")}break}case"timeout":{let s=o.node;if(s.type==="timeout"){let a=s.duration??"unknown";n.push(` Note over Program: timeout(${a})`)}break}case"parallel":{il(o.node,n," ");break}}return n.join(`
|
|
40
|
+
`)}import{Option as cl}from"effect";function Oo(e,t){for(let r of e){if(r.type==="layer"){let o=r,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 n=cl.getOrElse(v(r),()=>[]);n.length>0&&Oo(n,t)}}function Ge(e){let t=[];Oo(e.root.children,t);let r=[],n=new Map;for(let o of t){for(let s of o.operationLayerIds)r.push({from:o.id,to:s,kind:"merge"});for(let s of o.provides){let a=n.get(s)??[];a.push(o.id),n.set(s,a),r.push({from:o.id,to:s,kind:"provides"})}for(let s of o.requires)r.push({from:o.id,to:s,kind:"requires"})}return{layers:t,edges:r,serviceToLayers:n}}function Wo(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 r=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);r.set(i.id,c)}let n=[],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&&n.push({path:[...c.slice(d),i]});return}o.add(i),c.push(i);for(let d of r.get(i)??[])a(d,c);c.pop(),o.delete(i),s.add(i)}}for(let i of r.keys())a(i,[]);return n}function ll(e){let t=[];for(let[r,n]of e.serviceToLayers)n.length>1&&t.push({serviceId:r,providers:[...n]});return t}function dl(e){let t=new Set;for(let n of e.layers)for(let o of n.provides)t.add(o);let r=new Map;for(let n of e.layers)for(let o of n.requires)if(!t.has(o)){let s=r.get(o)??[];s.push(n.id),r.set(o,s)}return Array.from(r.entries()).map(([n,o])=>({serviceId:n,requiredBy:o}))}function ul(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 r=new Map,n=new Set;function o(s){let a=r.get(s);if(a!==void 0)return a;if(n.has(s))return 0;n.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 r.set(s,c),c}for(let s of e.layers)o(s.id);return r}function ye(e){return e.replace(/[^a-zA-Z0-9_]/g,"_")}var Hn=["#C8E6C9","#A5D6A7","#81C784","#66BB6A","#4CAF50","#43A047","#388E3C","#2E7D32","#1B5E20"];function fl(e){let t=[];t.push("graph TD"),t.push("");let r=Wo(e),n=new Set;for(let i of r)for(let c=0;c<i.path.length-1;c++)n.add(`${i.path[c]}\u2192${i.path[c+1]}`);let o=ul(e);for(let i of e.layers){let c=i.name??i.id;t.push(` ${ye(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(` ${ye(i)}["${i}"]`);t.push("");for(let i of e.edges){let c=n.has(`${i.from}\u2192${i.to}`);i.kind==="provides"?t.push(` ${ye(i.from)} -.->|provides| ${ye(i.to)}`):i.kind==="requires"?c?t.push(` ${ye(i.from)} -->|\u26A0 CYCLE| ${ye(i.to)}`):t.push(` ${ye(i.from)} --> ${ye(i.to)}`):t.push(` ${ye(i.from)} -->|merge| ${ye(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<Hn.length;i++)t.push(` classDef depth${i} fill:${Hn[i]},stroke:#333`);for(let i of e.layers){let c=Math.min(o.get(i.id)??0,Hn.length-1);t.push(` class ${ye(i.id)} depth${c}`)}if(r.length>0){t.push(" classDef cycleNode fill:#FFCDD2,stroke:#C62828,stroke-width:3px");let i=new Set;for(let c of r)for(let d of c.path)i.add(d);for(let c of i)t.push(` class ${ye(c)} cycleNode`)}return t.join(`
|
|
41
|
+
`)}function lt(e){return e.replace(/[^a-zA-Z0-9_]/g,"_")}function pl(e,t={}){let r=t.direction??"TB",n=Ge(e);if(n.layers.length===0)return`flowchart ${r}
|
|
42
|
+
NoLayers((No layers))`;let o=[`flowchart ${r}`],s=new Set;for(let i of n.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 n.layers){let c=i.name??i.id,d=i.lifecycle!=="default"?` (${i.lifecycle})`:"",l=lt(i.id);o.push(` ${l}["${c}${d}"]`),i.isMerged&&a.add(l)}for(let i of s)o.push(` ${lt(i)}{{"${i}"}}`);for(let i of n.edges){let c=lt(i.from),d=lt(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 n.layers){let c=lt(i.id);a.has(c)?o.push(` class ${c} mergedStyle`):o.push(` class ${c} layerStyle`)}for(let i of s)o.push(` class ${lt(i)} serviceStyle`);return o.join(`
|
|
43
|
+
`)}import{Option as gl}from"effect";function Un(e){return e.replace(/"/g,"#quot;").replace(/</g,"#lt;").replace(/>/g,"#gt;").replace(/\(/g,"#lpar;").replace(/\)/g,"#rpar;")}function Ko(e,t){for(let r of e){(r.type==="retry"||r.type==="timeout")&&t.push({node:r,index:t.length});let n=gl.getOrElse(v(r),()=>[]);n.length>0&&Ko(n,t)}}function ml(e){if(e.type!=="retry")return"";let t=e.scheduleInfo;if(!t)return"retry";let r=[t.baseStrategy];return t.maxRetries!==void 0&&t.maxRetries!=="unlimited"&&r.push(`${t.maxRetries}x`),t.initialDelay&&r.push(t.initialDelay),t.maxDelay&&r.push(`max ${t.maxDelay}`),t.jittered&&r.push("+jitter"),r.join(" ")}function hl(e){let t=e.source;return t===void 0?"Operation":t.displayName?t.displayName:t.name?t.name:"Operation"}function yl(e,t={}){let r=t.direction??"LR",n=[];if(Ko(e.root.children,n),n.length===0)return`flowchart ${r}
|
|
44
|
+
NoRetry((No retry/timeout patterns))`;let o=[`flowchart ${r}`];for(let{node:s,index:a}of n){let i=`N${a}`,c=Un(hl(s));if(s.type==="retry"){let d=s,l=Un(ml(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=Un(`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 Sl(e,t={}){let r=t.direction??"LR",n=e.root.requiredServices??[],o=e.root.dependencies;if(n.length===0)return`flowchart ${r}
|
|
46
|
+
NoMocks((No services to mock - pure computation))`;let s=new Set(o.filter(l=>l.isLayer).map(l=>l.name)),a=[`flowchart ${r}`],i=[],c=[];for(let l=0;l<n.length;l++){let f=`S${l}`,u=n[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=n.length===1?"mock":"mocks";return a.push(""),a.push(` Note[Requires ${n.length} service ${d}]`),a.join(`
|
|
47
|
+
`)}import{Option as qo}from"effect";function Bo(e){return`S${e}`}function Zt(e){return e.replace(/"/g,"#quot;").replace(/</g,"#lt;").replace(/>/g,"#gt;").replace(/\(/g,"#lpar;").replace(/\)/g,"#rpar;")}function jo(e){let t=[];if(e.type==="pipe"){let n=e,o=[],s=n.typeFlow?.[0]??("typeSignature"in n.initial?n.initial.typeSignature:void 0);s&&o.push({successType:s.successType,errorType:s.errorType,isEffectful:!1});for(let a=0;a<n.transformations.length;a++){let i=n.transformations[a];if(!i)continue;let c=i.type==="transform"?i.transformType:i.name??i.type,d=i.type==="transform"?i.isEffectful:!1,l=n.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 r=qo.getOrElse(v(e),()=>[]);for(let n of r)t.push(...jo(n));return t}function _o(e){let t=[];if(e.type==="generator"){let n=e,o=[];for(let s of n.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 r=qo.getOrElse(v(e),()=>[]);for(let n of r)t.push(..._o(n));return t}function xl(e,t={}){let r=t.direction??"LR",n=[];for(let i of e.root.children)n.push(...jo(i)),n.push(..._o(i));if(n.length===0)return`flowchart ${r}
|
|
48
|
+
NoData((No data transformations))`;let o=[`flowchart ${r}`],s=[],a=0;for(let i of n){let c=a;for(let d=0;d<i.length;d++){let l=i[d];if(!l)continue;let f=Bo(c+d),u=Zt(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=Bo(c+d+1),m=Zt(p.successType),S=p.transformLabel??"",h=l.errorType,N=p.errorType;N!==h&&N!=="never"&&N!=="unknown"&&(S=S?`${S}<br/>E: ${Zt(N)}`:`E: ${Zt(N)}`);let x=p.isEffectful?"==>":"-->";d===0?o.push(` ${f}["${u}"] ${x}|${S}| ${g}["${m}"]`):o.push(` ${f} ${x}|${S}| ${g}["${m}"]`)}else d===0&&o.push(` ${f}["${u}"]`)}a+=i.length}return[...o,...s].join(`
|
|
49
|
+
`)}import{Option as Al}from"effect";import{Option as Tt}from"effect";var zo={cyclomaticWarning:10,cyclomaticError:20,pathCountWarning:50,maxDepthWarning:5};function Se(e){let t=e.root.children,r=El(t),n=bl(t),o=Nl(t),s=vl(t),a=wl(t),i=Tl(t);return{cyclomaticComplexity:r,cognitiveComplexity:n,pathCount:o,maxDepth:s,maxParallelBreadth:a,decisionPoints:i}}function El(e){let t=1;for(let r of e)t+=ae(r);return t}function ae(e){let t=v(e),r=Tt.getOrElse(t,()=>[]),n=0;switch(e.type){case"conditional":n+=1;for(let o of r)n+=ae(o);break;case"race":n+=Math.max(0,e.children.length-1);for(let o of e.children)n+=ae(o);break;case"loop":n+=1,n+=ae(e.body);break;case"generator":case"pipe":case"parallel":case"error-handler":case"retry":case"timeout":case"resource":case"layer":for(let o of r)n+=ae(o);break;case"decision":n+=1;for(let o of r)n+=ae(o);break;case"switch":n+=Math.max(0,e.cases.length-1);for(let o of r)n+=ae(o);break;case"try-catch":n+=1;for(let o of r)n+=ae(o);break;case"terminal":case"opaque":for(let o of r)n+=ae(o);break;case"match":e.matchedTags&&e.matchedTags.length>1&&(n+=e.matchedTags.length-1);break;case"interruption":e.handler&&(n+=1,n+=ae(e.handler)),e.source&&(n+=ae(e.source));break;case"cause":if(e.children)for(let o of e.children)n+=ae(o);break;case"transform":e.source&&(n+=ae(e.source));break;case"channel":case"sink":e.source&&(n+=ae(e.source));break;case"exit":case"schedule":case"effect":case"unknown":break}return n}function bl(e){return Cl(e,0)}function Cl(e,t){let r=0;for(let n of e)r+=re(n,t);return r}function re(e,t){let r=v(e),n=Tt.getOrElse(r,()=>[]),o=0;switch(e.type){case"conditional":o+=1+t,o+=re(e.onTrue,t+1),e.onFalse&&(o+=re(e.onFalse,t+1));break;case"loop":o+=1+t,o+=re(e.body,t+1);break;case"race":o+=e.children.length;for(let s of e.children)o+=re(s,t+1);break;case"parallel":o+=Math.max(0,e.children.length-1);for(let s of e.children)o+=re(s,t);break;case"generator":case"pipe":case"error-handler":case"retry":case"timeout":case"resource":case"layer":for(let s of n)o+=re(s,t);break;case"decision":o+=1+t;for(let s of e.onTrue)o+=re(s,t+1);if(e.onFalse)for(let s of e.onFalse)o+=re(s,t+1);break;case"switch":o+=1+t;for(let s of e.cases)for(let a of s.body)o+=re(a,t+1);break;case"try-catch":o+=1+t;for(let s of n)o+=re(s,t+1);break;case"terminal":if(e.value)for(let s of e.value)o+=re(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+=re(e.handler,t+1)),e.source&&(o+=re(e.source,t));break;case"cause":if(e.children)for(let s of e.children)o+=re(s,t);break;case"transform":e.source&&(o+=re(e.source,t));break;case"channel":case"sink":e.source&&(o+=re(e.source,t));break;case"exit":case"schedule":case"effect":case"unknown":break}return o}function Nl(e){let t=1,r=!1;for(let n of e){let o=Xt(n);o==="unbounded"?r=!0:t*=o}return r?"unbounded":t}function Xt(e){let t=v(e),r=Tt.getOrElse(t,()=>[]);switch(e.type){case"conditional":{let n=Je([e.onTrue]),o=e.onFalse?Je([e.onFalse]):1;return n==="unbounded"||o==="unbounded"?"unbounded":n+o}case"race":{let n=0;for(let o of e.children){let s=Xt(o);if(s==="unbounded")return"unbounded";n+=s}return Math.max(1,n)}case"parallel":{let n=1;for(let o of e.children){let s=Xt(o);if(s==="unbounded")return"unbounded";n*=s}return n}case"loop":return"unbounded";case"generator":case"pipe":case"error-handler":case"retry":case"timeout":case"resource":case"layer":return Je(r);case"effect":case"unknown":case"opaque":return 1;case"decision":{let n=Je([...e.onTrue]),o=e.onFalse?Je([...e.onFalse]):1;return n==="unbounded"||o==="unbounded"?"unbounded":n+o}case"switch":{let n=0;for(let o of e.cases){let s=Je([...o.body]);if(s==="unbounded")return"unbounded";n+=s}return Math.max(1,n)}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 Je(r)}}function Je(e){let t=1;for(let r of e){let n=Xt(r);if(n==="unbounded")return"unbounded";t*=n}return t}function vl(e){let t=0;for(let r of e)t=Math.max(t,se(r,0));return t}function se(e,t){let r=v(e),n=Tt.getOrElse(r,()=>[]),o=t;switch(e.type){case"conditional":o=Math.max(o,se(e.onTrue,t+1)),e.onFalse&&(o=Math.max(o,se(e.onFalse,t+1)));break;case"loop":o=Math.max(o,se(e.body,t+1));break;case"parallel":case"race":for(let s of e.children)o=Math.max(o,se(s,t+1));break;case"generator":case"pipe":case"error-handler":case"retry":case"timeout":case"resource":case"layer":for(let s of n)o=Math.max(o,se(s,t));break;case"decision":for(let s of e.onTrue)o=Math.max(o,se(s,t+1));if(e.onFalse)for(let s of e.onFalse)o=Math.max(o,se(s,t+1));break;case"switch":for(let s of e.cases)for(let a of s.body)o=Math.max(o,se(a,t+1));break;case"try-catch":for(let s of n)o=Math.max(o,se(s,t+1));break;case"terminal":if(e.value)for(let s of e.value)o=Math.max(o,se(s,t));break;case"opaque":break;case"match":break;case"interruption":e.source&&(o=Math.max(o,se(e.source,t+1))),e.handler&&(o=Math.max(o,se(e.handler,t+1)));break;case"cause":if(e.children)for(let s of e.children)o=Math.max(o,se(s,t));break;case"transform":e.source&&(o=Math.max(o,se(e.source,t)));break;case"channel":case"sink":e.source&&(o=Math.max(o,se(e.source,t)));break;case"exit":case"schedule":case"effect":case"unknown":break}return o}function wl(e){let t=0;for(let r of e)t=Math.max(t,ie(r));return t}function ie(e){let t=v(e),r=Tt.getOrElse(t,()=>[]),n=0;switch(e.type){case"parallel":case"race":n=e.children.length;for(let o of e.children)n=Math.max(n,ie(o));break;case"conditional":n=Math.max(ie(e.onTrue),e.onFalse?ie(e.onFalse):0);break;case"loop":n=ie(e.body);break;case"generator":case"pipe":case"error-handler":case"retry":case"timeout":case"resource":case"layer":for(let o of r)n=Math.max(n,ie(o));break;case"decision":for(let o of e.onTrue)n=Math.max(n,ie(o));if(e.onFalse)for(let o of e.onFalse)n=Math.max(n,ie(o));break;case"switch":for(let o of e.cases)for(let s of o.body)n=Math.max(n,ie(s));break;case"try-catch":for(let o of r)n=Math.max(n,ie(o));break;case"terminal":if(e.value)for(let o of e.value)n=Math.max(n,ie(o));break;case"opaque":break;case"interruption":e.source&&(n=Math.max(n,ie(e.source))),e.handler&&(n=Math.max(n,ie(e.handler)));break;case"cause":if(e.children)for(let o of e.children)n=Math.max(n,ie(o));break;case"transform":e.source&&(n=Math.max(n,ie(e.source)));break;case"channel":case"sink":e.source&&(n=Math.max(n,ie(e.source)));break;case"match":case"exit":case"schedule":case"effect":case"unknown":break}return n}function Tl(e){let t=0;for(let r of e)t+=ae(r);return t}function kl(e,t=zo){let r=[],n=[];e.cyclomaticComplexity>=t.cyclomaticError?(r.push({type:"cyclomatic",message:`Cyclomatic complexity (${e.cyclomaticComplexity}) exceeds error threshold (${t.cyclomaticError})`,severity:"error"}),n.push("Consider breaking this program into smaller effects")):e.cyclomaticComplexity>=t.cyclomaticWarning&&(r.push({type:"cyclomatic",message:`Cyclomatic complexity (${e.cyclomaticComplexity}) exceeds warning threshold (${t.cyclomaticWarning})`,severity:"warning"}),n.push("Consider simplifying conditional logic or extracting sub-effects")),e.pathCount==="unbounded"?(r.push({type:"paths",message:"Program has unbounded paths due to loops",severity:"warning"}),n.push("Ensure loop termination conditions are well-tested")):e.pathCount>=t.pathCountWarning&&(r.push({type:"paths",message:`Path count (${e.pathCount}) exceeds threshold (${t.pathCountWarning})`,severity:"warning"}),n.push("High path count makes exhaustive testing difficult - consider simplifying")),e.maxDepth>=t.maxDepthWarning&&(r.push({type:"depth",message:`Nesting depth (${e.maxDepth}) exceeds threshold (${t.maxDepthWarning})`,severity:"warning"}),n.push("Deep nesting reduces readability - consider flattening or extracting"));let o="low",s=r.some(i=>i.severity==="error"),a=r.some(i=>i.severity==="warning");return s?o="very-high":a&&(o=r.length>=2?"high":"medium"),{level:o,warnings:r,recommendations:n}}function Il(e,t){let r=[];if(r.push("## Effect Program Complexity Report"),r.push(""),r.push(`**Overall Complexity:** ${t.level.toUpperCase()}`),r.push(""),r.push("### Metrics"),r.push(""),r.push("| Metric | Value |"),r.push("|--------|-------|"),r.push(`| Cyclomatic Complexity | ${e.cyclomaticComplexity} |`),r.push(`| Cognitive Complexity | ${e.cognitiveComplexity} |`),r.push(`| Unique Paths | ${e.pathCount} |`),r.push(`| Max Nesting Depth | ${e.maxDepth} |`),r.push(`| Max Parallel Breadth | ${e.maxParallelBreadth} |`),r.push(`| Decision Points | ${e.decisionPoints} |`),r.push(""),t.warnings.length>0){r.push("### Warnings"),r.push("");for(let n of t.warnings){let o=n.severity==="error"?"ERROR":"WARNING";r.push(`- **${o}:** ${n.message}`)}r.push("")}if(t.recommendations.length>0){r.push("### Recommendations"),r.push("");for(let n of t.recommendations)r.push(`- ${n}`);r.push("")}return r.join(`
|
|
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(`
|
|
51
|
+
`)];return a.length>0&&(c.push(""),c.push(a.join(`
|
|
52
|
+
`))),c.join(`
|
|
53
|
+
`)}function Td(e){let t=0;return e.map(r=>/^ {2}\S/.test(r)?(t++,` ${t}. ${r.trimStart()}`):r)}function Xo(e){return wd(e.root,e)}function kd(e){return e.map(t=>Xo(t)).join(`
|
|
54
|
+
|
|
55
|
+
---
|
|
56
|
+
|
|
57
|
+
`)}var Id={generator:"gen",direct:"direct",pipe:"pipe",run:"run","workflow-execute":"wf-exec",class:"class",classProperty:"classProp",classMethod:"classMeth"};function es(e){return Id[e]}function Ad(e){let t=e.root.programName,r=es(e.root.source),n=e.metadata.stats.totalEffects,o=e.root.dependencies.length,s=e.root.errorTypes.length,a=e.metadata.stats.errorHandlerCount,i=Se(e).cyclomaticComplexity;return[t,r,`${n} steps`,`${o} services`,`${s} errors`,`${a} ${a===1?"handler":"handlers"}`,`complexity: ${i}`].join(" | ")}function Fd(e){return{program:e.root.programName,kind:es(e.root.source),steps:e.metadata.stats.totalEffects,services:e.root.dependencies.length,errors:e.root.errorTypes.length,handlers:e.metadata.stats.errorHandlerCount,complexity:Se(e).cyclomaticComplexity}}function Rd(e){if(e.length===0)return"(no programs)";let t=e.map(Fd),r={program:"Program",kind:"Kind",steps:"Steps",services:"Services",errors:"Errors",handlers:"Handlers",complexity:"Complexity"},n={program:Math.max(r.program.length,...t.map(d=>d.program.length)),kind:Math.max(r.kind.length,...t.map(d=>d.kind.length)),steps:Math.max(r.steps.length,...t.map(d=>String(d.steps).length)),services:Math.max(r.services.length,...t.map(d=>String(d.services).length)),errors:Math.max(r.errors.length,...t.map(d=>String(d.errors).length)),handlers:Math.max(r.handlers.length,...t.map(d=>String(d.handlers).length)),complexity:Math.max(r.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(r.program,n.program),o(r.kind,n.kind),o(r.steps,n.steps),o(r.services,n.services),o(r.errors,n.errors),o(r.handlers,n.handlers),o(r.complexity,n.complexity)].join(" | "),i=["-".repeat(n.program),"-".repeat(n.kind),"-".repeat(n.steps),"-".repeat(n.services),"-".repeat(n.errors),"-".repeat(n.handlers),"-".repeat(n.complexity)].join("-+-"),c=t.map(d=>[o(d.program,n.program),o(d.kind,n.kind),s(String(d.steps),n.steps),s(String(d.services),n.services),s(String(d.errors),n.errors),s(String(d.handlers),n.handlers),s(String(d.complexity),n.complexity)].join(" | "));return[a,i,...c].join(`
|
|
58
|
+
`)}function $d(e){let t=new Set,r=new Map;for(let s of e){let a=s.root.programName,i=r.get(a)??new Set;for(let c of s.root.dependencies)t.add(c.name),i.add(c.name);r.set(a,i)}let n=[...t].sort((s,a)=>s.localeCompare(a)),o=[...r.keys()].sort((s,a)=>s.localeCompare(a));return ts(o,n,(s,a)=>{let i=r.get(s);return i?i.has(a):!1},{programs:e.length,services:n.length})}function Dd(e){let t=[],r=new Set,n=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),r.add(d.programName),n.add(`${d.filePath}::${d.programName}`);o.set(a,c)}t.sort((a,i)=>a.localeCompare(i));let s=[...r].sort((a,i)=>a.localeCompare(i));return ts(s,t,(a,i)=>{let c=o.get(i);return c?c.has(a):!1},{programs:n.size,services:t.length})}function ts(e,t,r,n){let o=n?.programs??e.length,s=n?.services??t.length;if(e.length===0||t.length===0)return`_No dependencies found._
|
|
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=>r(c,l)?"\u2713":"");a.push(`| ${c} | ${d.join(" | ")} |`)}return a.push(""),a.push(`${o} programs \xD7 ${s} services`),a.join(`
|
|
61
|
+
`)}import{Effect as ns}from"effect";var rs={pretty:!0,includeMetadata:!0,compact:!1},Pd=(e,t)=>ns.gen(function*(){let r={...rs,...t},n=r.pretty?2:void 0,o=r.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,os,n)}),Md=(e,t)=>ns.gen(function*(){let r={...rs,...t},n=r.pretty?2:void 0,o=e.map(s=>r.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,os,n)}),os=(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 Ld(e){return e==="light"?"daylight":e==="dark"?"midnight":e}function Od(e,t={}){let r=t.title??`${e.root.programName} - Effect Analysis`,n=Ld(t.theme),o=le(e).replace(/<\/script>/gi,"<\\/script>"),s=kt(e),a=Se(e),i=le(e,{dataFlowOverlay:!0}).replace(/<\/script>/gi,"<\\/script>"),c=le(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=n?`"${n}"`:"null";return`<!DOCTYPE html>
|
|
62
|
+
<html lang="en" data-theme="midnight">
|
|
63
|
+
<head>
|
|
64
|
+
<meta charset="UTF-8">
|
|
65
|
+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
66
|
+
<title>${Gn(r)}</title>
|
|
67
|
+
<script src="https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js"></script>
|
|
68
|
+
<style>
|
|
69
|
+
/* Theme definitions */
|
|
70
|
+
[data-theme="midnight"] {
|
|
71
|
+
--bg: #0f1117; --fg: #d4d7e0; --panel-bg: #161921; --header-bg: #1c1f2b;
|
|
72
|
+
--border: #262a3a; --accent: #7b9dea; --accent-dim: rgba(123,157,234,0.12);
|
|
73
|
+
--selected-bg: #1a3a5c;
|
|
74
|
+
}
|
|
75
|
+
[data-theme="ocean"] {
|
|
76
|
+
--bg: #0a1628; --fg: #c8d8ee; --panel-bg: #0f1e35; --header-bg: #142742;
|
|
77
|
+
--border: #1a3452; --accent: #4da6e8; --accent-dim: rgba(77,166,232,0.12);
|
|
78
|
+
--selected-bg: #0f2847;
|
|
79
|
+
}
|
|
80
|
+
[data-theme="ember"] {
|
|
81
|
+
--bg: #1a0f0f; --fg: #e0d0c8; --panel-bg: #221414; --header-bg: #2e1a1a;
|
|
82
|
+
--border: #3a2222; --accent: #e8845a; --accent-dim: rgba(232,132,90,0.12);
|
|
83
|
+
--selected-bg: #2e1a1a;
|
|
84
|
+
}
|
|
85
|
+
[data-theme="forest"] {
|
|
86
|
+
--bg: #0c1a0f; --fg: #c8d8c8; --panel-bg: #111f14; --header-bg: #18281a;
|
|
87
|
+
--border: #1e3a20; --accent: #5ac87a; --accent-dim: rgba(90,200,122,0.12);
|
|
88
|
+
--selected-bg: #18281a;
|
|
89
|
+
}
|
|
90
|
+
[data-theme="daylight"] {
|
|
91
|
+
--bg: #f8f9fb; --fg: #1a2030; --panel-bg: #ffffff; --header-bg: #ffffff;
|
|
92
|
+
--border: #dde1ea; --accent: #3a6fd8; --accent-dim: rgba(58,111,216,0.08);
|
|
93
|
+
--selected-bg: #e3f2fd;
|
|
94
|
+
}
|
|
95
|
+
[data-theme="paper"] {
|
|
96
|
+
--bg: #faf8f5; --fg: #2a2218; --panel-bg: #fffefa; --header-bg: #fffefa;
|
|
97
|
+
--border: #e0d8cc; --accent: #b07830; --accent-dim: rgba(176,120,48,0.08);
|
|
98
|
+
--selected-bg: #f4f0e8;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
* { box-sizing: border-box; margin: 0; padding: 0; }
|
|
102
|
+
body { font-family: system-ui, -apple-system, sans-serif; background: var(--bg); color: var(--fg); }
|
|
103
|
+
|
|
104
|
+
.header { padding: 0.75rem 1rem; background: var(--header-bg); border-bottom: 1px solid var(--border); display: flex; align-items: center; gap: 1rem; flex-wrap: wrap; }
|
|
105
|
+
.header h1 { font-size: 1.1rem; font-weight: 600; }
|
|
106
|
+
.header .stats { font-size: 0.8rem; opacity: 0.7; }
|
|
107
|
+
|
|
108
|
+
.theme-picker { position: relative; margin-left: auto; }
|
|
109
|
+
.theme-picker button { padding: 4px 10px; border: 1px solid var(--border); border-radius: 4px; background: var(--panel-bg); color: var(--fg); cursor: pointer; font-size: 0.8rem; }
|
|
110
|
+
.theme-menu { display: none; position: absolute; right: 0; top: 100%; margin-top: 4px; background: var(--panel-bg); border: 1px solid var(--border); border-radius: 6px; padding: 4px 0; min-width: 140px; z-index: 100; box-shadow: 0 4px 12px rgba(0,0,0,0.2); }
|
|
111
|
+
.theme-menu.open { display: block; }
|
|
112
|
+
.theme-menu button { display: block; width: 100%; padding: 6px 12px; border: none; background: transparent; color: var(--fg); text-align: left; cursor: pointer; font-size: 0.8rem; }
|
|
113
|
+
.theme-menu button:hover { background: var(--accent-dim); }
|
|
114
|
+
.theme-menu button.active { color: var(--accent); font-weight: 600; }
|
|
115
|
+
|
|
116
|
+
.toolbar { padding: 0.5rem 1rem; background: var(--panel-bg); border-bottom: 1px solid var(--border); display: flex; gap: 0.5rem; flex-wrap: wrap; align-items: center; }
|
|
117
|
+
.toolbar input[type="text"] { padding: 4px 8px; border: 1px solid var(--border); border-radius: 4px; background: var(--bg); color: var(--fg); font-size: 0.85rem; width: 200px; }
|
|
118
|
+
.toolbar select { padding: 4px 8px; border: 1px solid var(--border); border-radius: 4px; background: var(--bg); color: var(--fg); font-size: 0.85rem; }
|
|
119
|
+
.toolbar label { font-size: 0.85rem; display: flex; align-items: center; gap: 4px; cursor: pointer; }
|
|
120
|
+
.toolbar .sep { width: 1px; height: 20px; background: var(--border); margin: 0 4px; }
|
|
121
|
+
|
|
122
|
+
.layout { display: grid; grid-template-columns: 1fr 380px; height: calc(100vh - 90px); }
|
|
123
|
+
@media (max-width: 900px) { .layout { grid-template-columns: 1fr; grid-template-rows: 1fr 1fr; } }
|
|
124
|
+
|
|
125
|
+
.diagram-pane { overflow: auto; padding: 1rem; border-right: 1px solid var(--border); }
|
|
126
|
+
.diagram-pane .mermaid { min-height: 200px; }
|
|
127
|
+
|
|
128
|
+
.sidebar { overflow-y: auto; display: flex; flex-direction: column; }
|
|
129
|
+
.sidebar-tabs { display: flex; border-bottom: 1px solid var(--border); background: var(--header-bg); }
|
|
130
|
+
.sidebar-tabs button { flex: 1; padding: 8px; border: none; background: transparent; color: var(--fg); cursor: pointer; font-size: 0.8rem; border-bottom: 2px solid transparent; }
|
|
131
|
+
.sidebar-tabs button.active { border-bottom-color: var(--accent); font-weight: 600; }
|
|
132
|
+
.sidebar-tabs button:hover { background: var(--panel-bg); }
|
|
133
|
+
|
|
134
|
+
.tab-content { flex: 1; overflow-y: auto; padding: 0.75rem; font-size: 0.85rem; }
|
|
135
|
+
.tab-content[hidden] { display: none; }
|
|
136
|
+
|
|
137
|
+
.detail-section { margin-bottom: 1rem; }
|
|
138
|
+
.detail-section h3 { font-size: 0.9rem; margin-bottom: 0.4rem; color: var(--accent); }
|
|
139
|
+
.detail-section pre { background: var(--panel-bg); padding: 0.5rem; border-radius: 4px; overflow-x: auto; font-size: 0.75rem; white-space: pre-wrap; word-break: break-word; }
|
|
140
|
+
.detail-section table { width: 100%; border-collapse: collapse; font-size: 0.8rem; }
|
|
141
|
+
.detail-section td, .detail-section th { padding: 4px 8px; text-align: left; border-bottom: 1px solid var(--border); }
|
|
142
|
+
|
|
143
|
+
.path-item { padding: 6px 8px; border: 1px solid var(--border); border-radius: 4px; margin-bottom: 4px; cursor: pointer; font-size: 0.8rem; }
|
|
144
|
+
.path-item:hover { background: var(--panel-bg); }
|
|
145
|
+
.path-item.selected { border-color: var(--accent); background: var(--selected-bg); }
|
|
146
|
+
.path-step { display: inline-block; padding: 2px 6px; margin: 1px; background: var(--panel-bg); border-radius: 3px; font-size: 0.75rem; }
|
|
147
|
+
|
|
148
|
+
.complexity-badge { display: inline-block; padding: 2px 8px; border-radius: 10px; font-size: 0.75rem; font-weight: 600; }
|
|
149
|
+
.complexity-low { background: #C8E6C9; color: #1B5E20; }
|
|
150
|
+
.complexity-medium { background: #FFF9C4; color: #F57F17; }
|
|
151
|
+
.complexity-high { background: #FFCDD2; color: #B71C1C; }
|
|
152
|
+
</style>
|
|
153
|
+
</head>
|
|
154
|
+
<body>
|
|
155
|
+
<div class="header">
|
|
156
|
+
<h1>${Gn(r)}</h1>
|
|
157
|
+
<span class="stats" id="complexity-stats"></span>
|
|
158
|
+
<div class="theme-picker">
|
|
159
|
+
<button onclick="toggleThemeMenu()" id="theme-btn">Theme</button>
|
|
160
|
+
<div class="theme-menu" id="theme-menu">
|
|
161
|
+
<button onclick="applyTheme('midnight')">Midnight</button>
|
|
162
|
+
<button onclick="applyTheme('ocean')">Ocean</button>
|
|
163
|
+
<button onclick="applyTheme('ember')">Ember</button>
|
|
164
|
+
<button onclick="applyTheme('forest')">Forest</button>
|
|
165
|
+
<button onclick="applyTheme('daylight')">Daylight</button>
|
|
166
|
+
<button onclick="applyTheme('paper')">Paper</button>
|
|
167
|
+
</div>
|
|
168
|
+
</div>
|
|
169
|
+
</div>
|
|
170
|
+
<div class="toolbar">
|
|
171
|
+
<input type="text" id="search" placeholder="Search nodes..." oninput="handleSearch(this.value)">
|
|
172
|
+
<select id="typeFilter" onchange="handleTypeFilter(this.value)">
|
|
173
|
+
<option value="">All types</option>
|
|
174
|
+
</select>
|
|
175
|
+
<div class="sep"></div>
|
|
176
|
+
<label><input type="checkbox" id="toggleDataFlow" onchange="toggleOverlay('data')"> Data Flow</label>
|
|
177
|
+
<label><input type="checkbox" id="toggleErrorFlow" onchange="toggleOverlay('error')"> Error Flow</label>
|
|
178
|
+
<div class="sep"></div>
|
|
179
|
+
<select id="pathSelect" onchange="selectPath(this.value)">
|
|
180
|
+
<option value="">Select path...</option>
|
|
181
|
+
</select>
|
|
182
|
+
</div>
|
|
183
|
+
<div class="layout">
|
|
184
|
+
<div class="diagram-pane">
|
|
185
|
+
<pre class="mermaid" id="mermaid-diagram">${Gn(o)}</pre>
|
|
186
|
+
</div>
|
|
187
|
+
<div class="sidebar">
|
|
188
|
+
<div class="sidebar-tabs">
|
|
189
|
+
<button class="active" onclick="showTab('details')">Details</button>
|
|
190
|
+
<button onclick="showTab('paths')">Paths</button>
|
|
191
|
+
<button onclick="showTab('ir')">IR</button>
|
|
192
|
+
</div>
|
|
193
|
+
<div class="tab-content" id="tab-details">
|
|
194
|
+
<div class="detail-section">
|
|
195
|
+
<h3>Complexity</h3>
|
|
196
|
+
<table id="complexity-table"></table>
|
|
197
|
+
</div>
|
|
198
|
+
<div class="detail-section" id="node-details">
|
|
199
|
+
<h3>Node Details</h3>
|
|
200
|
+
<p style="opacity:0.6">Click a node in the diagram to see details.</p>
|
|
201
|
+
</div>
|
|
202
|
+
</div>
|
|
203
|
+
<div class="tab-content" id="tab-paths" hidden>
|
|
204
|
+
<div id="paths-list"></div>
|
|
205
|
+
</div>
|
|
206
|
+
<div class="tab-content" id="tab-ir" hidden>
|
|
207
|
+
<pre id="ir-json" style="font-size:0.7rem">${d}</pre>
|
|
208
|
+
</div>
|
|
209
|
+
</div>
|
|
210
|
+
</div>
|
|
211
|
+
<script>
|
|
212
|
+
var INITIAL_THEME = ${u};
|
|
213
|
+
var STORAGE_KEY = 'effect-viz-theme';
|
|
214
|
+
var DARK_THEMES = ['midnight', 'ocean', 'ember', 'forest'];
|
|
215
|
+
|
|
216
|
+
var MERMAID_THEME_VARS = {
|
|
217
|
+
midnight: { primaryColor: '#1e2233', primaryTextColor: '#d4d7e0', primaryBorderColor: '#3a4266', lineColor: '#3a4266', secondaryColor: '#262a3a', tertiaryColor: '#1c1f2b', background: '#0f1117', mainBkg: '#1e2233', nodeBorder: '#3a4266', clusterBkg: '#161921', clusterBorder: '#3a4266', titleColor: '#d4d7e0', edgeLabelBackground: '#161921', nodeTextColor: '#d4d7e0' },
|
|
218
|
+
ocean: { primaryColor: '#132d4a', primaryTextColor: '#c8d8ee', primaryBorderColor: '#1f4a70', lineColor: '#1f4a70', secondaryColor: '#0f1e35', tertiaryColor: '#142742', background: '#0a1628', mainBkg: '#132d4a', nodeBorder: '#1f4a70', clusterBkg: '#0f1e35', clusterBorder: '#1f4a70', titleColor: '#c8d8ee', edgeLabelBackground: '#0f1e35', nodeTextColor: '#c8d8ee' },
|
|
219
|
+
ember: { primaryColor: '#2e1c18', primaryTextColor: '#e0d0c8', primaryBorderColor: '#5a3328', lineColor: '#5a3328', secondaryColor: '#221414', tertiaryColor: '#2e1a1a', background: '#1a0f0f', mainBkg: '#2e1c18', nodeBorder: '#5a3328', clusterBkg: '#221414', clusterBorder: '#5a3328', titleColor: '#e0d0c8', edgeLabelBackground: '#221414', nodeTextColor: '#e0d0c8' },
|
|
220
|
+
forest: { primaryColor: '#152e1a', primaryTextColor: '#c8d8c8', primaryBorderColor: '#264a2c', lineColor: '#264a2c', secondaryColor: '#111f14', tertiaryColor: '#18281a', background: '#0c1a0f', mainBkg: '#152e1a', nodeBorder: '#264a2c', clusterBkg: '#111f14', clusterBorder: '#264a2c', titleColor: '#c8d8c8', edgeLabelBackground: '#111f14', nodeTextColor: '#c8d8c8' },
|
|
221
|
+
daylight: { primaryColor: '#e8ecf4', primaryTextColor: '#1a2030', primaryBorderColor: '#b0b8cc', lineColor: '#b0b8cc', secondaryColor: '#f0f2f8', tertiaryColor: '#ffffff', background: '#f8f9fb', mainBkg: '#e8ecf4', nodeBorder: '#b0b8cc', clusterBkg: '#ffffff', clusterBorder: '#dde1ea', titleColor: '#1a2030', edgeLabelBackground: '#ffffff', nodeTextColor: '#1a2030' },
|
|
222
|
+
paper: { primaryColor: '#f0ebe0', primaryTextColor: '#2a2218', primaryBorderColor: '#c8bda8', lineColor: '#c8bda8', secondaryColor: '#f5f0e8', tertiaryColor: '#fffefa', background: '#faf8f5', mainBkg: '#f0ebe0', nodeBorder: '#c8bda8', clusterBkg: '#fffefa', clusterBorder: '#e0d8cc', titleColor: '#2a2218', edgeLabelBackground: '#fffefa', nodeTextColor: '#2a2218' }
|
|
223
|
+
};
|
|
224
|
+
|
|
225
|
+
function getSystemPreference() {
|
|
226
|
+
if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
|
|
227
|
+
return 'midnight';
|
|
228
|
+
}
|
|
229
|
+
return 'daylight';
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
function resolveTheme() {
|
|
233
|
+
if (INITIAL_THEME) return INITIAL_THEME;
|
|
234
|
+
try {
|
|
235
|
+
var stored = localStorage.getItem(STORAGE_KEY);
|
|
236
|
+
if (stored) return stored;
|
|
237
|
+
} catch(e) {}
|
|
238
|
+
return getSystemPreference();
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
// Restyle SVG nodes after Mermaid renders to match the active theme.
|
|
242
|
+
// Mermaid classDef styles are baked into SVG elements as inline style with !important,
|
|
243
|
+
// so we must directly modify the style attribute to override them.
|
|
244
|
+
function rethemeSvgNodes(themeName) {
|
|
245
|
+
var isDark = DARK_THEMES.indexOf(themeName) >= 0;
|
|
246
|
+
var vars = MERMAID_THEME_VARS[themeName] || MERMAID_THEME_VARS.midnight;
|
|
247
|
+
var svg = document.querySelector('.mermaid svg');
|
|
248
|
+
if (!svg) return;
|
|
249
|
+
// Override all label-container shapes (nodes)
|
|
250
|
+
var shapes = svg.querySelectorAll('.label-container');
|
|
251
|
+
shapes.forEach(function(el) {
|
|
252
|
+
el.setAttribute('style', 'fill:' + vars.primaryColor + ' !important;stroke:' + vars.primaryBorderColor + ' !important;stroke-width:1px !important');
|
|
253
|
+
});
|
|
254
|
+
// Override node labels text color
|
|
255
|
+
var labels = svg.querySelectorAll('.nodeLabel, .label');
|
|
256
|
+
labels.forEach(function(el) {
|
|
257
|
+
el.style.color = vars.primaryTextColor;
|
|
258
|
+
el.style.fill = vars.primaryTextColor;
|
|
259
|
+
});
|
|
260
|
+
// Override edge paths
|
|
261
|
+
var edges = svg.querySelectorAll('.flowchart-link');
|
|
262
|
+
edges.forEach(function(el) {
|
|
263
|
+
el.style.stroke = vars.lineColor;
|
|
264
|
+
});
|
|
265
|
+
// Override edge labels
|
|
266
|
+
var edgeLabels = svg.querySelectorAll('.edgeLabel');
|
|
267
|
+
edgeLabels.forEach(function(el) {
|
|
268
|
+
el.style.backgroundColor = vars.edgeLabelBackground;
|
|
269
|
+
el.style.color = vars.primaryTextColor;
|
|
270
|
+
});
|
|
271
|
+
var edgeLabelRects = svg.querySelectorAll('.edgeLabel rect');
|
|
272
|
+
edgeLabelRects.forEach(function(el) {
|
|
273
|
+
el.setAttribute('style', 'fill:' + vars.edgeLabelBackground + ' !important');
|
|
274
|
+
});
|
|
275
|
+
// Override arrowheads
|
|
276
|
+
var markers = svg.querySelectorAll('.marker, .arrowMarkerPath');
|
|
277
|
+
markers.forEach(function(el) {
|
|
278
|
+
el.setAttribute('style', 'fill:' + vars.lineColor + ' !important;stroke:' + vars.lineColor + ' !important');
|
|
279
|
+
});
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
function applyTheme(name, skipRerender) {
|
|
283
|
+
document.documentElement.setAttribute('data-theme', name);
|
|
284
|
+
try { localStorage.setItem(STORAGE_KEY, name); } catch(e) {}
|
|
285
|
+
// Update mermaid theme with custom variables matching our theme
|
|
286
|
+
var vars = MERMAID_THEME_VARS[name] || MERMAID_THEME_VARS.midnight;
|
|
287
|
+
mermaid.initialize({ startOnLoad: false, theme: 'base', themeVariables: vars, securityLevel: 'loose' });
|
|
288
|
+
if (!skipRerender) {
|
|
289
|
+
var el = document.getElementById('mermaid-diagram');
|
|
290
|
+
if (el) {
|
|
291
|
+
el.removeAttribute('data-processed');
|
|
292
|
+
mermaid.init(undefined, el);
|
|
293
|
+
// Re-apply node colors after Mermaid re-renders
|
|
294
|
+
setTimeout(function() { rethemeSvgNodes(name); }, 500);
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
// Update active state in menu
|
|
298
|
+
var btns = document.querySelectorAll('.theme-menu button');
|
|
299
|
+
btns.forEach(function(b) {
|
|
300
|
+
b.classList.toggle('active', b.textContent.toLowerCase() === name);
|
|
301
|
+
});
|
|
302
|
+
document.getElementById('theme-menu').classList.remove('open');
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
function toggleThemeMenu() {
|
|
306
|
+
document.getElementById('theme-menu').classList.toggle('open');
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
// Close menu on outside click
|
|
310
|
+
document.addEventListener('click', function(e) {
|
|
311
|
+
var picker = document.querySelector('.theme-picker');
|
|
312
|
+
if (picker && !picker.contains(e.target)) {
|
|
313
|
+
document.getElementById('theme-menu').classList.remove('open');
|
|
314
|
+
}
|
|
315
|
+
});
|
|
316
|
+
|
|
317
|
+
// Listen for system preference changes
|
|
318
|
+
if (window.matchMedia) {
|
|
319
|
+
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', function(e) {
|
|
320
|
+
// Only react if no explicit theme was set
|
|
321
|
+
try {
|
|
322
|
+
if (!localStorage.getItem(STORAGE_KEY) && !INITIAL_THEME) {
|
|
323
|
+
applyTheme(e.matches ? 'midnight' : 'daylight');
|
|
324
|
+
}
|
|
325
|
+
} catch(ex) {}
|
|
326
|
+
});
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
// Apply initial theme (skip re-render since Mermaid hasn't rendered yet)
|
|
330
|
+
applyTheme(resolveTheme(), true);
|
|
331
|
+
|
|
332
|
+
// Init Mermaid (single init on page load)
|
|
333
|
+
var currentThemeName = resolveTheme();
|
|
334
|
+
var initVars = MERMAID_THEME_VARS[currentThemeName] || MERMAID_THEME_VARS.midnight;
|
|
335
|
+
mermaid.initialize({ startOnLoad: true, theme: 'base', themeVariables: initVars, securityLevel: 'loose' });
|
|
336
|
+
|
|
337
|
+
const IR_DATA = ${d};
|
|
338
|
+
const PATHS_DATA = ${l};
|
|
339
|
+
const COMPLEXITY = ${f};
|
|
340
|
+
const DIAGRAMS = {
|
|
341
|
+
base: ${JSON.stringify(o)},
|
|
342
|
+
dataFlow: ${JSON.stringify(i)},
|
|
343
|
+
errorFlow: ${JSON.stringify(c)}
|
|
344
|
+
};
|
|
345
|
+
|
|
346
|
+
// Complexity stats
|
|
347
|
+
document.getElementById('complexity-stats').textContent =
|
|
348
|
+
'CC: ' + COMPLEXITY.cyclomaticComplexity +
|
|
349
|
+
' | Cognitive: ' + COMPLEXITY.cognitiveComplexity +
|
|
350
|
+
' | Depth: ' + COMPLEXITY.maxDepth +
|
|
351
|
+
' | Paths: ' + COMPLEXITY.pathCount;
|
|
352
|
+
|
|
353
|
+
// Complexity table
|
|
354
|
+
var ct = document.getElementById('complexity-table');
|
|
355
|
+
ct.innerHTML = Object.entries(COMPLEXITY).map(function(e) {
|
|
356
|
+
return '<tr><td>' + e[0] + '</td><td><b>' + e[1] + '</b></td></tr>';
|
|
357
|
+
}).join('');
|
|
358
|
+
|
|
359
|
+
// Paths list
|
|
360
|
+
var pl = document.getElementById('paths-list');
|
|
361
|
+
var pathSelect = document.getElementById('pathSelect');
|
|
362
|
+
PATHS_DATA.forEach(function(p, i) {
|
|
363
|
+
var div = document.createElement('div');
|
|
364
|
+
div.className = 'path-item';
|
|
365
|
+
div.onclick = function() { selectPath(i); };
|
|
366
|
+
div.innerHTML = '<b>Path ' + (i+1) + '</b> (' + p.steps.length + ' steps)<br>' +
|
|
367
|
+
p.steps.map(function(s) { return '<span class="path-step">' + (s.name||s.nodeId) + '</span>'; }).join(' \u2192 ');
|
|
368
|
+
pl.appendChild(div);
|
|
369
|
+
var opt = document.createElement('option');
|
|
370
|
+
opt.value = i;
|
|
371
|
+
opt.textContent = 'Path ' + (i+1) + ' (' + p.steps.length + ' steps)';
|
|
372
|
+
pathSelect.appendChild(opt);
|
|
373
|
+
});
|
|
374
|
+
|
|
375
|
+
// Build flat node index for click-to-navigate
|
|
376
|
+
var nodeIndex = {};
|
|
377
|
+
function indexNodes(nodes) {
|
|
378
|
+
if (!nodes) return;
|
|
379
|
+
nodes.forEach(function(n) {
|
|
380
|
+
if (n.id) nodeIndex[n.id] = n;
|
|
381
|
+
// Recurse into known child arrays
|
|
382
|
+
if (n.children) indexNodes(n.children);
|
|
383
|
+
if (n.onTrue) indexNodes(n.onTrue);
|
|
384
|
+
if (n.onFalse) indexNodes(n.onFalse);
|
|
385
|
+
if (n.tryBody) indexNodes(n.tryBody);
|
|
386
|
+
if (n.catchBody) indexNodes(n.catchBody);
|
|
387
|
+
if (n.finallyBody) indexNodes(n.finallyBody);
|
|
388
|
+
if (n.body) indexNodes(n.body);
|
|
389
|
+
if (n.yields) n.yields.forEach(function(y) { if (y.effect) indexNodes([y.effect]); });
|
|
390
|
+
if (n.source && n.source.id) indexNodes([n.source]);
|
|
391
|
+
if (n.handler && n.handler.id) indexNodes([n.handler]);
|
|
392
|
+
if (n.operations) indexNodes(n.operations);
|
|
393
|
+
if (n.cases) n.cases.forEach(function(c) { if (c.body) indexNodes(c.body); });
|
|
394
|
+
});
|
|
395
|
+
}
|
|
396
|
+
indexNodes(IR_DATA.root.children);
|
|
397
|
+
|
|
398
|
+
// Type filter populate
|
|
399
|
+
var types = new Set();
|
|
400
|
+
function collectTypes(nodes) {
|
|
401
|
+
if (!nodes) return;
|
|
402
|
+
nodes.forEach(function(n) {
|
|
403
|
+
types.add(n.type);
|
|
404
|
+
if (n.children) collectTypes(n.children);
|
|
405
|
+
if (n.onTrue) collectTypes(n.onTrue);
|
|
406
|
+
if (n.onFalse) collectTypes(n.onFalse);
|
|
407
|
+
if (n.body) collectTypes(n.body);
|
|
408
|
+
if (n.tryBody) collectTypes(n.tryBody);
|
|
409
|
+
if (n.catchBody) collectTypes(n.catchBody);
|
|
410
|
+
});
|
|
411
|
+
}
|
|
412
|
+
collectTypes(IR_DATA.root.children);
|
|
413
|
+
var tf = document.getElementById('typeFilter');
|
|
414
|
+
Array.from(types).sort().forEach(function(t) {
|
|
415
|
+
var opt = document.createElement('option');
|
|
416
|
+
opt.value = t; opt.textContent = t;
|
|
417
|
+
tf.appendChild(opt);
|
|
418
|
+
});
|
|
419
|
+
|
|
420
|
+
// Tab switching
|
|
421
|
+
function showTab(name) {
|
|
422
|
+
document.querySelectorAll('.tab-content').forEach(function(el) { el.hidden = true; });
|
|
423
|
+
document.querySelectorAll('.sidebar-tabs button').forEach(function(el) { el.classList.remove('active'); });
|
|
424
|
+
document.getElementById('tab-' + name).hidden = false;
|
|
425
|
+
event.target.classList.add('active');
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
// Search
|
|
429
|
+
function handleSearch(q) {
|
|
430
|
+
// Simple text highlight in IR tab
|
|
431
|
+
var pre = document.getElementById('ir-json');
|
|
432
|
+
if (!q) { pre.innerHTML = JSON.stringify(IR_DATA, null, 2); return; }
|
|
433
|
+
var text = JSON.stringify(IR_DATA, null, 2);
|
|
434
|
+
var escaped = q.replace(/[.*+?^\${}()|\\[\\]\\\\]/g, '\\\\$&');
|
|
435
|
+
pre.innerHTML = text.replace(new RegExp(escaped, 'gi'), '<mark>$&</mark>');
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
function handleTypeFilter(type) {
|
|
439
|
+
// Scroll IR to first occurrence of selected type
|
|
440
|
+
if (!type) return;
|
|
441
|
+
var pre = document.getElementById('ir-json');
|
|
442
|
+
var text = pre.textContent;
|
|
443
|
+
var idx = text.indexOf('"type": "' + type + '"');
|
|
444
|
+
if (idx >= 0) {
|
|
445
|
+
showTab('ir');
|
|
446
|
+
document.querySelectorAll('.sidebar-tabs button').forEach(function(b) {
|
|
447
|
+
b.classList.toggle('active', b.textContent === 'IR');
|
|
448
|
+
});
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
// Overlay toggles
|
|
453
|
+
function toggleOverlay(kind) {
|
|
454
|
+
var el = document.getElementById('mermaid-diagram');
|
|
455
|
+
var dataOn = document.getElementById('toggleDataFlow').checked;
|
|
456
|
+
var errorOn = document.getElementById('toggleErrorFlow').checked;
|
|
457
|
+
var src = DIAGRAMS.base;
|
|
458
|
+
if (dataOn) src = DIAGRAMS.dataFlow;
|
|
459
|
+
if (errorOn) src = DIAGRAMS.errorFlow;
|
|
460
|
+
if (dataOn && errorOn) src = DIAGRAMS.dataFlow; // data takes precedence
|
|
461
|
+
el.innerHTML = src;
|
|
462
|
+
el.removeAttribute('data-processed');
|
|
463
|
+
mermaid.init(undefined, el);
|
|
464
|
+
var curTheme = document.documentElement.getAttribute('data-theme') || 'midnight';
|
|
465
|
+
setTimeout(function() { rethemeSvgNodes(curTheme); }, 500);
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
// Path selection
|
|
469
|
+
function selectPath(idx) {
|
|
470
|
+
idx = parseInt(idx);
|
|
471
|
+
document.querySelectorAll('.path-item').forEach(function(el, i) {
|
|
472
|
+
el.classList.toggle('selected', i === idx);
|
|
473
|
+
});
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
// Click-to-navigate: show node details when clicking on diagram nodes
|
|
477
|
+
function showNodeDetails(nodeId) {
|
|
478
|
+
var node = nodeIndex[nodeId];
|
|
479
|
+
if (!node) return;
|
|
480
|
+
var det = document.getElementById('node-details');
|
|
481
|
+
var loc = node.location ? node.location.filePath + ':' + node.location.line + ':' + node.location.column : 'N/A';
|
|
482
|
+
var html = '<h3>Node Details</h3>';
|
|
483
|
+
html += '<table>';
|
|
484
|
+
html += '<tr><td>ID</td><td><code>' + node.id + '</code></td></tr>';
|
|
485
|
+
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>';
|
|
488
|
+
if (node.semanticRole) html += '<tr><td>Role</td><td>' + node.semanticRole + '</td></tr>';
|
|
489
|
+
html += '<tr><td>Location</td><td><code>' + loc + '</code></td></tr>';
|
|
490
|
+
if (node.typeSignature) {
|
|
491
|
+
var sig = node.typeSignature;
|
|
492
|
+
html += '<tr><td>Type Sig</td><td><code>Effect<' + (sig.successType||'?') + ', ' + (sig.errorType||'?') + ', ' + (sig.requirementsType||'?') + '></code></td></tr>';
|
|
493
|
+
}
|
|
494
|
+
html += '</table>';
|
|
495
|
+
if (node.description) html += '<p style="margin-top:0.5rem;opacity:0.8">' + node.description + '</p>';
|
|
496
|
+
det.innerHTML = html;
|
|
497
|
+
// Switch to details tab
|
|
498
|
+
document.querySelectorAll('.tab-content').forEach(function(el) { el.hidden = true; });
|
|
499
|
+
document.querySelectorAll('.sidebar-tabs button').forEach(function(b) { b.classList.remove('active'); });
|
|
500
|
+
document.getElementById('tab-details').hidden = false;
|
|
501
|
+
document.querySelectorAll('.sidebar-tabs button')[0].classList.add('active');
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
// Register Mermaid click callbacks and apply theme to SVG after rendering
|
|
505
|
+
document.addEventListener('DOMContentLoaded', function() {
|
|
506
|
+
setTimeout(function() {
|
|
507
|
+
rethemeSvgNodes(document.documentElement.getAttribute('data-theme') || 'midnight');
|
|
508
|
+
var svgNodes = document.querySelectorAll('.mermaid svg .node');
|
|
509
|
+
svgNodes.forEach(function(el) {
|
|
510
|
+
el.style.cursor = 'pointer';
|
|
511
|
+
el.addEventListener('click', function() {
|
|
512
|
+
var id = el.id || '';
|
|
513
|
+
// Mermaid node IDs often have prefixes; try to match against nodeIndex
|
|
514
|
+
for (var key in nodeIndex) {
|
|
515
|
+
if (id.indexOf(key) >= 0 || id.indexOf(key.replace(/[^a-zA-Z0-9]/g, '_')) >= 0) {
|
|
516
|
+
showNodeDetails(key);
|
|
517
|
+
return;
|
|
518
|
+
}
|
|
519
|
+
}
|
|
520
|
+
});
|
|
521
|
+
});
|
|
522
|
+
}, 1000);
|
|
523
|
+
});
|
|
524
|
+
</script>
|
|
525
|
+
</body>
|
|
526
|
+
</html>`}function Gn(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}import{Option as Wd}from"effect";var Kd={includeDiagram:!0,includeComplexity:!0,includeServiceDeps:!0,includeErrors:!0,includeDataFlow:!0};function ss(e,t,r){for(let n of e){let o=Bd(n,r);o&&t.push(o);let s=Wd.getOrElse(v(n),()=>[]);s.length>0&&ss(s,t,r+1)}}function Bd(e,t){switch(e.type){case"effect":return{name:e.callee||"Effect",type:"effect",description: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:`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:`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:`Stream pipeline${e.pipeline.length>0?`: ${e.pipeline.map(r=>r.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 is(e,t){let r={...Kd,...t},n=[];if(n.push(`# ${e.root.programName}`),n.push(""),e.root.jsdocDescription&&(n.push(e.root.jsdocDescription),n.push("")),n.push("## Overview"),n.push(""),n.push(`- **Source**: \`${e.metadata.filePath}\``),n.push(`- **Entry**: ${e.root.source}`),e.root.typeSignature){let s=e.root.typeSignature;n.push(`- **Type**: \`Effect<${s.successType}, ${s.errorType}, ${s.requirementsType}>\``)}n.push("");let o=[];if(ss(e.root.children,o,0),o.length>0){n.push("## Workflow Steps"),n.push("");for(let s of o){let a=" ".repeat(s.depth);n.push(`${a}- **${s.name}** _(${s.type})_: ${s.description}`)}n.push("")}if(r.includeServiceDeps&&e.root.dependencies.length>0){n.push("## Service Dependencies"),n.push(""),n.push("| Service | Type | Layer |"),n.push("|---------|------|-------|");for(let s of e.root.dependencies)n.push(`| ${s.name} | ${s.typeSignature??"-"} | ${s.isLayer?"Yes":"No"} |`);n.push("")}if(r.includeErrors){let s=Ve(e);if(s.allErrors.length>0){n.push("## Error Types"),n.push("");for(let a of s.allErrors){let i=s.errorToSteps.get(a)??[];n.push(`- **${a}**: produced by ${i.length} step(s)`)}n.push("")}}if(r.includeComplexity){let s=Se(e);n.push("## Complexity Metrics"),n.push(""),n.push("| Metric | Value |"),n.push("|--------|-------|"),n.push(`| Cyclomatic Complexity | ${s.cyclomaticComplexity} |`),n.push(`| Cognitive Complexity | ${s.cognitiveComplexity} |`),n.push(`| Max Depth | ${s.maxDepth} |`),n.push(`| Decision Points | ${s.decisionPoints} |`),n.push(`| Max Parallel Breadth | ${s.maxParallelBreadth} |`),n.push("")}if(r.includeDataFlow){let s=Nt(e);if(s.undefinedReads.length>0||s.duplicateWrites.length>0){n.push("## Data Flow Warnings"),n.push("");for(let a of s.undefinedReads)n.push(`- **Undefined read**: \`${a.key}\` read by ${a.readerName??a.readerId}`);for(let a of s.duplicateWrites)n.push(`- **Duplicate write**: \`${a.key}\` written by ${a.writerIds.join(", ")}`);n.push("")}}return r.includeDiagram&&(n.push("## Flow Diagram"),n.push(""),n.push("```mermaid"),n.push(le(e)),n.push("```"),n.push("")),n.join(`
|
|
527
|
+
`)}function qd(e,t){let r=[];r.push("# Effect Program Documentation"),r.push(""),r.push(`Generated: ${new Date().toISOString()}`),r.push(""),r.push("## Programs"),r.push("");for(let n of e)r.push(`- [${n.root.programName}](#${n.root.programName.toLowerCase().replace(/[^a-z0-9]/g,"-")})`);r.push("");for(let n of e)r.push("---"),r.push(""),r.push(is(n,t)),r.push("");return r.join(`
|
|
528
|
+
`)}import{Option as jd}from"effect";function _d(e){return e?e.typeConfidence:"unknown"}function zd(e){return!e||e==="never"?"never":e}function Hd(e){return!e||e==="never"?[]:we(e).filter(t=>t!=="never")}function Jn(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 Ae(e,t,r){for(let n of e){let o=Ud(n,r);o&&t.push(o);let s=r;if(n.type==="loop"){s={...s,inLoop:!0,loopType:n.loopType,iterationSource:n.iterSource},Ae([n.body],t,s);continue}if(n.type==="retry"){let i=n.scheduleInfo?{attempts:n.scheduleInfo.maxRetries??"unlimited",backoff:n.scheduleInfo.baseStrategy}:{attempts:"unlimited",backoff:n.schedule??"unknown"};s={...s,inRetry:i},Ae([n.source],t,s);continue}if(n.type==="timeout"){s={...s,inTimeout:{ms:n.duration??"unknown"}},Ae([n.source],t,s);continue}if(n.type==="resource"){n.use&&Ae([n.use],t,r);continue}if(n.type==="error-handler"){Ae([n.source],t,r),n.handler&&Ae([n.handler],t,r);continue}if(n.type==="generator"){let i=n.yields.map(c=>c.effect);Ae(i,t,s);continue}let a=jd.getOrElse(v(n),()=>[]);a.length>0&&Ae(a,t,s)}}function Ud(e,t){switch(e.type){case"effect":{let r=e.typeSignature,n=r?.successType??"unknown",o=r?.errorType??"never";return{stepId:e.id,name:e.displayName??e.callee,callee:e.callee,outputType:n,outputTypeKind:_d(r),outputTypeDisplay:n,outputTypeText:r?`Effect<${r.successType}, ${r.errorType}, ${r.requirementsType}>`:`Effect<${n}>`,errorTypeDisplay:zd(o),errors:Hd(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 r=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:r}}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:Jn(e.acquire),use:e.use?Jn(e.use):void 0,release:Jn(e.release)};case"error-handler":{if(e.handlerType==="catchTag"||e.handlerType==="catchTags"){let r=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:r.join(" | ")||"unknown",errors:r,stepKind:"error-handler"}}return null}default:return null}}function as(e,t,r){let n=le(e,{direction:t?.direction??"TB"}),o=[];return Ae(e.root.children,o,{}),{title:e.root.programName,code:r??"",mermaid:n,stepDetails:o}}function Vd(e,t,r){return e.map(n=>as(n,t,r))}import{Option as cs}from"effect";function At(e,t){for(let r of e){if(r.type==="effect"){let o=r,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 n=cs.getOrElse(v(r),()=>[]);n.length>0&&At(n,t)}}function Yn(e,t){for(let r of e){if(r.type==="generator"){for(let o of r.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 n=cs.getOrElse(v(r),()=>[]);n.length>0&&Yn(n,t)}}function Gd(e,t,r={}){let n=new Set(e.map(l=>l.root.programName)),o=e.length>0?e[0]:void 0,s=r.entryProgramName??(o?o.root.programName:""),a={programs:new Map,entryProgram:s,circularDependencies:[],unresolvedReferences:[]};for(let l of e){let f=l.root.programName,u=[];At(l.root.children,u);let p=u.filter(m=>n.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)n.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 S=[];At(m.root.children,S),S.some(h=>h.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 ls(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.programs.get(s);if(a)for(let i of a.calls)i.resolved&&o(i.targetProgram);n.delete(s),r.add(s),t.push(s)}for(let s of e.programs.keys())o(s);return t}function Jd(e,t){let r=new Set,n=new Set;function o(s){if(n.has(s))return;n.add(s);let a=e.programs.get(s);if(a)for(let i of a.calls)i.resolved&&(r.add(i.targetProgram),o(i.targetProgram))}return o(t),Array.from(r)}function Yd(e,t){let r=new Set,n=new Set;function o(s){if(n.has(s))return;n.add(s);let a=e.programs.get(s);if(a)for(let i of a.calledBy)r.add(i),o(i)}return o(t),Array.from(r)}function Qd(e){let t=0,r=0;for(let s of e.programs.values())t+=Se(s.ir).cyclomaticComplexity;let n=ls(e),o=new Map;for(let s of n){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),r=Math.max(r,i)}return{totalCyclomaticComplexity:t,totalPrograms:e.programs.size,maxDepth:r,hasCircularDependencies:e.circularDependencies.length>0}}function Zd(e){let t=[],r=n=>n.replace(/[^a-zA-Z0-9_]/g,"_");t.push("flowchart TD"),t.push(""),t.push(" %% Program Composition Graph"),t.push("");for(let[n]of e.programs){let s=n===e.entryProgram?`${r(n)}[["${n}"]]
|
|
529
|
+
`:` ${r(n)}["${n}"]`;t.push(s.startsWith(" ")?s:` ${s}`)}t.push("");for(let[,n]of e.programs)for(let o of n.calls)if(o.resolved){let s=o.callSite?`L${o.callSite.line}`:"";s?t.push(` ${r(n.name)} -->|${s}| ${r(o.targetProgram)}`):t.push(` ${r(n.name)} --> ${r(o.targetProgram)}`)}if(t.push(""),t.push(" classDef entryPoint fill:#C8E6C9,stroke:#2E7D32,stroke-width:3px"),t.push(` class ${r(e.entryProgram)} entryPoint`),e.circularDependencies.length>0){t.push(" classDef cyclic fill:#FFCDD2,stroke:#C62828,stroke-width:2px");let n=new Set;for(let o of e.circularDependencies)for(let s of o)n.add(s);for(let o of n)t.push(` class ${r(o)} cyclic`)}return t.join(`
|
|
530
|
+
`)}function Xd(e){let t=[],r=s=>s.replace(/[^a-zA-Z0-9_]/g,"_");t.push("flowchart TD"),t.push("");let n=new Map;for(let[,s]of e.programs){let a=n.get(s.filePath)??[];a.push(s),n.set(s.filePath,a)}let o=0;for(let[s,a]of n){let i=s.split("/").pop()??s;t.push(` subgraph file${o}["${i}"]`);for(let c of a)c.name===e.entryProgram?t.push(` ${r(c.name)}[["${c.name}"]]`):t.push(` ${r(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(` ${r(s.name)} -->|${i}| ${r(a.targetProgram)}`)}if(e.unresolvedReferences.length>0){t.push(""),t.push(" %% Unresolved references");for(let s of e.unresolvedReferences){let a=`unresolved_${r(s.programName)}`;t.push(` ${a}["? ${s.programName}"]`),t.push(` ${r(s.referencedFrom)} -.-> ${a}`)}t.push(" classDef unresolved fill:#FFF3CD,stroke:#856404,stroke-dasharray:5");for(let s of e.unresolvedReferences)t.push(` class unresolved_${r(s.programName)} unresolved`)}return t.join(`
|
|
531
|
+
`)}function eu(e,t={},r){let n=new Set,o=new Map,s=new Map;for(let[u,p]of e)for(let g of p){let m=g.root.programName;n.add(m),o.set(m,u),s.set(m,g)}let a=n.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=[];At(p.root.children,m);let S=[];Yn(p.root.children,S);for(let C of S)if(!m.some(E=>E.callee===C.callee)){let E={callee:C.callee};C.location&&(E.location=C.location),m.push(E)}let h=m.filter(C=>n.has(C.callee)&&C.callee!==u).map(C=>C.location?{targetProgram:C.callee,callSite:C.location,resolved:!0}:{targetProgram:C.callee,resolved:!0}),N=r?new Set(r.services.keys()):new Set;for(let C of m)n.has(C.callee)&&C.callee!==u||C.callee.startsWith("Effect.")||C.callee.includes(".")||C.callee!==u&&(N.has(C.callee)||c.unresolvedReferences.push({programName:C.callee,referencedFrom:u,reason:"Program not found in project"}));let x=[];for(let[C,E]of s){if(C===u)continue;let y=[];At(E.root.children,y);let w=[];Yn(E.root.children,w),(y.some(k=>k.callee===u)||w.some(k=>k.callee===u))&&x.push(C)}c.programs.set(u,{name:u,filePath:g,ir:p,calls:h,calledBy:x})}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 tu(e,t){let r=[],n=o=>o.replace(/[^a-zA-Z0-9_]/g,"_");r.push("flowchart TD"),r.push(""),r.push(" %% Programs");for(let[o]of e.programs)o===e.entryProgram?r.push(` ${n(o)}[["${o}"]]`):r.push(` ${n(o)}["${o}"]`);r.push(""),r.push(" %% Services");for(let[o]of t.services)r.push(` svc_${n(o)}{{{"${o}"}}}`);r.push(""),r.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*";r.push(` ${n(o.name)} -->|${a}| ${n(s.targetProgram)}`)}r.push(""),r.push(" %% Service dependencies");for(let[o,s]of t.services)for(let a of s.consumers)e.programs.has(a.programName)&&r.push(` ${n(a.programName)} -.->|yield*| svc_${n(o)}`);r.push(""),r.push(" %% Service layer dependencies");for(let[o,s]of t.services)for(let a of s.dependencies)t.services.has(a)&&r.push(` svc_${n(o)} -.-> svc_${n(a)}`);r.push(""),r.push(" classDef entryPoint fill:#C8E6C9,stroke:#2E7D32,stroke-width:3px"),r.push(" classDef service fill:#E3F2FD,stroke:#1565C0,stroke-width:2px"),r.push(` class ${n(e.entryProgram)} entryPoint`);for(let o of t.services.keys())r.push(` class svc_${n(o)} service`);return r.join(`
|
|
532
|
+
`)}import{Option as nu}from"effect";function ru(e){return e.startsWith("Ref.")||e.startsWith("FiberRef.")||e.startsWith("SynchronizedRef.")}function ou(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 su(e){return e.startsWith("Ref.")?"Ref":e.startsWith("FiberRef.")?"FiberRef":e.startsWith("SynchronizedRef.")?"SynchronizedRef":"Ref"}var iu=new Set(["set","update","modify","getAndSet","getAndUpdate"]);function au(e){let t=[],r=[],n=new Map,o=new Map;function s(c){for(let d of c){if(d.type==="effect"){let f=d,u=f.callee;if(ru(u)){let p=su(u),g=ou(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),iu.has(g)){r.push({refId:p,nodeId:f.id,operation:g});let S=o.get(p)??[];S.push(f.id),o.set(p,S)}else if(g==="get"){let S=n.get(p)??[];S.push(f.id),n.set(p,S)}}}let l=nu.getOrElse(v(d),()=>[]);l.length>0&&s(l)}}s(e.root.children);let a=Array.from(new Set([...n.keys(),...o.keys()])).map(c=>({refId:c,readers:n.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:r,potentialRaces:i,stateGraph:a}}import{Option as cu}from"effect";function lu(e){let t=[],r=[],n=[],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}),r.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}),r.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}),r.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}),r.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}),r.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}),r.push(f)}}else(l.startsWith("Pool.")||l.startsWith("KeyedPool."))&&n.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=cu.getOrElse(v(i),()=>[]);c.length>0&&s(c)}}return s(e.root.children),{acquisitions:t,scopeBoundaries:r,poolCreations:n,potentialLeaks:o}}import{Option as ds}from"effect";function us(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 fs(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 du(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 ps(e){return e.startsWith("Metric.")||e.includes(".track")}function uu(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 fu(e){let t=[],r=[],n=[],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 x=p,C=x.callee??"";if(o++,us(C)){let E={nodeId:x.id};x.location&&(E.location={line:x.location.line,column:x.location.column}),t.push(E)}if(f&&s++,fs(C)){let E={nodeId:x.id,level:du(C)};x.location&&(E.location={line:x.location.line,column:x.location.column}),r.push(E)}if(ps(C)){let E=C.includes("tagged")||C.includes("taggedWith"),y={nodeId:x.id,type:uu(C),...E?{isTagged:!0}:{}};x.location&&(y.location={line:x.location.line,column:x.location.column}),n.push(y)}u&&a++}if(p.type==="error-handler"){c++;let x=p;if(x.handler){let C=!1,E=y=>{if(y.type==="effect"){let k=y.callee??"";fs(k)&&(C=!0)}ds.getOrElse(v(y),()=>[]).forEach(E)};E(x.handler),C&&i++}}let g=ds.getOrElse(v(p),()=>[]),m=p.type==="effect"&&us(p.callee??""),S=p.type==="effect"&&ps(p.callee??""),h=f||m,N=u||S;g.length>0&&d(g,h,N)}}return d(e.root.children,!1,!1),{spans:t,logPoints:r,metrics:n,coverage:{effectCount:o,effectsWithSpans:s,effectsWithMetrics:a,errorHandlersWithLogging:i,errorHandlerCount:c}}}import{Option as pu}from"effect";function gu(e){let t=new Map,r=new Map;for(let a of e.layers)for(let i of a.provides){let c=r.get(i)??[];c.push(a.id),r.set(i,c)}for(let a of e.layers){let i=[];for(let c of a.requires)for(let d of r.get(c)??[])d!==a.id&&i.push(d);t.set(a.id,i)}let n=new Set,o=new Set,s=a=>{if(n.has(a))return!0;if(o.has(a))return!1;n.add(a);for(let i of t.get(a)??[])if(s(i))return!0;return n.delete(a),o.add(a),!1};for(let a of t.keys())if(s(a))return!1;return!0}function mu(e){let t=wt(e),r=Ge(e),n=new Map;for(let u of r.layers)for(let p of u.provides)n.set(p,u.id);let o=t.requiredServices.map(u=>u.serviceId),s=[],a=!0;for(let u of o){let p=n.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=gu(r),c=new Map;for(let u of r.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=pu.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:n,entries:s,layerGraphAcyclic:i,valid:a,...f.length>0?{layerConflicts:f}:{}}}function hu(e){let t=[];t.push(`Service Completeness Report for ${e.programName}:`);for(let r of e.entries){let n=r.status==="ok"?"\u2713":"\u2717",o=r.providedBy?` \u2192 provided by ${r.providedBy}`:"";t.push(` ${n} ${r.serviceId}${o} ${r.status==="missing"?r.message:""}`)}return t.push(""),t.push(e.valid?"All required services have providers.":"Some required services have no provider."),t.join(`
|
|
533
|
+
`)}import{Option as dt}from"effect";var yu={requireErrors:!0,requireParallelErrors:!0,warningsAsErrors:!1};function Su(e,t={}){let r={...yu,...t,requireErrors:t.requireErrors??!0,requireParallelErrors:t.requireParallelErrors??!0,warningsAsErrors:t.warningsAsErrors??!1},n=[];gs(e.root.children,r,n,!1),ms(e.root.children,n,new Set),hs(e.root.children,n,!1),ys(e.root.children,n),Ss(e.root.children,n),xu(e,n);let o=n.filter(a=>a.severity==="error"||r.warningsAsErrors&&a.severity==="warning"),s=n.filter(a=>a.severity==="warning"&&!r.warningsAsErrors);return{valid:o.length===0,diagnostics:n,errors:o,warnings:s}}function gs(e,t,r,n=!1){for(let o of e){let s=n||o.type==="error-handler";if(o.type==="effect"){let i=o;Eu(i,t,r);let c=i.typeSignature?.errorType?.trim();c&&c!=="never"&&!n&&r.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()==="")&&r.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()==="")&&r.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=dt.getOrElse(v(o),()=>[]);a.length>0&&gs(a,t,r,s)}}function ms(e,t,r){for(let n of e){if(n.type==="fiber"){let s=n;(s.operation==="fork"||s.operation==="forkAll")&&!s.isScoped&&!s.isDaemon&&!r.has("join")&&!r.has("interrupt")&&!r.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")&&r.add(s.operation)}let o=dt.getOrElse(v(n),()=>[]);o.length>0&&ms(o,t,r)}}function hs(e,t,r){for(let n of e){n.type==="resource"&&!r&&t.push({rule:"resource-missing-scope",severity:"warning",message:"acquireRelease without visible Effect.scoped in scope",fix:"Wrap resource usage in Effect.scoped",location:n.location,nodeId:n.id});let o=n.type==="effect"&&n.callee==="Effect.scoped",s=dt.getOrElse(v(n),()=>[]);s.length>0&&hs(s,t,r||o)}}function ys(e,t){for(let r of e){if(r.type==="parallel"&&r.children.length>5){let o=r.callee||"";(o.includes("all")||o.includes("forEach"))&&t.push({rule:"unbounded-concurrency",severity:"warning",message:`${o} with ${r.children.length} children \u2014 consider adding { concurrency } option`,fix:"Add { concurrency: N } to limit concurrent execution",location:r.location,nodeId:r.id})}r.type==="loop"&&(r.loopType==="forEach"||r.loopType==="validate")&&t.push({rule:"unbounded-concurrency",severity:"warning",message:`Effect.${r.loopType} may run unbounded \u2014 consider concurrency control`,fix:"Add { concurrency: N } option",location:r.location,nodeId:r.id});let n=dt.getOrElse(v(r),()=>[]);n.length>0&&ys(n,t)}}function Ss(e,t){for(let r of e){if(r.type==="decision"){let o=r.label.trim();(o==="true"||o==="false")&&t.push({rule:"dead-code-path",severity:"warning",message:`Decision "${r.condition}" always resolves to ${o} \u2014 ${o==="true"?"false":"true"} branch is dead code`,fix:"Remove the dead branch or fix the condition",location:r.location,nodeId:r.id})}let n=dt.getOrElse(v(r),()=>[]);n.length>0&&Ss(n,t)}}function xu(e,t){let r=Ge(e);if(r.layers.length===0)return;let n=new Set;for(let o of r.layers)for(let s of o.requires)n.add(s);xs(e.root.children,n);for(let o of r.layers)for(let s of o.provides)n.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 xs(e,t){for(let r of e){if(r.type==="effect"){let o=r.requiredServices??[];for(let s of o)t.add(s.serviceId)}let n=dt.getOrElse(v(r),()=>[]);n.length>0&&xs(n,t)}}function Eu(e,t,r){if(!t.requireErrors)return;let n=e.typeSignature?.errorType;if(!n){r.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}n.trim()==="unknown"&&r.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 bu(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 r of e.diagnostics){let n=r.severity==="error"?"x":"!",o=r.location?`:${r.location.line}:${r.location.column}`:"";t.push(`[${n}] [${r.rule}]${o}`),t.push(` ${r.message}`),r.fix&&t.push(` Fix: ${r.fix}`),t.push("")}return t.join(`
|
|
534
|
+
`)}function Cu(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 Nu(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 vu={testNamePrefix:"should",testNameGenerator:Iu,includeLoopPaths:!0};function wu(e,t={}){let r={...vu,...t},n=e;r.includeLoopPaths||(n=e.filter(i=>!i.hasLoops));let o=n.map(i=>Tu(i,r)),s=Ru(n),a=$u(o,s);return{paths:o,conditions:s,summary:a}}function Tu(e,t){let r=t.testNameGenerator(e),n=ku(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:r,description:e.description,setupConditions:o,expectedSteps:s,priority:n}}function ku(e){return e.conditions.length===0&&!e.hasLoops?"high":e.hasLoops&&e.conditions.length>2?"low":"medium"}function Iu(e){let t=["should"];if(e.steps.length>0){let r=e.steps.filter(n=>!n.repeated).slice(0,3);if(r.length>0){let n=r.map(o=>Au(o.name??o.nodeId));t.push(n.join(" then "))}}if(e.conditions.length>0){t.push("when");let r=e.conditions.slice(0,2).map(n=>{let o=Fu(n.expression);return n.mustBe?o:`not ${o}`});t.push(r.join(" and "))}return e.hasLoops&&t.push("(with iteration)"),t.join(" ")}function Au(e){return e.replace(/([a-z])([A-Z])/g,"$1 $2").replace(/([A-Z])([A-Z][a-z])/g,"$1 $2").toLowerCase()}function Fu(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 Ru(e){let t=new Map;for(let r of e)for(let n of r.conditions){let o=n.expression;t.has(o)||t.set(o,{whenTrue:[],whenFalse:[]});let s=t.get(o);s&&(n.mustBe?s.whenTrue.push(r.id):s.whenFalse.push(r.id))}return Array.from(t.entries()).map(([r,n])=>({expression:r,affectedPathsWhenTrue:n.whenTrue,affectedPathsWhenFalse:n.whenFalse}))}function $u(e,t){let r=e.filter(o=>o.priority==="high").length,n=Math.max(1,t.length*2);return{totalPaths:e.length,highPriorityPaths:r,totalConditions:t.length,minTestsForCoverage:n}}function Du(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 r=e.paths.filter(s=>s.priority==="high"),n=e.paths.filter(s=>s.priority==="medium"),o=e.paths.filter(s=>s.priority==="low");if(r.length>0){t.push("### High Priority"),t.push("");for(let s of r)t.push(...Qn(s));t.push("")}if(n.length>0){t.push("### Medium Priority"),t.push("");for(let s of n)t.push(...Qn(s));t.push("")}if(o.length>0){t.push("### Low Priority"),t.push("");for(let s of o)t.push(...Qn(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(`
|
|
535
|
+
`)}function Qn(e){let t=[];if(t.push(`#### ${e.suggestedTestName}`),t.push(""),e.setupConditions.length>0){t.push("**Setup:**");for(let r of e.setupConditions)t.push(`- ${r}`);t.push("")}t.push("**Expected Steps:**");for(let r=0;r<e.expectedSteps.length;r++)t.push(`${r+1}. ${e.expectedSteps[r]}`);return t.push(""),t}function Pu(e,t={}){let r=t.testRunner??"vitest",n=t.programName??"program",o=[];r==="vitest"?o.push("import { describe, it, expect } from 'vitest';"):r==="jest"?o.push("// Jest test file"):(o.push("import { describe, it } from 'mocha';"),o.push("import { expect } from 'chai';")),o.push(""),o.push(`describe('${n}', () => {`);for(let s of e.paths){o.push(""),o.push(` it('${Mu(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(${n});`),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(`
|
|
536
|
+
`)}function Mu(e){return e.replace(/'/g,"\\'").replace(/"/g,'\\"')}function Lu(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 r of e.paths){let n=r.priority==="high"?"***":r.priority==="medium"?"**":"*";t.push(`[ ] ${n} ${r.suggestedTestName}`),r.setupConditions.length>0&&t.push(` Conditions: ${r.setupConditions.join(", ")}`)}return t.join(`
|
|
537
|
+
`)}import{Project as Ou,SyntaxKind as Wu}from"ts-morph";function Ku(e,t,r){let{line:n,column:o}=r.getLineAndColumnAtPos(t.getStart());return{filePath:e,line:n+1,column:o}}function Bu(e,t){let r=new Ou({useInMemoryFileSystem:!0}),n=t?r.createSourceFile(e,t):r.addSourceFileAtPath(e),o=[],s=[],a=[],i=[],c=new Map,d=[];for(let l of n.getDescendantsOfKind(Wu.CallExpression)){let u=l.getExpression().getText(),p=Ku(e,l,n),S=l.getArguments()[0]?.getText().replace(/["'`]/g,"").trim()??"unknown",h=l.getParent()?.getText()??"",N=h.includes("withDefault"),x=S.toUpperCase().replace(/[^A-Z0-9]/g,"_");c.set(S,x);let C=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(C!==void 0){let y={key:S,type:C,required:!N,hasDefault:N,location:p};N||h.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:S,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,w]of E)if(u===y||u.startsWith(y+"(")||u.startsWith(y+"<")){d.push({kind:w,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 |","|------------|------|----------|---------|--------|"],r=[...e.requiredConfigs,...e.optionalConfigs,...e.secretConfigs],n=new Set;for(let o of r){if(n.has(o.key))continue;n.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: ${n.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(`
|
|
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 cf(e){let t=["flowchart TB"],r=0,n=new Map,o=s=>{let a=`${s}${r++}`;return n.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(`
|
|
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 Ps(e,t){return t?.pretty??!0?JSON.stringify(e,null,2):JSON.stringify(e)}function Jf(e){let t=new Map,r=/^\s*(n\d+)\["[^"]*"\]/gm,n;for(;(n=r.exec(e))!==null;){let o=n[1]??"";t.set(o,o)}return t}function Ms(e,t,r){let n=r?.direction??"TB",o=r?.showRemovedSteps??!1,s=le(e,{direction:n}),a=Jf(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(`
|
|
542
|
+
`),p=[];for(let g of u){let m=/^\s*(n\d+)\["([^"]*)"\]/.exec(g);if(!m)continue;let S=m[1]??"",h=m[2]??"";for(let N of t.steps)if(N.callee&&h.includes(N.callee)){f.set(N.stepId,S);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
|
+
`+p.join(`
|
|
544
|
+
`)+`
|
|
545
|
+
`}import{execSync as Yf}from"child_process";function Ls(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 Os(e,t,r){try{return Yf(`git show ${e}:${t}`,{cwd:r??process.cwd(),encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch(n){let o=n instanceof Error?n.message:String(n);throw new Error(`Failed to resolve git source ${e}:${t}: ${o}`,{cause:n})}}import{Option as Qf}from"effect";function Ws(e){return e.type==="cause"||e.type==="exit"||e.type==="effect"&&(e.callee==="Effect.cause"||e.callee==="Effect.exit")?!0:Qf.getOrElse(v(e),()=>[]).some(Ws)}function Zf(e){let t=e.metadata.stats,r=e.root,o=[{format:"mermaid-services",score:r.dependencies.length*2+(r.requiredServices?.length??0)},{format:"mermaid-concurrency",score:t.parallelCount*3+t.raceCount*3},{format:"mermaid-errors",score:r.errorTypes.length>0?r.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:r.source==="pipe"?5:0},{format:"mermaid-causes",score:r.children.some(Ws)?4:0},{format:"mermaid-timeline",score:r.dependencies.length>2?3:0},{format:"mermaid-testability",score:(r.requiredServices?.length??0)*2}].filter(a=>a.score>0).sort((a,i)=>i.score-a.score).slice(0,2).map(a=>a.format);return[Vn(e)==="railway"?"mermaid-railway":"mermaid",...o]}import{Option as Xf}from"effect";function Ks(e,t,r){for(let n of e){if(n.type==="fiber"){let s=n;(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&&r.add(s.joinPoint),r.add(s.id))}let o=Xf.getOrElse(v(n),()=>[]);o.length>0&&Ks(o,t,r)}}function ep(e,t){return e.isScoped?"safe":e.isDaemon?"daemon":t?"safe":e.operation==="forkAll"?"uncertain":e.operation==="forkIn"?"safe":"potential-leak"}function tp(e){let t=[],r=new Set;Ks(e.root.children,t,r);let n=t.map(c=>{let d=r.size>0,l=ep(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=n.filter(c=>c.risk==="potential-leak"),s=n.filter(c=>c.risk==="daemon"),a=n.filter(c=>c.risk==="safe"),i=n.filter(c=>c.risk==="uncertain");return{forks:n,potentialLeaks:o,daemonForks:s,safeForks:a,summary:{total:n.length,safe:a.length,daemon:s.length,potentialLeaks:o.length,uncertain:i.length}}}function np(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 r of e.potentialLeaks){let n=r.location?` at ${r.location.filePath}:${r.location.line}`:"";t.push(`- \`${r.operation}\` (id: ${r.nodeId})${n}`)}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 r of e.daemonForks){let n=r.location?` at ${r.location.filePath}:${r.location.line}`:"";t.push(`- \`${r.operation}\` (id: ${r.nodeId})${n}`)}}return t.join(`
|
|
546
|
+
`)}import{Option as ve}from"effect";var qs={name:"untagged-yield",description:"Detects yields in Effect.gen that are not assigned to a variable",severity:"warning",check:e=>{let t=[],r=(n,o)=>{if($t(n))for(let a of n.yields)!a.variableName&&a.effect.type!=="unknown"&&t.push({rule:"untagged-yield",message:`Untagged yield detected: ${je(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(n);if(ve.isSome(s))for(let a of s.value)r(a,n.id)};for(let n of e.root.children)r(n);return t}},js={name:"missing-error-handler",description:"Detects Effect operations that can fail but have no error handling",severity:"error",check:e=>{let t=[],r=(n,o=!1)=>{let s=o||pt(n);je(n)&&n.typeSignature&&n.typeSignature.errorType!=="never"&&!s&&(["Effect.try","Effect.tryPromise","Effect.fail","Effect.catchAll"].some(l=>n.callee.includes(l))||n.typeSignature.errorType!=="unknown")&&t.push({rule:"missing-error-handler",message:`Effect "${n.callee}" can fail with error type "${n.typeSignature.errorType}" but has no error handler`,severity:"error",location:n.location,nodeId:n.id,suggestion:"Add .pipe(Effect.catchAll(...)) or handle the error appropriately"});let a=v(n);if(ve.isSome(a))for(let i of a.value)r(i,s)};for(let n of e.root.children)r(n);return t}};function Bs(e){let t=new Set,r=n=>{if(je(n)){let s=n.callee;s&&!/\.|\(/.test(s)&&/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(s)&&t.add(s),n.name&&t.add(n.name)}let o=v(n);if(ve.isSome(o))for(let s of o.value)r(s)};return r(e),t}var _s={name:"dead-code",description:"Detects yields whose results are never used",severity:"warning",check:e=>{let t=[],r=n=>{if($t(n)){let s=n.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 Bs(f.effect))d.add(u)}if(n.returnNode)for(let l of Bs(n.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(n);if(ve.isSome(o))for(let s of o.value)r(s)};for(let n of e.root.children)r(n);return t}},zs={name:"complex-layer",description:"Detects Layer compositions that might be overly complex",severity:"warning",check:e=>{let t=[],r=0,n=0,o=s=>{je(s)&&(s.callee.includes("Layer.")||s.callee.includes(".provide"))&&(r++,(s.callee.includes("provide")||s.callee.includes("provideService"))&&n++);let a=v(s);if(ve.isSome(a))for(let i of a.value)o(i)};for(let s of e.root.children)o(s);return r>10&&t.push({rule:"complex-layer",message:`Program has ${r} 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"}),n>5&&t.push({rule:"complex-layer",message:`Program has ${n} Layer.provide calls, suggesting deep dependency nesting`,severity:"warning",suggestion:"Consider flattening your Layer hierarchy or using Layer.mergeAll instead of nested provides"}),t}},Hs={name:"catchAll-vs-catchTag",description:"Suggests using catchTag instead of catchAll when error type is tagged",severity:"info",check:e=>{let t=[],r=n=>{pt(n)&&n.handlerType==="catchAll"&&t.push({rule:"catchAll-vs-catchTag",message:"Using catchAll - consider catchTag if error type has _tag discriminator",severity:"info",location:n.location,nodeId:n.id,suggestion:'Use Effect.catchTag("ErrorTag", handler) for better type safety'});let o=v(n);if(ve.isSome(o))for(let s of o.value)r(s)};for(let n of e.root.children)r(n);return t}},Us={name:"error-type-too-wide",description:"Warns when error type is unknown or Error instead of tagged errors",severity:"warning",check:e=>{let t=[],r=n=>{if(je(n)){let s=n.typeSignature?.errorType.trim();(s==="unknown"||s==="Error")&&t.push({rule:"error-type-too-wide",message:`Effect "${n.callee}" has wide error type "${s}"`,severity:"warning",location:n.location,nodeId:n.id,suggestion:'Use branded/tagged errors (e.g. { _tag: "NotFound" }) for better handling'})}let o=v(n);if(ve.isSome(o))for(let s of o.value)r(s)};for(let n of e.root.children)r(n);return t}},Vs={name:"unbounded-parallelism",description:"Warns when Effect.all uses unbounded concurrency",severity:"warning",check:e=>{let t=[],r=n=>{on(n)&&n.concurrency==="unbounded"&&t.push({rule:"unbounded-parallelism",message:`Parallel effect uses unbounded concurrency (${n.children.length} branches)`,severity:"warning",location:n.location,nodeId:n.id,suggestion:"Consider { concurrency: N } to limit parallelism"});let o=v(n);if(ve.isSome(o))for(let s of o.value)r(s)};for(let n of e.root.children)r(n);return t}},Gs={name:"redundant-pipe",description:"pipe() with single transformation could be inlined",severity:"info",check:e=>{let t=[],r=n=>{rn(n)&&n.transformations.length===0&&t.push({rule:"redundant-pipe",message:"Pipe has no transformations (only initial effect)",severity:"info",location:n.location,nodeId:n.id,suggestion:"Use the effect directly or add transformations"});let o=v(n);if(ve.isSome(o))for(let s of o.value)r(s)};for(let n of e.root.children)r(n);return t}},Js={name:"ordie-on-recoverable",description:"orDie converts errors to defects; ensure only used for unrecoverable cases",severity:"info",check:e=>{let t=[],r=n=>{pt(n)&&n.handlerType==="orDie"&&t.push({rule:"ordie-on-recoverable",message:"orDie used - typed errors become defects",severity:"info",location:n.location,nodeId:n.id,suggestion:"Reserve orDie for truly unrecoverable cases; handle recoverable errors with catchTag/catchAll"});let o=v(n);if(ve.isSome(o))for(let s of o.value)r(s)};for(let n of e.root.children)r(n);return t}},Ys=[qs,js,_s,zs,Hs,Us,Vs,Gs,Js],rp=(e,t=Ys)=>{let r=[];for(let a of t){let i=a.check(e);r.push(...i)}let n=r.filter(a=>a.severity==="error").length,o=r.filter(a=>a.severity==="warning").length,s=r.filter(a=>a.severity==="info").length;return{issues:r,summary:{errors:n,warnings:o,infos:s,total:r.length}}},op=(e,t)=>{let r=[];if(r.push(`# Lint Report: ${t}`),r.push(""),r.push("## Summary"),r.push(`- **Errors**: ${e.summary.errors}`),r.push(`- **Warnings**: ${e.summary.warnings}`),r.push(`- **Info**: ${e.summary.infos}`),r.push(`- **Total Issues**: ${e.summary.total}`),r.push(""),e.issues.length>0){r.push("## Issues"),r.push("");for(let n of e.issues){let o=n.severity==="error"?"\u274C":n.severity==="warning"?"\u26A0\uFE0F":"\u2139\uFE0F";r.push(`${o} **${n.rule}** (${n.severity})`),r.push(` ${n.message}`),n.location&&r.push(` at ${n.location.filePath}:${n.location.line}`),n.suggestion&&r.push(` \u{1F4A1} ${n.suggestion}`),r.push("")}}else r.push("## \u2705 No Issues Found"),r.push("");return r.join(`
|
|
547
|
+
`)};export{Ys as DEFAULT_LINT_RULES,zo as DEFAULT_THRESHOLDS,Ct as analyze,Bu as analyzeConfig,Pn as analyzeEffectFile,Mn as analyzeEffectSource,Ve as analyzeErrorFlow,vt as analyzeErrorPropagation,tp as analyzeFiberLeaks,Sf as analyzeGenYields,zu as analyzeMatch,fu as analyzeObservability,Gu as analyzePlatformUsage,Gd as analyzeProgramGraph,Va as analyzeProject,eu as analyzeProjectComposition,If as analyzeRequestBatching,vf as analyzeRpcPatterns,lu as analyzeScopeResource,wt as analyzeServiceFlow,Ef as analyzeSqlPatterns,au as analyzeStateFlow,$f as analyzeStm,ff as analyzeTestingPatterns,kl as assessComplexity,Nt as buildDataFlowGraph,Ge as buildLayerDependencyGraph,_t as buildProjectServiceMap,hd as buildTopOffendersReport,Se as calculateComplexity,Qd as calculateGraphComplexity,nd as calculatePathStatistics,Hs as catchAllVsCatchTagRule,mu as checkDICompleteness,yf as checkVersionCompat,zs as complexLayerRule,gd as computeFileDiagramQuality,Qo as computeProgramDiagramQuality,or as constValueToJS,zf as createConstCache,_s as deadCodeRule,Mf as decodePlaygroundPayload,ll as detectDiamondDependencies,Wo as detectLayerCycles,$s as diffPrograms,Pf as encodePlaygroundPayload,Us as errorTypeTooWideRule,Df as exportForPlayground,ki as extractCauseTypeSignature,_e as extractEffectTypeSignature,sf as extractHttpApiStructure,ln as extractLayerTypeSignature,Ti as extractScheduleTypeSignature,Ii as extractSchemaInfo,gt as extractServiceRequirements,wi as extractStreamTypeSignature,Uf as extractString,Hf as extractStringArray,rd as filterPaths,go as findCycles,fo as findMigrationOpportunities,Xa as findMigrationOpportunitiesInProject,dl as findUnsatisfiedServices,Il as formatComplexitySummary,qu as formatConfigReport,hu as formatDICompletenessReport,bu as formatDiagnostics,Cu as formatDiagnosticsJSON,gc as formatErrorSummary,np as formatFiberLeakReport,op as formatLintReport,ec as formatMigrationReport,Lu as formatTestChecklist,Pu as formatTestMatrixAsCode,Du as formatTestMatrixMarkdown,Ei as formatTypeSignature,Vd as generateMultipleShowcase,kt as generatePaths,Ho as generatePathsWithMetadata,as as generateShowcase,wu as generateTestMatrix,qf as getCached,oc as getConsumers,nc as getDataFlowOrder,Jd as getDependencies,Yd as getDependents,bs as getEffectVersion,uc as getErrorProducers,dc as getErrorsAtPoint,rc as getProducers,v as getStaticChildren,Nu as getSummary,ls as getTopologicalOrder,sc as getTransitiveDependencies,Vn as inferBestDiagramType,ur as isSchemaType,oi as isStaticCauseNode,di as isStaticConcurrencyPrimitiveNode,ti as isStaticConditionalNode,je as isStaticEffectNode,pt as isStaticErrorHandlerNode,si as isStaticExitNode,ui as isStaticFiberNode,$t as isStaticGeneratorNode,ri as isStaticLayerNode,ni as isStaticLoopNode,ai as isStaticMatchNode,on as isStaticParallelNode,rn as isStaticPipeNode,Qs as isStaticRaceNode,ei as isStaticResourceNode,Zs as isStaticRetryNode,ii as isStaticScheduleNode,li as isStaticStreamNode,Xs as isStaticTimeoutNode,ci as isStaticTransformNode,sn as isStaticUnknownNode,rp as lintEffectProgram,Nd as loadDiagramQualityHintsFromEslintJson,js as missingErrorHandlerRule,Js as orDieWarningRule,Ls as parseSourceArg,Gs as redundantPipeRule,af as renderApiDocsMarkdown,cf as renderApiDocsMermaid,Xc as renderCausesMermaid,Xd as renderCompositionMermaid,tu as renderCompositionWithServicesMermaid,rl as renderConcurrencyMermaid,ac as renderDataFlowMermaid,xl as renderDataflowMermaid,Gc as renderDecisionsMermaid,$d as renderDependencyMatrix,Dd as renderDependencyMatrixFromServiceMap,Ps as renderDiffJSON,Ds as renderDiffMarkdown,Ms as renderDiffMermaid,is as renderDocumentation,vo as renderEnhancedMermaid,wc as renderEnhancedMermaidEffect,pc as renderErrorFlowMermaid,_c as renderErrorsMermaid,Xo as renderExplanation,Zd as renderGraphMermaid,Od as renderInteractiveHTML,Pd as renderJSON,fl as renderLayerGraphMermaid,pl as renderLayersMermaid,xc as renderMermaid,qd as renderMultiProgramDocs,kd as renderMultipleExplanations,Md as renderMultipleJSON,Rd as renderMultipleSummaries,lf as renderOpenApiPaths,Cc as renderPathsMermaid,Wc as renderRailwayMermaid,kc as renderRetryGanttMermaid,yl as renderRetryMermaid,Tc as renderSequenceMermaid,Ic as renderServiceGraphMermaid,Bc as renderServicesMermaid,qc as renderServicesMermaidFromMap,le as renderStaticMermaid,Ad as renderSummary,Sl as renderTestabilityMermaid,al as renderTimelineMermaid,ht as resetIdCounter,rr as resolveConst,Os as resolveGitSource,Ke as resolveNode,Ga as runCoverageAudit,Ft as schemaToJsonSchema,Zf as selectFormats,jf as setCached,Gt as summarizePathSteps,xi as trackTypeTransformation,Vs as unboundedParallelismRule,qs as untaggedYieldRule,ic as validateDataFlow,Su as validateStrict,fc as validateWorkflowErrors};
|
|
548
|
+
//# sourceMappingURL=index.js.map
|