-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathcontent-tag.ts
More file actions
61 lines (49 loc) · 1.23 KB
/
content-tag.ts
File metadata and controls
61 lines (49 loc) · 1.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/* eslint-disable @typescript-eslint/consistent-type-definitions, eslint-comments/disable-enable-pair, jsdoc/require-jsdoc, unicorn/prefer-export-from */
import {
type Parsed as ContentTag,
Preprocessor,
type PreprocessorOptions,
} from 'content-tag';
type Range = {
end: number;
start: number;
};
const BufferMap = new Map<string, Buffer>();
export function getBuffer(string_: string): Buffer {
let buffer = BufferMap.get(string_);
if (!buffer) {
buffer = Buffer.from(string_);
BufferMap.set(string_, buffer);
}
return buffer;
}
export function parse(
file: string,
options?: PreprocessorOptions,
): ContentTag[] {
const preprocessor = new Preprocessor();
return preprocessor.parse(file, options);
}
export function replaceContents(
file: string,
options: {
contents: string;
range: Range;
},
): string {
const { contents, range } = options;
return [
sliceByteRange(file, 0, range.start),
contents,
sliceByteRange(file, range.end),
].join('');
}
export function sliceByteRange(
string_: string,
indexStart: number,
indexEnd?: number,
): string {
const buffer = getBuffer(string_);
return buffer.slice(indexStart, indexEnd).toString();
}
export type { ContentTag, Range };