neue Homepage auf react basis

This commit is contained in:
2026-08-07 21:39:30 +02:00
parent 164bdd19ad
commit ee89442c04
52191 changed files with 1230242 additions and 58 deletions
+119
View File
@@ -0,0 +1,119 @@
import { FormEncType, HTMLFormMethod } from "../router/utils.js";
import { RelativeRoutingType } from "../router/router.js";
//#region lib/dom/dom.d.ts
type ParamKeyValuePair = [string, string];
type URLSearchParamsInit = string | ParamKeyValuePair[] | Record<string, string | string[]> | URLSearchParams;
/**
* Creates a URLSearchParams object using the given initializer.
*
* This is identical to `new URLSearchParams(init)` except it also supports
* arrays as values in the object form of the initializer instead of just
* strings. This is convenient when you need multiple values for a given key,
* but don't want to use an array initializer.
*
* @example
* // Instead of:
* let searchParams = new URLSearchParams([
* ["sort", "name"],
* ["sort", "price"],
* ]);
*
* // You can do:
* let searchParams = createSearchParams({
* sort: ["name", "price"],
* });
*
* @public
* @category Utils
* @param init The value used to initialize the URL search parameters.
* @returns A URLSearchParams object containing the initialized search
* parameters.
*/
declare function createSearchParams(init?: URLSearchParamsInit): URLSearchParams;
type JsonObject = { [Key in string]: JsonValue } & { [Key in string]?: JsonValue | undefined };
type JsonArray = JsonValue[] | readonly JsonValue[];
type JsonPrimitive = string | number | boolean | null;
type JsonValue = JsonPrimitive | JsonObject | JsonArray;
type SubmitTarget = HTMLFormElement | HTMLButtonElement | HTMLInputElement | FormData | URLSearchParams | JsonValue | null;
/**
* Submit options shared by both navigations and fetchers
*/
interface SharedSubmitOptions {
/**
* The HTTP method used to submit the form. Overrides `<form method>`.
* Defaults to "GET".
*/
method?: HTMLFormMethod;
/**
* The action URL path used to submit the form. Overrides `<form action>`.
* Defaults to the path of the current route.
*/
action?: string;
/**
* The encoding used to submit the form. Overrides `<form encType>`.
* Defaults to "application/x-www-form-urlencoded".
*/
encType?: FormEncType;
/**
* Determines whether the form action is relative to the route hierarchy or
* the pathname. Use this if you want to opt out of navigating the route
* hierarchy and want to instead route based on /-delimited URL segments
*/
relative?: RelativeRoutingType;
/**
* In browser-based environments, prevent resetting scroll after this
* navigation when using the <ScrollRestoration> component
*/
preventScrollReset?: boolean;
/**
* Enable flushSync for this submission's state updates
*/
flushSync?: boolean;
/**
* Specify the default revalidation behavior after this submission
*
* If no `shouldRevalidate` functions are present on the active routes, then this
* value will be used directly. Otherwise it will be passed into `shouldRevalidate`
* so the route can make the final determination on revalidation. This can be
* useful when updating search params and you don't want to trigger a revalidation.
*
* By default (when not specified), loaders will revalidate according to the routers
* standard revalidation behavior.
*/
defaultShouldRevalidate?: boolean;
}
/**
* Submit options available to fetchers
*/
interface FetcherSubmitOptions extends SharedSubmitOptions {}
/**
* Submit options available to navigations
*/
interface SubmitOptions extends FetcherSubmitOptions {
/**
* Set `true` to replace the current entry in the browser's history stack
* instead of creating a new one (i.e. stay on "the same page"). Defaults
* to `false`.
*/
replace?: boolean;
/**
* State object to add to the history stack entry for this navigation
*/
state?: any;
/**
* Indicate a specific fetcherKey to use when using navigate=false
*/
fetcherKey?: string;
/**
* navigate=false will use a fetcher instead of a navigation
*/
navigate?: boolean;
/**
* Enable view transitions on this submission navigation
*/
viewTransition?: boolean;
}
//#endregion
export { FetcherSubmitOptions, ParamKeyValuePair, SubmitOptions, SubmitTarget, URLSearchParamsInit, createSearchParams };
+143
View File
@@ -0,0 +1,143 @@
/**
* react-router v8.3.0
*
* 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
*/
import { warning } from "../router/history.js";
import { stripBasename } from "../router/utils.js";
const defaultEncType = "application/x-www-form-urlencoded";
function isHtmlElement(object) {
return typeof HTMLElement !== "undefined" && object instanceof HTMLElement;
}
function isButtonElement(object) {
return isHtmlElement(object) && object.tagName.toLowerCase() === "button";
}
function isFormElement(object) {
return isHtmlElement(object) && object.tagName.toLowerCase() === "form";
}
function isInputElement(object) {
return isHtmlElement(object) && object.tagName.toLowerCase() === "input";
}
function isModifiedEvent(event) {
return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey);
}
function shouldProcessLinkClick(event, target) {
return event.button === 0 && (!target || target === "_self") && !isModifiedEvent(event);
}
/**
* Creates a URLSearchParams object using the given initializer.
*
* This is identical to `new URLSearchParams(init)` except it also supports
* arrays as values in the object form of the initializer instead of just
* strings. This is convenient when you need multiple values for a given key,
* but don't want to use an array initializer.
*
* @example
* // Instead of:
* let searchParams = new URLSearchParams([
* ["sort", "name"],
* ["sort", "price"],
* ]);
*
* // You can do:
* let searchParams = createSearchParams({
* sort: ["name", "price"],
* });
*
* @public
* @category Utils
* @param init The value used to initialize the URL search parameters.
* @returns A URLSearchParams object containing the initialized search
* parameters.
*/
function createSearchParams(init = "") {
return new URLSearchParams(typeof init === "string" || Array.isArray(init) || init instanceof URLSearchParams ? init : Object.keys(init).reduce((memo, key) => {
let value = init[key];
return memo.concat(Array.isArray(value) ? value.map((v) => [key, v]) : [[key, value]]);
}, []));
}
function getSearchParamsForLocation(locationSearch, defaultSearchParams) {
let searchParams = createSearchParams(locationSearch);
if (defaultSearchParams) defaultSearchParams.forEach((_, key) => {
if (!searchParams.has(key)) defaultSearchParams.getAll(key).forEach((value) => {
searchParams.append(key, value);
});
});
return searchParams;
}
let _formDataSupportsSubmitter = null;
function isFormDataSubmitterSupported() {
if (_formDataSupportsSubmitter === null) try {
new FormData(document.createElement("form"), 0);
_formDataSupportsSubmitter = false;
} catch (e) {
_formDataSupportsSubmitter = true;
}
return _formDataSupportsSubmitter;
}
const supportedFormEncTypes = new Set([
"application/x-www-form-urlencoded",
"multipart/form-data",
"text/plain"
]);
function getFormEncType(encType) {
if (encType != null && !supportedFormEncTypes.has(encType)) {
warning(false, `"${encType}" is not a valid \`encType\` for \`<Form>\`/\`<fetcher.Form>\` and will default to "${defaultEncType}"`);
return null;
}
return encType;
}
function getFormSubmissionInfo(target, basename) {
let method;
let action;
let encType;
let formData;
let body;
if (isFormElement(target)) {
let attr = target.getAttribute("action");
action = attr ? stripBasename(attr, basename) : null;
method = target.getAttribute("method") || "get";
encType = getFormEncType(target.getAttribute("enctype")) || defaultEncType;
formData = new FormData(target);
} else if (isButtonElement(target) || isInputElement(target) && (target.type === "submit" || target.type === "image")) {
let form = target.form;
if (form == null) throw new Error(`Cannot submit a <button> or <input type="submit"> without a <form>`);
let attr = target.getAttribute("formaction") || form.getAttribute("action");
action = attr ? stripBasename(attr, basename) : null;
method = target.getAttribute("formmethod") || form.getAttribute("method") || "get";
encType = getFormEncType(target.getAttribute("formenctype")) || getFormEncType(form.getAttribute("enctype")) || defaultEncType;
formData = new FormData(form, target);
if (!isFormDataSubmitterSupported()) {
let { name, type, value } = target;
if (type === "image") {
let prefix = name ? `${name}.` : "";
formData.append(`${prefix}x`, "0");
formData.append(`${prefix}y`, "0");
} else if (name) formData.append(name, value);
}
} else if (isHtmlElement(target)) throw new Error("Cannot submit element that is not <form>, <button>, or <input type=\"submit|image\">");
else {
method = "get";
action = null;
encType = defaultEncType;
body = target;
}
if (formData && encType === "text/plain") {
body = formData;
formData = void 0;
}
return {
action,
method: method.toLowerCase(),
encType,
formData,
body
};
}
//#endregion
export { createSearchParams, getFormSubmissionInfo, getSearchParamsForLocation, shouldProcessLinkClick };
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+138
View File
@@ -0,0 +1,138 @@
import { Location } from "../router/history.js";
import { DataRouteObject, RouteBranch, RouteObject } from "../router/utils.js";
import { FutureConfig, Router, StaticHandlerContext } from "../router/router.js";
import * as React$1 from "react";
//#region lib/dom/server.d.ts
/**
* @category Types
*/
interface StaticRouterProps {
/**
* The base URL for the static router (default: `/`)
*/
basename?: string;
/**
* The child elements to render inside the static router
*/
children?: React$1.ReactNode;
/**
* The {@link Location} to render the static router at (default: `/`)
*/
location: Partial<Location> | string;
}
/**
* A {@link Router | `<Router>`} that may not navigate to any other {@link Location}.
* This is useful on the server where there is no stateful UI.
*
* @public
* @category Declarative Routers
* @mode declarative
* @param props Props
* @param {StaticRouterProps.basename} props.basename n/a
* @param {StaticRouterProps.children} props.children n/a
* @param {StaticRouterProps.location} props.location n/a
* @returns A React element that renders the static {@link Router | `<Router>`}
*/
declare function StaticRouter({
basename,
children,
location: locationProp
}: StaticRouterProps): React$1.JSX.Element;
/**
* @category Types
*/
interface StaticRouterProviderProps {
/**
* The {@link StaticHandlerContext} returned from {@link StaticHandler}'s
* `query`
*/
context: StaticHandlerContext;
/**
* The static {@link DataRouter} from {@link createStaticRouter}
*/
router: Router;
/**
* Whether to hydrate the router on the client (default `true`)
*/
hydrate?: boolean;
/**
* The [`nonce`](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Global_attributes/nonce)
* to use for the hydration [`<script>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script)
* tag
*/
nonce?: string;
}
/**
* A {@link DataRouter} that may not navigate to any other {@link Location}.
* This is useful on the server where there is no stateful UI.
*
* @example
* export async function handleRequest(request: Request) {
* let { query, dataRoutes } = createStaticHandler(routes);
* let context = await query(request));
*
* if (context instanceof Response) {
* return context;
* }
*
* let router = createStaticRouter(dataRoutes, context);
* return new Response(
* ReactDOMServer.renderToString(<StaticRouterProvider ... />),
* { headers: { "Content-Type": "text/html" } }
* );
* }
*
* @public
* @category Data Routers
* @mode data
* @param props Props
* @param {StaticRouterProviderProps.context} props.context n/a
* @param {StaticRouterProviderProps.hydrate} props.hydrate n/a
* @param {StaticRouterProviderProps.nonce} props.nonce n/a
* @param {StaticRouterProviderProps.router} props.router n/a
* @returns A React element that renders the static router provider
*/
declare function StaticRouterProvider({
context,
router,
hydrate,
nonce
}: StaticRouterProviderProps): React$1.JSX.Element;
/**
* Create a static {@link DataRouter} for server-side rendering
*
* @example
* export async function handleRequest(request: Request) {
* let { query, dataRoutes } = createStaticHandler(routes);
* let context = await query(request);
*
* if (context instanceof Response) {
* return context;
* }
*
* let router = createStaticRouter(dataRoutes, context);
* return new Response(
* ReactDOMServer.renderToString(<StaticRouterProvider ... />),
* { headers: { "Content-Type": "text/html" } }
* );
* }
*
* @public
* @category Data Routers
* @mode data
* @param routes The route objects to create a static {@link DataRouter} for
* @param context The {@link StaticHandlerContext} returned from {@link StaticHandler}'s
* `query`
* @param opts Options
* @param opts.future Future flags for the static {@link DataRouter}
* @param opts.branches Optional pre-computed route branches
* @returns A static {@link DataRouter} that can be used to render the provided routes
*/
declare function createStaticRouter(routes: RouteObject[], context: StaticHandlerContext, opts?: {
branches?: RouteBranch<DataRouteObject>[];
future?: Partial<FutureConfig>;
}): Router;
//#endregion
export { StaticRouter, StaticRouterProps, StaticRouterProvider, StaticRouterProviderProps, createStaticRouter };
+301
View File
@@ -0,0 +1,301 @@
/**
* react-router v8.3.0
*
* 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
*/
import { ABSOLUTE_URL_REGEX } from "../router/url.js";
import { createPath, invariant, parsePath } from "../router/history.js";
import { convertRoutesToDataRoutes, isRouteErrorResponse } from "../router/utils.js";
import { IDLE_BLOCKER, IDLE_FETCHER, IDLE_NAVIGATION } from "../router/router.js";
import { DataRouterContext, DataRouterStateContext, FetchersContext, ViewTransitionContext } from "../context.js";
import { DataRoutes, Router } from "../components.js";
import { escapeHtml } from "./ssr/markup.js";
import * as React$1 from "react";
//#region lib/dom/server.tsx
/**
* A {@link Router | `<Router>`} that may not navigate to any other {@link Location}.
* This is useful on the server where there is no stateful UI.
*
* @public
* @category Declarative Routers
* @mode declarative
* @param props Props
* @param {StaticRouterProps.basename} props.basename n/a
* @param {StaticRouterProps.children} props.children n/a
* @param {StaticRouterProps.location} props.location n/a
* @returns A React element that renders the static {@link Router | `<Router>`}
*/
function StaticRouter({ basename, children, location: locationProp = "/" }) {
if (typeof locationProp === "string") locationProp = parsePath(locationProp);
let action = "POP";
let location = {
pathname: locationProp.pathname || "/",
search: locationProp.search || "",
hash: locationProp.hash || "",
state: locationProp.state != null ? locationProp.state : null,
key: locationProp.key || "default",
mask: void 0
};
let staticNavigator = getStatelessNavigator();
return /* @__PURE__ */ React$1.createElement(Router, {
basename,
children,
location,
navigationType: action,
navigator: staticNavigator,
static: true,
useTransitions: false
});
}
/**
* A {@link DataRouter} that may not navigate to any other {@link Location}.
* This is useful on the server where there is no stateful UI.
*
* @example
* export async function handleRequest(request: Request) {
* let { query, dataRoutes } = createStaticHandler(routes);
* let context = await query(request));
*
* if (context instanceof Response) {
* return context;
* }
*
* let router = createStaticRouter(dataRoutes, context);
* return new Response(
* ReactDOMServer.renderToString(<StaticRouterProvider ... />),
* { headers: { "Content-Type": "text/html" } }
* );
* }
*
* @public
* @category Data Routers
* @mode data
* @param props Props
* @param {StaticRouterProviderProps.context} props.context n/a
* @param {StaticRouterProviderProps.hydrate} props.hydrate n/a
* @param {StaticRouterProviderProps.nonce} props.nonce n/a
* @param {StaticRouterProviderProps.router} props.router n/a
* @returns A React element that renders the static router provider
*/
function StaticRouterProvider({ context, router, hydrate = true, nonce }) {
invariant(router && context, "You must provide `router` and `context` to <StaticRouterProvider>");
let dataRouterContext = {
router,
navigator: getStatelessNavigator(),
static: true,
staticContext: context,
basename: context.basename || "/"
};
let fetchersContext = /* @__PURE__ */ new Map();
let hydrateScript = "";
if (hydrate !== false) {
let data = {
loaderData: context.loaderData,
actionData: context.actionData,
errors: serializeErrors(context.errors)
};
hydrateScript = `window.__staticRouterHydrationData = JSON.parse(${escapeHtml(JSON.stringify(JSON.stringify(data)))});`;
}
let { state } = dataRouterContext.router;
return /* @__PURE__ */ React$1.createElement(React$1.Fragment, null, /* @__PURE__ */ React$1.createElement(DataRouterContext.Provider, { value: dataRouterContext }, /* @__PURE__ */ React$1.createElement(DataRouterStateContext.Provider, { value: state }, /* @__PURE__ */ React$1.createElement(FetchersContext.Provider, { value: fetchersContext }, /* @__PURE__ */ React$1.createElement(ViewTransitionContext.Provider, { value: { isTransitioning: false } }, /* @__PURE__ */ React$1.createElement(Router, {
basename: dataRouterContext.basename,
location: state.location,
navigationType: state.historyAction,
navigator: dataRouterContext.navigator,
static: dataRouterContext.static,
useTransitions: false
}, /* @__PURE__ */ React$1.createElement(DataRoutes, {
manifest: router.manifest,
routes: router.routes,
future: router.future,
state,
isStatic: true
})))))), hydrateScript ? /* @__PURE__ */ React$1.createElement("script", {
suppressHydrationWarning: true,
nonce,
dangerouslySetInnerHTML: { __html: hydrateScript }
}) : null);
}
function serializeErrors(errors) {
if (!errors) return null;
let entries = Object.entries(errors);
let serialized = {};
for (let [key, val] of entries) if (isRouteErrorResponse(val)) serialized[key] = {
...val,
__type: "RouteErrorResponse"
};
else if (val instanceof Error) serialized[key] = {
message: val.message,
__type: "Error",
...val.name !== "Error" ? { __subType: val.name } : {}
};
else serialized[key] = val;
return serialized;
}
function getStatelessNavigator() {
return {
createHref,
encodeLocation,
push(to) {
throw new Error(`You cannot use navigator.push() on the server because it is a stateless environment. This error was probably triggered when you did a \`navigate(${JSON.stringify(to)})\` somewhere in your app.`);
},
replace(to) {
throw new Error(`You cannot use navigator.replace() on the server because it is a stateless environment. This error was probably triggered when you did a \`navigate(${JSON.stringify(to)}, { replace: true })\` somewhere in your app.`);
},
go(delta) {
throw new Error(`You cannot use navigator.go() on the server because it is a stateless environment. This error was probably triggered when you did a \`navigate(${delta})\` somewhere in your app.`);
},
back() {
throw new Error("You cannot use navigator.back() on the server because it is a stateless environment.");
},
forward() {
throw new Error("You cannot use navigator.forward() on the server because it is a stateless environment.");
}
};
}
/**
* Create a static {@link DataRouter} for server-side rendering
*
* @example
* export async function handleRequest(request: Request) {
* let { query, dataRoutes } = createStaticHandler(routes);
* let context = await query(request);
*
* if (context instanceof Response) {
* return context;
* }
*
* let router = createStaticRouter(dataRoutes, context);
* return new Response(
* ReactDOMServer.renderToString(<StaticRouterProvider ... />),
* { headers: { "Content-Type": "text/html" } }
* );
* }
*
* @public
* @category Data Routers
* @mode data
* @param routes The route objects to create a static {@link DataRouter} for
* @param context The {@link StaticHandlerContext} returned from {@link StaticHandler}'s
* `query`
* @param opts Options
* @param opts.future Future flags for the static {@link DataRouter}
* @param opts.branches Optional pre-computed route branches
* @returns A static {@link DataRouter} that can be used to render the provided routes
*/
function createStaticRouter(routes, context, opts = {}) {
let manifest = {};
let dataRoutes = convertRoutesToDataRoutes(routes, void 0, void 0, manifest);
let matches = context.matches.map((match) => {
let route = manifest[match.route.id] || match.route;
return {
...match,
route
};
});
let msg = (method) => `You cannot use router.${method}() on the server because it is a stateless environment`;
return {
get basename() {
return context.basename;
},
get future() {
return { ...opts?.future };
},
get state() {
return {
historyAction: "POP",
location: context.location,
matches,
loaderData: context.loaderData,
actionData: context.actionData,
errors: context.errors,
initialized: true,
renderFallback: false,
navigation: IDLE_NAVIGATION,
restoreScrollPosition: null,
preventScrollReset: false,
revalidation: "idle",
fetchers: /* @__PURE__ */ new Map(),
blockers: /* @__PURE__ */ new Map()
};
},
get routes() {
return dataRoutes;
},
get branches() {
return opts.branches;
},
get manifest() {
return manifest;
},
get window() {},
initialize() {
throw msg("initialize");
},
subscribe() {
throw msg("subscribe");
},
enableScrollRestoration() {
throw msg("enableScrollRestoration");
},
navigate() {
throw msg("navigate");
},
fetch() {
throw msg("fetch");
},
revalidate() {
throw msg("revalidate");
},
createHref,
encodeLocation,
getFetcher() {
return IDLE_FETCHER;
},
deleteFetcher() {
throw msg("deleteFetcher");
},
resetFetcher() {
throw msg("resetFetcher");
},
dispose() {
throw msg("dispose");
},
getBlocker() {
return IDLE_BLOCKER;
},
deleteBlocker() {
throw msg("deleteBlocker");
},
patchRoutes() {
throw msg("patchRoutes");
},
_internalFetchControllers: /* @__PURE__ */ new Map(),
_internalSetRoutes() {
throw msg("_internalSetRoutes");
},
_internalSetStateDoNotUseOrYouWillBreakYourApp() {
throw msg("_internalSetStateDoNotUseOrYouWillBreakYourApp");
}
};
}
function createHref(to) {
return typeof to === "string" ? to : createPath(to);
}
function encodeLocation(to) {
let href = typeof to === "string" ? to : createPath(to);
href = href.replace(/ $/, "%20");
let encoded = ABSOLUTE_URL_REGEX.test(href) ? new URL(href) : new URL(href, "http://localhost");
return {
pathname: encoded.pathname,
search: encoded.search,
hash: encoded.hash
};
}
//#endregion
export { StaticRouter, StaticRouterProvider, createStaticRouter };
@@ -0,0 +1,198 @@
import { PageLinkDescriptor } from "../../router/links.js";
import { FrameworkContextObject } from "./entry.js";
import * as React$1 from "react";
//#region lib/dom/ssr/components.d.ts
declare const FrameworkContext: React$1.Context<FrameworkContextObject | undefined>;
/**
* Defines the [lazy route discovery](../../explanation/lazy-route-discovery)
* behavior of the link/form:
*
* - "render" - default, discover the route when the link renders
* - "none" - don't eagerly discover, only discover if the link is clicked
*/
type DiscoverBehavior = "render" | "none";
/**
* Defines the prefetching behavior of the link:
*
* - "none": Never fetched
* - "intent": Fetched when the user focuses or hovers the link
* - "render": Fetched when the link is rendered
* - "viewport": Fetched when the link is in the viewport
*/
type PrefetchBehavior = "intent" | "render" | "none" | "viewport";
/**
* Props for the {@link Links} component.
*
* @category Types
*/
interface LinksProps {
/**
* A [`nonce`](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Global_attributes/nonce)
* attribute to render on the [`<link>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link)
* element. If not provided in Framework Mode, it will default to any
* {@link ServerRouter | `<ServerRouter nonce>`} prop.
*/
nonce?: string | undefined;
/**
* A [`crossOrigin`](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/crossorigin)
* attribute to render on the [`<link>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link)
* element
*/
crossOrigin?: "anonymous" | "use-credentials";
}
/**
* Renders all the [`<link>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link)
* tags created by the route module's [`links`](../../start/framework/route-module#links)
* export. You should render it inside the [`<head>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/head)
* of your document.
*
* @example
* import { Links } from "react-router";
*
* export default function Root() {
* return (
* <html>
* <head>
* <Links />
* </head>
* <body></body>
* </html>
* );
* }
*
* @public
* @category Components
* @mode framework
* @param props Props
* @param {LinksProps.nonce} props.nonce n/a
* @param {LinksProps.crossOrigin} props.crossOrigin n/a
* @returns A collection of React elements for [`<link>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link)
* tags
*/
declare function Links({
nonce,
crossOrigin
}: LinksProps): React$1.JSX.Element;
/**
* Renders [`<link rel=prefetch|modulepreload>`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLinkElement/rel)
* tags for modules and data of another page to enable an instant navigation to
* that page. [`<Link prefetch>`](./Link#prefetch) uses this internally, but you
* can render it to prefetch a page for any other reason.
*
* For example, you may render one of this as the user types into a search field
* to prefetch search results before they click through to their selection.
*
* @example
* import { PrefetchPageLinks } from "react-router";
*
* <PrefetchPageLinks page="/absolute/path" />
*
* @public
* @category Components
* @mode framework
* @param props Props
* @param {PageLinkDescriptor.page} props.page n/a
* @param props.linkProps Additional props to spread onto the [`<link>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link)
* tags, such as [`crossOrigin`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLinkElement/crossOrigin),
* [`integrity`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLinkElement/integrity),
* [`rel`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLinkElement/rel),
* etc.
* @returns A collection of React elements for [`<link>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link)
* tags
*/
declare function PrefetchPageLinks({
page,
...linkProps
}: PageLinkDescriptor): React$1.JSX.Element | null;
/**
* Renders all the [`<meta>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meta)
* tags created by the route module's [`meta`](../../start/framework/route-module#meta)
* export. You should render it inside the [`<head>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/head)
* of your document.
*
* @example
* import { Meta } from "react-router";
*
* export default function Root() {
* return (
* <html>
* <head>
* <Meta />
* </head>
* </html>
* );
* }
*
* @public
* @category Components
* @mode framework
* @returns A collection of React elements for [`<meta>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meta)
* tags
*/
declare function Meta(): React$1.JSX.Element;
/**
* A couple common attributes:
*
* - `<Scripts crossOrigin>` for hosting your static assets on a different
* server than your app.
* - `<Scripts nonce>` to support a [content security policy for scripts](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src)
* with [nonce-sources](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/Sources#sources)
* for your [`<script>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script)
* tags.
*
* You cannot pass through attributes such as [`async`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLScriptElement/async),
* [`defer`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLScriptElement/defer),
* [`noModule`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLScriptElement/noModule),
* [`src`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLScriptElement/src),
* or [`type`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLScriptElement/type),
* because they are managed by React Router internally.
*
* @category Types
*/
type ScriptsProps = Omit<React$1.HTMLProps<HTMLScriptElement>, "async" | "children" | "dangerouslySetInnerHTML" | "defer" | "noModule" | "src" | "suppressHydrationWarning" | "type"> & {
/**
* A [`nonce`](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Global_attributes/nonce)
* attribute to render on the [`<script>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script)
* element. If not provided in Framework Mode, it will default to any
* {@link ServerRouter | `<ServerRouter nonce>`} prop.
*/
nonce?: string | undefined;
};
/**
* Renders the client runtime of your app. It should be rendered inside the
* [`<body>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/body)
* of the document.
*
* If server rendering, you can omit `<Scripts/>` and the app will work as a
* traditional web app without JavaScript, relying solely on HTML and browser
* behaviors.
*
* @example
* import { Scripts } from "react-router";
*
* export default function Root() {
* return (
* <html>
* <head />
* <body>
* <Scripts />
* </body>
* </html>
* );
* }
*
* @public
* @category Components
* @mode framework
* @param scriptProps Additional props to spread onto the [`<script>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script)
* tags, such as [`crossOrigin`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLScriptElement/crossOrigin),
* [`nonce`](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Global_attributes/nonce),
* etc.
* @returns A collection of React elements for [`<script>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script)
* tags
*/
declare function Scripts(scriptProps: ScriptsProps): React$1.JSX.Element | null;
//#endregion
export { DiscoverBehavior, FrameworkContext, Links, LinksProps, Meta, PrefetchBehavior, PrefetchPageLinks, Scripts, ScriptsProps };
@@ -0,0 +1,589 @@
/**
* react-router v8.3.0
*
* 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
*/
import { matchRoutes } from "../../router/utils.js";
import { DataRouterContext, DataRouterStateContext, useIsRSCRouterContext } from "../../context.js";
import { useLocation } from "../../hooks.js";
import { warnOnce } from "../../server-runtime/warnings.js";
import invariant from "./invariant.js";
import { getKeyedLinksForMatches, getKeyedPrefetchLinks, getModuleLinkHrefs, getNewMatchesForLinks, isPageLinkDescriptor } from "./links.js";
import { escapeHtml } from "./markup.js";
import { singleFetchUrl } from "./single-fetch.js";
import { getPartialManifest, isFogOfWarEnabled } from "./fog-of-war.js";
import * as React$1 from "react";
//#region lib/dom/ssr/components.tsx
function useDataRouterContext() {
let context = React$1.useContext(DataRouterContext);
invariant(context, "You must render this element inside a <DataRouterContext.Provider> element");
return context;
}
function useDataRouterStateContext() {
let context = React$1.useContext(DataRouterStateContext);
invariant(context, "You must render this element inside a <DataRouterStateContext.Provider> element");
return context;
}
const FrameworkContext = React$1.createContext(void 0);
FrameworkContext.displayName = "FrameworkContext";
function useFrameworkContext() {
let context = React$1.useContext(FrameworkContext);
invariant(context, "You must render this element inside a <HydratedRouter> element");
return context;
}
function usePrefetchBehavior(prefetch, theirElementProps) {
let frameworkContext = React$1.useContext(FrameworkContext);
let [maybePrefetch, setMaybePrefetch] = React$1.useState(false);
let [shouldPrefetch, setShouldPrefetch] = React$1.useState(false);
let { onFocus, onBlur, onMouseEnter, onMouseLeave, onTouchStart } = theirElementProps;
let ref = React$1.useRef(null);
React$1.useEffect(() => {
if (prefetch === "render") setShouldPrefetch(true);
if (prefetch === "viewport") {
let callback = (entries) => {
entries.forEach((entry) => {
setShouldPrefetch(entry.isIntersecting);
});
};
let observer = new IntersectionObserver(callback, { threshold: .5 });
if (ref.current) observer.observe(ref.current);
return () => {
observer.disconnect();
};
}
}, [prefetch]);
React$1.useEffect(() => {
if (maybePrefetch) {
let id = setTimeout(() => {
setShouldPrefetch(true);
}, 100);
return () => {
clearTimeout(id);
};
}
}, [maybePrefetch]);
let setIntent = () => {
setMaybePrefetch(true);
};
let cancelIntent = () => {
setMaybePrefetch(false);
setShouldPrefetch(false);
};
if (!frameworkContext) return [
false,
ref,
{}
];
if (prefetch !== "intent") return [
shouldPrefetch,
ref,
{}
];
return [
shouldPrefetch,
ref,
{
onFocus: composeEventHandlers(onFocus, setIntent),
onBlur: composeEventHandlers(onBlur, cancelIntent),
onMouseEnter: composeEventHandlers(onMouseEnter, setIntent),
onMouseLeave: composeEventHandlers(onMouseLeave, cancelIntent),
onTouchStart: composeEventHandlers(onTouchStart, setIntent)
}
];
}
function composeEventHandlers(theirHandler, ourHandler) {
return (event) => {
theirHandler && theirHandler(event);
if (!event.defaultPrevented) ourHandler(event);
};
}
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;
}
const CRITICAL_CSS_DATA_ATTRIBUTE = "data-react-router-critical-css";
/**
* Renders all the [`<link>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link)
* tags created by the route module's [`links`](../../start/framework/route-module#links)
* export. You should render it inside the [`<head>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/head)
* of your document.
*
* @example
* import { Links } from "react-router";
*
* export default function Root() {
* return (
* <html>
* <head>
* <Links />
* </head>
* <body></body>
* </html>
* );
* }
*
* @public
* @category Components
* @mode framework
* @param props Props
* @param {LinksProps.nonce} props.nonce n/a
* @param {LinksProps.crossOrigin} props.crossOrigin n/a
* @returns A collection of React elements for [`<link>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link)
* tags
*/
function Links({ nonce, crossOrigin }) {
let { isSpaMode, manifest, routeModules, criticalCss, nonce: contextNonce } = useFrameworkContext();
let { errors, matches: routerMatches } = useDataRouterStateContext();
let matches = getActiveMatches(routerMatches, errors, isSpaMode);
let keyedLinks = React$1.useMemo(() => getKeyedLinksForMatches(matches, routeModules, manifest), [
matches,
routeModules,
manifest
]);
if (nonce == null && contextNonce) nonce = contextNonce;
return /* @__PURE__ */ React$1.createElement(React$1.Fragment, null, typeof criticalCss === "string" ? /* @__PURE__ */ React$1.createElement("style", {
[CRITICAL_CSS_DATA_ATTRIBUTE]: "",
nonce,
dangerouslySetInnerHTML: { __html: criticalCss }
}) : null, typeof criticalCss === "object" ? /* @__PURE__ */ React$1.createElement("link", {
[CRITICAL_CSS_DATA_ATTRIBUTE]: "",
rel: "stylesheet",
href: criticalCss.href,
nonce,
crossOrigin
}) : null, keyedLinks.map(({ key, link }) => isPageLinkDescriptor(link) ? /* @__PURE__ */ React$1.createElement(PrefetchPageLinks, {
key,
nonce,
...link,
crossOrigin: link.crossOrigin ?? crossOrigin
}) : /* @__PURE__ */ React$1.createElement("link", {
key,
nonce,
...link,
crossOrigin: link.crossOrigin ?? crossOrigin
})));
}
/**
* Renders [`<link rel=prefetch|modulepreload>`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLinkElement/rel)
* tags for modules and data of another page to enable an instant navigation to
* that page. [`<Link prefetch>`](./Link#prefetch) uses this internally, but you
* can render it to prefetch a page for any other reason.
*
* For example, you may render one of this as the user types into a search field
* to prefetch search results before they click through to their selection.
*
* @example
* import { PrefetchPageLinks } from "react-router";
*
* <PrefetchPageLinks page="/absolute/path" />
*
* @public
* @category Components
* @mode framework
* @param props Props
* @param {PageLinkDescriptor.page} props.page n/a
* @param props.linkProps Additional props to spread onto the [`<link>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link)
* tags, such as [`crossOrigin`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLinkElement/crossOrigin),
* [`integrity`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLinkElement/integrity),
* [`rel`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLinkElement/rel),
* etc.
* @returns A collection of React elements for [`<link>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link)
* tags
*/
function PrefetchPageLinks({ page, ...linkProps }) {
let rsc = useIsRSCRouterContext();
let { nonce: contextNonce } = useFrameworkContext();
let { router } = useDataRouterContext();
let matches = React$1.useMemo(() => matchRoutes(router.routes, page, router.basename), [
router.routes,
page,
router.basename
]);
if (!matches) return null;
if (linkProps.nonce == null && contextNonce) linkProps = {
...linkProps,
nonce: contextNonce
};
if (rsc) return /* @__PURE__ */ React$1.createElement(RSCPrefetchPageLinksImpl, {
page,
matches,
...linkProps
});
return /* @__PURE__ */ React$1.createElement(PrefetchPageLinksImpl, {
page,
matches,
...linkProps
});
}
function useKeyedPrefetchLinks(matches) {
let { manifest, routeModules } = useFrameworkContext();
let [keyedPrefetchLinks, setKeyedPrefetchLinks] = React$1.useState([]);
React$1.useEffect(() => {
let interrupted = false;
getKeyedPrefetchLinks(matches, manifest, routeModules).then((links) => {
if (!interrupted) setKeyedPrefetchLinks(links);
});
return () => {
interrupted = true;
};
}, [
matches,
manifest,
routeModules
]);
return keyedPrefetchLinks;
}
function RSCPrefetchPageLinksImpl({ page, matches: nextMatches, ...linkProps }) {
let location = useLocation();
let dataHrefs = React$1.useMemo(() => {
if (page === location.pathname + location.search + location.hash) return [];
let url = singleFetchUrl(page, "rsc");
let hasSomeRoutesWithShouldRevalidate = false;
let targetRoutes = [];
for (let match of nextMatches) if (typeof match.route.shouldRevalidate === "function") hasSomeRoutesWithShouldRevalidate = true;
else targetRoutes.push(match.route.id);
if (hasSomeRoutesWithShouldRevalidate && targetRoutes.length > 0) url.searchParams.set("_routes", targetRoutes.join(","));
return [url.pathname + url.search];
}, [
page,
location,
nextMatches
]);
return /* @__PURE__ */ React$1.createElement(React$1.Fragment, null, dataHrefs.map((href) => /* @__PURE__ */ React$1.createElement("link", {
key: href,
rel: "prefetch",
as: "fetch",
href,
...linkProps
})));
}
function PrefetchPageLinksImpl({ page, matches: nextMatches, ...linkProps }) {
let location = useLocation();
let { manifest, routeModules } = useFrameworkContext();
let { loaderData, matches } = useDataRouterStateContext();
let newMatchesForData = React$1.useMemo(() => getNewMatchesForLinks(page, nextMatches, matches, manifest, location, "data"), [
page,
nextMatches,
matches,
manifest,
location
]);
let newMatchesForAssets = React$1.useMemo(() => getNewMatchesForLinks(page, nextMatches, matches, manifest, location, "assets"), [
page,
nextMatches,
matches,
manifest,
location
]);
let dataHrefs = React$1.useMemo(() => {
if (page === location.pathname + location.search + location.hash) return [];
let routesParams = /* @__PURE__ */ new Set();
let foundOptOutRoute = false;
nextMatches.forEach((m) => {
let manifestRoute = manifest.routes[m.route.id];
if (!manifestRoute || !manifestRoute.hasLoader) return;
if (!newMatchesForData.some((m2) => m2.route.id === m.route.id) && m.route.id in loaderData && routeModules[m.route.id]?.shouldRevalidate) foundOptOutRoute = true;
else if (manifestRoute.hasClientLoader) foundOptOutRoute = true;
else routesParams.add(m.route.id);
});
if (routesParams.size === 0) return [];
let url = singleFetchUrl(page, "data");
if (foundOptOutRoute && routesParams.size > 0) url.searchParams.set("_routes", nextMatches.filter((m) => routesParams.has(m.route.id)).map((m) => m.route.id).join(","));
return [url.pathname + url.search];
}, [
loaderData,
location,
manifest,
newMatchesForData,
nextMatches,
page,
routeModules
]);
let moduleHrefs = React$1.useMemo(() => getModuleLinkHrefs(newMatchesForAssets, manifest), [newMatchesForAssets, manifest]);
let keyedPrefetchLinks = useKeyedPrefetchLinks(newMatchesForAssets);
return /* @__PURE__ */ React$1.createElement(React$1.Fragment, null, dataHrefs.map((href) => /* @__PURE__ */ React$1.createElement("link", {
key: href,
rel: "prefetch",
as: "fetch",
href,
...linkProps
})), moduleHrefs.map((href) => /* @__PURE__ */ React$1.createElement("link", {
key: href,
rel: "modulepreload",
href,
...linkProps
})), keyedPrefetchLinks.map(({ key, link }) => /* @__PURE__ */ React$1.createElement("link", {
key,
nonce: linkProps.nonce,
...link,
crossOrigin: link.crossOrigin ?? linkProps.crossOrigin
})));
}
/**
* Renders all the [`<meta>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meta)
* tags created by the route module's [`meta`](../../start/framework/route-module#meta)
* export. You should render it inside the [`<head>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/head)
* of your document.
*
* @example
* import { Meta } from "react-router";
*
* export default function Root() {
* return (
* <html>
* <head>
* <Meta />
* </head>
* </html>
* );
* }
*
* @public
* @category Components
* @mode framework
* @returns A collection of React elements for [`<meta>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meta)
* tags
*/
function Meta() {
let { isSpaMode, routeModules } = useFrameworkContext();
let { errors, matches: routerMatches, loaderData } = useDataRouterStateContext();
let location = useLocation();
let _matches = getActiveMatches(routerMatches, errors, isSpaMode);
let error = null;
if (errors) error = errors[_matches[_matches.length - 1].route.id];
let meta = [];
let leafMeta = null;
let matches = [];
for (let i = 0; i < _matches.length; i++) {
let _match = _matches[i];
let routeId = _match.route.id;
let data = loaderData[routeId];
let params = _match.params;
let routeModule = routeModules[routeId];
let routeMeta = [];
let match = {
id: routeId,
loaderData: data,
meta: [],
params: _match.params,
pathname: _match.pathname,
handle: _match.route.handle,
error
};
matches[i] = match;
if (routeModule?.meta) routeMeta = typeof routeModule.meta === "function" ? routeModule.meta({
loaderData: data,
params,
location,
matches,
error
}) : Array.isArray(routeModule.meta) ? [...routeModule.meta] : routeModule.meta;
else if (leafMeta) routeMeta = [...leafMeta];
routeMeta = routeMeta || [];
if (!Array.isArray(routeMeta)) throw new Error("The route at " + _match.route.path + " returns an invalid value. All route meta functions must return an array of meta objects.\n\nTo reference the meta function API, see https://reactrouter.com/start/framework/route-module#meta");
match.meta = routeMeta;
matches[i] = match;
meta = [...routeMeta];
leafMeta = meta;
}
return /* @__PURE__ */ React$1.createElement(React$1.Fragment, null, meta.flat().map((metaProps) => {
if (!metaProps) return null;
if ("tagName" in metaProps) {
let { tagName, ...rest } = metaProps;
if (!isValidMetaTag(tagName)) {
console.warn(`A meta object uses an invalid tagName: ${tagName}. Expected either 'link' or 'meta'`);
return null;
}
let Comp = tagName;
return /* @__PURE__ */ React$1.createElement(Comp, {
key: JSON.stringify(rest),
...rest
});
}
if ("title" in metaProps) return /* @__PURE__ */ React$1.createElement("title", { key: "title" }, String(metaProps.title));
if ("charset" in metaProps) {
metaProps.charSet ??= metaProps.charset;
delete metaProps.charset;
}
if ("charSet" in metaProps && metaProps.charSet != null) return typeof metaProps.charSet === "string" ? /* @__PURE__ */ React$1.createElement("meta", {
key: "charSet",
charSet: metaProps.charSet
}) : null;
if ("script:ld+json" in metaProps) try {
let json = JSON.stringify(metaProps["script:ld+json"]);
return /* @__PURE__ */ React$1.createElement("script", {
key: `script:ld+json:${json}`,
type: "application/ld+json",
dangerouslySetInnerHTML: { __html: escapeHtml(json) }
});
} catch (e) {
return null;
}
return /* @__PURE__ */ React$1.createElement("meta", {
key: JSON.stringify(metaProps),
...metaProps
});
}));
}
function isValidMetaTag(tagName) {
return typeof tagName === "string" && /^(meta|link)$/.test(tagName);
}
/**
* Tracks whether hydration is finished, so scripts can be skipped
* during client-side updates.
*/
let isHydrated = false;
function setIsHydrated() {
isHydrated = true;
}
/**
* Renders the client runtime of your app. It should be rendered inside the
* [`<body>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/body)
* of the document.
*
* If server rendering, you can omit `<Scripts/>` and the app will work as a
* traditional web app without JavaScript, relying solely on HTML and browser
* behaviors.
*
* @example
* import { Scripts } from "react-router";
*
* export default function Root() {
* return (
* <html>
* <head />
* <body>
* <Scripts />
* </body>
* </html>
* );
* }
*
* @public
* @category Components
* @mode framework
* @param scriptProps Additional props to spread onto the [`<script>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script)
* tags, such as [`crossOrigin`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLScriptElement/crossOrigin),
* [`nonce`](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Global_attributes/nonce),
* etc.
* @returns A collection of React elements for [`<script>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script)
* tags
*/
function Scripts(scriptProps) {
let { manifest, serverHandoffString, isSpaMode, renderMeta, routeDiscovery, ssr, nonce: contextNonce } = useFrameworkContext();
let { router, static: isStatic, staticContext } = useDataRouterContext();
let { matches: routerMatches } = useDataRouterStateContext();
let isRSCRouterContext = useIsRSCRouterContext();
let enableFogOfWar = isFogOfWarEnabled(routeDiscovery, ssr);
if (scriptProps.nonce == null && contextNonce) scriptProps = {
...scriptProps,
nonce: contextNonce
};
if (renderMeta) renderMeta.didRenderScripts = true;
let matches = getActiveMatches(routerMatches, null, isSpaMode);
React$1.useEffect(() => {
setIsHydrated();
}, []);
let initialScripts = React$1.useMemo(() => {
if (isRSCRouterContext) return null;
let contextScript = staticContext ? `window.__reactRouterContext = ${serverHandoffString};window.__reactRouterContext.stream = new ReadableStream({start(controller){window.__reactRouterContext.streamController = controller;}}).pipeThrough(new TextEncoderStream());` : " ";
let routeModulesScript = !isStatic ? " " : `${manifest.hmr?.runtime ? `import ${JSON.stringify(manifest.hmr.runtime)};` : ""}${!enableFogOfWar ? `import ${JSON.stringify(manifest.url)}` : ""};
${matches.map((match, routeIndex) => {
let routeVarName = `route${routeIndex}`;
let manifestEntry = manifest.routes[match.route.id];
invariant(manifestEntry, `Route ${match.route.id} not found in manifest`);
let { clientActionModule, clientLoaderModule, clientMiddlewareModule, hydrateFallbackModule, module } = manifestEntry;
let chunks = [
...clientActionModule ? [{
module: clientActionModule,
varName: `${routeVarName}_clientAction`
}] : [],
...clientLoaderModule ? [{
module: clientLoaderModule,
varName: `${routeVarName}_clientLoader`
}] : [],
...clientMiddlewareModule ? [{
module: clientMiddlewareModule,
varName: `${routeVarName}_clientMiddleware`
}] : [],
...hydrateFallbackModule ? [{
module: hydrateFallbackModule,
varName: `${routeVarName}_HydrateFallback`
}] : [],
{
module,
varName: `${routeVarName}_main`
}
];
if (chunks.length === 1) return `import * as ${routeVarName} from ${JSON.stringify(module)};`;
return [chunks.map((chunk) => `import * as ${chunk.varName} from "${chunk.module}";`).join("\n"), `const ${routeVarName} = {${chunks.map((chunk) => `...${chunk.varName}`).join(",")}};`].join("\n");
}).join("\n")}
${enableFogOfWar ? `window.__reactRouterManifest = ${JSON.stringify(getPartialManifest(manifest, router), null, 2)};` : ""}
window.__reactRouterRouteModules = {${matches.map((match, index) => `${JSON.stringify(match.route.id)}:route${index}`).join(",")}};
import(${JSON.stringify(manifest.entry.module)});`;
return /* @__PURE__ */ React$1.createElement(React$1.Fragment, null, /* @__PURE__ */ React$1.createElement("script", {
...scriptProps,
suppressHydrationWarning: true,
dangerouslySetInnerHTML: { __html: contextScript },
type: void 0
}), /* @__PURE__ */ React$1.createElement("script", {
...scriptProps,
suppressHydrationWarning: true,
dangerouslySetInnerHTML: { __html: routeModulesScript },
type: "module",
async: true
}));
}, []);
let preloads = isHydrated || isRSCRouterContext ? [] : [...new Set(manifest.entry.imports.concat(getModuleLinkHrefs(matches, manifest, { includeHydrateFallback: true })))];
let sri = typeof manifest.sri === "object" ? manifest.sri : {};
warnOnce(!isRSCRouterContext, "The <Scripts /> element is a no-op when using RSC and can be safely removed.");
return isHydrated || isRSCRouterContext ? null : /* @__PURE__ */ React$1.createElement(React$1.Fragment, null, typeof manifest.sri === "object" ? /* @__PURE__ */ React$1.createElement("script", {
...scriptProps,
"rr-importmap": "",
type: "importmap",
suppressHydrationWarning: true,
dangerouslySetInnerHTML: { __html: JSON.stringify({ integrity: sri }) }
}) : null, !enableFogOfWar ? /* @__PURE__ */ React$1.createElement("link", {
rel: "modulepreload",
href: manifest.url,
crossOrigin: scriptProps.crossOrigin,
integrity: sri[manifest.url],
nonce: scriptProps.nonce,
suppressHydrationWarning: true
}) : null, /* @__PURE__ */ React$1.createElement("link", {
rel: "modulepreload",
href: manifest.entry.module,
crossOrigin: scriptProps.crossOrigin,
integrity: sri[manifest.entry.module],
nonce: scriptProps.nonce,
suppressHydrationWarning: true
}), preloads.map((path) => /* @__PURE__ */ React$1.createElement("link", {
key: path,
rel: "modulepreload",
href: path,
crossOrigin: scriptProps.crossOrigin,
integrity: sri[path],
nonce: scriptProps.nonce,
suppressHydrationWarning: true
})), initialScripts);
}
function mergeRefs(...refs) {
return (value) => {
refs.forEach((ref) => {
if (typeof ref === "function") ref(value);
else if (ref != null) ref.current = value;
});
};
}
//#endregion
export { CRITICAL_CSS_DATA_ATTRIBUTE, FrameworkContext, Links, Meta, PrefetchPageLinks, Scripts, mergeRefs, setIsHydrated, useFrameworkContext, usePrefetchBehavior };
+29
View File
@@ -0,0 +1,29 @@
/**
* react-router v8.3.0
*
* 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
*/
//#region 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;
}
//#endregion
export { createRequestInit };
@@ -0,0 +1,60 @@
import { DataRouteObject, RouteBranch, RouteManifest } from "../../router/utils.js";
import { StaticHandlerContext } from "../../router/router.js";
import { RouteModules } from "./routeModules.js";
import { EntryRoute } from "./routes.js";
import { ServerBuild } from "../../server-runtime/build.js";
//#region lib/dom/ssr/entry.d.ts
type SerializedError = {
message: string;
stack?: string;
};
interface FrameworkContextObject {
manifest: AssetsManifest;
routeModules: RouteModules;
criticalCss?: CriticalCss;
serverHandoffString?: string;
future: FutureConfig;
ssr: boolean;
isSpaMode: boolean;
routeDiscovery: ServerBuild["routeDiscovery"];
nonce?: string;
serializeError?(error: Error): SerializedError;
renderMeta?: {
didRenderScripts?: boolean;
streamCache?: Record<number, Promise<void> & {
result?: {
done: boolean;
value: string;
};
error?: unknown;
}>;
};
}
interface EntryContext extends FrameworkContextObject {
branches: RouteBranch<DataRouteObject>[];
staticHandlerContext: StaticHandlerContext;
serverHandoffStream?: ReadableStream<Uint8Array>;
}
type FutureConfig = Record<string, never>;
type CriticalCss = string | {
rel: "stylesheet";
href: string;
};
interface AssetsManifest {
entry: {
imports: string[];
module: string;
};
routes: RouteManifest<EntryRoute>;
url: string;
version: string;
hmr?: {
timestamp?: number;
runtime: string;
};
sri?: Record<string, string> | true;
}
//#endregion
export { AssetsManifest, CriticalCss, EntryContext, FrameworkContextObject, FutureConfig };
@@ -0,0 +1,27 @@
import { Location } from "../../router/history.js";
import * as React$1 from "react";
//#region lib/dom/ssr/errorBoundaries.d.ts
type RemixErrorBoundaryProps = React$1.PropsWithChildren<{
location: Location;
isOutsideRemixApp?: boolean;
error?: Error;
}>;
type RemixErrorBoundaryState = {
error: null | Error;
location: Location;
};
declare class RemixErrorBoundary extends React$1.Component<RemixErrorBoundaryProps, RemixErrorBoundaryState> {
constructor(props: RemixErrorBoundaryProps);
static getDerivedStateFromError(error: Error): {
error: Error;
};
static getDerivedStateFromProps(props: RemixErrorBoundaryProps, state: RemixErrorBoundaryState): {
error: Error | null;
location: Location<any>;
};
render(): string | number | bigint | boolean | Iterable<React$1.ReactNode> | Promise<string | number | bigint | boolean | React$1.ReactPortal | React$1.ReactElement<unknown, string | React$1.JSXElementConstructor<any>> | Iterable<React$1.ReactNode> | null | undefined> | React$1.JSX.Element | null | undefined;
}
//#endregion
export { RemixErrorBoundary };
@@ -0,0 +1,87 @@
/**
* react-router v8.3.0
*
* 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
*/
import { isRouteErrorResponse } from "../../router/utils.js";
import { Scripts, useFrameworkContext } from "./components.js";
import * as React$1 from "react";
//#region lib/dom/ssr/errorBoundaries.tsx
var RemixErrorBoundary = class extends React$1.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__ */ React$1.createElement(RemixRootDefaultErrorBoundary, {
error: this.state.error,
isOutsideRemixApp: true
});
else return this.props.children;
}
};
/**
* When app's don't provide a root level ErrorBoundary, we default to this.
*/
function RemixRootDefaultErrorBoundary({ error, isOutsideRemixApp }) {
let { nonce } = useFrameworkContext();
console.error(error);
let heyDeveloper = /* @__PURE__ */ React$1.createElement("script", {
nonce,
dangerouslySetInnerHTML: { __html: `
console.log(
"💿 Hey developer 👋. You can provide a way better UX than this when your app throws errors. Check out https://reactrouter.com/how-to/error-boundary for more information."
);
` }
});
if (isRouteErrorResponse(error)) return /* @__PURE__ */ React$1.createElement(BoundaryShell, { title: "Unhandled Thrown Response!" }, /* @__PURE__ */ React$1.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__ */ React$1.createElement(BoundaryShell, {
title: "Application Error!",
isOutsideRemixApp
}, /* @__PURE__ */ React$1.createElement("h1", { style: { fontSize: "24px" } }, "Application Error"), /* @__PURE__ */ React$1.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__ */ React$1.createElement("html", { lang: "en" }, /* @__PURE__ */ React$1.createElement("head", null, /* @__PURE__ */ React$1.createElement("meta", { charSet: "utf-8" }), /* @__PURE__ */ React$1.createElement("meta", {
name: "viewport",
content: "width=device-width,initial-scale=1,viewport-fit=cover"
}), /* @__PURE__ */ React$1.createElement("title", null, title)), /* @__PURE__ */ React$1.createElement("body", null, /* @__PURE__ */ React$1.createElement("main", { style: {
fontFamily: "system-ui, sans-serif",
padding: "2rem"
} }, children, renderScripts ? /* @__PURE__ */ React$1.createElement(Scripts, null) : null)));
}
//#endregion
export { BoundaryShell, RemixErrorBoundary, RemixRootDefaultErrorBoundary };
@@ -0,0 +1,33 @@
/**
* react-router v8.3.0
*
* 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
*/
import { BoundaryShell } from "./errorBoundaries.js";
import { useFrameworkContext } from "./components.js";
import * as React$1 from "react";
//#region lib/dom/ssr/fallback.tsx
function RemixRootDefaultHydrateFallback() {
let { nonce } = useFrameworkContext();
return /* @__PURE__ */ React$1.createElement(BoundaryShell, {
title: "Loading...",
renderScripts: true
}, /* @__PURE__ */ React$1.createElement("script", {
nonce,
dangerouslySetInnerHTML: { __html: `
console.log(
"💿 Hey developer 👋. You can provide a way better UX than this " +
"when your app is loading JS modules and/or running \`clientLoader\` " +
"functions. Check out https://reactrouter.com/start/framework/route-module#hydratefallback " +
"for more information."
);
` }
}));
}
//#endregion
export { RemixRootDefaultHydrateFallback };
@@ -0,0 +1,12 @@
import { PatchRoutesOnNavigationFunction } from "../../router/utils.js";
import { Router } from "../../router/router.js";
import { RouteModules } from "./routeModules.js";
import { AssetsManifest } from "./entry.js";
import { ServerBuild } from "../../server-runtime/build.js";
//#region lib/dom/ssr/fog-of-war.d.ts
declare function getPatchRoutesOnNavigationFunction(getRouter: () => Router, manifest: AssetsManifest, routeModules: RouteModules, ssr: boolean, routeDiscovery: ServerBuild["routeDiscovery"], isSpaMode: boolean, basename: string | undefined): PatchRoutesOnNavigationFunction | undefined;
declare function useFogOFWarDiscovery(router: Router, manifest: AssetsManifest, routeModules: RouteModules, ssr: boolean, routeDiscovery: ServerBuild["routeDiscovery"], isSpaMode: boolean): void;
//#endregion
export { getPatchRoutesOnNavigationFunction, useFogOFWarDiscovery };
@@ -0,0 +1,185 @@
/**
* react-router v8.3.0
*
* 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
*/
import { createPath } from "../../router/history.js";
import { joinPaths, matchRoutesImpl } from "../../router/utils.js";
import { createClientRoutes } from "./routes.js";
import * as React$1 from "react";
//#region lib/dom/ssr/fog-of-war.ts
const nextPaths = /* @__PURE__ */ new Set();
const discoveredPathsMaxSize = 1e3;
const discoveredPaths = /* @__PURE__ */ new Set();
const URL_LIMIT = 7680;
function getPathsWithAncestors(paths) {
let result = /* @__PURE__ */ new Set();
paths.forEach((path) => {
if (!path.startsWith("/")) path = `/${path}`;
for (let i = 1; i < path.length; i++) if (path[i] === "/") result.add(path.slice(0, i));
result.add(path);
});
return Array.from(result);
}
function isFogOfWarEnabled(routeDiscovery, ssr) {
return routeDiscovery.mode === "lazy" && ssr === true;
}
function getPartialManifest({ sri, ...manifest }, router) {
let routeIds = new Set(router.state.matches.map((m) => m.route.id));
let segments = router.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 = matchRoutesImpl(router.routes, path, router.basename || "/", false, router.branches);
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,
sri: sri ? true : void 0
};
}
function getPatchRoutesOnNavigationFunction(getRouter, manifest, routeModules, ssr, routeDiscovery, isSpaMode, basename) {
if (!isFogOfWarEnabled(routeDiscovery, ssr)) return;
return async ({ path, patch, signal, fetcherKey }) => {
if (discoveredPaths.has(path)) return;
let { state } = getRouter();
await fetchAndApplyManifestPatches([path], fetcherKey ? window.location.href : createPath(state.navigation.location || state.location), manifest, routeModules, ssr, isSpaMode, basename, routeDiscovery.manifestPath, patch, signal);
};
}
function useFogOFWarDiscovery(router, manifest, routeModules, ssr, routeDiscovery, isSpaMode) {
React$1.useEffect(() => {
if (!isFogOfWarEnabled(routeDiscovery, ssr) || window.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, null, manifest, routeModules, ssr, isSpaMode, router.basename, routeDiscovery.manifestPath, router.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();
}, [
ssr,
isSpaMode,
manifest,
routeModules,
router,
routeDiscovery
]);
}
function getManifestPath(_manifestPath, basename) {
let manifestPath = _manifestPath || "/__manifest";
return basename == null ? manifestPath : joinPaths([basename, manifestPath]);
}
const MANIFEST_VERSION_STORAGE_KEY = "react-router-manifest-version";
async function handleClientVersionMismatch(needsReload, version, errorReloadPath) {
if (!needsReload) {
try {
sessionStorage.removeItem(MANIFEST_VERSION_STORAGE_KEY);
} catch {}
return false;
}
if (!errorReloadPath) {
console.warn("Detected a manifest version mismatch during eager route discovery. The next navigation/fetch to an undiscovered route will result in a new document navigation to sync up with the latest manifest.");
return true;
}
try {
if (sessionStorage.getItem(MANIFEST_VERSION_STORAGE_KEY) === version) {
console.error("Unable to discover routes due to manifest version mismatch.");
return true;
}
sessionStorage.setItem(MANIFEST_VERSION_STORAGE_KEY, version);
} catch {}
window.location.href = errorReloadPath;
console.warn("Detected manifest version mismatch, reloading...");
await new Promise(() => {});
return true;
}
async function fetchAndApplyManifestPatches(paths, errorReloadPath, manifest, routeModules, ssr, isSpaMode, basename, manifestPath, patchRoutes, signal) {
paths = getPathsWithAncestors(paths);
const searchParams = new URLSearchParams();
searchParams.set("paths", paths.sort().join(","));
searchParams.set("version", manifest.version);
let url = new URL(getManifestPath(manifestPath, basename), window.location.origin);
url.search = searchParams.toString();
if (url.toString().length > 7680) {
nextPaths.clear();
return;
}
let serverPatches;
try {
let res = await fetch(url, { signal });
if (!res.ok) throw new Error(`${res.status} ${res.statusText}`);
if (await handleClientVersionMismatch(res.status === 204 && res.headers.has("X-Remix-Reload-Document"), manifest.version, errorReloadPath)) return;
serverPatches = await res.json();
} catch (e) {
if (signal?.aborted) return;
throw e;
}
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, ssr, isSpaMode, parentId)));
}
function addToFifoQueue(path, queue) {
if (queue.size >= discoveredPathsMaxSize) {
let first = queue.values().next().value;
if (first !== void 0) queue.delete(first);
}
queue.add(path);
}
function debounce(callback, wait) {
let timeoutId;
return (...args) => {
window.clearTimeout(timeoutId);
timeoutId = window.setTimeout(() => callback(...args), wait);
};
}
//#endregion
export { URL_LIMIT, getManifestPath, getPartialManifest, getPatchRoutesOnNavigationFunction, getPathsWithAncestors, handleClientVersionMismatch, isFogOfWarEnabled, useFogOFWarDiscovery };
@@ -0,0 +1,32 @@
import { Path } from "../../router/history.js";
import { DataRouteObject } from "../../router/utils.js";
import { HydrationState, Router } from "../../router/router.js";
import { ClientLoaderFunction } from "./routeModules.js";
//#region lib/dom/ssr/hydration.d.ts
declare function getHydrationData({
state,
routes,
getRouteInfo,
location,
basename,
isSpaMode
}: {
state: {
loaderData?: Router["state"]["loaderData"];
actionData?: Router["state"]["actionData"];
errors?: Router["state"]["errors"];
};
routes: DataRouteObject[];
getRouteInfo: (routeId: string) => {
clientLoader: ClientLoaderFunction | undefined;
hasLoader: boolean;
hasHydrateFallback: boolean;
};
location: Path;
basename: string | undefined;
isSpaMode: boolean;
}): HydrationState;
//#endregion
export { getHydrationData };
@@ -0,0 +1,29 @@
/**
* react-router v8.3.0
*
* 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
*/
import { matchRoutes } from "../../router/utils.js";
import { shouldHydrateRouteLoader } from "./routes.js";
//#region lib/dom/ssr/hydration.tsx
function getHydrationData({ state, routes, getRouteInfo, location, basename, isSpaMode }) {
let hydrationData = {
...state,
loaderData: { ...state.loaderData }
};
let initialMatches = matchRoutes(routes, location, basename);
if (initialMatches) for (let match of initialMatches) {
let routeId = match.route.id;
let routeInfo = getRouteInfo(routeId);
if (shouldHydrateRouteLoader(routeId, routeInfo.clientLoader, routeInfo.hasLoader, isSpaMode) && (routeInfo.hasHydrateFallback || !routeInfo.hasLoader)) delete hydrationData.loaderData[routeId];
else if (!routeInfo.hasLoader) hydrationData.loaderData[routeId] = null;
}
return hydrationData;
}
//#endregion
export { getHydrationData };
@@ -0,0 +1,16 @@
/**
* react-router v8.3.0
*
* 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
*/
//#region lib/dom/ssr/invariant.ts
function invariant(value, message) {
if (value === false || value === null || typeof value === "undefined") throw new Error(message);
}
//#endregion
export { invariant as default };
+170
View File
@@ -0,0 +1,170 @@
/**
* react-router v8.3.0
*
* 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
*/
import { loadRouteModule } from "./routeModules.js";
//#region lib/dom/ssr/links.ts
/**
* Gets all the links for a set of matches. The modules are assumed to have been
* loaded already.
*/
function getKeyedLinksForMatches(matches, routeModules, manifest) {
return dedupeLinkDescriptors(matches.map((match) => {
let module = routeModules[match.route.id];
let route = manifest.routes[match.route.id];
return [route && route.css ? route.css.map((href) => ({
rel: "stylesheet",
href
})) : [], module?.links?.() || []];
}).flat(2), getModuleLinkHrefs(matches, manifest));
}
function getRouteCssDescriptors(route) {
if (!route.css) return [];
return route.css.map((href) => ({
rel: "stylesheet",
href
}));
}
async function prefetchRouteCss(route) {
if (!route.css) return;
let descriptors = getRouteCssDescriptors(route);
await Promise.all(descriptors.map(prefetchStyleLink));
}
async function prefetchStyleLinks(route, routeModule) {
if (!route.css && !routeModule.links || !isPreloadSupported()) return;
let descriptors = [];
if (route.css) descriptors.push(...getRouteCssDescriptors(route));
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"
});
await Promise.all(styleLinks.map(prefetchStyleLink));
}
async function prefetchStyleLink(descriptor) {
return new Promise((resolve) => {
if (descriptor.media && !window.matchMedia(descriptor.media).matches || document.querySelector(`link[rel="stylesheet"][href="${descriptor.href}"]`)) return 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";
}
function isHtmlLinkDescriptor(object) {
if (object == null) return false;
if (object.href == null) return object.rel === "preload" && typeof object.imageSrcSet === "string" && typeof object.imageSizes === "string";
return typeof object.rel === "string" && typeof object.href === "string";
}
async function getKeyedPrefetchLinks(matches, manifest, routeModules) {
return dedupeLinkDescriptors((await Promise.all(matches.map(async (match) => {
let route = manifest.routes[match.route.id];
if (route) {
let mod = await loadRouteModule(route, routeModules);
return mod.links ? mod.links() : [];
}
return [];
}))).flat(1).filter(isHtmlLinkDescriptor).filter((link) => link.rel === "stylesheet" || link.rel === "preload").map((link) => link.rel === "stylesheet" ? {
...link,
rel: "prefetch",
as: "style"
} : {
...link,
rel: "prefetch"
}));
}
function getNewMatchesForLinks(page, nextMatches, currentMatches, manifest, location, mode) {
let isNew = (match, index) => {
if (!currentMatches[index]) return true;
return match.route.id !== currentMatches[index].route.id;
};
let matchPathChanged = (match, index) => {
return currentMatches[index].pathname !== match.pathname || currentMatches[index].route.path?.endsWith("*") && currentMatches[index].params["*"] !== match.params["*"];
};
if (mode === "assets") return nextMatches.filter((match, index) => isNew(match, index) || matchPathChanged(match, index));
if (mode === "data") return nextMatches.filter((match, index) => {
let manifestRoute = manifest.routes[match.route.id];
if (!manifestRoute || !manifestRoute.hasLoader) return false;
if (isNew(match, index) || matchPathChanged(match, index)) return true;
if (match.route.shouldRevalidate) {
let routeChoice = match.route.shouldRevalidate({
currentUrl: new URL(location.pathname + location.search + location.hash, window.origin),
currentParams: currentMatches[0]?.params || {},
nextUrl: new URL(page, window.origin),
nextParams: match.params,
defaultShouldRevalidate: true
});
if (typeof routeChoice === "boolean") return routeChoice;
}
return true;
});
return [];
}
function getModuleLinkHrefs(matches, manifest, { includeHydrateFallback } = {}) {
return dedupeHrefs(matches.map((match) => {
let route = manifest.routes[match.route.id];
if (!route) return [];
let hrefs = [route.module];
if (route.clientActionModule) hrefs = hrefs.concat(route.clientActionModule);
if (route.clientLoaderModule) hrefs = hrefs.concat(route.clientLoaderModule);
if (includeHydrateFallback && route.hydrateFallbackModule) hrefs = hrefs.concat(route.hydrateFallbackModule);
if (route.imports) hrefs = hrefs.concat(route.imports);
return hrefs;
}).flat(1));
}
function dedupeHrefs(hrefs) {
return [...new Set(hrefs)];
}
function sortKeys(obj) {
let sorted = {};
let keys = Object.keys(obj).sort();
for (let key of keys) sorted[key] = obj[key];
return sorted;
}
function dedupeLinkDescriptors(descriptors, preloads) {
let set = /* @__PURE__ */ new Set();
let preloadsSet = new Set(preloads);
return descriptors.reduce((deduped, descriptor) => {
if (preloads && !isPageLinkDescriptor(descriptor) && descriptor.as === "script" && descriptor.href && preloadsSet.has(descriptor.href)) return deduped;
let key = JSON.stringify(sortKeys(descriptor));
if (!set.has(key)) {
set.add(key);
deduped.push({
key,
link: descriptor
});
}
return deduped;
}, []);
}
let _isPreloadSupported;
function isPreloadSupported() {
if (_isPreloadSupported !== void 0) return _isPreloadSupported;
let el = document.createElement("link");
_isPreloadSupported = el.relList.supports("preload");
el = null;
return _isPreloadSupported;
}
//#endregion
export { getKeyedLinksForMatches, getKeyedPrefetchLinks, getModuleLinkHrefs, getNewMatchesForLinks, isPageLinkDescriptor, prefetchRouteCss, prefetchStyleLinks };
@@ -0,0 +1,24 @@
/**
* react-router v8.3.0
*
* 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
*/
//#region lib/dom/ssr/markup.ts
const ESCAPE_LOOKUP = {
"&": "\\u0026",
">": "\\u003e",
"<": "\\u003c",
"\u2028": "\\u2028",
"\u2029": "\\u2029"
};
const ESCAPE_REGEX = /[&><\u2028\u2029]/g;
function escapeHtml(html) {
return html.replace(ESCAPE_REGEX, (match) => ESCAPE_LOOKUP[match]);
}
//#endregion
export { escapeHtml };
@@ -0,0 +1,206 @@
import { Location } from "../../router/history.js";
import { ActionFunction, ActionFunctionArgs, DataRouteMatch, DataStrategyResult, LoaderFunction, LoaderFunctionArgs, MiddlewareFunction, Params, ShouldRevalidateFunction } from "../../router/utils.js";
import { LinkDescriptor } from "../../router/links.js";
import { SerializeFrom } from "../../types/route-data.js";
import { ComponentType, ReactElement } from "react";
//#region lib/dom/ssr/routeModules.d.ts
interface RouteModules {
[routeId: string]: RouteModule | undefined;
}
/**
* The shape of a route module shipped to the client
*/
interface RouteModule {
clientAction?: ClientActionFunction;
clientLoader?: ClientLoaderFunction;
clientMiddleware?: MiddlewareFunction<Record<string, DataStrategyResult>>[];
ErrorBoundary?: ErrorBoundaryComponent;
HydrateFallback?: HydrateFallbackComponent;
Layout?: LayoutComponent;
default: RouteComponent;
handle?: RouteHandle;
links?: LinksFunction;
meta?: MetaFunction;
shouldRevalidate?: ShouldRevalidateFunction;
}
/**
* The shape of a route module on the server
*/
interface ServerRouteModule extends RouteModule {
action?: ActionFunction;
headers?: HeadersFunction | {
[name: string]: string;
};
loader?: LoaderFunction;
middleware?: MiddlewareFunction<Response>[];
}
/**
* A function that handles data mutations for a route on the client
*/
type ClientActionFunction = (args: ClientActionFunctionArgs) => ReturnType<ActionFunction>;
/**
* Arguments passed to a route `clientAction` function
*/
type ClientActionFunctionArgs = ActionFunctionArgs & {
serverAction: <T = unknown>() => Promise<SerializeFrom<T>>;
};
/**
* A function that loads data for a route on the client
*/
type ClientLoaderFunction = ((args: ClientLoaderFunctionArgs) => ReturnType<LoaderFunction>) & {
hydrate?: boolean;
};
/**
* Arguments passed to a route `clientLoader` function
*/
type ClientLoaderFunctionArgs = LoaderFunctionArgs & {
serverLoader: <T = unknown>() => Promise<SerializeFrom<T>>;
};
/**
* ErrorBoundary to display for this route
*/
type ErrorBoundaryComponent = ComponentType;
type HeadersArgs = {
loaderHeaders: Headers;
parentHeaders: Headers;
actionHeaders: Headers;
errorHeaders: Headers | undefined;
};
/**
* A function that returns HTTP headers to be used for a route. These headers
* will be merged with (and take precedence over) headers from parent routes.
*/
interface HeadersFunction {
(args: HeadersArgs): Headers | HeadersInit;
}
/**
* `<Route HydrateFallback>` component to render on initial loads
* when client loaders are present
*/
type HydrateFallbackComponent = ComponentType;
/**
* Optional, root-only `<Route Layout>` component to wrap the root content in.
* Useful for defining the <html>/<head>/<body> document shell shared by the
* Component, HydrateFallback, and ErrorBoundary
*/
type LayoutComponent = ComponentType<{
children: ReactElement<unknown, ErrorBoundaryComponent | HydrateFallbackComponent | RouteComponent>;
}>;
/**
* A function that defines `<link>` tags to be inserted into the `<head>` of
* the document on route transitions.
*
* @see https://reactrouter.com/start/framework/route-module#meta
*/
interface LinksFunction {
(): LinkDescriptor[];
}
interface MetaMatch<RouteId extends string = string, Loader extends LoaderFunction | ClientLoaderFunction | unknown = unknown> {
id: RouteId;
pathname: DataRouteMatch["pathname"];
loaderData: Loader extends LoaderFunction | ClientLoaderFunction ? SerializeFrom<Loader> : unknown;
handle?: RouteHandle;
params: DataRouteMatch["params"];
meta: MetaDescriptor[];
error?: unknown;
}
type MetaMatches<MatchLoaders extends Record<string, LoaderFunction | ClientLoaderFunction | unknown> = Record<string, unknown>> = Array<{ [K in keyof MatchLoaders]: MetaMatch<Exclude<K, number | symbol>, MatchLoaders[K]> }[keyof MatchLoaders]>;
interface MetaArgs<Loader extends LoaderFunction | ClientLoaderFunction | unknown = unknown, MatchLoaders extends Record<string, LoaderFunction | ClientLoaderFunction | unknown> = Record<string, unknown>> {
loaderData: (Loader extends LoaderFunction | ClientLoaderFunction ? SerializeFrom<Loader> : unknown) | undefined;
params: Params;
location: Location;
matches: MetaMatches<MatchLoaders>;
error?: unknown;
}
/**
* A function that returns an array of data objects to use for rendering
* metadata HTML tags in a route. These tags are not rendered on descendant
* routes in the route hierarchy. In other words, they will only be rendered on
* the route in which they are exported.
*
* @param Loader - The type of the current route's loader function
* @param MatchLoaders - Mapping from a parent route's filepath to its loader
* function type
*
* Note that parent route filepaths are relative to the `app/` directory.
*
* For example, if this meta function is for `/sales/customers/$customerId`:
*
* ```ts
* // app/root.tsx
* const loader = () => ({ hello: "world" })
* export type Loader = typeof loader
*
* // app/routes/sales.tsx
* const loader = () => ({ salesCount: 1074 })
* export type Loader = typeof loader
*
* // app/routes/sales/customers.tsx
* const loader = () => ({ customerCount: 74 })
* export type Loader = typeof loader
*
* // app/routes/sales/customers/$customersId.tsx
* import type { Loader as RootLoader } from "../../../root"
* import type { Loader as SalesLoader } from "../../sales"
* import type { Loader as CustomersLoader } from "../../sales/customers"
*
* const loader = () => ({ name: "Customer name" })
*
* const meta: MetaFunction<typeof loader, {
* "root": RootLoader,
* "routes/sales": SalesLoader,
* "routes/sales/customers": CustomersLoader,
* }> = ({ loaderData, matches }) => {
* const { name } = loaderData
* // ^? string
* const { customerCount } = matches.find((match) => match.id === "routes/sales/customers").loaderData
* // ^? number
* const { salesCount } = matches.find((match) => match.id === "routes/sales").loaderData
* // ^? number
* const { hello } = matches.find((match) => match.id === "root").loaderData
* // ^? "world"
* }
* ```
*/
interface MetaFunction<Loader extends LoaderFunction | ClientLoaderFunction | unknown = unknown, MatchLoaders extends Record<string, LoaderFunction | ClientLoaderFunction | unknown> = Record<string, unknown>> {
(args: MetaArgs<Loader, MatchLoaders>): MetaDescriptor[] | undefined;
}
type MetaDescriptor = {
charSet: "utf-8";
} | {
title: string;
} | {
name: string;
content: string;
} | {
property: string;
content: string;
} | {
httpEquiv: string;
content: string;
} | {
"script:ld+json": LdJsonObject | LdJsonObject[];
} | {
tagName: "meta" | "link";
[name: string]: string;
} | {
[name: string]: unknown;
};
type LdJsonObject = { [Key in string]: LdJsonValue } & { [Key in string]?: LdJsonValue | undefined };
type LdJsonArray = LdJsonValue[] | readonly LdJsonValue[];
type LdJsonPrimitive = string | number | boolean | null;
type LdJsonValue = LdJsonPrimitive | LdJsonObject | LdJsonArray;
/**
* A React component that is rendered for a route.
*/
type RouteComponent = ComponentType<{}>;
/**
* An arbitrary object that is associated with a route.
*
* @see https://reactrouter.com/how-to/using-handle
*/
type RouteHandle = unknown;
//#endregion
export { ClientActionFunction, ClientActionFunctionArgs, ClientLoaderFunction, ClientLoaderFunctionArgs, HeadersArgs, HeadersFunction, LinksFunction, MetaArgs, MetaDescriptor, MetaFunction, RouteModules, ServerRouteModule };
@@ -0,0 +1,31 @@
/**
* react-router v8.3.0
*
* 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
*/
//#region 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 && import.meta.hot) throw error;
window.location.reload();
return new Promise(() => {});
}
}
//#endregion
export { loadRouteModule };
@@ -0,0 +1,75 @@
import { InitialEntry } from "../../router/history.js";
import { ActionFunction, IndexRouteObject, LoaderFunction, NonIndexRouteObject, RouterContextProvider } from "../../router/utils.js";
import { HydrationState } from "../../router/router.js";
import { LinksFunction, MetaFunction } from "./routeModules.js";
import { FutureConfig } from "./entry.js";
import * as React$1 from "react";
//#region lib/dom/ssr/routes-test-stub.d.ts
interface StubRouteExtensions {
Component?: React$1.ComponentType<any>;
HydrateFallback?: React$1.ComponentType<any>;
ErrorBoundary?: React$1.ComponentType<any>;
loader?: LoaderFunction;
action?: ActionFunction;
children?: StubRouteObject[];
meta?: MetaFunction;
links?: LinksFunction;
}
interface StubIndexRouteObject extends Omit<IndexRouteObject, "Component" | "HydrateFallback" | "ErrorBoundary" | "loader" | "action" | "element" | "errorElement" | "children">, StubRouteExtensions {}
interface StubNonIndexRouteObject extends Omit<NonIndexRouteObject, "Component" | "HydrateFallback" | "ErrorBoundary" | "loader" | "action" | "element" | "errorElement" | "children">, StubRouteExtensions {}
type StubRouteObject = StubIndexRouteObject | StubNonIndexRouteObject;
interface RoutesTestStubProps {
/**
* The initial entries in the history stack. This allows you to start a test with
* multiple locations already in the history stack (for testing a back navigation, etc.)
* The test will default to the last entry in initialEntries if no initialIndex is provided.
* e.g. initialEntries={["/home", "/about", "/contact"]}
*/
initialEntries?: InitialEntry[];
/**
* The initial index in the history stack to render. This allows you to start a test at a specific entry.
* It defaults to the last entry in initialEntries.
* e.g.
* initialEntries: ["/", "/events/123"]
* initialIndex: 1 // start at "/events/123"
*/
initialIndex?: number;
/**
* Used to set the route's initial loader and action data.
* e.g. hydrationData={{
* loaderData: { "/contact": { locale: "en-US" } },
* actionData: { "/login": { errors: { email: "invalid email" } }}
* }}
*/
hydrationData?: HydrationState;
/**
* Future flags mimicking the settings in react-router.config.ts
*/
future?: Partial<FutureConfig>;
}
/**
* Creates a React component that renders the provided routes in a test-friendly
* React Router context.
*
* Use this to unit test components that rely on router context, such as
* `loaderData`, `actionData`, and route matches.
*
* @public
* @category Utils
* @mode framework
* @mode data
* @param routes The route objects to render in the test router.
* @param _context An optional {@link RouterContextProvider} for supplying
* application context values to route middleware, loaders, and actions.
* @returns A React component that renders the test router.
*/
declare function createRoutesStub(routes: StubRouteObject[], _context?: RouterContextProvider): ({
initialEntries,
initialIndex,
hydrationData,
future
}: RoutesTestStubProps) => React$1.JSX.Element;
//#endregion
export { RoutesTestStubProps, createRoutesStub };
@@ -0,0 +1,121 @@
/**
* react-router v8.3.0
*
* 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
*/
import { RouterContextProvider, convertRoutesToDataRoutes } from "../../router/utils.js";
import { Outlet, RouterProvider, createMemoryRouter, withComponentProps, withErrorBoundaryProps, withHydrateFallbackProps } from "../../components.js";
import { FrameworkContext } from "./components.js";
import * as React$1 from "react";
//#region lib/dom/ssr/routes-test-stub.tsx
/**
* Creates a React component that renders the provided routes in a test-friendly
* React Router context.
*
* Use this to unit test components that rely on router context, such as
* `loaderData`, `actionData`, and route matches.
*
* @public
* @category Utils
* @mode framework
* @mode data
* @param routes The route objects to render in the test router.
* @param _context An optional {@link RouterContextProvider} for supplying
* application context values to route middleware, loaders, and actions.
* @returns A React component that renders the test router.
*/
function createRoutesStub(routes, _context) {
return function RoutesTestStub({ initialEntries, initialIndex, hydrationData, future }) {
let routerRef = React$1.useRef(null);
let frameworkContextRef = React$1.useRef(null);
if (routerRef.current == null || frameworkContextRef.current == null) {
frameworkContextRef.current = {
future: {},
manifest: {
routes: {},
entry: {
imports: [],
module: ""
},
url: "",
version: ""
},
routeModules: {},
ssr: false,
isSpaMode: false,
routeDiscovery: {
mode: "lazy",
manifestPath: "/__manifest"
}
};
routerRef.current = createMemoryRouter(processRoutes(convertRoutesToDataRoutes(routes, (r) => r), _context ?? new RouterContextProvider(), frameworkContextRef.current.manifest, frameworkContextRef.current.routeModules), {
initialEntries,
initialIndex,
hydrationData
});
}
return /* @__PURE__ */ React$1.createElement(FrameworkContext.Provider, { value: frameworkContextRef.current }, /* @__PURE__ */ React$1.createElement(RouterProvider, { router: routerRef.current }));
};
}
function processRoutes(routes, context, manifest, routeModules, parentId) {
return routes.map((route) => {
if (!route.id) throw new Error("Expected a route.id in react-router processRoutes() function");
let newRoute = {
id: route.id,
path: route.path,
index: route.index,
Component: route.Component ? withComponentProps(route.Component) : void 0,
HydrateFallback: route.HydrateFallback ? withHydrateFallbackProps(route.HydrateFallback) : void 0,
ErrorBoundary: route.ErrorBoundary ? withErrorBoundaryProps(route.ErrorBoundary) : void 0,
action: route.action ? (args) => route.action({
...args,
context
}) : void 0,
loader: route.loader ? (args) => route.loader({
...args,
context
}) : void 0,
middleware: route.middleware ? route.middleware.map((mw) => (...args) => mw({
...args[0],
context
}, args[1])) : void 0,
handle: route.handle,
shouldRevalidate: route.shouldRevalidate
};
let entryRoute = {
id: route.id,
path: route.path,
index: route.index,
parentId,
hasAction: route.action != null,
hasLoader: route.loader != null,
hasClientAction: false,
hasClientLoader: false,
hasClientMiddleware: false,
hasErrorBoundary: route.ErrorBoundary != null,
module: "build/stub-path-to-module.js",
clientActionModule: void 0,
clientLoaderModule: void 0,
clientMiddlewareModule: void 0,
hydrateFallbackModule: void 0
};
manifest.routes[newRoute.id] = entryRoute;
routeModules[route.id] = {
default: newRoute.Component || Outlet,
ErrorBoundary: newRoute.ErrorBoundary || void 0,
handle: route.handle,
links: route.links,
meta: route.meta,
shouldRevalidate: route.shouldRevalidate
};
if (route.children) newRoute.children = processRoutes(route.children, context, manifest, routeModules, newRoute.id);
return newRoute;
});
}
//#endregion
export { createRoutesStub };
@@ -0,0 +1,33 @@
import { DataRouteObject, RouteManifest } from "../../router/utils.js";
import { HydrationState } from "../../router/router.js";
import { ClientLoaderFunction, RouteModules } from "./routeModules.js";
//#region lib/dom/ssr/routes.d.ts
interface Route {
index?: boolean;
caseSensitive?: boolean;
id: string;
parentId?: string;
path?: string;
}
interface EntryRoute extends Route {
hasAction: boolean;
hasLoader: boolean;
hasClientAction: boolean;
hasClientLoader: boolean;
hasClientMiddleware: boolean;
hasErrorBoundary: boolean;
imports?: string[];
css?: string[];
module: string;
clientActionModule: string | undefined;
clientLoaderModule: string | undefined;
clientMiddlewareModule: string | undefined;
hydrateFallbackModule: string | undefined;
parentId?: string;
}
declare function createClientRoutesWithHMRRevalidationOptOut(needsRevalidation: Set<string>, manifest: RouteManifest<EntryRoute>, routeModulesCache: RouteModules, initialState: HydrationState, ssr: boolean, isSpaMode: boolean): DataRouteObject[];
declare function createClientRoutes(manifest: RouteManifest<EntryRoute>, routeModulesCache: RouteModules, initialState: HydrationState | null, ssr: boolean, isSpaMode: boolean, parentId?: string, routesByParentId?: Record<string, Omit<EntryRoute, "children">[]>, needsRevalidation?: Set<string>): DataRouteObject[];
declare function shouldHydrateRouteLoader(routeId: string, clientLoader: ClientLoaderFunction | undefined, hasLoader: boolean, isSpaMode: boolean): boolean;
//#endregion
export { EntryRoute, Route, createClientRoutes, createClientRoutesWithHMRRevalidationOptOut, shouldHydrateRouteLoader };
@@ -0,0 +1,303 @@
/**
* react-router v8.3.0
*
* 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
*/
import { ErrorResponseImpl, compilePath } from "../../router/utils.js";
import { useRouteError } from "../../hooks.js";
import invariant from "./invariant.js";
import { loadRouteModule } from "./routeModules.js";
import { prefetchRouteCss, prefetchStyleLinks } from "./links.js";
import { RemixRootDefaultErrorBoundary } from "./errorBoundaries.js";
import { RemixRootDefaultHydrateFallback } from "./fallback.js";
import * as React$1 from "react";
//#region 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 Component = 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__ */ React$1.createElement(RemixRootDefaultErrorBoundary, { error: useRouteError() }) : void 0;
if (route.id === "root" && routeModule.Layout) return {
...Component ? { element: /* @__PURE__ */ React$1.createElement(routeModule.Layout, null, /* @__PURE__ */ React$1.createElement(Component, null)) } : { Component },
...ErrorBoundary ? { errorElement: /* @__PURE__ */ React$1.createElement(routeModule.Layout, null, /* @__PURE__ */ React$1.createElement(ErrorBoundary, null)) } : { ErrorBoundary },
...HydrateFallback ? { hydrateFallbackElement: /* @__PURE__ */ React$1.createElement(routeModule.Layout, null, /* @__PURE__ */ React$1.createElement(HydrateFallback, null)) } : { HydrateFallback }
};
return {
Component,
ErrorBoundary,
HydrateFallback
};
}
function createServerRoutes(manifest, routeModules, future, isSpaMode, parentId = "", routesByParentId = groupRoutesByParentId(manifest), spaModeLazyPromise = Promise.resolve({ Component: () => null })) {
return (routesByParentId[parentId] || []).map((route) => {
let routeModule = routeModules[route.id];
invariant(routeModule, "No `routeModule` available to create server routes");
let dataRoute = {
...getRouteComponents(route, routeModule, isSpaMode),
caseSensitive: route.caseSensitive,
id: route.id,
index: route.index,
path: route.path,
handle: routeModule.handle,
lazy: isSpaMode ? () => spaModeLazyPromise : void 0,
loader: route.hasLoader || route.hasClientLoader ? () => null : void 0
};
let children = createServerRoutes(manifest, routeModules, future, isSpaMode, route.id, routesByParentId, spaModeLazyPromise);
if (children.length > 0) dataRoute.children = children;
return dataRoute;
});
}
function createClientRoutesWithHMRRevalidationOptOut(needsRevalidation, manifest, routeModulesCache, initialState, ssr, isSpaMode) {
return createClientRoutes(manifest, routeModulesCache, initialState, ssr, isSpaMode, "", groupRoutesByParentId(manifest), needsRevalidation);
}
function preventInvalidServerHandlerCall(type, route) {
if (type === "loader" && !route.hasLoader || type === "action" && !route.hasAction) {
let msg = `You are trying to call ${type === "action" ? "serverAction()" : "serverLoader()"} on a route that does not have a server ${type} (routeId: "${route.id}")`;
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, ssr, isSpaMode, parentId = "", routesByParentId = groupRoutesByParentId(manifest), needsRevalidation) {
return (routesByParentId[parentId] || []).map((route) => {
let routeModule = routeModulesCache[route.id];
function fetchServerHandler(singleFetch) {
invariant(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);
}
function prefetchModule(modulePath) {
import(
/* @vite-ignore */
/* webpackIgnore: true */
modulePath
);
}
function prefetchRouteModuleChunks(route) {
if (route.clientActionModule) prefetchModule(route.clientActionModule);
if (route.clientLoaderModule) prefetchModule(route.clientLoaderModule);
}
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),
middleware: routeModule.clientMiddleware,
handle: routeModule.handle,
shouldRevalidate: getShouldRevalidateFunction(dataRoute.path, routeModule, route, ssr, 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, context, pattern, url }, singleFetch) => {
let _isHydrationRequest = isHydrationRequest;
isHydrationRequest = false;
return await prefetchStylesAndCallHandler(async () => {
invariant(routeModule, "No `routeModule` available for critical-route loader");
if (!routeModule.clientLoader) return fetchServerLoader(singleFetch);
return routeModule.clientLoader({
request,
params,
context,
pattern,
url,
async serverLoader() {
preventInvalidServerHandlerCall("loader", route);
if (_isHydrationRequest) {
if (hasInitialData) return initialData;
if (hasInitialError) throw initialError;
}
return fetchServerLoader(singleFetch);
}
});
});
};
dataRoute.loader.hydrate = shouldHydrateRouteLoader(route.id, routeModule.clientLoader, route.hasLoader, isSpaMode);
dataRoute.action = ({ request, params, context, pattern, url }, singleFetch) => {
return prefetchStylesAndCallHandler(async () => {
invariant(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,
context,
pattern,
url,
async serverAction() {
preventInvalidServerHandlerCall("action", route);
return fetchServerAction(singleFetch);
}
});
});
};
} else {
if (!route.hasClientLoader) dataRoute.loader = (_, singleFetch) => prefetchStylesAndCallHandler(() => {
return fetchServerLoader(singleFetch);
});
if (!route.hasClientAction) dataRoute.action = (_, singleFetch) => prefetchStylesAndCallHandler(() => {
if (isSpaMode) throw noActionDefinedError("clientAction", route.id);
return fetchServerAction(singleFetch);
});
let lazyRoutePromise;
async function getLazyRoute() {
if (lazyRoutePromise) return await lazyRoutePromise;
lazyRoutePromise = (async () => {
if (route.clientLoaderModule || route.clientActionModule) await new Promise((resolve) => setTimeout(resolve, 0));
let routeModulePromise = loadRouteModuleWithBlockingLinks(route, routeModulesCache);
prefetchRouteModuleChunks(route);
return await routeModulePromise;
})();
return await lazyRoutePromise;
}
dataRoute.lazy = {
loader: route.hasClientLoader ? async () => {
let { clientLoader } = route.clientLoaderModule ? await import(
/* @vite-ignore */
/* webpackIgnore: true */
route.clientLoaderModule
) : await getLazyRoute();
invariant(clientLoader, "No `clientLoader` export found");
return (args, singleFetch) => clientLoader({
...args,
async serverLoader() {
preventInvalidServerHandlerCall("loader", route);
return fetchServerLoader(singleFetch);
}
});
} : void 0,
action: route.hasClientAction ? async () => {
let clientActionPromise = route.clientActionModule ? import(
/* @vite-ignore */
/* webpackIgnore: true */
route.clientActionModule
) : getLazyRoute();
prefetchRouteModuleChunks(route);
let { clientAction } = await clientActionPromise;
invariant(clientAction, "No `clientAction` export found");
return (args, singleFetch) => clientAction({
...args,
async serverAction() {
preventInvalidServerHandlerCall("action", route);
return fetchServerAction(singleFetch);
}
});
} : void 0,
middleware: route.hasClientMiddleware ? async () => {
let { clientMiddleware } = route.clientMiddlewareModule ? await import(
/* @vite-ignore */
/* webpackIgnore: true */
route.clientMiddlewareModule
) : await getLazyRoute();
invariant(clientMiddleware, "No `clientMiddleware` export found");
return clientMiddleware;
} : void 0,
shouldRevalidate: async () => {
let lazyRoute = await getLazyRoute();
return getShouldRevalidateFunction(dataRoute.path, lazyRoute, route, ssr, needsRevalidation);
},
handle: async () => (await getLazyRoute()).handle,
Component: async () => (await getLazyRoute()).Component,
ErrorBoundary: route.hasErrorBoundary ? async () => (await getLazyRoute()).ErrorBoundary : void 0
};
}
let children = createClientRoutes(manifest, routeModulesCache, initialState, ssr, isSpaMode, route.id, routesByParentId, needsRevalidation);
if (children.length > 0) dataRoute.children = children;
return dataRoute;
});
}
function getShouldRevalidateFunction(path, route, manifestRoute, ssr, needsRevalidation) {
if (needsRevalidation) return wrapShouldRevalidateForHdr(manifestRoute.id, route.shouldRevalidate, needsRevalidation);
if (!ssr && manifestRoute.hasLoader && !manifestRoute.hasClientLoader) {
let myParams = path ? compilePath(path)[1].map((p) => p.paramName) : [];
const didParamsChange = (opts) => myParams.some((p) => opts.currentParams[p] !== opts.nextParams[p]);
if (route.shouldRevalidate) {
let fn = route.shouldRevalidate;
return (opts) => fn({
...opts,
defaultShouldRevalidate: didParamsChange(opts)
});
} else return (opts) => didParamsChange(opts);
}
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 routeModulePromise = loadRouteModule(route, routeModules);
let prefetchRouteCssPromise = prefetchRouteCss(route);
let routeModule = await routeModulePromise;
await Promise.all([prefetchRouteCssPromise, prefetchStyleLinks(route, routeModule)]);
return {
Component: getRouteModuleComponent(routeModule),
ErrorBoundary: routeModule.ErrorBoundary,
clientMiddleware: routeModule.clientMiddleware,
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;
if (!(typeof routeModule.default === "object" && Object.keys(routeModule.default).length === 0)) return routeModule.default;
}
function shouldHydrateRouteLoader(routeId, clientLoader, hasLoader, isSpaMode) {
return isSpaMode && routeId !== "root" || clientLoader != null && (clientLoader.hydrate === true || hasLoader !== true);
}
//#endregion
export { createClientRoutes, createClientRoutesWithHMRRevalidationOptOut, createServerRoutes, noActionDefinedError, shouldHydrateRouteLoader };
@@ -0,0 +1,48 @@
import { EntryContext } from "./entry.js";
import { ReactElement } from "react";
//#region lib/dom/ssr/server.d.ts
/**
* @category Types
*/
interface ServerRouterProps {
/**
* The entry context containing the manifest, route modules, and other data
* needed for rendering.
*/
context: EntryContext;
/**
* The URL of the request being handled.
*/
url: string | URL;
/**
* An optional `nonce` for [Content Security Policy (CSP)](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CSP)
* compliance. This is applied to inline scripts rendered by React Router and
* used as the default for nonce-aware components such as {@link Links | `<Links>`},
* {@link Scripts | `<Scripts>`}, and {@link ScrollRestoration | `<ScrollRestoration>`}
* when they do not provide their own `nonce`.
*/
nonce?: string;
}
/**
* The server entry point for a React Router app in Framework Mode. This
* component is used to generate the HTML in the response from the server. See
* [`entry.server.tsx`](../framework-conventions/entry.server.tsx).
*
* @public
* @category Framework Routers
* @mode framework
* @param props Props
* @param {ServerRouterProps.context} props.context n/a
* @param {ServerRouterProps.nonce} props.nonce n/a
* @param {ServerRouterProps.url} props.url n/a
* @returns A React element that represents the server-rendered application.
*/
declare function ServerRouter({
context,
url,
nonce
}: ServerRouterProps): ReactElement;
//#endregion
export { ServerRouter, ServerRouterProps };
@@ -0,0 +1,69 @@
/**
* react-router v8.3.0
*
* 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
*/
import { StreamTransfer } from "./single-fetch.js";
import { RemixErrorBoundary } from "./errorBoundaries.js";
import { createServerRoutes, shouldHydrateRouteLoader } from "./routes.js";
import { FrameworkContext } from "./components.js";
import { StaticRouterProvider, createStaticRouter } from "../server.js";
import * as React$1 from "react";
//#region lib/dom/ssr/server.tsx
/**
* The server entry point for a React Router app in Framework Mode. This
* component is used to generate the HTML in the response from the server. See
* [`entry.server.tsx`](../framework-conventions/entry.server.tsx).
*
* @public
* @category Framework Routers
* @mode framework
* @param props Props
* @param {ServerRouterProps.context} props.context n/a
* @param {ServerRouterProps.nonce} props.nonce n/a
* @param {ServerRouterProps.url} props.url n/a
* @returns A React element that represents the server-rendered application.
*/
function ServerRouter({ context, url, nonce }) {
if (typeof url === "string") url = new URL(url);
let { manifest, routeModules, criticalCss, serverHandoffString } = context;
let routes = createServerRoutes(manifest.routes, routeModules, context.future, context.isSpaMode);
context.staticHandlerContext.loaderData = { ...context.staticHandlerContext.loaderData };
for (let match of context.staticHandlerContext.matches) {
let routeId = match.route.id;
let route = routeModules[routeId];
let manifestRoute = context.manifest.routes[routeId];
if (route && manifestRoute && shouldHydrateRouteLoader(routeId, route.clientLoader, manifestRoute.hasLoader, context.isSpaMode) && (route.HydrateFallback || !manifestRoute.hasLoader)) delete context.staticHandlerContext.loaderData[routeId];
}
let router = createStaticRouter(routes, context.staticHandlerContext, { branches: context.branches });
return /* @__PURE__ */ React$1.createElement(React$1.Fragment, null, /* @__PURE__ */ React$1.createElement(FrameworkContext.Provider, { value: {
manifest,
routeModules,
criticalCss,
serverHandoffString,
future: context.future,
ssr: context.ssr,
isSpaMode: context.isSpaMode,
routeDiscovery: context.routeDiscovery,
nonce,
serializeError: context.serializeError,
renderMeta: context.renderMeta
} }, /* @__PURE__ */ React$1.createElement(RemixErrorBoundary, { location: router.state.location }, /* @__PURE__ */ React$1.createElement(StaticRouterProvider, {
router,
context: context.staticHandlerContext,
hydrate: false
}))), context.serverHandoffStream ? /* @__PURE__ */ React$1.createElement(React$1.Suspense, null, /* @__PURE__ */ React$1.createElement(StreamTransfer, {
context,
identifier: 0,
reader: context.serverHandoffStream.getReader(),
textDecoder: new TextDecoder(),
nonce
})) : null);
}
//#endregion
export { ServerRouter };
@@ -0,0 +1,14 @@
import { DataStrategyFunction } from "../../router/utils.js";
import { Router } from "../../router/router.js";
import { RouteModules } from "./routeModules.js";
import { AssetsManifest } from "./entry.js";
//#region lib/dom/ssr/single-fetch.d.ts
declare const SingleFetchRedirectSymbol: unique symbol;
declare function getTurboStreamSingleFetchDataStrategy(getRouter: () => Router, manifest: AssetsManifest, routeModules: RouteModules, ssr: boolean): DataStrategyFunction;
declare function decodeViaTurboStream(body: ReadableStream<Uint8Array>, global: Window | typeof globalThis): Promise<{
done: Promise<void>;
value: unknown;
}>;
//#endregion
export { SingleFetchRedirectSymbol, decodeViaTurboStream, getTurboStreamSingleFetchDataStrategy };
@@ -0,0 +1,345 @@
/**
* react-router v8.3.0
*
* 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
*/
import { ErrorResponseImpl, SUPPORTED_ERROR_TYPES, data, isRouteErrorResponse, redirect } from "../../router/utils.js";
import { isDataWithResponseInit, isResponse } from "../../router/router.js";
import invariant from "./invariant.js";
import { escapeHtml } from "./markup.js";
import { decode } from "../../../vendor/turbo-stream-v2/turbo-stream.js";
import { createRequestInit } from "./data.js";
import * as React$1 from "react";
//#region lib/dom/ssr/single-fetch.tsx
const SingleFetchRedirectSymbol = Symbol("SingleFetchRedirect");
var SingleFetchNoResultError = class extends Error {};
const NO_BODY_STATUS_CODES = new Set([
100,
101,
204,
205
]);
function StreamTransfer({ context, identifier, reader, textDecoder, nonce }) {
if (!context.renderMeta || !context.renderMeta.didRenderScripts) return null;
if (!context.renderMeta.streamCache) context.renderMeta.streamCache = {};
let { streamCache } = context.renderMeta;
let promise = streamCache[identifier];
if (!promise) promise = streamCache[identifier] = reader.read().then((result) => {
streamCache[identifier].result = {
done: result.done,
value: textDecoder.decode(result.value, { stream: true })
};
}).catch((e) => {
streamCache[identifier].error = e;
});
if (promise.error) throw promise.error;
if (promise.result === void 0) throw promise;
let { done, value } = promise.result;
let scriptTag = value ? /* @__PURE__ */ React$1.createElement("script", {
nonce,
dangerouslySetInnerHTML: { __html: `window.__reactRouterContext.streamController.enqueue(${escapeHtml(JSON.stringify(value))});` }
}) : null;
if (done) return /* @__PURE__ */ React$1.createElement(React$1.Fragment, null, scriptTag, /* @__PURE__ */ React$1.createElement("script", {
nonce,
dangerouslySetInnerHTML: { __html: `window.__reactRouterContext.streamController.close();` }
}));
else return /* @__PURE__ */ React$1.createElement(React$1.Fragment, null, scriptTag, /* @__PURE__ */ React$1.createElement(React$1.Suspense, null, /* @__PURE__ */ React$1.createElement(StreamTransfer, {
context,
identifier: identifier + 1,
reader,
textDecoder,
nonce
})));
}
function getTurboStreamSingleFetchDataStrategy(getRouter, manifest, routeModules, ssr) {
let dataStrategy = getSingleFetchDataStrategyImpl(getRouter, (match) => {
let manifestRoute = manifest.routes[match.route.id];
invariant(manifestRoute, "Route not found in manifest");
return {
hasLoader: manifestRoute.hasLoader,
hasClientLoader: manifestRoute.hasClientLoader
};
}, fetchAndDecodeViaTurboStream, ssr);
return async (args) => args.runClientMiddleware(dataStrategy);
}
function getSingleFetchDataStrategyImpl(getRouter, getRouteInfo, fetchAndDecode, ssr, shouldAllowOptOut = () => true) {
return async (args) => {
let { request, matches, fetcherKey } = args;
let router = getRouter();
if (request.method !== "GET") return singleFetchActionStrategy(args, fetchAndDecode);
let foundRevalidatingServerLoader = matches.some((m) => {
let { hasLoader, hasClientLoader } = getRouteInfo(m);
return m.shouldCallHandler() && hasLoader && !hasClientLoader;
});
if (!ssr && !foundRevalidatingServerLoader) return nonSsrStrategy(args, getRouteInfo, fetchAndDecode);
if (fetcherKey) return singleFetchLoaderFetcherStrategy(args, fetchAndDecode);
return singleFetchLoaderNavigationStrategy(args, router, getRouteInfo, fetchAndDecode, ssr, shouldAllowOptOut);
};
}
async function singleFetchActionStrategy(args, fetchAndDecode) {
let actionMatch = args.matches.find((m) => m.shouldCallHandler());
invariant(actionMatch, "No action match found");
let actionStatus = void 0;
let result = await actionMatch.resolve(async (handler) => {
return await handler(async () => {
let { data, status } = await fetchAndDecode(args, [actionMatch.route.id]);
actionStatus = status;
return unwrapSingleFetchResult(data, actionMatch.route.id);
});
});
if (isResponse(result.result) || isRouteErrorResponse(result.result) || isDataWithResponseInit(result.result)) return { [actionMatch.route.id]: result };
return { [actionMatch.route.id]: {
type: result.type,
result: data(result.result, actionStatus)
} };
}
async function nonSsrStrategy(args, getRouteInfo, fetchAndDecode) {
let matchesToLoad = args.matches.filter((m) => m.shouldCallHandler());
let results = {};
await Promise.all(matchesToLoad.map((m) => m.resolve(async (handler) => {
try {
let { hasClientLoader } = getRouteInfo(m);
let routeId = m.route.id;
let result = hasClientLoader ? await handler(async () => {
let { data } = await fetchAndDecode(args, [routeId]);
return unwrapSingleFetchResult(data, routeId);
}) : await handler();
results[m.route.id] = {
type: "data",
result
};
} catch (e) {
results[m.route.id] = {
type: "error",
result: e
};
}
})));
return results;
}
async function singleFetchLoaderNavigationStrategy(args, router, getRouteInfo, fetchAndDecode, ssr, shouldAllowOptOut = () => true) {
let routesParams = /* @__PURE__ */ new Set();
let foundOptOutRoute = false;
let routeDfds = args.matches.map(() => createDeferred());
let singleFetchDfd = createDeferred();
let results = {};
let resolvePromise = Promise.all(args.matches.map(async (m, i) => m.resolve(async (handler) => {
routeDfds[i].resolve();
let routeId = m.route.id;
let { hasLoader, hasClientLoader } = getRouteInfo(m);
let defaultShouldRevalidate = !m.shouldRevalidateArgs || m.shouldRevalidateArgs.actionStatus == null || m.shouldRevalidateArgs.actionStatus < 400;
if (!m.shouldCallHandler(defaultShouldRevalidate)) {
foundOptOutRoute ||= m.shouldRevalidateArgs != null && hasLoader;
return;
}
if (shouldAllowOptOut(m) && hasClientLoader) {
if (hasLoader) foundOptOutRoute = true;
try {
results[routeId] = {
type: "data",
result: await handler(async () => {
let { data } = await fetchAndDecode(args, [routeId]);
return unwrapSingleFetchResult(data, routeId);
})
};
} catch (e) {
results[routeId] = {
type: "error",
result: e
};
}
return;
}
if (hasLoader) routesParams.add(routeId);
try {
results[routeId] = {
type: "data",
result: await handler(async () => {
return unwrapSingleFetchResult(await singleFetchDfd.promise, routeId);
})
};
} catch (e) {
results[routeId] = {
type: "error",
result: e
};
}
})));
await Promise.all(routeDfds.map((d) => d.promise));
if ((!router.state.initialized && router.state.navigation.state === "idle" || routesParams.size === 0) && !window.__reactRouterHdrActive) singleFetchDfd.resolve({ routes: {} });
else {
let targetRoutes = ssr && foundOptOutRoute && routesParams.size > 0 ? [...routesParams.keys()] : void 0;
try {
let data = await fetchAndDecode(args, targetRoutes);
singleFetchDfd.resolve(data.data);
} catch (e) {
singleFetchDfd.reject(e);
}
}
await resolvePromise;
await bubbleMiddlewareErrors(singleFetchDfd.promise, args.matches, routesParams, results);
return results;
}
async function bubbleMiddlewareErrors(singleFetchPromise, matches, routesParams, results) {
try {
let middlewareError;
let fetchedData = await singleFetchPromise;
if ("routes" in fetchedData) {
for (let match of matches) if (match.route.id in fetchedData.routes) {
let routeResult = fetchedData.routes[match.route.id];
if ("error" in routeResult) {
middlewareError = routeResult.error;
if (results[match.route.id]?.result == null) results[match.route.id] = {
type: "error",
result: middlewareError
};
break;
}
}
}
if (middlewareError !== void 0) Array.from(routesParams.values()).forEach((routeId) => {
if (results[routeId].result instanceof SingleFetchNoResultError) results[routeId].result = middlewareError;
});
} catch (e) {}
}
async function singleFetchLoaderFetcherStrategy(args, fetchAndDecode) {
let fetcherMatch = args.matches.find((m) => m.shouldCallHandler());
invariant(fetcherMatch, "No fetcher match found");
let routeId = fetcherMatch.route.id;
let result = await fetcherMatch.resolve(async (handler) => handler(async () => {
let { data } = await fetchAndDecode(args, [routeId]);
return unwrapSingleFetchResult(data, routeId);
}));
return { [fetcherMatch.route.id]: result };
}
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, extension) {
let url = typeof reqUrl === "string" ? new URL(reqUrl, typeof window === "undefined" ? "server://singlefetch/" : window.location.origin) : reqUrl;
if (url.pathname.endsWith("/")) url.pathname = `${url.pathname}_.${extension}`;
else url.pathname = `${url.pathname}.${extension}`;
return url;
}
async function fetchAndDecodeViaTurboStream(args, targetRoutes) {
let { request } = args;
let url = singleFetchUrl(request.url, "data");
if (request.method === "GET") {
url = stripIndexParam(url);
if (targetRoutes) url.searchParams.set("_routes", targetRoutes.join(","));
}
let res = await fetch(url, await createRequestInit(request));
if (res.status >= 400 && !res.headers.has("X-Remix-Response")) throw new ErrorResponseImpl(res.status, res.statusText, await res.text());
if (res.status === 204 && res.headers.has("X-Remix-Redirect")) return {
status: 202,
data: { redirect: {
redirect: res.headers.get("X-Remix-Redirect"),
status: Number(res.headers.get("X-Remix-Status") || "302"),
revalidate: res.headers.get("X-Remix-Revalidate") === "true",
reload: res.headers.get("X-Remix-Reload-Document") === "true",
replace: res.headers.get("X-Remix-Replace") === "true"
} }
};
if (NO_BODY_STATUS_CODES.has(res.status)) {
let routes = {};
if (targetRoutes && request.method !== "GET") routes[targetRoutes[0]] = { data: void 0 };
return {
status: res.status,
data: { routes }
};
}
invariant(res.body, "No response body to decode");
try {
let decoded = await decodeViaTurboStream(res.body, window);
let data;
if (request.method === "GET") {
let typed = decoded.value;
if (SingleFetchRedirectSymbol in typed) data = { redirect: typed[SingleFetchRedirectSymbol] };
else data = { routes: typed };
} else {
let typed = decoded.value;
let routeId = targetRoutes?.[0];
invariant(routeId, "No routeId found for single fetch call decoding");
if ("redirect" in typed) data = { redirect: typed };
else data = { routes: { [routeId]: typed } };
}
return {
status: res.status,
data
};
} catch (e) {
throw new Error("Unable to decode turbo-stream response");
}
}
function decodeViaTurboStream(body, global) {
return decode(body, { plugins: [(type, ...rest) => {
if (type === "SanitizedError") {
let [name, message, stack] = rest;
let Constructor = Error;
if (name && SUPPORTED_ERROR_TYPES.includes(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 [data, status, statusText] = rest;
return { value: new ErrorResponseImpl(status, statusText, data) };
}
if (type === "SingleFetchRedirect") return { value: { [SingleFetchRedirectSymbol]: rest[0] } };
if (type === "SingleFetchClassInstance") return { value: rest[0] };
if (type === "SingleFetchFallback") return { value: void 0 };
}] });
}
function unwrapSingleFetchResult(result, routeId) {
if ("redirect" in result) {
let { redirect: location, revalidate, reload, replace, status } = result.redirect;
throw redirect(location, {
status,
headers: {
...revalidate ? { "X-Remix-Revalidate": "yes" } : null,
...reload ? { "X-Remix-Reload-Document": "yes" } : null,
...replace ? { "X-Remix-Replace": "yes" } : null
}
});
}
let routeResult = result.routes[routeId];
if (routeResult == null) throw new SingleFetchNoResultError(`No result found for routeId "${routeId}"`);
else if ("error" in routeResult) throw routeResult.error;
else if ("data" in routeResult) return routeResult.data;
else throw new Error(`Invalid response found for routeId "${routeId}"`);
}
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,
resolve,
reject
};
}
//#endregion
export { NO_BODY_STATUS_CODES, SingleFetchRedirectSymbol, StreamTransfer, decodeViaTurboStream, getSingleFetchDataStrategyImpl, getTurboStreamSingleFetchDataStrategy, singleFetchUrl, stripIndexParam };