feat: init

This commit is contained in:
2026-02-13 22:02:30 +01:00
commit 8f9ff830fb
16711 changed files with 3307340 additions and 0 deletions

21
node_modules/magic-regexp/LICENCE generated vendored Normal file
View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2022 Daniel Roe
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

54
node_modules/magic-regexp/README.md generated vendored Normal file
View File

@@ -0,0 +1,54 @@
# 🦄 magic-regexp
[![npm version][npm-version-src]][npm-version-href]
[![npm downloads][npm-downloads-src]][npm-downloads-href]
[![Github Actions][github-actions-src]][github-actions-href]
[![Codecov][codecov-src]][codecov-href]
[![Bundlephobia][bundlephobia-src]][bundlephobia-href]
> A compiled-away, type-safe, readable RegExp alternative
- [✨  Changelog](https://github.com/danielroe/magic-regexp/blob/main/CHANGELOG.md)
- [📖  Documentation](https://regexp.dev)
- [▶️  Online playground](https://www.typescriptlang.org/play/?#code/JYWwDg9gTgLgBAbzgYwBYEMoBoVQKbox4BKeA5gKIAeYOAJsGcDDnlesjADYCeOI6HgCM8OCADs8AeSgBZaKLgB3aHQDCGKHAC+cAGZQIIOAHIBTZAFp8ZNmBMAoBwHoAVK4dxXKDONtwYCE9vUEhYRAA6KN0DI1NzYCsbO2c9AFdYVDwoSwTkRy8AiACoHgCeMDw4LjwANzwuOFJKGjgBGDQ4fABnNK4YbrgACjts0DxxGHQuAEpg5ydnZzgAFQq8OhR0MBgMqrJDNLBuh2QJbvgASQARAH1iCjgAXlwCImbqMBH2Tl4hk2AdEsJhmEXQ4joQwYTBgERg426QwArKCDhAjhsAIKIgF0EEzOZncQXOBoo6DF4mbpGKqAywAJgAzAAWACcAAY4Fl8Mp9hATBF2mghjd7hQZgB+CJk44uZZwBVwAB6EsWywAimlEgBrSzgoEMWBlbp4ED1KCnc7wADKFFkADUKMQxc9XoQSORPkNPHAJNI5AooYxmKjDpU6Nj-gIAFbQEFYH0CkwJhV+mTyfBBmGh9HhyNmYDiOMzFNtQQif4RZO+yTpwNoTA5jERnFgQhofEJuYOW0Op1iuXK1WW4nwHp9eAvZD4d0fGjfDjcHj-PQQCDOIgXCLR7ogsF6IhQf5CTDOfFwvAXY+n1frzewncgtVNPB6bITZCXopwMD4WrAdFul4LYdj2TYZUGNJukLMgAiyUkwzgcR0BAPARxJFYKAAOQoFYXSnGd3k9ecfTYRc-hUKB1E0aUwyxHE9GAKALg0TB42UVRWKgWjc3o-4TSJai2JLGt-QzPAhgbKACR9BUwQhCJ8DffBxE-FYIH4vBBK4p9FTgeS6EU1931UvB1JXJiWM0eMHG7IkSXHfp6VdTCcLwh4LyvExXIAHieJ4pH8gA+NyQSAA)
## Features
- Runtime is zero-dependency and ultra-minimal
- Ships with transform to compile to pure RegExp
- Automatically typed capture groups
- Natural language syntax
- Generated RegExp displays on hover
[📖  Read more](https://regexp.dev)
## 💻 Development
- Clone this repository
- Enable [Corepack](https://github.com/nodejs/corepack) using `corepack enable` (use `npm i -g corepack` for Node.js < 16.10)
- Install dependencies using `pnpm install`
- Run interactive tests using `pnpm dev`
## Similar packages
- [verbal-expressions](http://verbalexpressions.github.io/)
- [typed-regex](https://github.com/phenax/typed-regex/)
## License
Made with ❤️
Published under [MIT License](./LICENCE).
<!-- Badges -->
[npm-version-src]: https://img.shields.io/npm/v/magic-regexp?style=flat-square
[npm-version-href]: https://npmjs.com/package/magic-regexp
[npm-downloads-src]: https://img.shields.io/npm/dm/magic-regexp?style=flat-square
[npm-downloads-href]: https://npmjs.com/package/magic-regexp
[github-actions-src]: https://img.shields.io/github/actions/workflow/status/danielroe/magic-regexp/ci.yml?branch=main&style=flat-square
[github-actions-href]: https://github.com/danielroe/magic-regexp/actions?query=workflow%3Aci
[codecov-src]: https://img.shields.io/codecov/c/gh/danielroe/magic-regexp/main?style=flat-square
[codecov-href]: https://codecov.io/gh/danielroe/magic-regexp
[bundlephobia-src]: https://img.shields.io/bundlephobia/minzip/magic-regexp?style=flat-square
[bundlephobia-href]: https://bundlephobia.com/package/magic-regexp

265
node_modules/magic-regexp/dist/converter.cjs generated vendored Normal file
View File

@@ -0,0 +1,265 @@
'use strict';
const regexpTree = require('regexp-tree');
function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e.default : e; }
const regexpTree__default = /*#__PURE__*/_interopDefaultCompat(regexpTree);
function build(node) {
if (node === null)
return "";
switch (node.type) {
case "CharacterClass": {
const exprs = combineContinuousSimpleChars(node.expressions);
if (exprs.length === 1) {
const first = exprs[0];
if (typeof first === "string") {
return node.negative ? `charNotIn(${first})` : `charIn(${first})`;
} else if (first.type === "Char" && first.kind === "meta" && node.negative) {
if (first.value === "\\t")
return `not.tab`;
if (first.value === "\\n")
return `not.linefeed`;
if (first.value === "\\r")
return `not.carriageReturn`;
} else {
const range = normalizeClassRange(first);
if (range === "A-Z")
return node.negative ? `not.letter.uppercase` : `letter.uppercase`;
else if (range === "a-z")
return node.negative ? `not.letter.lowercase` : `letter.lowercase`;
}
} else if (exprs.length === 2) {
if (typeof exprs[0] !== "string" && typeof exprs[1] !== "string") {
const range1 = normalizeClassRange(exprs[0]);
const range2 = normalizeClassRange(exprs[1]);
if (range1 === "A-Z" && range2 === "a-z" || range1 === "a-z" && range2 === "A-Z")
return node.negative ? `not.letter` : `letter`;
}
}
throw new Error("Unsupported for Complex charactor class");
}
case "Disjunction":
return chain(build(node.left), `or(${build(node.right)})`);
case "Assertion":
switch (node.kind) {
case "\\b":
return "wordBoundary";
case "\\B":
return "not.wordBoundary";
case "^":
return chain("", "at.lineStart()");
case "$":
return chain("", "at.lineEnd()");
case "Lookbehind":
return chain("", `${node.negative ? "notAfter" : "after"}(${build(node.assertion)})`);
case "Lookahead":
return chain("", `${node.negative ? "notBefore" : "before"}(${build(node.assertion)})`);
/* v8 ignore next 2 */
default:
throw new TypeError(`Unknown Assertion kind: ${node.kind}`);
}
case "Char":
if (node.kind === "meta") {
switch (node.value) {
case ".":
return "char";
case "\\w":
return "wordChar";
case "\\d":
return "digit";
case "\\s":
return "whitespace";
case "\\t":
return "tab";
case "\\n":
return "linefeed";
case "\\r":
return "carriageReturn";
case "\\W":
return "not.wordChar";
case "\\D":
return "not.digit";
case "\\S":
return "not.whitespace";
case "\f":
case "\v":
default:
throw new Error(`Unsupported Meta Char: ${node.value}`);
}
} else {
const char = getChar(node);
if (char === null)
throw new Error(`Unknown Char: ${node.value}`);
return `'${char}'`;
}
case "Repetition": {
const quantifier = node.quantifier;
const expr = build(node.expression);
const lazy = !quantifier.greedy;
if (lazy)
throw new Error("Unsupported for lazy quantifier");
switch (quantifier.kind) {
case "+":
return `oneOrMore(${expr})`;
case "?":
return `maybe(${expr})`;
case "*":
return chain(expr, "times.any()");
case "Range":
if (quantifier.from === quantifier.to)
return chain(expr, `times(${quantifier.from})`);
else if (!quantifier.to)
return chain(expr, `times.atLeast(${quantifier.from})`);
else if (quantifier.from === 0)
return chain(expr, `times.atMost(${quantifier.to})`);
return chain(expr, `times.between(${quantifier.from}, ${quantifier.to})`);
/* v8 ignore next 2 */
default:
return "";
}
}
case "Alternative": {
const alts = combineContinuousSimpleChars(node.expressions);
const exprs = [];
for (let i = 0; i < alts.length; i++) {
const alt = alts[i];
if (typeof alt === "string") {
exprs.push(alt);
continue;
}
if (alt.type === "Assertion") {
switch (alt.kind) {
case "^": {
const next = alts[++i];
if (next === void 0)
throw new Error(`Unexpected assertion: ${JSON.stringify(alt)}`);
exprs.push(chain(next, "at.lineStart()"));
continue;
}
case "$": {
const prev = exprs.pop();
if (prev === void 0)
throw new Error(`Unexpected assertion: ${JSON.stringify(alt)}`);
exprs.push(chain(prev, "at.lineEnd()"));
continue;
}
case "Lookbehind": {
const next = alts[++i];
if (next === void 0)
throw new Error(`Unexpected assertion: ${JSON.stringify(alt)}`);
const helper = alt.negative ? "notAfter" : "after";
exprs.push(chain(next, `${helper}(${build(alt.assertion)})`));
continue;
}
case "Lookahead": {
const prev = exprs.pop();
if (prev === void 0)
throw new Error(`Unexpected assertion: ${JSON.stringify(alt)}`);
const helper = alt.negative ? "notBefore" : "before";
exprs.push(chain(prev, `${helper}(${build(alt.assertion)})`));
continue;
}
}
}
if (alt.type === "Backreference") {
if (alt.kind !== "name")
throw new Error(`Unsupport for number reference`);
const ref = chain(`exactly(${exprs.join(", ")})`, `and.referenceTo('${alt.reference}')`);
exprs.length = 0;
exprs.push(ref);
continue;
}
exprs.push(build(alt));
}
return exprs.join(", ");
}
case "Group":
if (node.capturing)
return chain(build(node.expression), node.name ? `as('${node.name}')` : "grouped()");
else return chain(build(node.expression));
/* v8 ignore next 2 */
case "Backreference":
return chain("", `and.referenceTo('${node.reference}')`);
}
}
function normalizeClassRange(node) {
if (node.type === "ClassRange")
return `${node.from.value}-${node.to.value}`;
}
function combineContinuousSimpleChars(expressions) {
let simpleChars = "";
const exprs = expressions.reduce(
(acc, expr) => {
const char = expr.type === "Char" ? getChar(expr) : null;
if (char !== null) {
simpleChars += char;
} else {
if (simpleChars) {
acc.push(`'${simpleChars}'`);
simpleChars = "";
}
acc.push(expr);
}
return acc;
},
[]
);
if (simpleChars)
exprs.push(`'${simpleChars}'`);
return exprs;
}
function getChar(char) {
function escapeSimpleChar(char2) {
return char2 === "'" ? "\\'" : char2;
}
switch (char.kind) {
case "simple":
return escapeSimpleChar(char.value);
case "oct":
case "decimal":
case "hex":
case "unicode":
if ("symbol" in char)
return escapeSimpleChar(char.symbol);
}
return null;
}
function chain(expr, helper) {
let _expr = "";
if (typeof expr === "string") {
if (expr === "")
_expr = "exactly('')";
else _expr = expr.startsWith("'") && expr.endsWith("'") ? `exactly(${expr})` : expr;
} else {
_expr = build(expr);
}
return helper ? `${_expr}.${helper}` : _expr;
}
function buildFlags(flags) {
if (!flags)
return "";
const readableFlags = flags.split("").map((flag) => {
return {
d: "withIndices",
i: "caseInsensitive",
g: "global",
m: "multiline",
s: "dotAll",
u: "unicode",
y: "sticky"
}[flag] || `'${flag}'`;
});
return `[${readableFlags.join(", ")}]`;
}
function convert(regex, { argsOnly = false } = {}) {
const ast = regexpTree__default.parse(regex);
if (ast.type !== "RegExp")
throw new TypeError(`Unexpected RegExp AST: ${ast.type}`);
const flags = buildFlags(ast.flags);
const args = build(ast.body) + (flags ? `, ${flags}` : "");
return argsOnly ? args : `createRegExp(${args})`;
}
exports.convert = convert;

5
node_modules/magic-regexp/dist/converter.d.cts generated vendored Normal file
View File

@@ -0,0 +1,5 @@
declare function convert(regex: RegExp, { argsOnly }?: {
argsOnly?: boolean | undefined;
}): string;
export { convert };

5
node_modules/magic-regexp/dist/converter.d.mts generated vendored Normal file
View File

@@ -0,0 +1,5 @@
declare function convert(regex: RegExp, { argsOnly }?: {
argsOnly?: boolean | undefined;
}): string;
export { convert };

5
node_modules/magic-regexp/dist/converter.d.ts generated vendored Normal file
View File

@@ -0,0 +1,5 @@
declare function convert(regex: RegExp, { argsOnly }?: {
argsOnly?: boolean | undefined;
}): string;
export { convert };

259
node_modules/magic-regexp/dist/converter.mjs generated vendored Normal file
View File

@@ -0,0 +1,259 @@
import regexpTree from 'regexp-tree';
function build(node) {
if (node === null)
return "";
switch (node.type) {
case "CharacterClass": {
const exprs = combineContinuousSimpleChars(node.expressions);
if (exprs.length === 1) {
const first = exprs[0];
if (typeof first === "string") {
return node.negative ? `charNotIn(${first})` : `charIn(${first})`;
} else if (first.type === "Char" && first.kind === "meta" && node.negative) {
if (first.value === "\\t")
return `not.tab`;
if (first.value === "\\n")
return `not.linefeed`;
if (first.value === "\\r")
return `not.carriageReturn`;
} else {
const range = normalizeClassRange(first);
if (range === "A-Z")
return node.negative ? `not.letter.uppercase` : `letter.uppercase`;
else if (range === "a-z")
return node.negative ? `not.letter.lowercase` : `letter.lowercase`;
}
} else if (exprs.length === 2) {
if (typeof exprs[0] !== "string" && typeof exprs[1] !== "string") {
const range1 = normalizeClassRange(exprs[0]);
const range2 = normalizeClassRange(exprs[1]);
if (range1 === "A-Z" && range2 === "a-z" || range1 === "a-z" && range2 === "A-Z")
return node.negative ? `not.letter` : `letter`;
}
}
throw new Error("Unsupported for Complex charactor class");
}
case "Disjunction":
return chain(build(node.left), `or(${build(node.right)})`);
case "Assertion":
switch (node.kind) {
case "\\b":
return "wordBoundary";
case "\\B":
return "not.wordBoundary";
case "^":
return chain("", "at.lineStart()");
case "$":
return chain("", "at.lineEnd()");
case "Lookbehind":
return chain("", `${node.negative ? "notAfter" : "after"}(${build(node.assertion)})`);
case "Lookahead":
return chain("", `${node.negative ? "notBefore" : "before"}(${build(node.assertion)})`);
/* v8 ignore next 2 */
default:
throw new TypeError(`Unknown Assertion kind: ${node.kind}`);
}
case "Char":
if (node.kind === "meta") {
switch (node.value) {
case ".":
return "char";
case "\\w":
return "wordChar";
case "\\d":
return "digit";
case "\\s":
return "whitespace";
case "\\t":
return "tab";
case "\\n":
return "linefeed";
case "\\r":
return "carriageReturn";
case "\\W":
return "not.wordChar";
case "\\D":
return "not.digit";
case "\\S":
return "not.whitespace";
case "\f":
case "\v":
default:
throw new Error(`Unsupported Meta Char: ${node.value}`);
}
} else {
const char = getChar(node);
if (char === null)
throw new Error(`Unknown Char: ${node.value}`);
return `'${char}'`;
}
case "Repetition": {
const quantifier = node.quantifier;
const expr = build(node.expression);
const lazy = !quantifier.greedy;
if (lazy)
throw new Error("Unsupported for lazy quantifier");
switch (quantifier.kind) {
case "+":
return `oneOrMore(${expr})`;
case "?":
return `maybe(${expr})`;
case "*":
return chain(expr, "times.any()");
case "Range":
if (quantifier.from === quantifier.to)
return chain(expr, `times(${quantifier.from})`);
else if (!quantifier.to)
return chain(expr, `times.atLeast(${quantifier.from})`);
else if (quantifier.from === 0)
return chain(expr, `times.atMost(${quantifier.to})`);
return chain(expr, `times.between(${quantifier.from}, ${quantifier.to})`);
/* v8 ignore next 2 */
default:
return "";
}
}
case "Alternative": {
const alts = combineContinuousSimpleChars(node.expressions);
const exprs = [];
for (let i = 0; i < alts.length; i++) {
const alt = alts[i];
if (typeof alt === "string") {
exprs.push(alt);
continue;
}
if (alt.type === "Assertion") {
switch (alt.kind) {
case "^": {
const next = alts[++i];
if (next === void 0)
throw new Error(`Unexpected assertion: ${JSON.stringify(alt)}`);
exprs.push(chain(next, "at.lineStart()"));
continue;
}
case "$": {
const prev = exprs.pop();
if (prev === void 0)
throw new Error(`Unexpected assertion: ${JSON.stringify(alt)}`);
exprs.push(chain(prev, "at.lineEnd()"));
continue;
}
case "Lookbehind": {
const next = alts[++i];
if (next === void 0)
throw new Error(`Unexpected assertion: ${JSON.stringify(alt)}`);
const helper = alt.negative ? "notAfter" : "after";
exprs.push(chain(next, `${helper}(${build(alt.assertion)})`));
continue;
}
case "Lookahead": {
const prev = exprs.pop();
if (prev === void 0)
throw new Error(`Unexpected assertion: ${JSON.stringify(alt)}`);
const helper = alt.negative ? "notBefore" : "before";
exprs.push(chain(prev, `${helper}(${build(alt.assertion)})`));
continue;
}
}
}
if (alt.type === "Backreference") {
if (alt.kind !== "name")
throw new Error(`Unsupport for number reference`);
const ref = chain(`exactly(${exprs.join(", ")})`, `and.referenceTo('${alt.reference}')`);
exprs.length = 0;
exprs.push(ref);
continue;
}
exprs.push(build(alt));
}
return exprs.join(", ");
}
case "Group":
if (node.capturing)
return chain(build(node.expression), node.name ? `as('${node.name}')` : "grouped()");
else return chain(build(node.expression));
/* v8 ignore next 2 */
case "Backreference":
return chain("", `and.referenceTo('${node.reference}')`);
}
}
function normalizeClassRange(node) {
if (node.type === "ClassRange")
return `${node.from.value}-${node.to.value}`;
}
function combineContinuousSimpleChars(expressions) {
let simpleChars = "";
const exprs = expressions.reduce(
(acc, expr) => {
const char = expr.type === "Char" ? getChar(expr) : null;
if (char !== null) {
simpleChars += char;
} else {
if (simpleChars) {
acc.push(`'${simpleChars}'`);
simpleChars = "";
}
acc.push(expr);
}
return acc;
},
[]
);
if (simpleChars)
exprs.push(`'${simpleChars}'`);
return exprs;
}
function getChar(char) {
function escapeSimpleChar(char2) {
return char2 === "'" ? "\\'" : char2;
}
switch (char.kind) {
case "simple":
return escapeSimpleChar(char.value);
case "oct":
case "decimal":
case "hex":
case "unicode":
if ("symbol" in char)
return escapeSimpleChar(char.symbol);
}
return null;
}
function chain(expr, helper) {
let _expr = "";
if (typeof expr === "string") {
if (expr === "")
_expr = "exactly('')";
else _expr = expr.startsWith("'") && expr.endsWith("'") ? `exactly(${expr})` : expr;
} else {
_expr = build(expr);
}
return helper ? `${_expr}.${helper}` : _expr;
}
function buildFlags(flags) {
if (!flags)
return "";
const readableFlags = flags.split("").map((flag) => {
return {
d: "withIndices",
i: "caseInsensitive",
g: "global",
m: "multiline",
s: "dotAll",
u: "unicode",
y: "sticky"
}[flag] || `'${flag}'`;
});
return `[${readableFlags.join(", ")}]`;
}
function convert(regex, { argsOnly = false } = {}) {
const ast = regexpTree.parse(regex);
if (ast.type !== "RegExp")
throw new TypeError(`Unexpected RegExp AST: ${ast.type}`);
const flags = buildFlags(ast.flags);
const args = build(ast.body) + (flags ? `, ${flags}` : "");
return argsOnly ? args : `createRegExp(${args})`;
}
export { convert };

37
node_modules/magic-regexp/dist/further-magic.cjs generated vendored Normal file
View File

@@ -0,0 +1,37 @@
'use strict';
const flags = require('./shared/magic-regexp.DNdg2jII.cjs');
const regexp = require('type-level-regexp/regexp');
const createRegExp = (...inputs) => {
const flags$1 = inputs.length > 1 && (Array.isArray(inputs[inputs.length - 1]) || inputs[inputs.length - 1] instanceof Set) ? inputs.pop() : void 0;
return new RegExp(flags.exactly(...inputs).toString(), [...flags$1 || ""].join(""));
};
exports.anyOf = flags.anyOf;
exports.carriageReturn = flags.carriageReturn;
exports.caseInsensitive = flags.caseInsensitive;
exports.char = flags.char;
exports.charIn = flags.charIn;
exports.charNotIn = flags.charNotIn;
exports.digit = flags.digit;
exports.dotAll = flags.dotAll;
exports.exactly = flags.exactly;
exports.global = flags.global;
exports.letter = flags.letter;
exports.linefeed = flags.linefeed;
exports.maybe = flags.maybe;
exports.multiline = flags.multiline;
exports.not = flags.not;
exports.oneOrMore = flags.oneOrMore;
exports.sticky = flags.sticky;
exports.tab = flags.tab;
exports.unicode = flags.unicode;
exports.whitespace = flags.whitespace;
exports.withIndices = flags.withIndices;
exports.word = flags.word;
exports.wordBoundary = flags.wordBoundary;
exports.wordChar = flags.wordChar;
exports.spreadRegExpIterator = regexp.spreadRegExpIterator;
exports.spreadRegExpMatchArray = regexp.spreadRegExpMatchArray;
exports.createRegExp = createRegExp;

46
node_modules/magic-regexp/dist/further-magic.d.cts generated vendored Normal file
View File

@@ -0,0 +1,46 @@
import { MatchRegExp, ParseRegExp, MatchAllRegExp, RegExpMatchResult, ReplaceWithRegExp } from 'type-level-regexp/regexp';
export { spreadRegExpIterator, spreadRegExpMatchArray } from 'type-level-regexp/regexp';
import { F as Flag, J as Join, I as InputSource, b as MapToValues, c as MapToGroups, U as UnionToTuple } from './shared/magic-regexp.Cp7m-ws-.cjs';
export { h as Input, a as MagicRegExpMatchArray, D as MapToStringCapturedBy, S as StringCapturedBy, k as anyOf, y as carriageReturn, e as caseInsensitive, l as char, i as charIn, j as charNotIn, q as digit, f as dotAll, B as exactly, g as global, t as letter, x as linefeed, A as maybe, m as multiline, z as not, C as oneOrMore, s as sticky, v as tab, u as unicode, r as whitespace, w as withIndices, n as word, p as wordBoundary, o as wordChar } from './shared/magic-regexp.Cp7m-ws-.cjs';
declare const NamedGroupsS: unique symbol;
declare const ValueS: unique symbol;
declare const FlagsS: unique symbol;
type MagicRegExp<Value extends string, NamedGroups extends string | never = never, Flags extends Flag[] | never = never> = RegExp & {
[NamedGroupsS]: NamedGroups;
[ValueS]: Value;
[FlagsS]: Flags;
};
declare const createRegExp: {
/** Create Magic RegExp from Input helpers and string (string will be sanitized) */
<Inputs extends InputSource[]>(...inputs: Inputs): MagicRegExp<`/${Join<MapToValues<Inputs>, '', ''>}/`, MapToGroups<Inputs>, []>;
<Inputs extends InputSource[], FlagUnion extends Flag | undefined = undefined, CloneFlagUnion extends Flag | undefined = FlagUnion, Flags extends Flag[] = CloneFlagUnion extends undefined ? [] : UnionToTuple<FlagUnion> extends infer F extends Flag[] ? F : never>(...inputs: [...Inputs, [...Flags] | string | Set<FlagUnion>]): MagicRegExp<`/${Join<MapToValues<Inputs>, '', ''>}/${Join<Flags, '', ''>}`, MapToGroups<Inputs>, Flags>;
};
declare global {
interface String {
match<InputString extends string, RegExpPattern extends string, Flags extends Flag[]>(this: InputString, regexp: MagicRegExp<`/${RegExpPattern}/${Join<Flags, '', ''>}`, string, Flags>): MatchRegExp<InputString, ParseRegExp<RegExpPattern>, Flag[] extends Flags ? never : Flags[number]>;
/** @deprecated String.matchAll requires global flag to be set. */
matchAll<R extends MagicRegExp<string, string, Exclude<Flag, 'g'>[]>>(regexp: R): never;
matchAll<InputString extends string, RegExpPattern extends string, Flags extends Flag[]>(this: InputString, regexp: MagicRegExp<`/${RegExpPattern}/${Join<Flags, '', ''>}`, string, Flags>): MatchAllRegExp<InputString, ParseRegExp<RegExpPattern>, Flag[] extends Flags ? never : Flags[number]>;
/** @deprecated String.matchAll requires global flag to be set. */
matchAll<R extends MagicRegExp<string, string, never>>(regexp: R): never;
replace<InputString extends string, RegExpPattern extends string, Flags extends Flag[], ReplaceValue extends string, RegExpParsedAST extends any[] = string extends RegExpPattern ? never : ParseRegExp<RegExpPattern>, MatchResult = MatchRegExp<InputString, RegExpParsedAST, Flags[number]>, Match extends any[] = MatchResult extends RegExpMatchResult<{
matched: infer MatchArray extends any[];
namedCaptures: [string, any];
input: infer Input extends string;
restInput: string | undefined;
}, {
index: infer Index extends number;
groups: infer Groups;
input: string;
keys: (...arg: any) => any;
}> ? [...MatchArray, Index, Input, Groups] : never>(this: InputString, regexp: MagicRegExp<`/${RegExpPattern}/${Join<Flags, '', ''>}`, string, Flags>, replaceValue: ReplaceValue | ((...match: Match) => ReplaceValue)): any[] extends RegExpParsedAST ? never : ReplaceWithRegExp<InputString, RegExpParsedAST, ReplaceValue, Flags[number]>;
/** @deprecated String.replaceAll requires global flag to be set. */
replaceAll<R extends MagicRegExp<string, string, never>>(searchValue: R, replaceValue: string | ((substring: string, ...args: any[]) => string)): never;
/** @deprecated String.replaceAll requires global flag to be set. */
replaceAll<R extends MagicRegExp<string, string, Exclude<Flag, 'g'>[]>>(searchValue: R, replaceValue: string | ((substring: string, ...args: any[]) => string)): never;
}
}
export { Flag, type MagicRegExp, createRegExp };

46
node_modules/magic-regexp/dist/further-magic.d.mts generated vendored Normal file
View File

@@ -0,0 +1,46 @@
import { MatchRegExp, ParseRegExp, MatchAllRegExp, RegExpMatchResult, ReplaceWithRegExp } from 'type-level-regexp/regexp';
export { spreadRegExpIterator, spreadRegExpMatchArray } from 'type-level-regexp/regexp';
import { F as Flag, J as Join, I as InputSource, b as MapToValues, c as MapToGroups, U as UnionToTuple } from './shared/magic-regexp.Cp7m-ws-.mjs';
export { h as Input, a as MagicRegExpMatchArray, D as MapToStringCapturedBy, S as StringCapturedBy, k as anyOf, y as carriageReturn, e as caseInsensitive, l as char, i as charIn, j as charNotIn, q as digit, f as dotAll, B as exactly, g as global, t as letter, x as linefeed, A as maybe, m as multiline, z as not, C as oneOrMore, s as sticky, v as tab, u as unicode, r as whitespace, w as withIndices, n as word, p as wordBoundary, o as wordChar } from './shared/magic-regexp.Cp7m-ws-.mjs';
declare const NamedGroupsS: unique symbol;
declare const ValueS: unique symbol;
declare const FlagsS: unique symbol;
type MagicRegExp<Value extends string, NamedGroups extends string | never = never, Flags extends Flag[] | never = never> = RegExp & {
[NamedGroupsS]: NamedGroups;
[ValueS]: Value;
[FlagsS]: Flags;
};
declare const createRegExp: {
/** Create Magic RegExp from Input helpers and string (string will be sanitized) */
<Inputs extends InputSource[]>(...inputs: Inputs): MagicRegExp<`/${Join<MapToValues<Inputs>, '', ''>}/`, MapToGroups<Inputs>, []>;
<Inputs extends InputSource[], FlagUnion extends Flag | undefined = undefined, CloneFlagUnion extends Flag | undefined = FlagUnion, Flags extends Flag[] = CloneFlagUnion extends undefined ? [] : UnionToTuple<FlagUnion> extends infer F extends Flag[] ? F : never>(...inputs: [...Inputs, [...Flags] | string | Set<FlagUnion>]): MagicRegExp<`/${Join<MapToValues<Inputs>, '', ''>}/${Join<Flags, '', ''>}`, MapToGroups<Inputs>, Flags>;
};
declare global {
interface String {
match<InputString extends string, RegExpPattern extends string, Flags extends Flag[]>(this: InputString, regexp: MagicRegExp<`/${RegExpPattern}/${Join<Flags, '', ''>}`, string, Flags>): MatchRegExp<InputString, ParseRegExp<RegExpPattern>, Flag[] extends Flags ? never : Flags[number]>;
/** @deprecated String.matchAll requires global flag to be set. */
matchAll<R extends MagicRegExp<string, string, Exclude<Flag, 'g'>[]>>(regexp: R): never;
matchAll<InputString extends string, RegExpPattern extends string, Flags extends Flag[]>(this: InputString, regexp: MagicRegExp<`/${RegExpPattern}/${Join<Flags, '', ''>}`, string, Flags>): MatchAllRegExp<InputString, ParseRegExp<RegExpPattern>, Flag[] extends Flags ? never : Flags[number]>;
/** @deprecated String.matchAll requires global flag to be set. */
matchAll<R extends MagicRegExp<string, string, never>>(regexp: R): never;
replace<InputString extends string, RegExpPattern extends string, Flags extends Flag[], ReplaceValue extends string, RegExpParsedAST extends any[] = string extends RegExpPattern ? never : ParseRegExp<RegExpPattern>, MatchResult = MatchRegExp<InputString, RegExpParsedAST, Flags[number]>, Match extends any[] = MatchResult extends RegExpMatchResult<{
matched: infer MatchArray extends any[];
namedCaptures: [string, any];
input: infer Input extends string;
restInput: string | undefined;
}, {
index: infer Index extends number;
groups: infer Groups;
input: string;
keys: (...arg: any) => any;
}> ? [...MatchArray, Index, Input, Groups] : never>(this: InputString, regexp: MagicRegExp<`/${RegExpPattern}/${Join<Flags, '', ''>}`, string, Flags>, replaceValue: ReplaceValue | ((...match: Match) => ReplaceValue)): any[] extends RegExpParsedAST ? never : ReplaceWithRegExp<InputString, RegExpParsedAST, ReplaceValue, Flags[number]>;
/** @deprecated String.replaceAll requires global flag to be set. */
replaceAll<R extends MagicRegExp<string, string, never>>(searchValue: R, replaceValue: string | ((substring: string, ...args: any[]) => string)): never;
/** @deprecated String.replaceAll requires global flag to be set. */
replaceAll<R extends MagicRegExp<string, string, Exclude<Flag, 'g'>[]>>(searchValue: R, replaceValue: string | ((substring: string, ...args: any[]) => string)): never;
}
}
export { Flag, type MagicRegExp, createRegExp };

46
node_modules/magic-regexp/dist/further-magic.d.ts generated vendored Normal file
View File

@@ -0,0 +1,46 @@
import { MatchRegExp, ParseRegExp, MatchAllRegExp, RegExpMatchResult, ReplaceWithRegExp } from 'type-level-regexp/regexp';
export { spreadRegExpIterator, spreadRegExpMatchArray } from 'type-level-regexp/regexp';
import { F as Flag, J as Join, I as InputSource, b as MapToValues, c as MapToGroups, U as UnionToTuple } from './shared/magic-regexp.Cp7m-ws-.js';
export { h as Input, a as MagicRegExpMatchArray, D as MapToStringCapturedBy, S as StringCapturedBy, k as anyOf, y as carriageReturn, e as caseInsensitive, l as char, i as charIn, j as charNotIn, q as digit, f as dotAll, B as exactly, g as global, t as letter, x as linefeed, A as maybe, m as multiline, z as not, C as oneOrMore, s as sticky, v as tab, u as unicode, r as whitespace, w as withIndices, n as word, p as wordBoundary, o as wordChar } from './shared/magic-regexp.Cp7m-ws-.js';
declare const NamedGroupsS: unique symbol;
declare const ValueS: unique symbol;
declare const FlagsS: unique symbol;
type MagicRegExp<Value extends string, NamedGroups extends string | never = never, Flags extends Flag[] | never = never> = RegExp & {
[NamedGroupsS]: NamedGroups;
[ValueS]: Value;
[FlagsS]: Flags;
};
declare const createRegExp: {
/** Create Magic RegExp from Input helpers and string (string will be sanitized) */
<Inputs extends InputSource[]>(...inputs: Inputs): MagicRegExp<`/${Join<MapToValues<Inputs>, '', ''>}/`, MapToGroups<Inputs>, []>;
<Inputs extends InputSource[], FlagUnion extends Flag | undefined = undefined, CloneFlagUnion extends Flag | undefined = FlagUnion, Flags extends Flag[] = CloneFlagUnion extends undefined ? [] : UnionToTuple<FlagUnion> extends infer F extends Flag[] ? F : never>(...inputs: [...Inputs, [...Flags] | string | Set<FlagUnion>]): MagicRegExp<`/${Join<MapToValues<Inputs>, '', ''>}/${Join<Flags, '', ''>}`, MapToGroups<Inputs>, Flags>;
};
declare global {
interface String {
match<InputString extends string, RegExpPattern extends string, Flags extends Flag[]>(this: InputString, regexp: MagicRegExp<`/${RegExpPattern}/${Join<Flags, '', ''>}`, string, Flags>): MatchRegExp<InputString, ParseRegExp<RegExpPattern>, Flag[] extends Flags ? never : Flags[number]>;
/** @deprecated String.matchAll requires global flag to be set. */
matchAll<R extends MagicRegExp<string, string, Exclude<Flag, 'g'>[]>>(regexp: R): never;
matchAll<InputString extends string, RegExpPattern extends string, Flags extends Flag[]>(this: InputString, regexp: MagicRegExp<`/${RegExpPattern}/${Join<Flags, '', ''>}`, string, Flags>): MatchAllRegExp<InputString, ParseRegExp<RegExpPattern>, Flag[] extends Flags ? never : Flags[number]>;
/** @deprecated String.matchAll requires global flag to be set. */
matchAll<R extends MagicRegExp<string, string, never>>(regexp: R): never;
replace<InputString extends string, RegExpPattern extends string, Flags extends Flag[], ReplaceValue extends string, RegExpParsedAST extends any[] = string extends RegExpPattern ? never : ParseRegExp<RegExpPattern>, MatchResult = MatchRegExp<InputString, RegExpParsedAST, Flags[number]>, Match extends any[] = MatchResult extends RegExpMatchResult<{
matched: infer MatchArray extends any[];
namedCaptures: [string, any];
input: infer Input extends string;
restInput: string | undefined;
}, {
index: infer Index extends number;
groups: infer Groups;
input: string;
keys: (...arg: any) => any;
}> ? [...MatchArray, Index, Input, Groups] : never>(this: InputString, regexp: MagicRegExp<`/${RegExpPattern}/${Join<Flags, '', ''>}`, string, Flags>, replaceValue: ReplaceValue | ((...match: Match) => ReplaceValue)): any[] extends RegExpParsedAST ? never : ReplaceWithRegExp<InputString, RegExpParsedAST, ReplaceValue, Flags[number]>;
/** @deprecated String.replaceAll requires global flag to be set. */
replaceAll<R extends MagicRegExp<string, string, never>>(searchValue: R, replaceValue: string | ((substring: string, ...args: any[]) => string)): never;
/** @deprecated String.replaceAll requires global flag to be set. */
replaceAll<R extends MagicRegExp<string, string, Exclude<Flag, 'g'>[]>>(searchValue: R, replaceValue: string | ((substring: string, ...args: any[]) => string)): never;
}
}
export { Flag, type MagicRegExp, createRegExp };

10
node_modules/magic-regexp/dist/further-magic.mjs generated vendored Normal file
View File

@@ -0,0 +1,10 @@
import { e as exactly } from './shared/magic-regexp.DKp_q_HX.mjs';
export { f as anyOf, q as carriageReturn, c as caseInsensitive, h as char, a as charIn, b as charNotIn, l as digit, d as dotAll, g as global, o as letter, p as linefeed, v as maybe, m as multiline, r as not, x as oneOrMore, s as sticky, t as tab, u as unicode, n as whitespace, w as withIndices, i as word, k as wordBoundary, j as wordChar } from './shared/magic-regexp.DKp_q_HX.mjs';
export { spreadRegExpIterator, spreadRegExpMatchArray } from 'type-level-regexp/regexp';
const createRegExp = (...inputs) => {
const flags = inputs.length > 1 && (Array.isArray(inputs[inputs.length - 1]) || inputs[inputs.length - 1] instanceof Set) ? inputs.pop() : void 0;
return new RegExp(exactly(...inputs).toString(), [...flags || ""].join(""));
};
export { createRegExp, exactly };

34
node_modules/magic-regexp/dist/index.cjs generated vendored Normal file
View File

@@ -0,0 +1,34 @@
'use strict';
const flags = require('./shared/magic-regexp.DNdg2jII.cjs');
const createRegExp = (...inputs) => {
const flags$1 = inputs.length > 1 && (Array.isArray(inputs[inputs.length - 1]) || inputs[inputs.length - 1] instanceof Set) ? inputs.pop() : void 0;
return new RegExp(flags.exactly(...inputs).toString(), [...flags$1 || ""].join(""));
};
exports.anyOf = flags.anyOf;
exports.carriageReturn = flags.carriageReturn;
exports.caseInsensitive = flags.caseInsensitive;
exports.char = flags.char;
exports.charIn = flags.charIn;
exports.charNotIn = flags.charNotIn;
exports.digit = flags.digit;
exports.dotAll = flags.dotAll;
exports.exactly = flags.exactly;
exports.global = flags.global;
exports.letter = flags.letter;
exports.linefeed = flags.linefeed;
exports.maybe = flags.maybe;
exports.multiline = flags.multiline;
exports.not = flags.not;
exports.oneOrMore = flags.oneOrMore;
exports.sticky = flags.sticky;
exports.tab = flags.tab;
exports.unicode = flags.unicode;
exports.whitespace = flags.whitespace;
exports.withIndices = flags.withIndices;
exports.word = flags.word;
exports.wordBoundary = flags.wordBoundary;
exports.wordChar = flags.wordChar;
exports.createRegExp = createRegExp;

27
node_modules/magic-regexp/dist/index.d.cts generated vendored Normal file
View File

@@ -0,0 +1,27 @@
import { M as MagicRegExp, F as Flag, a as MagicRegExpMatchArray, I as InputSource, J as Join, b as MapToValues, c as MapToGroups, d as MapToCapturedGroupsArr, U as UnionToTuple } from './shared/magic-regexp.Cp7m-ws-.cjs';
export { h as Input, D as MapToStringCapturedBy, S as StringCapturedBy, k as anyOf, y as carriageReturn, e as caseInsensitive, l as char, i as charIn, j as charNotIn, q as digit, f as dotAll, B as exactly, g as global, t as letter, x as linefeed, A as maybe, m as multiline, z as not, C as oneOrMore, s as sticky, v as tab, u as unicode, r as whitespace, w as withIndices, n as word, p as wordBoundary, o as wordChar } from './shared/magic-regexp.Cp7m-ws-.cjs';
declare const createRegExp: {
/** Create Magic RegExp from Input helpers and string (string will be sanitized) */
<Inputs extends InputSource[]>(...inputs: Inputs): MagicRegExp<`/${Join<MapToValues<Inputs>, '', ''>}/`, MapToGroups<Inputs>, MapToCapturedGroupsArr<Inputs>, never>;
<Inputs extends InputSource[], Flags extends Flag[] = never[]>(...inputs: [...Inputs, [...Flags]]): MagicRegExp<`/${Join<MapToValues<Inputs>, '', ''>}/${Join<Flags, '', ''>}`, MapToGroups<Inputs>, MapToCapturedGroupsArr<Inputs>, Flags[number]>;
<Inputs extends InputSource[], FlagUnion extends Flag = never, Flags extends Flag[] = UnionToTuple<FlagUnion> extends infer F extends Flag[] ? F : never>(...inputs: [...Inputs, Set<FlagUnion>]): MagicRegExp<`/${Join<MapToValues<Inputs>, '', ''>}/${Join<Flags, '', ''>}`, MapToGroups<Inputs>, MapToCapturedGroupsArr<Inputs>, Flags[number]>;
};
declare global {
interface String {
match<R extends MagicRegExp<string, string, (string | undefined)[], Exclude<Flag, 'g'>>>(regexp: R): MagicRegExpMatchArray<R> | null;
match<R extends MagicRegExp<string, string, (string | undefined)[], 'g'>>(regexp: R): string[] | null;
/** @deprecated String.matchAll requires global flag to be set. */
matchAll<R extends MagicRegExp<string, string, (string | undefined)[], never>>(regexp: R): never;
/** @deprecated String.matchAll requires global flag to be set. */
matchAll<R extends MagicRegExp<string, string, (string | undefined)[], Exclude<Flag, 'g'>>>(regexp: R): never;
matchAll<R extends MagicRegExp<string, string, (string | undefined)[], string>>(regexp: R): IterableIterator<MagicRegExpMatchArray<R>>;
/** @deprecated String.replaceAll requires global flag to be set. */
replaceAll<R extends MagicRegExp<string, string, (string | undefined)[], never>>(searchValue: R, replaceValue: string | ((substring: string, ...args: any[]) => string)): never;
/** @deprecated String.replaceAll requires global flag to be set. */
replaceAll<R extends MagicRegExp<string, string, (string | undefined)[], Exclude<Flag, 'g'>>>(searchValue: R, replaceValue: string | ((substring: string, ...args: any[]) => string)): never;
}
}
export { Flag, MagicRegExp, MagicRegExpMatchArray, createRegExp };

27
node_modules/magic-regexp/dist/index.d.mts generated vendored Normal file
View File

@@ -0,0 +1,27 @@
import { M as MagicRegExp, F as Flag, a as MagicRegExpMatchArray, I as InputSource, J as Join, b as MapToValues, c as MapToGroups, d as MapToCapturedGroupsArr, U as UnionToTuple } from './shared/magic-regexp.Cp7m-ws-.mjs';
export { h as Input, D as MapToStringCapturedBy, S as StringCapturedBy, k as anyOf, y as carriageReturn, e as caseInsensitive, l as char, i as charIn, j as charNotIn, q as digit, f as dotAll, B as exactly, g as global, t as letter, x as linefeed, A as maybe, m as multiline, z as not, C as oneOrMore, s as sticky, v as tab, u as unicode, r as whitespace, w as withIndices, n as word, p as wordBoundary, o as wordChar } from './shared/magic-regexp.Cp7m-ws-.mjs';
declare const createRegExp: {
/** Create Magic RegExp from Input helpers and string (string will be sanitized) */
<Inputs extends InputSource[]>(...inputs: Inputs): MagicRegExp<`/${Join<MapToValues<Inputs>, '', ''>}/`, MapToGroups<Inputs>, MapToCapturedGroupsArr<Inputs>, never>;
<Inputs extends InputSource[], Flags extends Flag[] = never[]>(...inputs: [...Inputs, [...Flags]]): MagicRegExp<`/${Join<MapToValues<Inputs>, '', ''>}/${Join<Flags, '', ''>}`, MapToGroups<Inputs>, MapToCapturedGroupsArr<Inputs>, Flags[number]>;
<Inputs extends InputSource[], FlagUnion extends Flag = never, Flags extends Flag[] = UnionToTuple<FlagUnion> extends infer F extends Flag[] ? F : never>(...inputs: [...Inputs, Set<FlagUnion>]): MagicRegExp<`/${Join<MapToValues<Inputs>, '', ''>}/${Join<Flags, '', ''>}`, MapToGroups<Inputs>, MapToCapturedGroupsArr<Inputs>, Flags[number]>;
};
declare global {
interface String {
match<R extends MagicRegExp<string, string, (string | undefined)[], Exclude<Flag, 'g'>>>(regexp: R): MagicRegExpMatchArray<R> | null;
match<R extends MagicRegExp<string, string, (string | undefined)[], 'g'>>(regexp: R): string[] | null;
/** @deprecated String.matchAll requires global flag to be set. */
matchAll<R extends MagicRegExp<string, string, (string | undefined)[], never>>(regexp: R): never;
/** @deprecated String.matchAll requires global flag to be set. */
matchAll<R extends MagicRegExp<string, string, (string | undefined)[], Exclude<Flag, 'g'>>>(regexp: R): never;
matchAll<R extends MagicRegExp<string, string, (string | undefined)[], string>>(regexp: R): IterableIterator<MagicRegExpMatchArray<R>>;
/** @deprecated String.replaceAll requires global flag to be set. */
replaceAll<R extends MagicRegExp<string, string, (string | undefined)[], never>>(searchValue: R, replaceValue: string | ((substring: string, ...args: any[]) => string)): never;
/** @deprecated String.replaceAll requires global flag to be set. */
replaceAll<R extends MagicRegExp<string, string, (string | undefined)[], Exclude<Flag, 'g'>>>(searchValue: R, replaceValue: string | ((substring: string, ...args: any[]) => string)): never;
}
}
export { Flag, MagicRegExp, MagicRegExpMatchArray, createRegExp };

27
node_modules/magic-regexp/dist/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1,27 @@
import { M as MagicRegExp, F as Flag, a as MagicRegExpMatchArray, I as InputSource, J as Join, b as MapToValues, c as MapToGroups, d as MapToCapturedGroupsArr, U as UnionToTuple } from './shared/magic-regexp.Cp7m-ws-.js';
export { h as Input, D as MapToStringCapturedBy, S as StringCapturedBy, k as anyOf, y as carriageReturn, e as caseInsensitive, l as char, i as charIn, j as charNotIn, q as digit, f as dotAll, B as exactly, g as global, t as letter, x as linefeed, A as maybe, m as multiline, z as not, C as oneOrMore, s as sticky, v as tab, u as unicode, r as whitespace, w as withIndices, n as word, p as wordBoundary, o as wordChar } from './shared/magic-regexp.Cp7m-ws-.js';
declare const createRegExp: {
/** Create Magic RegExp from Input helpers and string (string will be sanitized) */
<Inputs extends InputSource[]>(...inputs: Inputs): MagicRegExp<`/${Join<MapToValues<Inputs>, '', ''>}/`, MapToGroups<Inputs>, MapToCapturedGroupsArr<Inputs>, never>;
<Inputs extends InputSource[], Flags extends Flag[] = never[]>(...inputs: [...Inputs, [...Flags]]): MagicRegExp<`/${Join<MapToValues<Inputs>, '', ''>}/${Join<Flags, '', ''>}`, MapToGroups<Inputs>, MapToCapturedGroupsArr<Inputs>, Flags[number]>;
<Inputs extends InputSource[], FlagUnion extends Flag = never, Flags extends Flag[] = UnionToTuple<FlagUnion> extends infer F extends Flag[] ? F : never>(...inputs: [...Inputs, Set<FlagUnion>]): MagicRegExp<`/${Join<MapToValues<Inputs>, '', ''>}/${Join<Flags, '', ''>}`, MapToGroups<Inputs>, MapToCapturedGroupsArr<Inputs>, Flags[number]>;
};
declare global {
interface String {
match<R extends MagicRegExp<string, string, (string | undefined)[], Exclude<Flag, 'g'>>>(regexp: R): MagicRegExpMatchArray<R> | null;
match<R extends MagicRegExp<string, string, (string | undefined)[], 'g'>>(regexp: R): string[] | null;
/** @deprecated String.matchAll requires global flag to be set. */
matchAll<R extends MagicRegExp<string, string, (string | undefined)[], never>>(regexp: R): never;
/** @deprecated String.matchAll requires global flag to be set. */
matchAll<R extends MagicRegExp<string, string, (string | undefined)[], Exclude<Flag, 'g'>>>(regexp: R): never;
matchAll<R extends MagicRegExp<string, string, (string | undefined)[], string>>(regexp: R): IterableIterator<MagicRegExpMatchArray<R>>;
/** @deprecated String.replaceAll requires global flag to be set. */
replaceAll<R extends MagicRegExp<string, string, (string | undefined)[], never>>(searchValue: R, replaceValue: string | ((substring: string, ...args: any[]) => string)): never;
/** @deprecated String.replaceAll requires global flag to be set. */
replaceAll<R extends MagicRegExp<string, string, (string | undefined)[], Exclude<Flag, 'g'>>>(searchValue: R, replaceValue: string | ((substring: string, ...args: any[]) => string)): never;
}
}
export { Flag, MagicRegExp, MagicRegExpMatchArray, createRegExp };

9
node_modules/magic-regexp/dist/index.mjs generated vendored Normal file
View File

@@ -0,0 +1,9 @@
import { e as exactly } from './shared/magic-regexp.DKp_q_HX.mjs';
export { f as anyOf, q as carriageReturn, c as caseInsensitive, h as char, a as charIn, b as charNotIn, l as digit, d as dotAll, g as global, o as letter, p as linefeed, v as maybe, m as multiline, r as not, x as oneOrMore, s as sticky, t as tab, u as unicode, n as whitespace, w as withIndices, i as word, k as wordBoundary, j as wordChar } from './shared/magic-regexp.DKp_q_HX.mjs';
const createRegExp = (...inputs) => {
const flags = inputs.length > 1 && (Array.isArray(inputs[inputs.length - 1]) || inputs[inputs.length - 1] instanceof Set) ? inputs.pop() : void 0;
return new RegExp(exactly(...inputs).toString(), [...flags || ""].join(""));
};
export { createRegExp, exactly };

View File

@@ -0,0 +1,224 @@
type Flag = 'd' | 'g' | 'i' | 'm' | 's' | 'u' | 'y';
/** Generate indices for substring matches */
declare const withIndices = "d";
/** Case-insensitive search */
declare const caseInsensitive = "i";
/** Global search */
declare const global = "g";
/** Multi-line search */
declare const multiline = "m";
/** Allows `.` to match newline characters */
declare const dotAll = "s";
/** Treat a pattern as a sequence of unicode code points */
declare const unicode = "u";
/** Perform a "sticky" search that matches starting at the current position in the target string */
declare const sticky = "y";
type Join<T extends string[], Prefix extends string = '', Joiner extends string = '|'> = T extends [infer F, ...infer R] ? F extends string ? `${Prefix}${F}${R extends string[] ? Join<R, Joiner, Joiner> : ''}` : '' : '';
type UnionToIntersection<Union> = (Union extends Union ? (a: Union) => any : never) extends (a: infer I) => any ? I : never;
type UnionToTuple<Union, Tuple extends any[] = []> = UnionToIntersection<Union extends any ? () => Union : never> extends () => infer Item ? UnionToTuple<Exclude<Union, Item>, [...Tuple, Item]> : Tuple;
declare const NamedGroupsS: unique symbol;
declare const ValueS: unique symbol;
declare const CapturedGroupsArrS: unique symbol;
declare const FlagsS: unique symbol;
type MagicRegExp<Value extends string, NamedGroups extends string | never = never, CapturedGroupsArr extends (string | undefined)[] = [], Flags extends string | never = never> = RegExp & {
[NamedGroupsS]: NamedGroups;
[CapturedGroupsArrS]: CapturedGroupsArr;
[ValueS]: Value;
[FlagsS]: Flags;
};
type ExtractGroups<T extends MagicRegExp<string, string, (string | undefined)[], string>> = T extends MagicRegExp<string, infer V, (string | undefined)[], string> ? V : never;
type StringWithHint<S extends string> = string & {
_capturedBy: S;
};
type StringCapturedBy<S extends string> = StringWithHint<S>;
type MapToStringCapturedBy<Ar extends (string | undefined)[]> = {
[K in keyof Ar]: Ar[K] extends string ? StringCapturedBy<Ar[K]> | undefined : undefined;
};
type MagicRegExpMatchArray<T extends MagicRegExp<string, string, any[], string>> = Omit<RegExpMatchArray, 'groups'> & {
groups: Record<ExtractGroups<T>, string | undefined>;
} & {
[index: number | string | symbol]: never;
} & (T extends MagicRegExp<string, string, infer CapturedGroupsArr, string> ? readonly [string | undefined, ...MapToStringCapturedBy<CapturedGroupsArr>] : {});
type IfUnwrapped<Value extends string, Yes, No> = Value extends `(${string})` ? No : StripEscapes<Value> extends `${infer A}${infer B}` ? A extends '' ? No : B extends '' ? No : Yes : never;
/** This matches any character in the string provided */
declare const charIn: (<T extends string>(chars: T) => CharInput<Escape<T, "^" | "]" | "\\" | "-">>) & CharInput<"">;
/** This matches any character that is not in the string provided */
declare const charNotIn: (<T extends string>(chars: T) => CharInput<`^${Escape<T, "^" | "]" | "\\" | "-">}`>) & CharInput<"^">;
/**
* This takes a variable number of inputs and matches any of them
* @example
* anyOf('foo', maybe('bar'), 'baz') // => /(?:foo|(?:bar)?|baz)/
* @argument inputs - arbitrary number of `string` or `Input`, where `string` will be escaped
*/
declare function anyOf<Inputs extends InputSource[]>(...inputs: Inputs): Input<`(?:${Join<MapToValues<Inputs>>})`, MapToGroups<Inputs>, MapToCapturedGroupsArr<Inputs>>;
declare const char: Input<".", never, []>;
declare const word: Input<"\\b\\w+\\b", never, []>;
declare const wordChar: Input<"\\w", never, []>;
declare const wordBoundary: Input<"\\b", never, []>;
declare const digit: Input<"\\d", never, []>;
declare const whitespace: Input<"\\s", never, []>;
declare const letter: Input<"[a-zA-Z]", never, []> & {
lowercase: Input<"[a-z]", never, []>;
uppercase: Input<"[A-Z]", never, []>;
};
declare const tab: Input<"\\t", never, []>;
declare const linefeed: Input<"\\n", never, []>;
declare const carriageReturn: Input<"\\r", never, []>;
declare const not: {
word: Input<"\\W+", never, []>;
wordChar: Input<"\\W", never, []>;
wordBoundary: Input<"\\B", never, []>;
digit: Input<"\\D", never, []>;
whitespace: Input<"\\S", never, []>;
letter: Input<"[^a-zA-Z]", never, []> & {
lowercase: Input<"[^a-z]", never, []>;
uppercase: Input<"[^A-Z]", never, []>;
};
tab: Input<"[^\\t]", never, []>;
linefeed: Input<"[^\\n]", never, []>;
carriageReturn: Input<"[^\\r]", never, []>;
};
/**
* Equivalent to `?` - takes a variable number of inputs and marks them as optional
* @example
* maybe('foo', exactly('ba?r')) // => /(?:fooba\?r)?/
* @argument inputs - arbitrary number of `string` or `Input`, where `string` will be escaped
*/
declare function maybe<Inputs extends InputSource[], Value extends string = Join<MapToValues<Inputs>, '', ''>>(...inputs: Inputs): Input<IfUnwrapped<Value, `(?:${Value})?`, `${Value}?`>, MapToGroups<Inputs>, MapToCapturedGroupsArr<Inputs>>;
/**
* This takes a variable number of inputs and concatenate their patterns, and escapes string inputs to match it exactly
* @example
* exactly('fo?o', maybe('bar')) // => /fo\?o(?:bar)?/
* @argument inputs - arbitrary number of `string` or `Input`, where `string` will be escaped
*/
declare function exactly<Inputs extends InputSource[]>(...inputs: Inputs): Input<Join<MapToValues<Inputs>, '', ''>, MapToGroups<Inputs>, MapToCapturedGroupsArr<Inputs>>;
/**
* Equivalent to `+` - this takes a variable number of inputs and marks them as repeatable, any number of times but at least once
* @example
* oneOrMore('foo', maybe('bar')) // => /(?:foo(?:bar)?)+/
* @argument inputs - arbitrary number of `string` or `Input`, where `string` will be escaped
*/
declare function oneOrMore<Inputs extends InputSource[], Value extends string = Join<MapToValues<Inputs>, '', ''>>(...inputs: Inputs): Input<IfUnwrapped<Value, `(?:${Value})+`, `${Value}+`>, MapToGroups<Inputs>, MapToCapturedGroupsArr<Inputs>>;
type Escape<T extends string, EscapeChar extends string> = T extends `${infer Start}${EscapeChar}${string}` ? Start extends `${string}${EscapeChar}${string}` ? never : T extends `${Start}${infer Char}${string}` ? Char extends EscapeChar ? T extends `${Start}${Char}${infer Rest}` ? `${Start}\\${Char}${Escape<Rest, EscapeChar>}` : never : never : never : T;
type EscapeChar<T extends string> = Escape<T, '\\' | '^' | '-' | ']'>;
type StripEscapes<T extends string> = T extends `${infer A}\\${infer B}` ? `${A}${B}` : T;
type ExactEscapeChar = '.' | '*' | '+' | '?' | '^' | '$' | '{' | '}' | '(' | ')' | '|' | '[' | ']' | '/';
type GetValue<T extends InputSource> = T extends string ? Escape<T, ExactEscapeChar> : T extends Input<infer R> ? R : never;
interface Input<V extends string, G extends string = never, C extends (string | undefined)[] = []> {
/**
* this takes a variable number of inputs and adds them as new pattern to the current input, or you can use `and.referenceTo(groupName)` to adds a new pattern referencing to a named group
* @example
* exactly('foo').and('bar', maybe('baz')) // => /foobar(?:baz)?/
* @argument inputs - arbitrary number of `string` or `Input`, where `string` will be escaped
*/
and: {
<I extends InputSource[], CG extends any[] = MapToCapturedGroupsArr<I>>(...inputs: I): Input<`${V}${Join<MapToValues<I>, '', ''>}`, G | MapToGroups<I>, [...C, ...CG]>;
/** this adds a new pattern to the current input, with the pattern reference to a named group. */
referenceTo: <N extends G>(groupName: N) => Input<`${V}\\k<${N}>`, G, C>;
};
/**
* this takes a variable number of inputs and provides as an alternative to the current input
* @example
* exactly('foo').or('bar', maybe('baz')) // => /foo|bar(?:baz)?/
* @argument inputs - arbitrary number of `string` or `Input`, where `string` will be escaped
*/
or: <I extends InputSource[], CG extends any[] = MapToCapturedGroupsArr<I>>(...inputs: I) => Input<`(?:${V}|${Join<MapToValues<I>, '', ''>})`, G | MapToGroups<I>, [...C, ...CG]>;
/**
* this takes a variable number of inputs and activate a positive lookbehind. Make sure to check [browser support](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#browser_compatibility) as not all browsers support lookbehinds (notably Safari)
* @example
* exactly('foo').after('bar', maybe('baz')) // => /(?<=bar(?:baz)?)foo/
* @argument inputs - arbitrary number of `string` or `Input`, where `string` will be escaped
*/
after: <I extends InputSource[], CG extends any[] = MapToCapturedGroupsArr<I>>(...inputs: I) => Input<`(?<=${Join<MapToValues<I>, '', ''>})${V}`, G | MapToGroups<I>, [...CG, ...C]>;
/**
* this takes a variable number of inputs and activate a positive lookahead
* @example
* exactly('foo').before('bar', maybe('baz')) // => /foo(?=bar(?:baz)?)/
* @argument inputs - arbitrary number of `string` or `Input`, where `string` will be escaped
*/
before: <I extends InputSource[], CG extends any[] = MapToCapturedGroupsArr<I>>(...inputs: I) => Input<`${V}(?=${Join<MapToValues<I>, '', ''>})`, G, [...C, ...CG]>;
/**
* these takes a variable number of inputs and activate a negative lookbehind. Make sure to check [browser support](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#browser_compatibility) as not all browsers support lookbehinds (notably Safari)
* @example
* exactly('foo').notAfter('bar', maybe('baz')) // => /(?<!bar(?:baz)?)foo/
* @argument inputs - arbitrary number of `string` or `Input`, where `string` will be escaped
*/
notAfter: <I extends InputSource[], CG extends any[] = MapToCapturedGroupsArr<I, true>>(...inputs: I) => Input<`(?<!${Join<MapToValues<I>, '', ''>})${V}`, G, [...CG, ...C]>;
/**
* this takes a variable number of inputs and activate a negative lookahead
* @example
* exactly('foo').notBefore('bar', maybe('baz')) // => /foo(?!bar(?:baz)?)/
* @argument inputs - arbitrary number of `string` or `Input`, where `string` will be escaped
*/
notBefore: <I extends InputSource[], CG extends any[] = MapToCapturedGroupsArr<I, true>>(...inputs: I) => Input<`${V}(?!${Join<MapToValues<I>, '', ''>})`, G, [...C, ...CG]>;
/** repeat the previous pattern an exact number of times */
times: {
<N extends number, NV extends string = IfUnwrapped<V, `(?:${V}){${N}}`, `${V}{${N}}`>>(number: N): Input<NV, G, C>;
/** specify that the expression can repeat any number of times, _including none_ */
any: <NV extends string = IfUnwrapped<V, `(?:${V})*`, `${V}*`>>() => Input<NV, G, C>;
/** specify that the expression must occur at least `N` times */
atLeast: <N extends number, NV extends string = IfUnwrapped<V, `(?:${V}){${N},}`, `${V}{${N},}`>>(number: N) => Input<NV, G, C>;
/** specify that the expression must occur at most `N` times */
atMost: <N extends number, NV extends string = IfUnwrapped<V, `(?:${V}){0,${N}}`, `${V}{0,${N}}`>>(number: N) => Input<NV, G, C>;
/** specify a range of times to repeat the previous pattern */
between: <Min extends number, Max extends number, NV extends string = IfUnwrapped<V, `(?:${V}){${Min},${Max}}`, `${V}{${Min},${Max}}`>>(min: Min, max: Max) => Input<NV, G, C>;
};
/** this defines the entire input so far as a named capture group. You will get type safety when using the resulting RegExp with `String.match()`. Alias for `groupedAs` */
as: <K extends string>(key: K) => Input<V extends `(?:${infer S})` ? `(?<${K}>${S})` : `(?<${K}>${V})`, G | K, [
V extends `(?:${infer S})` ? `(?<${K}>${S})` : `(?<${K}>${V})`,
...C
]>;
/** this defines the entire input so far as a named capture group. You will get type safety when using the resulting RegExp with `String.match()` */
groupedAs: <K extends string>(key: K) => Input<V extends `(?:${infer S})` ? `(?<${K}>${S})` : `(?<${K}>${V})`, G | K, [
V extends `(?:${infer S})` ? `(?<${K}>${S})` : `(?<${K}>${V})`,
...C
]>;
/** this capture the entire input so far as an anonymous group */
grouped: () => Input<V extends `(?:${infer S})${infer E}` ? `(${S})${E}` : `(${V})`, G, [
V extends `(?:${infer S})${'' | '?' | '+' | '*' | `{${string}}`}` ? `(${S})` : `(${V})`,
...C
]>;
/** this allows you to match beginning/ends of lines with `at.lineStart()` and `at.lineEnd()` */
at: {
lineStart: () => Input<`^${V}`, G, C>;
lineEnd: () => Input<`${V}$`, G, C>;
};
/** this allows you to mark the input so far as optional */
optionally: <NV extends string = IfUnwrapped<V, `(?:${V})?`, `${V}?`>>() => Input<NV, G, C>;
toString: () => string;
}
interface CharInput<T extends string> extends Input<`[${T}]`> {
orChar: (<Or extends string>(chars: Or) => CharInput<`${T}${EscapeChar<Or>}`>) & CharInput<T>;
from: <From extends string, To extends string>(charFrom: From, charTo: To) => CharInput<`${T}${EscapeChar<From>}-${EscapeChar<To>}`>;
}
type InputSource<S extends string = string, T extends string = never> = S | Input<any, T>;
type MapToValues<T extends InputSource[]> = T extends [
infer First,
...infer Rest extends InputSource[]
] ? First extends InputSource ? [GetValue<First>, ...MapToValues<Rest>] : [] : [];
type MapToGroups<T extends InputSource[]> = T extends [
infer First,
...infer Rest extends InputSource[]
] ? First extends Input<any, infer K> ? K | MapToGroups<Rest> : MapToGroups<Rest> : never;
type MapToCapturedGroupsArr<Inputs extends any[], MapToUndefined extends boolean = false, CapturedGroupsArr extends any[] = [], Count extends any[] = []> = Count['length'] extends Inputs['length'] ? CapturedGroupsArr : Inputs[Count['length']] extends Input<any, any, infer CaptureGroups> ? [CaptureGroups] extends [never] ? MapToCapturedGroupsArr<Inputs, MapToUndefined, [...CapturedGroupsArr], [...Count, '']> : MapToUndefined extends true ? MapToCapturedGroupsArr<Inputs, MapToUndefined, [
...CapturedGroupsArr,
undefined
], [
...Count,
''
]> : MapToCapturedGroupsArr<Inputs, MapToUndefined, [
...CapturedGroupsArr,
...CaptureGroups
], [
...Count,
''
]> : MapToCapturedGroupsArr<Inputs, MapToUndefined, [...CapturedGroupsArr], [...Count, '']>;
export { maybe as A, exactly as B, oneOrMore as C, type MapToStringCapturedBy as D, type Flag as F, type InputSource as I, type Join as J, type MagicRegExp as M, type StringCapturedBy as S, type UnionToTuple as U, type MagicRegExpMatchArray as a, type MapToValues as b, type MapToGroups as c, type MapToCapturedGroupsArr as d, caseInsensitive as e, dotAll as f, global as g, type Input as h, charIn as i, charNotIn as j, anyOf as k, char as l, multiline as m, word as n, wordChar as o, wordBoundary as p, digit as q, whitespace as r, sticky as s, letter as t, unicode as u, tab as v, withIndices as w, linefeed as x, carriageReturn as y, not as z };

View File

@@ -0,0 +1,224 @@
type Flag = 'd' | 'g' | 'i' | 'm' | 's' | 'u' | 'y';
/** Generate indices for substring matches */
declare const withIndices = "d";
/** Case-insensitive search */
declare const caseInsensitive = "i";
/** Global search */
declare const global = "g";
/** Multi-line search */
declare const multiline = "m";
/** Allows `.` to match newline characters */
declare const dotAll = "s";
/** Treat a pattern as a sequence of unicode code points */
declare const unicode = "u";
/** Perform a "sticky" search that matches starting at the current position in the target string */
declare const sticky = "y";
type Join<T extends string[], Prefix extends string = '', Joiner extends string = '|'> = T extends [infer F, ...infer R] ? F extends string ? `${Prefix}${F}${R extends string[] ? Join<R, Joiner, Joiner> : ''}` : '' : '';
type UnionToIntersection<Union> = (Union extends Union ? (a: Union) => any : never) extends (a: infer I) => any ? I : never;
type UnionToTuple<Union, Tuple extends any[] = []> = UnionToIntersection<Union extends any ? () => Union : never> extends () => infer Item ? UnionToTuple<Exclude<Union, Item>, [...Tuple, Item]> : Tuple;
declare const NamedGroupsS: unique symbol;
declare const ValueS: unique symbol;
declare const CapturedGroupsArrS: unique symbol;
declare const FlagsS: unique symbol;
type MagicRegExp<Value extends string, NamedGroups extends string | never = never, CapturedGroupsArr extends (string | undefined)[] = [], Flags extends string | never = never> = RegExp & {
[NamedGroupsS]: NamedGroups;
[CapturedGroupsArrS]: CapturedGroupsArr;
[ValueS]: Value;
[FlagsS]: Flags;
};
type ExtractGroups<T extends MagicRegExp<string, string, (string | undefined)[], string>> = T extends MagicRegExp<string, infer V, (string | undefined)[], string> ? V : never;
type StringWithHint<S extends string> = string & {
_capturedBy: S;
};
type StringCapturedBy<S extends string> = StringWithHint<S>;
type MapToStringCapturedBy<Ar extends (string | undefined)[]> = {
[K in keyof Ar]: Ar[K] extends string ? StringCapturedBy<Ar[K]> | undefined : undefined;
};
type MagicRegExpMatchArray<T extends MagicRegExp<string, string, any[], string>> = Omit<RegExpMatchArray, 'groups'> & {
groups: Record<ExtractGroups<T>, string | undefined>;
} & {
[index: number | string | symbol]: never;
} & (T extends MagicRegExp<string, string, infer CapturedGroupsArr, string> ? readonly [string | undefined, ...MapToStringCapturedBy<CapturedGroupsArr>] : {});
type IfUnwrapped<Value extends string, Yes, No> = Value extends `(${string})` ? No : StripEscapes<Value> extends `${infer A}${infer B}` ? A extends '' ? No : B extends '' ? No : Yes : never;
/** This matches any character in the string provided */
declare const charIn: (<T extends string>(chars: T) => CharInput<Escape<T, "^" | "]" | "\\" | "-">>) & CharInput<"">;
/** This matches any character that is not in the string provided */
declare const charNotIn: (<T extends string>(chars: T) => CharInput<`^${Escape<T, "^" | "]" | "\\" | "-">}`>) & CharInput<"^">;
/**
* This takes a variable number of inputs and matches any of them
* @example
* anyOf('foo', maybe('bar'), 'baz') // => /(?:foo|(?:bar)?|baz)/
* @argument inputs - arbitrary number of `string` or `Input`, where `string` will be escaped
*/
declare function anyOf<Inputs extends InputSource[]>(...inputs: Inputs): Input<`(?:${Join<MapToValues<Inputs>>})`, MapToGroups<Inputs>, MapToCapturedGroupsArr<Inputs>>;
declare const char: Input<".", never, []>;
declare const word: Input<"\\b\\w+\\b", never, []>;
declare const wordChar: Input<"\\w", never, []>;
declare const wordBoundary: Input<"\\b", never, []>;
declare const digit: Input<"\\d", never, []>;
declare const whitespace: Input<"\\s", never, []>;
declare const letter: Input<"[a-zA-Z]", never, []> & {
lowercase: Input<"[a-z]", never, []>;
uppercase: Input<"[A-Z]", never, []>;
};
declare const tab: Input<"\\t", never, []>;
declare const linefeed: Input<"\\n", never, []>;
declare const carriageReturn: Input<"\\r", never, []>;
declare const not: {
word: Input<"\\W+", never, []>;
wordChar: Input<"\\W", never, []>;
wordBoundary: Input<"\\B", never, []>;
digit: Input<"\\D", never, []>;
whitespace: Input<"\\S", never, []>;
letter: Input<"[^a-zA-Z]", never, []> & {
lowercase: Input<"[^a-z]", never, []>;
uppercase: Input<"[^A-Z]", never, []>;
};
tab: Input<"[^\\t]", never, []>;
linefeed: Input<"[^\\n]", never, []>;
carriageReturn: Input<"[^\\r]", never, []>;
};
/**
* Equivalent to `?` - takes a variable number of inputs and marks them as optional
* @example
* maybe('foo', exactly('ba?r')) // => /(?:fooba\?r)?/
* @argument inputs - arbitrary number of `string` or `Input`, where `string` will be escaped
*/
declare function maybe<Inputs extends InputSource[], Value extends string = Join<MapToValues<Inputs>, '', ''>>(...inputs: Inputs): Input<IfUnwrapped<Value, `(?:${Value})?`, `${Value}?`>, MapToGroups<Inputs>, MapToCapturedGroupsArr<Inputs>>;
/**
* This takes a variable number of inputs and concatenate their patterns, and escapes string inputs to match it exactly
* @example
* exactly('fo?o', maybe('bar')) // => /fo\?o(?:bar)?/
* @argument inputs - arbitrary number of `string` or `Input`, where `string` will be escaped
*/
declare function exactly<Inputs extends InputSource[]>(...inputs: Inputs): Input<Join<MapToValues<Inputs>, '', ''>, MapToGroups<Inputs>, MapToCapturedGroupsArr<Inputs>>;
/**
* Equivalent to `+` - this takes a variable number of inputs and marks them as repeatable, any number of times but at least once
* @example
* oneOrMore('foo', maybe('bar')) // => /(?:foo(?:bar)?)+/
* @argument inputs - arbitrary number of `string` or `Input`, where `string` will be escaped
*/
declare function oneOrMore<Inputs extends InputSource[], Value extends string = Join<MapToValues<Inputs>, '', ''>>(...inputs: Inputs): Input<IfUnwrapped<Value, `(?:${Value})+`, `${Value}+`>, MapToGroups<Inputs>, MapToCapturedGroupsArr<Inputs>>;
type Escape<T extends string, EscapeChar extends string> = T extends `${infer Start}${EscapeChar}${string}` ? Start extends `${string}${EscapeChar}${string}` ? never : T extends `${Start}${infer Char}${string}` ? Char extends EscapeChar ? T extends `${Start}${Char}${infer Rest}` ? `${Start}\\${Char}${Escape<Rest, EscapeChar>}` : never : never : never : T;
type EscapeChar<T extends string> = Escape<T, '\\' | '^' | '-' | ']'>;
type StripEscapes<T extends string> = T extends `${infer A}\\${infer B}` ? `${A}${B}` : T;
type ExactEscapeChar = '.' | '*' | '+' | '?' | '^' | '$' | '{' | '}' | '(' | ')' | '|' | '[' | ']' | '/';
type GetValue<T extends InputSource> = T extends string ? Escape<T, ExactEscapeChar> : T extends Input<infer R> ? R : never;
interface Input<V extends string, G extends string = never, C extends (string | undefined)[] = []> {
/**
* this takes a variable number of inputs and adds them as new pattern to the current input, or you can use `and.referenceTo(groupName)` to adds a new pattern referencing to a named group
* @example
* exactly('foo').and('bar', maybe('baz')) // => /foobar(?:baz)?/
* @argument inputs - arbitrary number of `string` or `Input`, where `string` will be escaped
*/
and: {
<I extends InputSource[], CG extends any[] = MapToCapturedGroupsArr<I>>(...inputs: I): Input<`${V}${Join<MapToValues<I>, '', ''>}`, G | MapToGroups<I>, [...C, ...CG]>;
/** this adds a new pattern to the current input, with the pattern reference to a named group. */
referenceTo: <N extends G>(groupName: N) => Input<`${V}\\k<${N}>`, G, C>;
};
/**
* this takes a variable number of inputs and provides as an alternative to the current input
* @example
* exactly('foo').or('bar', maybe('baz')) // => /foo|bar(?:baz)?/
* @argument inputs - arbitrary number of `string` or `Input`, where `string` will be escaped
*/
or: <I extends InputSource[], CG extends any[] = MapToCapturedGroupsArr<I>>(...inputs: I) => Input<`(?:${V}|${Join<MapToValues<I>, '', ''>})`, G | MapToGroups<I>, [...C, ...CG]>;
/**
* this takes a variable number of inputs and activate a positive lookbehind. Make sure to check [browser support](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#browser_compatibility) as not all browsers support lookbehinds (notably Safari)
* @example
* exactly('foo').after('bar', maybe('baz')) // => /(?<=bar(?:baz)?)foo/
* @argument inputs - arbitrary number of `string` or `Input`, where `string` will be escaped
*/
after: <I extends InputSource[], CG extends any[] = MapToCapturedGroupsArr<I>>(...inputs: I) => Input<`(?<=${Join<MapToValues<I>, '', ''>})${V}`, G | MapToGroups<I>, [...CG, ...C]>;
/**
* this takes a variable number of inputs and activate a positive lookahead
* @example
* exactly('foo').before('bar', maybe('baz')) // => /foo(?=bar(?:baz)?)/
* @argument inputs - arbitrary number of `string` or `Input`, where `string` will be escaped
*/
before: <I extends InputSource[], CG extends any[] = MapToCapturedGroupsArr<I>>(...inputs: I) => Input<`${V}(?=${Join<MapToValues<I>, '', ''>})`, G, [...C, ...CG]>;
/**
* these takes a variable number of inputs and activate a negative lookbehind. Make sure to check [browser support](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#browser_compatibility) as not all browsers support lookbehinds (notably Safari)
* @example
* exactly('foo').notAfter('bar', maybe('baz')) // => /(?<!bar(?:baz)?)foo/
* @argument inputs - arbitrary number of `string` or `Input`, where `string` will be escaped
*/
notAfter: <I extends InputSource[], CG extends any[] = MapToCapturedGroupsArr<I, true>>(...inputs: I) => Input<`(?<!${Join<MapToValues<I>, '', ''>})${V}`, G, [...CG, ...C]>;
/**
* this takes a variable number of inputs and activate a negative lookahead
* @example
* exactly('foo').notBefore('bar', maybe('baz')) // => /foo(?!bar(?:baz)?)/
* @argument inputs - arbitrary number of `string` or `Input`, where `string` will be escaped
*/
notBefore: <I extends InputSource[], CG extends any[] = MapToCapturedGroupsArr<I, true>>(...inputs: I) => Input<`${V}(?!${Join<MapToValues<I>, '', ''>})`, G, [...C, ...CG]>;
/** repeat the previous pattern an exact number of times */
times: {
<N extends number, NV extends string = IfUnwrapped<V, `(?:${V}){${N}}`, `${V}{${N}}`>>(number: N): Input<NV, G, C>;
/** specify that the expression can repeat any number of times, _including none_ */
any: <NV extends string = IfUnwrapped<V, `(?:${V})*`, `${V}*`>>() => Input<NV, G, C>;
/** specify that the expression must occur at least `N` times */
atLeast: <N extends number, NV extends string = IfUnwrapped<V, `(?:${V}){${N},}`, `${V}{${N},}`>>(number: N) => Input<NV, G, C>;
/** specify that the expression must occur at most `N` times */
atMost: <N extends number, NV extends string = IfUnwrapped<V, `(?:${V}){0,${N}}`, `${V}{0,${N}}`>>(number: N) => Input<NV, G, C>;
/** specify a range of times to repeat the previous pattern */
between: <Min extends number, Max extends number, NV extends string = IfUnwrapped<V, `(?:${V}){${Min},${Max}}`, `${V}{${Min},${Max}}`>>(min: Min, max: Max) => Input<NV, G, C>;
};
/** this defines the entire input so far as a named capture group. You will get type safety when using the resulting RegExp with `String.match()`. Alias for `groupedAs` */
as: <K extends string>(key: K) => Input<V extends `(?:${infer S})` ? `(?<${K}>${S})` : `(?<${K}>${V})`, G | K, [
V extends `(?:${infer S})` ? `(?<${K}>${S})` : `(?<${K}>${V})`,
...C
]>;
/** this defines the entire input so far as a named capture group. You will get type safety when using the resulting RegExp with `String.match()` */
groupedAs: <K extends string>(key: K) => Input<V extends `(?:${infer S})` ? `(?<${K}>${S})` : `(?<${K}>${V})`, G | K, [
V extends `(?:${infer S})` ? `(?<${K}>${S})` : `(?<${K}>${V})`,
...C
]>;
/** this capture the entire input so far as an anonymous group */
grouped: () => Input<V extends `(?:${infer S})${infer E}` ? `(${S})${E}` : `(${V})`, G, [
V extends `(?:${infer S})${'' | '?' | '+' | '*' | `{${string}}`}` ? `(${S})` : `(${V})`,
...C
]>;
/** this allows you to match beginning/ends of lines with `at.lineStart()` and `at.lineEnd()` */
at: {
lineStart: () => Input<`^${V}`, G, C>;
lineEnd: () => Input<`${V}$`, G, C>;
};
/** this allows you to mark the input so far as optional */
optionally: <NV extends string = IfUnwrapped<V, `(?:${V})?`, `${V}?`>>() => Input<NV, G, C>;
toString: () => string;
}
interface CharInput<T extends string> extends Input<`[${T}]`> {
orChar: (<Or extends string>(chars: Or) => CharInput<`${T}${EscapeChar<Or>}`>) & CharInput<T>;
from: <From extends string, To extends string>(charFrom: From, charTo: To) => CharInput<`${T}${EscapeChar<From>}-${EscapeChar<To>}`>;
}
type InputSource<S extends string = string, T extends string = never> = S | Input<any, T>;
type MapToValues<T extends InputSource[]> = T extends [
infer First,
...infer Rest extends InputSource[]
] ? First extends InputSource ? [GetValue<First>, ...MapToValues<Rest>] : [] : [];
type MapToGroups<T extends InputSource[]> = T extends [
infer First,
...infer Rest extends InputSource[]
] ? First extends Input<any, infer K> ? K | MapToGroups<Rest> : MapToGroups<Rest> : never;
type MapToCapturedGroupsArr<Inputs extends any[], MapToUndefined extends boolean = false, CapturedGroupsArr extends any[] = [], Count extends any[] = []> = Count['length'] extends Inputs['length'] ? CapturedGroupsArr : Inputs[Count['length']] extends Input<any, any, infer CaptureGroups> ? [CaptureGroups] extends [never] ? MapToCapturedGroupsArr<Inputs, MapToUndefined, [...CapturedGroupsArr], [...Count, '']> : MapToUndefined extends true ? MapToCapturedGroupsArr<Inputs, MapToUndefined, [
...CapturedGroupsArr,
undefined
], [
...Count,
''
]> : MapToCapturedGroupsArr<Inputs, MapToUndefined, [
...CapturedGroupsArr,
...CaptureGroups
], [
...Count,
''
]> : MapToCapturedGroupsArr<Inputs, MapToUndefined, [...CapturedGroupsArr], [...Count, '']>;
export { maybe as A, exactly as B, oneOrMore as C, type MapToStringCapturedBy as D, type Flag as F, type InputSource as I, type Join as J, type MagicRegExp as M, type StringCapturedBy as S, type UnionToTuple as U, type MagicRegExpMatchArray as a, type MapToValues as b, type MapToGroups as c, type MapToCapturedGroupsArr as d, caseInsensitive as e, dotAll as f, global as g, type Input as h, charIn as i, charNotIn as j, anyOf as k, char as l, multiline as m, word as n, wordChar as o, wordBoundary as p, digit as q, whitespace as r, sticky as s, letter as t, unicode as u, tab as v, withIndices as w, linefeed as x, carriageReturn as y, not as z };

View File

@@ -0,0 +1,224 @@
type Flag = 'd' | 'g' | 'i' | 'm' | 's' | 'u' | 'y';
/** Generate indices for substring matches */
declare const withIndices = "d";
/** Case-insensitive search */
declare const caseInsensitive = "i";
/** Global search */
declare const global = "g";
/** Multi-line search */
declare const multiline = "m";
/** Allows `.` to match newline characters */
declare const dotAll = "s";
/** Treat a pattern as a sequence of unicode code points */
declare const unicode = "u";
/** Perform a "sticky" search that matches starting at the current position in the target string */
declare const sticky = "y";
type Join<T extends string[], Prefix extends string = '', Joiner extends string = '|'> = T extends [infer F, ...infer R] ? F extends string ? `${Prefix}${F}${R extends string[] ? Join<R, Joiner, Joiner> : ''}` : '' : '';
type UnionToIntersection<Union> = (Union extends Union ? (a: Union) => any : never) extends (a: infer I) => any ? I : never;
type UnionToTuple<Union, Tuple extends any[] = []> = UnionToIntersection<Union extends any ? () => Union : never> extends () => infer Item ? UnionToTuple<Exclude<Union, Item>, [...Tuple, Item]> : Tuple;
declare const NamedGroupsS: unique symbol;
declare const ValueS: unique symbol;
declare const CapturedGroupsArrS: unique symbol;
declare const FlagsS: unique symbol;
type MagicRegExp<Value extends string, NamedGroups extends string | never = never, CapturedGroupsArr extends (string | undefined)[] = [], Flags extends string | never = never> = RegExp & {
[NamedGroupsS]: NamedGroups;
[CapturedGroupsArrS]: CapturedGroupsArr;
[ValueS]: Value;
[FlagsS]: Flags;
};
type ExtractGroups<T extends MagicRegExp<string, string, (string | undefined)[], string>> = T extends MagicRegExp<string, infer V, (string | undefined)[], string> ? V : never;
type StringWithHint<S extends string> = string & {
_capturedBy: S;
};
type StringCapturedBy<S extends string> = StringWithHint<S>;
type MapToStringCapturedBy<Ar extends (string | undefined)[]> = {
[K in keyof Ar]: Ar[K] extends string ? StringCapturedBy<Ar[K]> | undefined : undefined;
};
type MagicRegExpMatchArray<T extends MagicRegExp<string, string, any[], string>> = Omit<RegExpMatchArray, 'groups'> & {
groups: Record<ExtractGroups<T>, string | undefined>;
} & {
[index: number | string | symbol]: never;
} & (T extends MagicRegExp<string, string, infer CapturedGroupsArr, string> ? readonly [string | undefined, ...MapToStringCapturedBy<CapturedGroupsArr>] : {});
type IfUnwrapped<Value extends string, Yes, No> = Value extends `(${string})` ? No : StripEscapes<Value> extends `${infer A}${infer B}` ? A extends '' ? No : B extends '' ? No : Yes : never;
/** This matches any character in the string provided */
declare const charIn: (<T extends string>(chars: T) => CharInput<Escape<T, "^" | "]" | "\\" | "-">>) & CharInput<"">;
/** This matches any character that is not in the string provided */
declare const charNotIn: (<T extends string>(chars: T) => CharInput<`^${Escape<T, "^" | "]" | "\\" | "-">}`>) & CharInput<"^">;
/**
* This takes a variable number of inputs and matches any of them
* @example
* anyOf('foo', maybe('bar'), 'baz') // => /(?:foo|(?:bar)?|baz)/
* @argument inputs - arbitrary number of `string` or `Input`, where `string` will be escaped
*/
declare function anyOf<Inputs extends InputSource[]>(...inputs: Inputs): Input<`(?:${Join<MapToValues<Inputs>>})`, MapToGroups<Inputs>, MapToCapturedGroupsArr<Inputs>>;
declare const char: Input<".", never, []>;
declare const word: Input<"\\b\\w+\\b", never, []>;
declare const wordChar: Input<"\\w", never, []>;
declare const wordBoundary: Input<"\\b", never, []>;
declare const digit: Input<"\\d", never, []>;
declare const whitespace: Input<"\\s", never, []>;
declare const letter: Input<"[a-zA-Z]", never, []> & {
lowercase: Input<"[a-z]", never, []>;
uppercase: Input<"[A-Z]", never, []>;
};
declare const tab: Input<"\\t", never, []>;
declare const linefeed: Input<"\\n", never, []>;
declare const carriageReturn: Input<"\\r", never, []>;
declare const not: {
word: Input<"\\W+", never, []>;
wordChar: Input<"\\W", never, []>;
wordBoundary: Input<"\\B", never, []>;
digit: Input<"\\D", never, []>;
whitespace: Input<"\\S", never, []>;
letter: Input<"[^a-zA-Z]", never, []> & {
lowercase: Input<"[^a-z]", never, []>;
uppercase: Input<"[^A-Z]", never, []>;
};
tab: Input<"[^\\t]", never, []>;
linefeed: Input<"[^\\n]", never, []>;
carriageReturn: Input<"[^\\r]", never, []>;
};
/**
* Equivalent to `?` - takes a variable number of inputs and marks them as optional
* @example
* maybe('foo', exactly('ba?r')) // => /(?:fooba\?r)?/
* @argument inputs - arbitrary number of `string` or `Input`, where `string` will be escaped
*/
declare function maybe<Inputs extends InputSource[], Value extends string = Join<MapToValues<Inputs>, '', ''>>(...inputs: Inputs): Input<IfUnwrapped<Value, `(?:${Value})?`, `${Value}?`>, MapToGroups<Inputs>, MapToCapturedGroupsArr<Inputs>>;
/**
* This takes a variable number of inputs and concatenate their patterns, and escapes string inputs to match it exactly
* @example
* exactly('fo?o', maybe('bar')) // => /fo\?o(?:bar)?/
* @argument inputs - arbitrary number of `string` or `Input`, where `string` will be escaped
*/
declare function exactly<Inputs extends InputSource[]>(...inputs: Inputs): Input<Join<MapToValues<Inputs>, '', ''>, MapToGroups<Inputs>, MapToCapturedGroupsArr<Inputs>>;
/**
* Equivalent to `+` - this takes a variable number of inputs and marks them as repeatable, any number of times but at least once
* @example
* oneOrMore('foo', maybe('bar')) // => /(?:foo(?:bar)?)+/
* @argument inputs - arbitrary number of `string` or `Input`, where `string` will be escaped
*/
declare function oneOrMore<Inputs extends InputSource[], Value extends string = Join<MapToValues<Inputs>, '', ''>>(...inputs: Inputs): Input<IfUnwrapped<Value, `(?:${Value})+`, `${Value}+`>, MapToGroups<Inputs>, MapToCapturedGroupsArr<Inputs>>;
type Escape<T extends string, EscapeChar extends string> = T extends `${infer Start}${EscapeChar}${string}` ? Start extends `${string}${EscapeChar}${string}` ? never : T extends `${Start}${infer Char}${string}` ? Char extends EscapeChar ? T extends `${Start}${Char}${infer Rest}` ? `${Start}\\${Char}${Escape<Rest, EscapeChar>}` : never : never : never : T;
type EscapeChar<T extends string> = Escape<T, '\\' | '^' | '-' | ']'>;
type StripEscapes<T extends string> = T extends `${infer A}\\${infer B}` ? `${A}${B}` : T;
type ExactEscapeChar = '.' | '*' | '+' | '?' | '^' | '$' | '{' | '}' | '(' | ')' | '|' | '[' | ']' | '/';
type GetValue<T extends InputSource> = T extends string ? Escape<T, ExactEscapeChar> : T extends Input<infer R> ? R : never;
interface Input<V extends string, G extends string = never, C extends (string | undefined)[] = []> {
/**
* this takes a variable number of inputs and adds them as new pattern to the current input, or you can use `and.referenceTo(groupName)` to adds a new pattern referencing to a named group
* @example
* exactly('foo').and('bar', maybe('baz')) // => /foobar(?:baz)?/
* @argument inputs - arbitrary number of `string` or `Input`, where `string` will be escaped
*/
and: {
<I extends InputSource[], CG extends any[] = MapToCapturedGroupsArr<I>>(...inputs: I): Input<`${V}${Join<MapToValues<I>, '', ''>}`, G | MapToGroups<I>, [...C, ...CG]>;
/** this adds a new pattern to the current input, with the pattern reference to a named group. */
referenceTo: <N extends G>(groupName: N) => Input<`${V}\\k<${N}>`, G, C>;
};
/**
* this takes a variable number of inputs and provides as an alternative to the current input
* @example
* exactly('foo').or('bar', maybe('baz')) // => /foo|bar(?:baz)?/
* @argument inputs - arbitrary number of `string` or `Input`, where `string` will be escaped
*/
or: <I extends InputSource[], CG extends any[] = MapToCapturedGroupsArr<I>>(...inputs: I) => Input<`(?:${V}|${Join<MapToValues<I>, '', ''>})`, G | MapToGroups<I>, [...C, ...CG]>;
/**
* this takes a variable number of inputs and activate a positive lookbehind. Make sure to check [browser support](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#browser_compatibility) as not all browsers support lookbehinds (notably Safari)
* @example
* exactly('foo').after('bar', maybe('baz')) // => /(?<=bar(?:baz)?)foo/
* @argument inputs - arbitrary number of `string` or `Input`, where `string` will be escaped
*/
after: <I extends InputSource[], CG extends any[] = MapToCapturedGroupsArr<I>>(...inputs: I) => Input<`(?<=${Join<MapToValues<I>, '', ''>})${V}`, G | MapToGroups<I>, [...CG, ...C]>;
/**
* this takes a variable number of inputs and activate a positive lookahead
* @example
* exactly('foo').before('bar', maybe('baz')) // => /foo(?=bar(?:baz)?)/
* @argument inputs - arbitrary number of `string` or `Input`, where `string` will be escaped
*/
before: <I extends InputSource[], CG extends any[] = MapToCapturedGroupsArr<I>>(...inputs: I) => Input<`${V}(?=${Join<MapToValues<I>, '', ''>})`, G, [...C, ...CG]>;
/**
* these takes a variable number of inputs and activate a negative lookbehind. Make sure to check [browser support](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#browser_compatibility) as not all browsers support lookbehinds (notably Safari)
* @example
* exactly('foo').notAfter('bar', maybe('baz')) // => /(?<!bar(?:baz)?)foo/
* @argument inputs - arbitrary number of `string` or `Input`, where `string` will be escaped
*/
notAfter: <I extends InputSource[], CG extends any[] = MapToCapturedGroupsArr<I, true>>(...inputs: I) => Input<`(?<!${Join<MapToValues<I>, '', ''>})${V}`, G, [...CG, ...C]>;
/**
* this takes a variable number of inputs and activate a negative lookahead
* @example
* exactly('foo').notBefore('bar', maybe('baz')) // => /foo(?!bar(?:baz)?)/
* @argument inputs - arbitrary number of `string` or `Input`, where `string` will be escaped
*/
notBefore: <I extends InputSource[], CG extends any[] = MapToCapturedGroupsArr<I, true>>(...inputs: I) => Input<`${V}(?!${Join<MapToValues<I>, '', ''>})`, G, [...C, ...CG]>;
/** repeat the previous pattern an exact number of times */
times: {
<N extends number, NV extends string = IfUnwrapped<V, `(?:${V}){${N}}`, `${V}{${N}}`>>(number: N): Input<NV, G, C>;
/** specify that the expression can repeat any number of times, _including none_ */
any: <NV extends string = IfUnwrapped<V, `(?:${V})*`, `${V}*`>>() => Input<NV, G, C>;
/** specify that the expression must occur at least `N` times */
atLeast: <N extends number, NV extends string = IfUnwrapped<V, `(?:${V}){${N},}`, `${V}{${N},}`>>(number: N) => Input<NV, G, C>;
/** specify that the expression must occur at most `N` times */
atMost: <N extends number, NV extends string = IfUnwrapped<V, `(?:${V}){0,${N}}`, `${V}{0,${N}}`>>(number: N) => Input<NV, G, C>;
/** specify a range of times to repeat the previous pattern */
between: <Min extends number, Max extends number, NV extends string = IfUnwrapped<V, `(?:${V}){${Min},${Max}}`, `${V}{${Min},${Max}}`>>(min: Min, max: Max) => Input<NV, G, C>;
};
/** this defines the entire input so far as a named capture group. You will get type safety when using the resulting RegExp with `String.match()`. Alias for `groupedAs` */
as: <K extends string>(key: K) => Input<V extends `(?:${infer S})` ? `(?<${K}>${S})` : `(?<${K}>${V})`, G | K, [
V extends `(?:${infer S})` ? `(?<${K}>${S})` : `(?<${K}>${V})`,
...C
]>;
/** this defines the entire input so far as a named capture group. You will get type safety when using the resulting RegExp with `String.match()` */
groupedAs: <K extends string>(key: K) => Input<V extends `(?:${infer S})` ? `(?<${K}>${S})` : `(?<${K}>${V})`, G | K, [
V extends `(?:${infer S})` ? `(?<${K}>${S})` : `(?<${K}>${V})`,
...C
]>;
/** this capture the entire input so far as an anonymous group */
grouped: () => Input<V extends `(?:${infer S})${infer E}` ? `(${S})${E}` : `(${V})`, G, [
V extends `(?:${infer S})${'' | '?' | '+' | '*' | `{${string}}`}` ? `(${S})` : `(${V})`,
...C
]>;
/** this allows you to match beginning/ends of lines with `at.lineStart()` and `at.lineEnd()` */
at: {
lineStart: () => Input<`^${V}`, G, C>;
lineEnd: () => Input<`${V}$`, G, C>;
};
/** this allows you to mark the input so far as optional */
optionally: <NV extends string = IfUnwrapped<V, `(?:${V})?`, `${V}?`>>() => Input<NV, G, C>;
toString: () => string;
}
interface CharInput<T extends string> extends Input<`[${T}]`> {
orChar: (<Or extends string>(chars: Or) => CharInput<`${T}${EscapeChar<Or>}`>) & CharInput<T>;
from: <From extends string, To extends string>(charFrom: From, charTo: To) => CharInput<`${T}${EscapeChar<From>}-${EscapeChar<To>}`>;
}
type InputSource<S extends string = string, T extends string = never> = S | Input<any, T>;
type MapToValues<T extends InputSource[]> = T extends [
infer First,
...infer Rest extends InputSource[]
] ? First extends InputSource ? [GetValue<First>, ...MapToValues<Rest>] : [] : [];
type MapToGroups<T extends InputSource[]> = T extends [
infer First,
...infer Rest extends InputSource[]
] ? First extends Input<any, infer K> ? K | MapToGroups<Rest> : MapToGroups<Rest> : never;
type MapToCapturedGroupsArr<Inputs extends any[], MapToUndefined extends boolean = false, CapturedGroupsArr extends any[] = [], Count extends any[] = []> = Count['length'] extends Inputs['length'] ? CapturedGroupsArr : Inputs[Count['length']] extends Input<any, any, infer CaptureGroups> ? [CaptureGroups] extends [never] ? MapToCapturedGroupsArr<Inputs, MapToUndefined, [...CapturedGroupsArr], [...Count, '']> : MapToUndefined extends true ? MapToCapturedGroupsArr<Inputs, MapToUndefined, [
...CapturedGroupsArr,
undefined
], [
...Count,
''
]> : MapToCapturedGroupsArr<Inputs, MapToUndefined, [
...CapturedGroupsArr,
...CaptureGroups
], [
...Count,
''
]> : MapToCapturedGroupsArr<Inputs, MapToUndefined, [...CapturedGroupsArr], [...Count, '']>;
export { maybe as A, exactly as B, oneOrMore as C, type MapToStringCapturedBy as D, type Flag as F, type InputSource as I, type Join as J, type MagicRegExp as M, type StringCapturedBy as S, type UnionToTuple as U, type MagicRegExpMatchArray as a, type MapToValues as b, type MapToGroups as c, type MapToCapturedGroupsArr as d, caseInsensitive as e, dotAll as f, global as g, type Input as h, charIn as i, charNotIn as j, anyOf as k, char as l, multiline as m, word as n, wordChar as o, wordBoundary as p, digit as q, whitespace as r, sticky as s, letter as t, unicode as u, tab as v, withIndices as w, linefeed as x, carriageReturn as y, not as z };

View File

@@ -0,0 +1,104 @@
const NO_WRAP_RE = /^(?:\(.*\)|\\?.)$/;
function wrap(s) {
const v = s.toString();
return NO_WRAP_RE.test(v) ? v : `(?:${v})`;
}
const GROUPED_AS_REPLACE_RE = /^(?:\(\?:(.+)\)|(.+))$/;
const GROUPED_REPLACE_RE = /^(?:\(\?:(.+)\)([?+*]|\{[\d,]+\})?|(.+))$/;
function createInput(s) {
const groupedAsFn = (key) => createInput(`(?<${key}>${`${s}`.replace(GROUPED_AS_REPLACE_RE, "$1$2")})`);
return {
toString: () => s.toString(),
and: Object.assign((...inputs) => createInput(`${s}${exactly(...inputs)}`), {
referenceTo: (groupName) => createInput(`${s}\\k<${groupName}>`)
}),
or: (...inputs) => createInput(`(?:${s}|${inputs.map((v) => exactly(v)).join("|")})`),
after: (...input) => createInput(`(?<=${exactly(...input)})${s}`),
before: (...input) => createInput(`${s}(?=${exactly(...input)})`),
notAfter: (...input) => createInput(`(?<!${exactly(...input)})${s}`),
notBefore: (...input) => createInput(`${s}(?!${exactly(...input)})`),
times: Object.assign((number) => createInput(`${wrap(s)}{${number}}`), {
any: () => createInput(`${wrap(s)}*`),
atLeast: (min) => createInput(`${wrap(s)}{${min},}`),
atMost: (max) => createInput(`${wrap(s)}{0,${max}}`),
between: (min, max) => createInput(`${wrap(s)}{${min},${max}}`)
}),
optionally: () => createInput(`${wrap(s)}?`),
as: groupedAsFn,
groupedAs: groupedAsFn,
grouped: () => createInput(`${s}`.replace(GROUPED_REPLACE_RE, "($1$3)$2")),
at: {
lineStart: () => createInput(`^${s}`),
lineEnd: () => createInput(`${s}$`)
}
};
}
const ESCAPE_REPLACE_RE = /[.*+?^${}()|[\]\\/]/g;
function createCharInput(raw) {
const input = createInput(`[${raw}]`);
const from = (charFrom, charTo) => createCharInput(`${raw}${escapeCharInput(charFrom)}-${escapeCharInput(charTo)}`);
const orChar = Object.assign((chars) => createCharInput(`${raw}${escapeCharInput(chars)}`), { from });
return Object.assign(input, { orChar, from });
}
function escapeCharInput(raw) {
return raw.replace(/[-\\^\]]/g, "\\$&");
}
const charIn = Object.assign((chars) => {
return createCharInput(escapeCharInput(chars));
}, createCharInput(""));
const charNotIn = Object.assign((chars) => {
return createCharInput(`^${escapeCharInput(chars)}`);
}, createCharInput("^"));
function anyOf(...inputs) {
return createInput(`(?:${inputs.map((a) => exactly(a)).join("|")})`);
}
const char = createInput(".");
const word = createInput("\\b\\w+\\b");
const wordChar = createInput("\\w");
const wordBoundary = createInput("\\b");
const digit = createInput("\\d");
const whitespace = createInput("\\s");
const letter = Object.assign(createInput("[a-zA-Z]"), {
lowercase: createInput("[a-z]"),
uppercase: createInput("[A-Z]")
});
const tab = createInput("\\t");
const linefeed = createInput("\\n");
const carriageReturn = createInput("\\r");
const not = {
word: createInput("\\W+"),
wordChar: createInput("\\W"),
wordBoundary: createInput("\\B"),
digit: createInput("\\D"),
whitespace: createInput("\\S"),
letter: Object.assign(createInput("[^a-zA-Z]"), {
lowercase: createInput("[^a-z]"),
uppercase: createInput("[^A-Z]")
}),
tab: createInput("[^\\t]"),
linefeed: createInput("[^\\n]"),
carriageReturn: createInput("[^\\r]")
};
function maybe(...inputs) {
return createInput(`${wrap(exactly(...inputs))}?`);
}
function exactly(...inputs) {
return createInput(
inputs.map((input) => typeof input === "string" ? input.replace(ESCAPE_REPLACE_RE, "\\$&") : input).join("")
);
}
function oneOrMore(...inputs) {
return createInput(`${wrap(exactly(...inputs))}+`);
}
const withIndices = "d";
const caseInsensitive = "i";
const global = "g";
const multiline = "m";
const dotAll = "s";
const unicode = "u";
const sticky = "y";
export { charIn as a, charNotIn as b, caseInsensitive as c, dotAll as d, exactly as e, anyOf as f, global as g, char as h, word as i, wordChar as j, wordBoundary as k, digit as l, multiline as m, whitespace as n, letter as o, linefeed as p, carriageReturn as q, not as r, sticky as s, tab as t, unicode as u, maybe as v, withIndices as w, oneOrMore as x };

View File

@@ -0,0 +1,129 @@
'use strict';
const NO_WRAP_RE = /^(?:\(.*\)|\\?.)$/;
function wrap(s) {
const v = s.toString();
return NO_WRAP_RE.test(v) ? v : `(?:${v})`;
}
const GROUPED_AS_REPLACE_RE = /^(?:\(\?:(.+)\)|(.+))$/;
const GROUPED_REPLACE_RE = /^(?:\(\?:(.+)\)([?+*]|\{[\d,]+\})?|(.+))$/;
function createInput(s) {
const groupedAsFn = (key) => createInput(`(?<${key}>${`${s}`.replace(GROUPED_AS_REPLACE_RE, "$1$2")})`);
return {
toString: () => s.toString(),
and: Object.assign((...inputs) => createInput(`${s}${exactly(...inputs)}`), {
referenceTo: (groupName) => createInput(`${s}\\k<${groupName}>`)
}),
or: (...inputs) => createInput(`(?:${s}|${inputs.map((v) => exactly(v)).join("|")})`),
after: (...input) => createInput(`(?<=${exactly(...input)})${s}`),
before: (...input) => createInput(`${s}(?=${exactly(...input)})`),
notAfter: (...input) => createInput(`(?<!${exactly(...input)})${s}`),
notBefore: (...input) => createInput(`${s}(?!${exactly(...input)})`),
times: Object.assign((number) => createInput(`${wrap(s)}{${number}}`), {
any: () => createInput(`${wrap(s)}*`),
atLeast: (min) => createInput(`${wrap(s)}{${min},}`),
atMost: (max) => createInput(`${wrap(s)}{0,${max}}`),
between: (min, max) => createInput(`${wrap(s)}{${min},${max}}`)
}),
optionally: () => createInput(`${wrap(s)}?`),
as: groupedAsFn,
groupedAs: groupedAsFn,
grouped: () => createInput(`${s}`.replace(GROUPED_REPLACE_RE, "($1$3)$2")),
at: {
lineStart: () => createInput(`^${s}`),
lineEnd: () => createInput(`${s}$`)
}
};
}
const ESCAPE_REPLACE_RE = /[.*+?^${}()|[\]\\/]/g;
function createCharInput(raw) {
const input = createInput(`[${raw}]`);
const from = (charFrom, charTo) => createCharInput(`${raw}${escapeCharInput(charFrom)}-${escapeCharInput(charTo)}`);
const orChar = Object.assign((chars) => createCharInput(`${raw}${escapeCharInput(chars)}`), { from });
return Object.assign(input, { orChar, from });
}
function escapeCharInput(raw) {
return raw.replace(/[-\\^\]]/g, "\\$&");
}
const charIn = Object.assign((chars) => {
return createCharInput(escapeCharInput(chars));
}, createCharInput(""));
const charNotIn = Object.assign((chars) => {
return createCharInput(`^${escapeCharInput(chars)}`);
}, createCharInput("^"));
function anyOf(...inputs) {
return createInput(`(?:${inputs.map((a) => exactly(a)).join("|")})`);
}
const char = createInput(".");
const word = createInput("\\b\\w+\\b");
const wordChar = createInput("\\w");
const wordBoundary = createInput("\\b");
const digit = createInput("\\d");
const whitespace = createInput("\\s");
const letter = Object.assign(createInput("[a-zA-Z]"), {
lowercase: createInput("[a-z]"),
uppercase: createInput("[A-Z]")
});
const tab = createInput("\\t");
const linefeed = createInput("\\n");
const carriageReturn = createInput("\\r");
const not = {
word: createInput("\\W+"),
wordChar: createInput("\\W"),
wordBoundary: createInput("\\B"),
digit: createInput("\\D"),
whitespace: createInput("\\S"),
letter: Object.assign(createInput("[^a-zA-Z]"), {
lowercase: createInput("[^a-z]"),
uppercase: createInput("[^A-Z]")
}),
tab: createInput("[^\\t]"),
linefeed: createInput("[^\\n]"),
carriageReturn: createInput("[^\\r]")
};
function maybe(...inputs) {
return createInput(`${wrap(exactly(...inputs))}?`);
}
function exactly(...inputs) {
return createInput(
inputs.map((input) => typeof input === "string" ? input.replace(ESCAPE_REPLACE_RE, "\\$&") : input).join("")
);
}
function oneOrMore(...inputs) {
return createInput(`${wrap(exactly(...inputs))}+`);
}
const withIndices = "d";
const caseInsensitive = "i";
const global = "g";
const multiline = "m";
const dotAll = "s";
const unicode = "u";
const sticky = "y";
exports.anyOf = anyOf;
exports.carriageReturn = carriageReturn;
exports.caseInsensitive = caseInsensitive;
exports.char = char;
exports.charIn = charIn;
exports.charNotIn = charNotIn;
exports.digit = digit;
exports.dotAll = dotAll;
exports.exactly = exactly;
exports.global = global;
exports.letter = letter;
exports.linefeed = linefeed;
exports.maybe = maybe;
exports.multiline = multiline;
exports.not = not;
exports.oneOrMore = oneOrMore;
exports.sticky = sticky;
exports.tab = tab;
exports.unicode = unicode;
exports.whitespace = whitespace;
exports.withIndices = withIndices;
exports.word = word;
exports.wordBoundary = wordBoundary;
exports.wordChar = wordChar;

96
node_modules/magic-regexp/dist/transform.cjs generated vendored Normal file
View File

@@ -0,0 +1,96 @@
'use strict';
const node_url = require('node:url');
const node_vm = require('node:vm');
const estreeWalker = require('estree-walker');
const magicRegExp = require('magic-regexp');
const MagicString = require('magic-string');
const mlly = require('mlly');
const ufo = require('ufo');
const unplugin = require('unplugin');
function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e.default : e; }
function _interopNamespaceCompat(e) {
if (e && typeof e === 'object' && 'default' in e) return e;
const n = Object.create(null);
if (e) {
for (const k in e) {
n[k] = e[k];
}
}
n.default = e;
return n;
}
const magicRegExp__namespace = /*#__PURE__*/_interopNamespaceCompat(magicRegExp);
const MagicString__default = /*#__PURE__*/_interopDefaultCompat(MagicString);
const MagicRegExpTransformPlugin = unplugin.createUnplugin(() => {
return {
name: "MagicRegExpTransformPlugin",
enforce: "post",
transformInclude(id) {
const { pathname, search } = ufo.parseURL(decodeURIComponent(node_url.pathToFileURL(id).href));
const { type } = ufo.parseQuery(search);
if (pathname.endsWith(".vue") && (type === "script" || !search))
return true;
if (pathname.match(/\.((c|m)?j|t)sx?$/g))
return true;
return false;
},
transform(code, id) {
if (!code.includes("magic-regexp"))
return;
const statements = mlly.findStaticImports(code).filter(
(i) => i.specifier === "magic-regexp" || i.specifier === "magic-regexp/further-magic"
);
if (!statements.length)
return;
const contextMap = { ...magicRegExp__namespace };
const wrapperNames = [];
let namespace;
for (const i of statements.flatMap((i2) => mlly.parseStaticImport(i2))) {
if (i.namespacedImport) {
namespace = i.namespacedImport;
contextMap[i.namespacedImport] = magicRegExp__namespace;
}
if (i.namedImports) {
for (const key in i.namedImports)
contextMap[i.namedImports[key]] = magicRegExp__namespace[key];
if (i.namedImports.createRegExp)
wrapperNames.push(i.namedImports.createRegExp);
}
}
const context = node_vm.createContext(contextMap);
const s = new MagicString__default(code);
estreeWalker.walk(this.parse(code), {
enter(_node) {
if (_node.type !== "CallExpression")
return;
const node = _node;
if (
// Normal call
!wrapperNames.includes(node.callee.name) && (node.callee.type !== "MemberExpression" || node.callee.object.type !== "Identifier" || node.callee.object.name !== namespace || node.callee.property.type !== "Identifier" || node.callee.property.name !== "createRegExp")
) {
return;
}
const { start, end } = node;
try {
const value = node_vm.runInContext(code.slice(start, end), context);
s.overwrite(start, end, value.toString());
} catch {
}
}
});
if (s.hasChanged()) {
return {
code: s.toString(),
map: s.generateMap({ includeContent: true, source: id })
};
}
}
};
});
exports.MagicRegExpTransformPlugin = MagicRegExpTransformPlugin;

5
node_modules/magic-regexp/dist/transform.d.cts generated vendored Normal file
View File

@@ -0,0 +1,5 @@
import * as unplugin from 'unplugin';
declare const MagicRegExpTransformPlugin: unplugin.UnpluginInstance<unknown, boolean>;
export { MagicRegExpTransformPlugin };

5
node_modules/magic-regexp/dist/transform.d.mts generated vendored Normal file
View File

@@ -0,0 +1,5 @@
import * as unplugin from 'unplugin';
declare const MagicRegExpTransformPlugin: unplugin.UnpluginInstance<unknown, boolean>;
export { MagicRegExpTransformPlugin };

5
node_modules/magic-regexp/dist/transform.d.ts generated vendored Normal file
View File

@@ -0,0 +1,5 @@
import * as unplugin from 'unplugin';
declare const MagicRegExpTransformPlugin: unplugin.UnpluginInstance<unknown, boolean>;
export { MagicRegExpTransformPlugin };

77
node_modules/magic-regexp/dist/transform.mjs generated vendored Normal file
View File

@@ -0,0 +1,77 @@
import { pathToFileURL } from 'node:url';
import { createContext, runInContext } from 'node:vm';
import { walk } from 'estree-walker';
import * as magicRegExp from 'magic-regexp';
import MagicString from 'magic-string';
import { findStaticImports, parseStaticImport } from 'mlly';
import { parseURL, parseQuery } from 'ufo';
import { createUnplugin } from 'unplugin';
const MagicRegExpTransformPlugin = createUnplugin(() => {
return {
name: "MagicRegExpTransformPlugin",
enforce: "post",
transformInclude(id) {
const { pathname, search } = parseURL(decodeURIComponent(pathToFileURL(id).href));
const { type } = parseQuery(search);
if (pathname.endsWith(".vue") && (type === "script" || !search))
return true;
if (pathname.match(/\.((c|m)?j|t)sx?$/g))
return true;
return false;
},
transform(code, id) {
if (!code.includes("magic-regexp"))
return;
const statements = findStaticImports(code).filter(
(i) => i.specifier === "magic-regexp" || i.specifier === "magic-regexp/further-magic"
);
if (!statements.length)
return;
const contextMap = { ...magicRegExp };
const wrapperNames = [];
let namespace;
for (const i of statements.flatMap((i2) => parseStaticImport(i2))) {
if (i.namespacedImport) {
namespace = i.namespacedImport;
contextMap[i.namespacedImport] = magicRegExp;
}
if (i.namedImports) {
for (const key in i.namedImports)
contextMap[i.namedImports[key]] = magicRegExp[key];
if (i.namedImports.createRegExp)
wrapperNames.push(i.namedImports.createRegExp);
}
}
const context = createContext(contextMap);
const s = new MagicString(code);
walk(this.parse(code), {
enter(_node) {
if (_node.type !== "CallExpression")
return;
const node = _node;
if (
// Normal call
!wrapperNames.includes(node.callee.name) && (node.callee.type !== "MemberExpression" || node.callee.object.type !== "Identifier" || node.callee.object.name !== namespace || node.callee.property.type !== "Identifier" || node.callee.property.name !== "createRegExp")
) {
return;
}
const { start, end } = node;
try {
const value = runInContext(code.slice(start, end), context);
s.overwrite(start, end, value.toString());
} catch {
}
}
});
if (s.hasChanged()) {
return {
code: s.toString(),
map: s.generateMap({ includeContent: true, source: id })
};
}
}
};
});
export { MagicRegExpTransformPlugin };

3
node_modules/magic-regexp/further-magic.d.ts generated vendored Normal file
View File

@@ -0,0 +1,3 @@
// Legacy stub for previous TS versions
export * from './dist/further-magic'

View File

@@ -0,0 +1,7 @@
Copyright (c) 2015-20 [these people](https://github.com/Rich-Harris/estree-walker/graphs/contributors)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@@ -0,0 +1,48 @@
# estree-walker
Simple utility for walking an [ESTree](https://github.com/estree/estree)-compliant AST, such as one generated by [acorn](https://github.com/marijnh/acorn).
## Installation
```bash
npm i estree-walker
```
## Usage
```js
var walk = require('estree-walker').walk;
var acorn = require('acorn');
ast = acorn.parse(sourceCode, options); // https://github.com/acornjs/acorn
walk(ast, {
enter(node, parent, prop, index) {
// some code happens
},
leave(node, parent, prop, index) {
// some code happens
}
});
```
Inside the `enter` function, calling `this.skip()` will prevent the node's children being walked, or the `leave` function (which is optional) being called.
Call `this.replace(new_node)` in either `enter` or `leave` to replace the current node with a new one.
Call `this.remove()` in either `enter` or `leave` to remove the current node.
## Why not use estraverse?
The ESTree spec is evolving to accommodate ES6/7. I've had a couple of experiences where [estraverse](https://github.com/estools/estraverse) was unable to handle an AST generated by recent versions of acorn, because it hard-codes visitor keys.
estree-walker, by contrast, simply enumerates a node's properties to find child nodes (and child lists of nodes), and is therefore resistant to spec changes. It's also much smaller. (The performance, if you're wondering, is basically identical.)
None of which should be taken as criticism of estraverse, which has more features and has been battle-tested in many more situations, and for which I'm very grateful.
## License
MIT

View File

@@ -0,0 +1,38 @@
{
"name": "estree-walker",
"description": "Traverse an ESTree-compliant AST",
"version": "3.0.3",
"private": false,
"author": "Rich Harris",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/Rich-Harris/estree-walker"
},
"type": "module",
"module": "./src/index.js",
"exports": {
"./package.json": "./package.json",
".": {
"types": "./types/index.d.ts",
"import": "./src/index.js"
}
},
"types": "types/index.d.ts",
"scripts": {
"prepublishOnly": "tsc && npm test",
"test": "uvu test"
},
"dependencies": {
"@types/estree": "^1.0.0"
},
"devDependencies": {
"typescript": "^4.9.0",
"uvu": "^0.5.1"
},
"files": [
"src",
"types",
"README.md"
]
}

View File

@@ -0,0 +1,152 @@
import { WalkerBase } from './walker.js';
/**
* @typedef { import('estree').Node} Node
* @typedef { import('./walker.js').WalkerContext} WalkerContext
* @typedef {(
* this: WalkerContext,
* node: Node,
* parent: Node | null,
* key: string | number | symbol | null | undefined,
* index: number | null | undefined
* ) => Promise<void>} AsyncHandler
*/
export class AsyncWalker extends WalkerBase {
/**
*
* @param {AsyncHandler} [enter]
* @param {AsyncHandler} [leave]
*/
constructor(enter, leave) {
super();
/** @type {boolean} */
this.should_skip = false;
/** @type {boolean} */
this.should_remove = false;
/** @type {Node | null} */
this.replacement = null;
/** @type {WalkerContext} */
this.context = {
skip: () => (this.should_skip = true),
remove: () => (this.should_remove = true),
replace: (node) => (this.replacement = node)
};
/** @type {AsyncHandler | undefined} */
this.enter = enter;
/** @type {AsyncHandler | undefined} */
this.leave = leave;
}
/**
* @template {Node} Parent
* @param {Node} node
* @param {Parent | null} parent
* @param {keyof Parent} [prop]
* @param {number | null} [index]
* @returns {Promise<Node | null>}
*/
async visit(node, parent, prop, index) {
if (node) {
if (this.enter) {
const _should_skip = this.should_skip;
const _should_remove = this.should_remove;
const _replacement = this.replacement;
this.should_skip = false;
this.should_remove = false;
this.replacement = null;
await this.enter.call(this.context, node, parent, prop, index);
if (this.replacement) {
node = this.replacement;
this.replace(parent, prop, index, node);
}
if (this.should_remove) {
this.remove(parent, prop, index);
}
const skipped = this.should_skip;
const removed = this.should_remove;
this.should_skip = _should_skip;
this.should_remove = _should_remove;
this.replacement = _replacement;
if (skipped) return node;
if (removed) return null;
}
/** @type {keyof Node} */
let key;
for (key in node) {
/** @type {unknown} */
const value = node[key];
if (value && typeof value === 'object') {
if (Array.isArray(value)) {
const nodes = /** @type {Array<unknown>} */ (value);
for (let i = 0; i < nodes.length; i += 1) {
const item = nodes[i];
if (isNode(item)) {
if (!(await this.visit(item, node, key, i))) {
// removed
i--;
}
}
}
} else if (isNode(value)) {
await this.visit(value, node, key, null);
}
}
}
if (this.leave) {
const _replacement = this.replacement;
const _should_remove = this.should_remove;
this.replacement = null;
this.should_remove = false;
await this.leave.call(this.context, node, parent, prop, index);
if (this.replacement) {
node = this.replacement;
this.replace(parent, prop, index, node);
}
if (this.should_remove) {
this.remove(parent, prop, index);
}
const removed = this.should_remove;
this.replacement = _replacement;
this.should_remove = _should_remove;
if (removed) return null;
}
}
return node;
}
}
/**
* Ducktype a node.
*
* @param {unknown} value
* @returns {value is Node}
*/
function isNode(value) {
return (
value !== null && typeof value === 'object' && 'type' in value && typeof value.type === 'string'
);
}

View File

@@ -0,0 +1,34 @@
import { SyncWalker } from './sync.js';
import { AsyncWalker } from './async.js';
/**
* @typedef {import('estree').Node} Node
* @typedef {import('./sync.js').SyncHandler} SyncHandler
* @typedef {import('./async.js').AsyncHandler} AsyncHandler
*/
/**
* @param {Node} ast
* @param {{
* enter?: SyncHandler
* leave?: SyncHandler
* }} walker
* @returns {Node | null}
*/
export function walk(ast, { enter, leave }) {
const instance = new SyncWalker(enter, leave);
return instance.visit(ast, null);
}
/**
* @param {Node} ast
* @param {{
* enter?: AsyncHandler
* leave?: AsyncHandler
* }} walker
* @returns {Promise<Node | null>}
*/
export async function asyncWalk(ast, { enter, leave }) {
const instance = new AsyncWalker(enter, leave);
return await instance.visit(ast, null);
}

View File

@@ -0,0 +1,152 @@
import { WalkerBase } from './walker.js';
/**
* @typedef { import('estree').Node} Node
* @typedef { import('./walker.js').WalkerContext} WalkerContext
* @typedef {(
* this: WalkerContext,
* node: Node,
* parent: Node | null,
* key: string | number | symbol | null | undefined,
* index: number | null | undefined
* ) => void} SyncHandler
*/
export class SyncWalker extends WalkerBase {
/**
*
* @param {SyncHandler} [enter]
* @param {SyncHandler} [leave]
*/
constructor(enter, leave) {
super();
/** @type {boolean} */
this.should_skip = false;
/** @type {boolean} */
this.should_remove = false;
/** @type {Node | null} */
this.replacement = null;
/** @type {WalkerContext} */
this.context = {
skip: () => (this.should_skip = true),
remove: () => (this.should_remove = true),
replace: (node) => (this.replacement = node)
};
/** @type {SyncHandler | undefined} */
this.enter = enter;
/** @type {SyncHandler | undefined} */
this.leave = leave;
}
/**
* @template {Node} Parent
* @param {Node} node
* @param {Parent | null} parent
* @param {keyof Parent} [prop]
* @param {number | null} [index]
* @returns {Node | null}
*/
visit(node, parent, prop, index) {
if (node) {
if (this.enter) {
const _should_skip = this.should_skip;
const _should_remove = this.should_remove;
const _replacement = this.replacement;
this.should_skip = false;
this.should_remove = false;
this.replacement = null;
this.enter.call(this.context, node, parent, prop, index);
if (this.replacement) {
node = this.replacement;
this.replace(parent, prop, index, node);
}
if (this.should_remove) {
this.remove(parent, prop, index);
}
const skipped = this.should_skip;
const removed = this.should_remove;
this.should_skip = _should_skip;
this.should_remove = _should_remove;
this.replacement = _replacement;
if (skipped) return node;
if (removed) return null;
}
/** @type {keyof Node} */
let key;
for (key in node) {
/** @type {unknown} */
const value = node[key];
if (value && typeof value === 'object') {
if (Array.isArray(value)) {
const nodes = /** @type {Array<unknown>} */ (value);
for (let i = 0; i < nodes.length; i += 1) {
const item = nodes[i];
if (isNode(item)) {
if (!this.visit(item, node, key, i)) {
// removed
i--;
}
}
}
} else if (isNode(value)) {
this.visit(value, node, key, null);
}
}
}
if (this.leave) {
const _replacement = this.replacement;
const _should_remove = this.should_remove;
this.replacement = null;
this.should_remove = false;
this.leave.call(this.context, node, parent, prop, index);
if (this.replacement) {
node = this.replacement;
this.replace(parent, prop, index, node);
}
if (this.should_remove) {
this.remove(parent, prop, index);
}
const removed = this.should_remove;
this.replacement = _replacement;
this.should_remove = _should_remove;
if (removed) return null;
}
}
return node;
}
}
/**
* Ducktype a node.
*
* @param {unknown} value
* @returns {value is Node}
*/
function isNode(value) {
return (
value !== null && typeof value === 'object' && 'type' in value && typeof value.type === 'string'
);
}

View File

@@ -0,0 +1,61 @@
/**
* @typedef { import('estree').Node} Node
* @typedef {{
* skip: () => void;
* remove: () => void;
* replace: (node: Node) => void;
* }} WalkerContext
*/
export class WalkerBase {
constructor() {
/** @type {boolean} */
this.should_skip = false;
/** @type {boolean} */
this.should_remove = false;
/** @type {Node | null} */
this.replacement = null;
/** @type {WalkerContext} */
this.context = {
skip: () => (this.should_skip = true),
remove: () => (this.should_remove = true),
replace: (node) => (this.replacement = node)
};
}
/**
* @template {Node} Parent
* @param {Parent | null | undefined} parent
* @param {keyof Parent | null | undefined} prop
* @param {number | null | undefined} index
* @param {Node} node
*/
replace(parent, prop, index, node) {
if (parent && prop) {
if (index != null) {
/** @type {Array<Node>} */ (parent[prop])[index] = node;
} else {
/** @type {Node} */ (parent[prop]) = node;
}
}
}
/**
* @template {Node} Parent
* @param {Parent | null | undefined} parent
* @param {keyof Parent | null | undefined} prop
* @param {number | null | undefined} index
*/
remove(parent, prop, index) {
if (parent && prop) {
if (index !== null && index !== undefined) {
/** @type {Array<Node>} */ (parent[prop]).splice(index, 1);
} else {
delete parent[prop];
}
}
}
}

View File

@@ -0,0 +1,36 @@
/**
* @typedef { import('estree').Node} Node
* @typedef { import('./walker.js').WalkerContext} WalkerContext
* @typedef {(
* this: WalkerContext,
* node: Node,
* parent: Node | null,
* key: string | number | symbol | null | undefined,
* index: number | null | undefined
* ) => Promise<void>} AsyncHandler
*/
export class AsyncWalker extends WalkerBase {
/**
*
* @param {AsyncHandler} [enter]
* @param {AsyncHandler} [leave]
*/
constructor(enter?: AsyncHandler | undefined, leave?: AsyncHandler | undefined);
/** @type {AsyncHandler | undefined} */
enter: AsyncHandler | undefined;
/** @type {AsyncHandler | undefined} */
leave: AsyncHandler | undefined;
/**
* @template {Node} Parent
* @param {Node} node
* @param {Parent | null} parent
* @param {keyof Parent} [prop]
* @param {number | null} [index]
* @returns {Promise<Node | null>}
*/
visit<Parent extends import("estree").Node>(node: Node, parent: Parent | null, prop?: keyof Parent | undefined, index?: number | null | undefined): Promise<Node | null>;
}
export type Node = import('estree').Node;
export type WalkerContext = import('./walker.js').WalkerContext;
export type AsyncHandler = (this: WalkerContext, node: Node, parent: Node | null, key: string | number | symbol | null | undefined, index: number | null | undefined) => Promise<void>;
import { WalkerBase } from "./walker.js";

View File

@@ -0,0 +1,32 @@
/**
* @typedef {import('estree').Node} Node
* @typedef {import('./sync.js').SyncHandler} SyncHandler
* @typedef {import('./async.js').AsyncHandler} AsyncHandler
*/
/**
* @param {Node} ast
* @param {{
* enter?: SyncHandler
* leave?: SyncHandler
* }} walker
* @returns {Node | null}
*/
export function walk(ast: Node, { enter, leave }: {
enter?: SyncHandler;
leave?: SyncHandler;
}): Node | null;
/**
* @param {Node} ast
* @param {{
* enter?: AsyncHandler
* leave?: AsyncHandler
* }} walker
* @returns {Promise<Node | null>}
*/
export function asyncWalk(ast: Node, { enter, leave }: {
enter?: AsyncHandler;
leave?: AsyncHandler;
}): Promise<Node | null>;
export type Node = import('estree').Node;
export type SyncHandler = import('./sync.js').SyncHandler;
export type AsyncHandler = import('./async.js').AsyncHandler;

View File

@@ -0,0 +1,36 @@
/**
* @typedef { import('estree').Node} Node
* @typedef { import('./walker.js').WalkerContext} WalkerContext
* @typedef {(
* this: WalkerContext,
* node: Node,
* parent: Node | null,
* key: string | number | symbol | null | undefined,
* index: number | null | undefined
* ) => void} SyncHandler
*/
export class SyncWalker extends WalkerBase {
/**
*
* @param {SyncHandler} [enter]
* @param {SyncHandler} [leave]
*/
constructor(enter?: SyncHandler | undefined, leave?: SyncHandler | undefined);
/** @type {SyncHandler | undefined} */
enter: SyncHandler | undefined;
/** @type {SyncHandler | undefined} */
leave: SyncHandler | undefined;
/**
* @template {Node} Parent
* @param {Node} node
* @param {Parent | null} parent
* @param {keyof Parent} [prop]
* @param {number | null} [index]
* @returns {Node | null}
*/
visit<Parent extends import("estree").Node>(node: Node, parent: Parent | null, prop?: keyof Parent | undefined, index?: number | null | undefined): Node | null;
}
export type Node = import('estree').Node;
export type WalkerContext = import('./walker.js').WalkerContext;
export type SyncHandler = (this: WalkerContext, node: Node, parent: Node | null, key: string | number | symbol | null | undefined, index: number | null | undefined) => void;
import { WalkerBase } from "./walker.js";

View File

@@ -0,0 +1,39 @@
/**
* @typedef { import('estree').Node} Node
* @typedef {{
* skip: () => void;
* remove: () => void;
* replace: (node: Node) => void;
* }} WalkerContext
*/
export class WalkerBase {
/** @type {boolean} */
should_skip: boolean;
/** @type {boolean} */
should_remove: boolean;
/** @type {Node | null} */
replacement: Node | null;
/** @type {WalkerContext} */
context: WalkerContext;
/**
* @template {Node} Parent
* @param {Parent | null | undefined} parent
* @param {keyof Parent | null | undefined} prop
* @param {number | null | undefined} index
* @param {Node} node
*/
replace<Parent extends import("estree").Node>(parent: Parent | null | undefined, prop: keyof Parent | null | undefined, index: number | null | undefined, node: Node): void;
/**
* @template {Node} Parent
* @param {Parent | null | undefined} parent
* @param {keyof Parent | null | undefined} prop
* @param {number | null | undefined} index
*/
remove<Parent_1 extends import("estree").Node>(parent: Parent_1 | null | undefined, prop: keyof Parent_1 | null | undefined, index: number | null | undefined): void;
}
export type Node = import('estree').Node;
export type WalkerContext = {
skip: () => void;
remove: () => void;
replace: (node: Node) => void;
};

View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2021-PRESENT Nuxt Contrib
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -0,0 +1,35 @@
# Unplugin
[![npm version][npm-version-src]][npm-version-href]
[![npm downloads][npm-downloads-src]][npm-downloads-href]
[![License][license-src]][license-href]
Unified plugin system for build tools.
Currently supports:
- [Vite](https://vite.dev/)
- [Rollup](https://rollupjs.org/)
- [Webpack](https://webpack.js.org/)
- [esbuild](https://esbuild.github.io/)
- [Rspack](https://www.rspack.dev/)
- [Rolldown](https://rolldown.rs/)
- [Farm](https://www.farmfe.org/)
- And every framework built on top of them.
## Documentations
Learn more on the [Documentation](https://unplugin.unjs.io/)
## License
[MIT](./LICENSE) License © 2021-PRESENT Nuxt Contrib
<!-- Badges -->
[npm-version-src]: https://img.shields.io/npm/v/unplugin?style=flat&colorA=18181B&colorB=F0DB4F
[npm-version-href]: https://npmjs.com/package/unplugin
[npm-downloads-src]: https://img.shields.io/npm/dm/unplugin?style=flat&colorA=18181B&colorB=F0DB4F
[npm-downloads-href]: https://npmjs.com/package/unplugin
[license-src]: https://img.shields.io/github/license/unjs/unplugin.svg?style=flat&colorA=18181B&colorB=F0DB4F
[license-href]: https://github.com/unjs/unplugin/blob/main/LICENSE

View File

@@ -0,0 +1,169 @@
//#region rolldown:runtime
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
key = keys[i];
if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
get: ((k) => from[k]).bind(null, key),
enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
});
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
value: mod,
enumerable: true
}) : target, mod));
//#endregion
let node_path = require("node:path");
node_path = __toESM(node_path);
let picomatch = require("picomatch");
picomatch = __toESM(picomatch);
let acorn = require("acorn");
acorn = __toESM(acorn);
//#region src/utils/general.ts
function toArray(array) {
array = array || [];
if (Array.isArray(array)) return array;
return [array];
}
//#endregion
//#region src/utils/filter.ts
const BACKSLASH_REGEX = /\\/g;
function normalize(path) {
return path.replace(BACKSLASH_REGEX, "/");
}
const ABSOLUTE_PATH_REGEX = /^(?:\/|(?:[A-Z]:)?[/\\|])/i;
function isAbsolute(path) {
return ABSOLUTE_PATH_REGEX.test(path);
}
function getMatcherString(glob, cwd) {
if (glob.startsWith("**") || isAbsolute(glob)) return normalize(glob);
return normalize((0, node_path.resolve)(cwd, glob));
}
function patternToIdFilter(pattern) {
if (pattern instanceof RegExp) return (id) => {
const normalizedId = normalize(id);
const result = pattern.test(normalizedId);
pattern.lastIndex = 0;
return result;
};
const matcher = (0, picomatch.default)(getMatcherString(pattern, process.cwd()), { dot: true });
return (id) => {
return matcher(normalize(id));
};
}
function patternToCodeFilter(pattern) {
if (pattern instanceof RegExp) return (code) => {
const result = pattern.test(code);
pattern.lastIndex = 0;
return result;
};
return (code) => code.includes(pattern);
}
function createFilter(exclude, include) {
if (!exclude && !include) return;
return (input) => {
if (exclude?.some((filter) => filter(input))) return false;
if (include?.some((filter) => filter(input))) return true;
return !(include && include.length > 0);
};
}
function normalizeFilter(filter) {
if (typeof filter === "string" || filter instanceof RegExp) return { include: [filter] };
if (Array.isArray(filter)) return { include: filter };
return {
exclude: filter.exclude ? toArray(filter.exclude) : void 0,
include: filter.include ? toArray(filter.include) : void 0
};
}
function createIdFilter(filter) {
if (!filter) return;
const { exclude, include } = normalizeFilter(filter);
const excludeFilter = exclude?.map(patternToIdFilter);
const includeFilter = include?.map(patternToIdFilter);
return createFilter(excludeFilter, includeFilter);
}
function createCodeFilter(filter) {
if (!filter) return;
const { exclude, include } = normalizeFilter(filter);
const excludeFilter = exclude?.map(patternToCodeFilter);
const includeFilter = include?.map(patternToCodeFilter);
return createFilter(excludeFilter, includeFilter);
}
function createFilterForId(filter) {
const filterFunction = createIdFilter(filter);
return filterFunction ? (id) => !!filterFunction(id) : void 0;
}
function createFilterForTransform(idFilter, codeFilter) {
if (!idFilter && !codeFilter) return;
const idFilterFunction = createIdFilter(idFilter);
const codeFilterFunction = createCodeFilter(codeFilter);
return (id, code) => {
let fallback = true;
if (idFilterFunction) fallback &&= idFilterFunction(id);
if (!fallback) return false;
if (codeFilterFunction) fallback &&= codeFilterFunction(code);
return fallback;
};
}
function normalizeObjectHook(name, hook) {
let handler;
let filter;
if (typeof hook === "function") handler = hook;
else {
handler = hook.handler;
const hookFilter = hook.filter;
if (name === "resolveId" || name === "load") filter = createFilterForId(hookFilter?.id);
else filter = createFilterForTransform(hookFilter?.id, hookFilter?.code);
}
return {
handler,
filter: filter || (() => true)
};
}
//#endregion
//#region src/utils/context.ts
function parse(code, opts = {}) {
return acorn.Parser.parse(code, {
sourceType: "module",
ecmaVersion: "latest",
locations: true,
...opts
});
}
//#endregion
Object.defineProperty(exports, '__toESM', {
enumerable: true,
get: function () {
return __toESM;
}
});
Object.defineProperty(exports, 'normalizeObjectHook', {
enumerable: true,
get: function () {
return normalizeObjectHook;
}
});
Object.defineProperty(exports, 'parse', {
enumerable: true,
get: function () {
return parse;
}
});
Object.defineProperty(exports, 'toArray', {
enumerable: true,
get: function () {
return toArray;
}
});

View File

@@ -0,0 +1,69 @@
const require_context = require('./context-CQfDPcdE.cjs');
let node_path = require("node:path");
node_path = require_context.__toESM(node_path);
let node_buffer = require("node:buffer");
node_buffer = require_context.__toESM(node_buffer);
//#region src/rspack/context.ts
function createBuildContext(compiler, compilation, loaderContext, inputSourceMap) {
return {
getNativeBuildContext() {
return {
framework: "rspack",
compiler,
compilation,
loaderContext,
inputSourceMap
};
},
addWatchFile(file) {
const cwd = process.cwd();
compilation.fileDependencies.add((0, node_path.resolve)(cwd, file));
},
getWatchFiles() {
return Array.from(compilation.fileDependencies);
},
parse: require_context.parse,
emitFile(emittedFile) {
const outFileName = emittedFile.fileName || emittedFile.name;
if (emittedFile.source && outFileName) {
const { sources } = compilation.compiler.webpack;
compilation.emitAsset(outFileName, new sources.RawSource(typeof emittedFile.source === "string" ? emittedFile.source : node_buffer.Buffer.from(emittedFile.source)));
}
}
};
}
function createContext(loader) {
return {
error: (error) => loader.emitError(normalizeMessage(error)),
warn: (message) => loader.emitWarning(normalizeMessage(message))
};
}
function normalizeMessage(error) {
const err = new Error(typeof error === "string" ? error : error.message);
if (typeof error === "object") {
err.stack = error.stack;
err.cause = error.meta;
}
return err;
}
//#endregion
Object.defineProperty(exports, 'createBuildContext', {
enumerable: true,
get: function () {
return createBuildContext;
}
});
Object.defineProperty(exports, 'createContext', {
enumerable: true,
get: function () {
return createContext;
}
});
Object.defineProperty(exports, 'normalizeMessage', {
enumerable: true,
get: function () {
return normalizeMessage;
}
});

View File

@@ -0,0 +1,120 @@
import { resolve } from "node:path";
import picomatch from "picomatch";
import { Parser } from "acorn";
//#region src/utils/general.ts
function toArray(array) {
array = array || [];
if (Array.isArray(array)) return array;
return [array];
}
//#endregion
//#region src/utils/filter.ts
const BACKSLASH_REGEX = /\\/g;
function normalize$1(path$1) {
return path$1.replace(BACKSLASH_REGEX, "/");
}
const ABSOLUTE_PATH_REGEX = /^(?:\/|(?:[A-Z]:)?[/\\|])/i;
function isAbsolute$1(path$1) {
return ABSOLUTE_PATH_REGEX.test(path$1);
}
function getMatcherString(glob, cwd) {
if (glob.startsWith("**") || isAbsolute$1(glob)) return normalize$1(glob);
return normalize$1(resolve(cwd, glob));
}
function patternToIdFilter(pattern) {
if (pattern instanceof RegExp) return (id) => {
const normalizedId = normalize$1(id);
const result = pattern.test(normalizedId);
pattern.lastIndex = 0;
return result;
};
const matcher = picomatch(getMatcherString(pattern, process.cwd()), { dot: true });
return (id) => {
return matcher(normalize$1(id));
};
}
function patternToCodeFilter(pattern) {
if (pattern instanceof RegExp) return (code) => {
const result = pattern.test(code);
pattern.lastIndex = 0;
return result;
};
return (code) => code.includes(pattern);
}
function createFilter(exclude, include) {
if (!exclude && !include) return;
return (input) => {
if (exclude?.some((filter) => filter(input))) return false;
if (include?.some((filter) => filter(input))) return true;
return !(include && include.length > 0);
};
}
function normalizeFilter(filter) {
if (typeof filter === "string" || filter instanceof RegExp) return { include: [filter] };
if (Array.isArray(filter)) return { include: filter };
return {
exclude: filter.exclude ? toArray(filter.exclude) : void 0,
include: filter.include ? toArray(filter.include) : void 0
};
}
function createIdFilter(filter) {
if (!filter) return;
const { exclude, include } = normalizeFilter(filter);
const excludeFilter = exclude?.map(patternToIdFilter);
const includeFilter = include?.map(patternToIdFilter);
return createFilter(excludeFilter, includeFilter);
}
function createCodeFilter(filter) {
if (!filter) return;
const { exclude, include } = normalizeFilter(filter);
const excludeFilter = exclude?.map(patternToCodeFilter);
const includeFilter = include?.map(patternToCodeFilter);
return createFilter(excludeFilter, includeFilter);
}
function createFilterForId(filter) {
const filterFunction = createIdFilter(filter);
return filterFunction ? (id) => !!filterFunction(id) : void 0;
}
function createFilterForTransform(idFilter, codeFilter) {
if (!idFilter && !codeFilter) return;
const idFilterFunction = createIdFilter(idFilter);
const codeFilterFunction = createCodeFilter(codeFilter);
return (id, code) => {
let fallback = true;
if (idFilterFunction) fallback &&= idFilterFunction(id);
if (!fallback) return false;
if (codeFilterFunction) fallback &&= codeFilterFunction(code);
return fallback;
};
}
function normalizeObjectHook(name, hook) {
let handler;
let filter;
if (typeof hook === "function") handler = hook;
else {
handler = hook.handler;
const hookFilter = hook.filter;
if (name === "resolveId" || name === "load") filter = createFilterForId(hookFilter?.id);
else filter = createFilterForTransform(hookFilter?.id, hookFilter?.code);
}
return {
handler,
filter: filter || (() => true)
};
}
//#endregion
//#region src/utils/context.ts
function parse(code, opts = {}) {
return Parser.parse(code, {
sourceType: "module",
ecmaVersion: "latest",
locations: true,
...opts
});
}
//#endregion
export { normalizeObjectHook as n, toArray as r, parse as t };

View File

@@ -0,0 +1,92 @@
const require_context = require('./context-CQfDPcdE.cjs');
let node_path = require("node:path");
node_path = require_context.__toESM(node_path);
let node_buffer = require("node:buffer");
node_buffer = require_context.__toESM(node_buffer);
let node_process = require("node:process");
node_process = require_context.__toESM(node_process);
let node_module = require("node:module");
node_module = require_context.__toESM(node_module);
//#region src/webpack/context.ts
function contextOptionsFromCompilation(compilation) {
return {
addWatchFile(file) {
(compilation.fileDependencies ?? compilation.compilationDependencies).add(file);
},
getWatchFiles() {
return Array.from(compilation.fileDependencies ?? compilation.compilationDependencies);
}
};
}
const require$1 = (0, node_module.createRequire)(require("url").pathToFileURL(__filename).href);
function getSource(fileSource) {
return new (require$1("webpack")).sources.RawSource(typeof fileSource === "string" ? fileSource : node_buffer.Buffer.from(fileSource.buffer));
}
function createBuildContext(options, compiler, compilation, loaderContext, inputSourceMap) {
return {
parse: require_context.parse,
addWatchFile(id) {
options.addWatchFile((0, node_path.resolve)(node_process.default.cwd(), id));
},
emitFile(emittedFile) {
const outFileName = emittedFile.fileName || emittedFile.name;
if (emittedFile.source && outFileName) {
if (!compilation) throw new Error("unplugin/webpack: emitFile outside supported hooks (buildStart, buildEnd, load, transform, watchChange)");
compilation.emitAsset(outFileName, getSource(emittedFile.source));
}
},
getWatchFiles() {
return options.getWatchFiles();
},
getNativeBuildContext() {
return {
framework: "webpack",
compiler,
compilation,
loaderContext,
inputSourceMap
};
}
};
}
function createContext(loader) {
return {
error: (error) => loader.emitError(normalizeMessage(error)),
warn: (message) => loader.emitWarning(normalizeMessage(message))
};
}
function normalizeMessage(error) {
const err = new Error(typeof error === "string" ? error : error.message);
if (typeof error === "object") {
err.stack = error.stack;
err.cause = error.meta;
}
return err;
}
//#endregion
Object.defineProperty(exports, 'contextOptionsFromCompilation', {
enumerable: true,
get: function () {
return contextOptionsFromCompilation;
}
});
Object.defineProperty(exports, 'createBuildContext', {
enumerable: true,
get: function () {
return createBuildContext;
}
});
Object.defineProperty(exports, 'createContext', {
enumerable: true,
get: function () {
return createContext;
}
});
Object.defineProperty(exports, 'normalizeMessage', {
enumerable: true,
get: function () {
return normalizeMessage;
}
});

View File

@@ -0,0 +1,50 @@
import { t as parse } from "./context-Csj9j3eN.js";
import { resolve } from "node:path";
import { Buffer } from "node:buffer";
//#region src/rspack/context.ts
function createBuildContext(compiler, compilation, loaderContext, inputSourceMap) {
return {
getNativeBuildContext() {
return {
framework: "rspack",
compiler,
compilation,
loaderContext,
inputSourceMap
};
},
addWatchFile(file) {
const cwd = process.cwd();
compilation.fileDependencies.add(resolve(cwd, file));
},
getWatchFiles() {
return Array.from(compilation.fileDependencies);
},
parse,
emitFile(emittedFile) {
const outFileName = emittedFile.fileName || emittedFile.name;
if (emittedFile.source && outFileName) {
const { sources } = compilation.compiler.webpack;
compilation.emitAsset(outFileName, new sources.RawSource(typeof emittedFile.source === "string" ? emittedFile.source : Buffer.from(emittedFile.source)));
}
}
};
}
function createContext(loader) {
return {
error: (error) => loader.emitError(normalizeMessage(error)),
warn: (message) => loader.emitWarning(normalizeMessage(message))
};
}
function normalizeMessage(error) {
const err = new Error(typeof error === "string" ? error : error.message);
if (typeof error === "object") {
err.stack = error.stack;
err.cause = error.meta;
}
return err;
}
//#endregion
export { createContext as n, normalizeMessage as r, createBuildContext as t };

View File

@@ -0,0 +1,65 @@
import { t as parse } from "./context-Csj9j3eN.js";
import { createRequire } from "node:module";
import { resolve } from "node:path";
import { Buffer } from "node:buffer";
import process from "node:process";
//#region src/webpack/context.ts
function contextOptionsFromCompilation(compilation) {
return {
addWatchFile(file) {
(compilation.fileDependencies ?? compilation.compilationDependencies).add(file);
},
getWatchFiles() {
return Array.from(compilation.fileDependencies ?? compilation.compilationDependencies);
}
};
}
const require = createRequire(import.meta.url);
function getSource(fileSource) {
return new (require("webpack")).sources.RawSource(typeof fileSource === "string" ? fileSource : Buffer.from(fileSource.buffer));
}
function createBuildContext(options, compiler, compilation, loaderContext, inputSourceMap) {
return {
parse,
addWatchFile(id) {
options.addWatchFile(resolve(process.cwd(), id));
},
emitFile(emittedFile) {
const outFileName = emittedFile.fileName || emittedFile.name;
if (emittedFile.source && outFileName) {
if (!compilation) throw new Error("unplugin/webpack: emitFile outside supported hooks (buildStart, buildEnd, load, transform, watchChange)");
compilation.emitAsset(outFileName, getSource(emittedFile.source));
}
},
getWatchFiles() {
return options.getWatchFiles();
},
getNativeBuildContext() {
return {
framework: "webpack",
compiler,
compilation,
loaderContext,
inputSourceMap
};
}
};
}
function createContext(loader) {
return {
error: (error) => loader.emitError(normalizeMessage(error)),
warn: (message) => loader.emitWarning(normalizeMessage(message))
};
}
function normalizeMessage(error) {
const err = new Error(typeof error === "string" ? error : error.message);
if (typeof error === "object") {
err.stack = error.stack;
err.cause = error.meta;
}
return err;
}
//#endregion
export { normalizeMessage as i, createBuildContext as n, createContext as r, contextOptionsFromCompilation as t };

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,198 @@
import { CompilationContext, JsPlugin } from "@farmfe/core";
import { Compilation, Compiler as RspackCompiler, LoaderContext, RspackPluginInstance } from "@rspack/core";
import { BuildOptions, Loader, Plugin as EsbuildPlugin, PluginBuild } from "esbuild";
import { Plugin as RolldownPlugin } from "rolldown";
import { AstNode, EmittedAsset, Plugin as RollupPlugin, PluginContextMeta, SourceMapInput } from "rollup";
import { Plugin as UnloaderPlugin } from "unloader";
import { Plugin as VitePlugin } from "vite";
import { Compilation as Compilation$1, Compiler as WebpackCompiler, LoaderContext as LoaderContext$1, WebpackPluginInstance } from "webpack";
import VirtualModulesPlugin from "webpack-virtual-modules";
//#region src/types.d.ts
type Thenable<T> = T | Promise<T>;
/**
* Null or whatever
*/
type Nullable<T> = T | null | undefined;
/**
* Array, or not yet
*/
type Arrayable<T> = T | Array<T>;
interface SourceMapCompact {
file?: string | undefined;
mappings: string;
names: string[];
sourceRoot?: string | undefined;
sources: string[];
sourcesContent?: (string | null)[] | undefined;
version: number;
}
type TransformResult = string | {
code: string;
map?: SourceMapInput | SourceMapCompact | null | undefined;
} | null | undefined | void;
interface ExternalIdResult {
id: string;
external?: boolean | undefined;
}
type NativeBuildContext = {
framework: "webpack";
compiler: WebpackCompiler;
compilation?: Compilation$1 | undefined;
loaderContext?: LoaderContext$1<{
unpluginName: string;
}> | undefined;
inputSourceMap?: any;
} | {
framework: "esbuild";
build: PluginBuild;
} | {
framework: "rspack";
compiler: RspackCompiler;
compilation: Compilation;
loaderContext?: LoaderContext | undefined;
inputSourceMap?: any;
} | {
framework: "farm";
context: CompilationContext;
};
interface UnpluginBuildContext {
addWatchFile: (id: string) => void;
emitFile: (emittedFile: EmittedAsset) => void;
getWatchFiles: () => string[];
parse: (input: string, options?: any) => AstNode;
getNativeBuildContext?: (() => NativeBuildContext) | undefined;
}
type StringOrRegExp = string | RegExp;
type FilterPattern = Arrayable<StringOrRegExp>;
type StringFilter = FilterPattern | {
include?: FilterPattern | undefined;
exclude?: FilterPattern | undefined;
};
interface HookFilter {
id?: StringFilter | undefined;
code?: StringFilter | undefined;
}
interface ObjectHook<T extends HookFnMap[keyof HookFnMap], F extends keyof HookFilter> {
filter?: Pick<HookFilter, F> | undefined;
handler: T;
}
type Hook<T extends HookFnMap[keyof HookFnMap], F extends keyof HookFilter> = T | ObjectHook<T, F>;
interface HookFnMap {
buildStart: (this: UnpluginBuildContext) => Thenable<void>;
buildEnd: (this: UnpluginBuildContext) => Thenable<void>;
transform: (this: UnpluginBuildContext & UnpluginContext, code: string, id: string) => Thenable<TransformResult>;
load: (this: UnpluginBuildContext & UnpluginContext, id: string) => Thenable<TransformResult>;
resolveId: (this: UnpluginBuildContext & UnpluginContext, id: string, importer: string | undefined, options: {
isEntry: boolean;
}) => Thenable<string | ExternalIdResult | null | undefined>;
writeBundle: (this: void) => Thenable<void>;
}
interface UnpluginOptions {
name: string;
enforce?: "post" | "pre" | undefined;
buildStart?: HookFnMap["buildStart"] | undefined;
buildEnd?: HookFnMap["buildEnd"] | undefined;
transform?: Hook<HookFnMap["transform"], "code" | "id"> | undefined;
load?: Hook<HookFnMap["load"], "id"> | undefined;
resolveId?: Hook<HookFnMap["resolveId"], "id"> | undefined;
writeBundle?: HookFnMap["writeBundle"] | undefined;
watchChange?: ((this: UnpluginBuildContext, id: string, change: {
event: "create" | "update" | "delete";
}) => void) | undefined;
/**
* Custom predicate function to filter modules to be loaded.
* When omitted, all modules will be included (might have potential perf impact on Webpack).
*
* @deprecated Use `load.filter` instead.
*/
loadInclude?: ((id: string) => boolean | null | undefined) | undefined;
/**
* Custom predicate function to filter modules to be transformed.
* When omitted, all modules will be included (might have potential perf impact on Webpack).
*
* @deprecated Use `transform.filter` instead.
*/
transformInclude?: ((id: string) => boolean | null | undefined) | undefined;
rollup?: Partial<RollupPlugin> | undefined;
webpack?: ((compiler: WebpackCompiler) => void) | undefined;
rspack?: ((compiler: RspackCompiler) => void) | undefined;
vite?: Partial<VitePlugin> | undefined;
unloader?: Partial<UnloaderPlugin> | undefined;
rolldown?: Partial<RolldownPlugin> | undefined;
esbuild?: {
onResolveFilter?: RegExp | undefined;
onLoadFilter?: RegExp | undefined;
loader?: Loader | ((code: string, id: string) => Loader) | undefined;
setup?: ((build: PluginBuild) => void | Promise<void>) | undefined;
config?: ((options: BuildOptions) => void) | undefined;
} | undefined;
farm?: Partial<JsPlugin> | undefined;
}
interface ResolvedUnpluginOptions extends UnpluginOptions {
__vfs?: VirtualModulesPlugin | undefined;
__vfsModules?: Map<string, Promise<unknown>> | Set<string> | undefined;
__virtualModulePrefix: string;
}
type UnpluginFactory<UserOptions, Nested extends boolean = boolean> = (options: UserOptions, meta: UnpluginContextMeta) => Nested extends true ? Array<UnpluginOptions> : UnpluginOptions;
type UnpluginFactoryOutput<UserOptions, Return> = undefined extends UserOptions ? (options?: UserOptions | undefined) => Return : (options: UserOptions) => Return;
interface UnpluginInstance<UserOptions, Nested extends boolean = boolean> {
rollup: UnpluginFactoryOutput<UserOptions, Nested extends true ? Array<RollupPlugin> : RollupPlugin>;
vite: UnpluginFactoryOutput<UserOptions, Nested extends true ? Array<VitePlugin> : VitePlugin>;
rolldown: UnpluginFactoryOutput<UserOptions, Nested extends true ? Array<RolldownPlugin> : RolldownPlugin>;
webpack: UnpluginFactoryOutput<UserOptions, WebpackPluginInstance>;
rspack: UnpluginFactoryOutput<UserOptions, RspackPluginInstance>;
esbuild: UnpluginFactoryOutput<UserOptions, EsbuildPlugin>;
unloader: UnpluginFactoryOutput<UserOptions, Nested extends true ? Array<UnloaderPlugin> : UnloaderPlugin>;
farm: UnpluginFactoryOutput<UserOptions, JsPlugin>;
raw: UnpluginFactory<UserOptions, Nested>;
}
type UnpluginContextMeta = Partial<PluginContextMeta> & ({
framework: "rollup" | "vite" | "rolldown" | "farm" | "unloader";
} | {
framework: "webpack";
webpack: {
compiler: WebpackCompiler;
};
} | {
framework: "esbuild";
/** Set the host plugin name of esbuild when returning multiple plugins */
esbuildHostName?: string | undefined;
} | {
framework: "rspack";
rspack: {
compiler: RspackCompiler;
};
});
interface UnpluginMessage {
name?: string | undefined;
id?: string | undefined;
message: string;
stack?: string | undefined;
code?: string | undefined;
plugin?: string | undefined;
pluginCode?: unknown | undefined;
loc?: {
column: number;
file?: string | undefined;
line: number;
} | undefined;
meta?: any;
}
interface UnpluginContext {
error: (message: string | UnpluginMessage) => void;
warn: (message: string | UnpluginMessage) => void;
}
//#endregion
//#region src/define.d.ts
declare function createUnplugin<UserOptions, Nested extends boolean = boolean>(factory: UnpluginFactory<UserOptions, Nested>): UnpluginInstance<UserOptions, Nested>;
declare function createEsbuildPlugin<UserOptions, Nested extends boolean = boolean>(factory: UnpluginFactory<UserOptions, Nested>): UnpluginInstance<UserOptions>["esbuild"];
declare function createRollupPlugin<UserOptions, Nested extends boolean = boolean>(factory: UnpluginFactory<UserOptions, Nested>): UnpluginInstance<UserOptions>["rollup"];
declare function createVitePlugin<UserOptions, Nested extends boolean = boolean>(factory: UnpluginFactory<UserOptions, Nested>): UnpluginInstance<UserOptions>["vite"];
declare function createRolldownPlugin<UserOptions, Nested extends boolean = boolean>(factory: UnpluginFactory<UserOptions, Nested>): UnpluginInstance<UserOptions>["rolldown"];
declare function createWebpackPlugin<UserOptions, Nested extends boolean = boolean>(factory: UnpluginFactory<UserOptions, Nested>): UnpluginInstance<UserOptions>["webpack"];
declare function createRspackPlugin<UserOptions, Nested extends boolean = boolean>(factory: UnpluginFactory<UserOptions, Nested>): UnpluginInstance<UserOptions>["rspack"];
declare function createFarmPlugin<UserOptions, Nested extends boolean = boolean>(factory: UnpluginFactory<UserOptions, Nested>): UnpluginInstance<UserOptions>["farm"];
declare function createUnloaderPlugin<UserOptions, Nested extends boolean = boolean>(factory: UnpluginFactory<UserOptions, Nested>): UnpluginInstance<UserOptions>["unloader"];
//#endregion
export { Arrayable, type EsbuildPlugin, ExternalIdResult, FilterPattern, Hook, HookFilter, HookFnMap, NativeBuildContext, Nullable, ObjectHook, ResolvedUnpluginOptions, type RolldownPlugin, type RollupPlugin, type RspackCompiler, type RspackPluginInstance, SourceMapCompact, StringFilter, StringOrRegExp, Thenable, TransformResult, type UnloaderPlugin, UnpluginBuildContext, UnpluginContext, UnpluginContextMeta, UnpluginFactory, UnpluginFactoryOutput, UnpluginInstance, UnpluginMessage, UnpluginOptions, type VitePlugin, type WebpackCompiler, type WebpackPluginInstance, createEsbuildPlugin, createFarmPlugin, createRolldownPlugin, createRollupPlugin, createRspackPlugin, createUnloaderPlugin, createUnplugin, createVitePlugin, createWebpackPlugin };

View File

@@ -0,0 +1,198 @@
import VirtualModulesPlugin from "webpack-virtual-modules";
import { CompilationContext, JsPlugin } from "@farmfe/core";
import { Compilation, Compiler as RspackCompiler, LoaderContext, RspackPluginInstance } from "@rspack/core";
import { BuildOptions, Loader, Plugin as EsbuildPlugin, PluginBuild } from "esbuild";
import { Plugin as RolldownPlugin } from "rolldown";
import { AstNode, EmittedAsset, Plugin as RollupPlugin, PluginContextMeta, SourceMapInput } from "rollup";
import { Plugin as UnloaderPlugin } from "unloader";
import { Plugin as VitePlugin } from "vite";
import { Compilation as Compilation$1, Compiler as WebpackCompiler, LoaderContext as LoaderContext$1, WebpackPluginInstance } from "webpack";
//#region src/types.d.ts
type Thenable<T> = T | Promise<T>;
/**
* Null or whatever
*/
type Nullable<T> = T | null | undefined;
/**
* Array, or not yet
*/
type Arrayable<T> = T | Array<T>;
interface SourceMapCompact {
file?: string | undefined;
mappings: string;
names: string[];
sourceRoot?: string | undefined;
sources: string[];
sourcesContent?: (string | null)[] | undefined;
version: number;
}
type TransformResult = string | {
code: string;
map?: SourceMapInput | SourceMapCompact | null | undefined;
} | null | undefined | void;
interface ExternalIdResult {
id: string;
external?: boolean | undefined;
}
type NativeBuildContext = {
framework: "webpack";
compiler: WebpackCompiler;
compilation?: Compilation$1 | undefined;
loaderContext?: LoaderContext$1<{
unpluginName: string;
}> | undefined;
inputSourceMap?: any;
} | {
framework: "esbuild";
build: PluginBuild;
} | {
framework: "rspack";
compiler: RspackCompiler;
compilation: Compilation;
loaderContext?: LoaderContext | undefined;
inputSourceMap?: any;
} | {
framework: "farm";
context: CompilationContext;
};
interface UnpluginBuildContext {
addWatchFile: (id: string) => void;
emitFile: (emittedFile: EmittedAsset) => void;
getWatchFiles: () => string[];
parse: (input: string, options?: any) => AstNode;
getNativeBuildContext?: (() => NativeBuildContext) | undefined;
}
type StringOrRegExp = string | RegExp;
type FilterPattern = Arrayable<StringOrRegExp>;
type StringFilter = FilterPattern | {
include?: FilterPattern | undefined;
exclude?: FilterPattern | undefined;
};
interface HookFilter {
id?: StringFilter | undefined;
code?: StringFilter | undefined;
}
interface ObjectHook<T extends HookFnMap[keyof HookFnMap], F extends keyof HookFilter> {
filter?: Pick<HookFilter, F> | undefined;
handler: T;
}
type Hook<T extends HookFnMap[keyof HookFnMap], F extends keyof HookFilter> = T | ObjectHook<T, F>;
interface HookFnMap {
buildStart: (this: UnpluginBuildContext) => Thenable<void>;
buildEnd: (this: UnpluginBuildContext) => Thenable<void>;
transform: (this: UnpluginBuildContext & UnpluginContext, code: string, id: string) => Thenable<TransformResult>;
load: (this: UnpluginBuildContext & UnpluginContext, id: string) => Thenable<TransformResult>;
resolveId: (this: UnpluginBuildContext & UnpluginContext, id: string, importer: string | undefined, options: {
isEntry: boolean;
}) => Thenable<string | ExternalIdResult | null | undefined>;
writeBundle: (this: void) => Thenable<void>;
}
interface UnpluginOptions {
name: string;
enforce?: "post" | "pre" | undefined;
buildStart?: HookFnMap["buildStart"] | undefined;
buildEnd?: HookFnMap["buildEnd"] | undefined;
transform?: Hook<HookFnMap["transform"], "code" | "id"> | undefined;
load?: Hook<HookFnMap["load"], "id"> | undefined;
resolveId?: Hook<HookFnMap["resolveId"], "id"> | undefined;
writeBundle?: HookFnMap["writeBundle"] | undefined;
watchChange?: ((this: UnpluginBuildContext, id: string, change: {
event: "create" | "update" | "delete";
}) => void) | undefined;
/**
* Custom predicate function to filter modules to be loaded.
* When omitted, all modules will be included (might have potential perf impact on Webpack).
*
* @deprecated Use `load.filter` instead.
*/
loadInclude?: ((id: string) => boolean | null | undefined) | undefined;
/**
* Custom predicate function to filter modules to be transformed.
* When omitted, all modules will be included (might have potential perf impact on Webpack).
*
* @deprecated Use `transform.filter` instead.
*/
transformInclude?: ((id: string) => boolean | null | undefined) | undefined;
rollup?: Partial<RollupPlugin> | undefined;
webpack?: ((compiler: WebpackCompiler) => void) | undefined;
rspack?: ((compiler: RspackCompiler) => void) | undefined;
vite?: Partial<VitePlugin> | undefined;
unloader?: Partial<UnloaderPlugin> | undefined;
rolldown?: Partial<RolldownPlugin> | undefined;
esbuild?: {
onResolveFilter?: RegExp | undefined;
onLoadFilter?: RegExp | undefined;
loader?: Loader | ((code: string, id: string) => Loader) | undefined;
setup?: ((build: PluginBuild) => void | Promise<void>) | undefined;
config?: ((options: BuildOptions) => void) | undefined;
} | undefined;
farm?: Partial<JsPlugin> | undefined;
}
interface ResolvedUnpluginOptions extends UnpluginOptions {
__vfs?: VirtualModulesPlugin | undefined;
__vfsModules?: Map<string, Promise<unknown>> | Set<string> | undefined;
__virtualModulePrefix: string;
}
type UnpluginFactory<UserOptions, Nested extends boolean = boolean> = (options: UserOptions, meta: UnpluginContextMeta) => Nested extends true ? Array<UnpluginOptions> : UnpluginOptions;
type UnpluginFactoryOutput<UserOptions, Return> = undefined extends UserOptions ? (options?: UserOptions | undefined) => Return : (options: UserOptions) => Return;
interface UnpluginInstance<UserOptions, Nested extends boolean = boolean> {
rollup: UnpluginFactoryOutput<UserOptions, Nested extends true ? Array<RollupPlugin> : RollupPlugin>;
vite: UnpluginFactoryOutput<UserOptions, Nested extends true ? Array<VitePlugin> : VitePlugin>;
rolldown: UnpluginFactoryOutput<UserOptions, Nested extends true ? Array<RolldownPlugin> : RolldownPlugin>;
webpack: UnpluginFactoryOutput<UserOptions, WebpackPluginInstance>;
rspack: UnpluginFactoryOutput<UserOptions, RspackPluginInstance>;
esbuild: UnpluginFactoryOutput<UserOptions, EsbuildPlugin>;
unloader: UnpluginFactoryOutput<UserOptions, Nested extends true ? Array<UnloaderPlugin> : UnloaderPlugin>;
farm: UnpluginFactoryOutput<UserOptions, JsPlugin>;
raw: UnpluginFactory<UserOptions, Nested>;
}
type UnpluginContextMeta = Partial<PluginContextMeta> & ({
framework: "rollup" | "vite" | "rolldown" | "farm" | "unloader";
} | {
framework: "webpack";
webpack: {
compiler: WebpackCompiler;
};
} | {
framework: "esbuild";
/** Set the host plugin name of esbuild when returning multiple plugins */
esbuildHostName?: string | undefined;
} | {
framework: "rspack";
rspack: {
compiler: RspackCompiler;
};
});
interface UnpluginMessage {
name?: string | undefined;
id?: string | undefined;
message: string;
stack?: string | undefined;
code?: string | undefined;
plugin?: string | undefined;
pluginCode?: unknown | undefined;
loc?: {
column: number;
file?: string | undefined;
line: number;
} | undefined;
meta?: any;
}
interface UnpluginContext {
error: (message: string | UnpluginMessage) => void;
warn: (message: string | UnpluginMessage) => void;
}
//#endregion
//#region src/define.d.ts
declare function createUnplugin<UserOptions, Nested extends boolean = boolean>(factory: UnpluginFactory<UserOptions, Nested>): UnpluginInstance<UserOptions, Nested>;
declare function createEsbuildPlugin<UserOptions, Nested extends boolean = boolean>(factory: UnpluginFactory<UserOptions, Nested>): UnpluginInstance<UserOptions>["esbuild"];
declare function createRollupPlugin<UserOptions, Nested extends boolean = boolean>(factory: UnpluginFactory<UserOptions, Nested>): UnpluginInstance<UserOptions>["rollup"];
declare function createVitePlugin<UserOptions, Nested extends boolean = boolean>(factory: UnpluginFactory<UserOptions, Nested>): UnpluginInstance<UserOptions>["vite"];
declare function createRolldownPlugin<UserOptions, Nested extends boolean = boolean>(factory: UnpluginFactory<UserOptions, Nested>): UnpluginInstance<UserOptions>["rolldown"];
declare function createWebpackPlugin<UserOptions, Nested extends boolean = boolean>(factory: UnpluginFactory<UserOptions, Nested>): UnpluginInstance<UserOptions>["webpack"];
declare function createRspackPlugin<UserOptions, Nested extends boolean = boolean>(factory: UnpluginFactory<UserOptions, Nested>): UnpluginInstance<UserOptions>["rspack"];
declare function createFarmPlugin<UserOptions, Nested extends boolean = boolean>(factory: UnpluginFactory<UserOptions, Nested>): UnpluginInstance<UserOptions>["farm"];
declare function createUnloaderPlugin<UserOptions, Nested extends boolean = boolean>(factory: UnpluginFactory<UserOptions, Nested>): UnpluginInstance<UserOptions>["unloader"];
//#endregion
export { Arrayable, type EsbuildPlugin, ExternalIdResult, FilterPattern, Hook, HookFilter, HookFnMap, NativeBuildContext, Nullable, ObjectHook, ResolvedUnpluginOptions, type RolldownPlugin, type RollupPlugin, type RspackCompiler, type RspackPluginInstance, SourceMapCompact, StringFilter, StringOrRegExp, Thenable, TransformResult, type UnloaderPlugin, UnpluginBuildContext, UnpluginContext, UnpluginContextMeta, UnpluginFactory, UnpluginFactoryOutput, UnpluginInstance, UnpluginMessage, UnpluginOptions, type VitePlugin, type WebpackCompiler, type WebpackPluginInstance, createEsbuildPlugin, createFarmPlugin, createRolldownPlugin, createRollupPlugin, createRspackPlugin, createUnloaderPlugin, createUnplugin, createVitePlugin, createWebpackPlugin };

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,27 @@
const require_context = require('../../context-CQfDPcdE.cjs');
const require_webpack_like = require('../../webpack-like-DDVwPJ4e.cjs');
const require_context$1 = require('../../context-CrbHoDid.cjs');
const require_utils = require('../../utils-CJMEEaD7.cjs');
//#region src/rspack/loaders/load.ts
async function load(source, map) {
const callback = this.async();
const { plugin } = this.query;
let id = this.resource;
if (!plugin?.load || !id) return callback(null, source, map);
if (require_utils.isVirtualModuleId(id, plugin)) id = require_utils.decodeVirtualModuleId(id, plugin);
const context = require_context$1.createContext(this);
const { handler } = require_context.normalizeObjectHook("load", plugin.load);
try {
const res = await handler.call(Object.assign({}, this._compilation && require_context$1.createBuildContext(this._compiler, this._compilation, this), context), require_webpack_like.normalizeAbsolutePath(id));
if (res == null) callback(null, source, map);
else if (typeof res !== "string") callback(null, res.code, res.map ?? map);
else callback(null, res, map);
} catch (error) {
if (error instanceof Error) callback(error);
else callback(new Error(String(error)));
}
}
//#endregion
module.exports = load;

View File

@@ -0,0 +1,5 @@
import { LoaderContext } from "@rspack/core";
//#region src/rspack/loaders/load.d.ts
declare function load(this: LoaderContext, source: string, map: any): Promise<void>;
export = load;

View File

@@ -0,0 +1,6 @@
import { LoaderContext } from "@rspack/core";
//#region src/rspack/loaders/load.d.ts
declare function load(this: LoaderContext, source: string, map: any): Promise<void>;
//#endregion
export { load as default };

View File

@@ -0,0 +1,27 @@
import { n as normalizeObjectHook } from "../../context-Csj9j3eN.js";
import { t as normalizeAbsolutePath } from "../../webpack-like-DFGTNSuV.js";
import { n as createContext, t as createBuildContext } from "../../context-DkYlx1xL.js";
import { i as isVirtualModuleId, n as decodeVirtualModuleId } from "../../utils-BosfZ0pB.js";
//#region src/rspack/loaders/load.ts
async function load(source, map) {
const callback = this.async();
const { plugin } = this.query;
let id = this.resource;
if (!plugin?.load || !id) return callback(null, source, map);
if (isVirtualModuleId(id, plugin)) id = decodeVirtualModuleId(id, plugin);
const context = createContext(this);
const { handler } = normalizeObjectHook("load", plugin.load);
try {
const res = await handler.call(Object.assign({}, this._compilation && createBuildContext(this._compiler, this._compilation, this), context), normalizeAbsolutePath(id));
if (res == null) callback(null, source, map);
else if (typeof res !== "string") callback(null, res.code, res.map ?? map);
else callback(null, res, map);
} catch (error) {
if (error instanceof Error) callback(error);
else callback(new Error(String(error)));
}
}
//#endregion
export { load as default };

View File

@@ -0,0 +1,25 @@
const require_context = require('../../context-CQfDPcdE.cjs');
const require_context$1 = require('../../context-CrbHoDid.cjs');
//#region src/rspack/loaders/transform.ts
async function transform(source, map) {
const callback = this.async();
const { plugin } = this.query;
if (!plugin?.transform) return callback(null, source, map);
const id = this.resource;
const context = require_context$1.createContext(this);
const { handler, filter } = require_context.normalizeObjectHook("transform", plugin.transform);
if (!filter(this.resource, source)) return callback(null, source, map);
try {
const res = await handler.call(Object.assign({}, this._compilation && require_context$1.createBuildContext(this._compiler, this._compilation, this, map), context), source, id);
if (res == null) callback(null, source, map);
else if (typeof res !== "string") callback(null, res.code, map == null ? map : res.map || map);
else callback(null, res, map);
} catch (error) {
if (error instanceof Error) callback(error);
else callback(new Error(String(error)));
}
}
//#endregion
module.exports = transform;

View File

@@ -0,0 +1,5 @@
import { LoaderContext } from "@rspack/core";
//#region src/rspack/loaders/transform.d.ts
declare function transform(this: LoaderContext, source: string, map: any): Promise<void>;
export = transform;

View File

@@ -0,0 +1,6 @@
import { LoaderContext } from "@rspack/core";
//#region src/rspack/loaders/transform.d.ts
declare function transform(this: LoaderContext, source: string, map: any): Promise<void>;
//#endregion
export { transform as default };

View File

@@ -0,0 +1,25 @@
import { n as normalizeObjectHook } from "../../context-Csj9j3eN.js";
import { n as createContext, t as createBuildContext } from "../../context-DkYlx1xL.js";
//#region src/rspack/loaders/transform.ts
async function transform(source, map) {
const callback = this.async();
const { plugin } = this.query;
if (!plugin?.transform) return callback(null, source, map);
const id = this.resource;
const context = createContext(this);
const { handler, filter } = normalizeObjectHook("transform", plugin.transform);
if (!filter(this.resource, source)) return callback(null, source, map);
try {
const res = await handler.call(Object.assign({}, this._compilation && createBuildContext(this._compiler, this._compilation, this, map), context), source, id);
if (res == null) callback(null, source, map);
else if (typeof res !== "string") callback(null, res.code, map == null ? map : res.map || map);
else callback(null, res, map);
} catch (error) {
if (error instanceof Error) callback(error);
else callback(new Error(String(error)));
}
}
//#endregion
export { transform as default };

View File

@@ -0,0 +1,54 @@
import fs from "node:fs";
import { basename, dirname, resolve } from "node:path";
//#region src/rspack/utils.ts
function encodeVirtualModuleId(id, plugin) {
return resolve(plugin.__virtualModulePrefix, encodeURIComponent(id));
}
function decodeVirtualModuleId(encoded, _plugin) {
return decodeURIComponent(basename(encoded));
}
function isVirtualModuleId(encoded, plugin) {
return dirname(encoded) === plugin.__virtualModulePrefix;
}
var FakeVirtualModulesPlugin = class FakeVirtualModulesPlugin {
name = "FakeVirtualModulesPlugin";
static counters = /* @__PURE__ */ new Map();
static initCleanup = false;
constructor(plugin) {
this.plugin = plugin;
if (!FakeVirtualModulesPlugin.initCleanup) {
FakeVirtualModulesPlugin.initCleanup = true;
process.once("exit", () => {
FakeVirtualModulesPlugin.counters.forEach((_, dir) => {
fs.rmSync(dir, {
recursive: true,
force: true
});
});
});
}
}
apply(compiler) {
const dir = this.plugin.__virtualModulePrefix;
if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
const counter = FakeVirtualModulesPlugin.counters.get(dir) ?? 0;
FakeVirtualModulesPlugin.counters.set(dir, counter + 1);
compiler.hooks.shutdown.tap(this.name, () => {
const counter$1 = (FakeVirtualModulesPlugin.counters.get(dir) ?? 1) - 1;
if (counter$1 === 0) {
FakeVirtualModulesPlugin.counters.delete(dir);
fs.rmSync(dir, {
recursive: true,
force: true
});
} else FakeVirtualModulesPlugin.counters.set(dir, counter$1);
});
}
async writeModule(file) {
return fs.promises.writeFile(file, "");
}
};
//#endregion
export { isVirtualModuleId as i, decodeVirtualModuleId as n, encodeVirtualModuleId as r, FakeVirtualModulesPlugin as t };

View File

@@ -0,0 +1,80 @@
const require_context = require('./context-CQfDPcdE.cjs');
let node_fs = require("node:fs");
node_fs = require_context.__toESM(node_fs);
let node_path = require("node:path");
node_path = require_context.__toESM(node_path);
//#region src/rspack/utils.ts
function encodeVirtualModuleId(id, plugin) {
return (0, node_path.resolve)(plugin.__virtualModulePrefix, encodeURIComponent(id));
}
function decodeVirtualModuleId(encoded, _plugin) {
return decodeURIComponent((0, node_path.basename)(encoded));
}
function isVirtualModuleId(encoded, plugin) {
return (0, node_path.dirname)(encoded) === plugin.__virtualModulePrefix;
}
var FakeVirtualModulesPlugin = class FakeVirtualModulesPlugin {
name = "FakeVirtualModulesPlugin";
static counters = /* @__PURE__ */ new Map();
static initCleanup = false;
constructor(plugin) {
this.plugin = plugin;
if (!FakeVirtualModulesPlugin.initCleanup) {
FakeVirtualModulesPlugin.initCleanup = true;
process.once("exit", () => {
FakeVirtualModulesPlugin.counters.forEach((_, dir) => {
node_fs.default.rmSync(dir, {
recursive: true,
force: true
});
});
});
}
}
apply(compiler) {
const dir = this.plugin.__virtualModulePrefix;
if (!node_fs.default.existsSync(dir)) node_fs.default.mkdirSync(dir, { recursive: true });
const counter = FakeVirtualModulesPlugin.counters.get(dir) ?? 0;
FakeVirtualModulesPlugin.counters.set(dir, counter + 1);
compiler.hooks.shutdown.tap(this.name, () => {
const counter$1 = (FakeVirtualModulesPlugin.counters.get(dir) ?? 1) - 1;
if (counter$1 === 0) {
FakeVirtualModulesPlugin.counters.delete(dir);
node_fs.default.rmSync(dir, {
recursive: true,
force: true
});
} else FakeVirtualModulesPlugin.counters.set(dir, counter$1);
});
}
async writeModule(file) {
return node_fs.default.promises.writeFile(file, "");
}
};
//#endregion
Object.defineProperty(exports, 'FakeVirtualModulesPlugin', {
enumerable: true,
get: function () {
return FakeVirtualModulesPlugin;
}
});
Object.defineProperty(exports, 'decodeVirtualModuleId', {
enumerable: true,
get: function () {
return decodeVirtualModuleId;
}
});
Object.defineProperty(exports, 'encodeVirtualModuleId', {
enumerable: true,
get: function () {
return encodeVirtualModuleId;
}
});
Object.defineProperty(exports, 'isVirtualModuleId', {
enumerable: true,
get: function () {
return isVirtualModuleId;
}
});

View File

@@ -0,0 +1,45 @@
const require_context = require('./context-CQfDPcdE.cjs');
let node_path = require("node:path");
node_path = require_context.__toESM(node_path);
//#region src/utils/webpack-like.ts
function transformUse(data, plugin, transformLoader) {
if (data.resource == null) return [];
const id = normalizeAbsolutePath(data.resource + (data.resourceQuery || ""));
if (plugin.transformInclude && !plugin.transformInclude(id)) return [];
const { filter } = require_context.normalizeObjectHook("load", plugin.transform);
if (!filter(id)) return [];
return [{
loader: transformLoader,
options: { plugin },
ident: plugin.name
}];
}
/**
* Normalizes a given path when it's absolute. Normalizing means returning a new path by converting
* the input path to the native os format. This is useful in cases where we want to normalize
* the `id` argument of a hook. Any absolute ids should be in the default format
* of the operating system. Any relative imports or node_module imports should remain
* untouched.
*
* @param path - Path to normalize.
* @returns a new normalized path.
*/
function normalizeAbsolutePath(path) {
if ((0, node_path.isAbsolute)(path)) return (0, node_path.normalize)(path);
else return path;
}
//#endregion
Object.defineProperty(exports, 'normalizeAbsolutePath', {
enumerable: true,
get: function () {
return normalizeAbsolutePath;
}
});
Object.defineProperty(exports, 'transformUse', {
enumerable: true,
get: function () {
return transformUse;
}
});

View File

@@ -0,0 +1,33 @@
import { n as normalizeObjectHook } from "./context-Csj9j3eN.js";
import { isAbsolute, normalize } from "node:path";
//#region src/utils/webpack-like.ts
function transformUse(data, plugin, transformLoader) {
if (data.resource == null) return [];
const id = normalizeAbsolutePath(data.resource + (data.resourceQuery || ""));
if (plugin.transformInclude && !plugin.transformInclude(id)) return [];
const { filter } = normalizeObjectHook("load", plugin.transform);
if (!filter(id)) return [];
return [{
loader: transformLoader,
options: { plugin },
ident: plugin.name
}];
}
/**
* Normalizes a given path when it's absolute. Normalizing means returning a new path by converting
* the input path to the native os format. This is useful in cases where we want to normalize
* the `id` argument of a hook. Any absolute ids should be in the default format
* of the operating system. Any relative imports or node_module imports should remain
* untouched.
*
* @param path - Path to normalize.
* @returns a new normalized path.
*/
function normalizeAbsolutePath(path$1) {
if (isAbsolute(path$1)) return normalize(path$1);
else return path$1;
}
//#endregion
export { transformUse as n, normalizeAbsolutePath as t };

View File

@@ -0,0 +1,28 @@
const require_context = require('../../context-CQfDPcdE.cjs');
const require_webpack_like = require('../../webpack-like-DDVwPJ4e.cjs');
const require_context$1 = require('../../context-D7WFmOmt.cjs');
//#region src/webpack/loaders/load.ts
async function load(source, map) {
const callback = this.async();
const { plugin } = this.query;
let id = this.resource;
if (!plugin?.load || !id) return callback(null, source, map);
if (id.startsWith(plugin.__virtualModulePrefix)) id = decodeURIComponent(id.slice(plugin.__virtualModulePrefix.length));
const context = require_context$1.createContext(this);
const { handler } = require_context.normalizeObjectHook("load", plugin.load);
const res = await handler.call(Object.assign({}, require_context$1.createBuildContext({
addWatchFile: (file) => {
this.addDependency(file);
},
getWatchFiles: () => {
return this.getDependencies();
}
}, this._compiler, this._compilation, this), context), require_webpack_like.normalizeAbsolutePath(id));
if (res == null) callback(null, source, map);
else if (typeof res !== "string") callback(null, res.code, res.map ?? map);
else callback(null, res, map);
}
//#endregion
module.exports = load;

View File

@@ -0,0 +1,5 @@
import { LoaderContext } from "webpack";
//#region src/webpack/loaders/load.d.ts
declare function load(this: LoaderContext<any>, source: string, map: any): Promise<void>;
export = load;

View File

@@ -0,0 +1,6 @@
import { LoaderContext } from "webpack";
//#region src/webpack/loaders/load.d.ts
declare function load(this: LoaderContext<any>, source: string, map: any): Promise<void>;
//#endregion
export { load as default };

View File

@@ -0,0 +1,28 @@
import { n as normalizeObjectHook } from "../../context-Csj9j3eN.js";
import { t as normalizeAbsolutePath } from "../../webpack-like-DFGTNSuV.js";
import { n as createBuildContext, r as createContext } from "../../context-OCFO8EW1.js";
//#region src/webpack/loaders/load.ts
async function load(source, map) {
const callback = this.async();
const { plugin } = this.query;
let id = this.resource;
if (!plugin?.load || !id) return callback(null, source, map);
if (id.startsWith(plugin.__virtualModulePrefix)) id = decodeURIComponent(id.slice(plugin.__virtualModulePrefix.length));
const context = createContext(this);
const { handler } = normalizeObjectHook("load", plugin.load);
const res = await handler.call(Object.assign({}, createBuildContext({
addWatchFile: (file) => {
this.addDependency(file);
},
getWatchFiles: () => {
return this.getDependencies();
}
}, this._compiler, this._compilation, this), context), normalizeAbsolutePath(id));
if (res == null) callback(null, source, map);
else if (typeof res !== "string") callback(null, res.code, res.map ?? map);
else callback(null, res, map);
}
//#endregion
export { load as default };

View File

@@ -0,0 +1,31 @@
const require_context = require('../../context-CQfDPcdE.cjs');
const require_context$1 = require('../../context-D7WFmOmt.cjs');
//#region src/webpack/loaders/transform.ts
async function transform(source, map) {
const callback = this.async();
const { plugin } = this.query;
if (!plugin?.transform) return callback(null, source, map);
const context = require_context$1.createContext(this);
const { handler, filter } = require_context.normalizeObjectHook("transform", plugin.transform);
if (!filter(this.resource, source)) return callback(null, source, map);
try {
const res = await handler.call(Object.assign({}, require_context$1.createBuildContext({
addWatchFile: (file) => {
this.addDependency(file);
},
getWatchFiles: () => {
return this.getDependencies();
}
}, this._compiler, this._compilation, this, map), context), source, this.resource);
if (res == null) callback(null, source, map);
else if (typeof res !== "string") callback(null, res.code, map == null ? map : res.map || map);
else callback(null, res, map);
} catch (error) {
if (error instanceof Error) callback(error);
else callback(new Error(String(error)));
}
}
//#endregion
module.exports = transform;

View File

@@ -0,0 +1,5 @@
import { LoaderContext } from "webpack";
//#region src/webpack/loaders/transform.d.ts
declare function transform(this: LoaderContext<any>, source: string, map: any): Promise<void>;
export = transform;

View File

@@ -0,0 +1,6 @@
import { LoaderContext } from "webpack";
//#region src/webpack/loaders/transform.d.ts
declare function transform(this: LoaderContext<any>, source: string, map: any): Promise<void>;
//#endregion
export { transform as default };

View File

@@ -0,0 +1,31 @@
import { n as normalizeObjectHook } from "../../context-Csj9j3eN.js";
import { n as createBuildContext, r as createContext } from "../../context-OCFO8EW1.js";
//#region src/webpack/loaders/transform.ts
async function transform(source, map) {
const callback = this.async();
const { plugin } = this.query;
if (!plugin?.transform) return callback(null, source, map);
const context = createContext(this);
const { handler, filter } = normalizeObjectHook("transform", plugin.transform);
if (!filter(this.resource, source)) return callback(null, source, map);
try {
const res = await handler.call(Object.assign({}, createBuildContext({
addWatchFile: (file) => {
this.addDependency(file);
},
getWatchFiles: () => {
return this.getDependencies();
}
}, this._compiler, this._compilation, this, map), context), source, this.resource);
if (res == null) callback(null, source, map);
else if (typeof res !== "string") callback(null, res.code, map == null ? map : res.map || map);
else callback(null, res, map);
} catch (error) {
if (error instanceof Error) callback(error);
else callback(new Error(String(error)));
}
}
//#endregion
export { transform as default };

View File

@@ -0,0 +1,92 @@
{
"name": "unplugin",
"type": "module",
"version": "2.3.11",
"description": "Unified plugin system for build tools",
"license": "MIT",
"homepage": "https://unplugin.unjs.io",
"repository": {
"type": "git",
"url": "git+https://github.com/unjs/unplugin.git"
},
"sideEffects": false,
"exports": {
".": {
"import": "./dist/index.js",
"require": "./dist/index.cjs"
},
"./dist/webpack/loaders/*": "./dist/webpack/loaders/*.cjs",
"./dist/rspack/loaders/*": "./dist/rspack/loaders/*.cjs"
},
"main": "dist/index.js",
"module": "dist/index.js",
"types": "dist/index.d.ts",
"files": [
"dist"
],
"engines": {
"node": ">=18.12.0"
},
"dependencies": {
"@jridgewell/remapping": "^2.3.5",
"acorn": "^8.15.0",
"picomatch": "^4.0.3",
"webpack-virtual-modules": "^0.6.2"
},
"devDependencies": {
"@antfu/eslint-config": "^6.2.0",
"@antfu/ni": "^27.0.1",
"@farmfe/cli": "^1.0.5",
"@farmfe/core": "^1.7.11",
"@rspack/cli": "^1.6.0",
"@rspack/core": "^1.6.0",
"@types/fs-extra": "^11.0.4",
"@types/node": "^24.10.0",
"@types/picomatch": "^4.0.2",
"ansis": "^4.2.0",
"bumpp": "^10.3.1",
"esbuild": "^0.25.12",
"esbuild-plugin-copy": "^2.1.1",
"eslint": "^9.39.0",
"eslint-plugin-format": "^1.0.2",
"fast-glob": "^3.3.3",
"fs-extra": "^11.3.2",
"jiti": "^2.6.1",
"lint-staged": "^16.2.6",
"magic-string": "^0.30.21",
"rolldown": "^1.0.0-beta.46",
"rollup": "^4.52.5",
"simple-git-hooks": "^2.13.1",
"tsdown": "^0.15.12",
"typescript": "~5.9.3",
"unloader": "^0.5.0",
"unplugin-unused": "^0.5.5",
"vite": "^7.1.12",
"vitest": "^4.0.6",
"webpack": "^5.102.1",
"webpack-cli": "^6.0.1",
"unplugin": "2.3.11"
},
"resolutions": {
"esbuild": "catalog:"
},
"simple-git-hooks": {
"pre-commit": "pnpm i --frozen-lockfile --ignore-scripts --offline && npx lint-staged"
},
"lint-staged": {
"*": "eslint --fix"
},
"scripts": {
"build": "tsdown",
"dev": "tsdown --watch src",
"lint": "eslint --cache .",
"lint:fix": "nr lint --fix",
"typecheck": "tsc --noEmit",
"docs:dev": "pnpm -C docs run dev",
"docs:build": "pnpm -C docs run build",
"docs:gen-files": "pnpm -C docs run gen-files",
"release": "bumpp",
"test": "nr test:build && vitest run --pool=forks",
"test:build": "jiti scripts/buildFixtures.ts"
}
}

19
node_modules/magic-regexp/nuxt.mjs generated vendored Normal file
View File

@@ -0,0 +1,19 @@
import { addImportsSources, addVitePlugin, addWebpackPlugin, defineNuxtModule } from '@nuxt/kit'
import * as magicRegexp from 'magic-regexp'
import { MagicRegExpTransformPlugin } from 'magic-regexp/transform'
export default defineNuxtModule({
setup(_options, nuxt) {
addImportsSources({
from: 'magic-regexp',
imports: Object.keys(magicRegexp),
})
// Disable RegExp code transformation in development mode
if (nuxt.options.dev)
return
addWebpackPlugin(MagicRegExpTransformPlugin.webpack())
addVitePlugin(MagicRegExpTransformPlugin.vite())
},
})

93
node_modules/magic-regexp/package.json generated vendored Normal file
View File

@@ -0,0 +1,93 @@
{
"name": "magic-regexp",
"version": "0.10.0",
"packageManager": "pnpm@10.9.0",
"description": "A compiled-away, type-safe, readable RegExp alternative",
"license": "MIT",
"repository": {
"type": "git",
"url": "git+https://github.com/unjs/magic-regexp.git"
},
"sideEffects": false,
"exports": {
".": {
"import": "./dist/index.mjs",
"require": "./dist/index.cjs"
},
"./converter": {
"import": "./dist/converter.mjs",
"require": "./dist/converter.cjs"
},
"./transform": {
"import": "./dist/transform.mjs",
"require": "./dist/transform.cjs"
},
"./further-magic": {
"import": "./dist/further-magic.mjs",
"require": "./dist/further-magic.cjs"
},
"./nuxt": "./nuxt.mjs"
},
"main": "./dist/index.cjs",
"module": "./dist/index.mjs",
"types": "./dist/index.d.ts",
"files": [
"dist",
"further-magic.d.ts",
"nuxt.mjs",
"transform.d.ts"
],
"scripts": {
"build": "unbuild",
"dev": "vitest dev",
"docs:generate": "nuxi generate docs",
"lint": "eslint .",
"prepare": "npx simple-git-hooks && pnpm build",
"prepublishOnly": "pnpm lint && pnpm test",
"release": "bumpp && npm publish",
"test": "vitest run",
"test:types": "tsc --noEmit"
},
"dependencies": {
"estree-walker": "^3.0.3",
"magic-string": "^0.30.12",
"mlly": "^1.7.2",
"regexp-tree": "^0.1.27",
"type-level-regexp": "~0.1.17",
"ufo": "^1.5.4",
"unplugin": "^2.0.0"
},
"devDependencies": {
"@antfu/eslint-config": "4.12.0",
"@codspeed/vitest-plugin": "4.0.1",
"@nuxt/kit": "3.16.2",
"@types/estree": "1.0.7",
"@types/node": "22.14.1",
"@vitest/coverage-v8": "3.1.2",
"acorn": "8.14.1",
"bumpp": "10.1.0",
"eslint": "9.25.0",
"expect-type": "1.2.1",
"lint-staged": "latest",
"rollup": "4.40.0",
"simple-git-hooks": "2.12.1",
"typescript": "5.8.3",
"unbuild": "3.5.0",
"vite": "6.3.2",
"vitest": "3.1.2"
},
"resolutions": {
"magic-regexp": "link:.",
"nuxt": "3.16.2",
"vite": "6.3.2",
"vue": "3.5.13"
},
"simple-git-hooks": {
"pre-commit": "npx lint-staged"
},
"lint-staged": {
"*": [
"npx eslint --fix"
]
}
}

3
node_modules/magic-regexp/transform.d.ts generated vendored Normal file
View File

@@ -0,0 +1,3 @@
// Legacy stub for previous TS versions
export * from './dist/transform'