Install the package via bun add --dev bun-workspaces to use the API.
See the Glossary for more fundamental concepts.
Required Bun version: ^1.2.x
createFileSystemProject(options: CreateFileSystemProjectOptions): FileSystemProject
Create a FileSystemProject, the core of bun-workspaces's functionality, based on a given root directory.
This finds Workspaces by reading the project's bun.lock file, which means bun install must be run to have up-to-date
workspace information.
It will also detect and utilize any workspace configuration found.
import { createFileSystemProject } from "bun-workspaces";
const project = createFileSystemProject({
rootDirectory: "./path/to/project/root" // relative from process.cwd()
});
console.log(project.name); // The name from the root package.json
console.log(project.workspaces); // An array of workspaces found in the project
An object representing a workspace in a Project.
Set workspace aliases in the workspace configuration to make it easier to reference workspaces.
{
// The name of the workspace from its package.json
name: "my-workspace",
// The relative path to the workspace from the project root
path: "my/workspace/path",
// The glob pattern from the root package.json "workspaces" field
// that this workspace was matched from
matchPattern: "my/workspace/pattern/*",
// The scripts available in the workspace's package.json
scripts: ["my-script"],
// Aliases defined in workspace configuration (see the Configuration section)
aliases: ["my-alias"]
}
The core of bun-workspaces's functionality.
It contains a list of Workspaces and provides
several useful methods for working with them. A Project is typically initialized at a git repository's root directory.
The Project root should contain the package.json file in which "workspaces" are defined.
Usually created via createFileSystemProject.
type: string
The name of the project. This is typically the name found in the root package.json unless otherwise provided.
type: string
The given root directory of the project.
type: Workspace[]
The list of all Workspaces in the project.
findWorkspaceByName(workspaceName: string): Workspace | null
Find a Workspace by its package.json name.
// Find a workspace by its package.json name (or returns null)
const workspace = project.findWorkspaceByName("my-workspace");
findWorkspaceByAlias(alias: string): Workspace | null
Find a Workspace by its alias, if set in its workspace configuration.
// Find a workspace by its alias (or returns null)
const workspace = project.findWorkspaceByAlias("my-alias");
findWorkspaceByNameOrAlias(nameOrAlias: string): Workspace | null
Find a Workspace by its package.json name or alias, if set in its workspace configuration.
Since aliases are validated to be unique to each workspace and not clash with other workspaces' package.json names, this method can still unambiguously find a workspace.
// Find a workspace by its package.json name or alias (or returns null)
const workspace = project.findWorkspaceByNameOrAlias("my-workspace");
findWorkspacesByPattern(workspacePattern: string): Workspace[]
Find a list of Workspaces by their name, using a wildcard pattern.
To prevent ambiguity, this method does not match workspace aliases.
// An array of workspaces whose names match the wildcard pattern
const workspaces = project.findWorkspacesByPattern("my-pattern-*");
listWorkspacesWithScript(scriptName: string): Workspace[]
Get an array of all Workspaces that have a given script in their package.json "scripts" field.
// An array of workspaces that have "my-script"
// in their package.json "scripts" field
const workspaces = project.listWorkspacesWithScript("my-script"));
mapScriptsToWorkspaces(): Record<string, WorkspaceScriptMetadata>
Get a mapping of all project script names to the Workspaces that have them in their package.json "scripts" field.
// An object mapping all script names to the workspaces
// that have them in their package.json "scripts" field
const scriptMap = project.mapScriptsToWorkspaces();
// An array of Workspaces
const { workspaces } = scriptMap["my-script"];
createScriptCommand(options: CreateProjectScriptCommandOptions): CreateProjectScriptCommandResult
Create metadata that can be used to run a Workspace's script.
The "method" option changes what kind of bun command is implemented to run the script.
"cd" (the default) is generally recommended over "filter" in order to get full stdout/stderr output from the script.
// Does not run a script, but provides
// metadata that can be used to do so.
const {
commandDetails: { command, workingDirectory },
} = project.createScriptCommand({
scriptName: "my-script",
workspaceNameOrAlias: "my-workspace",
method: "cd", // optional, defaults to "cd" (other option "filter")
args: "--my-appended-args", // optional, append args to the command
});
// A means by which you may actually run the script
const subprocess = Bun.spawn(["sh", "-c", command], {
cwd: workingDirectory,
});
Inherits from Project. Used to represent a project in the file system. Created via createFileSystemProject.
Includes methods for running scripts in the workspaces of the project.
runWorkspaceScript(options: RunWorkspaceScriptOptions): RunWorkspaceScriptResult
Run a script in a given workspace.
const { output, exit } = project.runWorkspaceScript({
workspaceNameOrAlias: "my-workspace",
script: "my-script",
args: "--my --appended --args", // optional, arguments to add to the command
});
// Get a stream of the script subprocess's output
for await (const { outputChunk } of output) {
console.log(outputChunk.raw); // The raw output content (Uint8Array)
console.log(outputChunk.decode()); // The output chunk's content (string)
console.log(outputChunk.decode({ stripAnsi: true })); // Text with ANSI codes sanitized (string)
console.log(outputChunk.streamName); // The output stream, "stdout" or "stderr"
}
// Get data about the script execution after it exits
const exitResult = await exit;
console.log(exitResult.exitCode); // The exit code (number)
console.log(exitResult.signal); // The exit signal (string), or null
console.log(exitResult.success); // true if exit code was 0
console.log(exitResult.startTimeISO); // Start time (string)
console.log(exitResult.endTimeISO); // End time (string)
console.log(exitResult.durationMs); // Duration in milliseconds (number)
console.log(exitResult.metadata.workspace); // The target workspace (Workspace)
runScriptAcrossWorkspaces(options: RunScriptAcrossWorkspacesOptions): RunScriptAcrossWorkspacesResult
,
Run a script in all workspaces that have it in their package.json "scripts" field.
const { output, summary } = project.runScriptAcrossWorkspaces({
workspacePatterns: ["*"], // this will run in all workspaces that have my-script
script: "my-script", // the package.json "scripts" field name to run
args: "--my --appended --args", // optional, arguments to add to the command
parallel: true, // optional, run the scripts in parallel
});
// Get a stream of script output
for await (const { outputChunk, scriptMetadata } of output) {
console.log(outputChunk.decode()); // the output chunk's content (string)
console.log(outputChunk.decode({ stripAnsi: true })); // text with ANSI codes sanitized (string)
console.log(outputChunk.streamName); // "stdout" or "stderr"
// The metadata can distinguish which workspace script
// the current output chunk came from
console.log(scriptMetadata.workspace); // Workspace object
}
// Get final summary data and script exit details after all scripts have completed
const summaryResult = await summary;
console.log(summaryResult.totalCount); // Total number of scripts
console.log(summaryResult.allSuccess); // true if all scripts succeeded
console.log(summaryResult.successCount); // Number of scripts that succeeded
console.log(summaryResult.failureCount); // Number of scripts that failed
console.log(summaryResult.startTimeISO); // Start time (string)
console.log(summaryResult.endTimeISO); // End time (string)
console.log(summaryResult.durationMs); // Total duration in milliseconds (number)
// The exit details of each workspace script
for (const exitResult of summaryResult.scriptResults) {
console.log(exitResult.exitCode); // The exit code (number)
console.log(exitResult.signal); // The exit signal (string), or null
console.log(exitResult.success); // true if exit code was 0
console.log(exitResult.startTimeISO); // Start time (ISO string)
console.log(exitResult.endTimeISO); // End time (ISO string)
console.log(exitResult.durationMs); // Duration in milliseconds (number)
console.log(exitResult.metadata.workspace); // The target workspace (Workspace)
}
See more on running inline scripts.
See more on running parallel scripts.
See more on script runtime metadata, such as environment variables available in scripts and interpolating values in inline scripts and args such as <workspaceName>.
createMemoryProject(options: CreateMemoryProjectOptions): MemoryProject
Create a Project from a given array of Workspaces.
Usually used only for testing purposes to do without the need for a real project in the file system.
Since it doesn't read anything from the file system, it isn't affected by workspace configuration.
A MemoryProject currently does not support running scripts directly, though a means of mocking script execution may be added later, considering demand.
import { createMemoryProject } from "bun-workspaces";
const testProject = createMemoryProject({
rootDirectory: "test-project-directory", // optional
name: "test-project", // optional
workspaces: [
{
name: "my-test-workspace",
path: "my/test/workspace/path",
matchPattern: "my/test/workspace/pattern/*",
scripts: ["my-test-script"],
aliases: ["test-alias"]
}
]
});
setLogLevel(level: LogLevelSetting)
Set the global logging level. Defaults to "info" or "error" when NODE_ENV is "test".
import { setLogLevel } from "bun-workspaces";
setLogLevel("debug");
setLogLevel("info"); // default
setLogLevel("warn");
setLogLevel("error"); // default when NODE_ENV is "test"
setLogLevel("silent");