@hyperfrontend/workspace/lint

lint

The projects rule family for @hyperfrontend/linter: three rules that read the workspace graph, and the readers a workspace's own rules share with them.

import { PROJECTS_FAMILY } from '@hyperfrontend/workspace/lint'

export default [
  { families: { projects: PROJECTS_FAMILY } },
  { files: ['**/*.ts'], rules: { 'projects/module-boundaries': ['error', { depConstraints: [] }] } },
  { files: ['**/package.json'], rules: { 'projects/dependency-checks': 'error' } },
  { files: ['**/project.json'], rules: { 'projects/command-lines': 'error' } },
]
RuleChecks
projects/module-boundariesImports between projects: aliases, cycles, tags, buildable dependencies
projects/dependency-checksA buildable project's manifest against what its files import
projects/command-linesShell lines of a project's targets for what sh and cmd.exe read apart

The readers resolve what a rule of your own needs about the file it lints: the workspace root and project that own it (workspaceRootOf, projectRootOf), its project file and manifest (readProjectFile, readPackageFile), the aliases of tsconfig.base.json (pathAliases) and the exports of a module (moduleExports).

Their options, messages and fixes are those of Nx's ESLint plugin (see licenses/nx.txt), reduced to the options a workspace configures, and they reach the same verdicts while loading nothing from Nx.

The project graph

The graph entry builds, once per lint process, the graph Nx would build, and the rules read it:

  • Projects: every directory holding a project.json or a package.json among the files Git tracks or would track, less what .hfignore excludes. Names, types, tags and targets follow Nx: a package.json beside a project.json adds its scripts as targets and npm: tags from its private flag and its keywords.
  • npm packages: the root package-lock.json, one node per name and version.
  • Dependencies: each code file's imports, read with the linter's own parser under Nx's rules, so a require inside a function or an import() counts as dynamic exactly when Nx counts it so; each package.json's dependencies; and the implicit dependencies a project declares.

Imports are remembered in node_modules/.cache/hyperfrontend-lint/imports.json: a file whose size and modification time are unchanged is not read again, and one whose content hash is unchanged is not parsed again. Like Nx's cached graph, the graph reflects the files on disk, not unsaved editor buffers.

module-boundaries

Reports an import that:

  • reaches another project by a relative or absolute path instead of its alias, with a fix that rewrites it to the alias when the imported names can be traced through the project's entry points;
  • names its own project's alias, with a fix that rewrites it to a relative path;
  • closes a cycle between projects, or imports an application;
  • statically imports a library the project loads lazily elsewhere;
  • from a buildable library, names a library without a build target (enforceBuildableLibDependency);
  • reaches a project whose tags the depConstraints do not allow (sourceTag with onlyDependOnLibsWithTags).

Options: allow (patterns of specifiers never reported), depConstraints and enforceBuildableLibDependency, the ones this workspace sets. The base sets them in lint.base.config.ts, with narrower allow lists for apps/package-e2e in the root lint.config.ts and for apps/docs-site in its own config; the shipped demos turn the rule off.

dependency-checks

For a project with a build target, compares the dependencies, peerDependencies and optionalDependencies of its package.json with the packages the files of the build's inputs import, at the versions installed where they import them from. It reports and fixes missing packages, packages nothing imports, ranges the installed version does not satisfy, and a manifest with no dependency section at all.

Options: ignoredDependencies and ignoredFiles. Each project's lint.config.ts lists what its build bundles or never imports, with the reason beside each entry; the library generator's template starts every new library with @hyperfrontend/testing ignored.

command-lines

The workspace runner starts every @hyperfrontend/workspace:run-commands line through the platform shell (src/runner/commands.ts): sh on Linux and macOS, cmd.exe on Windows. In a project.json, each target's command, the command of its options, and every entry of their commands (a string, or an object's command) is checked for what the two shells read differently:

MessageReported when
singleQuoteA ' outside double quotes: cmd.exe passes it through as part of the argument
envPrefixThe line starts with NAME=value, which cmd.exe does not read as an assignment
variableA $NAME, ${NAME}, $(…) or %NAME%, which only one shell expands, quoted or not
separatorA ; or a lone & outside double quotes; &&, ||, | and 2>&1 mean the same in both
globA * or ? outside double quotes, which only sh expands
backslashA \ outside double quotes, which sh reads as an escape

A line with several problems is reported once for each. Nothing is fixed: the replacement is a judgement about the command, such as moving a variable into the target's env or quoting a pattern so the program matches it.

Options: include, the selectors of the workspace/cross-platform rule, defaulting to every publishable library. The workspace selects publishable libraries, the root project.json, tools/** and apps/package-e2e/**: the projects whose targets the Windows and macOS legs run, or a contributor runs on their own machine. The docs site and the demos build on Linux alone, and their cp lines are left as they are.

API Reference§

ƒ Functions

§function

baseConfigRootOf(directory: string): string

The nearest directory at or above another that holds a tsconfig.base.json.
Parameters
NameTypeDescription
§directory
stringWhere to start
Returns
string
That directory, or null when none holds the file
Example

Finding the workspace from the file a rule is checking

baseConfigRootOf('/repo/libs/features/src/host') // => '/repo'
baseConfigRootOf('/tmp') // => null
§function

checkedProject(path: string, include: unknown): string

The project root of a file the rule checks.
Parameters
NameTypeDescription
§path
stringThe file's absolute path
§include
unknownThe selectors of the files checked
Returns
string
The root of the project owning the file, or null when the file is not checked
Example

The default selector against a rule's `include` option

checkedProject('/repo/libs/features/project.json', [{ publishableLibraries: true }]) // => '/repo/libs/features'
checkedProject('/repo/apps/docs-site/project.json', [{ publishableLibraries: true }]) // => null
checkedProject('/repo/apps/docs-site/project.json', [{ files: ['apps/**/project.json'] }]) // => '/repo/apps/docs-site'
§function

isNodeProject(root: string): boolean

Whether a project runs on Node.
Parameters
NameTypeDescription
§root
stringThe absolute directory of the project
Returns
boolean
Whether a runtime source of it imports a node: module
Example

A spec's `node:` import does not make a browser library a Node project

isNodeProject('/repo/libs/workspace') // => true
isNodeProject('/repo/libs/features') // => false, even with `import { tmpdir } from 'node:os'` in a *.spec.ts
§function

isPublishableLibrary(directory: string): boolean

Whether a directory holds a publishable library.
Parameters
NameTypeDescription
§directory
stringThe absolute directory that would hold project.json
Returns
boolean
True when the project is a library with build and publish targets
Example

Gating a rule to publishable libraries

const root = projectRootOf(dirname(context.file.path))
if (root === null || !isPublishableLibrary(root)) return {}
§function

isPublishableProject(project: ProjectFile): boolean

Whether a project file describes a publishable library: a library with build and publish targets.
Parameters
NameTypeDescription
§project
ProjectFileThe parsed file
Returns
boolean
True for a publishable library
Example

A library needs both targets

isPublishableProject({ projectType: 'library', targets: { build: {}, publish: {} } }) // => true
isPublishableProject({ projectType: 'library', targets: { build: {} } }) // => false
isPublishableProject({ projectType: 'application', targets: { build: {}, publish: {} } }) // => false
isPublishableProject(null) // => false
§function

moduleDeclarations(file: string): unknown

The top-level declarations of a module, in source order; a name exported through a list is marked exported.
Parameters
NameTypeDescription
§file
stringThe absolute path
Returns
unknown
The declarations, none when the file is missing or does not parse
Example

A name exported through a list is marked exported

// const helper = () => 1
// export const { a, b } = pair
// export { helper }
moduleDeclarations('/repo/libs/features/src/util.ts').map(({ name, kind, exported }) => ({ name, kind, exported }))
// => [{ name: 'helper', kind: 'variable', exported: true }, { name: 'a', kind: 'variable', exported: true }, { name: 'b', kind: 'variable', exported: true }]
§function

moduleExports(file: string): unknown

The names a module exports, with the declaration behind each; export * and export { x } from are followed, a cycle is cut, and an exported name whose declaration is not found is kept with an unknown kind.
Parameters
NameTypeDescription
§file
stringThe absolute path
Returns
unknown
The exports, in the order the module lists them
Example

Following a re-export to the file that declares the name

// libs/features/src/index.ts: export { open as openHost } from './host/open'
//                             export * from './types'
const exports = moduleExports('/repo/libs/features/src/index.ts')
exports.find((item) => item.name === 'openHost')
// => { name: 'openHost', kind: 'function', node: <FunctionDeclaration>, file: '/repo/libs/features/src/host/open.ts' }
exports.some((item) => item.name === 'open') // => false, the local name is not exported
exports.find((item) => item.name === 'HostOptions')?.kind // => 'interface', brought in by the star re-export
§function

parsedModule(file: string): Node

The program of a source file, parsed once.
Parameters
NameTypeDescription
§file
stringThe absolute path
Returns
Node
The program, or null when the file is missing or does not parse
Example

The same program on every call

const program = parsedModule('/repo/libs/features/src/index.ts')
program?.kind // => 'Program'
parsedModule('/repo/libs/features/src/index.ts') === program // => true
parsedModule('/repo/libs/features/src/missing.ts') // => null
§function

pathAliases(workspaceRoot: string): unknown

The aliases a workspace's base configuration declares, in declaration order.
Parameters
NameTypeDescription
§workspaceRoot
stringThe directory holding tsconfig.base.json
Returns
unknown
The aliases, none when the file is missing, unreadable or declares no paths
Example

The first target of each alias, made absolute

pathAliases('/repo')
// => [
//   { alias: '@hyperfrontend/features', source: '/repo/libs/features/src/index.ts' },
//   { alias: '@hyperfrontend/features/*', source: '/repo/libs/features/src/*' },
//   { alias: '@scope/empty', source: null }, // paths: { '@scope/empty': [] }
// ]
§function

projectRootOf(directory: string): string

The root of the project that owns a directory, as project-scope finds it: the nearest directory with a project.json, or a manifest that looks like a project's.
Parameters
NameTypeDescription
§directory
stringWhere to start
Returns
string
The root, or null
Example

The project, not the workspace, that holds a file

projectRootOf('/repo/libs/features/src/host') // => '/repo/libs/features'
projectRootOf('/repo/libs/features/e2e/src') // => '/repo/libs/features/e2e', the nearest project.json
projectRootOf('/repo/tools') // => '/repo', the workspace is its own project
§function

readPackageFile(directory: string): PackageFile

Reads a directory's package.json.
Parameters
NameTypeDescription
§directory
stringThe absolute directory
Returns
PackageFile
The parsed manifest, or null when there is none or it is not an object
Example

The fields are untyped until checked

const manifest = readPackageFile('/repo/libs/features')
const name = typeof manifest?.name === 'string' ? manifest.name : null // => '@hyperfrontend/features'
§function

readProjectFile(directory: string): ProjectFile

Reads a directory's project.json.
Parameters
NameTypeDescription
§directory
stringThe absolute directory
Returns
ProjectFile
The parsed file, or null when there is none or it is not an object
Example

Reading a target's existence from a rule

const project = readProjectFile('/repo/libs/features')
project?.name // => 'lib-features'
project?.targets?.['publish'] !== undefined // => true
readProjectFile('/repo/libs/vendored') // => null, a package.json alone has no project.json
§function

resolveModule(from: string, specifier: string): string

The file a relative specifier names from a module: the written path, the source file of an emitted extension, then the extensions and the index files tried in order.
Parameters
NameTypeDescription
§from
stringThe absolute path of the importing module
§specifier
stringThe specifier as written
Returns
string
The absolute path of the file, or null for a bare specifier or a missing file
Example

An emitted extension finds its source first

const from = '/repo/libs/features/src/index.ts'
resolveModule(from, './host/open.js') // => '/repo/libs/features/src/host/open.ts'
resolveModule(from, './host') // => '/repo/libs/features/src/host/index.ts'
resolveModule(from, '@hyperfrontend/nexus') // => null, bare specifiers are not resolved here
§function

workspaceRootOf(directory: string): string

The workspace root above a directory, as project-scope finds it: a workspace marker such as hf.json, else a manifest declaring workspaces, else the nearest manifest.
Parameters
NameTypeDescription
§directory
stringWhere to start
Returns
string
The root, or null
Example

Making a checked file's path workspace-relative

const root = workspaceRootOf(dirname(context.file.path)) // => '/repo'
relative(root!, context.file.path) // => 'libs/features/src/index.ts'
workspaceRootOf('/tmp') // => null

◈ Interfaces

§interface

CommandLinesOptions

The rule's options.
Properties
§readonly include?:unknownThe project files checked; replaces the default of every publishable library.
§interface

Declaration

A top-level declaration of a module.
Properties
§readonly name:stringThe declared name.
§readonly kind:DeclarationKindWhat kind of thing it declares.
§readonly node:NodeThe declaring node, or null when the name is only known to exist.
§readonly file:stringThe absolute path of the file holding the declaration.
§readonly exported:booleanWhether the file exports it under that name.
§interface

DependencyChecksOptions

The rule's options.
Properties
§readonly ignoredDependencies?:unknownPackages never reported.
§readonly ignoredFiles?:unknownFile patterns whose imports are not counted, {projectRoot} standing for the project's root.
§interface

DependencyConstraint

A tag constraint.
Properties
§readonly sourceTag:stringThe tag of the projects the constraint governs.
§readonly onlyDependOnLibsWithTags?:unknownThe tags at least one of which every imported project must carry; none means no tagged project.
§interface

ModuleBoundariesOptions

The rule's options.
Properties
§readonly allow?:unknownImports never checked: prefix/*, prefix/, prefix/** /suffix or a regular expression.
§readonly depConstraints?:unknownThe tag constraints projects must respect.
§readonly enforceBuildableLibDependency?:booleanWhether a buildable library may import only buildable libraries.
§interface

ModuleExport

A name a module exports, with the declaration behind it.
Properties
§readonly name:stringThe exported name.
§readonly kind:DeclarationKindWhat kind of thing it is.
§readonly node:NodeThe declaring node, or null when the declaration was not found.
§readonly file:stringThe absolute path of the file holding the declaration, or the re-exporting file when unknown.
§interface

PackageFile

The fields of package.json the rules read from disk.
Properties
§readonly name?:unknownThe package name.
§readonly engines?:Readonly<Record<string, unknown>>The engines the package declares.
§readonly exports?:unknownThe exports map.
§readonly description?:unknownThe description.
§interface

PathAlias

One alias of the base configuration.
Properties
§readonly alias:stringThe alias as imports write it, such as @scope/pkg/sub.
§readonly source:stringThe absolute path of the first file the alias maps to, or null when it maps to none.
§interface

ProjectFile

The fields of project.json the rules read.
Properties
§readonly name?:unknownThe Nx project name.
§readonly projectType?:unknownlibrary or application.
§readonly targets?:Readonly<Record<string, unknown>>The targets by name.
§readonly metadata?:Readonly<Record<string, unknown>>Free-form metadata: compatibility, deploy, lifecycle.
§interface

Selector

One way a file is selected.
Properties
§readonly publishableLibraries?:booleanSelects every file of a publishable library.
§readonly files?:unknownSelects every file matching one of these workspace-relative globs.

◆ Types

§type

DeclarationKind

What kind of thing a declaration is.
type DeclarationKind = "function" | "class" | "interface" | "type" | "enum" | "variable" | "namespace" | "unknown"

● Variables

§type

BASE_CONFIG

The file that holds the aliases.
§type

PROJECTS_FAMILY

The rules of the family by name, registered under the prefix projects in a configuration: { families: { projects: PROJECTS_FAMILY } }.