# graph 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`](https://www.hyperfrontend.dev/docs/libraries/workspace/graph/#api-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 | `` or `/` | the manifest's exports, cross-checked with the aliases | | external | `@` | `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 | `:` | 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](https://www.hyperfrontend.dev/docs/libraries/workspace/graph/#api-Role) 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`](https://www.hyperfrontend.dev/docs/libraries/workspace/graph/#api-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. ```bash 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`](https://www.hyperfrontend.dev/docs/libraries/workspace/graph/#api-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. ```bash npx hf graph build npx hf graph verify npx hf graph status --json ``` ## API Reference ### Functions #### algorithmVersion ```typescript function algorithmVersion(root: string): string ``` The algorithm that builds the graph for a workspace: a hash of the graph sources where the workspace aliases the graph package to its source, else `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** `string`: The algorithm's name #### blobHashes ```typescript function blobHashes(root: string, paths: unknown): Map ``` The blob ids git would store for files of the working tree, with the checkout's filters applied, so a file hashed here agrees with the index entry of the same content. **Parameters** | Name | Type | Description | | --- | --- | --- | | `root` | `string` | The workspace root, absolute | | `paths` | `unknown` | The files, workspace-relative and POSIX | **Returns** `Map`: Each path to its blob id #### buildGraph ```typescript function buildGraph(root: string, options: BuildOptions): WorkspaceGraph ``` Builds the graph of a workspace. **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** `WorkspaceGraph`: The graph of projects, edges, npm uses, aliases and versions **Example: Building from a file list and imports the caller already holds** ```typescript 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/...'] }, ...] ``` **Example: A fresh graph each call, unlike `workspaceGraph`** ```typescript buildGraph(root) === buildGraph(root) // => false ``` #### buildState ```typescript function buildState(root: string, options: BuildStateOptions): BuiltState ``` Builds the state of a workspace under its lock: reads what is persisted, redoes what the plan says, writes the files whose bytes changed. **Parameters** | Name | Type | Description | | --- | --- | --- | | `root` | `string` | The workspace root, absolute | | `options` | `BuildStateOptions` | Whether to build cold (default: `{}`) | **Returns** `BuiltState`: The graph, the state and what the build did **Example: An incremental build after one file changed** ```typescript 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 // => 42 ``` **Example: Forcing a cold build** ```typescript buildState(root, { force: true }).outcome.plan.mode // => 'cold' ``` #### canonicalJson ```typescript function canonicalJson(value: unknown): string ``` The canonical JSON text of a value: keys sorted at every depth, no whitespace. **Parameters** | Name | Type | Description | | --- | --- | --- | | `value` | `unknown` | Any JSON value | **Returns** `string`: The text **Example: Key order and whitespace are normalised, array order is kept** ```typescript 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 ``` #### changeSet ```typescript function changeSet(root: string, base: string, head: string): ChangeSet ``` The files that changed from the merge base of two revisions to the head, or to the working tree when the head is null, less what `.hfignore` leaves out. **Parameters** | Name | Type | Description | | --- | --- | --- | | `root` | `string` | The workspace root, absolute | | `base` | `string` | The base revision | | `head` | `string` | The head revision, or null for the working tree | **Returns** `ChangeSet`: The change set, sorted by path **Example: The working tree against `main`, untracked files included** ```typescript 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 }, ...] ``` **Example: Two commits, as CI frames a pull request** ```typescript changeSet(root, 'origin/main', 'HEAD').head // => 'HEAD' ``` #### closureOf ```typescript function closureOf(graph: WorkspaceGraph, seeds: Iterable, kinds: ReadonlySet): Closure ``` Everything a set of files reaches through edges of the given kinds. **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** `Closure`: The reachable files and projects, with how each was reached **Example: What a change can reach from a library's entry** ```typescript 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 whole ``` **Example: Type-only edges left out, as a `test` target sees the graph** ```typescript const kinds = relevantKinds('test') closureOf(graph, seeds, kinds).files.size <= closureOf(graph, seeds, ALL_KINDS).files.size // => true ``` #### compareEdges ```typescript function compareEdges(left: Edge, right: Edge): number ``` Orders two edges deterministically: by source, target, kind, role, specifier, then evidence. **Parameters** | Name | Type | Description | | --- | --- | --- | | `left` | `Edge` | One edge | | `right` | `Edge` | Another | **Returns** `number`: Negative, zero or positive as a comparator does **Example: Checking that a list of edges is already canonical** ```typescript const canonical = graph.records.every((edge, index) => index === 0 || compareEdges(graph.records[index - 1]!, edge) <= 0) // => true ``` #### compareText ```typescript function compareText(left: string, right: string): number ``` Orders two strings by code unit, the way every serialisation of the graph is ordered. **Parameters** | Name | Type | Description | | --- | --- | --- | | `left` | `string` | One string | | `right` | `string` | Another | **Returns** `number`: Negative, zero or positive as a comparator does **Example: Code-unit order, not locale order** ```typescript ['b', 'B', 'a', 'A'].sort(compareText) // => ['A', 'B', 'a', 'b'] ['b', 'B', 'a', 'A'].sort((left, right) => left.localeCompare(right)) // => ['a', 'A', 'b', 'B'] ``` #### configurationKind ```typescript function configurationKind(path: string, project: ProjectRecord): ConfigurationKind ``` What kind of configuration of its project a file is, if any. **Parameters** | Name | Type | Description | | --- | --- | --- | | `path` | `string` | The path, workspace-relative | | `project` | `ProjectRecord` | The project owning it | **Returns** `ConfigurationKind`: The kind, or null for a source, asset or documentation file **Example: Configuration sits at the project root; a nested tsconfig is a source like any other** ```typescript 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) // => null ``` #### currentMeta ```typescript function currentMeta(root: string, files: unknown): GraphMeta ``` The meta of a state written now from the given files. **Parameters** | Name | Type | Description | | --- | --- | --- | | `root` | `string` | The workspace root, absolute | | `files` | `unknown` | The workspace's files with their hashes | **Returns** `GraphMeta`: What a state written now is written by and from #### describeReason ```typescript function describeReason(item: Reason): string[] ``` The lines describing one reason: the rule, the file and the sentence, then the path followed. **Parameters** | Name | Type | Description | | --- | --- | --- | | `item` | `Reason` | The reason described | **Returns** `string[]`: One or two lines **Example: A reason with and without a path** ```typescript 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'] ``` #### digestOf ```typescript function digestOf(body: unknown): string ``` The digest of a JSON body: the sha256 of its canonical text. **Parameters** | Name | Type | Description | | --- | --- | --- | | `body` | `unknown` | Any JSON value | **Returns** `string`: The hex digest **Example: Two writers agree on a digest whatever order they built the body in** ```typescript digestOf({ files: [{ path: 'a', hash: '1' }], meta: {} }) === digestOf({ meta: {}, files: [{ hash: '1', path: 'a' }] }) // => true ``` #### discoverProjects ```typescript function discoverProjects(root: string, files: unknown): Map ``` The projects of a workspace: one per directory holding a `project.json`, and one per directory holding a `package.json` alone, named by the configuration or the manifest. **Parameters** | Name | Type | Description | | --- | --- | --- | | `root` | `string` | The workspace root, absolute | | `files` | `unknown` | The workspace's files | **Returns** `Map`: The projects by name, with their files assigned to the deepest owning root **Example: A file belongs to the deepest project above it** ```typescript 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 none ``` **Example: A directory with a `package.json` alone is a project named by the manifest** ```typescript // libs/vendored/package.json: { "name": "@scope/vendored" }, no project.json discoverProjects(root, listFiles(root)).get('@scope/vendored')?.configuration // => null ``` #### entriesBody ```typescript function entriesBody(graph: WorkspaceGraph, hashes: ReadonlyMap): Record ``` The entries body: each entry's closure and the digest of the content it reaches. **Parameters** | Name | Type | Description | | --- | --- | --- | | `graph` | `WorkspaceGraph` | The graph whose entries are closed over | | `hashes` | `ReadonlyMap` | The hash of each file | **Returns** `Record`: The closures by entry id #### entriesOfProject ```typescript function entriesOfProject(project: ProjectRecord, aliases: ReadonlyMap, files: ReadonlySet): EntryNode[] ``` The entries of a project: its export subpaths, then the aliases naming its package, each to the source file it resolves to. A subpath or alias naming no file in the project is left out. **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[]`: The entries, in the order found **Example: The alias wins where it and `exports` name the same entry** ```typescript // 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 it ``` #### entryClosures ```typescript function entryClosures(graph: WorkspaceGraph): Map ``` The closure of every entry, following every edge kind. **Parameters** | Name | Type | Description | | --- | --- | --- | | `graph` | `WorkspaceGraph` | The graph whose entries are closed over | **Returns** `Map`: Each entry id to what its file reaches **Example: Which entries a file's change can reach** ```typescript 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'] ``` #### envelopeText ```typescript function envelopeText(body: unknown): string ``` The text of a state file holding a body: the canonical JSON of its envelope, with the body canonicalised once and digested as written. **Parameters** | Name | Type | Description | | --- | --- | --- | | `body` | `unknown` | The body to wrap | **Returns** `string`: The text, with a trailing newline #### expandInputs ```typescript function expandInputs(root: string, project: ProjectRecord, inputs: unknown): string[] ``` The file patterns a list of inputs stands for, named inputs expanded through the workspace's and the project's definitions. **Parameters** | Name | Type | Description | | --- | --- | --- | | `root` | `string` | The workspace root | | `project` | `ProjectRecord` | The project whose named inputs apply | | `inputs` | `unknown` | The inputs to expand | **Returns** `string[]`: The patterns, `{projectRoot}` still unreplaced **Example: A name no definition knows is kept as a pattern** ```typescript // hf.json: { namedInputs: { production: ['default', '!{projectRoot}/**/*.spec.ts'] } } expandInputs(root, project, ['production', '{workspaceRoot}/tsconfig.base.json']) // => ['{projectRoot}/**/*', '!{projectRoot}/**/*.spec.ts', '{workspaceRoot}/tsconfig.base.json'] ``` **Example: A named input that names itself expands once** ```typescript // hf.json: { namedInputs: { default: ['default', '{workspaceRoot}/hf.json'] } } expandInputs(root, project, ['default']) // => ['{workspaceRoot}/hf.json'] ``` #### exportTarget ```typescript function exportTarget(value: unknown): string ``` The file an export value names: a string, or the first string found among the conditions of an object, conditions nested in conditions included. **Parameters** | Name | Type | Description | | --- | --- | --- | | `value` | `unknown` | The value of one `exports` key | **Returns** `string`: The path as the manifest writes it, or null when the value names no file **Example: Conditions are searched in order, nested ones included** ```typescript 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) // => null ``` #### fileFilterOf ```typescript function fileFilterOf(patterns: unknown, projectRoot: string): FileFilter ``` Whether a file is an input under a list of patterns: it matches a positive pattern and no negative one, where the `production` 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** | Name | Type | Description | | --- | --- | --- | | `patterns` | `unknown` | The expanded patterns, `{projectRoot}` unreplaced | | `projectRoot` | `string` | The root `{projectRoot}` stands for | **Returns** `FileFilter`: Whether a file of a role is an input **Example: Positive and negative patterns, placed on the project** ```typescript 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 src ``` **Example: An extended glob the compiler cannot read excludes nothing** ```typescript fileFilterOf(['{projectRoot}/**/*', '!{projectRoot}/**/+(a|b).ts'], 'libs/features')('libs/features/a.ts', 'production') // => true ``` #### fileOf ```typescript function fileOf(files: ReadonlySet, path: string): string ``` The file a path names, with an extension or an index file supplied when the path has none. **Parameters** | Name | Type | Description | | --- | --- | --- | | `files` | `ReadonlySet` | The workspace's files | | `path` | `string` | The workspace-relative path, POSIX | **Returns** `string`: The file, or null when none matches **Example: An emitted `.js` name finds the TypeScript source behind it** ```typescript 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') // => null ``` #### formatAffected ```typescript function formatAffected(set: AffectedSet, mode: ExplainMode): string[] ``` The lines an affected set prints as. **Parameters** | Name | Type | Description | | --- | --- | --- | | `set` | `AffectedSet` | The decisions of one target | | `mode` | `ExplainMode` | The selected ids alone, or the explanation | **Returns** `string[]`: The lines **Example: The task ids alone, ready for a runner** ```typescript 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'] ``` **Example: The full explanation** ```typescript 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-nexus ``` #### formatTask ```typescript function formatTask(set: AffectedSet, task: string): string[] ``` The lines explaining one task of an affected set. **Parameters** | Name | Type | Description | | --- | --- | --- | | `set` | `AffectedSet` | The affected set | | `task` | `string` | The task id, `:` | **Returns** `string[]`: The decision with its reasons, or one line saying the target has no such task **Example: Why one task was skipped** ```typescript 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'] ``` #### graphBody ```typescript function graphBody(graph: WorkspaceGraph): GraphBody ``` The graph body of a graph. **Parameters** | Name | Type | Description | | --- | --- | --- | | `graph` | `WorkspaceGraph` | The graph serialised | **Returns** `GraphBody`: The projects, nodes, records and edges in canonical order #### hashesByPath ```typescript function hashesByPath(records: unknown): Map ``` Indexes the records for lookup. **Parameters** | Name | Type | Description | | --- | --- | --- | | `records` | `unknown` | The file records | **Returns** `Map`: Each path to its hash #### hasTarget ```typescript function hasTarget(project: ProjectRecord, target: string): boolean ``` Whether a project declares a target. **Parameters** | Name | Type | Description | | --- | --- | --- | | `project` | `ProjectRecord` | The project whose targets are read | | `target` | `string` | The target's name | **Returns** `boolean`: True when the project's configuration declares it **Example: Selecting the projects a target can run on** ```typescript const graph = workspaceGraph(root) const buildable = [...graph.projects.values()].filter((project) => hasTarget(project, 'build')) ``` #### hopTo ```typescript function hopTo(closure: Closure, path: string, project: string): Hop ``` The hop through which a file entered the closure, for a reached file or a file of a collapsed project. **Parameters** | Name | Type | Description | | --- | --- | --- | | `closure` | `Closure` | The closure asked about | | `path` | `string` | The file asked about | | `project` | `string` | The project owning it, or null | **Returns** `Hop`: The hop, or null when the closure does not reach the file **Example: A file of a collapsed project is reached through the project's hop** ```typescript 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 ``` #### ignoredPatterns ```typescript function ignoredPatterns(root: string): Glob[] ``` The patterns `.hfignore` lists, compiled. **Parameters** | Name | Type | Description | | --- | --- | --- | | `root` | `string` | The workspace root | **Returns** `Glob[]`: The globs, none when the file is absent **Example: Applying the workspace's ignores to a path of your own** ```typescript 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') // => false ``` #### importsBody ```typescript function importsBody(imports: ImportTable, hashes: ReadonlyMap): Record ``` The imports body: one record per code file among the given, with the hash it was read from. **Parameters** | Name | Type | Description | | --- | --- | --- | | `imports` | `ImportTable` | The imports by path | | `hashes` | `ReadonlyMap` | The hash of each file | **Returns** `Record`: The records by path #### importsOfFiles ```typescript function importsOfFiles(root: string, files: unknown): Map ``` The imports of every code file among the given, from the cache where the file is unchanged and from the parser otherwise; the cache is rewritten only when an entry changed. A file that no longer exists is left out, and one that does not parse is recorded as null and is not remembered, so a parser that learns to read it reads it next time. **Parameters** | Name | Type | Description | | --- | --- | --- | | `root` | `string` | The workspace root, absolute | | `files` | `unknown` | The workspace-relative paths | **Returns** `Map`: The imports by path, for the code files only **Example: Only code files appear, and a parse failure is recorded as null** ```typescript 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 parse ``` #### importsOfText ```typescript function importsOfText(text: string, file: string): FileImport[] ``` The imports of a text. **Parameters** | Name | Type | Description | | --- | --- | --- | | `text` | `string` | The file's text | | `file` | `string` | Its path, whose extension decides the dialect | **Returns** `FileImport[]`: The imports, in source order, or null when the text does not parse **Example: Each form an import can take** ```typescript 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 }, // ] ``` **Example: A file that does not parse** ```typescript importsOfText('import {', 'src/broken.ts') // => null ``` #### inferLintTargets ```typescript function inferLintTargets(root: string, projects: ReadonlyMap): Map ``` Gives every project but the workspace root a `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`: The same projects, the inferred target added to their configuration **Example: The target a project gets when it declares none** ```typescript // 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 one ``` #### installedPackages ```typescript function installedPackages(root: string): InstalledPackages ``` The installed versions of a workspace. **Parameters** | Name | Type | Description | | --- | --- | --- | | `root` | `string` | The workspace root, absolute | **Returns** `InstalledPackages`: The top-level versions and the nested ones; empty without a lock file **Example: A package installed twice at different versions** ```typescript 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 version ``` #### isCodeFile ```typescript function isCodeFile(path: string): boolean ``` Whether a file's imports count: a code file outside any node_modules. **Parameters** | Name | Type | Description | | --- | --- | --- | | `path` | `string` | The workspace-relative path | **Returns** `boolean`: Whether to read it **Example: Declaration files count, vendored packages do not** ```typescript 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') // => false ``` #### isCompatibleTarget ```typescript function isCompatibleTarget(own: TargetRecord, defaults: TargetDefaults): boolean ``` Whether the workspace defaults of a target apply to a project's target, as Nx decides it: they do unless the two name different executors, or both name `run-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** `boolean`: True when Nx would merge the defaults into the target **Example: Two `run-commands` targets are the same target only when they run the same command** ```typescript 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) // => true ``` #### isGlobalConfig ```typescript function isGlobalConfig(path: string): boolean ``` Whether a file is one whose change invalidates the whole workspace. **Parameters** | Name | Type | Description | | --- | --- | --- | | `path` | `string` | The path, workspace-relative | **Returns** `boolean`: True for `hf.json`, the root manifest, the lock file and the base tsconfig **Example: Only the root's own files count** ```typescript isGlobalConfig('package-lock.json') // => true isGlobalConfig('libs/features/package.json') // => false ``` #### isStaleLock ```typescript function isStaleLock(path: string, staleMs: number): boolean ``` Whether a lock file no longer protects anything: it is gone, older than the bound, or held by a process that is not running. **Parameters** | Name | Type | Description | | --- | --- | --- | | `path` | `string` | The lock file | | `staleMs` | `number` | The bound on its age, in milliseconds | **Returns** `boolean`: True when the lock may be removed #### libraryOfE2e ```typescript function libraryOfE2e(graph: WorkspaceGraph, project: ProjectRecord): ProjectRecord ``` The library an e2e project tests. **Parameters** | Name | Type | Description | | --- | --- | --- | | `graph` | `WorkspaceGraph` | The graph the projects belong to | | `project` | `ProjectRecord` | A project with an e2e target | **Returns** `ProjectRecord`: The first implicit dependency with a build target, or null **Example: The library an e2e project packs** ```typescript 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 builds ``` #### lintCommand ```typescript function lintCommand(root: string, command: string): string ``` The command of the `lint` target inferred for a project. **Parameters** | Name | Type | Description | | --- | --- | --- | | `root` | `string` | The project root, workspace-relative and POSIX | | `command` | `string` | The command as `hf.json` writes it | **Returns** `string`: The command as it runs from the project's root **Example: The workspace root token becomes the way back up from the project** ```typescript lintCommand('libs/features', 'node {workspaceRoot}/tools/lint/bin/lint.ts .') // => 'node ../../tools/lint/bin/lint.ts .' lintCommand('libs/features', 'hf-lint .') // => 'hf-lint .' ``` #### listFileRecords ```typescript function listFileRecords(root: string): FileRecord[] ``` The files of a workspace with their hashes: those git tracks or could track, less the ignored and less the tracked files the working tree no longer holds. **Parameters** | Name | Type | Description | | --- | --- | --- | | `root` | `string` | The workspace root, absolute | **Returns** `FileRecord[]`: The records, sorted by path **Example: The hash follows the working tree, not the index** ```typescript 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 call ``` #### listFiles ```typescript function listFiles(root: string): string[] ``` The files of a workspace: those git tracks or could track, less the ignored, as workspace-relative POSIX paths. **Parameters** | Name | Type | Description | | --- | --- | --- | | `root` | `string` | The workspace root, absolute | **Returns** `string[]`: The paths, in git's order **Example: Untracked files count, ignored and `.hfignore`d ones do not** ```typescript 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/**` ``` #### metaDifferences ```typescript function metaDifferences(previous: GraphMeta, current: GraphMeta): string[] ``` What differs between the meta of a persisted state and the current one. **Parameters** | Name | Type | Description | | --- | --- | --- | | `previous` | `GraphMeta` | The persisted meta | | `current` | `GraphMeta` | The meta a build would write now | **Returns** `string[]`: The differing keys, configuration files as `config:`; empty when they agree **Example: Why a build goes cold** ```typescript 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 incremental ``` #### nodeId ```typescript function nodeId(node: GraphNode): string ``` The id of a node, unique across kinds. **Parameters** | Name | Type | Description | | --- | --- | --- | | `node` | `GraphNode` | The node to identify | **Returns** `string`: `:` **Example: One id per kind** ```typescript 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' ``` #### packageNameOf ```typescript function packageNameOf(specifier: string): string ``` The package a specifier names: its first segment, or its first two for a scoped package. **Parameters** | Name | Type | Description | | --- | --- | --- | | `specifier` | `string` | The bare specifier | **Returns** `string`: The package name, scope included **Example: Scoped and unscoped subpaths** ```typescript packageNameOf('@hyperfrontend/features/host') // => '@hyperfrontend/features' packageNameOf('typescript/lib/tsserverlibrary') // => 'typescript' ``` #### packagesOf ```typescript function packagesOf(workspaces: unknown, projects: ReadonlyMap): Map ``` The projects importable by their package names: those the root manifest's `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`: The map, empty when the root declares no workspaces **Example: Only projects under a declared workspace glob are importable by package name** ```typescript import { compileGlob } from '@hyperfrontend/linter/helpers' const { projects } = workspaceGraph(root) packagesOf([compileGlob('libs/*')], projects).has('@hyperfrontend/features') // => true packagesOf([], projects).size // => 0 ``` #### parseNameStatus ```typescript function parseNameStatus(output: string): FileChange[] ``` The changes `git 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[]`: The changes, in git's order **Example: A rename carries two paths, a copy counts as an addition** ```typescript 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 }, // ] ``` #### planUpdate ```typescript function planUpdate(previous: PersistedState, meta: GraphMeta, files: unknown): UpdatePlan ``` Plans a build. **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** `UpdatePlan`: What to reparse, what to reuse and why #### prerequisitesOf ```typescript function prerequisitesOf(graph: WorkspaceGraph, project: ProjectRecord, target: string): Prerequisite[] ``` The tasks a project's target runs after that exist: the target of each project an entry names, when that project has it; each once, in the order the entries name them, and never the task itself. The entries are the project's own `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[]`: The tasks that must succeed before the target runs **Example: The three forms, read against the graph** ```typescript // 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' }, // ] ``` **Example: An object entry is refused rather than skipped** ```typescript // 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:target ``` #### previousGraph ```typescript function previousGraph(root: string, changes: ChangeSet): WorkspaceGraph ``` The graph at the base of a change set, when the selection needs it: only a deleted or renamed path asks what read it before the change. **Parameters** | Name | Type | Description | | --- | --- | --- | | `root` | `string` | The workspace root, absolute | | `changes` | `ChangeSet` | The change set, or null for a selection of everything | **Returns** `WorkspaceGraph`: The graph at the change set's base, or undefined when no change removed a path **Example: Built only when a path was deleted or renamed** ```typescript 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 }) ``` #### previousWorkspaceFile ```typescript function previousWorkspaceFile(root: string, changes: ChangeSet): WorkspaceFile ``` The `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** | Name | Type | Description | | --- | --- | --- | | `root` | `string` | The workspace root, absolute | | `changes` | `ChangeSet` | The change set, or null for a selection of everything | **Returns** `WorkspaceFile`: The file's content at the base, empty where the base had none, or undefined when the change set leaves the file alone **Example: Read only when the file changed** ```typescript 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 }) ``` #### printableProject ```typescript function printableProject(project: ProjectRecord): PrintableProject ``` A project as the state prints it. **Parameters** | Name | Type | Description | | --- | --- | --- | | `project` | `ProjectRecord` | The project whose fields are printed | **Returns** `PrintableProject`: The record without its manifest and configuration #### projectOfFile ```typescript function projectOfFile(projects: ReadonlyMap, file: string): ProjectRecord ``` The project owning a file: the one with the deepest root above it, the workspace itself last. **Parameters** | Name | Type | Description | | --- | --- | --- | | `projects` | `ReadonlyMap` | The projects by name | | `file` | `string` | The workspace-relative path | **Returns** `ProjectRecord`: The project, or null when the workspace has no root project **Example: The deepest root wins, the workspace itself catches the rest** ```typescript 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 // => '.' ``` #### readAliases ```typescript function readAliases(root: string): Map ``` The path aliases of a workspace, from its `tsconfig.base.json`. **Parameters** | Name | Type | Description | | --- | --- | --- | | `root` | `string` | The workspace root, absolute | **Returns** `Map`: Each alias to its targets, none when the file or its paths are absent **Example: Every target of an alias is kept, not only the first** ```typescript 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') // => undefined ``` #### readerVersion ```typescript function readerVersion(root: string): string ``` The version of the reader for a workspace: the cache format, then a hash of the parser's sources where the workspace aliases the parser package to its source, else the version of the installed engine, which carries its own copy of the parser. A cache another version wrote is discarded. **Parameters** | Name | Type | Description | | --- | --- | --- | | `root` | `string` | The workspace root, absolute | **Returns** `string`: The version string **Example: The two forms a version takes** ```typescript 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 imports ``` #### readImports ```typescript function readImports(root: string, file: string): FileImport[] ``` The imports of one code file, read and parsed now. **Parameters** | Name | Type | Description | | --- | --- | --- | | `root` | `string` | The workspace root, absolute | | `file` | `string` | The workspace-relative path | **Returns** `FileImport[]`: The imports, or null when the file does not parse **Example: Bypassing the cache for one file** ```typescript readImports(root, 'libs/features/src/index.ts')?.map((item) => item.specifier) // => ['@hyperfrontend/nexus', './host/open', ...] ``` #### readJson ```typescript function readJson(path: string): Value ``` Reads a JSON file, or nothing when it does not exist or does not parse. **Parameters** | Name | Type | Description | | --- | --- | --- | | `path` | `string` | The file's absolute path | **Returns** `Value`: The value, or null **Example: A missing or malformed file reads as null rather than throwing** ```typescript 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": ` ``` #### readState ```typescript function readState(root: string): PersistedState ``` The persisted state of a workspace, or nothing when any of its files is missing or invalid. **Parameters** | Name | Type | Description | | --- | --- | --- | | `root` | `string` | The workspace root, absolute | **Returns** `PersistedState`: The state, or null **Example: All five files or nothing** ```typescript 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 null ``` #### readStateFile ```typescript function readStateFile(path: string): Body ``` The body of a state file, or nothing when the file is absent, does not parse, follows another schema, is not laid out as written, or does not match its own digest. **Parameters** | Name | Type | Description | | --- | --- | --- | | `path` | `string` | The file, absolute | **Returns** `Body`: The body, or null #### readWorkspaceFile ```typescript function readWorkspaceFile(root: string): WorkspaceFile ``` The `hf.json` of a root, read once. **Parameters** | Name | Type | Description | | --- | --- | --- | | `root` | `string` | The workspace root, absolute | **Returns** `WorkspaceFile`: The file's content, empty where there is none **Example: Reading the defaults of a target** ```typescript const { targetDefaults, namedInputs } = readWorkspaceFile(root) targetDefaults?.['build']?.inputs // => ['production', '^production'] namedInputs?.['production'] // => ['default', '!{projectRoot}/**/*.spec.ts', ...] ``` **Example: A workspace without an `hf.json`** ```typescript readWorkspaceFile('/tmp/empty') // => {} ``` #### relevantKinds ```typescript function relevantKinds(target: string): ReadonlySet ``` The edge kinds that carry a change to a target: every kind, less `type` for a target that runs under type stripping. **Parameters** | Name | Type | Description | | --- | --- | --- | | `target` | `string` | The target's name | **Returns** `ReadonlySet`: The kinds that carry a change to it **Example: A type-only import never selects a test or lint task** ```typescript relevantKinds('build').has('type') // => true relevantKinds('test').has('type') // => false relevantKinds('lint').has('value') // => true ``` #### resolveSpecifier ```typescript function resolveSpecifier(resolver: Resolver, from: string, specifier: string): Resolution ``` Resolves a specifier seen from a file as Nx does: a relative path or an alias target names the project whose root holds it, whether or not the file exists; an alias that names no project falls through to the package lookup, where a package name resolves to the file of the entry it names. **Parameters** | Name | Type | Description | | --- | --- | --- | | `resolver` | `Resolver` | What is known of the workspace | | `from` | `string` | The importing file, workspace-relative | | `specifier` | `string` | The specifier as written | **Returns** `Resolution`: What it names **Example: The four kinds a specifier resolves to** ```typescript const graph = workspaceGraph(root) const from = 'libs/features/src/index.ts' resolveSpecifier(graph, from, './host/open') // => { kind: 'project', project: , file: 'libs/features/src/host/open.ts', path: 'libs/features/src/host/open' } resolveSpecifier(graph, from, '@hyperfrontend/nexus') // => { kind: 'project', project: , 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 path ``` **Example: A relative path to a file that does not exist still names its project** ```typescript const resolution = resolveSpecifier(graph, from, './missing') if (resolution.kind === 'project') resolution.file // => null, the project is lib-features all the same ``` #### roleFilterOf ```typescript function roleFilterOf(patterns: unknown): RoleFilter ``` Whether the files of a role count under a list of input patterns: every role, unless the patterns carry the `production` exclusions, which leave specs and test and lint configuration out. **Parameters** | Name | Type | Description | | --- | --- | --- | | `patterns` | `unknown` | The expanded patterns | **Returns** `RoleFilter`: Whether files of a role count **Example: The `production` exclusions are read by role, not by pattern** ```typescript const production = roleFilterOf(expandInputs(root, project, ['production'])) production('production') // => true production('spec') // => false production('docs') // => true roleFilterOf(['{projectRoot}/**/*'])('spec') // => true ``` #### roleOf ```typescript function roleOf(file: string, projectRoot: string): Role ``` The role of a file within its project. **Parameters** | Name | Type | Description | | --- | --- | --- | | `file` | `string` | The path to classify, workspace-relative and POSIX | | `projectRoot` | `string` | The owning project's root, workspace-relative and POSIX; `.` for the workspace itself | **Returns** `Role`: Which role the file plays **Example: The roles, as the `production` named input draws the line** ```typescript 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 it ``` #### ruleHop ```typescript function ruleHop(closure: Closure, path: string): Hop ``` The hop that brought a file into the closure under a fallback rule, if any: the nearest collapse along the chain that reached it. **Parameters** | Name | Type | Description | | --- | --- | --- | | `closure` | `Closure` | The closure the file was reached in | | `path` | `string` | The reached file | **Returns** `Hop`: The hop carrying the rule, or null when ordinary edges reached the file **Example: Telling a precise reach from a conservative one** ```typescript 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 precisely ``` #### selectAffected ```typescript function selectAffected(options: SelectOptions): Map ``` Decides the tasks of the requested targets. **Parameters** | Name | Type | Description | | --- | --- | --- | | `options` | `SelectOptions` | The graph, the changes, the targets and the previous graph | **Returns** `Map`: The affected set of each requested target, and of each target one of them depends on **Example: Deciding the tests to run for the working tree against `main`** ```typescript 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 safe ``` **Example: A depended-on target is decided as well** ```typescript // hf.json: { targetDefaults: { test: { dependsOn: ['^build'] } } } [...selectAffected({ graph, changes, targets: ['test'] }).keys()] // => ['test', 'build'] ``` #### selfInputs ```typescript function selfInputs(root: string, project: ProjectRecord, target: string): string[] ``` The file patterns of a target's own inputs, named inputs expanded, the dependencies' left out. **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[]`: The patterns, `{projectRoot}` still unreplaced **Example: Only the project's own side of the inputs is kept** ```typescript // inputs: ['production', '^production', { input: 'default', dependencies: true }] selfInputs(root, project, 'build') // => ['{projectRoot}/**/*', '!{projectRoot}/**/?(*.)+(spec|test).[jt]s?(x)?(.snap)', ...] ``` #### sha256 ```typescript function sha256(content: string | Buffer): string ``` The sha256 of a text or buffer, as hex. **Parameters** | Name | Type | Description | | --- | --- | --- | | `content` | `string \| Buffer` | What to hash | **Returns** `string`: The hex digest #### sortEdges ```typescript function sortEdges(edges: unknown): Edge[] ``` The edges in their canonical order, so two graphs built from the same inputs serialise to the same bytes whatever order their edges were found in. **Parameters** | Name | Type | Description | | --- | --- | --- | | `edges` | `unknown` | The edges in any order | **Returns** `Edge[]`: A sorted copy **Example: One order whatever order the edges arrived in** ```typescript 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 place ``` #### sourcesHash ```typescript function sourcesHash(directory: string): string ``` A hash of the TypeScript sources under a directory, specs and test utilities left out, so the algorithm that wrote a state is named by the code that implements it. **Parameters** | Name | Type | Description | | --- | --- | --- | | `directory` | `string` | The directory, absolute | **Returns** `string`: The hex digest of every source's content, in path order #### stateDirectory ```typescript function stateDirectory(root: string): string ``` The state directory of a workspace. **Parameters** | Name | Type | Description | | --- | --- | --- | | `root` | `string` | The workspace root, absolute | **Returns** `string`: `/.hf/graph` **Example: Locating one state file** ```typescript join(stateDirectory(root), STATE_FILES.meta) // => '/repo/.hf/graph/meta.json' ``` #### stateStatus ```typescript function stateStatus(root: string): StateStatus ``` What is persisted and what a build would do, without building. **Parameters** | Name | Type | Description | | --- | --- | --- | | `root` | `string` | The workspace root, absolute | **Returns** `StateStatus`: Whether a state is persisted, its meta and digests, and the plan **Example: What a build would do, without doing it** ```typescript 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': '...', ... } ``` #### substituteWildcard ```typescript function substituteWildcard(pattern: string, value: string): string ``` A path pattern with its wildcard, the first `*`, standing for a value taken literally. **Parameters** | Name | Type | Description | | --- | --- | --- | | `pattern` | `string` | The pattern, as a tsconfig path alias or target writes it | | `value` | `string` | What the wildcard stands for | **Returns** `string`: The pattern with the value in place of its wildcard, or as is when it has none **Example: Filling the alias target for a wildcard alias** ```typescript 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' ``` #### targetDefaultsFor ```typescript function targetDefaultsFor(root: string, project: ProjectRecord, target: string): TargetDefaults ``` The workspace defaults that apply to a project's target: the entry under the target's name in `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** `TargetDefaults`: The defaults, or null when there are none or they do not apply **Example: Defaults that name another executor do not apply** ```typescript // 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 name ``` #### targetDependsOn ```typescript function targetDependsOn(root: string, project: ProjectRecord, target: string): unknown ``` The tasks a target runs after: the project's own `dependsOn`, 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** `unknown`: The dependencies as written, none when neither configures any **Example: The project's own `dependsOn` replaces the defaults rather than adding to them** ```typescript // hf.json: { targetDefaults: { build: { dependsOn: ['^build'] } } } // project.json: { targets: { build: { dependsOn: ['lint'] } } } targetDependsOn(root, project, 'build') // => ['lint'] targetDependsOn(root, project, 'test') // => [] ``` #### targetExecutor ```typescript function targetExecutor(root: string, project: ProjectRecord, target: string): Configured ``` The executor of a target: the project's own, 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** `Configured`: The executor and where it comes from, or null when neither names one **Example: Finding which file to edit to change a target's executor** ```typescript const executor = targetExecutor(root, project, 'build') // => { value: '@hyperfrontend/package:build', from: 'defaults' } const file = executor?.from === 'project' ? `${project.root}/project.json` : 'hf.json' ``` #### targetInputs ```typescript function targetInputs(root: string, project: ProjectRecord, target: string): Configured ``` The inputs of a target: the project's own, else the workspace defaults, else Nx's implicit `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`: The inputs and where they come from **Example: A target configured without inputs falls back to Nx's implicit pair** ```typescript const graph = workspaceGraph(root) const project = graph.projects.get('lib-features')! targetInputs(root, project, 'typecheck') // => { value: ['default', '^default'], from: 'implicit' } ``` **Example: Telling the project's own inputs from the workspace defaults** ```typescript const { from } = targetInputs(root, project, 'build') if (from === 'defaults') console.log('build inputs come from hf.json') ``` #### taskId ```typescript function taskId(task: TaskRef): string ``` The id of a task as Nx writes it. **Parameters** | Name | Type | Description | | --- | --- | --- | | `task` | `TaskRef` | The task to identify | **Returns** `string`: `:` **Example: Matching a decision's task against a ref** ```typescript 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 selected ``` #### taskInputs ```typescript function taskInputs(root: string, project: ProjectRecord, target: string): TaskInputs ``` What a task reads. **Parameters** | Name | Type | Description | | --- | --- | --- | | `root` | `string` | The workspace root, absolute | | `project` | `ProjectRecord` | The project whose task is read | | `target` | `string` | The target's name | **Returns** `TaskInputs`: The own-file filter, the dependency filter, the named projects and the relevant kinds **Example: What a build reads of itself and of its dependencies** ```typescript // 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') // => true ``` **Example: A task that reads no dependency input** ```typescript // inputs: ['default'] taskInputs(root, project, 'lint').dependencies // => null ``` **Example: The lint configuration starts the lint closure alone** ```typescript // 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 it ``` #### traceOf ```typescript function traceOf(closure: Closure, path: string): string[] ``` The chain of node ids from a seed of the closure to a file: each file visited, with the entry an edge went through where it did. **Parameters** | Name | Type | Description | | --- | --- | --- | | `closure` | `Closure` | The closure the file was reached in | | `path` | `string` | The reached file | **Returns** `string[]`: The ids, the seed first and the file last **Example: The path an explanation prints** ```typescript 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 reached ``` #### verifyState ```typescript function verifyState(root: string): Verification ``` Verifies the persisted state against a cold build of the working tree. **Parameters** | Name | Type | Description | | --- | --- | --- | | `root` | `string` | The workspace root, absolute | **Returns** `Verification`: Whether every state file agrees, and which do not **Example: A CI check that the committed state matches a cold build** ```typescript 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 = 1 ``` #### withLock ```typescript function withLock(directory: string, work: () => Result, options: LockOptions): Result ``` Runs work while holding the directory's lock, taken over from a stale holder and waited for from a live one; the lock is released whether the work returns or throws. **Parameters** | Name | Type | Description | | --- | --- | --- | | `directory` | `string` | The state directory, created when absent | | `work` | `() => Result` | The work run while the lock is held | | `options` | `LockOptions` | The staleness bound, the wait and the poll interval (default: `{}`) | **Returns** `Result`: What the work returned **Example: Writing under the lock, with a short wait for a tool that must not block** ```typescript 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 once ``` #### workspaceGraph ```typescript function workspaceGraph(root: string): WorkspaceGraph ``` The graph of a workspace, built on first request. **Parameters** | Name | Type | Description | | --- | --- | --- | | `root` | `string` | The workspace root, absolute | **Returns** `WorkspaceGraph`: The graph, the same object on every later request **Example: Asking the graph what a file imports and who owns it** ```typescript 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: , 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 root ``` #### writeStateFile ```typescript function writeStateFile(path: string, text: string): boolean ``` Writes a state file unless it already holds the same text; a process writes its own temporary file and renames it into place, so a reader never sees half a file. **Parameters** | Name | Type | Description | | --- | --- | --- | | `path` | `string` | The file, absolute | | `text` | `string` | What it should hold | **Returns** `boolean`: True when the file was written, false when it already agreed ### Interfaces #### AffectedSet The tasks of one target an analysis selected and skipped. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly target` | `string` | The target analysed. | | `readonly changes` | `ChangeSet` | The change set analysed. | | `readonly selected` | `unknown` | The tasks selected, sorted by id. | | `readonly skipped` | `unknown` | The tasks skipped, sorted by id, each with the reason it was safe to skip. | | `readonly fallbacks` | `unknown` | The fallback rules that fired while the closures were followed: unresolved loads, dangling imports, parse failures, cycles. | #### BuildOptions What a build may be given instead of reading it. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly files?` | `unknown` | The workspace's files, in place of asking git. | | `readonly imports?` | `ImportTable` | The imports of the code files, in place of reading them through the import cache. | #### BuildOutcome What a build did. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly plan` | `UpdatePlan` | The plan the build followed. | | `readonly written` | `unknown` | The state files whose bytes changed. | | `readonly durationMs` | `number` | How long the build took, in milliseconds. | #### BuildStateOptions How a build runs. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly force?` | `boolean` | Whether to ignore the persisted state and build cold. | #### BuiltinResolution A specifier naming a Node built-in. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly kind` | `"builtin"` | The resolution's kind. | #### BuiltState A built state with the graph it describes. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly graph` | `WorkspaceGraph` | The graph. | | `readonly state` | `PersistedState` | The state as written. | | `readonly outcome` | `BuildOutcome` | What the build did. | #### ChangeSet The files that changed between two revisions. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly base` | `string` | The base revision. | | `readonly head` | `string` | The head revision; the working tree when null. | | `readonly changes` | `unknown` | The changes, sorted by path. | #### Closure What a set of files reaches. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly files` | `ReadonlyMap` | Every reachable file, with how it was reached first. | | `readonly projects` | `ReadonlyMap` | Every project collapsed to project level, with why. | | `readonly touched` | `ReadonlySet` | Every project any file of which is reachable. | | `readonly fallbacks` | `unknown` | The fallbacks that fired. | #### ConfigNode A configuration file a target reads. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly kind` | `"config"` | The node's kind. | | `readonly path` | `string` | The file, workspace-relative and POSIX. | #### Configured A target setting with its origin. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly value` | `Value` | The value in force. | | `readonly from` | `SettingSource` | The project's configuration, the workspace defaults, or Nx's implicit default. | #### DependsOnObject A task dependency written as an object. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly target?` | `string` | The target depended on. | | `readonly projects?` | `string \| unknown` | Whose target: the project's dependencies, named projects, or the project itself when absent. | | `readonly dependencies?` | `boolean` | Whether the dependencies' target is meant. | #### Edge One edge between two nodes. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly source` | `string` | The depending node's id, as `nodeId` writes it. | | `readonly target` | `string` | The depended-on node's id. | | `readonly kind` | `EdgeKind` | What produced the edge. | | `readonly role` | `Role` | The role of the importing or declaring file. | | `readonly path` | `EdgePath` | The specifier and its resolution, or null for an edge no specifier drew. | | `readonly targets` | `unknown` | The targets the edge is relevant to; empty means every target. | | `readonly evidence` | `EdgeEvidence` | Where the edge was drawn. | #### EdgeGroup The edges between two projects of one kind and one role, grouped. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly source` | `string` | The depending project. | | `readonly target` | `string` | The project depended on. | | `readonly kind` | `EdgeKind` | What produced the edges. | | `readonly role` | `Role` | The role of the files that drew them. | | `readonly files` | `unknown` | The files of the source that draw the edges, in listing order. | #### EdgePath The specifier an edge was written with and what it resolved to. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly specifier` | `string` | The specifier as written in the source or configuration. | | `readonly resolved` | `string` | The resolved file, workspace-relative and POSIX, or the package name; null when unresolved. | #### EntriesBody What the entries state file holds. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly entries` | `Readonly>` | Each entry's closure, by entry id. | #### EntryClosure One entry's reach. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly file` | `string` | The file the entry resolves to. | | `readonly project` | `string` | The project owning the entry. | | `readonly files` | `unknown` | Every file a change of which can reach the entry, sorted. | | `readonly digest` | `string` | The sha256 of the sorted `path hash` lines of those files. | #### EntryNode An entry point a project exposes: a package name or a package subpath. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly kind` | `"entry"` | The node's kind. | | `readonly id` | `string` | `` or `/`, as consumers import it. | | `readonly project` | `string` | The project that owns the entry. | | `readonly file` | `string` | The file the entry resolves to, workspace-relative and POSIX. | #### Envelope A state file's content. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly body` | `Body` | The body. | | `readonly digest` | `string` | The sha256 of the body's canonical text. | | `readonly schema` | `string` | The schema the file follows. | #### ExternalNode An installed npm package. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly kind` | `"external"` | The node's kind. | | `readonly name` | `string` | The package name, scope included. | | `readonly version` | `string` | The installed version, or null when the lock file records none. | #### Fallback A fallback that fired while the closure was followed. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly edge` | `Edge` | The edge that could not be followed precisely. | | `readonly rule` | `ReasonRule` | The rule that fired. | | `readonly project` | `string` | The project collapsed to project level. | #### FileChange One changed file. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly status` | `ChangeStatus` | What happened to it. | | `readonly path` | `string` | The path at the head revision, or the deleted path. | | `readonly previousPath` | `string` | The path at the base revision for a rename, else null. | #### FileImport One import of a file. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly specifier` | `string` | The specifier as written, or the expression's text for an `unresolved` load. | | `readonly dynamic` | `boolean` | Whether Nx counts it as dynamic: an `import()`, a `require` under braces, an import type opening a type alias. | | `readonly kind` | `ImportKind` | The form of the statement. | | `readonly typeOnly` | `boolean` | Whether the statement brings in types alone, so erasing it leaves the runtime unchanged. | | `readonly names` | `unknown` | The names imported or re-exported: `default`, `*` for a namespace, the exported names; empty when unknown or none. | | `readonly line` | `number` | The one-based line of the statement. | | `readonly column` | `number` | The one-based column of the statement. | #### FileNode A file the workspace tracks. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly kind` | `"file"` | The node's kind. | | `readonly path` | `string` | The path, workspace-relative and POSIX. | | `readonly project` | `string` | The owning project, or null when no project root contains the file. | | `readonly role` | `Role` | The role the file plays in its project. | #### FileRecord One file and the hash of its content. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly path` | `string` | The path, workspace-relative and POSIX. | | `readonly hash` | `string` | The blob id of the content. | #### FilesBody What the files state file holds. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly files` | `unknown` | Every file with its hash, sorted by path. | #### GraphBody What the graph state file holds. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly projects` | `unknown` | The projects, sorted by name. | | `readonly nodes` | `unknown` | Every node, sorted by id. | | `readonly records` | `unknown` | Every qualified edge, in canonical order. | | `readonly edges` | `Readonly>` | The project edges as Nx draws them, by project. | #### GraphMeta What a state was written by and from. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly schema` | `string` | The schema of the state files. | | `readonly algorithm` | `string` | The algorithm that wrote the state: a hash of the graph sources, or `installed:` of the installed engine. | | `readonly reader` | `string` | The import reader, as `readerVersion` names it. | | `readonly node` | `string` | The Node major the state was written on, kept because the parser can differ. | | `readonly config` | `Readonly>` | The hash of each global configuration file, null for one the workspace lacks. | #### Hop How a file or project entered the closure. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly from` | `string` | The file whose edge or collapse brought it in, or null for a seed. | | `readonly edge` | `Edge` | The edge followed, or null for a seed or a collapse without one. | | `readonly rule` | `ReasonRule` | The fallback rule that brought it in, or null for an ordinary edge. | #### ImportRecord What is remembered of one code file's imports. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly hash` | `string` | The hash of the content the imports were read from. | | `readonly imports` | `unknown` | The imports, or null for a file the parser could not read. | #### ImportsBody What the imports state file holds. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly files` | `Readonly>` | The import record of each code file, by path. | #### InputObject An input written as an object. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly fileset?` | `string` | A file pattern. | | `readonly input?` | `string` | A named input. | | `readonly dependencies?` | `boolean` | Whether the input is the dependencies' rather than the project's. | | `readonly projects?` | `string \| unknown` | Whose input it is: `self`, `dependencies` or a list of projects. | #### LockOptions How a lock is taken. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly staleMs?` | `number` | After how many milliseconds a lock counts as stale whatever its holder, 60 s by default. | | `readonly timeoutMs?` | `number` | How long to wait for a live lock before giving up, 60 s by default. | | `readonly pollMs?` | `number` | How long to pause between attempts, 50 ms by default. | #### NpmResolution A specifier naming an npm package. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly kind` | `"npm"` | The resolution's kind. | | `readonly name` | `string` | The package name, scope included. | #### NpmUse The npm packages a project's files import. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly name` | `string` | The package name. | | `readonly files` | `unknown` | The files importing it. | #### PackageManifest A project's `package.json`, as far as the graph reads it. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly name?` | `string` | The package name. | | `readonly version?` | `string` | The version. | | `readonly private?` | `boolean` | Whether the package is private. | | `readonly keywords?` | `unknown` | The keywords, which become tags. | | `readonly dependencies?` | `Readonly>` | The runtime dependencies. | | `readonly devDependencies?` | `Readonly>` | The development dependencies. | | `readonly peerDependencies?` | `Readonly>` | The peer dependencies. | | `readonly optionalDependencies?` | `Readonly>` | The optional dependencies. | | `readonly exports?` | `unknown` | The exports map. | | `readonly engines?` | `Readonly>` | The engines the package declares, `node` among them. | | `readonly executors?` | `string` | The executors manifest, relative to the package, for a package that implements executors. | | `readonly generators?` | `string` | The generators manifest, relative to the package, for a package that implements generators. | #### PersistedState The whole persisted state. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly files` | `FilesBody` | The files and their hashes. | | `readonly imports` | `ImportsBody` | The imports by path. | | `readonly graph` | `GraphBody` | The graph. | | `readonly entries` | `EntriesBody` | The entry closures. | | `readonly meta` | `GraphMeta` | What wrote the state and from what. | #### Prerequisite A task another task runs after. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly id` | `string` | `:`. | | `readonly project` | `string` | The project. | | `readonly target` | `string` | The target. | #### ProjectConfiguration A project's `project.json`, as far as the graph reads it. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly name?` | `string` | The project's name. | | `readonly projectType?` | `string` | `application` or `library`. | | `readonly tags?` | `unknown` | The tags. | | `readonly implicitDependencies?` | `unknown` | The projects this one depends on without importing them. | | `readonly targets?` | `Readonly>` | The targets by name. | | `readonly metadata?` | `Readonly>` | The metadata. | | `readonly sourceRoot?` | `string` | The source root. | | `readonly namedInputs?` | `Readonly>` | The named inputs the project defines for its targets. | #### ProjectEdge An edge between projects, as Nx draws it. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly source` | `string` | The depending project. | | `readonly target` | `string` | The project depended on. | | `readonly type` | `"dynamic" \| "static" \| "implicit"` | `static` for an import, `dynamic` for a dynamic import, `implicit` for a declaration. | | `readonly files` | `unknown` | The files of the source that draw the edge, for an import. | #### ProjectInput Another project whose files a task names as inputs. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly project` | `string` | The project. | | `readonly input` | `string` | The named input evaluated on that project's files. | | `readonly files` | `OwnerFilter` | Which of its files count, given its root. | #### ProjectNode A project, named as Nx names it. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly kind` | `"project"` | The node's kind. | | `readonly name` | `string` | The project's name. | | `readonly root` | `string` | The root, workspace-relative and POSIX; `.` for the workspace itself. | #### ProjectRecord One project: the data behind a `ProjectNode`. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly name` | `string` | The name Nx knows it by. | | `readonly root` | `string` | The root, workspace-relative and POSIX; `.` for the workspace itself. | | `readonly type` | `"app" \| "lib"` | `app` or `lib`. | | `readonly tags` | `unknown` | The tags: the manifest's visibility and keywords, then the configuration's. | | `readonly implicitDependencies` | `unknown` | The projects it depends on by declaration. | | `readonly files` | `unknown` | The files it owns, workspace-relative and POSIX, in listing order. | | `readonly manifest` | `PackageManifest` | The manifest, or null when the project has none. | | `readonly configuration` | `ProjectConfiguration` | The configuration, or null when the project has none. | #### ProjectResolution A specifier naming a workspace project. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly kind` | `"project"` | The resolution's kind. | | `readonly project` | `ProjectRecord` | The project the specifier names. | | `readonly file` | `string` | The file within it, or null when the specifier names a package without a matching entry or a missing file. | | `readonly path` | `string` | The workspace-relative path the specifier named, or null for a package name. | #### Reason Why a task was selected or skipped. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly rule` | `ReasonRule` | The rule that fired. | | `readonly file` | `string` | The changed file the reason starts from, or null for a reason no file started. | | `readonly path` | `unknown` | The edges followed from the file to the task's project, as `source → target` ids. | | `readonly message` | `string` | One sentence for a reader. | #### Resolver What the resolver knows of the workspace. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly root` | `string` | The workspace root, absolute. | | `readonly files` | `ReadonlySet` | The files, workspace-relative. | | `readonly projects` | `ReadonlyMap` | The projects by name. | | `readonly aliases` | `ReadonlyMap` | The path aliases, from `tsconfig.base.json`, each to its targets. | | `readonly packages` | `ReadonlyMap` | The projects by package name. | | `readonly entries` | `ReadonlyMap` | The entries every project exposes, by id. | #### SelectOptions What an analysis needs. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly graph` | `WorkspaceGraph` | The graph at the head of the change. | | `readonly changes` | `ChangeSet` | The change set. | | `readonly targets` | `unknown` | The targets to decide; a target another depends on is decided as well. | | `readonly previous?` | `WorkspaceGraph` | The graph at the base of the change, which lets a deleted or renamed module name the tasks it reached. | | `readonly previousWorkspace?` | `WorkspaceFile` | The `hf.json` at the base of the change, which lets a change to it select only the tasks that resolve differently afterwards. | | `readonly ignoredInputs?` | `unknown` | Named 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. | #### StateStatus What `status` reports. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly present` | `boolean` | Whether a valid state is persisted. | | `readonly meta` | `GraphMeta` | The persisted meta, or null. | | `readonly digests` | `Readonly>` | The digest of each persisted state file's body, or null. | | `readonly plan` | `StatusPlan` | What a build would do now. | #### TargetDefaults A target's defaults, as far as they are read. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly inputs?` | `unknown` | The inputs. | | `readonly executor?` | `string` | The executor. | | `readonly options?` | `TargetOptions` | The options, as far as they identify a `run-commands` target. | | `readonly dependsOn?` | `unknown` | The tasks the target runs after. | #### TargetOptions The options that identify what a `run-commands` target runs. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly command?` | `string` | The one command of a `run-commands` target. | | `readonly cwd?` | `string` | The directory a `run-commands` target runs from. | | `readonly commands?` | `unknown` | The commands of a `run-commands` target. | #### TargetRecord A target of a project, as far as the graph reads it. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly executor?` | `string` | The executor, `:`. | | `readonly options?` | `TargetOptions` | The options, as far as they identify a `run-commands` target. | | `readonly inputs?` | `unknown` | The inputs, as `project.json` writes them. | | `readonly dependsOn?` | `unknown` | The tasks this target runs after, as `project.json` writes them. | #### TaskDecision One task's decision with its reasons. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly task` | `string` | The task's id, `:`. | | `readonly reasons` | `unknown` | The reasons, in the order the rules fired. | #### TaskInputs What a task reads. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly self` | `FileFilter` | Whether one of the project's own files is an input. | | `readonly reach` | `FileFilter` | Whether 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` | `OwnerFilter` | Which files of the project's dependencies count, given a dependency's root, or null when the task reads no dependency input. | | `readonly projects` | `unknown` | The other projects whose files the task names. | | `readonly kinds` | `ReadonlySet` | The edge kinds that carry a change to the task. | | `readonly key` | `string` | A key identifying the start set, shared by tasks reading the same own files. | #### TaskRef A task: one target of one project. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly kind` | `"task"` | The node's kind. | | `readonly project` | `string` | The project. | | `readonly target` | `string` | The target. | #### ToolNode An executor or command a target runs, resolved to the project implementing it. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly kind` | `"tool"` | The node's kind. | | `readonly id` | `string` | The executor or command as the target names it, for example `@hyperfrontend/package:build`. | | `readonly project` | `string` | The workspace project implementing it, or null for an installed tool. | | `readonly entry` | `string` | The entry of that project the tool loads, or null when none is known. | #### UnknownResolution A specifier naming a path no project holds. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly kind` | `"unknown"` | The resolution's kind. | | `readonly path` | `string` | The workspace-relative path the specifier named. | #### UpdatePlan What a build will do. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly mode` | `UpdateMode` | How much is redone. | | `readonly reasons` | `unknown` | Why: the missing state, the meta keys that differ, or the counts of changed files. | | `readonly added` | `unknown` | The files added since the state was written. | | `readonly changed` | `unknown` | The files whose content changed. | | `readonly deleted` | `unknown` | The files no longer present. | | `readonly reparse` | `unknown` | The code files to parse. | | `readonly reuse` | `ReadonlyMap` | The import records to reuse, by path. | #### Verification A verification's result. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly ok` | `boolean` | Whether the persisted state equals a cold build. | | `readonly differences` | `unknown` | The state files that differ, or why the comparison could not run. | #### WorkspaceFile The root `hf.json`, as far as the targets are read. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly namedInputs?` | `Readonly>` | The named inputs. | | `readonly targetDefaults?` | `Readonly>` | The defaults of each target. | #### WorkspaceGraph A workspace's graph. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly files` | `ReadonlySet` | The files, workspace-relative. | | `readonly projects` | `ReadonlyMap` | The projects by name. | | `readonly aliases` | `ReadonlyMap` | The path aliases, from `tsconfig.base.json`, each to its targets. | | `readonly root` | `string` | The workspace root, absolute. | | `readonly edges` | `ReadonlyMap` | The edges by source project, then by target project and type, as Nx draws them. | | `readonly packages` | `ReadonlyMap` | The projects by package name. | | `readonly entries` | `ReadonlyMap` | The entries every project exposes, by id. | | `readonly npmUses` | `ReadonlyMap` | The npm packages each project's files import. | | `readonly versions` | `ReadonlyMap` | The installed version of each top-level package. | | `readonly nested` | `ReadonlySet` | Each `name@version` installed below another package. | | `readonly imports` | `ImportTable` | The imports of each code file, null for a file the parser could not read. | | `readonly nodes` | `ReadonlyMap` | Every node, by id. | | `readonly records` | `unknown` | Every qualified edge, in canonical order. | | `readonly groups` | `ReadonlyMap` | The qualified edges between a project and each node outside it, grouped by kind and role, by source project. | | `readonly projectOf` | `(file: string) => ProjectRecord` | The project owning a file. | | `readonly resolve` | `(from: string, specifier: string) => Resolution` | What a specifier names, seen from a file. | ### Types #### ChangeStatus One of the change statuses. ```typescript type ChangeStatus = indexedAccess ``` #### ConfigurationKind What kind of configuration a changed file is. ```typescript type ConfigurationKind = Readonly<{ Configuration: "configuration"; Manifest: "manifest" }> ``` #### ConfigurationKind One of the configuration kinds. ```typescript type ConfigurationKind = indexedAccess ``` #### DependsOn A task dependency: `target`, `^target`, or the object form. ```typescript type DependsOn = string | DependsOnObject ``` #### EdgeEvidence What an edge rests on. ```typescript type EdgeEvidence = SourceEvidence | ConfigurationEvidence ``` #### EdgeKind One of the edge kinds. ```typescript type EdgeKind = indexedAccess ``` #### ExplainMode How an affected set is printed. ```typescript type ExplainMode = "tasks" | "explain" ``` #### FileFilter Whether a file of a given role is an input. ```typescript type FileFilter = (path: string, role: Role) => boolean ``` #### GraphNode Any node of the graph. ```typescript type GraphNode = ProjectNode | FileNode | EntryNode | ExternalNode | ToolNode | ConfigNode | TaskRef ``` #### ImportKind One of the import forms. ```typescript type ImportKind = indexedAccess ``` #### ImportTable The imports of each code file: the list read, or null for a file the parser could not read. ```typescript type ImportTable = ReadonlyMap ``` #### InputDefinition An input of a target, as `hf.json` and `project.json` write it. ```typescript type InputDefinition = string | InputObject ``` #### NodeKind One of the node kinds. ```typescript type NodeKind = indexedAccess ``` #### PrintableProject A project as the state prints it: the record without its manifest and configuration. ```typescript type PrintableProject = Omit ``` #### ReasonRule One of the reason rules. ```typescript type ReasonRule = indexedAccess ``` #### Resolution What a specifier names. ```typescript type Resolution = ProjectResolution | NpmResolution | BuiltinResolution | UnknownResolution ``` #### Role One of the roles. ```typescript type Role = indexedAccess ``` #### RoleFilter Whether files of a role count. ```typescript type RoleFilter = (role: Role) => boolean ``` #### SettingSource Where a target setting was configured. ```typescript type SettingSource = "project" | "defaults" | "implicit" ``` #### StateKey A key of the state. ```typescript type StateKey = unknown ``` #### UpdateMode One of the update modes. ```typescript type UpdateMode = indexedAccess ``` ### Variables #### ALL_KINDS Every edge kind. ```typescript const ALL_KINDS: ReadonlySet ``` **Value** `...` #### ChangeStatus What happened to one file between two revisions. ```typescript const ChangeStatus: Readonly<{ Added: "added"; Deleted: "deleted"; Modified: "modified"; Renamed: "renamed" }> ``` **Value** `...` #### EdgeKind The kinds of edge, by what produces them. ```typescript const EdgeKind: Readonly<{ Config: "config"; Declared: "declared"; Dynamic: "dynamic"; Manifest: "manifest"; ReExportAll: "re-export-all"; SideEffect: "side-effect"; Tool: "tool"; Type: "type"; Unresolved: "unresolved"; Value: "value" }> ``` **Value** `...` #### ENGINE_INPUT The named input the workspace file gives the code that runs every task: the runner, the loader hooks and the command line of the engine. A target naming it among its inputs runs when that code changes; the release flow leaves it out, since the engine changes what a task does and never what a build emits. ```typescript const ENGINE_INPUT: "engine" ``` **Value** `'engine'` #### EXECUTOR_SHARED_INPUT The named input the workspace file gives the helpers every executor of the engine shares: the JSON reader, the logger, and where the workspace resolves a package or writes a build. A task running an executor runs when they change; the release flow leaves them out, since they find tools and read manifests and never shape what a build emits. ```typescript const EXECUTOR_SHARED_INPUT: "executorShared" ``` **Value** `'executorShared'` #### GLOBAL_CONFIG The files whose change invalidates the whole graph: aliases, externals, inputs. ```typescript const GLOBAL_CONFIG: unknown ``` **Value** `...` #### ImportKind The forms an import takes, by what the statement brings in; `unresolved` for a load whose specifier is not a literal. ```typescript const ImportKind: Readonly<{ Dynamic: "dynamic"; ReExportAll: "re-export-all"; SideEffect: "side-effect"; Type: "type"; Unresolved: "unresolved"; Value: "value" }> ``` **Value** `...` #### LINT_COMMAND The command of the inferred `lint` target where `hf.json` names none: the linter's own executable, on the project. ```typescript const LINT_COMMAND: "hf-lint ." ``` **Value** `'hf-lint .'` #### LOCK_FILE The lock file's name within the state directory. ```typescript const LOCK_FILE: ".lock" ``` **Value** `'.lock'` #### NodeKind The kinds of node. ```typescript const NodeKind: Readonly<{ Config: "config"; Entry: "entry"; External: "external"; File: "file"; Project: "project"; Task: "task"; Tool: "tool" }> ``` **Value** `...` #### PRODUCTION_EXCLUSIONS The exclusions of the `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. ```typescript const PRODUCTION_EXCLUSIONS: unknown ``` **Value** `...` #### ReasonRule The closed set of rules an affected decision can rest on. ```typescript const ReasonRule: Readonly<{ ChangedInput: "changed-input"; Cycle: "cycle"; DeclaredDependency: "declared-dependency"; DeletedModule: "deleted-module"; DependencyManifest: "dependency-manifest"; DependentTask: "dependent-task"; ExternalReExport: "external-re-export"; GlobalConfig: "global-config"; KindIrrelevant: "kind-irrelevant"; ParseFailure: "parse-failure"; ProjectConfiguration: "project-configuration"; ReachableFromEntry: "reachable-from-entry"; RenamedModule: "renamed-module"; RoleIrrelevant: "role-irrelevant"; SameResolution: "same-resolution"; SideEffectImport: "side-effect-import"; StateInvalidated: "state-invalidated"; ToolChanged: "tool-changed"; Unreachable: "unreachable"; UnresolvedImport: "unresolved-import" }> ``` **Value** `...` #### Role The roles a file can play. ```typescript const Role: Readonly<{ Asset: "asset"; BuildConfig: "build-config"; Docs: "docs"; LintConfig: "lint-config"; Production: "production"; Script: "script"; Spec: "spec"; TestConfig: "test-config" }> ``` **Value** `...` #### RUN_COMMANDS The executor of a target that runs shell commands. The engine runs it itself, so no project implements it. ```typescript const RUN_COMMANDS: "@hyperfrontend/workspace:run-commands" ``` **Value** `'@hyperfrontend/workspace:run-commands'` #### SCHEMA The shape of the state files; raised when any body's shape changes. ```typescript const SCHEMA: "hf-graph/1" ``` **Value** `'hf-graph/1'` #### STATE_FILES The state files, by the key of the state they hold. ```typescript const STATE_FILES: Readonly<{ entries: "entries.json"; files: "files.json"; graph: "graph.json"; imports: "imports.json"; meta: "meta.json" }> ``` **Value** `...` #### TYPE_BLIND_TARGETS The targets that strip types before running, so a type-only import does not reach them. ```typescript const TYPE_BLIND_TARGETS: unknown ``` **Value** `...` #### UpdateMode How much of a build is redone. ```typescript const UpdateMode: Readonly<{ Cold: "cold"; Incremental: "incremental"; Warm: "warm" }> ``` **Value** `...` --- Canonical page: https://www.hyperfrontend.dev/docs/libraries/workspace/graph/ This file: https://www.hyperfrontend.dev/docs/libraries/workspace/graph.md Documentation index: https://www.hyperfrontend.dev/llms.txt