@hyperfrontend/workspace/graphgraph
The owned workspace graph: what a workspace is made of and how its parts reach one another, qualified more finely than a project-level graph can be, so that a change can be traced to exactly the tasks it affects.
workspaceGraph builds it once per process from the files git tracks or would track (less .hfignore), the project.json and package.json files among them, tsconfig.base.json, hf.json and package-lock.json.
| Node kind | Identity | Read from |
|---|---|---|
| project | the project name | project.json, or a lone package.json |
| file | workspace-relative POSIX path, with its role | git ls-files |
| entry | <package> or <package>/<subpath> | the manifest's exports, cross-checked with the aliases |
| external | <name>@<version> | package-lock.json |
| tool | the executor a target runs | project.json targets, hf.json defaults, executors.json |
| config | a configuration file or glob a target reads | target inputs after the named inputs expand |
| task | <project>:<target> | targets after the defaults merge |
Two views of the same imports
The graph keeps the project edges a project-level tool would draw (static, dynamic, implicit) and, beside them, every qualified edge in one canonical order: from a file to the file, entry or installed package it imports, or from a project to the projects it declares, the packages its manifest depends on, the tools its targets run and the configuration its inputs name.
Each record carries its kind (value, type, side effect, re-export, dynamic, unresolved, manifest, declared, tool, config), the role of the file that drew it, what it resolved to and its evidence. The records between a project and each node outside it are grouped by kind and role, so an import from a spec is visible as such rather than collapsed into one project dependency.
A file's role (production, spec, test config, lint config, build config, script, docs, asset) derives from the exclusions of the production named input in hf.json plus fixed patterns. Imports are parsed once and remembered under node_modules/.cache/: a file whose size and modification time are unchanged is not read again, and one whose content hash is unchanged is not parsed again.
Affected analysis
selectAffected decides, for every task of a target, whether a change set selects it, and writes the reason either way. A task is selected by a changed file among its own inputs, by a changed file of another project its closure reaches, by a changed implementation of a tool it runs, by a changed manifest or configuration of a project it depends on, by a global configuration file, or because a task it runs after is selected. hf.json is judged per task when its base content is given: a task is selected only if it resolves differently (executor, inputs, dependencies) or names the file as an input.
What the graph cannot follow precisely it counts whole, and says so: a dynamic load it cannot name, a file that does not parse, a dangling import, a project re-exported whole, every member of a cross-project cycle, every implicit dependency. A load of consumer code marked import(/* hf-graph: opaque */ href) draws no edge.
Three rules go beyond what the inputs say. A type-only import does not reach test or lint, which strip types before running. Build reaches its dependencies from production files alone, since its artifact derives from nothing else; every other target reaches them from every file it reads, less the project's lint configuration, which only lint loads: the configuration imports the rules it turns on, and following it from a test or typecheck closure would make every rule module an input of those targets.
A changed implementation of a tool reaches every task running the tool through the value imports of the implementation file, unless the task's inputs name the tool's project. Then the named files are the whole of what the task reads from it. A caller may also leave named inputs out of a selection by name, which is how the version flow asks the same graph which builds a change can alter without counting the inputs reserved for the engine's own code.
npx hf graph explain lib-logging
npx hf graph explain lib-logging:build --base main
npx hf graph affected --target test --base origin/main --explain
Persisted state
buildState keeps the graph under .hf/graph/ as canonical JSON envelopes: the files with the blob id git computes for each, the imports keyed by that hash, the graph, the files each entry can reach, and the metadata that decides whether a rebuild is cold. A build reparses only the files whose content changed and rewrites only the state files whose bytes differ; two checkouts of the same commit hold the same state, which the verify command checks in CI.
npx hf graph build
npx hf graph verify
npx hf graph status --jsonAPI Reference§
ƒ Functions
installed: and the version of the installed engine, so a state one version wrote is rebuilt by the next.Parameters
| Name | Type | Description |
|---|---|---|
§root | string | The workspace root, absolute |
Returns
stringParameters
Returns
Map< string, string>Parameters
| Name | Type | Description |
|---|---|---|
§root | string | The workspace root, absolute |
§options | BuildOptions | The files and imports to build from, where the caller has them(default: {}) |
Returns
WorkspaceGraphExamples
Building from a file list and imports the caller already holds
const files = listFiles(root)
const imports = importsOfFiles(root, files)
const graph = buildGraph(root, { files, imports })
graph.npmUses.get('lib-workspace') // => [{ name: '@hyperfrontend/linter', files: ['libs/workspace/src/...'] }, ...]A fresh graph each call, unlike `workspaceGraph`
buildGraph(root) === buildGraph(root) // => falseParameters
| Name | Type | Description |
|---|---|---|
§root | string | The workspace root, absolute |
§options | BuildStateOptions | Whether to build cold(default: {}) |
Returns
BuiltStateExamples
An incremental build after one file changed
const { graph, outcome } = buildState(root)
outcome.plan.mode // => 'incremental'
outcome.plan.reasons // => ['0 added', '1 changed', '0 deleted']
outcome.plan.reparse // => ['libs/features/src/index.ts']
outcome.written // => ['files.json', 'imports.json', 'entries.json'], graph.json held the same bytes
graph.projects.size // => 42Forcing a cold build
buildState(root, { force: true }).outcome.plan.mode // => 'cold'Parameters
| Name | Type | Description |
|---|---|---|
§value | unknown | Any JSON value |
Returns
stringExample
Key order and whitespace are normalised, array order is kept
canonicalJson({ b: [{ z: 1, a: 2 }], a: 'x' }) // => '{"a":"x","b":[{"a":2,"z":1}]}'
canonicalJson({ a: 1, b: 2 }) === canonicalJson({ b: 2, a: 1 }) // => true.hfignore leaves out.Parameters
Returns
ChangeSetExamples
The working tree against `main`, untracked files included
const changes = changeSet(root, 'main', null)
changes.base // => 'a1b2c3...', the merge base rather than main's tip
changes.head // => null
changes.changes // => [{ status: 'added', path: 'libs/features/src/new.ts', previousPath: null }, ...]Two commits, as CI frames a pull request
changeSet(root, 'origin/main', 'HEAD').head // => 'HEAD'closureOf( graph: WorkspaceGraph, seeds: Iterable< string>, kinds: ReadonlySet< EdgeKind>): Closure
Parameters
| Name | Type | Description |
|---|---|---|
§graph | WorkspaceGraph | The graph whose edges are followed |
§seeds | Iterable< | The files to start from, workspace-relative |
§kinds | ReadonlySet< | The edge kinds to follow; unresolved and side-effect edges are always honoured |
Returns
ClosureExamples
What a change can reach from a library's entry
const graph = workspaceGraph(root)
const closure = closureOf(graph, ['libs/features/src/index.ts'], ALL_KINDS)
closure.files.has('libs/nexus/src/core/registry.ts') // => true when the entry imports it, however indirectly
closure.files.get('libs/features/src/index.ts') // => { from: null, edge: null, rule: null }, a seed
closure.touched // => Set { 'lib-features', 'lib-nexus', ... }
closure.projects // => Map {}, unless a fallback collapsed a project to wholeType-only edges left out, as a `test` target sees the graph
const kinds = relevantKinds('test')
closureOf(graph, seeds, kinds).files.size <= closureOf(graph, seeds, ALL_KINDS).files.size // => trueReturns
numberExample
Checking that a list of edges is already canonical
const canonical = graph.records.every((edge, index) => index === 0 || compareEdges(graph.records[index - 1]!, edge) <= 0)
// => trueReturns
numberExample
Code-unit order, not locale order
['b', 'B', 'a', 'A'].sort(compareText) // => ['A', 'B', 'a', 'b']
['b', 'B', 'a', 'A'].sort((left, right) => left.localeCompare(right)) // => ['a', 'A', 'b', 'B']Parameters
| Name | Type | Description |
|---|---|---|
§path | string | The path, workspace-relative |
§project | ProjectRecord | The project owning it |
Returns
ConfigurationKindExample
Configuration sits at the project root; a nested tsconfig is a source like any other
const project = graph.projects.get('lib-features')! // root 'libs/features'
configurationKind('libs/features/package.json', project) // => 'manifest'
configurationKind('libs/features/tsconfig.lib.json', project) // => 'configuration'
configurationKind('libs/features/lint.config.ts', project) // => 'configuration'
configurationKind('libs/features/e2e/tsconfig.json', project) // => null
configurationKind('libs/features/src/index.ts', project) // => nullParameters
Returns
GraphMetaReturns
string[ ]Example
A reason with and without a path
describeReason({ rule: 'changed-input', file: 'libs/a/src/x.ts', path: [], message: 'libs/a/src/x.ts is an input of lib-a:build (production file of lib-a)' })
// => ['changed-input libs/a/src/x.ts: libs/a/src/x.ts is an input of lib-a:build (production file of lib-a)']
describeReason({ rule: 'dependent-task', file: null, path: ['task:lib-a:build'], message: 'lib-a:test runs after lib-a:build, which is selected' })
// => ['dependent-task: lib-a:test runs after lib-a:build, which is selected', ' via task:lib-a:build']Parameters
| Name | Type | Description |
|---|---|---|
§body | unknown | Any JSON value |
Returns
stringExample
Two writers agree on a digest whatever order they built the body in
digestOf({ files: [{ path: 'a', hash: '1' }], meta: {} }) === digestOf({ meta: {}, files: [{ hash: '1', path: 'a' }] }) // => trueproject.json, and one per directory holding a package.json alone, named by the configuration or the manifest.Parameters
Returns
Map< string, ProjectRecord>Examples
A file belongs to the deepest project above it
const projects = discoverProjects(root, listFiles(root))
const workspace = [...projects.values()].find((project) => project.root === '.')!
workspace.files.includes('libs/features/src/index.ts') // => false, lib-features owns it
projects.get('lib-features')?.type // => 'lib', inferred from the location when project.json names noneA directory with a `package.json` alone is a project named by the manifest
// libs/vendored/package.json: { "name": "@scope/vendored" }, no project.json
discoverProjects(root, listFiles(root)).get('@scope/vendored')?.configuration // => nullentriesBody( graph: WorkspaceGraph, hashes: ReadonlyMap< string, string>): Record< string, EntryClosure>
Parameters
| Name | Type | Description |
|---|---|---|
§graph | WorkspaceGraph | The graph whose entries are closed over |
§hashes | ReadonlyMap< | The hash of each file |
Returns
Record< string, EntryClosure>entriesOfProject( project: ProjectRecord, aliases: ReadonlyMap< string, unknown>, files: ReadonlySet< string>): EntryNode[ ]
Parameters
| Name | Type | Description |
|---|---|---|
§project | ProjectRecord | The project whose entries are read |
§aliases | ReadonlyMap< | The workspace's path aliases, each to its targets |
§files | ReadonlySet< | The workspace's files |
Returns
EntryNode[ ]Example
The alias wins where it and `exports` name the same entry
// package.json: { name: '@hyperfrontend/features', exports: { '.': './dist/index.js', './host': './dist/host.js' } }
// tsconfig.base.json paths: { '@hyperfrontend/features': ['libs/features/src/index.ts'] }
const files = new Set(listFiles(root))
entriesOfProject(project, readAliases(root), files)
// => [{ kind: 'entry', id: '@hyperfrontend/features', project: 'lib-features', file: 'libs/features/src/index.ts' }]
// './host' is left out: dist/host.js is not among the files, and no alias names itParameters
| Name | Type | Description |
|---|---|---|
§graph | WorkspaceGraph | The graph whose entries are closed over |
Example
Which entries a file's change can reach
const changed = 'libs/nexus/src/core/registry.ts'
const reaching = [...entryClosures(graph)].filter(([, closure]) => closure.files.has(changed)).map(([id]) => id)
// => ['@hyperfrontend/nexus', '@hyperfrontend/features', '@hyperfrontend/features/host']Parameters
| Name | Type | Description |
|---|---|---|
§body | unknown | The body to wrap |
Returns
stringParameters
| Name | Type | Description |
|---|---|---|
§root | string | The workspace root |
§project | ProjectRecord | The project whose named inputs apply |
§inputs | unknown | The inputs to expand |
Returns
string[ ]{projectRoot} still unreplacedExamples
A name no definition knows is kept as a pattern
// hf.json: { namedInputs: { production: ['default', '!{projectRoot}/**/*.spec.ts'] } }
expandInputs(root, project, ['production', '{workspaceRoot}/tsconfig.base.json'])
// => ['{projectRoot}/**/*', '!{projectRoot}/**/*.spec.ts', '{workspaceRoot}/tsconfig.base.json']A named input that names itself expands once
// hf.json: { namedInputs: { default: ['default', '{workspaceRoot}/hf.json'] } }
expandInputs(root, project, ['default']) // => ['{workspaceRoot}/hf.json']Parameters
| Name | Type | Description |
|---|---|---|
§value | unknown | The value of one exports key |
Returns
stringExample
Conditions are searched in order, nested ones included
exportTarget('./src/index.ts') // => './src/index.ts'
exportTarget({ types: './dist/index.d.ts', import: './dist/index.js' }) // => './dist/index.js', import before types
exportTarget({ node: { import: './dist/node.js' }, default: './dist/index.js' }) // => './dist/index.js'
exportTarget({ import: { default: './dist/index.js' } }) // => './dist/index.js'
exportTarget(null) // => nullproduction exclusions are read by role and any other extended glob is left unapplied, so a file is never excluded by a pattern the compiler cannot read.Parameters
Returns
FileFilterExamples
Positive and negative patterns, placed on the project
const inputs = fileFilterOf(['{projectRoot}/src/**/*', '!{projectRoot}/src/**/*.md'], 'libs/features')
inputs('libs/features/src/index.ts', 'production') // => true
inputs('libs/features/src/README.md', 'docs') // => false
inputs('libs/features/package.json', 'build-config') // => false, not under srcAn extended glob the compiler cannot read excludes nothing
fileFilterOf(['{projectRoot}/**/*', '!{projectRoot}/**/+(a|b).ts'], 'libs/features')('libs/features/a.ts', 'production') // => trueParameters
| Name | Type | Description |
|---|---|---|
§files | ReadonlySet< | The workspace's files |
§path | string | The workspace-relative path, POSIX |
Returns
stringExample
An emitted `.js` name finds the TypeScript source behind it
const files = new Set(['libs/features/src/index.ts', 'libs/features/src/host/open.tsx'])
fileOf(files, 'libs/features/src/index.js') // => 'libs/features/src/index.ts'
fileOf(files, 'libs/features/src') // => 'libs/features/src/index.ts'
fileOf(files, 'libs/features/src/host/open') // => 'libs/features/src/host/open.tsx'
fileOf(files, 'libs/features/src/missing') // => nullParameters
| Name | Type | Description |
|---|---|---|
§set | AffectedSet | The decisions of one target |
§mode | ExplainMode | The selected ids alone, or the explanation |
Returns
string[ ]Examples
The task ids alone, ready for a runner
const graph = workspaceGraph(root)
const changes = changeSet(root, 'main', null)
const sets = selectAffected({ graph, changes, targets: ['test'], previous: previousGraph(root, changes) })
formatAffected(sets.get('test')!, 'tasks') // => ['lib-features:test', 'lib-nexus:test']The full explanation
formatAffected(sets.get('test')!, 'explain').join('\n')
// test: 2 of 14 tasks selected, 3 changed files, a1b2c3d4e5f6 → working tree
// lib-nexus:test
// changed-input libs/nexus/src/core/registry.ts: libs/nexus/src/core/registry.ts is an input of lib-nexus:test (production file of lib-nexus)
// ...
// skipped 12 tasks
// lib-builder:test
// unreachable libs/nexus/src/core/registry.ts: ... lib-builder does not depend on lib-nexusParameters
| Name | Type | Description |
|---|---|---|
§set | AffectedSet | The affected set |
§task | string | The task id, <project>:<target> |
Returns
string[ ]Example
Why one task was skipped
formatTask(sets.get('test')!, 'lib-builder:test')
// => ['lib-builder:test is skipped', ' unreachable libs/nexus/src/core/registry.ts: ...']
formatTask(sets.get('test')!, 'docs-site:test') // => ['docs-site:test is not a task of test']Parameters
| Name | Type | Description |
|---|---|---|
§graph | WorkspaceGraph | The graph serialised |
Returns
GraphBodyParameters
| Name | Type | Description |
|---|---|---|
§records | unknown | The file records |
Returns
Map< string, string>Parameters
| Name | Type | Description |
|---|---|---|
§project | ProjectRecord | The project whose targets are read |
§target | string | The target's name |
Returns
booleanExample
Selecting the projects a target can run on
const graph = workspaceGraph(root)
const buildable = [...graph.projects.values()].filter((project) => hasTarget(project, 'build'))Parameters
Returns
HopExample
A file of a collapsed project is reached through the project's hop
hopTo(closure, 'libs/nexus/src/core/registry.ts', 'lib-nexus') // => the hop that reached the file, or the one that collapsed lib-nexus
hopTo(closure, 'README.md', null) // => null.hfignore lists, compiled.Parameters
| Name | Type | Description |
|---|---|---|
§root | string | The workspace root |
Returns
Glob[ ]Example
Applying the workspace's ignores to a path of your own
import { matchesAny } from '@hyperfrontend/linter/helpers'
const ignores = ignoredPatterns(root) // from a .hfignore holding `# build output` and `dist/**`
matchesAny(ignores, 'dist/libs/features/index.js') // => true
matchesAny(ignores, 'libs/features/src/index.ts') // => falseimportsBody( imports: ImportTable, hashes: ReadonlyMap< string, string>): Record< string, ImportRecord>
Parameters
| Name | Type | Description |
|---|---|---|
§imports | ImportTable | The imports by path |
§hashes | ReadonlyMap< | The hash of each file |
Returns
Record< string, ImportRecord>Parameters
Returns
Map< string, unknown>Example
Only code files appear, and a parse failure is recorded as null
const imports = importsOfFiles(root, listFiles(root))
imports.has('README.md') // => false
imports.get('libs/features/src/index.ts')?.length // => 7
imports.get('libs/broken/src/index.ts') // => null, when the file does not parseParameters
Returns
FileImport[ ]Examples
Each form an import can take
importsOfText(
[
"import type { Node } from '@hyperfrontend/linter'",
"import './polyfill'",
"export * from './host'",
"const mod = await import(`./locale/${lang}`)",
].join('\n'),
'src/index.ts'
)
// => [
// { specifier: '@hyperfrontend/linter', dynamic: false, kind: 'type', typeOnly: true, names: ['Node'], line: 1, column: 1 },
// { specifier: './polyfill', dynamic: false, kind: 'side-effect', typeOnly: false, names: [], line: 2, column: 1 },
// { specifier: './host', dynamic: false, kind: 're-export-all', typeOnly: false, names: ['*'], line: 3, column: 1 },
// { specifier: '`./locale/${lang}`', dynamic: true, kind: 'unresolved', typeOnly: false, names: [], line: 4, column: 19 },
// ]A file that does not parse
importsOfText('import {', 'src/broken.ts') // => nullinferLintTargets( root: string, projects: ReadonlyMap< string, ProjectRecord>): Map< string, ProjectRecord>
lint target where it declares none, leaving out the projects whose project files hf.json lists under lint.exclude and the projects the linter would find no lint.config.ts for, in their root or above it. The target runs the command hf.json names under lint.command, or the linter's own executable. A project with an install target lints after it.Parameters
| Name | Type | Description |
|---|---|---|
§root | string | The workspace root, absolute |
§projects | ReadonlyMap< | The projects, by name |
Returns
Map< string, ProjectRecord>Example
The target a project gets when it declares none
// hf.json: { lint: { command: 'node {workspaceRoot}/tools/lint/bin/lint.ts .', exclude: ['libs/vendored/**'] } }
const inferred = inferLintTargets(root, projects)
inferred.get('lib-features')?.configuration?.targets?.['lint']
// => { executor: '@hyperfrontend/workspace:run-commands',
// options: { command: 'node ../../tools/lint/bin/lint.ts .', cwd: 'libs/features' } }
hasTarget(inferred.get('@scope/vendored')!, 'lint') // => false, excluded
hasTarget(inferred.get('tool-local')!, 'lint') // => false, no lint.config.ts in tools/local or above it
hasTarget(inferred.get('hyperfrontend')!, 'lint') // => false, the workspace root never gets oneParameters
| Name | Type | Description |
|---|---|---|
§root | string | The workspace root, absolute |
Returns
InstalledPackagesExample
A package installed twice at different versions
const { hoisted, nested } = installedPackages(root)
hoisted.get('minimatch') // => '10.0.1', from node_modules/minimatch
nested.has('minimatch@3.1.2') // => true, from node_modules/typedoc/node_modules/minimatch
hoisted.get('@hyperfrontend/features') // => undefined, workspace links carry no versionParameters
| Name | Type | Description |
|---|---|---|
§path | string | The workspace-relative path |
Returns
booleanExample
Declaration files count, vendored packages do not
isCodeFile('libs/features/src/index.ts') // => true
isCodeFile('libs/features/src/types.d.ts') // => true
isCodeFile('libs/features/node_modules/left-pad/index.js') // => false
isCodeFile('libs/features/README.md') // => falserun-commands with different commands.Parameters
| Name | Type | Description |
|---|---|---|
§own | TargetRecord | The target as the project writes it, or undefined for a target the defaults alone define |
§defaults | TargetDefaults | The defaults for the target's name |
Returns
booleanExample
Two `run-commands` targets are the same target only when they run the same command
const shell = '@hyperfrontend/workspace:run-commands'
const defaults = { executor: shell, options: { command: 'hf-lint .' }, inputs: ['default'] }
isCompatibleTarget({ executor: shell, options: { command: 'hf-lint .' } }, defaults) // => true
isCompatibleTarget({ executor: shell, options: { command: 'tsc -p .' } }, defaults) // => false
isCompatibleTarget({ executor: '@hyperfrontend/package:build' }, defaults) // => false
isCompatibleTarget(undefined, defaults) // => trueParameters
| Name | Type | Description |
|---|---|---|
§path | string | The path, workspace-relative |
Returns
booleanhf.json, the root manifest, the lock file and the base tsconfigExample
Only the root's own files count
isGlobalConfig('package-lock.json') // => true
isGlobalConfig('libs/features/package.json') // => falseParameters
Returns
booleanParameters
| Name | Type | Description |
|---|---|---|
§graph | WorkspaceGraph | The graph the projects belong to |
§project | ProjectRecord | A project with an e2e target |
Returns
ProjectRecordExample
The library an e2e project packs
const graph = workspaceGraph(root)
libraryOfE2e(graph, graph.projects.get('e2e-lib-features')!)?.name // => 'lib-features'
libraryOfE2e(graph, graph.projects.get('lib-features')!) // => null, no implicit dependency buildslint target inferred for a project.Parameters
Returns
stringExample
The workspace root token becomes the way back up from the project
lintCommand('libs/features', 'node {workspaceRoot}/tools/lint/bin/lint.ts .')
// => 'node ../../tools/lint/bin/lint.ts .'
lintCommand('libs/features', 'hf-lint .') // => 'hf-lint .'Parameters
| Name | Type | Description |
|---|---|---|
§root | string | The workspace root, absolute |
Returns
FileRecord[ ]Example
The hash follows the working tree, not the index
const records = listFileRecords(root)
records[0] // => { path: '.hfignore', hash: '3b18e512dba79e4c8300dd08aeb37f8e728b8dad' }
records.some((record) => record.path.startsWith('.hf/')) // => false, the state never describes itself
// edit a tracked file without staging it: its hash changes on the next callParameters
| Name | Type | Description |
|---|---|---|
§root | string | The workspace root, absolute |
Returns
string[ ]Example
Untracked files count, ignored and `.hfignore`d ones do not
const files = listFiles(root)
files.includes('libs/workspace/src/new-file.ts') // => true, before it is ever added
files.includes('node_modules/typescript/package.json') // => false, with or without a .gitignore
files.includes('apps/docs-site/.next/cache') // => false when .hfignore lists `apps/docs-site/.next/**`Parameters
Returns
string[ ]config:<file>; empty when they agreeExample
Why a build goes cold
const persisted = readState(root)!.meta
metaDifferences(persisted, currentMeta(root, listFileRecords(root)))
// => ['node', 'config:package-lock.json'] after a Node upgrade and an install
// => [] when the next build may be warm or incrementalReturns
string<kind>:<identity>Example
One id per kind
nodeId({ kind: 'project', name: 'lib-features', root: 'libs/features' }) // => 'project:lib-features'
nodeId({ kind: 'file', path: 'libs/features/src/index.ts', project: 'lib-features', role: 'production' }) // => 'file:libs/features/src/index.ts'
nodeId({ kind: 'entry', id: '@hyperfrontend/features/host', project: 'lib-features', file: 'libs/features/src/host.ts' }) // => 'entry:@hyperfrontend/features/host'
nodeId({ kind: 'external', name: 'typescript', version: '5.9.2' }) // => 'external:typescript@5.9.2'
nodeId({ kind: 'external', name: 'typescript', version: null }) // => 'external:typescript@*'
nodeId({ kind: 'task', project: 'lib-features', target: 'build' }) // => 'task:lib-features:build'Parameters
| Name | Type | Description |
|---|---|---|
§specifier | string | The bare specifier |
Returns
stringExample
Scoped and unscoped subpaths
packageNameOf('@hyperfrontend/features/host') // => '@hyperfrontend/features'
packageNameOf('typescript/lib/tsserverlibrary') // => 'typescript'packagesOf( workspaces: unknown, projects: ReadonlyMap< string, ProjectRecord>): Map< string, ProjectRecord>
workspaces globs cover, since Nx resolves a package name to a workspace project only for a package-manager workspace.Parameters
| Name | Type | Description |
|---|---|---|
§workspaces | unknown | The globs of the root manifest's workspaces, compiled |
§projects | ReadonlyMap< | The projects by name |
Returns
Map< string, ProjectRecord>Example
Only projects under a declared workspace glob are importable by package name
import { compileGlob } from '@hyperfrontend/linter/helpers'
const { projects } = workspaceGraph(root)
packagesOf([compileGlob('libs/*')], projects).has('@hyperfrontend/features') // => true
packagesOf([], projects).size // => 0git diff --name-status -z lists: a status, then one path, or two for a rename or copy.Parameters
| Name | Type | Description |
|---|---|---|
§output | string | The NUL-separated output |
Returns
FileChange[ ]Example
A rename carries two paths, a copy counts as an addition
parseNameStatus('M\0libs/a.ts\0R100\0libs/old.ts\0libs/new.ts\0C75\0libs/x.ts\0libs/y.ts\0')
// => [
// { status: 'modified', path: 'libs/a.ts', previousPath: null },
// { status: 'renamed', path: 'libs/new.ts', previousPath: 'libs/old.ts' },
// { status: 'added', path: 'libs/y.ts', previousPath: null },
// ]Parameters
| Name | Type | Description |
|---|---|---|
§previous | PersistedState | The persisted state, or null when there is none to build on |
§meta | GraphMeta | The meta a build would write now |
§files | unknown | The workspace's files with their hashes |
Returns
UpdatePlanprerequisitesOf( graph: WorkspaceGraph, project: ProjectRecord, target: string): Prerequisite[ ]
dependsOn, else the workspace defaults.Parameters
| Name | Type | Description |
|---|---|---|
§graph | WorkspaceGraph | The graph the projects belong to |
§project | ProjectRecord | The depending project |
§target | string | The depending target |
Returns
Prerequisite[ ]Examples
The three forms, read against the graph
// project.json of lib-features: { targets: { build: { dependsOn: ['lint', '^build', 'lib-builder:build'] } } }
const graph = workspaceGraph(root)
prerequisitesOf(graph, graph.projects.get('lib-features')!, 'build')
// => [
// { id: 'lib-features:lint', project: 'lib-features', target: 'lint' },
// { id: 'lib-nexus:build', project: 'lib-nexus', target: 'build' }, // each project lib-features has an edge to
// { id: 'lib-builder:build', project: 'lib-builder', target: 'build' },
// ]An object entry is refused rather than skipped
// dependsOn: [{ target: 'build', projects: 'dependencies' }]
prerequisitesOf(graph, project, 'build')
// throws: lib-features:build depends on {"target":"build","projects":"dependencies"}, which is not one of the forms read: target, ^target or project:targetParameters
Returns
WorkspaceGraphExample
Built only when a path was deleted or renamed
const changes = changeSet(root, 'main', null)
const previous = previousGraph(root, changes) // => undefined for edits and additions alone
selectAffected({ graph: workspaceGraph(root), changes, targets: ['test'], previous })hf.json as it stood at the base of a change set, when the selection needs it: only a change to the file asks what each task resolved to before.Parameters
Returns
WorkspaceFileExample
Read only when the file changed
const changes = changeSet(root, 'main', null)
const previousWorkspace = previousWorkspaceFile(root, changes) // => undefined unless hf.json is among the changes
selectAffected({ graph: workspaceGraph(root), changes, targets: ['test'], previousWorkspace })Parameters
| Name | Type | Description |
|---|---|---|
§project | ProjectRecord | The project whose fields are printed |
Returns
PrintableProjectParameters
| Name | Type | Description |
|---|---|---|
§projects | ReadonlyMap< | The projects by name |
§file | string | The workspace-relative path |
Returns
ProjectRecordExample
The deepest root wins, the workspace itself catches the rest
const { projects } = workspaceGraph(root)
projectOfFile(projects, 'libs/features/e2e/src/open.spec.ts')?.name // => 'e2e-lib-features'
projectOfFile(projects, 'libs/features/src/index.ts')?.name // => 'lib-features'
projectOfFile(projects, 'tsconfig.base.json')?.root // => '.'tsconfig.base.json.Parameters
| Name | Type | Description |
|---|---|---|
§root | string | The workspace root, absolute |
Returns
Map< string, unknown>Example
Every target of an alias is kept, not only the first
const aliases = readAliases(root)
aliases.get('@hyperfrontend/workspace/graph') // => ['libs/workspace/src/graph/index.ts']
aliases.get('@hyperfrontend/features/*') // => ['libs/features/src/*', 'libs/features/src/*.ts']
aliases.get('left-pad') // => undefinedParameters
| Name | Type | Description |
|---|---|---|
§root | string | The workspace root, absolute |
Returns
stringExample
The two forms a version takes
readerVersion(root) // => '3:4f2a...' where the workspace aliases @hyperfrontend/linter to its sources
readerVersion(root) // => '3:0.11.2' where the installed engine's parser reads the importsParameters
Returns
FileImport[ ]Example
Bypassing the cache for one file
readImports(root, 'libs/features/src/index.ts')?.map((item) => item.specifier)
// => ['@hyperfrontend/nexus', './host/open', ...]Parameters
| Name | Type | Description |
|---|---|---|
§path | string | The file's absolute path |
Returns
ValueExample
A missing or malformed file reads as null rather than throwing
readJson<{ name?: string }>(join(root, 'package.json'))?.name // => 'hyperfrontend'
readJson(join(root, 'absent.json')) // => null
readJson(join(root, 'broken.json')) // => null, for a file holding `{ "name": `Parameters
| Name | Type | Description |
|---|---|---|
§root | string | The workspace root, absolute |
Returns
PersistedStateExample
All five files or nothing
const state = readState(root)
state?.meta.schema // => 'hf-graph/1'
state?.graph.projects.map((project) => project.name) // => ['docs-site', 'lib-features', ...]
// delete or hand-edit any one of the files and the whole state reads as nullParameters
| Name | Type | Description |
|---|---|---|
§path | string | The file, absolute |
Returns
Bodyhf.json of a root, read once.Parameters
| Name | Type | Description |
|---|---|---|
§root | string | The workspace root, absolute |
Returns
WorkspaceFileExamples
Reading the defaults of a target
const { targetDefaults, namedInputs } = readWorkspaceFile(root)
targetDefaults?.['build']?.inputs // => ['production', '^production']
namedInputs?.['production'] // => ['default', '!{projectRoot}/**/*.spec.ts', ...]A workspace without an `hf.json`
readWorkspaceFile('/tmp/empty') // => {}type for a target that runs under type stripping.Parameters
| Name | Type | Description |
|---|---|---|
§target | string | The target's name |
Returns
ReadonlySet< EdgeKind>Example
A type-only import never selects a test or lint task
relevantKinds('build').has('type') // => true
relevantKinds('test').has('type') // => false
relevantKinds('lint').has('value') // => trueParameters
Returns
ResolutionExamples
The four kinds a specifier resolves to
const graph = workspaceGraph(root)
const from = 'libs/features/src/index.ts'
resolveSpecifier(graph, from, './host/open') // => { kind: 'project', project: <lib-features>, file: 'libs/features/src/host/open.ts', path: 'libs/features/src/host/open' }
resolveSpecifier(graph, from, '@hyperfrontend/nexus') // => { kind: 'project', project: <lib-nexus>, file: 'libs/nexus/src/index.ts', path: null }
resolveSpecifier(graph, from, 'node:path') // => { kind: 'builtin' }
resolveSpecifier(graph, from, 'typescript/lib/tsserverlibrary') // => { kind: 'npm', name: 'typescript' }
// 'unknown' is answered only where no project, the workspace root included, holds the pathA relative path to a file that does not exist still names its project
const resolution = resolveSpecifier(graph, from, './missing')
if (resolution.kind === 'project') resolution.file // => null, the project is lib-features all the sameproduction exclusions, which leave specs and test and lint configuration out.Parameters
| Name | Type | Description |
|---|---|---|
§patterns | unknown | The expanded patterns |
Returns
RoleFilterExample
The `production` exclusions are read by role, not by pattern
const production = roleFilterOf(expandInputs(root, project, ['production']))
production('production') // => true
production('spec') // => false
production('docs') // => true
roleFilterOf(['{projectRoot}/**/*'])('spec') // => trueParameters
Returns
RoleExample
The roles, as the `production` named input draws the line
roleOf('libs/features/src/index.ts', 'libs/features') // => 'production'
roleOf('libs/features/src/index.spec.ts', 'libs/features') // => 'spec'
roleOf('libs/features/src/__test-utils__/host.ts', 'libs/features') // => 'spec'
roleOf('libs/features/lint.config.ts', 'libs/features') // => 'lint-config'
roleOf('libs/features/tsconfig.lib.json', 'libs/features') // => 'build-config'
roleOf('libs/features/scripts/release.ts', 'libs/features') // => 'script'
roleOf('libs/features/README.md', 'libs/features') // => 'docs'
roleOf('libs/features/assets/logo.svg', 'libs/features') // => 'asset'
roleOf('tools/lint/bin/lint.ts', '.') // => 'production', the workspace root owns itParameters
Returns
HopExample
Telling a precise reach from a conservative one
const hop = ruleHop(closure, 'libs/nexus/src/core/registry.ts')
hop?.rule // => 'unresolved-import' when a file on the chain loads an expression, null when every edge was followed preciselyParameters
| Name | Type | Description |
|---|---|---|
§options | SelectOptions | The graph, the changes, the targets and the previous graph |
Returns
Map< string, AffectedSet>Examples
Deciding the tests to run for the working tree against `main`
import { changeSet, previousGraph, selectAffected, workspaceGraph } from '@hyperfrontend/workspace/graph'
const graph = workspaceGraph(root)
const changes = changeSet(root, 'main', null)
const sets = selectAffected({ graph, changes, targets: ['test'], previous: previousGraph(root, changes) })
const tests = sets.get('test')!
tests.selected.map((decision) => decision.task) // => ['lib-features:test', 'lib-nexus:test']
tests.selected[0]!.reasons[0]!.rule // => 'changed-input'
tests.skipped[0]!.reasons[0]!.rule // => 'unreachable', every skip names the rule that makes it safeA depended-on target is decided as well
// hf.json: { targetDefaults: { test: { dependsOn: ['^build'] } } }
[...selectAffected({ graph, changes, targets: ['test'] }).keys()] // => ['test', 'build']Parameters
| Name | Type | Description |
|---|---|---|
§root | string | The workspace root |
§project | ProjectRecord | The project whose target is read |
§target | string | The target's name |
Returns
string[ ]{projectRoot} still unreplacedExample
Only the project's own side of the inputs is kept
// inputs: ['production', '^production', { input: 'default', dependencies: true }]
selfInputs(root, project, 'build')
// => ['{projectRoot}/**/*', '!{projectRoot}/**/?(*.)+(spec|test).[jt]s?(x)?(.snap)', ...]Parameters
| Name | Type | Description |
|---|---|---|
§content | string | Buffer< | What to hash |
Returns
stringParameters
| Name | Type | Description |
|---|---|---|
§edges | unknown | The edges in any order |
Returns
Edge[ ]Example
One order whatever order the edges arrived in
const forward = sortEdges(edges)
const backward = sortEdges([...edges].reverse())
JSON.stringify(forward) === JSON.stringify(backward) // => true
forward === edges // => false, the input is never sorted in placeParameters
| Name | Type | Description |
|---|---|---|
§directory | string | The directory, absolute |
Returns
stringParameters
| Name | Type | Description |
|---|---|---|
§root | string | The workspace root, absolute |
Returns
string<root>/.hf/graphExample
Locating one state file
join(stateDirectory(root), STATE_FILES.meta) // => '/repo/.hf/graph/meta.json'Parameters
| Name | Type | Description |
|---|---|---|
§root | string | The workspace root, absolute |
Returns
StateStatusExample
What a build would do, without doing it
const status = stateStatus(root)
status.present // => true
status.plan // => { mode: 'incremental', reasons: ['2 added', '0 changed', '0 deleted'], added: [...], changed: [], deleted: [], reparse: 2 }
status.digests // => { 'files.json': '9f86d0...', 'imports.json': '...', ... }*, standing for a value taken literally.Parameters
Returns
stringExample
Filling the alias target for a wildcard alias
substituteWildcard('libs/features/src/*.ts', 'host/open') // => 'libs/features/src/host/open.ts'
substituteWildcard('libs/features/src/index.ts', 'host/open') // => 'libs/features/src/index.ts'hf.json, when the target is compatible with it.Parameters
| Name | Type | Description |
|---|---|---|
§root | string | The workspace root, absolute |
§project | ProjectRecord | The project whose target is read |
§target | string | The target's name |
Returns
TargetDefaultsExample
Defaults that name another executor do not apply
// hf.json: { targetDefaults: { build: { executor: '@hyperfrontend/package:build', inputs: ['production'] } } }
// project.json: { targets: { build: { executor: '@hyperfrontend/workspace:run-commands', ... } } }
targetDefaultsFor(root, project, 'build') // => null
targetDefaultsFor(root, project, 'publish') // => null, no entry under that namedependsOn, else the workspace defaults.Parameters
| Name | Type | Description |
|---|---|---|
§root | string | The workspace root, absolute |
§project | ProjectRecord | The project whose target is read |
§target | string | The target's name |
Returns
unknownExample
The project's own `dependsOn` replaces the defaults rather than adding to them
// hf.json: { targetDefaults: { build: { dependsOn: ['^build'] } } }
// project.json: { targets: { build: { dependsOn: ['lint'] } } }
targetDependsOn(root, project, 'build') // => ['lint']
targetDependsOn(root, project, 'test') // => []Parameters
| Name | Type | Description |
|---|---|---|
§root | string | The workspace root, absolute |
§project | ProjectRecord | The project whose target is read |
§target | string | The target's name |
Returns
Configured< string>Example
Finding which file to edit to change a target's executor
const executor = targetExecutor(root, project, 'build')
// => { value: '@hyperfrontend/package:build', from: 'defaults' }
const file = executor?.from === 'project' ? `${project.root}/project.json` : 'hf.json'default and ^default.Parameters
| Name | Type | Description |
|---|---|---|
§root | string | The workspace root, absolute |
§project | ProjectRecord | The project whose target is read |
§target | string | The target's name |
Returns
Configured< unknown>Examples
A target configured without inputs falls back to Nx's implicit pair
const graph = workspaceGraph(root)
const project = graph.projects.get('lib-features')!
targetInputs(root, project, 'typecheck')
// => { value: ['default', '^default'], from: 'implicit' }Telling the project's own inputs from the workspace defaults
const { from } = targetInputs(root, project, 'build')
if (from === 'defaults') console.log('build inputs come from hf.json')Returns
string<project>:<target>Example
Matching a decision's task against a ref
const ref = { kind: 'task', project: 'lib-features', target: 'build' } as const
sets.get('build')?.selected.some((decision) => decision.task === taskId(ref)) // => true when lib-features:build is selectedParameters
| Name | Type | Description |
|---|---|---|
§root | string | The workspace root, absolute |
§project | ProjectRecord | The project whose task is read |
§target | string | The target's name |
Returns
TaskInputsExamples
What a build reads of itself and of its dependencies
// inputs: ['production', '^production']
const inputs = taskInputs(root, graph.projects.get('lib-features')!, 'build')
inputs.self('libs/features/src/index.spec.ts', 'spec') // => false
inputs.reach('libs/features/src/index.ts', 'production') // => true
inputs.dependencies?.('libs/nexus')('libs/nexus/src/index.ts', 'production') // => true
inputs.kinds.has('type') // => trueA task that reads no dependency input
// inputs: ['default']
taskInputs(root, project, 'lint').dependencies // => nullThe lint configuration starts the lint closure alone
// inputs: ['default', '^production'] for test; lint.config.ts imports the base config, which imports the rules
taskInputs(root, project, 'lint').reach('libs/features/lint.config.ts', 'lint-config') // => true
taskInputs(root, project, 'test').reach('libs/features/lint.config.ts', 'lint-config') // => false, a test never loads itParameters
Returns
string[ ]Example
The path an explanation prints
const closure = closureOf(graph, ['libs/features/src/index.ts'], ALL_KINDS)
traceOf(closure, 'libs/nexus/src/core/registry.ts')
// => ['file:libs/features/src/index.ts', 'entry:@hyperfrontend/nexus', 'file:libs/nexus/src/index.ts', 'file:libs/nexus/src/core/registry.ts']
traceOf(closure, 'libs/unrelated/src/index.ts') // => ['file:libs/unrelated/src/index.ts'], a file the closure never reachedParameters
| Name | Type | Description |
|---|---|---|
§root | string | The workspace root, absolute |
Returns
VerificationExample
A CI check that the committed state matches a cold build
const { ok, differences } = verifyState(root)
// => { ok: false, differences: ['imports.json'] } when an import changed since the state was written
// => { ok: false, differences: ['no persisted state'] } when there is nothing to compare
if (!ok) process.exitCode = 1Parameters
| Name | Type | Description |
|---|---|---|
§directory | string | The state directory, created when absent |
§work | ( | The work run while the lock is held |
§options | LockOptions | The staleness bound, the wait and the poll interval(default: {}) |
Returns
ResultExample
Writing under the lock, with a short wait for a tool that must not block
const outcome = withLock(stateDirectory(root), () => buildState(root), { timeoutMs: 5_000 })
// throws after 5 s while another live process holds the lock:
// the graph state at /repo/.hf/graph is locked by another process
// a lock left by a process that died is taken over at onceParameters
| Name | Type | Description |
|---|---|---|
§root | string | The workspace root, absolute |
Returns
WorkspaceGraphExample
Asking the graph what a file imports and who owns it
import { workspaceGraph } from '@hyperfrontend/workspace/graph'
const graph = workspaceGraph(root)
graph.projectOf('libs/features/src/index.ts')?.name // => 'lib-features'
graph.resolve('libs/features/src/index.ts', '@hyperfrontend/nexus')
// => { kind: 'project', project: <lib-nexus>, file: 'libs/nexus/src/index.ts', path: null }
graph.edges.get('lib-features') // => [{ source: 'lib-features', target: 'lib-nexus', type: 'static', files: [...] }]
workspaceGraph(root) === graph // => true, built once per rootReturns
boolean◈ Interfaces
Properties
readonly fallbacks:unknownThe fallback rules that fired while the closures were followed: unresolved loads, dangling imports, parse failures, cycles.Properties
readonly imports?:ImportTableThe imports of the code files, in place of reading them through the import cache.Properties
Properties
Properties
Properties
Properties
Properties
Properties
Properties
readonly from:SettingSourceThe project's configuration, the workspace defaults, or Nx's implicit default.Properties
Properties
Properties
Properties
Properties
Properties
Properties
Properties
Properties
Properties
Properties
Properties
readonly specifier:stringThe specifier as written, or the expression's text for an unresolved load.readonly dynamic:booleanWhether Nx counts it as dynamic: an import(), a require under braces, an import type opening a type alias.readonly typeOnly:booleanWhether the statement brings in types alone, so erasing it leaves the runtime unchanged.readonly names:unknownThe names imported or re-exported: default, * for a namespace, the exported names; empty when unknown or none.Properties
Properties
Properties
Properties
Properties
readonly algorithm:stringThe algorithm that wrote the state: a hash of the graph sources, or installed:<version> of the installed engine.Properties
Properties
Properties
Properties
Properties
Properties
package.json, as far as the graph reads it.Properties
readonly engines?:Readonly< Record< string, string>>The engines the package declares, node among them.readonly executors?:stringThe executors manifest, relative to the package, for a package that implements executors.readonly generators?:stringThe generators manifest, relative to the package, for a package that implements generators.Properties
Properties
project.json, as far as the graph reads it.Properties
Properties
readonly type:"dynamic" | "static" | "implicit"static for an import, dynamic for a dynamic import, implicit for a declaration.Properties
Properties
ProjectNode.Properties
Properties
readonly file:stringThe file within it, or null when the specifier names a package without a matching entry or a missing file.Properties
readonly path:unknownThe edges followed from the file to the task's project, as source → target ids.Properties
readonly aliases:ReadonlyMap< string, unknown>The path aliases, from tsconfig.base.json, each to its targets.Properties
readonly previous?:WorkspaceGraphThe graph at the base of the change, which lets a deleted or renamed module name the tasks it reached.readonly previousWorkspace?:WorkspaceFileThe hf.json at the base of the change, which lets a change to it select only the tasks that resolve differently afterwards.readonly ignoredInputs?:unknownNamed inputs whose files do not count, by name: the release flow leaves out the engine, which changes what a task does and never what a build emits. An ignored input still names its project, so it still bounds what a tool implemented there reaches.status reports.Properties
Properties
run-commands target runs.Properties
Properties
Properties
Properties
readonly reach:FileFilterWhether one of the project's own files is a start of the task's dependency closure: the inputs, less the lint configuration for a target other than lint.readonly dependencies:OwnerFilterWhich files of the project's dependencies count, given a dependency's root, or null when the task reads no dependency input.Properties
Properties
readonly id:stringThe executor or command as the target names it, for example @hyperfrontend/package:build.Properties
Properties
readonly reasons:unknownWhy: the missing state, the meta keys that differ, or the counts of changed files.Properties
hf.json, as far as the targets are read.Properties
Properties
readonly aliases:ReadonlyMap< string, unknown>The path aliases, from tsconfig.base.json, each to its targets.readonly edges:ReadonlyMap< string, unknown>The edges by source project, then by target project and type, as Nx draws them.readonly imports:ImportTableThe imports of each code file, null for a file the parser could not read.readonly groups:ReadonlyMap< string, unknown>The qualified edges between a project and each node outside it, grouped by kind and role, by source project.readonly resolve:( from: string, specifier: string) => ResolutionWhat a specifier names, seen from a file.◆ Types
type ConfigurationKind = Readonly< { Configuration: "configuration"; Manifest: "manifest" }>type ConfigurationKind = indexedAccesstarget, ^target, or the object form.type DependsOn = string | DependsOnObjecttype EdgeEvidence = SourceEvidence | ConfigurationEvidencetype FileFilter = ( path: string, role: Role) => booleantype GraphNode = ProjectNode | FileNode | EntryNode | ExternalNode | ToolNode | ConfigNode | TaskReftype ImportTable = ReadonlyMap< string, unknown | null>hf.json and project.json write it.type InputDefinition = string | InputObjecttype PrintableProject = Omit< ProjectRecord, "manifest" | "configuration">type Resolution = ProjectResolution | NpmResolution | BuiltinResolution | UnknownResolutiontype SettingSource = "project" | "defaults" | "implicit"● Variables
unresolved for a load whose specifier is not a literal.lint target where hf.json names none: the linter's own executable, on the project.production named input this module implements, written as hf.json writes them. A spec compares the list with the workspace's hf.json, so an exclusion added there without a matching rule here is noticed rather than silently treated as production.