@hyperfrontend/workspace/runnerrunner
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
<package>:<name>.Parameters
| Name | Type | Description |
|---|---|---|
§root | string | The workspace root, absolute |
§projects | ReadonlyMap< | The workspace's projects by name |
Returns
string[ ]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', ...]loadExecutor( source: ExecutorSource, importModule: ImportModule, executor: string): Promise< ExecutorFunction>
Parameters
| Name | Type | Description |
|---|---|---|
§source | ExecutorSource | Where the executor lives |
§importModule | ImportModule | Imports a module from its path |
§executor | string | The executor, for the error |
Returns
Promise< ExecutorFunction>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 passedloadGenerator( source: GeneratorSource, importModule: ImportModule, written: string): Promise< Generator>
Parameters
| Name | Type | Description |
|---|---|---|
§source | GeneratorSource | Where the generator lives |
§importModule | ImportModule | Imports a module from its absolute path |
§written | string | The generator as the command line names it, for the refusal |
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' })locateExecutor( root: string, projects: ReadonlyMap< string, ProjectRecord>, executor: string): ExecutorSource
Parameters
| Name | Type | Description |
|---|---|---|
§root | string | The workspace root, absolute |
§projects | ReadonlyMap< | The workspace's projects by name |
§executor | string | The executor, <package>:<name> |
Returns
ExecutorSourceExamples
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/toolinglocateGenerator( root: string, projects: ReadonlyMap< string, ProjectRecord>, written: string): GeneratorSource
Parameters
| Name | Type | Description |
|---|---|---|
§root | string | The workspace root, absolute |
§projects | ReadonlyMap< | The workspace's projects by name |
§written | string | The generator as the command line names it, <name> or <package>:<name> |
Returns
GeneratorSourceExamples
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 nameParameters
Returns
Promise< number>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"Parameters
| Name | Type | Description |
|---|---|---|
§outcomes | unknown | How each task ended |
Returns
string[ ]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']affected.Parameters
| Name | Type | Description |
|---|---|---|
§argv | unknown | The arguments after affected |
Returns
AffectedRequestExample
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: [] }run-many.Parameters
| Name | Type | Description |
|---|---|---|
§argv | unknown | The arguments after run-many |
Returns
ManyRequestExample
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: [] }Parameters
| Name | Type | Description |
|---|---|---|
§graph | WorkspaceGraph | The workspace graph |
§request | ManyRequest | The targets and projects asked for |
Returns
PlannedTask[ ]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'] },
// ]dependsOn reaches, each after its prerequisites, in the order given otherwise; a cycle is refused with its path.Parameters
| Name | Type | Description |
|---|---|---|
§graph | WorkspaceGraph | The workspace graph |
§tasks | unknown | The tasks asked for, each of a project of the graph |
Returns
PlannedTask[ ]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'] },
// ]runGenerator( tree: Tree, written: string, options: Record< string, unknown>, importModule: ImportModule): Promise< void>
Parameters
| Name | Type | Description |
|---|---|---|
§tree | Tree | The tree the generator edits, rooted at the workspace |
§written | string | The generator as the command line names it, <name> or <package>:<name> |
§options | Record< | The options the generator is called with |
§importModule | ImportModule | Imports a module from its absolute path; the process's own import when omitted(default: ...) |
Returns
Promise< void>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 featureLibraryParameters
Returns
Promise< TaskOutcome[ ]>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 }]Parameters
Returns
Promise< boolean>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 firstParameters
Returns
string[ ]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' })withDefaults( options: Readonly< Record< string, unknown>>, schema: ExecutorSchema): Record< string, unknown>
Parameters
| Name | Type | Description |
|---|---|---|
§options | Readonly< | The options of the target and the command line |
§schema | ExecutorSchema | The executor's options schema |
Returns
Record< string, unknown>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
Properties
Properties
projects:Record< string, ProjectConfiguration>Every project's configuration by name, targets resolved.Properties
Properties
Properties
executors.json.Properties
Properties
Properties
generators.json.Properties
Properties
lint target the workspace infers for its projects.Properties
Properties
Properties
Properties
Properties
Properties
readonly write:( line: string) => voidWrites a line of the runner's own: the command about to run, or why one failed.Properties
Properties
project.json and the targetDefaults of hf.json write it.Properties
Properties
Properties
Methods
listChanges( ): TreeChange[ ]read( path: string): Buffer< ArrayBufferLike>Parameters
| Name | Type | Description |
|---|---|---|
§path | string |
write( path: string, content: string | Buffer< ArrayBufferLike>): voidParameters
| Name | Type | Description |
|---|---|---|
§path | string | |
§content | string | Buffer< |
Properties
hf.json writes it.Properties
targetDefaults?:Record< string, TargetConfiguration>The defaults of each target, by executor or by target name.◆ Types
type Executor = ( options: Options, context: ExecutorContext) => Promise< ExecutorResult> | ExecutorResulttype ExecutorFunction = ( options: Record< string, unknown>, context: ExecutorContext) => unknowntype Generator = ( tree: Tree, options: Options) => unknowntype ImportModule = ( file: string) => Promise< ExecutorModule>