literate-regex 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Modifications Copyright 2025 jeffy-g
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,231 @@
1
+ ![LICENSE](https://img.shields.io/badge/Lisence-Apache2.0-blue.svg)
2
+ [![npm version](https://badge.fury.io/js/literate-regex.svg)](https://badge.fury.io/js/literate-regex)
3
+ ![npm bundle size](https://img.shields.io/bundlephobia/min/literate-regex?style=plastic)
4
+ ![npm](https://img.shields.io/npm/dm/literate-regex.svg?style=plastic)
5
+ ![npms.io](https://img.shields.io/npms-io/maintenance-score/literate-regex)
6
+ ![Libraries.io dependency status for GitHub repo](https://img.shields.io/librariesio/github/jeffy-g/literate-regex)
7
+
8
+ # literate-regex
9
+
10
+ A literate, typed JavaScript regex toolkit — powered by TypeScript.
11
+
12
+ > Write regex like a human. Ship it like a machine.
13
+
14
+
15
+ ## ✨ Motivation
16
+
17
+ Regular expressions are absurdly powerful — a tiny automaton you can carry in your pocket.
18
+ But once a regex grows beyond “a few tokens and a prayer”, it becomes:
19
+
20
+ - hard to read
21
+ - easy to break
22
+ - painful to maintain
23
+
24
+ This library exists to keep regexes **literate**.
25
+
26
+ Write a multi-line, commented, PCRE-style regex source (with `#` notes), then normalize it into a compact JavaScript `RegExp.source` **while preserving the normalized source as a TypeScript string literal type**.
27
+
28
+ That gives you two superpowers:
29
+
30
+ 1. **Human-friendly editing** (readable formatting + comments)
31
+ 2. **Machine-friendly safety** (typed, normalized sources that flow through your codebase)
32
+
33
+ In short: fewer regex jump-scares, more confidence.
34
+
35
+ ### Before
36
+ ```ts
37
+ const re = /^(?:\s*\/\*\*\s+|\s+\*?\s+)(?:(?=@(...))|...)/gm;
38
+ ```
39
+
40
+ ### After
41
+ ```ts
42
+ const RE_SOURCE = `
43
+ /^ # start
44
+ (?: ... ) # jsdoc start
45
+ ... # more notes
46
+ /gm` as const;
47
+
48
+ const re = compilePCREStyleRegExpLiteral(RE_SOURCE);
49
+ ```
50
+
51
+ ---
52
+
53
+ ## ✨ Features
54
+
55
+ - **PCRE-ish style regex source**:
56
+ - multi-line formatting
57
+ - `# ...` line comments
58
+ - `\#` escape for literal `#`
59
+ - **Type-level normalization**:
60
+ - derive normalized JS `RegExp.source` as a string literal type
61
+ - **Optional global augmentation**:
62
+ - opt-in only (`import "literate-regex/global"`)
63
+ - Designed to reduce TypeScript instantiation pain:
64
+ - line-oriented normalization (helps avoid `ts(2589)` compared to naive full-string scanning)
65
+
66
+ ---
67
+
68
+ ## 📦 Install
69
+
70
+ ```bash
71
+ npm i literate-regex
72
+ # or
73
+ pnpm add literate-regex
74
+ # or
75
+ yarn add literate-regex
76
+ ```
77
+
78
+ ---
79
+
80
+ ## 🚀 Quick Start
81
+
82
+ ```ts
83
+ import { PCREStyleToJsRegExpSource } from "literate-regex";
84
+
85
+ // Only those who want to expand globally
86
+ import "literate-regex/global";
87
+ ```
88
+
89
+ ---
90
+
91
+ ## 🧠 Type-level normalization
92
+
93
+ ### 1) Write a readable PCRE-style source
94
+
95
+ * `#` starts a line comment (unless escaped)
96
+ * `\#` is kept as a literal `#`
97
+ * whitespace characters are stripped during normalization
98
+
99
+ ```ts
100
+ import type { PCREStyleToJsRegExpSource } from "./literate-regex";
101
+
102
+ // sample 1
103
+ const RE_SOURCE = `
104
+ ^ # start
105
+ (?:\\#\\w+) # literal "#"
106
+ \\s+ # whitespace
107
+ ` as const;
108
+
109
+ // type JsSource = "^(?:#\\w+)\\s+"
110
+ type JsSource = PCREStyleToJsRegExpSource<typeof RE_SOURCE>;
111
+ ```
112
+
113
+ > Tip: You must use `as const` to preserve the source as a string literal type.
114
+
115
+ ---
116
+
117
+ ## 🔧 Runtime normalization (optional)
118
+
119
+ `PCREStyleToJsRegExpSource<...>` is purely type-level.
120
+ If you also normalize at runtime, mirror the same rules:
121
+
122
+ ```ts
123
+ import { normalizePCREStyleSource } from "literate-regex";
124
+ // import type { PCREStyleToJsRegExpSource } from "literate-regex";
125
+
126
+ // sample 2
127
+ const src = `
128
+ ^ # start
129
+ \\#\\w+ # literal
130
+ ` as const;
131
+
132
+ // '^#\\w+'
133
+ // const normalized: "^#\\w+"
134
+ const normalized = normalizePCREStyleSource(src);
135
+ ```
136
+
137
+ ## 🔧 Runtime creation Compile PCRE Style RegExpLiteral
138
+
139
+ ```ts
140
+ import {
141
+ TypedRegExp,
142
+ // normalizePCREStyleSource,
143
+ compilePCREStyleRegExpLiteral,
144
+ } from "literate-regex";
145
+ import type {
146
+ RegExpLiteralParts,
147
+ PCREStyleToJsRegExpSource,
148
+ RegExpExecArrayFixedPretty,
149
+ ReplacerFunctionSignature,
150
+ } from "literate-regex";
151
+
152
+ //
153
+ // sample of compilePCREStyleRegExpLiteral
154
+ //
155
+ const pcreStyledRegex = `/
156
+ (\\(\\?\#[\\s\\S]*?(?<!\\\\)\\)(?=\\s*$|.)) # multi line comment
157
+ |
158
+ (?:^(?:\\s+|))?(?<![\\\\])(\\#(?:\\s|[\\s\\S])*?$) # single line comment
159
+ |
160
+ (?<regexFragment>
161
+ (?:^\\s+)?(?:[^\\s]+)
162
+ )+ # regex flagment
163
+ |
164
+ ([\\r|\\r\\n|\\n]+|[\\x20\\t]+(?=$)?) # whitespaces
165
+ /gm`;
166
+
167
+ const jsRegex = compilePCREStyleRegExpLiteral(pcreStyledRegex);
168
+
169
+ type TPcreStyledRegex = typeof pcreStyledRegex;
170
+ type TJsRegexSource = PCREStyleToJsRegExpSource<TPcreStyledRegex>;
171
+ type TJsRegexLiteralParts = RegExpLiteralParts<TJsRegexSource>;
172
+
173
+ type TJsRegexExecArray = RegExpExecArrayFixedPretty<
174
+ TypedRegExp<TJsRegexLiteralParts["pattern"]>
175
+ >;
176
+ type TJsRegexStringReplacer = ReplacerFunctionSignature<
177
+ TypedRegExp<TJsRegexLiteralParts["pattern"]>
178
+ >;
179
+ let m = jsRegex.exec(pcreStyledRegex);
180
+ type Test0 = TJsRegexExecArray extends typeof m ? true : false;
181
+ type Test1 = typeof m extends TJsRegexExecArray ? true : false;
182
+
183
+ const replacer: TJsRegexStringReplacer = (...args) => "";
184
+ pcreStyledRegex.replace(jsRegex, replacer);
185
+ pcreStyledRegex.replace(jsRegex, "");
186
+ ```
187
+
188
+ ---
189
+
190
+ ## 🌍 Global augmentation (opt-in)
191
+
192
+ This package provides an optional global augmentation entry:
193
+
194
+ ```ts
195
+ import "literate-regex/global";
196
+ ```
197
+
198
+ This is intentionally **opt-in** to avoid unexpected type pollution across projects.
199
+
200
+ ---
201
+
202
+ ## ⚠️ Notes & limitations
203
+
204
+ * This is **not a full PCRE parser**. It focuses on:
205
+
206
+ * line comments (`# ...`)
207
+ * escaping `\#`
208
+ * whitespace stripping
209
+ * Very large type-level inputs may still hit TS limits depending on your environment.
210
+ If that happens, split your regex source into smaller pieces.
211
+
212
+ ---
213
+
214
+ ## 📚 References
215
+
216
+ This library’s whitespace set is based on the ECMAScript definition used by RegExp `\s`
217
+ (WhiteSpace ∪ LineTerminator).
218
+
219
+ - ECMA-262: White Space (Table 33)
220
+ https://tc39.es/ecma262/#sec-white-space
221
+ - ECMA-262: Line Terminators (Table 34)
222
+ https://tc39.es/ecma262/#sec-line-terminators
223
+ - MDN: RegExp character classes (`\s` equivalence)
224
+ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Character_classes
225
+
226
+ ---
227
+
228
+ ## 📜 License
229
+
230
+ Released under the `Apache-2.0` License.
231
+ See [LICENSE](./LICENSE) for details.
@@ -0,0 +1,41 @@
1
+ "use strict";
2
+ /*!
3
+ // Copyright jeffy-g 2025
4
+ //
5
+ // Licensed under the Apache License, Version 2.0 (the "License");
6
+ // you may not use this file except in compliance with the License.
7
+ // You may obtain a copy of the License at
8
+ //
9
+ // http://www.apache.org/licenses/LICENSE-2.0
10
+ //
11
+ // Unless required by applicable law or agreed to in writing, software
12
+ // distributed under the License is distributed on an "AS IS" BASIS,
13
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ // See the License for the specific language governing permissions and
15
+ // limitations under the License.
16
+ */
17
+ Object.defineProperty(exports, "__esModule", { value: true });
18
+ exports.version = exports.compilePCREStyleRegExpLiteral = exports.extractJsRegexPartsFromPCREStyleRegExpLiteral = exports.normalizePCREStyleSource = void 0;
19
+ const NORMALIZE_PCRE_STYLE_REGEX = /(?<!\\)\#\s*.*$|\s+/gm;
20
+ const normalizePCREStyleSource = (src) => {
21
+ return src.replace(NORMALIZE_PCRE_STYLE_REGEX, "").replace(/\\#/g, "#");
22
+ };
23
+ exports.normalizePCREStyleSource = normalizePCREStyleSource;
24
+ const extractJsRegexPartsFromPCREStyleRegExpLiteral = (src) => {
25
+ const normalized = (0, exports.normalizePCREStyleSource)(src);
26
+ if (normalized[0] !== "/")
27
+ throw new Error("Expected regex literal to start with '/'");
28
+ const lastSlash = normalized.lastIndexOf("/");
29
+ if (lastSlash <= 0)
30
+ throw new Error("Invalid regex literal: missing trailing '/'");
31
+ const pattern = normalized.slice(1, lastSlash);
32
+ const flags = normalized.slice(lastSlash + 1);
33
+ return { pattern, flags };
34
+ };
35
+ exports.extractJsRegexPartsFromPCREStyleRegExpLiteral = extractJsRegexPartsFromPCREStyleRegExpLiteral;
36
+ const compilePCREStyleRegExpLiteral = (src) => {
37
+ const { pattern, flags } = (0, exports.extractJsRegexPartsFromPCREStyleRegExpLiteral)(src);
38
+ return new RegExp(pattern, flags);
39
+ };
40
+ exports.compilePCREStyleRegExpLiteral = compilePCREStyleRegExpLiteral;
41
+ exports.version = "v0.5.0";
@@ -0,0 +1,35 @@
1
+ /*!
2
+ // Copyright jeffy-g 2025
3
+ //
4
+ // Licensed under the Apache License, Version 2.0 (the "License");
5
+ // you may not use this file except in compliance with the License.
6
+ // You may obtain a copy of the License at
7
+ //
8
+ // http://www.apache.org/licenses/LICENSE-2.0
9
+ //
10
+ // Unless required by applicable law or agreed to in writing, software
11
+ // distributed under the License is distributed on an "AS IS" BASIS,
12
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ // See the License for the specific language governing permissions and
14
+ // limitations under the License.
15
+ */
16
+ const NORMALIZE_PCRE_STYLE_REGEX = /(?<!\\)\#\s*.*$|\s+/gm;
17
+ export const normalizePCREStyleSource = (src) => {
18
+ return src.replace(NORMALIZE_PCRE_STYLE_REGEX, "").replace(/\\#/g, "#");
19
+ };
20
+ export const extractJsRegexPartsFromPCREStyleRegExpLiteral = (src) => {
21
+ const normalized = normalizePCREStyleSource(src);
22
+ if (normalized[0] !== "/")
23
+ throw new Error("Expected regex literal to start with '/'");
24
+ const lastSlash = normalized.lastIndexOf("/");
25
+ if (lastSlash <= 0)
26
+ throw new Error("Invalid regex literal: missing trailing '/'");
27
+ const pattern = normalized.slice(1, lastSlash);
28
+ const flags = normalized.slice(lastSlash + 1);
29
+ return { pattern, flags };
30
+ };
31
+ export const compilePCREStyleRegExpLiteral = (src) => {
32
+ const { pattern, flags } = extractJsRegexPartsFromPCREStyleRegExpLiteral(src);
33
+ return new RegExp(pattern, flags);
34
+ };
35
+ export const version = "v0.5.0";
@@ -0,0 +1,67 @@
1
+ /*!
2
+ // Copyright jeffy-g 2025
3
+ //
4
+ // Licensed under the Apache License, Version 2.0 (the "License");
5
+ // you may not use this file except in compliance with the License.
6
+ // You may obtain a copy of the License at
7
+ //
8
+ // http://www.apache.org/licenses/LICENSE-2.0
9
+ //
10
+ // Unless required by applicable law or agreed to in writing, software
11
+ // distributed under the License is distributed on an "AS IS" BASIS,
12
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ // See the License for the specific language governing permissions and
14
+ // limitations under the License.
15
+ */
16
+ /**
17
+ * @file literate-regex/global.d.ts
18
+ */
19
+ import type {
20
+ TypedRegExp,
21
+ StringReplacerFunction,
22
+ RegExpExecArrayFixedPretty,
23
+ } from "./index.d.ts";
24
+ declare global {
25
+ interface RegExp {
26
+ /**
27
+ * Executes a search on a string using a regular expression pattern, and returns an array containing the results of that search.
28
+ * @template {string} P
29
+ * @template {string} F
30
+ * @param {TypedRegExp<P, F>} this The regular expression object.
31
+ * @param {string} str The String object or string literal on which to perform the search.
32
+ * @returns {RegExpExecArrayFixedPretty< this > | null} An array of results or null if no match is found.
33
+ */
34
+ exec<const P extends string, const F extends string = "">(this: TypedRegExp<P, F>, str: string): RegExpExecArrayFixedPretty< this > | null;
35
+ }
36
+ interface String {
37
+ /**
38
+ * Replaces occurrences of a pattern in the string with a specified replacement.
39
+ * @template {RegExp | string} SV
40
+ * @param searchValue A regular expression object.
41
+ * @param replaceValue A string or a function to create the new substring.
42
+ */
43
+ replace<SV extends RegExp | string>(this: string, searchValue: SV, replaceValue: StringReplacerFunction<SV>): string;
44
+ }
45
+ interface RegExpConstructor {
46
+ /**
47
+ * Creates a typed RegExp object with literal types for the pattern and flags.
48
+ * @template {string} P
49
+ * @template {string} F
50
+ * @param {P} pattern The regular expression pattern.
51
+ * @param {F} [flags] The flags for the regular expression.
52
+ * @returns {TypedRegExp<P, F>} A typed RegExp object.
53
+ */
54
+ new <const P extends string, const F extends string = "">(pattern: P, flags?: F): TypedRegExp<P, F>;
55
+ /**
56
+ * Creates a typed RegExp object with literal types for the pattern and flags.
57
+ * @template {string} P
58
+ * @template {string} F
59
+ * @param {P} pattern The regular expression pattern.
60
+ * @param {F} [flags] The flags for the regular expression.
61
+ * @returns {TypedRegExp<P, F>} A typed RegExp object.
62
+ */
63
+ <const P extends string, const F extends string = "">(pattern: P, flags?: F): TypedRegExp<P, F>;
64
+ readonly prototype: RegExp;
65
+ }
66
+ }
67
+ export {};
@@ -0,0 +1,26 @@
1
+ /*!
2
+ // Copyright jeffy-g 2025
3
+ //
4
+ // Licensed under the Apache License, Version 2.0 (the "License");
5
+ // you may not use this file except in compliance with the License.
6
+ // You may obtain a copy of the License at
7
+ //
8
+ // http://www.apache.org/licenses/LICENSE-2.0
9
+ //
10
+ // Unless required by applicable law or agreed to in writing, software
11
+ // distributed under the License is distributed on an "AS IS" BASIS,
12
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ // See the License for the specific language governing permissions and
14
+ // limitations under the License.
15
+ */
16
+ /**
17
+ * @file literate-regex/index.d.ts
18
+ * @desc It is recommended to add `"skipLibCheck": true` to your tsconfig.
19
+ */
20
+ export * from "./types/common";
21
+ export * from "./types/regex";
22
+ export * from "./types/pcre";
23
+ export * from "./types/captures";
24
+ export * from "./types/parser";
25
+ export * from "./types/replacer";
26
+ export as namespace XRegex;
@@ -0,0 +1,192 @@
1
+ /*!
2
+ // Copyright jeffy-g 2025
3
+ //
4
+ // Licensed under the Apache License, Version 2.0 (the "License");
5
+ // you may not use this file except in compliance with the License.
6
+ // You may obtain a copy of the License at
7
+ //
8
+ // http://www.apache.org/licenses/LICENSE-2.0
9
+ //
10
+ // Unless required by applicable law or agreed to in writing, software
11
+ // distributed under the License is distributed on an "AS IS" BASIS,
12
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ // See the License for the specific language governing permissions and
14
+ // limitations under the License.
15
+ */
16
+ /**
17
+ * @file types/captures.d.ts
18
+ */
19
+ import type {
20
+ TupleOf,
21
+ IsEmptyRecord,
22
+ } from "./common.d.ts";
23
+ import type { RegExpSource } from "./regex.d.ts";
24
+ import type {
25
+ RegExpFlags,
26
+ HasStrictRegExpFlag,
27
+ } from "./regex-util.d.ts";
28
+ /*!
29
+ // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
30
+ // Named Capture Groups
31
+ // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
32
+ */
33
+ type FirstChar<S extends string> = S extends `${infer F}${infer _}` ? F : never;
34
+ /**
35
+ * Recursively extracts parts that match the format (?<GroupName>...) from a string pattern,
36
+ * without considering nesting, and unions them.
37
+ * @template S - A string pattern.
38
+ */
39
+ export type ExtractGroupNames<S extends unknown> =
40
+ S extends `${infer _Before}(?<${infer Rest}`
41
+ ? FirstChar<Rest> extends "=" | "!"
42
+ ? ExtractGroupNames<Rest>
43
+ : Rest extends `${infer GroupName}>${infer After}`
44
+ ? GroupName extends ""
45
+ ? "ExtractGroupNames: regex pattern error!"
46
+ : GroupName | ExtractGroupNames<After>
47
+ : never
48
+ : never;
49
+ /**
50
+ * Creates an object type with keys as the extracted group names and values as strings.
51
+ * If no groups are found, it results in an empty object.
52
+ * @template R - A RegExp type.
53
+ * @date 2025/12/24 14:46:30 - It may be possible to extract the group name accurately (?)
54
+ */
55
+ export type RegExpNamedGroups<R extends RegExp> =
56
+ R extends RegExp & { readonly source: infer S extends string }
57
+ ? ExtractGroupNames<S> extends infer K
58
+ ? [K] extends [never]
59
+ ? undefined
60
+ : { [P in K & string]: string | undefined }
61
+ : undefined
62
+ : undefined;
63
+ /*!
64
+ // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
65
+ // Capture Groups
66
+ // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
67
+ */
68
+ /**
69
+ * Preprocesses escape sequences in a string pattern by replacing escaped backslashes and characters.
70
+ *
71
+ * + NOTE: This type is used to preprocess the pattern string before counting capture groups.
72
+ *
73
+ * @template S - A string pattern.
74
+ * @template Result - The resulting string after preprocessing.
75
+ * @internal
76
+ */
77
+ export type __PreprocessEscapes<S extends string, Result extends string = ""> =
78
+ S extends `\\\\${infer Rest}`
79
+ ? __PreprocessEscapes<Rest, `${Result}__`>
80
+ : S extends `\\${infer EscapedChar}${infer Rest}`
81
+ ? __PreprocessEscapes<Rest, `${Result}_!`>
82
+ : S extends `${infer Char}${infer Rest}`
83
+ ? __PreprocessEscapes<Rest, `${Result}${Char}`>
84
+ : Result;
85
+ /**
86
+ * Counts the exact number of capture groups in a string pattern.
87
+ * @template S - A string pattern.
88
+ * @template Counter - An array used to count the capture groups.
89
+ */
90
+ export type CountCaptureGroups<
91
+ S extends string,
92
+ Counter extends unknown[] = []
93
+ > =
94
+ __PreprocessEscapes<S> extends `${infer _Before}(${infer Rest}`
95
+ ? Rest extends `${"?:" | "?=" | "?!" | "?<=" | "?<!"}${infer After}`
96
+ ? CountCaptureGroups<After, Counter>
97
+ : CountCaptureGroups<Rest, [...Counter, unknown]>
98
+ : Counter["length"];
99
+ /**
100
+ * Builds a tuple type whose length equals the number of capture groups.
101
+ * @template Count - Number of capture groups.
102
+ * @template Result - Accumulator (internal).
103
+ */
104
+ export type BuildCaptureTuple<
105
+ Count extends number, ArrayType = string,
106
+ > = TupleOf<Count, ArrayType>;
107
+ export type CaptureOptTuple<N extends number, T = string | undefined> =
108
+ N extends 0 ? [] :
109
+ N extends 1 ? [$1: T] :
110
+ N extends 2 ? [$1: T, $2: T] :
111
+ N extends 3 ? [$1: T, $2: T, $3: T] :
112
+ N extends 4 ? [$1: T, $2: T, $3: T, $4: T] :
113
+ N extends 5 ? [$1: T, $2: T, $3: T, $4: T, $5: T] :
114
+ N extends 6 ? [$1: T, $2: T, $3: T, $4: T, $5: T, $6: T] :
115
+ N extends 7 ? [$1: T, $2: T, $3: T, $4: T, $5: T, $6: T, $7: T] :
116
+ N extends 8 ? [$1: T, $2: T, $3: T, $4: T, $5: T, $6: T, $7: T, $8: T] :
117
+ N extends 9 ? [$1: T, $2: T, $3: T, $4: T, $5: T, $6: T, $7: T, $8: T, $9: T] :
118
+ N extends 10 ? [$1: T, $2: T, $3: T, $4: T, $5: T, $6: T, $7: T, $8: T, $9: T, $10: T] :
119
+ N extends 11 ? [$1: T, $2: T, $3: T, $4: T, $5: T, $6: T, $7: T, $8: T, $9: T, $10: T, $11: T] :
120
+ N extends 12 ? [$1: T, $2: T, $3: T, $4: T, $5: T, $6: T, $7: T, $8: T, $9: T, $10: T, $11: T, $12: T] :
121
+ N extends 13 ? [$1: T, $2: T, $3: T, $4: T, $5: T, $6: T, $7: T, $8: T, $9: T, $10: T, $11: T, $12: T, $13: T] :
122
+ N extends 14 ? [$1: T, $2: T, $3: T, $4: T, $5: T, $6: T, $7: T, $8: T, $9: T, $10: T, $11: T, $12: T, $13: T, $14: T] :
123
+ N extends 15 ? [$1: T, $2: T, $3: T, $4: T, $5: T, $6: T, $7: T, $8: T, $9: T, $10: T, $11: T, $12: T, $13: T, $14: T, $15: T] :
124
+ N extends 16 ? [$1: T, $2: T, $3: T, $4: T, $5: T, $6: T, $7: T, $8: T, $9: T, $10: T, $11: T, $12: T, $13: T, $14: T, $15: T, $16: T] :
125
+ BuildCaptureTuple<N, T>;
126
+ /*!
127
+ // - - - - - - - - - - - - - - - - -
128
+ // Indices (v0.4.0)
129
+ // - - - - - - - - - - - - - - - - -
130
+ */
131
+ /**
132
+ * @internal
133
+ */
134
+ type TIndicesItem = [index: number, lastIndex: number];
135
+ /**
136
+ * @internal
137
+ */
138
+ type RegExpIndicesGroups<NamedGroups> = IsEmptyRecord<NamedGroups> extends true
139
+ ? undefined
140
+ : { [P in keyof NamedGroups & string]: TIndicesItem | undefined };
141
+ /**
142
+ * @internal
143
+ */
144
+ type RegExpIndicesTuple<GroupCount extends number> = [
145
+ match: TIndicesItem,
146
+ ...BuildCaptureTuple<GroupCount, TIndicesItem | undefined>
147
+ ];
148
+ /**
149
+ *
150
+ */
151
+ export type RegExpIndicesArray<GroupCount extends number, NamedGroups> = RegExpIndicesTuple<GroupCount> & {
152
+ groups: RegExpIndicesGroups<NamedGroups>;
153
+ };
154
+ /**
155
+ * @internal
156
+ */
157
+ type RegExpExecArrayFixedBase<
158
+ R extends RegExp,
159
+ GroupCount extends number,
160
+ NamedGroups,
161
+ Tuple extends unknown[] = BuildCaptureTuple<GroupCount, string | undefined>
162
+ > = HasStrictRegExpFlag<RegExpFlags<R>, "d"> extends true
163
+ ? [match: string, ...Tuple] & {
164
+ groups: IsEmptyRecord<NamedGroups> extends true ? undefined : NamedGroups;
165
+ index: number;
166
+ input: string;
167
+ indices: RegExpIndicesArray<GroupCount, NamedGroups>
168
+ } : [match: string, ...Tuple] & {
169
+ groups: IsEmptyRecord<NamedGroups> extends true ? undefined : NamedGroups;
170
+ index: number;
171
+ input: string;
172
+ }
173
+ /**
174
+ * Represents a fixed version of RegExpExecArray that includes the matched string,
175
+ * captures, and optionally named groups.
176
+ * @template R - A RegExp type.
177
+ * @template S - The source string of the RegExp.
178
+ * @template GroupCount - The number of capture groups.
179
+ */
180
+ export type RegExpExecArrayFixed<
181
+ R extends RegExp,
182
+ S extends RegExpSource<R> = RegExpSource<R>,
183
+ GroupCount extends number = CountCaptureGroups<S>,
184
+ NamedGroups = RegExpNamedGroups<R>
185
+ > = RegExpExecArrayFixedBase<R, GroupCount, NamedGroups>;
186
+ export type RegExpExecArrayFixedPretty<
187
+ R extends RegExp,
188
+ S extends RegExpSource<R> = RegExpSource<R>,
189
+ GroupCount extends number = CountCaptureGroups<S>,
190
+ NamedGroups = RegExpNamedGroups<R>
191
+ > = RegExpExecArrayFixedBase<R, GroupCount, NamedGroups, CaptureOptTuple<GroupCount>>;
192
+ export {};
@@ -0,0 +1,56 @@
1
+ /*!
2
+ // Copyright jeffy-g 2025
3
+ //
4
+ // Licensed under the Apache License, Version 2.0 (the "License");
5
+ // you may not use this file except in compliance with the License.
6
+ // You may obtain a copy of the License at
7
+ //
8
+ // http://www.apache.org/licenses/LICENSE-2.0
9
+ //
10
+ // Unless required by applicable law or agreed to in writing, software
11
+ // distributed under the License is distributed on an "AS IS" BASIS,
12
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ // See the License for the specific language governing permissions and
14
+ // limitations under the License.
15
+ */
16
+ /**
17
+ * @file types/common.d.ts
18
+ */
19
+ export type TupleOf<
20
+ Count extends number, ArrayType,
21
+ Result extends ArrayType[] = []
22
+ > = Result["length"] extends Count
23
+ ? Result
24
+ : TupleOf<Count, ArrayType, [...Result, ArrayType]>;
25
+ export type IsEmptyRecord<T> =
26
+ [T] extends [undefined] ? true :
27
+ [keyof T] extends [never] ? true : false;
28
+ /**
29
+ * StringToUnion<"abc"> -> "a" | "b" | "c"
30
+ * StringToUnion<string> -> string
31
+ *
32
+ * Note: splits by UTF-16 code units (like JS `.split("")`).
33
+ */
34
+ export type StringToUnion<S extends string> =
35
+ [string] extends [S]
36
+ ? string
37
+ : S extends `${infer H}${infer T}`
38
+ ? H | StringToUnion<T>
39
+ : never;
40
+ /**
41
+ * StringLength<S> -> length as a number literal, or `number` if S is not a literal.
42
+ *
43
+ * - StringLength<""> -> 0
44
+ * - StringLength<"abc"> -> 3
45
+ * - StringLength<string> -> number
46
+ * - StringLength<`a${string}`> -> number
47
+ *
48
+ * Note: counts UTF-16 code units (like JS `.length`).
49
+ */
50
+ export type StringLength<S extends string, Acc extends unknown[] = []> =
51
+ [string] extends [S]
52
+ ? number
53
+ : S extends `${infer _H}${infer T}`
54
+ ? StringLength<T, [unknown, ...Acc]>
55
+ : Acc["length"];
56
+ export {};
@@ -0,0 +1,54 @@
1
+ /*!
2
+ // Copyright jeffy-g 2025
3
+ //
4
+ // Licensed under the Apache License, Version 2.0 (the "License");
5
+ // you may not use this file except in compliance with the License.
6
+ // You may obtain a copy of the License at
7
+ //
8
+ // http://www.apache.org/licenses/LICENSE-2.0
9
+ //
10
+ // Unless required by applicable law or agreed to in writing, software
11
+ // distributed under the License is distributed on an "AS IS" BASIS,
12
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ // See the License for the specific language governing permissions and
14
+ // limitations under the License.
15
+ */
16
+ /**
17
+ * @file types/parser.d.ts
18
+ */
19
+ import type { StringToUnion } from "./common.d.ts";
20
+ import type { TypedRegExp } from "./regex.d.ts";
21
+ import type { PCREStyleToJsRegExpSource } from "./pcre.d.ts";
22
+ /*!
23
+ // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
24
+ // Parse PCRE Style Regex Literal
25
+ // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
26
+ */
27
+ export type TRegexpFlag = "dgimsuvy";
28
+ export type TValidRegExpFlag = StringToUnion<TRegexpFlag> | "";
29
+ type StripFlagsFromEnd<S extends string, Acc extends string = ""> =
30
+ S extends `${infer Rest}y` ? StripFlagsFromEnd<Rest, `y${Acc}`> :
31
+ S extends `${infer Rest}v` ? StripFlagsFromEnd<Rest, `v${Acc}`> :
32
+ S extends `${infer Rest}u` ? StripFlagsFromEnd<Rest, `u${Acc}`> :
33
+ S extends `${infer Rest}s` ? StripFlagsFromEnd<Rest, `s${Acc}`> :
34
+ S extends `${infer Rest}m` ? StripFlagsFromEnd<Rest, `m${Acc}`> :
35
+ S extends `${infer Rest}i` ? StripFlagsFromEnd<Rest, `i${Acc}`> :
36
+ S extends `${infer Rest}g` ? StripFlagsFromEnd<Rest, `g${Acc}`> :
37
+ S extends `${infer Rest}d` ? StripFlagsFromEnd<Rest, `d${Acc}`> : { body: S; flags: Acc };
38
+ export type RegExpLiteralParts<L extends string> =
39
+ StripFlagsFromEnd<L> extends { body: infer B extends string; flags: infer F extends string }
40
+ ? B extends `/${infer AfterStart}`
41
+ ? AfterStart extends `${infer Pattern}/`
42
+ ? { pattern: Pattern; flags: F }
43
+ : never
44
+ : never
45
+ : never;
46
+ export type PCREStyleRegExpParts<S extends string> = RegExpLiteralParts<PCREStyleToJsRegExpSource<S>>;
47
+ export type PCREStyleRegExpPattern<S extends string> = PCREStyleRegExpParts<S>["pattern"];
48
+ export type PCREStyleRegExpFlags<S extends string> = PCREStyleRegExpParts<S>["flags"];
49
+ export declare const extractJsRegexPartsFromPCREStyleRegExpLiteral: <const S extends string>(src: S) => PCREStyleRegExpParts<S>;
50
+ export declare const compilePCREStyleRegExpLiteral: <
51
+ const S extends string,
52
+ const This = TypedRegExp<PCREStyleRegExpPattern<S>, PCREStyleRegExpFlags<S>>
53
+ >(src: S) => This;
54
+ export {};
@@ -0,0 +1,160 @@
1
+ /*!
2
+ // Copyright jeffy-g 2025
3
+ //
4
+ // Licensed under the Apache License, Version 2.0 (the "License");
5
+ // you may not use this file except in compliance with the License.
6
+ // You may obtain a copy of the License at
7
+ //
8
+ // http://www.apache.org/licenses/LICENSE-2.0
9
+ //
10
+ // Unless required by applicable law or agreed to in writing, software
11
+ // distributed under the License is distributed on an "AS IS" BASIS,
12
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ // See the License for the specific language governing permissions and
14
+ // limitations under the License.
15
+ */
16
+ /**
17
+ * @file types/pcre.d.ts
18
+ */
19
+ /*! [2025/12/31 13:01:03]
20
+ * ## Support PCRE-style regex source (type-level)
21
+ *
22
+ * @remarks
23
+ * This module provides **type-level normalization** for "PCRE-ish" regex sources:
24
+ * you can write a readable multi-line regex with indentation and `# ...` comments,
25
+ * then derive a compact JavaScript `RegExp` source at compile time.
26
+ *
27
+ * Why type-level? Because it lets us:
28
+ * - keep the regex readable in source code (with comments and formatting)
29
+ * - ensure the normalized output is stable and verifiable (via type assertions)
30
+ *
31
+ * ## Supported rules
32
+ * - `#` starts a comment and consumes the rest of the **current line**
33
+ * - `\#` escapes `#` as a literal (comment is NOT started) and normalizes to `#`
34
+ * - whitespace characters are removed during normalization
35
+ * - newlines are normalized: `\r\n` and `\r` become `\n`
36
+ *
37
+ * ## Design note (ts(2589) survival)
38
+ * Naively scanning the entire string character-by-character (multiple passes)
39
+ * can hit TypeScript's instantiation depth limit (`ts(2589)`).
40
+ * This implementation is **line-oriented**:
41
+ * it strips each line, then concatenates results.
42
+ * That tends to scale much better for long, commented regex sources.
43
+ *
44
+ * ## Non-goals (for now)
45
+ * This is not a full PCRE parser. It intentionally focuses on comment + whitespace
46
+ * normalization for readability and DX.
47
+ */
48
+ /**
49
+ * Union of whitespace characters used by this library.
50
+ *
51
+ * + A set aligned with ECMAScript RegExp **`\s`** (WhiteSpace ∪ LineTerminator)
52
+ *
53
+ * The union is used to normalize "PCRE-style" regex sources at the type level.
54
+ * @internal
55
+ */
56
+ type TWhiteSpace =
57
+ | "\x09"
58
+ | "\x0A"
59
+ | "\x0B"
60
+ | "\x0C"
61
+ | "\x0D"
62
+ | "\x20"
63
+ | "\u00A0"
64
+ | "\u1680"
65
+ | "\u2000"
66
+ | "\u2001"
67
+ | "\u2002"
68
+ | "\u2003"
69
+ | "\u2004"
70
+ | "\u2005"
71
+ | "\u2006"
72
+ | "\u2007"
73
+ | "\u2008"
74
+ | "\u2009"
75
+ | "\u200A"
76
+ | "\u2028" | "\u2029"
77
+ | "\u202F" | "\u205F" | "\u3000"
78
+ | "\uFEFF";
79
+ /**
80
+ * Normalize newline sequences for line-based parsing.
81
+ *
82
+ * + Align **`\r\n`** and **`\r`** to **`\n`** (makes splitting easier)
83
+ *
84
+ * @template S - Input string literal.
85
+ * @returns A new string literal with `\r\n` and `\r` normalized to `\n`.
86
+ * @internal
87
+ *
88
+ * @example
89
+ * type X = NormalizeNewlines<"a\r\nb\rc\n">; // "a\nb\nc\n"
90
+ */
91
+ type NormalizeNewlines<S extends string> =
92
+ S extends `${infer A}\r\n${infer B}` ? NormalizeNewlines<`${A}\n${B}`> :
93
+ S extends `${infer A}\r${infer B}` ? NormalizeNewlines<`${A}\n${B}`> :
94
+ S;
95
+ /**
96
+ * Strip and normalize a single line of a PCRE-style regex source.
97
+ *
98
+ * @remarks
99
+ * Rules:
100
+ * - `\#` is treated as a literal `#` (the backslash is dropped)
101
+ * - an unescaped `#` starts a line comment and truncates the rest
102
+ * - all whitespace characters are removed
103
+ * - other escapes like `\s`, `\w`, `\/`, `\*` are preserved as-is
104
+ *
105
+ * @template S - One line of source (no `\n`).
106
+ * @template Acc - Accumulator for the normalized output.
107
+ *
108
+ * @example
109
+ * type A = StripLine<" \\#\\w+ # comment ">; // "#\\w+"
110
+ * type B = StripLine<" abc # comment">; // "abc"
111
+ *
112
+ * @internal
113
+ *
114
+ * @todo
115
+ * - Handle `\\#` (a literal backslash + literal #) more strictly.
116
+ * - Do not treat `#` as a comment starter inside character classes (`[...]`).
117
+ */
118
+ type StripLine<S extends string, Acc extends string = ""> =
119
+ S extends `\\#${infer Rest}`
120
+ ? StripLine<Rest, `${Acc}#`>
121
+ : S extends `\\${infer C}${infer Rest}`
122
+ ? StripLine<Rest, `${Acc}\\${C}`>
123
+ : S extends `#${string}`
124
+ ? Acc
125
+ : S extends `${infer C}${infer Rest}`
126
+ ? C extends TWhiteSpace
127
+ ? StripLine<Rest, Acc>
128
+ : StripLine<Rest, `${Acc}${C}`>
129
+ : Acc;
130
+ /**
131
+ * Convert a multi-line PCRE-style regex source into a compact JS `RegExp.source`.
132
+ *
133
+ * @remarks
134
+ * This type:
135
+ * 1) normalizes newlines, 2) splits by line, 3) applies {@link StripLine},
136
+ * then 4) concatenates the results.
137
+ *
138
+ * @template Input - A `const` string literal of the PCRE-ish source.
139
+ * @template Acc - Accumulator for the result.
140
+ * @template S - Internal normalized newline buffer (do not pass manually).
141
+ *
142
+ * @example
143
+ * const RE_SOURCE = `
144
+ * ^ # start
145
+ * (?:\\#\\w+) # keep literal "#"
146
+ * ` as const;
147
+ *
148
+ * type Src = PCREStyleToJsRegExpSource<typeof RE_SOURCE>;
149
+ * // "^(:?##\\w+)" ... (depending on your actual input)
150
+ */
151
+ export type PCREStyleToJsRegExpSource<
152
+ Input extends string,
153
+ Acc extends string = "",
154
+ S extends string = NormalizeNewlines<Input>,
155
+ > =
156
+ S extends `${infer Line}\n${infer Rest}`
157
+ ? PCREStyleToJsRegExpSource<Input, `${Acc}${StripLine<Line>}`, Rest>
158
+ : `${Acc}${StripLine<S>}`;
159
+ export declare const normalizePCREStyleSource: <const S extends string>(src: S) => PCREStyleToJsRegExpSource<S>;
160
+ export {};
@@ -0,0 +1,81 @@
1
+ /*!
2
+ // Copyright jeffy-g 2026
3
+ //
4
+ // Licensed under the Apache License, Version 2.0 (the "License");
5
+ // you may not use this file except in compliance with the License.
6
+ // You may obtain a copy of the License at
7
+ //
8
+ // http://www.apache.org/licenses/LICENSE-2.0
9
+ //
10
+ // Unless required by applicable law or agreed to in writing, software
11
+ // distributed under the License is distributed on an "AS IS" BASIS,
12
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ // See the License for the specific language governing permissions and
14
+ // limitations under the License.
15
+ */
16
+ /**
17
+ * @file types/regex-util.d.ts
18
+ */
19
+ import type {
20
+ StringLength,
21
+ StringToUnion,
22
+ } from "./common.d.ts";
23
+ import type {
24
+ TRegexpFlag,
25
+ TValidRegExpFlag,
26
+ } from "./parser.d.ts";
27
+ /**
28
+ * @internal
29
+ */
30
+ type ExceedsMaxRegExpFlagCount<N extends number> =
31
+ number extends N ? boolean : N extends 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 ? false : true;
32
+ /**
33
+ * @internal
34
+ */
35
+ type IsUniqueChars<S extends string, Seen extends string = never> =
36
+ S extends `${infer H}${infer T}`
37
+ ? H extends Seen ? false : IsUniqueChars<T, Seen | H>
38
+ : true;
39
+ /**
40
+ * @internal
41
+ */
42
+ type NormalizeFlags<
43
+ F extends string, Order extends string = TRegexpFlag, Out extends string = "",
44
+ > = Order extends `${infer C}${infer Rest}`
45
+ ? NormalizeFlags<
46
+ F, Rest, F extends `${string}${C}${string}` ? `${Out}${C}` : Out
47
+ > : Out;
48
+ export type CanonicalFlags<F extends string> =
49
+ [string] extends [F] ? string :
50
+ Exclude<StringToUnion<F>, TValidRegExpFlag> extends never
51
+ ? IsUniqueChars<F> extends true
52
+ ? ExceedsMaxRegExpFlagCount<StringLength<F>> extends true
53
+ ? never
54
+ : NormalizeFlags<F>
55
+ : never
56
+ : never;
57
+ export type IsStrictFlags<F extends string> =
58
+ CanonicalFlags<F> extends never ? false : true;
59
+ type ValidateFlags<F extends string, Seen extends string = ""> =
60
+ F extends ""
61
+ ? true
62
+ : IsStrictFlags<F> extends false
63
+ ? false
64
+ : F extends `${infer C}${infer Rest}`
65
+ ? C extends TValidRegExpFlag
66
+ ? C extends Seen
67
+ ? false
68
+ : ValidateFlags<Rest, `${Seen}${C}`>
69
+ : false
70
+ : false;
71
+ export type RegExpFlags<R extends RegExp> =
72
+ R extends RegExp & { readonly flags: infer F extends string }
73
+ ? ValidateFlags<F> extends true
74
+ ? F : string
75
+ : string;
76
+ /**
77
+ * @internal
78
+ */
79
+ export type HasStrictRegExpFlag<F extends string, C extends TValidRegExpFlag> =
80
+ ValidateFlags<F> extends true ? F extends `${string}${C}${string}` ? true : false : false;
81
+ export {};
@@ -0,0 +1,76 @@
1
+ /*!
2
+ // Copyright jeffy-g 2025
3
+ //
4
+ // Licensed under the Apache License, Version 2.0 (the "License");
5
+ // you may not use this file except in compliance with the License.
6
+ // You may obtain a copy of the License at
7
+ //
8
+ // http://www.apache.org/licenses/LICENSE-2.0
9
+ //
10
+ // Unless required by applicable law or agreed to in writing, software
11
+ // distributed under the License is distributed on an "AS IS" BASIS,
12
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ // See the License for the specific language governing permissions and
14
+ // limitations under the License.
15
+ */
16
+ /**
17
+ * @file types/regex.d.ts
18
+ */
19
+ import type {
20
+ CountCaptureGroups,
21
+ RegExpNamedGroups,
22
+ RegExpIndicesArray,
23
+ RegExpExecArrayFixedPretty,
24
+ } from "./captures.d.ts";
25
+ import type { RegExpFlags, HasStrictRegExpFlag } from "./regex-util.d.ts";
26
+ import type { StringReplacerFunction } from "./replacer.d.ts";
27
+ declare const __typedRegExpBrand: unique symbol;
28
+ /**
29
+ * DO NOT USE CONSUMER
30
+ * @internal
31
+ */
32
+ type TypedRegExpBrand = { readonly [__typedRegExpBrand]: true };
33
+ /**
34
+ * + v0.3.0 feature
35
+ *
36
+ * @since v0.3.0
37
+ */
38
+ export type TypedRegExpTypes<
39
+ R extends RegExp,
40
+ S extends RegExpSource<R> = RegExpSource<R>,
41
+ NamedGroups = RegExpNamedGroups<R>,
42
+ GroupCount extends number = CountCaptureGroups<S>,
43
+ IsTypedRegExp = R extends TypedRegExpBrand ? true : false,
44
+ GROUPS = true extends IsTypedRegExp ? NamedGroups : never,
45
+ EXEC = true extends IsTypedRegExp ? RegExpExecArrayFixedPretty<R, S, GroupCount, NamedGroups> : never,
46
+ REPLACER = true extends IsTypedRegExp ? StringReplacerFunction<R> : never,
47
+ INDICES = true extends IsTypedRegExp ? RegExpIndicesArray<GroupCount, NamedGroups> : never,
48
+ > = true extends IsTypedRegExp ? {
49
+ groups: GROUPS;
50
+ exec: EXEC;
51
+ replacer: REPLACER;
52
+ indices: HasStrictRegExpFlag<RegExpFlags<R>, "d"> extends true ? INDICES : never;
53
+ } : never;
54
+ /**
55
+ * @since 2025/12/24 12:27:39
56
+ * @commit js-dev-tool@6ff89180acfb53c1a0bf9aebadfa12b210bfb3f8
57
+ */
58
+ export type TypedRegExp<P extends string, F extends string = ""> = RegExp & {
59
+ readonly source: P;
60
+ readonly flags: F;
61
+ } & TypedRegExpBrand & {
62
+ types: TypedRegExpTypes<TypedRegExp<P, F>>;
63
+ };
64
+ /**
65
+ * Extracts the literal type from the source property of a RegExp.
66
+ * @template R - A RegExp type.
67
+ */
68
+ export type RegExpSource<R extends RegExp> = R extends RegExp & { readonly source: infer T } ? T : never;
69
+ /**
70
+ * @deprecated description
71
+ */
72
+ export declare function createRegExp<
73
+ const P extends string,
74
+ const F extends string = ""
75
+ >(pattern: P, flags?: F): TypedRegExp<P, F>;
76
+ export {};
@@ -0,0 +1,60 @@
1
+ /*!
2
+ // Copyright jeffy-g 2025
3
+ //
4
+ // Licensed under the Apache License, Version 2.0 (the "License");
5
+ // you may not use this file except in compliance with the License.
6
+ // You may obtain a copy of the License at
7
+ //
8
+ // http://www.apache.org/licenses/LICENSE-2.0
9
+ //
10
+ // Unless required by applicable law or agreed to in writing, software
11
+ // distributed under the License is distributed on an "AS IS" BASIS,
12
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ // See the License for the specific language governing permissions and
14
+ // limitations under the License.
15
+ */
16
+ /**
17
+ * @file types/replacer.d.ts
18
+ */
19
+ import type {
20
+ TypedRegExp,
21
+ RegExpSource,
22
+ } from "./regex.d.ts";
23
+ import type { IsEmptyRecord } from "./common.d.ts";
24
+ import type { CountCaptureGroups, RegExpNamedGroups, CaptureOptTuple } from "./captures.d.ts";
25
+ /*!
26
+ // ============================================================================
27
+ // Helper Types for Replacer
28
+ // ============================================================================
29
+ */
30
+ /**
31
+ * Creates the parameter types for String.replace callback function.
32
+ *
33
+ * @example
34
+ * type Params = StringReplacerParams<typeof myRegex>;
35
+ * // [match: string, ...captures: string[], offset: number, string: string, groups?: {...}]
36
+ */
37
+ export type StringReplacerParams<
38
+ R extends RegExp,
39
+ S extends RegExpSource<R> = RegExpSource<R>,
40
+ GroupCount extends number = CountCaptureGroups<S>,
41
+ NamedGroups = RegExpNamedGroups<R>
42
+ > = IsEmptyRecord<NamedGroups> extends true ? [
43
+ match: string,
44
+ ...captures: CaptureOptTuple<GroupCount>,
45
+ offset: number,
46
+ input: string,
47
+ ] : [
48
+ match: string,
49
+ ...captures: CaptureOptTuple<GroupCount>,
50
+ offset: number,
51
+ input: string,
52
+ groups: NamedGroups
53
+ ];
54
+ export type StringReplacerFunction<R> =
55
+ R extends TypedRegExp<infer P extends string, infer F extends string>
56
+ ? (...args: StringReplacerParams<TypedRegExp<P, F>, P>) => string
57
+ : R extends RegExp
58
+ ? (match: string, ...rest: any[]) => string
59
+ : string;
60
+ export {};
package/package.json ADDED
@@ -0,0 +1,34 @@
1
+ {
2
+ "name": "literate-regex",
3
+ "version": "0.5.1",
4
+ "description": "Write readable (literate) regex sources with # comments, then normalize them to JS RegExp.source at the type level.",
5
+ "license": "Apache-2.0",
6
+ "sideEffects": false,
7
+ "main": "./dist/cjs/index.js",
8
+ "module": "./dist/esm/index.mjs",
9
+ "types": "./dist/index.d.ts",
10
+ "exports": {
11
+ ".": {
12
+ "types": "./dist/index.d.ts",
13
+ "import": "./dist/esm/index.mjs",
14
+ "require": "./dist/cjs/index.js"
15
+ },
16
+ "./global": {
17
+ "types": "./dist/global.d.ts"
18
+ }
19
+ },
20
+ "files": [
21
+ "README.md",
22
+ "LICENSE",
23
+ "dist"
24
+ ],
25
+ "keywords": [
26
+ "regex",
27
+ "regexp",
28
+ "literate",
29
+ "types",
30
+ "typescript",
31
+ "pcre",
32
+ "jsdoc"
33
+ ]
34
+ }