diff --git "a/.opencode/node_modules/effect/src/Graph.ts" "b/.opencode/node_modules/effect/src/Graph.ts" --- "a/.opencode/node_modules/effect/src/Graph.ts" +++ "b/.opencode/node_modules/effect/src/Graph.ts" @@ -1,4 +1,11 @@ /** + * Models relationships between indexed nodes and edges. + * + * This module provides immutable and scoped-mutable graph data structures. A + * graph can be directed or undirected, and it can store user-defined data on + * both nodes and edges. The module includes traversal, analysis, path-finding, + * transformation, and diagram export utilities. + * * @since 4.0.0 */ @@ -19,24 +26,65 @@ const TypeId = "~effect/collections/Graph" /** * Node index for node identification using plain numbers. * - * @since 4.0.0 + * **When to use** + * + * Use when storing or passing the stable identifier of a graph node between + * `Graph` operations. + * + * **Details** + * + * `addNode` allocates node identifiers from the graph's next node index. + * + * **Gotchas** + * + * A `NodeIndex` is an identifier, not an array offset. Removed node identifiers + * are not reused. + * + * @see {@link EdgeIndex} for edge identifiers instead of node identifiers + * @see {@link addNode} for creating node identifiers + * * @category models + * @since 3.18.0 */ export type NodeIndex = number /** * Edge index for edge identification using plain numbers. * - * @since 4.0.0 + * **When to use** + * + * Use when you need to keep the identifier for a graph edge so you can later + * read, update, remove, or compare that edge. + * + * **Gotchas** + * + * An `EdgeIndex` is an identifier, not an array offset. Removed edge + * identifiers are not reused. + * + * @see {@link NodeIndex} for node identifiers instead of edge identifiers + * @see {@link Edge} for the edge value addressed by this identifier + * @see {@link addEdge} for creating edge identifiers + * @see {@link getEdge} for reading edges by identifier + * * @category models + * @since 3.18.0 */ export type EdgeIndex = number /** - * Edge data containing source, target, and user data. + * Represents edge data containing source, target, and user data. + * + * **When to use** + * + * Use as the graph edge value that carries source node, target node, and stored + * edge data together. + * + * @see {@link getEdge} for reading a single edge by identifier + * @see {@link addEdge} for adding edges to a graph + * @see {@link edges} for iterating graph edges * - * @since 4.0.0 * @category models + * @since 3.18.0 */ export class Edge extends Data.Class<{ readonly source: NodeIndex @@ -47,16 +95,29 @@ export class Edge extends Data.Class<{ /** * Graph type for distinguishing directed and undirected graphs. * - * @since 4.0.0 + * **When to use** + * + * Use when writing graph-polymorphic types or helpers that need to preserve + * whether a graph is directed or undirected. + * + * @see {@link Graph} for immutable graphs parameterized by kind + * @see {@link MutableGraph} for mutable graphs parameterized by kind + * * @category models + * @since 3.18.0 */ export type Kind = "directed" | "undirected" /** - * Graph prototype interface. + * Common structural interface shared by immutable and mutable graphs. + * + * **Details** + * + * Contains the node and edge maps, adjacency indexes, allocation counters, and + * shared protocols used by both `Graph` and `MutableGraph`. * - * @since 4.0.0 * @category models + * @since 3.18.0 */ export interface Proto extends Iterable, Equal.Equal, Pipeable, Inspectable { readonly [TypeId]: typeof TypeId @@ -72,8 +133,17 @@ export interface Proto extends Iterable, /** * Immutable graph interface. * - * @since 4.0.0 + * **When to use** + * + * Use as the immutable graph model for code that queries, traverses, + * transforms, or analyzes graph structure without mutating it. + * + * @see {@link MutableGraph} for the mutable counterpart used inside mutation scopes + * @see {@link DirectedGraph} for a `Graph` fixed to directed edges + * @see {@link UndirectedGraph} for a `Graph` fixed to undirected edges + * * @category models + * @since 3.18.0 */ export interface Graph extends Proto { readonly type: T @@ -83,8 +153,18 @@ export interface Graph extends Proto< /** * Mutable graph interface. * - * @since 4.0.0 + * **When to use** + * + * Use when adding, removing, or updating nodes and edges inside a graph + * mutation scope. + * + * @see {@link Graph} for the immutable graph interface + * @see {@link mutate} for scoped mutation of an immutable graph + * @see {@link beginMutation} for opening a mutable graph manually + * @see {@link endMutation} for returning to an immutable graph + * * @category models + * @since 3.18.0 */ export interface MutableGraph extends Proto { readonly type: T @@ -92,34 +172,80 @@ export interface MutableGraph extends } /** - * Directed graph type alias. + * Immutable graph type for source-to-target relationships. + * + * **When to use** + * + * Use as the immutable graph type when edge direction is part of the model and + * traversal or neighbor queries should follow source-to-target edges. + * + * **Details** + * + * `DirectedGraph` is a `Graph` with node data of type + * `N` and edge data of type `E`. + * + * @see {@link directed} for constructing directed graphs + * @see {@link Graph} for the generic immutable graph type + * @see {@link UndirectedGraph} for graphs whose edges connect both endpoints + * @see {@link MutableDirectedGraph} for the mutable directed graph type * - * @since 4.0.0 * @category models + * @since 3.18.0 */ export type DirectedGraph = Graph /** - * Undirected graph type alias. + * Immutable graph type for relationships without source-to-target direction. + * + * **When to use** + * + * Use when modeling relationships where each edge connects both endpoints + * without a source-to-target direction. + * + * **Details** + * + * `UndirectedGraph` is a `Graph`. + * + * @see {@link undirected} for constructing undirected graphs + * @see {@link DirectedGraph} for graphs whose edges have source-to-target direction + * @see {@link MutableUndirectedGraph} for the mutable undirected graph type * - * @since 4.0.0 * @category models + * @since 3.18.0 */ export type UndirectedGraph = Graph /** * Mutable directed graph type alias. * - * @since 4.0.0 + * **When to use** + * + * Use when annotating a temporary graph value that can be changed in place and + * whose edges have source-to-target direction. + * + * @see {@link MutableGraph} for the generic mutable graph type + * @see {@link DirectedGraph} for the immutable directed graph type + * @see {@link MutableUndirectedGraph} for mutable graphs without edge direction + * * @category models + * @since 3.18.0 */ export type MutableDirectedGraph = MutableGraph /** * Mutable undirected graph type alias. * - * @since 4.0.0 + * **When to use** + * + * Use when annotating a temporary graph value that can be changed in place and + * whose edges connect both endpoints without direction. + * + * @see {@link MutableDirectedGraph} for mutable graphs with directed edges + * @see {@link UndirectedGraph} for the immutable undirected graph type + * @see {@link MutableGraph} for the generic mutable graph type + * * @category models + * @since 3.18.0 */ export type MutableUndirectedGraph = MutableGraph @@ -205,8 +331,17 @@ const ProtoGraph = { // TODO: Do we need safe variants for these? /** - * @since 4.0.0 + * Error thrown by graph operations when the requested graph structure is + * invalid, such as referencing a missing node or using unsupported edge + * weights. + * + * **When to use** + * + * Use when handling failures thrown by graph operations that reject invalid + * graph structure or unsupported algorithm inputs. + * * @category errors + * @since 3.18.0 */ export class GraphError extends Data.TaggedError("GraphError")<{ readonly message: string @@ -220,15 +355,28 @@ const missingNode = (node: number) => new GraphError({ message: `Node ${node} do // ============================================================================= /** + * Returns `true` if a value has the graph runtime type identifier, narrowing + * it to a `Graph`. + * + * **When to use** + * + * Use to narrow an unknown value before treating it as a graph value. + * + * **Gotchas** + * + * This guard checks the shared graph runtime type identifier and does not + * distinguish immutable graphs from mutable graphs. + * + * @category guards * @since 4.0.0 - * @category Guards */ export const isGraph = (u: unknown): u is Graph => hasProperty(u, TypeId) /** * Creates a directed graph, optionally with initial mutations. * - * @example + * **Example** (Creating a directed graph) + * * ```ts * import { Graph } from "effect" * @@ -242,8 +390,8 @@ export const isGraph = (u: unknown): u is Graph => hasProperty * }) * ``` * - * @since 4.0.0 * @category constructors + * @since 3.18.0 */ export const directed = (mutate?: (mutable: MutableDirectedGraph) => void): DirectedGraph => { const graph: Mutable> = Object.create(ProtoGraph) @@ -269,7 +417,8 @@ export const directed = (mutate?: (mutable: MutableDirectedGraph) => /** * Creates an undirected graph, optionally with initial mutations. * - * @example + * **Example** (Creating an undirected graph) + * * ```ts * import { Graph } from "effect" * @@ -283,8 +432,8 @@ export const directed = (mutate?: (mutable: MutableDirectedGraph) => * }) * ``` * - * @since 4.0.0 * @category constructors + * @since 3.18.0 */ export const undirected = (mutate?: (mutable: MutableUndirectedGraph) => void): UndirectedGraph => { const graph: Mutable> = Object.create(ProtoGraph) @@ -314,7 +463,8 @@ export const undirected = (mutate?: (mutable: MutableUndirectedGraph /** * Creates a mutable scope for safe graph mutations by copying the data structure. * - * @example + * **Example** (Beginning a mutation scope) + * * ```ts * import { Graph } from "effect" * @@ -323,8 +473,8 @@ export const undirected = (mutate?: (mutable: MutableUndirectedGraph * // Now mutable can be safely modified without affecting original graph * ``` * - * @since 4.0.0 * @category mutations + * @since 3.18.0 */ export const beginMutation = ( graph: Graph @@ -358,7 +508,8 @@ export const beginMutation = ( /** * Converts a mutable graph back to an immutable graph, ending the mutation scope. * - * @example + * **Example** (Ending a mutation scope) + * * ```ts * import { Graph } from "effect" * @@ -368,8 +519,8 @@ export const beginMutation = ( * const newGraph = Graph.endMutation(mutable) * ``` * - * @since 4.0.0 * @category mutations + * @since 3.18.0 */ export const endMutation = ( mutable: MutableGraph @@ -391,55 +542,70 @@ export const endMutation = ( /** * Performs scoped mutations on a graph, automatically managing the mutation lifecycle. * - * @example + * **Example** (Applying scoped mutations) + * * ```ts * import { Graph } from "effect" * * const graph = Graph.directed() * const newGraph = Graph.mutate(graph, (mutable) => { - * // Safe mutations go here - * // mutable gets automatically converted back to immutable + * const nodeA = Graph.addNode(mutable, "A") + * const nodeB = Graph.addNode(mutable, "B") + * Graph.addEdge(mutable, nodeA, nodeB, 1) * }) + * + * console.log(Graph.nodeCount(newGraph)) // 2 + * console.log(Graph.edgeCount(newGraph)) // 1 * ``` * - * @since 4.0.0 * @category mutations + * @since 3.18.0 */ export const mutate: { /** * Performs scoped mutations on a graph, automatically managing the mutation lifecycle. * - * @example + * **Example** (Applying scoped mutations) + * * ```ts * import { Graph } from "effect" * * const graph = Graph.directed() * const newGraph = Graph.mutate(graph, (mutable) => { - * // Safe mutations go here - * // mutable gets automatically converted back to immutable + * const nodeA = Graph.addNode(mutable, "A") + * const nodeB = Graph.addNode(mutable, "B") + * Graph.addEdge(mutable, nodeA, nodeB, 1) * }) + * + * console.log(Graph.nodeCount(newGraph)) // 2 + * console.log(Graph.edgeCount(newGraph)) // 1 * ``` * - * @since 4.0.0 * @category mutations + * @since 3.18.0 */ (f: (mutable: MutableGraph) => void): (graph: Graph) => Graph /** * Performs scoped mutations on a graph, automatically managing the mutation lifecycle. * - * @example + * **Example** (Applying scoped mutations) + * * ```ts * import { Graph } from "effect" * * const graph = Graph.directed() * const newGraph = Graph.mutate(graph, (mutable) => { - * // Safe mutations go here - * // mutable gets automatically converted back to immutable + * const nodeA = Graph.addNode(mutable, "A") + * const nodeB = Graph.addNode(mutable, "B") + * Graph.addEdge(mutable, nodeA, nodeB, 1) * }) + * + * console.log(Graph.nodeCount(newGraph)) // 2 + * console.log(Graph.edgeCount(newGraph)) // 1 * ``` * - * @since 4.0.0 * @category mutations + * @since 3.18.0 */ (graph: Graph, f: (mutable: MutableGraph) => void): Graph } = dual(2, ( @@ -458,7 +624,23 @@ export const mutate: { /** * Adds a new node to a mutable graph and returns its index. * - * @example + * **When to use** + * + * Use to allocate a new node in a mutable graph before storing edges or + * querying it by index. + * + * **Details** + * + * The returned index is allocated from the graph's next node index. The mutable + * graph stores the node data and initializes empty incoming and outgoing edge + * indexes for the new node. + * + * **Gotchas** + * + * `NodeIndex` values are identifiers and are not reused after removals. + * + * **Example** (Adding nodes) + * * ```ts * import { Graph } from "effect" * @@ -470,8 +652,12 @@ export const mutate: { * }) * ``` * - * @since 4.0.0 + * @see {@link mutate} for obtaining a mutable graph from an immutable graph + * @see {@link addEdge} for connecting existing nodes + * @see {@link removeNode} for removing nodes from a mutable graph + * * @category mutations + * @since 3.18.0 */ export const addNode = ( mutable: MutableGraph, @@ -493,12 +679,12 @@ export const addNode = ( } /** - * Gets the data associated with a node index, if it exists. + * Gets the data associated with a node index safely, if it exists. + * + * **Example** (Getting node data) * - * @example * ```ts - * import { Graph } from "effect" - * import * as Option from "effect/Option" + * import { Graph, Option } from "effect" * * const graph = Graph.mutate(Graph.directed(), (mutable) => { * Graph.addNode(mutable, "Node A") @@ -512,17 +698,17 @@ export const addNode = ( * } * ``` * - * @since 4.0.0 * @category getters + * @since 3.18.0 */ export const getNode: { /** - * Gets the data associated with a node index, if it exists. + * Gets the data associated with a node index safely, if it exists. + * + * **Example** (Getting node data) * - * @example * ```ts - * import { Graph } from "effect" - * import * as Option from "effect/Option" + * import { Graph, Option } from "effect" * * const graph = Graph.mutate(Graph.directed(), (mutable) => { * Graph.addNode(mutable, "Node A") @@ -536,17 +722,17 @@ export const getNode: { * } * ``` * - * @since 4.0.0 * @category getters + * @since 3.18.0 */ (nodeIndex: NodeIndex): (graph: Graph | MutableGraph) => Option.Option /** - * Gets the data associated with a node index, if it exists. + * Gets the data associated with a node index safely, if it exists. + * + * **Example** (Getting node data) * - * @example * ```ts - * import { Graph } from "effect" - * import * as Option from "effect/Option" + * import { Graph, Option } from "effect" * * const graph = Graph.mutate(Graph.directed(), (mutable) => { * Graph.addNode(mutable, "Node A") @@ -560,8 +746,8 @@ export const getNode: { * } * ``` * - * @since 4.0.0 * @category getters + * @since 3.18.0 */ (graph: Graph | MutableGraph, nodeIndex: NodeIndex): Option.Option } = dual(2, ( @@ -570,9 +756,10 @@ export const getNode: { ): Option.Option => graph.nodes.has(nodeIndex) ? Option.some(graph.nodes.get(nodeIndex)!) : Option.none()) /** - * Checks if a node with the given index exists in the graph. + * Checks whether a node with the given index exists in the graph. + * + * **Example** (Checking node existence) * - * @example * ```ts * import { Graph } from "effect" * @@ -589,14 +776,15 @@ export const getNode: { * console.log(notExists) // false * ``` * - * @since 4.0.0 * @category getters + * @since 3.18.0 */ export const hasNode: { /** - * Checks if a node with the given index exists in the graph. + * Checks whether a node with the given index exists in the graph. + * + * **Example** (Checking node existence) * - * @example * ```ts * import { Graph } from "effect" * @@ -613,14 +801,15 @@ export const hasNode: { * console.log(notExists) // false * ``` * - * @since 4.0.0 * @category getters + * @since 3.18.0 */ (nodeIndex: NodeIndex): (graph: Graph | MutableGraph) => boolean /** - * Checks if a node with the given index exists in the graph. + * Checks whether a node with the given index exists in the graph. + * + * **Example** (Checking node existence) * - * @example * ```ts * import { Graph } from "effect" * @@ -637,8 +826,8 @@ export const hasNode: { * console.log(notExists) // false * ``` * - * @since 4.0.0 * @category getters + * @since 3.18.0 */ (graph: Graph | MutableGraph, nodeIndex: NodeIndex): boolean } = dual(2, ( @@ -649,7 +838,8 @@ export const hasNode: { /** * Returns the number of nodes in the graph. * - * @example + * **Example** (Counting nodes) + * * ```ts * import { Graph } from "effect" * @@ -665,8 +855,8 @@ export const hasNode: { * console.log(Graph.nodeCount(graphWithNodes)) // 3 * ``` * - * @since 4.0.0 * @category getters + * @since 3.18.0 */ export const nodeCount = ( graph: Graph | MutableGraph @@ -675,7 +865,8 @@ export const nodeCount = ( /** * Finds the first node that matches the given predicate. * - * @example + * **Example** (Finding the first matching node) + * * ```ts * import { Graph } from "effect" * @@ -692,14 +883,15 @@ export const nodeCount = ( * console.log(notFound) // Option.none() * ``` * - * @since 4.0.0 * @category getters + * @since 3.18.0 */ export const findNode: { /** * Finds the first node that matches the given predicate. * - * @example + * **Example** (Finding the first matching node) + * * ```ts * import { Graph } from "effect" * @@ -716,14 +908,15 @@ export const findNode: { * console.log(notFound) // Option.none() * ``` * - * @since 4.0.0 * @category getters + * @since 3.18.0 */ (predicate: (data: N) => boolean): (graph: Graph | MutableGraph) => Option.Option /** * Finds the first node that matches the given predicate. * - * @example + * **Example** (Finding the first matching node) + * * ```ts * import { Graph } from "effect" * @@ -740,8 +933,8 @@ export const findNode: { * console.log(notFound) // Option.none() * ``` * - * @since 4.0.0 * @category getters + * @since 3.18.0 */ ( graph: Graph | MutableGraph, @@ -762,7 +955,8 @@ export const findNode: { /** * Finds all nodes that match the given predicate. * - * @example + * **Example** (Finding matching nodes) + * * ```ts * import { Graph } from "effect" * @@ -779,14 +973,15 @@ export const findNode: { * console.log(empty) // [] * ``` * - * @since 4.0.0 * @category getters + * @since 3.18.0 */ export const findNodes: { /** * Finds all nodes that match the given predicate. * - * @example + * **Example** (Finding matching nodes) + * * ```ts * import { Graph } from "effect" * @@ -803,14 +998,15 @@ export const findNodes: { * console.log(empty) // [] * ``` * - * @since 4.0.0 * @category getters + * @since 3.18.0 */ (predicate: (data: N) => boolean): (graph: Graph | MutableGraph) => Array /** * Finds all nodes that match the given predicate. * - * @example + * **Example** (Finding matching nodes) + * * ```ts * import { Graph } from "effect" * @@ -827,8 +1023,8 @@ export const findNodes: { * console.log(empty) // [] * ``` * - * @since 4.0.0 * @category getters + * @since 3.18.0 */ ( graph: Graph | MutableGraph, @@ -850,7 +1046,8 @@ export const findNodes: { /** * Finds the first edge that matches the given predicate. * - * @example + * **Example** (Finding the first matching edge) + * * ```ts * import { Graph } from "effect" * @@ -869,14 +1066,15 @@ export const findNodes: { * console.log(notFound) // Option.none() * ``` * - * @since 4.0.0 * @category getters + * @since 3.18.0 */ export const findEdge: { /** * Finds the first edge that matches the given predicate. * - * @example + * **Example** (Finding the first matching edge) + * * ```ts * import { Graph } from "effect" * @@ -895,14 +1093,15 @@ export const findEdge: { * console.log(notFound) // Option.none() * ``` * - * @since 4.0.0 * @category getters + * @since 3.18.0 */ (predicate: (data: E, source: NodeIndex, target: NodeIndex) => boolean): (graph: Graph | MutableGraph) => Option.Option /** * Finds the first edge that matches the given predicate. * - * @example + * **Example** (Finding the first matching edge) + * * ```ts * import { Graph } from "effect" * @@ -921,8 +1120,8 @@ export const findEdge: { * console.log(notFound) // Option.none() * ``` * - * @since 4.0.0 * @category getters + * @since 3.18.0 */ ( graph: Graph | MutableGraph, @@ -943,7 +1142,8 @@ export const findEdge: { /** * Finds all edges that match the given predicate. * - * @example + * **Example** (Finding matching edges) + * * ```ts * import { Graph } from "effect" * @@ -963,14 +1163,15 @@ export const findEdge: { * console.log(empty) // [] * ``` * - * @since 4.0.0 * @category getters + * @since 3.18.0 */ export const findEdges: { /** * Finds all edges that match the given predicate. * - * @example + * **Example** (Finding matching edges) + * * ```ts * import { Graph } from "effect" * @@ -990,14 +1191,15 @@ export const findEdges: { * console.log(empty) // [] * ``` * - * @since 4.0.0 * @category getters + * @since 3.18.0 */ (predicate: (data: E, source: NodeIndex, target: NodeIndex) => boolean): (graph: Graph | MutableGraph) => Array /** * Finds all edges that match the given predicate. * - * @example + * **Example** (Finding matching edges) + * * ```ts * import { Graph } from "effect" * @@ -1017,8 +1219,8 @@ export const findEdges: { * console.log(empty) // [] * ``` * - * @since 4.0.0 * @category getters + * @since 3.18.0 */ ( graph: Graph | MutableGraph, @@ -1040,7 +1242,8 @@ export const findEdges: { /** * Updates a single node's data by applying a transformation function. * - * @example + * **Example** (Updating node data) + * * ```ts * import { Graph } from "effect" * @@ -1054,8 +1257,8 @@ export const findEdges: { * console.log(nodeData) // Option.some("NODE A") * ``` * - * @since 4.0.0 - * @category transformations + * @category transforming + * @since 3.18.0 */ export const updateNode = ( mutable: MutableGraph, @@ -1074,7 +1277,8 @@ export const updateNode = ( /** * Updates a single edge's data by applying a transformation function. * - * @example + * **Example** (Updating edge data) + * * ```ts * import { Graph } from "effect" * @@ -1086,11 +1290,11 @@ export const updateNode = ( * }) * * const edgeData = Graph.getEdge(result, 0) - * console.log(edgeData) // new Graph.Edge({ source: 0, target: 1, data: 20 }) + * console.log(edgeData) // Option.some(new Graph.Edge({ source: 0, target: 1, data: 20 })) * ``` * - * @since 4.0.0 * @category mutations + * @since 3.18.0 */ export const updateEdge = ( mutable: MutableGraph, @@ -1107,9 +1311,15 @@ export const updateEdge = ( } /** - * Creates a new graph with transformed node data using the provided mapping function. + * Transforms every node's data in a mutable graph in place using the provided + * mapping function. + * + * **Details** + * + * Node indices and edges are preserved; only the stored node data is replaced. + * + * **Example** (Mapping node data) * - * @example * ```ts * import { Graph } from "effect" * @@ -1121,11 +1331,11 @@ export const updateEdge = ( * }) * * const nodeData = Graph.getNode(graph, 0) - * console.log(nodeData) // new Graph.Node("NODE A") + * console.log(nodeData) // Option.some("NODE A") * ``` * - * @since 4.0.0 - * @category transformations + * @category transforming + * @since 3.18.0 */ export const mapNodes = ( mutable: MutableGraph, @@ -1141,7 +1351,8 @@ export const mapNodes = ( /** * Transforms all edge data in a mutable graph using the provided mapping function. * - * @example + * **Example** (Mapping edge data) + * * ```ts * import { Graph } from "effect" * @@ -1155,11 +1366,11 @@ export const mapNodes = ( * }) * * const edgeData = Graph.getEdge(graph, 0) - * console.log(edgeData) // new Graph.Edge({ source: 0, target: 1, data: 20 }) + * console.log(edgeData) // Option.some(new Graph.Edge({ source: 0, target: 1, data: 20 })) * ``` * - * @since 4.0.0 - * @category transformations + * @category transforming + * @since 3.18.0 */ export const mapEdges = ( mutable: MutableGraph, @@ -1176,9 +1387,35 @@ export const mapEdges = ( } /** - * Reverses all edge directions in a mutable graph by swapping source and target nodes. + * @internal + */ +const rebuildAdjacency = ( + mutable: MutableGraph +): void => { + mutable.adjacency.clear() + mutable.reverseAdjacency.clear() + + for (const nodeIndex of mutable.nodes.keys()) { + mutable.adjacency.set(nodeIndex, []) + mutable.reverseAdjacency.set(nodeIndex, []) + } + + for (const [edgeIndex, edgeData] of mutable.edges) { + mutable.adjacency.get(edgeData.source)!.push(edgeIndex) + mutable.reverseAdjacency.get(edgeData.target)!.push(edgeIndex) + + if (mutable.type === "undirected") { + mutable.adjacency.get(edgeData.target)!.push(edgeIndex) + mutable.reverseAdjacency.get(edgeData.source)!.push(edgeIndex) + } + } +} + +/** + * Swaps source and target nodes for every edge in a mutable graph. + * + * **Example** (Reversing edge directions) * - * @example * ```ts * import { Graph } from "effect" * @@ -1192,15 +1429,19 @@ export const mapEdges = ( * }) * * const edge0 = Graph.getEdge(graph, 0) - * console.log(edge0) // new Graph.Edge({ source: 1, target: 0, data: 1 }) - B -> A + * console.log(edge0) // Option.some(new Graph.Edge({ source: 1, target: 0, data: 1 })) * ``` * - * @since 4.0.0 - * @category transformations + * @category transforming + * @since 3.18.0 */ export const reverse = ( mutable: MutableGraph ): void => { + if (mutable.type === "undirected") { + return + } + // Reverse all edges by swapping source and target for (const [index, edgeData] of mutable.edges) { mutable.edges.set( @@ -1213,22 +1454,7 @@ export const reverse = ( ) } - // Clear and rebuild adjacency lists with reversed directions - mutable.adjacency.clear() - mutable.reverseAdjacency.clear() - - // Rebuild adjacency lists with reversed directions - for (const [edgeIndex, edgeData] of mutable.edges) { - // Add to forward adjacency (source -> target) - const sourceEdges = mutable.adjacency.get(edgeData.source) || [] - sourceEdges.push(edgeIndex) - mutable.adjacency.set(edgeData.source, sourceEdges) - - // Add to reverse adjacency (target <- source) - const targetEdges = mutable.reverseAdjacency.get(edgeData.target) || [] - targetEdges.push(edgeIndex) - mutable.reverseAdjacency.set(edgeData.target, targetEdges) - } + rebuildAdjacency(mutable) // Invalidate cycle flag since edge directions changed mutable.acyclic = Option.none() @@ -1238,10 +1464,10 @@ export const reverse = ( * Filters and optionally transforms nodes in a mutable graph using a predicate function. * Nodes that return Option.none are removed along with all their connected edges. * - * @example + * **Example** (Filtering and mapping nodes) + * * ```ts - * import { Graph } from "effect" - * import * as Option from "effect/Option" + * import { Graph, Option } from "effect" * * const graph = Graph.directed((mutable) => { * const a = Graph.addNode(mutable, "active") @@ -1261,8 +1487,8 @@ export const reverse = ( * console.log(Graph.nodeCount(graph)) // 2 (only "active" nodes remain) * ``` * - * @since 4.0.0 - * @category transformations + * @category transforming + * @since 3.18.0 */ export const filterMapNodes = ( mutable: MutableGraph, @@ -1292,10 +1518,10 @@ export const filterMapNodes = ( * Filters and optionally transforms edges in a mutable graph using a predicate function. * Edges that return Option.none are removed from the graph. * - * @example + * **Example** (Filtering and mapping edges) + * * ```ts - * import { Graph } from "effect" - * import * as Option from "effect/Option" + * import { Graph, Option } from "effect" * * const graph = Graph.directed((mutable) => { * const a = Graph.addNode(mutable, "A") @@ -1315,8 +1541,8 @@ export const filterMapNodes = ( * console.log(Graph.edgeCount(graph)) // 2 (edges with weight 5 removed) * ``` * - * @since 4.0.0 - * @category transformations + * @category transforming + * @since 3.18.0 */ export const filterMapEdges = ( mutable: MutableGraph, @@ -1349,7 +1575,8 @@ export const filterMapEdges = ( * Filters nodes by removing those that don't match the predicate. * This function modifies the mutable graph in place. * - * @example + * **Example** (Filtering nodes) + * * ```ts * import { Graph } from "effect" * @@ -1366,8 +1593,8 @@ export const filterMapEdges = ( * console.log(Graph.nodeCount(graph)) // 2 (only "active" nodes remain) * ``` * - * @since 4.0.0 - * @category transformations + * @category transforming + * @since 3.18.0 */ export const filterNodes = ( mutable: MutableGraph, @@ -1392,7 +1619,8 @@ export const filterNodes = ( * Filters edges by removing those that don't match the predicate. * This function modifies the mutable graph in place. * - * @example + * **Example** (Filtering edges) + * * ```ts * import { Graph } from "effect" * @@ -1412,8 +1640,8 @@ export const filterNodes = ( * console.log(Graph.edgeCount(graph)) // 2 (edge with weight 5 removed) * ``` * - * @since 4.0.0 - * @category transformations + * @category transforming + * @since 3.18.0 */ export const filterEdges = ( mutable: MutableGraph, @@ -1465,7 +1693,24 @@ const invalidateCycleFlagOnAddition = ( /** * Adds a new edge to a mutable graph and returns its index. * - * @example + * **When to use** + * + * Use to connect two existing nodes in a mutable graph while storing edge data + * and receiving the new edge identifier. + * + * **Details** + * + * Creates an `Edge` with the source, target, and data at the next edge index, + * updates adjacency indexes, and increments the graph's next edge index. + * Undirected graphs register the same edge for both endpoints. + * + * **Gotchas** + * + * The source and target nodes must already exist in the mutable graph; missing + * endpoints throw a `GraphError`. + * + * **Example** (Adding edges) + * * ```ts * import { Graph } from "effect" * @@ -1477,8 +1722,13 @@ const invalidateCycleFlagOnAddition = ( * }) * ``` * - * @since 4.0.0 + * @see {@link mutate} for obtaining a mutable graph from an immutable graph + * @see {@link addNode} for creating node indexes before connecting them + * @see {@link getEdge} for reading the returned edge + * @see {@link removeEdge} for removing an edge from a mutable graph + * * @category mutations + * @since 3.18.0 */ export const addEdge = ( mutable: MutableGraph, @@ -1537,7 +1787,8 @@ export const addEdge = ( /** * Removes a node and all its incident edges from a mutable graph. * - * @example + * **Example** (Removing a node) + * * ```ts * import { Graph } from "effect" * @@ -1551,8 +1802,8 @@ export const addEdge = ( * }) * ``` * - * @since 4.0.0 * @category mutations + * @since 3.18.0 */ export const removeNode = ( mutable: MutableGraph, @@ -1600,7 +1851,8 @@ export const removeNode = ( /** * Removes an edge from a mutable graph. * - * @example + * **Example** (Removing an edge) + * * ```ts * import { Graph } from "effect" * @@ -1614,8 +1866,8 @@ export const removeNode = ( * }) * ``` * - * @since 4.0.0 * @category mutations + * @since 3.18.0 */ export const removeEdge = ( mutable: MutableGraph, @@ -1690,9 +1942,10 @@ const removeEdgeInternal = ( // ============================================================================= /** - * Gets the edge data associated with an edge index, if it exists. + * Gets the edge data associated with an edge index safely, if it exists. + * + * **Example** (Getting edge data) * - * @example * ```ts * import { Graph } from "effect" * @@ -1707,13 +1960,13 @@ const removeEdgeInternal = ( * * if (edgeData._tag === "Some") { * console.log(edgeData.value.data) // 42 - * console.log(edgeData.value.source) // NodeIndex(0) - * console.log(edgeData.value.target) // NodeIndex(1) + * console.log(edgeData.value.source) // 0 + * console.log(edgeData.value.target) // 1 * } * ``` * - * @since 4.0.0 * @category getters + * @since 3.18.0 */ export const getEdge: { // ============================================================================= @@ -1721,9 +1974,10 @@ export const getEdge: { // ============================================================================= /** - * Gets the edge data associated with an edge index, if it exists. + * Gets the edge data associated with an edge index safely, if it exists. + * + * **Example** (Getting edge data) * - * @example * ```ts * import { Graph } from "effect" * @@ -1738,13 +1992,13 @@ export const getEdge: { * * if (edgeData._tag === "Some") { * console.log(edgeData.value.data) // 42 - * console.log(edgeData.value.source) // NodeIndex(0) - * console.log(edgeData.value.target) // NodeIndex(1) + * console.log(edgeData.value.source) // 0 + * console.log(edgeData.value.target) // 1 * } * ``` * - * @since 4.0.0 * @category getters + * @since 3.18.0 */ (edgeIndex: EdgeIndex): (graph: Graph | MutableGraph) => Option.Option> // ============================================================================= @@ -1752,9 +2006,10 @@ export const getEdge: { // ============================================================================= /** - * Gets the edge data associated with an edge index, if it exists. + * Gets the edge data associated with an edge index safely, if it exists. + * + * **Example** (Getting edge data) * - * @example * ```ts * import { Graph } from "effect" * @@ -1769,13 +2024,13 @@ export const getEdge: { * * if (edgeData._tag === "Some") { * console.log(edgeData.value.data) // 42 - * console.log(edgeData.value.source) // NodeIndex(0) - * console.log(edgeData.value.target) // NodeIndex(1) + * console.log(edgeData.value.source) // 0 + * console.log(edgeData.value.target) // 1 * } * ``` * - * @since 4.0.0 * @category getters + * @since 3.18.0 */ (graph: Graph | MutableGraph, edgeIndex: EdgeIndex): Option.Option> } = dual(2, ( @@ -1784,9 +2039,10 @@ export const getEdge: { ): Option.Option> => Option.fromUndefinedOr(graph.edges.get(edgeIndex))) /** - * Checks if an edge exists between two nodes in the graph. + * Checks whether an edge exists between two nodes in the graph. + * + * **Example** (Checking edge existence) * - * @example * ```ts * import { Graph } from "effect" * @@ -1808,14 +2064,15 @@ export const getEdge: { * console.log(hasAC) // false * ``` * - * @since 4.0.0 * @category getters + * @since 3.18.0 */ export const hasEdge: { /** - * Checks if an edge exists between two nodes in the graph. + * Checks whether an edge exists between two nodes in the graph. + * + * **Example** (Checking edge existence) * - * @example * ```ts * import { Graph } from "effect" * @@ -1837,14 +2094,15 @@ export const hasEdge: { * console.log(hasAC) // false * ``` * - * @since 4.0.0 * @category getters + * @since 3.18.0 */ (source: NodeIndex, target: NodeIndex): (graph: Graph | MutableGraph) => boolean /** - * Checks if an edge exists between two nodes in the graph. + * Checks whether an edge exists between two nodes in the graph. + * + * **Example** (Checking edge existence) * - * @example * ```ts * import { Graph } from "effect" * @@ -1866,8 +2124,8 @@ export const hasEdge: { * console.log(hasAC) // false * ``` * - * @since 4.0.0 * @category getters + * @since 3.18.0 */ ( graph: Graph | MutableGraph, @@ -1887,8 +2145,11 @@ export const hasEdge: { // Check if any edge in the adjacency list connects to the target for (const edgeIndex of adjacencyList) { const edge = graph.edges.get(edgeIndex) - if (edge !== undefined && edge.target === target) { - return true + if (edge !== undefined) { + const neighbor = graph.type === "undirected" && edge.target === source ? edge.source : edge.target + if (neighbor === target) { + return true + } } } @@ -1898,7 +2159,8 @@ export const hasEdge: { /** * Returns the number of edges in the graph. * - * @example + * **Example** (Counting edges) + * * ```ts * import { Graph } from "effect" * @@ -1917,17 +2179,48 @@ export const hasEdge: { * console.log(Graph.edgeCount(graphWithEdges)) // 3 * ``` * - * @since 4.0.0 * @category getters + * @since 3.18.0 */ export const edgeCount = ( graph: Graph | MutableGraph ): number => graph.edges.size +const getDirectedNeighbors = ( + graph: Graph | MutableGraph, + nodeIndex: NodeIndex, + direction: Direction +): Array => { + const adjacencyMap = direction === "incoming" + ? graph.reverseAdjacency + : graph.adjacency + + const adjacencyList = adjacencyMap.get(nodeIndex) + if (adjacencyList === undefined) { + return [] + } + + const result: Array = [] + for (const edgeIndex of adjacencyList) { + const edge = graph.edges.get(edgeIndex) + if (edge !== undefined) { + result.push(direction === "incoming" ? edge.source : edge.target) + } + } + + return result +} + /** - * Returns the neighboring nodes (targets of outgoing edges) for a given node. + * Returns the neighboring node indices for a node. + * + * **Details** + * + * For directed graphs, neighbors are the targets of outgoing edges. For + * undirected graphs, neighbors are the other endpoints of incident edges. + * + * **Example** (Getting outgoing neighbors) * - * @example * ```ts * import { Graph } from "effect" * @@ -1944,20 +2237,26 @@ export const edgeCount = ( * const nodeC = 2 * * const neighborsA = Graph.neighbors(graph, nodeA) - * console.log(neighborsA) // [NodeIndex(1), NodeIndex(2)] + * console.log(neighborsA) // [1, 2] * * const neighborsB = Graph.neighbors(graph, nodeB) * console.log(neighborsB) // [] * ``` * - * @since 4.0.0 * @category getters + * @since 3.18.0 */ export const neighbors: { /** - * Returns the neighboring nodes (targets of outgoing edges) for a given node. + * Returns the neighboring node indices for a node. + * + * **Details** + * + * For directed graphs, neighbors are the targets of outgoing edges. For + * undirected graphs, neighbors are the other endpoints of incident edges. + * + * **Example** (Getting outgoing neighbors) * - * @example * ```ts * import { Graph } from "effect" * @@ -1974,20 +2273,26 @@ export const neighbors: { * const nodeC = 2 * * const neighborsA = Graph.neighbors(graph, nodeA) - * console.log(neighborsA) // [NodeIndex(1), NodeIndex(2)] + * console.log(neighborsA) // [1, 2] * * const neighborsB = Graph.neighbors(graph, nodeB) * console.log(neighborsB) // [] * ``` * - * @since 4.0.0 * @category getters + * @since 3.18.0 */ (nodeIndex: NodeIndex): (graph: Graph | MutableGraph) => Array /** - * Returns the neighboring nodes (targets of outgoing edges) for a given node. + * Returns the neighboring node indices for a node. + * + * **Details** + * + * For directed graphs, neighbors are the targets of outgoing edges. For + * undirected graphs, neighbors are the other endpoints of incident edges. + * + * **Example** (Getting outgoing neighbors) * - * @example * ```ts * import { Graph } from "effect" * @@ -2004,14 +2309,14 @@ export const neighbors: { * const nodeC = 2 * * const neighborsA = Graph.neighbors(graph, nodeA) - * console.log(neighborsA) // [NodeIndex(1), NodeIndex(2)] + * console.log(neighborsA) // [1, 2] * * const neighborsB = Graph.neighbors(graph, nodeB) * console.log(neighborsB) // [] * ``` * - * @since 4.0.0 * @category getters + * @since 3.18.0 */ (graph: Graph | MutableGraph, nodeIndex: NodeIndex): Array } = dual(2, ( @@ -2023,26 +2328,163 @@ export const neighbors: { return getUndirectedNeighbors(graph as any, nodeIndex) } - const adjacencyList = graph.adjacency.get(nodeIndex) - if (adjacencyList === undefined) { - return [] - } + return getDirectedNeighbors(graph as Graph | MutableGraph, nodeIndex, "outgoing") +}) - const result: Array = [] - for (const edgeIndex of adjacencyList) { - const edge = graph.edges.get(edgeIndex) - if (edge !== undefined) { - result.push(edge.target) - } +/** + * Returns the outgoing neighbor node indices for a node in a directed graph. + * + * **When to use** + * + * Use when you need the nodes reached by following outgoing edges from a node in + * a directed graph. + * + * **Gotchas** + * + * Throws a `GraphError` when used with an undirected graph. + * + * @see {@link predecessors} for incoming neighbors in a directed graph + * @see {@link neighbors} for generic neighbor lookup across graph kinds + * + * @category queries + * @since 4.0.0 + */ +export const successors: { + /** + * Returns the outgoing neighbor node indices for a node in a directed graph. + * + * **When to use** + * + * Use when you need the nodes reached by following outgoing edges from a node in + * a directed graph. + * + * **Gotchas** + * + * Throws a `GraphError` when used with an undirected graph. + * + * @see {@link predecessors} for incoming neighbors in a directed graph + * @see {@link neighbors} for generic neighbor lookup across graph kinds + * + * @category queries + * @since 4.0.0 + */ + (nodeIndex: NodeIndex): (graph: Graph | MutableGraph) => Array + /** + * Returns the outgoing neighbor node indices for a node in a directed graph. + * + * **When to use** + * + * Use when you need the nodes reached by following outgoing edges from a node in + * a directed graph. + * + * **Gotchas** + * + * Throws a `GraphError` when used with an undirected graph. + * + * @see {@link predecessors} for incoming neighbors in a directed graph + * @see {@link neighbors} for generic neighbor lookup across graph kinds + * + * @category queries + * @since 4.0.0 + */ + ( + graph: Graph | MutableGraph, + nodeIndex: NodeIndex + ): Array +} = dual(2, ( + graph: Graph | MutableGraph, + nodeIndex: NodeIndex +): Array => { + if (graph.type === "undirected") { + throw new GraphError({ message: "Cannot get successors of undirected graph" }) } + return getDirectedNeighbors(graph as Graph | MutableGraph, nodeIndex, "outgoing") +}) - return result +/** + * Returns the incoming neighbor node indices for a node in a directed graph. + * + * **When to use** + * + * Use when you need the nodes that reach a node by following incoming edges in a + * directed graph. + * + * **Gotchas** + * + * Throws a `GraphError` when used with an undirected graph. + * + * @see {@link successors} for outgoing neighbors in a directed graph + * @see {@link neighbors} for generic neighbor lookup across graph kinds + * + * @category queries + * @since 4.0.0 + */ +export const predecessors: { + /** + * Returns the incoming neighbor node indices for a node in a directed graph. + * + * **When to use** + * + * Use when you need the nodes that reach a node by following incoming edges in a + * directed graph. + * + * **Gotchas** + * + * Throws a `GraphError` when used with an undirected graph. + * + * @see {@link successors} for outgoing neighbors in a directed graph + * @see {@link neighbors} for generic neighbor lookup across graph kinds + * + * @category queries + * @since 4.0.0 + */ + (nodeIndex: NodeIndex): (graph: Graph | MutableGraph) => Array + /** + * Returns the incoming neighbor node indices for a node in a directed graph. + * + * **When to use** + * + * Use when you need the nodes that reach a node by following incoming edges in a + * directed graph. + * + * **Gotchas** + * + * Throws a `GraphError` when used with an undirected graph. + * + * @see {@link successors} for outgoing neighbors in a directed graph + * @see {@link neighbors} for generic neighbor lookup across graph kinds + * + * @category queries + * @since 4.0.0 + */ + ( + graph: Graph | MutableGraph, + nodeIndex: NodeIndex + ): Array +} = dual(2, ( + graph: Graph | MutableGraph, + nodeIndex: NodeIndex +): Array => { + if (graph.type === "undirected") { + throw new GraphError({ message: "Cannot get predecessors of undirected graph" }) + } + return getDirectedNeighbors(graph as Graph | MutableGraph, nodeIndex, "incoming") }) /** - * Get neighbors of a node in a specific direction for bidirectional traversal. + * Gets directed neighbors of a node in a specific direction. + * + * **When to use** + * + * Use when maintaining existing code that already passes an explicit traversal + * direction. New code should prefer `successors` or `predecessors`. + * + * **Gotchas** + * + * Throws a `GraphError` when used with an undirected graph. + * + * **Example** (Traversing directed neighbors) * - * @example * ```ts * import { Graph } from "effect" * @@ -2062,14 +2504,27 @@ export const neighbors: { * const incoming = Graph.neighborsDirected(graph, nodeB, "incoming") * ``` * - * @since 4.0.0 + * @deprecated Use {@link successors} for outgoing neighbors or {@link predecessors} for incoming neighbors. + * @see {@link successors} for outgoing neighbors in a directed graph + * @see {@link predecessors} for incoming neighbors in a directed graph * @category queries + * @since 3.18.0 */ export const neighborsDirected: { /** - * Get neighbors of a node in a specific direction for bidirectional traversal. + * Gets directed neighbors of a node in a specific direction. + * + * **When to use** + * + * Use when maintaining existing code that already passes an explicit traversal + * direction. New code should prefer `successors` or `predecessors`. + * + * **Gotchas** + * + * Throws a `GraphError` when used with an undirected graph. + * + * **Example** (Traversing directed neighbors) * - * @example * ```ts * import { Graph } from "effect" * @@ -2089,14 +2544,27 @@ export const neighborsDirected: { * const incoming = Graph.neighborsDirected(graph, nodeB, "incoming") * ``` * - * @since 4.0.0 + * @deprecated Use {@link successors} for outgoing neighbors or {@link predecessors} for incoming neighbors. + * @see {@link successors} for outgoing neighbors in a directed graph + * @see {@link predecessors} for incoming neighbors in a directed graph * @category queries + * @since 3.18.0 */ - (nodeIndex: NodeIndex, direction: Direction): (graph: Graph | MutableGraph) => Array + (nodeIndex: NodeIndex, direction: Direction): (graph: Graph | MutableGraph) => Array /** - * Get neighbors of a node in a specific direction for bidirectional traversal. + * Gets directed neighbors of a node in a specific direction. + * + * **When to use** + * + * Use when maintaining existing code that already passes an explicit traversal + * direction. New code should prefer `successors` or `predecessors`. + * + * **Gotchas** + * + * Throws a `GraphError` when used with an undirected graph. + * + * **Example** (Traversing directed neighbors) * - * @example * ```ts * import { Graph } from "effect" * @@ -2116,11 +2584,14 @@ export const neighborsDirected: { * const incoming = Graph.neighborsDirected(graph, nodeB, "incoming") * ``` * - * @since 4.0.0 + * @deprecated Use {@link successors} for outgoing neighbors or {@link predecessors} for incoming neighbors. + * @see {@link successors} for outgoing neighbors in a directed graph + * @see {@link predecessors} for incoming neighbors in a directed graph * @category queries + * @since 3.18.0 */ - ( - graph: Graph | MutableGraph, + ( + graph: Graph | MutableGraph, nodeIndex: NodeIndex, direction: Direction ): Array @@ -2129,28 +2600,10 @@ export const neighborsDirected: { nodeIndex: NodeIndex, direction: Direction ): Array => { - const adjacencyMap = direction === "incoming" - ? graph.reverseAdjacency - : graph.adjacency - - const adjacencyList = adjacencyMap.get(nodeIndex) - if (adjacencyList === undefined) { - return [] - } - - const result: Array = [] - for (const edgeIndex of adjacencyList) { - const edge = graph.edges.get(edgeIndex) - if (edge !== undefined) { - // For incoming direction, we want the source node instead of target - const neighborNode = direction === "incoming" - ? edge.source - : edge.target - result.push(neighborNode) - } + if (graph.type === "undirected") { + throw new GraphError({ message: "Cannot get directed neighbors of undirected graph" }) } - - return result + return getDirectedNeighbors(graph as Graph | MutableGraph, nodeIndex, direction) }) // ============================================================================= @@ -2160,12 +2613,15 @@ export const neighborsDirected: { /** * Configuration options for GraphViz DOT format generation from graphs. * - * Provides customization for node labels, edge labels, and graph naming - * in DOT format compatible with GraphViz tools. + * **Details** + * + * These options customize node labels, edge labels, and graph naming in DOT + * format compatible with GraphViz tools. + * + * **Example** (Configuring GraphViz labels) * - * @example * ```ts - * import type * as Graph from "effect/Graph" + * import type { Graph } from "effect" * * // Basic options with custom labels * const basicOptions: Graph.GraphVizOptions = { @@ -2181,8 +2637,8 @@ export const neighborsDirected: { * } * ``` * - * @since 4.0.0 - * @category models + * @category options + * @since 3.18.0 */ export interface GraphVizOptions { /** @@ -2207,7 +2663,8 @@ export interface GraphVizOptions { /** * Exports a graph to GraphViz DOT format for visualization. * - * @example + * **Example** (Exporting GraphViz DOT) + * * ```ts * import { Graph } from "effect" * @@ -2232,14 +2689,15 @@ export interface GraphVizOptions { * // } * ``` * - * @since 4.0.0 - * @category utils + * @category converting + * @since 3.18.0 */ export const toGraphViz: { /** * Exports a graph to GraphViz DOT format for visualization. * - * @example + * **Example** (Exporting GraphViz DOT) + * * ```ts * import { Graph } from "effect" * @@ -2264,14 +2722,15 @@ export const toGraphViz: { * // } * ``` * - * @since 4.0.0 - * @category utils + * @category converting + * @since 3.18.0 */ (options?: GraphVizOptions): (graph: Graph | MutableGraph) => string /** * Exports a graph to GraphViz DOT format for visualization. * - * @example + * **Example** (Exporting GraphViz DOT) + * * ```ts * import { Graph } from "effect" * @@ -2296,8 +2755,8 @@ export const toGraphViz: { * // } * ``` * - * @since 4.0.0 - * @category utils + * @category converting + * @since 3.18.0 */ ( graph: Graph | MutableGraph, @@ -2343,6 +2802,8 @@ export const toGraphViz: { /** * Mermaid node shape types for diagram visualization. * + * **Details** + * * Each shape produces different visual representations in Mermaid diagrams: * - `rectangle`: Standard rectangular nodes `A["label"]` * - `rounded`: Rounded rectangular nodes `A("label")` @@ -2353,9 +2814,10 @@ export const toGraphViz: { * - `subroutine`: Subroutine-style nodes `A[["label"]]` * - `cylindrical`: Cylindrical database-style nodes `A[("label")]` * - * @example + * **Example** (Selecting Mermaid node shapes) + * * ```ts - * import type * as Graph from "effect/Graph" + * import type { Graph } from "effect" * * // Shape selector function for different node types * const shapeSelector = (nodeData: string): Graph.MermaidNodeShape => { @@ -2371,8 +2833,8 @@ export const toGraphViz: { * } * ``` * - * @since 4.0.0 * @category models + * @since 3.18.0 */ export type MermaidNodeShape = | "rectangle" // A["label"] @@ -2387,15 +2849,18 @@ export type MermaidNodeShape = /** * Mermaid diagram direction types for controlling layout orientation. * + * **Details** + * * Determines the flow direction of nodes and edges in the diagram: * - `TB`/`TD`: Top to Bottom (vertical layout, default) * - `BT`: Bottom to Top (reverse vertical) * - `LR`: Left to Right (horizontal layout) * - `RL`: Right to Left (reverse horizontal) * - * @example + * **Example** (Configuring Mermaid directions) + * * ```ts - * import type * as Graph from "effect/Graph" + * import type { Graph } from "effect" * * // Horizontal workflow diagram * const horizontalOptions: Graph.MermaidOptions = { @@ -2413,8 +2878,8 @@ export type MermaidNodeShape = * } * ``` * - * @since 4.0.0 * @category models + * @since 3.18.0 */ export type MermaidDirection = | "TB" // Top to Bottom (default) @@ -2426,6 +2891,8 @@ export type MermaidDirection = /** * Mermaid diagram types for different visualization formats. * + * **Details** + * * Specifies the Mermaid diagram syntax to use: * - `flowchart`: For directed graphs with arrows (`A --> B`) * - `graph`: For undirected graphs with lines (`A --- B`) @@ -2433,9 +2900,10 @@ export type MermaidDirection = * When not specified, automatically selects based on graph type: * directed graphs use "flowchart", undirected graphs use "graph". * - * @example + * **Example** (Selecting Mermaid diagram types) + * * ```ts - * import type * as Graph from "effect/Graph" + * import type { Graph } from "effect" * * // Force flowchart format (even for undirected graphs) * const flowchartOptions: Graph.MermaidOptions = { @@ -2451,8 +2919,8 @@ export type MermaidDirection = * const autoOptions: Graph.MermaidOptions = {} * ``` * - * @since 4.0.0 * @category models + * @since 3.18.0 */ export type MermaidDiagramType = | "flowchart" // For directed graphs @@ -2461,18 +2929,21 @@ export type MermaidDiagramType = /** * Configuration options for Mermaid diagram generation, following GraphViz pattern. * - * @since 4.0.0 * @category models + * @since 4.0.0 */ /** * Configuration options for Mermaid diagram generation from graphs. * - * Provides customization for node labels, edge labels, diagram type, - * layout direction, node shapes, and graph naming in Mermaid format. + * **Details** + * + * These options customize node labels, edge labels, diagram type, layout + * direction, node shapes, and graph naming in Mermaid format. + * + * **Example** (Configuring Mermaid output) * - * @example * ```ts - * import type * as Graph from "effect/Graph" + * import type { Graph } from "effect" * * // Basic options with custom labels * const basicOptions: Graph.MermaidOptions = { @@ -2490,8 +2961,8 @@ export type MermaidDiagramType = * } * ``` * - * @since 4.0.0 - * @category models + * @category options + * @since 3.18.0 */ export interface MermaidOptions { /** @@ -2582,14 +3053,17 @@ const formatMermaidNode = ( /** * Exports a graph to Mermaid diagram format for visualization. * + * **Details** + * * Mermaid is a popular diagram-as-code tool that generates flowcharts and other * visualizations from text-based definitions. This function converts Effect Graph * structures to valid Mermaid syntax for use in documentation, web applications, * and visualization tools. * - * @example + * **Example** (Exporting a directed Mermaid diagram) + * * ```ts - * import * as Graph from "effect/Graph" + * import { Graph } from "effect" * * // Basic directed graph export * const graph = Graph.directed((mutable) => { @@ -2610,9 +3084,10 @@ const formatMermaidNode = ( * // 0 -->|"2"| 2 * ``` * - * @example + * **Example** (Exporting an undirected Mermaid diagram) + * * ```ts - * import * as Graph from "effect/Graph" + * import { Graph } from "effect" * * // Undirected graph with custom labels and direction * const socialGraph = Graph.undirected<{ name: string }, string>((mutable) => { @@ -2637,9 +3112,10 @@ const formatMermaidNode = ( * // 1 ---|"colleagues"| 2 * ``` * - * @example + * **Example** (Customizing Mermaid node shapes) + * * ```ts - * import * as Graph from "effect/Graph" + * import { Graph } from "effect" * * // Advanced styling with node shapes for flowchart * const workflow = Graph.directed<{ type: string; name: string }, string>( @@ -2688,9 +3164,10 @@ const formatMermaidNode = ( * // 2 --> 3 * ``` * - * @example + * **Example** (Visualizing dependency graphs) + * * ```ts - * import * as Graph from "effect/Graph" + * import { Graph } from "effect" * * // Real-world example: Software dependency graph * interface Dependency { @@ -2749,25 +3226,24 @@ const formatMermaidNode = ( * // 0 -->|"builds with"| 3 * ``` * - * @param graph - The graph to export (directed or undirected) - * @param options - Optional configuration for the Mermaid output - * @returns Mermaid diagram syntax as a string - * - * @since 4.0.0 - * @category utils + * @category converting + * @since 3.18.0 */ export const toMermaid: { /** * Exports a graph to Mermaid diagram format for visualization. * + * **Details** + * * Mermaid is a popular diagram-as-code tool that generates flowcharts and other * visualizations from text-based definitions. This function converts Effect Graph * structures to valid Mermaid syntax for use in documentation, web applications, * and visualization tools. * - * @example + * **Example** (Exporting a directed Mermaid diagram) + * * ```ts - * import * as Graph from "effect/Graph" + * import { Graph } from "effect" * * // Basic directed graph export * const graph = Graph.directed((mutable) => { @@ -2788,9 +3264,10 @@ export const toMermaid: { * // 0 -->|"2"| 2 * ``` * - * @example + * **Example** (Exporting an undirected Mermaid diagram) + * * ```ts - * import * as Graph from "effect/Graph" + * import { Graph } from "effect" * * // Undirected graph with custom labels and direction * const socialGraph = Graph.undirected<{ name: string }, string>((mutable) => { @@ -2815,9 +3292,10 @@ export const toMermaid: { * // 1 ---|"colleagues"| 2 * ``` * - * @example + * **Example** (Customizing Mermaid node shapes) + * * ```ts - * import * as Graph from "effect/Graph" + * import { Graph } from "effect" * * // Advanced styling with node shapes for flowchart * const workflow = Graph.directed<{ type: string; name: string }, string>( @@ -2866,9 +3344,10 @@ export const toMermaid: { * // 2 --> 3 * ``` * - * @example + * **Example** (Visualizing dependency graphs) + * * ```ts - * import * as Graph from "effect/Graph" + * import { Graph } from "effect" * * // Real-world example: Software dependency graph * interface Dependency { @@ -2927,25 +3406,24 @@ export const toMermaid: { * // 0 -->|"builds with"| 3 * ``` * - * @param graph - The graph to export (directed or undirected) - * @param options - Optional configuration for the Mermaid output - * @returns Mermaid diagram syntax as a string - * - * @since 4.0.0 - * @category utils + * @category converting + * @since 3.18.0 */ (options?: MermaidOptions): (graph: Graph | MutableGraph) => string /** * Exports a graph to Mermaid diagram format for visualization. * + * **Details** + * * Mermaid is a popular diagram-as-code tool that generates flowcharts and other * visualizations from text-based definitions. This function converts Effect Graph * structures to valid Mermaid syntax for use in documentation, web applications, * and visualization tools. * - * @example + * **Example** (Exporting a directed Mermaid diagram) + * * ```ts - * import * as Graph from "effect/Graph" + * import { Graph } from "effect" * * // Basic directed graph export * const graph = Graph.directed((mutable) => { @@ -2966,9 +3444,10 @@ export const toMermaid: { * // 0 -->|"2"| 2 * ``` * - * @example + * **Example** (Exporting an undirected Mermaid diagram) + * * ```ts - * import * as Graph from "effect/Graph" + * import { Graph } from "effect" * * // Undirected graph with custom labels and direction * const socialGraph = Graph.undirected<{ name: string }, string>((mutable) => { @@ -2993,9 +3472,10 @@ export const toMermaid: { * // 1 ---|"colleagues"| 2 * ``` * - * @example + * **Example** (Customizing Mermaid node shapes) + * * ```ts - * import * as Graph from "effect/Graph" + * import { Graph } from "effect" * * // Advanced styling with node shapes for flowchart * const workflow = Graph.directed<{ type: string; name: string }, string>( @@ -3044,9 +3524,10 @@ export const toMermaid: { * // 2 --> 3 * ``` * - * @example + * **Example** (Visualizing dependency graphs) + * * ```ts - * import * as Graph from "effect/Graph" + * import { Graph } from "effect" * * // Real-world example: Software dependency graph * interface Dependency { @@ -3105,12 +3586,8 @@ export const toMermaid: { * // 0 -->|"builds with"| 3 * ``` * - * @param graph - The graph to export (directed or undirected) - * @param options - Optional configuration for the Mermaid output - * @returns Mermaid diagram syntax as a string - * - * @since 4.0.0 - * @category utils + * @category converting + * @since 3.18.0 */ ( graph: Graph | MutableGraph, @@ -3170,7 +3647,8 @@ export const toMermaid: { /** * Direction for graph traversal, indicating which edges to follow. * - * @example + * **Example** (Traversing by direction) + * * ```ts * import { Graph } from "effect" * @@ -3191,8 +3669,8 @@ export const toMermaid: { * ) * ``` * - * @since 4.0.0 * @category models + * @since 3.18.0 */ export type Direction = "outgoing" | "incoming" @@ -3201,13 +3679,16 @@ export type Direction = "outgoing" | "incoming" // ============================================================================= /** - * Checks if the graph is acyclic (contains no cycles). + * Checks whether the graph is acyclic (contains no cycles). + * + * **Details** * * Uses depth-first search to detect back edges, which indicate cycles. * For directed graphs, any back edge creates a cycle. For undirected graphs, * a back edge that doesn't go to the immediate parent creates a cycle. * - * @example + * **Example** (Checking cycles) + * * ```ts * import { Graph } from "effect" * @@ -3231,8 +3712,8 @@ export type Direction = "outgoing" | "incoming" * console.log(Graph.isAcyclic(cyclic)) // false * ``` * - * @since 4.0.0 * @category algorithms + * @since 3.18.0 */ export const isAcyclic = ( graph: Graph | MutableGraph @@ -3242,6 +3723,37 @@ export const isAcyclic = ( return graph.acyclic.value } + if (graph.type === "undirected") { + const visited = new Set() + + for (const startNode of graph.nodes.keys()) { + if (visited.has(startNode)) { + continue + } + + visited.add(startNode) + const stack: Array<{ node: NodeIndex; parent: NodeIndex | null }> = [{ node: startNode, parent: null }] + + while (stack.length > 0) { + const { node, parent } = stack.pop()! + const nodeNeighbors = getUndirectedNeighbors(graph as any, node) + + for (const neighbor of nodeNeighbors) { + if (!visited.has(neighbor)) { + visited.add(neighbor) + stack.push({ node: neighbor, parent: node }) + } else if (neighbor !== parent) { + graph.acyclic = Option.some(false) + return false + } + } + } + } + + graph.acyclic = Option.some(true) + return true + } + // Stack-safe DFS cycle detection using iterative approach const visited = new Set() const recursionStack = new Set() @@ -3278,7 +3790,11 @@ export const isAcyclic = ( recursionStack.add(node) // Get neighbors for this node - const nodeNeighbors = Array.from(neighborsDirected(graph, node, "outgoing")) + const nodeNeighbors = getDirectedNeighbors( + graph as Graph | MutableGraph, + node, + "outgoing" + ) stack[stack.length - 1] = [node, nodeNeighbors, 0, false] continue } @@ -3311,13 +3827,16 @@ export const isAcyclic = ( } /** - * Checks if an undirected graph is bipartite. + * Checks whether an undirected graph is bipartite. + * + * **Details** * * A bipartite graph is one whose vertices can be divided into two disjoint sets * such that no two vertices within the same set are adjacent. Uses BFS coloring * to determine bipartiteness. * - * @example + * **Example** (Checking bipartite graphs) + * * ```ts * import { Graph } from "effect" * @@ -3345,8 +3864,8 @@ export const isAcyclic = ( * console.log(Graph.isBipartite(triangle)) // false * ``` * - * @since 4.0.0 * @category algorithms + * @since 3.18.0 */ export const isBipartite = ( graph: Graph | MutableGraph @@ -3422,11 +3941,27 @@ const getUndirectedNeighbors = ( return Array.from(neighbors) } +const getTraversalNeighbors = ( + graph: Graph | MutableGraph, + nodeIndex: NodeIndex, + direction: Direction +): Array => + graph.type === "undirected" + ? getUndirectedNeighbors(graph as any, nodeIndex) + : getDirectedNeighbors(graph as Graph | MutableGraph, nodeIndex, direction) + +const getTraversableNeighbor = ( + graph: Graph | MutableGraph, + current: NodeIndex, + edge: Edge +): NodeIndex => graph.type === "undirected" && edge.target === current ? edge.source : edge.target + /** - * Find connected components in an undirected graph. + * Finds connected components in an undirected graph. * Each component is represented as an array of node indices. * - * @example + * **Example** (Finding connected components) + * * ```ts * import { Graph } from "effect" * @@ -3443,8 +3978,8 @@ const getUndirectedNeighbors = ( * console.log(components) // [[0, 1], [2, 3]] * ``` * - * @since 4.0.0 * @category algorithms + * @since 3.18.0 */ export const connectedComponents = ( graph: Graph | MutableGraph @@ -3481,10 +4016,15 @@ export const connectedComponents = ( } /** - * Find strongly connected components in a directed graph using Kosaraju's algorithm. + * Finds strongly connected components in a directed graph using Kosaraju's algorithm. * Each SCC is represented as an array of node indices. * - * @example + * **Gotchas** + * + * Throws a `GraphError` when used with an undirected graph. + * + * **Example** (Finding strongly connected components) + * * ```ts * import { Graph } from "effect" * @@ -3501,12 +4041,16 @@ export const connectedComponents = ( * console.log(sccs) // [[0, 1, 2]] * ``` * - * @since 4.0.0 * @category algorithms + * @since 3.18.0 */ -export const stronglyConnectedComponents = ( - graph: Graph | MutableGraph +export const stronglyConnectedComponents = ( + graph: Graph | MutableGraph ): Array> => { + if ((graph as Graph | MutableGraph).type === "undirected") { + throw new GraphError({ message: "Cannot find strongly connected components of undirected graph" }) + } + const visited = new Set() const finishOrder: Array = [] // Iterate directly over node keys @@ -3532,7 +4076,7 @@ export const stronglyConnectedComponents = ( } visited.add(node) - const nodeNeighborsList = neighbors(graph, node) + const nodeNeighborsList = getDirectedNeighbors(graph, node, "outgoing") stack[stack.length - 1] = [node, nodeNeighborsList, 0, false] continue } @@ -3602,10 +4146,31 @@ export const stronglyConnectedComponents = ( // ============================================================================= /** - * Result of a shortest path computation containing the path and total distance. + * Result of a shortest path computation. + * + * **When to use** + * + * Use to read the successful source-to-target shortest path returned by + * path-finding algorithms, including the ordered node indices, total distance, + * and traversed edge data. + * + * **Details** + * + * Contains the node-index path, the total numeric distance, and the edge data + * encountered along the path. + * + * **Gotchas** + * + * `costs` contains original edge data, not the numeric output of the cost + * function unless the edge data is numeric. + * + * @see {@link dijkstra} for shortest paths with non-negative edge costs + * @see {@link astar} for heuristic shortest-path search + * @see {@link bellmanFord} for shortest paths that may include negative edge weights + * @see {@link AllPairsResult} for the all-pairs shortest-path result shape * - * @since 4.0.0 * @category models + * @since 3.18.0 */ export interface PathResult { readonly path: Array @@ -3614,10 +4179,29 @@ export interface PathResult { } /** - * Configuration for Dijkstra's algorithm. + * Configuration for finding a shortest path with Dijkstra's algorithm. + * + * **When to use** + * + * Use when configuring `dijkstra` to find a shortest path between two existing + * node indices with non-negative edge costs. + * + * **Details** + * + * Specifies the source and target node indices, plus a cost function that maps + * each edge's data to a non-negative numeric weight. + * + * **Gotchas** + * + * `dijkstra` throws a `GraphError` when either endpoint does not exist or when + * the cost function returns a negative weight. + * + * @see {@link dijkstra} for the algorithm that consumes this configuration + * @see {@link AstarConfig} for heuristic shortest-path search + * @see {@link BellmanFordConfig} for shortest paths that may include negative edge weights * - * @since 4.0.0 * @category models + * @since 3.18.0 */ export interface DijkstraConfig { source: NodeIndex @@ -3625,13 +4209,34 @@ export interface DijkstraConfig { cost: (edgeData: E) => number } +const validateNonNegativeEdgeWeights = ( + graph: Graph | MutableGraph, + cost: (edgeData: E) => number, + algorithm: string +): Map => { + const edgeWeights = new Map() + for (const [edgeIndex, edgeData] of graph.edges) { + const weight = cost(edgeData.data) + if (weight < 0 || Number.isNaN(weight)) { + throw new GraphError({ message: `${algorithm} requires non-negative edge weights` }) + } + edgeWeights.set(edgeIndex, weight) + } + return edgeWeights +} + /** - * Find the shortest path between two nodes using Dijkstra's algorithm. + * Finds the shortest path from the configured source node to the target node + * using Dijkstra's algorithm. * - * Dijkstra's algorithm works with non-negative edge weights and finds the shortest - * path from a source node to a target node in O((V + E) log V) time complexity. + * **Details** + * + * Edge costs must be non-negative. Returns `Option.none()` when the target is + * not reachable, and throws a `GraphError` when either endpoint is missing or a + * negative edge cost is encountered. + * + * **Example** (Finding shortest paths with Dijkstra) * - * @example * ```ts * import { Graph } from "effect" * @@ -3656,17 +4261,22 @@ export interface DijkstraConfig { * } * ``` * - * @since 4.0.0 * @category algorithms + * @since 3.18.0 */ export const dijkstra: { /** - * Find the shortest path between two nodes using Dijkstra's algorithm. + * Finds the shortest path from the configured source node to the target node + * using Dijkstra's algorithm. + * + * **Details** * - * Dijkstra's algorithm works with non-negative edge weights and finds the shortest - * path from a source node to a target node in O((V + E) log V) time complexity. + * Edge costs must be non-negative. Returns `Option.none()` when the target is + * not reachable, and throws a `GraphError` when either endpoint is missing or a + * negative edge cost is encountered. + * + * **Example** (Finding shortest paths with Dijkstra) * - * @example * ```ts * import { Graph } from "effect" * @@ -3691,17 +4301,22 @@ export const dijkstra: { * } * ``` * - * @since 4.0.0 * @category algorithms + * @since 3.18.0 */ (config: DijkstraConfig): (graph: Graph | MutableGraph) => Option.Option> /** - * Find the shortest path between two nodes using Dijkstra's algorithm. + * Finds the shortest path from the configured source node to the target node + * using Dijkstra's algorithm. + * + * **Details** + * + * Edge costs must be non-negative. Returns `Option.none()` when the target is + * not reachable, and throws a `GraphError` when either endpoint is missing or a + * negative edge cost is encountered. * - * Dijkstra's algorithm works with non-negative edge weights and finds the shortest - * path from a source node to a target node in O((V + E) log V) time complexity. + * **Example** (Finding shortest paths with Dijkstra) * - * @example * ```ts * import { Graph } from "effect" * @@ -3726,8 +4341,8 @@ export const dijkstra: { * } * ``` * - * @since 4.0.0 * @category algorithms + * @since 3.18.0 */ (graph: Graph | MutableGraph, config: DijkstraConfig): Option.Option> } = dual(2, ( @@ -3742,6 +4357,8 @@ export const dijkstra: { throw missingNode(config.target) } + const edgeWeights = validateNonNegativeEdgeWeights(graph, config.cost, "Dijkstra's algorithm") + // Early return if source equals target if (config.source === config.target) { return Option.some({ @@ -3801,13 +4418,8 @@ export const dijkstra: { for (const edgeIndex of adjacencyList) { const edge = graph.edges.get(edgeIndex) if (edge !== undefined) { - const neighbor = edge.target - const cost = config.cost(edge.data) - - // Validate non-negative weights - if (cost < 0) { - throw new GraphError({ message: "Dijkstra's algorithm requires non-negative edge weights" }) - } + const neighbor = getTraversableNeighbor(graph, currentNode, edge) + const cost = edgeWeights.get(edgeIndex)! const newDistance = currentDistance + cost const neighborDistance = distances.get(neighbor)! @@ -3857,10 +4469,24 @@ export const dijkstra: { }) /** - * Result of all-pairs shortest path computation. + * Result of an all-pairs shortest path computation. + * + * **When to use** + * + * Use when storing or passing around the complete output of `floydWarshall` so + * callers can look up shortest distances, node paths, and edge data for any + * source and target node pair. + * + * **Details** + * + * Contains distance, node-path, and edge-data maps keyed by source and target + * node indices. + * + * @see {@link floydWarshall} for computing an all-pairs shortest path result + * @see {@link PathResult} for the single source-to-target result shape used by path-finding algorithms * - * @since 4.0.0 * @category models + * @since 3.18.0 */ export interface AllPairsResult { readonly distances: Map> @@ -3869,14 +4495,17 @@ export interface AllPairsResult { } /** - * Find shortest paths between all pairs of nodes using Floyd-Warshall algorithm. + * Finds shortest paths between all pairs of nodes using the Floyd-Warshall + * algorithm. * - * Floyd-Warshall algorithm computes shortest paths between all pairs of nodes in O(V³) time. - * It can handle negative edge weights and detect negative cycles. + * **Details** * - * Throws if a negative cycle is detected that affects the path to target. + * Computes distances, reconstructed node paths, and edge-data paths for every + * source and target pair in O(V^3) time. Negative edge weights are allowed, but + * a `GraphError` is thrown if any negative cycle is detected. + * + * **Example** (Finding all-pairs shortest paths) * - * @example * ```ts * import { Graph } from "effect" * @@ -3894,19 +4523,22 @@ export interface AllPairsResult { * const pathAToC = result.paths.get(0)?.get(2) // [0, 1, 2] * ``` * - * @since 4.0.0 * @category algorithms + * @since 3.18.0 */ export const floydWarshall: { /** - * Find shortest paths between all pairs of nodes using Floyd-Warshall algorithm. + * Finds shortest paths between all pairs of nodes using the Floyd-Warshall + * algorithm. * - * Floyd-Warshall algorithm computes shortest paths between all pairs of nodes in O(V³) time. - * It can handle negative edge weights and detect negative cycles. + * **Details** * - * Throws if a negative cycle is detected that affects the path to target. + * Computes distances, reconstructed node paths, and edge-data paths for every + * source and target pair in O(V^3) time. Negative edge weights are allowed, but + * a `GraphError` is thrown if any negative cycle is detected. + * + * **Example** (Finding all-pairs shortest paths) * - * @example * ```ts * import { Graph } from "effect" * @@ -3924,19 +4556,22 @@ export const floydWarshall: { * const pathAToC = result.paths.get(0)?.get(2) // [0, 1, 2] * ``` * - * @since 4.0.0 * @category algorithms + * @since 3.18.0 */ (cost: (edgeData: E) => number): (graph: Graph | MutableGraph) => AllPairsResult /** - * Find shortest paths between all pairs of nodes using Floyd-Warshall algorithm. + * Finds shortest paths between all pairs of nodes using the Floyd-Warshall + * algorithm. * - * Floyd-Warshall algorithm computes shortest paths between all pairs of nodes in O(V³) time. - * It can handle negative edge weights and detect negative cycles. + * **Details** * - * Throws if a negative cycle is detected that affects the path to target. + * Computes distances, reconstructed node paths, and edge-data paths for every + * source and target pair in O(V^3) time. Negative edge weights are allowed, but + * a `GraphError` is thrown if any negative cycle is detected. + * + * **Example** (Finding all-pairs shortest paths) * - * @example * ```ts * import { Graph } from "effect" * @@ -3954,8 +4589,8 @@ export const floydWarshall: { * const pathAToC = result.paths.get(0)?.get(2) // [0, 1, 2] * ``` * - * @since 4.0.0 * @category algorithms + * @since 3.18.0 */ ( graph: Graph | MutableGraph, @@ -3999,6 +4634,15 @@ export const floydWarshall: { next.get(i)!.set(j, j) edgeMatrix.get(i)!.set(j, edgeData.data) } + + if (graph.type === "undirected") { + const reverseWeight = distances.get(j)!.get(i)! + if (weight < reverseWeight) { + distances.get(j)!.set(i, weight) + next.get(j)!.set(i, i) + edgeMatrix.get(j)!.set(i, edgeData.data) + } + } } // Floyd-Warshall main loop @@ -4073,10 +4717,24 @@ export const floydWarshall: { }) /** - * Configuration for A* pathfinding algorithm. + * Configuration for finding a shortest path with the A* algorithm. + * + * **When to use** + * + * Use when configuring `astar` for point-to-point shortest-path searches where + * node data can provide a heuristic estimate toward the target. + * + * **Details** + * + * Specifies the source and target node indices, an edge-cost function, and a + * heuristic that estimates the remaining cost from a node to the target. + * + * @see {@link astar} for the algorithm that consumes this configuration + * @see {@link DijkstraConfig} for shortest paths without a heuristic + * @see {@link BellmanFordConfig} for shortest paths that may include negative edge weights * - * @since 4.0.0 * @category models + * @since 3.18.0 */ export interface AstarConfig { source: NodeIndex @@ -4086,13 +4744,18 @@ export interface AstarConfig { } /** - * Find the shortest path between two nodes using A* pathfinding algorithm. + * Finds the shortest path from the configured source node to the target node + * using the A* pathfinding algorithm. + * + * **Details** * - * A* is an extension of Dijkstra's algorithm that uses a heuristic function to guide - * the search towards the target, potentially finding paths faster than Dijkstra's. - * The heuristic must be admissible (never overestimate the actual cost). + * The edge-cost function must return non-negative weights, and the heuristic + * should be consistent to preserve shortest-path guarantees. Returns + * `Option.none()` when the target is not reachable, and throws a `GraphError` + * when either endpoint is missing or a negative edge cost is encountered. + * + * **Example** (Finding shortest paths with A-star) * - * @example * ```ts * import { Graph } from "effect" * @@ -4123,18 +4786,23 @@ export interface AstarConfig { * } * ``` * - * @since 4.0.0 * @category algorithms + * @since 3.18.0 */ export const astar: { /** - * Find the shortest path between two nodes using A* pathfinding algorithm. + * Finds the shortest path from the configured source node to the target node + * using the A* pathfinding algorithm. * - * A* is an extension of Dijkstra's algorithm that uses a heuristic function to guide - * the search towards the target, potentially finding paths faster than Dijkstra's. - * The heuristic must be admissible (never overestimate the actual cost). + * **Details** + * + * The edge-cost function must return non-negative weights, and the heuristic + * should be consistent to preserve shortest-path guarantees. Returns + * `Option.none()` when the target is not reachable, and throws a `GraphError` + * when either endpoint is missing or a negative edge cost is encountered. + * + * **Example** (Finding shortest paths with A-star) * - * @example * ```ts * import { Graph } from "effect" * @@ -4165,18 +4833,23 @@ export const astar: { * } * ``` * - * @since 4.0.0 * @category algorithms + * @since 3.18.0 */ (config: AstarConfig): (graph: Graph | MutableGraph) => Option.Option> /** - * Find the shortest path between two nodes using A* pathfinding algorithm. + * Finds the shortest path from the configured source node to the target node + * using the A* pathfinding algorithm. + * + * **Details** * - * A* is an extension of Dijkstra's algorithm that uses a heuristic function to guide - * the search towards the target, potentially finding paths faster than Dijkstra's. - * The heuristic must be admissible (never overestimate the actual cost). + * The edge-cost function must return non-negative weights, and the heuristic + * should be consistent to preserve shortest-path guarantees. Returns + * `Option.none()` when the target is not reachable, and throws a `GraphError` + * when either endpoint is missing or a negative edge cost is encountered. + * + * **Example** (Finding shortest paths with A-star) * - * @example * ```ts * import { Graph } from "effect" * @@ -4207,8 +4880,8 @@ export const astar: { * } * ``` * - * @since 4.0.0 * @category algorithms + * @since 3.18.0 */ (graph: Graph | MutableGraph, config: AstarConfig): Option.Option> } = dual(2, ( @@ -4223,6 +4896,8 @@ export const astar: { throw missingNode(config.target) } + const edgeWeights = validateNonNegativeEdgeWeights(graph, config.cost, "A* algorithm") + // Early return if source equals target if (config.source === config.target) { return Option.some({ @@ -4297,13 +4972,8 @@ export const astar: { for (const edgeIndex of adjacencyList) { const edge = graph.edges.get(edgeIndex) if (edge !== undefined) { - const neighbor = edge.target - const weight = config.cost(edge.data) - - // Validate non-negative weights - if (weight < 0) { - throw new GraphError({ message: "A* algorithm requires non-negative edge weights" }) - } + const neighbor = getTraversableNeighbor(graph, currentNode, edge) + const weight = edgeWeights.get(edgeIndex)! const tentativeGScore = currentGScore + weight const neighborGScore = gScore.get(neighbor)! @@ -4362,10 +5032,24 @@ export const astar: { }) /** - * Configuration for Bellman-Ford algorithm. + * Configuration for finding a shortest path with the Bellman-Ford algorithm. + * + * **When to use** + * + * Use when configuring `bellmanFord` to find a shortest path where edge + * weights may be negative. + * + * **Details** + * + * Specifies the source and target node indices, plus a cost function that maps + * each edge's data to a numeric weight. + * + * @see {@link bellmanFord} for the algorithm that consumes this configuration + * @see {@link DijkstraConfig} for non-negative edge costs + * @see {@link AstarConfig} for heuristic shortest-path search * - * @since 4.0.0 * @category models + * @since 3.18.0 */ export interface BellmanFordConfig { source: NodeIndex @@ -4374,13 +5058,17 @@ export interface BellmanFordConfig { } /** - * Find the shortest path between two nodes using Bellman-Ford algorithm. + * Finds the shortest path from the configured source node to the target node + * using the Bellman-Ford algorithm. + * + * **Details** * - * Bellman-Ford algorithm can handle negative edge weights and detects negative cycles. - * It has O(VE) time complexity, slower than Dijkstra's but more versatile. - * Returns Option.none() if a negative cycle is detected that affects the path. + * Negative edge weights are allowed. Returns `Option.none()` when the target is + * unreachable or when a negative cycle affects the path to the target. Throws a + * `GraphError` when either endpoint is missing. + * + * **Example** (Finding shortest paths with Bellman-Ford) * - * @example * ```ts * import { Graph } from "effect" * @@ -4405,18 +5093,22 @@ export interface BellmanFordConfig { * } * ``` * - * @since 4.0.0 * @category algorithms + * @since 3.18.0 */ export const bellmanFord: { /** - * Find the shortest path between two nodes using Bellman-Ford algorithm. + * Finds the shortest path from the configured source node to the target node + * using the Bellman-Ford algorithm. + * + * **Details** + * + * Negative edge weights are allowed. Returns `Option.none()` when the target is + * unreachable or when a negative cycle affects the path to the target. Throws a + * `GraphError` when either endpoint is missing. * - * Bellman-Ford algorithm can handle negative edge weights and detects negative cycles. - * It has O(VE) time complexity, slower than Dijkstra's but more versatile. - * Returns Option.none() if a negative cycle is detected that affects the path. + * **Example** (Finding shortest paths with Bellman-Ford) * - * @example * ```ts * import { Graph } from "effect" * @@ -4441,18 +5133,22 @@ export const bellmanFord: { * } * ``` * - * @since 4.0.0 * @category algorithms + * @since 3.18.0 */ (config: BellmanFordConfig): (graph: Graph | MutableGraph) => Option.Option> /** - * Find the shortest path between two nodes using Bellman-Ford algorithm. + * Finds the shortest path from the configured source node to the target node + * using the Bellman-Ford algorithm. + * + * **Details** * - * Bellman-Ford algorithm can handle negative edge weights and detects negative cycles. - * It has O(VE) time complexity, slower than Dijkstra's but more versatile. - * Returns Option.none() if a negative cycle is detected that affects the path. + * Negative edge weights are allowed. Returns `Option.none()` when the target is + * unreachable or when a negative cycle affects the path to the target. Throws a + * `GraphError` when either endpoint is missing. + * + * **Example** (Finding shortest paths with Bellman-Ford) * - * @example * ```ts * import { Graph } from "effect" * @@ -4477,8 +5173,8 @@ export const bellmanFord: { * } * ``` * - * @since 4.0.0 * @category algorithms + * @since 3.18.0 */ ( graph: Graph | MutableGraph, @@ -4525,6 +5221,14 @@ export const bellmanFord: { weight, edgeData: edgeData.data }) + if (graph.type === "undirected" && edgeData.source !== edgeData.target) { + edges.push({ + source: edgeData.target, + target: edgeData.source, + weight, + edgeData: edgeData.data + }) + } } // Relax edges up to V-1 times @@ -4566,14 +5270,8 @@ export const bellmanFord: { affectedNodes.add(node) // Add all nodes reachable from this node - const adjacencyList = graph.adjacency.get(node) - if (adjacencyList !== undefined) { - for (const edgeIndex of adjacencyList) { - const edge = graph.edges.get(edgeIndex) - if (edge !== undefined) { - queue.push(edge.target) - } - } + for (const neighbor of getTraversalNeighbors(graph, node, "outgoing")) { + queue.push(neighbor) } } @@ -4614,13 +5312,16 @@ export const bellmanFord: { }) /** - * Concrete class for iterables that produce [NodeIndex, NodeData] tuples. + * Represents an iterable wrapper used by graph traversal and listing APIs. + * + * **Details** + * + * A `Walker` yields `[index, data]` pairs lazily and can be viewed as just the + * indices, just the values, or mapped entries with `indices`, `values`, + * `entries`, and `visit`. * - * This class provides a common abstraction for all iterables that return node data, - * including traversal iterators (DFS, BFS, etc.) and element iterators (nodes, externals). - * It uses a mapEntry function pattern for flexible iteration and transformation. + * **Example** (Working with node walkers) * - * @example * ```ts * import { Graph } from "effect" * @@ -4644,8 +5345,8 @@ export const bellmanFord: { * const nodeEntries = Array.from(Graph.entries(allNodes)) // [[0, "A"], [1, "B"]] * ``` * - * @since 4.0.0 * @category models + * @since 3.18.0 */ export class Walker implements Iterable<[T, N]> { // @ts-ignore @@ -4654,11 +5355,14 @@ export class Walker implements Iterable<[T, N]> { /** * Visits each element and maps it to a value using the provided function. * + * **Details** + * * Takes a function that receives the index and data, * and returns an iterable of the mapped values. Skips elements that * no longer exist in the graph. * - * @example + * **Example** (Visiting walker elements) + * * ```ts * import { Graph } from "effect" * @@ -4682,7 +5386,6 @@ export class Walker implements Iterable<[T, N]> { * ``` * * @since 4.0.0 - * @category iterators */ readonly visit: (f: (index: T, data: N) => U) => Iterable @@ -4694,7 +5397,8 @@ export class Walker implements Iterable<[T, N]> { * and returns an iterable of the mapped values. Skips elements that * no longer exist in the graph. * - * @example + * **Example** (Visiting walker elements) + * * ```ts * import { Graph } from "effect" * @@ -4717,8 +5421,8 @@ export class Walker implements Iterable<[T, N]> { * console.log(custom) // [{ id: 0, name: "A" }, { id: 1, name: "B" }] * ``` * - * @since 4.0.0 * @category iterators + * @since 4.0.0 */ visit: (f: (index: T, data: N) => U) => Iterable ) { @@ -4731,8 +5435,16 @@ export class Walker implements Iterable<[T, N]> { * Type alias for node iteration using Walker. * NodeWalker is represented as Walker. * - * @since 4.0.0 + * **When to use** + * + * Use as the shared node walker type returned by graph traversal and node + * listing APIs. + * + * @see {@link Walker} for the generic lazy iterator wrapper + * @see {@link EdgeWalker} for edge iterators + * * @category models + * @since 3.18.0 */ export type NodeWalker = Walker @@ -4740,15 +5452,26 @@ export type NodeWalker = Walker * Type alias for edge iteration using Walker. * EdgeWalker is represented as Walker>. * - * @since 4.0.0 + * **When to use** + * + * Use to type helpers or parameters that consume edge iterators returned by + * `Graph` APIs, where each item is keyed by an `EdgeIndex` and carries the + * full `Edge`. + * + * @see {@link Walker} for the generic lazy iterator wrapper + * @see {@link NodeWalker} for node iterators + * @see {@link edges} for creating edge walkers + * * @category models + * @since 3.18.0 */ export type EdgeWalker = Walker> /** * Returns an iterator over the indices in the walker. * - * @example + * **Example** (Iterating walker indices) + * * ```ts * import { Graph } from "effect" * @@ -4763,15 +5486,16 @@ export type EdgeWalker = Walker> * console.log(indices) // [0, 1] * ``` * - * @since 4.0.0 - * @category utilities + * @category iterators + * @since 3.18.0 */ export const indices = (walker: Walker): Iterable => walker.visit((index, _) => index) /** * Returns an iterator over the values (data) in the walker. * - * @example + * **Example** (Iterating walker values) + * * ```ts * import { Graph } from "effect" * @@ -4786,15 +5510,16 @@ export const indices = (walker: Walker): Iterable => walker.visit * console.log(values) // ["A", "B"] * ``` * - * @since 4.0.0 - * @category utilities + * @category iterators + * @since 3.18.0 */ export const values = (walker: Walker): Iterable => walker.visit((_, data) => data) /** * Returns an iterator over [index, data] entries in the walker. * - * @example + * **Example** (Iterating walker entries) + * * ```ts * import { Graph } from "effect" * @@ -4809,17 +5534,37 @@ export const values = (walker: Walker): Iterable => walker.visit( * console.log(entries) // [[0, "A"], [1, "B"]] * ``` * - * @since 4.0.0 - * @category utilities + * @category iterators + * @since 3.18.0 */ export const entries = (walker: Walker): Iterable<[T, N]> => walker.visit((index, data) => [index, data] as [T, N]) /** - * Configuration options for search iterators. + * Configuration for DFS, BFS, and postorder graph traversals. + * + * **When to use** + * + * Use to configure the starting node indices and edge-following direction for + * lazy graph traversals. + * + * **Details** + * + * `start` supplies the node indices where traversal begins. If it is omitted, + * the iterator is empty. `direction` chooses whether traversal follows + * outgoing or incoming edges. + * + * **Gotchas** + * + * Traversal creation throws a `GraphError` when any configured `start` node + * does not exist. + * + * @see {@link dfs} for depth-first traversal + * @see {@link bfs} for breadth-first traversal + * @see {@link dfsPostOrder} for depth-first postorder traversal * - * @since 4.0.0 * @category models + * @since 3.18.0 */ export interface SearchConfig { readonly start?: Array @@ -4827,12 +5572,17 @@ export interface SearchConfig { } /** - * Creates a new DFS iterator with optional configuration. + * Creates a lazy depth-first traversal iterator from the configured start + * nodes. * - * The iterator maintains a stack of nodes to visit and tracks discovered nodes. - * It provides lazy evaluation of the depth-first search. + * **Details** + * + * If no start nodes are supplied, the iterator is empty. The `direction` option + * chooses whether to follow outgoing or incoming edges. Throws a `GraphError` + * if any configured start node does not exist. + * + * **Example** (Traversing depth-first) * - * @example * ```ts * import { Graph } from "effect" * @@ -4855,17 +5605,22 @@ export interface SearchConfig { * // Can be used programmatically * ``` * - * @since 4.0.0 * @category iterators + * @since 3.18.0 */ export const dfs: { /** - * Creates a new DFS iterator with optional configuration. + * Creates a lazy depth-first traversal iterator from the configured start + * nodes. + * + * **Details** * - * The iterator maintains a stack of nodes to visit and tracks discovered nodes. - * It provides lazy evaluation of the depth-first search. + * If no start nodes are supplied, the iterator is empty. The `direction` option + * chooses whether to follow outgoing or incoming edges. Throws a `GraphError` + * if any configured start node does not exist. + * + * **Example** (Traversing depth-first) * - * @example * ```ts * import { Graph } from "effect" * @@ -4888,17 +5643,22 @@ export const dfs: { * // Can be used programmatically * ``` * - * @since 4.0.0 * @category iterators + * @since 3.18.0 */ (config?: SearchConfig): (graph: Graph | MutableGraph) => NodeWalker /** - * Creates a new DFS iterator with optional configuration. + * Creates a lazy depth-first traversal iterator from the configured start + * nodes. + * + * **Details** + * + * If no start nodes are supplied, the iterator is empty. The `direction` option + * chooses whether to follow outgoing or incoming edges. Throws a `GraphError` + * if any configured start node does not exist. * - * The iterator maintains a stack of nodes to visit and tracks discovered nodes. - * It provides lazy evaluation of the depth-first search. + * **Example** (Traversing depth-first) * - * @example * ```ts * import { Graph } from "effect" * @@ -4921,8 +5681,8 @@ export const dfs: { * // Can be used programmatically * ``` * - * @since 4.0.0 * @category iterators + * @since 3.18.0 */ (graph: Graph | MutableGraph, config?: SearchConfig): NodeWalker } = dual((args) => isGraph(args[0]), ( @@ -4959,7 +5719,7 @@ export const dfs: { continue } - const neighbors = neighborsDirected(graph, current, direction) + const neighbors = getTraversalNeighbors(graph, current, direction) for (let i = neighbors.length - 1; i >= 0; i--) { const neighbor = neighbors[i] if (!discovered.has(neighbor)) { @@ -4979,12 +5739,17 @@ export const dfs: { }) /** - * Creates a new BFS iterator with optional configuration. + * Creates a lazy breadth-first traversal iterator from the configured start + * nodes. + * + * **Details** * - * The iterator maintains a queue of nodes to visit and tracks discovered nodes. - * It provides lazy evaluation of the breadth-first search. + * If no start nodes are supplied, the iterator is empty. The `direction` option + * chooses whether to follow outgoing or incoming edges. Throws a `GraphError` + * if any configured start node does not exist. + * + * **Example** (Traversing breadth-first) * - * @example * ```ts * import { Graph } from "effect" * @@ -5007,17 +5772,22 @@ export const dfs: { * // Can be used programmatically * ``` * - * @since 4.0.0 * @category iterators + * @since 3.18.0 */ export const bfs: { /** - * Creates a new BFS iterator with optional configuration. + * Creates a lazy breadth-first traversal iterator from the configured start + * nodes. * - * The iterator maintains a queue of nodes to visit and tracks discovered nodes. - * It provides lazy evaluation of the breadth-first search. + * **Details** + * + * If no start nodes are supplied, the iterator is empty. The `direction` option + * chooses whether to follow outgoing or incoming edges. Throws a `GraphError` + * if any configured start node does not exist. + * + * **Example** (Traversing breadth-first) * - * @example * ```ts * import { Graph } from "effect" * @@ -5040,17 +5810,22 @@ export const bfs: { * // Can be used programmatically * ``` * - * @since 4.0.0 * @category iterators + * @since 3.18.0 */ (config?: SearchConfig): (graph: Graph | MutableGraph) => NodeWalker /** - * Creates a new BFS iterator with optional configuration. + * Creates a lazy breadth-first traversal iterator from the configured start + * nodes. + * + * **Details** * - * The iterator maintains a queue of nodes to visit and tracks discovered nodes. - * It provides lazy evaluation of the breadth-first search. + * If no start nodes are supplied, the iterator is empty. The `direction` option + * chooses whether to follow outgoing or incoming edges. Throws a `GraphError` + * if any configured start node does not exist. + * + * **Example** (Traversing breadth-first) * - * @example * ```ts * import { Graph } from "effect" * @@ -5073,8 +5848,8 @@ export const bfs: { * // Can be used programmatically * ``` * - * @since 4.0.0 * @category iterators + * @since 3.18.0 */ (graph: Graph | MutableGraph, config?: SearchConfig): NodeWalker } = dual((args) => isGraph(args[0]), ( @@ -5103,7 +5878,7 @@ export const bfs: { if (!discovered.has(current)) { discovered.add(current) - const neighbors = neighborsDirected(graph, current, direction) + const neighbors = getTraversalNeighbors(graph, current, direction) for (const neighbor of neighbors) { if (!discovered.has(neighbor)) { queue.push(neighbor) @@ -5127,10 +5902,26 @@ export const bfs: { }) /** - * Configuration options for topological sort iterator. + * Configuration for the topological sort iterator. + * + * **When to use** + * + * Use to prioritize specific zero in-degree nodes in a topological sort. + * + * **Details** + * + * `initials` optionally supplies zero in-degree node indices used as + * prioritized initial queue entries. Topological sorting still includes the + * other zero in-degree nodes and produces a complete topological order. + * + * **Gotchas** + * + * Throws a `GraphError` when any initial node has incoming edges. + * + * @see {@link topo} for the iterator that consumes this configuration * - * @since 4.0.0 * @category models + * @since 3.18.0 */ export interface TopoConfig { readonly initials?: Array @@ -5139,10 +5930,13 @@ export interface TopoConfig { /** * Creates a new topological sort iterator with optional configuration. * + * **Details** + * * The iterator uses Kahn's algorithm to lazily produce nodes in topological order. * Throws an error if the graph contains cycles. * - * @example + * **Example** (Sorting topologically) + * * ```ts * import { Graph } from "effect" * @@ -5163,7 +5957,7 @@ export interface TopoConfig { * // With initial nodes * const topo2 = Graph.topo(graph, { initials: [0] }) * - * // Throws error for cyclic graph + * // Check before sorting a cyclic graph * const cyclicGraph = Graph.directed((mutable) => { * const a = Graph.addNode(mutable, "A") * const b = Graph.addNode(mutable, "B") @@ -5171,24 +5965,25 @@ export interface TopoConfig { * Graph.addEdge(mutable, b, a, 2) // Creates cycle * }) * - * try { - * Graph.topo(cyclicGraph) // Throws: "Cannot perform topological sort on cyclic graph" - * } catch (error) { - * console.log((error as Error).message) + * if (!Graph.isAcyclic(cyclicGraph)) { + * console.log("cyclic graph") // cyclic graph * } * ``` * - * @since 4.0.0 * @category iterators + * @since 3.18.0 */ export const topo: { /** * Creates a new topological sort iterator with optional configuration. * + * **Details** + * * The iterator uses Kahn's algorithm to lazily produce nodes in topological order. * Throws an error if the graph contains cycles. * - * @example + * **Example** (Sorting topologically) + * * ```ts * import { Graph } from "effect" * @@ -5209,7 +6004,7 @@ export const topo: { * // With initial nodes * const topo2 = Graph.topo(graph, { initials: [0] }) * - * // Throws error for cyclic graph + * // Check before sorting a cyclic graph * const cyclicGraph = Graph.directed((mutable) => { * const a = Graph.addNode(mutable, "A") * const b = Graph.addNode(mutable, "B") @@ -5217,24 +6012,25 @@ export const topo: { * Graph.addEdge(mutable, b, a, 2) // Creates cycle * }) * - * try { - * Graph.topo(cyclicGraph) // Throws: "Cannot perform topological sort on cyclic graph" - * } catch (error) { - * console.log((error as Error).message) + * if (!Graph.isAcyclic(cyclicGraph)) { + * console.log("cyclic graph") // cyclic graph * } * ``` * - * @since 4.0.0 * @category iterators + * @since 3.18.0 */ (config?: TopoConfig): (graph: Graph | MutableGraph) => NodeWalker /** * Creates a new topological sort iterator with optional configuration. * + * **Details** + * * The iterator uses Kahn's algorithm to lazily produce nodes in topological order. * Throws an error if the graph contains cycles. * - * @example + * **Example** (Sorting topologically) + * * ```ts * import { Graph } from "effect" * @@ -5255,7 +6051,7 @@ export const topo: { * // With initial nodes * const topo2 = Graph.topo(graph, { initials: [0] }) * - * // Throws error for cyclic graph + * // Check before sorting a cyclic graph * const cyclicGraph = Graph.directed((mutable) => { * const a = Graph.addNode(mutable, "A") * const b = Graph.addNode(mutable, "B") @@ -5263,21 +6059,23 @@ export const topo: { * Graph.addEdge(mutable, b, a, 2) // Creates cycle * }) * - * try { - * Graph.topo(cyclicGraph) // Throws: "Cannot perform topological sort on cyclic graph" - * } catch (error) { - * console.log((error as Error).message) + * if (!Graph.isAcyclic(cyclicGraph)) { + * console.log("cyclic graph") // cyclic graph * } * ``` * - * @since 4.0.0 * @category iterators + * @since 3.18.0 */ (graph: Graph | MutableGraph, config?: TopoConfig): NodeWalker } = dual((args) => isGraph(args[0]), ( graph: Graph | MutableGraph, config: TopoConfig = {} ): NodeWalker => { + if (graph.type === "undirected") { + throw new GraphError({ message: "Cannot perform topological sort on undirected graph" }) + } + // Check if graph is acyclic first if (!isAcyclic(graph)) { throw new GraphError({ message: "Cannot perform topological sort on cyclic graph" }) @@ -5296,6 +6094,7 @@ export const topo: { [Symbol.iterator]: () => { const inDegree = new Map() const remaining = new Set() + const initialSet = new Set(initials) const queue = [...initials] // Initialize in-degree counts @@ -5310,12 +6109,16 @@ export const topo: { inDegree.set(edgeData.target, currentInDegree + 1) } - // Add nodes with zero in-degree to queue if no initials provided - if (initials.length === 0) { - for (const [nodeIndex, degree] of inDegree) { - if (degree === 0) { - queue.push(nodeIndex) - } + for (const nodeIndex of initials) { + if (inDegree.get(nodeIndex)! !== 0) { + throw new GraphError({ message: `Initial node ${nodeIndex} has incoming edges` }) + } + } + + // Add remaining zero in-degree nodes after prioritized initials. + for (const [nodeIndex, degree] of inDegree) { + if (degree === 0 && !initialSet.has(nodeIndex)) { + queue.push(nodeIndex) } } @@ -5327,7 +6130,11 @@ export const topo: { remaining.delete(current) // Process outgoing edges, reducing in-degree of targets - const neighbors = neighborsDirected(graph, current, "outgoing") + const neighbors = getDirectedNeighbors( + graph as Graph | MutableGraph, + current, + "outgoing" + ) for (const neighbor of neighbors) { if (remaining.has(neighbor)) { const currentInDegree = inDegree.get(neighbor) || 0 @@ -5358,13 +6165,17 @@ export const topo: { }) /** - * Creates a new DFS postorder iterator with optional configuration. + * Creates a lazy depth-first postorder traversal iterator from the configured + * start nodes. + * + * **Details** + * + * Nodes are emitted after their reachable descendants have been processed. If + * no start nodes are supplied, the iterator is empty. The `direction` option + * chooses whether to follow outgoing or incoming edges. * - * The iterator maintains a stack with visit state tracking and emits nodes - * in postorder (after all descendants have been processed). Essential for - * dependency resolution and tree destruction algorithms. + * **Example** (Traversing in postorder) * - * @example * ```ts * import { Graph } from "effect" * @@ -5383,18 +6194,22 @@ export const topo: { * } * ``` * - * @since 4.0.0 * @category iterators + * @since 3.18.0 */ export const dfsPostOrder: { /** - * Creates a new DFS postorder iterator with optional configuration. + * Creates a lazy depth-first postorder traversal iterator from the configured + * start nodes. + * + * **Details** * - * The iterator maintains a stack with visit state tracking and emits nodes - * in postorder (after all descendants have been processed). Essential for - * dependency resolution and tree destruction algorithms. + * Nodes are emitted after their reachable descendants have been processed. If + * no start nodes are supplied, the iterator is empty. The `direction` option + * chooses whether to follow outgoing or incoming edges. + * + * **Example** (Traversing in postorder) * - * @example * ```ts * import { Graph } from "effect" * @@ -5413,18 +6228,22 @@ export const dfsPostOrder: { * } * ``` * - * @since 4.0.0 * @category iterators + * @since 3.18.0 */ (config?: SearchConfig): (graph: Graph | MutableGraph) => NodeWalker /** - * Creates a new DFS postorder iterator with optional configuration. + * Creates a lazy depth-first postorder traversal iterator from the configured + * start nodes. * - * The iterator maintains a stack with visit state tracking and emits nodes - * in postorder (after all descendants have been processed). Essential for - * dependency resolution and tree destruction algorithms. + * **Details** + * + * Nodes are emitted after their reachable descendants have been processed. If + * no start nodes are supplied, the iterator is empty. The `direction` option + * chooses whether to follow outgoing or incoming edges. + * + * **Example** (Traversing in postorder) * - * @example * ```ts * import { Graph } from "effect" * @@ -5443,8 +6262,8 @@ export const dfsPostOrder: { * } * ``` * - * @since 4.0.0 * @category iterators + * @since 3.18.0 */ (graph: Graph | MutableGraph, config?: SearchConfig): NodeWalker } = dual((args) => isGraph(args[0]), ( @@ -5483,7 +6302,7 @@ export const dfsPostOrder: { if (!current.visitedChildren) { current.visitedChildren = true - const neighbors = neighborsDirected(graph, current.node, direction) + const neighbors = getTraversalNeighbors(graph, current.node, direction) for (let i = neighbors.length - 1; i >= 0; i--) { const neighbor = neighbors[i] @@ -5517,10 +6336,13 @@ export const dfsPostOrder: { /** * Creates an iterator over all node indices in the graph. * + * **Details** + * * The iterator produces node indices in the order they were added to the graph. * This provides access to all nodes regardless of connectivity. * - * @example + * **Example** (Iterating all nodes) + * * ```ts * import { Graph } from "effect" * @@ -5535,8 +6357,8 @@ export const dfsPostOrder: { * console.log(indices) // [0, 1, 2] * ``` * - * @since 4.0.0 * @category iterators + * @since 3.18.0 */ export const nodes = ( graph: Graph | MutableGraph @@ -5562,10 +6384,13 @@ export const nodes = ( /** * Creates an iterator over all edge indices in the graph. * + * **Details** + * * The iterator produces edge indices in the order they were added to the graph. * This provides access to all edges regardless of connectivity. * - * @example + * **Example** (Iterating all edges) + * * ```ts * import { Graph } from "effect" * @@ -5581,8 +6406,8 @@ export const nodes = ( * console.log(indices) // [0, 1] * ``` * - * @since 4.0.0 * @category iterators + * @since 3.18.0 */ export const edges = ( graph: Graph | MutableGraph @@ -5606,23 +6431,40 @@ export const edges = ( })) /** - * Configuration for externals iterator. + * Configuration for selecting external nodes. + * + * **When to use** + * + * Use to configure how `externals` identifies graph boundary nodes when you + * need sinks with no outgoing edges or sources with no incoming edges. + * + * **Details** + * + * `direction` chooses which missing edge direction makes a node external: + * `"outgoing"` selects nodes with no outgoing edges, and `"incoming"` selects + * nodes with no incoming edges. If omitted, `direction` defaults to + * `"outgoing"`. + * + * @see {@link externals} for the iterator that consumes this configuration * - * @since 4.0.0 * @category models + * @since 3.18.0 */ export interface ExternalsConfig { readonly direction?: Direction } /** - * Creates an iterator over external nodes (nodes without edges in specified direction). + * Creates an iterator over external nodes (nodes without edges in the specified direction). + * + * **Details** * - * External nodes are nodes that have no outgoing edges (direction="outgoing") or - * no incoming edges (direction="incoming"). These are useful for finding + * External nodes have no outgoing edges (`direction: "outgoing"`) or no + * incoming edges (`direction: "incoming"`). These are useful for finding * sources, sinks, or isolated nodes. * - * @example + * **Example** (Iterating external nodes) + * * ```ts * import { Graph } from "effect" * @@ -5649,18 +6491,21 @@ export interface ExternalsConfig { * console.log(sources) // [0, 3] * ``` * - * @since 4.0.0 * @category iterators + * @since 3.18.0 */ export const externals: { /** - * Creates an iterator over external nodes (nodes without edges in specified direction). + * Creates an iterator over external nodes (nodes without edges in the specified direction). * - * External nodes are nodes that have no outgoing edges (direction="outgoing") or - * no incoming edges (direction="incoming"). These are useful for finding + * **Details** + * + * External nodes have no outgoing edges (`direction: "outgoing"`) or no + * incoming edges (`direction: "incoming"`). These are useful for finding * sources, sinks, or isolated nodes. * - * @example + * **Example** (Iterating external nodes) + * * ```ts * import { Graph } from "effect" * @@ -5687,18 +6532,21 @@ export const externals: { * console.log(sources) // [0, 3] * ``` * - * @since 4.0.0 * @category iterators + * @since 3.18.0 */ (config?: ExternalsConfig): (graph: Graph | MutableGraph) => NodeWalker /** - * Creates an iterator over external nodes (nodes without edges in specified direction). + * Creates an iterator over external nodes (nodes without edges in the specified direction). + * + * **Details** * - * External nodes are nodes that have no outgoing edges (direction="outgoing") or - * no incoming edges (direction="incoming"). These are useful for finding + * External nodes have no outgoing edges (`direction: "outgoing"`) or no + * incoming edges (`direction: "incoming"`). These are useful for finding * sources, sinks, or isolated nodes. * - * @example + * **Example** (Iterating external nodes) + * * ```ts * import { Graph } from "effect" * @@ -5725,8 +6573,8 @@ export const externals: { * console.log(sources) // [0, 3] * ``` * - * @since 4.0.0 * @category iterators + * @since 3.18.0 */ (graph: Graph | MutableGraph, config?: ExternalsConfig): NodeWalker } = dual((args) => isGraph(args[0]), (