@trackunit/repo-checks
v0.0.83
Published
Repository-level checks for Trackunit repositories, run over the whole repo rather than per file.
Keywords
Readme
@trackunit/repo-checks
Repository-level checks for Trackunit repositories, run over the whole repo rather than per file.
This package is for Trackunit internal usage.
Checks
Doc references
doc-references reads every .md and .mdx document in the repository (extension in any case) and reports file references whose target or #anchor doesn't exist. A reference is a link, an image, or a link reference definition, plus inline code when constructs.inlineCode is on.
It aims for zero false positives: a reference it can't resolve with certainty is skipped, never reported. Each reference gives at most one finding, with one of three reasons: missing, caseMismatch, or missingAnchor, which covers both an anchor in another document and one in the same document. For a document docs/index.md next to a docs/guide.md that has a ## Installation heading:
# Index
## Overview
[setup](./setup.md)
[guide](./Guide.md)
[install](./guide.md#instalation)
[overview](#overveiw)docs/index.md:5:1 ./setup.md missing
docs/index.md:6:1 ./Guide.md caseMismatch did you mean ./guide.md
docs/index.md:7:1 ./guide.md#instalation missingAnchor
docs/index.md:8:1 #overveiw missingAnchor| Reason | Meaning |
| --------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| missing | The target doesn't exist, or exists as the wrong kind: a target with a file extension must be a file, one ending in / must be a directory. A target outside the repository is missing even if it exists on your machine. |
| caseMismatch | The target exists only under different letter case. This passes on macOS but breaks on Linux CI and GitHub, so it is decided case-exactly on every filesystem. did you mean gives the on-disk casing when exactly one rewrite is known; it's omitted when siblings differ only by case, when the reference has placeholders, or when a segment to recase is percent-encoded. |
| missingAnchor | The target exists, but its #fragment names no heading or anchor in it (a cross-document anchor). |
| missingAnchor | A fragment-only link (#overveiw) names no heading or anchor in its own document (a same-document anchor). |
Links resolve relative to the document, and a leading / from the repository root. Inline code tries the document's directory, then the repository root. A URL's ?query and #fragment are stripped and it is percent-decoded before it is resolved.
What is never checked
These are categorically not repository paths, so they are skipped whatever the config says:
- anything with a URL scheme (
https://,mailto:,file:) or starting with//; - container and registry images, such as
ghcr.io/org/image:1.2orlocalhost:5000/app@sha256:...; - home-directory paths starting with
~(~/.npmrc); - globs: anything containing
*(libs/**/README.md); - shell variables: anything containing
$($HOME/bin,${DIR}/x.md); - multi-word spans: anything containing whitespace, such as an inline-code command;
- Storybook links with a
?path=query (see Storybook links); - code blocks, fenced or indented, and frontmatter, which are never read for references; in
.mdx, ESM (import/export),{expressions}, and JSX attributes aren't read either, though markdown in JSX children is; - references whose shape isn't a path under the current options (see
directoriesandbareFilenames).
Anchors
A fragment matches when it names, case-insensitively and percent-decoded:
- a heading slugged as GitHub does, with
-1,-2for repeats, or a heading's custom{#id}; - an HTML
id=orname=attribute, the text of an HTML<h1>-<h6>, or a stringid/nameon an.mdxJSX element; - a footnote, as GitHub renders it (
fn-<label>,fnref-<label>); - any of these behind GitHub's
user-content-prefix; top, or a GitHub line reference such as#L10or#L10C2-L12C5.
Fragments are checked only into .md and .mdx targets. A fragment is never reported when its target's anchors can't be known for certain:
- the target is larger than 1 MiB, or can't be read or parsed;
- the reference has placeholders, so the target is one arbitrary match;
- the fragment is itself a placeholder under the configured
placeholders(#<name>,#{name},#{{name}},#:name), whether fragment-only or after a path (./guide.md#<name>); the path is still checked, and with a convention removed fromplaceholdersits fragments are checked as literal anchors; - the target, or for a fragment-only link the document itself, is an
.mdxdocument whose rendered page may have anchors parsing can't see. That is an.mdxdocument with any ESM (import,export), a component or custom element (<Meta>,<Title />,<doc-toc>), a JSX<h1>-<h6>, a JSX spread or{expression}attribute value, an{expression}holding code (including in a heading,# Hi {name}), YAML frontmatter, or a footnote reference inside a heading. Comment-only{/* ... */}expressions and built-in HTML elements with string attributes don't count.
Exists on disk
Targets are checked against the working tree, not the git index. A gitignored or uncommitted file counts as present, so a link to a file you haven't committed yet, or to one a setup script generates, passes locally and fails in a fresh CI checkout. Commit the target with the link.
Documents are found with git ls-files: tracked and untracked files, minus gitignored ones, that exist on disk. Outside a git work tree the checker walks the file system instead, skipping .git, node_modules, dist, build, and coverage.
Storybook links
storybook-links finds .md and .mdx documents as doc-references does and reports Storybook links whose ID is in none of the Storybook indexes you pass with --index, or is there only as the other entry type. A Storybook link is a link, an image, or a link reference definition whose target is a ?path=/docs/<id> or ?path=/story/<id> query, possibly beside other query parameters, either:
- relative: the query alone or after
/,./, or../(../?path=/story/<id>); - absolute on a checked host, by default only
design.iris.trackunit.com(seehosts):https://design.iris.trackunit.com/?path=/docs/<id>, also with a base path such as a feature-branch deployment (https://design.iris.trackunit.com/<branch>/?path=/docs/<id>) and withhttp://. The host matches case-insensitively, and only on the scheme's default port.
For a document docs/index.md and an index with a components-button--docs docs entry and a components-button--default story, but no components-button--primary:
# Index
[button](?path=/story/components-button--primary)
[button docs](?path=/docs/components-button--docs)
[default button](?path=/docs/components-button--default)
[deployed](https://design.iris.trackunit.com/?path=/story/components-button--primary)docs/index.md:3:1 ?path=/story/components-button--primary unknownStoryId
docs/index.md:5:1 ?path=/docs/components-button--default wrongStoryType did you mean ?path=/story/components-button--default
docs/index.md:6:1 https://design.iris.trackunit.com/?path=/story/components-button--primary unknownStoryId| Reason | Meaning |
| ---------------- | ------------------------------------------------------------------------------ |
| unknownStoryId | The <id> in ?path=/<type>/<id> is an entry in none of the --index files. |
| wrongStoryType | The <id> is an entry only of the other type: a /docs/ link to a story, or a /story/ link to a docs page. did you mean gives the link with /docs/ and /story/ swapped, keeping any host, base path, and other query parameters; it's omitted when the path=/docs/ or path=/story/ prefix is percent-encoded. |
An ID found in any of the indexes passes, since no single Storybook covers every ID; it passes as either type it has in any of them.
Not checked:
- links with a
#fragment, relative or absolute; - absolute URLs on a host that isn't checked (a third-party Storybook can't be checked against our indexes), with a non-default port or credentials, or with a scheme other than
http:andhttps:, and protocol-relative URLs (//design.iris.trackunit.com/?path=...); - absolute URLs whose path names a file other than
index.html, such asiframe.html?id=<id>; - code blocks, inline code, frontmatter, and in
.mdxESM,{expressions}, and JSX attributes, as fordoc-references; .tsand.tsxfiles, such as theparameters.docsof a story;- HTML
<a href>and other raw HTML; - query paths in other shapes, such as
docs/?path=or a/Docs/type.
The storybookLinks config section sets the checked hosts, documents to skip, and IDs never reported. To skip the links on one line, put a storybook-links-ignore-next-line comment above it; doc-references-ignore-next-line doesn't affect storybook-links.
AI agents should use the machine-readable index at /llms.txt instead of the Storybook HTML; it links to per-component docs at /ai?storyId=<id>.
Producing an index
storybook index writes the index without building Storybook:
npx storybook index -c <configDir> -o <file><configDir> is the Storybook's config directory (the one with main.ts). Pass one --index per Storybook your documents link to.
Running it
CLI
npx @trackunit/repo-checks doc-references [--root <dir>] [--format text|json]| Flag | Default | Meaning |
| ----------------- | ------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| --root <dir> | the repository root of the current directory (the current directory outside a repository) | The directory whose documents are checked. A subdirectory checks only the documents below it; paths in findings stay relative to the repository root. |
| --format <fmt> | text | text: one file:line:col target reason[ did you mean <path>] line per finding, nothing when clean. json: an array of findings with file, line, column, target, kind (link, image, definition, inlineCode), reason, and suggestion when known; [] when clean. |
| --help, -h | | Print usage. |
npx @trackunit/repo-checks storybook-links --index <file> [--index <file>...] [--root <dir>] [--format text|json]storybook-links takes --root and --format as above, plus:
| Flag | Default | Meaning |
| ---------------- | ------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| --index <file> | | Required, repeatable: a storybook index output file. The IDs of every given index are combined. A relative path resolves against the current directory, not --root. |
Findings are sorted by file, line, and column, so the output is the same on every host.
Exit codes
| Code | Meaning |
| ---- | ----------------------------------------------------------------------------------------------------------------------------------------------- |
| 0 | No findings. |
| 1 | One or more findings. |
| 2 | The check couldn't run: a usage error, an invalid config, a document that can't be parsed (an .mdx that isn't valid MDX), or an unreadable path. For storybook-links, also no --index, or an index that is missing, unreadable, not valid JSON, or not shaped like a storybook index output. |
In manager
yarn nx run platform-test:doc-referencesThe same spec runs in yarn nx run platform-test:test, so a broken reference fails the pull request. On master, "Test on master" skips it (SKIP_DOC_REFERENCES=true), and a separate "Check doc references on master" job runs it and alerts Slack on failure. No deploy job requires that job, so a reference broken by a merge (two pull requests that each pass alone) never blocks production. The config is repo-checks.config.json at the repository root.
Programmatic use
import { checkDocReferences, formatFinding, loadConfig } from "@trackunit/repo-checks";
const { config } = loadConfig(rootDir);
const findings = checkDocReferences({ rootDir, config: config.docReferences });
console.log(findings.map(formatFinding).join("\n"));import { checkStorybookLinks, formatFinding, loadConfig, StorybookIndexError } from "@trackunit/repo-checks";
const { config } = loadConfig(rootDir);
try {
const findings = checkStorybookLinks({
rootDir,
indexFiles: ["storybook-index.json"],
config: config.storybookLinks,
});
console.log(findings.map(formatFinding).join("\n"));
} catch (error) {
if (!(error instanceof StorybookIndexError)) throw error;
console.error(error.message);
process.exitCode = 2;
}The optional config is the storybookLinks section as written in the file; omitted, every default applies. checkStorybookLinks validates it first, throwing ConfigError when it is invalid, then loads every index before reading any document, so a bad index throws instead of giving a clean result: StorybookIndexError for an index that isn't valid JSON or an index, or for an empty indexFiles, and ReadError for one that can't be read. Relative indexFiles resolve against process.cwd().
Configuration
Options live in repo-checks.config.json at the repository root (the nearest .git at or above --root): under docReferences for doc-references, described in the table below, and under storybookLinks for storybook-links. The file is optional: no file, or {}, means every default. The file is validated as a whole, so an invalid section fails either command. An unknown key, a wrong type, or a bad value fails the run with exit code 2 and a message naming the key:
Error: Invalid config /repo/repo-checks.config.json: docReferences.ignore: expected { extend: [...] } to add to the defaults or { replace: [...] } to swap them out (a bare array is ambiguous)| Option | Type | Default |
| --------------------------------- | ------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- |
| rootDir | string | unset: the nearest directory at or above --root with a .git directory or file |
| ignore | { "extend": [...] } or { "replace": [...] } of globs | ["**/dist/**", "**/build/**", "**/node_modules/**", "**/coverage/**", "**/*.{zip,tgz,tar.gz,jar,whl}"] |
| exclude | array of globs | [] |
| placeholders | { "extend": [...] } or { "replace": [...] } of conventions | ["angle", "curly", "double-curly", "colon", "path-to"] |
| constructs | object of booleans | { "links": true, "images": true, "definitions": true, "inlineCode": false } |
| directories | boolean | false |
| bareFilenames | boolean | false |
Globs in ignore and exclude are picomatch globs matched against the path relative to the repository root (or to rootDir when set) with / separators. They are case-sensitive and match dotfiles. They are never matched against the bare file name, so README.md matches only the root README; write **/README.md for every one.
List options: extend, replace, empty
ignore and placeholders have defaults, so they take an object that says how yours combine with them. A bare array is rejected because it can't say which you meant.
{ "docReferences": { "ignore": { "extend": ["generated/**"] } } }{ "docReferences": { "ignore": { "replace": ["generated/**"] } } }{ "docReferences": { "ignore": { "replace": [] } } }The first adds to the defaults, the second swaps them out, and the third empties the list. Exactly one of extend and replace is allowed.
rootDir
The repository root. Unset, it is the nearest directory with a .git directory or file, so a git worktree or submodule is its own root. It is the base for references starting with /, and the second place inline code is tried. When set, it is also what ignore and exclude globs and the file paths in findings are relative to. A relative value resolves against the config file's directory. References resolving outside it are missing.
{ "docReferences": { "rootDir": "docs" } }ignore
The defaults cover conventional generated output. Globs matched against the repository-relative path a reference resolves to. A matching reference is never reported, existing or not. For a reference that may name a directory (no file extension, or a trailing /), a glob ending in /** also covers the directory itself, so a reference to dist/ is ignored before a build creates it. Takes { "extend": [...] } or { "replace": [...] }, as in List options:
{ "docReferences": { "ignore": { "extend": ["**/storybook-static/**"] } } }{ "docReferences": { "ignore": { "replace": ["**/dist/**"] } } }{ "docReferences": { "ignore": { "replace": [] } } }exclude
Globs of documents that are never read or checked, such as a CHANGELOG or archived records whose old links are part of the history. Excluded documents stay valid targets: references to them, and anchors into them, are checked as usual. Gitignored documents are already skipped, so exclude has no defaults and is a plain array. It rejects { "extend" } and { "replace" }, globs starting with / or ./, and globs ending in / (which match no document; write docs/archive/**):
{ "docReferences": { "exclude": ["CHANGELOG.md", "docs/archive/**"] } }placeholders
The defaults are every named convention. A reference with a placeholder is matched as a wildcard: it passes when at least one real path matches it. The named conventions:
| Convention | Example | Notes |
| -------------- | -------------------------- | ------------------------------------------------------------------------------------------------------------- |
| angle | docs/<skill>/SKILL.md | |
| curly | libs/{library}/README.md | Not a brace pair that is part of {{name}}. |
| double-curly | apps/{{app}}/project.json| |
| colon | routes/:id/page.tsx | Only at the start of a segment, so app:build is literal. |
| path-to | path/to/file.ts | A leading path/to/ (after any ./) followed by at least one segment marks the whole reference as illustrative: it is never checked. |
How a placeholder matches:
- It matches one or more characters within a single path segment, never across
/, and never the empty string. - Placeholders with the same name are correlated: they must bind to the same value wherever they appear, from any convention.
docs/<name>/<name>.mdmatchesdocs/intro/intro.mdbut notdocs/intro/setup.md. - Text beside a placeholder (
eval-ineval-<skill>) must match case-exactly. - A segment with two placeholders and no text between them (
<a><b>.md) is ambiguous, so the reference is skipped. - Matches inside ignored locations, and in
.git, don't count. *is not a placeholder: globs are skipped before resolution.
Any other entry is a custom regex, applied within one segment, with exactly one capture group for the placeholder's name. A regex that matches plain words, such as (\w+), turns every segment into a wildcard and so disables the check.
{ "docReferences": { "placeholders": { "extend": ["\\[(\\w+)\\]"] } } }{ "docReferences": { "placeholders": { "replace": ["angle"] } } }{ "docReferences": { "placeholders": { "replace": [] } } }The first adds Next.js-style [slug] segments, the second keeps only <name> so {name} and :name are literal text, and the third makes every reference literal, path/to/ ones included.
constructs
Which markdown constructs are checked. Only the keys you name change, so there is no extend or replace:
{ "docReferences": { "constructs": { "inlineCode": true } } }{ "docReferences": { "constructs": { "images": false } } }Inline code is opt-in: measured on manager, about 96% of inline-code findings were false positives, mostly paths written relative to an implied project root. Turn it on where your docs write repository-relative paths in backticks.
directories
Also check extensionless references that contain a /, such as libs/react/components/ or docs/guides, as file-or-directory references. With it off, a reference with a / is checked only when it has a file extension (a final . and 1-8 letters or digits).
{ "docReferences": { "directories": true } }bareFilenames
Also check inline code without a /, such as `README.md`. Most such spans are package names, versions, or commands. A link, image, or definition URL without a /, such as [x](README.md), is always checked, since it can only be a path relative to the document. An extensionless bare word (README) is checked only when both bareFilenames and directories are on.
{ "docReferences": { "bareFilenames": true } }storybookLinks
Options for storybook-links, in the same file and validated the same way. None of the docReferences options apply to it.
| Option | Type | Default |
| --------- | ------------------------------------------------------------ | ------------------------------- |
| exclude | array of globs | [] |
| ignore | array of Storybook ID globs | [] |
| hosts | { "extend": [...] } or { "replace": [...] } of hostnames | ["design.iris.trackunit.com"] |
exclude is a plain array of picomatch globs of documents that are never read, matched against the path relative to the repository root, with the same rules as the docReferences exclude:
{ "storybookLinks": { "exclude": ["legacy/**"] } }ignore is a plain array of picomatch globs matched against the Storybook ID alone, not the /docs/ or /story/ type or the rest of the link. A link whose ID matches is never reported, relative or absolute, whatever the indexes hold. A negated glob (!foo--wip) is rejected, since it would ignore every other ID. This skips both ?path=/docs/foo--wip and ?path=/story/bar--wip:
{ "storybookLinks": { "ignore": ["*--wip"] } }IDs contain no /, so a glob with one, or an empty glob, is rejected.
hosts are the hosts whose absolute links are checked; relative links always are. Each entry is a bare hostname, without a scheme, port, path, or credentials, written as a URL writes it (an internationalised domain in its xn-- form), and is matched case-insensitively. It has a default, so it takes { "extend": [...] } or { "replace": [...] }, as in List options, and a bare array is rejected:
Error: Invalid config /repo/repo-checks.config.json: storybookLinks.hosts: expected { extend: [...] } to add to the defaults or { replace: [...] } to swap them out (a bare array is ambiguous){ "storybookLinks": { "hosts": { "extend": ["storybook.example.com"] } } }{ "storybookLinks": { "hosts": { "replace": [] } } }The first also checks links to storybook.example.com; the second checks relative links only.
Ignore comments
When a reference is intentionally broken, first prefer a fenced code block, which is never checked. Otherwise put an ignore comment on the line directly above the reference; it suppresses every reference on the next line. The : reason is optional, but say why, so the next reader knows whether it can go.
In .md:
<!-- doc-references-ignore-next-line: renamed in the next release -->
See [the old guide](./old-guide.md).In .mdx, which has no HTML comments:
{/* doc-references-ignore-next-line: generated at build time */}
See [the API reference](./api.md).The reason, when given, follows a : inside the comment. For a reference-style link, the reference checked is the definition, so the comment goes above the definition, not above the [text][label] that uses it:
See [the old guide][old].
<!-- doc-references-ignore-next-line: archived -->
[old]: ./old-guide.mdstorybook-links has its own marker, storybook-links-ignore-next-line, written the same way and with the same rules. Each check honours only its own marker, so a doc-references-ignore-next-line comment doesn't suppress Storybook links, and a storybook-links-ignore-next-line comment doesn't suppress doc-references findings.
<!-- storybook-links-ignore-next-line: renamed upstream -->
See [the button docs](?path=/docs/components-button--docs).{/* storybook-links-ignore-next-line: renamed upstream */}
See [the button docs](?path=/docs/components-button--docs).To skip a whole document, use exclude, or the storybookLinks exclude; to skip a whole target location, use ignore, or the storybookLinks ignore for Storybook IDs.
Running unit tests
Run yarn nx run repo-checks:test to execute the unit tests via Vitest.
Trackunit
For more info and a full guide on Iris App SDK Development, please visit our Developer Hub.
This package was developed by Trackunit ApS. Trackunit is the leading SaaS-based IoT solution for the construction industry, offering an ecosystem of hardware, fleet management software & telematics.
