# generators 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`](https://www.hyperfrontend.dev/docs/libraries/workspace/generators/workspace.md) | The root configuration the engine reads, into a repository that has none | | [`library`](https://www.hyperfrontend.dev/docs/libraries/workspace/generators/library.md) | A TypeScript library with its project, manifest, configurations and a first spec | | [`make-publishable`](https://www.hyperfrontend.dev/docs/libraries/workspace/generators/make-publishable.md) | The targets, manifest fields, README and e2e project a published package needs | | [`rename`](https://www.hyperfrontend.dev/docs/libraries/workspace/generators/rename.md) | A project's new name, carried into everything that refers to it | | [`move`](https://www.hyperfrontend.dev/docs/libraries/workspace/generators/move.md) | A project under another directory, with its names, aliases and references brought along | A local generator composes them by name through [`runGenerator`](https://www.hyperfrontend.dev/docs/libraries/workspace/generators/#api-runGenerator), which resolves the name the way the command line does and runs the generator on the tree it is given: ```ts import type { Generator } from '@hyperfrontend/workspace' import { runGenerator, updateJson } from '@hyperfrontend/workspace/generators' interface Options { name: string } const service: Generator = 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 service ``` ## API Reference ### Functions #### addTsConfigPath ```typescript function addTsConfigPath(tree: Tree, options: AddPathOptions): void ``` Add a new path mapping to tsconfig.base.json. Maintains alphabetical sorting. **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** ```typescript 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 sorted ``` #### blockBounds ```typescript function blockBounds(lines: unknown, opens: (line: string) => boolean, closes: (line: string) => boolean, what: string): BlockBounds ``` Locate a block by the line that opens it and the first later line that closes it. **Parameters** | Name | Type | Description | | --- | --- | --- | | `lines` | `unknown` | The lines to search | | `opens` | `(line: string) => boolean` | Recognises the opening line | | `closes` | `(line: string) => boolean` | Recognises the closing line | | `what` | `string` | Names the block in the error raised when it is not there | **Returns** `BlockBounds`: The indices of the opening and closing lines **Example: Locating the rules block of a lint configuration** ```typescript 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 found ``` #### compactVersion ```typescript function compactVersion(version: string): string ``` A version without the trailing zero segments a reader does not need. **Parameters** | Name | Type | Description | | --- | --- | --- | | `version` | `string` | A version such as `22.18.0` | **Returns** `string`: The version with trailing `.0` segments dropped, `22.18` **Example: Dropping the trailing zero segments** ```typescript compactVersion('18.0.0') // '18' compactVersion('20.10.5') // '20.10.5' ``` #### compileIgnoreRules ```typescript function compileIgnoreRules(text: string, base: string): IgnoreRule[] ``` The rules of one `.gitignore`. **Parameters** | Name | Type | Description | | --- | --- | --- | | `text` | `string` | The file's text | | `base` | `string` | The directory the file sits in, relative to the root, or an empty string | **Returns** `IgnoreRule[]`: The rules in order; comments and blank lines dropped **Example: How the lines of a `.gitignore` are read** ```typescript 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: '' }, // ] ``` #### findLine ```typescript function findLine(lines: unknown, matches: (line: string) => boolean, from: number): number ``` Find the first line a predicate accepts. **Parameters** | Name | Type | Description | | --- | --- | --- | | `lines` | `unknown` | The lines to search | | `matches` | `(line: string) => boolean` | The predicate | | `from` | `number` | The index to start searching at | **Returns** `number`: The index of the first matching line, or -1 when none matches **Example: The search starts where told** ```typescript 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) // => -1 ``` #### formatFiles ```typescript function formatFiles(tree: Tree, prettier: Prettier): Promise ``` Formats every created or updated file of the tree in place. **Parameters** | Name | Type | Description | | --- | --- | --- | | `tree` | `Tree` | The tree whose changes are formatted | | `prettier` | `Prettier` | The prettier to format with; the workspace's own when omitted (default: `...`) | **Returns** `Promise`: Resolves when every file is written back **Example: The last step of a generator** ```typescript 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 ```typescript function generateFiles(tree: Tree, source: string, target: string, substitutions: Substitutions, options: GenerateFilesOptions): void ``` Writes every file of a template directory under a target directory of the tree. **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** ```typescript 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 there ``` #### getPackageNameFromProject ```typescript function getPackageNameFromProject(tree: Tree, projectRoot: string): string ``` Get package name from a project's package.json file. **Parameters** | Name | Type | Description | | --- | --- | --- | | `tree` | `Tree` | The virtual file system tree | | `projectRoot` | `string` | The project root path | **Returns** `string`: The package name or null if not found **Example: Telling a package from a bare project** ```typescript getPackageNameFromProject(tree, 'libs/core') // => '@acme/core' getPackageNameFromProject(tree, 'apps/docs') // => null ``` #### getProjects ```typescript function getProjects(tree: Tree): Map ``` Every project of the tree, by name. **Parameters** | Name | Type | Description | | --- | --- | --- | | `tree` | `Tree` | The tree read | **Returns** `Map`: The projects, in path order **Example: A project the same run created is already there** ```typescript 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 ``` #### globalNameOf ```typescript function globalNameOf(packageName: string): string ``` The global a browser bundle of a package registers under: the scope and the name as one class name, `@scope/my-lib` giving `ScopeMyLib`. **Parameters** | Name | Type | Description | | --- | --- | --- | | `packageName` | `string` | A package name, scoped or not | **Returns** `string`: The identifier a browser attaches the bundle under **Example: The scope becomes part of the global** ```typescript globalNameOf('@acme/data-utils') // => 'AcmeDataUtils' globalNameOf('data-utils') // => 'DataUtils' ``` #### indentOf ```typescript function indentOf(line: string): string ``` The leading whitespace of a line. **Parameters** | Name | Type | Description | | --- | --- | --- | | `line` | `string` | One line of the file | **Returns** `string`: Its indentation, empty for a line that starts at the margin **Example: Matching the indentation of a neighbouring line** ```typescript indentOf(' rules: {') // => ' ' indentOf('\tcommand: "hf-lint .",') // => '\t' indentOf('export default [') // => '' ``` #### isIgnored ```typescript function isIgnored(path: string, isDirectory: boolean, rules: unknown): boolean ``` Whether git would ignore a path under the rules in force. **Parameters** | Name | Type | Description | | --- | --- | --- | | `path` | `string` | The path relative to the root | | `isDirectory` | `boolean` | Whether the path names a directory | | `rules` | `unknown` | The rules in order, the deepest `.gitignore` last | **Returns** `boolean`: True when the last matching rule ignores it **Example: The last matching rule decides** ```typescript 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 alone ``` #### joinLines ```typescript function joinLines(text: TextLines): string ``` Join lines back into a text with the ending they were split from. **Parameters** | Name | Type | Description | | --- | --- | --- | | `text` | `TextLines` | The lines and their ending | **Returns** `string`: The text **Example: Editing a line and writing the file back byte for byte** ```typescript 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 endings ``` #### joinPathFragments ```typescript function joinPathFragments(...fragments: unknown): string ``` Fragments joined and normalised as a POSIX path; a native path among them is made portable first. **Parameters** | Name | Type | Description | | --- | --- | --- | | `...fragments` | `unknown` | The parts of the path | **Returns** `string`: The joined path with forward slashes **Example: A path fit for a configuration file, whatever the platform** ```typescript joinPathFragments('libs', 'utils\\data', './package.json') // => 'libs/utils/data/package.json' ``` #### moveTsConfigPaths ```typescript function moveTsConfigPaths(tree: Tree, options: MovePathOptions): void ``` Update path mappings for a moved project in tsconfig.base.json. Updates both the key (package name) and value (file path). Maintains alphabetical sorting. **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** ```typescript 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'] ``` #### names ```typescript function names(name: string): Names ``` The forms of a name. **Parameters** | Name | Type | Description | | --- | --- | --- | | `name` | `string` | Any spelling, such as `my-lib`, `myLib` or `MY_LIB` | **Returns** `Names`: The class, property, constant and file forms **Example: The forms a template reads** ```typescript names('data-utils') // => { name: 'data-utils', className: 'DataUtils', propertyName: 'dataUtils', constantName: 'DATA_UTILS', fileName: 'data-utils' } names('DataUtils').fileName // => 'data-utils' ``` #### nodeFloorOf ```typescript function nodeFloorOf(range: string): string ``` The lowest version an engines range names: the first version number in it. **Parameters** | Name | Type | Description | | --- | --- | --- | | `range` | `string` | An engines range such as `>=22.18.0` | **Returns** `string`: The version, `22.18.0` **Example: Reading the floor of an engines range** ```typescript nodeFloorOf('>=18.0.0') // '18.0.0' nodeFloorOf('^20.10 || >=22') // '20.10' ``` #### offsetFromRoot ```typescript function offsetFromRoot(directory: string): string ``` The relative path from a directory back to the root it is under: one `../` 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 segment **Example: Pointing a project's tsconfig at the base one** ```typescript `${offsetFromRoot('libs/utils/data')}tsconfig.base.json` // => '../../../tsconfig.base.json' offsetFromRoot('.') // => './' ``` #### prettierOf ```typescript function prettierOf(root: string): Prettier ``` The prettier a workspace installs, resolved from its root the way any module of the workspace resolves it. **Parameters** | Name | Type | Description | | --- | --- | --- | | `root` | `string` | The workspace root, absolute | **Returns** `Prettier`: Its API **Example: Formatting a text with the workspace's prettier and configuration** ```typescript 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" ``` #### quote ```typescript function quote(value: string): string ``` Write a value as a single-quoted TypeScript string literal. **Parameters** | Name | Type | Description | | --- | --- | --- | | `value` | `string` | The text | **Returns** `string`: The literal, with backslashes and quotes escaped **Example: Writing a path into TypeScript source** ```typescript quote('@acme/core') // => "'@acme/core'" quote("it's") // => "'it\\'s'" quote('C:\\repo') // => "'C:\\\\repo'" ``` #### readJson ```typescript function readJson(tree: Tree, path: string): Value ``` The value of a JSON file of the tree. **Parameters** | Name | Type | Description | | --- | --- | --- | | `tree` | `Tree` | The tree the file is read from | | `path` | `string` | The file, relative to the root | **Returns** `Value`: The parsed value **Example: Reading a manifest the tree holds** ```typescript 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.json ``` #### readPackageJsonInfo ```typescript function readPackageJsonInfo(tree: Tree, projectRoot: string): PackageJsonInfo ``` Read package name, description and keywords from a project's package.json. **Parameters** | Name | Type | Description | | --- | --- | --- | | `tree` | `Tree` | The virtual file system tree | | `projectRoot` | `string` | The project root path | **Returns** `PackageJsonInfo`: Package name and description **Example: A project with and without a manifest** ```typescript 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.json ``` #### readProjectConfiguration ```typescript function readProjectConfiguration(tree: Tree, name: string): ProjectConfiguration ``` One project of the tree. **Parameters** | Name | Type | Description | | --- | --- | --- | | `tree` | `Tree` | The tree the project is read from | | `name` | `string` | Which project | **Returns** `ProjectConfiguration`: Its configuration **Example: The root a generator writes under** ```typescript 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') ``` #### readRootManifest ```typescript function readRootManifest(tree: Tree): RootManifest ``` The root `package.json` of the tree, or nothing when the tree has none. **Parameters** | Name | Type | Description | | --- | --- | --- | | `tree` | `Tree` | The tree whose root is looked at | **Returns** `RootManifest`: The manifest's fields the generators inherit from **Example: What a new package inherits** ```typescript 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' ``` #### renameTsConfigPaths ```typescript function renameTsConfigPaths(tree: Tree, options: RenamePathOptions): void ``` Rename path mappings in tsconfig.base.json. Handles both exact matches and prefixed paths (e.g., `@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** ```typescript 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 ``` #### renderExpression ```typescript function renderExpression(expression: string, substitutions: Substitutions): string ``` The text an expression renders as: the value a dotted path names, optionally with one `.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** `string`: The text **Example: Dotted paths and the one call a template may make** ```typescript 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 ``` #### renderTemplate ```typescript function renderTemplate(template: string, substitutions: Substitutions): string ``` A template with every `<%= expression %>` rendered. **Parameters** | Name | Type | Description | | --- | --- | --- | | `template` | `string` | The template text | | `substitutions` | `Substitutions` | The values | **Returns** `string`: The rendered text **Example: Rendering one template text** ```typescript renderTemplate('export class <%= names.className %> {}\n', { names: names('data-utils') }) // => 'export class DataUtils {}\n' ``` #### replaceDescriptionPackageName ```typescript function replaceDescriptionPackageName(json: JsonWithDescription, currentPackageName: string, newPackageName: string): void ``` Update description field by replacing package name references. Mutates the json object in place for use inside updateJson callbacks. **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** ```typescript import type { NamedJson } from '@hyperfrontend/workspace/generators' import { replaceDescriptionPackageName, updateJson } from '@hyperfrontend/workspace/generators' updateJson(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 ```typescript function runGenerator(tree: Tree, written: string, options: Record, importModule: ImportModule): Promise ``` 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** | Name | Type | Description | | --- | --- | --- | | `tree` | `Tree` | The tree the generator edits, rooted at the workspace | | `written` | `string` | The generator as the command line names it, `` or `:` | | `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`: Resolves when the generator has run **Example: A workspace generator composing the packaged `library` generator** ```typescript 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 ``` #### scopedName ```typescript function scopedName(scope: string, name: string): string ``` The package name a scope and a name make. **Parameters** | Name | Type | Description | | --- | --- | --- | | `scope` | `string` | The scope with its `@`, or undefined for no scope | | `name` | `string` | The name under the scope | **Returns** `string`: `@scope/name`, or the name alone **Example: Renaming a package under its current scope** ```typescript scopedName(scopeOf('@acme/core'), 'kernel') // => '@acme/kernel' scopedName(undefined, 'kernel') // => 'kernel' ``` #### scopeOf ```typescript function scopeOf(packageName: string): string ``` The scope of a package name. **Parameters** | Name | Type | Description | | --- | --- | --- | | `packageName` | `string` | A package name, scoped or not | **Returns** `string`: The scope with its `@`, or undefined for an unscoped name **Example: Scoped and unscoped names** ```typescript scopeOf('@acme/core') // => '@acme' scopeOf('lodash') // => undefined ``` #### sortPaths ```typescript function sortPaths(paths: Record): Record ``` Sort paths object alphabetically by key. **Parameters** | Name | Type | Description | | --- | --- | --- | | `paths` | `Record` | The paths object to sort | **Returns** `Record`: Sorted paths object **Example: A stable order for the alias map** ```typescript 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'] } ``` #### splitLines ```typescript function splitLines(content: string): TextLines ``` Split a text into lines, keeping the line ending it uses. **Parameters** | Name | Type | Description | | --- | --- | --- | | `content` | `string` | The text to split | **Returns** `TextLines`: The lines and their ending **Example: The ending is remembered, not normalised** ```typescript splitLines('a\r\nb\r\n') // => { lines: ['a', 'b', ''], eol: '\r\n' } splitLines('a\nb') // => { lines: ['a', 'b'], eol: '\n' } ``` #### unscopedName ```typescript function unscopedName(packageName: string): string ``` A package name without its scope. **Parameters** | Name | Type | Description | | --- | --- | --- | | `packageName` | `string` | A package name, scoped or not | **Returns** `string`: The part after the scope's slash, or the name as given **Example: The name a directory takes** ```typescript unscopedName('@acme/core') // => 'core' unscopedName('lodash') // => 'lodash' ``` #### updateContentReferences ```typescript function updateContentReferences(tree: Tree, options: UpdateContentOptions): void ``` Update all content references (README + JSDoc). Convenience function combining updateReadmeReferences and updateModuleJSDoc. **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** ```typescript 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/kernel ``` #### updateJson ```typescript function updateJson(tree: Tree, path: string, updater: (value: Value) => Value): void ``` Rewrites a JSON file through an updater. **Parameters** | Name | Type | Description | | --- | --- | --- | | `tree` | `Tree` | The tree the file lives in | | `path` | `string` | The file, relative to the root | | `updater` | `(value: Value) => Value` | Maps the current value to the one written | **Example: Adding a target to an existing project** ```typescript import type { ProjectConfiguration } from '@hyperfrontend/workspace/generators' import { updateJson } from '@hyperfrontend/workspace/generators' updateJson(tree, 'libs/core/project.json', (json) => { json.targets = { ...json.targets, docs: { command: 'typedoc' } } return json }) ``` #### updateModuleJSDoc ```typescript function updateModuleJSDoc(tree: Tree, options: UpdateContentOptions): void ``` Update `@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** ```typescript 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 stay ``` #### updateProjectReferences ```typescript function updateProjectReferences(tree: Tree, options: UpdateReferencesOptions): void ``` Renames a project in every other project's `implicitDependencies` 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** ```typescript 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 untouched ``` #### updateReadmeReferences ```typescript function updateReadmeReferences(tree: Tree, options: UpdateContentOptions): void ``` Update README.md with new package name references. **Parameters** | 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** ```typescript 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 alone ``` #### visitNotIgnoredFiles ```typescript function visitNotIgnoredFiles(tree: Tree, directory: string, visitor: (path: string) => void): void ``` Visits every file under a directory of the tree that git would not ignore. **Parameters** | Name | Type | Description | | --- | --- | --- | | `tree` | `Tree` | The tree walked | | `directory` | `string` | Where to start, relative to the root; an empty string or `.` for the root | | `visitor` | `(path: string) => void` | Called with each file's path relative to the root | **Example: Rewriting every source file of a project** ```typescript 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 visited ``` #### writeJson ```typescript function writeJson(tree: Tree, path: string, value: unknown): void ``` Writes a value as two-space JSON with a trailing newline. **Parameters** | Name | Type | Description | | --- | --- | --- | | `tree` | `Tree` | The tree the file is written to | | `path` | `string` | The file, relative to the root | | `value` | `unknown` | What to write | **Example: A new project's manifest** ```typescript 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 #### AddPathOptions Options for adding a new path mapping. **Properties** | Name | Type | Description | | --- | --- | --- | | `packageName` | `string` | npm package name (e.g., '@hyperfrontend/data-utils') | | `projectRoot` | `string` | Project root path (e.g., 'libs/utils/data') | #### BlockBounds The first and last line of a bracketed block. **Properties** | Name | Type | Description | | --- | --- | --- | | `open` | `number` | Index of the line that opens the block | | `close` | `number` | Index of the line that closes the block | #### Funding Where sponsorship of a package goes. **Properties** | Name | Type | Description | | --- | --- | --- | | `type?` | `string` | The platform | | `url?` | `string` | The page | #### IgnoreRule One line of a `.gitignore`, read. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly negated` | `boolean` | Whether a match re-includes the path. | | `readonly directoryOnly` | `boolean` | Whether the rule matches directories alone. | | `readonly anchored` | `boolean` | Whether the pattern names a path under the ignore file's directory rather than a name at any depth. | | `readonly glob` | `string` | The glob, without its anchors. | | `readonly base` | `string` | The directory the ignore file sits in, relative to the root, or an empty string. | #### JsonWithDescription JSON object with an optional description field. **Properties** | Name | Type | Description | | --- | --- | --- | | `description?` | `unknown` | Optional description text | #### MovePathOptions Options for moving path mappings. **Properties** | Name | Type | Description | | --- | --- | --- | | `currentProjectRoot` | `string` | Current project root path | | `newProjectRoot` | `string` | New project root path | | `currentPackageName` | `string` | Current npm package name | | `newPackageName` | `string` | New npm package name | | `updateName` | `boolean` | Whether the name is being updated | #### NamedJson A project or package manifest as far as a rename reads it. **Properties** | Name | Type | Description | | --- | --- | --- | | `description?` | `unknown` | Optional description text | | `name?` | `string` | The project or package name | #### Names The forms of a name. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly name` | `string` | The name as given. | | `readonly className` | `string` | UpperCamelCase. | | `readonly propertyName` | `string` | lowerCamelCase. | | `readonly constantName` | `string` | CONSTANT_CASE. | | `readonly fileName` | `string` | lower-hyphenated. | #### PackageJsonInfo Result of reading package.json metadata. **Properties** | Name | Type | Description | | --- | --- | --- | | `name` | `string` | Package name or null if not found | | `description` | `string` | Package description or empty string | | `keywords` | `string[]` | npm keywords, empty when the package declares none | #### Prettier The part of prettier's API that formatting the tree uses. ##### format ```typescript format(source: string, options: Record): Promise ``` Formats a text with options. **Parameters** | Name | Type | Description | | --- | --- | --- | | `source` | `string` | | | `options` | `Record` | | ##### getFileInfo ```typescript getFileInfo(file: string, options: FileInfoOptions): Promise ``` Whether a file is ignored and which parser handles it. **Parameters** | Name | Type | Description | | --- | --- | --- | | `file` | `string` | | | `options` | `FileInfoOptions` | | ##### resolveConfig ```typescript resolveConfig(file: string, options: ResolveConfigOptions): Promise> ``` The configuration that applies to a file, or null when none does. **Parameters** | Name | Type | Description | | --- | --- | --- | | `file` | `string` | | | `options` | `ResolveConfigOptions` | | #### ProjectConfiguration The parts of a `project.json` a generator reads, with the project's name and root settled. **Properties** | Name | Type | Description | | --- | --- | --- | | `name` | `string` | The project's name: the file's, or its directory's. | | `root` | `string` | The project's directory, relative to the root. | | `sourceRoot?` | `string` | Where its sources live. | | `description?` | `string` | What the project is for. | | `projectType?` | `string` | The kind of project. | | `tags?` | `string[]` | The tags the module boundaries read. | | `implicitDependencies?` | `string[]` | Projects depended on without an import. | | `targets?` | `Record` | The targets, by name. | | `metadata?` | `Record` | Free-form metadata. | #### RenamePathOptions Options for renaming path mappings. **Properties** | Name | Type | Description | | --- | --- | --- | | `currentPackageName` | `string` | Current npm package name | | `newPackageName` | `string` | New npm package name | #### Repository Where a repository's packages are kept, as the root manifest states it. **Properties** | Name | Type | Description | | --- | --- | --- | | `type?` | `string` | The kind of repository, such as `git` | | `url?` | `string` | Its URL | | `directory?` | `string` | The directory of one package within it | #### RootManifest The root `package.json` as far as the generators read it: what every package of the workspace inherits from it. **Properties** | Name | Type | Description | | --- | --- | --- | | `name?` | `string` | The workspace's own name, whose scope its packages take | | `license?` | `string` | The licence its packages are under | | `repository?` | `string \| Repository` | The repository its packages are kept in | | `funding?` | `string \| Funding` | Where sponsorship goes | | `engines?` | `Record` | The engines its packages run on | #### TextLines A text split into lines, remembering the line ending it was written with so it can be joined back without changing a single byte it did not mean to. **Properties** | Name | Type | Description | | --- | --- | --- | | `lines` | `string[]` | The lines, without their endings | | `eol` | `string` | The ending every line was separated by | #### Tree A virtual file tree: reads fall through to the files, writes are recorded until committed. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly root` | `string` | The directory every path is relative to, absolute. | ##### children ```typescript children(path: string): string[] ``` The names directly under a directory. **Parameters** | Name | Type | Description | | --- | --- | --- | | `path` | `string` | | ##### delete ```typescript delete(path: string): void ``` Records a file's deletion. **Parameters** | Name | Type | Description | | --- | --- | --- | | `path` | `string` | | ##### exists ```typescript exists(path: string): boolean ``` Whether a file or directory is there. **Parameters** | Name | Type | Description | | --- | --- | --- | | `path` | `string` | | ##### isFile ```typescript isFile(path: string): boolean ``` Whether the path names a file. **Parameters** | Name | Type | Description | | --- | --- | --- | | `path` | `string` | | ##### listChanges ```typescript listChanges(): TreeChange[] ``` Every change recorded so far. ##### read ```typescript read(path: string): Buffer ``` The content of a file, or null when there is none. **Parameters** | Name | Type | Description | | --- | --- | --- | | `path` | `string` | | ```typescript read(path: string, encoding: "utf-8"): string ``` The text of a file, or null when there is none. **Parameters** | Name | Type | Description | | --- | --- | --- | | `path` | `string` | | | `encoding` | `"utf-8"` | | ##### write ```typescript write(path: string, content: string | Buffer): void ``` Records a file's content. **Parameters** | Name | Type | Description | | --- | --- | --- | | `path` | `string` | | | `content` | `string \| Buffer` | | #### TreeChange One change a tree has recorded since it was opened. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly path` | `string` | The path, relative to the tree's root, POSIX. | | `readonly type` | `"CREATE" \| "UPDATE" \| "DELETE"` | What happened to the file. | | `readonly content?` | `Buffer` | The content written, or nothing for a deletion. | #### UpdateContentOptions Options for updating content references. **Properties** | Name | Type | Description | | --- | --- | --- | | `projectRoot` | `string` | Project root path | | `currentPackageName` | `string` | Current npm package name | | `newPackageName` | `string` | New npm package name | #### UpdateReferencesOptions How a project is renamed in the configurations that refer to it. **Properties** | Name | Type | Description | | --- | --- | --- | | `currentProjectName` | `string` | The project's current name | | `newProjectName` | `string` | The project's new name | | `excludeRoots?` | `string[]` | The roots of projects whose configuration is left alone, such as the moved project's old and new roots | ### Types #### Generator A generator: the default export of the module a generators manifest names. ```typescript type Generator = (tree: Tree, options: Options) => unknown ``` #### Substitutions The values a template may name. ```typescript type Substitutions = Readonly> ``` ### Variables #### DEFAULT_NODE_ENGINE The Node.js range a package declares when it declares none of its own. ```typescript const DEFAULT_NODE_ENGINE: ">=18.0.0" ``` **Value** `'>=18.0.0'` #### DEFAULT_NPM_ENGINE The npm range a package declares when it declares none of its own. ```typescript const DEFAULT_NPM_ENGINE: ">=8.0.0" ``` **Value** `'>=8.0.0'` #### PRINT_WIDTH The line width the workspace's formatter wraps at. A transform that writes a line longer than this would be rewritten by the next format pass, so the transforms break such a line themselves and running them twice changes nothing. ```typescript const PRINT_WIDTH: 140 ``` **Value** `140` --- Canonical page: https://www.hyperfrontend.dev/docs/libraries/workspace/generators/ This file: https://www.hyperfrontend.dev/docs/libraries/workspace/generators.md Documentation index: https://www.hyperfrontend.dev/llms.txt