@pact-toolbox/utils
Version:
269 lines (268 loc) • 9.32 kB
text/typescript
import * as Docker$1 from "dockerode";
import Docker from "dockerode";
import { ConsolaInstance, LogLevels } from "consola";
import { isCancel, select, spinner, spinner as spinner$1, text } from "@clack/prompts";
import { colors } from "consola/utils";
import { ExecOptions, exec } from "node:child_process";
import { detectPort } from "detect-port";
import { getRandomPort } from "get-port-please";
import { ChildProcessWithoutNullStreams } from "child_process";
//#region src/chainwebApi.d.ts
/**
* Custom error class for Chainweb-related errors.
*/
declare class ChainWebError extends Error {
cause?: Error | undefined;
constructor(message: string, cause?: Error | undefined);
}
/**
* Checks if the Chainweb node is healthy.
* @param serviceUrl - The base URL of the Chainweb service.
* @param timeout - Optional timeout in milliseconds.
* @returns Promise<boolean> - True if the node is healthy, false otherwise.
*/
declare function isChainWebNodeOk(serviceUrl: string, timeout?: number): Promise<boolean>;
/**
* Checks if the Chainweb node has reached the target block height.
* @param targetHeight - The target block height.
* @param serviceUrl - The base URL of the Chainweb service.
* @param timeout - Optional timeout in milliseconds.
* @returns Promise<boolean> - True if the node is at or above the target height, false otherwise.
*/
declare function isChainWebAtHeight(targetHeight: number, serviceUrl: string, timeout?: number): Promise<boolean>;
interface MakeBlocksParams {
count?: number;
chainIds?: string[];
onDemandUrl: string;
}
/**
* Requests the Chainweb node to create blocks on specified chains.
* @param params - Parameters including count, chainIds, and onDemandUrl.
* @returns Promise<any> - The response data from the server.
*/
declare function makeBlocks({
count,
chainIds,
onDemandUrl
}: MakeBlocksParams): Promise<any>;
/**
* Checks if blocks were successfully created.
* @param params - Parameters including count, chainIds, and onDemandUrl.
* @returns Promise<boolean> - True if blocks were made successfully, false otherwise.
*/
declare function didMakeBlocks(params: MakeBlocksParams): Promise<boolean>;
//#endregion
//#region src/cleanup.d.ts
type CleanupFunction = () => void | Promise<void>;
declare function cleanupOnExit(cleanupFn: CleanupFunction): void;
//#endregion
//#region src/date.d.ts
declare function formatDate(date: Date | string): string;
//#endregion
//#region src/logger.d.ts
declare const logger: ConsolaInstance;
type Logger = ConsolaInstance;
//#endregion
//#region src/docker/types.d.ts
interface DockerServiceConfig {
containerName: string;
image?: string;
platform?: string;
restart?: string;
stopSignal?: string;
stopGracePeriod?: number;
ulimits?: {
Name: string;
Soft: number;
Hard: number;
}[];
dependsOn?: {
[key: string]: {
condition: string;
};
};
entrypoint?: string | string[];
command?: string[];
ports?: {
target: number;
published: string | number;
protocol?: string;
}[];
volumes?: string[];
environment?: string[] | {
[key: string]: string;
};
labels?: {
[key: string]: string;
};
build?: {
context: string;
dockerfile: string;
};
profiles?: string[];
expose?: string[];
healthCheck?: Docker$1.HealthConfig;
deploy?: {
replicas?: number;
restartPolicy?: {
condition?: "on-failure" | "none" | "always" | "unless-stopped";
delay?: string;
maxAttempts?: number;
window?: string;
};
};
}
//#endregion
//#region src/prompts.d.ts
type Spinner = ReturnType<typeof spinner$1>;
//#endregion
//#region src/docker/DockerService.d.ts
interface DockerServiceOptions {
serviceName?: string;
networkName: string;
docker: Docker;
logger: Logger;
spinner: Spinner;
}
declare class DockerService {
#private;
readonly serviceName: string;
readonly config: DockerServiceConfig;
readonly containerName: string;
healthCheckFailed: boolean;
// #spinner: Spinner;
constructor(config: DockerServiceConfig, options: DockerServiceOptions);
prepareImage(): Promise<void>;
start(): Promise<void>;
stop(): Promise<void>;
remove(): Promise<void>;
isHealthy(): Promise<boolean>;
waitForHealthy(timeoutMs?: number, intervalMs?: number): Promise<void>;
streamLogs(): Promise<void>;
stopLogStream(): void;
}
//#endregion
//#region src/docker/ContainerOrchestrator.d.ts
interface ContainerOrchestratorOptions {
networkName: string;
volumes: string[];
logger: Logger;
spinner: Spinner;
}
declare class ContainerOrchestrator {
#private;
constructor(options: ContainerOrchestratorOptions);
startServices(serviceConfigs: DockerServiceConfig[]): Promise<void>;
streamAllLogs(): Promise<void>;
stopAllLogStreams(): void;
stopAllServices(): Promise<void>;
}
//#endregion
//#region src/docker/utils.d.ts
declare const DOCKER_SOCKET: string;
declare function isDockerInstalled(): boolean;
declare function getServiceColor(serviceName: string): typeof colors.cyan;
//#endregion
//#region src/fs.d.ts
declare function ensureDir(dirPath: string): Promise<void>;
declare function writeFile(filePath: string, content: string): Promise<void>;
//#endregion
//#region src/helpers.d.ts
declare class TimeoutError extends Error {
constructor(message?: string);
}
declare class AbortError extends Error {
constructor(message?: string);
}
declare function delay(ms: number, signal?: AbortSignal): Promise<void>;
interface PollOptions {
/**
* Total timeout in milliseconds
* @default 30000
* */
timeout: number;
/**
* Polling interval in milliseconds
* @default 100
* */
interval?: number;
/**
* Optional AbortSignal for cancellation
*/
signal?: AbortSignal;
/**
* Whether to stop polling if fn throws an error
* @default false
*/
stopOnError?: boolean;
}
/**
* Polls a function until it returns true or the timeout is reached
*/
declare function pollFn(fn: () => Promise<boolean>, options: PollOptions): Promise<void>;
declare const execAsync: typeof exec.__promisify__;
interface ExecuteCommandResult {
stdout: string | Buffer;
stderr: string | Buffer;
}
declare function executeCommand(command: string, options?: ExecOptions): Promise<ExecuteCommandResult>;
//#endregion
//#region src/pact.d.ts
declare const PACT_VERSION_REGEX: RegExp;
declare function isAnyPactInstalled(match?: string): Promise<boolean>;
declare function getCurrentPactVersion(): Promise<string | undefined>;
declare function installPact(version?: string, nightly?: boolean): Promise<{
stdout: string | Buffer;
stderr: string | Buffer;
}>;
//#endregion
//#region src/port.d.ts
interface RandomPorts {
public: number;
service: number;
onDemand: number;
stratum: number;
p2p: number;
}
/**
* Gets a series of random network ports with gaps between each.
*
* @param host - The host for which to get the ports. Defaults to '127.0.0.1'.
* @param startGap - The minimum gap between successive ports. Defaults to 10.
* @param endGap - The maximum gap between successive ports. Defaults to 100.
* @returns An object containing the random ports assigned for public, service, on-demand, stratum, and p2p services.
* @throws {Error} If it fails to find a suitable port for any of the services.
*/
declare function getRandomNetworkPorts(host?: string, startGap?: number, endGap?: number): Promise<RandomPorts>;
declare function isPortTaken(port: number | string): Promise<boolean>;
//#endregion
//#region src/process.d.ts
interface RunBinOptions {
silent?: boolean;
cwd?: string;
env?: NodeJS.ProcessEnv;
resolveOnStart?: boolean;
resolveIf?: (data: string) => boolean;
}
declare function runBin(bin: string, args: string[], options?: RunBinOptions): Promise<ChildProcessWithoutNullStreams>;
declare function killProcess(name: string): Promise<void>;
//#endregion
//#region src/template.d.ts
/**
* Replaces placeholders in the given template string with corresponding values from the context.
*
* Placeholders are in the format `{{key}}`, where `key` corresponds to a property in the context object.
* Whitespace around the key inside the curly braces is trimmed.
*
* @param template - The template string containing placeholders.
* @param context - An object containing values to replace placeholders in the template.
* @returns The template string with placeholders replaced by corresponding context values.
* @throws {Error} If any placeholders remain after replacement due to missing context values.
*/
declare function fillTemplatePlaceholders(template: string, context: Record<string, any>): string;
//#endregion
//#region src/uuid.d.ts
declare function getUuid(): string;
//#endregion
export { AbortError, ChainWebError, ContainerOrchestrator, DOCKER_SOCKET, DockerService, DockerServiceConfig, LogLevels, Logger, MakeBlocksParams, PACT_VERSION_REGEX, PollOptions, RunBinOptions, Spinner, TimeoutError, cleanupOnExit, delay, detectPort, didMakeBlocks, ensureDir, execAsync, executeCommand, fillTemplatePlaceholders, formatDate, getCurrentPactVersion, getRandomNetworkPorts, getRandomPort, getServiceColor, getUuid, installPact, isAnyPactInstalled, isCancel, isChainWebAtHeight, isChainWebNodeOk, isDockerInstalled, isPortTaken, killProcess, logger, makeBlocks, pollFn, runBin, select, spinner, text, writeFile };
//# sourceMappingURL=index.d.cts.map