inital commit

This commit is contained in:
2026-01-01 15:25:19 +05:30
commit f0ae49465a
36361 changed files with 4894111 additions and 0 deletions

View File

@@ -0,0 +1,38 @@
let handlers = new Set();
let queue = [];
function drain() {
// Draining should never happen synchronously in case multiple handlers are
// registered.
setTimeout(function() {
while(// Until we are out of events:
Boolean(queue.length) && // Or, if all handlers removed themselves as a result of handling the
// event(s)
Boolean(handlers.size)){
const ev = queue.shift();
handlers.forEach((handler)=>handler(ev));
}
}, 1);
}
export function emit(ev) {
queue.push(Object.freeze({
...ev
}));
drain();
}
export function on(fn) {
if (handlers.has(fn)) {
return false;
}
handlers.add(fn);
drain();
return true;
}
export function off(fn) {
if (handlers.has(fn)) {
handlers.delete(fn);
return true;
}
return false;
}
//# sourceMappingURL=bus.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../src/client/components/react-dev-overlay/pages/bus.ts"],"sourcesContent":["import type { BusEvent } from '../shared'\n\nexport type BusEventHandler = (ev: BusEvent) => void\n\nlet handlers: Set<BusEventHandler> = new Set()\nlet queue: BusEvent[] = []\n\nfunction drain() {\n // Draining should never happen synchronously in case multiple handlers are\n // registered.\n setTimeout(function () {\n while (\n // Until we are out of events:\n Boolean(queue.length) &&\n // Or, if all handlers removed themselves as a result of handling the\n // event(s)\n Boolean(handlers.size)\n ) {\n const ev = queue.shift()!\n handlers.forEach((handler) => handler(ev))\n }\n }, 1)\n}\n\nexport function emit(ev: BusEvent): void {\n queue.push(Object.freeze({ ...ev }))\n drain()\n}\n\nexport function on(fn: BusEventHandler): boolean {\n if (handlers.has(fn)) {\n return false\n }\n\n handlers.add(fn)\n drain()\n return true\n}\n\nexport function off(fn: BusEventHandler): boolean {\n if (handlers.has(fn)) {\n handlers.delete(fn)\n return true\n }\n\n return false\n}\n"],"names":["handlers","Set","queue","drain","setTimeout","Boolean","length","size","ev","shift","forEach","handler","emit","push","Object","freeze","on","fn","has","add","off","delete"],"mappings":"AAIA,IAAIA,WAAiC,IAAIC;AACzC,IAAIC,QAAoB,EAAE;AAE1B,SAASC;IACP,2EAA2E;IAC3E,cAAc;IACdC,WAAW;QACT,MACE,8BAA8B;QAC9BC,QAAQH,MAAMI,MAAM,KACpB,qEAAqE;QACrE,WAAW;QACXD,QAAQL,SAASO,IAAI,EACrB;YACA,MAAMC,KAAKN,MAAMO,KAAK;YACtBT,SAASU,OAAO,CAAC,CAACC,UAAYA,QAAQH;QACxC;IACF,GAAG;AACL;AAEA,OAAO,SAASI,KAAKJ,EAAY;IAC/BN,MAAMW,IAAI,CAACC,OAAOC,MAAM,CAAC;QAAE,GAAGP,EAAE;IAAC;IACjCL;AACF;AAEA,OAAO,SAASa,GAAGC,EAAmB;IACpC,IAAIjB,SAASkB,GAAG,CAACD,KAAK;QACpB,OAAO;IACT;IAEAjB,SAASmB,GAAG,CAACF;IACbd;IACA,OAAO;AACT;AAEA,OAAO,SAASiB,IAAIH,EAAmB;IACrC,IAAIjB,SAASkB,GAAG,CAACD,KAAK;QACpBjB,SAASqB,MAAM,CAACJ;QAChB,OAAO;IACT;IAEA,OAAO;AACT"}

View File

@@ -0,0 +1,127 @@
import * as Bus from './bus';
import { parseStack } from '../utils/parse-stack';
import { parseComponentStack } from '../utils/parse-component-stack';
import { hydrationErrorState, storeHydrationErrorStateFromConsoleArgs } from '../../errors/hydration-error-info';
import { ACTION_BEFORE_REFRESH, ACTION_BUILD_ERROR, ACTION_BUILD_OK, ACTION_DEV_INDICATOR, ACTION_REFRESH, ACTION_STATIC_INDICATOR, ACTION_UNHANDLED_ERROR, ACTION_UNHANDLED_REJECTION, ACTION_VERSION_INFO } from '../shared';
import { attachHydrationErrorState } from '../../errors/attach-hydration-error-state';
let isRegistered = false;
let stackTraceLimit = undefined;
function handleError(error) {
if (!error || !(error instanceof Error) || typeof error.stack !== 'string') {
// A non-error was thrown, we don't have anything to show. :-(
return;
}
attachHydrationErrorState(error);
const componentStackTrace = error._componentStack || hydrationErrorState.componentStack;
const componentStackFrames = typeof componentStackTrace === 'string' ? parseComponentStack(componentStackTrace) : undefined;
// Skip ModuleBuildError and ModuleNotFoundError, as it will be sent through onBuildError callback.
// This is to avoid same error as different type showing up on client to cause flashing.
if (error.name !== 'ModuleBuildError' && error.name !== 'ModuleNotFoundError') {
Bus.emit({
type: ACTION_UNHANDLED_ERROR,
reason: error,
frames: parseStack(error.stack),
componentStackFrames
});
}
}
let origConsoleError = console.error;
function nextJsHandleConsoleError() {
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/d50323eb845c5fde0d720cae888bf35dedd05506/packages/react-reconciler/src/ReactFiberErrorLogger.js#L78
const error = process.env.NODE_ENV !== 'production' ? args[1] : args[0];
storeHydrationErrorStateFromConsoleArgs(...args);
handleError(error);
origConsoleError.apply(window.console, args);
}
function onUnhandledError(event) {
const error = event == null ? void 0 : event.error;
handleError(error);
}
function onUnhandledRejection(ev) {
const reason = ev == null ? void 0 : ev.reason;
if (!reason || !(reason instanceof Error) || typeof reason.stack !== 'string') {
// A non-error was thrown, we don't have anything to show. :-(
return;
}
const e = reason;
Bus.emit({
type: ACTION_UNHANDLED_REJECTION,
reason: reason,
frames: parseStack(e.stack)
});
}
export function register() {
if (isRegistered) {
return;
}
isRegistered = true;
try {
const limit = Error.stackTraceLimit;
Error.stackTraceLimit = 50;
stackTraceLimit = limit;
} catch (e) {}
window.addEventListener('error', onUnhandledError);
window.addEventListener('unhandledrejection', onUnhandledRejection);
window.console.error = nextJsHandleConsoleError;
}
export function unregister() {
if (!isRegistered) {
return;
}
isRegistered = false;
if (stackTraceLimit !== undefined) {
try {
Error.stackTraceLimit = stackTraceLimit;
} catch (e) {}
stackTraceLimit = undefined;
}
window.removeEventListener('error', onUnhandledError);
window.removeEventListener('unhandledrejection', onUnhandledRejection);
window.console.error = origConsoleError;
}
export function onBuildOk() {
Bus.emit({
type: ACTION_BUILD_OK
});
}
export function onBuildError(message) {
Bus.emit({
type: ACTION_BUILD_ERROR,
message
});
}
export function onRefresh() {
Bus.emit({
type: ACTION_REFRESH
});
}
export function onBeforeRefresh() {
Bus.emit({
type: ACTION_BEFORE_REFRESH
});
}
export function onVersionInfo(versionInfo) {
Bus.emit({
type: ACTION_VERSION_INFO,
versionInfo
});
}
export function onStaticIndicator(isStatic) {
Bus.emit({
type: ACTION_STATIC_INDICATOR,
staticIndicator: isStatic
});
}
export function onDevIndicator(devIndicatorsState) {
Bus.emit({
type: ACTION_DEV_INDICATOR,
devIndicator: devIndicatorsState
});
}
export { getErrorByType } from '../utils/get-error-by-type';
export { getServerError } from '../utils/node-stack-frames';
//# sourceMappingURL=client.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,27 @@
import React from 'react';
import * as Bus from './bus';
import { useErrorOverlayReducer } from '../shared';
import { Router } from '../../../router';
export const usePagesDevOverlay = ()=>{
const [state, dispatch] = useErrorOverlayReducer('pages');
React.useEffect(()=>{
Bus.on(dispatch);
const { handleStaticIndicator } = require('./hot-reloader-client');
Router.events.on('routeChangeComplete', handleStaticIndicator);
return function() {
Router.events.off('routeChangeComplete', handleStaticIndicator);
Bus.off(dispatch);
};
}, [
dispatch
]);
const onComponentError = React.useCallback((_error, _componentStack)=>{
// TODO: special handling
}, []);
return {
state,
onComponentError
};
};
//# sourceMappingURL=hooks.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../src/client/components/react-dev-overlay/pages/hooks.ts"],"sourcesContent":["import React from 'react'\nimport * as Bus from './bus'\nimport { useErrorOverlayReducer } from '../shared'\nimport { Router } from '../../../router'\n\nexport const usePagesDevOverlay = () => {\n const [state, dispatch] = useErrorOverlayReducer('pages')\n\n React.useEffect(() => {\n Bus.on(dispatch)\n\n const { handleStaticIndicator } =\n require('./hot-reloader-client') as typeof import('./hot-reloader-client')\n\n Router.events.on('routeChangeComplete', handleStaticIndicator)\n\n return function () {\n Router.events.off('routeChangeComplete', handleStaticIndicator)\n Bus.off(dispatch)\n }\n }, [dispatch])\n\n const onComponentError = React.useCallback(\n (_error: Error, _componentStack: string | null) => {\n // TODO: special handling\n },\n []\n )\n\n return {\n state,\n onComponentError,\n }\n}\n"],"names":["React","Bus","useErrorOverlayReducer","Router","usePagesDevOverlay","state","dispatch","useEffect","on","handleStaticIndicator","require","events","off","onComponentError","useCallback","_error","_componentStack"],"mappings":"AAAA,OAAOA,WAAW,QAAO;AACzB,YAAYC,SAAS,QAAO;AAC5B,SAASC,sBAAsB,QAAQ,YAAW;AAClD,SAASC,MAAM,QAAQ,kBAAiB;AAExC,OAAO,MAAMC,qBAAqB;IAChC,MAAM,CAACC,OAAOC,SAAS,GAAGJ,uBAAuB;IAEjDF,MAAMO,SAAS,CAAC;QACdN,IAAIO,EAAE,CAACF;QAEP,MAAM,EAAEG,qBAAqB,EAAE,GAC7BC,QAAQ;QAEVP,OAAOQ,MAAM,CAACH,EAAE,CAAC,uBAAuBC;QAExC,OAAO;YACLN,OAAOQ,MAAM,CAACC,GAAG,CAAC,uBAAuBH;YACzCR,IAAIW,GAAG,CAACN;QACV;IACF,GAAG;QAACA;KAAS;IAEb,MAAMO,mBAAmBb,MAAMc,WAAW,CACxC,CAACC,QAAeC;IACd,yBAAyB;IAC3B,GACA,EAAE;IAGJ,OAAO;QACLX;QACAQ;IACF;AACF,EAAC"}

View File

@@ -0,0 +1,433 @@
// TODO: Remove use of `any` type. Fix no-use-before-define violations.
/* eslint-disable @typescript-eslint/no-use-before-define */ /**
* MIT License
*
* Copyright (c) 2013-present, Facebook, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/ // This file is a modified version of the Create React App HMR dev client that
// can be found here:
// https://github.com/facebook/create-react-app/blob/v3.4.1/packages/react-dev-utils/webpackHotDevClient.js
import { register, onBuildError, onBuildOk, onBeforeRefresh, onRefresh, onVersionInfo, onStaticIndicator, onDevIndicator } from './client';
import stripAnsi from 'next/dist/compiled/strip-ansi';
import { addMessageListener, sendMessage } from './websocket';
import formatWebpackMessages from '../utils/format-webpack-messages';
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 { RuntimeErrorHandler } from '../../errors/runtime-error-handler';
window.__nextDevClientId = Math.round(Math.random() * 100 + Date.now());
let customHmrEventHandler;
let turbopackMessageListeners = [];
let MODE = 'webpack';
export default function connect(mode) {
MODE = mode;
register();
addMessageListener((payload)=>{
if (!('action' in payload)) {
return;
}
try {
processMessage(payload);
} catch (err) {
var _err_stack;
console.warn('[HMR] Invalid message: ' + JSON.stringify(payload) + '\n' + ((_err_stack = err == null ? void 0 : err.stack) != null ? _err_stack : ''));
}
});
return {
subscribeToHmrEvent (handler) {
customHmrEventHandler = handler;
},
onUnrecoverableError () {
RuntimeErrorHandler.hadRuntimeError = true;
},
addTurbopackMessageListener (cb) {
turbopackMessageListeners.push(cb);
},
sendTurbopackMessage (msg) {
sendMessage(msg);
},
handleUpdateError (err) {
performFullReload(err);
}
};
}
// Remember some state related to hot module replacement.
var isFirstCompilation = true;
var mostRecentCompilationHash = null;
var hasCompileErrors = false;
function clearOutdatedErrors() {
// Clean up outdated compile errors, if any.
if (typeof console !== 'undefined' && typeof console.clear === 'function') {
if (hasCompileErrors) {
console.clear();
}
}
}
// Successful compilation.
function handleSuccess() {
clearOutdatedErrors();
if (MODE === 'webpack') {
const isHotUpdate = !isFirstCompilation || window.__NEXT_DATA__.page !== '/_error' && isUpdateAvailable();
isFirstCompilation = false;
hasCompileErrors = false;
// Attempt to apply hot updates or reload.
if (isHotUpdate) {
tryApplyUpdates(onBeforeFastRefresh, onFastRefresh);
}
} else {
reportHmrLatency([
...turbopackUpdatedModules
]);
onBuildOk();
}
}
// Compilation with warnings (e.g. ESLint).
function handleWarnings(warnings) {
clearOutdatedErrors();
const isHotUpdate = !isFirstCompilation;
isFirstCompilation = false;
hasCompileErrors = false;
function printWarnings() {
// Print warnings to the console.
const formatted = formatWebpackMessages({
warnings: warnings,
errors: []
});
if (typeof console !== 'undefined' && typeof console.warn === 'function') {
var _formatted_warnings;
for(let i = 0; i < ((_formatted_warnings = formatted.warnings) == null ? void 0 : _formatted_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(formatted.warnings[i]));
}
}
}
printWarnings();
// Attempt to apply hot updates or reload.
if (isHotUpdate) {
tryApplyUpdates(onBeforeFastRefresh, onFastRefresh);
}
}
// Compilation with errors (e.g. syntax error or missing modules).
function handleErrors(errors) {
clearOutdatedErrors();
isFirstCompilation = false;
hasCompileErrors = true;
// "Massage" webpack messages.
var formatted = formatWebpackMessages({
errors: errors,
warnings: []
});
// Only show the first error.
onBuildError(formatted.errors[0]);
// Also log them to the console.
if (typeof console !== 'undefined' && typeof console.error === 'function') {
for(var 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;
}
}
}
let startLatency = null;
let turbopackLastUpdateLatency = null;
let turbopackUpdatedModules = new Set();
let isrManifest = {};
function onBeforeFastRefresh(updatedModules) {
if (updatedModules.length > 0) {
// Only trigger a pending state if we have updates to apply
// (cf. onFastRefresh)
onBeforeRefresh();
}
}
function onFastRefresh(updatedModules) {
if (updatedModules === void 0) updatedModules = [];
onBuildOk();
if (updatedModules.length === 0) {
return;
}
onRefresh();
reportHmrLatency();
}
function reportHmrLatency(updatedModules) {
if (updatedModules === void 0) updatedModules = [];
if (!startLatency) return;
// turbopack has a debounce for the BUILT event which we don't want to
// incorrectly show in this number, use the last TURBOPACK_MESSAGE time
let endLatency = turbopackLastUpdateLatency != null ? turbopackLastUpdateLatency : 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'
}));
if (self.__NEXT_HMR_LATENCY_CB) {
self.__NEXT_HMR_LATENCY_CB(latency);
}
}
// There is a newer version of the code available.
function handleAvailableHash(hash) {
// Update last known compilation hash.
mostRecentCompilationHash = hash;
}
export function handleStaticIndicator() {
if (process.env.__NEXT_DEV_INDICATOR) {
var _window_next_router_components__app;
const routeInfo = window.next.router.components[window.next.router.pathname];
const pageComponent = routeInfo == null ? void 0 : routeInfo.Component;
const appComponent = (_window_next_router_components__app = window.next.router.components['/_app']) == null ? void 0 : _window_next_router_components__app.Component;
const isDynamicPage = Boolean(pageComponent == null ? void 0 : pageComponent.getInitialProps) || Boolean(routeInfo.__N_SSP);
const hasAppGetInitialProps = Boolean(appComponent == null ? void 0 : appComponent.getInitialProps) && (appComponent == null ? void 0 : appComponent.getInitialProps) !== (appComponent == null ? void 0 : appComponent.origGetInitialProps);
const isPageStatic = window.location.pathname in isrManifest || !isDynamicPage && !hasAppGetInitialProps;
onStaticIndicator(isPageStatic);
}
}
/** Handles messages from the sevrer for the Pages Router. */ function processMessage(obj) {
if (!('action' in obj)) {
return;
}
// Use turbopack message for analytics, (still need built for webpack)
switch(obj.action){
case HMR_ACTIONS_SENT_TO_BROWSER.ISR_MANIFEST:
{
isrManifest = obj.data;
handleStaticIndicator();
break;
}
case HMR_ACTIONS_SENT_TO_BROWSER.BUILDING:
{
startLatency = Date.now();
turbopackLastUpdateLatency = null;
turbopackUpdatedModules.clear();
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) onVersionInfo(obj.versionInfo);
if ('devIndicator' in obj) onDevIndicator(obj.devIndicator);
const hasErrors = Boolean(errors && errors.length);
if (hasErrors) {
sendMessage(JSON.stringify({
event: 'client-error',
errorCount: errors.length,
clientId: window.__nextDevClientId
}));
return handleErrors(errors);
}
const hasWarnings = Boolean(warnings && warnings.length);
if (hasWarnings) {
sendMessage(JSON.stringify({
event: 'client-warning',
warningCount: warnings.length,
clientId: window.__nextDevClientId
}));
return handleWarnings(warnings);
}
sendMessage(JSON.stringify({
event: 'client-success',
clientId: window.__nextDevClientId
}));
return handleSuccess();
}
case HMR_ACTIONS_SENT_TO_BROWSER.SERVER_COMPONENT_CHANGES:
{
if (hasCompileErrors || RuntimeErrorHandler.hadRuntimeError) {
window.location.reload();
}
return;
}
case HMR_ACTIONS_SENT_TO_BROWSER.SERVER_ERROR:
{
const { errorJSON } = obj;
if (errorJSON) {
const { message, stack } = JSON.parse(errorJSON);
const error = Object.defineProperty(new Error(message), "__NEXT_ERROR_CODE", {
value: "E394",
enumerable: false,
configurable: true
});
error.stack = stack;
handleErrors([
error
]);
}
return;
}
case HMR_ACTIONS_SENT_TO_BROWSER.TURBOPACK_CONNECTED:
{
for (const listener of turbopackMessageListeners){
listener({
type: HMR_ACTIONS_SENT_TO_BROWSER.TURBOPACK_CONNECTED,
data: obj.data
});
}
break;
}
case HMR_ACTIONS_SENT_TO_BROWSER.TURBOPACK_MESSAGE:
{
const updatedModules = extractModulesFromTurbopackMessage(obj.data);
onBeforeFastRefresh([
...updatedModules
]);
for (const listener of turbopackMessageListeners){
listener({
type: HMR_ACTIONS_SENT_TO_BROWSER.TURBOPACK_MESSAGE,
data: obj.data
});
}
if (RuntimeErrorHandler.hadRuntimeError) {
console.warn(REACT_REFRESH_FULL_RELOAD_FROM_ERROR);
performFullReload(null);
}
onRefresh();
for (const module1 of updatedModules){
turbopackUpdatedModules.add(module1);
}
turbopackLastUpdateLatency = Date.now();
break;
}
default:
{
if (customHmrEventHandler) {
customHmrEventHandler(obj);
break;
}
break;
}
}
}
// Is there a newer version of this code available?
function isUpdateAvailable() {
/* 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 TODO: module.hot exists but type needs to be added. Can't use `as any` here as webpack parses for `module.hot` calls.
return module.hot.status() === 'idle';
}
function afterApplyUpdates(fn) {
if (canApplyUpdates()) {
fn();
} else {
function handler(status) {
if (status === 'idle') {
// @ts-expect-error TODO: module.hot exists but type needs to be added. Can't use `as any` here as webpack parses for `module.hot` calls.
module.hot.removeStatusHandler(handler);
fn();
}
}
// @ts-expect-error TODO: module.hot exists but type needs to be added. Can't use `as any` here as webpack parses for `module.hot` calls.
module.hot.addStatusHandler(handler);
}
}
// Attempt to update code on the fly, fall back to a hard reload.
function tryApplyUpdates(onBeforeHotUpdate, onHotUpdateSuccess) {
// @ts-expect-error TODO: module.hot exists but type needs to be added. Can't use `as any` here as webpack parses for `module.hot` calls.
if (!module.hot) {
// HotModuleReplacementPlugin is not in Webpack configuration.
console.error('HotModuleReplacementPlugin is not in Webpack configuration.');
// window.location.reload();
return;
}
if (!isUpdateAvailable() || !canApplyUpdates()) {
onBuildOk();
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('[Fast Refresh] performing full reload because your application had an unrecoverable error');
}
performFullReload(err);
return;
}
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.
// However, this time, don't trigger a pending refresh state.
tryApplyUpdates(updatedModules.length > 0 ? undefined : onBeforeHotUpdate, updatedModules.length > 0 ? onBuildOk : onHotUpdateSuccess);
} else {
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 TODO: module.hot exists but type needs to be added. Can't use `as any` here as webpack parses for `module.hot` calls.
module.hot.check(/* autoApply */ false).then((updatedModules)=>{
if (!updatedModules) {
return null;
}
if (typeof onBeforeHotUpdate === 'function') {
onBeforeHotUpdate(updatedModules);
}
// @ts-expect-error TODO: module.hot exists but type needs to be added. Can't use `as any` here as webpack parses for `module.hot` calls.
return module.hot.apply();
}).then((updatedModules)=>{
handleApplyUpdates(null, updatedModules);
}, (err)=>{
handleApplyUpdates(err, null);
});
}
export function performFullReload(err) {
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
}));
window.location.reload();
}
//# sourceMappingURL=hot-reloader-client.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,28 @@
import React from 'react';
export class PagesDevOverlayErrorBoundary extends React.PureComponent {
static getDerivedStateFromError(error) {
return {
error
};
}
componentDidCatch(error, // Loosely typed because it depends on the React version and was
// accidentally excluded in some versions.
errorInfo) {
this.props.onError(error, (errorInfo == null ? void 0 : errorInfo.componentStack) || null);
this.setState({
error
});
}
// 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() {
// The component has to be unmounted or else it would continue to error
return this.state.error ? null : this.props.children;
}
constructor(...args){
super(...args), this.state = {
error: null
};
}
}
//# sourceMappingURL=pages-dev-overlay-error-boundary.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../src/client/components/react-dev-overlay/pages/pages-dev-overlay-error-boundary.tsx"],"sourcesContent":["import React from 'react'\n\ntype PagesDevOverlayErrorBoundaryProps = {\n children?: React.ReactNode\n onError: (error: Error, componentStack: string | null) => void\n}\ntype PagesDevOverlayErrorBoundaryState = { error: Error | null }\n\nexport class PagesDevOverlayErrorBoundary extends React.PureComponent<\n PagesDevOverlayErrorBoundaryProps,\n PagesDevOverlayErrorBoundaryState\n> {\n state = { error: null }\n\n static getDerivedStateFromError(error: Error) {\n return { error }\n }\n\n componentDidCatch(\n error: Error,\n // Loosely typed because it depends on the React version and was\n // accidentally excluded in some versions.\n errorInfo?: { componentStack?: string | null }\n ) {\n this.props.onError(error, errorInfo?.componentStack || null)\n this.setState({ error })\n }\n\n // Explicit type is needed to avoid the generated `.d.ts` having a wide return type that could be specific to the `@types/react` version.\n render(): React.ReactNode {\n // The component has to be unmounted or else it would continue to error\n return this.state.error ? null : this.props.children\n }\n}\n"],"names":["React","PagesDevOverlayErrorBoundary","PureComponent","getDerivedStateFromError","error","componentDidCatch","errorInfo","props","onError","componentStack","setState","render","state","children"],"mappings":"AAAA,OAAOA,WAAW,QAAO;AAQzB,OAAO,MAAMC,qCAAqCD,MAAME,aAAa;IAMnE,OAAOC,yBAAyBC,KAAY,EAAE;QAC5C,OAAO;YAAEA;QAAM;IACjB;IAEAC,kBACED,KAAY,EACZ,gEAAgE;IAChE,0CAA0C;IAC1CE,SAA8C,EAC9C;QACA,IAAI,CAACC,KAAK,CAACC,OAAO,CAACJ,OAAOE,CAAAA,6BAAAA,UAAWG,cAAc,KAAI;QACvD,IAAI,CAACC,QAAQ,CAAC;YAAEN;QAAM;IACxB;IAEA,yIAAyI;IACzIO,SAA0B;QACxB,uEAAuE;QACvE,OAAO,IAAI,CAACC,KAAK,CAACR,KAAK,GAAG,OAAO,IAAI,CAACG,KAAK,CAACM,QAAQ;IACtD;;QAxBK,qBAILD,QAAQ;YAAER,OAAO;QAAK;;AAqBxB"}

View File

@@ -0,0 +1,27 @@
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { useState } from 'react';
import { PagesDevOverlayErrorBoundary } from './pages-dev-overlay-error-boundary';
import { usePagesDevOverlay } from './hooks';
import { FontStyles } from '../font/font-styles';
import { DevOverlay } from '../ui/dev-overlay';
export function PagesDevOverlay(param) {
let { children } = param;
const { state, onComponentError } = usePagesDevOverlay();
const [isErrorOverlayOpen, setIsErrorOverlayOpen] = useState(true);
return /*#__PURE__*/ _jsxs(_Fragment, {
children: [
/*#__PURE__*/ _jsx(PagesDevOverlayErrorBoundary, {
onError: onComponentError,
children: children != null ? children : null
}),
/*#__PURE__*/ _jsx(FontStyles, {}),
/*#__PURE__*/ _jsx(DevOverlay, {
state: state,
isErrorOverlayOpen: isErrorOverlayOpen,
setIsErrorOverlayOpen: setIsErrorOverlayOpen
})
]
});
}
//# sourceMappingURL=pages-dev-overlay.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../src/client/components/react-dev-overlay/pages/pages-dev-overlay.tsx"],"sourcesContent":["import { useState } from 'react'\nimport { PagesDevOverlayErrorBoundary } from './pages-dev-overlay-error-boundary'\nimport { usePagesDevOverlay } from './hooks'\nimport { FontStyles } from '../font/font-styles'\nimport { DevOverlay } from '../ui/dev-overlay'\n\nexport type ErrorType = 'runtime' | 'build'\n\nexport type PagesDevOverlayType = typeof PagesDevOverlay\n\ninterface PagesDevOverlayProps {\n children?: React.ReactNode\n}\n\nexport function PagesDevOverlay({ children }: PagesDevOverlayProps) {\n const { state, onComponentError } = usePagesDevOverlay()\n\n const [isErrorOverlayOpen, setIsErrorOverlayOpen] = useState(true)\n\n return (\n <>\n <PagesDevOverlayErrorBoundary onError={onComponentError}>\n {children ?? null}\n </PagesDevOverlayErrorBoundary>\n\n {/* Fonts can only be loaded outside the Shadow DOM. */}\n <FontStyles />\n <DevOverlay\n state={state}\n isErrorOverlayOpen={isErrorOverlayOpen}\n setIsErrorOverlayOpen={setIsErrorOverlayOpen}\n />\n </>\n )\n}\n"],"names":["useState","PagesDevOverlayErrorBoundary","usePagesDevOverlay","FontStyles","DevOverlay","PagesDevOverlay","children","state","onComponentError","isErrorOverlayOpen","setIsErrorOverlayOpen","onError"],"mappings":";AAAA,SAASA,QAAQ,QAAQ,QAAO;AAChC,SAASC,4BAA4B,QAAQ,qCAAoC;AACjF,SAASC,kBAAkB,QAAQ,UAAS;AAC5C,SAASC,UAAU,QAAQ,sBAAqB;AAChD,SAASC,UAAU,QAAQ,oBAAmB;AAU9C,OAAO,SAASC,gBAAgB,KAAkC;IAAlC,IAAA,EAAEC,QAAQ,EAAwB,GAAlC;IAC9B,MAAM,EAAEC,KAAK,EAAEC,gBAAgB,EAAE,GAAGN;IAEpC,MAAM,CAACO,oBAAoBC,sBAAsB,GAAGV,SAAS;IAE7D,qBACE;;0BACE,KAACC;gBAA6BU,SAASH;0BACpCF,mBAAAA,WAAY;;0BAIf,KAACH;0BACD,KAACC;gBACCG,OAAOA;gBACPE,oBAAoBA;gBACpBC,uBAAuBA;;;;AAI/B"}

View File

@@ -0,0 +1,72 @@
import { HMR_ACTIONS_SENT_TO_BROWSER } from '../../../../server/dev/hot-reloader-types';
import { getSocketUrl } from '../utils/get-socket-url';
let source;
const eventCallbacks = [];
export function addMessageListener(callback) {
eventCallbacks.push(callback);
}
export function sendMessage(data) {
if (!source || source.readyState !== source.OPEN) return;
return source.send(data);
}
let reconnections = 0;
let reloading = false;
let serverSessionId = null;
export function connectHMR(options) {
function init() {
if (source) source.close();
function handleOnline() {
reconnections = 0;
window.console.log('[HMR] connected');
}
function handleMessage(event) {
// While the page is reloading, don't respond to any more messages.
// On reconnect, the server may send an empty list of changes if it was restarted.
if (reloading) {
return;
}
// Coerce into HMR_ACTION_TYPES as that is the format.
const msg = JSON.parse(event.data);
if ('action' in msg && msg.action === HMR_ACTIONS_SENT_TO_BROWSER.TURBOPACK_CONNECTED) {
if (serverSessionId !== null && serverSessionId !== msg.data.sessionId) {
// Either the server's session id has changed and it's a new server, or
// it's been too long since we disconnected and we should reload the page.
// There could be 1) unhandled server errors and/or 2) stale content.
// Perform a hard reload of the page.
window.location.reload();
reloading = true;
return;
}
serverSessionId = msg.data.sessionId;
}
for (const eventCallback of eventCallbacks){
eventCallback(msg);
}
}
let timer;
function handleDisconnect() {
source.onerror = null;
source.onclose = null;
source.close();
reconnections++;
// After 25 reconnects we'll want to reload the page as it indicates the dev server is no longer running.
if (reconnections > 25) {
reloading = true;
window.location.reload();
return;
}
clearTimeout(timer);
// Try again after 5 seconds
timer = setTimeout(init, reconnections > 5 ? 5000 : 1000);
}
const url = getSocketUrl(options.assetPrefix);
source = new window.WebSocket("" + url + options.path);
source.onopen = handleOnline;
source.onerror = handleDisconnect;
source.onclose = handleDisconnect;
source.onmessage = handleMessage;
}
init();
}
//# sourceMappingURL=websocket.js.map

File diff suppressed because one or more lines are too long