@hyperfrontend/workspace/generatorsgenerators
What the packaged generators are built from, so a generator of your own composes them on the same tree: the tree's JSON, project and template helpers, the names and paths a generator writes, the manifest and alias updates a rename needs, and the running of a generator by name.
| Generator | What it writes |
|---|---|
workspace | The root configuration the engine reads, into a repository that has none |
library | A TypeScript library with its project, manifest, configurations and a first spec |
make-publishable | The targets, manifest fields, README and e2e project a published package needs |
rename | A project's new name, carried into everything that refers to it |
move | A project under another directory, with its names, aliases and references brought along |
A local generator composes them by name through runGenerator, which resolves the name the way the command line does and runs the generator on the tree it is given:
import type { Generator } from '@hyperfrontend/workspace'
import { runGenerator, updateJson } from '@hyperfrontend/workspace/generators'
interface Options {
name: string
}
const service: Generator<Options> = async (tree, options) => {
await runGenerator(tree, 'library', {
name: options.name,
directory: 'services',
tags: ['type:service'],
})
updateJson<{ tags?: string[] }>(tree, `services/${options.name}/project.json`, (project) => ({
...project,
tags: [...(project.tags ?? []), 'scope:internal'],
}))
}
export default serviceAPI Reference§
ƒ Functions
Parameters
| Name | Type | Description |
|---|---|---|
§tree | Tree | The virtual file system tree |
§options | AddPathOptions | Options containing package name and project root |
Example
Registering a new library's alias
import { addTsConfigPath } from '@hyperfrontend/workspace/generators'
addTsConfigPath(tree, { packageName: '@acme/data-utils', projectRoot: 'libs/utils/data' })
// tsconfig.base.json compilerOptions.paths gains '@acme/data-utils': ['libs/utils/data/src/index.ts'], keys sortedblockBounds( lines: unknown, opens: ( line: string) => boolean, closes: ( line: string) => boolean, what: string): BlockBounds
Parameters
Returns
BlockBoundsExample
Locating the rules block of a lint configuration
const lines = ['export default [', ' {', ' rules: {', " 'a': 'error',", ' },', ' },', ']']
blockBounds(lines, (line) => line.trim() === 'rules: {', (line) => line.trim() === '},', 'the rules block')
// => { open: 2, close: 4 }
blockBounds(lines, (line) => line.trim() === 'ignores: [', (line) => line.trim() === '],', 'the ignores block')
// throws: the ignores block: the block that opens it was not foundParameters
| Name | Type | Description |
|---|---|---|
§version | string | A version such as 22.18.0 |
Returns
string.0 segments dropped, 22.18Example
Dropping the trailing zero segments
compactVersion('18.0.0') // '18'
compactVersion('20.10.5') // '20.10.5'.gitignore.Parameters
Returns
IgnoreRule[ ]Example
How the lines of a `.gitignore` are read
compileIgnoreRules('# build output\ndist/\n!dist/keep.txt\n', '')
// => [
// { negated: false, directoryOnly: true, anchored: false, glob: 'dist', base: '' },
// { negated: true, directoryOnly: false, anchored: true, glob: 'dist/keep.txt', base: '' },
// ]Parameters
Returns
numberExample
The search starts where told
const lines = ['import a from "a"', '', 'export default [', ' a,', ']']
findLine(lines, (line) => line.startsWith('export default'), 0) // => 2
findLine(lines, (line) => line === ']', 3) // => 4
findLine(lines, (line) => line.startsWith('import'), 1) // => -1Parameters
Returns
Promise< void>Example
The last step of a generator
import type { Generator } from '@hyperfrontend/workspace/generators'
import { formatFiles, writeJson } from '@hyperfrontend/workspace/generators'
const addConfig: Generator<{ project: string; skipFormat?: boolean }> = async (tree, options) => {
writeJson(tree, `libs/${options.project}/custom.json`, { enabled: true })
if (!options.skipFormat) await formatFiles(tree)
}generateFiles( tree: Tree, source: string, target: string, substitutions: Substitutions, options: GenerateFilesOptions): void
Parameters
| Name | Type | Description |
|---|---|---|
§tree | Tree | The tree written to |
§source | string | The template directory, absolute |
§target | string | The directory the files land under, relative to the tree's root |
§substitutions | Substitutions | The values the templates name |
§options | GenerateFilesOptions | Whether files already there are kept(default: {}) |
Example
A generator's `files` directory written under the project
import { join } from 'node:path'
import { generateFiles, names } from '@hyperfrontend/workspace/generators'
// files/src/index.ts.template holds: export const <%= names.propertyName %> = '<%= names.name %>'
generateFiles(tree, join(import.meta.dirname, 'files'), 'libs/data-utils', { names: names('data-utils') }, { keepExisting: true })
// writes libs/data-utils/src/index.ts holding "export const dataUtils = 'data-utils'", unless the file is already thereParameters
Returns
stringExample
Telling a package from a bare project
getPackageNameFromProject(tree, 'libs/core') // => '@acme/core'
getPackageNameFromProject(tree, 'apps/docs') // => nullReturns
Map< string, ProjectConfiguration>Example
A project the same run created is already there
import { getProjects, writeJson } from '@hyperfrontend/workspace/generators'
writeJson(tree, 'libs/data/project.json', { projectType: 'library' })
getProjects(tree).get('data') // => { name: 'data', root: 'libs/data', projectType: 'library' }, named after its directory@scope/my-lib giving ScopeMyLib.Parameters
| Name | Type | Description |
|---|---|---|
§packageName | string | A package name, scoped or not |
Returns
stringExample
The scope becomes part of the global
globalNameOf('@acme/data-utils') // => 'AcmeDataUtils'
globalNameOf('data-utils') // => 'DataUtils'Parameters
| Name | Type | Description |
|---|---|---|
§line | string | One line of the file |
Returns
stringExample
Matching the indentation of a neighbouring line
indentOf(' rules: {') // => ' '
indentOf('\tcommand: "hf-lint .",') // => '\t'
indentOf('export default [') // => ''Parameters
Returns
booleanExample
The last matching rule decides
const rules = compileIgnoreRules('dist/\n!dist/keep.txt\n', '')
isIgnored('libs/core/dist', true, rules) // => true
isIgnored('dist/keep.txt', false, rules) // => false
isIgnored('dist', false, rules) // => false: the rule names directories aloneReturns
stringExample
Editing a line and writing the file back byte for byte
const text = splitLines(tree.read('lint.base.config.ts', 'utf-8') ?? '')
text.lines.splice(3, 0, " '@acme/lint-rules',")
tree.write('lint.base.config.ts', joinLines(text)) // the file keeps its CRLF or LF endingsParameters
| Name | Type | Description |
|---|---|---|
§...fragments | unknown | The parts of the path |
Returns
stringExample
A path fit for a configuration file, whatever the platform
joinPathFragments('libs', 'utils\\data', './package.json') // => 'libs/utils/data/package.json'Parameters
| Name | Type | Description |
|---|---|---|
§tree | Tree | The virtual file system tree |
§options | MovePathOptions | Options with current/new roots and package names |
Example
Moving the aliases with the directory, keeping the name
moveTsConfigPaths(tree, {
currentProjectRoot: 'libs/core',
newProjectRoot: 'packages/core',
currentPackageName: '@acme/core',
newPackageName: '@acme/core',
updateName: false,
})
// '@acme/core': ['libs/core/src/index.ts'] became '@acme/core': ['packages/core/src/index.ts']Parameters
| Name | Type | Description |
|---|---|---|
§name | string | Any spelling, such as my-lib, myLib or MY_LIB |
Returns
NamesExample
The forms a template reads
names('data-utils')
// => { name: 'data-utils', className: 'DataUtils', propertyName: 'dataUtils', constantName: 'DATA_UTILS', fileName: 'data-utils' }
names('DataUtils').fileName // => 'data-utils'Parameters
| Name | Type | Description |
|---|---|---|
§range | string | An engines range such as >=22.18.0 |
Returns
string22.18.0Example
Reading the floor of an engines range
nodeFloorOf('>=18.0.0') // '18.0.0'
nodeFloorOf('^20.10 || >=22') // '20.10'../ per segment.Parameters
| Name | Type | Description |
|---|---|---|
§directory | string | A directory relative to the root, such as libs/utils/data |
Returns
string./ for the root itself, else ../ repeated once per segmentExample
Pointing a project's tsconfig at the base one
`${offsetFromRoot('libs/utils/data')}tsconfig.base.json` // => '../../../tsconfig.base.json'
offsetFromRoot('.') // => './'Parameters
| Name | Type | Description |
|---|---|---|
§root | string | The workspace root, absolute |
Returns
PrettierExample
Formatting a text with the workspace's prettier and configuration
const prettier = prettierOf(tree.root)
const options = { ...(await prettier.resolveConfig(`${tree.root}/libs/core/src/index.ts`, { editorconfig: true })), filepath: 'index.ts' }
await prettier.format('export const a={b:1}', options) // => "export const a = { b: 1 }\n"Parameters
| Name | Type | Description |
|---|---|---|
§value | string | The text |
Returns
stringExample
Writing a path into TypeScript source
quote('@acme/core') // => "'@acme/core'"
quote("it's") // => "'it\\'s'"
quote('C:\\repo') // => "'C:\\\\repo'"Parameters
Returns
ValueExample
Reading a manifest the tree holds
import { readJson } from '@hyperfrontend/workspace/generators'
readJson<{ name: string; version: string }>(tree, 'libs/core/package.json') // => { name: '@acme/core', version: '1.0.0' }
readJson(tree, 'libs/core/missing.json') // throws: Cannot find libs/core/missing.jsonParameters
Returns
PackageJsonInfoExample
A project with and without a manifest
readPackageJsonInfo(tree, 'libs/core') // => { name: '@acme/core', description: 'Core library.', keywords: ['core', 'acme'] }
readPackageJsonInfo(tree, 'apps/docs') // => { name: null, description: '', keywords: [] } when apps/docs has no package.jsonReturns
ProjectConfigurationExample
The root a generator writes under
const project = readProjectConfiguration(tree, 'lib-core')
// => { name: 'lib-core', root: 'libs/core', projectType: 'library', targets: { build: { ... } } }
tree.write(`${project.root}/src/generated.ts`, 'export const generated = true\n')package.json of the tree, or nothing when the tree has none.Returns
RootManifestExample
What a new package inherits
import { readRootManifest, scopeOf } from '@hyperfrontend/workspace/generators'
const root = readRootManifest(tree)
// => { name: '@acme/workspace', license: 'MIT', repository: { type: 'git', url: 'https://github.com/acme/workspace.git' } }
scopeOf(root.name ?? '') // => '@acme'@pkg/sub). Maintains alphabetical sorting.Parameters
| Name | Type | Description |
|---|---|---|
§tree | Tree | The virtual file system tree |
§options | RenamePathOptions | Options with current and new package names |
Example
The entry points of a package are renamed with it
renameTsConfigPaths(tree, { currentPackageName: '@acme/core', newPackageName: '@acme/kernel' })
// '@acme/core' and '@acme/core/testing' became '@acme/kernel' and '@acme/kernel/testing'; '@acme/core-ui' is untouched.replace("search", "replacement") applied; a missing member renders as nothing.Parameters
| Name | Type | Description |
|---|---|---|
§expression | string | The text between <%= and %> |
§substitutions | Substitutions | The values |
Returns
stringExample
Dotted paths and the one call a template may make
const substitutions = { names: names('data-utils'), packageName: '@acme/data-utils' }
renderExpression('names.className', substitutions) // => 'DataUtils'
renderExpression('packageName.replace("@", "")', substitutions) // => 'acme/data-utils'
renderExpression('names.missing', substitutions) // => ''
renderExpression('other', substitutions) // throws: other is not defined for the template<%= expression %> rendered.Parameters
| Name | Type | Description |
|---|---|---|
§template | string | The template text |
§substitutions | Substitutions | The values |
Returns
stringExample
Rendering one template text
renderTemplate('export class <%= names.className %> {}\n', { names: names('data-utils') })
// => 'export class DataUtils {}\n'replaceDescriptionPackageName( json: JsonWithDescription, currentPackageName: string, newPackageName: string): void
Parameters
| Name | Type | Description |
|---|---|---|
§json | JsonWithDescription | The JSON object to update |
§currentPackageName | string | Package name to replace |
§newPackageName | string | Replacement package name |
Example
Inside an `updateJson` updater
import type { NamedJson } from '@hyperfrontend/workspace/generators'
import { replaceDescriptionPackageName, updateJson } from '@hyperfrontend/workspace/generators'
updateJson<NamedJson>(tree, 'e2e/core/project.json', (json) => {
replaceDescriptionPackageName(json, '@acme/core', '@acme/kernel')
return json // description "E2E tests for @acme/core" now reads "E2E tests for @acme/kernel"
})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
string@scope/name, or the name aloneExample
Renaming a package under its current scope
scopedName(scopeOf('@acme/core'), 'kernel') // => '@acme/kernel'
scopedName(undefined, 'kernel') // => 'kernel'Parameters
| Name | Type | Description |
|---|---|---|
§packageName | string | A package name, scoped or not |
Returns
string@, or undefined for an unscoped nameExample
Scoped and unscoped names
scopeOf('@acme/core') // => '@acme'
scopeOf('lodash') // => undefinedReturns
Record< string, string[ ]>Example
A stable order for the alias map
sortPaths({ '@acme/utils': ['libs/utils/src/index.ts'], '@acme/core': ['libs/core/src/index.ts'] })
// => { '@acme/core': ['libs/core/src/index.ts'], '@acme/utils': ['libs/utils/src/index.ts'] }Parameters
| Name | Type | Description |
|---|---|---|
§content | string | The text to split |
Returns
TextLinesExample
The ending is remembered, not normalised
splitLines('a\r\nb\r\n') // => { lines: ['a', 'b', ''], eol: '\r\n' }
splitLines('a\nb') // => { lines: ['a', 'b'], eol: '\n' }Parameters
| Name | Type | Description |
|---|---|---|
§packageName | string | A package name, scoped or not |
Returns
stringExample
The name a directory takes
unscopedName('@acme/core') // => 'core'
unscopedName('lodash') // => 'lodash'Parameters
| Name | Type | Description |
|---|---|---|
§tree | Tree | The virtual file system tree |
§options | UpdateContentOptions | Options containing project root and package names |
Example
Carrying a package's new name into its prose
import { updateContentReferences } from '@hyperfrontend/workspace/generators'
updateContentReferences(tree, { projectRoot: 'libs/core', currentPackageName: '@acme/core', newPackageName: '@acme/kernel' })
// libs/core/README.md and the @module header of libs/core/src/index.ts now say @acme/kernelParameters
Example
Adding a target to an existing project
import type { ProjectConfiguration } from '@hyperfrontend/workspace/generators'
import { updateJson } from '@hyperfrontend/workspace/generators'
updateJson<ProjectConfiguration>(tree, 'libs/core/project.json', (json) => {
json.targets = { ...json.targets, docs: { command: 'typedoc' } }
return json
})@module JSDoc tags in source files.Parameters
| Name | Type | Description |
|---|---|---|
§tree | Tree | The virtual file system tree |
§options | UpdateContentOptions | Options containing project root and package names |
Example
Only the entry's `@module` tag is rewritten
updateModuleJSDoc(tree, { projectRoot: 'libs/core', currentPackageName: '@acme/core', newPackageName: '@acme/kernel' })
// "@module @acme/core" in libs/core/src/index.ts now reads "@module @acme/kernel"; other mentions of the name stayimplicitDependencies and dependsOn entries.Parameters
| Name | Type | Description |
|---|---|---|
§tree | Tree | The tree the configurations live in |
§options | UpdateReferencesOptions | The current and new names, and the roots to skip |
Example
The projects that depend on a renamed one follow it
updateProjectReferences(tree, { currentProjectName: 'lib-core', newProjectName: 'lib-kernel' })
// e2e/core/project.json: implicitDependencies ['lib-core'] became ['lib-kernel']
// apps/shell/project.json: a target's dependsOn ['lib-core'] became ['lib-kernel']; '^build' entries are untouchedParameters
| Name | Type | Description |
|---|---|---|
§tree | Tree | The virtual file system tree |
§options | UpdateContentOptions | Options containing project root and package names |
Example
Every mention in the README follows the package
updateReadmeReferences(tree, { projectRoot: 'libs/core', currentPackageName: '@acme/core', newPackageName: '@acme/kernel' })
// "npm install @acme/core" in libs/core/README.md now reads "npm install @acme/kernel"; a project without a README is left aloneParameters
Example
Rewriting every source file of a project
import { visitNotIgnoredFiles } from '@hyperfrontend/workspace/generators'
visitNotIgnoredFiles(tree, 'libs/core', (path) => {
if (!path.endsWith('.ts')) return
const content = tree.read(path, 'utf-8') ?? ''
tree.write(path, content.replaceAll('@acme/core', '@acme/kernel'))
})
// libs/core/node_modules and anything libs/core/.gitignore lists are never visitedParameters
Example
A new project's manifest
writeJson(tree, 'libs/core/project.json', { name: 'lib-core', projectType: 'library', targets: { build: {} } })
tree.read('libs/core/project.json', 'utf-8') // => '{\n "name": "lib-core",\n "projectType": "library",\n "targets": {\n "build": {}\n }\n}\n'◈ Interfaces
Properties
Properties
.gitignore, read.Properties
Properties
Properties
Properties
Methods
project.json a generator reads, with the project's name and root settled.Properties
Properties
Properties
package.json as far as the generators read it: what every package of the workspace inherits from 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
Properties
Properties
◆ Types
type Generator = ( tree: Tree, options: Options) => unknown