5504 lines
178 KiB
JavaScript
5504 lines
178 KiB
JavaScript
/**
|
|
* 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
|
|
*/
|
|
"use strict";
|
|
var __create = Object.create;
|
|
var __defProp = Object.defineProperty;
|
|
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
var __getProtoOf = Object.getPrototypeOf;
|
|
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
var __export = (target, all) => {
|
|
for (var name in all)
|
|
__defProp(target, name, { get: all[name], enumerable: true });
|
|
};
|
|
var __copyProps = (to, from, except, desc) => {
|
|
if (from && typeof from === "object" || typeof from === "function") {
|
|
for (let key of __getOwnPropNames(from))
|
|
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
}
|
|
return to;
|
|
};
|
|
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
// If the importer is in node compatibility mode or this is not an ESM
|
|
// file that has been converted to a CommonJS file using a Babel-
|
|
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
mod
|
|
));
|
|
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
|
|
// dom-export.ts
|
|
var dom_export_exports = {};
|
|
__export(dom_export_exports, {
|
|
HydratedRouter: () => HydratedRouter,
|
|
RouterProvider: () => RouterProvider2
|
|
});
|
|
module.exports = __toCommonJS(dom_export_exports);
|
|
|
|
// lib/dom-export/dom-router-provider.tsx
|
|
var React10 = __toESM(require("react"));
|
|
var ReactDOM = __toESM(require("react-dom"));
|
|
|
|
// lib/router/history.ts
|
|
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, createHref, 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 createHref(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;
|
|
}
|
|
|
|
// lib/router/utils.ts
|
|
var immutableRouteKeys = /* @__PURE__ */ new Set([
|
|
"lazy",
|
|
"caseSensitive",
|
|
"path",
|
|
"id",
|
|
"index",
|
|
"children"
|
|
]);
|
|
function isIndexRoute(route) {
|
|
return route.index === true;
|
|
}
|
|
function convertRoutesToDataRoutes(routes, mapRouteProperties2, parentPath = [], manifest = {}) {
|
|
return routes.map((route, index) => {
|
|
let treePath = [...parentPath, String(index)];
|
|
let id = typeof route.id === "string" ? route.id : treePath.join("-");
|
|
invariant(
|
|
route.index !== true || !route.children,
|
|
`Cannot specify children on an index route`
|
|
);
|
|
invariant(
|
|
!manifest[id],
|
|
`Found a route id collision on id "${id}". Route id's must be globally unique within Data Router usages`
|
|
);
|
|
if (isIndexRoute(route)) {
|
|
let indexRoute = {
|
|
...route,
|
|
...mapRouteProperties2(route),
|
|
id
|
|
};
|
|
manifest[id] = indexRoute;
|
|
return indexRoute;
|
|
} else {
|
|
let pathOrLayoutRoute = {
|
|
...route,
|
|
...mapRouteProperties2(route),
|
|
id,
|
|
children: void 0
|
|
};
|
|
manifest[id] = pathOrLayoutRoute;
|
|
if (route.children) {
|
|
pathOrLayoutRoute.children = convertRoutesToDataRoutes(
|
|
route.children,
|
|
mapRouteProperties2,
|
|
treePath,
|
|
manifest
|
|
);
|
|
}
|
|
return pathOrLayoutRoute;
|
|
}
|
|
});
|
|
}
|
|
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 convertRouteMatchToUiMatch(match, loaderData) {
|
|
let { route, pathname, params } = match;
|
|
return {
|
|
id: route.id,
|
|
pathname,
|
|
params,
|
|
data: loaderData[route.id],
|
|
handle: route.handle
|
|
};
|
|
}
|
|
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;
|
|
var DataWithResponseInit = class {
|
|
constructor(data2, init) {
|
|
this.type = "DataWithResponseInit";
|
|
this.data = data2;
|
|
this.init = init || null;
|
|
}
|
|
};
|
|
function data(data2, init) {
|
|
return new DataWithResponseInit(
|
|
data2,
|
|
typeof init === "number" ? { status: init } : init
|
|
);
|
|
}
|
|
var redirect = (url, init = 302) => {
|
|
let responseInit = init;
|
|
if (typeof responseInit === "number") {
|
|
responseInit = { status: responseInit };
|
|
} else if (typeof responseInit.status === "undefined") {
|
|
responseInit.status = 302;
|
|
}
|
|
let headers = new Headers(responseInit.headers);
|
|
headers.set("Location", url);
|
|
return new Response(null, { ...responseInit, headers });
|
|
};
|
|
var ErrorResponseImpl = class {
|
|
constructor(status, statusText, data2, internal = false) {
|
|
this.status = status;
|
|
this.statusText = statusText || "";
|
|
this.internal = internal;
|
|
if (data2 instanceof Error) {
|
|
this.data = data2.toString();
|
|
this.error = data2;
|
|
} else {
|
|
this.data = data2;
|
|
}
|
|
}
|
|
};
|
|
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"
|
|
];
|
|
var validMutationMethods = new Set(
|
|
validMutationMethodsArr
|
|
);
|
|
var validRequestMethodsArr = [
|
|
"GET",
|
|
...validMutationMethodsArr
|
|
];
|
|
var validRequestMethods = new Set(validRequestMethodsArr);
|
|
var redirectStatusCodes = /* @__PURE__ */ new Set([301, 302, 303, 307, 308]);
|
|
var redirectPreserveMethodStatusCodes = /* @__PURE__ */ new Set([307, 308]);
|
|
var IDLE_NAVIGATION = {
|
|
state: "idle",
|
|
location: void 0,
|
|
formMethod: void 0,
|
|
formAction: void 0,
|
|
formEncType: void 0,
|
|
formData: void 0,
|
|
json: void 0,
|
|
text: void 0
|
|
};
|
|
var IDLE_FETCHER = {
|
|
state: "idle",
|
|
data: void 0,
|
|
formMethod: void 0,
|
|
formAction: void 0,
|
|
formEncType: void 0,
|
|
formData: void 0,
|
|
json: void 0,
|
|
text: void 0
|
|
};
|
|
var IDLE_BLOCKER = {
|
|
state: "unblocked",
|
|
proceed: void 0,
|
|
reset: void 0,
|
|
location: void 0
|
|
};
|
|
var ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i;
|
|
var defaultMapRouteProperties = (route) => ({
|
|
hasErrorBoundary: Boolean(route.hasErrorBoundary)
|
|
});
|
|
var TRANSITIONS_STORAGE_KEY = "remix-router-transitions";
|
|
var ResetLoaderDataSymbol = Symbol("ResetLoaderData");
|
|
function createRouter(init) {
|
|
const routerWindow = init.window ? init.window : typeof window !== "undefined" ? window : void 0;
|
|
const isBrowser = typeof routerWindow !== "undefined" && typeof routerWindow.document !== "undefined" && typeof routerWindow.document.createElement !== "undefined";
|
|
invariant(
|
|
init.routes.length > 0,
|
|
"You must provide a non-empty routes array to createRouter"
|
|
);
|
|
let mapRouteProperties2 = init.mapRouteProperties || defaultMapRouteProperties;
|
|
let manifest = {};
|
|
let dataRoutes = convertRoutesToDataRoutes(
|
|
init.routes,
|
|
mapRouteProperties2,
|
|
void 0,
|
|
manifest
|
|
);
|
|
let inFlightDataRoutes;
|
|
let basename = init.basename || "/";
|
|
let dataStrategyImpl = init.dataStrategy || defaultDataStrategy;
|
|
let patchRoutesOnNavigationImpl = init.patchRoutesOnNavigation;
|
|
let future = {
|
|
...init.future
|
|
};
|
|
let unlistenHistory = null;
|
|
let subscribers = /* @__PURE__ */ new Set();
|
|
let savedScrollPositions = null;
|
|
let getScrollRestorationKey = null;
|
|
let getScrollPosition = null;
|
|
let initialScrollRestored = init.hydrationData != null;
|
|
let initialMatches = matchRoutes(dataRoutes, init.history.location, basename);
|
|
let initialMatchesIsFOW = false;
|
|
let initialErrors = null;
|
|
if (initialMatches == null && !patchRoutesOnNavigationImpl) {
|
|
let error = getInternalRouterError(404, {
|
|
pathname: init.history.location.pathname
|
|
});
|
|
let { matches, route } = getShortCircuitMatches(dataRoutes);
|
|
initialMatches = matches;
|
|
initialErrors = { [route.id]: error };
|
|
}
|
|
if (initialMatches && !init.hydrationData) {
|
|
let fogOfWar = checkFogOfWar(
|
|
initialMatches,
|
|
dataRoutes,
|
|
init.history.location.pathname
|
|
);
|
|
if (fogOfWar.active) {
|
|
initialMatches = null;
|
|
}
|
|
}
|
|
let initialized;
|
|
if (!initialMatches) {
|
|
initialized = false;
|
|
initialMatches = [];
|
|
let fogOfWar = checkFogOfWar(
|
|
null,
|
|
dataRoutes,
|
|
init.history.location.pathname
|
|
);
|
|
if (fogOfWar.active && fogOfWar.matches) {
|
|
initialMatchesIsFOW = true;
|
|
initialMatches = fogOfWar.matches;
|
|
}
|
|
} else if (initialMatches.some((m) => m.route.lazy)) {
|
|
initialized = false;
|
|
} else if (!initialMatches.some((m) => m.route.loader)) {
|
|
initialized = true;
|
|
} else {
|
|
let loaderData = init.hydrationData ? init.hydrationData.loaderData : null;
|
|
let errors = init.hydrationData ? init.hydrationData.errors : null;
|
|
if (errors) {
|
|
let idx = initialMatches.findIndex(
|
|
(m) => errors[m.route.id] !== void 0
|
|
);
|
|
initialized = initialMatches.slice(0, idx + 1).every((m) => !shouldLoadRouteOnHydration(m.route, loaderData, errors));
|
|
} else {
|
|
initialized = initialMatches.every(
|
|
(m) => !shouldLoadRouteOnHydration(m.route, loaderData, errors)
|
|
);
|
|
}
|
|
}
|
|
let router2;
|
|
let state = {
|
|
historyAction: init.history.action,
|
|
location: init.history.location,
|
|
matches: initialMatches,
|
|
initialized,
|
|
navigation: IDLE_NAVIGATION,
|
|
// Don't restore on initial updateState() if we were SSR'd
|
|
restoreScrollPosition: init.hydrationData != null ? false : null,
|
|
preventScrollReset: false,
|
|
revalidation: "idle",
|
|
loaderData: init.hydrationData && init.hydrationData.loaderData || {},
|
|
actionData: init.hydrationData && init.hydrationData.actionData || null,
|
|
errors: init.hydrationData && init.hydrationData.errors || initialErrors,
|
|
fetchers: /* @__PURE__ */ new Map(),
|
|
blockers: /* @__PURE__ */ new Map()
|
|
};
|
|
let pendingAction = "POP" /* Pop */;
|
|
let pendingPreventScrollReset = false;
|
|
let pendingNavigationController;
|
|
let pendingViewTransitionEnabled = false;
|
|
let appliedViewTransitions = /* @__PURE__ */ new Map();
|
|
let removePageHideEventListener = null;
|
|
let isUninterruptedRevalidation = false;
|
|
let isRevalidationRequired = false;
|
|
let cancelledFetcherLoads = /* @__PURE__ */ new Set();
|
|
let fetchControllers = /* @__PURE__ */ new Map();
|
|
let incrementingLoadId = 0;
|
|
let pendingNavigationLoadId = -1;
|
|
let fetchReloadIds = /* @__PURE__ */ new Map();
|
|
let fetchRedirectIds = /* @__PURE__ */ new Set();
|
|
let fetchLoadMatches = /* @__PURE__ */ new Map();
|
|
let activeFetchers = /* @__PURE__ */ new Map();
|
|
let fetchersQueuedForDeletion = /* @__PURE__ */ new Set();
|
|
let blockerFunctions = /* @__PURE__ */ new Map();
|
|
let unblockBlockerHistoryUpdate = void 0;
|
|
let pendingRevalidationDfd = null;
|
|
function initialize() {
|
|
unlistenHistory = init.history.listen(
|
|
({ action: historyAction, location, delta }) => {
|
|
if (unblockBlockerHistoryUpdate) {
|
|
unblockBlockerHistoryUpdate();
|
|
unblockBlockerHistoryUpdate = void 0;
|
|
return;
|
|
}
|
|
warning(
|
|
blockerFunctions.size === 0 || delta != null,
|
|
"You are trying to use a blocker on a POP navigation to a location that was not created by @remix-run/router. This will fail silently in production. This can happen if you are navigating outside the router via `window.history.pushState`/`window.location.hash` instead of using router navigation APIs. This can also happen if you are using createHashRouter and the user manually changes the URL."
|
|
);
|
|
let blockerKey = shouldBlockNavigation({
|
|
currentLocation: state.location,
|
|
nextLocation: location,
|
|
historyAction
|
|
});
|
|
if (blockerKey && delta != null) {
|
|
let nextHistoryUpdatePromise = new Promise((resolve) => {
|
|
unblockBlockerHistoryUpdate = resolve;
|
|
});
|
|
init.history.go(delta * -1);
|
|
updateBlocker(blockerKey, {
|
|
state: "blocked",
|
|
location,
|
|
proceed() {
|
|
updateBlocker(blockerKey, {
|
|
state: "proceeding",
|
|
proceed: void 0,
|
|
reset: void 0,
|
|
location
|
|
});
|
|
nextHistoryUpdatePromise.then(() => init.history.go(delta));
|
|
},
|
|
reset() {
|
|
let blockers = new Map(state.blockers);
|
|
blockers.set(blockerKey, IDLE_BLOCKER);
|
|
updateState({ blockers });
|
|
}
|
|
});
|
|
return;
|
|
}
|
|
return startNavigation(historyAction, location);
|
|
}
|
|
);
|
|
if (isBrowser) {
|
|
restoreAppliedTransitions(routerWindow, appliedViewTransitions);
|
|
let _saveAppliedTransitions = () => persistAppliedTransitions(routerWindow, appliedViewTransitions);
|
|
routerWindow.addEventListener("pagehide", _saveAppliedTransitions);
|
|
removePageHideEventListener = () => routerWindow.removeEventListener("pagehide", _saveAppliedTransitions);
|
|
}
|
|
if (!state.initialized) {
|
|
startNavigation("POP" /* Pop */, state.location, {
|
|
initialHydration: true
|
|
});
|
|
}
|
|
return router2;
|
|
}
|
|
function dispose() {
|
|
if (unlistenHistory) {
|
|
unlistenHistory();
|
|
}
|
|
if (removePageHideEventListener) {
|
|
removePageHideEventListener();
|
|
}
|
|
subscribers.clear();
|
|
pendingNavigationController && pendingNavigationController.abort();
|
|
state.fetchers.forEach((_, key) => deleteFetcher(key));
|
|
state.blockers.forEach((_, key) => deleteBlocker(key));
|
|
}
|
|
function subscribe(fn) {
|
|
subscribers.add(fn);
|
|
return () => subscribers.delete(fn);
|
|
}
|
|
function updateState(newState, opts = {}) {
|
|
state = {
|
|
...state,
|
|
...newState
|
|
};
|
|
let unmountedFetchers = [];
|
|
let mountedFetchers = [];
|
|
state.fetchers.forEach((fetcher, key) => {
|
|
if (fetcher.state === "idle") {
|
|
if (fetchersQueuedForDeletion.has(key)) {
|
|
unmountedFetchers.push(key);
|
|
} else {
|
|
mountedFetchers.push(key);
|
|
}
|
|
}
|
|
});
|
|
fetchersQueuedForDeletion.forEach((key) => {
|
|
if (!state.fetchers.has(key) && !fetchControllers.has(key)) {
|
|
unmountedFetchers.push(key);
|
|
}
|
|
});
|
|
[...subscribers].forEach(
|
|
(subscriber) => subscriber(state, {
|
|
deletedFetchers: unmountedFetchers,
|
|
viewTransitionOpts: opts.viewTransitionOpts,
|
|
flushSync: opts.flushSync === true
|
|
})
|
|
);
|
|
unmountedFetchers.forEach((key) => deleteFetcher(key));
|
|
mountedFetchers.forEach((key) => state.fetchers.delete(key));
|
|
}
|
|
function completeNavigation(location, newState, { flushSync: flushSync2 } = {}) {
|
|
let isActionReload = state.actionData != null && state.navigation.formMethod != null && isMutationMethod(state.navigation.formMethod) && state.navigation.state === "loading" && location.state?._isRedirect !== true;
|
|
let actionData;
|
|
if (newState.actionData) {
|
|
if (Object.keys(newState.actionData).length > 0) {
|
|
actionData = newState.actionData;
|
|
} else {
|
|
actionData = null;
|
|
}
|
|
} else if (isActionReload) {
|
|
actionData = state.actionData;
|
|
} else {
|
|
actionData = null;
|
|
}
|
|
let loaderData = newState.loaderData ? mergeLoaderData(
|
|
state.loaderData,
|
|
newState.loaderData,
|
|
newState.matches || [],
|
|
newState.errors
|
|
) : state.loaderData;
|
|
let blockers = state.blockers;
|
|
if (blockers.size > 0) {
|
|
blockers = new Map(blockers);
|
|
blockers.forEach((_, k) => blockers.set(k, IDLE_BLOCKER));
|
|
}
|
|
let preventScrollReset = pendingPreventScrollReset === true || state.navigation.formMethod != null && isMutationMethod(state.navigation.formMethod) && location.state?._isRedirect !== true;
|
|
if (inFlightDataRoutes) {
|
|
dataRoutes = inFlightDataRoutes;
|
|
inFlightDataRoutes = void 0;
|
|
}
|
|
if (isUninterruptedRevalidation) {
|
|
} else if (pendingAction === "POP" /* Pop */) {
|
|
} else if (pendingAction === "PUSH" /* Push */) {
|
|
init.history.push(location, location.state);
|
|
} else if (pendingAction === "REPLACE" /* Replace */) {
|
|
init.history.replace(location, location.state);
|
|
}
|
|
let viewTransitionOpts;
|
|
if (pendingAction === "POP" /* Pop */) {
|
|
let priorPaths = appliedViewTransitions.get(state.location.pathname);
|
|
if (priorPaths && priorPaths.has(location.pathname)) {
|
|
viewTransitionOpts = {
|
|
currentLocation: state.location,
|
|
nextLocation: location
|
|
};
|
|
} else if (appliedViewTransitions.has(location.pathname)) {
|
|
viewTransitionOpts = {
|
|
currentLocation: location,
|
|
nextLocation: state.location
|
|
};
|
|
}
|
|
} else if (pendingViewTransitionEnabled) {
|
|
let toPaths = appliedViewTransitions.get(state.location.pathname);
|
|
if (toPaths) {
|
|
toPaths.add(location.pathname);
|
|
} else {
|
|
toPaths = /* @__PURE__ */ new Set([location.pathname]);
|
|
appliedViewTransitions.set(state.location.pathname, toPaths);
|
|
}
|
|
viewTransitionOpts = {
|
|
currentLocation: state.location,
|
|
nextLocation: location
|
|
};
|
|
}
|
|
updateState(
|
|
{
|
|
...newState,
|
|
// matches, errors, fetchers go through as-is
|
|
actionData,
|
|
loaderData,
|
|
historyAction: pendingAction,
|
|
location,
|
|
initialized: true,
|
|
navigation: IDLE_NAVIGATION,
|
|
revalidation: "idle",
|
|
restoreScrollPosition: getSavedScrollPosition(
|
|
location,
|
|
newState.matches || state.matches
|
|
),
|
|
preventScrollReset,
|
|
blockers
|
|
},
|
|
{
|
|
viewTransitionOpts,
|
|
flushSync: flushSync2 === true
|
|
}
|
|
);
|
|
pendingAction = "POP" /* Pop */;
|
|
pendingPreventScrollReset = false;
|
|
pendingViewTransitionEnabled = false;
|
|
isUninterruptedRevalidation = false;
|
|
isRevalidationRequired = false;
|
|
pendingRevalidationDfd?.resolve();
|
|
pendingRevalidationDfd = null;
|
|
}
|
|
async function navigate(to, opts) {
|
|
if (typeof to === "number") {
|
|
init.history.go(to);
|
|
return;
|
|
}
|
|
let normalizedPath = normalizeTo(
|
|
state.location,
|
|
state.matches,
|
|
basename,
|
|
to,
|
|
opts?.fromRouteId,
|
|
opts?.relative
|
|
);
|
|
let { path, submission, error } = normalizeNavigateOptions(
|
|
false,
|
|
normalizedPath,
|
|
opts
|
|
);
|
|
let currentLocation = state.location;
|
|
let nextLocation = createLocation(state.location, path, opts && opts.state);
|
|
nextLocation = {
|
|
...nextLocation,
|
|
...init.history.encodeLocation(nextLocation)
|
|
};
|
|
let userReplace = opts && opts.replace != null ? opts.replace : void 0;
|
|
let historyAction = "PUSH" /* Push */;
|
|
if (userReplace === true) {
|
|
historyAction = "REPLACE" /* Replace */;
|
|
} else if (userReplace === false) {
|
|
} else if (submission != null && isMutationMethod(submission.formMethod) && submission.formAction === state.location.pathname + state.location.search) {
|
|
historyAction = "REPLACE" /* Replace */;
|
|
}
|
|
let preventScrollReset = opts && "preventScrollReset" in opts ? opts.preventScrollReset === true : void 0;
|
|
let flushSync2 = (opts && opts.flushSync) === true;
|
|
let blockerKey = shouldBlockNavigation({
|
|
currentLocation,
|
|
nextLocation,
|
|
historyAction
|
|
});
|
|
if (blockerKey) {
|
|
updateBlocker(blockerKey, {
|
|
state: "blocked",
|
|
location: nextLocation,
|
|
proceed() {
|
|
updateBlocker(blockerKey, {
|
|
state: "proceeding",
|
|
proceed: void 0,
|
|
reset: void 0,
|
|
location: nextLocation
|
|
});
|
|
navigate(to, opts);
|
|
},
|
|
reset() {
|
|
let blockers = new Map(state.blockers);
|
|
blockers.set(blockerKey, IDLE_BLOCKER);
|
|
updateState({ blockers });
|
|
}
|
|
});
|
|
return;
|
|
}
|
|
await startNavigation(historyAction, nextLocation, {
|
|
submission,
|
|
// Send through the formData serialization error if we have one so we can
|
|
// render at the right error boundary after we match routes
|
|
pendingError: error,
|
|
preventScrollReset,
|
|
replace: opts && opts.replace,
|
|
enableViewTransition: opts && opts.viewTransition,
|
|
flushSync: flushSync2
|
|
});
|
|
}
|
|
function revalidate() {
|
|
if (!pendingRevalidationDfd) {
|
|
pendingRevalidationDfd = createDeferred();
|
|
}
|
|
interruptActiveLoads();
|
|
updateState({ revalidation: "loading" });
|
|
let promise = pendingRevalidationDfd.promise;
|
|
if (state.navigation.state === "submitting") {
|
|
return promise;
|
|
}
|
|
if (state.navigation.state === "idle") {
|
|
startNavigation(state.historyAction, state.location, {
|
|
startUninterruptedRevalidation: true
|
|
});
|
|
return promise;
|
|
}
|
|
startNavigation(
|
|
pendingAction || state.historyAction,
|
|
state.navigation.location,
|
|
{
|
|
overrideNavigation: state.navigation,
|
|
// Proxy through any rending view transition
|
|
enableViewTransition: pendingViewTransitionEnabled === true
|
|
}
|
|
);
|
|
return promise;
|
|
}
|
|
async function startNavigation(historyAction, location, opts) {
|
|
pendingNavigationController && pendingNavigationController.abort();
|
|
pendingNavigationController = null;
|
|
pendingAction = historyAction;
|
|
isUninterruptedRevalidation = (opts && opts.startUninterruptedRevalidation) === true;
|
|
saveScrollPosition(state.location, state.matches);
|
|
pendingPreventScrollReset = (opts && opts.preventScrollReset) === true;
|
|
pendingViewTransitionEnabled = (opts && opts.enableViewTransition) === true;
|
|
let routesToUse = inFlightDataRoutes || dataRoutes;
|
|
let loadingNavigation = opts && opts.overrideNavigation;
|
|
let matches = opts?.initialHydration && state.matches && state.matches.length > 0 && !initialMatchesIsFOW ? (
|
|
// `matchRoutes()` has already been called if we're in here via `router.initialize()`
|
|
state.matches
|
|
) : matchRoutes(routesToUse, location, basename);
|
|
let flushSync2 = (opts && opts.flushSync) === true;
|
|
if (matches && state.initialized && !isRevalidationRequired && isHashChangeOnly(state.location, location) && !(opts && opts.submission && isMutationMethod(opts.submission.formMethod))) {
|
|
completeNavigation(location, { matches }, { flushSync: flushSync2 });
|
|
return;
|
|
}
|
|
let fogOfWar = checkFogOfWar(matches, routesToUse, location.pathname);
|
|
if (fogOfWar.active && fogOfWar.matches) {
|
|
matches = fogOfWar.matches;
|
|
}
|
|
if (!matches) {
|
|
let { error, notFoundMatches, route } = handleNavigational404(
|
|
location.pathname
|
|
);
|
|
completeNavigation(
|
|
location,
|
|
{
|
|
matches: notFoundMatches,
|
|
loaderData: {},
|
|
errors: {
|
|
[route.id]: error
|
|
}
|
|
},
|
|
{ flushSync: flushSync2 }
|
|
);
|
|
return;
|
|
}
|
|
pendingNavigationController = new AbortController();
|
|
let request = createClientSideRequest(
|
|
init.history,
|
|
location,
|
|
pendingNavigationController.signal,
|
|
opts && opts.submission
|
|
);
|
|
let pendingActionResult;
|
|
if (opts && opts.pendingError) {
|
|
pendingActionResult = [
|
|
findNearestBoundary(matches).route.id,
|
|
{ type: "error" /* error */, error: opts.pendingError }
|
|
];
|
|
} else if (opts && opts.submission && isMutationMethod(opts.submission.formMethod)) {
|
|
let actionResult = await handleAction(
|
|
request,
|
|
location,
|
|
opts.submission,
|
|
matches,
|
|
fogOfWar.active,
|
|
{ replace: opts.replace, flushSync: flushSync2 }
|
|
);
|
|
if (actionResult.shortCircuited) {
|
|
return;
|
|
}
|
|
if (actionResult.pendingActionResult) {
|
|
let [routeId, result] = actionResult.pendingActionResult;
|
|
if (isErrorResult(result) && isRouteErrorResponse(result.error) && result.error.status === 404) {
|
|
pendingNavigationController = null;
|
|
completeNavigation(location, {
|
|
matches: actionResult.matches,
|
|
loaderData: {},
|
|
errors: {
|
|
[routeId]: result.error
|
|
}
|
|
});
|
|
return;
|
|
}
|
|
}
|
|
matches = actionResult.matches || matches;
|
|
pendingActionResult = actionResult.pendingActionResult;
|
|
loadingNavigation = getLoadingNavigation(location, opts.submission);
|
|
flushSync2 = false;
|
|
fogOfWar.active = false;
|
|
request = createClientSideRequest(
|
|
init.history,
|
|
request.url,
|
|
request.signal
|
|
);
|
|
}
|
|
let {
|
|
shortCircuited,
|
|
matches: updatedMatches,
|
|
loaderData,
|
|
errors
|
|
} = await handleLoaders(
|
|
request,
|
|
location,
|
|
matches,
|
|
fogOfWar.active,
|
|
loadingNavigation,
|
|
opts && opts.submission,
|
|
opts && opts.fetcherSubmission,
|
|
opts && opts.replace,
|
|
opts && opts.initialHydration === true,
|
|
flushSync2,
|
|
pendingActionResult
|
|
);
|
|
if (shortCircuited) {
|
|
return;
|
|
}
|
|
pendingNavigationController = null;
|
|
completeNavigation(location, {
|
|
matches: updatedMatches || matches,
|
|
...getActionDataForCommit(pendingActionResult),
|
|
loaderData,
|
|
errors
|
|
});
|
|
}
|
|
async function handleAction(request, location, submission, matches, isFogOfWar, opts = {}) {
|
|
interruptActiveLoads();
|
|
let navigation = getSubmittingNavigation(location, submission);
|
|
updateState({ navigation }, { flushSync: opts.flushSync === true });
|
|
if (isFogOfWar) {
|
|
let discoverResult = await discoverRoutes(
|
|
matches,
|
|
location.pathname,
|
|
request.signal
|
|
);
|
|
if (discoverResult.type === "aborted") {
|
|
return { shortCircuited: true };
|
|
} else if (discoverResult.type === "error") {
|
|
let boundaryId = findNearestBoundary(discoverResult.partialMatches).route.id;
|
|
return {
|
|
matches: discoverResult.partialMatches,
|
|
pendingActionResult: [
|
|
boundaryId,
|
|
{
|
|
type: "error" /* error */,
|
|
error: discoverResult.error
|
|
}
|
|
]
|
|
};
|
|
} else if (!discoverResult.matches) {
|
|
let { notFoundMatches, error, route } = handleNavigational404(
|
|
location.pathname
|
|
);
|
|
return {
|
|
matches: notFoundMatches,
|
|
pendingActionResult: [
|
|
route.id,
|
|
{
|
|
type: "error" /* error */,
|
|
error
|
|
}
|
|
]
|
|
};
|
|
} else {
|
|
matches = discoverResult.matches;
|
|
}
|
|
}
|
|
let result;
|
|
let actionMatch = getTargetMatch(matches, location);
|
|
if (!actionMatch.route.action && !actionMatch.route.lazy) {
|
|
result = {
|
|
type: "error" /* error */,
|
|
error: getInternalRouterError(405, {
|
|
method: request.method,
|
|
pathname: location.pathname,
|
|
routeId: actionMatch.route.id
|
|
})
|
|
};
|
|
} else {
|
|
let results = await callDataStrategy(
|
|
"action",
|
|
state,
|
|
request,
|
|
[actionMatch],
|
|
matches,
|
|
null
|
|
);
|
|
result = results[actionMatch.route.id];
|
|
if (request.signal.aborted) {
|
|
return { shortCircuited: true };
|
|
}
|
|
}
|
|
if (isRedirectResult(result)) {
|
|
let replace2;
|
|
if (opts && opts.replace != null) {
|
|
replace2 = opts.replace;
|
|
} else {
|
|
let location2 = normalizeRedirectLocation(
|
|
result.response.headers.get("Location"),
|
|
new URL(request.url),
|
|
basename
|
|
);
|
|
replace2 = location2 === state.location.pathname + state.location.search;
|
|
}
|
|
await startRedirectNavigation(request, result, true, {
|
|
submission,
|
|
replace: replace2
|
|
});
|
|
return { shortCircuited: true };
|
|
}
|
|
if (isErrorResult(result)) {
|
|
let boundaryMatch = findNearestBoundary(matches, actionMatch.route.id);
|
|
if ((opts && opts.replace) !== true) {
|
|
pendingAction = "PUSH" /* Push */;
|
|
}
|
|
return {
|
|
matches,
|
|
pendingActionResult: [boundaryMatch.route.id, result]
|
|
};
|
|
}
|
|
return {
|
|
matches,
|
|
pendingActionResult: [actionMatch.route.id, result]
|
|
};
|
|
}
|
|
async function handleLoaders(request, location, matches, isFogOfWar, overrideNavigation, submission, fetcherSubmission, replace2, initialHydration, flushSync2, pendingActionResult) {
|
|
let loadingNavigation = overrideNavigation || getLoadingNavigation(location, submission);
|
|
let activeSubmission = submission || fetcherSubmission || getSubmissionFromNavigation(loadingNavigation);
|
|
let shouldUpdateNavigationState = !isUninterruptedRevalidation && !initialHydration;
|
|
if (isFogOfWar) {
|
|
if (shouldUpdateNavigationState) {
|
|
let actionData = getUpdatedActionData(pendingActionResult);
|
|
updateState(
|
|
{
|
|
navigation: loadingNavigation,
|
|
...actionData !== void 0 ? { actionData } : {}
|
|
},
|
|
{
|
|
flushSync: flushSync2
|
|
}
|
|
);
|
|
}
|
|
let discoverResult = await discoverRoutes(
|
|
matches,
|
|
location.pathname,
|
|
request.signal
|
|
);
|
|
if (discoverResult.type === "aborted") {
|
|
return { shortCircuited: true };
|
|
} else if (discoverResult.type === "error") {
|
|
let boundaryId = findNearestBoundary(discoverResult.partialMatches).route.id;
|
|
return {
|
|
matches: discoverResult.partialMatches,
|
|
loaderData: {},
|
|
errors: {
|
|
[boundaryId]: discoverResult.error
|
|
}
|
|
};
|
|
} else if (!discoverResult.matches) {
|
|
let { error, notFoundMatches, route } = handleNavigational404(
|
|
location.pathname
|
|
);
|
|
return {
|
|
matches: notFoundMatches,
|
|
loaderData: {},
|
|
errors: {
|
|
[route.id]: error
|
|
}
|
|
};
|
|
} else {
|
|
matches = discoverResult.matches;
|
|
}
|
|
}
|
|
let routesToUse = inFlightDataRoutes || dataRoutes;
|
|
let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(
|
|
init.history,
|
|
state,
|
|
matches,
|
|
activeSubmission,
|
|
location,
|
|
initialHydration === true,
|
|
isRevalidationRequired,
|
|
cancelledFetcherLoads,
|
|
fetchersQueuedForDeletion,
|
|
fetchLoadMatches,
|
|
fetchRedirectIds,
|
|
routesToUse,
|
|
basename,
|
|
pendingActionResult
|
|
);
|
|
pendingNavigationLoadId = ++incrementingLoadId;
|
|
if (matchesToLoad.length === 0 && revalidatingFetchers.length === 0) {
|
|
let updatedFetchers2 = markFetchRedirectsDone();
|
|
completeNavigation(
|
|
location,
|
|
{
|
|
matches,
|
|
loaderData: {},
|
|
// Commit pending error if we're short circuiting
|
|
errors: pendingActionResult && isErrorResult(pendingActionResult[1]) ? { [pendingActionResult[0]]: pendingActionResult[1].error } : null,
|
|
...getActionDataForCommit(pendingActionResult),
|
|
...updatedFetchers2 ? { fetchers: new Map(state.fetchers) } : {}
|
|
},
|
|
{ flushSync: flushSync2 }
|
|
);
|
|
return { shortCircuited: true };
|
|
}
|
|
if (shouldUpdateNavigationState) {
|
|
let updates = {};
|
|
if (!isFogOfWar) {
|
|
updates.navigation = loadingNavigation;
|
|
let actionData = getUpdatedActionData(pendingActionResult);
|
|
if (actionData !== void 0) {
|
|
updates.actionData = actionData;
|
|
}
|
|
}
|
|
if (revalidatingFetchers.length > 0) {
|
|
updates.fetchers = getUpdatedRevalidatingFetchers(revalidatingFetchers);
|
|
}
|
|
updateState(updates, { flushSync: flushSync2 });
|
|
}
|
|
revalidatingFetchers.forEach((rf) => {
|
|
abortFetcher(rf.key);
|
|
if (rf.controller) {
|
|
fetchControllers.set(rf.key, rf.controller);
|
|
}
|
|
});
|
|
let abortPendingFetchRevalidations = () => revalidatingFetchers.forEach((f) => abortFetcher(f.key));
|
|
if (pendingNavigationController) {
|
|
pendingNavigationController.signal.addEventListener(
|
|
"abort",
|
|
abortPendingFetchRevalidations
|
|
);
|
|
}
|
|
let { loaderResults, fetcherResults } = await callLoadersAndMaybeResolveData(
|
|
state,
|
|
matches,
|
|
matchesToLoad,
|
|
revalidatingFetchers,
|
|
request
|
|
);
|
|
if (request.signal.aborted) {
|
|
return { shortCircuited: true };
|
|
}
|
|
if (pendingNavigationController) {
|
|
pendingNavigationController.signal.removeEventListener(
|
|
"abort",
|
|
abortPendingFetchRevalidations
|
|
);
|
|
}
|
|
revalidatingFetchers.forEach((rf) => fetchControllers.delete(rf.key));
|
|
let redirect2 = findRedirect(loaderResults);
|
|
if (redirect2) {
|
|
await startRedirectNavigation(request, redirect2.result, true, {
|
|
replace: replace2
|
|
});
|
|
return { shortCircuited: true };
|
|
}
|
|
redirect2 = findRedirect(fetcherResults);
|
|
if (redirect2) {
|
|
fetchRedirectIds.add(redirect2.key);
|
|
await startRedirectNavigation(request, redirect2.result, true, {
|
|
replace: replace2
|
|
});
|
|
return { shortCircuited: true };
|
|
}
|
|
let { loaderData, errors } = processLoaderData(
|
|
state,
|
|
matches,
|
|
loaderResults,
|
|
pendingActionResult,
|
|
revalidatingFetchers,
|
|
fetcherResults
|
|
);
|
|
if (initialHydration && state.errors) {
|
|
errors = { ...state.errors, ...errors };
|
|
}
|
|
let updatedFetchers = markFetchRedirectsDone();
|
|
let didAbortFetchLoads = abortStaleFetchLoads(pendingNavigationLoadId);
|
|
let shouldUpdateFetchers = updatedFetchers || didAbortFetchLoads || revalidatingFetchers.length > 0;
|
|
return {
|
|
matches,
|
|
loaderData,
|
|
errors,
|
|
...shouldUpdateFetchers ? { fetchers: new Map(state.fetchers) } : {}
|
|
};
|
|
}
|
|
function getUpdatedActionData(pendingActionResult) {
|
|
if (pendingActionResult && !isErrorResult(pendingActionResult[1])) {
|
|
return {
|
|
[pendingActionResult[0]]: pendingActionResult[1].data
|
|
};
|
|
} else if (state.actionData) {
|
|
if (Object.keys(state.actionData).length === 0) {
|
|
return null;
|
|
} else {
|
|
return state.actionData;
|
|
}
|
|
}
|
|
}
|
|
function getUpdatedRevalidatingFetchers(revalidatingFetchers) {
|
|
revalidatingFetchers.forEach((rf) => {
|
|
let fetcher = state.fetchers.get(rf.key);
|
|
let revalidatingFetcher = getLoadingFetcher(
|
|
void 0,
|
|
fetcher ? fetcher.data : void 0
|
|
);
|
|
state.fetchers.set(rf.key, revalidatingFetcher);
|
|
});
|
|
return new Map(state.fetchers);
|
|
}
|
|
async function fetch2(key, routeId, href, opts) {
|
|
abortFetcher(key);
|
|
let flushSync2 = (opts && opts.flushSync) === true;
|
|
let routesToUse = inFlightDataRoutes || dataRoutes;
|
|
let normalizedPath = normalizeTo(
|
|
state.location,
|
|
state.matches,
|
|
basename,
|
|
href,
|
|
routeId,
|
|
opts?.relative
|
|
);
|
|
let matches = matchRoutes(routesToUse, normalizedPath, basename);
|
|
let fogOfWar = checkFogOfWar(matches, routesToUse, normalizedPath);
|
|
if (fogOfWar.active && fogOfWar.matches) {
|
|
matches = fogOfWar.matches;
|
|
}
|
|
if (!matches) {
|
|
setFetcherError(
|
|
key,
|
|
routeId,
|
|
getInternalRouterError(404, { pathname: normalizedPath }),
|
|
{ flushSync: flushSync2 }
|
|
);
|
|
return;
|
|
}
|
|
let { path, submission, error } = normalizeNavigateOptions(
|
|
true,
|
|
normalizedPath,
|
|
opts
|
|
);
|
|
if (error) {
|
|
setFetcherError(key, routeId, error, { flushSync: flushSync2 });
|
|
return;
|
|
}
|
|
let match = getTargetMatch(matches, path);
|
|
let preventScrollReset = (opts && opts.preventScrollReset) === true;
|
|
if (submission && isMutationMethod(submission.formMethod)) {
|
|
await handleFetcherAction(
|
|
key,
|
|
routeId,
|
|
path,
|
|
match,
|
|
matches,
|
|
fogOfWar.active,
|
|
flushSync2,
|
|
preventScrollReset,
|
|
submission
|
|
);
|
|
return;
|
|
}
|
|
fetchLoadMatches.set(key, { routeId, path });
|
|
await handleFetcherLoader(
|
|
key,
|
|
routeId,
|
|
path,
|
|
match,
|
|
matches,
|
|
fogOfWar.active,
|
|
flushSync2,
|
|
preventScrollReset,
|
|
submission
|
|
);
|
|
}
|
|
async function handleFetcherAction(key, routeId, path, match, requestMatches, isFogOfWar, flushSync2, preventScrollReset, submission) {
|
|
interruptActiveLoads();
|
|
fetchLoadMatches.delete(key);
|
|
function detectAndHandle405Error(m) {
|
|
if (!m.route.action && !m.route.lazy) {
|
|
let error = getInternalRouterError(405, {
|
|
method: submission.formMethod,
|
|
pathname: path,
|
|
routeId
|
|
});
|
|
setFetcherError(key, routeId, error, { flushSync: flushSync2 });
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|
|
if (!isFogOfWar && detectAndHandle405Error(match)) {
|
|
return;
|
|
}
|
|
let existingFetcher = state.fetchers.get(key);
|
|
updateFetcherState(key, getSubmittingFetcher(submission, existingFetcher), {
|
|
flushSync: flushSync2
|
|
});
|
|
let abortController = new AbortController();
|
|
let fetchRequest = createClientSideRequest(
|
|
init.history,
|
|
path,
|
|
abortController.signal,
|
|
submission
|
|
);
|
|
if (isFogOfWar) {
|
|
let discoverResult = await discoverRoutes(
|
|
requestMatches,
|
|
path,
|
|
fetchRequest.signal
|
|
);
|
|
if (discoverResult.type === "aborted") {
|
|
return;
|
|
} else if (discoverResult.type === "error") {
|
|
setFetcherError(key, routeId, discoverResult.error, { flushSync: flushSync2 });
|
|
return;
|
|
} else if (!discoverResult.matches) {
|
|
setFetcherError(
|
|
key,
|
|
routeId,
|
|
getInternalRouterError(404, { pathname: path }),
|
|
{ flushSync: flushSync2 }
|
|
);
|
|
return;
|
|
} else {
|
|
requestMatches = discoverResult.matches;
|
|
match = getTargetMatch(requestMatches, path);
|
|
if (detectAndHandle405Error(match)) {
|
|
return;
|
|
}
|
|
}
|
|
}
|
|
fetchControllers.set(key, abortController);
|
|
let originatingLoadId = incrementingLoadId;
|
|
let actionResults = await callDataStrategy(
|
|
"action",
|
|
state,
|
|
fetchRequest,
|
|
[match],
|
|
requestMatches,
|
|
key
|
|
);
|
|
let actionResult = actionResults[match.route.id];
|
|
if (fetchRequest.signal.aborted) {
|
|
if (fetchControllers.get(key) === abortController) {
|
|
fetchControllers.delete(key);
|
|
}
|
|
return;
|
|
}
|
|
if (fetchersQueuedForDeletion.has(key)) {
|
|
if (isRedirectResult(actionResult) || isErrorResult(actionResult)) {
|
|
updateFetcherState(key, getDoneFetcher(void 0));
|
|
return;
|
|
}
|
|
} else {
|
|
if (isRedirectResult(actionResult)) {
|
|
fetchControllers.delete(key);
|
|
if (pendingNavigationLoadId > originatingLoadId) {
|
|
updateFetcherState(key, getDoneFetcher(void 0));
|
|
return;
|
|
} else {
|
|
fetchRedirectIds.add(key);
|
|
updateFetcherState(key, getLoadingFetcher(submission));
|
|
return startRedirectNavigation(fetchRequest, actionResult, false, {
|
|
fetcherSubmission: submission,
|
|
preventScrollReset
|
|
});
|
|
}
|
|
}
|
|
if (isErrorResult(actionResult)) {
|
|
setFetcherError(key, routeId, actionResult.error);
|
|
return;
|
|
}
|
|
}
|
|
let nextLocation = state.navigation.location || state.location;
|
|
let revalidationRequest = createClientSideRequest(
|
|
init.history,
|
|
nextLocation,
|
|
abortController.signal
|
|
);
|
|
let routesToUse = inFlightDataRoutes || dataRoutes;
|
|
let matches = state.navigation.state !== "idle" ? matchRoutes(routesToUse, state.navigation.location, basename) : state.matches;
|
|
invariant(matches, "Didn't find any matches after fetcher action");
|
|
let loadId = ++incrementingLoadId;
|
|
fetchReloadIds.set(key, loadId);
|
|
let loadFetcher = getLoadingFetcher(submission, actionResult.data);
|
|
state.fetchers.set(key, loadFetcher);
|
|
let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(
|
|
init.history,
|
|
state,
|
|
matches,
|
|
submission,
|
|
nextLocation,
|
|
false,
|
|
isRevalidationRequired,
|
|
cancelledFetcherLoads,
|
|
fetchersQueuedForDeletion,
|
|
fetchLoadMatches,
|
|
fetchRedirectIds,
|
|
routesToUse,
|
|
basename,
|
|
[match.route.id, actionResult]
|
|
);
|
|
revalidatingFetchers.filter((rf) => rf.key !== key).forEach((rf) => {
|
|
let staleKey = rf.key;
|
|
let existingFetcher2 = state.fetchers.get(staleKey);
|
|
let revalidatingFetcher = getLoadingFetcher(
|
|
void 0,
|
|
existingFetcher2 ? existingFetcher2.data : void 0
|
|
);
|
|
state.fetchers.set(staleKey, revalidatingFetcher);
|
|
abortFetcher(staleKey);
|
|
if (rf.controller) {
|
|
fetchControllers.set(staleKey, rf.controller);
|
|
}
|
|
});
|
|
updateState({ fetchers: new Map(state.fetchers) });
|
|
let abortPendingFetchRevalidations = () => revalidatingFetchers.forEach((rf) => abortFetcher(rf.key));
|
|
abortController.signal.addEventListener(
|
|
"abort",
|
|
abortPendingFetchRevalidations
|
|
);
|
|
let { loaderResults, fetcherResults } = await callLoadersAndMaybeResolveData(
|
|
state,
|
|
matches,
|
|
matchesToLoad,
|
|
revalidatingFetchers,
|
|
revalidationRequest
|
|
);
|
|
if (abortController.signal.aborted) {
|
|
return;
|
|
}
|
|
abortController.signal.removeEventListener(
|
|
"abort",
|
|
abortPendingFetchRevalidations
|
|
);
|
|
fetchReloadIds.delete(key);
|
|
fetchControllers.delete(key);
|
|
revalidatingFetchers.forEach((r) => fetchControllers.delete(r.key));
|
|
let redirect2 = findRedirect(loaderResults);
|
|
if (redirect2) {
|
|
return startRedirectNavigation(
|
|
revalidationRequest,
|
|
redirect2.result,
|
|
false,
|
|
{ preventScrollReset }
|
|
);
|
|
}
|
|
redirect2 = findRedirect(fetcherResults);
|
|
if (redirect2) {
|
|
fetchRedirectIds.add(redirect2.key);
|
|
return startRedirectNavigation(
|
|
revalidationRequest,
|
|
redirect2.result,
|
|
false,
|
|
{ preventScrollReset }
|
|
);
|
|
}
|
|
let { loaderData, errors } = processLoaderData(
|
|
state,
|
|
matches,
|
|
loaderResults,
|
|
void 0,
|
|
revalidatingFetchers,
|
|
fetcherResults
|
|
);
|
|
if (state.fetchers.has(key)) {
|
|
let doneFetcher = getDoneFetcher(actionResult.data);
|
|
state.fetchers.set(key, doneFetcher);
|
|
}
|
|
abortStaleFetchLoads(loadId);
|
|
if (state.navigation.state === "loading" && loadId > pendingNavigationLoadId) {
|
|
invariant(pendingAction, "Expected pending action");
|
|
pendingNavigationController && pendingNavigationController.abort();
|
|
completeNavigation(state.navigation.location, {
|
|
matches,
|
|
loaderData,
|
|
errors,
|
|
fetchers: new Map(state.fetchers)
|
|
});
|
|
} else {
|
|
updateState({
|
|
errors,
|
|
loaderData: mergeLoaderData(
|
|
state.loaderData,
|
|
loaderData,
|
|
matches,
|
|
errors
|
|
),
|
|
fetchers: new Map(state.fetchers)
|
|
});
|
|
isRevalidationRequired = false;
|
|
}
|
|
}
|
|
async function handleFetcherLoader(key, routeId, path, match, matches, isFogOfWar, flushSync2, preventScrollReset, submission) {
|
|
let existingFetcher = state.fetchers.get(key);
|
|
updateFetcherState(
|
|
key,
|
|
getLoadingFetcher(
|
|
submission,
|
|
existingFetcher ? existingFetcher.data : void 0
|
|
),
|
|
{ flushSync: flushSync2 }
|
|
);
|
|
let abortController = new AbortController();
|
|
let fetchRequest = createClientSideRequest(
|
|
init.history,
|
|
path,
|
|
abortController.signal
|
|
);
|
|
if (isFogOfWar) {
|
|
let discoverResult = await discoverRoutes(
|
|
matches,
|
|
path,
|
|
fetchRequest.signal
|
|
);
|
|
if (discoverResult.type === "aborted") {
|
|
return;
|
|
} else if (discoverResult.type === "error") {
|
|
setFetcherError(key, routeId, discoverResult.error, { flushSync: flushSync2 });
|
|
return;
|
|
} else if (!discoverResult.matches) {
|
|
setFetcherError(
|
|
key,
|
|
routeId,
|
|
getInternalRouterError(404, { pathname: path }),
|
|
{ flushSync: flushSync2 }
|
|
);
|
|
return;
|
|
} else {
|
|
matches = discoverResult.matches;
|
|
match = getTargetMatch(matches, path);
|
|
}
|
|
}
|
|
fetchControllers.set(key, abortController);
|
|
let originatingLoadId = incrementingLoadId;
|
|
let results = await callDataStrategy(
|
|
"loader",
|
|
state,
|
|
fetchRequest,
|
|
[match],
|
|
matches,
|
|
key
|
|
);
|
|
let result = results[match.route.id];
|
|
if (fetchControllers.get(key) === abortController) {
|
|
fetchControllers.delete(key);
|
|
}
|
|
if (fetchRequest.signal.aborted) {
|
|
return;
|
|
}
|
|
if (fetchersQueuedForDeletion.has(key)) {
|
|
updateFetcherState(key, getDoneFetcher(void 0));
|
|
return;
|
|
}
|
|
if (isRedirectResult(result)) {
|
|
if (pendingNavigationLoadId > originatingLoadId) {
|
|
updateFetcherState(key, getDoneFetcher(void 0));
|
|
return;
|
|
} else {
|
|
fetchRedirectIds.add(key);
|
|
await startRedirectNavigation(fetchRequest, result, false, {
|
|
preventScrollReset
|
|
});
|
|
return;
|
|
}
|
|
}
|
|
if (isErrorResult(result)) {
|
|
setFetcherError(key, routeId, result.error);
|
|
return;
|
|
}
|
|
updateFetcherState(key, getDoneFetcher(result.data));
|
|
}
|
|
async function startRedirectNavigation(request, redirect2, isNavigation, {
|
|
submission,
|
|
fetcherSubmission,
|
|
preventScrollReset,
|
|
replace: replace2
|
|
} = {}) {
|
|
if (redirect2.response.headers.has("X-Remix-Revalidate")) {
|
|
isRevalidationRequired = true;
|
|
}
|
|
let location = redirect2.response.headers.get("Location");
|
|
invariant(location, "Expected a Location header on the redirect Response");
|
|
location = normalizeRedirectLocation(
|
|
location,
|
|
new URL(request.url),
|
|
basename
|
|
);
|
|
let redirectLocation = createLocation(state.location, location, {
|
|
_isRedirect: true
|
|
});
|
|
if (isBrowser) {
|
|
let isDocumentReload = false;
|
|
if (redirect2.response.headers.has("X-Remix-Reload-Document")) {
|
|
isDocumentReload = true;
|
|
} else if (ABSOLUTE_URL_REGEX.test(location)) {
|
|
const url = init.history.createURL(location);
|
|
isDocumentReload = // Hard reload if it's an absolute URL to a new origin
|
|
url.origin !== routerWindow.location.origin || // Hard reload if it's an absolute URL that does not match our basename
|
|
stripBasename(url.pathname, basename) == null;
|
|
}
|
|
if (isDocumentReload) {
|
|
if (replace2) {
|
|
routerWindow.location.replace(location);
|
|
} else {
|
|
routerWindow.location.assign(location);
|
|
}
|
|
return;
|
|
}
|
|
}
|
|
pendingNavigationController = null;
|
|
let redirectNavigationType = replace2 === true || redirect2.response.headers.has("X-Remix-Replace") ? "REPLACE" /* Replace */ : "PUSH" /* Push */;
|
|
let { formMethod, formAction, formEncType } = state.navigation;
|
|
if (!submission && !fetcherSubmission && formMethod && formAction && formEncType) {
|
|
submission = getSubmissionFromNavigation(state.navigation);
|
|
}
|
|
let activeSubmission = submission || fetcherSubmission;
|
|
if (redirectPreserveMethodStatusCodes.has(redirect2.response.status) && activeSubmission && isMutationMethod(activeSubmission.formMethod)) {
|
|
await startNavigation(redirectNavigationType, redirectLocation, {
|
|
submission: {
|
|
...activeSubmission,
|
|
formAction: location
|
|
},
|
|
// Preserve these flags across redirects
|
|
preventScrollReset: preventScrollReset || pendingPreventScrollReset,
|
|
enableViewTransition: isNavigation ? pendingViewTransitionEnabled : void 0
|
|
});
|
|
} else {
|
|
let overrideNavigation = getLoadingNavigation(
|
|
redirectLocation,
|
|
submission
|
|
);
|
|
await startNavigation(redirectNavigationType, redirectLocation, {
|
|
overrideNavigation,
|
|
// Send fetcher submissions through for shouldRevalidate
|
|
fetcherSubmission,
|
|
// Preserve these flags across redirects
|
|
preventScrollReset: preventScrollReset || pendingPreventScrollReset,
|
|
enableViewTransition: isNavigation ? pendingViewTransitionEnabled : void 0
|
|
});
|
|
}
|
|
}
|
|
async function callDataStrategy(type, state2, request, matchesToLoad, matches, fetcherKey) {
|
|
let results;
|
|
let dataResults = {};
|
|
try {
|
|
results = await callDataStrategyImpl(
|
|
dataStrategyImpl,
|
|
type,
|
|
state2,
|
|
request,
|
|
matchesToLoad,
|
|
matches,
|
|
fetcherKey,
|
|
manifest,
|
|
mapRouteProperties2
|
|
);
|
|
} catch (e) {
|
|
matchesToLoad.forEach((m) => {
|
|
dataResults[m.route.id] = {
|
|
type: "error" /* error */,
|
|
error: e
|
|
};
|
|
});
|
|
return dataResults;
|
|
}
|
|
for (let [routeId, result] of Object.entries(results)) {
|
|
if (isRedirectDataStrategyResult(result)) {
|
|
let response = result.result;
|
|
dataResults[routeId] = {
|
|
type: "redirect" /* redirect */,
|
|
response: normalizeRelativeRoutingRedirectResponse(
|
|
response,
|
|
request,
|
|
routeId,
|
|
matches,
|
|
basename
|
|
)
|
|
};
|
|
} else {
|
|
dataResults[routeId] = await convertDataStrategyResultToDataResult(
|
|
result
|
|
);
|
|
}
|
|
}
|
|
return dataResults;
|
|
}
|
|
async function callLoadersAndMaybeResolveData(state2, matches, matchesToLoad, fetchersToLoad, request) {
|
|
let loaderResultsPromise = callDataStrategy(
|
|
"loader",
|
|
state2,
|
|
request,
|
|
matchesToLoad,
|
|
matches,
|
|
null
|
|
);
|
|
let fetcherResultsPromise = Promise.all(
|
|
fetchersToLoad.map(async (f) => {
|
|
if (f.matches && f.match && f.controller) {
|
|
let results = await callDataStrategy(
|
|
"loader",
|
|
state2,
|
|
createClientSideRequest(init.history, f.path, f.controller.signal),
|
|
[f.match],
|
|
f.matches,
|
|
f.key
|
|
);
|
|
let result = results[f.match.route.id];
|
|
return { [f.key]: result };
|
|
} else {
|
|
return Promise.resolve({
|
|
[f.key]: {
|
|
type: "error" /* error */,
|
|
error: getInternalRouterError(404, {
|
|
pathname: f.path
|
|
})
|
|
}
|
|
});
|
|
}
|
|
})
|
|
);
|
|
let loaderResults = await loaderResultsPromise;
|
|
let fetcherResults = (await fetcherResultsPromise).reduce(
|
|
(acc, r) => Object.assign(acc, r),
|
|
{}
|
|
);
|
|
return {
|
|
loaderResults,
|
|
fetcherResults
|
|
};
|
|
}
|
|
function interruptActiveLoads() {
|
|
isRevalidationRequired = true;
|
|
fetchLoadMatches.forEach((_, key) => {
|
|
if (fetchControllers.has(key)) {
|
|
cancelledFetcherLoads.add(key);
|
|
}
|
|
abortFetcher(key);
|
|
});
|
|
}
|
|
function updateFetcherState(key, fetcher, opts = {}) {
|
|
state.fetchers.set(key, fetcher);
|
|
updateState(
|
|
{ fetchers: new Map(state.fetchers) },
|
|
{ flushSync: (opts && opts.flushSync) === true }
|
|
);
|
|
}
|
|
function setFetcherError(key, routeId, error, opts = {}) {
|
|
let boundaryMatch = findNearestBoundary(state.matches, routeId);
|
|
deleteFetcher(key);
|
|
updateState(
|
|
{
|
|
errors: {
|
|
[boundaryMatch.route.id]: error
|
|
},
|
|
fetchers: new Map(state.fetchers)
|
|
},
|
|
{ flushSync: (opts && opts.flushSync) === true }
|
|
);
|
|
}
|
|
function getFetcher(key) {
|
|
activeFetchers.set(key, (activeFetchers.get(key) || 0) + 1);
|
|
if (fetchersQueuedForDeletion.has(key)) {
|
|
fetchersQueuedForDeletion.delete(key);
|
|
}
|
|
return state.fetchers.get(key) || IDLE_FETCHER;
|
|
}
|
|
function deleteFetcher(key) {
|
|
let fetcher = state.fetchers.get(key);
|
|
if (fetchControllers.has(key) && !(fetcher && fetcher.state === "loading" && fetchReloadIds.has(key))) {
|
|
abortFetcher(key);
|
|
}
|
|
fetchLoadMatches.delete(key);
|
|
fetchReloadIds.delete(key);
|
|
fetchRedirectIds.delete(key);
|
|
fetchersQueuedForDeletion.delete(key);
|
|
cancelledFetcherLoads.delete(key);
|
|
state.fetchers.delete(key);
|
|
}
|
|
function queueFetcherForDeletion(key) {
|
|
let count = (activeFetchers.get(key) || 0) - 1;
|
|
if (count <= 0) {
|
|
activeFetchers.delete(key);
|
|
fetchersQueuedForDeletion.add(key);
|
|
} else {
|
|
activeFetchers.set(key, count);
|
|
}
|
|
updateState({ fetchers: new Map(state.fetchers) });
|
|
}
|
|
function abortFetcher(key) {
|
|
let controller = fetchControllers.get(key);
|
|
if (controller) {
|
|
controller.abort();
|
|
fetchControllers.delete(key);
|
|
}
|
|
}
|
|
function markFetchersDone(keys) {
|
|
for (let key of keys) {
|
|
let fetcher = getFetcher(key);
|
|
let doneFetcher = getDoneFetcher(fetcher.data);
|
|
state.fetchers.set(key, doneFetcher);
|
|
}
|
|
}
|
|
function markFetchRedirectsDone() {
|
|
let doneKeys = [];
|
|
let updatedFetchers = false;
|
|
for (let key of fetchRedirectIds) {
|
|
let fetcher = state.fetchers.get(key);
|
|
invariant(fetcher, `Expected fetcher: ${key}`);
|
|
if (fetcher.state === "loading") {
|
|
fetchRedirectIds.delete(key);
|
|
doneKeys.push(key);
|
|
updatedFetchers = true;
|
|
}
|
|
}
|
|
markFetchersDone(doneKeys);
|
|
return updatedFetchers;
|
|
}
|
|
function abortStaleFetchLoads(landedId) {
|
|
let yeetedKeys = [];
|
|
for (let [key, id] of fetchReloadIds) {
|
|
if (id < landedId) {
|
|
let fetcher = state.fetchers.get(key);
|
|
invariant(fetcher, `Expected fetcher: ${key}`);
|
|
if (fetcher.state === "loading") {
|
|
abortFetcher(key);
|
|
fetchReloadIds.delete(key);
|
|
yeetedKeys.push(key);
|
|
}
|
|
}
|
|
}
|
|
markFetchersDone(yeetedKeys);
|
|
return yeetedKeys.length > 0;
|
|
}
|
|
function getBlocker(key, fn) {
|
|
let blocker = state.blockers.get(key) || IDLE_BLOCKER;
|
|
if (blockerFunctions.get(key) !== fn) {
|
|
blockerFunctions.set(key, fn);
|
|
}
|
|
return blocker;
|
|
}
|
|
function deleteBlocker(key) {
|
|
state.blockers.delete(key);
|
|
blockerFunctions.delete(key);
|
|
}
|
|
function updateBlocker(key, newBlocker) {
|
|
let blocker = state.blockers.get(key) || IDLE_BLOCKER;
|
|
invariant(
|
|
blocker.state === "unblocked" && newBlocker.state === "blocked" || blocker.state === "blocked" && newBlocker.state === "blocked" || blocker.state === "blocked" && newBlocker.state === "proceeding" || blocker.state === "blocked" && newBlocker.state === "unblocked" || blocker.state === "proceeding" && newBlocker.state === "unblocked",
|
|
`Invalid blocker state transition: ${blocker.state} -> ${newBlocker.state}`
|
|
);
|
|
let blockers = new Map(state.blockers);
|
|
blockers.set(key, newBlocker);
|
|
updateState({ blockers });
|
|
}
|
|
function shouldBlockNavigation({
|
|
currentLocation,
|
|
nextLocation,
|
|
historyAction
|
|
}) {
|
|
if (blockerFunctions.size === 0) {
|
|
return;
|
|
}
|
|
if (blockerFunctions.size > 1) {
|
|
warning(false, "A router only supports one blocker at a time");
|
|
}
|
|
let entries = Array.from(blockerFunctions.entries());
|
|
let [blockerKey, blockerFunction] = entries[entries.length - 1];
|
|
let blocker = state.blockers.get(blockerKey);
|
|
if (blocker && blocker.state === "proceeding") {
|
|
return;
|
|
}
|
|
if (blockerFunction({ currentLocation, nextLocation, historyAction })) {
|
|
return blockerKey;
|
|
}
|
|
}
|
|
function handleNavigational404(pathname) {
|
|
let error = getInternalRouterError(404, { pathname });
|
|
let routesToUse = inFlightDataRoutes || dataRoutes;
|
|
let { matches, route } = getShortCircuitMatches(routesToUse);
|
|
return { notFoundMatches: matches, route, error };
|
|
}
|
|
function enableScrollRestoration(positions, getPosition, getKey) {
|
|
savedScrollPositions = positions;
|
|
getScrollPosition = getPosition;
|
|
getScrollRestorationKey = getKey || null;
|
|
if (!initialScrollRestored && state.navigation === IDLE_NAVIGATION) {
|
|
initialScrollRestored = true;
|
|
let y = getSavedScrollPosition(state.location, state.matches);
|
|
if (y != null) {
|
|
updateState({ restoreScrollPosition: y });
|
|
}
|
|
}
|
|
return () => {
|
|
savedScrollPositions = null;
|
|
getScrollPosition = null;
|
|
getScrollRestorationKey = null;
|
|
};
|
|
}
|
|
function getScrollKey(location, matches) {
|
|
if (getScrollRestorationKey) {
|
|
let key = getScrollRestorationKey(
|
|
location,
|
|
matches.map((m) => convertRouteMatchToUiMatch(m, state.loaderData))
|
|
);
|
|
return key || location.key;
|
|
}
|
|
return location.key;
|
|
}
|
|
function saveScrollPosition(location, matches) {
|
|
if (savedScrollPositions && getScrollPosition) {
|
|
let key = getScrollKey(location, matches);
|
|
savedScrollPositions[key] = getScrollPosition();
|
|
}
|
|
}
|
|
function getSavedScrollPosition(location, matches) {
|
|
if (savedScrollPositions) {
|
|
let key = getScrollKey(location, matches);
|
|
let y = savedScrollPositions[key];
|
|
if (typeof y === "number") {
|
|
return y;
|
|
}
|
|
}
|
|
return null;
|
|
}
|
|
function checkFogOfWar(matches, routesToUse, pathname) {
|
|
if (patchRoutesOnNavigationImpl) {
|
|
if (!matches) {
|
|
let fogMatches = matchRoutesImpl(
|
|
routesToUse,
|
|
pathname,
|
|
basename,
|
|
true
|
|
);
|
|
return { active: true, matches: fogMatches || [] };
|
|
} else {
|
|
if (Object.keys(matches[0].params).length > 0) {
|
|
let partialMatches = matchRoutesImpl(
|
|
routesToUse,
|
|
pathname,
|
|
basename,
|
|
true
|
|
);
|
|
return { active: true, matches: partialMatches };
|
|
}
|
|
}
|
|
}
|
|
return { active: false, matches: null };
|
|
}
|
|
async function discoverRoutes(matches, pathname, signal) {
|
|
if (!patchRoutesOnNavigationImpl) {
|
|
return { type: "success", matches };
|
|
}
|
|
let partialMatches = matches;
|
|
while (true) {
|
|
let isNonHMR = inFlightDataRoutes == null;
|
|
let routesToUse = inFlightDataRoutes || dataRoutes;
|
|
let localManifest = manifest;
|
|
try {
|
|
await patchRoutesOnNavigationImpl({
|
|
path: pathname,
|
|
matches: partialMatches,
|
|
patch: (routeId, children) => {
|
|
if (signal.aborted) return;
|
|
patchRoutesImpl(
|
|
routeId,
|
|
children,
|
|
routesToUse,
|
|
localManifest,
|
|
mapRouteProperties2
|
|
);
|
|
}
|
|
});
|
|
} catch (e) {
|
|
return { type: "error", error: e, partialMatches };
|
|
} finally {
|
|
if (isNonHMR && !signal.aborted) {
|
|
dataRoutes = [...dataRoutes];
|
|
}
|
|
}
|
|
if (signal.aborted) {
|
|
return { type: "aborted" };
|
|
}
|
|
let newMatches = matchRoutes(routesToUse, pathname, basename);
|
|
if (newMatches) {
|
|
return { type: "success", matches: newMatches };
|
|
}
|
|
let newPartialMatches = matchRoutesImpl(
|
|
routesToUse,
|
|
pathname,
|
|
basename,
|
|
true
|
|
);
|
|
if (!newPartialMatches || partialMatches.length === newPartialMatches.length && partialMatches.every(
|
|
(m, i) => m.route.id === newPartialMatches[i].route.id
|
|
)) {
|
|
return { type: "success", matches: null };
|
|
}
|
|
partialMatches = newPartialMatches;
|
|
}
|
|
}
|
|
function _internalSetRoutes(newRoutes) {
|
|
manifest = {};
|
|
inFlightDataRoutes = convertRoutesToDataRoutes(
|
|
newRoutes,
|
|
mapRouteProperties2,
|
|
void 0,
|
|
manifest
|
|
);
|
|
}
|
|
function patchRoutes(routeId, children) {
|
|
let isNonHMR = inFlightDataRoutes == null;
|
|
let routesToUse = inFlightDataRoutes || dataRoutes;
|
|
patchRoutesImpl(
|
|
routeId,
|
|
children,
|
|
routesToUse,
|
|
manifest,
|
|
mapRouteProperties2
|
|
);
|
|
if (isNonHMR) {
|
|
dataRoutes = [...dataRoutes];
|
|
updateState({});
|
|
}
|
|
}
|
|
router2 = {
|
|
get basename() {
|
|
return basename;
|
|
},
|
|
get future() {
|
|
return future;
|
|
},
|
|
get state() {
|
|
return state;
|
|
},
|
|
get routes() {
|
|
return dataRoutes;
|
|
},
|
|
get window() {
|
|
return routerWindow;
|
|
},
|
|
initialize,
|
|
subscribe,
|
|
enableScrollRestoration,
|
|
navigate,
|
|
fetch: fetch2,
|
|
revalidate,
|
|
// Passthrough to history-aware createHref used by useHref so we get proper
|
|
// hash-aware URLs in DOM paths
|
|
createHref: (to) => init.history.createHref(to),
|
|
encodeLocation: (to) => init.history.encodeLocation(to),
|
|
getFetcher,
|
|
deleteFetcher: queueFetcherForDeletion,
|
|
dispose,
|
|
getBlocker,
|
|
deleteBlocker,
|
|
patchRoutes,
|
|
_internalFetchControllers: fetchControllers,
|
|
// TODO: Remove setRoutes, it's temporary to avoid dealing with
|
|
// updating the tree while validating the update algorithm.
|
|
_internalSetRoutes
|
|
};
|
|
return router2;
|
|
}
|
|
function isSubmissionNavigation(opts) {
|
|
return opts != null && ("formData" in opts && opts.formData != null || "body" in opts && opts.body !== void 0);
|
|
}
|
|
function normalizeTo(location, matches, basename, to, fromRouteId, relative) {
|
|
let contextualMatches;
|
|
let activeRouteMatch;
|
|
if (fromRouteId) {
|
|
contextualMatches = [];
|
|
for (let match of matches) {
|
|
contextualMatches.push(match);
|
|
if (match.route.id === fromRouteId) {
|
|
activeRouteMatch = match;
|
|
break;
|
|
}
|
|
}
|
|
} else {
|
|
contextualMatches = matches;
|
|
activeRouteMatch = matches[matches.length - 1];
|
|
}
|
|
let path = resolveTo(
|
|
to ? to : ".",
|
|
getResolveToMatches(contextualMatches),
|
|
stripBasename(location.pathname, basename) || location.pathname,
|
|
relative === "path"
|
|
);
|
|
if (to == null) {
|
|
path.search = location.search;
|
|
path.hash = location.hash;
|
|
}
|
|
if ((to == null || to === "" || to === ".") && activeRouteMatch) {
|
|
let nakedIndex = hasNakedIndexQuery(path.search);
|
|
if (activeRouteMatch.route.index && !nakedIndex) {
|
|
path.search = path.search ? path.search.replace(/^\?/, "?index&") : "?index";
|
|
} else if (!activeRouteMatch.route.index && nakedIndex) {
|
|
let params = new URLSearchParams(path.search);
|
|
let indexValues = params.getAll("index");
|
|
params.delete("index");
|
|
indexValues.filter((v) => v).forEach((v) => params.append("index", v));
|
|
let qs = params.toString();
|
|
path.search = qs ? `?${qs}` : "";
|
|
}
|
|
}
|
|
if (basename !== "/") {
|
|
path.pathname = path.pathname === "/" ? basename : joinPaths([basename, path.pathname]);
|
|
}
|
|
return createPath(path);
|
|
}
|
|
function normalizeNavigateOptions(isFetcher, path, opts) {
|
|
if (!opts || !isSubmissionNavigation(opts)) {
|
|
return { path };
|
|
}
|
|
if (opts.formMethod && !isValidMethod(opts.formMethod)) {
|
|
return {
|
|
path,
|
|
error: getInternalRouterError(405, { method: opts.formMethod })
|
|
};
|
|
}
|
|
let getInvalidBodyError = () => ({
|
|
path,
|
|
error: getInternalRouterError(400, { type: "invalid-body" })
|
|
});
|
|
let rawFormMethod = opts.formMethod || "get";
|
|
let formMethod = rawFormMethod.toUpperCase();
|
|
let formAction = stripHashFromPath(path);
|
|
if (opts.body !== void 0) {
|
|
if (opts.formEncType === "text/plain") {
|
|
if (!isMutationMethod(formMethod)) {
|
|
return getInvalidBodyError();
|
|
}
|
|
let text = typeof opts.body === "string" ? opts.body : opts.body instanceof FormData || opts.body instanceof URLSearchParams ? (
|
|
// https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#plain-text-form-data
|
|
Array.from(opts.body.entries()).reduce(
|
|
(acc, [name, value]) => `${acc}${name}=${value}
|
|
`,
|
|
""
|
|
)
|
|
) : String(opts.body);
|
|
return {
|
|
path,
|
|
submission: {
|
|
formMethod,
|
|
formAction,
|
|
formEncType: opts.formEncType,
|
|
formData: void 0,
|
|
json: void 0,
|
|
text
|
|
}
|
|
};
|
|
} else if (opts.formEncType === "application/json") {
|
|
if (!isMutationMethod(formMethod)) {
|
|
return getInvalidBodyError();
|
|
}
|
|
try {
|
|
let json = typeof opts.body === "string" ? JSON.parse(opts.body) : opts.body;
|
|
return {
|
|
path,
|
|
submission: {
|
|
formMethod,
|
|
formAction,
|
|
formEncType: opts.formEncType,
|
|
formData: void 0,
|
|
json,
|
|
text: void 0
|
|
}
|
|
};
|
|
} catch (e) {
|
|
return getInvalidBodyError();
|
|
}
|
|
}
|
|
}
|
|
invariant(
|
|
typeof FormData === "function",
|
|
"FormData is not available in this environment"
|
|
);
|
|
let searchParams;
|
|
let formData;
|
|
if (opts.formData) {
|
|
searchParams = convertFormDataToSearchParams(opts.formData);
|
|
formData = opts.formData;
|
|
} else if (opts.body instanceof FormData) {
|
|
searchParams = convertFormDataToSearchParams(opts.body);
|
|
formData = opts.body;
|
|
} else if (opts.body instanceof URLSearchParams) {
|
|
searchParams = opts.body;
|
|
formData = convertSearchParamsToFormData(searchParams);
|
|
} else if (opts.body == null) {
|
|
searchParams = new URLSearchParams();
|
|
formData = new FormData();
|
|
} else {
|
|
try {
|
|
searchParams = new URLSearchParams(opts.body);
|
|
formData = convertSearchParamsToFormData(searchParams);
|
|
} catch (e) {
|
|
return getInvalidBodyError();
|
|
}
|
|
}
|
|
let submission = {
|
|
formMethod,
|
|
formAction,
|
|
formEncType: opts && opts.formEncType || "application/x-www-form-urlencoded",
|
|
formData,
|
|
json: void 0,
|
|
text: void 0
|
|
};
|
|
if (isMutationMethod(submission.formMethod)) {
|
|
return { path, submission };
|
|
}
|
|
let parsedPath = parsePath(path);
|
|
if (isFetcher && parsedPath.search && hasNakedIndexQuery(parsedPath.search)) {
|
|
searchParams.append("index", "");
|
|
}
|
|
parsedPath.search = `?${searchParams}`;
|
|
return { path: createPath(parsedPath), submission };
|
|
}
|
|
function getLoaderMatchesUntilBoundary(matches, boundaryId, includeBoundary = false) {
|
|
let index = matches.findIndex((m) => m.route.id === boundaryId);
|
|
if (index >= 0) {
|
|
return matches.slice(0, includeBoundary ? index + 1 : index);
|
|
}
|
|
return matches;
|
|
}
|
|
function getMatchesToLoad(history, state, matches, submission, location, initialHydration, isRevalidationRequired, cancelledFetcherLoads, fetchersQueuedForDeletion, fetchLoadMatches, fetchRedirectIds, routesToUse, basename, pendingActionResult) {
|
|
let actionResult = pendingActionResult ? isErrorResult(pendingActionResult[1]) ? pendingActionResult[1].error : pendingActionResult[1].data : void 0;
|
|
let currentUrl = history.createURL(state.location);
|
|
let nextUrl = history.createURL(location);
|
|
let boundaryMatches = matches;
|
|
if (initialHydration && state.errors) {
|
|
boundaryMatches = getLoaderMatchesUntilBoundary(
|
|
matches,
|
|
Object.keys(state.errors)[0],
|
|
true
|
|
);
|
|
} else if (pendingActionResult && isErrorResult(pendingActionResult[1])) {
|
|
boundaryMatches = getLoaderMatchesUntilBoundary(
|
|
matches,
|
|
pendingActionResult[0]
|
|
);
|
|
}
|
|
let actionStatus = pendingActionResult ? pendingActionResult[1].statusCode : void 0;
|
|
let shouldSkipRevalidation = actionStatus && actionStatus >= 400;
|
|
let navigationMatches = boundaryMatches.filter((match, index) => {
|
|
let { route } = match;
|
|
if (route.lazy) {
|
|
return true;
|
|
}
|
|
if (route.loader == null) {
|
|
return false;
|
|
}
|
|
if (initialHydration) {
|
|
return shouldLoadRouteOnHydration(route, state.loaderData, state.errors);
|
|
}
|
|
if (isNewLoader(state.loaderData, state.matches[index], match)) {
|
|
return true;
|
|
}
|
|
let currentRouteMatch = state.matches[index];
|
|
let nextRouteMatch = match;
|
|
return shouldRevalidateLoader(match, {
|
|
currentUrl,
|
|
currentParams: currentRouteMatch.params,
|
|
nextUrl,
|
|
nextParams: nextRouteMatch.params,
|
|
...submission,
|
|
actionResult,
|
|
actionStatus,
|
|
defaultShouldRevalidate: shouldSkipRevalidation ? false : (
|
|
// Forced revalidation due to submission, useRevalidator, or X-Remix-Revalidate
|
|
isRevalidationRequired || currentUrl.pathname + currentUrl.search === nextUrl.pathname + nextUrl.search || // Search params affect all loaders
|
|
currentUrl.search !== nextUrl.search || isNewRouteInstance(currentRouteMatch, nextRouteMatch)
|
|
)
|
|
});
|
|
});
|
|
let revalidatingFetchers = [];
|
|
fetchLoadMatches.forEach((f, key) => {
|
|
if (initialHydration || !matches.some((m) => m.route.id === f.routeId) || fetchersQueuedForDeletion.has(key)) {
|
|
return;
|
|
}
|
|
let fetcherMatches = matchRoutes(routesToUse, f.path, basename);
|
|
if (!fetcherMatches) {
|
|
revalidatingFetchers.push({
|
|
key,
|
|
routeId: f.routeId,
|
|
path: f.path,
|
|
matches: null,
|
|
match: null,
|
|
controller: null
|
|
});
|
|
return;
|
|
}
|
|
let fetcher = state.fetchers.get(key);
|
|
let fetcherMatch = getTargetMatch(fetcherMatches, f.path);
|
|
let shouldRevalidate = false;
|
|
if (fetchRedirectIds.has(key)) {
|
|
shouldRevalidate = false;
|
|
} else if (cancelledFetcherLoads.has(key)) {
|
|
cancelledFetcherLoads.delete(key);
|
|
shouldRevalidate = true;
|
|
} else if (fetcher && fetcher.state !== "idle" && fetcher.data === void 0) {
|
|
shouldRevalidate = isRevalidationRequired;
|
|
} else {
|
|
shouldRevalidate = shouldRevalidateLoader(fetcherMatch, {
|
|
currentUrl,
|
|
currentParams: state.matches[state.matches.length - 1].params,
|
|
nextUrl,
|
|
nextParams: matches[matches.length - 1].params,
|
|
...submission,
|
|
actionResult,
|
|
actionStatus,
|
|
defaultShouldRevalidate: shouldSkipRevalidation ? false : isRevalidationRequired
|
|
});
|
|
}
|
|
if (shouldRevalidate) {
|
|
revalidatingFetchers.push({
|
|
key,
|
|
routeId: f.routeId,
|
|
path: f.path,
|
|
matches: fetcherMatches,
|
|
match: fetcherMatch,
|
|
controller: new AbortController()
|
|
});
|
|
}
|
|
});
|
|
return [navigationMatches, revalidatingFetchers];
|
|
}
|
|
function shouldLoadRouteOnHydration(route, loaderData, errors) {
|
|
if (route.lazy) {
|
|
return true;
|
|
}
|
|
if (!route.loader) {
|
|
return false;
|
|
}
|
|
let hasData = loaderData != null && loaderData[route.id] !== void 0;
|
|
let hasError = errors != null && errors[route.id] !== void 0;
|
|
if (!hasData && hasError) {
|
|
return false;
|
|
}
|
|
if (typeof route.loader === "function" && route.loader.hydrate === true) {
|
|
return true;
|
|
}
|
|
return !hasData && !hasError;
|
|
}
|
|
function isNewLoader(currentLoaderData, currentMatch, match) {
|
|
let isNew = (
|
|
// [a] -> [a, b]
|
|
!currentMatch || // [a, b] -> [a, c]
|
|
match.route.id !== currentMatch.route.id
|
|
);
|
|
let isMissingData = !currentLoaderData.hasOwnProperty(match.route.id);
|
|
return isNew || isMissingData;
|
|
}
|
|
function isNewRouteInstance(currentMatch, match) {
|
|
let currentPath = currentMatch.route.path;
|
|
return (
|
|
// param change for this match, /users/123 -> /users/456
|
|
currentMatch.pathname !== match.pathname || // splat param changed, which is not present in match.path
|
|
// e.g. /files/images/avatar.jpg -> files/finances.xls
|
|
currentPath != null && currentPath.endsWith("*") && currentMatch.params["*"] !== match.params["*"]
|
|
);
|
|
}
|
|
function shouldRevalidateLoader(loaderMatch, arg) {
|
|
if (loaderMatch.route.shouldRevalidate) {
|
|
let routeChoice = loaderMatch.route.shouldRevalidate(arg);
|
|
if (typeof routeChoice === "boolean") {
|
|
return routeChoice;
|
|
}
|
|
}
|
|
return arg.defaultShouldRevalidate;
|
|
}
|
|
function patchRoutesImpl(routeId, children, routesToUse, manifest, mapRouteProperties2) {
|
|
let childrenToPatch;
|
|
if (routeId) {
|
|
let route = manifest[routeId];
|
|
invariant(
|
|
route,
|
|
`No route found to patch children into: routeId = ${routeId}`
|
|
);
|
|
if (!route.children) {
|
|
route.children = [];
|
|
}
|
|
childrenToPatch = route.children;
|
|
} else {
|
|
childrenToPatch = routesToUse;
|
|
}
|
|
let uniqueChildren = children.filter(
|
|
(newRoute) => !childrenToPatch.some(
|
|
(existingRoute) => isSameRoute(newRoute, existingRoute)
|
|
)
|
|
);
|
|
let newRoutes = convertRoutesToDataRoutes(
|
|
uniqueChildren,
|
|
mapRouteProperties2,
|
|
[routeId || "_", "patch", String(childrenToPatch?.length || "0")],
|
|
manifest
|
|
);
|
|
childrenToPatch.push(...newRoutes);
|
|
}
|
|
function isSameRoute(newRoute, existingRoute) {
|
|
if ("id" in newRoute && "id" in existingRoute && newRoute.id === existingRoute.id) {
|
|
return true;
|
|
}
|
|
if (!(newRoute.index === existingRoute.index && newRoute.path === existingRoute.path && newRoute.caseSensitive === existingRoute.caseSensitive)) {
|
|
return false;
|
|
}
|
|
if ((!newRoute.children || newRoute.children.length === 0) && (!existingRoute.children || existingRoute.children.length === 0)) {
|
|
return true;
|
|
}
|
|
return newRoute.children.every(
|
|
(aChild, i) => existingRoute.children?.some((bChild) => isSameRoute(aChild, bChild))
|
|
);
|
|
}
|
|
async function loadLazyRouteModule(route, mapRouteProperties2, manifest) {
|
|
if (!route.lazy) {
|
|
return;
|
|
}
|
|
let lazyRoute = await route.lazy();
|
|
if (!route.lazy) {
|
|
return;
|
|
}
|
|
let routeToUpdate = manifest[route.id];
|
|
invariant(routeToUpdate, "No route found in manifest");
|
|
let routeUpdates = {};
|
|
for (let lazyRouteProperty in lazyRoute) {
|
|
let staticRouteValue = routeToUpdate[lazyRouteProperty];
|
|
let isPropertyStaticallyDefined = staticRouteValue !== void 0 && // This property isn't static since it should always be updated based
|
|
// on the route updates
|
|
lazyRouteProperty !== "hasErrorBoundary";
|
|
warning(
|
|
!isPropertyStaticallyDefined,
|
|
`Route "${routeToUpdate.id}" has a static property "${lazyRouteProperty}" defined but its lazy function is also returning a value for this property. The lazy route property "${lazyRouteProperty}" will be ignored.`
|
|
);
|
|
if (!isPropertyStaticallyDefined && !immutableRouteKeys.has(lazyRouteProperty)) {
|
|
routeUpdates[lazyRouteProperty] = lazyRoute[lazyRouteProperty];
|
|
}
|
|
}
|
|
Object.assign(routeToUpdate, routeUpdates);
|
|
Object.assign(routeToUpdate, {
|
|
// To keep things framework agnostic, we use the provided `mapRouteProperties`
|
|
// function to set the framework-aware properties (`element`/`hasErrorBoundary`)
|
|
// since the logic will differ between frameworks.
|
|
...mapRouteProperties2(routeToUpdate),
|
|
lazy: void 0
|
|
});
|
|
}
|
|
async function defaultDataStrategy({
|
|
matches
|
|
}) {
|
|
let matchesToLoad = matches.filter((m) => m.shouldLoad);
|
|
let results = await Promise.all(matchesToLoad.map((m) => m.resolve()));
|
|
return results.reduce(
|
|
(acc, result, i) => Object.assign(acc, { [matchesToLoad[i].route.id]: result }),
|
|
{}
|
|
);
|
|
}
|
|
async function callDataStrategyImpl(dataStrategyImpl, type, state, request, matchesToLoad, matches, fetcherKey, manifest, mapRouteProperties2, requestContext) {
|
|
let loadRouteDefinitionsPromises = matches.map(
|
|
(m) => m.route.lazy ? loadLazyRouteModule(m.route, mapRouteProperties2, manifest) : void 0
|
|
);
|
|
let dsMatches = matches.map((match, i) => {
|
|
let loadRoutePromise = loadRouteDefinitionsPromises[i];
|
|
let shouldLoad = matchesToLoad.some((m) => m.route.id === match.route.id);
|
|
let resolve = async (handlerOverride) => {
|
|
if (handlerOverride && request.method === "GET" && (match.route.lazy || match.route.loader)) {
|
|
shouldLoad = true;
|
|
}
|
|
return shouldLoad ? callLoaderOrAction(
|
|
type,
|
|
request,
|
|
match,
|
|
loadRoutePromise,
|
|
handlerOverride,
|
|
requestContext
|
|
) : Promise.resolve({ type: "data" /* data */, result: void 0 });
|
|
};
|
|
return {
|
|
...match,
|
|
shouldLoad,
|
|
resolve
|
|
};
|
|
});
|
|
let results = await dataStrategyImpl({
|
|
matches: dsMatches,
|
|
request,
|
|
params: matches[0].params,
|
|
fetcherKey,
|
|
context: requestContext
|
|
});
|
|
try {
|
|
await Promise.all(loadRouteDefinitionsPromises);
|
|
} catch (e) {
|
|
}
|
|
return results;
|
|
}
|
|
async function callLoaderOrAction(type, request, match, loadRoutePromise, handlerOverride, staticContext) {
|
|
let result;
|
|
let onReject;
|
|
let runHandler = (handler) => {
|
|
let reject;
|
|
let abortPromise = new Promise((_, r) => reject = r);
|
|
onReject = () => reject();
|
|
request.signal.addEventListener("abort", onReject);
|
|
let actualHandler = (ctx) => {
|
|
if (typeof handler !== "function") {
|
|
return Promise.reject(
|
|
new Error(
|
|
`You cannot call the handler for a route which defines a boolean "${type}" [routeId: ${match.route.id}]`
|
|
)
|
|
);
|
|
}
|
|
return handler(
|
|
{
|
|
request,
|
|
params: match.params,
|
|
context: staticContext
|
|
},
|
|
...ctx !== void 0 ? [ctx] : []
|
|
);
|
|
};
|
|
let handlerPromise = (async () => {
|
|
try {
|
|
let val = await (handlerOverride ? handlerOverride((ctx) => actualHandler(ctx)) : actualHandler());
|
|
return { type: "data", result: val };
|
|
} catch (e) {
|
|
return { type: "error", result: e };
|
|
}
|
|
})();
|
|
return Promise.race([handlerPromise, abortPromise]);
|
|
};
|
|
try {
|
|
let handler = match.route[type];
|
|
if (loadRoutePromise) {
|
|
if (handler) {
|
|
let handlerError;
|
|
let [value] = await Promise.all([
|
|
// If the handler throws, don't let it immediately bubble out,
|
|
// since we need to let the lazy() execution finish so we know if this
|
|
// route has a boundary that can handle the error
|
|
runHandler(handler).catch((e) => {
|
|
handlerError = e;
|
|
}),
|
|
loadRoutePromise
|
|
]);
|
|
if (handlerError !== void 0) {
|
|
throw handlerError;
|
|
}
|
|
result = value;
|
|
} else {
|
|
await loadRoutePromise;
|
|
handler = match.route[type];
|
|
if (handler) {
|
|
result = await runHandler(handler);
|
|
} else if (type === "action") {
|
|
let url = new URL(request.url);
|
|
let pathname = url.pathname + url.search;
|
|
throw getInternalRouterError(405, {
|
|
method: request.method,
|
|
pathname,
|
|
routeId: match.route.id
|
|
});
|
|
} else {
|
|
return { type: "data" /* data */, result: void 0 };
|
|
}
|
|
}
|
|
} else if (!handler) {
|
|
let url = new URL(request.url);
|
|
let pathname = url.pathname + url.search;
|
|
throw getInternalRouterError(404, {
|
|
pathname
|
|
});
|
|
} else {
|
|
result = await runHandler(handler);
|
|
}
|
|
} catch (e) {
|
|
return { type: "error" /* error */, result: e };
|
|
} finally {
|
|
if (onReject) {
|
|
request.signal.removeEventListener("abort", onReject);
|
|
}
|
|
}
|
|
return result;
|
|
}
|
|
async function convertDataStrategyResultToDataResult(dataStrategyResult) {
|
|
let { result, type } = dataStrategyResult;
|
|
if (isResponse(result)) {
|
|
let data2;
|
|
try {
|
|
let contentType = result.headers.get("Content-Type");
|
|
if (contentType && /\bapplication\/json\b/.test(contentType)) {
|
|
if (result.body == null) {
|
|
data2 = null;
|
|
} else {
|
|
data2 = await result.json();
|
|
}
|
|
} else {
|
|
data2 = await result.text();
|
|
}
|
|
} catch (e) {
|
|
return { type: "error" /* error */, error: e };
|
|
}
|
|
if (type === "error" /* error */) {
|
|
return {
|
|
type: "error" /* error */,
|
|
error: new ErrorResponseImpl(result.status, result.statusText, data2),
|
|
statusCode: result.status,
|
|
headers: result.headers
|
|
};
|
|
}
|
|
return {
|
|
type: "data" /* data */,
|
|
data: data2,
|
|
statusCode: result.status,
|
|
headers: result.headers
|
|
};
|
|
}
|
|
if (type === "error" /* error */) {
|
|
if (isDataWithResponseInit(result)) {
|
|
if (result.data instanceof Error) {
|
|
return {
|
|
type: "error" /* error */,
|
|
error: result.data,
|
|
statusCode: result.init?.status,
|
|
headers: result.init?.headers ? new Headers(result.init.headers) : void 0
|
|
};
|
|
}
|
|
return {
|
|
type: "error" /* error */,
|
|
error: new ErrorResponseImpl(
|
|
result.init?.status || 500,
|
|
void 0,
|
|
result.data
|
|
),
|
|
statusCode: isRouteErrorResponse(result) ? result.status : void 0,
|
|
headers: result.init?.headers ? new Headers(result.init.headers) : void 0
|
|
};
|
|
}
|
|
return {
|
|
type: "error" /* error */,
|
|
error: result,
|
|
statusCode: isRouteErrorResponse(result) ? result.status : void 0
|
|
};
|
|
}
|
|
if (isDataWithResponseInit(result)) {
|
|
return {
|
|
type: "data" /* data */,
|
|
data: result.data,
|
|
statusCode: result.init?.status,
|
|
headers: result.init?.headers ? new Headers(result.init.headers) : void 0
|
|
};
|
|
}
|
|
return { type: "data" /* data */, data: result };
|
|
}
|
|
function normalizeRelativeRoutingRedirectResponse(response, request, routeId, matches, basename) {
|
|
let location = response.headers.get("Location");
|
|
invariant(
|
|
location,
|
|
"Redirects returned/thrown from loaders/actions must have a Location header"
|
|
);
|
|
if (!ABSOLUTE_URL_REGEX.test(location)) {
|
|
let trimmedMatches = matches.slice(
|
|
0,
|
|
matches.findIndex((m) => m.route.id === routeId) + 1
|
|
);
|
|
location = normalizeTo(
|
|
new URL(request.url),
|
|
trimmedMatches,
|
|
basename,
|
|
location
|
|
);
|
|
response.headers.set("Location", location);
|
|
}
|
|
return response;
|
|
}
|
|
function normalizeRedirectLocation(location, currentUrl, basename) {
|
|
if (ABSOLUTE_URL_REGEX.test(location)) {
|
|
let normalizedLocation = location;
|
|
let url = normalizedLocation.startsWith("//") ? new URL(currentUrl.protocol + normalizedLocation) : new URL(normalizedLocation);
|
|
let isSameBasename = stripBasename(url.pathname, basename) != null;
|
|
if (url.origin === currentUrl.origin && isSameBasename) {
|
|
return url.pathname + url.search + url.hash;
|
|
}
|
|
}
|
|
return location;
|
|
}
|
|
function createClientSideRequest(history, location, signal, submission) {
|
|
let url = history.createURL(stripHashFromPath(location)).toString();
|
|
let init = { signal };
|
|
if (submission && isMutationMethod(submission.formMethod)) {
|
|
let { formMethod, formEncType } = submission;
|
|
init.method = formMethod.toUpperCase();
|
|
if (formEncType === "application/json") {
|
|
init.headers = new Headers({ "Content-Type": formEncType });
|
|
init.body = JSON.stringify(submission.json);
|
|
} else if (formEncType === "text/plain") {
|
|
init.body = submission.text;
|
|
} else if (formEncType === "application/x-www-form-urlencoded" && submission.formData) {
|
|
init.body = convertFormDataToSearchParams(submission.formData);
|
|
} else {
|
|
init.body = submission.formData;
|
|
}
|
|
}
|
|
return new Request(url, init);
|
|
}
|
|
function convertFormDataToSearchParams(formData) {
|
|
let searchParams = new URLSearchParams();
|
|
for (let [key, value] of formData.entries()) {
|
|
searchParams.append(key, typeof value === "string" ? value : value.name);
|
|
}
|
|
return searchParams;
|
|
}
|
|
function convertSearchParamsToFormData(searchParams) {
|
|
let formData = new FormData();
|
|
for (let [key, value] of searchParams.entries()) {
|
|
formData.append(key, value);
|
|
}
|
|
return formData;
|
|
}
|
|
function processRouteLoaderData(matches, results, pendingActionResult, isStaticHandler = false, skipLoaderErrorBubbling = false) {
|
|
let loaderData = {};
|
|
let errors = null;
|
|
let statusCode;
|
|
let foundError = false;
|
|
let loaderHeaders = {};
|
|
let pendingError = pendingActionResult && isErrorResult(pendingActionResult[1]) ? pendingActionResult[1].error : void 0;
|
|
matches.forEach((match) => {
|
|
if (!(match.route.id in results)) {
|
|
return;
|
|
}
|
|
let id = match.route.id;
|
|
let result = results[id];
|
|
invariant(
|
|
!isRedirectResult(result),
|
|
"Cannot handle redirect results in processLoaderData"
|
|
);
|
|
if (isErrorResult(result)) {
|
|
let error = result.error;
|
|
if (pendingError !== void 0) {
|
|
error = pendingError;
|
|
pendingError = void 0;
|
|
}
|
|
errors = errors || {};
|
|
if (skipLoaderErrorBubbling) {
|
|
errors[id] = error;
|
|
} else {
|
|
let boundaryMatch = findNearestBoundary(matches, id);
|
|
if (errors[boundaryMatch.route.id] == null) {
|
|
errors[boundaryMatch.route.id] = error;
|
|
}
|
|
}
|
|
if (!isStaticHandler) {
|
|
loaderData[id] = ResetLoaderDataSymbol;
|
|
}
|
|
if (!foundError) {
|
|
foundError = true;
|
|
statusCode = isRouteErrorResponse(result.error) ? result.error.status : 500;
|
|
}
|
|
if (result.headers) {
|
|
loaderHeaders[id] = result.headers;
|
|
}
|
|
} else {
|
|
loaderData[id] = result.data;
|
|
if (result.statusCode && result.statusCode !== 200 && !foundError) {
|
|
statusCode = result.statusCode;
|
|
}
|
|
if (result.headers) {
|
|
loaderHeaders[id] = result.headers;
|
|
}
|
|
}
|
|
});
|
|
if (pendingError !== void 0 && pendingActionResult) {
|
|
errors = { [pendingActionResult[0]]: pendingError };
|
|
loaderData[pendingActionResult[0]] = void 0;
|
|
}
|
|
return {
|
|
loaderData,
|
|
errors,
|
|
statusCode: statusCode || 200,
|
|
loaderHeaders
|
|
};
|
|
}
|
|
function processLoaderData(state, matches, results, pendingActionResult, revalidatingFetchers, fetcherResults) {
|
|
let { loaderData, errors } = processRouteLoaderData(
|
|
matches,
|
|
results,
|
|
pendingActionResult
|
|
);
|
|
revalidatingFetchers.forEach((rf) => {
|
|
let { key, match, controller } = rf;
|
|
let result = fetcherResults[key];
|
|
invariant(result, "Did not find corresponding fetcher result");
|
|
if (controller && controller.signal.aborted) {
|
|
return;
|
|
} else if (isErrorResult(result)) {
|
|
let boundaryMatch = findNearestBoundary(state.matches, match?.route.id);
|
|
if (!(errors && errors[boundaryMatch.route.id])) {
|
|
errors = {
|
|
...errors,
|
|
[boundaryMatch.route.id]: result.error
|
|
};
|
|
}
|
|
state.fetchers.delete(key);
|
|
} else if (isRedirectResult(result)) {
|
|
invariant(false, "Unhandled fetcher revalidation redirect");
|
|
} else {
|
|
let doneFetcher = getDoneFetcher(result.data);
|
|
state.fetchers.set(key, doneFetcher);
|
|
}
|
|
});
|
|
return { loaderData, errors };
|
|
}
|
|
function mergeLoaderData(loaderData, newLoaderData, matches, errors) {
|
|
let mergedLoaderData = Object.entries(newLoaderData).filter(([, v]) => v !== ResetLoaderDataSymbol).reduce((merged, [k, v]) => {
|
|
merged[k] = v;
|
|
return merged;
|
|
}, {});
|
|
for (let match of matches) {
|
|
let id = match.route.id;
|
|
if (!newLoaderData.hasOwnProperty(id) && loaderData.hasOwnProperty(id) && match.route.loader) {
|
|
mergedLoaderData[id] = loaderData[id];
|
|
}
|
|
if (errors && errors.hasOwnProperty(id)) {
|
|
break;
|
|
}
|
|
}
|
|
return mergedLoaderData;
|
|
}
|
|
function getActionDataForCommit(pendingActionResult) {
|
|
if (!pendingActionResult) {
|
|
return {};
|
|
}
|
|
return isErrorResult(pendingActionResult[1]) ? {
|
|
// Clear out prior actionData on errors
|
|
actionData: {}
|
|
} : {
|
|
actionData: {
|
|
[pendingActionResult[0]]: pendingActionResult[1].data
|
|
}
|
|
};
|
|
}
|
|
function findNearestBoundary(matches, routeId) {
|
|
let eligibleMatches = routeId ? matches.slice(0, matches.findIndex((m) => m.route.id === routeId) + 1) : [...matches];
|
|
return eligibleMatches.reverse().find((m) => m.route.hasErrorBoundary === true) || matches[0];
|
|
}
|
|
function getShortCircuitMatches(routes) {
|
|
let route = routes.length === 1 ? routes[0] : routes.find((r) => r.index || !r.path || r.path === "/") || {
|
|
id: `__shim-error-route__`
|
|
};
|
|
return {
|
|
matches: [
|
|
{
|
|
params: {},
|
|
pathname: "",
|
|
pathnameBase: "",
|
|
route
|
|
}
|
|
],
|
|
route
|
|
};
|
|
}
|
|
function getInternalRouterError(status, {
|
|
pathname,
|
|
routeId,
|
|
method,
|
|
type,
|
|
message
|
|
} = {}) {
|
|
let statusText = "Unknown Server Error";
|
|
let errorMessage = "Unknown @remix-run/router error";
|
|
if (status === 400) {
|
|
statusText = "Bad Request";
|
|
if (method && pathname && routeId) {
|
|
errorMessage = `You made a ${method} request to "${pathname}" but did not provide a \`loader\` for route "${routeId}", so there is no way to handle the request.`;
|
|
} else if (type === "invalid-body") {
|
|
errorMessage = "Unable to encode submission body";
|
|
}
|
|
} else if (status === 403) {
|
|
statusText = "Forbidden";
|
|
errorMessage = `Route "${routeId}" does not match URL "${pathname}"`;
|
|
} else if (status === 404) {
|
|
statusText = "Not Found";
|
|
errorMessage = `No route matches URL "${pathname}"`;
|
|
} else if (status === 405) {
|
|
statusText = "Method Not Allowed";
|
|
if (method && pathname && routeId) {
|
|
errorMessage = `You made a ${method.toUpperCase()} request to "${pathname}" but did not provide an \`action\` for route "${routeId}", so there is no way to handle the request.`;
|
|
} else if (method) {
|
|
errorMessage = `Invalid request method "${method.toUpperCase()}"`;
|
|
}
|
|
}
|
|
return new ErrorResponseImpl(
|
|
status || 500,
|
|
statusText,
|
|
new Error(errorMessage),
|
|
true
|
|
);
|
|
}
|
|
function findRedirect(results) {
|
|
let entries = Object.entries(results);
|
|
for (let i = entries.length - 1; i >= 0; i--) {
|
|
let [key, result] = entries[i];
|
|
if (isRedirectResult(result)) {
|
|
return { key, result };
|
|
}
|
|
}
|
|
}
|
|
function stripHashFromPath(path) {
|
|
let parsedPath = typeof path === "string" ? parsePath(path) : path;
|
|
return createPath({ ...parsedPath, hash: "" });
|
|
}
|
|
function isHashChangeOnly(a, b) {
|
|
if (a.pathname !== b.pathname || a.search !== b.search) {
|
|
return false;
|
|
}
|
|
if (a.hash === "") {
|
|
return b.hash !== "";
|
|
} else if (a.hash === b.hash) {
|
|
return true;
|
|
} else if (b.hash !== "") {
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|
|
function isRedirectDataStrategyResult(result) {
|
|
return isResponse(result.result) && redirectStatusCodes.has(result.result.status);
|
|
}
|
|
function isErrorResult(result) {
|
|
return result.type === "error" /* error */;
|
|
}
|
|
function isRedirectResult(result) {
|
|
return (result && result.type) === "redirect" /* redirect */;
|
|
}
|
|
function isDataWithResponseInit(value) {
|
|
return typeof value === "object" && value != null && "type" in value && "data" in value && "init" in value && value.type === "DataWithResponseInit";
|
|
}
|
|
function isResponse(value) {
|
|
return value != null && typeof value.status === "number" && typeof value.statusText === "string" && typeof value.headers === "object" && typeof value.body !== "undefined";
|
|
}
|
|
function isValidMethod(method) {
|
|
return validRequestMethods.has(method.toUpperCase());
|
|
}
|
|
function isMutationMethod(method) {
|
|
return validMutationMethods.has(method.toUpperCase());
|
|
}
|
|
function hasNakedIndexQuery(search) {
|
|
return new URLSearchParams(search).getAll("index").some((v) => v === "");
|
|
}
|
|
function getTargetMatch(matches, location) {
|
|
let search = typeof location === "string" ? parsePath(location).search : location.search;
|
|
if (matches[matches.length - 1].route.index && hasNakedIndexQuery(search || "")) {
|
|
return matches[matches.length - 1];
|
|
}
|
|
let pathMatches = getPathContributingMatches(matches);
|
|
return pathMatches[pathMatches.length - 1];
|
|
}
|
|
function getSubmissionFromNavigation(navigation) {
|
|
let { formMethod, formAction, formEncType, text, formData, json } = navigation;
|
|
if (!formMethod || !formAction || !formEncType) {
|
|
return;
|
|
}
|
|
if (text != null) {
|
|
return {
|
|
formMethod,
|
|
formAction,
|
|
formEncType,
|
|
formData: void 0,
|
|
json: void 0,
|
|
text
|
|
};
|
|
} else if (formData != null) {
|
|
return {
|
|
formMethod,
|
|
formAction,
|
|
formEncType,
|
|
formData,
|
|
json: void 0,
|
|
text: void 0
|
|
};
|
|
} else if (json !== void 0) {
|
|
return {
|
|
formMethod,
|
|
formAction,
|
|
formEncType,
|
|
formData: void 0,
|
|
json,
|
|
text: void 0
|
|
};
|
|
}
|
|
}
|
|
function getLoadingNavigation(location, submission) {
|
|
if (submission) {
|
|
let navigation = {
|
|
state: "loading",
|
|
location,
|
|
formMethod: submission.formMethod,
|
|
formAction: submission.formAction,
|
|
formEncType: submission.formEncType,
|
|
formData: submission.formData,
|
|
json: submission.json,
|
|
text: submission.text
|
|
};
|
|
return navigation;
|
|
} else {
|
|
let navigation = {
|
|
state: "loading",
|
|
location,
|
|
formMethod: void 0,
|
|
formAction: void 0,
|
|
formEncType: void 0,
|
|
formData: void 0,
|
|
json: void 0,
|
|
text: void 0
|
|
};
|
|
return navigation;
|
|
}
|
|
}
|
|
function getSubmittingNavigation(location, submission) {
|
|
let navigation = {
|
|
state: "submitting",
|
|
location,
|
|
formMethod: submission.formMethod,
|
|
formAction: submission.formAction,
|
|
formEncType: submission.formEncType,
|
|
formData: submission.formData,
|
|
json: submission.json,
|
|
text: submission.text
|
|
};
|
|
return navigation;
|
|
}
|
|
function getLoadingFetcher(submission, data2) {
|
|
if (submission) {
|
|
let fetcher = {
|
|
state: "loading",
|
|
formMethod: submission.formMethod,
|
|
formAction: submission.formAction,
|
|
formEncType: submission.formEncType,
|
|
formData: submission.formData,
|
|
json: submission.json,
|
|
text: submission.text,
|
|
data: data2
|
|
};
|
|
return fetcher;
|
|
} else {
|
|
let fetcher = {
|
|
state: "loading",
|
|
formMethod: void 0,
|
|
formAction: void 0,
|
|
formEncType: void 0,
|
|
formData: void 0,
|
|
json: void 0,
|
|
text: void 0,
|
|
data: data2
|
|
};
|
|
return fetcher;
|
|
}
|
|
}
|
|
function getSubmittingFetcher(submission, existingFetcher) {
|
|
let fetcher = {
|
|
state: "submitting",
|
|
formMethod: submission.formMethod,
|
|
formAction: submission.formAction,
|
|
formEncType: submission.formEncType,
|
|
formData: submission.formData,
|
|
json: submission.json,
|
|
text: submission.text,
|
|
data: existingFetcher ? existingFetcher.data : void 0
|
|
};
|
|
return fetcher;
|
|
}
|
|
function getDoneFetcher(data2) {
|
|
let fetcher = {
|
|
state: "idle",
|
|
formMethod: void 0,
|
|
formAction: void 0,
|
|
formEncType: void 0,
|
|
formData: void 0,
|
|
json: void 0,
|
|
text: void 0,
|
|
data: data2
|
|
};
|
|
return fetcher;
|
|
}
|
|
function restoreAppliedTransitions(_window, transitions) {
|
|
try {
|
|
let sessionPositions = _window.sessionStorage.getItem(
|
|
TRANSITIONS_STORAGE_KEY
|
|
);
|
|
if (sessionPositions) {
|
|
let json = JSON.parse(sessionPositions);
|
|
for (let [k, v] of Object.entries(json || {})) {
|
|
if (v && Array.isArray(v)) {
|
|
transitions.set(k, new Set(v || []));
|
|
}
|
|
}
|
|
}
|
|
} catch (e) {
|
|
}
|
|
}
|
|
function persistAppliedTransitions(_window, transitions) {
|
|
if (transitions.size > 0) {
|
|
let json = {};
|
|
for (let [k, v] of transitions) {
|
|
json[k] = [...v];
|
|
}
|
|
try {
|
|
_window.sessionStorage.setItem(
|
|
TRANSITIONS_STORAGE_KEY,
|
|
JSON.stringify(json)
|
|
);
|
|
} catch (error) {
|
|
warning(
|
|
false,
|
|
`Failed to save applied view transitions in sessionStorage (${error}).`
|
|
);
|
|
}
|
|
}
|
|
}
|
|
function createDeferred() {
|
|
let resolve;
|
|
let reject;
|
|
let promise = new Promise((res, rej) => {
|
|
resolve = async (val) => {
|
|
res(val);
|
|
try {
|
|
await promise;
|
|
} catch (e) {
|
|
}
|
|
};
|
|
reject = async (error) => {
|
|
rej(error);
|
|
try {
|
|
await promise;
|
|
} catch (e) {
|
|
}
|
|
};
|
|
});
|
|
return {
|
|
promise,
|
|
//@ts-ignore
|
|
resolve,
|
|
//@ts-ignore
|
|
reject
|
|
};
|
|
}
|
|
|
|
// lib/components.tsx
|
|
var React3 = __toESM(require("react"));
|
|
|
|
// lib/context.ts
|
|
var React = __toESM(require("react"));
|
|
var DataRouterContext = React.createContext(null);
|
|
DataRouterContext.displayName = "DataRouter";
|
|
var DataRouterStateContext = React.createContext(null);
|
|
DataRouterStateContext.displayName = "DataRouterState";
|
|
var ViewTransitionContext = React.createContext({
|
|
isTransitioning: false
|
|
});
|
|
ViewTransitionContext.displayName = "ViewTransition";
|
|
var FetchersContext = React.createContext(
|
|
/* @__PURE__ */ new Map()
|
|
);
|
|
FetchersContext.displayName = "Fetchers";
|
|
var AwaitContext = React.createContext(null);
|
|
AwaitContext.displayName = "Await";
|
|
var NavigationContext = React.createContext(
|
|
null
|
|
);
|
|
NavigationContext.displayName = "Navigation";
|
|
var LocationContext = React.createContext(
|
|
null
|
|
);
|
|
LocationContext.displayName = "Location";
|
|
var RouteContext = React.createContext({
|
|
outlet: null,
|
|
matches: [],
|
|
isDataRoute: false
|
|
});
|
|
RouteContext.displayName = "Route";
|
|
var RouteErrorContext = React.createContext(null);
|
|
RouteErrorContext.displayName = "RouteError";
|
|
|
|
// lib/hooks.tsx
|
|
var React2 = __toESM(require("react"));
|
|
var ENABLE_DEV_WARNINGS = true;
|
|
function useInRouterContext() {
|
|
return React2.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 React2.useContext(LocationContext).location;
|
|
}
|
|
var OutletContext = React2.createContext(null);
|
|
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 } = React2.useContext(NavigationContext);
|
|
let { matches: parentMatches } = React2.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;
|
|
if (ENABLE_DEV_WARNINGS) {
|
|
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 });
|
|
if (ENABLE_DEV_WARNINGS) {
|
|
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__ */ React2.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;
|
|
if (ENABLE_DEV_WARNINGS) {
|
|
console.error(
|
|
"Error handled by React Router default ErrorBoundary:",
|
|
error
|
|
);
|
|
devInfo = /* @__PURE__ */ React2.createElement(React2.Fragment, null, /* @__PURE__ */ React2.createElement("p", null, "\u{1F4BF} Hey developer \u{1F44B}"), /* @__PURE__ */ React2.createElement("p", null, "You can provide a way better UX than this when your app throws errors by providing your own ", /* @__PURE__ */ React2.createElement("code", { style: codeStyles }, "ErrorBoundary"), " or", " ", /* @__PURE__ */ React2.createElement("code", { style: codeStyles }, "errorElement"), " prop on your route."));
|
|
}
|
|
return /* @__PURE__ */ React2.createElement(React2.Fragment, null, /* @__PURE__ */ React2.createElement("h2", null, "Unexpected Application Error!"), /* @__PURE__ */ React2.createElement("h3", { style: { fontStyle: "italic" } }, message), stack ? /* @__PURE__ */ React2.createElement("pre", { style: preStyles }, stack) : null, devInfo);
|
|
}
|
|
var defaultErrorElement = /* @__PURE__ */ React2.createElement(DefaultErrorComponent, null);
|
|
var RenderErrorBoundary = class extends React2.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__ */ React2.createElement(RouteContext.Provider, { value: this.props.routeContext }, /* @__PURE__ */ React2.createElement(
|
|
RouteErrorContext.Provider,
|
|
{
|
|
value: this.state.error,
|
|
children: this.props.component
|
|
}
|
|
)) : this.props.children;
|
|
}
|
|
};
|
|
function RenderedRoute({ routeContext, match, children }) {
|
|
let dataRouterContext = React2.useContext(DataRouterContext);
|
|
if (dataRouterContext && dataRouterContext.static && dataRouterContext.staticContext && (match.route.errorElement || match.route.ErrorBoundary)) {
|
|
dataRouterContext.staticContext._deepestRenderedBoundaryId = match.route.id;
|
|
}
|
|
return /* @__PURE__ */ React2.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__ */ React2.createElement(match.route.Component, null);
|
|
} else if (match.route.element) {
|
|
children = match.route.element;
|
|
} else {
|
|
children = outlet;
|
|
}
|
|
return /* @__PURE__ */ React2.createElement(
|
|
RenderedRoute,
|
|
{
|
|
match,
|
|
routeContext: {
|
|
outlet,
|
|
matches: matches2,
|
|
isDataRoute: dataRouterState != null
|
|
},
|
|
children
|
|
}
|
|
);
|
|
};
|
|
return dataRouterState && (match.route.ErrorBoundary || match.route.errorElement || index === 0) ? /* @__PURE__ */ React2.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 useDataRouterState(hookName) {
|
|
let state = React2.useContext(DataRouterStateContext);
|
|
invariant(state, getDataRouterConsoleError(hookName));
|
|
return state;
|
|
}
|
|
function useRouteContext(hookName) {
|
|
let route = React2.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 useRouteError() {
|
|
let error = React2.useContext(RouteErrorContext);
|
|
let state = useDataRouterState("useRouteError" /* UseRouteError */);
|
|
let routeId = useCurrentRouteId("useRouteError" /* UseRouteError */);
|
|
if (error !== void 0) {
|
|
return error;
|
|
}
|
|
return state.errors?.[routeId];
|
|
}
|
|
var alreadyWarned = {};
|
|
function warningOnce(key, cond, message) {
|
|
if (!cond && !alreadyWarned[key]) {
|
|
alreadyWarned[key] = true;
|
|
warning(false, message);
|
|
}
|
|
}
|
|
|
|
// lib/server-runtime/warnings.ts
|
|
var alreadyWarned2 = {};
|
|
function warnOnce(condition, message) {
|
|
if (!condition && !alreadyWarned2[message]) {
|
|
alreadyWarned2[message] = true;
|
|
console.warn(message);
|
|
}
|
|
}
|
|
|
|
// lib/components.tsx
|
|
var ENABLE_DEV_WARNINGS2 = true;
|
|
function mapRouteProperties(route) {
|
|
let updates = {
|
|
// Note: this check also occurs in createRoutesFromChildren so update
|
|
// there if you change this -- please and thank you!
|
|
hasErrorBoundary: route.hasErrorBoundary || route.ErrorBoundary != null || route.errorElement != null
|
|
};
|
|
if (route.Component) {
|
|
if (ENABLE_DEV_WARNINGS2) {
|
|
if (route.element) {
|
|
warning(
|
|
false,
|
|
"You should not include both `Component` and `element` on your route - `Component` will be used."
|
|
);
|
|
}
|
|
}
|
|
Object.assign(updates, {
|
|
element: React3.createElement(route.Component),
|
|
Component: void 0
|
|
});
|
|
}
|
|
if (route.HydrateFallback) {
|
|
if (ENABLE_DEV_WARNINGS2) {
|
|
if (route.hydrateFallbackElement) {
|
|
warning(
|
|
false,
|
|
"You should not include both `HydrateFallback` and `hydrateFallbackElement` on your route - `HydrateFallback` will be used."
|
|
);
|
|
}
|
|
}
|
|
Object.assign(updates, {
|
|
hydrateFallbackElement: React3.createElement(route.HydrateFallback),
|
|
HydrateFallback: void 0
|
|
});
|
|
}
|
|
if (route.ErrorBoundary) {
|
|
if (ENABLE_DEV_WARNINGS2) {
|
|
if (route.errorElement) {
|
|
warning(
|
|
false,
|
|
"You should not include both `ErrorBoundary` and `errorElement` on your route - `ErrorBoundary` will be used."
|
|
);
|
|
}
|
|
}
|
|
Object.assign(updates, {
|
|
errorElement: React3.createElement(route.ErrorBoundary),
|
|
ErrorBoundary: void 0
|
|
});
|
|
}
|
|
return updates;
|
|
}
|
|
var Deferred = class {
|
|
constructor() {
|
|
this.status = "pending";
|
|
this.promise = new Promise((resolve, reject) => {
|
|
this.resolve = (value) => {
|
|
if (this.status === "pending") {
|
|
this.status = "resolved";
|
|
resolve(value);
|
|
}
|
|
};
|
|
this.reject = (reason) => {
|
|
if (this.status === "pending") {
|
|
this.status = "rejected";
|
|
reject(reason);
|
|
}
|
|
};
|
|
});
|
|
}
|
|
};
|
|
function RouterProvider({
|
|
router: router2,
|
|
flushSync: reactDomFlushSyncImpl
|
|
}) {
|
|
let [state, setStateImpl] = React3.useState(router2.state);
|
|
let [pendingState, setPendingState] = React3.useState();
|
|
let [vtContext, setVtContext] = React3.useState({
|
|
isTransitioning: false
|
|
});
|
|
let [renderDfd, setRenderDfd] = React3.useState();
|
|
let [transition, setTransition] = React3.useState();
|
|
let [interruption, setInterruption] = React3.useState();
|
|
let fetcherData = React3.useRef(/* @__PURE__ */ new Map());
|
|
let setState = React3.useCallback(
|
|
(newState, { deletedFetchers, flushSync: flushSync2, viewTransitionOpts }) => {
|
|
newState.fetchers.forEach((fetcher, key) => {
|
|
if (fetcher.data !== void 0) {
|
|
fetcherData.current.set(key, fetcher.data);
|
|
}
|
|
});
|
|
deletedFetchers.forEach((key) => fetcherData.current.delete(key));
|
|
warnOnce(
|
|
flushSync2 === false || reactDomFlushSyncImpl != null,
|
|
'You provided the `flushSync` option to a router update, but you are not using the `<RouterProvider>` from `react-router/dom` so `ReactDOM.flushSync()` is unavailable. Please update your app to `import { RouterProvider } from "react-router/dom"` and ensure you have `react-dom` installed as a dependency to use the `flushSync` option.'
|
|
);
|
|
let isViewTransitionAvailable = router2.window != null && router2.window.document != null && typeof router2.window.document.startViewTransition === "function";
|
|
warnOnce(
|
|
viewTransitionOpts == null || isViewTransitionAvailable,
|
|
"You provided the `viewTransition` option to a router update, but you do not appear to be running in a DOM environment as `window.startViewTransition` is not available."
|
|
);
|
|
if (!viewTransitionOpts || !isViewTransitionAvailable) {
|
|
if (reactDomFlushSyncImpl && flushSync2) {
|
|
reactDomFlushSyncImpl(() => setStateImpl(newState));
|
|
} else {
|
|
React3.startTransition(() => setStateImpl(newState));
|
|
}
|
|
return;
|
|
}
|
|
if (reactDomFlushSyncImpl && flushSync2) {
|
|
reactDomFlushSyncImpl(() => {
|
|
if (transition) {
|
|
renderDfd && renderDfd.resolve();
|
|
transition.skipTransition();
|
|
}
|
|
setVtContext({
|
|
isTransitioning: true,
|
|
flushSync: true,
|
|
currentLocation: viewTransitionOpts.currentLocation,
|
|
nextLocation: viewTransitionOpts.nextLocation
|
|
});
|
|
});
|
|
let t = router2.window.document.startViewTransition(() => {
|
|
reactDomFlushSyncImpl(() => setStateImpl(newState));
|
|
});
|
|
t.finished.finally(() => {
|
|
reactDomFlushSyncImpl(() => {
|
|
setRenderDfd(void 0);
|
|
setTransition(void 0);
|
|
setPendingState(void 0);
|
|
setVtContext({ isTransitioning: false });
|
|
});
|
|
});
|
|
reactDomFlushSyncImpl(() => setTransition(t));
|
|
return;
|
|
}
|
|
if (transition) {
|
|
renderDfd && renderDfd.resolve();
|
|
transition.skipTransition();
|
|
setInterruption({
|
|
state: newState,
|
|
currentLocation: viewTransitionOpts.currentLocation,
|
|
nextLocation: viewTransitionOpts.nextLocation
|
|
});
|
|
} else {
|
|
setPendingState(newState);
|
|
setVtContext({
|
|
isTransitioning: true,
|
|
flushSync: false,
|
|
currentLocation: viewTransitionOpts.currentLocation,
|
|
nextLocation: viewTransitionOpts.nextLocation
|
|
});
|
|
}
|
|
},
|
|
[router2.window, reactDomFlushSyncImpl, transition, renderDfd]
|
|
);
|
|
React3.useLayoutEffect(() => router2.subscribe(setState), [router2, setState]);
|
|
React3.useEffect(() => {
|
|
if (vtContext.isTransitioning && !vtContext.flushSync) {
|
|
setRenderDfd(new Deferred());
|
|
}
|
|
}, [vtContext]);
|
|
React3.useEffect(() => {
|
|
if (renderDfd && pendingState && router2.window) {
|
|
let newState = pendingState;
|
|
let renderPromise = renderDfd.promise;
|
|
let transition2 = router2.window.document.startViewTransition(async () => {
|
|
React3.startTransition(() => setStateImpl(newState));
|
|
await renderPromise;
|
|
});
|
|
transition2.finished.finally(() => {
|
|
setRenderDfd(void 0);
|
|
setTransition(void 0);
|
|
setPendingState(void 0);
|
|
setVtContext({ isTransitioning: false });
|
|
});
|
|
setTransition(transition2);
|
|
}
|
|
}, [pendingState, renderDfd, router2.window]);
|
|
React3.useEffect(() => {
|
|
if (renderDfd && pendingState && state.location.key === pendingState.location.key) {
|
|
renderDfd.resolve();
|
|
}
|
|
}, [renderDfd, transition, state.location, pendingState]);
|
|
React3.useEffect(() => {
|
|
if (!vtContext.isTransitioning && interruption) {
|
|
setPendingState(interruption.state);
|
|
setVtContext({
|
|
isTransitioning: true,
|
|
flushSync: false,
|
|
currentLocation: interruption.currentLocation,
|
|
nextLocation: interruption.nextLocation
|
|
});
|
|
setInterruption(void 0);
|
|
}
|
|
}, [vtContext.isTransitioning, interruption]);
|
|
let navigator2 = React3.useMemo(() => {
|
|
return {
|
|
createHref: router2.createHref,
|
|
encodeLocation: router2.encodeLocation,
|
|
go: (n) => router2.navigate(n),
|
|
push: (to, state2, opts) => router2.navigate(to, {
|
|
state: state2,
|
|
preventScrollReset: opts?.preventScrollReset
|
|
}),
|
|
replace: (to, state2, opts) => router2.navigate(to, {
|
|
replace: true,
|
|
state: state2,
|
|
preventScrollReset: opts?.preventScrollReset
|
|
})
|
|
};
|
|
}, [router2]);
|
|
let basename = router2.basename || "/";
|
|
let dataRouterContext = React3.useMemo(
|
|
() => ({
|
|
router: router2,
|
|
navigator: navigator2,
|
|
static: false,
|
|
basename
|
|
}),
|
|
[router2, navigator2, basename]
|
|
);
|
|
return /* @__PURE__ */ React3.createElement(React3.Fragment, null, /* @__PURE__ */ React3.createElement(DataRouterContext.Provider, { value: dataRouterContext }, /* @__PURE__ */ React3.createElement(DataRouterStateContext.Provider, { value: state }, /* @__PURE__ */ React3.createElement(FetchersContext.Provider, { value: fetcherData.current }, /* @__PURE__ */ React3.createElement(ViewTransitionContext.Provider, { value: vtContext }, /* @__PURE__ */ React3.createElement(
|
|
Router,
|
|
{
|
|
basename,
|
|
location: state.location,
|
|
navigationType: state.historyAction,
|
|
navigator: navigator2
|
|
},
|
|
/* @__PURE__ */ React3.createElement(
|
|
MemoizedDataRoutes,
|
|
{
|
|
routes: router2.routes,
|
|
future: router2.future,
|
|
state
|
|
}
|
|
)
|
|
))))), null);
|
|
}
|
|
var MemoizedDataRoutes = React3.memo(DataRoutes);
|
|
function DataRoutes({
|
|
routes,
|
|
future,
|
|
state
|
|
}) {
|
|
return useRoutesImpl(routes, void 0, state, future);
|
|
}
|
|
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 = React3.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 = React3.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, navigationType]);
|
|
warning(
|
|
locationContext != null,
|
|
`<Router basename="${basename}"> is not able to match the URL "${pathname}${search}${hash}" because it does not start with the basename, so the <Router> won't render anything.`
|
|
);
|
|
if (locationContext == null) {
|
|
return null;
|
|
}
|
|
return /* @__PURE__ */ React3.createElement(NavigationContext.Provider, { value: navigationContext }, /* @__PURE__ */ React3.createElement(LocationContext.Provider, { children, value: locationContext }));
|
|
}
|
|
|
|
// lib/dom/ssr/components.tsx
|
|
var React9 = __toESM(require("react"));
|
|
|
|
// lib/dom/ssr/invariant.ts
|
|
function invariant2(value, message) {
|
|
if (value === false || value === null || typeof value === "undefined") {
|
|
throw new Error(message);
|
|
}
|
|
}
|
|
|
|
// lib/dom/ssr/routeModules.ts
|
|
async function loadRouteModule(route, routeModulesCache) {
|
|
if (route.id in routeModulesCache) {
|
|
return routeModulesCache[route.id];
|
|
}
|
|
try {
|
|
let routeModule = await import(
|
|
/* @vite-ignore */
|
|
/* webpackIgnore: true */
|
|
route.module
|
|
);
|
|
routeModulesCache[route.id] = routeModule;
|
|
return routeModule;
|
|
} catch (error) {
|
|
console.error(
|
|
`Error loading route module \`${route.module}\`, reloading page...`
|
|
);
|
|
console.error(error);
|
|
if (window.__reactRouterContext && window.__reactRouterContext.isSpaMode && // @ts-expect-error
|
|
void 0) {
|
|
throw error;
|
|
}
|
|
window.location.reload();
|
|
return new Promise(() => {
|
|
});
|
|
}
|
|
}
|
|
|
|
// lib/dom/ssr/links.ts
|
|
async function prefetchStyleLinks(route, routeModule) {
|
|
if (!route.css && !routeModule.links || !isPreloadSupported()) return;
|
|
let descriptors = [];
|
|
if (route.css) {
|
|
descriptors.push(...route.css.map((href) => ({ rel: "stylesheet", href })));
|
|
}
|
|
if (routeModule.links) {
|
|
descriptors.push(...routeModule.links());
|
|
}
|
|
if (descriptors.length === 0) return;
|
|
let styleLinks = [];
|
|
for (let descriptor of descriptors) {
|
|
if (!isPageLinkDescriptor(descriptor) && descriptor.rel === "stylesheet") {
|
|
styleLinks.push({
|
|
...descriptor,
|
|
rel: "preload",
|
|
as: "style"
|
|
});
|
|
}
|
|
}
|
|
let matchingLinks = styleLinks.filter(
|
|
(link) => (!link.media || window.matchMedia(link.media).matches) && !document.querySelector(`link[rel="stylesheet"][href="${link.href}"]`)
|
|
);
|
|
await Promise.all(matchingLinks.map(prefetchStyleLink));
|
|
}
|
|
async function prefetchStyleLink(descriptor) {
|
|
return new Promise((resolve) => {
|
|
let link = document.createElement("link");
|
|
Object.assign(link, descriptor);
|
|
function removeLink() {
|
|
if (document.head.contains(link)) {
|
|
document.head.removeChild(link);
|
|
}
|
|
}
|
|
link.onload = () => {
|
|
removeLink();
|
|
resolve();
|
|
};
|
|
link.onerror = () => {
|
|
removeLink();
|
|
resolve();
|
|
};
|
|
document.head.appendChild(link);
|
|
});
|
|
}
|
|
function isPageLinkDescriptor(object) {
|
|
return object != null && typeof object.page === "string";
|
|
}
|
|
var _isPreloadSupported;
|
|
function isPreloadSupported() {
|
|
if (_isPreloadSupported !== void 0) {
|
|
return _isPreloadSupported;
|
|
}
|
|
let el = document.createElement("link");
|
|
_isPreloadSupported = el.relList.supports("preload");
|
|
el = null;
|
|
return _isPreloadSupported;
|
|
}
|
|
|
|
// lib/dom/ssr/markup.ts
|
|
function createHtml(html) {
|
|
return { __html: html };
|
|
}
|
|
|
|
// lib/dom/ssr/single-fetch.tsx
|
|
var React4 = __toESM(require("react"));
|
|
var import_turbo_stream = require("turbo-stream");
|
|
|
|
// lib/dom/ssr/data.ts
|
|
async function createRequestInit(request) {
|
|
let init = { signal: request.signal };
|
|
if (request.method !== "GET") {
|
|
init.method = request.method;
|
|
let contentType = request.headers.get("Content-Type");
|
|
if (contentType && /\bapplication\/json\b/.test(contentType)) {
|
|
init.headers = { "Content-Type": contentType };
|
|
init.body = JSON.stringify(await request.json());
|
|
} else if (contentType && /\btext\/plain\b/.test(contentType)) {
|
|
init.headers = { "Content-Type": contentType };
|
|
init.body = await request.text();
|
|
} else if (contentType && /\bapplication\/x-www-form-urlencoded\b/.test(contentType)) {
|
|
init.body = new URLSearchParams(await request.text());
|
|
} else {
|
|
init.body = await request.formData();
|
|
}
|
|
}
|
|
return init;
|
|
}
|
|
|
|
// lib/dom/ssr/single-fetch.tsx
|
|
var SingleFetchRedirectSymbol = Symbol("SingleFetchRedirect");
|
|
function getSingleFetchDataStrategy(manifest, routeModules, getRouter) {
|
|
return async ({ request, matches, fetcherKey }) => {
|
|
if (request.method !== "GET") {
|
|
return singleFetchActionStrategy(request, matches);
|
|
}
|
|
if (fetcherKey) {
|
|
return singleFetchLoaderFetcherStrategy(request, matches);
|
|
}
|
|
return singleFetchLoaderNavigationStrategy(
|
|
manifest,
|
|
routeModules,
|
|
getRouter(),
|
|
request,
|
|
matches
|
|
);
|
|
};
|
|
}
|
|
async function singleFetchActionStrategy(request, matches) {
|
|
let actionMatch = matches.find((m) => m.shouldLoad);
|
|
invariant2(actionMatch, "No action match found");
|
|
let actionStatus = void 0;
|
|
let result = await actionMatch.resolve(async (handler) => {
|
|
let result2 = await handler(async () => {
|
|
let url = singleFetchUrl(request.url);
|
|
let init = await createRequestInit(request);
|
|
let { data: data2, status } = await fetchAndDecode(url, init);
|
|
actionStatus = status;
|
|
return unwrapSingleFetchResult(
|
|
data2,
|
|
actionMatch.route.id
|
|
);
|
|
});
|
|
return result2;
|
|
});
|
|
if (isResponse(result.result) || isRouteErrorResponse(result.result)) {
|
|
return { [actionMatch.route.id]: result };
|
|
}
|
|
return {
|
|
[actionMatch.route.id]: {
|
|
type: result.type,
|
|
result: data(result.result, actionStatus)
|
|
}
|
|
};
|
|
}
|
|
async function singleFetchLoaderNavigationStrategy(manifest, routeModules, router2, request, matches) {
|
|
let routesParams = /* @__PURE__ */ new Set();
|
|
let foundOptOutRoute = false;
|
|
let routeDfds = matches.map(() => createDeferred2());
|
|
let routesLoadedPromise = Promise.all(routeDfds.map((d) => d.promise));
|
|
let singleFetchDfd = createDeferred2();
|
|
let url = stripIndexParam(singleFetchUrl(request.url));
|
|
let init = await createRequestInit(request);
|
|
let results = {};
|
|
let resolvePromise = Promise.all(
|
|
matches.map(
|
|
async (m, i) => m.resolve(async (handler) => {
|
|
routeDfds[i].resolve();
|
|
let manifestRoute = manifest.routes[m.route.id];
|
|
if (!m.shouldLoad) {
|
|
if (!router2.state.initialized) {
|
|
return;
|
|
}
|
|
if (m.route.id in router2.state.loaderData && manifestRoute && manifestRoute.hasLoader && routeModules[m.route.id]?.shouldRevalidate) {
|
|
foundOptOutRoute = true;
|
|
return;
|
|
}
|
|
}
|
|
if (manifestRoute && manifestRoute.hasClientLoader) {
|
|
if (manifestRoute.hasLoader) {
|
|
foundOptOutRoute = true;
|
|
}
|
|
try {
|
|
let result = await fetchSingleLoader(
|
|
handler,
|
|
url,
|
|
init,
|
|
m.route.id
|
|
);
|
|
results[m.route.id] = { type: "data", result };
|
|
} catch (e) {
|
|
results[m.route.id] = { type: "error", result: e };
|
|
}
|
|
return;
|
|
}
|
|
if (manifestRoute && manifestRoute.hasLoader) {
|
|
routesParams.add(m.route.id);
|
|
}
|
|
try {
|
|
let result = await handler(async () => {
|
|
let data2 = await singleFetchDfd.promise;
|
|
return unwrapSingleFetchResults(data2, m.route.id);
|
|
});
|
|
results[m.route.id] = {
|
|
type: "data",
|
|
result
|
|
};
|
|
} catch (e) {
|
|
results[m.route.id] = {
|
|
type: "error",
|
|
result: e
|
|
};
|
|
}
|
|
})
|
|
)
|
|
);
|
|
await routesLoadedPromise;
|
|
if ((!router2.state.initialized || routesParams.size === 0) && !window.__reactRouterHdrActive) {
|
|
singleFetchDfd.resolve({});
|
|
} else {
|
|
try {
|
|
if (foundOptOutRoute && routesParams.size > 0) {
|
|
url.searchParams.set(
|
|
"_routes",
|
|
matches.filter((m) => routesParams.has(m.route.id)).map((m) => m.route.id).join(",")
|
|
);
|
|
}
|
|
let data2 = await fetchAndDecode(url, init);
|
|
singleFetchDfd.resolve(data2.data);
|
|
} catch (e) {
|
|
singleFetchDfd.reject(e);
|
|
}
|
|
}
|
|
await resolvePromise;
|
|
return results;
|
|
}
|
|
async function singleFetchLoaderFetcherStrategy(request, matches) {
|
|
let fetcherMatch = matches.find((m) => m.shouldLoad);
|
|
invariant2(fetcherMatch, "No fetcher match found");
|
|
let result = await fetcherMatch.resolve(async (handler) => {
|
|
let url = stripIndexParam(singleFetchUrl(request.url));
|
|
let init = await createRequestInit(request);
|
|
return fetchSingleLoader(handler, url, init, fetcherMatch.route.id);
|
|
});
|
|
return { [fetcherMatch.route.id]: result };
|
|
}
|
|
function fetchSingleLoader(handler, url, init, routeId) {
|
|
return handler(async () => {
|
|
let singleLoaderUrl = new URL(url);
|
|
singleLoaderUrl.searchParams.set("_routes", routeId);
|
|
let { data: data2 } = await fetchAndDecode(singleLoaderUrl, init);
|
|
return unwrapSingleFetchResults(data2, routeId);
|
|
});
|
|
}
|
|
function stripIndexParam(url) {
|
|
let indexValues = url.searchParams.getAll("index");
|
|
url.searchParams.delete("index");
|
|
let indexValuesToKeep = [];
|
|
for (let indexValue of indexValues) {
|
|
if (indexValue) {
|
|
indexValuesToKeep.push(indexValue);
|
|
}
|
|
}
|
|
for (let toKeep of indexValuesToKeep) {
|
|
url.searchParams.append("index", toKeep);
|
|
}
|
|
return url;
|
|
}
|
|
function singleFetchUrl(reqUrl) {
|
|
let url = typeof reqUrl === "string" ? new URL(
|
|
reqUrl,
|
|
// This can be called during the SSR flow via PrefetchPageLinksImpl so
|
|
// don't assume window is available
|
|
typeof window === "undefined" ? "server://singlefetch/" : window.location.origin
|
|
) : reqUrl;
|
|
if (url.pathname === "/") {
|
|
url.pathname = "_root.data";
|
|
} else {
|
|
url.pathname = `${url.pathname.replace(/\/$/, "")}.data`;
|
|
}
|
|
return url;
|
|
}
|
|
async function fetchAndDecode(url, init) {
|
|
let res = await fetch(url, init);
|
|
if (res.status === 404 && !res.headers.has("X-Remix-Response")) {
|
|
throw new ErrorResponseImpl(404, "Not Found", true);
|
|
}
|
|
const NO_BODY_STATUS_CODES = /* @__PURE__ */ new Set([100, 101, 204, 205]);
|
|
if (NO_BODY_STATUS_CODES.has(res.status)) {
|
|
if (!init.method || init.method === "GET") {
|
|
return { status: res.status, data: {} };
|
|
} else {
|
|
return { status: res.status, data: { data: void 0 } };
|
|
}
|
|
}
|
|
invariant2(res.body, "No response body to decode");
|
|
try {
|
|
let decoded = await decodeViaTurboStream(res.body, window);
|
|
return { status: res.status, data: decoded.value };
|
|
} catch (e) {
|
|
throw new Error("Unable to decode turbo-stream response");
|
|
}
|
|
}
|
|
function decodeViaTurboStream(body, global) {
|
|
return (0, import_turbo_stream.decode)(body, {
|
|
plugins: [
|
|
(type, ...rest) => {
|
|
if (type === "SanitizedError") {
|
|
let [name, message, stack] = rest;
|
|
let Constructor = Error;
|
|
if (name && name in global && typeof global[name] === "function") {
|
|
Constructor = global[name];
|
|
}
|
|
let error = new Constructor(message);
|
|
error.stack = stack;
|
|
return { value: error };
|
|
}
|
|
if (type === "ErrorResponse") {
|
|
let [data2, status, statusText] = rest;
|
|
return {
|
|
value: new ErrorResponseImpl(status, statusText, data2)
|
|
};
|
|
}
|
|
if (type === "SingleFetchRedirect") {
|
|
return { value: { [SingleFetchRedirectSymbol]: rest[0] } };
|
|
}
|
|
if (type === "SingleFetchClassInstance") {
|
|
return { value: rest[0] };
|
|
}
|
|
if (type === "SingleFetchFallback") {
|
|
return { value: void 0 };
|
|
}
|
|
}
|
|
]
|
|
});
|
|
}
|
|
function unwrapSingleFetchResults(results, routeId) {
|
|
let redirect2 = results[SingleFetchRedirectSymbol];
|
|
if (redirect2) {
|
|
return unwrapSingleFetchResult(redirect2, routeId);
|
|
}
|
|
return results[routeId] !== void 0 ? unwrapSingleFetchResult(results[routeId], routeId) : null;
|
|
}
|
|
function unwrapSingleFetchResult(result, routeId) {
|
|
if ("error" in result) {
|
|
throw result.error;
|
|
} else if ("redirect" in result) {
|
|
let headers = {};
|
|
if (result.revalidate) {
|
|
headers["X-Remix-Revalidate"] = "yes";
|
|
}
|
|
if (result.reload) {
|
|
headers["X-Remix-Reload-Document"] = "yes";
|
|
}
|
|
if (result.replace) {
|
|
headers["X-Remix-Replace"] = "yes";
|
|
}
|
|
throw redirect(result.redirect, { status: result.status, headers });
|
|
} else if ("data" in result) {
|
|
return result.data;
|
|
} else {
|
|
throw new Error(`No response found for routeId "${routeId}"`);
|
|
}
|
|
}
|
|
function createDeferred2() {
|
|
let resolve;
|
|
let reject;
|
|
let promise = new Promise((res, rej) => {
|
|
resolve = async (val) => {
|
|
res(val);
|
|
try {
|
|
await promise;
|
|
} catch (e) {
|
|
}
|
|
};
|
|
reject = async (error) => {
|
|
rej(error);
|
|
try {
|
|
await promise;
|
|
} catch (e) {
|
|
}
|
|
};
|
|
});
|
|
return {
|
|
promise,
|
|
//@ts-ignore
|
|
resolve,
|
|
//@ts-ignore
|
|
reject
|
|
};
|
|
}
|
|
|
|
// lib/dom/ssr/fog-of-war.ts
|
|
var React8 = __toESM(require("react"));
|
|
|
|
// lib/dom/ssr/routes.tsx
|
|
var React7 = __toESM(require("react"));
|
|
|
|
// lib/dom/ssr/errorBoundaries.tsx
|
|
var React5 = __toESM(require("react"));
|
|
var RemixErrorBoundary = class extends React5.Component {
|
|
constructor(props) {
|
|
super(props);
|
|
this.state = { error: props.error || null, location: props.location };
|
|
}
|
|
static getDerivedStateFromError(error) {
|
|
return { error };
|
|
}
|
|
static getDerivedStateFromProps(props, state) {
|
|
if (state.location !== props.location) {
|
|
return { error: props.error || null, location: props.location };
|
|
}
|
|
return { error: props.error || state.error, location: state.location };
|
|
}
|
|
render() {
|
|
if (this.state.error) {
|
|
return /* @__PURE__ */ React5.createElement(
|
|
RemixRootDefaultErrorBoundary,
|
|
{
|
|
error: this.state.error,
|
|
isOutsideRemixApp: true
|
|
}
|
|
);
|
|
} else {
|
|
return this.props.children;
|
|
}
|
|
}
|
|
};
|
|
function RemixRootDefaultErrorBoundary({
|
|
error,
|
|
isOutsideRemixApp
|
|
}) {
|
|
console.error(error);
|
|
let heyDeveloper = /* @__PURE__ */ React5.createElement(
|
|
"script",
|
|
{
|
|
dangerouslySetInnerHTML: {
|
|
__html: `
|
|
console.log(
|
|
"\u{1F4BF} Hey developer \u{1F44B}. You can provide a way better UX than this when your app throws errors. Check out https://remix.run/guides/errors for more information."
|
|
);
|
|
`
|
|
}
|
|
}
|
|
);
|
|
if (isRouteErrorResponse(error)) {
|
|
return /* @__PURE__ */ React5.createElement(BoundaryShell, { title: "Unhandled Thrown Response!" }, /* @__PURE__ */ React5.createElement("h1", { style: { fontSize: "24px" } }, error.status, " ", error.statusText), heyDeveloper);
|
|
}
|
|
let errorInstance;
|
|
if (error instanceof Error) {
|
|
errorInstance = error;
|
|
} else {
|
|
let errorString = error == null ? "Unknown Error" : typeof error === "object" && "toString" in error ? error.toString() : JSON.stringify(error);
|
|
errorInstance = new Error(errorString);
|
|
}
|
|
return /* @__PURE__ */ React5.createElement(
|
|
BoundaryShell,
|
|
{
|
|
title: "Application Error!",
|
|
isOutsideRemixApp
|
|
},
|
|
/* @__PURE__ */ React5.createElement("h1", { style: { fontSize: "24px" } }, "Application Error"),
|
|
/* @__PURE__ */ React5.createElement(
|
|
"pre",
|
|
{
|
|
style: {
|
|
padding: "2rem",
|
|
background: "hsla(10, 50%, 50%, 0.1)",
|
|
color: "red",
|
|
overflow: "auto"
|
|
}
|
|
},
|
|
errorInstance.stack
|
|
),
|
|
heyDeveloper
|
|
);
|
|
}
|
|
function BoundaryShell({
|
|
title,
|
|
renderScripts,
|
|
isOutsideRemixApp,
|
|
children
|
|
}) {
|
|
let { routeModules } = useFrameworkContext();
|
|
if (routeModules.root?.Layout && !isOutsideRemixApp) {
|
|
return children;
|
|
}
|
|
return /* @__PURE__ */ React5.createElement("html", { lang: "en" }, /* @__PURE__ */ React5.createElement("head", null, /* @__PURE__ */ React5.createElement("meta", { charSet: "utf-8" }), /* @__PURE__ */ React5.createElement(
|
|
"meta",
|
|
{
|
|
name: "viewport",
|
|
content: "width=device-width,initial-scale=1,viewport-fit=cover"
|
|
}
|
|
), /* @__PURE__ */ React5.createElement("title", null, title)), /* @__PURE__ */ React5.createElement("body", null, /* @__PURE__ */ React5.createElement("main", { style: { fontFamily: "system-ui, sans-serif", padding: "2rem" } }, children, renderScripts ? /* @__PURE__ */ React5.createElement(Scripts, null) : null)));
|
|
}
|
|
|
|
// lib/dom/ssr/fallback.tsx
|
|
var React6 = __toESM(require("react"));
|
|
function RemixRootDefaultHydrateFallback() {
|
|
return /* @__PURE__ */ React6.createElement(BoundaryShell, { title: "Loading...", renderScripts: true }, /* @__PURE__ */ React6.createElement(
|
|
"script",
|
|
{
|
|
dangerouslySetInnerHTML: {
|
|
__html: `
|
|
console.log(
|
|
"\u{1F4BF} Hey developer \u{1F44B}. You can provide a way better UX than this " +
|
|
"when your app is loading JS modules and/or running \`clientLoader\` " +
|
|
"functions. Check out https://remix.run/route/hydrate-fallback " +
|
|
"for more information."
|
|
);
|
|
`
|
|
}
|
|
}
|
|
));
|
|
}
|
|
|
|
// lib/dom/ssr/routes.tsx
|
|
function groupRoutesByParentId(manifest) {
|
|
let routes = {};
|
|
Object.values(manifest).forEach((route) => {
|
|
if (route) {
|
|
let parentId = route.parentId || "";
|
|
if (!routes[parentId]) {
|
|
routes[parentId] = [];
|
|
}
|
|
routes[parentId].push(route);
|
|
}
|
|
});
|
|
return routes;
|
|
}
|
|
function getRouteComponents(route, routeModule, isSpaMode) {
|
|
let Component4 = getRouteModuleComponent(routeModule);
|
|
let HydrateFallback = routeModule.HydrateFallback && (!isSpaMode || route.id === "root") ? routeModule.HydrateFallback : route.id === "root" ? RemixRootDefaultHydrateFallback : void 0;
|
|
let ErrorBoundary = routeModule.ErrorBoundary ? routeModule.ErrorBoundary : route.id === "root" ? () => /* @__PURE__ */ React7.createElement(RemixRootDefaultErrorBoundary, { error: useRouteError() }) : void 0;
|
|
if (route.id === "root" && routeModule.Layout) {
|
|
return {
|
|
...Component4 ? {
|
|
element: /* @__PURE__ */ React7.createElement(routeModule.Layout, null, /* @__PURE__ */ React7.createElement(Component4, null))
|
|
} : { Component: Component4 },
|
|
...ErrorBoundary ? {
|
|
errorElement: /* @__PURE__ */ React7.createElement(routeModule.Layout, null, /* @__PURE__ */ React7.createElement(ErrorBoundary, null))
|
|
} : { ErrorBoundary },
|
|
...HydrateFallback ? {
|
|
hydrateFallbackElement: /* @__PURE__ */ React7.createElement(routeModule.Layout, null, /* @__PURE__ */ React7.createElement(HydrateFallback, null))
|
|
} : { HydrateFallback }
|
|
};
|
|
}
|
|
return { Component: Component4, ErrorBoundary, HydrateFallback };
|
|
}
|
|
function createClientRoutesWithHMRRevalidationOptOut(needsRevalidation, manifest, routeModulesCache, initialState, future, isSpaMode) {
|
|
return createClientRoutes(
|
|
manifest,
|
|
routeModulesCache,
|
|
initialState,
|
|
isSpaMode,
|
|
"",
|
|
groupRoutesByParentId(manifest),
|
|
needsRevalidation
|
|
);
|
|
}
|
|
function preventInvalidServerHandlerCall(type, route, isSpaMode) {
|
|
if (isSpaMode) {
|
|
let fn2 = type === "action" ? "serverAction()" : "serverLoader()";
|
|
let msg2 = `You cannot call ${fn2} in SPA Mode (routeId: "${route.id}")`;
|
|
console.error(msg2);
|
|
throw new ErrorResponseImpl(400, "Bad Request", new Error(msg2), true);
|
|
}
|
|
let fn = type === "action" ? "serverAction()" : "serverLoader()";
|
|
let msg = `You are trying to call ${fn} on a route that does not have a server ${type} (routeId: "${route.id}")`;
|
|
if (type === "loader" && !route.hasLoader || type === "action" && !route.hasAction) {
|
|
console.error(msg);
|
|
throw new ErrorResponseImpl(400, "Bad Request", new Error(msg), true);
|
|
}
|
|
}
|
|
function noActionDefinedError(type, routeId) {
|
|
let article = type === "clientAction" ? "a" : "an";
|
|
let msg = `Route "${routeId}" does not have ${article} ${type}, but you are trying to submit to it. To fix this, please add ${article} \`${type}\` function to the route`;
|
|
console.error(msg);
|
|
throw new ErrorResponseImpl(405, "Method Not Allowed", new Error(msg), true);
|
|
}
|
|
function createClientRoutes(manifest, routeModulesCache, initialState, isSpaMode, parentId = "", routesByParentId = groupRoutesByParentId(manifest), needsRevalidation) {
|
|
return (routesByParentId[parentId] || []).map((route) => {
|
|
let routeModule = routeModulesCache[route.id];
|
|
function fetchServerHandler(singleFetch) {
|
|
invariant2(
|
|
typeof singleFetch === "function",
|
|
"No single fetch function available for route handler"
|
|
);
|
|
return singleFetch();
|
|
}
|
|
function fetchServerLoader(singleFetch) {
|
|
if (!route.hasLoader) return Promise.resolve(null);
|
|
return fetchServerHandler(singleFetch);
|
|
}
|
|
function fetchServerAction(singleFetch) {
|
|
if (!route.hasAction) {
|
|
throw noActionDefinedError("action", route.id);
|
|
}
|
|
return fetchServerHandler(singleFetch);
|
|
}
|
|
async function prefetchStylesAndCallHandler(handler) {
|
|
let cachedModule = routeModulesCache[route.id];
|
|
let linkPrefetchPromise = cachedModule ? prefetchStyleLinks(route, cachedModule) : Promise.resolve();
|
|
try {
|
|
return handler();
|
|
} finally {
|
|
await linkPrefetchPromise;
|
|
}
|
|
}
|
|
let dataRoute = {
|
|
id: route.id,
|
|
index: route.index,
|
|
path: route.path
|
|
};
|
|
if (routeModule) {
|
|
Object.assign(dataRoute, {
|
|
...dataRoute,
|
|
...getRouteComponents(route, routeModule, isSpaMode),
|
|
handle: routeModule.handle,
|
|
shouldRevalidate: getShouldRevalidateFunction(
|
|
routeModule,
|
|
route.id,
|
|
needsRevalidation
|
|
)
|
|
});
|
|
let hasInitialData = initialState && initialState.loaderData && route.id in initialState.loaderData;
|
|
let initialData = hasInitialData ? initialState?.loaderData?.[route.id] : void 0;
|
|
let hasInitialError = initialState && initialState.errors && route.id in initialState.errors;
|
|
let initialError = hasInitialError ? initialState?.errors?.[route.id] : void 0;
|
|
let isHydrationRequest = needsRevalidation == null && (routeModule.clientLoader?.hydrate === true || !route.hasLoader);
|
|
dataRoute.loader = async ({ request, params }, singleFetch) => {
|
|
try {
|
|
let result = await prefetchStylesAndCallHandler(async () => {
|
|
invariant2(
|
|
routeModule,
|
|
"No `routeModule` available for critical-route loader"
|
|
);
|
|
if (!routeModule.clientLoader) {
|
|
if (isSpaMode) return null;
|
|
return fetchServerLoader(singleFetch);
|
|
}
|
|
return routeModule.clientLoader({
|
|
request,
|
|
params,
|
|
async serverLoader() {
|
|
preventInvalidServerHandlerCall("loader", route, isSpaMode);
|
|
if (isHydrationRequest) {
|
|
if (hasInitialData) {
|
|
return initialData;
|
|
}
|
|
if (hasInitialError) {
|
|
throw initialError;
|
|
}
|
|
}
|
|
return fetchServerLoader(singleFetch);
|
|
}
|
|
});
|
|
});
|
|
return result;
|
|
} finally {
|
|
isHydrationRequest = false;
|
|
}
|
|
};
|
|
dataRoute.loader.hydrate = shouldHydrateRouteLoader(
|
|
route,
|
|
routeModule,
|
|
isSpaMode
|
|
);
|
|
dataRoute.action = ({ request, params }, singleFetch) => {
|
|
return prefetchStylesAndCallHandler(async () => {
|
|
invariant2(
|
|
routeModule,
|
|
"No `routeModule` available for critical-route action"
|
|
);
|
|
if (!routeModule.clientAction) {
|
|
if (isSpaMode) {
|
|
throw noActionDefinedError("clientAction", route.id);
|
|
}
|
|
return fetchServerAction(singleFetch);
|
|
}
|
|
return routeModule.clientAction({
|
|
request,
|
|
params,
|
|
async serverAction() {
|
|
preventInvalidServerHandlerCall("action", route, isSpaMode);
|
|
return fetchServerAction(singleFetch);
|
|
}
|
|
});
|
|
});
|
|
};
|
|
} else {
|
|
if (!route.hasClientLoader) {
|
|
dataRoute.loader = ({ request }, singleFetch) => prefetchStylesAndCallHandler(() => {
|
|
if (isSpaMode) return Promise.resolve(null);
|
|
return fetchServerLoader(singleFetch);
|
|
});
|
|
}
|
|
if (!route.hasClientAction) {
|
|
dataRoute.action = ({ request }, singleFetch) => prefetchStylesAndCallHandler(() => {
|
|
if (isSpaMode) {
|
|
throw noActionDefinedError("clientAction", route.id);
|
|
}
|
|
return fetchServerAction(singleFetch);
|
|
});
|
|
}
|
|
dataRoute.lazy = async () => {
|
|
let mod = await loadRouteModuleWithBlockingLinks(
|
|
route,
|
|
routeModulesCache
|
|
);
|
|
let lazyRoute = { ...mod };
|
|
if (mod.clientLoader) {
|
|
let clientLoader = mod.clientLoader;
|
|
lazyRoute.loader = (args, singleFetch) => clientLoader({
|
|
...args,
|
|
async serverLoader() {
|
|
preventInvalidServerHandlerCall("loader", route, isSpaMode);
|
|
return fetchServerLoader(singleFetch);
|
|
}
|
|
});
|
|
}
|
|
if (mod.clientAction) {
|
|
let clientAction = mod.clientAction;
|
|
lazyRoute.action = (args, singleFetch) => clientAction({
|
|
...args,
|
|
async serverAction() {
|
|
preventInvalidServerHandlerCall("action", route, isSpaMode);
|
|
return fetchServerAction(singleFetch);
|
|
}
|
|
});
|
|
}
|
|
return {
|
|
...lazyRoute.loader ? { loader: lazyRoute.loader } : {},
|
|
...lazyRoute.action ? { action: lazyRoute.action } : {},
|
|
hasErrorBoundary: lazyRoute.hasErrorBoundary,
|
|
shouldRevalidate: getShouldRevalidateFunction(
|
|
lazyRoute,
|
|
route.id,
|
|
needsRevalidation
|
|
),
|
|
handle: lazyRoute.handle,
|
|
// No need to wrap these in layout since the root route is never
|
|
// loaded via route.lazy()
|
|
Component: lazyRoute.Component,
|
|
ErrorBoundary: lazyRoute.ErrorBoundary
|
|
};
|
|
};
|
|
}
|
|
let children = createClientRoutes(
|
|
manifest,
|
|
routeModulesCache,
|
|
initialState,
|
|
isSpaMode,
|
|
route.id,
|
|
routesByParentId,
|
|
needsRevalidation
|
|
);
|
|
if (children.length > 0) dataRoute.children = children;
|
|
return dataRoute;
|
|
});
|
|
}
|
|
function getShouldRevalidateFunction(route, routeId, needsRevalidation) {
|
|
if (needsRevalidation) {
|
|
return wrapShouldRevalidateForHdr(
|
|
routeId,
|
|
route.shouldRevalidate,
|
|
needsRevalidation
|
|
);
|
|
}
|
|
if (route.shouldRevalidate) {
|
|
let fn = route.shouldRevalidate;
|
|
return (opts) => fn({ ...opts, defaultShouldRevalidate: true });
|
|
}
|
|
return route.shouldRevalidate;
|
|
}
|
|
function wrapShouldRevalidateForHdr(routeId, routeShouldRevalidate, needsRevalidation) {
|
|
let handledRevalidation = false;
|
|
return (arg) => {
|
|
if (!handledRevalidation) {
|
|
handledRevalidation = true;
|
|
return needsRevalidation.has(routeId);
|
|
}
|
|
return routeShouldRevalidate ? routeShouldRevalidate(arg) : arg.defaultShouldRevalidate;
|
|
};
|
|
}
|
|
async function loadRouteModuleWithBlockingLinks(route, routeModules) {
|
|
let routeModule = await loadRouteModule(route, routeModules);
|
|
await prefetchStyleLinks(route, routeModule);
|
|
return {
|
|
Component: getRouteModuleComponent(routeModule),
|
|
ErrorBoundary: routeModule.ErrorBoundary,
|
|
clientAction: routeModule.clientAction,
|
|
clientLoader: routeModule.clientLoader,
|
|
handle: routeModule.handle,
|
|
links: routeModule.links,
|
|
meta: routeModule.meta,
|
|
shouldRevalidate: routeModule.shouldRevalidate
|
|
};
|
|
}
|
|
function getRouteModuleComponent(routeModule) {
|
|
if (routeModule.default == null) return void 0;
|
|
let isEmptyObject = typeof routeModule.default === "object" && Object.keys(routeModule.default).length === 0;
|
|
if (!isEmptyObject) {
|
|
return routeModule.default;
|
|
}
|
|
}
|
|
function shouldHydrateRouteLoader(route, routeModule, isSpaMode) {
|
|
return isSpaMode && route.id !== "root" || routeModule.clientLoader != null && (routeModule.clientLoader.hydrate === true || route.hasLoader !== true);
|
|
}
|
|
|
|
// lib/dom/ssr/fog-of-war.ts
|
|
var nextPaths = /* @__PURE__ */ new Set();
|
|
var discoveredPathsMaxSize = 1e3;
|
|
var discoveredPaths = /* @__PURE__ */ new Set();
|
|
var URL_LIMIT = 7680;
|
|
function isFogOfWarEnabled(isSpaMode) {
|
|
return !isSpaMode;
|
|
}
|
|
function getPartialManifest(manifest, router2) {
|
|
let routeIds = new Set(router2.state.matches.map((m) => m.route.id));
|
|
let segments = router2.state.location.pathname.split("/").filter(Boolean);
|
|
let paths = ["/"];
|
|
segments.pop();
|
|
while (segments.length > 0) {
|
|
paths.push(`/${segments.join("/")}`);
|
|
segments.pop();
|
|
}
|
|
paths.forEach((path) => {
|
|
let matches = matchRoutes(router2.routes, path, router2.basename);
|
|
if (matches) {
|
|
matches.forEach((m) => routeIds.add(m.route.id));
|
|
}
|
|
});
|
|
let initialRoutes = [...routeIds].reduce(
|
|
(acc, id) => Object.assign(acc, { [id]: manifest.routes[id] }),
|
|
{}
|
|
);
|
|
return {
|
|
...manifest,
|
|
routes: initialRoutes
|
|
};
|
|
}
|
|
function getPatchRoutesOnNavigationFunction(manifest, routeModules, isSpaMode, basename) {
|
|
if (!isFogOfWarEnabled(isSpaMode)) {
|
|
return void 0;
|
|
}
|
|
return async ({ path, patch }) => {
|
|
if (discoveredPaths.has(path)) {
|
|
return;
|
|
}
|
|
await fetchAndApplyManifestPatches(
|
|
[path],
|
|
manifest,
|
|
routeModules,
|
|
isSpaMode,
|
|
basename,
|
|
patch
|
|
);
|
|
};
|
|
}
|
|
function useFogOFWarDiscovery(router2, manifest, routeModules, isSpaMode) {
|
|
React8.useEffect(() => {
|
|
if (!isFogOfWarEnabled(isSpaMode) || navigator.connection?.saveData === true) {
|
|
return;
|
|
}
|
|
function registerElement(el) {
|
|
let path = el.tagName === "FORM" ? el.getAttribute("action") : el.getAttribute("href");
|
|
if (!path) {
|
|
return;
|
|
}
|
|
let pathname = el.tagName === "A" ? el.pathname : new URL(path, window.location.origin).pathname;
|
|
if (!discoveredPaths.has(pathname)) {
|
|
nextPaths.add(pathname);
|
|
}
|
|
}
|
|
async function fetchPatches() {
|
|
document.querySelectorAll("a[data-discover], form[data-discover]").forEach(registerElement);
|
|
let lazyPaths = Array.from(nextPaths.keys()).filter((path) => {
|
|
if (discoveredPaths.has(path)) {
|
|
nextPaths.delete(path);
|
|
return false;
|
|
}
|
|
return true;
|
|
});
|
|
if (lazyPaths.length === 0) {
|
|
return;
|
|
}
|
|
try {
|
|
await fetchAndApplyManifestPatches(
|
|
lazyPaths,
|
|
manifest,
|
|
routeModules,
|
|
isSpaMode,
|
|
router2.basename,
|
|
router2.patchRoutes
|
|
);
|
|
} catch (e) {
|
|
console.error("Failed to fetch manifest patches", e);
|
|
}
|
|
}
|
|
let debouncedFetchPatches = debounce(fetchPatches, 100);
|
|
fetchPatches();
|
|
let observer = new MutationObserver(() => debouncedFetchPatches());
|
|
observer.observe(document.documentElement, {
|
|
subtree: true,
|
|
childList: true,
|
|
attributes: true,
|
|
attributeFilter: ["data-discover", "href", "action"]
|
|
});
|
|
return () => observer.disconnect();
|
|
}, [isSpaMode, manifest, routeModules, router2]);
|
|
}
|
|
async function fetchAndApplyManifestPatches(paths, manifest, routeModules, isSpaMode, basename, patchRoutes) {
|
|
let manifestPath = `${basename != null ? basename : "/"}/__manifest`.replace(
|
|
/\/+/g,
|
|
"/"
|
|
);
|
|
let url = new URL(manifestPath, window.location.origin);
|
|
paths.sort().forEach((path) => url.searchParams.append("p", path));
|
|
url.searchParams.set("version", manifest.version);
|
|
if (url.toString().length > URL_LIMIT) {
|
|
nextPaths.clear();
|
|
return;
|
|
}
|
|
let res = await fetch(url);
|
|
if (!res.ok) {
|
|
throw new Error(`${res.status} ${res.statusText}`);
|
|
} else if (res.status >= 400) {
|
|
throw new Error(await res.text());
|
|
}
|
|
let serverPatches = await res.json();
|
|
let knownRoutes = new Set(Object.keys(manifest.routes));
|
|
let patches = Object.values(serverPatches).reduce((acc, route) => {
|
|
if (route && !knownRoutes.has(route.id)) {
|
|
acc[route.id] = route;
|
|
}
|
|
return acc;
|
|
}, {});
|
|
Object.assign(manifest.routes, patches);
|
|
paths.forEach((p) => addToFifoQueue(p, discoveredPaths));
|
|
let parentIds = /* @__PURE__ */ new Set();
|
|
Object.values(patches).forEach((patch) => {
|
|
if (patch && (!patch.parentId || !patches[patch.parentId])) {
|
|
parentIds.add(patch.parentId);
|
|
}
|
|
});
|
|
parentIds.forEach(
|
|
(parentId) => patchRoutes(
|
|
parentId || null,
|
|
createClientRoutes(patches, routeModules, null, isSpaMode, parentId)
|
|
)
|
|
);
|
|
}
|
|
function addToFifoQueue(path, queue) {
|
|
if (queue.size >= discoveredPathsMaxSize) {
|
|
let first = queue.values().next().value;
|
|
queue.delete(first);
|
|
}
|
|
queue.add(path);
|
|
}
|
|
function debounce(callback, wait) {
|
|
let timeoutId;
|
|
return (...args) => {
|
|
window.clearTimeout(timeoutId);
|
|
timeoutId = window.setTimeout(() => callback(...args), wait);
|
|
};
|
|
}
|
|
|
|
// lib/dom/ssr/components.tsx
|
|
function useDataRouterContext() {
|
|
let context = React9.useContext(DataRouterContext);
|
|
invariant2(
|
|
context,
|
|
"You must render this element inside a <DataRouterContext.Provider> element"
|
|
);
|
|
return context;
|
|
}
|
|
function useDataRouterStateContext() {
|
|
let context = React9.useContext(DataRouterStateContext);
|
|
invariant2(
|
|
context,
|
|
"You must render this element inside a <DataRouterStateContext.Provider> element"
|
|
);
|
|
return context;
|
|
}
|
|
var FrameworkContext = React9.createContext(void 0);
|
|
FrameworkContext.displayName = "FrameworkContext";
|
|
function useFrameworkContext() {
|
|
let context = React9.useContext(FrameworkContext);
|
|
invariant2(
|
|
context,
|
|
"You must render this element inside a <HydratedRouter> element"
|
|
);
|
|
return context;
|
|
}
|
|
function getActiveMatches(matches, errors, isSpaMode) {
|
|
if (isSpaMode && !isHydrated) {
|
|
return [matches[0]];
|
|
}
|
|
if (errors) {
|
|
let errorIdx = matches.findIndex((m) => errors[m.route.id] !== void 0);
|
|
return matches.slice(0, errorIdx + 1);
|
|
}
|
|
return matches;
|
|
}
|
|
var isHydrated = false;
|
|
function Scripts(props) {
|
|
let { manifest, serverHandoffString, isSpaMode, renderMeta } = useFrameworkContext();
|
|
let { router: router2, static: isStatic, staticContext } = useDataRouterContext();
|
|
let { matches: routerMatches } = useDataRouterStateContext();
|
|
let enableFogOfWar = isFogOfWarEnabled(isSpaMode);
|
|
if (renderMeta) {
|
|
renderMeta.didRenderScripts = true;
|
|
}
|
|
let matches = getActiveMatches(routerMatches, null, isSpaMode);
|
|
React9.useEffect(() => {
|
|
isHydrated = true;
|
|
}, []);
|
|
let initialScripts = React9.useMemo(() => {
|
|
let streamScript = "window.__reactRouterContext.stream = new ReadableStream({start(controller){window.__reactRouterContext.streamController = controller;}}).pipeThrough(new TextEncoderStream());";
|
|
let contextScript = staticContext ? `window.__reactRouterContext = ${serverHandoffString};${streamScript}` : " ";
|
|
let routeModulesScript = !isStatic ? " " : `${manifest.hmr?.runtime ? `import ${JSON.stringify(manifest.hmr.runtime)};` : ""}${!enableFogOfWar ? `import ${JSON.stringify(manifest.url)}` : ""};
|
|
${matches.map(
|
|
(match, index) => `import * as route${index} from ${JSON.stringify(
|
|
manifest.routes[match.route.id].module
|
|
)};`
|
|
).join("\n")}
|
|
${enableFogOfWar ? (
|
|
// Inline a minimal manifest with the SSR matches
|
|
`window.__reactRouterManifest = ${JSON.stringify(
|
|
getPartialManifest(manifest, router2),
|
|
null,
|
|
2
|
|
)};`
|
|
) : ""}
|
|
window.__reactRouterRouteModules = {${matches.map((match, index) => `${JSON.stringify(match.route.id)}:route${index}`).join(",")}};
|
|
|
|
import(${JSON.stringify(manifest.entry.module)});`;
|
|
return /* @__PURE__ */ React9.createElement(React9.Fragment, null, /* @__PURE__ */ React9.createElement(
|
|
"script",
|
|
{
|
|
...props,
|
|
suppressHydrationWarning: true,
|
|
dangerouslySetInnerHTML: createHtml(contextScript),
|
|
type: void 0
|
|
}
|
|
), /* @__PURE__ */ React9.createElement(
|
|
"script",
|
|
{
|
|
...props,
|
|
suppressHydrationWarning: true,
|
|
dangerouslySetInnerHTML: createHtml(routeModulesScript),
|
|
type: "module",
|
|
async: true
|
|
}
|
|
));
|
|
}, []);
|
|
let routePreloads = matches.map((match) => {
|
|
let route = manifest.routes[match.route.id];
|
|
return route ? (route.imports || []).concat([route.module]) : [];
|
|
}).flat(1);
|
|
let preloads = isHydrated ? [] : manifest.entry.imports.concat(routePreloads);
|
|
return isHydrated ? null : /* @__PURE__ */ React9.createElement(React9.Fragment, null, !enableFogOfWar ? /* @__PURE__ */ React9.createElement(
|
|
"link",
|
|
{
|
|
rel: "modulepreload",
|
|
href: manifest.url,
|
|
crossOrigin: props.crossOrigin
|
|
}
|
|
) : null, /* @__PURE__ */ React9.createElement(
|
|
"link",
|
|
{
|
|
rel: "modulepreload",
|
|
href: manifest.entry.module,
|
|
crossOrigin: props.crossOrigin
|
|
}
|
|
), dedupe(preloads).map((path) => /* @__PURE__ */ React9.createElement(
|
|
"link",
|
|
{
|
|
key: path,
|
|
rel: "modulepreload",
|
|
href: path,
|
|
crossOrigin: props.crossOrigin
|
|
}
|
|
)), initialScripts);
|
|
}
|
|
function dedupe(array) {
|
|
return [...new Set(array)];
|
|
}
|
|
|
|
// lib/dom/ssr/errors.ts
|
|
function deserializeErrors(errors) {
|
|
if (!errors) return null;
|
|
let entries = Object.entries(errors);
|
|
let serialized = {};
|
|
for (let [key, val] of entries) {
|
|
if (val && val.__type === "RouteErrorResponse") {
|
|
serialized[key] = new ErrorResponseImpl(
|
|
val.status,
|
|
val.statusText,
|
|
val.data,
|
|
val.internal === true
|
|
);
|
|
} else if (val && val.__type === "Error") {
|
|
if (val.__subType) {
|
|
let ErrorConstructor = window[val.__subType];
|
|
if (typeof ErrorConstructor === "function") {
|
|
try {
|
|
let error = new ErrorConstructor(val.message);
|
|
error.stack = val.stack;
|
|
serialized[key] = error;
|
|
} catch (e) {
|
|
}
|
|
}
|
|
}
|
|
if (serialized[key] == null) {
|
|
let error = new Error(val.message);
|
|
error.stack = val.stack;
|
|
serialized[key] = error;
|
|
}
|
|
} else {
|
|
serialized[key] = val;
|
|
}
|
|
}
|
|
return serialized;
|
|
}
|
|
|
|
// lib/dom-export/dom-router-provider.tsx
|
|
function RouterProvider2(props) {
|
|
return /* @__PURE__ */ React10.createElement(RouterProvider, { flushSync: ReactDOM.flushSync, ...props });
|
|
}
|
|
|
|
// lib/dom-export/hydrated-router.tsx
|
|
var React11 = __toESM(require("react"));
|
|
var ssrInfo = null;
|
|
var router = null;
|
|
function initSsrInfo() {
|
|
if (!ssrInfo && window.__reactRouterContext && window.__reactRouterManifest && window.__reactRouterRouteModules) {
|
|
ssrInfo = {
|
|
context: window.__reactRouterContext,
|
|
manifest: window.__reactRouterManifest,
|
|
routeModules: window.__reactRouterRouteModules,
|
|
stateDecodingPromise: void 0,
|
|
router: void 0,
|
|
routerInitialized: false
|
|
};
|
|
}
|
|
}
|
|
function createHydratedRouter() {
|
|
initSsrInfo();
|
|
if (!ssrInfo) {
|
|
throw new Error(
|
|
"You must be using the SSR features of React Router in order to skip passing a `router` prop to `<RouterProvider>`"
|
|
);
|
|
}
|
|
let localSsrInfo = ssrInfo;
|
|
if (!ssrInfo.stateDecodingPromise) {
|
|
let stream = ssrInfo.context.stream;
|
|
invariant(stream, "No stream found for single fetch decoding");
|
|
ssrInfo.context.stream = void 0;
|
|
ssrInfo.stateDecodingPromise = decodeViaTurboStream(stream, window).then((value) => {
|
|
ssrInfo.context.state = value.value;
|
|
localSsrInfo.stateDecodingPromise.value = true;
|
|
}).catch((e) => {
|
|
localSsrInfo.stateDecodingPromise.error = e;
|
|
});
|
|
}
|
|
if (ssrInfo.stateDecodingPromise.error) {
|
|
throw ssrInfo.stateDecodingPromise.error;
|
|
}
|
|
if (!ssrInfo.stateDecodingPromise.value) {
|
|
throw ssrInfo.stateDecodingPromise;
|
|
}
|
|
let routes = createClientRoutes(
|
|
ssrInfo.manifest.routes,
|
|
ssrInfo.routeModules,
|
|
ssrInfo.context.state,
|
|
ssrInfo.context.isSpaMode
|
|
);
|
|
let hydrationData = void 0;
|
|
if (!ssrInfo.context.isSpaMode) {
|
|
hydrationData = {
|
|
...ssrInfo.context.state,
|
|
loaderData: { ...ssrInfo.context.state.loaderData }
|
|
};
|
|
let initialMatches = matchRoutes(
|
|
routes,
|
|
window.location,
|
|
window.__reactRouterContext?.basename
|
|
);
|
|
if (initialMatches) {
|
|
for (let match of initialMatches) {
|
|
let routeId = match.route.id;
|
|
let route = ssrInfo.routeModules[routeId];
|
|
let manifestRoute = ssrInfo.manifest.routes[routeId];
|
|
if (route && manifestRoute && shouldHydrateRouteLoader(
|
|
manifestRoute,
|
|
route,
|
|
ssrInfo.context.isSpaMode
|
|
) && (route.HydrateFallback || !manifestRoute.hasLoader)) {
|
|
delete hydrationData.loaderData[routeId];
|
|
} else if (manifestRoute && !manifestRoute.hasLoader) {
|
|
hydrationData.loaderData[routeId] = null;
|
|
}
|
|
}
|
|
}
|
|
if (hydrationData && hydrationData.errors) {
|
|
hydrationData.errors = deserializeErrors(hydrationData.errors);
|
|
}
|
|
}
|
|
let router2 = createRouter({
|
|
routes,
|
|
history: createBrowserHistory(),
|
|
basename: ssrInfo.context.basename,
|
|
hydrationData,
|
|
mapRouteProperties,
|
|
dataStrategy: getSingleFetchDataStrategy(
|
|
ssrInfo.manifest,
|
|
ssrInfo.routeModules,
|
|
() => router2
|
|
),
|
|
patchRoutesOnNavigation: getPatchRoutesOnNavigationFunction(
|
|
ssrInfo.manifest,
|
|
ssrInfo.routeModules,
|
|
ssrInfo.context.isSpaMode,
|
|
ssrInfo.context.basename
|
|
)
|
|
});
|
|
ssrInfo.router = router2;
|
|
if (router2.state.initialized) {
|
|
ssrInfo.routerInitialized = true;
|
|
router2.initialize();
|
|
}
|
|
router2.createRoutesForHMR = /* spacer so ts-ignore does not affect the right hand of the assignment */
|
|
createClientRoutesWithHMRRevalidationOptOut;
|
|
window.__reactRouterDataRouter = router2;
|
|
return router2;
|
|
}
|
|
function HydratedRouter() {
|
|
if (!router) {
|
|
router = createHydratedRouter();
|
|
}
|
|
let [criticalCss, setCriticalCss] = React11.useState(
|
|
process.env.NODE_ENV === "development" ? ssrInfo?.context.criticalCss : void 0
|
|
);
|
|
if (process.env.NODE_ENV === "development") {
|
|
if (ssrInfo) {
|
|
window.__reactRouterClearCriticalCss = () => setCriticalCss(void 0);
|
|
}
|
|
}
|
|
let [location, setLocation] = React11.useState(router.state.location);
|
|
React11.useLayoutEffect(() => {
|
|
if (ssrInfo && ssrInfo.router && !ssrInfo.routerInitialized) {
|
|
ssrInfo.routerInitialized = true;
|
|
ssrInfo.router.initialize();
|
|
}
|
|
}, []);
|
|
React11.useLayoutEffect(() => {
|
|
if (ssrInfo && ssrInfo.router) {
|
|
return ssrInfo.router.subscribe((newState) => {
|
|
if (newState.location !== location) {
|
|
setLocation(newState.location);
|
|
}
|
|
});
|
|
}
|
|
}, [location]);
|
|
invariant(ssrInfo, "ssrInfo unavailable for HydratedRouter");
|
|
useFogOFWarDiscovery(
|
|
router,
|
|
ssrInfo.manifest,
|
|
ssrInfo.routeModules,
|
|
ssrInfo.context.isSpaMode
|
|
);
|
|
return (
|
|
// This fragment is important to ensure we match the <ServerRouter> JSX
|
|
// structure so that useId values hydrate correctly
|
|
/* @__PURE__ */ React11.createElement(React11.Fragment, null, /* @__PURE__ */ React11.createElement(
|
|
FrameworkContext.Provider,
|
|
{
|
|
value: {
|
|
manifest: ssrInfo.manifest,
|
|
routeModules: ssrInfo.routeModules,
|
|
future: ssrInfo.context.future,
|
|
criticalCss,
|
|
isSpaMode: ssrInfo.context.isSpaMode
|
|
}
|
|
},
|
|
/* @__PURE__ */ React11.createElement(RemixErrorBoundary, { location }, /* @__PURE__ */ React11.createElement(RouterProvider2, { router }))
|
|
), /* @__PURE__ */ React11.createElement(React11.Fragment, null))
|
|
);
|
|
}
|
|
// Annotate the CommonJS export names for ESM import in node:
|
|
0 && (module.exports = {
|
|
HydratedRouter,
|
|
RouterProvider
|
|
});
|