feat(wise-hearted-decor): initial luxury event decor website build with 5 pillars, portfolio, and booking funnel
This commit is contained in:
+8
@@ -0,0 +1,8 @@
|
||||
import { addPathPrefix } from '../shared/lib/router/utils/add-path-prefix';
|
||||
import { normalizePathTrailingSlash } from './normalize-trailing-slash';
|
||||
const basePath = process.env.__NEXT_ROUTER_BASEPATH || '';
|
||||
export function addBasePath(path, required) {
|
||||
return normalizePathTrailingSlash(process.env.__NEXT_MANUAL_CLIENT_BASE_PATH && !required ? path : addPathPrefix(path, basePath));
|
||||
}
|
||||
|
||||
//# sourceMappingURL=add-base-path.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../src/client/add-base-path.ts"],"sourcesContent":["import { addPathPrefix } from '../shared/lib/router/utils/add-path-prefix'\nimport { normalizePathTrailingSlash } from './normalize-trailing-slash'\n\nconst basePath = (process.env.__NEXT_ROUTER_BASEPATH as string) || ''\n\nexport function addBasePath(path: string, required?: boolean): string {\n return normalizePathTrailingSlash(\n process.env.__NEXT_MANUAL_CLIENT_BASE_PATH && !required\n ? path\n : addPathPrefix(path, basePath)\n )\n}\n"],"names":["addPathPrefix","normalizePathTrailingSlash","basePath","process","env","__NEXT_ROUTER_BASEPATH","addBasePath","path","required","__NEXT_MANUAL_CLIENT_BASE_PATH"],"mappings":"AAAA,SAASA,aAAa,QAAQ,6CAA4C;AAC1E,SAASC,0BAA0B,QAAQ,6BAA4B;AAEvE,MAAMC,WAAW,AAACC,QAAQC,GAAG,CAACC,sBAAsB,IAAe;AAEnE,OAAO,SAASC,YAAYC,IAAY,EAAEC,QAAkB;IAC1D,OAAOP,2BACLE,QAAQC,GAAG,CAACK,8BAA8B,IAAI,CAACD,WAC3CD,OACAP,cAAcO,MAAML;AAE5B"}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
import { normalizePathTrailingSlash } from './normalize-trailing-slash';
|
||||
export const addLocale = function(path) {
|
||||
for(var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++){
|
||||
args[_key - 1] = arguments[_key];
|
||||
}
|
||||
if (process.env.__NEXT_I18N_SUPPORT) {
|
||||
return normalizePathTrailingSlash(require('../shared/lib/router/utils/add-locale').addLocale(path, ...args));
|
||||
}
|
||||
return path;
|
||||
};
|
||||
|
||||
//# sourceMappingURL=add-locale.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../src/client/add-locale.ts"],"sourcesContent":["import type { addLocale as Fn } from '../shared/lib/router/utils/add-locale'\nimport { normalizePathTrailingSlash } from './normalize-trailing-slash'\n\nexport const addLocale: typeof Fn = (path, ...args) => {\n if (process.env.__NEXT_I18N_SUPPORT) {\n return normalizePathTrailingSlash(\n require('../shared/lib/router/utils/add-locale').addLocale(path, ...args)\n )\n }\n return path\n}\n"],"names":["normalizePathTrailingSlash","addLocale","path","args","process","env","__NEXT_I18N_SUPPORT","require"],"mappings":"AACA,SAASA,0BAA0B,QAAQ,6BAA4B;AAEvE,OAAO,MAAMC,YAAuB,SAACC;qCAASC;QAAAA;;IAC5C,IAAIC,QAAQC,GAAG,CAACC,mBAAmB,EAAE;QACnC,OAAON,2BACLO,QAAQ,yCAAyCN,SAAS,CAACC,SAASC;IAExE;IACA,OAAOD;AACT,EAAC"}
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
/**
|
||||
* Before starting the Next.js runtime and requiring any module, we need to make
|
||||
* sure the following scripts are executed in the correct order:
|
||||
* - Polyfills
|
||||
* - next/script with `beforeInteractive` strategy
|
||||
*/ const version = "15.1.0";
|
||||
window.next = {
|
||||
version,
|
||||
appDir: true
|
||||
};
|
||||
function loadScriptsInSequence(scripts, hydrate) {
|
||||
if (!scripts || !scripts.length) {
|
||||
return hydrate();
|
||||
}
|
||||
return scripts.reduce((promise, param)=>{
|
||||
let [src, props] = param;
|
||||
return promise.then(()=>{
|
||||
return new Promise((resolve, reject)=>{
|
||||
const el = document.createElement('script');
|
||||
if (props) {
|
||||
for(const key in props){
|
||||
if (key !== 'children') {
|
||||
el.setAttribute(key, props[key]);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (src) {
|
||||
el.src = src;
|
||||
el.onload = ()=>resolve();
|
||||
el.onerror = reject;
|
||||
} else if (props) {
|
||||
el.innerHTML = props.children;
|
||||
setTimeout(resolve);
|
||||
}
|
||||
document.head.appendChild(el);
|
||||
});
|
||||
});
|
||||
}, Promise.resolve()).catch((err)=>{
|
||||
console.error(err);
|
||||
// Still try to hydrate even if there's an error.
|
||||
}).then(()=>{
|
||||
hydrate();
|
||||
});
|
||||
}
|
||||
export function appBootstrap(callback) {
|
||||
loadScriptsInSequence(self.__next_s, ()=>{
|
||||
callback();
|
||||
});
|
||||
}
|
||||
|
||||
//# sourceMappingURL=app-bootstrap.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../src/client/app-bootstrap.ts"],"sourcesContent":["/**\n * Before starting the Next.js runtime and requiring any module, we need to make\n * sure the following scripts are executed in the correct order:\n * - Polyfills\n * - next/script with `beforeInteractive` strategy\n */\n\nconst version = process.env.__NEXT_VERSION\n\nwindow.next = {\n version,\n appDir: true,\n}\n\nfunction loadScriptsInSequence(\n scripts: [src: string, props: { [prop: string]: any }][],\n hydrate: () => void\n) {\n if (!scripts || !scripts.length) {\n return hydrate()\n }\n\n return scripts\n .reduce((promise, [src, props]) => {\n return promise.then(() => {\n return new Promise<void>((resolve, reject) => {\n const el = document.createElement('script')\n\n if (props) {\n for (const key in props) {\n if (key !== 'children') {\n el.setAttribute(key, props[key])\n }\n }\n }\n\n if (src) {\n el.src = src\n el.onload = () => resolve()\n el.onerror = reject\n } else if (props) {\n el.innerHTML = props.children\n setTimeout(resolve)\n }\n\n document.head.appendChild(el)\n })\n })\n }, Promise.resolve())\n .catch((err: Error) => {\n console.error(err)\n // Still try to hydrate even if there's an error.\n })\n .then(() => {\n hydrate()\n })\n}\n\nexport function appBootstrap(callback: () => void) {\n loadScriptsInSequence((self as any).__next_s, () => {\n callback()\n })\n}\n"],"names":["version","process","env","__NEXT_VERSION","window","next","appDir","loadScriptsInSequence","scripts","hydrate","length","reduce","promise","src","props","then","Promise","resolve","reject","el","document","createElement","key","setAttribute","onload","onerror","innerHTML","children","setTimeout","head","appendChild","catch","err","console","error","appBootstrap","callback","self","__next_s"],"mappings":"AAAA;;;;;CAKC,GAED,MAAMA,UAAUC,QAAQC,GAAG,CAACC,cAAc;AAE1CC,OAAOC,IAAI,GAAG;IACZL;IACAM,QAAQ;AACV;AAEA,SAASC,sBACPC,OAAwD,EACxDC,OAAmB;IAEnB,IAAI,CAACD,WAAW,CAACA,QAAQE,MAAM,EAAE;QAC/B,OAAOD;IACT;IAEA,OAAOD,QACJG,MAAM,CAAC,CAACC;YAAS,CAACC,KAAKC,MAAM;QAC5B,OAAOF,QAAQG,IAAI,CAAC;YAClB,OAAO,IAAIC,QAAc,CAACC,SAASC;gBACjC,MAAMC,KAAKC,SAASC,aAAa,CAAC;gBAElC,IAAIP,OAAO;oBACT,IAAK,MAAMQ,OAAOR,MAAO;wBACvB,IAAIQ,QAAQ,YAAY;4BACtBH,GAAGI,YAAY,CAACD,KAAKR,KAAK,CAACQ,IAAI;wBACjC;oBACF;gBACF;gBAEA,IAAIT,KAAK;oBACPM,GAAGN,GAAG,GAAGA;oBACTM,GAAGK,MAAM,GAAG,IAAMP;oBAClBE,GAAGM,OAAO,GAAGP;gBACf,OAAO,IAAIJ,OAAO;oBAChBK,GAAGO,SAAS,GAAGZ,MAAMa,QAAQ;oBAC7BC,WAAWX;gBACb;gBAEAG,SAASS,IAAI,CAACC,WAAW,CAACX;YAC5B;QACF;IACF,GAAGH,QAAQC,OAAO,IACjBc,KAAK,CAAC,CAACC;QACNC,QAAQC,KAAK,CAACF;IACd,iDAAiD;IACnD,GACCjB,IAAI,CAAC;QACJN;IACF;AACJ;AAEA,OAAO,SAAS0B,aAAaC,QAAoB;IAC/C7B,sBAAsB,AAAC8B,KAAaC,QAAQ,EAAE;QAC5CF;IACF;AACF"}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
// This gets assigned as a side-effect during app initialization. Because it
|
||||
// represents the build used to create the JS bundle, it should never change
|
||||
// after being set, so we store it in a global variable.
|
||||
//
|
||||
// When performing RSC requests, if the incoming data has a different build ID,
|
||||
// we perform an MPA navigation/refresh to load the updated build and ensure
|
||||
// that the client and server in sync.
|
||||
// Starts as an empty string. In practice, because setAppBuildId is called
|
||||
// during initialization before hydration starts, this will always get
|
||||
// reassigned to the actual build ID before it's ever needed by a navigation.
|
||||
// If for some reasons it didn't, due to a bug or race condition, then on
|
||||
// navigation the build comparision would fail and trigger an MPA navigation.
|
||||
let globalBuildId = '';
|
||||
export function setAppBuildId(buildId) {
|
||||
globalBuildId = buildId;
|
||||
}
|
||||
export function getAppBuildId() {
|
||||
return globalBuildId;
|
||||
}
|
||||
|
||||
//# sourceMappingURL=app-build-id.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../src/client/app-build-id.ts"],"sourcesContent":["// This gets assigned as a side-effect during app initialization. Because it\n// represents the build used to create the JS bundle, it should never change\n// after being set, so we store it in a global variable.\n//\n// When performing RSC requests, if the incoming data has a different build ID,\n// we perform an MPA navigation/refresh to load the updated build and ensure\n// that the client and server in sync.\n\n// Starts as an empty string. In practice, because setAppBuildId is called\n// during initialization before hydration starts, this will always get\n// reassigned to the actual build ID before it's ever needed by a navigation.\n// If for some reasons it didn't, due to a bug or race condition, then on\n// navigation the build comparision would fail and trigger an MPA navigation.\nlet globalBuildId: string = ''\n\nexport function setAppBuildId(buildId: string) {\n globalBuildId = buildId\n}\n\nexport function getAppBuildId(): string {\n return globalBuildId\n}\n"],"names":["globalBuildId","setAppBuildId","buildId","getAppBuildId"],"mappings":"AAAA,4EAA4E;AAC5E,4EAA4E;AAC5E,wDAAwD;AACxD,EAAE;AACF,+EAA+E;AAC/E,4EAA4E;AAC5E,sCAAsC;AAEtC,0EAA0E;AAC1E,sEAAsE;AACtE,6EAA6E;AAC7E,yEAAyE;AACzE,6EAA6E;AAC7E,IAAIA,gBAAwB;AAE5B,OAAO,SAASC,cAAcC,OAAe;IAC3CF,gBAAgBE;AAClB;AAEA,OAAO,SAASC;IACd,OAAOH;AACT"}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
import { startTransition, useCallback } from 'react';
|
||||
import { ACTION_SERVER_ACTION } from './components/router-reducer/router-reducer-types';
|
||||
let globalServerActionDispatcher = null;
|
||||
export function useServerActionDispatcher(dispatch) {
|
||||
const serverActionDispatcher = useCallback((actionPayload)=>{
|
||||
startTransition(()=>{
|
||||
dispatch({
|
||||
...actionPayload,
|
||||
type: ACTION_SERVER_ACTION
|
||||
});
|
||||
});
|
||||
}, [
|
||||
dispatch
|
||||
]);
|
||||
globalServerActionDispatcher = serverActionDispatcher;
|
||||
}
|
||||
export async function callServer(actionId, actionArgs) {
|
||||
const actionDispatcher = globalServerActionDispatcher;
|
||||
if (!actionDispatcher) {
|
||||
throw new Error('Invariant: missing action dispatcher.');
|
||||
}
|
||||
return new Promise((resolve, reject)=>{
|
||||
actionDispatcher({
|
||||
actionId,
|
||||
actionArgs,
|
||||
resolve,
|
||||
reject
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
//# sourceMappingURL=app-call-server.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../src/client/app-call-server.ts"],"sourcesContent":["import { startTransition, useCallback } from 'react'\nimport {\n ACTION_SERVER_ACTION,\n type ReducerActions,\n type ServerActionDispatcher,\n} from './components/router-reducer/router-reducer-types'\n\nlet globalServerActionDispatcher = null as ServerActionDispatcher | null\n\nexport function useServerActionDispatcher(\n dispatch: React.Dispatch<ReducerActions>\n) {\n const serverActionDispatcher: ServerActionDispatcher = useCallback(\n (actionPayload) => {\n startTransition(() => {\n dispatch({\n ...actionPayload,\n type: ACTION_SERVER_ACTION,\n })\n })\n },\n [dispatch]\n )\n globalServerActionDispatcher = serverActionDispatcher\n}\n\nexport async function callServer(actionId: string, actionArgs: any[]) {\n const actionDispatcher = globalServerActionDispatcher\n\n if (!actionDispatcher) {\n throw new Error('Invariant: missing action dispatcher.')\n }\n\n return new Promise((resolve, reject) => {\n actionDispatcher({\n actionId,\n actionArgs,\n resolve,\n reject,\n })\n })\n}\n"],"names":["startTransition","useCallback","ACTION_SERVER_ACTION","globalServerActionDispatcher","useServerActionDispatcher","dispatch","serverActionDispatcher","actionPayload","type","callServer","actionId","actionArgs","actionDispatcher","Error","Promise","resolve","reject"],"mappings":"AAAA,SAASA,eAAe,EAAEC,WAAW,QAAQ,QAAO;AACpD,SACEC,oBAAoB,QAGf,mDAAkD;AAEzD,IAAIC,+BAA+B;AAEnC,OAAO,SAASC,0BACdC,QAAwC;IAExC,MAAMC,yBAAiDL,YACrD,CAACM;QACCP,gBAAgB;YACdK,SAAS;gBACP,GAAGE,aAAa;gBAChBC,MAAMN;YACR;QACF;IACF,GACA;QAACG;KAAS;IAEZF,+BAA+BG;AACjC;AAEA,OAAO,eAAeG,WAAWC,QAAgB,EAAEC,UAAiB;IAClE,MAAMC,mBAAmBT;IAEzB,IAAI,CAACS,kBAAkB;QACrB,MAAM,IAAIC,MAAM;IAClB;IAEA,OAAO,IAAIC,QAAQ,CAACC,SAASC;QAC3BJ,iBAAiB;YACfF;YACAC;YACAI;YACAC;QACF;IACF;AACF"}
|
||||
+340
@@ -0,0 +1,340 @@
|
||||
'use client';
|
||||
import { jsx as _jsx } from "react/jsx-runtime";
|
||||
import React from 'react';
|
||||
import { formatUrl } from '../../shared/lib/router/utils/format-url';
|
||||
import { AppRouterContext } from '../../shared/lib/app-router-context.shared-runtime';
|
||||
import { useIntersection } from '../use-intersection';
|
||||
import { PrefetchKind } from '../components/router-reducer/router-reducer-types';
|
||||
import { useMergedRef } from '../use-merged-ref';
|
||||
import { isAbsoluteUrl } from '../../shared/lib/utils';
|
||||
import { addBasePath } from '../add-base-path';
|
||||
import { warnOnce } from '../../shared/lib/utils/warn-once';
|
||||
function prefetch(router, href, options) {
|
||||
if (typeof window === 'undefined') {
|
||||
return;
|
||||
}
|
||||
const doPrefetch = async ()=>{
|
||||
// note that `appRouter.prefetch()` is currently sync,
|
||||
// so we have to wrap this call in an async function to be able to catch() errors below.
|
||||
return router.prefetch(href, options);
|
||||
};
|
||||
// Prefetch the page if asked (only in the client)
|
||||
// We need to handle a prefetch error here since we may be
|
||||
// loading with priority which can reject but we don't
|
||||
// want to force navigation since this is only a prefetch
|
||||
doPrefetch().catch((err)=>{
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
// rethrow to show invalid URL errors
|
||||
throw err;
|
||||
}
|
||||
});
|
||||
}
|
||||
function isModifiedEvent(event) {
|
||||
const eventTarget = event.currentTarget;
|
||||
const target = eventTarget.getAttribute('target');
|
||||
return target && target !== '_self' || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey || // triggers resource download
|
||||
event.nativeEvent && event.nativeEvent.which === 2;
|
||||
}
|
||||
function linkClicked(e, router, href, as, replace, shallow, scroll) {
|
||||
const { nodeName } = e.currentTarget;
|
||||
// anchors inside an svg have a lowercase nodeName
|
||||
const isAnchorNodeName = nodeName.toUpperCase() === 'A';
|
||||
if (isAnchorNodeName && isModifiedEvent(e)) {
|
||||
// ignore click for browser’s default behavior
|
||||
return;
|
||||
}
|
||||
e.preventDefault();
|
||||
const navigate = ()=>{
|
||||
// If the router is an NextRouter instance it will have `beforePopState`
|
||||
const routerScroll = scroll != null ? scroll : true;
|
||||
if ('beforePopState' in router) {
|
||||
router[replace ? 'replace' : 'push'](href, as, {
|
||||
shallow,
|
||||
scroll: routerScroll
|
||||
});
|
||||
} else {
|
||||
router[replace ? 'replace' : 'push'](as || href, {
|
||||
scroll: routerScroll
|
||||
});
|
||||
}
|
||||
};
|
||||
React.startTransition(navigate);
|
||||
}
|
||||
function formatStringOrUrl(urlObjOrString) {
|
||||
if (typeof urlObjOrString === 'string') {
|
||||
return urlObjOrString;
|
||||
}
|
||||
return formatUrl(urlObjOrString);
|
||||
}
|
||||
/**
|
||||
* A React component that extends the HTML `<a>` element to provide [prefetching](https://nextjs.org/docs/app/building-your-application/routing/linking-and-navigating#2-prefetching)
|
||||
* and client-side navigation between routes.
|
||||
*
|
||||
* It is the primary way to navigate between routes in Next.js.
|
||||
*
|
||||
* Read more: [Next.js docs: `<Link>`](https://nextjs.org/docs/app/api-reference/components/link)
|
||||
*/ const Link = /*#__PURE__*/ React.forwardRef(function LinkComponent(props, forwardedRef) {
|
||||
let children;
|
||||
const { href: hrefProp, as: asProp, children: childrenProp, prefetch: prefetchProp = null, passHref, replace, shallow, scroll, onClick, onMouseEnter: onMouseEnterProp, onTouchStart: onTouchStartProp, legacyBehavior = false, ...restProps } = props;
|
||||
children = childrenProp;
|
||||
if (legacyBehavior && (typeof children === 'string' || typeof children === 'number')) {
|
||||
children = /*#__PURE__*/ _jsx("a", {
|
||||
children: children
|
||||
});
|
||||
}
|
||||
const router = React.useContext(AppRouterContext);
|
||||
const prefetchEnabled = prefetchProp !== false;
|
||||
/**
|
||||
* The possible states for prefetch are:
|
||||
* - null: this is the default "auto" mode, where we will prefetch partially if the link is in the viewport
|
||||
* - true: we will prefetch if the link is visible and prefetch the full page, not just partially
|
||||
* - false: we will not prefetch if in the viewport at all
|
||||
*/ const appPrefetchKind = prefetchProp === null ? PrefetchKind.AUTO : PrefetchKind.FULL;
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
function createPropError(args) {
|
||||
return new Error("Failed prop type: The prop `" + args.key + "` expects a " + args.expected + " in `<Link>`, but got `" + args.actual + "` instead." + (typeof window !== 'undefined' ? "\nOpen your browser's console to view the Component stack trace." : ''));
|
||||
}
|
||||
// TypeScript trick for type-guarding:
|
||||
const requiredPropsGuard = {
|
||||
href: true
|
||||
};
|
||||
const requiredProps = Object.keys(requiredPropsGuard);
|
||||
requiredProps.forEach((key)=>{
|
||||
if (key === 'href') {
|
||||
if (props[key] == null || typeof props[key] !== 'string' && typeof props[key] !== 'object') {
|
||||
throw createPropError({
|
||||
key,
|
||||
expected: '`string` or `object`',
|
||||
actual: props[key] === null ? 'null' : typeof props[key]
|
||||
});
|
||||
}
|
||||
} else {
|
||||
// TypeScript trick for type-guarding:
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
const _ = key;
|
||||
}
|
||||
});
|
||||
// TypeScript trick for type-guarding:
|
||||
const optionalPropsGuard = {
|
||||
as: true,
|
||||
replace: true,
|
||||
scroll: true,
|
||||
shallow: true,
|
||||
passHref: true,
|
||||
prefetch: true,
|
||||
onClick: true,
|
||||
onMouseEnter: true,
|
||||
onTouchStart: true,
|
||||
legacyBehavior: true
|
||||
};
|
||||
const optionalProps = Object.keys(optionalPropsGuard);
|
||||
optionalProps.forEach((key)=>{
|
||||
const valType = typeof props[key];
|
||||
if (key === 'as') {
|
||||
if (props[key] && valType !== 'string' && valType !== 'object') {
|
||||
throw createPropError({
|
||||
key,
|
||||
expected: '`string` or `object`',
|
||||
actual: valType
|
||||
});
|
||||
}
|
||||
} else if (key === 'onClick' || key === 'onMouseEnter' || key === 'onTouchStart') {
|
||||
if (props[key] && valType !== 'function') {
|
||||
throw createPropError({
|
||||
key,
|
||||
expected: '`function`',
|
||||
actual: valType
|
||||
});
|
||||
}
|
||||
} else if (key === 'replace' || key === 'scroll' || key === 'shallow' || key === 'passHref' || key === 'prefetch' || key === 'legacyBehavior') {
|
||||
if (props[key] != null && valType !== 'boolean') {
|
||||
throw createPropError({
|
||||
key,
|
||||
expected: '`boolean`',
|
||||
actual: valType
|
||||
});
|
||||
}
|
||||
} else {
|
||||
// TypeScript trick for type-guarding:
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
const _ = key;
|
||||
}
|
||||
});
|
||||
}
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
if (props.locale) {
|
||||
warnOnce('The `locale` prop is not supported in `next/link` while using the `app` router. Read more about app router internalization: https://nextjs.org/docs/app/building-your-application/routing/internationalization');
|
||||
}
|
||||
if (!asProp) {
|
||||
let href;
|
||||
if (typeof hrefProp === 'string') {
|
||||
href = hrefProp;
|
||||
} else if (typeof hrefProp === 'object' && typeof hrefProp.pathname === 'string') {
|
||||
href = hrefProp.pathname;
|
||||
}
|
||||
if (href) {
|
||||
const hasDynamicSegment = href.split('/').some((segment)=>segment.startsWith('[') && segment.endsWith(']'));
|
||||
if (hasDynamicSegment) {
|
||||
throw new Error("Dynamic href `" + href + "` found in <Link> while using the `/app` router, this is not supported. Read more: https://nextjs.org/docs/messages/app-dir-dynamic-href");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
const { href, as } = React.useMemo(()=>{
|
||||
const resolvedHref = formatStringOrUrl(hrefProp);
|
||||
return {
|
||||
href: resolvedHref,
|
||||
as: asProp ? formatStringOrUrl(asProp) : resolvedHref
|
||||
};
|
||||
}, [
|
||||
hrefProp,
|
||||
asProp
|
||||
]);
|
||||
const previousHref = React.useRef(href);
|
||||
const previousAs = React.useRef(as);
|
||||
// This will return the first child, if multiple are provided it will throw an error
|
||||
let child;
|
||||
if (legacyBehavior) {
|
||||
if (process.env.NODE_ENV === 'development') {
|
||||
if (onClick) {
|
||||
console.warn('"onClick" was passed to <Link> with `href` of `' + hrefProp + '` but "legacyBehavior" was set. The legacy behavior requires onClick be set on the child of next/link');
|
||||
}
|
||||
if (onMouseEnterProp) {
|
||||
console.warn('"onMouseEnter" was passed to <Link> with `href` of `' + hrefProp + '` but "legacyBehavior" was set. The legacy behavior requires onMouseEnter be set on the child of next/link');
|
||||
}
|
||||
try {
|
||||
child = React.Children.only(children);
|
||||
} catch (err) {
|
||||
if (!children) {
|
||||
throw new Error("No children were passed to <Link> with `href` of `" + hrefProp + "` but one child is required https://nextjs.org/docs/messages/link-no-children");
|
||||
}
|
||||
throw new Error("Multiple children were passed to <Link> with `href` of `" + hrefProp + "` but only one child is supported https://nextjs.org/docs/messages/link-multiple-children" + (typeof window !== 'undefined' ? " \nOpen your browser's console to view the Component stack trace." : ''));
|
||||
}
|
||||
} else {
|
||||
child = React.Children.only(children);
|
||||
}
|
||||
} else {
|
||||
if (process.env.NODE_ENV === 'development') {
|
||||
if ((children == null ? void 0 : children.type) === 'a') {
|
||||
throw new Error('Invalid <Link> with <a> child. Please remove <a> or use <Link legacyBehavior>.\nLearn more: https://nextjs.org/docs/messages/invalid-new-link-with-extra-anchor');
|
||||
}
|
||||
}
|
||||
}
|
||||
const childRef = legacyBehavior ? child && typeof child === 'object' && child.ref : forwardedRef;
|
||||
const [setIntersectionRef, isVisible, resetVisible] = useIntersection({
|
||||
rootMargin: '200px'
|
||||
});
|
||||
const setIntersectionWithResetRef = React.useCallback((el)=>{
|
||||
// Before the link getting observed, check if visible state need to be reset
|
||||
if (previousAs.current !== as || previousHref.current !== href) {
|
||||
resetVisible();
|
||||
previousAs.current = as;
|
||||
previousHref.current = href;
|
||||
}
|
||||
setIntersectionRef(el);
|
||||
}, [
|
||||
as,
|
||||
href,
|
||||
resetVisible,
|
||||
setIntersectionRef
|
||||
]);
|
||||
const setRef = useMergedRef(setIntersectionWithResetRef, childRef);
|
||||
// Prefetch the URL if we haven't already and it's visible.
|
||||
React.useEffect(()=>{
|
||||
// in dev, we only prefetch on hover to avoid wasting resources as the prefetch will trigger compiling the page.
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
return;
|
||||
}
|
||||
if (!router) {
|
||||
return;
|
||||
}
|
||||
// If we don't need to prefetch the URL, don't do prefetch.
|
||||
if (!isVisible || !prefetchEnabled) {
|
||||
return;
|
||||
}
|
||||
// Prefetch the URL.
|
||||
prefetch(router, href, {
|
||||
kind: appPrefetchKind
|
||||
});
|
||||
}, [
|
||||
as,
|
||||
href,
|
||||
isVisible,
|
||||
prefetchEnabled,
|
||||
router,
|
||||
appPrefetchKind
|
||||
]);
|
||||
const childProps = {
|
||||
ref: setRef,
|
||||
onClick (e) {
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
if (!e) {
|
||||
throw new Error('Component rendered inside next/link has to pass click event to "onClick" prop.');
|
||||
}
|
||||
}
|
||||
if (!legacyBehavior && typeof onClick === 'function') {
|
||||
onClick(e);
|
||||
}
|
||||
if (legacyBehavior && child.props && typeof child.props.onClick === 'function') {
|
||||
child.props.onClick(e);
|
||||
}
|
||||
if (!router) {
|
||||
return;
|
||||
}
|
||||
if (e.defaultPrevented) {
|
||||
return;
|
||||
}
|
||||
linkClicked(e, router, href, as, replace, shallow, scroll);
|
||||
},
|
||||
onMouseEnter (e) {
|
||||
if (!legacyBehavior && typeof onMouseEnterProp === 'function') {
|
||||
onMouseEnterProp(e);
|
||||
}
|
||||
if (legacyBehavior && child.props && typeof child.props.onMouseEnter === 'function') {
|
||||
child.props.onMouseEnter(e);
|
||||
}
|
||||
if (!router) {
|
||||
return;
|
||||
}
|
||||
if (!prefetchEnabled || process.env.NODE_ENV === 'development') {
|
||||
return;
|
||||
}
|
||||
prefetch(router, href, {
|
||||
kind: appPrefetchKind
|
||||
});
|
||||
},
|
||||
onTouchStart: process.env.__NEXT_LINK_NO_TOUCH_START ? undefined : function onTouchStart(e) {
|
||||
if (!legacyBehavior && typeof onTouchStartProp === 'function') {
|
||||
onTouchStartProp(e);
|
||||
}
|
||||
if (legacyBehavior && child.props && typeof child.props.onTouchStart === 'function') {
|
||||
child.props.onTouchStart(e);
|
||||
}
|
||||
if (!router) {
|
||||
return;
|
||||
}
|
||||
if (!prefetchEnabled) {
|
||||
return;
|
||||
}
|
||||
prefetch(router, href, {
|
||||
kind: appPrefetchKind
|
||||
});
|
||||
}
|
||||
};
|
||||
// If child is an <a> tag and doesn't have a href attribute, or if the 'passHref' property is
|
||||
// defined, we specify the current 'href', so that repetition is not needed by the user.
|
||||
// If the url is absolute, we can bypass the logic to prepend the basePath.
|
||||
if (isAbsoluteUrl(as)) {
|
||||
childProps.href = as;
|
||||
} else if (!legacyBehavior || passHref || child.type === 'a' && !('href' in child.props)) {
|
||||
childProps.href = addBasePath(as);
|
||||
}
|
||||
return legacyBehavior ? /*#__PURE__*/ React.cloneElement(child, childProps) : /*#__PURE__*/ _jsx("a", {
|
||||
...restProps,
|
||||
...childProps,
|
||||
children: children
|
||||
});
|
||||
});
|
||||
export default Link;
|
||||
|
||||
//# sourceMappingURL=link.js.map
|
||||
+1
File diff suppressed because one or more lines are too long
+22
@@ -0,0 +1,22 @@
|
||||
const basePath = process.env.__NEXT_ROUTER_BASEPATH || '';
|
||||
const pathname = "" + basePath + "/__nextjs_source-map";
|
||||
export const findSourceMapURL = process.env.NODE_ENV === 'development' ? function findSourceMapURL(filename) {
|
||||
if (filename === '') {
|
||||
return null;
|
||||
}
|
||||
if (filename.startsWith(document.location.origin) && filename.includes('/_next/static')) {
|
||||
// This is a request for a client chunk. This can only happen when
|
||||
// using Turbopack. In this case, since we control how those source
|
||||
// maps are generated, we can safely assume that the sourceMappingURL
|
||||
// is relative to the filename, with an added `.map` extension. The
|
||||
// browser can just request this file, and it gets served through the
|
||||
// normal dev server, without the need to route this through
|
||||
// the `/__nextjs_source-map` dev middleware.
|
||||
return "" + filename + ".map";
|
||||
}
|
||||
const url = new URL(pathname, document.location.origin);
|
||||
url.searchParams.set('filename', filename);
|
||||
return url.href;
|
||||
} : undefined;
|
||||
|
||||
//# sourceMappingURL=app-find-source-map-url.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../src/client/app-find-source-map-url.ts"],"sourcesContent":["const basePath = process.env.__NEXT_ROUTER_BASEPATH || ''\nconst pathname = `${basePath}/__nextjs_source-map`\n\nexport const findSourceMapURL =\n process.env.NODE_ENV === 'development'\n ? function findSourceMapURL(filename: string): string | null {\n if (filename === '') {\n return null\n }\n\n if (\n filename.startsWith(document.location.origin) &&\n filename.includes('/_next/static')\n ) {\n // This is a request for a client chunk. This can only happen when\n // using Turbopack. In this case, since we control how those source\n // maps are generated, we can safely assume that the sourceMappingURL\n // is relative to the filename, with an added `.map` extension. The\n // browser can just request this file, and it gets served through the\n // normal dev server, without the need to route this through\n // the `/__nextjs_source-map` dev middleware.\n return `${filename}.map`\n }\n\n const url = new URL(pathname, document.location.origin)\n url.searchParams.set('filename', filename)\n\n return url.href\n }\n : undefined\n"],"names":["basePath","process","env","__NEXT_ROUTER_BASEPATH","pathname","findSourceMapURL","NODE_ENV","filename","startsWith","document","location","origin","includes","url","URL","searchParams","set","href","undefined"],"mappings":"AAAA,MAAMA,WAAWC,QAAQC,GAAG,CAACC,sBAAsB,IAAI;AACvD,MAAMC,WAAW,AAAC,KAAEJ,WAAS;AAE7B,OAAO,MAAMK,mBACXJ,QAAQC,GAAG,CAACI,QAAQ,KAAK,gBACrB,SAASD,iBAAiBE,QAAgB;IACxC,IAAIA,aAAa,IAAI;QACnB,OAAO;IACT;IAEA,IACEA,SAASC,UAAU,CAACC,SAASC,QAAQ,CAACC,MAAM,KAC5CJ,SAASK,QAAQ,CAAC,kBAClB;QACA,kEAAkE;QAClE,mEAAmE;QACnE,qEAAqE;QACrE,mEAAmE;QACnE,qEAAqE;QACrE,4DAA4D;QAC5D,6CAA6C;QAC7C,OAAO,AAAC,KAAEL,WAAS;IACrB;IAEA,MAAMM,MAAM,IAAIC,IAAIV,UAAUK,SAASC,QAAQ,CAACC,MAAM;IACtDE,IAAIE,YAAY,CAACC,GAAG,CAAC,YAAYT;IAEjC,OAAOM,IAAII,IAAI;AACjB,IACAC,UAAS"}
|
||||
+202
@@ -0,0 +1,202 @@
|
||||
// imports polyfill from `@next/polyfill-module` after build.
|
||||
import { jsx as _jsx } from "react/jsx-runtime";
|
||||
import '../build/polyfills/polyfill-module';
|
||||
import './components/globals/patch-console';
|
||||
import './components/globals/handle-global-errors';
|
||||
import ReactDOMClient from 'react-dom/client';
|
||||
import React, { use } from 'react';
|
||||
// eslint-disable-next-line import/no-extraneous-dependencies
|
||||
import { createFromReadableStream } from 'react-server-dom-webpack/client';
|
||||
import { HeadManagerContext } from '../shared/lib/head-manager-context.shared-runtime';
|
||||
import { onRecoverableError } from './react-client-callbacks/shared';
|
||||
import { onCaughtError, onUncaughtError } from './react-client-callbacks/app-router';
|
||||
import { callServer } from './app-call-server';
|
||||
import { findSourceMapURL } from './app-find-source-map-url';
|
||||
import { createMutableActionQueue } from '../shared/lib/router/action-queue';
|
||||
import AppRouter from './components/app-router';
|
||||
import { createInitialRouterState } from './components/router-reducer/create-initial-router-state';
|
||||
import { MissingSlotContext } from '../shared/lib/app-router-context.shared-runtime';
|
||||
import { setAppBuildId } from './app-build-id';
|
||||
/// <reference types="react-dom/experimental" />
|
||||
const appElement = document;
|
||||
const encoder = new TextEncoder();
|
||||
let initialServerDataBuffer = undefined;
|
||||
let initialServerDataWriter = undefined;
|
||||
let initialServerDataLoaded = false;
|
||||
let initialServerDataFlushed = false;
|
||||
let initialFormStateData = null;
|
||||
function nextServerDataCallback(seg) {
|
||||
if (seg[0] === 0) {
|
||||
initialServerDataBuffer = [];
|
||||
} else if (seg[0] === 1) {
|
||||
if (!initialServerDataBuffer) throw new Error('Unexpected server data: missing bootstrap script.');
|
||||
if (initialServerDataWriter) {
|
||||
initialServerDataWriter.enqueue(encoder.encode(seg[1]));
|
||||
} else {
|
||||
initialServerDataBuffer.push(seg[1]);
|
||||
}
|
||||
} else if (seg[0] === 2) {
|
||||
initialFormStateData = seg[1];
|
||||
} else if (seg[0] === 3) {
|
||||
if (!initialServerDataBuffer) throw new Error('Unexpected server data: missing bootstrap script.');
|
||||
// Decode the base64 string back to binary data.
|
||||
const binaryString = atob(seg[1]);
|
||||
const decodedChunk = new Uint8Array(binaryString.length);
|
||||
for(var i = 0; i < binaryString.length; i++){
|
||||
decodedChunk[i] = binaryString.charCodeAt(i);
|
||||
}
|
||||
if (initialServerDataWriter) {
|
||||
initialServerDataWriter.enqueue(decodedChunk);
|
||||
} else {
|
||||
initialServerDataBuffer.push(decodedChunk);
|
||||
}
|
||||
}
|
||||
}
|
||||
function isStreamErrorOrUnfinished(ctr) {
|
||||
// If `desiredSize` is null, it means the stream is closed or errored. If it is lower than 0, the stream is still unfinished.
|
||||
return ctr.desiredSize === null || ctr.desiredSize < 0;
|
||||
}
|
||||
// There might be race conditions between `nextServerDataRegisterWriter` and
|
||||
// `DOMContentLoaded`. The former will be called when React starts to hydrate
|
||||
// the root, the latter will be called when the DOM is fully loaded.
|
||||
// For streaming, the former is called first due to partial hydration.
|
||||
// For non-streaming, the latter can be called first.
|
||||
// Hence, we use two variables `initialServerDataLoaded` and
|
||||
// `initialServerDataFlushed` to make sure the writer will be closed and
|
||||
// `initialServerDataBuffer` will be cleared in the right time.
|
||||
function nextServerDataRegisterWriter(ctr) {
|
||||
if (initialServerDataBuffer) {
|
||||
initialServerDataBuffer.forEach((val)=>{
|
||||
ctr.enqueue(typeof val === 'string' ? encoder.encode(val) : val);
|
||||
});
|
||||
if (initialServerDataLoaded && !initialServerDataFlushed) {
|
||||
if (isStreamErrorOrUnfinished(ctr)) {
|
||||
ctr.error(new Error('The connection to the page was unexpectedly closed, possibly due to the stop button being clicked, loss of Wi-Fi, or an unstable internet connection.'));
|
||||
} else {
|
||||
ctr.close();
|
||||
}
|
||||
initialServerDataFlushed = true;
|
||||
initialServerDataBuffer = undefined;
|
||||
}
|
||||
}
|
||||
initialServerDataWriter = ctr;
|
||||
}
|
||||
// When `DOMContentLoaded`, we can close all pending writers to finish hydration.
|
||||
const DOMContentLoaded = function() {
|
||||
if (initialServerDataWriter && !initialServerDataFlushed) {
|
||||
initialServerDataWriter.close();
|
||||
initialServerDataFlushed = true;
|
||||
initialServerDataBuffer = undefined;
|
||||
}
|
||||
initialServerDataLoaded = true;
|
||||
};
|
||||
// It's possible that the DOM is already loaded.
|
||||
if (document.readyState === 'loading') {
|
||||
document.addEventListener('DOMContentLoaded', DOMContentLoaded, false);
|
||||
} else {
|
||||
// Delayed in marco task to ensure it's executed later than hydration
|
||||
setTimeout(DOMContentLoaded);
|
||||
}
|
||||
const nextServerDataLoadingGlobal = self.__next_f = self.__next_f || [];
|
||||
nextServerDataLoadingGlobal.forEach(nextServerDataCallback);
|
||||
nextServerDataLoadingGlobal.push = nextServerDataCallback;
|
||||
const readable = new ReadableStream({
|
||||
start (controller) {
|
||||
nextServerDataRegisterWriter(controller);
|
||||
}
|
||||
});
|
||||
const initialServerResponse = createFromReadableStream(readable, {
|
||||
callServer,
|
||||
findSourceMapURL
|
||||
});
|
||||
// React overrides `.then` and doesn't return a new promise chain,
|
||||
// so we wrap the action queue in a promise to ensure that its value
|
||||
// is defined when the promise resolves.
|
||||
// https://github.com/facebook/react/blob/163365a07872337e04826c4f501565d43dbd2fd4/packages/react-client/src/ReactFlightClient.js#L189-L190
|
||||
const pendingActionQueue = new Promise((resolve, reject)=>{
|
||||
initialServerResponse.then((initialRSCPayload)=>{
|
||||
// setAppBuildId should be called only once, during JS initialization
|
||||
// and before any components have hydrated.
|
||||
setAppBuildId(initialRSCPayload.b);
|
||||
resolve(createMutableActionQueue(createInitialRouterState({
|
||||
initialFlightData: initialRSCPayload.f,
|
||||
initialCanonicalUrlParts: initialRSCPayload.c,
|
||||
initialParallelRoutes: new Map(),
|
||||
location: window.location,
|
||||
couldBeIntercepted: initialRSCPayload.i,
|
||||
postponed: initialRSCPayload.s,
|
||||
prerendered: initialRSCPayload.S
|
||||
})));
|
||||
}, (err)=>reject(err));
|
||||
});
|
||||
function ServerRoot() {
|
||||
const initialRSCPayload = use(initialServerResponse);
|
||||
const actionQueue = use(pendingActionQueue);
|
||||
const router = /*#__PURE__*/ _jsx(AppRouter, {
|
||||
actionQueue: actionQueue,
|
||||
globalErrorComponentAndStyles: initialRSCPayload.G,
|
||||
assetPrefix: initialRSCPayload.p
|
||||
});
|
||||
if (process.env.NODE_ENV === 'development' && initialRSCPayload.m) {
|
||||
// We provide missing slot information in a context provider only during development
|
||||
// as we log some additional information about the missing slots in the console.
|
||||
return /*#__PURE__*/ _jsx(MissingSlotContext, {
|
||||
value: initialRSCPayload.m,
|
||||
children: router
|
||||
});
|
||||
}
|
||||
return router;
|
||||
}
|
||||
const StrictModeIfEnabled = process.env.__NEXT_STRICT_MODE_APP ? React.StrictMode : React.Fragment;
|
||||
function Root(param) {
|
||||
let { children } = param;
|
||||
if (process.env.__NEXT_TEST_MODE) {
|
||||
// eslint-disable-next-line react-hooks/rules-of-hooks
|
||||
React.useEffect(()=>{
|
||||
window.__NEXT_HYDRATED = true;
|
||||
window.__NEXT_HYDRATED_CB == null ? void 0 : window.__NEXT_HYDRATED_CB.call(window);
|
||||
}, []);
|
||||
}
|
||||
return children;
|
||||
}
|
||||
const reactRootOptions = {
|
||||
onRecoverableError,
|
||||
onCaughtError,
|
||||
onUncaughtError
|
||||
};
|
||||
export function hydrate() {
|
||||
const reactEl = /*#__PURE__*/ _jsx(StrictModeIfEnabled, {
|
||||
children: /*#__PURE__*/ _jsx(HeadManagerContext.Provider, {
|
||||
value: {
|
||||
appDir: true
|
||||
},
|
||||
children: /*#__PURE__*/ _jsx(Root, {
|
||||
children: /*#__PURE__*/ _jsx(ServerRoot, {})
|
||||
})
|
||||
})
|
||||
});
|
||||
const rootLayoutMissingTags = window.__next_root_layout_missing_tags;
|
||||
const hasMissingTags = !!(rootLayoutMissingTags == null ? void 0 : rootLayoutMissingTags.length);
|
||||
const isError = document.documentElement.id === '__next_error__' || hasMissingTags;
|
||||
if (isError) {
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
const createDevOverlayElement = require('./components/react-dev-overlay/client-entry').createDevOverlayElement;
|
||||
const errorTree = createDevOverlayElement(reactEl);
|
||||
ReactDOMClient.createRoot(appElement, reactRootOptions).render(errorTree);
|
||||
} else {
|
||||
ReactDOMClient.createRoot(appElement, reactRootOptions).render(reactEl);
|
||||
}
|
||||
} else {
|
||||
React.startTransition(()=>ReactDOMClient.hydrateRoot(appElement, reactEl, {
|
||||
...reactRootOptions,
|
||||
formState: initialFormStateData
|
||||
}));
|
||||
}
|
||||
// TODO-APP: Remove this logic when Float has GC built-in in development.
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
const { linkGc } = require('./app-link-gc');
|
||||
linkGc();
|
||||
}
|
||||
}
|
||||
|
||||
//# sourceMappingURL=app-index.js.map
|
||||
+1
File diff suppressed because one or more lines are too long
+61
@@ -0,0 +1,61 @@
|
||||
export function linkGc() {
|
||||
// TODO-APP: Remove this logic when Float has GC built-in in development.
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
const callback = (mutationList)=>{
|
||||
for (const mutation of mutationList){
|
||||
if (mutation.type === 'childList') {
|
||||
for (const node of mutation.addedNodes){
|
||||
if ('tagName' in node && node.tagName === 'LINK') {
|
||||
var _link_dataset_precedence;
|
||||
const link = node;
|
||||
if ((_link_dataset_precedence = link.dataset.precedence) == null ? void 0 : _link_dataset_precedence.startsWith('next')) {
|
||||
const href = link.getAttribute('href');
|
||||
if (href) {
|
||||
const [resource, version] = href.split('?v=', 2);
|
||||
if (version) {
|
||||
const currentOrigin = window.location.origin;
|
||||
const allLinks = [
|
||||
...document.querySelectorAll('link[href^="' + resource + '"]'),
|
||||
// It's possible that the resource is a full URL or only pathname,
|
||||
// so we need to remove the alternative href as well.
|
||||
...document.querySelectorAll('link[href^="' + (resource.startsWith(currentOrigin) ? resource.slice(currentOrigin.length) : currentOrigin + resource) + '"]')
|
||||
];
|
||||
for (const otherLink of allLinks){
|
||||
var _otherLink_dataset_precedence;
|
||||
if ((_otherLink_dataset_precedence = otherLink.dataset.precedence) == null ? void 0 : _otherLink_dataset_precedence.startsWith('next')) {
|
||||
const otherHref = otherLink.getAttribute('href');
|
||||
if (otherHref) {
|
||||
const [, otherVersion] = otherHref.split('?v=', 2);
|
||||
if (!otherVersion || +otherVersion < +version) {
|
||||
// Delay the removal of the stylesheet to avoid FOUC
|
||||
// caused by `@font-face` rules, as they seem to be
|
||||
// a couple of ticks delayed between the old and new
|
||||
// styles being swapped even if the font is cached.
|
||||
setTimeout(()=>{
|
||||
otherLink.remove();
|
||||
}, 5);
|
||||
const preloadLink = document.querySelector('link[rel="preload"][as="style"][href="' + otherHref + '"]');
|
||||
if (preloadLink) {
|
||||
preloadLink.remove();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
// Create an observer instance linked to the callback function
|
||||
const observer = new MutationObserver(callback);
|
||||
observer.observe(document.head, {
|
||||
childList: true
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
//# sourceMappingURL=app-link-gc.js.map
|
||||
+1
File diff suppressed because one or more lines are too long
+10
@@ -0,0 +1,10 @@
|
||||
// TODO-APP: hydration warning
|
||||
import './app-webpack';
|
||||
import { appBootstrap } from './app-bootstrap';
|
||||
appBootstrap(()=>{
|
||||
const { hydrate } = require('./app-index');
|
||||
hydrate();
|
||||
}) // TODO-APP: build indicator
|
||||
;
|
||||
|
||||
//# sourceMappingURL=app-next-dev.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../src/client/app-next-dev.ts"],"sourcesContent":["// TODO-APP: hydration warning\n\nimport './app-webpack'\nimport { appBootstrap } from './app-bootstrap'\n\nappBootstrap(() => {\n const { hydrate } = require('./app-index')\n hydrate()\n})\n\n// TODO-APP: build indicator\n"],"names":["appBootstrap","hydrate","require"],"mappings":"AAAA,8BAA8B;AAE9B,OAAO,gBAAe;AACtB,SAASA,YAAY,QAAQ,kBAAiB;AAE9CA,aAAa;IACX,MAAM,EAAEC,OAAO,EAAE,GAAGC,QAAQ;IAC5BD;AACF,GAEA,4BAA4B"}
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
// TODO-APP: hydration warning
|
||||
import { appBootstrap } from './app-bootstrap';
|
||||
window.next.version += '-turbo';
|
||||
self.__webpack_hash__ = '';
|
||||
appBootstrap(()=>{
|
||||
const { hydrate } = require('./app-index');
|
||||
hydrate();
|
||||
}) // TODO-APP: build indicator
|
||||
;
|
||||
|
||||
//# sourceMappingURL=app-next-turbopack.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../src/client/app-next-turbopack.ts"],"sourcesContent":["// TODO-APP: hydration warning\n\nimport { appBootstrap } from './app-bootstrap'\n\nwindow.next.version += '-turbo'\n;(self as any).__webpack_hash__ = ''\n\nappBootstrap(() => {\n const { hydrate } = require('./app-index')\n hydrate()\n})\n\n// TODO-APP: build indicator\n"],"names":["appBootstrap","window","next","version","self","__webpack_hash__","hydrate","require"],"mappings":"AAAA,8BAA8B;AAE9B,SAASA,YAAY,QAAQ,kBAAiB;AAE9CC,OAAOC,IAAI,CAACC,OAAO,IAAI;AACrBC,KAAaC,gBAAgB,GAAG;AAElCL,aAAa;IACX,MAAM,EAAEM,OAAO,EAAE,GAAGC,QAAQ;IAC5BD;AACF,GAEA,4BAA4B"}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
// This import must go first because it needs to patch webpack chunk loading
|
||||
// before React patches chunk loading.
|
||||
import './app-webpack';
|
||||
import { appBootstrap } from './app-bootstrap';
|
||||
appBootstrap(()=>{
|
||||
const { hydrate } = require('./app-index');
|
||||
// Include app-router and layout-router in the main chunk
|
||||
require('next/dist/client/components/app-router');
|
||||
require('next/dist/client/components/layout-router');
|
||||
hydrate();
|
||||
});
|
||||
|
||||
//# sourceMappingURL=app-next.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../src/client/app-next.ts"],"sourcesContent":["// This import must go first because it needs to patch webpack chunk loading\n// before React patches chunk loading.\nimport './app-webpack'\nimport { appBootstrap } from './app-bootstrap'\n\nappBootstrap(() => {\n const { hydrate } = require('./app-index')\n // Include app-router and layout-router in the main chunk\n require('next/dist/client/components/app-router')\n require('next/dist/client/components/layout-router')\n hydrate()\n})\n"],"names":["appBootstrap","hydrate","require"],"mappings":"AAAA,4EAA4E;AAC5E,sCAAsC;AACtC,OAAO,gBAAe;AACtB,SAASA,YAAY,QAAQ,kBAAiB;AAE9CA,aAAa;IACX,MAAM,EAAEC,OAAO,EAAE,GAAGC,QAAQ;IAC5B,yDAAyD;IACzDA,QAAQ;IACRA,QAAQ;IACRD;AACF"}
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
// Override chunk URL mapping in the webpack runtime
|
||||
// https://github.com/webpack/webpack/blob/2738eebc7880835d88c727d364ad37f3ec557593/lib/RuntimeGlobals.js#L204
|
||||
import { getDeploymentIdQueryOrEmptyString } from '../build/deployment-id';
|
||||
import { encodeURIPath } from '../shared/lib/encode-uri-path';
|
||||
// If we have a deployment ID, we need to append it to the webpack chunk names
|
||||
// I am keeping the process check explicit so this can be statically optimized
|
||||
if (process.env.NEXT_DEPLOYMENT_ID) {
|
||||
const suffix = getDeploymentIdQueryOrEmptyString();
|
||||
// eslint-disable-next-line no-undef
|
||||
const getChunkScriptFilename = __webpack_require__.u;
|
||||
// eslint-disable-next-line no-undef
|
||||
__webpack_require__.u = function() {
|
||||
for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
|
||||
args[_key] = arguments[_key];
|
||||
}
|
||||
return(// We encode the chunk filename because our static server matches against and encoded
|
||||
// filename path.
|
||||
encodeURIPath(getChunkScriptFilename(...args)) + suffix);
|
||||
};
|
||||
// eslint-disable-next-line no-undef
|
||||
const getChunkCssFilename = __webpack_require__.k;
|
||||
// eslint-disable-next-line no-undef
|
||||
__webpack_require__.k = function() {
|
||||
for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
|
||||
args[_key] = arguments[_key];
|
||||
}
|
||||
return getChunkCssFilename(...args) + suffix;
|
||||
};
|
||||
// eslint-disable-next-line no-undef
|
||||
const getMiniCssFilename = __webpack_require__.miniCssF;
|
||||
// eslint-disable-next-line no-undef
|
||||
__webpack_require__.miniCssF = function() {
|
||||
for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
|
||||
args[_key] = arguments[_key];
|
||||
}
|
||||
return getMiniCssFilename(...args) + suffix;
|
||||
};
|
||||
} else {
|
||||
// eslint-disable-next-line no-undef
|
||||
const getChunkScriptFilename = __webpack_require__.u;
|
||||
// eslint-disable-next-line no-undef
|
||||
__webpack_require__.u = function() {
|
||||
for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
|
||||
args[_key] = arguments[_key];
|
||||
}
|
||||
return(// We encode the chunk filename because our static server matches against and encoded
|
||||
// filename path.
|
||||
encodeURIPath(getChunkScriptFilename(...args)));
|
||||
};
|
||||
// We don't need to override __webpack_require__.k because we don't modify
|
||||
// the css chunk name when not using deployment id suffixes
|
||||
// WE don't need to override __webpack_require__.miniCssF because we don't modify
|
||||
// the mini css chunk name when not using deployment id suffixes
|
||||
}
|
||||
|
||||
//# sourceMappingURL=app-webpack.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../src/client/app-webpack.ts"],"sourcesContent":["// Override chunk URL mapping in the webpack runtime\n// https://github.com/webpack/webpack/blob/2738eebc7880835d88c727d364ad37f3ec557593/lib/RuntimeGlobals.js#L204\n\nimport { getDeploymentIdQueryOrEmptyString } from '../build/deployment-id'\nimport { encodeURIPath } from '../shared/lib/encode-uri-path'\n\ndeclare const __webpack_require__: any\n\n// If we have a deployment ID, we need to append it to the webpack chunk names\n// I am keeping the process check explicit so this can be statically optimized\nif (process.env.NEXT_DEPLOYMENT_ID) {\n const suffix = getDeploymentIdQueryOrEmptyString()\n // eslint-disable-next-line no-undef\n const getChunkScriptFilename = __webpack_require__.u\n // eslint-disable-next-line no-undef\n __webpack_require__.u = (...args: any[]) =>\n // We encode the chunk filename because our static server matches against and encoded\n // filename path.\n encodeURIPath(getChunkScriptFilename(...args)) + suffix\n\n // eslint-disable-next-line no-undef\n const getChunkCssFilename = __webpack_require__.k\n // eslint-disable-next-line no-undef\n __webpack_require__.k = (...args: any[]) =>\n getChunkCssFilename(...args) + suffix\n\n // eslint-disable-next-line no-undef\n const getMiniCssFilename = __webpack_require__.miniCssF\n // eslint-disable-next-line no-undef\n __webpack_require__.miniCssF = (...args: any[]) =>\n getMiniCssFilename(...args) + suffix\n} else {\n // eslint-disable-next-line no-undef\n const getChunkScriptFilename = __webpack_require__.u\n // eslint-disable-next-line no-undef\n __webpack_require__.u = (...args: any[]) =>\n // We encode the chunk filename because our static server matches against and encoded\n // filename path.\n encodeURIPath(getChunkScriptFilename(...args))\n\n // We don't need to override __webpack_require__.k because we don't modify\n // the css chunk name when not using deployment id suffixes\n\n // WE don't need to override __webpack_require__.miniCssF because we don't modify\n // the mini css chunk name when not using deployment id suffixes\n}\n\nexport {}\n"],"names":["getDeploymentIdQueryOrEmptyString","encodeURIPath","process","env","NEXT_DEPLOYMENT_ID","suffix","getChunkScriptFilename","__webpack_require__","u","args","getChunkCssFilename","k","getMiniCssFilename","miniCssF"],"mappings":"AAAA,oDAAoD;AACpD,8GAA8G;AAE9G,SAASA,iCAAiC,QAAQ,yBAAwB;AAC1E,SAASC,aAAa,QAAQ,gCAA+B;AAI7D,8EAA8E;AAC9E,8EAA8E;AAC9E,IAAIC,QAAQC,GAAG,CAACC,kBAAkB,EAAE;IAClC,MAAMC,SAASL;IACf,oCAAoC;IACpC,MAAMM,yBAAyBC,oBAAoBC,CAAC;IACpD,oCAAoC;IACpCD,oBAAoBC,CAAC,GAAG;yCAAIC;YAAAA;;eAC1B,qFAAqF;QACrF,iBAAiB;QACjBR,cAAcK,0BAA0BG,SAASJ;;IAEnD,oCAAoC;IACpC,MAAMK,sBAAsBH,oBAAoBI,CAAC;IACjD,oCAAoC;IACpCJ,oBAAoBI,CAAC,GAAG;yCAAIF;YAAAA;;eAC1BC,uBAAuBD,QAAQJ;;IAEjC,oCAAoC;IACpC,MAAMO,qBAAqBL,oBAAoBM,QAAQ;IACvD,oCAAoC;IACpCN,oBAAoBM,QAAQ,GAAG;yCAAIJ;YAAAA;;eACjCG,sBAAsBH,QAAQJ;;AAClC,OAAO;IACL,oCAAoC;IACpC,MAAMC,yBAAyBC,oBAAoBC,CAAC;IACpD,oCAAoC;IACpCD,oBAAoBC,CAAC,GAAG;yCAAIC;YAAAA;;eAC1B,qFAAqF;QACrF,iBAAiB;QACjBR,cAAcK,0BAA0BG;;AAE1C,0EAA0E;AAC1E,2DAA2D;AAE3D,iFAAiF;AACjF,gEAAgE;AAClE"}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
import { addBasePath } from './add-base-path';
|
||||
/**
|
||||
* Function to correctly assign location to URL
|
||||
*
|
||||
* The method will add basePath, and will also correctly add location (including if it is a relative path)
|
||||
* @param location Location that should be added to the url
|
||||
* @param url Base URL to which the location should be assigned
|
||||
*/ export function assignLocation(location, url) {
|
||||
if (location.startsWith('.')) {
|
||||
const urlBase = url.origin + url.pathname;
|
||||
return new URL(// In order for a relative path to be added to the current url correctly, the current url must end with a slash
|
||||
// new URL('./relative', 'https://example.com/subdir').href -> 'https://example.com/relative'
|
||||
// new URL('./relative', 'https://example.com/subdir/').href -> 'https://example.com/subdir/relative'
|
||||
(urlBase.endsWith('/') ? urlBase : urlBase + '/') + location);
|
||||
}
|
||||
return new URL(addBasePath(location), url.href);
|
||||
}
|
||||
|
||||
//# sourceMappingURL=assign-location.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../src/client/assign-location.ts"],"sourcesContent":["import { addBasePath } from './add-base-path'\n\n/**\n * Function to correctly assign location to URL\n *\n * The method will add basePath, and will also correctly add location (including if it is a relative path)\n * @param location Location that should be added to the url\n * @param url Base URL to which the location should be assigned\n */\nexport function assignLocation(location: string, url: URL): URL {\n if (location.startsWith('.')) {\n const urlBase = url.origin + url.pathname\n return new URL(\n // In order for a relative path to be added to the current url correctly, the current url must end with a slash\n // new URL('./relative', 'https://example.com/subdir').href -> 'https://example.com/relative'\n // new URL('./relative', 'https://example.com/subdir/').href -> 'https://example.com/subdir/relative'\n (urlBase.endsWith('/') ? urlBase : urlBase + '/') + location\n )\n }\n\n return new URL(addBasePath(location), url.href)\n}\n"],"names":["addBasePath","assignLocation","location","url","startsWith","urlBase","origin","pathname","URL","endsWith","href"],"mappings":"AAAA,SAASA,WAAW,QAAQ,kBAAiB;AAE7C;;;;;;CAMC,GACD,OAAO,SAASC,eAAeC,QAAgB,EAAEC,GAAQ;IACvD,IAAID,SAASE,UAAU,CAAC,MAAM;QAC5B,MAAMC,UAAUF,IAAIG,MAAM,GAAGH,IAAII,QAAQ;QACzC,OAAO,IAAIC,IAIT,AAHA,+GAA+G;QAC/G,6FAA6F;QAC7F,qGAAqG;QACpGH,CAAAA,QAAQI,QAAQ,CAAC,OAAOJ,UAAUA,UAAU,GAAE,IAAKH;IAExD;IAEA,OAAO,IAAIM,IAAIR,YAAYE,WAAWC,IAAIO,IAAI;AAChD"}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
import { useContext } from 'react';
|
||||
import { RouterContext } from '../../shared/lib/router-context.shared-runtime';
|
||||
/**
|
||||
* useRouter from `next/compat/router` is designed to assist developers
|
||||
* migrating from `pages/` to `app/`. Unlike `next/router`, this hook does not
|
||||
* throw when the `NextRouter` is not mounted, and instead returns `null`. The
|
||||
* more concrete return type here lets developers use this hook within
|
||||
* components that could be shared between both `app/` and `pages/` and handle
|
||||
* to the case where the router is not mounted.
|
||||
*
|
||||
* @returns The `NextRouter` instance if it's available, otherwise `null`.
|
||||
*/ export function useRouter() {
|
||||
return useContext(RouterContext);
|
||||
}
|
||||
|
||||
//# sourceMappingURL=router.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../src/client/compat/router.ts"],"sourcesContent":["import { useContext } from 'react'\nimport { RouterContext } from '../../shared/lib/router-context.shared-runtime'\nimport type { NextRouter } from '../router'\n\n/**\n * useRouter from `next/compat/router` is designed to assist developers\n * migrating from `pages/` to `app/`. Unlike `next/router`, this hook does not\n * throw when the `NextRouter` is not mounted, and instead returns `null`. The\n * more concrete return type here lets developers use this hook within\n * components that could be shared between both `app/` and `pages/` and handle\n * to the case where the router is not mounted.\n *\n * @returns The `NextRouter` instance if it's available, otherwise `null`.\n */\nexport function useRouter(): NextRouter | null {\n return useContext(RouterContext)\n}\n"],"names":["useContext","RouterContext","useRouter"],"mappings":"AAAA,SAASA,UAAU,QAAQ,QAAO;AAClC,SAASC,aAAa,QAAQ,iDAAgD;AAG9E;;;;;;;;;CASC,GACD,OAAO,SAASC;IACd,OAAOF,WAAWC;AACpB"}
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { createPortal } from 'react-dom';
|
||||
const ANNOUNCER_TYPE = 'next-route-announcer';
|
||||
const ANNOUNCER_ID = '__next-route-announcer__';
|
||||
function getAnnouncerNode() {
|
||||
var _existingAnnouncer_shadowRoot;
|
||||
const existingAnnouncer = document.getElementsByName(ANNOUNCER_TYPE)[0];
|
||||
if (existingAnnouncer == null ? void 0 : (_existingAnnouncer_shadowRoot = existingAnnouncer.shadowRoot) == null ? void 0 : _existingAnnouncer_shadowRoot.childNodes[0]) {
|
||||
return existingAnnouncer.shadowRoot.childNodes[0];
|
||||
} else {
|
||||
const container = document.createElement(ANNOUNCER_TYPE);
|
||||
container.style.cssText = 'position:absolute';
|
||||
const announcer = document.createElement('div');
|
||||
announcer.ariaLive = 'assertive';
|
||||
announcer.id = ANNOUNCER_ID;
|
||||
announcer.role = 'alert';
|
||||
announcer.style.cssText = 'position:absolute;border:0;height:1px;margin:-1px;padding:0;width:1px;clip:rect(0 0 0 0);overflow:hidden;white-space:nowrap;word-wrap:normal';
|
||||
// Use shadow DOM here to avoid any potential CSS bleed
|
||||
const shadow = container.attachShadow({
|
||||
mode: 'open'
|
||||
});
|
||||
shadow.appendChild(announcer);
|
||||
document.body.appendChild(container);
|
||||
return announcer;
|
||||
}
|
||||
}
|
||||
export function AppRouterAnnouncer(param) {
|
||||
let { tree } = param;
|
||||
const [portalNode, setPortalNode] = useState(null);
|
||||
useEffect(()=>{
|
||||
const announcer = getAnnouncerNode();
|
||||
setPortalNode(announcer);
|
||||
return ()=>{
|
||||
const container = document.getElementsByTagName(ANNOUNCER_TYPE)[0];
|
||||
if (container == null ? void 0 : container.isConnected) {
|
||||
document.body.removeChild(container);
|
||||
}
|
||||
};
|
||||
}, []);
|
||||
const [routeAnnouncement, setRouteAnnouncement] = useState('');
|
||||
const previousTitle = useRef(undefined);
|
||||
useEffect(()=>{
|
||||
let currentTitle = '';
|
||||
if (document.title) {
|
||||
currentTitle = document.title;
|
||||
} else {
|
||||
const pageHeader = document.querySelector('h1');
|
||||
if (pageHeader) {
|
||||
currentTitle = pageHeader.innerText || pageHeader.textContent || '';
|
||||
}
|
||||
}
|
||||
// Only announce the title change, but not for the first load because screen
|
||||
// readers do that automatically.
|
||||
if (previousTitle.current !== undefined && previousTitle.current !== currentTitle) {
|
||||
setRouteAnnouncement(currentTitle);
|
||||
}
|
||||
previousTitle.current = currentTitle;
|
||||
}, [
|
||||
tree
|
||||
]);
|
||||
return portalNode ? /*#__PURE__*/ createPortal(routeAnnouncement, portalNode) : null;
|
||||
}
|
||||
|
||||
//# sourceMappingURL=app-router-announcer.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../src/client/components/app-router-announcer.tsx"],"sourcesContent":["import { useEffect, useRef, useState } from 'react'\nimport { createPortal } from 'react-dom'\nimport type { FlightRouterState } from '../../server/app-render/types'\n\nconst ANNOUNCER_TYPE = 'next-route-announcer'\nconst ANNOUNCER_ID = '__next-route-announcer__'\n\nfunction getAnnouncerNode() {\n const existingAnnouncer = document.getElementsByName(ANNOUNCER_TYPE)[0]\n if (existingAnnouncer?.shadowRoot?.childNodes[0]) {\n return existingAnnouncer.shadowRoot.childNodes[0] as HTMLElement\n } else {\n const container = document.createElement(ANNOUNCER_TYPE)\n container.style.cssText = 'position:absolute'\n const announcer = document.createElement('div')\n announcer.ariaLive = 'assertive'\n announcer.id = ANNOUNCER_ID\n announcer.role = 'alert'\n announcer.style.cssText =\n 'position:absolute;border:0;height:1px;margin:-1px;padding:0;width:1px;clip:rect(0 0 0 0);overflow:hidden;white-space:nowrap;word-wrap:normal'\n\n // Use shadow DOM here to avoid any potential CSS bleed\n const shadow = container.attachShadow({ mode: 'open' })\n shadow.appendChild(announcer)\n document.body.appendChild(container)\n return announcer\n }\n}\n\nexport function AppRouterAnnouncer({ tree }: { tree: FlightRouterState }) {\n const [portalNode, setPortalNode] = useState<HTMLElement | null>(null)\n\n useEffect(() => {\n const announcer = getAnnouncerNode()\n setPortalNode(announcer)\n return () => {\n const container = document.getElementsByTagName(ANNOUNCER_TYPE)[0]\n if (container?.isConnected) {\n document.body.removeChild(container)\n }\n }\n }, [])\n\n const [routeAnnouncement, setRouteAnnouncement] = useState('')\n const previousTitle = useRef<string | undefined>(undefined)\n\n useEffect(() => {\n let currentTitle = ''\n if (document.title) {\n currentTitle = document.title\n } else {\n const pageHeader = document.querySelector('h1')\n if (pageHeader) {\n currentTitle = pageHeader.innerText || pageHeader.textContent || ''\n }\n }\n\n // Only announce the title change, but not for the first load because screen\n // readers do that automatically.\n if (\n previousTitle.current !== undefined &&\n previousTitle.current !== currentTitle\n ) {\n setRouteAnnouncement(currentTitle)\n }\n previousTitle.current = currentTitle\n }, [tree])\n\n return portalNode ? createPortal(routeAnnouncement, portalNode) : null\n}\n"],"names":["useEffect","useRef","useState","createPortal","ANNOUNCER_TYPE","ANNOUNCER_ID","getAnnouncerNode","existingAnnouncer","document","getElementsByName","shadowRoot","childNodes","container","createElement","style","cssText","announcer","ariaLive","id","role","shadow","attachShadow","mode","appendChild","body","AppRouterAnnouncer","tree","portalNode","setPortalNode","getElementsByTagName","isConnected","removeChild","routeAnnouncement","setRouteAnnouncement","previousTitle","undefined","currentTitle","title","pageHeader","querySelector","innerText","textContent","current"],"mappings":"AAAA,SAASA,SAAS,EAAEC,MAAM,EAAEC,QAAQ,QAAQ,QAAO;AACnD,SAASC,YAAY,QAAQ,YAAW;AAGxC,MAAMC,iBAAiB;AACvB,MAAMC,eAAe;AAErB,SAASC;QAEHC;IADJ,MAAMA,oBAAoBC,SAASC,iBAAiB,CAACL,eAAe,CAAC,EAAE;IACvE,IAAIG,sCAAAA,gCAAAA,kBAAmBG,UAAU,qBAA7BH,8BAA+BI,UAAU,CAAC,EAAE,EAAE;QAChD,OAAOJ,kBAAkBG,UAAU,CAACC,UAAU,CAAC,EAAE;IACnD,OAAO;QACL,MAAMC,YAAYJ,SAASK,aAAa,CAACT;QACzCQ,UAAUE,KAAK,CAACC,OAAO,GAAG;QAC1B,MAAMC,YAAYR,SAASK,aAAa,CAAC;QACzCG,UAAUC,QAAQ,GAAG;QACrBD,UAAUE,EAAE,GAAGb;QACfW,UAAUG,IAAI,GAAG;QACjBH,UAAUF,KAAK,CAACC,OAAO,GACrB;QAEF,uDAAuD;QACvD,MAAMK,SAASR,UAAUS,YAAY,CAAC;YAAEC,MAAM;QAAO;QACrDF,OAAOG,WAAW,CAACP;QACnBR,SAASgB,IAAI,CAACD,WAAW,CAACX;QAC1B,OAAOI;IACT;AACF;AAEA,OAAO,SAASS,mBAAmB,KAAqC;IAArC,IAAA,EAAEC,IAAI,EAA+B,GAArC;IACjC,MAAM,CAACC,YAAYC,cAAc,GAAG1B,SAA6B;IAEjEF,UAAU;QACR,MAAMgB,YAAYV;QAClBsB,cAAcZ;QACd,OAAO;YACL,MAAMJ,YAAYJ,SAASqB,oBAAoB,CAACzB,eAAe,CAAC,EAAE;YAClE,IAAIQ,6BAAAA,UAAWkB,WAAW,EAAE;gBAC1BtB,SAASgB,IAAI,CAACO,WAAW,CAACnB;YAC5B;QACF;IACF,GAAG,EAAE;IAEL,MAAM,CAACoB,mBAAmBC,qBAAqB,GAAG/B,SAAS;IAC3D,MAAMgC,gBAAgBjC,OAA2BkC;IAEjDnC,UAAU;QACR,IAAIoC,eAAe;QACnB,IAAI5B,SAAS6B,KAAK,EAAE;YAClBD,eAAe5B,SAAS6B,KAAK;QAC/B,OAAO;YACL,MAAMC,aAAa9B,SAAS+B,aAAa,CAAC;YAC1C,IAAID,YAAY;gBACdF,eAAeE,WAAWE,SAAS,IAAIF,WAAWG,WAAW,IAAI;YACnE;QACF;QAEA,4EAA4E;QAC5E,iCAAiC;QACjC,IACEP,cAAcQ,OAAO,KAAKP,aAC1BD,cAAcQ,OAAO,KAAKN,cAC1B;YACAH,qBAAqBG;QACvB;QACAF,cAAcQ,OAAO,GAAGN;IAC1B,GAAG;QAACV;KAAK;IAET,OAAOC,2BAAaxB,aAAa6B,mBAAmBL,cAAc;AACpE"}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
export const RSC_HEADER = 'RSC';
|
||||
export const ACTION_HEADER = 'Next-Action';
|
||||
// TODO: Instead of sending the full router state, we only need to send the
|
||||
// segment path. Saves bytes. Then we could also use this field for segment
|
||||
// prefetches, which also need to specify a particular segment.
|
||||
export const NEXT_ROUTER_STATE_TREE_HEADER = 'Next-Router-State-Tree';
|
||||
export const NEXT_ROUTER_PREFETCH_HEADER = 'Next-Router-Prefetch';
|
||||
// This contains the path to the segment being prefetched.
|
||||
// TODO: If we change Next-Router-State-Tree to be a segment path, we can use
|
||||
// that instead. Then Next-Router-Prefetch and Next-Router-Segment-Prefetch can
|
||||
// be merged into a single enum.
|
||||
export const NEXT_ROUTER_SEGMENT_PREFETCH_HEADER = 'Next-Router-Segment-Prefetch';
|
||||
export const NEXT_HMR_REFRESH_HEADER = 'Next-HMR-Refresh';
|
||||
export const NEXT_URL = 'Next-Url';
|
||||
export const RSC_CONTENT_TYPE_HEADER = 'text/x-component';
|
||||
export const FLIGHT_HEADERS = [
|
||||
RSC_HEADER,
|
||||
NEXT_ROUTER_STATE_TREE_HEADER,
|
||||
NEXT_ROUTER_PREFETCH_HEADER,
|
||||
NEXT_HMR_REFRESH_HEADER,
|
||||
NEXT_ROUTER_SEGMENT_PREFETCH_HEADER
|
||||
];
|
||||
export const NEXT_RSC_UNION_QUERY = '_rsc';
|
||||
export const NEXT_ROUTER_STALE_TIME_HEADER = 'x-nextjs-stale-time';
|
||||
export const NEXT_DID_POSTPONE_HEADER = 'x-nextjs-postponed';
|
||||
export const NEXT_IS_PRERENDER_HEADER = 'x-nextjs-prerender';
|
||||
|
||||
//# sourceMappingURL=app-router-headers.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../src/client/components/app-router-headers.ts"],"sourcesContent":["export const RSC_HEADER = 'RSC' as const\nexport const ACTION_HEADER = 'Next-Action' as const\n// TODO: Instead of sending the full router state, we only need to send the\n// segment path. Saves bytes. Then we could also use this field for segment\n// prefetches, which also need to specify a particular segment.\nexport const NEXT_ROUTER_STATE_TREE_HEADER = 'Next-Router-State-Tree' as const\nexport const NEXT_ROUTER_PREFETCH_HEADER = 'Next-Router-Prefetch' as const\n// This contains the path to the segment being prefetched.\n// TODO: If we change Next-Router-State-Tree to be a segment path, we can use\n// that instead. Then Next-Router-Prefetch and Next-Router-Segment-Prefetch can\n// be merged into a single enum.\nexport const NEXT_ROUTER_SEGMENT_PREFETCH_HEADER =\n 'Next-Router-Segment-Prefetch' as const\nexport const NEXT_HMR_REFRESH_HEADER = 'Next-HMR-Refresh' as const\nexport const NEXT_URL = 'Next-Url' as const\nexport const RSC_CONTENT_TYPE_HEADER = 'text/x-component' as const\n\nexport const FLIGHT_HEADERS = [\n RSC_HEADER,\n NEXT_ROUTER_STATE_TREE_HEADER,\n NEXT_ROUTER_PREFETCH_HEADER,\n NEXT_HMR_REFRESH_HEADER,\n NEXT_ROUTER_SEGMENT_PREFETCH_HEADER,\n] as const\n\nexport const NEXT_RSC_UNION_QUERY = '_rsc' as const\n\nexport const NEXT_ROUTER_STALE_TIME_HEADER = 'x-nextjs-stale-time' as const\nexport const NEXT_DID_POSTPONE_HEADER = 'x-nextjs-postponed' as const\nexport const NEXT_IS_PRERENDER_HEADER = 'x-nextjs-prerender' as const\n"],"names":["RSC_HEADER","ACTION_HEADER","NEXT_ROUTER_STATE_TREE_HEADER","NEXT_ROUTER_PREFETCH_HEADER","NEXT_ROUTER_SEGMENT_PREFETCH_HEADER","NEXT_HMR_REFRESH_HEADER","NEXT_URL","RSC_CONTENT_TYPE_HEADER","FLIGHT_HEADERS","NEXT_RSC_UNION_QUERY","NEXT_ROUTER_STALE_TIME_HEADER","NEXT_DID_POSTPONE_HEADER","NEXT_IS_PRERENDER_HEADER"],"mappings":"AAAA,OAAO,MAAMA,aAAa,MAAc;AACxC,OAAO,MAAMC,gBAAgB,cAAsB;AACnD,2EAA2E;AAC3E,2EAA2E;AAC3E,+DAA+D;AAC/D,OAAO,MAAMC,gCAAgC,yBAAiC;AAC9E,OAAO,MAAMC,8BAA8B,uBAA+B;AAC1E,0DAA0D;AAC1D,6EAA6E;AAC7E,+EAA+E;AAC/E,gCAAgC;AAChC,OAAO,MAAMC,sCACX,+BAAuC;AACzC,OAAO,MAAMC,0BAA0B,mBAA2B;AAClE,OAAO,MAAMC,WAAW,WAAmB;AAC3C,OAAO,MAAMC,0BAA0B,mBAA2B;AAElE,OAAO,MAAMC,iBAAiB;IAC5BR;IACAE;IACAC;IACAE;IACAD;CACD,CAAS;AAEV,OAAO,MAAMK,uBAAuB,OAAe;AAEnD,OAAO,MAAMC,gCAAgC,sBAA8B;AAC3E,OAAO,MAAMC,2BAA2B,qBAA6B;AACrE,OAAO,MAAMC,2BAA2B,qBAA6B"}
|
||||
+594
@@ -0,0 +1,594 @@
|
||||
'use client';
|
||||
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
|
||||
import React, { use, useEffect, useMemo, useCallback, startTransition, useInsertionEffect, useDeferredValue } from 'react';
|
||||
import { AppRouterContext, LayoutRouterContext, GlobalLayoutRouterContext } from '../../shared/lib/app-router-context.shared-runtime';
|
||||
import { ACTION_HMR_REFRESH, ACTION_NAVIGATE, ACTION_PREFETCH, ACTION_REFRESH, ACTION_RESTORE, ACTION_SERVER_PATCH, PrefetchKind } from './router-reducer/router-reducer-types';
|
||||
import { createHrefFromUrl } from './router-reducer/create-href-from-url';
|
||||
import { SearchParamsContext, PathnameContext, PathParamsContext } from '../../shared/lib/hooks-client-context.shared-runtime';
|
||||
import { useReducer, useUnwrapState } from './use-reducer';
|
||||
import { ErrorBoundary } from './error-boundary';
|
||||
import { isBot } from '../../shared/lib/router/utils/is-bot';
|
||||
import { addBasePath } from '../add-base-path';
|
||||
import { AppRouterAnnouncer } from './app-router-announcer';
|
||||
import { RedirectBoundary } from './redirect-boundary';
|
||||
import { findHeadInCache } from './router-reducer/reducers/find-head-in-cache';
|
||||
import { unresolvedThenable } from './unresolved-thenable';
|
||||
import { removeBasePath } from '../remove-base-path';
|
||||
import { hasBasePath } from '../has-base-path';
|
||||
import { getSelectedParams } from './router-reducer/compute-changed-path';
|
||||
import { useNavFailureHandler } from './nav-failure-handler';
|
||||
import { useServerActionDispatcher } from '../app-call-server';
|
||||
import { prefetch as prefetchWithSegmentCache } from '../components/segment-cache/prefetch';
|
||||
import { getRedirectTypeFromError, getURLFromRedirectError } from './redirect';
|
||||
import { isRedirectError, RedirectType } from './redirect-error';
|
||||
const globalMutable = {};
|
||||
function isExternalURL(url) {
|
||||
return url.origin !== window.location.origin;
|
||||
}
|
||||
/**
|
||||
* Given a link href, constructs the URL that should be prefetched. Returns null
|
||||
* in cases where prefetching should be disabled, like external URLs, or
|
||||
* during development.
|
||||
* @param href The href passed to <Link>, router.prefetch(), or similar
|
||||
* @returns A URL object to prefetch, or null if prefetching should be disabled
|
||||
*/ export function createPrefetchURL(href) {
|
||||
// Don't prefetch for bots as they don't navigate.
|
||||
if (isBot(window.navigator.userAgent)) {
|
||||
return null;
|
||||
}
|
||||
let url;
|
||||
try {
|
||||
url = new URL(addBasePath(href), window.location.href);
|
||||
} catch (_) {
|
||||
// TODO: Does this need to throw or can we just console.error instead? Does
|
||||
// anyone rely on this throwing? (Seems unlikely.)
|
||||
throw new Error("Cannot prefetch '" + href + "' because it cannot be converted to a URL.");
|
||||
}
|
||||
// Don't prefetch during development (improves compilation performance)
|
||||
if (process.env.NODE_ENV === 'development') {
|
||||
return null;
|
||||
}
|
||||
// External urls can't be prefetched in the same way.
|
||||
if (isExternalURL(url)) {
|
||||
return null;
|
||||
}
|
||||
return url;
|
||||
}
|
||||
function HistoryUpdater(param) {
|
||||
let { appRouterState } = param;
|
||||
useInsertionEffect(()=>{
|
||||
if (process.env.__NEXT_APP_NAV_FAIL_HANDLING) {
|
||||
// clear pending URL as navigation is no longer
|
||||
// in flight
|
||||
window.next.__pendingUrl = undefined;
|
||||
}
|
||||
const { tree, pushRef, canonicalUrl } = appRouterState;
|
||||
const historyState = {
|
||||
...pushRef.preserveCustomHistoryState ? window.history.state : {},
|
||||
// Identifier is shortened intentionally.
|
||||
// __NA is used to identify if the history entry can be handled by the app-router.
|
||||
// __N is used to identify if the history entry can be handled by the old router.
|
||||
__NA: true,
|
||||
__PRIVATE_NEXTJS_INTERNALS_TREE: tree
|
||||
};
|
||||
if (pushRef.pendingPush && // Skip pushing an additional history entry if the canonicalUrl is the same as the current url.
|
||||
// This mirrors the browser behavior for normal navigation.
|
||||
createHrefFromUrl(new URL(window.location.href)) !== canonicalUrl) {
|
||||
// This intentionally mutates React state, pushRef is overwritten to ensure additional push/replace calls do not trigger an additional history entry.
|
||||
pushRef.pendingPush = false;
|
||||
window.history.pushState(historyState, '', canonicalUrl);
|
||||
} else {
|
||||
window.history.replaceState(historyState, '', canonicalUrl);
|
||||
}
|
||||
}, [
|
||||
appRouterState
|
||||
]);
|
||||
return null;
|
||||
}
|
||||
export function createEmptyCacheNode() {
|
||||
return {
|
||||
lazyData: null,
|
||||
rsc: null,
|
||||
prefetchRsc: null,
|
||||
head: null,
|
||||
prefetchHead: null,
|
||||
parallelRoutes: new Map(),
|
||||
loading: null
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Server response that only patches the cache and tree.
|
||||
*/ function useChangeByServerResponse(dispatch) {
|
||||
return useCallback((param)=>{
|
||||
let { previousTree, serverResponse } = param;
|
||||
startTransition(()=>{
|
||||
dispatch({
|
||||
type: ACTION_SERVER_PATCH,
|
||||
previousTree,
|
||||
serverResponse
|
||||
});
|
||||
});
|
||||
}, [
|
||||
dispatch
|
||||
]);
|
||||
}
|
||||
function useNavigate(dispatch) {
|
||||
return useCallback((href, navigateType, shouldScroll)=>{
|
||||
const url = new URL(addBasePath(href), location.href);
|
||||
if (process.env.__NEXT_APP_NAV_FAIL_HANDLING) {
|
||||
window.next.__pendingUrl = url;
|
||||
}
|
||||
return dispatch({
|
||||
type: ACTION_NAVIGATE,
|
||||
url,
|
||||
isExternalUrl: isExternalURL(url),
|
||||
locationSearch: location.search,
|
||||
shouldScroll: shouldScroll != null ? shouldScroll : true,
|
||||
navigateType,
|
||||
allowAliasing: true
|
||||
});
|
||||
}, [
|
||||
dispatch
|
||||
]);
|
||||
}
|
||||
function copyNextJsInternalHistoryState(data) {
|
||||
if (data == null) data = {};
|
||||
const currentState = window.history.state;
|
||||
const __NA = currentState == null ? void 0 : currentState.__NA;
|
||||
if (__NA) {
|
||||
data.__NA = __NA;
|
||||
}
|
||||
const __PRIVATE_NEXTJS_INTERNALS_TREE = currentState == null ? void 0 : currentState.__PRIVATE_NEXTJS_INTERNALS_TREE;
|
||||
if (__PRIVATE_NEXTJS_INTERNALS_TREE) {
|
||||
data.__PRIVATE_NEXTJS_INTERNALS_TREE = __PRIVATE_NEXTJS_INTERNALS_TREE;
|
||||
}
|
||||
return data;
|
||||
}
|
||||
function Head(param) {
|
||||
let { headCacheNode } = param;
|
||||
// If this segment has a `prefetchHead`, it's the statically prefetched data.
|
||||
// We should use that on initial render instead of `head`. Then we'll switch
|
||||
// to `head` when the dynamic response streams in.
|
||||
const head = headCacheNode !== null ? headCacheNode.head : null;
|
||||
const prefetchHead = headCacheNode !== null ? headCacheNode.prefetchHead : null;
|
||||
// If no prefetch data is available, then we go straight to rendering `head`.
|
||||
const resolvedPrefetchRsc = prefetchHead !== null ? prefetchHead : head;
|
||||
// We use `useDeferredValue` to handle switching between the prefetched and
|
||||
// final values. The second argument is returned on initial render, then it
|
||||
// re-renders with the first argument.
|
||||
//
|
||||
// @ts-expect-error The second argument to `useDeferredValue` is only
|
||||
// available in the experimental builds. When its disabled, it will always
|
||||
// return `head`.
|
||||
return useDeferredValue(head, resolvedPrefetchRsc);
|
||||
}
|
||||
/**
|
||||
* The global router that wraps the application components.
|
||||
*/ function Router(param) {
|
||||
let { actionQueue, assetPrefix } = param;
|
||||
const [state, dispatch] = useReducer(actionQueue);
|
||||
const { canonicalUrl } = useUnwrapState(state);
|
||||
// Add memoized pathname/query for useSearchParams and usePathname.
|
||||
const { searchParams, pathname } = useMemo(()=>{
|
||||
const url = new URL(canonicalUrl, typeof window === 'undefined' ? 'http://n' : window.location.href);
|
||||
return {
|
||||
// This is turned into a readonly class in `useSearchParams`
|
||||
searchParams: url.searchParams,
|
||||
pathname: hasBasePath(url.pathname) ? removeBasePath(url.pathname) : url.pathname
|
||||
};
|
||||
}, [
|
||||
canonicalUrl
|
||||
]);
|
||||
const changeByServerResponse = useChangeByServerResponse(dispatch);
|
||||
const navigate = useNavigate(dispatch);
|
||||
useServerActionDispatcher(dispatch);
|
||||
/**
|
||||
* The app router that is exposed through `useRouter`. It's only concerned with dispatching actions to the reducer, does not hold state.
|
||||
*/ const appRouter = useMemo(()=>{
|
||||
const routerInstance = {
|
||||
back: ()=>window.history.back(),
|
||||
forward: ()=>window.history.forward(),
|
||||
prefetch: process.env.__NEXT_PPR && process.env.__NEXT_CLIENT_SEGMENT_CACHE ? // data in the router reducer state; it writes into a global mutable
|
||||
// cache. So we don't need to dispatch an action.
|
||||
(href)=>prefetchWithSegmentCache(href, actionQueue.state.nextUrl) : (href, options)=>{
|
||||
// Use the old prefetch implementation.
|
||||
const url = createPrefetchURL(href);
|
||||
if (url !== null) {
|
||||
startTransition(()=>{
|
||||
var _options_kind;
|
||||
dispatch({
|
||||
type: ACTION_PREFETCH,
|
||||
url,
|
||||
kind: (_options_kind = options == null ? void 0 : options.kind) != null ? _options_kind : PrefetchKind.FULL
|
||||
});
|
||||
});
|
||||
}
|
||||
},
|
||||
replace: (href, options)=>{
|
||||
if (options === void 0) options = {};
|
||||
startTransition(()=>{
|
||||
var _options_scroll;
|
||||
navigate(href, 'replace', (_options_scroll = options.scroll) != null ? _options_scroll : true);
|
||||
});
|
||||
},
|
||||
push: (href, options)=>{
|
||||
if (options === void 0) options = {};
|
||||
startTransition(()=>{
|
||||
var _options_scroll;
|
||||
navigate(href, 'push', (_options_scroll = options.scroll) != null ? _options_scroll : true);
|
||||
});
|
||||
},
|
||||
refresh: ()=>{
|
||||
startTransition(()=>{
|
||||
dispatch({
|
||||
type: ACTION_REFRESH,
|
||||
origin: window.location.origin
|
||||
});
|
||||
});
|
||||
},
|
||||
hmrRefresh: ()=>{
|
||||
if (process.env.NODE_ENV !== 'development') {
|
||||
throw new Error('hmrRefresh can only be used in development mode. Please use refresh instead.');
|
||||
} else {
|
||||
startTransition(()=>{
|
||||
dispatch({
|
||||
type: ACTION_HMR_REFRESH,
|
||||
origin: window.location.origin
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
return routerInstance;
|
||||
}, [
|
||||
actionQueue,
|
||||
dispatch,
|
||||
navigate
|
||||
]);
|
||||
useEffect(()=>{
|
||||
// Exists for debugging purposes. Don't use in application code.
|
||||
if (window.next) {
|
||||
window.next.router = appRouter;
|
||||
}
|
||||
}, [
|
||||
appRouter
|
||||
]);
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
// eslint-disable-next-line react-hooks/rules-of-hooks
|
||||
const { cache, prefetchCache, tree } = useUnwrapState(state);
|
||||
// This hook is in a conditional but that is ok because `process.env.NODE_ENV` never changes
|
||||
// eslint-disable-next-line react-hooks/rules-of-hooks
|
||||
useEffect(()=>{
|
||||
// Add `window.nd` for debugging purposes.
|
||||
// This is not meant for use in applications as concurrent rendering will affect the cache/tree/router.
|
||||
// @ts-ignore this is for debugging
|
||||
window.nd = {
|
||||
router: appRouter,
|
||||
cache,
|
||||
prefetchCache,
|
||||
tree
|
||||
};
|
||||
}, [
|
||||
appRouter,
|
||||
cache,
|
||||
prefetchCache,
|
||||
tree
|
||||
]);
|
||||
}
|
||||
useEffect(()=>{
|
||||
// If the app is restored from bfcache, it's possible that
|
||||
// pushRef.mpaNavigation is true, which would mean that any re-render of this component
|
||||
// would trigger the mpa navigation logic again from the lines below.
|
||||
// This will restore the router to the initial state in the event that the app is restored from bfcache.
|
||||
function handlePageShow(event) {
|
||||
var _window_history_state;
|
||||
if (!event.persisted || !((_window_history_state = window.history.state) == null ? void 0 : _window_history_state.__PRIVATE_NEXTJS_INTERNALS_TREE)) {
|
||||
return;
|
||||
}
|
||||
// Clear the pendingMpaPath value so that a subsequent MPA navigation to the same URL can be triggered.
|
||||
// This is necessary because if the browser restored from bfcache, the pendingMpaPath would still be set to the value
|
||||
// of the last MPA navigation.
|
||||
globalMutable.pendingMpaPath = undefined;
|
||||
dispatch({
|
||||
type: ACTION_RESTORE,
|
||||
url: new URL(window.location.href),
|
||||
tree: window.history.state.__PRIVATE_NEXTJS_INTERNALS_TREE
|
||||
});
|
||||
}
|
||||
window.addEventListener('pageshow', handlePageShow);
|
||||
return ()=>{
|
||||
window.removeEventListener('pageshow', handlePageShow);
|
||||
};
|
||||
}, [
|
||||
dispatch
|
||||
]);
|
||||
useEffect(()=>{
|
||||
// Ensure that any redirect errors that bubble up outside of the RedirectBoundary
|
||||
// are caught and handled by the router.
|
||||
function handleUnhandledRedirect(event) {
|
||||
const error = 'reason' in event ? event.reason : event.error;
|
||||
if (isRedirectError(error)) {
|
||||
event.preventDefault();
|
||||
const url = getURLFromRedirectError(error);
|
||||
const redirectType = getRedirectTypeFromError(error);
|
||||
if (redirectType === RedirectType.push) {
|
||||
appRouter.push(url, {});
|
||||
} else {
|
||||
appRouter.replace(url, {});
|
||||
}
|
||||
}
|
||||
}
|
||||
window.addEventListener('error', handleUnhandledRedirect);
|
||||
window.addEventListener('unhandledrejection', handleUnhandledRedirect);
|
||||
return ()=>{
|
||||
window.removeEventListener('error', handleUnhandledRedirect);
|
||||
window.removeEventListener('unhandledrejection', handleUnhandledRedirect);
|
||||
};
|
||||
}, [
|
||||
appRouter
|
||||
]);
|
||||
// When mpaNavigation flag is set do a hard navigation to the new url.
|
||||
// Infinitely suspend because we don't actually want to rerender any child
|
||||
// components with the new URL and any entangled state updates shouldn't
|
||||
// commit either (eg: useTransition isPending should stay true until the page
|
||||
// unloads).
|
||||
//
|
||||
// This is a side effect in render. Don't try this at home, kids. It's
|
||||
// probably safe because we know this is a singleton component and it's never
|
||||
// in <Offscreen>. At least I hope so. (It will run twice in dev strict mode,
|
||||
// but that's... fine?)
|
||||
const { pushRef } = useUnwrapState(state);
|
||||
if (pushRef.mpaNavigation) {
|
||||
// if there's a re-render, we don't want to trigger another redirect if one is already in flight to the same URL
|
||||
if (globalMutable.pendingMpaPath !== canonicalUrl) {
|
||||
const location1 = window.location;
|
||||
if (pushRef.pendingPush) {
|
||||
location1.assign(canonicalUrl);
|
||||
} else {
|
||||
location1.replace(canonicalUrl);
|
||||
}
|
||||
globalMutable.pendingMpaPath = canonicalUrl;
|
||||
}
|
||||
// TODO-APP: Should we listen to navigateerror here to catch failed
|
||||
// navigations somehow? And should we call window.stop() if a SPA navigation
|
||||
// should interrupt an MPA one?
|
||||
use(unresolvedThenable);
|
||||
}
|
||||
useEffect(()=>{
|
||||
const originalPushState = window.history.pushState.bind(window.history);
|
||||
const originalReplaceState = window.history.replaceState.bind(window.history);
|
||||
// Ensure the canonical URL in the Next.js Router is updated when the URL is changed so that `usePathname` and `useSearchParams` hold the pushed values.
|
||||
const applyUrlFromHistoryPushReplace = (url)=>{
|
||||
var _window_history_state;
|
||||
const href = window.location.href;
|
||||
const tree = (_window_history_state = window.history.state) == null ? void 0 : _window_history_state.__PRIVATE_NEXTJS_INTERNALS_TREE;
|
||||
startTransition(()=>{
|
||||
dispatch({
|
||||
type: ACTION_RESTORE,
|
||||
url: new URL(url != null ? url : href, href),
|
||||
tree
|
||||
});
|
||||
});
|
||||
};
|
||||
/**
|
||||
* Patch pushState to ensure external changes to the history are reflected in the Next.js Router.
|
||||
* Ensures Next.js internal history state is copied to the new history entry.
|
||||
* Ensures usePathname and useSearchParams hold the newly provided url.
|
||||
*/ window.history.pushState = function pushState(data, _unused, url) {
|
||||
// Avoid a loop when Next.js internals trigger pushState/replaceState
|
||||
if ((data == null ? void 0 : data.__NA) || (data == null ? void 0 : data._N)) {
|
||||
return originalPushState(data, _unused, url);
|
||||
}
|
||||
data = copyNextJsInternalHistoryState(data);
|
||||
if (url) {
|
||||
applyUrlFromHistoryPushReplace(url);
|
||||
}
|
||||
return originalPushState(data, _unused, url);
|
||||
};
|
||||
/**
|
||||
* Patch replaceState to ensure external changes to the history are reflected in the Next.js Router.
|
||||
* Ensures Next.js internal history state is copied to the new history entry.
|
||||
* Ensures usePathname and useSearchParams hold the newly provided url.
|
||||
*/ window.history.replaceState = function replaceState(data, _unused, url) {
|
||||
// Avoid a loop when Next.js internals trigger pushState/replaceState
|
||||
if ((data == null ? void 0 : data.__NA) || (data == null ? void 0 : data._N)) {
|
||||
return originalReplaceState(data, _unused, url);
|
||||
}
|
||||
data = copyNextJsInternalHistoryState(data);
|
||||
if (url) {
|
||||
applyUrlFromHistoryPushReplace(url);
|
||||
}
|
||||
return originalReplaceState(data, _unused, url);
|
||||
};
|
||||
/**
|
||||
* Handle popstate event, this is used to handle back/forward in the browser.
|
||||
* By default dispatches ACTION_RESTORE, however if the history entry was not pushed/replaced by app-router it will reload the page.
|
||||
* That case can happen when the old router injected the history entry.
|
||||
*/ const onPopState = (event)=>{
|
||||
if (!event.state) {
|
||||
// TODO-APP: this case only happens when pushState/replaceState was called outside of Next.js. It should probably reload the page in this case.
|
||||
return;
|
||||
}
|
||||
// This case happens when the history entry was pushed by the `pages` router.
|
||||
if (!event.state.__NA) {
|
||||
window.location.reload();
|
||||
return;
|
||||
}
|
||||
// TODO-APP: Ideally the back button should not use startTransition as it should apply the updates synchronously
|
||||
// Without startTransition works if the cache is there for this path
|
||||
startTransition(()=>{
|
||||
dispatch({
|
||||
type: ACTION_RESTORE,
|
||||
url: new URL(window.location.href),
|
||||
tree: event.state.__PRIVATE_NEXTJS_INTERNALS_TREE
|
||||
});
|
||||
});
|
||||
};
|
||||
// Register popstate event to call onPopstate.
|
||||
window.addEventListener('popstate', onPopState);
|
||||
return ()=>{
|
||||
window.history.pushState = originalPushState;
|
||||
window.history.replaceState = originalReplaceState;
|
||||
window.removeEventListener('popstate', onPopState);
|
||||
};
|
||||
}, [
|
||||
dispatch
|
||||
]);
|
||||
const { cache, tree, nextUrl, focusAndScrollRef } = useUnwrapState(state);
|
||||
const matchingHead = useMemo(()=>{
|
||||
return findHeadInCache(cache, tree[1]);
|
||||
}, [
|
||||
cache,
|
||||
tree
|
||||
]);
|
||||
// Add memoized pathParams for useParams.
|
||||
const pathParams = useMemo(()=>{
|
||||
return getSelectedParams(tree);
|
||||
}, [
|
||||
tree
|
||||
]);
|
||||
const layoutRouterContext = useMemo(()=>{
|
||||
return {
|
||||
childNodes: cache.parallelRoutes,
|
||||
tree,
|
||||
// Root node always has `url`
|
||||
// Provided in AppTreeContext to ensure it can be overwritten in layout-router
|
||||
url: canonicalUrl,
|
||||
loading: cache.loading
|
||||
};
|
||||
}, [
|
||||
cache.parallelRoutes,
|
||||
tree,
|
||||
canonicalUrl,
|
||||
cache.loading
|
||||
]);
|
||||
const globalLayoutRouterContext = useMemo(()=>{
|
||||
return {
|
||||
changeByServerResponse,
|
||||
tree,
|
||||
focusAndScrollRef,
|
||||
nextUrl
|
||||
};
|
||||
}, [
|
||||
changeByServerResponse,
|
||||
tree,
|
||||
focusAndScrollRef,
|
||||
nextUrl
|
||||
]);
|
||||
let head;
|
||||
if (matchingHead !== null) {
|
||||
// The head is wrapped in an extra component so we can use
|
||||
// `useDeferredValue` to swap between the prefetched and final versions of
|
||||
// the head. (This is what LayoutRouter does for segment data, too.)
|
||||
//
|
||||
// The `key` is used to remount the component whenever the head moves to
|
||||
// a different segment.
|
||||
const [headCacheNode, headKey] = matchingHead;
|
||||
head = /*#__PURE__*/ _jsx(Head, {
|
||||
headCacheNode: headCacheNode
|
||||
}, headKey);
|
||||
} else {
|
||||
head = null;
|
||||
}
|
||||
let content = /*#__PURE__*/ _jsxs(RedirectBoundary, {
|
||||
children: [
|
||||
head,
|
||||
cache.rsc,
|
||||
/*#__PURE__*/ _jsx(AppRouterAnnouncer, {
|
||||
tree: tree
|
||||
})
|
||||
]
|
||||
});
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
if (typeof window !== 'undefined') {
|
||||
const { DevRootHTTPAccessFallbackBoundary } = require('./dev-root-http-access-fallback-boundary');
|
||||
content = /*#__PURE__*/ _jsx(DevRootHTTPAccessFallbackBoundary, {
|
||||
children: content
|
||||
});
|
||||
}
|
||||
const HotReloader = require('./react-dev-overlay/app/hot-reloader-client').default;
|
||||
content = /*#__PURE__*/ _jsx(HotReloader, {
|
||||
assetPrefix: assetPrefix,
|
||||
children: content
|
||||
});
|
||||
}
|
||||
return /*#__PURE__*/ _jsxs(_Fragment, {
|
||||
children: [
|
||||
/*#__PURE__*/ _jsx(HistoryUpdater, {
|
||||
appRouterState: useUnwrapState(state)
|
||||
}),
|
||||
/*#__PURE__*/ _jsx(RuntimeStyles, {}),
|
||||
/*#__PURE__*/ _jsx(PathParamsContext.Provider, {
|
||||
value: pathParams,
|
||||
children: /*#__PURE__*/ _jsx(PathnameContext.Provider, {
|
||||
value: pathname,
|
||||
children: /*#__PURE__*/ _jsx(SearchParamsContext.Provider, {
|
||||
value: searchParams,
|
||||
children: /*#__PURE__*/ _jsx(GlobalLayoutRouterContext.Provider, {
|
||||
value: globalLayoutRouterContext,
|
||||
children: /*#__PURE__*/ _jsx(AppRouterContext.Provider, {
|
||||
value: appRouter,
|
||||
children: /*#__PURE__*/ _jsx(LayoutRouterContext.Provider, {
|
||||
value: layoutRouterContext,
|
||||
children: content
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
]
|
||||
});
|
||||
}
|
||||
export default function AppRouter(param) {
|
||||
let { actionQueue, globalErrorComponentAndStyles: [globalErrorComponent, globalErrorStyles], assetPrefix } = param;
|
||||
useNavFailureHandler();
|
||||
return /*#__PURE__*/ _jsx(ErrorBoundary, {
|
||||
errorComponent: globalErrorComponent,
|
||||
errorStyles: globalErrorStyles,
|
||||
children: /*#__PURE__*/ _jsx(Router, {
|
||||
actionQueue: actionQueue,
|
||||
assetPrefix: assetPrefix
|
||||
})
|
||||
});
|
||||
}
|
||||
const runtimeStyles = new Set();
|
||||
let runtimeStyleChanged = new Set();
|
||||
globalThis._N_E_STYLE_LOAD = function(href) {
|
||||
let len = runtimeStyles.size;
|
||||
runtimeStyles.add(href);
|
||||
if (runtimeStyles.size !== len) {
|
||||
runtimeStyleChanged.forEach((cb)=>cb());
|
||||
}
|
||||
// TODO figure out how to get a promise here
|
||||
// But maybe it's not necessary as react would block rendering until it's loaded
|
||||
return Promise.resolve();
|
||||
};
|
||||
function RuntimeStyles() {
|
||||
const [, forceUpdate] = React.useState(0);
|
||||
const renderedStylesSize = runtimeStyles.size;
|
||||
useEffect(()=>{
|
||||
const changed = ()=>forceUpdate((c)=>c + 1);
|
||||
runtimeStyleChanged.add(changed);
|
||||
if (renderedStylesSize !== runtimeStyles.size) {
|
||||
changed();
|
||||
}
|
||||
return ()=>{
|
||||
runtimeStyleChanged.delete(changed);
|
||||
};
|
||||
}, [
|
||||
renderedStylesSize,
|
||||
forceUpdate
|
||||
]);
|
||||
const dplId = process.env.NEXT_DEPLOYMENT_ID ? "?dpl=" + process.env.NEXT_DEPLOYMENT_ID : '';
|
||||
return [
|
||||
...runtimeStyles
|
||||
].map((href, i)=>/*#__PURE__*/ _jsx("link", {
|
||||
rel: "stylesheet",
|
||||
href: "" + href + dplId,
|
||||
// @ts-ignore
|
||||
precedence: "next"
|
||||
}, i));
|
||||
}
|
||||
|
||||
//# sourceMappingURL=app-router.js.map
|
||||
+1
File diff suppressed because one or more lines are too long
+9
@@ -0,0 +1,9 @@
|
||||
import { BailoutToCSRError } from '../../shared/lib/lazy-dynamic/bailout-to-csr';
|
||||
import { workAsyncStorage } from '../../server/app-render/work-async-storage.external';
|
||||
export function bailoutToClientRendering(reason) {
|
||||
const workStore = workAsyncStorage.getStore();
|
||||
if (workStore == null ? void 0 : workStore.forceStatic) return;
|
||||
if (workStore == null ? void 0 : workStore.isStaticGeneration) throw new BailoutToCSRError(reason);
|
||||
}
|
||||
|
||||
//# sourceMappingURL=bailout-to-client-rendering.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../src/client/components/bailout-to-client-rendering.ts"],"sourcesContent":["import { BailoutToCSRError } from '../../shared/lib/lazy-dynamic/bailout-to-csr'\nimport { workAsyncStorage } from '../../server/app-render/work-async-storage.external'\n\nexport function bailoutToClientRendering(reason: string): void | never {\n const workStore = workAsyncStorage.getStore()\n\n if (workStore?.forceStatic) return\n\n if (workStore?.isStaticGeneration) throw new BailoutToCSRError(reason)\n}\n"],"names":["BailoutToCSRError","workAsyncStorage","bailoutToClientRendering","reason","workStore","getStore","forceStatic","isStaticGeneration"],"mappings":"AAAA,SAASA,iBAAiB,QAAQ,+CAA8C;AAChF,SAASC,gBAAgB,QAAQ,sDAAqD;AAEtF,OAAO,SAASC,yBAAyBC,MAAc;IACrD,MAAMC,YAAYH,iBAAiBI,QAAQ;IAE3C,IAAID,6BAAAA,UAAWE,WAAW,EAAE;IAE5B,IAAIF,6BAAAA,UAAWG,kBAAkB,EAAE,MAAM,IAAIP,kBAAkBG;AACjE"}
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
'use client';
|
||||
import { jsx as _jsx } from "react/jsx-runtime";
|
||||
import { InvariantError } from '../../shared/lib/invariant-error';
|
||||
/**
|
||||
* When the Page is a client component we send the params and searchParams to this client wrapper
|
||||
* where they are turned into dynamically tracked values before being passed to the actual Page component.
|
||||
*
|
||||
* additionally we may send promises representing the params and searchParams. We don't ever use these passed
|
||||
* values but it can be necessary for the sender to send a Promise that doesn't resolve in certain situations.
|
||||
* It is up to the caller to decide if the promises are needed.
|
||||
*/ export function ClientPageRoot(param) {
|
||||
let { Component, searchParams, params, // eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
promises } = param;
|
||||
if (typeof window === 'undefined') {
|
||||
const { workAsyncStorage } = require('../../server/app-render/work-async-storage.external');
|
||||
let clientSearchParams;
|
||||
let clientParams;
|
||||
// We are going to instrument the searchParams prop with tracking for the
|
||||
// appropriate context. We wrap differently in prerendering vs rendering
|
||||
const store = workAsyncStorage.getStore();
|
||||
if (!store) {
|
||||
throw new InvariantError('Expected workStore to exist when handling searchParams in a client Page.');
|
||||
}
|
||||
const { createSearchParamsFromClient } = require('../../server/request/search-params');
|
||||
clientSearchParams = createSearchParamsFromClient(searchParams, store);
|
||||
const { createParamsFromClient } = require('../../server/request/params');
|
||||
clientParams = createParamsFromClient(params, store);
|
||||
return /*#__PURE__*/ _jsx(Component, {
|
||||
params: clientParams,
|
||||
searchParams: clientSearchParams
|
||||
});
|
||||
} else {
|
||||
const { createRenderSearchParamsFromClient } = require('../../server/request/search-params.browser');
|
||||
const clientSearchParams = createRenderSearchParamsFromClient(searchParams);
|
||||
const { createRenderParamsFromClient } = require('../../server/request/params.browser');
|
||||
const clientParams = createRenderParamsFromClient(params);
|
||||
return /*#__PURE__*/ _jsx(Component, {
|
||||
params: clientParams,
|
||||
searchParams: clientSearchParams
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
//# sourceMappingURL=client-page.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../src/client/components/client-page.tsx"],"sourcesContent":["'use client'\n\nimport type { ParsedUrlQuery } from 'querystring'\nimport { InvariantError } from '../../shared/lib/invariant-error'\n\nimport type { Params } from '../../server/request/params'\n\n/**\n * When the Page is a client component we send the params and searchParams to this client wrapper\n * where they are turned into dynamically tracked values before being passed to the actual Page component.\n *\n * additionally we may send promises representing the params and searchParams. We don't ever use these passed\n * values but it can be necessary for the sender to send a Promise that doesn't resolve in certain situations.\n * It is up to the caller to decide if the promises are needed.\n */\nexport function ClientPageRoot({\n Component,\n searchParams,\n params,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n promises,\n}: {\n Component: React.ComponentType<any>\n searchParams: ParsedUrlQuery\n params: Params\n promises?: Array<Promise<any>>\n}) {\n if (typeof window === 'undefined') {\n const { workAsyncStorage } =\n require('../../server/app-render/work-async-storage.external') as typeof import('../../server/app-render/work-async-storage.external')\n\n let clientSearchParams: Promise<ParsedUrlQuery>\n let clientParams: Promise<Params>\n // We are going to instrument the searchParams prop with tracking for the\n // appropriate context. We wrap differently in prerendering vs rendering\n const store = workAsyncStorage.getStore()\n if (!store) {\n throw new InvariantError(\n 'Expected workStore to exist when handling searchParams in a client Page.'\n )\n }\n\n const { createSearchParamsFromClient } =\n require('../../server/request/search-params') as typeof import('../../server/request/search-params')\n clientSearchParams = createSearchParamsFromClient(searchParams, store)\n\n const { createParamsFromClient } =\n require('../../server/request/params') as typeof import('../../server/request/params')\n clientParams = createParamsFromClient(params, store)\n\n return <Component params={clientParams} searchParams={clientSearchParams} />\n } else {\n const { createRenderSearchParamsFromClient } =\n require('../../server/request/search-params.browser') as typeof import('../../server/request/search-params.browser')\n const clientSearchParams = createRenderSearchParamsFromClient(searchParams)\n const { createRenderParamsFromClient } =\n require('../../server/request/params.browser') as typeof import('../../server/request/params.browser')\n const clientParams = createRenderParamsFromClient(params)\n\n return <Component params={clientParams} searchParams={clientSearchParams} />\n }\n}\n"],"names":["InvariantError","ClientPageRoot","Component","searchParams","params","promises","window","workAsyncStorage","require","clientSearchParams","clientParams","store","getStore","createSearchParamsFromClient","createParamsFromClient","createRenderSearchParamsFromClient","createRenderParamsFromClient"],"mappings":"AAAA;;AAGA,SAASA,cAAc,QAAQ,mCAAkC;AAIjE;;;;;;;CAOC,GACD,OAAO,SAASC,eAAe,KAW9B;IAX8B,IAAA,EAC7BC,SAAS,EACTC,YAAY,EACZC,MAAM,EACN,6DAA6D;IAC7DC,QAAQ,EAMT,GAX8B;IAY7B,IAAI,OAAOC,WAAW,aAAa;QACjC,MAAM,EAAEC,gBAAgB,EAAE,GACxBC,QAAQ;QAEV,IAAIC;QACJ,IAAIC;QACJ,yEAAyE;QACzE,wEAAwE;QACxE,MAAMC,QAAQJ,iBAAiBK,QAAQ;QACvC,IAAI,CAACD,OAAO;YACV,MAAM,IAAIX,eACR;QAEJ;QAEA,MAAM,EAAEa,4BAA4B,EAAE,GACpCL,QAAQ;QACVC,qBAAqBI,6BAA6BV,cAAcQ;QAEhE,MAAM,EAAEG,sBAAsB,EAAE,GAC9BN,QAAQ;QACVE,eAAeI,uBAAuBV,QAAQO;QAE9C,qBAAO,KAACT;YAAUE,QAAQM;YAAcP,cAAcM;;IACxD,OAAO;QACL,MAAM,EAAEM,kCAAkC,EAAE,GAC1CP,QAAQ;QACV,MAAMC,qBAAqBM,mCAAmCZ;QAC9D,MAAM,EAAEa,4BAA4B,EAAE,GACpCR,QAAQ;QACV,MAAME,eAAeM,6BAA6BZ;QAElD,qBAAO,KAACF;YAAUE,QAAQM;YAAcP,cAAcM;;IACxD;AACF"}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
'use client';
|
||||
import { jsx as _jsx } from "react/jsx-runtime";
|
||||
import { InvariantError } from '../../shared/lib/invariant-error';
|
||||
/**
|
||||
* When the Page is a client component we send the params to this client wrapper
|
||||
* where they are turned into dynamically tracked values before being passed to the actual Segment component.
|
||||
*
|
||||
* additionally we may send a promise representing params. We don't ever use this passed
|
||||
* value but it can be necessary for the sender to send a Promise that doesn't resolve in certain situations
|
||||
* such as when dynamicIO is enabled. It is up to the caller to decide if the promises are needed.
|
||||
*/ export function ClientSegmentRoot(param) {
|
||||
let { Component, slots, params, // eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
promise } = param;
|
||||
if (typeof window === 'undefined') {
|
||||
const { workAsyncStorage } = require('../../server/app-render/work-async-storage.external');
|
||||
let clientParams;
|
||||
// We are going to instrument the searchParams prop with tracking for the
|
||||
// appropriate context. We wrap differently in prerendering vs rendering
|
||||
const store = workAsyncStorage.getStore();
|
||||
if (!store) {
|
||||
throw new InvariantError('Expected workStore to exist when handling params in a client segment such as a Layout or Template.');
|
||||
}
|
||||
const { createParamsFromClient } = require('../../server/request/params');
|
||||
clientParams = createParamsFromClient(params, store);
|
||||
return /*#__PURE__*/ _jsx(Component, {
|
||||
...slots,
|
||||
params: clientParams
|
||||
});
|
||||
} else {
|
||||
const { createRenderParamsFromClient } = require('../../server/request/params.browser');
|
||||
const clientParams = createRenderParamsFromClient(params);
|
||||
return /*#__PURE__*/ _jsx(Component, {
|
||||
...slots,
|
||||
params: clientParams
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
//# sourceMappingURL=client-segment.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../src/client/components/client-segment.tsx"],"sourcesContent":["'use client'\n\nimport { InvariantError } from '../../shared/lib/invariant-error'\n\nimport type { Params } from '../../server/request/params'\n\n/**\n * When the Page is a client component we send the params to this client wrapper\n * where they are turned into dynamically tracked values before being passed to the actual Segment component.\n *\n * additionally we may send a promise representing params. We don't ever use this passed\n * value but it can be necessary for the sender to send a Promise that doesn't resolve in certain situations\n * such as when dynamicIO is enabled. It is up to the caller to decide if the promises are needed.\n */\nexport function ClientSegmentRoot({\n Component,\n slots,\n params,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n promise,\n}: {\n Component: React.ComponentType<any>\n slots: { [key: string]: React.ReactNode }\n params: Params\n promise?: Promise<any>\n}) {\n if (typeof window === 'undefined') {\n const { workAsyncStorage } =\n require('../../server/app-render/work-async-storage.external') as typeof import('../../server/app-render/work-async-storage.external')\n\n let clientParams: Promise<Params>\n // We are going to instrument the searchParams prop with tracking for the\n // appropriate context. We wrap differently in prerendering vs rendering\n const store = workAsyncStorage.getStore()\n if (!store) {\n throw new InvariantError(\n 'Expected workStore to exist when handling params in a client segment such as a Layout or Template.'\n )\n }\n\n const { createParamsFromClient } =\n require('../../server/request/params') as typeof import('../../server/request/params')\n clientParams = createParamsFromClient(params, store)\n\n return <Component {...slots} params={clientParams} />\n } else {\n const { createRenderParamsFromClient } =\n require('../../server/request/params.browser') as typeof import('../../server/request/params.browser')\n const clientParams = createRenderParamsFromClient(params)\n return <Component {...slots} params={clientParams} />\n }\n}\n"],"names":["InvariantError","ClientSegmentRoot","Component","slots","params","promise","window","workAsyncStorage","require","clientParams","store","getStore","createParamsFromClient","createRenderParamsFromClient"],"mappings":"AAAA;;AAEA,SAASA,cAAc,QAAQ,mCAAkC;AAIjE;;;;;;;CAOC,GACD,OAAO,SAASC,kBAAkB,KAWjC;IAXiC,IAAA,EAChCC,SAAS,EACTC,KAAK,EACLC,MAAM,EACN,6DAA6D;IAC7DC,OAAO,EAMR,GAXiC;IAYhC,IAAI,OAAOC,WAAW,aAAa;QACjC,MAAM,EAAEC,gBAAgB,EAAE,GACxBC,QAAQ;QAEV,IAAIC;QACJ,yEAAyE;QACzE,wEAAwE;QACxE,MAAMC,QAAQH,iBAAiBI,QAAQ;QACvC,IAAI,CAACD,OAAO;YACV,MAAM,IAAIV,eACR;QAEJ;QAEA,MAAM,EAAEY,sBAAsB,EAAE,GAC9BJ,QAAQ;QACVC,eAAeG,uBAAuBR,QAAQM;QAE9C,qBAAO,KAACR;YAAW,GAAGC,KAAK;YAAEC,QAAQK;;IACvC,OAAO;QACL,MAAM,EAAEI,4BAA4B,EAAE,GACpCL,QAAQ;QACV,MAAMC,eAAeI,6BAA6BT;QAClD,qBAAO,KAACF;YAAW,GAAGC,KAAK;YAAEC,QAAQK;;IACvC;AACF"}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
import { jsx as _jsx } from "react/jsx-runtime";
|
||||
import React from 'react';
|
||||
export default function DefaultLayout(param) {
|
||||
let { children } = param;
|
||||
return /*#__PURE__*/ _jsx("html", {
|
||||
children: /*#__PURE__*/ _jsx("body", {
|
||||
children: children
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
//# sourceMappingURL=default-layout.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../src/client/components/default-layout.tsx"],"sourcesContent":["import React from 'react'\n\nexport default function DefaultLayout({\n children,\n}: {\n children: React.ReactNode\n}) {\n return (\n <html>\n <body>{children}</body>\n </html>\n )\n}\n"],"names":["React","DefaultLayout","children","html","body"],"mappings":";AAAA,OAAOA,WAAW,QAAO;AAEzB,eAAe,SAASC,cAAc,KAIrC;IAJqC,IAAA,EACpCC,QAAQ,EAGT,GAJqC;IAKpC,qBACE,KAACC;kBACC,cAAA,KAACC;sBAAMF;;;AAGb"}
|
||||
Generated
Vendored
+21
@@ -0,0 +1,21 @@
|
||||
'use client';
|
||||
import { jsx as _jsx } from "react/jsx-runtime";
|
||||
import React from 'react';
|
||||
import { HTTPAccessFallbackBoundary } from './http-access-fallback/error-boundary';
|
||||
// TODO: error on using forbidden and unauthorized in root layout
|
||||
export function bailOnRootNotFound() {
|
||||
throw new Error('notFound() is not allowed to use in root layout');
|
||||
}
|
||||
function NotAllowedRootHTTPFallbackError() {
|
||||
bailOnRootNotFound();
|
||||
return null;
|
||||
}
|
||||
export function DevRootHTTPAccessFallbackBoundary(param) {
|
||||
let { children } = param;
|
||||
return /*#__PURE__*/ _jsx(HTTPAccessFallbackBoundary, {
|
||||
notFound: /*#__PURE__*/ _jsx(NotAllowedRootHTTPFallbackError, {}),
|
||||
children: children
|
||||
});
|
||||
}
|
||||
|
||||
//# sourceMappingURL=dev-root-http-access-fallback-boundary.js.map
|
||||
Generated
Vendored
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../src/client/components/dev-root-http-access-fallback-boundary.tsx"],"sourcesContent":["'use client'\n\nimport React from 'react'\nimport { HTTPAccessFallbackBoundary } from './http-access-fallback/error-boundary'\n\n// TODO: error on using forbidden and unauthorized in root layout\nexport function bailOnRootNotFound() {\n throw new Error('notFound() is not allowed to use in root layout')\n}\n\nfunction NotAllowedRootHTTPFallbackError() {\n bailOnRootNotFound()\n return null\n}\n\nexport function DevRootHTTPAccessFallbackBoundary({\n children,\n}: {\n children: React.ReactNode\n}) {\n return (\n <HTTPAccessFallbackBoundary notFound={<NotAllowedRootHTTPFallbackError />}>\n {children}\n </HTTPAccessFallbackBoundary>\n )\n}\n"],"names":["React","HTTPAccessFallbackBoundary","bailOnRootNotFound","Error","NotAllowedRootHTTPFallbackError","DevRootHTTPAccessFallbackBoundary","children","notFound"],"mappings":"AAAA;;AAEA,OAAOA,WAAW,QAAO;AACzB,SAASC,0BAA0B,QAAQ,wCAAuC;AAElF,iEAAiE;AACjE,OAAO,SAASC;IACd,MAAM,IAAIC,MAAM;AAClB;AAEA,SAASC;IACPF;IACA,OAAO;AACT;AAEA,OAAO,SAASG,kCAAkC,KAIjD;IAJiD,IAAA,EAChDC,QAAQ,EAGT,GAJiD;IAKhD,qBACE,KAACL;QAA2BM,wBAAU,KAACH;kBACpCE;;AAGP"}
|
||||
+173
@@ -0,0 +1,173 @@
|
||||
'use client';
|
||||
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
|
||||
import React from 'react';
|
||||
import { useUntrackedPathname } from './navigation-untracked';
|
||||
import { isNextRouterError } from './is-next-router-error';
|
||||
import { handleHardNavError } from './nav-failure-handler';
|
||||
import { workAsyncStorage } from '../../server/app-render/work-async-storage.external';
|
||||
const styles = {
|
||||
error: {
|
||||
// https://github.com/sindresorhus/modern-normalize/blob/main/modern-normalize.css#L38-L52
|
||||
fontFamily: 'system-ui,"Segoe UI",Roboto,Helvetica,Arial,sans-serif,"Apple Color Emoji","Segoe UI Emoji"',
|
||||
height: '100vh',
|
||||
textAlign: 'center',
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center'
|
||||
},
|
||||
text: {
|
||||
fontSize: '14px',
|
||||
fontWeight: 400,
|
||||
lineHeight: '28px',
|
||||
margin: '0 8px'
|
||||
}
|
||||
};
|
||||
// if we are revalidating we want to re-throw the error so the
|
||||
// function crashes so we can maintain our previous cache
|
||||
// instead of caching the error page
|
||||
function HandleISRError(param) {
|
||||
let { error } = param;
|
||||
const store = workAsyncStorage.getStore();
|
||||
if ((store == null ? void 0 : store.isRevalidate) || (store == null ? void 0 : store.isStaticGeneration)) {
|
||||
console.error(error);
|
||||
throw error;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
export class ErrorBoundaryHandler extends React.Component {
|
||||
static getDerivedStateFromError(error) {
|
||||
if (isNextRouterError(error)) {
|
||||
// Re-throw if an expected internal Next.js router error occurs
|
||||
// this means it should be handled by a different boundary (such as a NotFound boundary in a parent segment)
|
||||
throw error;
|
||||
}
|
||||
return {
|
||||
error
|
||||
};
|
||||
}
|
||||
static getDerivedStateFromProps(props, state) {
|
||||
const { error } = state;
|
||||
// if we encounter an error while
|
||||
// a navigation is pending we shouldn't render
|
||||
// the error boundary and instead should fallback
|
||||
// to a hard navigation to attempt recovering
|
||||
if (process.env.__NEXT_APP_NAV_FAIL_HANDLING) {
|
||||
if (error && handleHardNavError(error)) {
|
||||
// clear error so we don't render anything
|
||||
return {
|
||||
error: null,
|
||||
previousPathname: props.pathname
|
||||
};
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Handles reset of the error boundary when a navigation happens.
|
||||
* Ensures the error boundary does not stay enabled when navigating to a new page.
|
||||
* Approach of setState in render is safe as it checks the previous pathname and then overrides
|
||||
* it as outlined in https://react.dev/reference/react/useState#storing-information-from-previous-renders
|
||||
*/ if (props.pathname !== state.previousPathname && state.error) {
|
||||
return {
|
||||
error: null,
|
||||
previousPathname: props.pathname
|
||||
};
|
||||
}
|
||||
return {
|
||||
error: state.error,
|
||||
previousPathname: props.pathname
|
||||
};
|
||||
}
|
||||
// Explicit type is needed to avoid the generated `.d.ts` having a wide return type that could be specific to the `@types/react` version.
|
||||
render() {
|
||||
if (this.state.error) {
|
||||
return /*#__PURE__*/ _jsxs(_Fragment, {
|
||||
children: [
|
||||
/*#__PURE__*/ _jsx(HandleISRError, {
|
||||
error: this.state.error
|
||||
}),
|
||||
this.props.errorStyles,
|
||||
this.props.errorScripts,
|
||||
/*#__PURE__*/ _jsx(this.props.errorComponent, {
|
||||
error: this.state.error,
|
||||
reset: this.reset
|
||||
})
|
||||
]
|
||||
});
|
||||
}
|
||||
return this.props.children;
|
||||
}
|
||||
constructor(props){
|
||||
super(props), this.reset = ()=>{
|
||||
this.setState({
|
||||
error: null
|
||||
});
|
||||
};
|
||||
this.state = {
|
||||
error: null,
|
||||
previousPathname: this.props.pathname
|
||||
};
|
||||
}
|
||||
}
|
||||
export function GlobalError(param) {
|
||||
let { error } = param;
|
||||
const digest = error == null ? void 0 : error.digest;
|
||||
return /*#__PURE__*/ _jsxs("html", {
|
||||
id: "__next_error__",
|
||||
children: [
|
||||
/*#__PURE__*/ _jsx("head", {}),
|
||||
/*#__PURE__*/ _jsxs("body", {
|
||||
children: [
|
||||
/*#__PURE__*/ _jsx(HandleISRError, {
|
||||
error: error
|
||||
}),
|
||||
/*#__PURE__*/ _jsx("div", {
|
||||
style: styles.error,
|
||||
children: /*#__PURE__*/ _jsxs("div", {
|
||||
children: [
|
||||
/*#__PURE__*/ _jsx("h2", {
|
||||
style: styles.text,
|
||||
children: "Application error: a " + (digest ? 'server' : 'client') + "-side exception has occurred (see the " + (digest ? 'server logs' : 'browser console') + " for more information)."
|
||||
}),
|
||||
digest ? /*#__PURE__*/ _jsx("p", {
|
||||
style: styles.text,
|
||||
children: "Digest: " + digest
|
||||
}) : null
|
||||
]
|
||||
})
|
||||
})
|
||||
]
|
||||
})
|
||||
]
|
||||
});
|
||||
}
|
||||
// Exported so that the import signature in the loaders can be identical to user
|
||||
// supplied custom global error signatures.
|
||||
export default GlobalError;
|
||||
/**
|
||||
* Handles errors through `getDerivedStateFromError`.
|
||||
* Renders the provided error component and provides a way to `reset` the error boundary state.
|
||||
*/ /**
|
||||
* Renders error boundary with the provided "errorComponent" property as the fallback.
|
||||
* If no "errorComponent" property is provided it renders the children without an error boundary.
|
||||
*/ export function ErrorBoundary(param) {
|
||||
let { errorComponent, errorStyles, errorScripts, children } = param;
|
||||
// When we're rendering the missing params shell, this will return null. This
|
||||
// is because we won't be rendering any not found boundaries or error
|
||||
// boundaries for the missing params shell. When this runs on the client
|
||||
// (where these errors can occur), we will get the correct pathname.
|
||||
const pathname = useUntrackedPathname();
|
||||
if (errorComponent) {
|
||||
return /*#__PURE__*/ _jsx(ErrorBoundaryHandler, {
|
||||
pathname: pathname,
|
||||
errorComponent: errorComponent,
|
||||
errorStyles: errorStyles,
|
||||
errorScripts: errorScripts,
|
||||
children: children
|
||||
});
|
||||
}
|
||||
return /*#__PURE__*/ _jsx(_Fragment, {
|
||||
children: children
|
||||
});
|
||||
}
|
||||
|
||||
//# sourceMappingURL=error-boundary.js.map
|
||||
+1
File diff suppressed because one or more lines are too long
+10
@@ -0,0 +1,10 @@
|
||||
import { jsx as _jsx } from "react/jsx-runtime";
|
||||
import { HTTPAccessErrorFallback } from './http-access-fallback/error-fallback';
|
||||
export default function Forbidden() {
|
||||
return /*#__PURE__*/ _jsx(HTTPAccessErrorFallback, {
|
||||
status: 403,
|
||||
message: "This page could not be accessed."
|
||||
});
|
||||
}
|
||||
|
||||
//# sourceMappingURL=forbidden-error.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../src/client/components/forbidden-error.tsx"],"sourcesContent":["import { HTTPAccessErrorFallback } from './http-access-fallback/error-fallback'\n\nexport default function Forbidden() {\n return (\n <HTTPAccessErrorFallback\n status={403}\n message=\"This page could not be accessed.\"\n />\n )\n}\n"],"names":["HTTPAccessErrorFallback","Forbidden","status","message"],"mappings":";AAAA,SAASA,uBAAuB,QAAQ,wCAAuC;AAE/E,eAAe,SAASC;IACtB,qBACE,KAACD;QACCE,QAAQ;QACRC,SAAQ;;AAGd"}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
import { HTTP_ERROR_FALLBACK_ERROR_CODE } from './http-access-fallback/http-access-fallback';
|
||||
// TODO: Add `forbidden` docs
|
||||
/**
|
||||
* @experimental
|
||||
* This function allows you to render the [forbidden.js file](https://nextjs.org/docs/app/api-reference/file-conventions/forbidden)
|
||||
* within a route segment as well as inject a tag.
|
||||
*
|
||||
* `forbidden()` can be used in
|
||||
* [Server Components](https://nextjs.org/docs/app/building-your-application/rendering/server-components),
|
||||
* [Route Handlers](https://nextjs.org/docs/app/building-your-application/routing/route-handlers), and
|
||||
* [Server Actions](https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions-and-mutations).
|
||||
*
|
||||
* Read more: [Next.js Docs: `forbidden`](https://nextjs.org/docs/app/api-reference/functions/forbidden)
|
||||
*/ const DIGEST = "" + HTTP_ERROR_FALLBACK_ERROR_CODE + ";403";
|
||||
export function forbidden() {
|
||||
if (!process.env.__NEXT_EXPERIMENTAL_AUTH_INTERRUPTS) {
|
||||
throw new Error("`forbidden()` is experimental and only allowed to be enabled when `experimental.authInterrupts` is enabled.");
|
||||
}
|
||||
// eslint-disable-next-line no-throw-literal
|
||||
const error = new Error(DIGEST);
|
||||
error.digest = DIGEST;
|
||||
throw error;
|
||||
}
|
||||
|
||||
//# sourceMappingURL=forbidden.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../src/client/components/forbidden.ts"],"sourcesContent":["import {\n HTTP_ERROR_FALLBACK_ERROR_CODE,\n type HTTPAccessFallbackError,\n} from './http-access-fallback/http-access-fallback'\n\n// TODO: Add `forbidden` docs\n/**\n * @experimental\n * This function allows you to render the [forbidden.js file](https://nextjs.org/docs/app/api-reference/file-conventions/forbidden)\n * within a route segment as well as inject a tag.\n *\n * `forbidden()` can be used in\n * [Server Components](https://nextjs.org/docs/app/building-your-application/rendering/server-components),\n * [Route Handlers](https://nextjs.org/docs/app/building-your-application/routing/route-handlers), and\n * [Server Actions](https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions-and-mutations).\n *\n * Read more: [Next.js Docs: `forbidden`](https://nextjs.org/docs/app/api-reference/functions/forbidden)\n */\n\nconst DIGEST = `${HTTP_ERROR_FALLBACK_ERROR_CODE};403`\n\nexport function forbidden(): never {\n if (!process.env.__NEXT_EXPERIMENTAL_AUTH_INTERRUPTS) {\n throw new Error(\n `\\`forbidden()\\` is experimental and only allowed to be enabled when \\`experimental.authInterrupts\\` is enabled.`\n )\n }\n\n // eslint-disable-next-line no-throw-literal\n const error = new Error(DIGEST) as HTTPAccessFallbackError\n ;(error as HTTPAccessFallbackError).digest = DIGEST\n throw error\n}\n"],"names":["HTTP_ERROR_FALLBACK_ERROR_CODE","DIGEST","forbidden","process","env","__NEXT_EXPERIMENTAL_AUTH_INTERRUPTS","Error","error","digest"],"mappings":"AAAA,SACEA,8BAA8B,QAEzB,8CAA6C;AAEpD,6BAA6B;AAC7B;;;;;;;;;;;CAWC,GAED,MAAMC,SAAS,AAAC,KAAED,iCAA+B;AAEjD,OAAO,SAASE;IACd,IAAI,CAACC,QAAQC,GAAG,CAACC,mCAAmC,EAAE;QACpD,MAAM,IAAIC,MACP;IAEL;IAEA,4CAA4C;IAC5C,MAAMC,QAAQ,IAAID,MAAML;IACtBM,MAAkCC,MAAM,GAAGP;IAC7C,MAAMM;AACR"}
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
import { handleGlobalErrors } from '../react-dev-overlay/internal/helpers/use-error-handler';
|
||||
handleGlobalErrors();
|
||||
|
||||
//# sourceMappingURL=handle-global-errors.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../../src/client/components/globals/handle-global-errors.ts"],"sourcesContent":["import { handleGlobalErrors } from '../react-dev-overlay/internal/helpers/use-error-handler'\n\nhandleGlobalErrors()\n"],"names":["handleGlobalErrors"],"mappings":"AAAA,SAASA,kBAAkB,QAAQ,0DAAyD;AAE5FA"}
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
import isError from '../../../lib/is-error';
|
||||
import { isNextRouterError } from '../is-next-router-error';
|
||||
import { handleClientError } from '../react-dev-overlay/internal/helpers/use-error-handler';
|
||||
export const originConsoleError = window.console.error;
|
||||
// Patch console.error to collect information about hydration errors
|
||||
export function patchConsoleError() {
|
||||
// Ensure it's only patched once
|
||||
if (typeof window === 'undefined') {
|
||||
return;
|
||||
}
|
||||
window.console.error = function error() {
|
||||
for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
|
||||
args[_key] = arguments[_key];
|
||||
}
|
||||
let maybeError;
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
const replayedError = matchReplayedError(...args);
|
||||
if (replayedError) {
|
||||
maybeError = replayedError;
|
||||
} else if (isError(args[0])) {
|
||||
maybeError = args[0];
|
||||
} else {
|
||||
// See https://github.com/facebook/react/blob/d50323eb845c5fde0d720cae888bf35dedd05506/packages/react-reconciler/src/ReactFiberErrorLogger.js#L78
|
||||
maybeError = args[1];
|
||||
}
|
||||
} else {
|
||||
maybeError = args[0];
|
||||
}
|
||||
if (!isNextRouterError(maybeError)) {
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
handleClientError(// replayed errors have their own complex format string that should be used,
|
||||
// but if we pass the error directly, `handleClientError` will ignore it
|
||||
maybeError, args, true);
|
||||
}
|
||||
originConsoleError.apply(window.console, args);
|
||||
}
|
||||
};
|
||||
}
|
||||
function matchReplayedError() {
|
||||
for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
|
||||
args[_key] = arguments[_key];
|
||||
}
|
||||
// See
|
||||
// https://github.com/facebook/react/blob/65a56d0e99261481c721334a3ec4561d173594cd/packages/react-devtools-shared/src/backend/flight/renderer.js#L88-L93
|
||||
//
|
||||
// Logs replayed from the server look like this:
|
||||
// [
|
||||
// "%c%s%c %o\n\n%s\n\n%s\n",
|
||||
// "background: #e6e6e6; ...",
|
||||
// " Server ", // can also be e.g. " Prerender "
|
||||
// "",
|
||||
// Error
|
||||
// "The above error occurred in the <Page> component."
|
||||
// ...
|
||||
// ]
|
||||
if (args.length > 3 && typeof args[0] === 'string' && args[0].startsWith('%c%s%c ') && typeof args[1] === 'string' && typeof args[2] === 'string' && typeof args[3] === 'string') {
|
||||
const maybeError = args[4];
|
||||
if (isError(maybeError)) {
|
||||
return maybeError;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
//# sourceMappingURL=intercept-console-error.js.map
|
||||
Generated
Vendored
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../../src/client/components/globals/intercept-console-error.ts"],"sourcesContent":["import isError from '../../../lib/is-error'\nimport { isNextRouterError } from '../is-next-router-error'\nimport { handleClientError } from '../react-dev-overlay/internal/helpers/use-error-handler'\n\nexport const originConsoleError = window.console.error\n\n// Patch console.error to collect information about hydration errors\nexport function patchConsoleError() {\n // Ensure it's only patched once\n if (typeof window === 'undefined') {\n return\n }\n window.console.error = function error(...args: any[]) {\n let maybeError: unknown\n if (process.env.NODE_ENV !== 'production') {\n const replayedError = matchReplayedError(...args)\n if (replayedError) {\n maybeError = replayedError\n } else if (isError(args[0])) {\n maybeError = args[0]\n } else {\n // See https://github.com/facebook/react/blob/d50323eb845c5fde0d720cae888bf35dedd05506/packages/react-reconciler/src/ReactFiberErrorLogger.js#L78\n maybeError = args[1]\n }\n } else {\n maybeError = args[0]\n }\n\n if (!isNextRouterError(maybeError)) {\n if (process.env.NODE_ENV !== 'production') {\n handleClientError(\n // replayed errors have their own complex format string that should be used,\n // but if we pass the error directly, `handleClientError` will ignore it\n maybeError,\n args,\n true\n )\n }\n\n originConsoleError.apply(window.console, args)\n }\n }\n}\n\nfunction matchReplayedError(...args: unknown[]): Error | null {\n // See\n // https://github.com/facebook/react/blob/65a56d0e99261481c721334a3ec4561d173594cd/packages/react-devtools-shared/src/backend/flight/renderer.js#L88-L93\n //\n // Logs replayed from the server look like this:\n // [\n // \"%c%s%c %o\\n\\n%s\\n\\n%s\\n\",\n // \"background: #e6e6e6; ...\",\n // \" Server \", // can also be e.g. \" Prerender \"\n // \"\",\n // Error\n // \"The above error occurred in the <Page> component.\"\n // ...\n // ]\n if (\n args.length > 3 &&\n typeof args[0] === 'string' &&\n args[0].startsWith('%c%s%c ') &&\n typeof args[1] === 'string' &&\n typeof args[2] === 'string' &&\n typeof args[3] === 'string'\n ) {\n const maybeError = args[4]\n if (isError(maybeError)) {\n return maybeError\n }\n }\n\n return null\n}\n"],"names":["isError","isNextRouterError","handleClientError","originConsoleError","window","console","error","patchConsoleError","args","maybeError","process","env","NODE_ENV","replayedError","matchReplayedError","apply","length","startsWith"],"mappings":"AAAA,OAAOA,aAAa,wBAAuB;AAC3C,SAASC,iBAAiB,QAAQ,0BAAyB;AAC3D,SAASC,iBAAiB,QAAQ,0DAAyD;AAE3F,OAAO,MAAMC,qBAAqBC,OAAOC,OAAO,CAACC,KAAK,CAAA;AAEtD,oEAAoE;AACpE,OAAO,SAASC;IACd,gCAAgC;IAChC,IAAI,OAAOH,WAAW,aAAa;QACjC;IACF;IACAA,OAAOC,OAAO,CAACC,KAAK,GAAG,SAASA;QAAM,IAAA,IAAA,OAAA,UAAA,QAAA,AAAGE,OAAH,UAAA,OAAA,OAAA,GAAA,OAAA,MAAA;YAAGA,KAAH,QAAA,SAAA,CAAA,KAAc;;QAClD,IAAIC;QACJ,IAAIC,QAAQC,GAAG,CAACC,QAAQ,KAAK,cAAc;YACzC,MAAMC,gBAAgBC,sBAAsBN;YAC5C,IAAIK,eAAe;gBACjBJ,aAAaI;YACf,OAAO,IAAIb,QAAQQ,IAAI,CAAC,EAAE,GAAG;gBAC3BC,aAAaD,IAAI,CAAC,EAAE;YACtB,OAAO;gBACL,iJAAiJ;gBACjJC,aAAaD,IAAI,CAAC,EAAE;YACtB;QACF,OAAO;YACLC,aAAaD,IAAI,CAAC,EAAE;QACtB;QAEA,IAAI,CAACP,kBAAkBQ,aAAa;YAClC,IAAIC,QAAQC,GAAG,CAACC,QAAQ,KAAK,cAAc;gBACzCV,kBACE,4EAA4E;gBAC5E,wEAAwE;gBACxEO,YACAD,MACA;YAEJ;YAEAL,mBAAmBY,KAAK,CAACX,OAAOC,OAAO,EAAEG;QAC3C;IACF;AACF;AAEA,SAASM;IAAmB,IAAA,IAAA,OAAA,UAAA,QAAA,AAAGN,OAAH,UAAA,OAAA,OAAA,GAAA,OAAA,MAAA;QAAGA,KAAH,QAAA,SAAA,CAAA,KAAkB;;IAC5C,MAAM;IACN,wJAAwJ;IACxJ,EAAE;IACF,gDAAgD;IAChD,IAAI;IACJ,+BAA+B;IAC/B,gCAAgC;IAChC,kDAAkD;IAClD,QAAQ;IACR,UAAU;IACV,wDAAwD;IACxD,QAAQ;IACR,IAAI;IACJ,IACEA,KAAKQ,MAAM,GAAG,KACd,OAAOR,IAAI,CAAC,EAAE,KAAK,YACnBA,IAAI,CAAC,EAAE,CAACS,UAAU,CAAC,cACnB,OAAOT,IAAI,CAAC,EAAE,KAAK,YACnB,OAAOA,IAAI,CAAC,EAAE,KAAK,YACnB,OAAOA,IAAI,CAAC,EAAE,KAAK,UACnB;QACA,MAAMC,aAAaD,IAAI,CAAC,EAAE;QAC1B,IAAIR,QAAQS,aAAa;YACvB,OAAOA;QACT;IACF;IAEA,OAAO;AACT"}
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
import { patchConsoleError } from './intercept-console-error';
|
||||
patchConsoleError();
|
||||
|
||||
//# sourceMappingURL=patch-console.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../../src/client/components/globals/patch-console.ts"],"sourcesContent":["import { patchConsoleError } from './intercept-console-error'\n\npatchConsoleError()\n"],"names":["patchConsoleError"],"mappings":"AAAA,SAASA,iBAAiB,QAAQ,4BAA2B;AAE7DA"}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
const DYNAMIC_ERROR_CODE = 'DYNAMIC_SERVER_USAGE';
|
||||
export class DynamicServerError extends Error {
|
||||
constructor(description){
|
||||
super("Dynamic server usage: " + description), this.description = description, this.digest = DYNAMIC_ERROR_CODE;
|
||||
}
|
||||
}
|
||||
export function isDynamicServerError(err) {
|
||||
if (typeof err !== 'object' || err === null || !('digest' in err) || typeof err.digest !== 'string') {
|
||||
return false;
|
||||
}
|
||||
return err.digest === DYNAMIC_ERROR_CODE;
|
||||
}
|
||||
|
||||
//# sourceMappingURL=hooks-server-context.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../src/client/components/hooks-server-context.ts"],"sourcesContent":["const DYNAMIC_ERROR_CODE = 'DYNAMIC_SERVER_USAGE'\n\nexport class DynamicServerError extends Error {\n digest: typeof DYNAMIC_ERROR_CODE = DYNAMIC_ERROR_CODE\n\n constructor(public readonly description: string) {\n super(`Dynamic server usage: ${description}`)\n }\n}\n\nexport function isDynamicServerError(err: unknown): err is DynamicServerError {\n if (\n typeof err !== 'object' ||\n err === null ||\n !('digest' in err) ||\n typeof err.digest !== 'string'\n ) {\n return false\n }\n\n return err.digest === DYNAMIC_ERROR_CODE\n}\n"],"names":["DYNAMIC_ERROR_CODE","DynamicServerError","Error","constructor","description","digest","isDynamicServerError","err"],"mappings":"AAAA,MAAMA,qBAAqB;AAE3B,OAAO,MAAMC,2BAA2BC;IAGtCC,YAAY,AAAgBC,WAAmB,CAAE;QAC/C,KAAK,CAAC,AAAC,2BAAwBA,mBADLA,cAAAA,kBAF5BC,SAAoCL;IAIpC;AACF;AAEA,OAAO,SAASM,qBAAqBC,GAAY;IAC/C,IACE,OAAOA,QAAQ,YACfA,QAAQ,QACR,CAAE,CAAA,YAAYA,GAAE,KAChB,OAAOA,IAAIF,MAAM,KAAK,UACtB;QACA,OAAO;IACT;IAEA,OAAOE,IAAIF,MAAM,KAAKL;AACxB"}
|
||||
Generated
Vendored
+120
@@ -0,0 +1,120 @@
|
||||
'use client';
|
||||
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
|
||||
/**
|
||||
* HTTPAccessFallbackBoundary is a boundary that catches errors and renders a
|
||||
* fallback component for HTTP errors.
|
||||
*
|
||||
* It receives the status code, and determine if it should render fallbacks for few HTTP 4xx errors.
|
||||
*
|
||||
* e.g. 404
|
||||
* 404 represents not found, and the fallback component pair contains the component and its styles.
|
||||
*
|
||||
*/ import React, { useContext } from 'react';
|
||||
import { useUntrackedPathname } from '../navigation-untracked';
|
||||
import { HTTPAccessErrorStatus, getAccessFallbackHTTPStatus, getAccessFallbackErrorTypeByStatus, isHTTPAccessFallbackError } from './http-access-fallback';
|
||||
import { warnOnce } from '../../../shared/lib/utils/warn-once';
|
||||
import { MissingSlotContext } from '../../../shared/lib/app-router-context.shared-runtime';
|
||||
class HTTPAccessFallbackErrorBoundary extends React.Component {
|
||||
componentDidCatch() {
|
||||
if (process.env.NODE_ENV === 'development' && this.props.missingSlots && // A missing children slot is the typical not-found case, so no need to warn
|
||||
!this.props.missingSlots.has('children')) {
|
||||
let warningMessage = 'No default component was found for a parallel route rendered on this page. Falling back to nearest NotFound boundary.\n' + 'Learn more: https://nextjs.org/docs/app/building-your-application/routing/parallel-routes#defaultjs\n\n';
|
||||
if (this.props.missingSlots.size > 0) {
|
||||
const formattedSlots = Array.from(this.props.missingSlots).sort((a, b)=>a.localeCompare(b)).map((slot)=>"@" + slot).join(', ');
|
||||
warningMessage += 'Missing slots: ' + formattedSlots;
|
||||
}
|
||||
warnOnce(warningMessage);
|
||||
}
|
||||
}
|
||||
static getDerivedStateFromError(error) {
|
||||
if (isHTTPAccessFallbackError(error)) {
|
||||
const httpStatus = getAccessFallbackHTTPStatus(error);
|
||||
return {
|
||||
triggeredStatus: httpStatus
|
||||
};
|
||||
}
|
||||
// Re-throw if error is not for 404
|
||||
throw error;
|
||||
}
|
||||
static getDerivedStateFromProps(props, state) {
|
||||
/**
|
||||
* Handles reset of the error boundary when a navigation happens.
|
||||
* Ensures the error boundary does not stay enabled when navigating to a new page.
|
||||
* Approach of setState in render is safe as it checks the previous pathname and then overrides
|
||||
* it as outlined in https://react.dev/reference/react/useState#storing-information-from-previous-renders
|
||||
*/ if (props.pathname !== state.previousPathname && state.triggeredStatus) {
|
||||
return {
|
||||
triggeredStatus: undefined,
|
||||
previousPathname: props.pathname
|
||||
};
|
||||
}
|
||||
return {
|
||||
triggeredStatus: state.triggeredStatus,
|
||||
previousPathname: props.pathname
|
||||
};
|
||||
}
|
||||
render() {
|
||||
const { notFound, forbidden, unauthorized, children } = this.props;
|
||||
const { triggeredStatus } = this.state;
|
||||
const errorComponents = {
|
||||
[HTTPAccessErrorStatus.NOT_FOUND]: notFound,
|
||||
[HTTPAccessErrorStatus.FORBIDDEN]: forbidden,
|
||||
[HTTPAccessErrorStatus.UNAUTHORIZED]: unauthorized
|
||||
};
|
||||
if (triggeredStatus) {
|
||||
const isNotFound = triggeredStatus === HTTPAccessErrorStatus.NOT_FOUND && notFound;
|
||||
const isForbidden = triggeredStatus === HTTPAccessErrorStatus.FORBIDDEN && forbidden;
|
||||
const isUnauthorized = triggeredStatus === HTTPAccessErrorStatus.UNAUTHORIZED && unauthorized;
|
||||
// If there's no matched boundary in this layer, keep throwing the error by rendering the children
|
||||
if (!(isNotFound || isForbidden || isUnauthorized)) {
|
||||
return children;
|
||||
}
|
||||
return /*#__PURE__*/ _jsxs(_Fragment, {
|
||||
children: [
|
||||
/*#__PURE__*/ _jsx("meta", {
|
||||
name: "robots",
|
||||
content: "noindex"
|
||||
}),
|
||||
process.env.NODE_ENV === 'development' && /*#__PURE__*/ _jsx("meta", {
|
||||
name: "next-error",
|
||||
content: getAccessFallbackErrorTypeByStatus(triggeredStatus)
|
||||
}),
|
||||
errorComponents[triggeredStatus]
|
||||
]
|
||||
});
|
||||
}
|
||||
return children;
|
||||
}
|
||||
constructor(props){
|
||||
super(props);
|
||||
this.state = {
|
||||
triggeredStatus: undefined,
|
||||
previousPathname: props.pathname
|
||||
};
|
||||
}
|
||||
}
|
||||
export function HTTPAccessFallbackBoundary(param) {
|
||||
let { notFound, forbidden, unauthorized, children } = param;
|
||||
// When we're rendering the missing params shell, this will return null. This
|
||||
// is because we won't be rendering any not found boundaries or error
|
||||
// boundaries for the missing params shell. When this runs on the client
|
||||
// (where these error can occur), we will get the correct pathname.
|
||||
const pathname = useUntrackedPathname();
|
||||
const missingSlots = useContext(MissingSlotContext);
|
||||
const hasErrorFallback = !!(notFound || forbidden || unauthorized);
|
||||
if (hasErrorFallback) {
|
||||
return /*#__PURE__*/ _jsx(HTTPAccessFallbackErrorBoundary, {
|
||||
pathname: pathname,
|
||||
notFound: notFound,
|
||||
forbidden: forbidden,
|
||||
unauthorized: unauthorized,
|
||||
missingSlots: missingSlots,
|
||||
children: children
|
||||
});
|
||||
}
|
||||
return /*#__PURE__*/ _jsx(_Fragment, {
|
||||
children: children
|
||||
});
|
||||
}
|
||||
|
||||
//# sourceMappingURL=error-boundary.js.map
|
||||
Generated
Vendored
+1
File diff suppressed because one or more lines are too long
Generated
Vendored
+80
@@ -0,0 +1,80 @@
|
||||
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
|
||||
import React from 'react';
|
||||
const styles = {
|
||||
error: {
|
||||
// https://github.com/sindresorhus/modern-normalize/blob/main/modern-normalize.css#L38-L52
|
||||
fontFamily: 'system-ui,"Segoe UI",Roboto,Helvetica,Arial,sans-serif,"Apple Color Emoji","Segoe UI Emoji"',
|
||||
height: '100vh',
|
||||
textAlign: 'center',
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center'
|
||||
},
|
||||
desc: {
|
||||
display: 'inline-block'
|
||||
},
|
||||
h1: {
|
||||
display: 'inline-block',
|
||||
margin: '0 20px 0 0',
|
||||
padding: '0 23px 0 0',
|
||||
fontSize: 24,
|
||||
fontWeight: 500,
|
||||
verticalAlign: 'top',
|
||||
lineHeight: '49px'
|
||||
},
|
||||
h2: {
|
||||
fontSize: 14,
|
||||
fontWeight: 400,
|
||||
lineHeight: '49px',
|
||||
margin: 0
|
||||
}
|
||||
};
|
||||
export function HTTPAccessErrorFallback(param) {
|
||||
let { status, message } = param;
|
||||
return /*#__PURE__*/ _jsxs(_Fragment, {
|
||||
children: [
|
||||
/*#__PURE__*/ _jsx("title", {
|
||||
children: status + ": " + message
|
||||
}),
|
||||
/*#__PURE__*/ _jsx("div", {
|
||||
style: styles.error,
|
||||
children: /*#__PURE__*/ _jsxs("div", {
|
||||
children: [
|
||||
/*#__PURE__*/ _jsx("style", {
|
||||
dangerouslySetInnerHTML: {
|
||||
/* Minified CSS from
|
||||
body { margin: 0; color: #000; background: #fff; }
|
||||
.next-error-h1 {
|
||||
border-right: 1px solid rgba(0, 0, 0, .3);
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: dark) {
|
||||
body { color: #fff; background: #000; }
|
||||
.next-error-h1 {
|
||||
border-right: 1px solid rgba(255, 255, 255, .3);
|
||||
}
|
||||
}
|
||||
*/ __html: "body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"
|
||||
}
|
||||
}),
|
||||
/*#__PURE__*/ _jsx("h1", {
|
||||
className: "next-error-h1",
|
||||
style: styles.h1,
|
||||
children: status
|
||||
}),
|
||||
/*#__PURE__*/ _jsx("div", {
|
||||
style: styles.desc,
|
||||
children: /*#__PURE__*/ _jsx("h2", {
|
||||
style: styles.h2,
|
||||
children: message
|
||||
})
|
||||
})
|
||||
]
|
||||
})
|
||||
})
|
||||
]
|
||||
});
|
||||
}
|
||||
|
||||
//# sourceMappingURL=error-fallback.js.map
|
||||
Generated
Vendored
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../../src/client/components/http-access-fallback/error-fallback.tsx"],"sourcesContent":["import React from 'react'\n\nconst styles: Record<string, React.CSSProperties> = {\n error: {\n // https://github.com/sindresorhus/modern-normalize/blob/main/modern-normalize.css#L38-L52\n fontFamily:\n 'system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"',\n height: '100vh',\n textAlign: 'center',\n display: 'flex',\n flexDirection: 'column',\n alignItems: 'center',\n justifyContent: 'center',\n },\n\n desc: {\n display: 'inline-block',\n },\n\n h1: {\n display: 'inline-block',\n margin: '0 20px 0 0',\n padding: '0 23px 0 0',\n fontSize: 24,\n fontWeight: 500,\n verticalAlign: 'top',\n lineHeight: '49px',\n },\n\n h2: {\n fontSize: 14,\n fontWeight: 400,\n lineHeight: '49px',\n margin: 0,\n },\n}\n\nexport function HTTPAccessErrorFallback({\n status,\n message,\n}: {\n status: number\n message: string\n}) {\n return (\n <>\n {/* <head> */}\n <title>{`${status}: ${message}`}</title>\n {/* </head> */}\n <div style={styles.error}>\n <div>\n <style\n dangerouslySetInnerHTML={{\n /* Minified CSS from\n body { margin: 0; color: #000; background: #fff; }\n .next-error-h1 {\n border-right: 1px solid rgba(0, 0, 0, .3);\n }\n\n @media (prefers-color-scheme: dark) {\n body { color: #fff; background: #000; }\n .next-error-h1 {\n border-right: 1px solid rgba(255, 255, 255, .3);\n }\n }\n */\n __html: `body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}`,\n }}\n />\n <h1 className=\"next-error-h1\" style={styles.h1}>\n {status}\n </h1>\n <div style={styles.desc}>\n <h2 style={styles.h2}>{message}</h2>\n </div>\n </div>\n </div>\n </>\n )\n}\n"],"names":["React","styles","error","fontFamily","height","textAlign","display","flexDirection","alignItems","justifyContent","desc","h1","margin","padding","fontSize","fontWeight","verticalAlign","lineHeight","h2","HTTPAccessErrorFallback","status","message","title","div","style","dangerouslySetInnerHTML","__html","className"],"mappings":";AAAA,OAAOA,WAAW,QAAO;AAEzB,MAAMC,SAA8C;IAClDC,OAAO;QACL,0FAA0F;QAC1FC,YACE;QACFC,QAAQ;QACRC,WAAW;QACXC,SAAS;QACTC,eAAe;QACfC,YAAY;QACZC,gBAAgB;IAClB;IAEAC,MAAM;QACJJ,SAAS;IACX;IAEAK,IAAI;QACFL,SAAS;QACTM,QAAQ;QACRC,SAAS;QACTC,UAAU;QACVC,YAAY;QACZC,eAAe;QACfC,YAAY;IACd;IAEAC,IAAI;QACFJ,UAAU;QACVC,YAAY;QACZE,YAAY;QACZL,QAAQ;IACV;AACF;AAEA,OAAO,SAASO,wBAAwB,KAMvC;IANuC,IAAA,EACtCC,MAAM,EACNC,OAAO,EAIR,GANuC;IAOtC,qBACE;;0BAEE,KAACC;0BAAO,AAAGF,SAAO,OAAIC;;0BAEtB,KAACE;gBAAIC,OAAOvB,OAAOC,KAAK;0BACtB,cAAA,MAACqB;;sCACC,KAACC;4BACCC,yBAAyB;gCACvB;;;;;;;;;;;;cAYA,GACAC,QAAS;4BACX;;sCAEF,KAACf;4BAAGgB,WAAU;4BAAgBH,OAAOvB,OAAOU,EAAE;sCAC3CS;;sCAEH,KAACG;4BAAIC,OAAOvB,OAAOS,IAAI;sCACrB,cAAA,KAACQ;gCAAGM,OAAOvB,OAAOiB,EAAE;0CAAGG;;;;;;;;AAMnC"}
|
||||
Generated
Vendored
+38
@@ -0,0 +1,38 @@
|
||||
export const HTTPAccessErrorStatus = {
|
||||
NOT_FOUND: 404,
|
||||
FORBIDDEN: 403,
|
||||
UNAUTHORIZED: 401
|
||||
};
|
||||
const ALLOWED_CODES = new Set(Object.values(HTTPAccessErrorStatus));
|
||||
export const HTTP_ERROR_FALLBACK_ERROR_CODE = 'NEXT_HTTP_ERROR_FALLBACK';
|
||||
/**
|
||||
* Checks an error to determine if it's an error generated by
|
||||
* the HTTP navigation APIs `notFound()`, `forbidden()` or `unauthorized()`.
|
||||
*
|
||||
* @param error the error that may reference a HTTP access error
|
||||
* @returns true if the error is a HTTP access error
|
||||
*/ export function isHTTPAccessFallbackError(error) {
|
||||
if (typeof error !== 'object' || error === null || !('digest' in error) || typeof error.digest !== 'string') {
|
||||
return false;
|
||||
}
|
||||
const [prefix, httpStatus] = error.digest.split(';');
|
||||
return prefix === HTTP_ERROR_FALLBACK_ERROR_CODE && ALLOWED_CODES.has(Number(httpStatus));
|
||||
}
|
||||
export function getAccessFallbackHTTPStatus(error) {
|
||||
const httpStatus = error.digest.split(';')[1];
|
||||
return Number(httpStatus);
|
||||
}
|
||||
export function getAccessFallbackErrorTypeByStatus(status) {
|
||||
switch(status){
|
||||
case 401:
|
||||
return 'unauthorized';
|
||||
case 403:
|
||||
return 'forbidden';
|
||||
case 404:
|
||||
return 'not-found';
|
||||
default:
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
//# sourceMappingURL=http-access-fallback.js.map
|
||||
Generated
Vendored
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../../src/client/components/http-access-fallback/http-access-fallback.ts"],"sourcesContent":["export const HTTPAccessErrorStatus = {\n NOT_FOUND: 404,\n FORBIDDEN: 403,\n UNAUTHORIZED: 401,\n}\n\nconst ALLOWED_CODES = new Set(Object.values(HTTPAccessErrorStatus))\n\nexport const HTTP_ERROR_FALLBACK_ERROR_CODE = 'NEXT_HTTP_ERROR_FALLBACK'\n\nexport type HTTPAccessFallbackError = Error & {\n digest: `${typeof HTTP_ERROR_FALLBACK_ERROR_CODE};${string}`\n}\n\n/**\n * Checks an error to determine if it's an error generated by\n * the HTTP navigation APIs `notFound()`, `forbidden()` or `unauthorized()`.\n *\n * @param error the error that may reference a HTTP access error\n * @returns true if the error is a HTTP access error\n */\nexport function isHTTPAccessFallbackError(\n error: unknown\n): error is HTTPAccessFallbackError {\n if (\n typeof error !== 'object' ||\n error === null ||\n !('digest' in error) ||\n typeof error.digest !== 'string'\n ) {\n return false\n }\n const [prefix, httpStatus] = error.digest.split(';')\n\n return (\n prefix === HTTP_ERROR_FALLBACK_ERROR_CODE &&\n ALLOWED_CODES.has(Number(httpStatus))\n )\n}\n\nexport function getAccessFallbackHTTPStatus(\n error: HTTPAccessFallbackError\n): number {\n const httpStatus = error.digest.split(';')[1]\n return Number(httpStatus)\n}\n\nexport function getAccessFallbackErrorTypeByStatus(\n status: number\n): 'not-found' | 'forbidden' | 'unauthorized' | undefined {\n switch (status) {\n case 401:\n return 'unauthorized'\n case 403:\n return 'forbidden'\n case 404:\n return 'not-found'\n default:\n return\n }\n}\n"],"names":["HTTPAccessErrorStatus","NOT_FOUND","FORBIDDEN","UNAUTHORIZED","ALLOWED_CODES","Set","Object","values","HTTP_ERROR_FALLBACK_ERROR_CODE","isHTTPAccessFallbackError","error","digest","prefix","httpStatus","split","has","Number","getAccessFallbackHTTPStatus","getAccessFallbackErrorTypeByStatus","status"],"mappings":"AAAA,OAAO,MAAMA,wBAAwB;IACnCC,WAAW;IACXC,WAAW;IACXC,cAAc;AAChB,EAAC;AAED,MAAMC,gBAAgB,IAAIC,IAAIC,OAAOC,MAAM,CAACP;AAE5C,OAAO,MAAMQ,iCAAiC,2BAA0B;AAMxE;;;;;;CAMC,GACD,OAAO,SAASC,0BACdC,KAAc;IAEd,IACE,OAAOA,UAAU,YACjBA,UAAU,QACV,CAAE,CAAA,YAAYA,KAAI,KAClB,OAAOA,MAAMC,MAAM,KAAK,UACxB;QACA,OAAO;IACT;IACA,MAAM,CAACC,QAAQC,WAAW,GAAGH,MAAMC,MAAM,CAACG,KAAK,CAAC;IAEhD,OACEF,WAAWJ,kCACXJ,cAAcW,GAAG,CAACC,OAAOH;AAE7B;AAEA,OAAO,SAASI,4BACdP,KAA8B;IAE9B,MAAMG,aAAaH,MAAMC,MAAM,CAACG,KAAK,CAAC,IAAI,CAAC,EAAE;IAC7C,OAAOE,OAAOH;AAChB;AAEA,OAAO,SAASK,mCACdC,MAAc;IAEd,OAAQA;QACN,KAAK;YACH,OAAO;QACT,KAAK;YACH,OAAO;QACT,KAAK;YACH,OAAO;QACT;YACE;IACJ;AACF"}
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
import isError from '../../lib/is-error';
|
||||
const hydrationErrorRegex = /hydration failed|while hydrating|content does not match|did not match|HTML didn't match/i;
|
||||
const reactUnifiedMismatchWarning = "Hydration failed because the server rendered HTML didn't match the client. As a result this tree will be regenerated on the client. This can happen if a SSR-ed Client Component used";
|
||||
const reactHydrationStartMessages = [
|
||||
reactUnifiedMismatchWarning,
|
||||
"A tree hydrated but some attributes of the server rendered HTML didn't match the client properties. This won't be patched up. This can happen if a SSR-ed Client Component used:"
|
||||
];
|
||||
const reactHydrationErrorDocLink = 'https://react.dev/link/hydration-mismatch';
|
||||
export const getDefaultHydrationErrorMessage = ()=>{
|
||||
return reactUnifiedMismatchWarning;
|
||||
};
|
||||
export function isHydrationError(error) {
|
||||
return isError(error) && hydrationErrorRegex.test(error.message);
|
||||
}
|
||||
export function isReactHydrationErrorMessage(msg) {
|
||||
return reactHydrationStartMessages.some((prefix)=>msg.startsWith(prefix));
|
||||
}
|
||||
export function getHydrationErrorStackInfo(rawMessage) {
|
||||
rawMessage = rawMessage.replace(/^Error: /, '');
|
||||
if (!isReactHydrationErrorMessage(rawMessage)) {
|
||||
return {
|
||||
message: null
|
||||
};
|
||||
}
|
||||
const firstLineBreak = rawMessage.indexOf('\n');
|
||||
rawMessage = rawMessage.slice(firstLineBreak + 1).trim();
|
||||
const [message, trailing] = rawMessage.split("" + reactHydrationErrorDocLink);
|
||||
const trimmedMessage = message.trim();
|
||||
// React built-in hydration diff starts with a newline, checking if length is > 1
|
||||
if (trailing && trailing.length > 1) {
|
||||
const stacks = [];
|
||||
const diffs = [];
|
||||
trailing.split('\n').forEach((line)=>{
|
||||
if (line.trim() === '') return;
|
||||
if (line.trim().startsWith('at ')) {
|
||||
stacks.push(line);
|
||||
} else {
|
||||
diffs.push(line);
|
||||
}
|
||||
});
|
||||
return {
|
||||
message: trimmedMessage,
|
||||
link: reactHydrationErrorDocLink,
|
||||
diff: diffs.join('\n'),
|
||||
stack: stacks.join('\n')
|
||||
};
|
||||
} else {
|
||||
return {
|
||||
message: trimmedMessage,
|
||||
link: reactHydrationErrorDocLink,
|
||||
stack: trailing
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
//# sourceMappingURL=is-hydration-error.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../src/client/components/is-hydration-error.ts"],"sourcesContent":["import isError from '../../lib/is-error'\n\nconst hydrationErrorRegex =\n /hydration failed|while hydrating|content does not match|did not match|HTML didn't match/i\n\nconst reactUnifiedMismatchWarning = `Hydration failed because the server rendered HTML didn't match the client. As a result this tree will be regenerated on the client. This can happen if a SSR-ed Client Component used`\n\nconst reactHydrationStartMessages = [\n reactUnifiedMismatchWarning,\n `A tree hydrated but some attributes of the server rendered HTML didn't match the client properties. This won't be patched up. This can happen if a SSR-ed Client Component used:`,\n]\n\nconst reactHydrationErrorDocLink = 'https://react.dev/link/hydration-mismatch'\n\nexport const getDefaultHydrationErrorMessage = () => {\n return reactUnifiedMismatchWarning\n}\n\nexport function isHydrationError(error: unknown): boolean {\n return isError(error) && hydrationErrorRegex.test(error.message)\n}\n\nexport function isReactHydrationErrorMessage(msg: string): boolean {\n return reactHydrationStartMessages.some((prefix) => msg.startsWith(prefix))\n}\n\nexport function getHydrationErrorStackInfo(rawMessage: string): {\n message: string | null\n link?: string\n stack?: string\n diff?: string\n} {\n rawMessage = rawMessage.replace(/^Error: /, '')\n if (!isReactHydrationErrorMessage(rawMessage)) {\n return { message: null }\n }\n const firstLineBreak = rawMessage.indexOf('\\n')\n rawMessage = rawMessage.slice(firstLineBreak + 1).trim()\n\n const [message, trailing] = rawMessage.split(`${reactHydrationErrorDocLink}`)\n const trimmedMessage = message.trim()\n // React built-in hydration diff starts with a newline, checking if length is > 1\n if (trailing && trailing.length > 1) {\n const stacks: string[] = []\n const diffs: string[] = []\n trailing.split('\\n').forEach((line) => {\n if (line.trim() === '') return\n if (line.trim().startsWith('at ')) {\n stacks.push(line)\n } else {\n diffs.push(line)\n }\n })\n\n return {\n message: trimmedMessage,\n link: reactHydrationErrorDocLink,\n diff: diffs.join('\\n'),\n stack: stacks.join('\\n'),\n }\n } else {\n return {\n message: trimmedMessage,\n link: reactHydrationErrorDocLink,\n stack: trailing, // without hydration diff\n }\n }\n}\n"],"names":["isError","hydrationErrorRegex","reactUnifiedMismatchWarning","reactHydrationStartMessages","reactHydrationErrorDocLink","getDefaultHydrationErrorMessage","isHydrationError","error","test","message","isReactHydrationErrorMessage","msg","some","prefix","startsWith","getHydrationErrorStackInfo","rawMessage","replace","firstLineBreak","indexOf","slice","trim","trailing","split","trimmedMessage","length","stacks","diffs","forEach","line","push","link","diff","join","stack"],"mappings":"AAAA,OAAOA,aAAa,qBAAoB;AAExC,MAAMC,sBACJ;AAEF,MAAMC,8BAA+B;AAErC,MAAMC,8BAA8B;IAClCD;IACC;CACF;AAED,MAAME,6BAA6B;AAEnC,OAAO,MAAMC,kCAAkC;IAC7C,OAAOH;AACT,EAAC;AAED,OAAO,SAASI,iBAAiBC,KAAc;IAC7C,OAAOP,QAAQO,UAAUN,oBAAoBO,IAAI,CAACD,MAAME,OAAO;AACjE;AAEA,OAAO,SAASC,6BAA6BC,GAAW;IACtD,OAAOR,4BAA4BS,IAAI,CAAC,CAACC,SAAWF,IAAIG,UAAU,CAACD;AACrE;AAEA,OAAO,SAASE,2BAA2BC,UAAkB;IAM3DA,aAAaA,WAAWC,OAAO,CAAC,YAAY;IAC5C,IAAI,CAACP,6BAA6BM,aAAa;QAC7C,OAAO;YAAEP,SAAS;QAAK;IACzB;IACA,MAAMS,iBAAiBF,WAAWG,OAAO,CAAC;IAC1CH,aAAaA,WAAWI,KAAK,CAACF,iBAAiB,GAAGG,IAAI;IAEtD,MAAM,CAACZ,SAASa,SAAS,GAAGN,WAAWO,KAAK,CAAC,AAAC,KAAEnB;IAChD,MAAMoB,iBAAiBf,QAAQY,IAAI;IACnC,iFAAiF;IACjF,IAAIC,YAAYA,SAASG,MAAM,GAAG,GAAG;QACnC,MAAMC,SAAmB,EAAE;QAC3B,MAAMC,QAAkB,EAAE;QAC1BL,SAASC,KAAK,CAAC,MAAMK,OAAO,CAAC,CAACC;YAC5B,IAAIA,KAAKR,IAAI,OAAO,IAAI;YACxB,IAAIQ,KAAKR,IAAI,GAAGP,UAAU,CAAC,QAAQ;gBACjCY,OAAOI,IAAI,CAACD;YACd,OAAO;gBACLF,MAAMG,IAAI,CAACD;YACb;QACF;QAEA,OAAO;YACLpB,SAASe;YACTO,MAAM3B;YACN4B,MAAML,MAAMM,IAAI,CAAC;YACjBC,OAAOR,OAAOO,IAAI,CAAC;QACrB;IACF,OAAO;QACL,OAAO;YACLxB,SAASe;YACTO,MAAM3B;YACN8B,OAAOZ;QACT;IACF;AACF"}
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
import { isHTTPAccessFallbackError } from './http-access-fallback/http-access-fallback';
|
||||
import { isRedirectError } from './redirect-error';
|
||||
/**
|
||||
* Returns true if the error is a navigation signal error. These errors are
|
||||
* thrown by user code to perform navigation operations and interrupt the React
|
||||
* render.
|
||||
*/ export function isNextRouterError(error) {
|
||||
return isRedirectError(error) || isHTTPAccessFallbackError(error);
|
||||
}
|
||||
|
||||
//# sourceMappingURL=is-next-router-error.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../src/client/components/is-next-router-error.ts"],"sourcesContent":["import {\n isHTTPAccessFallbackError,\n type HTTPAccessFallbackError,\n} from './http-access-fallback/http-access-fallback'\nimport { isRedirectError, type RedirectError } from './redirect-error'\n\n/**\n * Returns true if the error is a navigation signal error. These errors are\n * thrown by user code to perform navigation operations and interrupt the React\n * render.\n */\nexport function isNextRouterError(\n error: unknown\n): error is RedirectError | HTTPAccessFallbackError {\n return isRedirectError(error) || isHTTPAccessFallbackError(error)\n}\n"],"names":["isHTTPAccessFallbackError","isRedirectError","isNextRouterError","error"],"mappings":"AAAA,SACEA,yBAAyB,QAEpB,8CAA6C;AACpD,SAASC,eAAe,QAA4B,mBAAkB;AAEtE;;;;CAIC,GACD,OAAO,SAASC,kBACdC,KAAc;IAEd,OAAOF,gBAAgBE,UAAUH,0BAA0BG;AAC7D"}
|
||||
+432
@@ -0,0 +1,432 @@
|
||||
'use client';
|
||||
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
|
||||
import React, { useContext, use, startTransition, Suspense, useDeferredValue } from 'react';
|
||||
import ReactDOM from 'react-dom';
|
||||
import { LayoutRouterContext, GlobalLayoutRouterContext, TemplateContext } from '../../shared/lib/app-router-context.shared-runtime';
|
||||
import { fetchServerResponse } from './router-reducer/fetch-server-response';
|
||||
import { unresolvedThenable } from './unresolved-thenable';
|
||||
import { ErrorBoundary } from './error-boundary';
|
||||
import { matchSegment } from './match-segments';
|
||||
import { handleSmoothScroll } from '../../shared/lib/router/utils/handle-smooth-scroll';
|
||||
import { RedirectBoundary } from './redirect-boundary';
|
||||
import { HTTPAccessFallbackBoundary } from './http-access-fallback/error-boundary';
|
||||
import { getSegmentValue } from './router-reducer/reducers/get-segment-value';
|
||||
import { createRouterCacheKey } from './router-reducer/create-router-cache-key';
|
||||
import { hasInterceptionRouteInCurrentTree } from './router-reducer/reducers/has-interception-route-in-current-tree';
|
||||
/**
|
||||
* Add refetch marker to router state at the point of the current layout segment.
|
||||
* This ensures the response returned is not further down than the current layout segment.
|
||||
*/ function walkAddRefetch(segmentPathToWalk, treeToRecreate) {
|
||||
if (segmentPathToWalk) {
|
||||
const [segment, parallelRouteKey] = segmentPathToWalk;
|
||||
const isLast = segmentPathToWalk.length === 2;
|
||||
if (matchSegment(treeToRecreate[0], segment)) {
|
||||
if (treeToRecreate[1].hasOwnProperty(parallelRouteKey)) {
|
||||
if (isLast) {
|
||||
const subTree = walkAddRefetch(undefined, treeToRecreate[1][parallelRouteKey]);
|
||||
return [
|
||||
treeToRecreate[0],
|
||||
{
|
||||
...treeToRecreate[1],
|
||||
[parallelRouteKey]: [
|
||||
subTree[0],
|
||||
subTree[1],
|
||||
subTree[2],
|
||||
'refetch'
|
||||
]
|
||||
}
|
||||
];
|
||||
}
|
||||
return [
|
||||
treeToRecreate[0],
|
||||
{
|
||||
...treeToRecreate[1],
|
||||
[parallelRouteKey]: walkAddRefetch(segmentPathToWalk.slice(2), treeToRecreate[1][parallelRouteKey])
|
||||
}
|
||||
];
|
||||
}
|
||||
}
|
||||
}
|
||||
return treeToRecreate;
|
||||
}
|
||||
const __DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE = ReactDOM.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;
|
||||
// TODO-APP: Replace with new React API for finding dom nodes without a `ref` when available
|
||||
/**
|
||||
* Wraps ReactDOM.findDOMNode with additional logic to hide React Strict Mode warning
|
||||
*/ function findDOMNode(instance) {
|
||||
// Tree-shake for server bundle
|
||||
if (typeof window === 'undefined') return null;
|
||||
// __DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE.findDOMNode is null during module init.
|
||||
// We need to lazily reference it.
|
||||
const internal_reactDOMfindDOMNode = __DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE.findDOMNode;
|
||||
return internal_reactDOMfindDOMNode(instance);
|
||||
}
|
||||
const rectProperties = [
|
||||
'bottom',
|
||||
'height',
|
||||
'left',
|
||||
'right',
|
||||
'top',
|
||||
'width',
|
||||
'x',
|
||||
'y'
|
||||
];
|
||||
/**
|
||||
* Check if a HTMLElement is hidden or fixed/sticky position
|
||||
*/ function shouldSkipElement(element) {
|
||||
// we ignore fixed or sticky positioned elements since they'll likely pass the "in-viewport" check
|
||||
// and will result in a situation we bail on scroll because of something like a fixed nav,
|
||||
// even though the actual page content is offscreen
|
||||
if ([
|
||||
'sticky',
|
||||
'fixed'
|
||||
].includes(getComputedStyle(element).position)) {
|
||||
if (process.env.NODE_ENV === 'development') {
|
||||
console.warn('Skipping auto-scroll behavior due to `position: sticky` or `position: fixed` on element:', element);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
// Uses `getBoundingClientRect` to check if the element is hidden instead of `offsetParent`
|
||||
// because `offsetParent` doesn't consider document/body
|
||||
const rect = element.getBoundingClientRect();
|
||||
return rectProperties.every((item)=>rect[item] === 0);
|
||||
}
|
||||
/**
|
||||
* Check if the top corner of the HTMLElement is in the viewport.
|
||||
*/ function topOfElementInViewport(element, viewportHeight) {
|
||||
const rect = element.getBoundingClientRect();
|
||||
return rect.top >= 0 && rect.top <= viewportHeight;
|
||||
}
|
||||
/**
|
||||
* Find the DOM node for a hash fragment.
|
||||
* If `top` the page has to scroll to the top of the page. This mirrors the browser's behavior.
|
||||
* If the hash fragment is an id, the page has to scroll to the element with that id.
|
||||
* If the hash fragment is a name, the page has to scroll to the first element with that name.
|
||||
*/ function getHashFragmentDomNode(hashFragment) {
|
||||
// If the hash fragment is `top` the page has to scroll to the top of the page.
|
||||
if (hashFragment === 'top') {
|
||||
return document.body;
|
||||
}
|
||||
var _document_getElementById;
|
||||
// If the hash fragment is an id, the page has to scroll to the element with that id.
|
||||
return (_document_getElementById = document.getElementById(hashFragment)) != null ? _document_getElementById : // If the hash fragment is a name, the page has to scroll to the first element with that name.
|
||||
document.getElementsByName(hashFragment)[0];
|
||||
}
|
||||
class InnerScrollAndFocusHandler extends React.Component {
|
||||
componentDidMount() {
|
||||
this.handlePotentialScroll();
|
||||
}
|
||||
componentDidUpdate() {
|
||||
// Because this property is overwritten in handlePotentialScroll it's fine to always run it when true as it'll be set to false for subsequent renders.
|
||||
if (this.props.focusAndScrollRef.apply) {
|
||||
this.handlePotentialScroll();
|
||||
}
|
||||
}
|
||||
render() {
|
||||
return this.props.children;
|
||||
}
|
||||
constructor(...args){
|
||||
super(...args), this.handlePotentialScroll = ()=>{
|
||||
// Handle scroll and focus, it's only applied once in the first useEffect that triggers that changed.
|
||||
const { focusAndScrollRef, segmentPath } = this.props;
|
||||
if (focusAndScrollRef.apply) {
|
||||
// segmentPaths is an array of segment paths that should be scrolled to
|
||||
// if the current segment path is not in the array, the scroll is not applied
|
||||
// unless the array is empty, in which case the scroll is always applied
|
||||
if (focusAndScrollRef.segmentPaths.length !== 0 && !focusAndScrollRef.segmentPaths.some((scrollRefSegmentPath)=>segmentPath.every((segment, index)=>matchSegment(segment, scrollRefSegmentPath[index])))) {
|
||||
return;
|
||||
}
|
||||
let domNode = null;
|
||||
const hashFragment = focusAndScrollRef.hashFragment;
|
||||
if (hashFragment) {
|
||||
domNode = getHashFragmentDomNode(hashFragment);
|
||||
}
|
||||
// `findDOMNode` is tricky because it returns just the first child if the component is a fragment.
|
||||
// This already caused a bug where the first child was a <link/> in head.
|
||||
if (!domNode) {
|
||||
domNode = findDOMNode(this);
|
||||
}
|
||||
// If there is no DOM node this layout-router level is skipped. It'll be handled higher-up in the tree.
|
||||
if (!(domNode instanceof Element)) {
|
||||
return;
|
||||
}
|
||||
// Verify if the element is a HTMLElement and if we want to consider it for scroll behavior.
|
||||
// If the element is skipped, try to select the next sibling and try again.
|
||||
while(!(domNode instanceof HTMLElement) || shouldSkipElement(domNode)){
|
||||
// No siblings found that match the criteria are found, so handle scroll higher up in the tree instead.
|
||||
if (domNode.nextElementSibling === null) {
|
||||
return;
|
||||
}
|
||||
domNode = domNode.nextElementSibling;
|
||||
}
|
||||
// State is mutated to ensure that the focus and scroll is applied only once.
|
||||
focusAndScrollRef.apply = false;
|
||||
focusAndScrollRef.hashFragment = null;
|
||||
focusAndScrollRef.segmentPaths = [];
|
||||
handleSmoothScroll(()=>{
|
||||
// In case of hash scroll, we only need to scroll the element into view
|
||||
if (hashFragment) {
|
||||
;
|
||||
domNode.scrollIntoView();
|
||||
return;
|
||||
}
|
||||
// Store the current viewport height because reading `clientHeight` causes a reflow,
|
||||
// and it won't change during this function.
|
||||
const htmlElement = document.documentElement;
|
||||
const viewportHeight = htmlElement.clientHeight;
|
||||
// If the element's top edge is already in the viewport, exit early.
|
||||
if (topOfElementInViewport(domNode, viewportHeight)) {
|
||||
return;
|
||||
}
|
||||
// Otherwise, try scrolling go the top of the document to be backward compatible with pages
|
||||
// scrollIntoView() called on `<html/>` element scrolls horizontally on chrome and firefox (that shouldn't happen)
|
||||
// We could use it to scroll horizontally following RTL but that also seems to be broken - it will always scroll left
|
||||
// scrollLeft = 0 also seems to ignore RTL and manually checking for RTL is too much hassle so we will scroll just vertically
|
||||
htmlElement.scrollTop = 0;
|
||||
// Scroll to domNode if domNode is not in viewport when scrolled to top of document
|
||||
if (!topOfElementInViewport(domNode, viewportHeight)) {
|
||||
// Scroll into view doesn't scroll horizontally by default when not needed
|
||||
;
|
||||
domNode.scrollIntoView();
|
||||
}
|
||||
}, {
|
||||
// We will force layout by querying domNode position
|
||||
dontForceLayout: true,
|
||||
onlyHashChange: focusAndScrollRef.onlyHashChange
|
||||
});
|
||||
// Mutate after scrolling so that it can be read by `handleSmoothScroll`
|
||||
focusAndScrollRef.onlyHashChange = false;
|
||||
// Set focus on the element
|
||||
domNode.focus();
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
function ScrollAndFocusHandler(param) {
|
||||
let { segmentPath, children } = param;
|
||||
const context = useContext(GlobalLayoutRouterContext);
|
||||
if (!context) {
|
||||
throw new Error('invariant global layout router not mounted');
|
||||
}
|
||||
return /*#__PURE__*/ _jsx(InnerScrollAndFocusHandler, {
|
||||
segmentPath: segmentPath,
|
||||
focusAndScrollRef: context.focusAndScrollRef,
|
||||
children: children
|
||||
});
|
||||
}
|
||||
/**
|
||||
* InnerLayoutRouter handles rendering the provided segment based on the cache.
|
||||
*/ function InnerLayoutRouter(param) {
|
||||
let { parallelRouterKey, url, childNodes, segmentPath, tree, // TODO-APP: implement `<Offscreen>` when available.
|
||||
// isActive,
|
||||
cacheKey } = param;
|
||||
const context = useContext(GlobalLayoutRouterContext);
|
||||
if (!context) {
|
||||
throw new Error('invariant global layout router not mounted');
|
||||
}
|
||||
const { changeByServerResponse, tree: fullTree } = context;
|
||||
// Read segment path from the parallel router cache node.
|
||||
let childNode = childNodes.get(cacheKey);
|
||||
// When data is not available during rendering client-side we need to fetch
|
||||
// it from the server.
|
||||
if (childNode === undefined) {
|
||||
const newLazyCacheNode = {
|
||||
lazyData: null,
|
||||
rsc: null,
|
||||
prefetchRsc: null,
|
||||
head: null,
|
||||
prefetchHead: null,
|
||||
parallelRoutes: new Map(),
|
||||
loading: null
|
||||
};
|
||||
/**
|
||||
* Flight data fetch kicked off during render and put into the cache.
|
||||
*/ childNode = newLazyCacheNode;
|
||||
childNodes.set(cacheKey, newLazyCacheNode);
|
||||
}
|
||||
// `rsc` represents the renderable node for this segment.
|
||||
// If this segment has a `prefetchRsc`, it's the statically prefetched data.
|
||||
// We should use that on initial render instead of `rsc`. Then we'll switch
|
||||
// to `rsc` when the dynamic response streams in.
|
||||
//
|
||||
// If no prefetch data is available, then we go straight to rendering `rsc`.
|
||||
const resolvedPrefetchRsc = childNode.prefetchRsc !== null ? childNode.prefetchRsc : childNode.rsc;
|
||||
// We use `useDeferredValue` to handle switching between the prefetched and
|
||||
// final values. The second argument is returned on initial render, then it
|
||||
// re-renders with the first argument.
|
||||
//
|
||||
// @ts-expect-error The second argument to `useDeferredValue` is only
|
||||
// available in the experimental builds. When its disabled, it will always
|
||||
// return `rsc`.
|
||||
const rsc = useDeferredValue(childNode.rsc, resolvedPrefetchRsc);
|
||||
// `rsc` is either a React node or a promise for a React node, except we
|
||||
// special case `null` to represent that this segment's data is missing. If
|
||||
// it's a promise, we need to unwrap it so we can determine whether or not the
|
||||
// data is missing.
|
||||
const resolvedRsc = typeof rsc === 'object' && rsc !== null && typeof rsc.then === 'function' ? use(rsc) : rsc;
|
||||
if (!resolvedRsc) {
|
||||
// The data for this segment is not available, and there's no pending
|
||||
// navigation that will be able to fulfill it. We need to fetch more from
|
||||
// the server and patch the cache.
|
||||
// Check if there's already a pending request.
|
||||
let lazyData = childNode.lazyData;
|
||||
if (lazyData === null) {
|
||||
/**
|
||||
* Router state with refetch marker added
|
||||
*/ // TODO-APP: remove ''
|
||||
const refetchTree = walkAddRefetch([
|
||||
'',
|
||||
...segmentPath
|
||||
], fullTree);
|
||||
const includeNextUrl = hasInterceptionRouteInCurrentTree(fullTree);
|
||||
childNode.lazyData = lazyData = fetchServerResponse(new URL(url, location.origin), {
|
||||
flightRouterState: refetchTree,
|
||||
nextUrl: includeNextUrl ? context.nextUrl : null
|
||||
}).then((serverResponse)=>{
|
||||
startTransition(()=>{
|
||||
changeByServerResponse({
|
||||
previousTree: fullTree,
|
||||
serverResponse
|
||||
});
|
||||
});
|
||||
return serverResponse;
|
||||
});
|
||||
}
|
||||
// Suspend infinitely as `changeByServerResponse` will cause a different part of the tree to be rendered.
|
||||
// A falsey `resolvedRsc` indicates missing data -- we should not commit that branch, and we need to wait for the data to arrive.
|
||||
use(unresolvedThenable);
|
||||
}
|
||||
// If we get to this point, then we know we have something we can render.
|
||||
const subtree = // The layout router context narrows down tree and childNodes at each level.
|
||||
/*#__PURE__*/ _jsx(LayoutRouterContext.Provider, {
|
||||
value: {
|
||||
tree: tree[1][parallelRouterKey],
|
||||
childNodes: childNode.parallelRoutes,
|
||||
// TODO-APP: overriding of url for parallel routes
|
||||
url: url,
|
||||
loading: childNode.loading
|
||||
},
|
||||
children: resolvedRsc
|
||||
});
|
||||
// Ensure root layout is not wrapped in a div as the root layout renders `<html>`
|
||||
return subtree;
|
||||
}
|
||||
/**
|
||||
* Renders suspense boundary with the provided "loading" property as the fallback.
|
||||
* If no loading property is provided it renders the children without a suspense boundary.
|
||||
*/ function LoadingBoundary(param) {
|
||||
let { loading, children } = param;
|
||||
// If loading is a promise, unwrap it. This happens in cases where we haven't
|
||||
// yet received the loading data from the server — which includes whether or
|
||||
// not this layout has a loading component at all.
|
||||
//
|
||||
// It's OK to suspend here instead of inside the fallback because this
|
||||
// promise will resolve simultaneously with the data for the segment itself.
|
||||
// So it will never suspend for longer than it would have if we didn't use
|
||||
// a Suspense fallback at all.
|
||||
let loadingModuleData;
|
||||
if (typeof loading === 'object' && loading !== null && typeof loading.then === 'function') {
|
||||
const promiseForLoading = loading;
|
||||
loadingModuleData = use(promiseForLoading);
|
||||
} else {
|
||||
loadingModuleData = loading;
|
||||
}
|
||||
if (loadingModuleData) {
|
||||
const loadingRsc = loadingModuleData[0];
|
||||
const loadingStyles = loadingModuleData[1];
|
||||
const loadingScripts = loadingModuleData[2];
|
||||
return /*#__PURE__*/ _jsx(Suspense, {
|
||||
fallback: /*#__PURE__*/ _jsxs(_Fragment, {
|
||||
children: [
|
||||
loadingStyles,
|
||||
loadingScripts,
|
||||
loadingRsc
|
||||
]
|
||||
}),
|
||||
children: children
|
||||
});
|
||||
}
|
||||
return /*#__PURE__*/ _jsx(_Fragment, {
|
||||
children: children
|
||||
});
|
||||
}
|
||||
/**
|
||||
* OuterLayoutRouter handles the current segment as well as <Offscreen> rendering of other segments.
|
||||
* It can be rendered next to each other with a different `parallelRouterKey`, allowing for Parallel routes.
|
||||
*/ export default function OuterLayoutRouter(param) {
|
||||
let { parallelRouterKey, segmentPath, error, errorStyles, errorScripts, templateStyles, templateScripts, template, notFound, forbidden, unauthorized } = param;
|
||||
const context = useContext(LayoutRouterContext);
|
||||
if (!context) {
|
||||
throw new Error('invariant expected layout router to be mounted');
|
||||
}
|
||||
const { childNodes, tree, url, loading } = context;
|
||||
// Get the current parallelRouter cache node
|
||||
let childNodesForParallelRouter = childNodes.get(parallelRouterKey);
|
||||
// If the parallel router cache node does not exist yet, create it.
|
||||
// This writes to the cache when there is no item in the cache yet. It never *overwrites* existing cache items which is why it's safe in concurrent mode.
|
||||
if (!childNodesForParallelRouter) {
|
||||
childNodesForParallelRouter = new Map();
|
||||
childNodes.set(parallelRouterKey, childNodesForParallelRouter);
|
||||
}
|
||||
// Get the active segment in the tree
|
||||
// The reason arrays are used in the data format is that these are transferred from the server to the browser so it's optimized to save bytes.
|
||||
const treeSegment = tree[1][parallelRouterKey][0];
|
||||
// If segment is an array it's a dynamic route and we want to read the dynamic route value as the segment to get from the cache.
|
||||
const currentChildSegmentValue = getSegmentValue(treeSegment);
|
||||
/**
|
||||
* Decides which segments to keep rendering, all segments that are not active will be wrapped in `<Offscreen>`.
|
||||
*/ // TODO-APP: Add handling of `<Offscreen>` when it's available.
|
||||
const preservedSegments = [
|
||||
treeSegment
|
||||
];
|
||||
return /*#__PURE__*/ _jsx(_Fragment, {
|
||||
children: preservedSegments.map((preservedSegment)=>{
|
||||
const preservedSegmentValue = getSegmentValue(preservedSegment);
|
||||
const cacheKey = createRouterCacheKey(preservedSegment);
|
||||
return(/*
|
||||
- Error boundary
|
||||
- Only renders error boundary if error component is provided.
|
||||
- Rendered for each segment to ensure they have their own error state.
|
||||
- Loading boundary
|
||||
- Only renders suspense boundary if loading components is provided.
|
||||
- Rendered for each segment to ensure they have their own loading state.
|
||||
- Passed to the router during rendering to ensure it can be immediately rendered when suspending on a Flight fetch.
|
||||
*/ /*#__PURE__*/ _jsxs(TemplateContext.Provider, {
|
||||
value: /*#__PURE__*/ _jsx(ScrollAndFocusHandler, {
|
||||
segmentPath: segmentPath,
|
||||
children: /*#__PURE__*/ _jsx(ErrorBoundary, {
|
||||
errorComponent: error,
|
||||
errorStyles: errorStyles,
|
||||
errorScripts: errorScripts,
|
||||
children: /*#__PURE__*/ _jsx(LoadingBoundary, {
|
||||
loading: loading,
|
||||
children: /*#__PURE__*/ _jsx(HTTPAccessFallbackBoundary, {
|
||||
notFound: notFound,
|
||||
forbidden: forbidden,
|
||||
unauthorized: unauthorized,
|
||||
children: /*#__PURE__*/ _jsx(RedirectBoundary, {
|
||||
children: /*#__PURE__*/ _jsx(InnerLayoutRouter, {
|
||||
parallelRouterKey: parallelRouterKey,
|
||||
url: url,
|
||||
tree: tree,
|
||||
childNodes: childNodesForParallelRouter,
|
||||
segmentPath: segmentPath,
|
||||
cacheKey: cacheKey,
|
||||
isActive: currentChildSegmentValue === preservedSegmentValue
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
}),
|
||||
children: [
|
||||
templateStyles,
|
||||
templateScripts,
|
||||
template
|
||||
]
|
||||
}, createRouterCacheKey(preservedSegment, true)));
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
//# sourceMappingURL=layout-router.js.map
|
||||
+1
File diff suppressed because one or more lines are too long
+26
@@ -0,0 +1,26 @@
|
||||
import { getSegmentParam } from '../../server/app-render/get-segment-param';
|
||||
export const matchSegment = (existingSegment, segment)=>{
|
||||
// segment is either Array or string
|
||||
if (typeof existingSegment === 'string') {
|
||||
if (typeof segment === 'string') {
|
||||
// Common case: segment is just a string
|
||||
return existingSegment === segment;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
if (typeof segment === 'string') {
|
||||
return false;
|
||||
}
|
||||
return existingSegment[0] === segment[0] && existingSegment[1] === segment[1];
|
||||
};
|
||||
/*
|
||||
* This function is used to determine if an existing segment can be overridden by the incoming segment.
|
||||
*/ export const canSegmentBeOverridden = (existingSegment, segment)=>{
|
||||
var _getSegmentParam;
|
||||
if (Array.isArray(existingSegment) || !Array.isArray(segment)) {
|
||||
return false;
|
||||
}
|
||||
return ((_getSegmentParam = getSegmentParam(existingSegment)) == null ? void 0 : _getSegmentParam.param) === segment[0];
|
||||
};
|
||||
|
||||
//# sourceMappingURL=match-segments.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../src/client/components/match-segments.ts"],"sourcesContent":["import { getSegmentParam } from '../../server/app-render/get-segment-param'\nimport type { Segment } from '../../server/app-render/types'\n\nexport const matchSegment = (\n existingSegment: Segment,\n segment: Segment\n): boolean => {\n // segment is either Array or string\n if (typeof existingSegment === 'string') {\n if (typeof segment === 'string') {\n // Common case: segment is just a string\n return existingSegment === segment\n }\n return false\n }\n\n if (typeof segment === 'string') {\n return false\n }\n return existingSegment[0] === segment[0] && existingSegment[1] === segment[1]\n}\n\n/*\n * This function is used to determine if an existing segment can be overridden by the incoming segment.\n */\nexport const canSegmentBeOverridden = (\n existingSegment: Segment,\n segment: Segment\n): boolean => {\n if (Array.isArray(existingSegment) || !Array.isArray(segment)) {\n return false\n }\n\n return getSegmentParam(existingSegment)?.param === segment[0]\n}\n"],"names":["getSegmentParam","matchSegment","existingSegment","segment","canSegmentBeOverridden","Array","isArray","param"],"mappings":"AAAA,SAASA,eAAe,QAAQ,4CAA2C;AAG3E,OAAO,MAAMC,eAAe,CAC1BC,iBACAC;IAEA,oCAAoC;IACpC,IAAI,OAAOD,oBAAoB,UAAU;QACvC,IAAI,OAAOC,YAAY,UAAU;YAC/B,wCAAwC;YACxC,OAAOD,oBAAoBC;QAC7B;QACA,OAAO;IACT;IAEA,IAAI,OAAOA,YAAY,UAAU;QAC/B,OAAO;IACT;IACA,OAAOD,eAAe,CAAC,EAAE,KAAKC,OAAO,CAAC,EAAE,IAAID,eAAe,CAAC,EAAE,KAAKC,OAAO,CAAC,EAAE;AAC/E,EAAC;AAED;;CAEC,GACD,OAAO,MAAMC,yBAAyB,CACpCF,iBACAC;QAMOH;IAJP,IAAIK,MAAMC,OAAO,CAACJ,oBAAoB,CAACG,MAAMC,OAAO,CAACH,UAAU;QAC7D,OAAO;IACT;IAEA,OAAOH,EAAAA,mBAAAA,gBAAgBE,qCAAhBF,iBAAkCO,KAAK,MAAKJ,OAAO,CAAC,EAAE;AAC/D,EAAC"}
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
import { useEffect } from 'react';
|
||||
import { createHrefFromUrl } from './router-reducer/create-href-from-url';
|
||||
export function handleHardNavError(error) {
|
||||
if (error && typeof window !== 'undefined' && window.next.__pendingUrl && createHrefFromUrl(new URL(window.location.href)) !== createHrefFromUrl(window.next.__pendingUrl)) {
|
||||
console.error("Error occurred during navigation, falling back to hard navigation", error);
|
||||
window.location.href = window.next.__pendingUrl.toString();
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
export function useNavFailureHandler() {
|
||||
if (process.env.__NEXT_APP_NAV_FAIL_HANDLING) {
|
||||
// this if is only for DCE of the feature flag not conditional
|
||||
// eslint-disable-next-line react-hooks/rules-of-hooks
|
||||
useEffect(()=>{
|
||||
const uncaughtExceptionHandler = (evt)=>{
|
||||
const error = 'reason' in evt ? evt.reason : evt.error;
|
||||
// if we have an unhandled exception/rejection during
|
||||
// a navigation we fall back to a hard navigation to
|
||||
// attempt recovering to a good state
|
||||
handleHardNavError(error);
|
||||
};
|
||||
window.addEventListener('unhandledrejection', uncaughtExceptionHandler);
|
||||
window.addEventListener('error', uncaughtExceptionHandler);
|
||||
return ()=>{
|
||||
window.removeEventListener('error', uncaughtExceptionHandler);
|
||||
window.removeEventListener('unhandledrejection', uncaughtExceptionHandler);
|
||||
};
|
||||
}, []);
|
||||
}
|
||||
}
|
||||
|
||||
//# sourceMappingURL=nav-failure-handler.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../src/client/components/nav-failure-handler.ts"],"sourcesContent":["import { useEffect } from 'react'\nimport { createHrefFromUrl } from './router-reducer/create-href-from-url'\n\nexport function handleHardNavError(error: unknown): boolean {\n if (\n error &&\n typeof window !== 'undefined' &&\n window.next.__pendingUrl &&\n createHrefFromUrl(new URL(window.location.href)) !==\n createHrefFromUrl(window.next.__pendingUrl)\n ) {\n console.error(\n `Error occurred during navigation, falling back to hard navigation`,\n error\n )\n window.location.href = window.next.__pendingUrl.toString()\n return true\n }\n return false\n}\n\nexport function useNavFailureHandler() {\n if (process.env.__NEXT_APP_NAV_FAIL_HANDLING) {\n // this if is only for DCE of the feature flag not conditional\n // eslint-disable-next-line react-hooks/rules-of-hooks\n useEffect(() => {\n const uncaughtExceptionHandler = (\n evt: ErrorEvent | PromiseRejectionEvent\n ) => {\n const error = 'reason' in evt ? evt.reason : evt.error\n // if we have an unhandled exception/rejection during\n // a navigation we fall back to a hard navigation to\n // attempt recovering to a good state\n handleHardNavError(error)\n }\n window.addEventListener('unhandledrejection', uncaughtExceptionHandler)\n window.addEventListener('error', uncaughtExceptionHandler)\n return () => {\n window.removeEventListener('error', uncaughtExceptionHandler)\n window.removeEventListener(\n 'unhandledrejection',\n uncaughtExceptionHandler\n )\n }\n }, [])\n }\n}\n"],"names":["useEffect","createHrefFromUrl","handleHardNavError","error","window","next","__pendingUrl","URL","location","href","console","toString","useNavFailureHandler","process","env","__NEXT_APP_NAV_FAIL_HANDLING","uncaughtExceptionHandler","evt","reason","addEventListener","removeEventListener"],"mappings":"AAAA,SAASA,SAAS,QAAQ,QAAO;AACjC,SAASC,iBAAiB,QAAQ,wCAAuC;AAEzE,OAAO,SAASC,mBAAmBC,KAAc;IAC/C,IACEA,SACA,OAAOC,WAAW,eAClBA,OAAOC,IAAI,CAACC,YAAY,IACxBL,kBAAkB,IAAIM,IAAIH,OAAOI,QAAQ,CAACC,IAAI,OAC5CR,kBAAkBG,OAAOC,IAAI,CAACC,YAAY,GAC5C;QACAI,QAAQP,KAAK,CACV,qEACDA;QAEFC,OAAOI,QAAQ,CAACC,IAAI,GAAGL,OAAOC,IAAI,CAACC,YAAY,CAACK,QAAQ;QACxD,OAAO;IACT;IACA,OAAO;AACT;AAEA,OAAO,SAASC;IACd,IAAIC,QAAQC,GAAG,CAACC,4BAA4B,EAAE;QAC5C,8DAA8D;QAC9D,sDAAsD;QACtDf,UAAU;YACR,MAAMgB,2BAA2B,CAC/BC;gBAEA,MAAMd,QAAQ,YAAYc,MAAMA,IAAIC,MAAM,GAAGD,IAAId,KAAK;gBACtD,qDAAqD;gBACrD,oDAAoD;gBACpD,qCAAqC;gBACrCD,mBAAmBC;YACrB;YACAC,OAAOe,gBAAgB,CAAC,sBAAsBH;YAC9CZ,OAAOe,gBAAgB,CAAC,SAASH;YACjC,OAAO;gBACLZ,OAAOgB,mBAAmB,CAAC,SAASJ;gBACpCZ,OAAOgB,mBAAmB,CACxB,sBACAJ;YAEJ;QACF,GAAG,EAAE;IACP;AACF"}
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
import { useContext } from 'react';
|
||||
import { PathnameContext } from '../../shared/lib/hooks-client-context.shared-runtime';
|
||||
/**
|
||||
* This checks to see if the current render has any unknown route parameters.
|
||||
* It's used to trigger a different render path in the error boundary.
|
||||
*
|
||||
* @returns true if there are any unknown route parameters, false otherwise
|
||||
*/ function hasFallbackRouteParams() {
|
||||
if (typeof window === 'undefined') {
|
||||
// AsyncLocalStorage should not be included in the client bundle.
|
||||
const { workAsyncStorage } = require('../../server/app-render/work-async-storage.external');
|
||||
const workStore = workAsyncStorage.getStore();
|
||||
if (!workStore) return false;
|
||||
const { fallbackRouteParams } = workStore;
|
||||
if (!fallbackRouteParams || fallbackRouteParams.size === 0) return false;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
/**
|
||||
* This returns a `null` value if there are any unknown route parameters, and
|
||||
* otherwise returns the pathname from the context. This is an alternative to
|
||||
* `usePathname` that is used in the error boundary to avoid rendering the
|
||||
* error boundary when there are unknown route parameters. This doesn't throw
|
||||
* when accessed with unknown route parameters.
|
||||
*
|
||||
* @returns
|
||||
*
|
||||
* @internal
|
||||
*/ export function useUntrackedPathname() {
|
||||
// If there are any unknown route parameters we would typically throw
|
||||
// an error, but this internal method allows us to return a null value instead
|
||||
// for components that do not propagate the pathname to the static shell (like
|
||||
// the error boundary).
|
||||
if (hasFallbackRouteParams()) {
|
||||
return null;
|
||||
}
|
||||
// This shouldn't cause any issues related to conditional rendering because
|
||||
// the environment will be consistent for the render.
|
||||
// eslint-disable-next-line react-hooks/rules-of-hooks
|
||||
return useContext(PathnameContext);
|
||||
}
|
||||
|
||||
//# sourceMappingURL=navigation-untracked.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../src/client/components/navigation-untracked.ts"],"sourcesContent":["import { useContext } from 'react'\nimport { PathnameContext } from '../../shared/lib/hooks-client-context.shared-runtime'\n\n/**\n * This checks to see if the current render has any unknown route parameters.\n * It's used to trigger a different render path in the error boundary.\n *\n * @returns true if there are any unknown route parameters, false otherwise\n */\nfunction hasFallbackRouteParams() {\n if (typeof window === 'undefined') {\n // AsyncLocalStorage should not be included in the client bundle.\n const { workAsyncStorage } =\n require('../../server/app-render/work-async-storage.external') as typeof import('../../server/app-render/work-async-storage.external')\n\n const workStore = workAsyncStorage.getStore()\n if (!workStore) return false\n\n const { fallbackRouteParams } = workStore\n if (!fallbackRouteParams || fallbackRouteParams.size === 0) return false\n\n return true\n }\n\n return false\n}\n\n/**\n * This returns a `null` value if there are any unknown route parameters, and\n * otherwise returns the pathname from the context. This is an alternative to\n * `usePathname` that is used in the error boundary to avoid rendering the\n * error boundary when there are unknown route parameters. This doesn't throw\n * when accessed with unknown route parameters.\n *\n * @returns\n *\n * @internal\n */\nexport function useUntrackedPathname(): string | null {\n // If there are any unknown route parameters we would typically throw\n // an error, but this internal method allows us to return a null value instead\n // for components that do not propagate the pathname to the static shell (like\n // the error boundary).\n if (hasFallbackRouteParams()) {\n return null\n }\n\n // This shouldn't cause any issues related to conditional rendering because\n // the environment will be consistent for the render.\n // eslint-disable-next-line react-hooks/rules-of-hooks\n return useContext(PathnameContext)\n}\n"],"names":["useContext","PathnameContext","hasFallbackRouteParams","window","workAsyncStorage","require","workStore","getStore","fallbackRouteParams","size","useUntrackedPathname"],"mappings":"AAAA,SAASA,UAAU,QAAQ,QAAO;AAClC,SAASC,eAAe,QAAQ,uDAAsD;AAEtF;;;;;CAKC,GACD,SAASC;IACP,IAAI,OAAOC,WAAW,aAAa;QACjC,iEAAiE;QACjE,MAAM,EAAEC,gBAAgB,EAAE,GACxBC,QAAQ;QAEV,MAAMC,YAAYF,iBAAiBG,QAAQ;QAC3C,IAAI,CAACD,WAAW,OAAO;QAEvB,MAAM,EAAEE,mBAAmB,EAAE,GAAGF;QAChC,IAAI,CAACE,uBAAuBA,oBAAoBC,IAAI,KAAK,GAAG,OAAO;QAEnE,OAAO;IACT;IAEA,OAAO;AACT;AAEA;;;;;;;;;;CAUC,GACD,OAAO,SAASC;IACd,qEAAqE;IACrE,8EAA8E;IAC9E,8EAA8E;IAC9E,uBAAuB;IACvB,IAAIR,0BAA0B;QAC5B,OAAO;IACT;IAEA,2EAA2E;IAC3E,qDAAqD;IACrD,sDAAsD;IACtD,OAAOF,WAAWC;AACpB"}
|
||||
+211
@@ -0,0 +1,211 @@
|
||||
import { useContext, useMemo } from 'react';
|
||||
import { AppRouterContext, LayoutRouterContext } from '../../shared/lib/app-router-context.shared-runtime';
|
||||
import { SearchParamsContext, PathnameContext, PathParamsContext } from '../../shared/lib/hooks-client-context.shared-runtime';
|
||||
import { getSegmentValue } from './router-reducer/reducers/get-segment-value';
|
||||
import { PAGE_SEGMENT_KEY, DEFAULT_SEGMENT_KEY } from '../../shared/lib/segment';
|
||||
import { ReadonlyURLSearchParams } from './navigation.react-server';
|
||||
import { useDynamicRouteParams } from '../../server/app-render/dynamic-rendering';
|
||||
/**
|
||||
* A [Client Component](https://nextjs.org/docs/app/building-your-application/rendering/client-components) hook
|
||||
* that lets you *read* the current URL's search parameters.
|
||||
*
|
||||
* Learn more about [`URLSearchParams` on MDN](https://developer.mozilla.org/docs/Web/API/URLSearchParams)
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* "use client"
|
||||
* import { useSearchParams } from 'next/navigation'
|
||||
*
|
||||
* export default function Page() {
|
||||
* const searchParams = useSearchParams()
|
||||
* searchParams.get('foo') // returns 'bar' when ?foo=bar
|
||||
* // ...
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* Read more: [Next.js Docs: `useSearchParams`](https://nextjs.org/docs/app/api-reference/functions/use-search-params)
|
||||
*/ // Client components API
|
||||
export function useSearchParams() {
|
||||
const searchParams = useContext(SearchParamsContext);
|
||||
// In the case where this is `null`, the compat types added in
|
||||
// `next-env.d.ts` will add a new overload that changes the return type to
|
||||
// include `null`.
|
||||
const readonlySearchParams = useMemo(()=>{
|
||||
if (!searchParams) {
|
||||
// When the router is not ready in pages, we won't have the search params
|
||||
// available.
|
||||
return null;
|
||||
}
|
||||
return new ReadonlyURLSearchParams(searchParams);
|
||||
}, [
|
||||
searchParams
|
||||
]);
|
||||
if (typeof window === 'undefined') {
|
||||
// AsyncLocalStorage should not be included in the client bundle.
|
||||
const { bailoutToClientRendering } = require('./bailout-to-client-rendering');
|
||||
// TODO-APP: handle dynamic = 'force-static' here and on the client
|
||||
bailoutToClientRendering('useSearchParams()');
|
||||
}
|
||||
return readonlySearchParams;
|
||||
}
|
||||
/**
|
||||
* A [Client Component](https://nextjs.org/docs/app/building-your-application/rendering/client-components) hook
|
||||
* that lets you read the current URL's pathname.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* "use client"
|
||||
* import { usePathname } from 'next/navigation'
|
||||
*
|
||||
* export default function Page() {
|
||||
* const pathname = usePathname() // returns "/dashboard" on /dashboard?foo=bar
|
||||
* // ...
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* Read more: [Next.js Docs: `usePathname`](https://nextjs.org/docs/app/api-reference/functions/use-pathname)
|
||||
*/ // Client components API
|
||||
export function usePathname() {
|
||||
useDynamicRouteParams('usePathname()');
|
||||
// In the case where this is `null`, the compat types added in `next-env.d.ts`
|
||||
// will add a new overload that changes the return type to include `null`.
|
||||
return useContext(PathnameContext);
|
||||
}
|
||||
// Client components API
|
||||
export { ServerInsertedHTMLContext, useServerInsertedHTML } from '../../shared/lib/server-inserted-html.shared-runtime';
|
||||
/**
|
||||
*
|
||||
* This hook allows you to programmatically change routes inside [Client Component](https://nextjs.org/docs/app/building-your-application/rendering/client-components).
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* "use client"
|
||||
* import { useRouter } from 'next/navigation'
|
||||
*
|
||||
* export default function Page() {
|
||||
* const router = useRouter()
|
||||
* // ...
|
||||
* router.push('/dashboard') // Navigate to /dashboard
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* Read more: [Next.js Docs: `useRouter`](https://nextjs.org/docs/app/api-reference/functions/use-router)
|
||||
*/ // Client components API
|
||||
export function useRouter() {
|
||||
const router = useContext(AppRouterContext);
|
||||
if (router === null) {
|
||||
throw new Error('invariant expected app router to be mounted');
|
||||
}
|
||||
return router;
|
||||
}
|
||||
/**
|
||||
* A [Client Component](https://nextjs.org/docs/app/building-your-application/rendering/client-components) hook
|
||||
* that lets you read a route's dynamic params filled in by the current URL.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* "use client"
|
||||
* import { useParams } from 'next/navigation'
|
||||
*
|
||||
* export default function Page() {
|
||||
* // on /dashboard/[team] where pathname is /dashboard/nextjs
|
||||
* const { team } = useParams() // team === "nextjs"
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* Read more: [Next.js Docs: `useParams`](https://nextjs.org/docs/app/api-reference/functions/use-params)
|
||||
*/ // Client components API
|
||||
export function useParams() {
|
||||
useDynamicRouteParams('useParams()');
|
||||
return useContext(PathParamsContext);
|
||||
}
|
||||
/** Get the canonical parameters from the current level to the leaf node. */ // Client components API
|
||||
function getSelectedLayoutSegmentPath(tree, parallelRouteKey, first, segmentPath) {
|
||||
if (first === void 0) first = true;
|
||||
if (segmentPath === void 0) segmentPath = [];
|
||||
let node;
|
||||
if (first) {
|
||||
// Use the provided parallel route key on the first parallel route
|
||||
node = tree[1][parallelRouteKey];
|
||||
} else {
|
||||
// After first parallel route prefer children, if there's no children pick the first parallel route.
|
||||
const parallelRoutes = tree[1];
|
||||
var _parallelRoutes_children;
|
||||
node = (_parallelRoutes_children = parallelRoutes.children) != null ? _parallelRoutes_children : Object.values(parallelRoutes)[0];
|
||||
}
|
||||
if (!node) return segmentPath;
|
||||
const segment = node[0];
|
||||
let segmentValue = getSegmentValue(segment);
|
||||
if (!segmentValue || segmentValue.startsWith(PAGE_SEGMENT_KEY)) {
|
||||
return segmentPath;
|
||||
}
|
||||
segmentPath.push(segmentValue);
|
||||
return getSelectedLayoutSegmentPath(node, parallelRouteKey, false, segmentPath);
|
||||
}
|
||||
/**
|
||||
* A [Client Component](https://nextjs.org/docs/app/building-your-application/rendering/client-components) hook
|
||||
* that lets you read the active route segments **below** the Layout it is called from.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* 'use client'
|
||||
*
|
||||
* import { useSelectedLayoutSegments } from 'next/navigation'
|
||||
*
|
||||
* export default function ExampleClientComponent() {
|
||||
* const segments = useSelectedLayoutSegments()
|
||||
*
|
||||
* return (
|
||||
* <ul>
|
||||
* {segments.map((segment, index) => (
|
||||
* <li key={index}>{segment}</li>
|
||||
* ))}
|
||||
* </ul>
|
||||
* )
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* Read more: [Next.js Docs: `useSelectedLayoutSegments`](https://nextjs.org/docs/app/api-reference/functions/use-selected-layout-segments)
|
||||
*/ // Client components API
|
||||
export function useSelectedLayoutSegments(parallelRouteKey) {
|
||||
if (parallelRouteKey === void 0) parallelRouteKey = 'children';
|
||||
useDynamicRouteParams('useSelectedLayoutSegments()');
|
||||
const context = useContext(LayoutRouterContext);
|
||||
// @ts-expect-error This only happens in `pages`. Type is overwritten in navigation.d.ts
|
||||
if (!context) return null;
|
||||
return getSelectedLayoutSegmentPath(context.tree, parallelRouteKey);
|
||||
}
|
||||
/**
|
||||
* A [Client Component](https://nextjs.org/docs/app/building-your-application/rendering/client-components) hook
|
||||
* that lets you read the active route segment **one level below** the Layout it is called from.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* 'use client'
|
||||
* import { useSelectedLayoutSegment } from 'next/navigation'
|
||||
*
|
||||
* export default function ExampleClientComponent() {
|
||||
* const segment = useSelectedLayoutSegment()
|
||||
*
|
||||
* return <p>Active segment: {segment}</p>
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* Read more: [Next.js Docs: `useSelectedLayoutSegment`](https://nextjs.org/docs/app/api-reference/functions/use-selected-layout-segment)
|
||||
*/ // Client components API
|
||||
export function useSelectedLayoutSegment(parallelRouteKey) {
|
||||
if (parallelRouteKey === void 0) parallelRouteKey = 'children';
|
||||
useDynamicRouteParams('useSelectedLayoutSegment()');
|
||||
const selectedLayoutSegments = useSelectedLayoutSegments(parallelRouteKey);
|
||||
if (!selectedLayoutSegments || selectedLayoutSegments.length === 0) {
|
||||
return null;
|
||||
}
|
||||
const selectedLayoutSegment = parallelRouteKey === 'children' ? selectedLayoutSegments[0] : selectedLayoutSegments[selectedLayoutSegments.length - 1];
|
||||
// if the default slot is showing, we return null since it's not technically "selected" (it's a fallback)
|
||||
// and returning an internal value like `__DEFAULT__` would be confusing.
|
||||
return selectedLayoutSegment === DEFAULT_SEGMENT_KEY ? null : selectedLayoutSegment;
|
||||
}
|
||||
// Shared components APIs
|
||||
export { notFound, forbidden, unauthorized, redirect, permanentRedirect, RedirectType, ReadonlyURLSearchParams, unstable_rethrow } from './navigation.react-server';
|
||||
|
||||
//# sourceMappingURL=navigation.js.map
|
||||
+1
File diff suppressed because one or more lines are too long
+28
@@ -0,0 +1,28 @@
|
||||
/** @internal */ class ReadonlyURLSearchParamsError extends Error {
|
||||
constructor(){
|
||||
super('Method unavailable on `ReadonlyURLSearchParams`. Read more: https://nextjs.org/docs/app/api-reference/functions/use-search-params#updating-searchparams');
|
||||
}
|
||||
}
|
||||
class ReadonlyURLSearchParams extends URLSearchParams {
|
||||
/** @deprecated Method unavailable on `ReadonlyURLSearchParams`. Read more: https://nextjs.org/docs/app/api-reference/functions/use-search-params#updating-searchparams */ append() {
|
||||
throw new ReadonlyURLSearchParamsError();
|
||||
}
|
||||
/** @deprecated Method unavailable on `ReadonlyURLSearchParams`. Read more: https://nextjs.org/docs/app/api-reference/functions/use-search-params#updating-searchparams */ delete() {
|
||||
throw new ReadonlyURLSearchParamsError();
|
||||
}
|
||||
/** @deprecated Method unavailable on `ReadonlyURLSearchParams`. Read more: https://nextjs.org/docs/app/api-reference/functions/use-search-params#updating-searchparams */ set() {
|
||||
throw new ReadonlyURLSearchParamsError();
|
||||
}
|
||||
/** @deprecated Method unavailable on `ReadonlyURLSearchParams`. Read more: https://nextjs.org/docs/app/api-reference/functions/use-search-params#updating-searchparams */ sort() {
|
||||
throw new ReadonlyURLSearchParamsError();
|
||||
}
|
||||
}
|
||||
export { redirect, permanentRedirect } from './redirect';
|
||||
export { RedirectType } from './redirect-error';
|
||||
export { notFound } from './not-found';
|
||||
export { forbidden } from './forbidden';
|
||||
export { unauthorized } from './unauthorized';
|
||||
export { unstable_rethrow } from './unstable-rethrow';
|
||||
export { ReadonlyURLSearchParams };
|
||||
|
||||
//# sourceMappingURL=navigation.react-server.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../src/client/components/navigation.react-server.ts"],"sourcesContent":["/** @internal */\nclass ReadonlyURLSearchParamsError extends Error {\n constructor() {\n super(\n 'Method unavailable on `ReadonlyURLSearchParams`. Read more: https://nextjs.org/docs/app/api-reference/functions/use-search-params#updating-searchparams'\n )\n }\n}\n\nclass ReadonlyURLSearchParams extends URLSearchParams {\n /** @deprecated Method unavailable on `ReadonlyURLSearchParams`. Read more: https://nextjs.org/docs/app/api-reference/functions/use-search-params#updating-searchparams */\n append() {\n throw new ReadonlyURLSearchParamsError()\n }\n /** @deprecated Method unavailable on `ReadonlyURLSearchParams`. Read more: https://nextjs.org/docs/app/api-reference/functions/use-search-params#updating-searchparams */\n delete() {\n throw new ReadonlyURLSearchParamsError()\n }\n /** @deprecated Method unavailable on `ReadonlyURLSearchParams`. Read more: https://nextjs.org/docs/app/api-reference/functions/use-search-params#updating-searchparams */\n set() {\n throw new ReadonlyURLSearchParamsError()\n }\n /** @deprecated Method unavailable on `ReadonlyURLSearchParams`. Read more: https://nextjs.org/docs/app/api-reference/functions/use-search-params#updating-searchparams */\n sort() {\n throw new ReadonlyURLSearchParamsError()\n }\n}\n\nexport { redirect, permanentRedirect } from './redirect'\nexport { RedirectType } from './redirect-error'\nexport { notFound } from './not-found'\nexport { forbidden } from './forbidden'\nexport { unauthorized } from './unauthorized'\nexport { unstable_rethrow } from './unstable-rethrow'\nexport { ReadonlyURLSearchParams }\n"],"names":["ReadonlyURLSearchParamsError","Error","constructor","ReadonlyURLSearchParams","URLSearchParams","append","delete","set","sort","redirect","permanentRedirect","RedirectType","notFound","forbidden","unauthorized","unstable_rethrow"],"mappings":"AAAA,cAAc,GACd,MAAMA,qCAAqCC;IACzCC,aAAc;QACZ,KAAK,CACH;IAEJ;AACF;AAEA,MAAMC,gCAAgCC;IACpC,wKAAwK,GACxKC,SAAS;QACP,MAAM,IAAIL;IACZ;IACA,wKAAwK,GACxKM,SAAS;QACP,MAAM,IAAIN;IACZ;IACA,wKAAwK,GACxKO,MAAM;QACJ,MAAM,IAAIP;IACZ;IACA,wKAAwK,GACxKQ,OAAO;QACL,MAAM,IAAIR;IACZ;AACF;AAEA,SAASS,QAAQ,EAAEC,iBAAiB,QAAQ,aAAY;AACxD,SAASC,YAAY,QAAQ,mBAAkB;AAC/C,SAASC,QAAQ,QAAQ,cAAa;AACtC,SAASC,SAAS,QAAQ,cAAa;AACvC,SAASC,YAAY,QAAQ,iBAAgB;AAC7C,SAASC,gBAAgB,QAAQ,qBAAoB;AACrD,SAASZ,uBAAuB,GAAE"}
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
export default function NoopHead() {
|
||||
return null;
|
||||
}
|
||||
|
||||
//# sourceMappingURL=noop-head.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../src/client/components/noop-head.tsx"],"sourcesContent":["export default function NoopHead() {\n return null\n}\n"],"names":["NoopHead"],"mappings":"AAAA,eAAe,SAASA;IACtB,OAAO;AACT"}
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
import { jsx as _jsx } from "react/jsx-runtime";
|
||||
import { HTTPAccessErrorFallback } from './http-access-fallback/error-fallback';
|
||||
export default function NotFound() {
|
||||
return /*#__PURE__*/ _jsx(HTTPAccessErrorFallback, {
|
||||
status: 404,
|
||||
message: "This page could not be found."
|
||||
});
|
||||
}
|
||||
|
||||
//# sourceMappingURL=not-found-error.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../src/client/components/not-found-error.tsx"],"sourcesContent":["import { HTTPAccessErrorFallback } from './http-access-fallback/error-fallback'\n\nexport default function NotFound() {\n return (\n <HTTPAccessErrorFallback\n status={404}\n message=\"This page could not be found.\"\n />\n )\n}\n"],"names":["HTTPAccessErrorFallback","NotFound","status","message"],"mappings":";AAAA,SAASA,uBAAuB,QAAQ,wCAAuC;AAE/E,eAAe,SAASC;IACtB,qBACE,KAACD;QACCE,QAAQ;QACRC,SAAQ;;AAGd"}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
import { HTTP_ERROR_FALLBACK_ERROR_CODE } from './http-access-fallback/http-access-fallback';
|
||||
/**
|
||||
* This function allows you to render the [not-found.js file](https://nextjs.org/docs/app/api-reference/file-conventions/not-found)
|
||||
* within a route segment as well as inject a tag.
|
||||
*
|
||||
* `notFound()` can be used in
|
||||
* [Server Components](https://nextjs.org/docs/app/building-your-application/rendering/server-components),
|
||||
* [Route Handlers](https://nextjs.org/docs/app/building-your-application/routing/route-handlers), and
|
||||
* [Server Actions](https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions-and-mutations).
|
||||
*
|
||||
* - In a Server Component, this will insert a `<meta name="robots" content="noindex" />` meta tag and set the status code to 404.
|
||||
* - In a Route Handler or Server Action, it will serve a 404 to the caller.
|
||||
*
|
||||
* Read more: [Next.js Docs: `notFound`](https://nextjs.org/docs/app/api-reference/functions/not-found)
|
||||
*/ const DIGEST = "" + HTTP_ERROR_FALLBACK_ERROR_CODE + ";404";
|
||||
export function notFound() {
|
||||
// eslint-disable-next-line no-throw-literal
|
||||
const error = new Error(DIGEST);
|
||||
error.digest = DIGEST;
|
||||
throw error;
|
||||
}
|
||||
|
||||
//# sourceMappingURL=not-found.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../src/client/components/not-found.ts"],"sourcesContent":["import {\n HTTP_ERROR_FALLBACK_ERROR_CODE,\n type HTTPAccessFallbackError,\n} from './http-access-fallback/http-access-fallback'\n\n/**\n * This function allows you to render the [not-found.js file](https://nextjs.org/docs/app/api-reference/file-conventions/not-found)\n * within a route segment as well as inject a tag.\n *\n * `notFound()` can be used in\n * [Server Components](https://nextjs.org/docs/app/building-your-application/rendering/server-components),\n * [Route Handlers](https://nextjs.org/docs/app/building-your-application/routing/route-handlers), and\n * [Server Actions](https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions-and-mutations).\n *\n * - In a Server Component, this will insert a `<meta name=\"robots\" content=\"noindex\" />` meta tag and set the status code to 404.\n * - In a Route Handler or Server Action, it will serve a 404 to the caller.\n *\n * Read more: [Next.js Docs: `notFound`](https://nextjs.org/docs/app/api-reference/functions/not-found)\n */\n\nconst DIGEST = `${HTTP_ERROR_FALLBACK_ERROR_CODE};404`\n\nexport function notFound(): never {\n // eslint-disable-next-line no-throw-literal\n const error = new Error(DIGEST) as HTTPAccessFallbackError\n ;(error as HTTPAccessFallbackError).digest = DIGEST\n\n throw error\n}\n"],"names":["HTTP_ERROR_FALLBACK_ERROR_CODE","DIGEST","notFound","error","Error","digest"],"mappings":"AAAA,SACEA,8BAA8B,QAEzB,8CAA6C;AAEpD;;;;;;;;;;;;;CAaC,GAED,MAAMC,SAAS,AAAC,KAAED,iCAA+B;AAEjD,OAAO,SAASE;IACd,4CAA4C;IAC5C,MAAMC,QAAQ,IAAIC,MAAMH;IACtBE,MAAkCE,MAAM,GAAGJ;IAE7C,MAAME;AACR"}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
import { notFound } from './not-found';
|
||||
export const PARALLEL_ROUTE_DEFAULT_PATH = 'next/dist/client/components/parallel-route-default.js';
|
||||
export default function ParallelRouteDefault() {
|
||||
notFound();
|
||||
}
|
||||
|
||||
//# sourceMappingURL=parallel-route-default.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../src/client/components/parallel-route-default.tsx"],"sourcesContent":["import { notFound } from './not-found'\n\nexport const PARALLEL_ROUTE_DEFAULT_PATH =\n 'next/dist/client/components/parallel-route-default.js'\n\nexport default function ParallelRouteDefault() {\n notFound()\n}\n"],"names":["notFound","PARALLEL_ROUTE_DEFAULT_PATH","ParallelRouteDefault"],"mappings":"AAAA,SAASA,QAAQ,QAAQ,cAAa;AAEtC,OAAO,MAAMC,8BACX,wDAAuD;AAEzD,eAAe,SAASC;IACtBF;AACF"}
|
||||
+75
@@ -0,0 +1,75 @@
|
||||
/*
|
||||
This is a simple promise queue that allows you to limit the number of concurrent promises
|
||||
that are running at any given time. It's used to limit the number of concurrent
|
||||
prefetch requests that are being made to the server but could be used for other
|
||||
things as well.
|
||||
*/ import { _ as _class_private_field_loose_base } from "@swc/helpers/_/_class_private_field_loose_base";
|
||||
import { _ as _class_private_field_loose_key } from "@swc/helpers/_/_class_private_field_loose_key";
|
||||
var _maxConcurrency = /*#__PURE__*/ _class_private_field_loose_key("_maxConcurrency"), _runningCount = /*#__PURE__*/ _class_private_field_loose_key("_runningCount"), _queue = /*#__PURE__*/ _class_private_field_loose_key("_queue"), _processNext = /*#__PURE__*/ _class_private_field_loose_key("_processNext");
|
||||
export class PromiseQueue {
|
||||
enqueue(promiseFn) {
|
||||
let taskResolve;
|
||||
let taskReject;
|
||||
const taskPromise = new Promise((resolve, reject)=>{
|
||||
taskResolve = resolve;
|
||||
taskReject = reject;
|
||||
});
|
||||
const task = async ()=>{
|
||||
try {
|
||||
_class_private_field_loose_base(this, _runningCount)[_runningCount]++;
|
||||
const result = await promiseFn();
|
||||
taskResolve(result);
|
||||
} catch (error) {
|
||||
taskReject(error);
|
||||
} finally{
|
||||
_class_private_field_loose_base(this, _runningCount)[_runningCount]--;
|
||||
_class_private_field_loose_base(this, _processNext)[_processNext]();
|
||||
}
|
||||
};
|
||||
const enqueueResult = {
|
||||
promiseFn: taskPromise,
|
||||
task
|
||||
};
|
||||
// wonder if we should take a LIFO approach here
|
||||
_class_private_field_loose_base(this, _queue)[_queue].push(enqueueResult);
|
||||
_class_private_field_loose_base(this, _processNext)[_processNext]();
|
||||
return taskPromise;
|
||||
}
|
||||
bump(promiseFn) {
|
||||
const index = _class_private_field_loose_base(this, _queue)[_queue].findIndex((item)=>item.promiseFn === promiseFn);
|
||||
if (index > -1) {
|
||||
const bumpedItem = _class_private_field_loose_base(this, _queue)[_queue].splice(index, 1)[0];
|
||||
_class_private_field_loose_base(this, _queue)[_queue].unshift(bumpedItem);
|
||||
_class_private_field_loose_base(this, _processNext)[_processNext](true);
|
||||
}
|
||||
}
|
||||
constructor(maxConcurrency = 5){
|
||||
Object.defineProperty(this, _processNext, {
|
||||
value: processNext
|
||||
});
|
||||
Object.defineProperty(this, _maxConcurrency, {
|
||||
writable: true,
|
||||
value: void 0
|
||||
});
|
||||
Object.defineProperty(this, _runningCount, {
|
||||
writable: true,
|
||||
value: void 0
|
||||
});
|
||||
Object.defineProperty(this, _queue, {
|
||||
writable: true,
|
||||
value: void 0
|
||||
});
|
||||
_class_private_field_loose_base(this, _maxConcurrency)[_maxConcurrency] = maxConcurrency;
|
||||
_class_private_field_loose_base(this, _runningCount)[_runningCount] = 0;
|
||||
_class_private_field_loose_base(this, _queue)[_queue] = [];
|
||||
}
|
||||
}
|
||||
function processNext(forced) {
|
||||
if (forced === void 0) forced = false;
|
||||
if ((_class_private_field_loose_base(this, _runningCount)[_runningCount] < _class_private_field_loose_base(this, _maxConcurrency)[_maxConcurrency] || forced) && _class_private_field_loose_base(this, _queue)[_queue].length > 0) {
|
||||
var _class_private_field_loose_base__queue_shift;
|
||||
(_class_private_field_loose_base__queue_shift = _class_private_field_loose_base(this, _queue)[_queue].shift()) == null ? void 0 : _class_private_field_loose_base__queue_shift.task();
|
||||
}
|
||||
}
|
||||
|
||||
//# sourceMappingURL=promise-queue.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../src/client/components/promise-queue.ts"],"sourcesContent":["/*\n This is a simple promise queue that allows you to limit the number of concurrent promises\n that are running at any given time. It's used to limit the number of concurrent\n prefetch requests that are being made to the server but could be used for other\n things as well.\n*/\nexport class PromiseQueue {\n #maxConcurrency: number\n #runningCount: number\n #queue: Array<{\n promiseFn: Promise<any>\n task: () => void\n }>\n\n constructor(maxConcurrency = 5) {\n this.#maxConcurrency = maxConcurrency\n this.#runningCount = 0\n this.#queue = []\n }\n\n enqueue<T>(promiseFn: () => Promise<T>): Promise<T> {\n let taskResolve: (value: T | PromiseLike<T>) => void\n let taskReject: (reason?: any) => void\n\n const taskPromise = new Promise((resolve, reject) => {\n taskResolve = resolve\n taskReject = reject\n }) as Promise<T>\n\n const task = async () => {\n try {\n this.#runningCount++\n const result = await promiseFn()\n taskResolve(result)\n } catch (error) {\n taskReject(error)\n } finally {\n this.#runningCount--\n this.#processNext()\n }\n }\n\n const enqueueResult = { promiseFn: taskPromise, task }\n // wonder if we should take a LIFO approach here\n this.#queue.push(enqueueResult)\n this.#processNext()\n\n return taskPromise\n }\n\n bump(promiseFn: Promise<any>) {\n const index = this.#queue.findIndex((item) => item.promiseFn === promiseFn)\n\n if (index > -1) {\n const bumpedItem = this.#queue.splice(index, 1)[0]\n this.#queue.unshift(bumpedItem)\n this.#processNext(true)\n }\n }\n\n #processNext(forced = false) {\n if (\n (this.#runningCount < this.#maxConcurrency || forced) &&\n this.#queue.length > 0\n ) {\n this.#queue.shift()?.task()\n }\n }\n}\n"],"names":["PromiseQueue","enqueue","promiseFn","taskResolve","taskReject","taskPromise","Promise","resolve","reject","task","result","error","enqueueResult","push","bump","index","findIndex","item","bumpedItem","splice","unshift","constructor","maxConcurrency","forced","length","shift"],"mappings":"AAAA;;;;;AAKA;;IAEE,mFACA,+EACA,iEAmDA;AAtDF,OAAO,MAAMA;IAcXC,QAAWC,SAA2B,EAAc;QAClD,IAAIC;QACJ,IAAIC;QAEJ,MAAMC,cAAc,IAAIC,QAAQ,CAACC,SAASC;YACxCL,cAAcI;YACdH,aAAaI;QACf;QAEA,MAAMC,OAAO;YACX,IAAI;gBACF,gCAAA,IAAI,EAAC,eAAA;gBACL,MAAMC,SAAS,MAAMR;gBACrBC,YAAYO;YACd,EAAE,OAAOC,OAAO;gBACdP,WAAWO;YACb,SAAU;gBACR,gCAAA,IAAI,EAAC,eAAA;gBACL,gCAAA,IAAI,EAAC,cAAA;YACP;QACF;QAEA,MAAMC,gBAAgB;YAAEV,WAAWG;YAAaI;QAAK;QACrD,gDAAgD;QAChD,gCAAA,IAAI,EAAC,QAAA,QAAOI,IAAI,CAACD;QACjB,gCAAA,IAAI,EAAC,cAAA;QAEL,OAAOP;IACT;IAEAS,KAAKZ,SAAuB,EAAE;QAC5B,MAAMa,QAAQ,gCAAA,IAAI,EAAC,QAAA,QAAOC,SAAS,CAAC,CAACC,OAASA,KAAKf,SAAS,KAAKA;QAEjE,IAAIa,QAAQ,CAAC,GAAG;YACd,MAAMG,aAAa,gCAAA,IAAI,EAAC,QAAA,QAAOC,MAAM,CAACJ,OAAO,EAAE,CAAC,EAAE;YAClD,gCAAA,IAAI,EAAC,QAAA,QAAOK,OAAO,CAACF;YACpB,gCAAA,IAAI,EAAC,cAAA,cAAa;QACpB;IACF;IA5CAG,YAAYC,iBAAiB,CAAC,CAAE;QA8ChC,4BAAA;mBAAA;;QArDA,4BAAA;;mBAAA,KAAA;;QACA,4BAAA;;mBAAA,KAAA;;QACA,4BAAA;;mBAAA,KAAA;;QAME,gCAAA,IAAI,EAAC,iBAAA,mBAAkBA;QACvB,gCAAA,IAAI,EAAC,eAAA,iBAAgB;QACrB,gCAAA,IAAI,EAAC,QAAA,UAAS,EAAE;IAClB;AAkDF;AARE,SAAA,YAAaC,MAAc;IAAdA,IAAAA,mBAAAA,SAAS;IACpB,IACE,AAAC,CAAA,gCAAA,IAAI,EAAC,eAAA,iBAAgB,gCAAA,IAAI,EAAC,iBAAA,oBAAmBA,MAAK,KACnD,gCAAA,IAAI,EAAC,QAAA,QAAOC,MAAM,GAAG,GACrB;YACA;SAAA,+CAAA,gCAAA,IAAI,EAAC,QAAA,QAAOC,KAAK,uBAAjB,6CAAqBhB,IAAI;IAC3B;AACF"}
|
||||
Generated
Vendored
+76
@@ -0,0 +1,76 @@
|
||||
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
|
||||
import React from 'react';
|
||||
import { ShadowPortal } from '../internal/components/ShadowPortal';
|
||||
import { BuildError } from '../internal/container/BuildError';
|
||||
import { Errors } from '../internal/container/Errors';
|
||||
import { StaticIndicator } from '../internal/container/StaticIndicator';
|
||||
import { Base } from '../internal/styles/Base';
|
||||
import { ComponentStyles } from '../internal/styles/ComponentStyles';
|
||||
import { CssReset } from '../internal/styles/CssReset';
|
||||
import { RootLayoutMissingTagsError } from '../internal/container/root-layout-missing-tags-error';
|
||||
import { RuntimeErrorHandler } from '../internal/helpers/runtime-error-handler';
|
||||
class ReactDevOverlay extends React.PureComponent {
|
||||
static getDerivedStateFromError(error) {
|
||||
if (!error.stack) return {
|
||||
isReactError: false
|
||||
};
|
||||
RuntimeErrorHandler.hadRuntimeError = true;
|
||||
return {
|
||||
isReactError: true
|
||||
};
|
||||
}
|
||||
render() {
|
||||
var _state_rootLayoutMissingTags;
|
||||
const { state, children, dispatcher } = this.props;
|
||||
const { isReactError } = this.state;
|
||||
const hasBuildError = state.buildError != null;
|
||||
const hasRuntimeErrors = Boolean(state.errors.length);
|
||||
const hasStaticIndicator = state.staticIndicator;
|
||||
const debugInfo = state.debugInfo;
|
||||
return /*#__PURE__*/ _jsxs(_Fragment, {
|
||||
children: [
|
||||
isReactError ? /*#__PURE__*/ _jsxs("html", {
|
||||
children: [
|
||||
/*#__PURE__*/ _jsx("head", {}),
|
||||
/*#__PURE__*/ _jsx("body", {})
|
||||
]
|
||||
}) : children,
|
||||
/*#__PURE__*/ _jsxs(ShadowPortal, {
|
||||
children: [
|
||||
/*#__PURE__*/ _jsx(CssReset, {}),
|
||||
/*#__PURE__*/ _jsx(Base, {}),
|
||||
/*#__PURE__*/ _jsx(ComponentStyles, {}),
|
||||
((_state_rootLayoutMissingTags = state.rootLayoutMissingTags) == null ? void 0 : _state_rootLayoutMissingTags.length) ? /*#__PURE__*/ _jsx(RootLayoutMissingTagsError, {
|
||||
missingTags: state.rootLayoutMissingTags
|
||||
}) : hasBuildError ? /*#__PURE__*/ _jsx(BuildError, {
|
||||
message: state.buildError,
|
||||
versionInfo: state.versionInfo
|
||||
}) : /*#__PURE__*/ _jsxs(_Fragment, {
|
||||
children: [
|
||||
hasRuntimeErrors ? /*#__PURE__*/ _jsx(Errors, {
|
||||
isAppDir: true,
|
||||
initialDisplayState: isReactError ? 'fullscreen' : 'minimized',
|
||||
errors: state.errors,
|
||||
versionInfo: state.versionInfo,
|
||||
hasStaticIndicator: hasStaticIndicator,
|
||||
debugInfo: debugInfo
|
||||
}) : null,
|
||||
hasStaticIndicator && /*#__PURE__*/ _jsx(StaticIndicator, {
|
||||
dispatcher: dispatcher
|
||||
})
|
||||
]
|
||||
})
|
||||
]
|
||||
})
|
||||
]
|
||||
});
|
||||
}
|
||||
constructor(...args){
|
||||
super(...args), this.state = {
|
||||
isReactError: false
|
||||
};
|
||||
}
|
||||
}
|
||||
export { ReactDevOverlay as default };
|
||||
|
||||
//# sourceMappingURL=ReactDevOverlay.js.map
|
||||
Generated
Vendored
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../../../src/client/components/react-dev-overlay/app/ReactDevOverlay.tsx"],"sourcesContent":["import React from 'react'\nimport type { OverlayState } from '../shared'\nimport { ShadowPortal } from '../internal/components/ShadowPortal'\nimport { BuildError } from '../internal/container/BuildError'\nimport { Errors } from '../internal/container/Errors'\nimport { StaticIndicator } from '../internal/container/StaticIndicator'\nimport { Base } from '../internal/styles/Base'\nimport { ComponentStyles } from '../internal/styles/ComponentStyles'\nimport { CssReset } from '../internal/styles/CssReset'\nimport { RootLayoutMissingTagsError } from '../internal/container/root-layout-missing-tags-error'\nimport type { Dispatcher } from './hot-reloader-client'\nimport { RuntimeErrorHandler } from '../internal/helpers/runtime-error-handler'\n\ninterface ReactDevOverlayState {\n isReactError: boolean\n}\nexport default class ReactDevOverlay extends React.PureComponent<\n {\n state: OverlayState\n dispatcher?: Dispatcher\n children: React.ReactNode\n },\n ReactDevOverlayState\n> {\n state = { isReactError: false }\n\n static getDerivedStateFromError(error: Error): ReactDevOverlayState {\n if (!error.stack) return { isReactError: false }\n\n RuntimeErrorHandler.hadRuntimeError = true\n return {\n isReactError: true,\n }\n }\n\n render() {\n const { state, children, dispatcher } = this.props\n const { isReactError } = this.state\n\n const hasBuildError = state.buildError != null\n const hasRuntimeErrors = Boolean(state.errors.length)\n const hasStaticIndicator = state.staticIndicator\n const debugInfo = state.debugInfo\n\n return (\n <>\n {isReactError ? (\n <html>\n <head></head>\n <body></body>\n </html>\n ) : (\n children\n )}\n <ShadowPortal>\n <CssReset />\n <Base />\n <ComponentStyles />\n {state.rootLayoutMissingTags?.length ? (\n <RootLayoutMissingTagsError\n missingTags={state.rootLayoutMissingTags}\n />\n ) : hasBuildError ? (\n <BuildError\n message={state.buildError!}\n versionInfo={state.versionInfo}\n />\n ) : (\n <>\n {hasRuntimeErrors ? (\n <Errors\n isAppDir={true}\n initialDisplayState={\n isReactError ? 'fullscreen' : 'minimized'\n }\n errors={state.errors}\n versionInfo={state.versionInfo}\n hasStaticIndicator={hasStaticIndicator}\n debugInfo={debugInfo}\n />\n ) : null}\n\n {hasStaticIndicator && (\n <StaticIndicator dispatcher={dispatcher} />\n )}\n </>\n )}\n </ShadowPortal>\n </>\n )\n }\n}\n"],"names":["React","ShadowPortal","BuildError","Errors","StaticIndicator","Base","ComponentStyles","CssReset","RootLayoutMissingTagsError","RuntimeErrorHandler","ReactDevOverlay","PureComponent","getDerivedStateFromError","error","stack","isReactError","hadRuntimeError","render","state","children","dispatcher","props","hasBuildError","buildError","hasRuntimeErrors","Boolean","errors","length","hasStaticIndicator","staticIndicator","debugInfo","html","head","body","rootLayoutMissingTags","missingTags","message","versionInfo","isAppDir","initialDisplayState"],"mappings":";AAAA,OAAOA,WAAW,QAAO;AAEzB,SAASC,YAAY,QAAQ,sCAAqC;AAClE,SAASC,UAAU,QAAQ,mCAAkC;AAC7D,SAASC,MAAM,QAAQ,+BAA8B;AACrD,SAASC,eAAe,QAAQ,wCAAuC;AACvE,SAASC,IAAI,QAAQ,0BAAyB;AAC9C,SAASC,eAAe,QAAQ,qCAAoC;AACpE,SAASC,QAAQ,QAAQ,8BAA6B;AACtD,SAASC,0BAA0B,QAAQ,uDAAsD;AAEjG,SAASC,mBAAmB,QAAQ,4CAA2C;AAKhE,MAAMC,wBAAwBV,MAAMW,aAAa;IAU9D,OAAOC,yBAAyBC,KAAY,EAAwB;QAClE,IAAI,CAACA,MAAMC,KAAK,EAAE,OAAO;YAAEC,cAAc;QAAM;QAE/CN,oBAAoBO,eAAe,GAAG;QACtC,OAAO;YACLD,cAAc;QAChB;IACF;IAEAE,SAAS;YAuBAC;QAtBP,MAAM,EAAEA,KAAK,EAAEC,QAAQ,EAAEC,UAAU,EAAE,GAAG,IAAI,CAACC,KAAK;QAClD,MAAM,EAAEN,YAAY,EAAE,GAAG,IAAI,CAACG,KAAK;QAEnC,MAAMI,gBAAgBJ,MAAMK,UAAU,IAAI;QAC1C,MAAMC,mBAAmBC,QAAQP,MAAMQ,MAAM,CAACC,MAAM;QACpD,MAAMC,qBAAqBV,MAAMW,eAAe;QAChD,MAAMC,YAAYZ,MAAMY,SAAS;QAEjC,qBACE;;gBACGf,6BACC,MAACgB;;sCACC,KAACC;sCACD,KAACC;;qBAGHd;8BAEF,MAAClB;;sCACC,KAACM;sCACD,KAACF;sCACD,KAACC;wBACAY,EAAAA,+BAAAA,MAAMgB,qBAAqB,qBAA3BhB,6BAA6BS,MAAM,kBAClC,KAACnB;4BACC2B,aAAajB,MAAMgB,qBAAqB;6BAExCZ,8BACF,KAACpB;4BACCkC,SAASlB,MAAMK,UAAU;4BACzBc,aAAanB,MAAMmB,WAAW;2CAGhC;;gCACGb,iCACC,KAACrB;oCACCmC,UAAU;oCACVC,qBACExB,eAAe,eAAe;oCAEhCW,QAAQR,MAAMQ,MAAM;oCACpBW,aAAanB,MAAMmB,WAAW;oCAC9BT,oBAAoBA;oCACpBE,WAAWA;qCAEX;gCAEHF,oCACC,KAACxB;oCAAgBgB,YAAYA;;;;;;;;IAO3C;;QA1Ea,qBAQbF,QAAQ;YAAEH,cAAc;QAAM;;AAmEhC;AA3EA,SAAqBL,6BA2EpB"}
|
||||
Generated
Vendored
+533
@@ -0,0 +1,533 @@
|
||||
import { jsx as _jsx } from "react/jsx-runtime";
|
||||
import { useCallback, useEffect, startTransition, useMemo, useRef } from 'react';
|
||||
import stripAnsi from 'next/dist/compiled/strip-ansi';
|
||||
import formatWebpackMessages from '../internal/helpers/format-webpack-messages';
|
||||
import { useRouter } from '../../navigation';
|
||||
import { ACTION_BEFORE_REFRESH, ACTION_BUILD_ERROR, ACTION_BUILD_OK, ACTION_DEBUG_INFO, ACTION_REFRESH, ACTION_STATIC_INDICATOR, ACTION_UNHANDLED_ERROR, ACTION_UNHANDLED_REJECTION, ACTION_VERSION_INFO, useErrorOverlayReducer } from '../shared';
|
||||
import { parseStack } from '../internal/helpers/parse-stack';
|
||||
import ReactDevOverlay from './ReactDevOverlay';
|
||||
import { useErrorHandler } from '../internal/helpers/use-error-handler';
|
||||
import { RuntimeErrorHandler } from '../internal/helpers/runtime-error-handler';
|
||||
import { useSendMessage, useTurbopack, useWebsocket, useWebsocketPing } from '../internal/helpers/use-websocket';
|
||||
import { parseComponentStack } from '../internal/helpers/parse-component-stack';
|
||||
import { HMR_ACTIONS_SENT_TO_BROWSER } from '../../../../server/dev/hot-reloader-types';
|
||||
import { extractModulesFromTurbopackMessage } from '../../../../server/dev/extract-modules-from-turbopack-message';
|
||||
import { REACT_REFRESH_FULL_RELOAD_FROM_ERROR } from '../shared';
|
||||
import { useUntrackedPathname } from '../../navigation-untracked';
|
||||
import { getReactStitchedError } from '../internal/helpers/stitched-error';
|
||||
let mostRecentCompilationHash = null;
|
||||
let __nextDevClientId = Math.round(Math.random() * 100 + Date.now());
|
||||
let reloading = false;
|
||||
let startLatency = null;
|
||||
let pendingHotUpdateWebpack = Promise.resolve();
|
||||
let resolvePendingHotUpdateWebpack = ()=>{};
|
||||
function setPendingHotUpdateWebpack() {
|
||||
pendingHotUpdateWebpack = new Promise((resolve)=>{
|
||||
resolvePendingHotUpdateWebpack = ()=>{
|
||||
resolve();
|
||||
};
|
||||
});
|
||||
}
|
||||
export function waitForWebpackRuntimeHotUpdate() {
|
||||
return pendingHotUpdateWebpack;
|
||||
}
|
||||
function handleBeforeHotUpdateWebpack(dispatcher, hasUpdates) {
|
||||
if (hasUpdates) {
|
||||
dispatcher.onBeforeRefresh();
|
||||
}
|
||||
}
|
||||
function handleSuccessfulHotUpdateWebpack(dispatcher, sendMessage, updatedModules) {
|
||||
resolvePendingHotUpdateWebpack();
|
||||
dispatcher.onBuildOk();
|
||||
reportHmrLatency(sendMessage, updatedModules);
|
||||
dispatcher.onRefresh();
|
||||
}
|
||||
function reportHmrLatency(sendMessage, updatedModules) {
|
||||
if (!startLatency) return;
|
||||
let endLatency = Date.now();
|
||||
const latency = endLatency - startLatency;
|
||||
console.log("[Fast Refresh] done in " + latency + "ms");
|
||||
sendMessage(JSON.stringify({
|
||||
event: 'client-hmr-latency',
|
||||
id: window.__nextDevClientId,
|
||||
startTime: startLatency,
|
||||
endTime: endLatency,
|
||||
page: window.location.pathname,
|
||||
updatedModules,
|
||||
// Whether the page (tab) was hidden at the time the event occurred.
|
||||
// This can impact the accuracy of the event's timing.
|
||||
isPageHidden: document.visibilityState === 'hidden'
|
||||
}));
|
||||
}
|
||||
// There is a newer version of the code available.
|
||||
function handleAvailableHash(hash) {
|
||||
// Update last known compilation hash.
|
||||
mostRecentCompilationHash = hash;
|
||||
}
|
||||
/**
|
||||
* Is there a newer version of this code available?
|
||||
* For webpack: Check if the hash changed compared to __webpack_hash__
|
||||
* For Turbopack: Always true because it doesn't have __webpack_hash__
|
||||
*/ function isUpdateAvailable() {
|
||||
if (process.env.TURBOPACK) {
|
||||
return true;
|
||||
}
|
||||
/* globals __webpack_hash__ */ // __webpack_hash__ is the hash of the current compilation.
|
||||
// It's a global variable injected by Webpack.
|
||||
return mostRecentCompilationHash !== __webpack_hash__;
|
||||
}
|
||||
// Webpack disallows updates in other states.
|
||||
function canApplyUpdates() {
|
||||
// @ts-expect-error module.hot exists
|
||||
return module.hot.status() === 'idle';
|
||||
}
|
||||
function afterApplyUpdates(fn) {
|
||||
if (canApplyUpdates()) {
|
||||
fn();
|
||||
} else {
|
||||
function handler(status) {
|
||||
if (status === 'idle') {
|
||||
// @ts-expect-error module.hot exists
|
||||
module.hot.removeStatusHandler(handler);
|
||||
fn();
|
||||
}
|
||||
}
|
||||
// @ts-expect-error module.hot exists
|
||||
module.hot.addStatusHandler(handler);
|
||||
}
|
||||
}
|
||||
function performFullReload(err, sendMessage) {
|
||||
const stackTrace = err && (err.stack && err.stack.split('\n').slice(0, 5).join('\n') || err.message || err + '');
|
||||
sendMessage(JSON.stringify({
|
||||
event: 'client-full-reload',
|
||||
stackTrace,
|
||||
hadRuntimeError: !!RuntimeErrorHandler.hadRuntimeError,
|
||||
dependencyChain: err ? err.dependencyChain : undefined
|
||||
}));
|
||||
if (reloading) return;
|
||||
reloading = true;
|
||||
window.location.reload();
|
||||
}
|
||||
// Attempt to update code on the fly, fall back to a hard reload.
|
||||
function tryApplyUpdates(onBeforeUpdate, onHotUpdateSuccess, sendMessage, dispatcher) {
|
||||
if (!isUpdateAvailable() || !canApplyUpdates()) {
|
||||
resolvePendingHotUpdateWebpack();
|
||||
dispatcher.onBuildOk();
|
||||
reportHmrLatency(sendMessage, []);
|
||||
return;
|
||||
}
|
||||
function handleApplyUpdates(err, updatedModules) {
|
||||
if (err || RuntimeErrorHandler.hadRuntimeError || !updatedModules) {
|
||||
if (err) {
|
||||
console.warn('[Fast Refresh] performing full reload\n\n' + "Fast Refresh will perform a full reload when you edit a file that's imported by modules outside of the React rendering tree.\n" + 'You might have a file which exports a React component but also exports a value that is imported by a non-React component file.\n' + 'Consider migrating the non-React component export to a separate file and importing it into both files.\n\n' + 'It is also possible the parent component of the component you edited is a class component, which disables Fast Refresh.\n' + 'Fast Refresh requires at least one parent function component in your React tree.');
|
||||
} else if (RuntimeErrorHandler.hadRuntimeError) {
|
||||
console.warn(REACT_REFRESH_FULL_RELOAD_FROM_ERROR);
|
||||
}
|
||||
performFullReload(err, sendMessage);
|
||||
return;
|
||||
}
|
||||
const hasUpdates = Boolean(updatedModules.length);
|
||||
if (typeof onHotUpdateSuccess === 'function') {
|
||||
// Maybe we want to do something.
|
||||
onHotUpdateSuccess(updatedModules);
|
||||
}
|
||||
if (isUpdateAvailable()) {
|
||||
// While we were updating, there was a new update! Do it again.
|
||||
tryApplyUpdates(hasUpdates ? ()=>{} : onBeforeUpdate, hasUpdates ? ()=>dispatcher.onBuildOk() : onHotUpdateSuccess, sendMessage, dispatcher);
|
||||
} else {
|
||||
dispatcher.onBuildOk();
|
||||
if (process.env.__NEXT_TEST_MODE) {
|
||||
afterApplyUpdates(()=>{
|
||||
if (self.__NEXT_HMR_CB) {
|
||||
self.__NEXT_HMR_CB();
|
||||
self.__NEXT_HMR_CB = null;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
// https://webpack.js.org/api/hot-module-replacement/#check
|
||||
// @ts-expect-error module.hot exists
|
||||
module.hot.check(/* autoApply */ false).then((updatedModules)=>{
|
||||
if (!updatedModules) {
|
||||
return null;
|
||||
}
|
||||
if (typeof onBeforeUpdate === 'function') {
|
||||
const hasUpdates = Boolean(updatedModules.length);
|
||||
onBeforeUpdate(hasUpdates);
|
||||
}
|
||||
// https://webpack.js.org/api/hot-module-replacement/#apply
|
||||
// @ts-expect-error module.hot exists
|
||||
return module.hot.apply();
|
||||
}).then((updatedModules)=>{
|
||||
handleApplyUpdates(null, updatedModules);
|
||||
}, (err)=>{
|
||||
handleApplyUpdates(err, null);
|
||||
});
|
||||
}
|
||||
/** Handles messages from the sevrer for the App Router. */ function processMessage(obj, sendMessage, processTurbopackMessage, router, dispatcher, appIsrManifestRef, pathnameRef) {
|
||||
if (!('action' in obj)) {
|
||||
return;
|
||||
}
|
||||
function handleErrors(errors) {
|
||||
// "Massage" webpack messages.
|
||||
const formatted = formatWebpackMessages({
|
||||
errors: errors,
|
||||
warnings: []
|
||||
});
|
||||
// Only show the first error.
|
||||
dispatcher.onBuildError(formatted.errors[0]);
|
||||
// Also log them to the console.
|
||||
for(let i = 0; i < formatted.errors.length; i++){
|
||||
console.error(stripAnsi(formatted.errors[i]));
|
||||
}
|
||||
// Do not attempt to reload now.
|
||||
// We will reload on next success instead.
|
||||
if (process.env.__NEXT_TEST_MODE) {
|
||||
if (self.__NEXT_HMR_CB) {
|
||||
self.__NEXT_HMR_CB(formatted.errors[0]);
|
||||
self.__NEXT_HMR_CB = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
function handleHotUpdate() {
|
||||
if (process.env.TURBOPACK) {
|
||||
dispatcher.onBuildOk();
|
||||
} else {
|
||||
tryApplyUpdates(function onBeforeHotUpdate(hasUpdates) {
|
||||
handleBeforeHotUpdateWebpack(dispatcher, hasUpdates);
|
||||
}, function onSuccessfulHotUpdate(webpackUpdatedModules) {
|
||||
// Only dismiss it when we're sure it's a hot update.
|
||||
// Otherwise it would flicker right before the reload.
|
||||
handleSuccessfulHotUpdateWebpack(dispatcher, sendMessage, webpackUpdatedModules);
|
||||
}, sendMessage, dispatcher);
|
||||
}
|
||||
}
|
||||
switch(obj.action){
|
||||
case HMR_ACTIONS_SENT_TO_BROWSER.APP_ISR_MANIFEST:
|
||||
{
|
||||
if (process.env.__NEXT_APP_ISR_INDICATOR) {
|
||||
if (appIsrManifestRef) {
|
||||
appIsrManifestRef.current = obj.data;
|
||||
// handle initial status on receiving manifest
|
||||
// navigation is handled in useEffect for pathname changes
|
||||
// as we'll receive the updated manifest before usePathname
|
||||
// triggers for new value
|
||||
if (pathnameRef.current in obj.data) {
|
||||
var _localStorage;
|
||||
// the indicator can be hidden for an hour.
|
||||
// check if it's still hidden
|
||||
const indicatorHiddenAt = Number((_localStorage = localStorage) == null ? void 0 : _localStorage.getItem('__NEXT_DISMISS_PRERENDER_INDICATOR'));
|
||||
const isHidden = indicatorHiddenAt && !isNaN(indicatorHiddenAt) && Date.now() < indicatorHiddenAt;
|
||||
if (!isHidden) {
|
||||
dispatcher.onStaticIndicator(true);
|
||||
}
|
||||
} else {
|
||||
dispatcher.onStaticIndicator(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
case HMR_ACTIONS_SENT_TO_BROWSER.BUILDING:
|
||||
{
|
||||
startLatency = Date.now();
|
||||
if (!process.env.TURBOPACK) {
|
||||
setPendingHotUpdateWebpack();
|
||||
}
|
||||
console.log('[Fast Refresh] rebuilding');
|
||||
break;
|
||||
}
|
||||
case HMR_ACTIONS_SENT_TO_BROWSER.BUILT:
|
||||
case HMR_ACTIONS_SENT_TO_BROWSER.SYNC:
|
||||
{
|
||||
if (obj.hash) {
|
||||
handleAvailableHash(obj.hash);
|
||||
}
|
||||
const { errors, warnings } = obj;
|
||||
// Is undefined when it's a 'built' event
|
||||
if ('versionInfo' in obj) dispatcher.onVersionInfo(obj.versionInfo);
|
||||
if ('debug' in obj && obj.debug) dispatcher.onDebugInfo(obj.debug);
|
||||
const hasErrors = Boolean(errors && errors.length);
|
||||
// Compilation with errors (e.g. syntax error or missing modules).
|
||||
if (hasErrors) {
|
||||
sendMessage(JSON.stringify({
|
||||
event: 'client-error',
|
||||
errorCount: errors.length,
|
||||
clientId: __nextDevClientId
|
||||
}));
|
||||
handleErrors(errors);
|
||||
return;
|
||||
}
|
||||
const hasWarnings = Boolean(warnings && warnings.length);
|
||||
if (hasWarnings) {
|
||||
sendMessage(JSON.stringify({
|
||||
event: 'client-warning',
|
||||
warningCount: warnings.length,
|
||||
clientId: __nextDevClientId
|
||||
}));
|
||||
// Print warnings to the console.
|
||||
const formattedMessages = formatWebpackMessages({
|
||||
warnings: warnings,
|
||||
errors: []
|
||||
});
|
||||
for(let i = 0; i < formattedMessages.warnings.length; i++){
|
||||
if (i === 5) {
|
||||
console.warn('There were more warnings in other files.\n' + 'You can find a complete log in the terminal.');
|
||||
break;
|
||||
}
|
||||
console.warn(stripAnsi(formattedMessages.warnings[i]));
|
||||
}
|
||||
// No early return here as we need to apply modules in the same way between warnings only and compiles without warnings
|
||||
}
|
||||
sendMessage(JSON.stringify({
|
||||
event: 'client-success',
|
||||
clientId: __nextDevClientId
|
||||
}));
|
||||
if (obj.action === HMR_ACTIONS_SENT_TO_BROWSER.BUILT) {
|
||||
// Handle hot updates
|
||||
handleHotUpdate();
|
||||
}
|
||||
return;
|
||||
}
|
||||
case HMR_ACTIONS_SENT_TO_BROWSER.TURBOPACK_CONNECTED:
|
||||
{
|
||||
processTurbopackMessage({
|
||||
type: HMR_ACTIONS_SENT_TO_BROWSER.TURBOPACK_CONNECTED,
|
||||
data: {
|
||||
sessionId: obj.data.sessionId
|
||||
}
|
||||
});
|
||||
break;
|
||||
}
|
||||
case HMR_ACTIONS_SENT_TO_BROWSER.TURBOPACK_MESSAGE:
|
||||
{
|
||||
const updatedModules = extractModulesFromTurbopackMessage(obj.data);
|
||||
dispatcher.onBeforeRefresh();
|
||||
processTurbopackMessage({
|
||||
type: HMR_ACTIONS_SENT_TO_BROWSER.TURBOPACK_MESSAGE,
|
||||
data: obj.data
|
||||
});
|
||||
dispatcher.onRefresh();
|
||||
if (RuntimeErrorHandler.hadRuntimeError) {
|
||||
console.warn(REACT_REFRESH_FULL_RELOAD_FROM_ERROR);
|
||||
performFullReload(null, sendMessage);
|
||||
}
|
||||
reportHmrLatency(sendMessage, updatedModules);
|
||||
break;
|
||||
}
|
||||
// TODO-APP: make server component change more granular
|
||||
case HMR_ACTIONS_SENT_TO_BROWSER.SERVER_COMPONENT_CHANGES:
|
||||
{
|
||||
sendMessage(JSON.stringify({
|
||||
event: 'server-component-reload-page',
|
||||
clientId: __nextDevClientId
|
||||
}));
|
||||
if (RuntimeErrorHandler.hadRuntimeError) {
|
||||
if (reloading) return;
|
||||
reloading = true;
|
||||
return window.location.reload();
|
||||
}
|
||||
startTransition(()=>{
|
||||
router.hmrRefresh();
|
||||
dispatcher.onRefresh();
|
||||
});
|
||||
if (process.env.__NEXT_TEST_MODE) {
|
||||
if (self.__NEXT_HMR_CB) {
|
||||
self.__NEXT_HMR_CB();
|
||||
self.__NEXT_HMR_CB = null;
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
case HMR_ACTIONS_SENT_TO_BROWSER.RELOAD_PAGE:
|
||||
{
|
||||
sendMessage(JSON.stringify({
|
||||
event: 'client-reload-page',
|
||||
clientId: __nextDevClientId
|
||||
}));
|
||||
if (reloading) return;
|
||||
reloading = true;
|
||||
return window.location.reload();
|
||||
}
|
||||
case HMR_ACTIONS_SENT_TO_BROWSER.ADDED_PAGE:
|
||||
case HMR_ACTIONS_SENT_TO_BROWSER.REMOVED_PAGE:
|
||||
{
|
||||
// TODO-APP: potentially only refresh if the currently viewed page was added/removed.
|
||||
return router.hmrRefresh();
|
||||
}
|
||||
case HMR_ACTIONS_SENT_TO_BROWSER.SERVER_ERROR:
|
||||
{
|
||||
const { errorJSON } = obj;
|
||||
if (errorJSON) {
|
||||
const { message, stack } = JSON.parse(errorJSON);
|
||||
const error = new Error(message);
|
||||
error.stack = stack;
|
||||
handleErrors([
|
||||
error
|
||||
]);
|
||||
}
|
||||
return;
|
||||
}
|
||||
case HMR_ACTIONS_SENT_TO_BROWSER.DEV_PAGES_MANIFEST_UPDATE:
|
||||
{
|
||||
return;
|
||||
}
|
||||
default:
|
||||
{}
|
||||
}
|
||||
}
|
||||
export default function HotReload(param) {
|
||||
let { assetPrefix, children } = param;
|
||||
const [state, dispatch] = useErrorOverlayReducer();
|
||||
const dispatcher = useMemo(()=>{
|
||||
return {
|
||||
onBuildOk () {
|
||||
dispatch({
|
||||
type: ACTION_BUILD_OK
|
||||
});
|
||||
},
|
||||
onBuildError (message) {
|
||||
dispatch({
|
||||
type: ACTION_BUILD_ERROR,
|
||||
message
|
||||
});
|
||||
},
|
||||
onBeforeRefresh () {
|
||||
dispatch({
|
||||
type: ACTION_BEFORE_REFRESH
|
||||
});
|
||||
},
|
||||
onRefresh () {
|
||||
dispatch({
|
||||
type: ACTION_REFRESH
|
||||
});
|
||||
},
|
||||
onVersionInfo (versionInfo) {
|
||||
dispatch({
|
||||
type: ACTION_VERSION_INFO,
|
||||
versionInfo
|
||||
});
|
||||
},
|
||||
onStaticIndicator (status) {
|
||||
dispatch({
|
||||
type: ACTION_STATIC_INDICATOR,
|
||||
staticIndicator: status
|
||||
});
|
||||
},
|
||||
onDebugInfo (debugInfo) {
|
||||
dispatch({
|
||||
type: ACTION_DEBUG_INFO,
|
||||
debugInfo
|
||||
});
|
||||
}
|
||||
};
|
||||
}, [
|
||||
dispatch
|
||||
]);
|
||||
const handleOnUnhandledError = useCallback((error)=>{
|
||||
const errorDetails = error.details;
|
||||
// Component stack is added to the error in use-error-handler in case there was a hydration error
|
||||
const componentStackTrace = error._componentStack || (errorDetails == null ? void 0 : errorDetails.componentStack);
|
||||
const warning = errorDetails == null ? void 0 : errorDetails.warning;
|
||||
const stitchedError = getReactStitchedError(error);
|
||||
dispatch({
|
||||
type: ACTION_UNHANDLED_ERROR,
|
||||
reason: stitchedError,
|
||||
frames: parseStack(stitchedError.stack || ''),
|
||||
componentStackFrames: typeof componentStackTrace === 'string' ? parseComponentStack(componentStackTrace) : undefined,
|
||||
warning
|
||||
});
|
||||
}, [
|
||||
dispatch
|
||||
]);
|
||||
const handleOnUnhandledRejection = useCallback((reason)=>{
|
||||
const stitchedError = getReactStitchedError(reason);
|
||||
dispatch({
|
||||
type: ACTION_UNHANDLED_REJECTION,
|
||||
reason: stitchedError,
|
||||
frames: parseStack(stitchedError.stack || '')
|
||||
});
|
||||
}, [
|
||||
dispatch
|
||||
]);
|
||||
useErrorHandler(handleOnUnhandledError, handleOnUnhandledRejection);
|
||||
const webSocketRef = useWebsocket(assetPrefix);
|
||||
useWebsocketPing(webSocketRef);
|
||||
const sendMessage = useSendMessage(webSocketRef);
|
||||
const processTurbopackMessage = useTurbopack(sendMessage, (err)=>performFullReload(err, sendMessage));
|
||||
const router = useRouter();
|
||||
// We don't want access of the pathname for the dev tools to trigger a dynamic
|
||||
// access (as the dev overlay will never be present in production).
|
||||
const pathname = useUntrackedPathname();
|
||||
const appIsrManifestRef = useRef({});
|
||||
const pathnameRef = useRef(pathname);
|
||||
if (process.env.__NEXT_APP_ISR_INDICATOR) {
|
||||
// this conditional is only for dead-code elimination which
|
||||
// isn't a runtime conditional only build-time so ignore hooks rule
|
||||
// eslint-disable-next-line react-hooks/rules-of-hooks
|
||||
useEffect(()=>{
|
||||
pathnameRef.current = pathname;
|
||||
const appIsrManifest = appIsrManifestRef.current;
|
||||
if (appIsrManifest) {
|
||||
if (pathname && pathname in appIsrManifest) {
|
||||
try {
|
||||
var _localStorage;
|
||||
const indicatorHiddenAt = Number((_localStorage = localStorage) == null ? void 0 : _localStorage.getItem('__NEXT_DISMISS_PRERENDER_INDICATOR'));
|
||||
const isHidden = indicatorHiddenAt && !isNaN(indicatorHiddenAt) && Date.now() < indicatorHiddenAt;
|
||||
if (!isHidden) {
|
||||
dispatcher.onStaticIndicator(true);
|
||||
}
|
||||
} catch (reason) {
|
||||
let message = '';
|
||||
if (reason instanceof DOMException) {
|
||||
var _reason_stack;
|
||||
// Most likely a SecurityError, because of an unavailable localStorage
|
||||
message = (_reason_stack = reason.stack) != null ? _reason_stack : reason.message;
|
||||
} else if (reason instanceof Error) {
|
||||
var _reason_stack1;
|
||||
message = 'Error: ' + reason.message + '\n' + ((_reason_stack1 = reason.stack) != null ? _reason_stack1 : '');
|
||||
} else {
|
||||
message = 'Unexpected Exception: ' + reason;
|
||||
}
|
||||
console.warn('[HMR] ' + message);
|
||||
}
|
||||
} else {
|
||||
dispatcher.onStaticIndicator(false);
|
||||
}
|
||||
}
|
||||
}, [
|
||||
pathname,
|
||||
dispatcher
|
||||
]);
|
||||
}
|
||||
useEffect(()=>{
|
||||
const websocket = webSocketRef.current;
|
||||
if (!websocket) return;
|
||||
const handler = (event)=>{
|
||||
try {
|
||||
const obj = JSON.parse(event.data);
|
||||
processMessage(obj, sendMessage, processTurbopackMessage, router, dispatcher, appIsrManifestRef, pathnameRef);
|
||||
} catch (err) {
|
||||
var _err_stack;
|
||||
console.warn('[HMR] Invalid message: ' + JSON.stringify(event.data) + '\n' + ((_err_stack = err == null ? void 0 : err.stack) != null ? _err_stack : ''));
|
||||
}
|
||||
};
|
||||
websocket.addEventListener('message', handler);
|
||||
return ()=>websocket.removeEventListener('message', handler);
|
||||
}, [
|
||||
sendMessage,
|
||||
router,
|
||||
webSocketRef,
|
||||
dispatcher,
|
||||
processTurbopackMessage,
|
||||
appIsrManifestRef
|
||||
]);
|
||||
return /*#__PURE__*/ _jsx(ReactDevOverlay, {
|
||||
state: state,
|
||||
dispatcher: dispatcher,
|
||||
children: children
|
||||
});
|
||||
}
|
||||
|
||||
//# sourceMappingURL=hot-reloader-client.js.map
|
||||
Generated
Vendored
+1
File diff suppressed because one or more lines are too long
+48
@@ -0,0 +1,48 @@
|
||||
import { jsx as _jsx } from "react/jsx-runtime";
|
||||
import React from 'react';
|
||||
import ReactDevOverlay from './app/ReactDevOverlay';
|
||||
import { getSocketUrl } from './internal/helpers/get-socket-url';
|
||||
import { INITIAL_OVERLAY_STATE } from './shared';
|
||||
import { HMR_ACTIONS_SENT_TO_BROWSER } from '../../../server/dev/hot-reloader-types';
|
||||
// if an error is thrown while rendering an RSC stream, this will catch it in dev
|
||||
// and show the error overlay
|
||||
export function createDevOverlayElement(reactEl) {
|
||||
const rootLayoutMissingTags = window.__next_root_layout_missing_tags;
|
||||
const hasMissingTags = !!(rootLayoutMissingTags == null ? void 0 : rootLayoutMissingTags.length);
|
||||
const socketUrl = getSocketUrl(process.env.__NEXT_ASSET_PREFIX || '');
|
||||
const socket = new window.WebSocket("" + socketUrl + "/_next/webpack-hmr");
|
||||
// add minimal "hot reload" support for RSC errors
|
||||
const handler = (event)=>{
|
||||
let obj;
|
||||
try {
|
||||
obj = JSON.parse(event.data);
|
||||
} catch (e) {}
|
||||
if (!obj || !('action' in obj)) {
|
||||
return;
|
||||
}
|
||||
if (obj.action === HMR_ACTIONS_SENT_TO_BROWSER.SERVER_COMPONENT_CHANGES) {
|
||||
window.location.reload();
|
||||
}
|
||||
};
|
||||
socket.addEventListener('message', handler);
|
||||
const FallbackLayout = hasMissingTags ? (param)=>{
|
||||
let { children } = param;
|
||||
return /*#__PURE__*/ _jsx("html", {
|
||||
id: "__next_error__",
|
||||
children: /*#__PURE__*/ _jsx("body", {
|
||||
children: children
|
||||
})
|
||||
});
|
||||
} : React.Fragment;
|
||||
return /*#__PURE__*/ _jsx(FallbackLayout, {
|
||||
children: /*#__PURE__*/ _jsx(ReactDevOverlay, {
|
||||
state: {
|
||||
...INITIAL_OVERLAY_STATE,
|
||||
rootLayoutMissingTags
|
||||
},
|
||||
children: reactEl
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
//# sourceMappingURL=client-entry.js.map
|
||||
Generated
Vendored
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../../src/client/components/react-dev-overlay/client-entry.tsx"],"sourcesContent":["import React from 'react'\nimport ReactDevOverlay from './app/ReactDevOverlay'\nimport { getSocketUrl } from './internal/helpers/get-socket-url'\nimport { INITIAL_OVERLAY_STATE } from './shared'\nimport { HMR_ACTIONS_SENT_TO_BROWSER } from '../../../server/dev/hot-reloader-types'\n\n// if an error is thrown while rendering an RSC stream, this will catch it in dev\n// and show the error overlay\nexport function createDevOverlayElement(reactEl: React.ReactElement) {\n const rootLayoutMissingTags = window.__next_root_layout_missing_tags\n const hasMissingTags = !!rootLayoutMissingTags?.length\n const socketUrl = getSocketUrl(process.env.__NEXT_ASSET_PREFIX || '')\n const socket = new window.WebSocket(`${socketUrl}/_next/webpack-hmr`)\n\n // add minimal \"hot reload\" support for RSC errors\n const handler = (event: MessageEvent) => {\n let obj\n try {\n obj = JSON.parse(event.data)\n } catch {}\n\n if (!obj || !('action' in obj)) {\n return\n }\n\n if (obj.action === HMR_ACTIONS_SENT_TO_BROWSER.SERVER_COMPONENT_CHANGES) {\n window.location.reload()\n }\n }\n\n socket.addEventListener('message', handler)\n\n const FallbackLayout = hasMissingTags\n ? ({ children }: { children: React.ReactNode }) => (\n <html id=\"__next_error__\">\n <body>{children}</body>\n </html>\n )\n : React.Fragment\n\n return (\n <FallbackLayout>\n <ReactDevOverlay\n state={{ ...INITIAL_OVERLAY_STATE, rootLayoutMissingTags }}\n >\n {reactEl}\n </ReactDevOverlay>\n </FallbackLayout>\n )\n}\n"],"names":["React","ReactDevOverlay","getSocketUrl","INITIAL_OVERLAY_STATE","HMR_ACTIONS_SENT_TO_BROWSER","createDevOverlayElement","reactEl","rootLayoutMissingTags","window","__next_root_layout_missing_tags","hasMissingTags","length","socketUrl","process","env","__NEXT_ASSET_PREFIX","socket","WebSocket","handler","event","obj","JSON","parse","data","action","SERVER_COMPONENT_CHANGES","location","reload","addEventListener","FallbackLayout","children","html","id","body","Fragment","state"],"mappings":";AAAA,OAAOA,WAAW,QAAO;AACzB,OAAOC,qBAAqB,wBAAuB;AACnD,SAASC,YAAY,QAAQ,oCAAmC;AAChE,SAASC,qBAAqB,QAAQ,WAAU;AAChD,SAASC,2BAA2B,QAAQ,yCAAwC;AAEpF,iFAAiF;AACjF,6BAA6B;AAC7B,OAAO,SAASC,wBAAwBC,OAA2B;IACjE,MAAMC,wBAAwBC,OAAOC,+BAA+B;IACpE,MAAMC,iBAAiB,CAAC,EAACH,yCAAAA,sBAAuBI,MAAM;IACtD,MAAMC,YAAYV,aAAaW,QAAQC,GAAG,CAACC,mBAAmB,IAAI;IAClE,MAAMC,SAAS,IAAIR,OAAOS,SAAS,CAAC,AAAC,KAAEL,YAAU;IAEjD,kDAAkD;IAClD,MAAMM,UAAU,CAACC;QACf,IAAIC;QACJ,IAAI;YACFA,MAAMC,KAAKC,KAAK,CAACH,MAAMI,IAAI;QAC7B,EAAE,UAAM,CAAC;QAET,IAAI,CAACH,OAAO,CAAE,CAAA,YAAYA,GAAE,GAAI;YAC9B;QACF;QAEA,IAAIA,IAAII,MAAM,KAAKpB,4BAA4BqB,wBAAwB,EAAE;YACvEjB,OAAOkB,QAAQ,CAACC,MAAM;QACxB;IACF;IAEAX,OAAOY,gBAAgB,CAAC,WAAWV;IAEnC,MAAMW,iBAAiBnB,iBACnB;YAAC,EAAEoB,QAAQ,EAAiC;6BAC1C,KAACC;YAAKC,IAAG;sBACP,cAAA,KAACC;0BAAMH;;;QAGX9B,MAAMkC,QAAQ;IAElB,qBACE,KAACL;kBACC,cAAA,KAAC5B;YACCkC,OAAO;gBAAE,GAAGhC,qBAAqB;gBAAEI;YAAsB;sBAExDD;;;AAIT"}
|
||||
Generated
Vendored
+102
@@ -0,0 +1,102 @@
|
||||
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
||||
import Anser from 'next/dist/compiled/anser';
|
||||
import * as React from 'react';
|
||||
import stripAnsi from 'next/dist/compiled/strip-ansi';
|
||||
import { getFrameSource } from '../../helpers/stack-frame';
|
||||
import { useOpenInEditor } from '../../helpers/use-open-in-editor';
|
||||
import { HotlinkedText } from '../hot-linked-text';
|
||||
export const CodeFrame = function CodeFrame(param) {
|
||||
let { stackFrame, codeFrame } = param;
|
||||
// Strip leading spaces out of the code frame:
|
||||
const formattedFrame = React.useMemo(()=>{
|
||||
const lines = codeFrame.split(/\r?\n/g);
|
||||
// Find the minimum length of leading spaces after `|` in the code frame
|
||||
const miniLeadingSpacesLength = lines.map((line)=>/^>? +\d+ +\| [ ]+/.exec(stripAnsi(line)) === null ? null : /^>? +\d+ +\| ( *)/.exec(stripAnsi(line))).filter(Boolean).map((v)=>v.pop()).reduce((c, n)=>isNaN(c) ? n.length : Math.min(c, n.length), NaN);
|
||||
// When the minimum length of leading spaces is greater than 1, remove them
|
||||
// from the code frame to help the indentation looks better when there's a lot leading spaces.
|
||||
if (miniLeadingSpacesLength > 1) {
|
||||
return lines.map((line, a)=>~(a = line.indexOf('|')) ? line.substring(0, a) + line.substring(a).replace("^\\ {" + miniLeadingSpacesLength + "}", '') : line).join('\n');
|
||||
}
|
||||
return lines.join('\n');
|
||||
}, [
|
||||
codeFrame
|
||||
]);
|
||||
const decoded = React.useMemo(()=>{
|
||||
return Anser.ansiToJson(formattedFrame, {
|
||||
json: true,
|
||||
use_classes: true,
|
||||
remove_empty: true
|
||||
});
|
||||
}, [
|
||||
formattedFrame
|
||||
]);
|
||||
const open = useOpenInEditor({
|
||||
file: stackFrame.file,
|
||||
lineNumber: stackFrame.lineNumber,
|
||||
column: stackFrame.column
|
||||
});
|
||||
// TODO: make the caret absolute
|
||||
return /*#__PURE__*/ _jsxs("div", {
|
||||
"data-nextjs-codeframe": true,
|
||||
children: [
|
||||
/*#__PURE__*/ _jsx("div", {
|
||||
children: /*#__PURE__*/ _jsxs("p", {
|
||||
role: "link",
|
||||
onClick: open,
|
||||
tabIndex: 1,
|
||||
title: "Click to open in your editor",
|
||||
children: [
|
||||
/*#__PURE__*/ _jsxs("span", {
|
||||
children: [
|
||||
getFrameSource(stackFrame),
|
||||
" @",
|
||||
' ',
|
||||
/*#__PURE__*/ _jsx(HotlinkedText, {
|
||||
text: stackFrame.methodName
|
||||
})
|
||||
]
|
||||
}),
|
||||
/*#__PURE__*/ _jsxs("svg", {
|
||||
xmlns: "http://www.w3.org/2000/svg",
|
||||
viewBox: "0 0 24 24",
|
||||
fill: "none",
|
||||
stroke: "currentColor",
|
||||
strokeWidth: "2",
|
||||
strokeLinecap: "round",
|
||||
strokeLinejoin: "round",
|
||||
children: [
|
||||
/*#__PURE__*/ _jsx("path", {
|
||||
d: "M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"
|
||||
}),
|
||||
/*#__PURE__*/ _jsx("polyline", {
|
||||
points: "15 3 21 3 21 9"
|
||||
}),
|
||||
/*#__PURE__*/ _jsx("line", {
|
||||
x1: "10",
|
||||
y1: "14",
|
||||
x2: "21",
|
||||
y2: "3"
|
||||
})
|
||||
]
|
||||
})
|
||||
]
|
||||
})
|
||||
}),
|
||||
/*#__PURE__*/ _jsx("pre", {
|
||||
children: decoded.map((entry, index)=>/*#__PURE__*/ _jsx("span", {
|
||||
style: {
|
||||
color: entry.fg ? "var(--color-" + entry.fg + ")" : undefined,
|
||||
...entry.decoration === 'bold' ? {
|
||||
fontWeight: 800
|
||||
} : entry.decoration === 'italic' ? {
|
||||
fontStyle: 'italic'
|
||||
} : undefined
|
||||
},
|
||||
children: entry.content
|
||||
}, "frame-" + index))
|
||||
})
|
||||
]
|
||||
});
|
||||
};
|
||||
|
||||
//# sourceMappingURL=CodeFrame.js.map
|
||||
Generated
Vendored
+1
File diff suppressed because one or more lines are too long
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user