@hyperfrontend/workspace/runner

runner

The engine: the contract an executor or generator is written against, the resolution of the package that provides one, and the running of one task, of many in order, and of the tasks a change affects.

Writing an executor

A target names an executor as <package>:<name>. The package is the workspace project whose manifest carries that name, else the package of that name among the installed packages; its manifest names an executors.json, which names each module and schema, looked for beside the manifest and then under src/. A module written in TypeScript loads from source.

{
  "executors": {
    "hello": {
      "implementation": "./src/hello",
      "schema": "./src/hello.json",
      "description": "Says hello"
    }
  }
}
import type { Executor } from '@hyperfrontend/workspace'

interface Options {
  name: string
}

const hello: Executor<Options> = (options, context) => {
  process.stdout.write(`hello ${options.name} from ${context.projectName}\n`)
  return { success: true }
}

export default hello

The executor is called in the same process with the defaults of its schema and an ExecutorContext: the root, the project and target names, the target as configured, and every project of the workspace. An option given on the command line is read as the type the schema declares. An option the schema lists under required that neither the target nor the command line gives is refused before the executor runs, naming the option and the executor.

A generator is a function of a Tree and its options, listed in a generators.json the manifest names under generators, each entry naming its module under factory rather than implementation:

{
  "generators": {
    "note": {
      "factory": "./src/note/generator",
      "schema": "./src/note/schema.json",
      "description": "Writes a note"
    }
  }
}

The manifest's package.json points at both files: "executors": "./executors.json" and "generators": "./generators.json". The tree records every change and writes nothing until the run ends, which is what a dry run prints. A bare generator name goes to the one workspace project that lists it, then to this package; two workspace projects offering the same name are refused until the package is named.

Running tasks

runTask merges the target of the project's project.json with the defaults in hf.json and runs exactly that task; nothing it depends on runs first. A shell target (@hyperfrontend/workspace:run-commands, or a bare command) runs through the platform shell with node_modules/.bin on the path. Configurations are refused.

planMany orders the tasks of a selection by their prerequisites, and runPlanned runs them in that order, each in a process of its own, skipping the dependents of a failure. The affected run selects its tasks through the graph first and then runs them the same way.

API Reference§

ƒ Functions

§function

generatorNames(root: string, projects: ReadonlyMap<string, ProjectRecord>): string[]

Every generator a name could mean, as <package>:<name>.
Parameters
NameTypeDescription
§root
stringThe workspace root, absolute
§projects
ReadonlyMap<string, ProjectRecord>The workspace's projects by name
Returns
string[]
The generators of the workspace's projects, then the engine's own
Example

Listing what `npx hf generate` can run

import { discoverProjects, listFiles } from '@hyperfrontend/workspace/graph'
import { generatorNames } from '@hyperfrontend/workspace/runner'

generatorNames(root, discoverProjects(root, listFiles(root)))
// => ['@acme/tooling:component', '@hyperfrontend/workspace:workspace', '@hyperfrontend/workspace:library', ...]
§function

loadExecutor(source: ExecutorSource, importModule: ImportModule, executor: string): Promise<ExecutorFunction>

Imports the module implementing an executor and finds its default export.
Parameters
NameTypeDescription
§source
ExecutorSourceWhere the executor lives
§importModule
ImportModuleImports a module from its path
§executor
stringThe executor, for the error
Returns
Promise<ExecutorFunction>
The executor function
Example

Calling an executor outside a task

import { pathToFileURL } from 'node:url'
import { loadExecutor, locateExecutor, withDefaults } from '@hyperfrontend/workspace/runner'

const source = locateExecutor(root, projects, '@acme/tooling:lint')
const lint = await loadExecutor(source, (file) => import(pathToFileURL(file).href), '@acme/tooling:lint')
const result = await lint(withDefaults({ fix: true }, source.schema), context)
// => whatever the executor answers, { success: true } when it passed
§function

loadGenerator(source: GeneratorSource, importModule: ImportModule, written: string): Promise<Generator>

The generator a located module implements.
Parameters
NameTypeDescription
§source
GeneratorSourceWhere the generator lives
§importModule
ImportModuleImports a module from its absolute path
§written
stringThe generator as the command line names it, for the refusal
Returns
Promise<Generator>
The module's default export
Example

Loading a generator the runner located

import { pathToFileURL } from 'node:url'
import { loadGenerator, locateGenerator } from '@hyperfrontend/workspace/runner'

const generate = await loadGenerator(locateGenerator(root, projects, 'library'), (file) => import(pathToFileURL(file).href), 'library')
await generate(tree, { name: 'data-utils' })
§function

locateExecutor(root: string, projects: ReadonlyMap<string, ProjectRecord>, executor: string): ExecutorSource

Where the executor a target names lives.
Parameters
NameTypeDescription
§root
stringThe workspace root, absolute
§projects
ReadonlyMap<string, ProjectRecord>The workspace's projects by name
§executor
stringThe executor, <package>:<name>
Returns
ExecutorSource
The module and the options schema
Examples

Finding a packaged executor

import { discoverProjects, listFiles } from '@hyperfrontend/workspace/graph'
import { locateExecutor } from '@hyperfrontend/workspace/runner'

const projects = discoverProjects(root, listFiles(root))
locateExecutor(root, projects, '@hyperfrontend/workspace:typecheck')
// => { file: '/repo/node_modules/@hyperfrontend/workspace/executors/typecheck/index.js', schema: { properties: { tsConfig: { type: 'string' }, ... } } }

A workspace project stands in front of the installed package of the same name

locateExecutor(root, projects, '@acme/tooling:lint')
// => { file: '/repo/tools/tooling/src/executors/lint/index.ts', schema: { ... } } while tools/tooling carries @acme/tooling
§function

locateGenerator(root: string, projects: ReadonlyMap<string, ProjectRecord>, written: string): GeneratorSource

Where the generator a name means lives.
Parameters
NameTypeDescription
§root
stringThe workspace root, absolute
§projects
ReadonlyMap<string, ProjectRecord>The workspace's projects by name
§written
stringThe generator as the command line names it, <name> or <package>:<name>
Returns
GeneratorSource
The module and the options schema
Examples

A bare name prefers the workspace's own generator

locateGenerator(root, projects, 'library')
// => the library generator of a workspace project that lists one, else { file: '/repo/node_modules/@hyperfrontend/workspace/generators/library/index.js', schema: { ... } }

Naming the package settles it

locateGenerator(root, projects, '@hyperfrontend/workspace:library')
// => the engine's own, whatever the workspace lists under that name
§function

main(argv: unknown, host: RunHost): Promise<number>

The command line: runs the task it names and reports why it could not, when it could not.
Parameters
NameTypeDescription
§argv
unknownThe arguments after the entry, run <project>:<target> [--name=value ...]
§host
RunHostWhere the task runs and what it runs with
Returns
Promise<number>
The exit code: 0 when the task succeeded, 1 otherwise
Example

Reporting a refusal instead of throwing

await main(['run', 'lib-core:build:production'], host)
// => 1, after writing "hf run lib-core:build:production: lib-core:build:production names the configuration production; targets run without configurations"
§function

manySummary(outcomes: unknown): string[]

The summary of a run: one line per task and a count of each ending.
Parameters
NameTypeDescription
§outcomes
unknownHow each task ended
Returns
string[]
The lines
Example

The lines a run ends with

manySummary([
  { id: 'lib-core:build', status: 'succeeded', durationMs: 1840 },
  { id: 'app-shell:build', status: 'skipped', durationMs: 0 },
])
// => ['  succeeded lib-core:build (1.8 s)', '  skipped   app-shell:build (0.0 s)', '1 succeeded, 0 failed, 1 skipped']
§function

parseAffectedArgs(argv: unknown): AffectedRequest

Reads the command line of affected.
Parameters
NameTypeDescription
§argv
unknownThe arguments after affected
Returns
AffectedRequest
The request
Example

The working tree against `origin/main` unless told otherwise

parseAffectedArgs(['-t', 'test'])
// => { targets: ['test'], base: 'origin/main', head: null, args: [] }
parseAffectedArgs(['-t', 'test', '--base=v1.2.0', '--head', 'HEAD'])
// => { targets: ['test'], base: 'v1.2.0', head: 'HEAD', args: [] }
§function

parseManyArgs(argv: unknown): ManyRequest

Reads the command line of run-many.
Parameters
NameTypeDescription
§argv
unknownThe arguments after run-many
Returns
ManyRequest
The request
Example

Everything after the selection reaches the tasks

parseManyArgs(['-t', 'build,test', '-p', 'lib-*', '--verbose'])
// => { targets: ['build', 'test'], projects: ['lib-*'], args: ['--verbose'] }
parseManyArgs(['-t', 'build', '--all'])
// => { targets: ['build'], projects: null, args: [] }
§function

planMany(graph: WorkspaceGraph, request: ManyRequest): PlannedTask[]

Every task to run for a request, each after its prerequisites; a cycle is refused with its path.
Parameters
NameTypeDescription
§graph
WorkspaceGraphThe workspace graph
§request
ManyRequestThe targets and projects asked for
Returns
PlannedTask[]
The tasks in the order they run
Example

The prerequisites come first, unrequested

import { workspaceGraph } from '@hyperfrontend/workspace/graph'
import { planMany } from '@hyperfrontend/workspace/runner'

planMany(workspaceGraph(root), { targets: ['build'], projects: ['app-shell'], args: [] })
// => [
//   { id: 'lib-core:build', requested: false, after: [] },
//   { id: 'app-shell:build', requested: true, after: ['lib-core:build'] },
// ]
§function

planTasks(graph: WorkspaceGraph, tasks: unknown): PlannedTask[]

The given tasks and every task their dependsOn reaches, each after its prerequisites, in the order given otherwise; a cycle is refused with its path.
Parameters
NameTypeDescription
§graph
WorkspaceGraphThe workspace graph
§tasks
unknownThe tasks asked for, each of a project of the graph
Returns
PlannedTask[]
The tasks in the order they run
Example

Planning tasks chosen some other way than by name

planTasks(graph, [{ project: 'app-shell', target: 'e2e' }])
// => [
//   { id: 'lib-core:build', requested: false, after: [] },
//   { id: 'app-shell:build', requested: false, after: ['lib-core:build'] },
//   { id: 'app-shell:e2e', requested: true, after: ['app-shell:build'] },
// ]
§function

runGenerator(tree: Tree, written: string, options: Record<string, unknown>, importModule: ImportModule): Promise<void>

Runs the generator a name means over a tree, so a generator composes another by name: a workspace's own generator of that name, else the engine's.
Parameters
NameTypeDescription
§tree
TreeThe tree the generator edits, rooted at the workspace
§written
stringThe generator as the command line names it, <name> or <package>:<name>
§options
Record<string, unknown>The options the generator is called with
§importModule
ImportModuleImports a module from its absolute path; the process's own import when omitted(default: ...)
Returns
Promise<void>
Resolves when the generator has run
Example

A workspace generator composing the packaged `library` generator

import type { Generator } from '@hyperfrontend/workspace/generators'
import { runGenerator } from '@hyperfrontend/workspace/generators'

const featureLibrary: Generator<{ name: string }> = async (tree, options) => {
  await runGenerator(tree, 'library', { name: options.name, tags: ['type:feature'], skipFormat: true })
  tree.write(`libs/${options.name}/src/feature.ts`, 'export const feature = true\n')
}
export default featureLibrary
§function

runPlanned(tasks: unknown, args: unknown, host: ManyHost): Promise<TaskOutcome[]>

Runs planned tasks one at a time, skipping any whose prerequisite did not succeed.
Parameters
NameTypeDescription
§tasks
unknownThe tasks in order
§args
unknownThe arguments every requested task receives
§host
ManyHostHow a task runs, the clock and the output
Returns
Promise<TaskOutcome[]>
How each task ended, in order
Example

Running the plan in children of this command line

import { spawn } from 'node:child_process'
import { runPlanned, selfCommand } from '@hyperfrontend/workspace/runner'

const outcomes = await runPlanned(tasks, ['--verbose'], {
  runChild: (id, args) =>
    new Promise((resolve) => {
      const command = selfCommand(process, ['run', id, ...args])
      spawn(command[0] as string, command.slice(1), { stdio: 'inherit' }).on('close', (code) => resolve(code ?? 1))
    }),
  now: Date.now,
  write: (line) => process.stderr.write(`${line}\n`),
})
// => [{ id: 'lib-core:build', status: 'failed', durationMs: 1840 }, { id: 'app-shell:build', status: 'skipped', durationMs: 0 }]
§function

runTask(id: string, args: unknown, host: RunHost): Promise<boolean>

Runs one task.
Parameters
NameTypeDescription
§id
stringThe task, <project>:<target>
§args
unknownThe arguments after the task, --name=value or --name
§host
RunHostWhere the task runs and what it runs with
Returns
Promise<boolean>
True when the task succeeded
Example

Running one task in this process

import { spawn } from 'node:child_process'
import { pathToFileURL } from 'node:url'
import { runTask } from '@hyperfrontend/workspace/runner'

const succeeded = await runTask('lib-core:build', ['--clean=false'], {
  root,
  cwd: process.cwd(),
  env: process.env,
  platform: process.platform,
  execPath: process.execPath,
  spawn: (line, options) => spawn(line, options),
  write: (line) => process.stderr.write(`${line}\n`),
  importModule: (file) => import(pathToFileURL(file).href),
})
// => true when the build executor answered { success: true }; lib-core's dependsOn did not run first
§function

selfCommand(started: StartedAs, args: unknown): string[]

The argument vector that starts this command line again with other arguments.
Parameters
NameTypeDescription
§started
StartedAsThe running process
§args
unknownThe arguments of the new run
Returns
string[]
The executable, its flags, the entry module and the arguments
Example

Starting a task in a child the way this process was started

import { spawn } from 'node:child_process'
import { selfCommand } from '@hyperfrontend/workspace/runner'

const [program, ...args] = selfCommand(process, ['run', 'lib-core:build'])
// => ['/usr/bin/node', '--import=tsx', '/repo/node_modules/@hyperfrontend/workspace/bin/hf.mjs', 'run', 'lib-core:build']
spawn(program as string, args, { stdio: 'inherit' })
§function

withDefaults(options: Readonly<Record<string, unknown>>, schema: ExecutorSchema): Record<string, unknown>

Options with the defaults of their schema filled in where they are unset.
Parameters
NameTypeDescription
§options
Readonly<Record<string, unknown>>The options of the target and the command line
§schema
ExecutorSchemaThe executor's options schema
Returns
Record<string, unknown>
A copy of the options with the defaults applied
Example

Filling the options a target left unset

withDefaults({ tsConfig: 'libs/core/tsconfig.lib.json' }, { properties: { tsConfig: { type: 'string' }, strict: { type: 'boolean', default: true } } })
// => { tsConfig: 'libs/core/tsconfig.lib.json', strict: true }

◈ Interfaces

§interface

AffectedRequest

The targets asked for over a change, and the arguments every requested task receives.
Properties
§readonly targets:unknownThe targets.
§readonly base:stringThe base revision, origin/main when none is named.
§readonly head:stringThe head revision, or null for the working tree.
§readonly args:unknownThe arguments after the selection, passed to each requested task.
§interface

ExecutorContext

What an executor is called with besides its options.
Properties
§root:stringThe workspace root, absolute.
§cwd:stringThe directory the command line started in.
§projectName:stringThe project the task runs on.
§targetName:stringThe target the task runs.
§target:TargetConfigurationThe target, merged with its defaults and its tokens replaced.
§projects:Record<string, ProjectConfiguration>Every project's configuration by name, targets resolved.
§configuration:WorkspaceConfigurationThe workspace configuration.
§interface

ExecutorEntry

One executor of an executors manifest.
Properties
§implementation:stringThe module whose default export implements it, relative to the manifest.
§schema:stringThe schema of its options, relative to the manifest.
§description?:stringWhat it does.
§interface

ExecutorResult

What an executor answers.
Properties
§success:booleanWhether the task succeeded.
§interface

ExecutorSchema

An executor's options schema, as far as the runner reads it.
Properties
§readonly properties?:Readonly<Record<string, SchemaProperty>>The options.
§readonly required?:unknownThe options a run must give, from the target or the command line.
§interface

ExecutorsManifest

A package's executors.json.
Properties
§executors?:Record<string, ExecutorEntry>The executors by name.
§interface

ExecutorSource

Where an executor lives.
Properties
§readonly file:stringThe module implementing it, absolute.
§readonly schema:ExecutorSchemaThe schema of its options.
§interface

GeneratorEntry

One generator of a generators manifest.
Properties
§factory:stringThe module whose default export implements it, relative to the manifest.
§schema:stringThe schema of its options, relative to the manifest.
§description?:stringWhat it does.
§interface

GeneratorsManifest

A package's generators.json.
Properties
§generators?:Record<string, GeneratorEntry>The generators by name.
§interface

GeneratorSource

Where a generator lives.
Properties
§readonly file:stringThe module implementing it, absolute.
§readonly schema:GeneratorSchemaThe schema of its options.
§interface

LintSettings

The settings of the lint target the workspace infers for its projects.
Properties
§command?:stringThe command the inferred target runs from a project's root; {workspaceRoot} in it is the path from there to the workspace root. Defaults to hf-lint ..
§exclude?:string[]The project files whose projects get no inferred target, as globs.
§interface

ManyHost

What running the tasks needs.
Properties
§readonly runChild:(id: string, args: unknown) => Promise<number>Runs one task in a child, with the arguments after it; resolves to the exit code.
§readonly now:() => numberThe current time in milliseconds.
§readonly write:(line: string) => voidWrites a line to standard error.
§interface

ManyRequest

The tasks asked for and the arguments every requested task receives.
Properties
§readonly targets:unknownThe targets.
§readonly projects:unknownThe project names and globs, or null for every project.
§readonly args:unknownThe arguments after the selection, passed to each requested task.
§interface

PlannedTask

One task to run, in order.
Properties
§readonly id:string<project>:<target>.
§readonly requested:booleanWhether the task was asked for, rather than reached through dependsOn.
§readonly after:unknownThe tasks it runs after.
§interface

ProjectConfiguration

A project's configuration, as an executor reads it.
Properties
§name?:stringThe project's name.
§root:stringThe project's root, workspace-relative and POSIX.
§sourceRoot?:stringThe source root.
§projectType?:"application" | "library"application or library.
§tags?:string[]The tags.
§implicitDependencies?:string[]The projects this one depends on without importing them.
§targets?:Record<string, TargetConfiguration>The targets by name.
§metadata?:Readonly<Record<string, unknown>>Free-form metadata.
§interface

RunHost

Where a task runs and what it runs with.
Properties
§readonly cwd:stringThe directory the command line started in.
§readonly importModule:ImportModuleImports an executor's module.
§readonly root:stringThe workspace root, absolute.
§readonly env:EnvironmentThe environment the commands start from.
§readonly platform:stringThe platform, which decides how the search path is written.
§readonly execPath:stringThe running Node.js executable, whose directory joins the search path.
§readonly spawn:ShellSpawnStarts a command.
§readonly write:(line: string) => voidWrites a line of the runner's own: the command about to run, or why one failed.
§interface

SchemaProperty

One option of an executor's schema, as far as the runner reads it.
Properties
§readonly type?:stringThe JSON type.
§readonly default?:unknownThe value the option takes when a run leaves it unset.
§interface

StartedAs

What of a running process names the command line it was started as.
Properties
§readonly execPath:stringThe Node.js executable.
§readonly execArgv:unknownThe flags Node.js itself was given.
§readonly argv:unknownThe argument vector: the executable, the entry module, then the arguments.
§interface

TargetConfiguration

A target, as project.json and the targetDefaults of hf.json write it.
Properties
§executor?:stringThe executor, <package>:<name>.
§command?:stringA shell command, the short form of a run-commands target.
§options?:OptionsThe options the executor is called with.
§inputs?:unknownThe inputs whose change selects the target.
§dependsOn?:unknownThe tasks the target runs after.
§metadata?:Readonly<Record<string, unknown>>Free-form metadata.
§interface

TaskOutcome

How one task ended.
Properties
§readonly id:string<project>:<target>.
§readonly status:"succeeded" | "failed" | "skipped"Whether it ran and succeeded, ran and failed, or was skipped after a failed prerequisite.
§readonly durationMs:numberHow long it ran, in milliseconds; 0 when skipped.
§interface

TaskRef

A task named by its project and target.
Properties
§readonly project:stringThe project's name.
§readonly target:stringThe target.
§interface

Tree

A virtual file tree: reads fall through to the files, writes are recorded until committed.
Properties
§readonly root:stringThe directory every path is relative to, absolute.
Methods
§children(path: string): string[]
The names directly under a directory.

Parameters

NameTypeDescription
§path
string
§delete(path: string): void
Records a file's deletion.

Parameters

NameTypeDescription
§path
string
§exists(path: string): boolean
Whether a file or directory is there.

Parameters

NameTypeDescription
§path
string
§isFile(path: string): boolean
Whether the path names a file.

Parameters

NameTypeDescription
§path
string
§listChanges(): TreeChange[]
Every change recorded so far.
§read(path: string): Buffer<ArrayBufferLike>
The content of a file, or null when there is none.

Parameters

NameTypeDescription
§path
string
read(path: string, encoding: "utf-8"): string
The text of a file, or null when there is none.

Parameters

NameTypeDescription
§path
string
§encoding
"utf-8"
§write(path: string, content: string | Buffer<ArrayBufferLike>): void
Records a file's content.

Parameters

NameTypeDescription
§path
string
§content
string | Buffer<ArrayBufferLike>
§interface

TreeChange

One change a tree has recorded since it was opened.
Properties
§readonly path:stringThe path, relative to the tree's root, POSIX.
§readonly type:"CREATE" | "UPDATE" | "DELETE"What happened to the file.
§readonly content?:Buffer<ArrayBufferLike>The content written, or nothing for a deletion.
§interface

WorkspaceConfiguration

The workspace configuration, as hf.json writes it.
Properties
§targetDefaults?:Record<string, TargetConfiguration>The defaults of each target, by executor or by target name.
§namedInputs?:Record<string, unknown>The named inputs.
§lint?:LintSettingsThe inferred lint target's settings.

◆ Types

§type

Executor

An executor: the default export of the module an executors manifest names.
type Executor = (options: Options, context: ExecutorContext) => Promise<ExecutorResult> | ExecutorResult
§type

ExecutorFunction

An executor: called with the options and the context, it answers a promise of its result.
type ExecutorFunction = (options: Record<string, unknown>, context: ExecutorContext) => unknown
§type

ExecutorModule

A module as the runner reads it: its exports by name.
type ExecutorModule = Readonly<Record<string, unknown>>
§type

Generator

A generator: the default export of the module a generators manifest names.
type Generator = (tree: Tree, options: Options) => unknown
§type

ImportModule

Imports a module from its absolute path.
type ImportModule = (file: string) => Promise<ExecutorModule>

● Variables

§type

ENGINE_PACKAGE

The package whose generators answer to a bare name when no workspace project offers it.