Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Socket
Sign inDemoInstall

urlpattern-polyfill

Package Overview
Dependencies
Maintainers
3
Versions
33
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

urlpattern-polyfill - npm Package Compare versions

Comparing version 8.0.2 to 9.0.0

1423

dist/urlpattern.js

@@ -1,1422 +0,1 @@

// src/path-to-regex-modified.ts
var Part = class {
constructor(type, name, prefix, value, suffix, modifier) {
this.type = 3 /* kFixed */;
this.name = "";
this.prefix = "";
this.value = "";
this.suffix = "";
this.modifier = 3 /* kNone */;
this.type = type;
this.name = name;
this.prefix = prefix;
this.value = value;
this.suffix = suffix;
this.modifier = modifier;
}
hasCustomName() {
return this.name !== "" && typeof this.name !== "number";
}
};
var regexIdentifierStart = /[$_\p{ID_Start}]/u;
var regexIdentifierPart = /[$_\u200C\u200D\p{ID_Continue}]/u;
var kFullWildcardRegex = ".*";
function isASCII(str, extended) {
return (extended ? /^[\x00-\xFF]*$/ : /^[\x00-\x7F]*$/).test(str);
}
function lexer(str, lenient = false) {
const tokens = [];
let i = 0;
while (i < str.length) {
const char = str[i];
const ErrorOrInvalid = function(msg) {
if (!lenient)
throw new TypeError(msg);
tokens.push({ type: "INVALID_CHAR", index: i, value: str[i++] });
};
if (char === "*") {
tokens.push({ type: "ASTERISK", index: i, value: str[i++] });
continue;
}
if (char === "+" || char === "?") {
tokens.push({ type: "OTHER_MODIFIER", index: i, value: str[i++] });
continue;
}
if (char === "\\") {
tokens.push({ type: "ESCAPED_CHAR", index: i++, value: str[i++] });
continue;
}
if (char === "{") {
tokens.push({ type: "OPEN", index: i, value: str[i++] });
continue;
}
if (char === "}") {
tokens.push({ type: "CLOSE", index: i, value: str[i++] });
continue;
}
if (char === ":") {
let name = "";
let j = i + 1;
while (j < str.length) {
const code = str.substr(j, 1);
if (j === i + 1 && regexIdentifierStart.test(code) || j !== i + 1 && regexIdentifierPart.test(code)) {
name += str[j++];
continue;
}
break;
}
if (!name) {
ErrorOrInvalid(`Missing parameter name at ${i}`);
continue;
}
tokens.push({ type: "NAME", index: i, value: name });
i = j;
continue;
}
if (char === "(") {
let count = 1;
let pattern = "";
let j = i + 1;
let error = false;
if (str[j] === "?") {
ErrorOrInvalid(`Pattern cannot start with "?" at ${j}`);
continue;
}
while (j < str.length) {
if (!isASCII(str[j], false)) {
ErrorOrInvalid(`Invalid character '${str[j]}' at ${j}.`);
error = true;
break;
}
if (str[j] === "\\") {
pattern += str[j++] + str[j++];
continue;
}
if (str[j] === ")") {
count--;
if (count === 0) {
j++;
break;
}
} else if (str[j] === "(") {
count++;
if (str[j + 1] !== "?") {
ErrorOrInvalid(`Capturing groups are not allowed at ${j}`);
error = true;
break;
}
}
pattern += str[j++];
}
if (error) {
continue;
}
if (count) {
ErrorOrInvalid(`Unbalanced pattern at ${i}`);
continue;
}
if (!pattern) {
ErrorOrInvalid(`Missing pattern at ${i}`);
continue;
}
tokens.push({ type: "REGEX", index: i, value: pattern });
i = j;
continue;
}
tokens.push({ type: "CHAR", index: i, value: str[i++] });
}
tokens.push({ type: "END", index: i, value: "" });
return tokens;
}
function parse(str, options = {}) {
const tokens = lexer(str);
options.delimiter ?? (options.delimiter = "/#?");
options.prefixes ?? (options.prefixes = "./");
const segmentWildcardRegex = `[^${escapeString(options.delimiter)}]+?`;
const result = [];
let key = 0;
let i = 0;
let path = "";
let nameSet = /* @__PURE__ */ new Set();
const tryConsume = (type) => {
if (i < tokens.length && tokens[i].type === type)
return tokens[i++].value;
};
const tryConsumeModifier = () => {
return tryConsume("OTHER_MODIFIER") ?? tryConsume("ASTERISK");
};
const mustConsume = (type) => {
const value = tryConsume(type);
if (value !== void 0)
return value;
const { type: nextType, index } = tokens[i];
throw new TypeError(`Unexpected ${nextType} at ${index}, expected ${type}`);
};
const consumeText = () => {
let result2 = "";
let value;
while (value = tryConsume("CHAR") ?? tryConsume("ESCAPED_CHAR")) {
result2 += value;
}
return result2;
};
const DefaultEncodePart = (value) => {
return value;
};
const encodePart = options.encodePart || DefaultEncodePart;
let pendingFixedValue = "";
const appendToPendingFixedValue = (value) => {
pendingFixedValue += value;
};
const maybeAddPartFromPendingFixedValue = () => {
if (!pendingFixedValue.length) {
return;
}
result.push(new Part(3 /* kFixed */, "", "", encodePart(pendingFixedValue), "", 3 /* kNone */));
pendingFixedValue = "";
};
const addPart = (prefix, nameToken, regexOrWildcardToken, suffix, modifierToken) => {
let modifier = 3 /* kNone */;
switch (modifierToken) {
case "?":
modifier = 1 /* kOptional */;
break;
case "*":
modifier = 0 /* kZeroOrMore */;
break;
case "+":
modifier = 2 /* kOneOrMore */;
break;
}
if (!nameToken && !regexOrWildcardToken && modifier === 3 /* kNone */) {
appendToPendingFixedValue(prefix);
return;
}
maybeAddPartFromPendingFixedValue();
if (!nameToken && !regexOrWildcardToken) {
if (!prefix) {
return;
}
result.push(new Part(3 /* kFixed */, "", "", encodePart(prefix), "", modifier));
return;
}
let regexValue;
if (!regexOrWildcardToken) {
regexValue = segmentWildcardRegex;
} else if (regexOrWildcardToken === "*") {
regexValue = kFullWildcardRegex;
} else {
regexValue = regexOrWildcardToken;
}
let type = 2 /* kRegex */;
if (regexValue === segmentWildcardRegex) {
type = 1 /* kSegmentWildcard */;
regexValue = "";
} else if (regexValue === kFullWildcardRegex) {
type = 0 /* kFullWildcard */;
regexValue = "";
}
let name;
if (nameToken) {
name = nameToken;
} else if (regexOrWildcardToken) {
name = key++;
}
if (nameSet.has(name)) {
throw new TypeError(`Duplicate name '${name}'.`);
}
nameSet.add(name);
result.push(new Part(type, name, encodePart(prefix), regexValue, encodePart(suffix), modifier));
};
while (i < tokens.length) {
const charToken = tryConsume("CHAR");
const nameToken = tryConsume("NAME");
let regexOrWildcardToken = tryConsume("REGEX");
if (!nameToken && !regexOrWildcardToken) {
regexOrWildcardToken = tryConsume("ASTERISK");
}
if (nameToken || regexOrWildcardToken) {
let prefix = charToken ?? "";
if (options.prefixes.indexOf(prefix) === -1) {
appendToPendingFixedValue(prefix);
prefix = "";
}
maybeAddPartFromPendingFixedValue();
let modifierToken = tryConsumeModifier();
addPart(prefix, nameToken, regexOrWildcardToken, "", modifierToken);
continue;
}
const value = charToken ?? tryConsume("ESCAPED_CHAR");
if (value) {
appendToPendingFixedValue(value);
continue;
}
const openToken = tryConsume("OPEN");
if (openToken) {
const prefix = consumeText();
const nameToken2 = tryConsume("NAME");
let regexOrWildcardToken2 = tryConsume("REGEX");
if (!nameToken2 && !regexOrWildcardToken2) {
regexOrWildcardToken2 = tryConsume("ASTERISK");
}
const suffix = consumeText();
mustConsume("CLOSE");
const modifierToken = tryConsumeModifier();
addPart(prefix, nameToken2, regexOrWildcardToken2, suffix, modifierToken);
continue;
}
maybeAddPartFromPendingFixedValue();
mustConsume("END");
}
return result;
}
function escapeString(str) {
return str.replace(/([.+*?^${}()[\]|/\\])/g, "\\$1");
}
function flags(options) {
return options && options.ignoreCase ? "ui" : "u";
}
function stringToRegexp(path, names, options) {
return partsToRegexp(parse(path, options), names, options);
}
function modifierToString(modifier) {
switch (modifier) {
case 0 /* kZeroOrMore */:
return "*";
case 1 /* kOptional */:
return "?";
case 2 /* kOneOrMore */:
return "+";
case 3 /* kNone */:
return "";
}
}
function partsToRegexp(parts, names, options = {}) {
options.delimiter ?? (options.delimiter = "/#?");
options.prefixes ?? (options.prefixes = "./");
options.sensitive ?? (options.sensitive = false);
options.strict ?? (options.strict = false);
options.end ?? (options.end = true);
options.start ?? (options.start = true);
options.endsWith = "";
let result = options.start ? "^" : "";
for (const part of parts) {
if (part.type === 3 /* kFixed */) {
if (part.modifier === 3 /* kNone */) {
result += escapeString(part.value);
} else {
result += `(?:${escapeString(part.value)})${modifierToString(part.modifier)}`;
}
continue;
}
if (names)
names.push(part.name);
const segmentWildcardRegex = `[^${escapeString(options.delimiter)}]+?`;
let regexValue = part.value;
if (part.type === 1 /* kSegmentWildcard */)
regexValue = segmentWildcardRegex;
else if (part.type === 0 /* kFullWildcard */)
regexValue = kFullWildcardRegex;
if (!part.prefix.length && !part.suffix.length) {
if (part.modifier === 3 /* kNone */ || part.modifier === 1 /* kOptional */) {
result += `(${regexValue})${modifierToString(part.modifier)}`;
} else {
result += `((?:${regexValue})${modifierToString(part.modifier)})`;
}
continue;
}
if (part.modifier === 3 /* kNone */ || part.modifier === 1 /* kOptional */) {
result += `(?:${escapeString(part.prefix)}(${regexValue})${escapeString(part.suffix)})`;
result += modifierToString(part.modifier);
continue;
}
result += `(?:${escapeString(part.prefix)}`;
result += `((?:${regexValue})(?:`;
result += escapeString(part.suffix);
result += escapeString(part.prefix);
result += `(?:${regexValue}))*)${escapeString(part.suffix)})`;
if (part.modifier === 0 /* kZeroOrMore */) {
result += "?";
}
}
const endsWith = `[${escapeString(options.endsWith)}]|$`;
const delimiter = `[${escapeString(options.delimiter)}]`;
if (options.end) {
if (!options.strict) {
result += `${delimiter}?`;
}
if (!options.endsWith.length) {
result += "$";
} else {
result += `(?=${endsWith})`;
}
return new RegExp(result, flags(options));
}
if (!options.strict) {
result += `(?:${delimiter}(?=${endsWith}))?`;
}
let isEndDelimited = false;
if (parts.length) {
const lastPart = parts[parts.length - 1];
if (lastPart.type === 3 /* kFixed */ && lastPart.modifier === 3 /* kNone */) {
isEndDelimited = options.delimiter.indexOf(lastPart) > -1;
}
}
if (!isEndDelimited) {
result += `(?=${delimiter}|${endsWith})`;
}
return new RegExp(result, flags(options));
}
// src/url-utils.ts
var DEFAULT_OPTIONS = {
delimiter: "",
prefixes: "",
sensitive: true,
strict: true
};
var HOSTNAME_OPTIONS = {
delimiter: ".",
prefixes: "",
sensitive: true,
strict: true
};
var PATHNAME_OPTIONS = {
delimiter: "/",
prefixes: "/",
sensitive: true,
strict: true
};
function isAbsolutePathname(pathname, isPattern) {
if (!pathname.length) {
return false;
}
if (pathname[0] === "/") {
return true;
}
if (!isPattern) {
return false;
}
if (pathname.length < 2) {
return false;
}
if ((pathname[0] == "\\" || pathname[0] == "{") && pathname[1] == "/") {
return true;
}
return false;
}
function maybeStripPrefix(value, prefix) {
if (value.startsWith(prefix)) {
return value.substring(prefix.length, value.length);
}
return value;
}
function maybeStripSuffix(value, suffix) {
if (value.endsWith(suffix)) {
return value.substr(0, value.length - suffix.length);
}
return value;
}
function treatAsIPv6Hostname(value) {
if (!value || value.length < 2) {
return false;
}
if (value[0] === "[") {
return true;
}
if ((value[0] === "\\" || value[0] === "{") && value[1] === "[") {
return true;
}
return false;
}
var SPECIAL_SCHEMES = [
"ftp",
"file",
"http",
"https",
"ws",
"wss"
];
function isSpecialScheme(protocol_regexp) {
if (!protocol_regexp) {
return true;
}
for (const scheme of SPECIAL_SCHEMES) {
if (protocol_regexp.test(scheme)) {
return true;
}
}
return false;
}
function canonicalizeHash(hash, isPattern) {
hash = maybeStripPrefix(hash, "#");
if (isPattern || hash === "") {
return hash;
}
const url = new URL("https://example.com");
url.hash = hash;
return url.hash ? url.hash.substring(1, url.hash.length) : "";
}
function canonicalizeSearch(search, isPattern) {
search = maybeStripPrefix(search, "?");
if (isPattern || search === "") {
return search;
}
const url = new URL("https://example.com");
url.search = search;
return url.search ? url.search.substring(1, url.search.length) : "";
}
function canonicalizeHostname(hostname, isPattern) {
if (isPattern || hostname === "") {
return hostname;
}
if (treatAsIPv6Hostname(hostname)) {
return ipv6HostnameEncodeCallback(hostname);
} else {
return hostnameEncodeCallback(hostname);
}
}
function canonicalizePassword(password, isPattern) {
if (isPattern || password === "") {
return password;
}
const url = new URL("https://example.com");
url.password = password;
return url.password;
}
function canonicalizeUsername(username, isPattern) {
if (isPattern || username === "") {
return username;
}
const url = new URL("https://example.com");
url.username = username;
return url.username;
}
function canonicalizePathname(pathname, protocol, isPattern) {
if (isPattern || pathname === "") {
return pathname;
}
if (protocol && !SPECIAL_SCHEMES.includes(protocol)) {
const url = new URL(`${protocol}:${pathname}`);
return url.pathname;
}
const leadingSlash = pathname[0] == "/";
pathname = new URL(
!leadingSlash ? "/-" + pathname : pathname,
"https://example.com"
).pathname;
if (!leadingSlash) {
pathname = pathname.substring(2, pathname.length);
}
return pathname;
}
function canonicalizePort(port, protocol, isPattern) {
if (defaultPortForProtocol(protocol) === port) {
port = "";
}
if (isPattern || port === "") {
return port;
}
return portEncodeCallback(port);
}
function canonicalizeProtocol(protocol, isPattern) {
protocol = maybeStripSuffix(protocol, ":");
if (isPattern || protocol === "") {
return protocol;
}
return protocolEncodeCallback(protocol);
}
function defaultPortForProtocol(protocol) {
switch (protocol) {
case "ws":
case "http":
return "80";
case "wws":
case "https":
return "443";
case "ftp":
return "21";
default:
return "";
}
}
function protocolEncodeCallback(input) {
if (input === "") {
return input;
}
if (/^[-+.A-Za-z0-9]*$/.test(input))
return input.toLowerCase();
throw new TypeError(`Invalid protocol '${input}'.`);
}
function usernameEncodeCallback(input) {
if (input === "") {
return input;
}
const url = new URL("https://example.com");
url.username = input;
return url.username;
}
function passwordEncodeCallback(input) {
if (input === "") {
return input;
}
const url = new URL("https://example.com");
url.password = input;
return url.password;
}
function hostnameEncodeCallback(input) {
if (input === "") {
return input;
}
if (/[\t\n\r #%/:<>?@[\]^\\|]/g.test(input)) {
throw new TypeError(`Invalid hostname '${input}'`);
}
const url = new URL("https://example.com");
url.hostname = input;
return url.hostname;
}
function ipv6HostnameEncodeCallback(input) {
if (input === "") {
return input;
}
if (/[^0-9a-fA-F[\]:]/g.test(input)) {
throw new TypeError(`Invalid IPv6 hostname '${input}'`);
}
return input.toLowerCase();
}
function portEncodeCallback(input) {
if (input === "") {
return input;
}
if (/^[0-9]*$/.test(input) && parseInt(input) <= 65535) {
return input;
}
throw new TypeError(`Invalid port '${input}'.`);
}
function standardURLPathnameEncodeCallback(input) {
if (input === "") {
return input;
}
const url = new URL("https://example.com");
url.pathname = input[0] !== "/" ? "/-" + input : input;
if (input[0] !== "/") {
return url.pathname.substring(2, url.pathname.length);
}
return url.pathname;
}
function pathURLPathnameEncodeCallback(input) {
if (input === "") {
return input;
}
const url = new URL(`data:${input}`);
return url.pathname;
}
function searchEncodeCallback(input) {
if (input === "") {
return input;
}
const url = new URL("https://example.com");
url.search = input;
return url.search.substring(1, url.search.length);
}
function hashEncodeCallback(input) {
if (input === "") {
return input;
}
const url = new URL("https://example.com");
url.hash = input;
return url.hash.substring(1, url.hash.length);
}
// src/url-pattern-parser.ts
var Parser = class {
constructor(input) {
// The list of `LexToken`s produced by the path-to-regexp `lexer()` function
// when passed `input` with lenient mode enabled.
this.tokenList = [];
// As we parse the input string we populate a `URLPatternInit` dictionary
// with each component pattern. This is then the final result of the parse.
this.internalResult = {};
// The index of the current `LexToken` being considered.
this.tokenIndex = 0;
// The value to add to `tokenIndex` on each turn through the parse loop.
// While typically this is `1`, it is also set to `0` at times for things
// like state transitions, etc. It is automatically reset back to `1` at
// the top of the parse loop.
this.tokenIncrement = 1;
// The index of the first `LexToken` to include in the component string.
this.componentStart = 0;
// The current parse state. This should only be changed via `changeState()`
// or `rewindAndSetState()`.
this.state = 0 /* INIT */;
// The current nest depth of `{ }` pattern groupings.
this.groupDepth = 0;
// The current nesting depth of `[ ]` in hostname patterns.
this.hostnameIPv6BracketDepth = 0;
// True if we should apply parse rules as if this is a "standard" URL. If
// false then this is treated as a "not a base URL".
this.shouldTreatAsStandardURL = false;
this.input = input;
}
// Return the parse result. The result is only available after the
// `parse()` method completes.
get result() {
return this.internalResult;
}
// Attempt to parse the input string used to construct the Parser object.
// This method may only be called once. Any errors will be thrown as an
// exception. Retrieve the parse result by accessing the `Parser.result`
// property getter.
parse() {
this.tokenList = lexer(
this.input,
/*lenient=*/
true
);
for (; this.tokenIndex < this.tokenList.length; this.tokenIndex += this.tokenIncrement) {
this.tokenIncrement = 1;
if (this.tokenList[this.tokenIndex].type === "END") {
if (this.state === 0 /* INIT */) {
this.rewind();
if (this.isHashPrefix()) {
this.changeState(
9 /* HASH */,
/*skip=*/
1
);
} else if (this.isSearchPrefix()) {
this.changeState(
8 /* SEARCH */,
/*skip=*/
1
);
this.internalResult.hash = "";
} else {
this.changeState(
7 /* PATHNAME */,
/*skip=*/
0
);
this.internalResult.search = "";
this.internalResult.hash = "";
}
continue;
} else if (this.state === 2 /* AUTHORITY */) {
this.rewindAndSetState(5 /* HOSTNAME */);
continue;
}
this.changeState(
10 /* DONE */,
/*skip=*/
0
);
break;
}
if (this.groupDepth > 0) {
if (this.isGroupClose()) {
this.groupDepth -= 1;
} else {
continue;
}
}
if (this.isGroupOpen()) {
this.groupDepth += 1;
continue;
}
switch (this.state) {
case 0 /* INIT */:
if (this.isProtocolSuffix()) {
this.internalResult.username = "";
this.internalResult.password = "";
this.internalResult.hostname = "";
this.internalResult.port = "";
this.internalResult.pathname = "";
this.internalResult.search = "";
this.internalResult.hash = "";
this.rewindAndSetState(1 /* PROTOCOL */);
}
break;
case 1 /* PROTOCOL */:
if (this.isProtocolSuffix()) {
this.computeShouldTreatAsStandardURL();
let nextState = 7 /* PATHNAME */;
let skip = 1;
if (this.shouldTreatAsStandardURL) {
this.internalResult.pathname = "/";
}
if (this.nextIsAuthoritySlashes()) {
nextState = 2 /* AUTHORITY */;
skip = 3;
} else if (this.shouldTreatAsStandardURL) {
nextState = 2 /* AUTHORITY */;
}
this.changeState(nextState, skip);
}
break;
case 2 /* AUTHORITY */:
if (this.isIdentityTerminator()) {
this.rewindAndSetState(3 /* USERNAME */);
} else if (this.isPathnameStart() || this.isSearchPrefix() || this.isHashPrefix()) {
this.rewindAndSetState(5 /* HOSTNAME */);
}
break;
case 3 /* USERNAME */:
if (this.isPasswordPrefix()) {
this.changeState(
4 /* PASSWORD */,
/*skip=*/
1
);
} else if (this.isIdentityTerminator()) {
this.changeState(
5 /* HOSTNAME */,
/*skip=*/
1
);
}
break;
case 4 /* PASSWORD */:
if (this.isIdentityTerminator()) {
this.changeState(
5 /* HOSTNAME */,
/*skip=*/
1
);
}
break;
case 5 /* HOSTNAME */:
if (this.isIPv6Open()) {
this.hostnameIPv6BracketDepth += 1;
} else if (this.isIPv6Close()) {
this.hostnameIPv6BracketDepth -= 1;
}
if (this.isPortPrefix() && !this.hostnameIPv6BracketDepth) {
this.changeState(
6 /* PORT */,
/*skip=*/
1
);
} else if (this.isPathnameStart()) {
this.changeState(
7 /* PATHNAME */,
/*skip=*/
0
);
} else if (this.isSearchPrefix()) {
this.changeState(
8 /* SEARCH */,
/*skip=*/
1
);
} else if (this.isHashPrefix()) {
this.changeState(
9 /* HASH */,
/*skip=*/
1
);
}
break;
case 6 /* PORT */:
if (this.isPathnameStart()) {
this.changeState(
7 /* PATHNAME */,
/*skip=*/
0
);
} else if (this.isSearchPrefix()) {
this.changeState(
8 /* SEARCH */,
/*skip=*/
1
);
} else if (this.isHashPrefix()) {
this.changeState(
9 /* HASH */,
/*skip=*/
1
);
}
break;
case 7 /* PATHNAME */:
if (this.isSearchPrefix()) {
this.changeState(
8 /* SEARCH */,
/*skip=*/
1
);
} else if (this.isHashPrefix()) {
this.changeState(
9 /* HASH */,
/*skip=*/
1
);
}
break;
case 8 /* SEARCH */:
if (this.isHashPrefix()) {
this.changeState(
9 /* HASH */,
/*skip=*/
1
);
}
break;
case 9 /* HASH */:
break;
case 10 /* DONE */:
break;
}
}
}
changeState(newState, skip) {
switch (this.state) {
case 0 /* INIT */:
break;
case 1 /* PROTOCOL */:
this.internalResult.protocol = this.makeComponentString();
break;
case 2 /* AUTHORITY */:
break;
case 3 /* USERNAME */:
this.internalResult.username = this.makeComponentString();
break;
case 4 /* PASSWORD */:
this.internalResult.password = this.makeComponentString();
break;
case 5 /* HOSTNAME */:
this.internalResult.hostname = this.makeComponentString();
break;
case 6 /* PORT */:
this.internalResult.port = this.makeComponentString();
break;
case 7 /* PATHNAME */:
this.internalResult.pathname = this.makeComponentString();
break;
case 8 /* SEARCH */:
this.internalResult.search = this.makeComponentString();
break;
case 9 /* HASH */:
this.internalResult.hash = this.makeComponentString();
break;
case 10 /* DONE */:
break;
}
this.changeStateWithoutSettingComponent(newState, skip);
}
changeStateWithoutSettingComponent(newState, skip) {
this.state = newState;
this.componentStart = this.tokenIndex + skip;
this.tokenIndex += skip;
this.tokenIncrement = 0;
}
rewind() {
this.tokenIndex = this.componentStart;
this.tokenIncrement = 0;
}
rewindAndSetState(newState) {
this.rewind();
this.state = newState;
}
safeToken(index) {
if (index < 0) {
index = this.tokenList.length - index;
}
if (index < this.tokenList.length) {
return this.tokenList[index];
}
return this.tokenList[this.tokenList.length - 1];
}
isNonSpecialPatternChar(index, value) {
const token = this.safeToken(index);
return token.value === value && (token.type === "CHAR" || token.type === "ESCAPED_CHAR" || token.type === "INVALID_CHAR");
}
isProtocolSuffix() {
return this.isNonSpecialPatternChar(this.tokenIndex, ":");
}
nextIsAuthoritySlashes() {
return this.isNonSpecialPatternChar(this.tokenIndex + 1, "/") && this.isNonSpecialPatternChar(this.tokenIndex + 2, "/");
}
isIdentityTerminator() {
return this.isNonSpecialPatternChar(this.tokenIndex, "@");
}
isPasswordPrefix() {
return this.isNonSpecialPatternChar(this.tokenIndex, ":");
}
isPortPrefix() {
return this.isNonSpecialPatternChar(this.tokenIndex, ":");
}
isPathnameStart() {
return this.isNonSpecialPatternChar(this.tokenIndex, "/");
}
isSearchPrefix() {
if (this.isNonSpecialPatternChar(this.tokenIndex, "?")) {
return true;
}
if (this.tokenList[this.tokenIndex].value !== "?") {
return false;
}
const previousToken = this.safeToken(this.tokenIndex - 1);
return previousToken.type !== "NAME" && previousToken.type !== "REGEX" && previousToken.type !== "CLOSE" && previousToken.type !== "ASTERISK";
}
isHashPrefix() {
return this.isNonSpecialPatternChar(this.tokenIndex, "#");
}
isGroupOpen() {
return this.tokenList[this.tokenIndex].type == "OPEN";
}
isGroupClose() {
return this.tokenList[this.tokenIndex].type == "CLOSE";
}
isIPv6Open() {
return this.isNonSpecialPatternChar(this.tokenIndex, "[");
}
isIPv6Close() {
return this.isNonSpecialPatternChar(this.tokenIndex, "]");
}
makeComponentString() {
const token = this.tokenList[this.tokenIndex];
const componentCharStart = this.safeToken(this.componentStart).index;
return this.input.substring(componentCharStart, token.index);
}
computeShouldTreatAsStandardURL() {
const options = {};
Object.assign(options, DEFAULT_OPTIONS);
options.encodePart = protocolEncodeCallback;
const regexp = stringToRegexp(
this.makeComponentString(),
/*keys=*/
void 0,
options
);
this.shouldTreatAsStandardURL = isSpecialScheme(regexp);
}
};
// src/url-pattern.ts
var COMPONENTS = [
"protocol",
"username",
"password",
"hostname",
"port",
"pathname",
"search",
"hash"
];
var DEFAULT_PATTERN = "*";
function extractValues(url, baseURL) {
if (typeof url !== "string") {
throw new TypeError(`parameter 1 is not of type 'string'.`);
}
const o = new URL(url, baseURL);
return {
protocol: o.protocol.substring(0, o.protocol.length - 1),
username: o.username,
password: o.password,
hostname: o.hostname,
port: o.port,
pathname: o.pathname,
search: o.search !== "" ? o.search.substring(1, o.search.length) : void 0,
hash: o.hash !== "" ? o.hash.substring(1, o.hash.length) : void 0
};
}
function processBaseURLString(input, isPattern) {
if (!isPattern) {
return input;
}
return escapePatternString(input);
}
function applyInit(o, init, isPattern) {
let baseURL;
if (typeof init.baseURL === "string") {
try {
baseURL = new URL(init.baseURL);
o.protocol = processBaseURLString(baseURL.protocol.substring(0, baseURL.protocol.length - 1), isPattern);
o.username = processBaseURLString(baseURL.username, isPattern);
o.password = processBaseURLString(baseURL.password, isPattern);
o.hostname = processBaseURLString(baseURL.hostname, isPattern);
o.port = processBaseURLString(baseURL.port, isPattern);
o.pathname = processBaseURLString(baseURL.pathname, isPattern);
o.search = processBaseURLString(baseURL.search.substring(1, baseURL.search.length), isPattern);
o.hash = processBaseURLString(baseURL.hash.substring(1, baseURL.hash.length), isPattern);
} catch {
throw new TypeError(`invalid baseURL '${init.baseURL}'.`);
}
}
if (typeof init.protocol === "string") {
o.protocol = canonicalizeProtocol(init.protocol, isPattern);
}
if (typeof init.username === "string") {
o.username = canonicalizeUsername(init.username, isPattern);
}
if (typeof init.password === "string") {
o.password = canonicalizePassword(init.password, isPattern);
}
if (typeof init.hostname === "string") {
o.hostname = canonicalizeHostname(init.hostname, isPattern);
}
if (typeof init.port === "string") {
o.port = canonicalizePort(init.port, o.protocol, isPattern);
}
if (typeof init.pathname === "string") {
o.pathname = init.pathname;
if (baseURL && !isAbsolutePathname(o.pathname, isPattern)) {
const slashIndex = baseURL.pathname.lastIndexOf("/");
if (slashIndex >= 0) {
o.pathname = processBaseURLString(baseURL.pathname.substring(0, slashIndex + 1), isPattern) + o.pathname;
}
}
o.pathname = canonicalizePathname(o.pathname, o.protocol, isPattern);
}
if (typeof init.search === "string") {
o.search = canonicalizeSearch(init.search, isPattern);
}
if (typeof init.hash === "string") {
o.hash = canonicalizeHash(init.hash, isPattern);
}
return o;
}
function escapePatternString(value) {
return value.replace(/([+*?:{}()\\])/g, "\\$1");
}
function escapeRegexpString(value) {
return value.replace(/([.+*?^${}()[\]|/\\])/g, "\\$1");
}
function partsToPattern(parts, options) {
options.delimiter ?? (options.delimiter = "/#?");
options.prefixes ?? (options.prefixes = "./");
options.sensitive ?? (options.sensitive = false);
options.strict ?? (options.strict = false);
options.end ?? (options.end = true);
options.start ?? (options.start = true);
options.endsWith = "";
const kFullWildcardRegex2 = ".*";
const segmentWildcardRegex = `[^${escapeRegexpString(options.delimiter)}]+?`;
const regexIdentifierPart2 = /[$_\u200C\u200D\p{ID_Continue}]/u;
let result = "";
for (let i = 0; i < parts.length; ++i) {
const part = parts[i];
if (part.type === 3 /* kFixed */) {
if (part.modifier === 3 /* kNone */) {
result += escapePatternString(part.value);
continue;
}
result += `{${escapePatternString(part.value)}}${modifierToString(part.modifier)}`;
continue;
}
const customName = part.hasCustomName();
let needsGrouping = !!part.suffix.length || !!part.prefix.length && (part.prefix.length !== 1 || !options.prefixes.includes(part.prefix));
const lastPart = i > 0 ? parts[i - 1] : null;
const nextPart = i < parts.length - 1 ? parts[i + 1] : null;
if (!needsGrouping && customName && part.type === 1 /* kSegmentWildcard */ && part.modifier === 3 /* kNone */ && nextPart && !nextPart.prefix.length && !nextPart.suffix.length) {
if (nextPart.type === 3 /* kFixed */) {
const code = nextPart.value.length > 0 ? nextPart.value[0] : "";
needsGrouping = regexIdentifierPart2.test(code);
} else {
needsGrouping = !nextPart.hasCustomName();
}
}
if (!needsGrouping && !part.prefix.length && lastPart && lastPart.type === 3 /* kFixed */) {
const code = lastPart.value[lastPart.value.length - 1];
needsGrouping = options.prefixes.includes(code);
}
if (needsGrouping) {
result += "{";
}
result += escapePatternString(part.prefix);
if (customName) {
result += `:${part.name}`;
}
if (part.type === 2 /* kRegex */) {
result += `(${part.value})`;
} else if (part.type === 1 /* kSegmentWildcard */) {
if (!customName) {
result += `(${segmentWildcardRegex})`;
}
} else if (part.type === 0 /* kFullWildcard */) {
if (!customName && (!lastPart || lastPart.type === 3 /* kFixed */ || lastPart.modifier !== 3 /* kNone */ || needsGrouping || part.prefix !== "")) {
result += "*";
} else {
result += `(${kFullWildcardRegex2})`;
}
}
if (part.type === 1 /* kSegmentWildcard */ && customName && !!part.suffix.length) {
if (regexIdentifierPart2.test(part.suffix[0])) {
result += "\\";
}
}
result += escapePatternString(part.suffix);
if (needsGrouping) {
result += "}";
}
if (part.modifier !== 3 /* kNone */) {
result += modifierToString(part.modifier);
}
}
return result;
}
var URLPattern = class {
constructor(init = {}, baseURLOrOptions, options) {
this.regexp = {};
this.names = {};
this.component_pattern = {};
this.parts = {};
try {
let baseURL = void 0;
if (typeof baseURLOrOptions === "string") {
baseURL = baseURLOrOptions;
} else {
options = baseURLOrOptions;
}
if (typeof init === "string") {
const parser = new Parser(init);
parser.parse();
init = parser.result;
if (baseURL === void 0 && typeof init.protocol !== "string") {
throw new TypeError(`A base URL must be provided for a relative constructor string.`);
}
init.baseURL = baseURL;
} else {
if (!init || typeof init !== "object") {
throw new TypeError(`parameter 1 is not of type 'string' and cannot convert to dictionary.`);
}
if (baseURL) {
throw new TypeError(`parameter 1 is not of type 'string'.`);
}
}
if (typeof options === "undefined") {
options = { ignoreCase: false };
}
const ignoreCaseOptions = { ignoreCase: options.ignoreCase === true };
const defaults = {
pathname: DEFAULT_PATTERN,
protocol: DEFAULT_PATTERN,
username: DEFAULT_PATTERN,
password: DEFAULT_PATTERN,
hostname: DEFAULT_PATTERN,
port: DEFAULT_PATTERN,
search: DEFAULT_PATTERN,
hash: DEFAULT_PATTERN
};
this.pattern = applyInit(defaults, init, true);
if (defaultPortForProtocol(this.pattern.protocol) === this.pattern.port) {
this.pattern.port = "";
}
let component;
for (component of COMPONENTS) {
if (!(component in this.pattern))
continue;
const options2 = {};
const pattern = this.pattern[component];
this.names[component] = [];
switch (component) {
case "protocol":
Object.assign(options2, DEFAULT_OPTIONS);
options2.encodePart = protocolEncodeCallback;
break;
case "username":
Object.assign(options2, DEFAULT_OPTIONS);
options2.encodePart = usernameEncodeCallback;
break;
case "password":
Object.assign(options2, DEFAULT_OPTIONS);
options2.encodePart = passwordEncodeCallback;
break;
case "hostname":
Object.assign(options2, HOSTNAME_OPTIONS);
if (treatAsIPv6Hostname(pattern)) {
options2.encodePart = ipv6HostnameEncodeCallback;
} else {
options2.encodePart = hostnameEncodeCallback;
}
break;
case "port":
Object.assign(options2, DEFAULT_OPTIONS);
options2.encodePart = portEncodeCallback;
break;
case "pathname":
if (isSpecialScheme(this.regexp.protocol)) {
Object.assign(options2, PATHNAME_OPTIONS, ignoreCaseOptions);
options2.encodePart = standardURLPathnameEncodeCallback;
} else {
Object.assign(options2, DEFAULT_OPTIONS, ignoreCaseOptions);
options2.encodePart = pathURLPathnameEncodeCallback;
}
break;
case "search":
Object.assign(options2, DEFAULT_OPTIONS, ignoreCaseOptions);
options2.encodePart = searchEncodeCallback;
break;
case "hash":
Object.assign(options2, DEFAULT_OPTIONS, ignoreCaseOptions);
options2.encodePart = hashEncodeCallback;
break;
}
try {
this.parts[component] = parse(pattern, options2);
this.regexp[component] = partsToRegexp(
this.parts[component],
/* out */
this.names[component],
options2
);
this.component_pattern[component] = partsToPattern(this.parts[component], options2);
} catch (err) {
throw new TypeError(`invalid ${component} pattern '${this.pattern[component]}'.`);
}
}
} catch (err) {
throw new TypeError(`Failed to construct 'URLPattern': ${err.message}`);
}
}
test(input = {}, baseURL) {
let values = {
pathname: "",
protocol: "",
username: "",
password: "",
hostname: "",
port: "",
search: "",
hash: ""
};
if (typeof input !== "string" && baseURL) {
throw new TypeError(`parameter 1 is not of type 'string'.`);
}
if (typeof input === "undefined") {
return false;
}
try {
if (typeof input === "object") {
values = applyInit(values, input, false);
} else {
values = applyInit(values, extractValues(input, baseURL), false);
}
} catch (err) {
return false;
}
let component;
for (component of COMPONENTS) {
if (!this.regexp[component].exec(values[component])) {
return false;
}
}
return true;
}
exec(input = {}, baseURL) {
let values = {
pathname: "",
protocol: "",
username: "",
password: "",
hostname: "",
port: "",
search: "",
hash: ""
};
if (typeof input !== "string" && baseURL) {
throw new TypeError(`parameter 1 is not of type 'string'.`);
}
if (typeof input === "undefined") {
return;
}
try {
if (typeof input === "object") {
values = applyInit(values, input, false);
} else {
values = applyInit(values, extractValues(input, baseURL), false);
}
} catch (err) {
return null;
}
let result = {};
if (baseURL) {
result.inputs = [input, baseURL];
} else {
result.inputs = [input];
}
let component;
for (component of COMPONENTS) {
let match = this.regexp[component].exec(values[component]);
if (!match) {
return null;
}
let groups = {};
for (let [i, name] of this.names[component].entries()) {
if (typeof name === "string" || typeof name === "number") {
let value = match[i + 1];
groups[name] = value;
}
}
result[component] = {
input: values[component] ?? "",
groups
};
}
return result;
}
static compareComponent(component, left, right) {
const comparePart = (left2, right2) => {
for (let attr of ["type", "modifier", "prefix", "value", "suffix"]) {
if (left2[attr] < right2[attr])
return -1;
else if (left2[attr] === right2[attr])
continue;
else
return 1;
}
return 0;
};
const emptyFixedPart = new Part(3 /* kFixed */, "", "", "", "", 3 /* kNone */);
const wildcardOnlyPart = new Part(0 /* kFullWildcard */, "", "", "", "", 3 /* kNone */);
const comparePartList = (left2, right2) => {
let i = 0;
for (; i < Math.min(left2.length, right2.length); ++i) {
let result = comparePart(left2[i], right2[i]);
if (result)
return result;
}
if (left2.length === right2.length) {
return 0;
}
return comparePart(left2[i] ?? emptyFixedPart, right2[i] ?? emptyFixedPart);
};
if (!left.component_pattern[component] && !right.component_pattern[component]) {
return 0;
}
if (left.component_pattern[component] && !right.component_pattern[component]) {
return comparePartList(left.parts[component], [wildcardOnlyPart]);
}
if (!left.component_pattern[component] && right.component_pattern[component]) {
return comparePartList([wildcardOnlyPart], right.parts[component]);
}
return comparePartList(left.parts[component], right.parts[component]);
}
get protocol() {
return this.component_pattern.protocol;
}
get username() {
return this.component_pattern.username;
}
get password() {
return this.component_pattern.password;
}
get hostname() {
return this.component_pattern.hostname;
}
get port() {
return this.component_pattern.port;
}
get pathname() {
return this.component_pattern.pathname;
}
get search() {
return this.component_pattern.search;
}
get hash() {
return this.component_pattern.hash;
}
};
export {
URLPattern
};
var k=class{type=3;name="";prefix="";value="";suffix="";modifier=3;constructor(t,r,n,o,c,l){this.type=t,this.name=r,this.prefix=n,this.value=o,this.suffix=c,this.modifier=l}hasCustomName(){return this.name!==""&&typeof this.name!="number"}},Pe=/[$_\p{ID_Start}]/u,Se=/[$_\u200C\u200D\p{ID_Continue}]/u,M=".*";function ke(e,t){return(t?/^[\x00-\xFF]*$/:/^[\x00-\x7F]*$/).test(e)}function v(e,t=!1){let r=[],n=0;for(;n<e.length;){let o=e[n],c=function(l){if(!t)throw new TypeError(l);r.push({type:"INVALID_CHAR",index:n,value:e[n++]})};if(o==="*"){r.push({type:"ASTERISK",index:n,value:e[n++]});continue}if(o==="+"||o==="?"){r.push({type:"OTHER_MODIFIER",index:n,value:e[n++]});continue}if(o==="\\"){r.push({type:"ESCAPED_CHAR",index:n++,value:e[n++]});continue}if(o==="{"){r.push({type:"OPEN",index:n,value:e[n++]});continue}if(o==="}"){r.push({type:"CLOSE",index:n,value:e[n++]});continue}if(o===":"){let l="",s=n+1;for(;s<e.length;){let i=e.substr(s,1);if(s===n+1&&Pe.test(i)||s!==n+1&&Se.test(i)){l+=e[s++];continue}break}if(!l){c(`Missing parameter name at ${n}`);continue}r.push({type:"NAME",index:n,value:l}),n=s;continue}if(o==="("){let l=1,s="",i=n+1,a=!1;if(e[i]==="?"){c(`Pattern cannot start with "?" at ${i}`);continue}for(;i<e.length;){if(!ke(e[i],!1)){c(`Invalid character '${e[i]}' at ${i}.`),a=!0;break}if(e[i]==="\\"){s+=e[i++]+e[i++];continue}if(e[i]===")"){if(l--,l===0){i++;break}}else if(e[i]==="("&&(l++,e[i+1]!=="?")){c(`Capturing groups are not allowed at ${i}`),a=!0;break}s+=e[i++]}if(a)continue;if(l){c(`Unbalanced pattern at ${n}`);continue}if(!s){c(`Missing pattern at ${n}`);continue}r.push({type:"REGEX",index:n,value:s}),n=i;continue}r.push({type:"CHAR",index:n,value:e[n++]})}return r.push({type:"END",index:n,value:""}),r}function D(e,t={}){let r=v(e);t.delimiter??="/#?",t.prefixes??="./";let n=`[^${x(t.delimiter)}]+?`,o=[],c=0,l=0,s="",i=new Set,a=f=>{if(l<r.length&&r[l].type===f)return r[l++].value},h=()=>a("OTHER_MODIFIER")??a("ASTERISK"),p=f=>{let u=a(f);if(u!==void 0)return u;let{type:d,index:T}=r[l];throw new TypeError(`Unexpected ${d} at ${T}, expected ${f}`)},O=()=>{let f="",u;for(;u=a("CHAR")??a("ESCAPED_CHAR");)f+=u;return f},xe=f=>f,L=t.encodePart||xe,I="",H=f=>{I+=f},$=()=>{I.length&&(o.push(new k(3,"","",L(I),"",3)),I="")},G=(f,u,d,T,Y)=>{let g=3;switch(Y){case"?":g=1;break;case"*":g=0;break;case"+":g=2;break}if(!u&&!d&&g===3){H(f);return}if($(),!u&&!d){if(!f)return;o.push(new k(3,"","",L(f),"",g));return}let m;d?d==="*"?m=M:m=d:m=n;let R=2;m===n?(R=1,m=""):m===M&&(R=0,m="");let S;if(u?S=u:d&&(S=c++),i.has(S))throw new TypeError(`Duplicate name '${S}'.`);i.add(S),o.push(new k(R,S,L(f),m,L(T),g))};for(;l<r.length;){let f=a("CHAR"),u=a("NAME"),d=a("REGEX");if(!u&&!d&&(d=a("ASTERISK")),u||d){let g=f??"";t.prefixes.indexOf(g)===-1&&(H(g),g=""),$();let m=h();G(g,u,d,"",m);continue}let T=f??a("ESCAPED_CHAR");if(T){H(T);continue}if(a("OPEN")){let g=O(),m=a("NAME"),R=a("REGEX");!m&&!R&&(R=a("ASTERISK"));let S=O();p("CLOSE");let be=h();G(g,m,R,S,be);continue}$(),p("END")}return o}function x(e){return e.replace(/([.+*?^${}()[\]|/\\])/g,"\\$1")}function X(e){return e&&e.ignoreCase?"ui":"u"}function Z(e,t,r){return F(D(e,r),t,r)}function y(e){switch(e){case 0:return"*";case 1:return"?";case 2:return"+";case 3:return""}}function F(e,t,r={}){r.delimiter??="/#?",r.prefixes??="./",r.sensitive??=!1,r.strict??=!1,r.end??=!0,r.start??=!0,r.endsWith="";let n=r.start?"^":"";for(let s of e){if(s.type===3){s.modifier===3?n+=x(s.value):n+=`(?:${x(s.value)})${y(s.modifier)}`;continue}t&&t.push(s.name);let i=`[^${x(r.delimiter)}]+?`,a=s.value;if(s.type===1?a=i:s.type===0&&(a=M),!s.prefix.length&&!s.suffix.length){s.modifier===3||s.modifier===1?n+=`(${a})${y(s.modifier)}`:n+=`((?:${a})${y(s.modifier)})`;continue}if(s.modifier===3||s.modifier===1){n+=`(?:${x(s.prefix)}(${a})${x(s.suffix)})`,n+=y(s.modifier);continue}n+=`(?:${x(s.prefix)}`,n+=`((?:${a})(?:`,n+=x(s.suffix),n+=x(s.prefix),n+=`(?:${a}))*)${x(s.suffix)})`,s.modifier===0&&(n+="?")}let o=`[${x(r.endsWith)}]|$`,c=`[${x(r.delimiter)}]`;if(r.end)return r.strict||(n+=`${c}?`),r.endsWith.length?n+=`(?=${o})`:n+="$",new RegExp(n,X(r));r.strict||(n+=`(?:${c}(?=${o}))?`);let l=!1;if(e.length){let s=e[e.length-1];s.type===3&&s.modifier===3&&(l=r.delimiter.indexOf(s)>-1)}return l||(n+=`(?=${c}|${o})`),new RegExp(n,X(r))}var b={delimiter:"",prefixes:"",sensitive:!0,strict:!0},B={delimiter:".",prefixes:"",sensitive:!0,strict:!0},q={delimiter:"/",prefixes:"/",sensitive:!0,strict:!0};function J(e,t){return e.length?e[0]==="/"?!0:!t||e.length<2?!1:(e[0]=="\\"||e[0]=="{")&&e[1]=="/":!1}function Q(e,t){return e.startsWith(t)?e.substring(t.length,e.length):e}function Ee(e,t){return e.endsWith(t)?e.substr(0,e.length-t.length):e}function W(e){return!e||e.length<2?!1:e[0]==="["||(e[0]==="\\"||e[0]==="{")&&e[1]==="["}var ee=["ftp","file","http","https","ws","wss"];function N(e){if(!e)return!0;for(let t of ee)if(e.test(t))return!0;return!1}function te(e,t){if(e=Q(e,"#"),t||e==="")return e;let r=new URL("https://example.com");return r.hash=e,r.hash?r.hash.substring(1,r.hash.length):""}function re(e,t){if(e=Q(e,"?"),t||e==="")return e;let r=new URL("https://example.com");return r.search=e,r.search?r.search.substring(1,r.search.length):""}function ne(e,t){return t||e===""?e:W(e)?j(e):z(e)}function se(e,t){if(t||e==="")return e;let r=new URL("https://example.com");return r.password=e,r.password}function ie(e,t){if(t||e==="")return e;let r=new URL("https://example.com");return r.username=e,r.username}function ae(e,t,r){if(r||e==="")return e;if(t&&!ee.includes(t))return new URL(`${t}:${e}`).pathname;let n=e[0]=="/";return e=new URL(n?e:"/-"+e,"https://example.com").pathname,n||(e=e.substring(2,e.length)),e}function oe(e,t,r){return _(t)===e&&(e=""),r||e===""?e:K(e)}function ce(e,t){return e=Ee(e,":"),t||e===""?e:A(e)}function _(e){switch(e){case"ws":case"http":return"80";case"wws":case"https":return"443";case"ftp":return"21";default:return""}}function A(e){if(e==="")return e;if(/^[-+.A-Za-z0-9]*$/.test(e))return e.toLowerCase();throw new TypeError(`Invalid protocol '${e}'.`)}function le(e){if(e==="")return e;let t=new URL("https://example.com");return t.username=e,t.username}function he(e){if(e==="")return e;let t=new URL("https://example.com");return t.password=e,t.password}function z(e){if(e==="")return e;if(/[\t\n\r #%/:<>?@[\]^\\|]/g.test(e))throw new TypeError(`Invalid hostname '${e}'`);let t=new URL("https://example.com");return t.hostname=e,t.hostname}function j(e){if(e==="")return e;if(/[^0-9a-fA-F[\]:]/g.test(e))throw new TypeError(`Invalid IPv6 hostname '${e}'`);return e.toLowerCase()}function K(e){if(e===""||/^[0-9]*$/.test(e)&&parseInt(e)<=65535)return e;throw new TypeError(`Invalid port '${e}'.`)}function fe(e){if(e==="")return e;let t=new URL("https://example.com");return t.pathname=e[0]!=="/"?"/-"+e:e,e[0]!=="/"?t.pathname.substring(2,t.pathname.length):t.pathname}function ue(e){return e===""?e:new URL(`data:${e}`).pathname}function pe(e){if(e==="")return e;let t=new URL("https://example.com");return t.search=e,t.search.substring(1,t.search.length)}function de(e){if(e==="")return e;let t=new URL("https://example.com");return t.hash=e,t.hash.substring(1,t.hash.length)}var U=class{#i;#n=[];#t={};#e=0;#s=1;#u=0;#c=0;#p=0;#d=0;#g=!1;constructor(t){this.#i=t}get result(){return this.#t}parse(){for(this.#n=v(this.#i,!0);this.#e<this.#n.length;this.#e+=this.#s){if(this.#s=1,this.#n[this.#e].type==="END"){if(this.#c===0){this.#P(),this.#l()?this.#r(9,1):this.#h()?(this.#r(8,1),this.#t.hash=""):(this.#r(7,0),this.#t.search="",this.#t.hash="");continue}else if(this.#c===2){this.#f(5);continue}this.#r(10,0);break}if(this.#p>0)if(this.#T())this.#p-=1;else continue;if(this.#O()){this.#p+=1;continue}switch(this.#c){case 0:this.#S()&&(this.#t.username="",this.#t.password="",this.#t.hostname="",this.#t.port="",this.#t.pathname="",this.#t.search="",this.#t.hash="",this.#f(1));break;case 1:if(this.#S()){this.#C();let t=7,r=1;this.#g&&(this.#t.pathname="/"),this.#E()?(t=2,r=3):this.#g&&(t=2),this.#r(t,r)}break;case 2:this.#x()?this.#f(3):(this.#b()||this.#h()||this.#l())&&this.#f(5);break;case 3:this.#R()?this.#r(4,1):this.#x()&&this.#r(5,1);break;case 4:this.#x()&&this.#r(5,1);break;case 5:this.#A()?this.#d+=1:this.#w()&&(this.#d-=1),this.#y()&&!this.#d?this.#r(6,1):this.#b()?this.#r(7,0):this.#h()?this.#r(8,1):this.#l()&&this.#r(9,1);break;case 6:this.#b()?this.#r(7,0):this.#h()?this.#r(8,1):this.#l()&&this.#r(9,1);break;case 7:this.#h()?this.#r(8,1):this.#l()&&this.#r(9,1);break;case 8:this.#l()&&this.#r(9,1);break;case 9:break;case 10:break}}}#r(t,r){switch(this.#c){case 0:break;case 1:this.#t.protocol=this.#o();break;case 2:break;case 3:this.#t.username=this.#o();break;case 4:this.#t.password=this.#o();break;case 5:this.#t.hostname=this.#o();break;case 6:this.#t.port=this.#o();break;case 7:this.#t.pathname=this.#o();break;case 8:this.#t.search=this.#o();break;case 9:this.#t.hash=this.#o();break;case 10:break}this.#k(t,r)}#k(t,r){this.#c=t,this.#u=this.#e+r,this.#e+=r,this.#s=0}#P(){this.#e=this.#u,this.#s=0}#f(t){this.#P(),this.#c=t}#m(t){return t<0&&(t=this.#n.length-t),t<this.#n.length?this.#n[t]:this.#n[this.#n.length-1]}#a(t,r){let n=this.#m(t);return n.value===r&&(n.type==="CHAR"||n.type==="ESCAPED_CHAR"||n.type==="INVALID_CHAR")}#S(){return this.#a(this.#e,":")}#E(){return this.#a(this.#e+1,"/")&&this.#a(this.#e+2,"/")}#x(){return this.#a(this.#e,"@")}#R(){return this.#a(this.#e,":")}#y(){return this.#a(this.#e,":")}#b(){return this.#a(this.#e,"/")}#h(){if(this.#a(this.#e,"?"))return!0;if(this.#n[this.#e].value!=="?")return!1;let t=this.#m(this.#e-1);return t.type!=="NAME"&&t.type!=="REGEX"&&t.type!=="CLOSE"&&t.type!=="ASTERISK"}#l(){return this.#a(this.#e,"#")}#O(){return this.#n[this.#e].type=="OPEN"}#T(){return this.#n[this.#e].type=="CLOSE"}#A(){return this.#a(this.#e,"[")}#w(){return this.#a(this.#e,"]")}#o(){let t=this.#n[this.#e],r=this.#m(this.#u).index;return this.#i.substring(r,t.index)}#C(){let t={};Object.assign(t,b),t.encodePart=A;let r=Z(this.#o(),void 0,t);this.#g=N(r)}};var V=["protocol","username","password","hostname","port","pathname","search","hash"],E="*";function ge(e,t){if(typeof e!="string")throw new TypeError("parameter 1 is not of type 'string'.");let r=new URL(e,t);return{protocol:r.protocol.substring(0,r.protocol.length-1),username:r.username,password:r.password,hostname:r.hostname,port:r.port,pathname:r.pathname,search:r.search!==""?r.search.substring(1,r.search.length):void 0,hash:r.hash!==""?r.hash.substring(1,r.hash.length):void 0}}function P(e,t){return t?C(e):e}function w(e,t,r){let n;if(typeof t.baseURL=="string")try{n=new URL(t.baseURL),e.protocol=P(n.protocol.substring(0,n.protocol.length-1),r),e.username=P(n.username,r),e.password=P(n.password,r),e.hostname=P(n.hostname,r),e.port=P(n.port,r),e.pathname=P(n.pathname,r),e.search=P(n.search.substring(1,n.search.length),r),e.hash=P(n.hash.substring(1,n.hash.length),r)}catch{throw new TypeError(`invalid baseURL '${t.baseURL}'.`)}if(typeof t.protocol=="string"&&(e.protocol=ce(t.protocol,r)),typeof t.username=="string"&&(e.username=ie(t.username,r)),typeof t.password=="string"&&(e.password=se(t.password,r)),typeof t.hostname=="string"&&(e.hostname=ne(t.hostname,r)),typeof t.port=="string"&&(e.port=oe(t.port,e.protocol,r)),typeof t.pathname=="string"){if(e.pathname=t.pathname,n&&!J(e.pathname,r)){let o=n.pathname.lastIndexOf("/");o>=0&&(e.pathname=P(n.pathname.substring(0,o+1),r)+e.pathname)}e.pathname=ae(e.pathname,e.protocol,r)}return typeof t.search=="string"&&(e.search=re(t.search,r)),typeof t.hash=="string"&&(e.hash=te(t.hash,r)),e}function C(e){return e.replace(/([+*?:{}()\\])/g,"\\$1")}function Re(e){return e.replace(/([.+*?^${}()[\]|/\\])/g,"\\$1")}function ye(e,t){t.delimiter??="/#?",t.prefixes??="./",t.sensitive??=!1,t.strict??=!1,t.end??=!0,t.start??=!0,t.endsWith="";let r=".*",n=`[^${Re(t.delimiter)}]+?`,o=/[$_\u200C\u200D\p{ID_Continue}]/u,c="";for(let l=0;l<e.length;++l){let s=e[l];if(s.type===3){if(s.modifier===3){c+=C(s.value);continue}c+=`{${C(s.value)}}${y(s.modifier)}`;continue}let i=s.hasCustomName(),a=!!s.suffix.length||!!s.prefix.length&&(s.prefix.length!==1||!t.prefixes.includes(s.prefix)),h=l>0?e[l-1]:null,p=l<e.length-1?e[l+1]:null;if(!a&&i&&s.type===1&&s.modifier===3&&p&&!p.prefix.length&&!p.suffix.length)if(p.type===3){let O=p.value.length>0?p.value[0]:"";a=o.test(O)}else a=!p.hasCustomName();if(!a&&!s.prefix.length&&h&&h.type===3){let O=h.value[h.value.length-1];a=t.prefixes.includes(O)}a&&(c+="{"),c+=C(s.prefix),i&&(c+=`:${s.name}`),s.type===2?c+=`(${s.value})`:s.type===1?i||(c+=`(${n})`):s.type===0&&(!i&&(!h||h.type===3||h.modifier!==3||a||s.prefix!=="")?c+="*":c+=`(${r})`),s.type===1&&i&&s.suffix.length&&o.test(s.suffix[0])&&(c+="\\"),c+=C(s.suffix),a&&(c+="}"),s.modifier!==3&&(c+=y(s.modifier))}return c}var me=class{#i;#n={};#t={};#e={};#s={};constructor(t={},r,n){try{let o;if(typeof r=="string"?o=r:n=r,typeof t=="string"){let i=new U(t);if(i.parse(),t=i.result,o===void 0&&typeof t.protocol!="string")throw new TypeError("A base URL must be provided for a relative constructor string.");t.baseURL=o}else{if(!t||typeof t!="object")throw new TypeError("parameter 1 is not of type 'string' and cannot convert to dictionary.");if(o)throw new TypeError("parameter 1 is not of type 'string'.")}typeof n>"u"&&(n={ignoreCase:!1});let c={ignoreCase:n.ignoreCase===!0},l={pathname:E,protocol:E,username:E,password:E,hostname:E,port:E,search:E,hash:E};this.#i=w(l,t,!0),_(this.#i.protocol)===this.#i.port&&(this.#i.port="");let s;for(s of V){if(!(s in this.#i))continue;let i={},a=this.#i[s];switch(this.#t[s]=[],s){case"protocol":Object.assign(i,b),i.encodePart=A;break;case"username":Object.assign(i,b),i.encodePart=le;break;case"password":Object.assign(i,b),i.encodePart=he;break;case"hostname":Object.assign(i,B),W(a)?i.encodePart=j:i.encodePart=z;break;case"port":Object.assign(i,b),i.encodePart=K;break;case"pathname":N(this.#n.protocol)?(Object.assign(i,q,c),i.encodePart=fe):(Object.assign(i,b,c),i.encodePart=ue);break;case"search":Object.assign(i,b,c),i.encodePart=pe;break;case"hash":Object.assign(i,b,c),i.encodePart=de;break}try{this.#s[s]=D(a,i),this.#n[s]=F(this.#s[s],this.#t[s],i),this.#e[s]=ye(this.#s[s],i)}catch{throw new TypeError(`invalid ${s} pattern '${this.#i[s]}'.`)}}}catch(o){throw new TypeError(`Failed to construct 'URLPattern': ${o.message}`)}}test(t={},r){let n={pathname:"",protocol:"",username:"",password:"",hostname:"",port:"",search:"",hash:""};if(typeof t!="string"&&r)throw new TypeError("parameter 1 is not of type 'string'.");if(typeof t>"u")return!1;try{typeof t=="object"?n=w(n,t,!1):n=w(n,ge(t,r),!1)}catch{return!1}let o;for(o of V)if(!this.#n[o].exec(n[o]))return!1;return!0}exec(t={},r){let n={pathname:"",protocol:"",username:"",password:"",hostname:"",port:"",search:"",hash:""};if(typeof t!="string"&&r)throw new TypeError("parameter 1 is not of type 'string'.");if(typeof t>"u")return;try{typeof t=="object"?n=w(n,t,!1):n=w(n,ge(t,r),!1)}catch{return null}let o={};r?o.inputs=[t,r]:o.inputs=[t];let c;for(c of V){let l=this.#n[c].exec(n[c]);if(!l)return null;let s={};for(let[i,a]of this.#t[c].entries())if(typeof a=="string"||typeof a=="number"){let h=l[i+1];s[a]=h}o[c]={input:n[c]??"",groups:s}}return o}static compareComponent(t,r,n){let o=(i,a)=>{for(let h of["type","modifier","prefix","value","suffix"]){if(i[h]<a[h])return-1;if(i[h]===a[h])continue;return 1}return 0},c=new k(3,"","","","",3),l=new k(0,"","","","",3),s=(i,a)=>{let h=0;for(;h<Math.min(i.length,a.length);++h){let p=o(i[h],a[h]);if(p)return p}return i.length===a.length?0:o(i[h]??c,a[h]??c)};return!r.#e[t]&&!n.#e[t]?0:r.#e[t]&&!n.#e[t]?s(r.#s[t],[l]):!r.#e[t]&&n.#e[t]?s([l],n.#s[t]):s(r.#s[t],n.#s[t])}get protocol(){return this.#e.protocol}get username(){return this.#e.username}get password(){return this.#e.password}get hostname(){return this.#e.hostname}get port(){return this.#e.port}get pathname(){return this.#e.pathname}get search(){return this.#e.search}get hash(){return this.#e.hash}};export{me as URLPattern};

29

package.json
{
"name": "urlpattern-polyfill",
"version": "8.0.2",
"version": "9.0.0",
"description": "Polyfill for the URLPattern API",

@@ -42,6 +42,6 @@ "repository": {

"@ava/typescript": "^4.0.0",
"ava": "^5.2.0",
"esbuild": "^0.17.18",
"rimraf": "^5.0.0",
"typescript": "^5.0.4",
"ava": "^5.3.0",
"esbuild": "^0.17.19",
"rimraf": "^5.0.1",
"typescript": "^5.1.3",
"wireit": "^0.9.5"

@@ -62,16 +62,13 @@ },

"scripts": {
"build:esm": "wireit",
"build:cjs": "wireit",
"build": "wireit",
"sync-wpt": "wireit",
"copyTypeFiles": "wireit",
"prepFakeNodeModules": "wireit",
"test": "wireit",
"manual-test": "wireit",
"publish-dev": "wireit",
"publish-prod": "wireit"
"publish-patch": "wireit",
"publish-major": "wireit"
},
"wireit": {
"build:esm": {
"command": "esbuild --bundle --format=esm src/url-pattern.ts --outfile=dist/urlpattern.js",
"command": "esbuild --bundle --format=esm src/url-pattern.ts --outfile=dist/urlpattern.js --minify --target=es2022",
"output": [

@@ -85,3 +82,3 @@ "dist/urlpattern.js"

"build:cjs": {
"command": "esbuild --bundle --format=cjs src/url-pattern.ts --outfile=dist/urlpattern.cjs",
"command": "esbuild --bundle --format=cjs src/url-pattern.ts --outfile=dist/urlpattern.cjs --minify --target=es2022",
"output": [

@@ -139,3 +136,3 @@ "dist/urlpattern.cjs"

},
"publish-prod": {
"publish-patch": {
"command": "npm version patch && npm publish",

@@ -145,2 +142,8 @@ "dependencies": [

]
},
"publish-major": {
"command": "npm version major && npm publish",
"dependencies": [
"test"
]
}

@@ -147,0 +150,0 @@ },

@@ -41,2 +41,5 @@ [![run-tests](https://github.com/kenchris/urlpattern-polyfill/actions/workflows/workflow.yml/badge.svg)](https://github.com/kenchris/urlpattern-polyfill/actions/workflows/workflow.yml)

> ## Note:
> The line with `// @ts-ignore: Property 'UrlPattern' does not exist ` is needed in some environments because before you load the polyfill it might not be available, and the feature-check in the if statement gives an TypeScript error. The whole idea is that it loads when its not there.
## loading as CommonJs module

@@ -62,4 +65,2 @@

```
> ## Note:
> The line with `// @ts-ignore: Property 'UrlPattern' does not exist ` is needed in some environments because before you load the polyfill it might not be available, and the feature-check in the if statement gives an TypeScript error. The whole idea is that it loads when its not there.

@@ -231,2 +232,6 @@ > ## Note:

Breaking changes
===
- V9.0.0 drops support for NodeJS 14 and lower. NodeJS 15 or higher is required. This is due to using private class fields, so we can have better optimalizations. There is _No_ change in functionality, but we were able to reduce the size of the polyfill by ~2.5KB (~13%), thanks to a pr #118 from @jimmywarting.
Learn more

@@ -233,0 +238,0 @@ ===

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc