Library API
Effect v4 is the only supported Effect release. The small root interface covers
the canonical analysis/fidelity/trace workflow; expert capabilities live under
effect-analyzer/analysis, effect-analyzer/diagram,
effect-analyzer/rules, and effect-analyzer/migration.
import { analyze, renderMermaid, calculateComplexity } from "effect-analyzer/diagram"Package Entry Points
Section titled “Package Entry Points”| Import | Use it for |
|---|---|
effect-analyzer |
Analysis sessions, fidelity checks, trace adapters, runtime overlays |
effect-analyzer/analysis |
Full static analysis, project audits, IR traversal, paths, and data flow |
effect-analyzer/diagram |
Mermaid, HTML, JSON, summaries, and diagram quality |
effect-analyzer/rules |
Source linting, strict diagnostics, and rule metadata |
effect-analyzer/migration |
Migration findings and semantic diffs |
The v4 release removes expert APIs from the root import. Move each old root import to the matching entry point above.
Analysis
Section titled “Analysis”analysis
Section titled “analysis”The root package exports a configured Node analysis session. It initializes ts-morph before you analyze a file, source string, or project.
import { analysis } from "effect-analyzer"import { Effect } from "effect"
const one = await Effect.runPromise(analysis.file("./src/program.ts").single)const fromSource = await Effect.runPromise(analysis.source(source).all)const project = await Effect.runPromise(analysis.project("./src"))const audit = await Effect.runPromise(analysis.audit("./src"))
analysis.clearCaches()Call createAnalysisSession() when tests or tools need separate session objects. The sessions share the analyzer’s project cache until you call clearCaches().
analyze(path)
Section titled “analyze(path)”The primary entry point. Returns a fluent API for extracting programs from a file.
import { analyze } from "effect-analyzer/analysis"import { Effect } from "effect"
// Get a single program (throws if file has zero or multiple)const ir = await Effect.runPromise(analyze("./src/program.ts").single)
// Get all programs in a fileconst irs = await Effect.runPromise(analyze("./src/program.ts").all)
// Get a program by nameconst named = await Effect.runPromise(analyze("./src/program.ts").named("transfer"))analyzeEffectFile(filePath, options?)
Section titled “analyzeEffectFile(filePath, options?)”Lower-level file analysis. Returns StaticEffectIR[] - one IR per detected program.
analyzeEffectSource(source, filePath?, options?)
Section titled “analyzeEffectSource(source, filePath?, options?)”Analyze a TypeScript source string directly, without reading from disk:
import { analyzeEffectSource } from "effect-analyzer/analysis"
const irs = analyzeEffectSource(` import { Effect } from 'effect'; export const hello = Effect.succeed('world');`)analyze.source(code)
Section titled “analyze.source(code)”Analyze a TypeScript source string using the fluent API:
import { analyze } from "effect-analyzer/analysis"import { Effect } from "effect"
const ir = await Effect.runPromise(analyze.source(` import { Effect } from 'effect'; export const hello = Effect.succeed('world');`).single)The fluent API methods available on analyze(path) and analyze.source(code):
| Method | Description |
|---|---|
.single |
Returns exactly one program (fails if zero or multiple) |
.singleOption |
Returns Option<IR> - None if zero programs, fails if multiple |
.all |
Returns all programs as an array |
.named(name) |
Returns the program matching the given name |
.first |
Returns the first program (fails if zero programs) |
.firstOption |
Returns Option<IR> - the first program or None |
analyzeProject(dirPath, options?)
Section titled “analyzeProject(dirPath, options?)”Analyze all TypeScript files in a directory. Returns a ProjectAnalysisResult with per-file outcomes.
runCoverageAudit(dirPath, options?)
Section titled “runCoverageAudit(dirPath, options?)”Run a coverage audit across a directory. Returns a CoverageAuditResult with
named effectAdoption, analysisSuccess, and sourceResolution assessment
dimensions. Each dimension contains { numerator, denominator, rate }.
analysis.corpus(dirPath, options?)
Section titled “analysis.corpus(dirPath, options?)”Discover and analyze a project once. The returned Project corpus records every file and its Effect IR programs, zero-program result, analysis failure, and optional timing. Project-wide views use this shared evidence model.
Pass the corpus to analysis.projectFromCorpus(corpus) and
analysis.auditFromCorpus(corpus) to derive both views without scanning source
files again.
evaluateAuditPolicy(facts, policy)
Section titled “evaluateAuditPolicy(facts, policy)”Evaluate native CI expectations against an Audit assessment. Returns a pass or fail decision with typed violations and does not mutate the measurements.
Deep IR traversal
Section titled “Deep IR traversal”The analysis entry point exports one traversal vocabulary for the full IR tree. Traversal functions accept ir.root.children; the index accepts the full IR.
| Function | Result |
|---|---|
childrenOf(node) |
Direct children for any supported IR node |
visitIR(roots, visitor) |
Depth-first visit with parent and ancestor data |
flattenIR(roots) |
All nodes in depth-first order |
indexIR(ir) |
IDs, parents, runtime span paths, and span-path lookups |
runtimeSpanNames(node) |
Literal span names attached to one node |
The root package exports findStaticNodesForSpanPath(ir, path) for runtime-path lookups.
import { indexIR } from "effect-analyzer/analysis"
const index = indexIR(ir)const parent = index.parentById.get(nodeId)const spanPath = index.spanPathById.get(nodeId)Diagram Fidelity and Runtime Traces
Section titled “Diagram Fidelity and Runtime Traces”computeDiagramFidelity(ir) reports whether the IR can identify each diagram node without ambiguity. It reports unknown nodes, opaque nodes, computed span names, and duplicate span paths.
import { computeDiagramFidelity, formatDiagramFidelity,} from "effect-analyzer"
const report = computeDiagramFidelity(ir)console.log(formatDiagramFidelity(report))Use traceFromEffectSpans() for Effect v4 spans or traceFromOpenTelemetry() for exported OpenTelemetry spans. renderMermaidWithRuntimeTrace() colors matched nodes by runtime status and returns unmatched or ambiguous span IDs.
import { renderMermaidWithRuntimeTrace, traceFromOpenTelemetry,} from "effect-analyzer"
const trace = traceFromOpenTelemetry(readableSpans)const result = renderMermaidWithRuntimeTrace(ir, trace)
console.log(result.mermaid)console.log(result.unmatchedSpanIds)Read Diagram Fidelity for span naming rules and CI usage.
Rendering
Section titled “Rendering”Mermaid Diagrams
Section titled “Mermaid Diagrams”| Function | Description |
|---|---|
renderMermaid(ir, options?) |
Standard flowchart |
renderStaticMermaid(ir, options?) |
Static flowchart (no animation) |
renderRailwayMermaid(ir, options?) |
Railway diagram with error branches |
renderPathsMermaid(ir, options?) |
All execution paths as separate flows |
renderEnhancedMermaid(ir, options?) |
Rich annotations per node |
renderServiceGraphMermaid(ir) |
Service dependency graph |
renderSequenceMermaid(ir) |
Sequence diagram |
renderRetryGanttMermaid(ir) |
Retry timeline as Gantt chart |
renderGraphMermaid(graph) |
Cross-program composition graph |
renderCompositionMermaid(graph) |
Composition with call edges |
renderCompositionWithServicesMermaid(graph) |
Composition including service nodes |
All Mermaid renderers accept a MermaidOptions object:
import { renderMermaid } from "effect-analyzer/diagram"import { Effect } from "effect"
const diagram = await Effect.runPromise(renderMermaid(ir, { direction: "LR", // TB | LR | BT | RL styleGuide: true, // Apply readability heuristics}))Structured Output
Section titled “Structured Output”| Function | Description |
|---|---|
renderJSON(ir, options?) |
Full IR as JSON |
renderMultipleJSON(irs) |
Multiple IRs as JSON array |
renderExplanation(ir) |
Plain-English narrative |
renderMultipleExplanations(irs) |
Explanations for multiple programs |
renderSummary(ir) |
One-line summary |
renderMultipleSummaries(irs) |
Summaries for multiple programs |
renderDependencyMatrix(irs) |
Program-by-service dependency table |
renderDocumentation(ir, options?) |
Markdown documentation |
renderMultiProgramDocs(irs, options?) |
Documentation for multiple programs |
generateShowcase(ir, options?) |
Detailed step-by-step showcase |
Interactive HTML
Section titled “Interactive HTML”import { renderInteractiveHTML } from "effect-analyzer/diagram"
const html = renderInteractiveHTML(ir, { title: "Transfer Analysis", theme: "midnight", // midnight | ocean | ember | forest | daylight | paper})See Interactive HTML for full details.
API Documentation
Section titled “API Documentation”| Function | Description |
|---|---|
renderApiDocsMarkdown(structure) |
HttpApi structure to markdown |
renderApiDocsMermaid(structure) |
HttpApi structure to Mermaid |
renderOpenApiPaths(structure) |
Minimal OpenAPI paths |
extractHttpApiStructure(ir) |
Extract HttpApi info from IR |
Complexity
Section titled “Complexity”calculateComplexity(ir)
Section titled “calculateComplexity(ir)”Returns ComplexityMetrics with 6 metrics:
import { calculateComplexity } from "effect-analyzer/analysis"
const metrics = calculateComplexity(ir)// { cyclomaticComplexity, cognitiveComplexity, pathCount, maxDepth, maxParallelBreadth, decisionPoints }assessComplexity(metrics, thresholds?)
Section titled “assessComplexity(metrics, thresholds?)”Evaluate metrics against thresholds. Returns a ComplexityAssessment with severity and warnings.
formatComplexitySummary(metrics)
Section titled “formatComplexitySummary(metrics)”Format metrics as a human-readable one-liner.
DEFAULT_THRESHOLDS
Section titled “DEFAULT_THRESHOLDS”The default complexity thresholds object.
Path Generation
Section titled “Path Generation”generatePaths(ir, options?)
Section titled “generatePaths(ir, options?)”Enumerate execution paths. Returns EffectPath[].
import { generatePaths } from "effect-analyzer/analysis"
const paths = generatePaths(ir, { maxPaths: 100, expandLoops: true })generatePathsWithMetadata(ir, options?)
Section titled “generatePathsWithMetadata(ir, options?)”Same as generatePaths but returns a PathGenerationResult with a limitHit flag.
calculatePathStatistics(paths)
Section titled “calculatePathStatistics(paths)”Aggregate statistics across paths.
filterPaths(paths, criteria)
Section titled “filterPaths(paths, criteria)”Filter paths by step names, error conditions, or loop presence.
Test Matrix
Section titled “Test Matrix”generateTestMatrix(paths, options?)
Section titled “generateTestMatrix(paths, options?)”Generate test cases from paths. Returns a TestMatrix.
import { generateTestMatrix } from "effect-analyzer/analysis"
const matrix = generateTestMatrix(paths, { testNamePrefix: "should" })formatTestMatrixMarkdown(matrix)
Section titled “formatTestMatrixMarkdown(matrix)”Render the test matrix as a markdown table.
formatTestMatrixAsCode(matrix, options?)
Section titled “formatTestMatrixAsCode(matrix, options?)”Generate test code skeletons for vitest, jest, or mocha.
formatTestChecklist(matrix)
Section titled “formatTestChecklist(matrix)”Render the test matrix as a markdown checklist.
Data Flow
Section titled “Data Flow”buildDataFlowGraph(ir)
Section titled “buildDataFlowGraph(ir)”Build a data flow graph tracking value producers and consumers.
import { buildDataFlowGraph, getProducers, getConsumers } from "effect-analyzer/analysis"
const graph = buildDataFlowGraph(ir)const producers = getProducers(graph, "AccountService")const consumers = getConsumers(graph, "balance")getDataFlowOrder(graph)
Section titled “getDataFlowOrder(graph)”Topological order of data flow nodes.
getTransitiveDependencies(graph, nodeId)
Section titled “getTransitiveDependencies(graph, nodeId)”All transitive dependencies of a node.
findCycles(graph)
Section titled “findCycles(graph)”Detect circular dependencies in the data flow.
validateDataFlow(graph)
Section titled “validateDataFlow(graph)”Check for undefined reads and duplicate writes.
renderDataFlowMermaid(graph)
Section titled “renderDataFlowMermaid(graph)”Render the data flow graph as a Mermaid diagram.
Error Flow
Section titled “Error Flow”analyzeErrorFlow(ir)
Section titled “analyzeErrorFlow(ir)”Extract all error types and map them to steps.
analyzeErrorPropagation(ir)
Section titled “analyzeErrorPropagation(ir)”Track how errors propagate through the program and how handlers narrow them.
getErrorsAtPoint(propagation, nodeId)
Section titled “getErrorsAtPoint(propagation, nodeId)”Look up the error state at a specific node.
getErrorProducers(flow, errorType)
Section titled “getErrorProducers(flow, errorType)”Find all steps that can produce a given error type.
validateWorkflowErrors(ir)
Section titled “validateWorkflowErrors(ir)”Check for undeclared and unused error types.
renderErrorFlowMermaid(flow)
Section titled “renderErrorFlowMermaid(flow)”Render the error flow as a Mermaid diagram.
formatErrorSummary(flow)
Section titled “formatErrorSummary(flow)”Human-readable error summary.
Layer Analysis
Section titled “Layer Analysis”buildLayerDependencyGraph(irs)
Section titled “buildLayerDependencyGraph(irs)”Build a dependency graph of all layers in a set of IRs.
renderLayerGraphMermaid(graph)
Section titled “renderLayerGraphMermaid(graph)”Render the layer graph as Mermaid.
detectLayerCycles(graph)
Section titled “detectLayerCycles(graph)”Find circular layer dependencies.
detectDiamondDependencies(graph)
Section titled “detectDiamondDependencies(graph)”Find diamond dependencies in the layer graph.
findUnsatisfiedServices(graph)
Section titled “findUnsatisfiedServices(graph)”Find services that are required but have no layer provider.
Service Flow
Section titled “Service Flow”analyzeServiceFlow(ir)
Section titled “analyzeServiceFlow(ir)”Track service provisions, unsatisfied services, and lifecycle.
buildProjectServiceMap(irs)
Section titled “buildProjectServiceMap(irs)”Build a project-wide map of all services, their providers, and consumers.
diffPrograms(before, after, options?)
Section titled “diffPrograms(before, after, options?)”Compare two program IRs. Returns a structured diff.
renderDiffMarkdown(diff)
Section titled “renderDiffMarkdown(diff)”Render the diff as markdown.
renderDiffJSON(diff)
Section titled “renderDiffJSON(diff)”Render the diff as JSON.
renderDiffMermaid(diff)
Section titled “renderDiffMermaid(diff)”Render the diff as a Mermaid diagram with change highlights.
parseSourceArg(arg)
Section titled “parseSourceArg(arg)”Parse a ref:path string into its components.
resolveGitSource(arg)
Section titled “resolveGitSource(arg)”Resolve a git ref to source code.
Composition
Section titled “Composition”analyzeProgramGraph(irs, options?)
Section titled “analyzeProgramGraph(irs, options?)”Build a call graph across multiple programs.
analyzeProjectComposition(dirPath, options?)
Section titled “analyzeProjectComposition(dirPath, options?)”Analyze composition across an entire project.
getTopologicalOrder(graph)
Section titled “getTopologicalOrder(graph)”Topological sort of the program call graph.
getDependencies(graph, programName)
Section titled “getDependencies(graph, programName)”Get direct dependencies of a program.
getDependents(graph, programName)
Section titled “getDependents(graph, programName)”Get direct dependents of a program.
calculateGraphComplexity(graph)
Section titled “calculateGraphComplexity(graph)”Complexity metrics for the composition graph.
Diagnostics
Section titled “Diagnostics”validateStrict(ir, options?)
Section titled “validateStrict(ir, options?)”Validate an IR against strict diagnostic rules.
import { validateStrict } from "effect-analyzer/rules"
const result = validateStrict(ir, { warningsAsErrors: true })formatDiagnostics(result)
Section titled “formatDiagnostics(result)”Human-readable diagnostic output.
formatDiagnosticsJSON(result)
Section titled “formatDiagnosticsJSON(result)”JSON diagnostic output.
getSummary(result)
Section titled “getSummary(result)”Error and warning counts.
Const Inliner
Section titled “Const Inliner”createConstCache(sourceFile)
Section titled “createConstCache(sourceFile)”Build a cache of const declarations from a ts-morph source file.
resolveConst(name, cache)
Section titled “resolveConst(name, cache)”Look up a const value by name.
constValueToJS(value)
Section titled “constValueToJS(value)”Convert a ConstValue to a plain JavaScript value.
extractStringArray(node, cache)
Section titled “extractStringArray(node, cache)”Extract a string array from a const or literal.
extractString(node, cache)
Section titled “extractString(node, cache)”Extract a single string value.
Auto-Detection
Section titled “Auto-Detection”inferBestDiagramType(ir)
Section titled “inferBestDiagramType(ir)”Choose between 'mermaid' and 'railway' based on IR structure.
selectFormats(ir)
Section titled “selectFormats(ir)”Select the full set of auto-mode formats for a program.
Linting
Section titled “Linting”lintEffectProgram(ir, rules?)
Section titled “lintEffectProgram(ir, rules?)”Run lint rules against an Effect program IR.
import { lintEffectProgram, DEFAULT_LINT_RULES } from "effect-analyzer/rules"
const result = lintEffectProgram(ir, DEFAULT_LINT_RULES)formatLintReport(result)
Section titled “formatLintReport(result)”Format lint issues as a human-readable report.
Built-in Rules
Section titled “Built-in Rules”| Rule | Description |
|---|---|
errorTypeTooWideRule |
Error type is unknown or Error instead of a tagged union |
unboundedParallelismRule |
Effect.all without concurrency option |
redundantPipeRule |
Single-step pipe that could be simplified |
orDieWarningRule |
Use of Effect.orDie which discards error info |
untaggedYieldRule |
Yield without a descriptive variable name |
missingErrorHandlerRule |
Errors produced but no handler present |
deadCodeRule |
Unreachable code after terminal effects |
complexLayerRule |
Layer with too many dependencies |
catchVsCatchTagRule |
catch used where catchTag would be more precise |
Type Extraction
Section titled “Type Extraction”extractEffectTypeSignature(node)
Section titled “extractEffectTypeSignature(node)”Extract Effect<A, E, R> type parameters from a ts-morph node.
extractStreamTypeSignature(node)
Section titled “extractStreamTypeSignature(node)”Extract Stream<A, E, R> type parameters.
extractLayerTypeSignature(node)
Section titled “extractLayerTypeSignature(node)”Extract Layer<A, E, R> type parameters.
extractServiceRequirements(ir)
Section titled “extractServiceRequirements(ir)”Get all service requirements for a program.
formatTypeSignature(sig)
Section titled “formatTypeSignature(sig)”Format a type signature as a readable string.
Diagram Quality
Section titled “Diagram Quality”computeProgramDiagramQuality(ir)
Section titled “computeProgramDiagramQuality(ir)”Compute readability metrics for a program’s diagram.
computeFileDiagramQuality(irs)
Section titled “computeFileDiagramQuality(irs)”Compute quality metrics for all programs in a file.
buildTopOffendersReport(qualities)
Section titled “buildTopOffendersReport(qualities)”Build a report of the worst-quality diagrams.
Additional Analyzers
Section titled “Additional Analyzers”| Function | Description |
|---|---|
analyzeStateFlow(ir) |
Track Ref mutations and race conditions |
analyzeScopeResource(ir) |
Analyze acquireRelease and scope boundaries |
analyzeObservability(ir) |
Find spans, log points, and metrics |
analyzeFiberLeaks(ir) |
Detect potentially leaked fibers |
analyzeGenYields(ir) |
Detailed analysis of yield* bindings in generators |
analyzeMatch(ir) |
Analyze Match pattern sites and arms |
analyzePlatformUsage(ir) |
Detect Effect v4 platform-module usage |
analyzeSqlPatterns(ir) |
Detect @effect/sql patterns |
analyzeRpcPatterns(ir) |
Detect @effect/rpc patterns |
analyzeRequestBatching(ir) |
Detect request batching patterns |
analyzeStm(ir) |
Detect STM (software transactional memory) usage |
analyzeConfig(ir) |
Analyze Config usage |
analyzeTestingPatterns(ir) |
Detect testing patterns (TestContext, TestClock) |
checkDICompleteness(irs) |
Check if all services have layer providers |
formatDICompletenessReport(result) |
Format DI completeness check as a report |
findMigrationOpportunities(path) |
Find patterns migratable to Effect |
exportForPlayground(ir) |
Export IR for the Effect playground |