replace-in-file
Version:
A simple utility to quickly replace text in one or more files.
69 lines (68 loc) • 2.54 kB
TypeScript
import { Transform } from 'node:stream';
import type { TransformCallback } from 'node:stream';
import type { ParsedConfig, From, FromValue, To, ReplaceResult } from '../types.ts';
/**
* Parsed arguments of a String.replace() callback, which receives
* (match, ...captures, offset, string) plus a trailing named groups
* object if the regex contains named capture groups
*/
interface ReplaceArgs {
match: string;
captures: (string | undefined)[];
offset: number;
haystack: string;
groups?: Record<string, string | undefined>;
}
/**
* Helper to expand $-patterns in a string replacement, mirroring the native
* GetSubstitution semantics of String.replace() ($$, $&, $`, $', $n, $<name>)
*/
export declare function expandReplacement(template: string, { match, captures, offset, haystack, groups }: ReplaceArgs): string;
/**
* Transform stream that applies a single from/to replacement to a stream of
* text, finding matches across chunk boundaries. Matches up to the given
* window size are guaranteed to be found exactly; regex matches longer than
* the window are not. Memory usage stays bounded at roughly the incoming
* chunk size plus twice the window size, regardless of file size.
*/
export declare class ReplaceTransform extends Transform {
numMatches: number;
numReplacements: number;
hasReplaced: boolean;
private buffer;
private context;
private emitted;
private done;
private readonly replacement;
private readonly file;
private readonly pattern;
private readonly firstOnly;
private readonly window;
/**
* Constructor
*/
constructor(search: FromValue, replacement: To, file: string, maxMatchLength: number);
/**
* Accumulate incoming text and process what can be decided
*/
_transform(chunk: string, _encoding: BufferEncoding, callback: TransformCallback): void;
/**
* Process the remainder once the input ends
*/
_flush(callback: TransformCallback): void;
/**
* Process the buffered text, replacing matches that can no longer change
* with more input and emitting the decided portion
*/
private processBuffer;
/**
* Expand the replacement for a single match
*/
private expand;
}
/**
* Helper to replace in a single file using streams (async), keeping memory
* usage bounded regardless of file size
*/
export declare function replaceStreamAsync(source: string, from: From | From[], to: To | To[], config: ParsedConfig): Promise<ReplaceResult>;
export {};