@webcontainer/api
Version:
WebContainer Public API
343 lines (342 loc) • 12.9 kB
TypeScript
/**
* The WebContainer Public API allows you build custom applications on top of an in-browser Node.js runtime.
*
* Its main entrypoint is the {@link WebContainer} class.
*
* @packageDocumentation
*/
import type { FileSystemTree, AuthAPI, Unsubscribe, PreviewMessage, PreviewScriptOptions, ExportOptions, CodeEventType, CodeEvent } from './entities.js';
import { PreviewMessageType } from './preview-message-types.js';
export declare const auth: AuthAPI;
export type { DirectoryNode, FileNode, SymlinkNode, FileSystemTree, AuthAPI, AuthInitOptions, AuthFailedError, Unsubscribe, PreviewMessage, PreviewScriptOptions, BasePreviewMessage, ConsoleErrorMessage, UncaughtExceptionMessage, UnhandledRejectionMessage, ExportOptions, CodeEventType, CodeEvent, CodeEventFile, } from './entities.js';
export { PreviewMessageType };
export * from './utils.js';
/**
* The main export of this library. An instance of `WebContainer` represents a runtime
* ready to be used.
*/
export declare class WebContainer {
/**
* Gives access to the underlying file system.
*/
fs: FileSystemAPI;
private _tornDown;
private _unsubscribeFromTokenChangedListener;
/**
* Spawns a process.
*
* @param command - The program to be executed.
* @param args - The command-line arguments for the program.
*
* @example
* ```
* const install = await webcontainer.spawn('npm', ['i']);
* ```
*/
spawn(command: string, args: string[], options?: SpawnOptions): Promise<WebContainerProcess>;
/**
* Spawns a process without command-line arguments.
*
* @param command - The program to be executed.
*
* @example
* ```
* const install = await webcontainer.spawn('yarn');
* ```
*/
spawn(command: string, options?: SpawnOptions): Promise<WebContainerProcess>;
/**
* Exports the provided `path` in the format provided.
*
* @param path - The path to serialize.
* @param options - Additional serialize options.
*
* @example
* ```
* const fileTree = await webcontainer.export('dist', { format: 'json' });
* ```
*/
export(path: string): Promise<FileSystemTree>;
export(path: string, options: ExportOptions & {
format?: 'json';
}): Promise<FileSystemTree>;
export(path: string, options: ExportOptions): Promise<Uint8Array>;
/**
* Listens for `port` events, which are emitted when a port is opened or closed by some process.
*/
on(event: 'port', listener: PortListener): Unsubscribe;
/**
* Listens for `server-ready` events, emitted when a running server is listening for incoming
* connections and ready to answer requests.
*/
on(event: 'server-ready', listener: ServerReadyListener): Unsubscribe;
/**
* Listens for `preview-message` events, emitted when a preview sends a `PreviewMessage`.
*/
on(event: 'preview-message', listener: PreviewMessageListener): Unsubscribe;
/**
* Listens for `error` events, emitted when an internal error is triggered.
*/
on(event: 'error', listener: ErrorListener): Unsubscribe;
/**
* Listens for `xdg-open` events, emitted when the `xdg-open` command is invoked.
*/
on(event: 'xdg-open', listener: OpenListener): Unsubscribe;
/**
* Listens for `code` events, emitted when the `code` command is invoked.
*/
on(event: 'code', listener: CodeListener): Unsubscribe;
/**
* Mounts a tree of files into the filesystem. This can be specified as a tree object ({@link FileSystemTree})
* or as a binary snapshot generated by [`@webcontainer/snapshot`](https://www.npmjs.com/package/@webcontainer/snapshot).
*
* @param snapshotOrTree - A tree of files, or a binary snapshot. Note that binary payloads will be transferred.
* @param options.mountPoint - Specifies a nested path where the tree should be mounted.
*/
mount(snapshotOrTree: FileSystemTree | Uint8Array | ArrayBuffer, options?: {
mountPoint?: string;
}): Promise<void>;
/**
* Set a custom script to be injected into all previews. When this function is called, every
* future page reload will contain the provided script tag on all HTML responses.
*
* Note:
*
* When this function resolves, every preview reloaded _after_ will have the new script.
* Existing preview have to be explicitely reloaded.
*
* To reload a preview you can use `reloadPreview`.
*
* @param scriptSrc Source for the script tag.
* @param options Options to define which type of script this is.
*/
setPreviewScript(scriptSrc: string, options?: PreviewScriptOptions): Promise<void>;
/**
* The default value of the `PATH` environment variable for processes started through {@link spawn}.
*/
get path(): string;
/**
* The full path to the working directory (see {@link FileSystemAPI}).
*/
get workdir(): string;
/**
* Destroys the WebContainer instance, turning it unusable, and releases its resources. After this,
* a new WebContainer instance can be obtained by calling {@link WebContainer.boot | `boot`}.
*
* All entities derived from this instance (e.g. processes, the file system, etc.) also become unusable
* after calling this method.
*/
teardown(): void;
/**
* Boots a WebContainer. Only a single instance of WebContainer can be booted concurrently
* (see {@link WebContainer.teardown | `teardown`}).
*
* Booting WebContainer is an expensive operation.
*/
static boot(options?: BootOptions): Promise<WebContainer>;
}
/**
* Configure an API key to be used for this instance of WebContainer.
*
* @param key WebContainer API key.
*/
export declare function configureAPIKey(key: string): void;
export interface BootOptions {
/**
* The value of the {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cross-Origin-Embedder-Policy | COEP} header
* used to load your application.
*
* Choosing 'none' will result in no cross-origin isolation headers being used. This will only work on Chromium-based
* browsers as long as an Origin Trial is supported.
*
* This value is fixed the first time a WebContainer is booted, and cannot be changed in successive reboots.
*
* For more info about cross-origin isolation, see our {@link https://webcontainers.io/guides/quickstart | docs}.
*/
coep?: 'require-corp' | 'credentialless' | 'none';
/**
* Sets the _folder name_ for the working directory of your WebContainer instance (see {@link FileSystemAPI}).
* If not provided, it will be auto-generated.
*
* This is mostly a "cosmetic" option.
*/
workdirName?: string;
/**
* Whether errors occurring in preview iframes on the current page should be forwarded
* to the parent page. Captured errors originate from:
*
* - Calls to `console.error`
* - Any `unhandledrejection` events on `window`
* - Any uncaught `error` events on `window`
*
* If set to 'exceptions-only', 'console.error's are not forwarded.
*
* @default false
*/
forwardPreviewErrors?: boolean | 'exceptions-only';
}
/**
* @param port - The port on which the server is listening.
* @param type - The new status of the port.
* @param url - The url where the server can be accessed.
*/
export declare type PortListener = (port: number, type: 'open' | 'close', url: string) => void;
/**
* @param port - The port on which the readied server is listening.
* @param url - The url where the server can be accessed.
*/
export declare type ServerReadyListener = (port: number, url: string) => void;
/**
* @param message - The message sent by a preview.
*/
export declare type PreviewMessageListener = (message: PreviewMessage) => void;
/**
* @param error - The emitted error.
*/
export declare type ErrorListener = (error: {
message: string;
}) => void;
/**
* @param text - The file or URL.
*/
export declare type OpenListener = (text: string) => void;
/**
* @param type - Whether a file or diff is being opened.
* @param event - A list of specified paths.
*/
export declare type CodeListener = (type: CodeEventType, event: CodeEvent) => void;
/**
* A representation of a directory entry,
* see {@link https://nodejs.org/dist/latest-v16.x/docs/api/fs.html#class-fsdirent | the Node.js API}.
*/
export interface DirEnt<T> {
name: T;
isFile(): boolean;
isDirectory(): boolean;
}
/**
* Interface to interact directly with the WebContainer filesystem. Modeled after
* {@link https://nodejs.org/dist/latest-v16.x/docs/api/fs.html#promises-api | `fs.promises`} in Node.
*
* File system operations exposed here are scoped to the working directory: a given folder predetermined at boot time.
* All paths are resolved with respect to this working directory.
*/
export interface FileSystemAPI {
readdir(path: string, options: 'buffer' | {
encoding: 'buffer';
withFileTypes?: false;
}): Promise<Uint8Array[]>;
readdir(path: string, options?: {
encoding?: BufferEncoding | null;
withFileTypes?: false;
} | BufferEncoding | null): Promise<string[]>;
readdir(path: string, options: {
encoding: 'buffer';
withFileTypes: true;
}): Promise<DirEnt<Uint8Array>[]>;
readdir(path: string, options: {
encoding?: BufferEncoding | null;
withFileTypes: true;
}): Promise<DirEnt<string>[]>;
readFile(path: string, encoding?: null): Promise<Uint8Array>;
readFile(path: string, encoding: BufferEncoding): Promise<string>;
writeFile(path: string, data: string | Uint8Array, options?: string | {
encoding?: string | null;
} | null): Promise<void>;
mkdir(path: string, options?: {
recursive?: false;
}): Promise<void>;
mkdir(path: string, options: {
recursive: true;
}): Promise<string>;
rm(path: string, options?: {
force?: boolean;
recursive?: boolean;
}): Promise<void>;
rename(oldPath: string, newPath: string): Promise<void>;
watch(filename: string, options?: FSWatchOptions, listener?: FSWatchCallback): IFSWatcher;
watch(filename: string, listener?: FSWatchCallback): IFSWatcher;
}
/**
* Interface for manipulating watching.
*/
export interface IFSWatcher {
close(): void;
}
/**
* Options for configuring fs.watch.
*/
export declare type FSWatchOptions = {
encoding?: BufferEncoding | null;
persistent?: boolean;
recursive?: boolean;
} | string | null;
/**
* Callback triggered on watch events.
*/
export declare type FSWatchCallback = (event: 'rename' | 'change', filename: string | Uint8Array) => void;
/**
* A running process spawned in a {@link WebContainer}.
*/
export interface WebContainerProcess {
/**
* A promise for the exit code of the process.
*/
exit: Promise<number>;
/**
* An input stream for the attached pseudoterminal device.
*/
input: WritableStream<string>;
/**
* A stream that receives all terminal output, including the stdout and stderr emitted by the spawned process
* _and_ its descendants.
*
* Can be disabled by setting {@link SpawnOptions | `output` } to `false`.
*/
output: ReadableStream<string>;
/**
* Kills the process.
*/
kill(): void;
/**
* Resizes the attached terminal.
*/
resize(dimensions: {
cols: number;
rows: number;
}): void;
}
/**
* Options that control process spawning.
*/
export interface SpawnOptions {
/**
* Current working directory for the process, relative to the {@link WebContainer.workdir | `workdir`} of this instance (which
* you can change when {@link WebContainer.boot | booting `WebContainer`}).
*
* By default, the working directory of the spawned process is {@link WebContainer.workdir | `workdir`}.
*/
cwd?: string;
/**
* Environment variables to set for the process.
*/
env?: Record<string, string | number | boolean>;
/**
* When set to false, no terminal output is sent back to the process,
* and the {@link WebContainerProcess.output | `output`} stream will never produce any chunks.
*/
output?: boolean;
/**
* The size of the attached terminal.
*/
terminal?: {
cols: number;
rows: number;
};
}
/**
* Represents the character encoding options available for encoding and decoding data in Node.js buffers.
*
* @see {@link https://nodejs.org/api/buffer.html#buffer_buffers_and_character_encodings|Node.js Buffer Documentation}
*/
export declare type BufferEncoding = 'ascii' | 'utf8' | 'utf-8' | 'utf16le' | 'ucs2' | 'ucs-2' | 'base64' | 'base64url' | 'latin1' | 'binary' | 'hex';