> ## Documentation Index
> Fetch the complete documentation index at: https://docs.sightmap.org/llms.txt
> Use this file to discover all available pages before exploring further.

# Use Sightmap as a Go Library

> Import the same corpus loading, selector matching, and CDP client that power the sightmap CLI into your own Go tools.

The module `github.com/sightmap/sightmap/go` is the reference implementation behind the `sightmap` CLI — and it's importable. Consumers such as snapshot enrichers, analysis scripts, and custom agents use the library directly instead of re-implementing component matching, so semantics can't diverge between tools.

```bash theme={null}
go get github.com/sightmap/sightmap/go
```

Requires **Go 1.25.2+**.

## Design goals

* **One canonical component model and rule matcher.** Downstream consumers import this library rather than re-implementing matching.
* **Tree-level matching, not DOM queries.** Matching operates against a component tree — every node carries a `SelectorPart` — rather than via `document.querySelectorAll`. That enables offline analysis of exported snapshots and native-mobile compatibility via synthetic selectors.
* **One canonical probe.** The browser-side extractor (`cdp-probe.js`) is embedded once, in the `probe` package; consumers embed it from there so bounds, visibility, and interactivity logic cannot diverge.

## Package map

All import paths are rooted at `github.com/sightmap/sightmap/go/`.

| Package       | Purpose                                                                                                                         |
| ------------- | ------------------------------------------------------------------------------------------------------------------------------- |
| `sightmap`    | Corpus loading, thread-safe `Session` matching cache, `Validate` and `Lint`                                                     |
| `comps`       | Canonical component model types — `ComponentNode`, `SelectorPart`, `Bounds` — and tree operations (`Walk`, `Collect`, `Filter`) |
| `sel`         | CSS selector parsing and single-node matching for the sightmap selector subset                                                  |
| `match`       | NFA multi-query matcher — applies every component definition in a single tree traversal                                         |
| `extract`     | Post-probe pipeline: merges accessibility data into probe output and rebuilds the tree; no browser dependency                   |
| `browser`     | Minimal `Page` interface plus a direct-CDP client for any Chrome debugging port (no chromedp)                                   |
| `compquery`   | The component-query DSL engine — resolves queries like `ProductCard[name^="Weber"]` against extracted trees                     |
| `probe`       | The embedded canonical `cdp-probe.js` browser-side extractor                                                                    |
| `render`      | Tree rendering for snapshot- and inspect-style output                                                                           |
| `conformance` | Shared cross-implementation fixtures verifying identical matching semantics                                                     |

## Load a corpus and match a tree

The core flow is three calls: `DirLoader` points at a `.sightmap/` directory, `NewSession` wraps it in a compiled-query cache, and `MatchTree` applies the corpus to a component tree for a page URL.

```go main.go theme={null}
package main

import (
	"encoding/json"
	"fmt"
	"log"
	"os"

	"github.com/sightmap/sightmap/go/comps"
	"github.com/sightmap/sightmap/go/sightmap"
)

func main() {
	// Load every YAML file under .sightmap/ (lazily, on first use).
	sess := sightmap.NewSession(sightmap.DirLoader(".sightmap"))

	// Read a component tree saved by `sightmap snapshot --tree-out`.
	data, err := os.ReadFile("home.snap.tree.json")
	if err != nil {
		log.Fatal(err)
	}
	root := &comps.ComponentNode{}
	if err := json.Unmarshal(data, root); err != nil {
		log.Fatal(err)
	}

	// Apply the corpus to the tree for this page URL.
	matches, err := sess.MatchTree(root, "https://example.com/")
	if err != nil {
		log.Fatal(err)
	}

	// Walk the tree and print every matched node.
	comps.Walk(root, func(n *comps.ComponentNode, depth int) bool {
		if m := matches[n]; m != nil {
			fmt.Printf("%s -> [%s]\n", n.Role, m.Name)
		}
		return true
	})
}
```

`MatchTree` returns `map[*comps.ComponentNode]*match.SightmapMatch` — each match carries the component `Name` and its `Memory` notes. The view is selected from the URL's pathname using the same most-specific-wins route matching the CLI uses; if no view matches, global components still apply.

## Sessions

`sightmap.Session` is safe for concurrent use. It caches compiled match queries per (corpus generation, page URL) pair, so repeated `MatchTree` calls against the same URL are cheap. Useful methods beyond `MatchTree`:

| Method                   | Purpose                                                                                 |
| ------------------------ | --------------------------------------------------------------------------------------- |
| `Refresh()`              | Reload the corpus and invalidate the cache — call after `.sightmap/` YAML edits         |
| `Components(pageURL)`    | The merged component list for a URL, without needing a tree                             |
| `ViewForURL(pageURL)`    | The matching `View` (name, route, memory, capture URLs), or `nil` if only globals apply |
| `GlobalComponentNames()` | The set of names declared at global scope                                               |

Besides `DirLoader`, the package provides `StaticLoader` (wrap an already-built `*Corpus`) and `LoaderFunc` (adapt any `func() (*Corpus, error)`) — handy for tests and for corpora that don't live on disk.

## Validate and lint from Go

The same checks behind `sightmap validate` and `sightmap lint` are plain functions:

```go theme={null}
corpus, err := sightmap.DirLoader(".sightmap").Load()
if err != nil {
	log.Fatal(err)
}
for _, e := range sightmap.Validate(corpus) {
	fmt.Println("error:", e)
}
for _, w := range sightmap.Lint(corpus) {
	fmt.Println("warning:", w)
}
```

`LintWithCounts` augments lint with real per-component match counts from a snapshot, which is how `sightmap lint --snapshot` works.

## Where component trees come from

* **Saved captures** — every capture under `.sightmap/snapshots/{view}/` has a sibling `.snap.tree.json` file holding the raw `ComponentNode` tree; `sightmap snapshot --tree-out FILE` writes one anywhere you like. Unmarshal it straight into `*comps.ComponentNode` as in the example above.
* **Live pages** — the `browser` package dials a Chrome debugging port (`DialCDP`), and `ExtractComponents` runs the embedded probe against a page to produce the same tree shape.
* **Your own extraction** — the `extract` package builds a tree from raw probe and accessibility data with no browser dependency, and native consumers can synthesize `SelectorPart` values for non-DOM trees.

<Note>
  The `conformance` package ships tree-plus-corpus fixtures with expected matches. If you build a matching consumer in another language, run them to prove your semantics agree with the reference implementation — see [Conformance fixtures](/reference/conformance-fixtures).
</Note>

## Related

* [CLI overview](/cli/overview) — the command-line surface built on these packages
* [Curator vs. consumer](/concepts/curator-vs-consumer) — where a library consumer fits in the ecosystem
* [Schema reference](/reference/schema) — the YAML contract the loader reads
