npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@tscircuit/circuit-json-util

v0.0.135

Published

Utility library for working with tscircuit circuit json

Downloads

458,670

Readme

@tscircuit/circuit-json-util

Previously released as @tscircuit/soup-util

This is a small utility library for working with circuit json

It reduces the amount of code to retrieve or join elements from circuit json, it also neatly handles all the typing.

Exported API

| Function | Defined in | Description | | --- | --- | --- | | cju | lib/cju.ts | Creates the primary circuit-json utility object for querying and mutating circuit json arrays. | | su | lib/cju.ts | Alias for cju. | | cjuIndexed | lib/cju-indexed.ts | Creates an indexed utility optimized for large circuit-json datasets. | | transformSchematicElement | lib/transform-soup-elements.ts | Applies a transformation matrix to a single schematic element. | | transformSchematicElements | lib/transform-soup-elements.ts | Applies a transformation matrix to schematic elements in a soup. | | transformPCBElement | lib/transform-soup-elements.ts | Applies a transformation matrix to a single PCB element. | | transformPCBElements | lib/transform-soup-elements.ts | Applies a transformation matrix to PCB elements in a soup. | | transformPcbElement | lib/transform-soup-elements.ts | Alias export for transformPCBElement. | | transformPcbElements | lib/transform-soup-elements.ts | Alias export for transformPCBElements. | | directionToVec | lib/direction-to-vec.ts | Converts a cardinal direction to a vector. | | vecToDirection | lib/direction-to-vec.ts | Converts a vector to its nearest cardinal direction. | | rotateClockwise | lib/direction-to-vec.ts | Rotates a cardinal direction clockwise. | | rotateCounterClockwise | lib/direction-to-vec.ts | Rotates a cardinal direction counter-clockwise. | | rotateDirection | lib/direction-to-vec.ts | Rotates a direction by one or more quarter turns. | | oppositeDirection | lib/direction-to-vec.ts | Returns the opposite cardinal direction. | | oppositeSide | lib/direction-to-vec.ts | Returns the opposite side string (left/right/top/bottom). | | applySelector | lib/apply-selector.ts | Applies a selector string to circuit-json elements. | | applySelectorAST | lib/apply-selector.ts | Applies a parsed selector AST to circuit-json elements. | | getElementById | lib/get-element-by-id.ts | Finds an element by its primary id field. | | getElementId | lib/get-element-id.ts | Returns an element's primary id value. | | getReadableNameForElement | lib/readable-name-functions/get-readable-name-for-element.ts | Produces a human-readable label for an element. | | getReadableNameForPcbPort | lib/readable-name-functions/get-readable-name-for-pcb-port.ts | Produces a readable label for a PCB port. | | getReadableNameForPcbSmtpad | lib/readable-name-functions/get-readable-name-for-pcb-smtpad.ts | Produces a readable label for a PCB SMT pad. | | getReadableNameForPcbTrace | lib/readable-name-functions/get-readable-name-for-pcb-trace.ts | Produces a readable label for a PCB trace. | | getBoundsOfPcbElements | lib/get-bounds-of-pcb-elements.ts | Computes aggregate XY bounds for PCB elements. | | getPcbElementBounds | lib/get-bounds-of-pcb-elements.ts | Computes the axis-aligned XY bounds of one PCB element. | | getPcbElementsWithinBounds | lib/get-bounds-of-pcb-elements.ts | Selects PCB elements whose bounds intersect a region. | | getBoardBounds | lib/get-board-bounds.ts | Computes board bounds/size from width+height+center, or from outline points. | | getSchematicElementBounds | lib/get-schematic-element-bounds.ts | Computes the axis-aligned bounds of a schematic component, net label, or trace. | | findBoundsAndCenter | lib/find-bounds-and-center.ts | Computes bounds and center for a set of points. | | getPrimaryId | lib/get-primary-id.ts | Returns the name of an element type's primary id field. | | buildSubtree | lib/subtree.ts | Builds a relation-aware subtree from selected root elements. | | repositionPcbComponentTo | lib/reposition-pcb-component.ts | Repositions a PCB component and its linked PCB primitives. | | repositionPcbGroupTo | lib/reposition-pcb-group.ts | Repositions all PCB elements in a source group. | | repositionSchematicComponentTo | lib/reposition-schematic-component.ts | Repositions a schematic component and linked schematic primitives. | | repositionSchematicGroupTo | lib/reposition-schematic-group.ts | Repositions all schematic elements in a source group. | | getCircuitJsonTree | lib/getCircuitJsonTree.ts | Builds a tree representation of relation-linked circuit-json elements. | | getStringFromCircuitJsonTree | lib/getStringFromCircuitJsonTree.ts | Renders a circuit-json tree as text for debugging. | | getMinimumFlexContainer | lib/get-minimum-flex-container.ts | Computes a minimum flex container from layout constraints. | | getElementRenderLayers | lib/get-element-render-layers.ts | Returns schematic/PCB render layers used for an element. | | computeClearanceBetweenElements | lib/compute-clearance-between-elements.ts | Computes the minimum edge-to-edge clearance between two circuit elements using geometric decomposition. | | computeGapBetweenCopper | lib/compute-gap-between-copper.ts | Computes the minimum copper-to-copper gap between two circuit elements by decomposing them into primitive shapes. | | analyzePcbPin1Location | lib/analyze-pcb-pin1-location.ts | Infers a semantic pin 1 location from PCB pad geometry and numeric port hints. | | categorizeErrorOrWarning | lib/categorize-error-or-warning.ts | Categorizes DRC error/warning types into "netlist", "pin_specification", "placement", "routing", "source", or "unknown". | | getPourPolygon | lib/copper-geometry.ts | Converts rectangular, polygon, or BRep pours into copper polygons, preserving cutouts and bulge arcs. | | getSmtPadPolygon | lib/copper-geometry.ts | Converts SMT pad outlines into copper polygons. | | getPlatedHolePolygon | lib/copper-geometry.ts | Converts plated pads into copper polygons with drilled holes excluded. | | getViaPolygon | lib/copper-geometry.ts | Creates an annular copper polygon from a center and outer/hole diameters. | | getTraceSegmentPolygon | lib/copper-geometry.ts | Creates the convex hull of two endpoint disks, with equal or differing widths. | | copperPolygonsTouch | lib/copper-geometry.ts | Tests polygon contact or containment while respecting holes. | | placePolygon | lib/copper-geometry.ts | Rotates a polygon counterclockwise, then translates it to its board position. | | circlePolygon | lib/copper-geometry.ts | Creates a circular polygon with analytic arcs. | | roundedRectangle | lib/copper-geometry.ts | Creates a positioned and optionally rotated rectangle with rounded corners. |

Copper geometry

These helpers return Polygon objects from @flatten-js/core. Coordinates are PCB board-world points in millimeters, with +X right, +Y up, and counterclockwise rotation in degrees. Polygon plated-pad outlines are footprint-local offsets; getPlatedHolePolygon(pad, componentRotation) places them in board coordinates using the pad's rotation, or the supplied component rotation when omitted.

import { copperPolygonsTouch, getPlatedHolePolygon, getPourPolygon } from "@tscircuit/circuit-json-util"

const touches = copperPolygonsTouch(
  getPourPolygon(pour),
  getPlatedHolePolygon(platedHole),
)

Callers must check net membership and shared copper layers themselves: these helpers operate only on planar geometry. copperPolygonsTouch uses a default numerical tolerance of 1e-7 mm, not a manufacturing clearance. If callers scale the polygons, they must scale that tolerance by the same factor. The helpers do not modify their circuit-json inputs or generate routes.

Standard Usage

import { su } from "@tscircuit/circuit-json-util"

const circuitJson = [
  /* [ { type: "source_component", ... }, ... ] */
]

const pcb_component = su(circuitJson).pcb_component.get("1234")

const source_component = su(circuitJson).source_component.getUsing({
  pcb_component_id: "123",
})

const schematic_component = su(circuitJson).schematic_component.getWhere({
  width: 1,
})

const source_traces = su(circuitJson).source_trace.list({
  source_component_id: "123",
})

Optimized Indexed Version

For large circuit json, the library provides an optimized version with indexing for faster lookups:

import { cjuIndexed } from "@tscircuit/circuit-json-util"

const circuitJson = [
  /* large soup with many elements */
]

// Configure the indexes you want to use
const indexedSu = cjuIndexed(circuitJson, {
  indexConfig: {
    byId: true, // Index by element ID for fast .get() operations
    byType: true, // Index by element type for fast .list() operations
    byRelation: true, // Index relation fields (fields ending with _id)
    bySubcircuit: true, // Index by subcircuit_id for fast subcircuit filtering
    byCustomField: ["name", "ftype"], // Index specific fields you query often
  },
})

// Use the same API as the standard version, but with much better performance
const pcb_component = indexedSu.pcb_component.get("1234") // O(1) lookup

// Fast filtering by subcircuit
const subcircuitElements = indexedSu.source_component.list({
  subcircuit_id: "main",
})

The indexed version supports root-level insert, insertAll, and subtree as well as table operations. Root inserts assign IDs, including when an input supplies an ID, just like cju. Subtrees preserve the indexing and validation options and have their own collection; existing element objects are shared with the parent. list() returns a new array, so sorting or splicing it cannot modify the store's type index. The elements in that array remain live objects.

Categorize DRC Errors and Warnings

Use categorizeErrorOrWarning to map DRC result types to high-level check categories.

import { categorizeErrorOrWarning } from "@tscircuit/circuit-json-util"

categorizeErrorOrWarning("source_pin_must_be_connected_error") // "netlist"
categorizeErrorOrWarning("source_property_ignored_warning") // "source"
categorizeErrorOrWarning("source_no_power_pin_defined_warning") // "pin_specification"
categorizeErrorOrWarning({ error_type: "pcb_trace_error" }) // "routing"
categorizeErrorOrWarning({
  warning_type: "pcb_connector_not_in_accessible_orientation_warning",
}) // "placement"
categorizeErrorOrWarning("some_future_error_type") // "unknown"

Repositioning PCB Components

Use repositionPcbComponentTo to move a component and all of its related elements to a new center:

import { repositionPcbComponentTo } from "@tscircuit/circuit-json-util"

repositionPcbComponentTo(circuitJson, "pc1", { x: 10, y: 5 })

All ports, pads and traces referencing the component are translated by the same offset.

Use repositionSchematicComponentTo to move a schematic component and all related elements:

import { repositionSchematicComponentTo } from "@tscircuit/circuit-json-util"

repositionSchematicComponentTo(circuitJson, "sc1", { x: 10, y: 5 })

Move all elements in a schematic source group with repositionSchematicGroupTo:

import { repositionSchematicGroupTo } from "@tscircuit/circuit-json-util"

repositionSchematicGroupTo(circuitJson, "g1", { x: 20, y: 15 })

Compute Copper Gap

Use computeGapBetweenCopper to calculate the minimum copper clearance between two PCB elements.

It decomposes each element into primitive shapes (circle, rect, polygon) and returns the minimum distance across all shape-pair combinations. If an element does not produce any supported copper shapes, the function returns Infinity.

import { computeGapBetweenCopper } from "@tscircuit/circuit-json-util"

const gap = computeGapBetweenCopper(
  {
    type: "pcb_smtpad",
    pcb_smtpad_id: "pad1",
    shape: "circle",
    x: 0,
    y: 0,
    radius: 0.5,
    layer: "top",
  },
  {
    type: "pcb_smtpad",
    pcb_smtpad_id: "pad2",
    shape: "rect",
    x: 2,
    y: 0,
    width: 1,
    height: 1,
    layer: "top",
  },
)

console.log(gap) // 1

Currently supported decomposition targets include pcb_smtpad (circle/rect/polygon), pcb_trace wire segments, pcb_via, and pcb_plated_hole.