oneRepo API
Namespaces
Section titled “Namespaces”| Namespace | Description |
|---|---|
| builders | Common and reusable command-line option builders. |
| file | File manipulation functions. |
| git | Special handlers for managing complex queries and manipulation of the git repository’s state. |
Variables
Section titled “Variables”defaultConfig
Section titled “defaultConfig”const defaultConfig: Required<RootConfig>;Defined in: modules/onerepo/src/setup/setup.ts
Commands
Section titled “Commands”Argv<CommandArgv>
Section titled “Argv<CommandArgv>”type Argv<CommandArgv> = Arguments<CommandArgv & DefaultArgv>;Defined in: modules/yargs/src/yargs.ts
Helper for combining local parsed arguments along with the default arguments provided by the oneRepo command module.
Type Parameters
Section titled “Type Parameters”| Type Parameter | Default type | Description |
|---|---|---|
CommandArgv | object | Arguments that will be parsed for this command, always a union with `DefaultArgv` and `PositionalArgv`. |
Builder()<CommandArgv>
Section titled “Builder()<CommandArgv>”type Builder<CommandArgv> = (yargs) => Yargv<CommandArgv>;Defined in: modules/yargs/src/yargs.ts
Option argument parser for the given command. See Yargs .command(module) for more, but note that only the object variant is not accepted – only function variants will be accepted in oneRepo commands.
For common arguments that work in conjunction with `HandlerExtra` methods like getAffected(), you can use helpers from the `builders` namespace, like `builders.withAffected()`.
type Argv = { 'with-tacos'?: boolean;};
export const builder: Builder<Argv> = (yargs) => yargs.usage(`$0 ${command}`).option('with-tacos', { description: 'Include tacos', type: 'boolean', });Type Parameters
Section titled “Type Parameters”| Type Parameter | Default type | Description |
|---|---|---|
CommandArgv | object | Arguments that will be parsed for this command |
Parameters:
| Parameter | Type | Description |
|---|---|---|
yargs | Yargs | The Yargs instance. See Yargs .command(module) |
Returns: Yargv<CommandArgv>
See also:
- Yargs
.command(module)for general usage. - Common extensions via the `builders` namespace.
DefaultArgv
Section titled “DefaultArgv”type DefaultArgv = { dry-run: boolean; quiet: boolean; skip-engine-check: boolean; verbosity: number;};Defined in: modules/yargs/src/yargs.ts
Default: arguments provided globally for all commands. These arguments are included by when using `Builder` and `Handler`.
Properties
Section titled “Properties”dry-run
Section titled “dry-run”dry-run: boolean;Defined in: modules/yargs/src/yargs.ts
Whether the command should run non-destructive dry-mode. This prevents all subprocesses, files, and git operations from running unless explicitly specified as safe to run.
Also internally sets process.env.ONEREPO_DRY_RUN = 'true'.
Default: false
quiet: boolean;Defined in: modules/yargs/src/yargs.ts
Silence all logger output. Prevents all stdout and stderr output from the logger entirely.
Default: false
skip-engine-check
Section titled “skip-engine-check”skip-engine-check: boolean;Defined in: modules/yargs/src/yargs.ts
Skip the engines check. When false, oneRepo will the current process’s node version with the range for engines.node as defined in package.json. If not defined in the root package.json, this will be skipped.
Default: false
verbosity
Section titled “verbosity”verbosity: number;Defined in: modules/yargs/src/yargs.ts
Verbosity level for the Logger. See Logger.verbosity for more information.
Default: 3
Handler()<CommandArgv>
Section titled “Handler()<CommandArgv>”type Handler<CommandArgv> = (argv, extra) => Promise<void>;Defined in: modules/yargs/src/yargs.ts
Command handler that includes oneRepo tools like graph, logger, and more. This function is type-safe if Argv is correctly passed through to the type definition.
type Argv = { 'with-tacos'?: boolean;};export const handler: Handler<Argv> = (argv, { logger }) => { const { 'with-tacos': withTacos, '--': passthrough } = argv; logger.log(withTacos ? 'Include tacos' : 'No tacos, thanks'); logger.debug(passthrough);};Type Parameters
Section titled “Type Parameters”| Type Parameter | Default type | Description |
|---|---|---|
CommandArgv | object | Arguments that will be parsed for this command. DefaultArguments will be automatically merged into this object for use within the handler. |
Parameters:
| Parameter | Type |
|---|---|
argv | Argv<CommandArgv> |
extra | HandlerExtra |
Returns: Promise<void>
See also:
- Yargs
.command(module)for general usage. - `HandlerExtra` for extended extra arguments provided above and beyond the scope of Yargs.
HandlerExtra
Section titled “HandlerExtra”type HandlerExtra = { config: Required<RootConfig>; getAffected: (opts?) => Promise<Workspace[]>; getFilepaths: (opts?) => Promise<string[]>; getWorkspaces: (opts?) => Promise<Workspace[]>; graph: Graph; logger: Logger;};Defined in: modules/yargs/src/yargs.ts
Commands in oneRepo extend beyond what Yargs is able to provide by adding a second argument to the handler.
All extras are available as the second argument on your `Handler`
export const handler: Handler = (argv, { getAffected, getFilepaths, getWorkspace, logger }) => { logger.warn('Nothing to do!');};Overriding the affected threshold in getFilepaths
export const handler: Handler = (argv, { getFilepaths }) => { const filepaths = await getFilepaths({ affectedThreshold: 0 });};Properties
Section titled “Properties”config
Section titled “config”config: Required<RootConfig>;Defined in: modules/yargs/src/yargs.ts
This repository’s oneRepo config, resolved with all defaults.
getAffected()
Section titled “getAffected()”getAffected: (opts?) => Promise<Workspace[]>;Defined in: modules/yargs/src/yargs.ts
Get the affected Workspaces based on the current state of the repository.
This is a wrapped implementation of `builders.getAffected` that does not require passing the graph argument.
Parameters:
| Parameter | Type |
|---|---|
opts? | GetterOptions |
Returns: Promise<Workspace[]>
getFilepaths()
Section titled “getFilepaths()”getFilepaths: (opts?) => Promise<string[]>;Defined in: modules/yargs/src/yargs.ts
Get the affected filepaths based on the current inputs and state of the repository. Respects manual inputs provided by `builders.withFiles` if provided.
This is a wrapped implementation of `builders.getFilepaths` that does not require the graph and argv arguments.
Note: that when used with --affected, there is a default limit of 100 files before this will switch to returning affected Workspace paths. Use affectedThreshold: 0 to disable the limit.
Parameters:
| Parameter | Type |
|---|---|
opts? | FileGetterOptions |
Returns: Promise<string[]>
getWorkspaces()
Section titled “getWorkspaces()”getWorkspaces: (opts?) => Promise<Workspace[]>;Defined in: modules/yargs/src/yargs.ts
Get the affected Workspaces based on the current inputs and the state of the repository.
This function differs from getAffected in that it respects all input arguments provided by
`builders.withWorkspaces`, `builders.withFiles` and `builders.withAffected`.
This is a wrapped implementation of `builders.getWorkspaces` that does not require the graph and argv arguments.
Parameters:
| Parameter | Type |
|---|---|
opts? | GetterOptions |
Returns: Promise<Workspace[]>
graph: Graph;Defined in: modules/yargs/src/yargs.ts
The full monorepo `Graph`.
logger
Section titled “logger”logger: Logger;Defined in: modules/yargs/src/yargs.ts
Standard `Logger`. This should always be used in place of console.log methods unless you have
a specific need to write to standard out differently.
PositionalArgv
Section titled “PositionalArgv”type PositionalArgv = { _: (string | number)[]; --: string[]; $0: string;};Defined in: modules/yargs/src/yargs.ts
Always present in Builder and Handler arguments as parsed by Yargs.
Properties
Section titled “Properties”_: (string | number)[];Defined in: modules/yargs/src/yargs.ts
Positionals / non-option arguments. These will only be filled if you include .positional() or .strictCommands(false) in your Builder.
—
--: string[];Defined in: modules/yargs/src/yargs.ts
Any content that comes after ” — ” gets populated here. These are useful for spreading through to spawned run functions that may take extra options that you don’t want to enumerate and validate.
$0: string;Defined in: modules/yargs/src/yargs.ts
The script name or node command. Similar to process.argv[1]
Config
Section titled “Config”Config<CustomLifecycles>
Section titled “Config<CustomLifecycles>”type Config<CustomLifecycles> = RootConfig<CustomLifecycles> | WorkspaceConfig<CustomLifecycles>;Defined in: modules/onerepo/src/types/index.ts
Picks the correct config type between RootConfig and WorkspaceConfig based on whether the root property is set. Use this to help ensure your configs do not have any incorrect keys or values.
Satisfy a RootConfig:
import type { Config } from 'onerepo';
export default { root: true,} satisfies Config;Satisfy a WorkspaceConfig with custom lifecycles on tasks:
import type { Config } from 'onerepo';
export default { tasks: { stage: { serial: ['$0 build'], }, },} satisfies Config<'stage'>;Type Parameters
Section titled “Type Parameters”| Type Parameter | Default type |
|---|---|
CustomLifecycles extends string | void | void |
Lifecycle
Section titled “Lifecycle”type Lifecycle = | 'pre-commit' | 'post-commit' | 'post-checkout' | 'pre-merge' | 'post-merge' | 'pre-push' | 'build' | 'pre-deploy' | 'pre-publish' | 'post-publish';Defined in: modules/onerepo/src/types/tasks.ts
oneRepo comes with a pre-configured list of common lifecycles for grouping tasks.
RootConfig<CustomLifecycles>
Section titled “RootConfig<CustomLifecycles>”type RootConfig<CustomLifecycles> = { changes?: { filenames?: 'hash' | 'human'; formatting?: { commit?: string; footer?: string; }; prompts?: 'guided' | 'semver'; }; codeowners?: Record<string, string[]>; commands?: { directory?: string | false; ignore?: RegExp; }; dependencies?: { dedupe?: boolean; mode?: 'strict' | 'loose' | 'off'; }; head?: string; ignore?: string[]; meta?: Record<string, unknown>; plugins?: Plugin[]; root: true; taskConfig?: { lifecycles?: CustomLifecycles[]; stashUnstaged?: CustomLifecycles extends string ? Lifecycle | CustomLifecycles : Lifecycle[]; }; tasks?: TaskConfig<CustomLifecycles>; templateDir?: string; validation?: { schema?: string | null; }; vcs?: { autoSyncHooks?: boolean; hooksPath?: string; provider?: 'github' | 'gitlab' | 'bitbucket' | 'gitea'; }; visualizationUrl?: string;};Defined in: modules/onerepo/src/types/config-root.ts
Setup configuration for the root of the repository.
Type Parameters
Section titled “Type Parameters”| Type Parameter | Default type |
|---|---|
CustomLifecycles extends string | void | void |
Properties
Section titled “Properties”changes?
Section titled “changes?”optional changes: { filenames?: "hash" | "human"; formatting?: { commit?: string; footer?: string; }; prompts?: "guided" | "semver";};Defined in: modules/onerepo/src/types/config-root.ts
filenames?
Section titled “filenames?”optional filenames: "hash" | "human";Default: 'hash'
To generate human-readable unique filenames for change files, ensure human-id is installed.
formatting?
Section titled “formatting?”optional formatting: { commit?: string; footer?: string;};Default: {}
Override some formatting strings in generated changelog files.
export default { root: true, changes: { formatting: { commit: '([${ref.short}](https://github.com/paularmstrong/onerepo/commit/${ref}))', footer: '> Full changelog [${fromRef.short}...${throughRef.short}](https://github.com/my-repo/commits/${fromRef}...${throughRef})', }, },};formatting.commit?
Section titled “formatting.commit?”optional commit: string;Default: '(${ref.short})'
Format how the commit ref will appear at the end of the first line of each change entry.
Available replacement strings:
| Replacement | Description |
|---|---|
${ref.short} | 8-character version of the commit ref |
${ref} | Full commit ref |
formatting.footer?
Section titled “formatting.footer?”optional footer: string;Default: '_View git logs for full change list._'
Format the footer at the end of each version in the generated changelog files.
Available replacement strings:
| Replacement | Description |
|---|---|
${fromRef.short} | 8-character version of the first commit ref in the version |
${fromRef} | Full commit ref of the first commit in the version |
${through.short} | 8-character version of the last commit ref in the version |
${through} | Full commit ref of the last commit in the version |
${version} | New version string |
prompts?
Section titled “prompts?”optional prompts: "guided" | "semver";Default: 'guided'
Change the prompt question & answer style when adding change entries.
'guided': Gives more detailed explanations when release types.'semver': A simple choice list of semver release types.
codeowners?
Section titled “codeowners?”optional codeowners: Record<string, string[]>;Defined in: modules/onerepo/src/types/config-root.ts
Default: {}
Map of paths to array of owners.
When used with the codeowners commands, this configuration enables syncing configurations from Workspaces to the appropriate root level CODEOWNERS file given your vcsProvider as well as verifying that the root file is up to date.
export default { root: true, codeowners: { '*': ['@my-team', '@person'], scripts: ['@infra-team'], },};commands?
Section titled “commands?”optional commands: { directory?: string | false; ignore?: RegExp;};Defined in: modules/onerepo/src/types/config-root.ts
Configuration for custom commands.
directory?
Section titled “directory?”optional directory: string | false;Default: 'commands'
A string to use as filepaths to subcommands. We’ll look for commands in all Workspaces using this string. If any are found, they’ll be available from the CLI.
export default { root: true, commands: { directory: 'commands', },};Given the preceding configuration, commands will be searched for within the commands/ directory at the root of the repository as well as a directory of the same name at the root of each Workspace:
<root>/commands/*<root>/<workspaces>/commands/*
ignore?
Section titled “ignore?”optional ignore: RegExp;Default: /(/__\w+__/|\.test\.|\.spec\.|\.config\.)/
Prevent reading matched files in the commands.directory as commands.
When writing custom commands and Workspace-level subcommands, we may need to ignore certain files like tests, fixtures, and other helpers. Use a regular expression here to configure which files will be ignored when oneRepo parses and executes commands.
export default { root: true, commands: { ignore: /(/__\w+__/|\.test\.|\.spec\.|\.config\.)/, },};dependencies?
Section titled “dependencies?”optional dependencies: { dedupe?: boolean; mode?: "strict" | "loose" | "off";};Defined in: modules/onerepo/src/types/config-root.ts
dedupe?
Section titled “dedupe?”optional dedupe: boolean;Default: true
When modifying dependencies using the one dependencies command, a dedupe will automatically be run to reduce duplicate package versions that overlap the requested ranges. Set this to false to disable this behavior.
optional mode: "strict" | "loose" | "off";Default: 'loose'
The dependency mode will be used for node module dependency management and verification.
off: No validation will occur. Everything goes.loose: Reused third-party dependencies will be required to have semantic version overlap across unique branches of the Graph.strict: Versions of all dependencies across each discrete Workspace dependency tree must be strictly equal.
optional head: string;Defined in: modules/onerepo/src/types/config-root.ts
Default: 'main'
The default branch of your repo? Probably main, but it might be something else, so it’s helpful to put that here so that we can determine changed files accurately.
export default { root: true, head: 'develop',};ignore?
Section titled “ignore?”optional ignore: string[];Defined in: modules/onerepo/src/types/config-root.ts
Default: []
Array of fileglobs to ignore when calculating the changed Workspaces.
Periodically we may find that there are certain files or types of files that we know for a fact do not affect the validity of the repository or any code. When this happens and the files are modified, unnecessary tasks and processes will be spun up that don’t have any bearing on the outcome of the change.
To avoid extra processing, we can add file globs to ignore when calculated the afected Workspace graph.
export default { root: true, ignore: ['.github/\*'],};optional meta: Record<string, unknown>;Defined in: modules/onerepo/src/types/config-root.ts
Default: {}
A place to put any custom information or configuration. A helpful space for you to extend Workspace configurations for your own custom commands.
export default { root: true, meta: { tacos: 'are delicious', },};plugins?
Section titled “plugins?”optional plugins: Plugin[];Defined in: modules/onerepo/src/types/config-root.ts
Default: []
Add shared commands and extra handlers. See the official plugin list for more information.
import { eslint } from '@onerepo/plugins-eslint';export default { plugins: [eslint()],};root: true;Defined in: modules/onerepo/src/types/config-root.ts
Must be set to true in order to denote that this is the root of the repository.
taskConfig?
Section titled “taskConfig?”optional taskConfig: { lifecycles?: CustomLifecycles[]; stashUnstaged?: CustomLifecycles extends string ? Lifecycle | CustomLifecycles : Lifecycle[];};Defined in: modules/onerepo/src/types/config-root.ts
Optional extra configuration for tasks.
lifecycles?
Section titled “lifecycles?”optional lifecycles: CustomLifecycles[];Default: []
Additional task lifecycles to make available.
See `Lifecycle` for a list of pre-configured lifecycles.
export default { root: true, tasks: { lifecycles: ['deploy-staging'], },};stashUnstaged?
Section titled “stashUnstaged?”optional stashUnstaged: CustomLifecycles extends string ? Lifecycle | CustomLifecycles : Lifecycle[];Default: ['pre-commit']
Stash unstaged changes before running these tasks and re-apply them after the task has completed.
export default { root: true, tasks: { stashUnstaged: ['pre-commit', 'post-checkout'], },};tasks?
Section titled “tasks?”optional tasks: TaskConfig<CustomLifecycles>;Defined in: modules/onerepo/src/types/config-root.ts
Default: {}
Globally defined tasks per lifecycle. Tasks defined here will be assumed to run for all changes, regardless of affected Workspaces. Refer to the tasks command specifications for details and examples.
templateDir?
Section titled “templateDir?”optional templateDir: string;Defined in: modules/onerepo/src/types/config-root.ts
Default: './config/templates'
Folder path for generate command’s templates.
validation?
Section titled “validation?”optional validation: { schema?: string | null;};Defined in: modules/onerepo/src/types/config-root.ts
schema?
Section titled “schema?”optional schema: string | null;Default: undefined
File path for custom Graph and configuration file validation schema.
optional vcs: { autoSyncHooks?: boolean; hooksPath?: string; provider?: "github" | "gitlab" | "bitbucket" | "gitea";};Defined in: modules/onerepo/src/types/config-root.ts
Version control system settings.
autoSyncHooks?
Section titled “autoSyncHooks?”optional autoSyncHooks: boolean;Default: false
Automatically set and sync oneRepo-managed git hooks. Change the directory for your git hooks with the vcs.hooksPath setting. Refer to the Git hooks documentation to learn more.
export default { root: true, vcs: { autoSyncHooks: false, },};hooksPath?
Section titled “hooksPath?”optional hooksPath: string;Default: '.hooks'
Modify the default git hooks path for the repository. This will automatically be synchronized via one hooks sync unless explicitly disabled by setting vcs.autoSyncHooks to false.
export default { root: true, vcs: { hooksPath: '.githooks', },};provider?
Section titled “provider?”optional provider: "github" | "gitlab" | "bitbucket" | "gitea";Default: 'github'
The provider will be factored in to various commands, like CODEOWNERS generation.
export default { root: true, vcs: { provider: 'github', },};visualizationUrl?
Section titled “visualizationUrl?”optional visualizationUrl: string;Defined in: modules/onerepo/src/types/config-root.ts
Default: 'https://onerepo.tools/visualize/'
Override the URL used to visualize the Graph. The Graph data will be attached the the g query parameter as a JSON string of the DAG, compressed using zLib deflate.
type Task = string | TaskDef | string[];Defined in: modules/onerepo/src/types/tasks.ts
A Task can either be a string or `TaskDef` object with extra options, or an array of strings. If provided as an array of strings, each command will be run sequentially, waiting for the previous to succeed. If one command fails, the rest in the sequence will not be run.
To run sequences of commands with match and meta information, you can pass an array of strings to the cmd property of a `TaskDef`.
TaskConfig<CustomLifecycles>
Section titled “TaskConfig<CustomLifecycles>”type TaskConfig<CustomLifecycles> = Partial< Record<CustomLifecycles extends string ? Lifecycle | CustomLifecycles : Lifecycle, Tasks>>;Defined in: modules/onerepo/src/types/tasks.ts
Type Parameters
Section titled “Type Parameters”| Type Parameter | Default type |
|---|---|
CustomLifecycles extends string | void | void |
TaskDef
Section titled “TaskDef”type TaskDef = { cmd: string | string[]; match?: string | string[]; meta?: Record<string, unknown>;};Defined in: modules/onerepo/src/types/tasks.ts
Tasks can optionally include meta information or only be run if the configured match glob string matches the modified files. If no files match, the individual task will not be run.
export default { tasks: { 'pre-commit': { parallel: [ // Only run `astro check` if astro files have been modified { match: '*.astro', cmd: '$0 astro check' }, // Use a glob match with sequential tasks { match: '*.{ts,js}', cmd: ['$0 lint', '$0 format'] }, ], }, },} satisfies Config;Properties
Section titled “Properties”cmd: string | string[];Defined in: modules/onerepo/src/types/tasks.ts
String command(s) to run. If provided as an array of strings, each command will be run sequentially, waiting for the previous to succeed. If one command fails, the rest in the sequence will not be run.
The commands can use replaced tokens:
$0: the oneRepo CLI for your repository${workspaces}: replaced with a space-separated list of Workspace names necessary for the given lifecycle
match?
Section titled “match?”optional match: string | string[];Defined in: modules/onerepo/src/types/tasks.ts
Glob file match. This will force the cmd to run if any of the paths in the modified files list match the glob. Conversely, if no files are matched, the cmd will not run.
optional meta: Record<string, unknown>;Defined in: modules/onerepo/src/types/tasks.ts
Extra information that will be provided only when listing tasks with the --list option from the tasks command. This object is helpful when creating a matrix of runners with GitHub actions or similar CI pipelines.
type Tasks = { parallel?: Task[]; serial?: Task[];};Defined in: modules/onerepo/src/types/tasks.ts
Individual `Task`s in any `Lifecycle` may be grouped to run either serial (one after the other) or in parallel (multiple at the same time).
Properties
Section titled “Properties”parallel?
Section titled “parallel?”optional parallel: Task[];Defined in: modules/onerepo/src/types/tasks.ts
serial?
Section titled “serial?”optional serial: Task[];Defined in: modules/onerepo/src/types/tasks.ts
WorkspaceConfig<CustomLifecycles>
Section titled “WorkspaceConfig<CustomLifecycles>”type WorkspaceConfig<CustomLifecycles> = { codeowners?: Record<string, string[]>; commands?: { passthrough: Record< string, { command?: string; description: string; } >; }; meta?: Record<string, unknown>; tasks?: TaskConfig<CustomLifecycles>;};Defined in: modules/onerepo/src/types/config-workspace.ts
Type Parameters
Section titled “Type Parameters”| Type Parameter | Default type |
|---|---|
CustomLifecycles extends string | void | void |
Properties
Section titled “Properties”codeowners?
Section titled “codeowners?”optional codeowners: Record<string, string[]>;Defined in: modules/onerepo/src/types/config-workspace.ts
Default: {}.
Map of paths to array of owners.
When used with the codeowners commands, this configuration enables syncing configurations from Workspaces to the appropriate root level CODEOWNERS file given your RootConfig.vcs.provider as well as verifying that the root file is up to date.
export default { codeowners: { '*': ['@my-team', '@person'], scripts: ['@infra-team'], },};commands?
Section titled “commands?”optional commands: { passthrough: Record<string, { command?: string; description: string; }>;};Defined in: modules/onerepo/src/types/config-workspace.ts
Configuration for custom commands. To configure the commands directory, see RootConfig commands.directory.
passthrough
Section titled “passthrough”passthrough: Record< string, { command?: string; description: string; }>;Default: {}
Enable commands from installed dependencies. Similar to running npx <command>, but pulled into the oneRepo CLI and able to be limited by Workspace. Passthrough commands must have helpful descriptions.
export default { commands: { passthrough: { astro: { description: 'Run Astro commands directly.' }, start: { description: 'Run the Astro dev server.', command: 'astro dev --port=8000' }, }, },};optional meta: Record<string, unknown>;Defined in: modules/onerepo/src/types/config-workspace.ts
Default: {}
A place to put any custom information or configuration. A helpful space for you to extend Workspace configurations for your own custom commands.
export default { meta: { tacos: 'are delicious', },};tasks?
Section titled “tasks?”optional tasks: TaskConfig<CustomLifecycles>;Defined in: modules/onerepo/src/types/config-workspace.ts
Default: {}
Tasks for this Workspace. These will be merged with global tasks and any other affected Workspace tasks. Refer to the tasks command specifications for details and examples.
getGraph()
Section titled “getGraph()”function getGraph(workingDir?): Graph;Defined in: modules/graph/src/index.ts
Get the `Graph` given a particular root working directory. If the working directory is not a monorepo’s root, an empty Graph will be given in its place.
const graph = getGraph(process.cwd());assert.ok(graph.isRoot);Parameters:
| Parameter | Type |
|---|---|
workingDir? | string |
Returns: Graph
Defined in: modules/graph/src/Graph.ts
The oneRepo Graph is a representation of the entire repository’s `Workspaces` and how they depend upon each other. Most commonly, you will want to use the Graph to get lists of Workspaces that either depend on some input or are dependencies thereof:
const workspacesToCheck = graph.affected('tacos');for (const ws of workspacesToCheck) { // verify no issues based on changes}The Graph also includes various helpers for determining workspaces based on filepaths, name, and other factors.
Accessors
Section titled “Accessors”packageManager
Section titled “packageManager”Get Signature
Section titled “Get Signature”get packageManager(): PackageManager;Defined in: modules/graph/src/Graph.ts
Get the PackageManager that this Graph depends on. This object allows you to run many common package management commands safely, agnostic of any particular flavor of package management. Works with npm, Yarn, and pnpm.
await graph.packageManager.install();Returns: PackageManager
Get Signature
Section titled “Get Signature”get root(): Workspace;Defined in: modules/graph/src/Graph.ts
This returns the `Workspace` that is at the root of the repository.
Regardless of how the workspaces are configured with the package manager, the root package.json is always registered as a Workspace.
const root = graph.root;root.isRoot === true;Returns: Workspace
workspaces
Section titled “workspaces”Get Signature
Section titled “Get Signature”get workspaces(): Workspace[];Defined in: modules/graph/src/Graph.ts
Get a list of all `Workspaces` that are part of the repository Graph | `Graph`.
for (const workspace of graph.workspaces) { logger.info(workspace.name);}Returns: Workspace[]
Methods
Section titled “Methods”affected()
Section titled “affected()”affected<T>(source, type?): Workspace[];Defined in: modules/graph/src/Graph.ts
Get a list of `Workspaces` that will be affected by the given source(s). This is equivalent to graph.dependents(sources, true). See also `dependents`.
const dependents = graph.dependents(sources, true);const affected = graph.affected(sources);
assert.isEqual(dependents, affecteed);Type Parameters
Section titled “Type Parameters”| Type Parameter |
|---|
T extends string | Workspace |
Parameters:
| Parameter | Type | Description |
|---|---|---|
source | T | T[] | - |
type? | DepType | Filter the dependents to a dependency type. |
Returns: Workspace[]
dependencies()
Section titled “dependencies()”dependencies<T>( sources?, includeSelf?, type?): Workspace[];Defined in: modules/graph/src/Graph.ts
Get all dependency `Workspaces` of one or more input Workspaces or qualified names of Workspaces. This not only returns the direct dependencies, but all dependencies throughout the entire `Graph`. This returns the opposite result of `dependents`.
for (const workspace of graph.dependencies('tacos')) { logger.info(`"${workspace.name}" is a dependency of "tacos"`);}Type Parameters
Section titled “Type Parameters”| Type Parameter |
|---|
T extends string | Workspace |
Parameters:
| Parameter | Type | Description |
|---|---|---|
sources? | T | T[] | A list of `Workspaces` by `name`s or any available `aliases`. |
includeSelf? | boolean | Whether to include the Workspaces for the input sources in the return array. |
type? | DepType | Filter the dependencies to a dependency type. |
Returns: Workspace[]
dependents()
Section titled “dependents()”dependents<T>( sources?, includeSelf?, type?): Workspace[];Defined in: modules/graph/src/Graph.ts
Get all dependent `Workspaces` of one or more input Workspaces or qualified names of Workspaces. This not only returns the direct dependents, but all dependents throughout the entire `Graph`. This returns the opposite result of `dependencies`.
for (const workspace of graph.dependents('tacos')) { logger.info(`"${workspace.name}" depends on "tacos"`);}Type Parameters
Section titled “Type Parameters”| Type Parameter |
|---|
T extends string | Workspace |
Parameters:
| Parameter | Type | Description |
|---|---|---|
sources? | T | T[] | One or more Workspaces by name or Workspace instance |
includeSelf? | boolean | Whether to include the Workspaces for the input sources in the return array. |
type? | DepType | Filter the dependents to a dependency type. |
Returns: Workspace[]
getAllByLocation()
Section titled “getAllByLocation()”getAllByLocation(locations): Workspace[];Defined in: modules/graph/src/Graph.ts
Get all Workspaces given an array of filepaths.
const workspaces = graph.getAllByLocation([__dirname, 'file:///foo/bar']);Parameters:
| Parameter | Type | Description |
|---|---|---|
locations | string[] | A list of filepath strings. May be file URLs or string paths. |
Returns: Workspace[]
getAllByName()
Section titled “getAllByName()”getAllByName(names): Workspace[];Defined in: modules/graph/src/Graph.ts
Get a list of `Workspaces` by string names.
const workspaces = graph.getAllByName(['tacos', 'burritos']);Parameters:
| Parameter | Type | Description |
|---|---|---|
names | string[] | A list of Workspace `name`s or any available `aliases`. |
Returns: Workspace[]
getByLocation()
Section titled “getByLocation()”getByLocation(location): Workspace;Defined in: modules/graph/src/Graph.ts
Get the equivalent `Workspace` for a filepath. This can be any location within a Workspace, not just its root.
// in Node.jsgraph.getByLocation(__dirname);graph.getByLocation(import.meta.url);Parameters:
| Parameter | Type | Description |
|---|---|---|
location | string | A string or URL-based filepath. |
Returns: Workspace
Throws
Section titled “Throws”Error if no Workspace can be found.
getByName()
Section titled “getByName()”getByName(name): Workspace;Defined in: modules/graph/src/Graph.ts
Get a `Workspace` by string name.
const workspace = graph.getByName('my-cool-package');Parameters:
| Parameter | Type | Description |
|---|---|---|
name | string | A Workspace’s `name` or any available `aliases`. |
Returns: Workspace
Throws
Section titled “Throws”Error if no Workspace exists with the given input name.
Workspace
Section titled “Workspace”Defined in: modules/graph/src/Workspace.ts
Accessors
Section titled “Accessors”aliases
Section titled “aliases”Get Signature
Section titled “Get Signature”get aliases(): string[];Defined in: modules/graph/src/Workspace.ts
Allow custom array of aliases. If the fully qualified package name is scoped, this will include the un-scoped name
Returns: string[]
codeowners
Section titled “codeowners”Get Signature
Section titled “Get Signature”get codeowners(): NonNullable<Required<WorkspaceConfig["codeowners"]>>;Defined in: modules/graph/src/Workspace.ts
Returns: NonNullable<Required<WorkspaceConfig["codeowners"]>>
config
Section titled “config”Get Signature
Section titled “Get Signature”get config(): Required<RootConfig | WorkspaceConfig>;Defined in: modules/graph/src/Workspace.ts
Get the Workspace’s configuration
Returns: Required<RootConfig | WorkspaceConfig>
dependencies
Section titled “dependencies”Get Signature
Section titled “Get Signature”get dependencies(): Record<string, string>;Defined in: modules/graph/src/Workspace.ts
Get the package.json defined production dependencies for the Workspace.
Returns: Record<string, string>
Map of modules to their version.
description
Section titled “description”Get Signature
Section titled “Get Signature”get description(): undefined | string;Defined in: modules/graph/src/Workspace.ts
Canonical to the package.json "description" field.
Returns: undefined | string
devDependencies
Section titled “devDependencies”Get Signature
Section titled “Get Signature”get devDependencies(): Record<string, string>;Defined in: modules/graph/src/Workspace.ts
Get the package.json defined development dependencies for the Workspace.
Returns: Record<string, string>
Map of modules to their version.
isRoot
Section titled “isRoot”Get Signature
Section titled “Get Signature”get isRoot(): boolean;Defined in: modules/graph/src/Workspace.ts
Whether or not this Workspace is the root of the repository / Graph.
Returns: boolean
location
Section titled “location”Get Signature
Section titled “Get Signature”get location(): string;Defined in: modules/graph/src/Workspace.ts
Absolute path on the current filesystem to the Workspace.
Returns: string
Get Signature
Section titled “Get Signature”get main(): string;Defined in: modules/graph/src/Workspace.ts
Returns: string
Get Signature
Section titled “Get Signature”get name(): string;Defined in: modules/graph/src/Workspace.ts
The full name of the Workspace, as defined in its package.json
Returns: string
packageJson
Section titled “packageJson”Get Signature
Section titled “Get Signature”get packageJson(): PackageJson;Defined in: modules/graph/src/Workspace.ts
A full deep copy of the package.json file for the Workspace. Modifications to this object will not be preserved on the Workspace.
Returns: PackageJson
peerDependencies
Section titled “peerDependencies”Get Signature
Section titled “Get Signature”get peerDependencies(): Record<string, string>;Defined in: modules/graph/src/Workspace.ts
Get the package.json defined peer dependencies for the Workspace.
Returns: Record<string, string>
Map of modules to their version.
private
Section titled “private”Get Signature
Section titled “Get Signature”get private(): boolean;Defined in: modules/graph/src/Workspace.ts
If a Workspace package.json is set to private: true, it will not be available to publish through NPM or other package management registries.
Returns: boolean
publishablePackageJson
Section titled “publishablePackageJson”Get Signature
Section titled “Get Signature”get publishablePackageJson(): null | PublicPackageJson;Defined in: modules/graph/src/Workspace.ts
Get a version of the Workspace’s package.json that is meant for publishing.
This strips off devDependencies and applies appropriate `publishConfig` values to the root of the package.json. This feature enables your monorepo to use source-dependencies and avoid manually building shared Workspaces for every change in order to see them take affect in dependent Workspaces.
To take advantage of this, configure your package.json root level to point to source files and the publishConfig entries to point to the build location of those entrypoints.
{3 collapsed lines
"name": "my-module", "license": "MIT", "type": "module", "main": "./src/index.ts", "publishConfig": { "access": "public", "main": "./dist/index.js", "typings": "./dist/index.d.ts" }}Returns: null | PublicPackageJson
Get Signature
Section titled “Get Signature”get scope(): string;Defined in: modules/graph/src/Workspace.ts
Get module name scope if there is one, eg @onerepo
Returns: string
Get Signature
Section titled “Get Signature”get tasks(): TaskConfig;Defined in: modules/graph/src/Workspace.ts
Get the task configuration as defined in the onerepo.config.js file at the root of the Workspace.
Returns: TaskConfig
If a config does not exist, an empty object will be given.
version
Section titled “version”Get Signature
Section titled “Get Signature”get version(): undefined | string;Defined in: modules/graph/src/Workspace.ts
Returns: undefined | string
Methods
Section titled “Methods”getCodeowners()
Section titled “getCodeowners()”getCodeowners(filepath): string[];Defined in: modules/graph/src/Workspace.ts
Parameters:
| Parameter | Type |
|---|---|
filepath | string |
Returns: string[]
getTasks()
Section titled “getTasks()”getTasks(lifecycle): Required<Tasks>;Defined in: modules/graph/src/Workspace.ts
Get a list of Workspace tasks for the given lifecycle
Parameters:
| Parameter | Type |
|---|---|
lifecycle | string |
Returns: Required<Tasks>
relative()
Section titled “relative()”relative(to): string;Defined in: modules/graph/src/Workspace.ts
Get the relative path of an absolute path to the Workspace’s location root
const relativePath = workspace.relative('/some/absolute/path');Parameters:
| Parameter | Type | Description |
|---|---|---|
to | string | Absolute filepath |
Returns: string
Relative path to the workspace’s root location.
resolve()
Section titled “resolve()”resolve(...pathSegments): string;Defined in: modules/graph/src/Workspace.ts
Resolve a full filepath within the Workspace given the path segments. Similar to Node.js’s path.resolve().
const main = workspace.resolve(workspace.main);Parameters:
| Parameter | Type | Description |
|---|---|---|
…pathSegments | string[] | A sequence of paths or path segments |
Returns: string
Absolute path based on the input path segments
DependencyType
Section titled “DependencyType”const DependencyType: { DEV: 2; PEER: 1; PROD: 3;};Defined in: modules/graph/src/Graph.ts
Type declaration
Section titled “Type declaration”readonly DEV: 2;Development-only dependency (defined in devDependencies keys of package.json)
readonly PEER: 1;Peer dependency (defined in peerDependencies key of package.json)
readonly PROD: 3;Production dependency (defined in dependencies of package.json)
DepType
Section titled “DepType”type DepType = 1 | 2 | 3;Defined in: modules/graph/src/Graph.ts
Dependency type value.
See also: `DependencyType`
GraphSchemaValidators
Section titled “GraphSchemaValidators”type GraphSchemaValidators = Record<string, Record<string, | Schema & { $required?: boolean;} | (workspace, graph) => Schema & { $required?: boolean;}>>;Defined in: modules/onerepo/src/core/graph/schema.ts
Definition for graph verify JSON schema validators.
See “Validating configurations” for more examples and use cases.
import type { GraphSchemaValidators } from 'onerepo';
export default { '**': { 'package.json': { type: 'object', $required: true, properties: { name: { type: 'string' }, }, required: ['name'], }, },} satisfies GraphSchemaValidators;Logger
Section titled “Logger”bufferSubLogger()
Section titled “bufferSubLogger()”function bufferSubLogger(step): { end: () => Promise<void>; logger: Logger;};Defined in: modules/logger/src/index.ts
Alpha
Create a new Logger instance that has its output buffered up to a LogStep.
const step = logger.createStep(name, { writePrefixes: false });const subLogger = bufferSubLogger(step);const substep = subLogger.logger.createStep('Sub-step');substep.warning('This gets buffered');await substep.end();await subLogger.end();await step.en();Parameters:
| Parameter | Type |
|---|---|
step | LogStep |
Returns: ```ts
{
end: () => Promise
##### end()
```tsend: () => Promise<void>;Returns: Promise<void>
logger
Section titled “logger”logger: Logger;getLogger()
Section titled “getLogger()”function getLogger(opts?): Logger;Defined in: modules/logger/src/index.ts
This gets the logger singleton for use across all of oneRepo and its commands.
Available directly as `HandlerExtra` on `Handler` functions:
export const handler: Handler = (argv, { logger }) => { logger.log('Hello!');};Parameters:
| Parameter | Type |
|---|---|
opts? | Partial<LoggerOptions> |
Returns: Logger
stepWrapper()
Section titled “stepWrapper()”function stepWrapper<T>(options, fn): Promise<T>;Defined in: modules/logger/src/index.ts
For cases where multiple processes need to be completed, but should be joined under a single `LogStep` to avoid too much noisy output, this safely wraps an asynchronous function and handles step creation and completion, unless a step override is given.
export async function exists(filename: string, { step }: Options = {}) { return stepWrapper({ step, name: 'Step fallback name' }, (step) => { return; // do some work });}Type Parameters
Section titled “Type Parameters”| Type Parameter |
|---|
T |
Parameters:
| Parameter | Type |
|---|---|
options | { name: string; step?: LogStep; } |
options.name | string |
options.step? | LogStep |
fn | (step) => Promise<T> |
Returns: Promise<T>
Logger
Section titled “Logger”Defined in: modules/logger/src/Logger.ts
The oneRepo logger helps build commands and capture output from spawned subprocess in a way that’s both delightful to the end user and includes easy to scan and follow output.
All output will be redirected from stdout to stderr to ensure order of output and prevent confusion of what output can be piped and written to files.
If the current terminal is a TTY, output will be buffered and asynchronous steps will animated with a progress logger.
See `HandlerExtra` for access the the global Logger instance.
Accessors
Section titled “Accessors”hasError
Section titled “hasError”Get Signature
Section titled “Get Signature”get hasError(): boolean;Defined in: modules/logger/src/Logger.ts
Whether or not an error has been sent to the logger or any of its steps. This is not necessarily indicative of uncaught thrown errors, but solely on whether .error() has been called in the Logger or any Step instance.
Returns: boolean
hasInfo
Section titled “hasInfo”Get Signature
Section titled “Get Signature”get hasInfo(): boolean;Defined in: modules/logger/src/Logger.ts
Whether or not an info message has been sent to the logger or any of its steps.
Returns: boolean
hasLog
Section titled “hasLog”Get Signature
Section titled “Get Signature”get hasLog(): boolean;Defined in: modules/logger/src/Logger.ts
Whether or not a log message has been sent to the logger or any of its steps.
Returns: boolean
hasWarning
Section titled “hasWarning”Get Signature
Section titled “Get Signature”get hasWarning(): boolean;Defined in: modules/logger/src/Logger.ts
Whether or not a warning has been sent to the logger or any of its steps.
Returns: boolean
verbosity
Section titled “verbosity”Get Signature
Section titled “Get Signature”get verbosity(): Verbosity;Defined in: modules/logger/src/Logger.ts
Get the logger’s verbosity level
Returns: Verbosity
Set Signature
Section titled “Set Signature”set verbosity(value): void;Defined in: modules/logger/src/Logger.ts
Recursively applies the new verbosity to the logger and all of its active steps.
Parameters:
| Parameter | Type |
|---|---|
value | Verbosity |
Returns: void
writable
Section titled “writable”Get Signature
Section titled “Get Signature”get writable(): boolean;Defined in: modules/logger/src/Logger.ts
Returns: boolean
Methods
Section titled “Methods”createStep()
Section titled “createStep()”createStep(name, __namedParameters?): LogStep;Defined in: modules/logger/src/Logger.ts
Create a sub-step, `LogStep`, for the logger. This and any other step will be tracked and required to finish before exit.
const step = logger.createStep('Do fun stuff');// do some workawait step.end();Parameters:
| Parameter | Type | Description |
|---|---|---|
name | string | The name to be written and wrapped around any output logged to this new step. |
__namedParameters? | { writePrefixes?: boolean; } | - |
__namedParameters.writePrefixes? | boolean | - |
Returns: LogStep
pause()
Section titled “pause()”pause(write?): void;Defined in: modules/logger/src/Logger.ts
When the terminal is a TTY, steps are automatically animated with a progress indicator. There are times when it’s necessary to stop this animation, like when needing to capture user input from stdin. Call the pause() method before requesting input and `logger.unpause()` when complete.
This process is also automated by the `run()` function when stdio is set to pipe.
logger.pause();// capture inputlogger.unpause();Parameters:
| Parameter | Type |
|---|---|
write? | boolean |
Returns: void
unpause()
Section titled “unpause()”unpause(): void;Defined in: modules/logger/src/Logger.ts
Unpause the logger and resume writing buffered logs to stderr. See `logger.pause()` for more information.
Returns: void
Logging
Section titled “Logging”debug()
Section titled “debug()”debug(contents): void;Defined in: modules/logger/src/Logger.ts
Extra debug logging when verbosity greater than or equal to 4.
logger.debug('Log this content when verbosity is >= 4');If a function with zero arguments is passed, the function will be executed before writing. This is helpful for avoiding extra work in the event that the verbosity is not actually high enough to render the logged debug information:
logger.debug(() => bigArray.map((item) => item.name));Parameters:
| Parameter | Type | Description |
|---|---|---|
contents | unknown | Any value that can be converted to a string for writing to stderr. |
Returns: void
See also:
`debug()` This is a pass-through for the main step’s `debug()` method.
error()
Section titled “error()”error(contents): void;Defined in: modules/logger/src/Logger.ts
Log an error. This will cause the root logger to include an error and fail a command.
logger.error('Log this content when verbosity is >= 1');If a function with zero arguments is passed, the function will be executed before writing. This is helpful for avoiding extra work in the event that the verbosity is not actually high enough to render the logged error:
logger.error(() => bigArray.map((item) => item.name));Parameters:
| Parameter | Type | Description |
|---|---|---|
contents | unknown | Any value that can be converted to a string for writing to stderr. |
Returns: void
See also:
`error()` This is a pass-through for the main step’s `error()` method.
info()
Section titled “info()”info(contents): void;Defined in: modules/logger/src/Logger.ts
Should be used to convey information or instructions through the log, will log when verbositu >= 1
logger.info('Log this content when verbosity is >= 1');If a function with zero arguments is passed, the function will be executed before writing. This is helpful for avoiding extra work in the event that the verbosity is not actually high enough to render the logged information:
logger.info(() => bigArray.map((item) => item.name));Parameters:
| Parameter | Type | Description |
|---|---|---|
contents | unknown | Any value that can be converted to a string for writing to stderr. |
Returns: void
See also:
`info()` This is a pass-through for the main step’s `info()` method.
log(contents): void;Defined in: modules/logger/src/Logger.ts
General logging information. Useful for light informative debugging. Recommended to use sparingly.
logger.log('Log this content when verbosity is >= 3');If a function with zero arguments is passed, the function will be executed before writing. This is helpful for avoiding extra work in the event that the verbosity is not actually high enough to render the logged information:
logger.log(() => bigArray.map((item) => item.name));Parameters:
| Parameter | Type | Description |
|---|---|---|
contents | unknown | Any value that can be converted to a string for writing to stderr. |
Returns: void
See also:
`log()` This is a pass-through for the main step’s `log()` method.
timing()
Section titled “timing()”timing(start, end): void;Defined in: modules/logger/src/Logger.ts
Log timing information between two Node.js performance mark names.
Parameters:
| Parameter | Type | Description |
|---|---|---|
start | string | A PerformanceMark entry name |
end | string | A PerformanceMark entry name |
Returns: void
See also:
`timing()` This is a pass-through for the main step’s `timing()` method.
warn()
Section titled “warn()”warn(contents): void;Defined in: modules/logger/src/Logger.ts
Log a warning. Does not have any effect on the command run, but will be called out.
logger.warn('Log this content when verbosity is >= 2');If a function with zero arguments is passed, the function will be executed before writing. This is helpful for avoiding extra work in the event that the verbosity is not actually high enough to render the logged warning:
logger.warn(() => bigArray.map((item) => item.name));Parameters:
| Parameter | Type | Description |
|---|---|---|
contents | unknown | Any value that can be converted to a string for writing to stderr. |
Returns: void
See also:
`warn()` This is a pass-through for the main step’s `warn()` method.
LogStep
Section titled “LogStep”Defined in: modules/logger/src/LogStep.ts
Log steps should only be created via the `logger.createStep()` method.
const step = logger.createStep('Do some work');// ... long task with a bunch of potential outputawait step.end();Properties
Section titled “Properties”hasError
Section titled “hasError”hasError: boolean;Defined in: modules/logger/src/LogStep.ts
Whether or not an error has been sent to the step. This is not necessarily indicative of uncaught thrown errors, but solely on whether .error() has been called in this step.
hasInfo
Section titled “hasInfo”hasInfo: boolean;Defined in: modules/logger/src/LogStep.ts
Whether or not an info message has been sent to this step.
hasLog
Section titled “hasLog”hasLog: boolean;Defined in: modules/logger/src/LogStep.ts
Whether or not a log message has been sent to this step.
hasWarning
Section titled “hasWarning”hasWarning: boolean;Defined in: modules/logger/src/LogStep.ts
Whether or not a warning has been sent to this step.
Methods
Section titled “Methods”end(): Promise<void>;Defined in: modules/logger/src/LogStep.ts
Finish this step and flush all buffered logs. Once a step is ended, it will no longer accept any logging output and will be effectively removed from the base logger. Consider this method similar to a destructor or teardown.
await step.end();Returns: Promise<void>
Logging
Section titled “Logging”debug()
Section titled “debug()”debug(contents): void;Defined in: modules/logger/src/LogStep.ts
Extra debug logging when verbosity greater than or equal to 4.
step.debug('Log this content when verbosity is >= 4');If a function with zero arguments is passed, the function will be executed before writing. This is helpful for avoiding extra work in the event that the verbosity is not actually high enough to render the logged debug information:
step.debug(() => bigArray.map((item) => item.name));Parameters:
| Parameter | Type | Description |
|---|---|---|
contents | unknown | Any value that can be converted to a string for writing to stderr. |
Returns: void
error()
Section titled “error()”error(contents): void;Defined in: modules/logger/src/LogStep.ts
Log an error. This will cause the root logger to include an error and fail a command.
step.error('Log this content when verbosity is >= 1');If a function with zero arguments is passed, the function will be executed before writing. This is helpful for avoiding extra work in the event that the verbosity is not actually high enough to render the logged error:
step.error(() => bigArray.map((item) => item.name));Parameters:
| Parameter | Type | Description |
|---|---|---|
contents | unknown | Any value that can be converted to a string for writing to stderr. |
Returns: void
info()
Section titled “info()”info(contents): void;Defined in: modules/logger/src/LogStep.ts
Log an informative message. Should be used when trying to convey information with a user that is important enough to always be returned.
step.info('Log this content when verbosity is >= 1');If a function with zero arguments is passed, the function will be executed before writing. This is helpful for avoiding extra work in the event that the verbosity is not actually high enough to render the logged information:
step.info(() => bigArray.map((item) => item.name));Parameters:
| Parameter | Type | Description |
|---|---|---|
contents | unknown | Any value that can be converted to a string for writing to stderr. |
Returns: void
log(contents): void;Defined in: modules/logger/src/LogStep.ts
General logging information. Useful for light informative debugging. Recommended to use sparingly.
step.log('Log this content when verbosity is >= 3');If a function with zero arguments is passed, the function will be executed before writing. This is helpful for avoiding extra work in the event that the verbosity is not actually high enough to render the logged information:
step.log(() => bigArray.map((item) => item.name));Parameters:
| Parameter | Type | Description |
|---|---|---|
contents | unknown | Any value that can be converted to a string for writing to stderr. |
Returns: void
timing()
Section titled “timing()”timing(start, end): void;Defined in: modules/logger/src/LogStep.ts
Log timing information between two Node.js performance mark names.
Parameters:
| Parameter | Type | Description |
|---|---|---|
start | string | A PerformanceMark entry name |
end | string | A PerformanceMark entry name |
Returns: void
warn()
Section titled “warn()”warn(contents): void;Defined in: modules/logger/src/LogStep.ts
Log a warning. Does not have any effect on the command run, but will be called out.
step.warn('Log this content when verbosity is >= 2');If a function with zero arguments is passed, the function will be executed before writing. This is helpful for avoiding extra work in the event that the verbosity is not actually high enough to render the logged warning:
step.warn(() => bigArray.map((item) => item.name));Parameters:
| Parameter | Type | Description |
|---|---|---|
contents | unknown | Any value that can be converted to a string for writing to stderr. |
Returns: void
LoggerOptions
Section titled “LoggerOptions”type LoggerOptions = { stream?: Writable; verbosity: Verbosity;};Defined in: modules/logger/src/Logger.ts
Properties
Section titled “Properties”stream?
Section titled “stream?”optional stream: Writable;Defined in: modules/logger/src/Logger.ts
Advanced – override the writable stream in order to pipe logs elsewhere. Mostly used for dependency injection for @onerepo/test-cli.
verbosity
Section titled “verbosity”verbosity: Verbosity;Defined in: modules/logger/src/Logger.ts
Control how much and what kind of output the Logger will provide.
Verbosity
Section titled “Verbosity”type Verbosity = 0 | 1 | 2 | 3 | 4 | 5;Defined in: modules/logger/src/Logger.ts
Control the verbosity of the log output
| Value | What | Description |
|---|---|---|
<= 0 | Silent | No output will be read or written. |
>= 1 | Error, Info | |
>= 2 | Warnings | |
>= 3 | Log | |
>= 4 | Debug | logger.debug() will be included |
>= 5 | Timing | Extra performance timing metrics will be written |
Package management
Section titled “Package management”getLockfile()
Section titled “getLockfile()”function getLockfile(cwd): null | string;Defined in: modules/package-manager/src/get-package-manager.ts
Get the absolute path for the package manager’s lock file for this repository.
Parameters:
| Parameter | Type |
|---|---|
cwd | string |
Returns: null | string
getPackageManager()
Section titled “getPackageManager()”function getPackageManager(type): PackageManager;Defined in: modules/package-manager/src/index.ts
Get the `PackageManager` for the given package manager type (NPM, PNPm, or Yarn)
Parameters:
| Parameter | Type |
|---|---|
type | "pnpm" | "npm" | "yarn" |
Returns: PackageManager
getPackageManagerName()
Section titled “getPackageManagerName()”function getPackageManagerName(cwd, fromPkgJson?): 'pnpm' | 'npm' | 'yarn';Defined in: modules/package-manager/src/get-package-manager.ts
Get the package manager for the current working directory with some confidence
Parameters:
| Parameter | Type | Description |
|---|---|---|
cwd | string | Current working directory. Should be the root of the module/repository. |
fromPkgJson? | string | Value as defined in a package.json file, typically the packageManager value |
Returns: "pnpm" | "npm" | "yarn"
PackageManager
Section titled “PackageManager”Defined in: modules/package-manager/src/methods.ts
Implementation details for all package managers. This interface defines a subset of common methods typically needed when interacting with a monorepo and its dependency `Graph` & `Workspace`s.
Methods
Section titled “Methods”add(packages, opts?): Promise<void>;Defined in: modules/package-manager/src/methods.ts
Add one or more packages from external registries
Parameters:
| Parameter | Type | Description |
|---|---|---|
packages | string | string[] | One or more packages, by name and/or 'name@version'. |
opts? | { dev?: boolean; } | Various options to pass while installing the packages |
opts.dev? | boolean | Set to true to install as a devDependency. Default false |
Returns: Promise<void>
batch()
Section titled “batch()”batch(processes): Promise<(Error | [string, string])[]>;Defined in: modules/package-manager/src/methods.ts
Batch commands from npm packages as a batch of subprocesses using the package manager. Alternative to batching with npm exec and compatible APIs.
Parameters:
| Parameter | Type |
|---|---|
processes | RunSpec[] |
Returns: Promise<(Error | [string, string])[]>
See also:
`batch` for general subprocess batching.
dedupe()
Section titled “dedupe()”dedupe(): Promise<void>;Defined in: modules/package-manager/src/methods.ts
Reduce duplication in the package tree by checking overlapping ranges.
Returns: Promise<void>
info()
Section titled “info()”info(name, opts?): Promise<null | NpmInfo>;Defined in: modules/package-manager/src/methods.ts
Get standard information about a package
Parameters:
| Parameter | Type |
|---|---|
name | string |
opts? | Partial<RunSpec> |
Returns: Promise<null | NpmInfo>
install()
Section titled “install()”install(cwd?): Promise<string>;Defined in: modules/package-manager/src/methods.ts
Install current dependencies as listed in the package manager’s lock file
Parameters:
| Parameter | Type |
|---|---|
cwd? | string |
Returns: Promise<string>
loggedIn()
Section titled “loggedIn()”loggedIn(opts?): Promise<boolean>;Defined in: modules/package-manager/src/methods.ts
Check if the current user is logged in to the external registry
Parameters:
| Parameter | Type | Description |
|---|---|---|
opts? | { registry?: string; scope?: string; } | - |
opts.registry? | string | The base URL of your NPM registry. PNPM and NPM ignore scope and look up per-registry. |
opts.scope? | string | When using Yarn, lookups are done by registry configured by scope. This value must be included if you have separate registries for separate scopes. |
Returns: Promise<boolean>
publish()
Section titled “publish()”publish<T>(opts): Promise<void>;Defined in: modules/package-manager/src/methods.ts
Publish Workspaces to the external registry
Type Parameters
Section titled “Type Parameters”| Type Parameter |
|---|
T extends MinimalWorkspace |
Parameters:
| Parameter | Type | Description |
|---|---|---|
opts | { access?: "restricted" | "public"; cwd?: string; otp?: string; tag?: string; workspaces: T[]; } | - |
opts.access? | "restricted" | "public" | Set the registry access level for the package Default inferred from Workspaces publishConfig.access or 'public' |
opts.cwd? | string | Command working directory. Defaults to the repository root. |
opts.otp? | string | This is a one-time password from a two-factor authenticator. |
opts.tag? | string | If you ask npm to install a package and don’t tell it a specific version, then it will install the specified tag. Default 'latest' |
opts.workspaces | T[] | Workspaces to publish. If not provided or empty array, only the given Workspace at cwd will be published. This type is generally compatible with `Workspace`. |
Returns: Promise<void>
publishable()
Section titled “publishable()”publishable<T>(workspaces): Promise<T[]>;Defined in: modules/package-manager/src/methods.ts
Filter Workspaces to the set of those that are actually publishable. This will check both whether the package is not marked as “private” and if the current version is not in the external registry.
Type Parameters
Section titled “Type Parameters”| Type Parameter |
|---|
T extends MinimalWorkspace |
Parameters:
| Parameter | Type | Description |
|---|---|---|
workspaces | T[] | List of compatible `Workspace` objects. |
Returns: Promise<T[]>
remove()
Section titled “remove()”remove(packages): Promise<void>;Defined in: modules/package-manager/src/methods.ts
Remove one or more packages.
Parameters:
| Parameter | Type | Description |
|---|---|---|
packages | string | string[] | One or more packages, by name |
Returns: Promise<void>
run(opts): Promise<[string, string]>;Defined in: modules/package-manager/src/methods.ts
Run a command from an npm package as a subprocess using the package manager. Alternative to npm exec and compatible APIs.
Parameters:
| Parameter | Type |
|---|---|
opts | RunSpec |
Returns: Promise<[string, string]>
See also:
`batch` for general subprocess running.
MinimalWorkspace
Section titled “MinimalWorkspace”type MinimalWorkspace = { location?: string; name: string; private?: boolean; version?: string;};Defined in: modules/package-manager/src/methods.ts
Properties
Section titled “Properties”location?
Section titled “location?”optional location: string;Defined in: modules/package-manager/src/methods.ts
name: string;Defined in: modules/package-manager/src/methods.ts
private?
Section titled “private?”optional private: boolean;Defined in: modules/package-manager/src/methods.ts
version?
Section titled “version?”optional version: string;Defined in: modules/package-manager/src/methods.ts
NpmInfo
Section titled “NpmInfo”type NpmInfo = { dependencies: Record<string, string>; dist-tags: { [key: string]: string; latest: string; }; homepage: string; license: string; name: string; version: string; versions: string[];};Defined in: modules/package-manager/src/methods.ts
Properties
Section titled “Properties”dependencies
Section titled “dependencies”dependencies: Record<string, string>;Defined in: modules/package-manager/src/methods.ts
dist-tags
Section titled “dist-tags”dist-tags: {[key: string]: string; latest: string;};Defined in: modules/package-manager/src/methods.ts
Index Signature
Section titled “Index Signature”[key: string]: stringlatest
Section titled “latest”latest: string;homepage
Section titled “homepage”homepage: string;Defined in: modules/package-manager/src/methods.ts
license
Section titled “license”license: string;Defined in: modules/package-manager/src/methods.ts
name: string;Defined in: modules/package-manager/src/methods.ts
version
Section titled “version”version: string;Defined in: modules/package-manager/src/methods.ts
versions
Section titled “versions”versions: string[];Defined in: modules/package-manager/src/methods.ts
Plugins
Section titled “Plugins”Plugin
Section titled “Plugin”type Plugin = | PluginObject | (config, graph) => PluginObject;Defined in: modules/onerepo/src/types/plugin.ts
PluginObject
Section titled “PluginObject”type PluginObject = { shutdown?: (argv) => Promise<Record<string, unknown> | void> | Record<string, unknown> | void; startup?: (argv) => Promise<void> | void; yargs?: (yargs, visitor) => Yargs;};Defined in: modules/onerepo/src/types/plugin.ts
Properties
Section titled “Properties”shutdown()?
Section titled “shutdown()?”optional shutdown: (argv) => | Promise<Record<string, unknown> | void> | Record<string, unknown> | void;Defined in: modules/onerepo/src/types/plugin.ts
Runs just before the application process is exited. Allows returning data that will be merged with all other shutdown handlers.
Parameters:
| Parameter | Type |
|---|---|
argv | Argv<DefaultArgv> |
Returns: | Promise<Record<string, unknown> | void>
| Record<string, unknown>
| void
startup()?
Section titled “startup()?”optional startup: (argv) => Promise<void> | void;Defined in: modules/onerepo/src/types/plugin.ts
Runs before any and all commands after argument parsing. This is similar to global Yargs middleware, but guaranteed to have the fully resolved and parsed arguments.
Use this function for setting up global even listeners like PerformanceObserver, process events, etc.
Parameters:
| Parameter | Type |
|---|---|
argv | Argv<DefaultArgv> |
Returns: Promise<void> | void
yargs()?
Section titled “yargs()?”optional yargs: (yargs, visitor) => Yargs;Defined in: modules/onerepo/src/types/plugin.ts
A function that is called with the CLI’s yargs object and a visitor.
It is important to ensure every command passed through the visitor to enable all of the features of oneRepo. Without this step, you will not have access to the Workspace Graph, affected list, and much more.
Parameters:
| Parameter | Type |
|---|---|
yargs | Yargs |
visitor | NonNullable<RequireDirectoryOptions["visit"]> |
Returns: Yargs
Subprocess
Section titled “Subprocess”batch()
Section titled “batch()”function batch(processes, options?): Promise<(Error | [string, string])[]>;Defined in: modules/subprocess/src/index.ts
Batch multiple subprocesses, similar to Promise.all, but only run as many processes at a time fulfilling N-1 cores. If there are more processes than cores, as each process finishes, a new process will be picked to run, ensuring maximum CPU usage at all times.
If any process throws a SubprocessError, this function will reject with a BatchError, but only after all processes have completed running.
Most oneRepo commands will consist of at least one `run()` or `batch()` processes.
const processes: Array<RunSpec> = [ { name: 'Say hello', cmd: 'echo', args: ['"hello"'] }, { name: 'Say world', cmd: 'echo', args: ['"world"'] },];
const results = await batch(processes);
expect(results).toEqual([ ['hello', ''], ['world', ''],]);Parameters:
| Parameter | Type |
|---|---|
processes | (RunSpec | PromiseFn)[] |
options? | BatchOptions |
Returns: Promise<(Error | [string, string])[]>
Throws
Section titled “Throws”`BatchError` An object that includes a list of all of the `SubprocessError`s thrown.
See also: `PackageManager.batch` to safely batch executables exposed from third party modules.
function run(options): Promise<[string, string]>;Defined in: modules/subprocess/src/index.ts
Spawn a process and capture its stdout and stderr through a Logger Step. Most oneRepo commands will consist of at least one `run()` or `batch()` processes.
The run() command is an async wrapper around Node.js’s child_process.spawn and has a very similar API, with some additions. This command will buffer and catch all stdout and stderr responses.
await run({ name: 'Do some work', cmd: 'echo', args: ['"hello!"'],});Skipping failures:
If a subprocess fails when called through run(), a `SubprocessError` will be thrown. Some third-party tooling will exit with error codes as an informational tool. While this is discouraged, there’s nothing we can do about how they’ve been chosen to work. To prevent throwing errors, but still act on the stderr response, include the skipFailures option:
const [stdout, stderr] = await run({ name: 'Run dry', cmd: 'echo', args: ['"hello"'], skipFailures: true,});
logger.error(stderr);Dry-run:
By default, run() will respect oneRepo’s --dry-run option (see `DefaultArgv`, process.env.ONEREPO_DRY_RUN). When set, the process will not be spawned, but merely log information about what would run instead. To continue running a command, despite the --dry-run option being set, use runDry: true:
await run({ name: 'Run dry', cmd: 'echo', args: ['"hello"'], runDry: true,});Parameters:
| Parameter | Type |
|---|---|
options | RunSpec |
Returns: Promise<[string, string]>
A promise with an array of [stdout, stderr], as captured from the command run.
Throws
Section titled “Throws”`SubprocessError` if not skipFailures and the spawned process does not exit cleanly (with code 0)
See also: `PackageManager.run` to safely run executables exposed from third party modules.
runTasks()
Section titled “runTasks()”function runTasks(lifecycle, args, graph, logger?): Promise<void>;Defined in: modules/onerepo/src/core/tasks/run-tasks.ts
Alpha
Run Lifecycle tasks in commands other than the one tasks command. Use this function when you have a command triggering a Lifecycle in non-standard ways.
await runTasks('pre-publish', ['-w', 'my-workspace'], graph);Parameters:
| Parameter | Type | Description |
|---|---|---|
lifecycle | Lifecycle | The individual Lifecycle to trigger. |
args | string[] | Array of string arguments as if passed in from the command-line. |
graph | Graph | The current repository Graph. |
logger? | Logger | Optional Logger instance. Defaults to the current Logger (usually there is only one). |
Returns: Promise<void>
start()
Section titled “start()”function start(options): ChildProcess;Defined in: modules/subprocess/src/index.ts
Start a subprocess. For use when control over watching the stdout and stderr or long-running processes that are not expected to complete without SIGINT/SIGKILL.
Parameters:
| Parameter | Type |
|---|---|
options | Omit<RunSpec, "runDry" | "name"> |
Returns: ChildProcess
sudo()
Section titled “sudo()”function sudo(options): Promise<[string, string]>;Defined in: modules/subprocess/src/index.ts
This function is similar to run, but can request and run with elevated sudo permissions. This function should not be used unless you absolutely know that you will need to spawn an executable with elevated permissions.
This function will first check if sudo permissions are valid. If not, the logger will warn the user that sudo permissions are being requested and properly pause the animated logger while the user enters their password directly through stdin. If permissions are valid, no warning will be given.
await sudo({ name: 'Change permissions', cmd: 'chmod', args: ['a+x', '/usr/bin/thing'], reason: 'When prompted, please type your password and hit [RETURN] to allow `thing` to be run later',});Parameters:
| Parameter | Type |
|---|---|
options | Omit<RunSpec, "opts"> & { reason?: string; } |
Returns: Promise<[string, string]>
BatchError
Section titled “BatchError”Defined in: modules/subprocess/src/index.ts
Extends
Section titled “Extends”Error
Constructors
Section titled “Constructors”Constructor
Section titled “Constructor”new BatchError(errors, options?): BatchError;Defined in: modules/subprocess/src/index.ts
Parameters:
| Parameter | Type |
|---|---|
errors | (string | SubprocessError)[] |
options? | ErrorOptions |
Returns: BatchError
Overrides
Section titled “Overrides”Error.constructor;Properties
Section titled “Properties”errors
Section titled “errors”errors: (string | SubprocessError)[];Defined in: modules/subprocess/src/index.ts
SubprocessError
Section titled “SubprocessError”Defined in: modules/subprocess/src/index.ts
Extends
Section titled “Extends”Error
Constructors
Section titled “Constructors”Constructor
Section titled “Constructor”new SubprocessError(message, options?): SubprocessError;Defined in: modules/subprocess/src/index.ts
Parameters:
| Parameter | Type |
|---|---|
message | string |
options? | ErrorOptions |
Returns: SubprocessError
Overrides
Section titled “Overrides”Error.constructor;BatchOptions
Section titled “BatchOptions”type BatchOptions = { maxParallel?: number;};Defined in: modules/subprocess/src/index.ts
Options for running `batch()` subprocesses.
Properties
Section titled “Properties”maxParallel?
Section titled “maxParallel?”optional maxParallel: number;Defined in: modules/subprocess/src/index.ts
The absolute maximum number of subprocesses to batch. This amount will always be limited by the number of CPUs/cores available on the current machine.
Default: deterministic Number of CPUs - 1
PromiseFn()
Section titled “PromiseFn()”type PromiseFn = () => Promise<[string, string]>;Defined in: modules/subprocess/src/index.ts
Returns: Promise<[string, string]>
RunSpec
Section titled “RunSpec”type RunSpec = { args?: string[]; cmd: string; name: string; opts?: SpawnOptions; runDry?: boolean; skipFailures?: boolean; step?: LogStep;};Defined in: modules/subprocess/src/index.ts
The core configuration for `run`, `start`, `sudo`, and `batch` subprocessing.
Properties
Section titled “Properties”optional args: string[];Defined in: modules/subprocess/src/index.ts
Arguments to pass to the executable. All arguments must be separate string entries.
Beware that some commands have different ways of parsing arguments.
Typically, it is safest to have separate entries in the args array for the flag and its value:
args: ['--some-flag', 'some-flags-value']However, if an argument parser is implemented in a non-standard way, the flag and its value may need to be a single entry:
args: ['--some-flag=some-flags-value']cmd: string;Defined in: modules/subprocess/src/index.ts
The command to run. This should be an available executable or path to an executable.
name: string;Defined in: modules/subprocess/src/index.ts
A friendly name for the Step in log output.
optional opts: SpawnOptions;Defined in: modules/subprocess/src/index.ts
See the Node.js child_process.spawn() documentation for available options.
runDry?
Section titled “runDry?”optional runDry: boolean;Defined in: modules/subprocess/src/index.ts
Skip the --dry-run check and run this command anyway.
skipFailures?
Section titled “skipFailures?”optional skipFailures: boolean;Defined in: modules/subprocess/src/index.ts
Prevents throwing a `SubprocessError` in the event of the process failing and exiting with an unclean state.
optional step: LogStep;Defined in: modules/subprocess/src/index.ts
Pass a custom `LogStep` to bundle this process input & output into another step instead of creating a new one.
package.json
Section titled “package.json”getPublishablePackageJson()
Section titled “getPublishablePackageJson()”function getPublishablePackageJson(input): PublicPackageJson;Defined in: modules/package-manager/src/package-json.ts
Return a deep copy of a package.json suitabkle for publishing. Moves all non-standard publishConfig keys to the root of the package.json and deletes devDependencies.
Parameters:
| Parameter | Type |
|---|---|
input | PublicPackageJson |
Returns: PublicPackageJson
BasePackageJson
Section titled “BasePackageJson”type BasePackageJson = { alias?: string[]; author?: string | Person; bin?: string | Record<string, string>; bugs?: { email?: string; url?: string; }; bundleDependencies?: string[]; contributors?: (Person | string)[]; dependencies?: Record<string, string>; description?: string; devDependencies?: Record<string, string>; engines?: Record<string, string>; exports?: Record< string, | string | { default?: string; import?: string; require?: string; types?: string; } >; files?: string[]; homepage?: string; keywords?: string[]; license?: string; main?: string; name: string; optionalDependencies?: string[]; os?: string[]; overrides?: Record<string, string>; packageManager?: string; peerDependencies?: Record<string, string>; peerDependenciesMeta?: Record< string, { optional: boolean; } >; scripts?: Record<string, string>; version?: string;};Defined in: modules/package-manager/src/package-json.ts
Properties
Section titled “Properties”alias?
Section titled “alias?”optional alias: string[];Defined in: modules/package-manager/src/package-json.ts
Enable’s the `Graph` to look up `Workspace`s by shorter names or common `aliases` used by teams. This enables much short command-line execution. See `Graph.getByName` and `Graph.getAllByName`.
author?
Section titled “author?”optional author: string | Person;Defined in: modules/package-manager/src/package-json.ts
optional bin: string | Record<string, string>;Defined in: modules/package-manager/src/package-json.ts
optional bugs: { email?: string; url?: string;};Defined in: modules/package-manager/src/package-json.ts
email?
Section titled “email?”optional email: string;optional url: string;bundleDependencies?
Section titled “bundleDependencies?”optional bundleDependencies: string[];Defined in: modules/package-manager/src/package-json.ts
contributors?
Section titled “contributors?”optional contributors: (Person | string)[];Defined in: modules/package-manager/src/package-json.ts
dependencies?
Section titled “dependencies?”optional dependencies: Record<string, string>;Defined in: modules/package-manager/src/package-json.ts
description?
Section titled “description?”optional description: string;Defined in: modules/package-manager/src/package-json.ts
devDependencies?
Section titled “devDependencies?”optional devDependencies: Record<string, string>;Defined in: modules/package-manager/src/package-json.ts
engines?
Section titled “engines?”optional engines: Record<string, string>;Defined in: modules/package-manager/src/package-json.ts
exports?
Section titled “exports?”optional exports: Record<string, | string | { default?: string; import?: string; require?: string; types?: string;}>;Defined in: modules/package-manager/src/package-json.ts
files?
Section titled “files?”optional files: string[];Defined in: modules/package-manager/src/package-json.ts
homepage?
Section titled “homepage?”optional homepage: string;Defined in: modules/package-manager/src/package-json.ts
keywords?
Section titled “keywords?”optional keywords: string[];Defined in: modules/package-manager/src/package-json.ts
license?
Section titled “license?”optional license: string;Defined in: modules/package-manager/src/package-json.ts
optional main: string;Defined in: modules/package-manager/src/package-json.ts
name: string;Defined in: modules/package-manager/src/package-json.ts
The full name for the `Workspace`. This will be used within the package manager and publishable registry.
optionalDependencies?
Section titled “optionalDependencies?”optional optionalDependencies: string[];Defined in: modules/package-manager/src/package-json.ts
optional os: string[];Defined in: modules/package-manager/src/package-json.ts
overrides?
Section titled “overrides?”optional overrides: Record<string, string>;Defined in: modules/package-manager/src/package-json.ts
packageManager?
Section titled “packageManager?”optional packageManager: string;Defined in: modules/package-manager/src/package-json.ts
peerDependencies?
Section titled “peerDependencies?”optional peerDependencies: Record<string, string>;Defined in: modules/package-manager/src/package-json.ts
peerDependenciesMeta?
Section titled “peerDependenciesMeta?”optional peerDependenciesMeta: Record<string, { optional: boolean;}>;Defined in: modules/package-manager/src/package-json.ts
scripts?
Section titled “scripts?”optional scripts: Record<string, string>;Defined in: modules/package-manager/src/package-json.ts
version?
Section titled “version?”optional version: string;Defined in: modules/package-manager/src/package-json.ts
PackageJson
Section titled “PackageJson”type PackageJson = PrivatePackageJson | PublicPackageJson;Defined in: modules/package-manager/src/package-json.ts
Person
Section titled “Person”type Person = { email?: string; name?: string; url?: string;};Defined in: modules/package-manager/src/package-json.ts
Properties
Section titled “Properties”email?
Section titled “email?”optional email: string;Defined in: modules/package-manager/src/package-json.ts
optional name: string;Defined in: modules/package-manager/src/package-json.ts
optional url: string;Defined in: modules/package-manager/src/package-json.ts
PrivatePackageJson
Section titled “PrivatePackageJson”type PrivatePackageJson = { license?: 'UNLICENSED'; private: true; workspaces?: string[];} & BasePackageJson;Defined in: modules/package-manager/src/package-json.ts
Type declaration
Section titled “Type declaration”license?
Section titled “license?”optional license: "UNLICENSED";private
Section titled “private”private: true;workspaces?
Section titled “workspaces?”optional workspaces: string[];PublicPackageJson
Section titled “PublicPackageJson”type PublicPackageJson = { private?: false; publishConfig?: PublishConfig; workspaces?: never;} & BasePackageJson;Defined in: modules/package-manager/src/package-json.ts
Type declaration
Section titled “Type declaration”private?
Section titled “private?”optional private: false;publishConfig?
Section titled “publishConfig?”optional publishConfig: PublishConfig;workspaces?
Section titled “workspaces?”optional workspaces: never;PublishConfig
Section titled “PublishConfig”type PublishConfig = { [key: string]: unknown; bin?: string | Record<string, string>; exports?: Record< string, | string | { default?: string; import?: string; require?: string; types?: string; } >; main?: string; module?: string; typings?: string;};Defined in: modules/package-manager/src/package-json.ts
The publishConfig should follow NPM’s guidelines, apart from the possible defined extra keys here. Anything defined here will be merged back to the root of the package.json at publish time.
Use these keys to help differentiate between your repository’s source-dependency entrypoints vs published module entrypoints.
{3 collapsed lines
"name": "my-module", "license": "MIT", "type": "module", "main": "./src/index.ts", "publishConfig": { "access": "public", "main": "./dist/index.js", "typings": "./dist/index.d.ts" }}Indexable
Section titled “Indexable”[key: string]: unknownProperties
Section titled “Properties”optional bin: string | Record<string, string>;Defined in: modules/package-manager/src/package-json.ts
exports?
Section titled “exports?”optional exports: Record<string, | string | { default?: string; import?: string; require?: string; types?: string;}>;Defined in: modules/package-manager/src/package-json.ts
optional main: string;Defined in: modules/package-manager/src/package-json.ts
module?
Section titled “module?”optional module: string;Defined in: modules/package-manager/src/package-json.ts
typings?
Section titled “typings?”optional typings: string;Defined in: modules/package-manager/src/package-json.ts