-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathbuilders.ts
54 lines (45 loc) · 1.55 KB
/
builders.ts
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
import type { RegexFlags, RegexSequence } from './types';
import { encode } from './encoder';
/**
* Generate RegExp object from elements with optional flags.
*
* @param elements Single regex element or array of elements
* @param flags RegExp flags object
* @returns RegExp object
*/
export function buildRegExp(sequence: RegexSequence, flags?: RegexFlags): RegExp {
const pattern = encode(sequence).pattern;
ensureUnicodeFlagIfNeeded(pattern, flags);
const flagsString = encodeFlags(flags ?? {});
return new RegExp(pattern, flagsString);
}
/**
* Generate regex pattern from elements.
* @param elements Single regex element or array of elements
* @returns regex pattern string
*/
export function buildPattern(sequence: RegexSequence): string {
return encode(sequence).pattern;
}
function encodeFlags(flags: RegexFlags): string {
let result = '';
if (flags.global) result += 'g';
if (flags.ignoreCase) result += 'i';
if (flags.multiline) result += 'm';
if (flags.hasIndices) result += 'd';
if (flags.dotAll) result += 's';
if (flags.sticky) result += 'y';
if (flags.unicode) result += 'u';
return result;
}
// Matches unicode mode patterns: \u{...}, \p{...}, \P{...}, but avoids valid \\u{...}, etc
const unicodeModePatterns = /(?<!\\)(?:\\u|\\[pP])\{.+?\}/;
function ensureUnicodeFlagIfNeeded(pattern: string, flags: RegexFlags | undefined) {
if (flags?.unicode) {
return;
}
const match = pattern.match(unicodeModePatterns);
if (match) {
throw new Error(`Pattern "${match?.[0]}" requires "unicode" flag to be set.`);
}
}