UNPKG

@remotex-labs/xbuild

Version:

A versatile JavaScript and TypeScript toolchain build system

1,174 lines 117 kB
import type { Loader, OnLoadArgs, BuildResult, OnEndResult, PluginBuild, OnLoadResult, OnResolveArgs, OnResolveResult, BuildOptions, Format, Metafile, Message } from "esbuild"; import type { IncomingMessage, ServerResponse } from "http"; import type { SourceService } from "@remotex-labs/xmap"; import type { Argv } from "yargs"; import type { ChildProcessWithoutNullStreams } from "child_process"; import type { ParsedCommandLine } from "typescript"; import type { Context } from "vm"; /** * Interface for the build state that users can modify. * * This interface allows users to store and manage any custom data related to the build process. * * @template T - The type of values that can be stored in the state. */ export interface BuildState { [key: string]: unknown; } /** * A type that defines the possible return values of a plugin function. * * The function can return a Promise that resolves to `null` or `void`, or it can return `null` or `void` directly. */ export type pluginResultType = Promise<null | void> | null | void; /** * Defines the signature of a function that is called at the end of the build process. * * @param result - The `BuildResult` object that contains information about the outcome of the build process. * @param state - The current build state that users can modify. * @returns A `pluginResultType`, which may include asynchronous operations. */ export type OnEndType = (result: BuildResult, state: BuildState) => pluginResultType | OnEndResult | Promise<OnEndResult>; /** * Defines the signature of a function that is called at the start of the build process. * * @param build - The `PluginBuild` object that contains information about the build process and allows modifying build options. * @param state - The current build state that users can modify. * @returns A `pluginResultType`, which may include asynchronous operations. */ export type OnStartType = (build: PluginBuild, state: BuildState) => pluginResultType | OnEndResult | Promise<OnEndResult>; /** * Defines the signature of a function that is called during the resolution of an import path. * * @param args - The `OnResolveArgs` object, containing information about the file being resolved, such as its path, importer, namespace, etc. * @param state - The current build state that users can modify. * @returns A `Promise` or a direct `OnResolveResult` which can modify the resolved path, or a `pluginResultType` for * performing additional async tasks without altering resolution. */ export type OnResolveType = (args: OnResolveArgs, state: BuildState) => Promise<OnResolveResult | pluginResultType> | OnResolveResult | pluginResultType; /** * Defines the signature of a function that is called when a file is loaded. * * @param content - The content of the file being loaded, as either a `string` or `Uint8Array`. * @param loader - The type of loader used for the file, such as `js`, `ts`, `json`, or others. It can also be `undefined`. * @param args - The `OnLoadArgs` object, containing information about the file being loaded, such as its path, namespace, etc. * @param state - The current build state that users can modify. * @returns A `Promise` or direct `OnLoadResult`, which can modify the file content and loader, or a `pluginResultType` * for performing additional async tasks without altering the content. */ export type OnLoadType = (content: string | Uint8Array, loader: Loader | undefined, args: OnLoadArgs, state: BuildState) => Promise<OnLoadResult | pluginResultType> | OnLoadResult | pluginResultType; /** * Represents the format for specifying entry points in TypeScript declaration generation. * * This type allows for various formats to specify the entry points from which TypeScript declaration files should be generated. * The supported formats are: * - `Array<string>`: An array of file paths as strings. Each string represents a path to a TypeScript entry point file. * - `Record<string, string>`: An object where each key-value pair represents an entry point. * * The key is a name or identifier, and the value is the file path to the TypeScript entry point. * - `Array<{ in: string, out: string }>`: An array of objects, where each object specifies an input file path (`in`) * and an output file path (`out`). This format allows for specifying where each entry point file is located and * where its corresponding declaration file should be output. * * Example usage: * * ```ts * const entryPoints1: EntryPoints = ['src/index.ts', 'src/utils.ts']; * const entryPoints2: EntryPoints = { main: 'src/index.ts', utils: 'src/utils.ts' }; * const entryPoints3: EntryPoints = [{ in: 'src/index.ts', out: 'dist/index.d.ts' }, { in: 'src/utils.ts', out: 'dist/utils.d.ts' }]; * ``` */ export type EntryPoints = Array<string> | Record<string, string> | Array<{ in: string; out: string; }> | undefined; /** * Represents a deeply nested partial version of a given type `T`. * * This type utility allows for partial objects at any level of nesting. * It recursively makes all properties optional and applies the same behavior to nested objects. * * **Example Usage:** * * ```ts * interface User { * name: string; * address: { * street: string; * city: string; * }; * } * * // PartialDeep<User> will allow the following: * const partialUser: PartialDeep<User> = { * name: 'Alice', // 'name' is optional * address: { * city: 'Wonderland' // 'street' is optional * } * }; * ``` * * @template T - The type to be made partially optional and deeply nested. * * @typeParam T - The base type to apply the partial transformation. * * @example * ``` * type MyPartial = PartialDeep<{ a: number; b: { c: string; d: { e: boolean } } }>; * // MyPartial will be equivalent to: * // { * // a?: number; * // b?: { * // c?: string; * // d?: { * // e?: boolean; * // } * // } * // } * ``` */ export type PartialDeep<T> = { [P in keyof T]?: T[P] extends object ? PartialDeep<T[P]> : T[P]; }; /** * Represents a module with its exports and an optional default export. * * This interface provides a structure to define and interact with the exports of a module. * It includes both named and default exports, where default exports are of a specific type. * * @interface ModuleInterface * * @property exports - An object representing the exports of the module. * The keys are strings that represent the names of the exports, and the values can be of any type. * * @property exports[key: string] - A dictionary where each key is a string representing the export name, * and the associated value can be of any type. * * @property [exports.default] - An optional default export. * The default export, if present, is of type `ConfigurationInterface`. */ export interface ModuleInterface { /** * An object representing the exports of the module. * The keys are strings representing export names, and the values can be of any type. * * @property default - An optional default export of type `ConfigurationInterface`. */ exports: { [key: string]: unknown; default?: ConfigurationInterface; }; } /** * Configuration options for the serve the build. * * This object allows you to specify various settings related to the server, * such as the port, host, SSL/TLS certificates, and request handling functions. * * @example * ```ts * const serverConfig = { * serve: { * active: true, * port: 8080, * host: 'localhost', * keyfile: '/path/to/ssl/keyfile.pem', * certfile: '/path/to/ssl/certfile.pem', * onStart: () => { * console.log('Server started'); * } * onRequest: (req, res, next) => { * console.log('Server request received'); * next(); * } * } * }; * ``` * * @public */ export interface Serve { port: number; host: string; active: boolean; keyfile?: string; certfile?: string; onRequest?: (req: IncomingMessage, res: ServerResponse, next: () => void) => void; onStart?: () => void; } /** * Defines the lifecycle hooks used in the plugin system. * * This interface specifies the types for various hooks that can be registered * to customize the behavior of the build process. Each hook corresponds to a * specific stage in the lifecycle of an esbuild operation. * * @interface hooks * * @property onEnd - A hook function that is called after the build process completes. * This allows for post-processing or cleanup tasks. * @property onLoad - A hook function that is called when esbuild attempts to load a module. * It can be used to modify the contents of the loaded module. * @property onStart - A hook function that is called before the build process starts. * This is useful for initialization tasks or logging. * @property onResolve - A hook function that is called when esbuild attempts to resolve a module path. * It can be used to customize module resolution behavior. * * @example * ```ts * const myHooks: hooks = { * onEnd: async (result) => { * console.log('Build finished:', result); * }, * onLoad: async (contents, loader, args) => { * // Modify contents if necessary * return { contents, loader }; * }, * onStart: async (build) => { * console.log('Build started:', build); * }, * onResolve: async (args) => { * if (args.path === 'my-module') { * return { path: './src/my-module.ts' }; * } * return null; * } * }; * ``` * * @see OnEndType * @see OnLoadType * @see OnStartType * @see OnResolveType */ export interface hooks { onEnd: OnEndType; onLoad: OnLoadType; onStart: OnStartType; onSuccess: OnEndType; onResolve: OnResolveType; } /** * Represents the configuration options for the build and development process. * * This interface defines various settings that control how the application is built and run, including development mode, * file watching, TypeScript declaration generation, error handling, TypeScript type checking, and esbuild bundler options. * * @example * ```ts * const config: ConfigurationInterface = { * dev: true, * watch: true, * declaration: true, * buildOnError: false, * noTypeChecker: false, * esbuild: { * entryPoints: ['./src/index.ts'], * bundle: true, * minify: true, * target: 'es2020' * }, * hooks: { * onStart: async (build) => { * console.log('Build started'); * }, * onEnd: async (result) => { * console.log('Build finished:', result); * } * } * }; * ``` * * In this example, the configuration sets the application to development mode with file watching enabled, * generates TypeScript declaration files, continues building on TypeScript errors, and includes esbuild options for bundling and minification. * Additionally, custom hooks are provided to log messages at the start and end of the build process. * * @public * @category Configuration */ export interface ConfigurationInterface { /** * Build and run entryPoint for development */ dev: boolean | Array<string>; /** * Enables watching for file changes during development. */ watch: boolean; /** * The directory where the generated `package.json` file will be saved, * indicating the module type (`"commonjs"` or `"module"`). * * - If the format is `esm`, the `package.json` file will contain `"type": "module"`. * - If the format is `cjs`, the `package.json` file will contain `"type": "commonjs"`. * * If this field is not set (`undefined`), the `package.json` file will be saved in the * `outdir` specified in the esbuild configuration. * * Example: * * ```ts * { * esbuild: { * outdir: 'dist', * format: 'esm' * }, * moduleTypeOutDir: 'custom/dist' * } * // This will create 'custom/dist/package.json' with the content: {"type": "module"} * * // If moduleTypeOutDir is not provided: * { * esbuild: { * outdir: 'dist', * format: 'cjs' * } * } * // This will create 'dist/package.json' with the content: {"type": "commonjs"} * ``` */ moduleTypeOutDir?: string; /** * Generates TypeScript declaration files. */ declaration: boolean; /** * Bundle declaration file */ bundleDeclaration: boolean; /** * Overrides the output directory for TypeScript declaration files (.d.ts). * * If this option is not set, the output directory specified in the `outDir` * field of your `tsconfig.json` will be used. * This allows for custom control * over where the declaration files are emitted, separate from the main * output directory for compiled JavaScript files. * * @default The `outDir` from `tsconfig.json` will be used if this is not provided. */ declarationOutDir?: string; /** * Continues building even if TypeScript type errors are present. */ buildOnError: boolean; /** * Skips TypeScript type checking. */ noTypeChecker: boolean; /** * Options for the esbuild bundler. */ esbuild: BuildOptions; /** * Option for the serve the build over http/s */ serve: Serve; /** * lifecycle hooks to customize the build process. * * This property allows you to provide implementations for various hooks defined in the `hooks` interface. * Using `Partial<hooks>` means you can specify only the hooks you want to implement, * while the others will default to `undefined`. */ hooks?: Partial<hooks>; /** * A dictionary of define options for the build process. * * This property allows you to specify global constants that can be replaced during the build process. * Each key-value pair in the `define` object represents a constant where the key is the name of the * constant, and the value is the string to replace it with. This is particularly useful for feature flags, * environment-specific configurations, or any other value that you may want to define at compile time. * * @example * ```ts * const config: ConfigurationInterface = { * dev: true, * define: { * 'process.env.NODE_ENV': 'development', * 'API_URL': 'https://api.example.com' * } * }; * ``` * * In this example, the constants `process.env.NODE_ENV` and `API_URL` will be replaced with their * corresponding values during the build, making it easy to manage different configurations across * various environments. * * @public */ define: Record<string, unknown>; /** Documentation: https://esbuild.github.io/api/#banner */ banner?: { [type: string]: string | (() => string); }; /** Documentation: https://esbuild.github.io/api/#footer */ footer?: { [type: string]: string | (() => string); }; } interface ExportedConfigurationInterface extends ConfigurationInterface { /** * Options for the esbuild bundler. */ esbuild: Omit<BuildOptions, 'plugins' | 'define'>; } /** * Type alias for a partial configuration object. * * This type represents a configuration where all properties of the * `ConfigurationInterface` are optional. It allows for flexible configuration * objects where only a subset of properties need to be specified. */ export type xBuildConfig = PartialDeep<ExportedConfigurationInterface>; /** * Represents a partially deep configuration type based on the `ConfigurationInterface`. * * This type is used to define configurations that may have some properties * missing or undefined. It leverages the `PartialDeep` utility type to allow * for flexibility in configuration management. */ export type PartialDeepConfigurationsType = PartialDeep<ConfigurationInterface>; /** * Defines the possible types for configurations. * * This type can either be a single instance of `PartialDeepConfigurationsType` * or an array of such instances. This flexibility allows for configurations * to be specified as a single object or as multiple objects, enabling * support for various build setups. * * @example * ```ts * // A single configuration object * const config: ConfigurationsType = { * esbuild: { * bundle: true, * outdir: 'dist' * } * }; * ``` * * @example * ```ts * // An array of configuration objects * const configs: ConfigurationsType = [ * { * esbuild: { * bundle: true, * outdir: 'dist/esm' * } * }, * { * esbuild: { * bundle: false, * outdir: 'dist/cjs', * declaration: false, * noTypeChecker: true * } * } * ]; * ``` */ export type ConfigurationsType = PartialDeepConfigurationsType | Array<PartialDeepConfigurationsType>; /** * Interface representing the command-line arguments for the build tool. * * @interface ArgvInterface * @property typeCheck - Flag indicating if the tool should perform type checking only. * @property node - Flag indicating if the build is intended for Node.js environment. * @property file - The entry file(s) to build. * @property dev - List of development-related options for the build. * @property debug - List of debugging-related options for the build. * @property serve - Flag indicating if an HTTP server should be started for the build folder. * @property outdir - The output directory for the build files. * @property declaration - Flag indicating if TypeScript declaration files should be generated. * @property watch - Flag indicating if the build should watch for file changes. * @property config - Path to the build configuration file (JavaScript or TypeScript). * @property tsconfig - Path to the TypeScript configuration file to use. * @property minify - Flag indicating if the code should be minified. * @property bundle - Flag indicating if the code should be bundled. * @property format - Defines the formats for the build output. */ export interface ArgvInterface { typeCheck: boolean; node: boolean; file: string; dev: Array<string>; debug: Array<string>; serve: boolean; outdir: string; declaration: boolean; watch: boolean; config: string; tsconfig: string; minify: boolean; bundle: boolean; format: Format; } /** * Represents an enhanced error type that extends the built-in Error object. * This type adds an optional property to store call stack information. * * @type ErrorType * * @extends Error * * @property callStacks - An optional array of call sites * captured when the error was created. This can provide additional context * regarding the call stack at the time of the error, useful for debugging. * * @example * ```ts * const myError: ErrorType = new Error("Something went wrong!"); * myError.callStacks = getCallStack(); // Assuming getCallStack captures call sites. * console.error(myError); * ``` */ export type ErrorType = Error & { callStacks?: Array<NodeJS.CallSite>; }; /** * Represents the state of a stack trace, containing information about the error, associated code, and formatted error message. * * @interface StackTraceStateInterface * @property error - The error object with attached `callStacks`. * @property blockCode - The block of code (if any) related to the error, or `null` if unavailable. * @property formattedError - A formatted string representing the error details. */ export interface StackTraceStateInterface { error: ErrorType & BaseError; blockCode: null | string; formattedError: string; } /** * Represents detailed information about a specific frame in the call stack. * * @interface FrameDetailsInterface * @property line - The line number where the frame occurred. * @property column - The column number where the frame occurred. * @property source - The source file path where the frame occurred. * @property functionName - The name of the function being executed at this frame, or an empty string if not available. */ export interface FrameDetailsInterface { line: number; column: number; source: string; functionName: string; } /** * A base class for custom errors with enhanced stack trace formatting and source code information. * * The `BaseError` class extends the native `Error` class, adding functionality to format the error stack * trace and include details from a source map service. This is useful for debugging errors in compiled * or transpiled code by providing clearer information about the source of the error. */ export declare abstract class BaseError extends Error { readonly sourceMap?: SourceService | undefined; callStacks: Array<NodeJS.CallSite>; /** * Creates a new instance of `BaseError`. * * This constructor initializes a new `BaseError` instance by setting the error message and formatting * the stack trace using the provided source map information. It also ensures the stack trace is maintained * correctly by using `Error.captureStackTrace` (if available). The default source map service is used if * none is provided. * * @param message - A descriptive error message to be associated with the error. * @param sourceMap - (Optional) The `SourceService` instance used to format and resolve the stack trace. * If not provided, the default source map service (`defaultSourceService`) is used. */ protected constructor(message: string, sourceMap?: SourceService | undefined); /** * Reformats the error stack trace using source map information. * * This function enhances the original error stack trace by attempting to map each entry * back to its original position in the source file using the provided source map service. * If the source map information is not available, it returns the original stack trace. * * @param error - The original error with stack trace of the error. * @returns The reformatted stack trace or the original stack trace if no mapping is available. */ protected reformatStack(error: ErrorType): string; } /** * An enumeration of ANSI color codes used for text formatting in the terminal. * * These colors can be used to format terminal output with various text colors, * including different shades of gray, yellow, and orange, among others. * * Each color code starts with an ANSI escape sequence (`\u001B`), followed by the color code. * The `Reset` option can be used to reset the terminal's text formatting back to the default. * * @example * ```ts * console.log(Color.BrightPink, 'This is bright pink text', Color.Reset); * ``` */ export declare const enum Colors { Reset = "\u001B[0m", Red = "\u001B[38;5;9m", Gray = "\u001B[38;5;243m", Cyan = "\u001B[38;5;81m", DarkGray = "\u001B[38;5;238m", LightCoral = "\u001B[38;5;203m", LightOrange = "\u001B[38;5;215m", OliveGreen = "\u001B[38;5;149m", BurntOrange = "\u001B[38;5;208m", LightGoldenrodYellow = "\u001B[38;5;221m", LightYellow = "\u001B[38;5;230m", CanaryYellow = "\u001B[38;5;227m", DeepOrange = "\u001B[38;5;166m", LightGray = "\u001B[38;5;252m", BrightPink = "\u001B[38;5;197m" } /** * Formats a message string with the specified ANSI color and optionally resets it after the message. * * This function applies an ANSI color code to the provided message, * and then appends the reset code to ensure that the color formatting doesn't extend beyond the message. * It's useful for outputting colored text in a terminal. If color formatting is not desired, * the function can return the message unformatted. * * @param color - The ANSI color code to apply. This is used only if `activeColor` is true. * @param msg - The message to be formatted with the specified color. * @param activeColor - A boolean flag indicating whether color formatting should be applied. Default is `__ACTIVE_COLOR`. * * @returns A string with the specified color applied to the message, * followed by a reset sequence if `activeColor` is true. * * @example * ```ts * const coloredMessage = setColor(Colors.LightOrange, 'This is a light orange message'); * console.log(coloredMessage); * ``` * * @example * ```ts * const plainMessage = setColor(Colors.LightOrange, 'This is a light orange message', false); * console.log(plainMessage); // Output will be without color formatting * ``` */ export declare function setColor(color: Colors, msg: string, activeColor?: boolean): string; export declare const xBuildLazy: { readonly service: SourceService; }; /** * Prepares the error stack trace for display. * * This function overrides the default stack trace preparation to provide a custom format, * including enhanced stack trace information and error details. * * @param error - The error object (Error or BaseError). * @param stackEntries - The array of stack entries from the call stack. * @returns The formatted stack trace as a string. */ export declare function formatStackTrace(error: ErrorType & BaseError, stackEntries: Array<NodeJS.CallSite>): string; /** * Parses command-line arguments into an `ArgvInterface` object using `yargs`. * * This function configures `yargs` to handle various build-related options for a JavaScript and TypeScript toolchain. * It returns an object that adheres to the `ArgvInterface` structure based on the parsed arguments. * * @param argv - An array of command-line arguments (e.g., `process.argv`). * @returns An object representing the parsed command-line arguments. * * @see {@link ArgvInterface} for the structure of the returned object. * * @example * // Example usage: * const args = argvParser(process.argv); * console.log(args.file); // Output: the file to build * console.log(args.dev); // Output: true or false based on the --dev flag */ export declare function argvParser(argv: Array<string>): Argv<ArgvInterface>; /** * The `BuildStateInterface` extends the `BuildState` interface to include additional properties related to the build * process, specifically for handling `ifdef` conditions and function removals in macros. * * @interface BuildStateInterface */ export interface BuildStateInterface extends BuildState { ifdef: Array<string>; macros: { removeFunctions: Set<string>; }; } /** * Spawns a new Node.js process to execute the provided JavaScript file, with optional debugging support. * * This function creates a new Node.js process to run the specified JavaScript file with source map support enabled. * It optionally starts the process in debug mode, which allows WebStorm or other debuggers to attach to the process. * The output and error streams of the spawned process are captured and logged to the console. * * @param filePath - The path to the JavaScript file to execute. * @param debug - A boolean flag to enable debugging. If `true`, the process will be started with the `--inspect-brk` option, * which opens a debugger on `0.0.0.0:9229`, allowing external debuggers to attach. * * @returns A `ChildProcessWithoutNullStreams` object representing the spawned process. * This object allows interaction with the process, including capturing its output and error streams. * * @remarks * - The `--enable-source-maps` flag is used to enable source map support, which allows better debugging by mapping * errors and stack traces to the original source code. * - If `debug` is `true`, the `--inspect-brk=0.0.0.0:9229` flag is added, starting the process in debug mode and pausing * execution until a debugger is attached. * - The output (`stdout`) and error (`stderr`) streams of the spawned process are logged to the console. * - The function returns a `ChildProcessWithoutNullStreams` object that can be used to interact with the spawned process, * such as handling its termination or sending input. * * @throws Error Throws an error if the Node.js process fails to start or if there are issues with the provided file path. * * @example * ```ts * import { spawn } from '@services/process.service'; * * // Run without debugging * const process = spawn('./path/to/script.js', false); * * process.on('close', (code) => { * console.log(`Process exited with code ${code}`); * }); * * // Run with debugging enabled * const debugProcess = spawn('./path/to/script.js', true); * * debugProcess.on('close', (code) => { * console.log(`Debug process exited with code ${code}`); * }); * ``` * * In these examples, the `spawn` function is used to execute a JavaScript file, once in normal mode and once with debugging enabled. * The process's exit code is logged when the process completes. * * @public * @category Services */ export declare function spawn(filePath: string, debug?: boolean): ChildProcessWithoutNullStreams; /** * Represents the result of transpiling a TypeScript file. * * This interface defines the structure of the output returned from a TypeScript transpilation process, * including the transpiled JavaScript code and the associated source map. * * @property code - The transpiled JavaScript code generated from the TypeScript file. * @property sourceMap - The source map associated with the transpiled JavaScript code. * * @remarks * - The `code` property contains the JavaScript code after TypeScript transpilation. * - The `sourceMap` property provides the source map that maps the transpiled JavaScript code back to the original TypeScript source. * - The source map is useful for debugging as it allows developers to trace errors in the generated JavaScript back to the original TypeScript code. * * @example * ```typescript * import { transpileFileInterface } from './transpileFileInterface'; * * const result: transpileFileInterface = { * code: 'console.log("Hello, world!");', * sourceMap: 'version: 3\nfile: out.js\nsources: ["file.ts"]\n' * }; * * console.log(result.code); // Output: console.log("Hello, world!"); * console.log(result.sourceMap); // Output: version: 3\nfile: out.js\nsources: ["file.ts"]\n * ``` * * In this example, the `transpileFileInterface` is used to represent the result of transpiling a TypeScript file. * The `code` contains the JavaScript code, while the `sourceMap` provides the mapping information for debugging purposes. * * @public * @category Interfaces */ export interface transpileFileInterface { code: string; sourceMap: string; } /** * Represents an error specific to the xBuild process. * * The `xBuildError` class extends the `BaseError` class to provide a custom error type for the xBuild system. * It includes additional functionality to maintain stack trace information and assigns a specific name to * the error, making it easier to identify and handle in different parts of the application. * * @augments BaseError */ export declare class xBuildError extends BaseError { /** * Original error stack */ originalErrorStack: string | undefined; /** * Creates an instance of `xBuildError`. * * @param message - The error message that describes the error. This message is passed to the base class * `BaseError` constructor and is used to provide context about the nature of the error. * @param options - Optional configuration for the error. This can include additional properties or settings * that customize the error's behavior. */ constructor(message: string, options?: ErrorOptions); } /** * Default build options for esbuild bundler in RemoteX framework. * * These options are used to configure how esbuild processes and bundles the TypeScript * files for the RemoteX testing framework. * * @public * @category Configuration */ export declare const defaultBuildOptions: BuildOptions; /** * Extracts the source map from the provided data string and returns the modified code and source map separately. * * This function searches for the inline source map in the data string using a regular expression, removes the * source map comment from the data string, and returns an object containing the code without the source map * comment and the extracted source map. * * @param dataString - The string containing the transpiled code with an inline source map. * @returns An object containing the modified code without the source map comment and the extracted source map. * @throws Error -Throws an error if the source map URL is not found in the data string. * * @public */ export declare function extractSourceMap(dataString: string): transpileFileInterface; /** * Transpiles a TypeScript file and extracts the source map. * * This function uses esbuild to transpile the specified TypeScript file based on provided build options, * and then extracts the source map from the transpiled code. * * @param filePath - The path to the TypeScript file to be transpiled. * @param buildOptions - Optional build options to override the default build options. * @returns A promise that resolves to an object containing the transpiled code and the extracted source map. * @throws Error - Throws an error if the build process fails or the source map extraction fails. * * @public * @category Services */ export declare function transpileFile(filePath: string, buildOptions?: BuildOptions): Promise<transpileFileInterface>; /** * The `analyzeDependencies` function analyzes the dependencies of a given entry point for a specified platform. * It performs a bundling operation and generates a metafile that contains detailed information about the * dependencies involved in the build process. * This is typically used to inspect the external packages and modules * that the entry point depends on. * * - **Input**: * - `entryPoint`: A string or array of strings representing the entry points for the build. * This defines the starting point(s) for the bundling process. * - `platform`: An optional parameter that specifies the platform to target for the build. * Default is `'browser'`. * * - **Output**: A `Promise` that resolves to an object containing: * - The `BuildResult` from the bundling process. * - A `metafile`, which contains detailed metadata about the build, including the dependencies analyzed. * * ## Example: * * ```ts * const result = await analyzeDependencies(['src/index.ts']); * console.log(result.metafile); // { inputs: { 'src/index.ts': { ... } }, outputs: { ... } } * * const nodeResult = await analyzeDependencies(['src/server.ts'], 'node'); * console.log(nodeResult.metafile); // { inputs: { 'src/server.ts': { ... } }, outputs: { ... } } * ``` * * @param entryPoint - The entry point(s) to be analyzed. * @param platform - The target platform for the build. * @returns A `Promise` that resolves to a `BuildResult` object along with a `metafile` containing dependency details. * @throws Error If the build process fails for any reason. */ export declare function analyzeDependencies(entryPoint: EntryPoints, platform?: BuildOptions['platform']): Promise<BuildResult & { metafile: Metafile; }>; /** * The `collectFunctionNames` function analyzes the provided TypeScript code and collects the names of functions * that should be removed based on specific conditions. The function searches for function declarations and variable * declarations where the function name or variable is prefixed with `$$`, and adds these function names to the * `removeFunctions` set in the provided `state` object. * * - **Input**: * - `code`: A string containing the TypeScript code to be analyzed. * - `state`: An object representing the current build state, specifically the `mocks` state, which includes * a `removeFunctions` set that will hold the names of functions that need to be removed. * * - **Output**: The function does not return any value. Instead, it modifies the `removeFunctions` set inside the * `state` object by adding function names that meet the criteria for removal. * * ## Error Handling: * - The function does not explicitly handle errors. If invalid TypeScript code is provided, `ts.createSourceFile` * may throw an error, which should be handled by the caller if necessary. * * @param code - The TypeScript code as a string that will be analyzed. * @param state - The build state containing the `removeFunctions` set to store the names of functions to be removed. * @returns `void` - The function modifies the `state` directly and does not return a value. */ export declare function collectFunctionNames(code: string, state: BuildStateInterface['macros']): void; /** * The `collectDeclaredFunctions` function processes the provided `meta` metafile and reads each file's contents * to find function declarations within preprocessor directives. It uses regular expressions to match `// ifdef` and * `// endif` blocks in the code and collects the function names from the code inside the `ifdef` block, based on the * `define` configuration in the `config` object. If the condition defined in the `ifdef` is not met (i.e., not defined * in the `config.define`), the function names found inside the block will be collected and added to the `removeFunctions` * set in the `state` object. * * - **Input**: * - `meta`: The `Metafile` object that contains the input files. The keys are file paths, and the values contain * metadata about those files. * - `config`: The configuration object containing a `define` field, which is an object of conditions that may be used * in the `ifdef` blocks. If a condition in an `ifdef` block is not defined in `config.define`, the functions in * that block will be collected. * - `state`: The build state, specifically the `mocks` state, which includes a `removeFunctions` set that stores * function names to be removed. * * - **Output**: This function does not return a value. It modifies the `removeFunctions` set within the provided `state` * object by adding the names of functions found inside unprocessed `ifdef` blocks. * * ## Error Handling: * - If a file cannot be read due to a filesystem error, the function will throw an error. * - If the provided `meta` or `config` is malformed, it may result in runtime errors. The caller should ensure valid input. * * @param meta - The `Metafile` object containing the list of input files and their metadata. * @param config - The configuration object that defines conditions used in `ifdef` blocks. * @param state - The build state containing the `removeFunctions` set to store function names to be removed. * @returns `void` - The function modifies the `state` directly and does not return a value. */ export declare function collectDeclaredFunctions(meta: Metafile, config: ConfigurationInterface, state: BuildStateInterface['macros']): Promise<void>; /** * The `parseMacros` function processes TypeScript or JavaScript files to transform macros defined within the content. * It ensures that the build state is initialized if necessary, analyzes file dependencies, collects declared functions * that are marked for removal, and applies transformations to the source code based on the macros. * If the file's extension is not `.ts` or `.js`, the function returns `undefined`. Otherwise, it transforms the code * and returns the result in the specified loader format. * * - **Input**: * - `content`: The content of the file as a string or `Uint8Array` to be parsed. * - `loader`: A string representing the loader type for transforming the code (e.g., `'ts'`, `'js'`). * - `args`: The `OnLoadArgs` object containing metadata for the current loading process, including the file path. * - `state`: The build state containing the `mocks` object, which includes a `removeFunctions` set that tracks * functions to be removed. * - `config`: The configuration object that defines how macros should be handled (e.g., conditions for macro processing). * * - **Output**: A `Promise` that resolves to an `OnLoadResult`, `pluginResultType`, or `undefined`. If the file is * of type `.ts` or `.js`, the transformed code is returned in the specified loader format (e.g., `'ts'`). If the file * extension is not recognized, the function returns `undefined`. * * ## Error Handling: * - If the file path does not end with `.ts` or `.js`, the function returns `undefined`. * - If `state.mocks` is not initialized, it will be set up by analyzing the file dependencies and collecting declared functions. * - If any errors occur during the analysis, function collection, or transformation, the function may throw an error. * * @param content - The content of the file as a string or `Uint8Array` to be parsed. * @param loader - The loader type for transforming the code (e.g., `'ts'` or `'js'`). * @param args - The `OnLoadArgs` containing metadata, including the file path. * @param state - The build state that includes `mocks` with the `removeFunctions` set. * @param config - The configuration object defining how macros should be handled. * @returns A `Promise` that resolves to the transformed code (`OnLoadResult` or `pluginResultType`), or `undefined` * if the file is not of type `.ts` or `.js`. */ export declare function parseMacros(content: string | Uint8Array, loader: Loader | undefined, args: OnLoadArgs, state: BuildStateInterface, config: ConfigurationInterface): Promise<OnLoadResult | pluginResultType | undefined>; /** * Represents an error that occurs during the esbuild process. * * This class extends the base error class to provide specific error handling for esbuild-related issues. * It captures the error message and maintains the proper stack trace, allowing for easier debugging * and identification of errors that occur during the build process. * * @class esBuildError * @extends BaseError */ export declare class esBuildError extends BaseError { originalErrorStack?: string; /** * Creates an instance of the EsbuildError class. * * @param message - An object containing the error message. The `text` property is used to initialize * the base error class with a descriptive message about the error encountered during the esbuild process. */ constructor(message: Message); /** * Generates a formatted error message with highlighted code. * * @param message - An esbuild Message object containing error information. * @returns A formatted string of the error message. */ private generateFormattedError; /** * Reads code from a file if it exists. * * @param path - The file path to read from. * @returns Array of lines if file exists, otherwise null. */ private readCode; /** * Formats a code snippet with highlighted errors. * * @param code - Array of code lines. * @param location - The error location within the file. * @returns A formatted and highlighted code snippet string. */ private formatCodeSnippet; /** * Applies color to a given text if colors are enabled. * * @param color - The color code. * @param text - The text to colorize. * @returns The colorized text if colors are active, otherwise plain text. */ private applyColor; } /** * ASCII Logo and Version Information * * @remarks * The `asciiLogo` constant stores an ASCII representation of the project logo * that will be displayed in the banner. This banner is rendered in a formatted * string in the `bannerComponent` function. * * The `cleanScreen` constant contains an ANSI escape code to clear the terminal screen. */ export declare const asciiLogo = "\n ______ _ _ _\n | ___ \\ (_) | | |\n__ _| |_/ /_ _ _| | __| |\n\\ \\/ / ___ \\ | | | | |/ _` |\n > <| |_/ / |_| | | | (_| |\n/_/\\_\\____/ \\__,_|_|_|\\__,_|\n"; export declare const cleanScreen = "\u001Bc"; /** * Renders the banner with the ASCII logo and version information. * * This function constructs and returns a formatted banner string that includes an ASCII logo and the version number. * The colors used for the ASCII logo and version number can be enabled or disabled based on the `activeColor` parameter. * If color formatting is enabled, the ASCII logo will be rendered in burnt orange, and the version number will be in bright pink. * * @param activeColor - A boolean flag indicating whether ANSI color formatting should be applied. Default is `__ACTIVE_COLOR`. * * @returns A formatted string containing the ASCII logo, version number, and ANSI color codes if `activeColor` is `true`. * * @remarks * The `bannerComponent` function clears the terminal screen, applies color formatting if enabled, and displays * the ASCII logo and version number. The version number is retrieved from the global `__VERSION` variable, and * the colors are reset after the text is rendered. * * @example * ```ts * console.log(bannerComponent()); * ``` * * This will output the banner to the console with the ASCII logo, version, and colors. * * @example * ```ts * console.log(bannerComponent(false)); * ``` * * This will output the banner to the console with the ASCII logo and version number without color formatting. * * @public */ export declare function bannerComponent(activeColor?: boolean): string; /** * A formatted string prefix used for logging build-related messages. * // todo optimize this */ export declare function prefix(): string; /** * A custom error class to handle errors occurring within a virtual machine (VM) execution context. * * The `VMRuntimeError` class extends the native `Error` class and enhances the error with * source map information to map stack traces back to the original source. This is particularly * useful when debugging errors from code executed in a `vm` or `evalmachine` environment. * * @param message - The error message describing the error. * @param originalError - The original error object thrown from the VM execution. * @param sourceMap - The `SourceService` providing source map data to link the error to its original source. * * @example * ```ts * try { * vm.run(someCode); * } catch (error) { * throw new VMRuntimeError("VM execution failed", error, sourceMapService); * } * ``` */ export declare class VMRuntimeError extends BaseError { /** * The original error thrown during the VM execution. */ originalError: Error; /** * Original error stack */ originalErrorStack: string | undefined; /** * Creates a new VMRuntimeError instance. * * This constructor initializes a new `VMRuntimeError` object, extending the native `Error` class with * additional information, including the original error and optional source map data. It also ensures that * the stack trace is correctly captured and reformatted using the source map (if provided) to enhance * debugging. * * @param originalError - The original error object that was thrown during the VM execution. * @param sourceMap - (Optional) The source map service used to map the error stack trace to its original * source code locations. If not provided, this will be `null`. * * @example * ```ts * try { * vm.run(code); * } catch (error) { * throw new VMRuntimeError(error, sourceMapService); * } * ``` */ constructor(originalError: ErrorType, sourceMap?: SourceService); } /** * Manages the HTTP or HTTPS server based on the provided configuration. * * The `ServerProvider` class initializes and starts either an HTTP or HTTPS server based on whether SSL certificates * are provided. It handles incoming requests, serves static files, and lists directory contents with appropriate * icons and colors. * * @class */ export declare class ServerProvider { /** * Root dir to serve */ private readonly rootDir; /** * Indicates whether the server is configured to use HTTPS. */ private readonly isHttps; /** * The server configuration object, including SSL certificate paths and other settings. */ private readonly config; /** * Creates an instance of ServerProvider. * * @param config - The server configuration object, including port number, SSL certificate paths, and an optional request handler. * @param dir - The root directory from which to serve files. * * @example * ```ts * import { ServerProvider } from './server-provider'; * * const serverConfig = { * port: 8080, * keyfile: './path/to/keyfile', * certfile: './path/to/certfile', * onRequest: (req, res, next) => { /* custom request handling *\/ } * }; * const provider = new ServerProvider(serverConfig, './public'); * provider.start(); * ``` * * This example shows how to create an instance of `ServerProvider` and start the server. */ constructor(config: Serve, dir: string); /** * Starts the server based on the configuration. * If SSL certificates are provided and valid, an HTTPS server is started. Otherwise, an HTTP server is started. * * @example * ```ts * provider.start(); * ``` * * This example demonstrates how to start the server. It will either start an HT