fabric-texture
Version:
This JavaScript library enables fast and efficient image distortion transformations using Canvas 2D.
1,336 lines (1,324 loc) • 2.38 MB
JavaScript
(function(l, r) { if (!l || l.getElementById('livereloadscript')) return; r = l.createElement('script'); r.async = 1; r.src = '//' + (self.location.host || 'localhost').split(':')[0] + ':35729/livereload.js?snipver=1'; r.id = 'livereloadscript'; l.getElementsByTagName('head')[0].appendChild(r) })(self.document);
(function (React, require$$0, fabric) {
'use strict';
function _interopNamespaceDefault(e) {
var n = Object.create(null);
if (e) {
Object.keys(e).forEach(function (k) {
if (k !== 'default') {
var d = Object.getOwnPropertyDescriptor(e, k);
Object.defineProperty(n, k, d.get ? d : {
enumerable: true,
get: function () { return e[k]; }
});
}
});
}
n.default = e;
return Object.freeze(n);
}
var React__namespace = /*#__PURE__*/_interopNamespaceDefault(React);
var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
function getDefaultExportFromCjs (x) {
return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
}
var createRoot;
var m$3 = require$$0;
{
createRoot = m$3.createRoot;
m$3.hydrateRoot;
}
var dist$1 = {};
Object.defineProperty(dist$1, "__esModule", {
value: true
});
dist$1.parse = parse;
dist$1.serialize = serialize;
/**
* RegExp to match cookie-name in RFC 6265 sec 4.1.1
* This refers out to the obsoleted definition of token in RFC 2616 sec 2.2
* which has been replaced by the token definition in RFC 7230 appendix B.
*
* cookie-name = token
* token = 1*tchar
* tchar = "!" / "#" / "$" / "%" / "&" / "'" /
* "*" / "+" / "-" / "." / "^" / "_" /
* "`" / "|" / "~" / DIGIT / ALPHA
*
* Note: Allowing more characters - https://github.com/jshttp/cookie/issues/191
* Allow same range as cookie value, except `=`, which delimits end of name.
*/
const cookieNameRegExp = /^[\u0021-\u003A\u003C\u003E-\u007E]+$/;
/**
* RegExp to match cookie-value in RFC 6265 sec 4.1.1
*
* cookie-value = *cookie-octet / ( DQUOTE *cookie-octet DQUOTE )
* cookie-octet = %x21 / %x23-2B / %x2D-3A / %x3C-5B / %x5D-7E
* ; US-ASCII characters excluding CTLs,
* ; whitespace DQUOTE, comma, semicolon,
* ; and backslash
*
* Allowing more characters: https://github.com/jshttp/cookie/issues/191
* Comma, backslash, and DQUOTE are not part of the parsing algorithm.
*/
const cookieValueRegExp = /^[\u0021-\u003A\u003C-\u007E]*$/;
/**
* RegExp to match domain-value in RFC 6265 sec 4.1.1
*
* domain-value = <subdomain>
* ; defined in [RFC1034], Section 3.5, as
* ; enhanced by [RFC1123], Section 2.1
* <subdomain> = <label> | <subdomain> "." <label>
* <label> = <let-dig> [ [ <ldh-str> ] <let-dig> ]
* Labels must be 63 characters or less.
* 'let-dig' not 'letter' in the first char, per RFC1123
* <ldh-str> = <let-dig-hyp> | <let-dig-hyp> <ldh-str>
* <let-dig-hyp> = <let-dig> | "-"
* <let-dig> = <letter> | <digit>
* <letter> = any one of the 52 alphabetic characters A through Z in
* upper case and a through z in lower case
* <digit> = any one of the ten digits 0 through 9
*
* Keep support for leading dot: https://github.com/jshttp/cookie/issues/173
*
* > (Note that a leading %x2E ("."), if present, is ignored even though that
* character is not permitted, but a trailing %x2E ("."), if present, will
* cause the user agent to ignore the attribute.)
*/
const domainValueRegExp = /^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i;
/**
* RegExp to match path-value in RFC 6265 sec 4.1.1
*
* path-value = <any CHAR except CTLs or ";">
* CHAR = %x01-7F
* ; defined in RFC 5234 appendix B.1
*/
const pathValueRegExp = /^[\u0020-\u003A\u003D-\u007E]*$/;
const __toString = Object.prototype.toString;
const NullObject = /* @__PURE__ */(() => {
const C = function () {};
C.prototype = Object.create(null);
return C;
})();
/**
* Parse a cookie header.
*
* Parse the given cookie header string into an object
* The object has the various cookies as keys(names) => values
*/
function parse(str, options) {
const obj = new NullObject();
const len = str.length;
// RFC 6265 sec 4.1.1, RFC 2616 2.2 defines a cookie name consists of one char minimum, plus '='.
if (len < 2) return obj;
const dec = options?.decode || decode$2;
let index = 0;
do {
const eqIdx = str.indexOf("=", index);
if (eqIdx === -1) break; // No more cookie pairs.
const colonIdx = str.indexOf(";", index);
const endIdx = colonIdx === -1 ? len : colonIdx;
if (eqIdx > endIdx) {
// backtrack on prior semicolon
index = str.lastIndexOf(";", eqIdx - 1) + 1;
continue;
}
const keyStartIdx = startIndex(str, index, eqIdx);
const keyEndIdx = endIndex(str, eqIdx, keyStartIdx);
const key = str.slice(keyStartIdx, keyEndIdx);
// only assign once
if (obj[key] === undefined) {
let valStartIdx = startIndex(str, eqIdx + 1, endIdx);
let valEndIdx = endIndex(str, endIdx, valStartIdx);
const value = dec(str.slice(valStartIdx, valEndIdx));
obj[key] = value;
}
index = endIdx + 1;
} while (index < len);
return obj;
}
function startIndex(str, index, max) {
do {
const code = str.charCodeAt(index);
if (code !== 0x20 /* */ && code !== 0x09 /* \t */) return index;
} while (++index < max);
return max;
}
function endIndex(str, index, min) {
while (index > min) {
const code = str.charCodeAt(--index);
if (code !== 0x20 /* */ && code !== 0x09 /* \t */) return index + 1;
}
return min;
}
/**
* Serialize data into a cookie header.
*
* Serialize a name value pair into a cookie string suitable for
* http headers. An optional options object specifies cookie parameters.
*
* serialize('foo', 'bar', { httpOnly: true })
* => "foo=bar; httpOnly"
*/
function serialize(name, val, options) {
const enc = options?.encode || encodeURIComponent;
if (!cookieNameRegExp.test(name)) {
throw new TypeError(`argument name is invalid: ${name}`);
}
const value = enc(val);
if (!cookieValueRegExp.test(value)) {
throw new TypeError(`argument val is invalid: ${val}`);
}
let str = name + "=" + value;
if (!options) return str;
if (options.maxAge !== undefined) {
if (!Number.isInteger(options.maxAge)) {
throw new TypeError(`option maxAge is invalid: ${options.maxAge}`);
}
str += "; Max-Age=" + options.maxAge;
}
if (options.domain) {
if (!domainValueRegExp.test(options.domain)) {
throw new TypeError(`option domain is invalid: ${options.domain}`);
}
str += "; Domain=" + options.domain;
}
if (options.path) {
if (!pathValueRegExp.test(options.path)) {
throw new TypeError(`option path is invalid: ${options.path}`);
}
str += "; Path=" + options.path;
}
if (options.expires) {
if (!isDate(options.expires) || !Number.isFinite(options.expires.valueOf())) {
throw new TypeError(`option expires is invalid: ${options.expires}`);
}
str += "; Expires=" + options.expires.toUTCString();
}
if (options.httpOnly) {
str += "; HttpOnly";
}
if (options.secure) {
str += "; Secure";
}
if (options.partitioned) {
str += "; Partitioned";
}
if (options.priority) {
const priority = typeof options.priority === "string" ? options.priority.toLowerCase() : undefined;
switch (priority) {
case "low":
str += "; Priority=Low";
break;
case "medium":
str += "; Priority=Medium";
break;
case "high":
str += "; Priority=High";
break;
default:
throw new TypeError(`option priority is invalid: ${options.priority}`);
}
}
if (options.sameSite) {
const sameSite = typeof options.sameSite === "string" ? options.sameSite.toLowerCase() : options.sameSite;
switch (sameSite) {
case true:
case "strict":
str += "; SameSite=Strict";
break;
case "lax":
str += "; SameSite=Lax";
break;
case "none":
str += "; SameSite=None";
break;
default:
throw new TypeError(`option sameSite is invalid: ${options.sameSite}`);
}
}
return str;
}
/**
* URL-decode string value. Optimized to skip native call when no %.
*/
function decode$2(str) {
if (str.indexOf("%") === -1) return str;
try {
return decodeURIComponent(str);
} catch (e) {
return str;
}
}
/**
* Determine if value is a Date.
*/
function isDate(val) {
return __toString.call(val) === "[object Date]";
}
/**
* react-router v7.1.5
*
* Copyright (c) Remix Software Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE.md file in the root directory of this source tree.
*
* @license MIT
*/
var PopStateEventType = "popstate";
function createBrowserHistory(options = {}) {
function createBrowserLocation(window2, globalHistory) {
let {
pathname,
search,
hash
} = window2.location;
return createLocation("", {
pathname,
search,
hash
},
// state defaults to `null` because `window.history.state` does
globalHistory.state && globalHistory.state.usr || null, globalHistory.state && globalHistory.state.key || "default");
}
function createBrowserHref(window2, to) {
return typeof to === "string" ? to : createPath(to);
}
return getUrlBasedHistory(createBrowserLocation, createBrowserHref, null, options);
}
function invariant(value, message) {
if (value === false || value === null || typeof value === "undefined") {
throw new Error(message);
}
}
function warning(cond, message) {
if (!cond) {
if (typeof console !== "undefined") console.warn(message);
try {
throw new Error(message);
} catch (e) {}
}
}
function createKey() {
return Math.random().toString(36).substring(2, 10);
}
function getHistoryState(location, index) {
return {
usr: location.state,
key: location.key,
idx: index
};
}
function createLocation(current, to, state = null, key) {
let location = {
pathname: typeof current === "string" ? current : current.pathname,
search: "",
hash: "",
...(typeof to === "string" ? parsePath(to) : to),
state,
// TODO: This could be cleaned up. push/replace should probably just take
// full Locations now and avoid the need to run through this flow at all
// But that's a pretty big refactor to the current test suite so going to
// keep as is for the time being and just let any incoming keys take precedence
key: to && to.key || key || createKey()
};
return location;
}
function createPath({
pathname = "/",
search = "",
hash = ""
}) {
if (search && search !== "?") pathname += search.charAt(0) === "?" ? search : "?" + search;
if (hash && hash !== "#") pathname += hash.charAt(0) === "#" ? hash : "#" + hash;
return pathname;
}
function parsePath(path) {
let parsedPath = {};
if (path) {
let hashIndex = path.indexOf("#");
if (hashIndex >= 0) {
parsedPath.hash = path.substring(hashIndex);
path = path.substring(0, hashIndex);
}
let searchIndex = path.indexOf("?");
if (searchIndex >= 0) {
parsedPath.search = path.substring(searchIndex);
path = path.substring(0, searchIndex);
}
if (path) {
parsedPath.pathname = path;
}
}
return parsedPath;
}
function getUrlBasedHistory(getLocation, createHref2, validateLocation, options = {}) {
let {
window: window2 = document.defaultView,
v5Compat = false
} = options;
let globalHistory = window2.history;
let action = "POP" /* Pop */;
let listener = null;
let index = getIndex();
if (index == null) {
index = 0;
globalHistory.replaceState({
...globalHistory.state,
idx: index
}, "");
}
function getIndex() {
let state = globalHistory.state || {
idx: null
};
return state.idx;
}
function handlePop() {
action = "POP" /* Pop */;
let nextIndex = getIndex();
let delta = nextIndex == null ? null : nextIndex - index;
index = nextIndex;
if (listener) {
listener({
action,
location: history.location,
delta
});
}
}
function push(to, state) {
action = "PUSH" /* Push */;
let location = createLocation(history.location, to, state);
if (validateLocation) validateLocation(location, to);
index = getIndex() + 1;
let historyState = getHistoryState(location, index);
let url = history.createHref(location);
try {
globalHistory.pushState(historyState, "", url);
} catch (error) {
if (error instanceof DOMException && error.name === "DataCloneError") {
throw error;
}
window2.location.assign(url);
}
if (v5Compat && listener) {
listener({
action,
location: history.location,
delta: 1
});
}
}
function replace2(to, state) {
action = "REPLACE" /* Replace */;
let location = createLocation(history.location, to, state);
if (validateLocation) validateLocation(location, to);
index = getIndex();
let historyState = getHistoryState(location, index);
let url = history.createHref(location);
globalHistory.replaceState(historyState, "", url);
if (v5Compat && listener) {
listener({
action,
location: history.location,
delta: 0
});
}
}
function createURL(to) {
let base = window2.location.origin !== "null" ? window2.location.origin : window2.location.href;
let href = typeof to === "string" ? to : createPath(to);
href = href.replace(/ $/, "%20");
invariant(base, `No window.location.(origin|href) available to create URL for href: ${href}`);
return new URL(href, base);
}
let history = {
get action() {
return action;
},
get location() {
return getLocation(window2, globalHistory);
},
listen(fn) {
if (listener) {
throw new Error("A history only accepts one active listener");
}
window2.addEventListener(PopStateEventType, handlePop);
listener = fn;
return () => {
window2.removeEventListener(PopStateEventType, handlePop);
listener = null;
};
},
createHref(to) {
return createHref2(window2, to);
},
createURL,
encodeLocation(to) {
let url = createURL(to);
return {
pathname: url.pathname,
search: url.search,
hash: url.hash
};
},
push,
replace: replace2,
go(n) {
return globalHistory.go(n);
}
};
return history;
}
function matchRoutes(routes, locationArg, basename = "/") {
return matchRoutesImpl(routes, locationArg, basename, false);
}
function matchRoutesImpl(routes, locationArg, basename, allowPartial) {
let location = typeof locationArg === "string" ? parsePath(locationArg) : locationArg;
let pathname = stripBasename(location.pathname || "/", basename);
if (pathname == null) {
return null;
}
let branches = flattenRoutes(routes);
rankRouteBranches(branches);
let matches = null;
for (let i = 0; matches == null && i < branches.length; ++i) {
let decoded = decodePath(pathname);
matches = matchRouteBranch(branches[i], decoded, allowPartial);
}
return matches;
}
function flattenRoutes(routes, branches = [], parentsMeta = [], parentPath = "") {
let flattenRoute = (route, index, relativePath) => {
let meta = {
relativePath: relativePath === void 0 ? route.path || "" : relativePath,
caseSensitive: route.caseSensitive === true,
childrenIndex: index,
route
};
if (meta.relativePath.startsWith("/")) {
invariant(meta.relativePath.startsWith(parentPath), `Absolute route path "${meta.relativePath}" nested under path "${parentPath}" is not valid. An absolute child route path must start with the combined path of all its parent routes.`);
meta.relativePath = meta.relativePath.slice(parentPath.length);
}
let path = joinPaths([parentPath, meta.relativePath]);
let routesMeta = parentsMeta.concat(meta);
if (route.children && route.children.length > 0) {
invariant(
// Our types know better, but runtime JS may not!
// @ts-expect-error
route.index !== true, `Index routes must not have child routes. Please remove all child routes from route path "${path}".`);
flattenRoutes(route.children, branches, routesMeta, path);
}
if (route.path == null && !route.index) {
return;
}
branches.push({
path,
score: computeScore(path, route.index),
routesMeta
});
};
routes.forEach((route, index) => {
if (route.path === "" || !route.path?.includes("?")) {
flattenRoute(route, index);
} else {
for (let exploded of explodeOptionalSegments(route.path)) {
flattenRoute(route, index, exploded);
}
}
});
return branches;
}
function explodeOptionalSegments(path) {
let segments = path.split("/");
if (segments.length === 0) return [];
let [first, ...rest] = segments;
let isOptional = first.endsWith("?");
let required = first.replace(/\?$/, "");
if (rest.length === 0) {
return isOptional ? [required, ""] : [required];
}
let restExploded = explodeOptionalSegments(rest.join("/"));
let result = [];
result.push(...restExploded.map(subpath => subpath === "" ? required : [required, subpath].join("/")));
if (isOptional) {
result.push(...restExploded);
}
return result.map(exploded => path.startsWith("/") && exploded === "" ? "/" : exploded);
}
function rankRouteBranches(branches) {
branches.sort((a, b) => a.score !== b.score ? b.score - a.score : compareIndexes(a.routesMeta.map(meta => meta.childrenIndex), b.routesMeta.map(meta => meta.childrenIndex)));
}
var paramRe = /^:[\w-]+$/;
var dynamicSegmentValue = 3;
var indexRouteValue = 2;
var emptySegmentValue = 1;
var staticSegmentValue = 10;
var splatPenalty = -2;
var isSplat = s => s === "*";
function computeScore(path, index) {
let segments = path.split("/");
let initialScore = segments.length;
if (segments.some(isSplat)) {
initialScore += splatPenalty;
}
if (index) {
initialScore += indexRouteValue;
}
return segments.filter(s => !isSplat(s)).reduce((score, segment) => score + (paramRe.test(segment) ? dynamicSegmentValue : segment === "" ? emptySegmentValue : staticSegmentValue), initialScore);
}
function compareIndexes(a, b) {
let siblings = a.length === b.length && a.slice(0, -1).every((n, i) => n === b[i]);
return siblings ?
// If two routes are siblings, we should try to match the earlier sibling
// first. This allows people to have fine-grained control over the matching
// behavior by simply putting routes with identical paths in the order they
// want them tried.
a[a.length - 1] - b[b.length - 1] :
// Otherwise, it doesn't really make sense to rank non-siblings by index,
// so they sort equally.
0;
}
function matchRouteBranch(branch, pathname, allowPartial = false) {
let {
routesMeta
} = branch;
let matchedParams = {};
let matchedPathname = "/";
let matches = [];
for (let i = 0; i < routesMeta.length; ++i) {
let meta = routesMeta[i];
let end = i === routesMeta.length - 1;
let remainingPathname = matchedPathname === "/" ? pathname : pathname.slice(matchedPathname.length) || "/";
let match = matchPath({
path: meta.relativePath,
caseSensitive: meta.caseSensitive,
end
}, remainingPathname);
let route = meta.route;
if (!match && end && allowPartial && !routesMeta[routesMeta.length - 1].route.index) {
match = matchPath({
path: meta.relativePath,
caseSensitive: meta.caseSensitive,
end: false
}, remainingPathname);
}
if (!match) {
return null;
}
Object.assign(matchedParams, match.params);
matches.push({
// TODO: Can this as be avoided?
params: matchedParams,
pathname: joinPaths([matchedPathname, match.pathname]),
pathnameBase: normalizePathname(joinPaths([matchedPathname, match.pathnameBase])),
route
});
if (match.pathnameBase !== "/") {
matchedPathname = joinPaths([matchedPathname, match.pathnameBase]);
}
}
return matches;
}
function matchPath(pattern, pathname) {
if (typeof pattern === "string") {
pattern = {
path: pattern,
caseSensitive: false,
end: true
};
}
let [matcher, compiledParams] = compilePath(pattern.path, pattern.caseSensitive, pattern.end);
let match = pathname.match(matcher);
if (!match) return null;
let matchedPathname = match[0];
let pathnameBase = matchedPathname.replace(/(.)\/+$/, "$1");
let captureGroups = match.slice(1);
let params = compiledParams.reduce((memo2, {
paramName,
isOptional
}, index) => {
if (paramName === "*") {
let splatValue = captureGroups[index] || "";
pathnameBase = matchedPathname.slice(0, matchedPathname.length - splatValue.length).replace(/(.)\/+$/, "$1");
}
const value = captureGroups[index];
if (isOptional && !value) {
memo2[paramName] = void 0;
} else {
memo2[paramName] = (value || "").replace(/%2F/g, "/");
}
return memo2;
}, {});
return {
params,
pathname: matchedPathname,
pathnameBase,
pattern
};
}
function compilePath(path, caseSensitive = false, end = true) {
warning(path === "*" || !path.endsWith("*") || path.endsWith("/*"), `Route path "${path}" will be treated as if it were "${path.replace(/\*$/, "/*")}" because the \`*\` character must always follow a \`/\` in the pattern. To get rid of this warning, please change the route path to "${path.replace(/\*$/, "/*")}".`);
let params = [];
let regexpSource = "^" + path.replace(/\/*\*?$/, "").replace(/^\/*/, "/").replace(/[\\.*+^${}|()[\]]/g, "\\$&").replace(/\/:([\w-]+)(\?)?/g, (_, paramName, isOptional) => {
params.push({
paramName,
isOptional: isOptional != null
});
return isOptional ? "/?([^\\/]+)?" : "/([^\\/]+)";
});
if (path.endsWith("*")) {
params.push({
paramName: "*"
});
regexpSource += path === "*" || path === "/*" ? "(.*)$" : "(?:\\/(.+)|\\/*)$";
} else if (end) {
regexpSource += "\\/*$";
} else if (path !== "" && path !== "/") {
regexpSource += "(?:(?=\\/|$))";
} else ;
let matcher = new RegExp(regexpSource, caseSensitive ? void 0 : "i");
return [matcher, params];
}
function decodePath(value) {
try {
return value.split("/").map(v => decodeURIComponent(v).replace(/\//g, "%2F")).join("/");
} catch (error) {
warning(false, `The URL path "${value}" could not be decoded because it is a malformed URL segment. This is probably due to a bad percent encoding (${error}).`);
return value;
}
}
function stripBasename(pathname, basename) {
if (basename === "/") return pathname;
if (!pathname.toLowerCase().startsWith(basename.toLowerCase())) {
return null;
}
let startIndex = basename.endsWith("/") ? basename.length - 1 : basename.length;
let nextChar = pathname.charAt(startIndex);
if (nextChar && nextChar !== "/") {
return null;
}
return pathname.slice(startIndex) || "/";
}
function resolvePath(to, fromPathname = "/") {
let {
pathname: toPathname,
search = "",
hash = ""
} = typeof to === "string" ? parsePath(to) : to;
let pathname = toPathname ? toPathname.startsWith("/") ? toPathname : resolvePathname(toPathname, fromPathname) : fromPathname;
return {
pathname,
search: normalizeSearch(search),
hash: normalizeHash(hash)
};
}
function resolvePathname(relativePath, fromPathname) {
let segments = fromPathname.replace(/\/+$/, "").split("/");
let relativeSegments = relativePath.split("/");
relativeSegments.forEach(segment => {
if (segment === "..") {
if (segments.length > 1) segments.pop();
} else if (segment !== ".") {
segments.push(segment);
}
});
return segments.length > 1 ? segments.join("/") : "/";
}
function getInvalidPathError(char, field, dest, path) {
return `Cannot include a '${char}' character in a manually specified \`to.${field}\` field [${JSON.stringify(path)}]. Please separate it out to the \`to.${dest}\` field. Alternatively you may provide the full path as a string in <Link to="..."> and the router will parse it for you.`;
}
function getPathContributingMatches(matches) {
return matches.filter((match, index) => index === 0 || match.route.path && match.route.path.length > 0);
}
function getResolveToMatches(matches) {
let pathMatches = getPathContributingMatches(matches);
return pathMatches.map((match, idx) => idx === pathMatches.length - 1 ? match.pathname : match.pathnameBase);
}
function resolveTo(toArg, routePathnames, locationPathname, isPathRelative = false) {
let to;
if (typeof toArg === "string") {
to = parsePath(toArg);
} else {
to = {
...toArg
};
invariant(!to.pathname || !to.pathname.includes("?"), getInvalidPathError("?", "pathname", "search", to));
invariant(!to.pathname || !to.pathname.includes("#"), getInvalidPathError("#", "pathname", "hash", to));
invariant(!to.search || !to.search.includes("#"), getInvalidPathError("#", "search", "hash", to));
}
let isEmptyPath = toArg === "" || to.pathname === "";
let toPathname = isEmptyPath ? "/" : to.pathname;
let from;
if (toPathname == null) {
from = locationPathname;
} else {
let routePathnameIndex = routePathnames.length - 1;
if (!isPathRelative && toPathname.startsWith("..")) {
let toSegments = toPathname.split("/");
while (toSegments[0] === "..") {
toSegments.shift();
routePathnameIndex -= 1;
}
to.pathname = toSegments.join("/");
}
from = routePathnameIndex >= 0 ? routePathnames[routePathnameIndex] : "/";
}
let path = resolvePath(to, from);
let hasExplicitTrailingSlash = toPathname && toPathname !== "/" && toPathname.endsWith("/");
let hasCurrentTrailingSlash = (isEmptyPath || toPathname === ".") && locationPathname.endsWith("/");
if (!path.pathname.endsWith("/") && (hasExplicitTrailingSlash || hasCurrentTrailingSlash)) {
path.pathname += "/";
}
return path;
}
var joinPaths = paths => paths.join("/").replace(/\/\/+/g, "/");
var normalizePathname = pathname => pathname.replace(/\/+$/, "").replace(/^\/*/, "/");
var normalizeSearch = search => !search || search === "?" ? "" : search.startsWith("?") ? search : "?" + search;
var normalizeHash = hash => !hash || hash === "#" ? "" : hash.startsWith("#") ? hash : "#" + hash;
function isRouteErrorResponse(error) {
return error != null && typeof error.status === "number" && typeof error.statusText === "string" && typeof error.internal === "boolean" && "data" in error;
}
// lib/router/router.ts
var validMutationMethodsArr = ["POST", "PUT", "PATCH", "DELETE"];
new Set(validMutationMethodsArr);
var validRequestMethodsArr = ["GET", ...validMutationMethodsArr];
new Set(validRequestMethodsArr);
var DataRouterContext = React__namespace.createContext(null);
DataRouterContext.displayName = "DataRouter";
var DataRouterStateContext = React__namespace.createContext(null);
DataRouterStateContext.displayName = "DataRouterState";
var ViewTransitionContext = React__namespace.createContext({
isTransitioning: false
});
ViewTransitionContext.displayName = "ViewTransition";
var FetchersContext = React__namespace.createContext( /* @__PURE__ */new Map());
FetchersContext.displayName = "Fetchers";
var AwaitContext = React__namespace.createContext(null);
AwaitContext.displayName = "Await";
var NavigationContext = React__namespace.createContext(null);
NavigationContext.displayName = "Navigation";
var LocationContext = React__namespace.createContext(null);
LocationContext.displayName = "Location";
var RouteContext = React__namespace.createContext({
outlet: null,
matches: [],
isDataRoute: false
});
RouteContext.displayName = "Route";
var RouteErrorContext = React__namespace.createContext(null);
RouteErrorContext.displayName = "RouteError";
function useHref(to, {
relative
} = {}) {
invariant(useInRouterContext(),
// TODO: This error is probably because they somehow have 2 versions of the
// router loaded. We can help them understand how to avoid that.
`useHref() may be used only in the context of a <Router> component.`);
let {
basename,
navigator: navigator2
} = React__namespace.useContext(NavigationContext);
let {
hash,
pathname,
search
} = useResolvedPath(to, {
relative
});
let joinedPathname = pathname;
if (basename !== "/") {
joinedPathname = pathname === "/" ? basename : joinPaths([basename, pathname]);
}
return navigator2.createHref({
pathname: joinedPathname,
search,
hash
});
}
function useInRouterContext() {
return React__namespace.useContext(LocationContext) != null;
}
function useLocation() {
invariant(useInRouterContext(),
// TODO: This error is probably because they somehow have 2 versions of the
// router loaded. We can help them understand how to avoid that.
`useLocation() may be used only in the context of a <Router> component.`);
return React__namespace.useContext(LocationContext).location;
}
var navigateEffectWarning = `You should call navigate() in a React.useEffect(), not when your component is first rendered.`;
function useIsomorphicLayoutEffect(cb) {
let isStatic = React__namespace.useContext(NavigationContext).static;
if (!isStatic) {
React__namespace.useLayoutEffect(cb);
}
}
function useNavigate() {
let {
isDataRoute
} = React__namespace.useContext(RouteContext);
return isDataRoute ? useNavigateStable() : useNavigateUnstable();
}
function useNavigateUnstable() {
invariant(useInRouterContext(),
// TODO: This error is probably because they somehow have 2 versions of the
// router loaded. We can help them understand how to avoid that.
`useNavigate() may be used only in the context of a <Router> component.`);
let dataRouterContext = React__namespace.useContext(DataRouterContext);
let {
basename,
navigator: navigator2
} = React__namespace.useContext(NavigationContext);
let {
matches
} = React__namespace.useContext(RouteContext);
let {
pathname: locationPathname
} = useLocation();
let routePathnamesJson = JSON.stringify(getResolveToMatches(matches));
let activeRef = React__namespace.useRef(false);
useIsomorphicLayoutEffect(() => {
activeRef.current = true;
});
let navigate = React__namespace.useCallback((to, options = {}) => {
warning(activeRef.current, navigateEffectWarning);
if (!activeRef.current) return;
if (typeof to === "number") {
navigator2.go(to);
return;
}
let path = resolveTo(to, JSON.parse(routePathnamesJson), locationPathname, options.relative === "path");
if (dataRouterContext == null && basename !== "/") {
path.pathname = path.pathname === "/" ? basename : joinPaths([basename, path.pathname]);
}
(!!options.replace ? navigator2.replace : navigator2.push)(path, options.state, options);
}, [basename, navigator2, routePathnamesJson, locationPathname, dataRouterContext]);
return navigate;
}
React__namespace.createContext(null);
function useResolvedPath(to, {
relative
} = {}) {
let {
matches
} = React__namespace.useContext(RouteContext);
let {
pathname: locationPathname
} = useLocation();
let routePathnamesJson = JSON.stringify(getResolveToMatches(matches));
return React__namespace.useMemo(() => resolveTo(to, JSON.parse(routePathnamesJson), locationPathname, relative === "path"), [to, routePathnamesJson, locationPathname, relative]);
}
function useRoutes(routes, locationArg) {
return useRoutesImpl(routes, locationArg);
}
function useRoutesImpl(routes, locationArg, dataRouterState, future) {
invariant(useInRouterContext(),
// TODO: This error is probably because they somehow have 2 versions of the
// router loaded. We can help them understand how to avoid that.
`useRoutes() may be used only in the context of a <Router> component.`);
let {
navigator: navigator2,
static: isStatic
} = React__namespace.useContext(NavigationContext);
let {
matches: parentMatches
} = React__namespace.useContext(RouteContext);
let routeMatch = parentMatches[parentMatches.length - 1];
let parentParams = routeMatch ? routeMatch.params : {};
let parentPathname = routeMatch ? routeMatch.pathname : "/";
let parentPathnameBase = routeMatch ? routeMatch.pathnameBase : "/";
let parentRoute = routeMatch && routeMatch.route;
{
let parentPath = parentRoute && parentRoute.path || "";
warningOnce(parentPathname, !parentRoute || parentPath.endsWith("*") || parentPath.endsWith("*?"), `You rendered descendant <Routes> (or called \`useRoutes()\`) at "${parentPathname}" (under <Route path="${parentPath}">) but the parent route path has no trailing "*". This means if you navigate deeper, the parent won't match anymore and therefore the child routes will never render.
Please change the parent <Route path="${parentPath}"> to <Route path="${parentPath === "/" ? "*" : `${parentPath}/*`}">.`);
}
let locationFromContext = useLocation();
let location;
if (locationArg) {
let parsedLocationArg = typeof locationArg === "string" ? parsePath(locationArg) : locationArg;
invariant(parentPathnameBase === "/" || parsedLocationArg.pathname?.startsWith(parentPathnameBase), `When overriding the location using \`<Routes location>\` or \`useRoutes(routes, location)\`, the location pathname must begin with the portion of the URL pathname that was matched by all parent routes. The current pathname base is "${parentPathnameBase}" but pathname "${parsedLocationArg.pathname}" was given in the \`location\` prop.`);
location = parsedLocationArg;
} else {
location = locationFromContext;
}
let pathname = location.pathname || "/";
let remainingPathname = pathname;
if (parentPathnameBase !== "/") {
let parentSegments = parentPathnameBase.replace(/^\//, "").split("/");
let segments = pathname.replace(/^\//, "").split("/");
remainingPathname = "/" + segments.slice(parentSegments.length).join("/");
}
let matches = !isStatic && dataRouterState && dataRouterState.matches && dataRouterState.matches.length > 0 ? dataRouterState.matches : matchRoutes(routes, {
pathname: remainingPathname
});
{
warning(parentRoute || matches != null, `No routes matched location "${location.pathname}${location.search}${location.hash}" `);
warning(matches == null || matches[matches.length - 1].route.element !== void 0 || matches[matches.length - 1].route.Component !== void 0 || matches[matches.length - 1].route.lazy !== void 0, `Matched leaf route at location "${location.pathname}${location.search}${location.hash}" does not have an element or Component. This means it will render an <Outlet /> with a null value by default resulting in an "empty" page.`);
}
let renderedMatches = _renderMatches(matches && matches.map(match => Object.assign({}, match, {
params: Object.assign({}, parentParams, match.params),
pathname: joinPaths([parentPathnameBase,
// Re-encode pathnames that were decoded inside matchRoutes
navigator2.encodeLocation ? navigator2.encodeLocation(match.pathname).pathname : match.pathname]),
pathnameBase: match.pathnameBase === "/" ? parentPathnameBase : joinPaths([parentPathnameBase,
// Re-encode pathnames that were decoded inside matchRoutes
navigator2.encodeLocation ? navigator2.encodeLocation(match.pathnameBase).pathname : match.pathnameBase])
})), parentMatches, dataRouterState, future);
if (locationArg && renderedMatches) {
return /* @__PURE__ */React__namespace.createElement(LocationContext.Provider, {
value: {
location: {
pathname: "/",
search: "",
hash: "",
state: null,
key: "default",
...location
},
navigationType: "POP" /* Pop */
}
}, renderedMatches);
}
return renderedMatches;
}
function DefaultErrorComponent() {
let error = useRouteError();
let message = isRouteErrorResponse(error) ? `${error.status} ${error.statusText}` : error instanceof Error ? error.message : JSON.stringify(error);
let stack = error instanceof Error ? error.stack : null;
let lightgrey = "rgba(200,200,200, 0.5)";
let preStyles = {
padding: "0.5rem",
backgroundColor: lightgrey
};
let codeStyles = {
padding: "2px 4px",
backgroundColor: lightgrey
};
let devInfo = null;
{
console.error("Error handled by React Router default ErrorBoundary:", error);
devInfo = /* @__PURE__ */React__namespace.createElement(React__namespace.Fragment, null, /* @__PURE__ */React__namespace.createElement("p", null, "\u{1F4BF} Hey developer \u{1F44B}"), /* @__PURE__ */React__namespace.createElement("p", null, "You can provide a way better UX than this when your app throws errors by providing your own ", /* @__PURE__ */React__namespace.createElement("code", {
style: codeStyles
}, "ErrorBoundary"), " or", " ", /* @__PURE__ */React__namespace.createElement("code", {
style: codeStyles
}, "errorElement"), " prop on your route."));
}
return /* @__PURE__ */React__namespace.createElement(React__namespace.Fragment, null, /* @__PURE__ */React__namespace.createElement("h2", null, "Unexpected Application Error!"), /* @__PURE__ */React__namespace.createElement("h3", {
style: {
fontStyle: "italic"
}
}, message), stack ? /* @__PURE__ */React__namespace.createElement("pre", {
style: preStyles
}, stack) : null, devInfo);
}
var defaultErrorElement = /* @__PURE__ */React__namespace.createElement(DefaultErrorComponent, null);
var RenderErrorBoundary = class extends React__namespace.Component {
constructor(props) {
super(props);
this.state = {
location: props.location,
revalidation: props.revalidation,
error: props.error
};
}
static getDerivedStateFromError(error) {
return {
error
};
}
static getDerivedStateFromProps(props, state) {
if (state.location !== props.location || state.revalidation !== "idle" && props.revalidation === "idle") {
return {
error: props.error,
location: props.location,
revalidation: props.revalidation
};
}
return {
error: props.error !== void 0 ? props.error : state.error,
location: state.location,
revalidation: props.revalidation || state.revalidation
};
}
componentDidCatch(error, errorInfo) {
console.error("React Router caught the following error during render", error, errorInfo);
}
render() {
return this.state.error !== void 0 ? /* @__PURE__ */React__namespace.createElement(RouteContext.Provider, {
value: this.props.routeContext
}, /* @__PURE__ */React__namespace.createElement(RouteErrorContext.Provider, {
value: this.state.error,
children: this.props.component
})) : this.props.children;
}
};
function RenderedRoute({
routeContext,
match,
children
}) {
let dataRouterContext = React__namespace.useContext(DataRouterContext);
if (dataRouterContext && dataRouterContext.static && dataRouterContext.staticContext && (match.route.errorElement || match.route.ErrorBoundary)) {
dataRouterContext.staticContext._deepestRenderedBoundaryId = match.route.id;
}
return /* @__PURE__ */React__namespace.createElement(RouteContext.Provider, {
value: routeContext
}, children);
}
function _renderMatches(matches, parentMatches = [], dataRouterState = null, future = null) {
if (matches == null) {
if (!dataRouterState) {
return null;
}
if (dataRouterState.errors) {
matches = dataRouterState.matches;
} else if (parentMatches.length === 0 && !dataRouterState.initialized && dataRouterState.matches.length > 0) {
matches = dataRouterState.matches;
} else {
return null;
}
}
let renderedMatches = matches;
let errors = dataRouterState?.errors;
if (errors != null) {
let errorIndex = renderedMatches.findIndex(m => m.route.id && errors?.[m.route.id] !== void 0);
invariant(errorIndex >= 0, `Could not find a matching route for errors on route IDs: ${Object.keys(errors).join(",")}`);
renderedMatches = renderedMatches.slice(0, Math.min(renderedMatches.length, errorIndex + 1));
}
let renderFallback = false;
let fallbackIndex = -1;
if (dataRouterState) {
for (let i = 0; i < renderedMatches.length; i++) {
let match = renderedMatches[i];
if (match.route.HydrateFallback || match.route.hydrateFallbackElement) {
fallbackIndex = i;
}
if (match.route.id) {
let {
loaderData,
errors: errors2
} = dataRouterState;
let needsToRunLoader = match.route.loader && !loaderData.hasOwnProperty(match.route.id) && (!errors2 || errors2[match.route.id] === void 0);
if (match.route.lazy || needsToRunLoader) {
renderFallback = true;
if (fallbackIndex >= 0) {
renderedMatches = renderedMatches.slice(0, fallbackIndex + 1);
} else {
renderedMatches = [renderedMatches[0]];
}
break;
}
}
}
}
return renderedMatches.reduceRight((outlet, match, index) => {
let error;
let shouldRenderHydrateFallback = false;
let errorElement = null;
let hydrateFallbackElement = null;
if (dataRouterState) {
error = errors && match.route.id ? errors[match.route.id] : void 0;
errorElement = match.route.errorElement || defaultErrorElement;
if (renderFallback) {
if (fallbackIndex < 0 && index === 0) {
warningOnce("route-fallback", false, "No `HydrateFallback` element provided to render during initial hydration");
shouldRenderHydrateFallback = true;
hydrateFallbackElement = null;
} else if (fallbackIndex === index) {
shouldRenderHydrateFallback = true;
hydrateFallbackElement = match.route.hydrateFallbackElement || null;
}
}
}
let matches2 = parentMatches.concat(renderedMatches.slice(0, index + 1));
let getChildren = () => {
let children;
if (error) {
children = errorElement;
} else if (shouldRenderHydrateFallback) {
children = hydrateFallbackElement;
} else if (match.route.Component) {
children = /* @__PURE__ */React__namespace.createElement(match.route.Component, null);
} else if (match.route.element) {
children = match.route.element;
} else {
children = outlet;
}
return /* @__PURE__ */React__namespace.createElement(RenderedRoute, {
match,
routeContext: {
outlet,
matches: matches2,
isDataRoute: dataRouterState != null
},
children
});
};
return dataRouterState && (match.route.ErrorBoundary || match.route.errorElement || index === 0) ? /* @__PURE__ */React__namespace.createElement(RenderErrorBoundary, {
location: dataRouterState.location,
revalidation: dataRouterState.revalidation,
component: errorElement,
error,
children: getChildren(),
routeContext: {
outlet: null,
matches: matches2,
isDataRoute: true
}
}) : getChildren();
}, null);
}
function getDataRouterConsoleError(hookName) {
return `${hookName} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`;
}
function useDataRouterContext(hookName) {
let ctx = React__namespace.useContext(DataRouterContext);
invariant(ctx, getDataRouterConsoleError(hookName));
return ctx;
}
function useDataRouterState(hookName) {
let state = React__namespace.useContext(DataRouterStateContext);
invariant(state, getDataRouterConsoleError(hookName));
return state;
}
function useRouteContext(hookName) {
let route = React__namespace.useContext(RouteContext);
invariant(route, getDataRouterConsoleError(hookName));
return route;
}
function useCurrentRouteId(hookName) {
let route = useRouteContext(hookName);
let thisRoute = route.matches[route.matches.length - 1];
invariant(thisRoute.route.id, `${hookName} can only be used on routes that contain a unique "id"`);
return thisRoute.route.id;
}
function useRouteId() {
return useCurrentRouteId("useRouteId" /* UseRouteId */);
}
function useRouteError() {
let error = React__namespace.useContext(RouteErrorContext);
let state = useDataRouterState("useRouteError" /* UseRouteError */);
let routeId = useCurrentRouteId("useRouteError" /* UseRouteError */);
if (error !== void 0) {
return error;
}
return state.errors?.[routeId];
}
function useNavigateStable() {
let {
router
} = useDataRouterContext("useNavigate" /* UseNavigateStable */);
let id = useCurrentRouteId("useNavigate" /* UseNavigateStable */);
let activeRef = React__namespace.useRef(false);
useIsomorphicLayoutEffect(() => {
activeRef.current = true;
});
let navigate = React__namespace.useCallback(async (to, options = {}) => {
warning(activeRef.current, navigateEffectWarning);
if (!activeRef.current) return;
if (typeof to === "number") {
router.navigate(to);
} else {
await router.navigate(to, {
fromRouteId: id,
...options
});
}
}, [router, id]);
return navigate;
}
var alreadyWarned = {};
function warningOnce(key, cond, message) {
if (!cond && !alreadyWarned[key]) {
alreadyWarned[key] = true;
warning(false, message);
}
}
React__namespace.memo(DataRoutes);
function DataRoutes({
routes,
future,
state
}) {
return useRoutesImpl(routes, void 0, state, future);
}
function Navigate({
to,
replace: replace2,
state,
relative
}) {
invariant(useInRouterContext(),
// TODO: This error is probably because they somehow have 2 versions of
// the router loaded. We can help them understand how to avoid that.
`<Navigate> may be used only in the context of a <Router> component.`);
let {
static: isStatic
} = React__namespace.useContext(NavigationContext);
warning(!isStatic, `<Navigate> must not be used on the initial render in a <StaticRouter>. This is a no-op, but you should modify your code so the <Navigate> is only ever rendered in response to some user interaction or state change.`);
let {
matches
} = React__namespace.useContext(RouteContext);
let {
pathname: locationPathname
} = useLocation();
let navigate = useNavigate();
let path = resolveTo(to, getResolveToMatches(matches), locationPathname, relative === "path");
let jsonPath = JSON.stringify(path);
React__namespace.useEffect(() => {
navigate(JSON.parse(jsonPath), {
replace: replace2,
state,
relative
});
}, [navigate, jsonPath, relative, replace2, state]);
return null;
}
function Route(_props) {
invariant(false, `A <Route> is only ever to be used as the child of <Routes> element, never rendered directly. Please wrap your <Route> in a <Routes>.`);
}
function Router({
basename: basenameProp = "/",
children = null,
location: locationProp,
navigationType = "POP" /* Pop */,
navigator: navigator2,
static: staticProp = false
}) {
invariant(!useInRouterContext(), `You cannot render a <Router> inside another <Router>. You should never have more than one in your app.`);
let basename = basenameProp.replace(/^\/*/, "/");
let navigationContext = React__namespace.useMemo(() => ({
basename,
navigator: navigator2,
static: staticProp,
future: {}
}), [basename, navigator2, staticProp]);
if (typeof locationProp === "string") {
locationProp = parsePath(locationProp);
}
let {
pathname = "/",
search = "",
hash = "",
state = null,
key = "default"
} = locationProp;
let locationContext = React__namespace.useMemo(() => {
let trailingPathname = stripBasename(pathname, basename);
if (trailingPathname == null) {
return null;
}
return {
location: {
pathname: trailingPathname,
search,
hash,
state,
key
},
navigationType
};
}, [basename, pathname, search, hash, state, key