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,5 @@
import type { BusEvent } from '../shared';
export type BusEventHandler = (ev: BusEvent) => void;
export declare function emit(ev: BusEvent): void;
export declare function on(fn: BusEventHandler): boolean;
export declare function off(fn: BusEventHandler): boolean;

View File

@@ -0,0 +1,70 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
emit: null,
off: null,
on: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
emit: function() {
return emit;
},
off: function() {
return off;
},
on: function() {
return on;
}
});
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);
}
function emit(ev) {
queue.push(Object.freeze({
...ev
}));
drain();
}
function on(fn) {
if (handlers.has(fn)) {
return false;
}
handlers.add(fn);
drain();
return true;
}
function off(fn) {
if (handlers.has(fn)) {
handlers.delete(fn);
return true;
}
return false;
}
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# 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":["emit","off","on","handlers","Set","queue","drain","setTimeout","Boolean","length","size","ev","shift","forEach","handler","push","Object","freeze","fn","has","add","delete"],"mappings":";;;;;;;;;;;;;;;;IAwBgBA,IAAI;eAAJA;;IAeAC,GAAG;eAAHA;;IAVAC,EAAE;eAAFA;;;AAzBhB,IAAIC,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;AAEO,SAASX,KAAKW,EAAY;IAC/BN,MAAMU,IAAI,CAACC,OAAOC,MAAM,CAAC;QAAE,GAAGN,EAAE;IAAC;IACjCL;AACF;AAEO,SAASJ,GAAGgB,EAAmB;IACpC,IAAIf,SAASgB,GAAG,CAACD,KAAK;QACpB,OAAO;IACT;IAEAf,SAASiB,GAAG,CAACF;IACbZ;IACA,OAAO;AACT;AAEO,SAASL,IAAIiB,EAAmB;IACrC,IAAIf,SAASgB,GAAG,CAACD,KAAK;QACpBf,SAASkB,MAAM,CAACH;QAChB,OAAO;IACT;IAEA,OAAO;AACT"}

View File

@@ -0,0 +1,13 @@
import type { VersionInfo } from '../../../../server/dev/parse-version-info';
import type { DevIndicatorServerState } from '../../../../server/dev/dev-indicator-server-state';
export declare function register(): void;
export declare function unregister(): void;
export declare function onBuildOk(): void;
export declare function onBuildError(message: string): void;
export declare function onRefresh(): void;
export declare function onBeforeRefresh(): void;
export declare function onVersionInfo(versionInfo: VersionInfo): void;
export declare function onStaticIndicator(isStatic: boolean): void;
export declare function onDevIndicator(devIndicatorsState: DevIndicatorServerState): void;
export { getErrorByType } from '../utils/get-error-by-type';
export { getServerError } from '../utils/node-stack-frames';

View File

@@ -0,0 +1,192 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
getErrorByType: null,
getServerError: null,
onBeforeRefresh: null,
onBuildError: null,
onBuildOk: null,
onDevIndicator: null,
onRefresh: null,
onStaticIndicator: null,
onVersionInfo: null,
register: null,
unregister: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
getErrorByType: function() {
return _geterrorbytype.getErrorByType;
},
getServerError: function() {
return _nodestackframes.getServerError;
},
onBeforeRefresh: function() {
return onBeforeRefresh;
},
onBuildError: function() {
return onBuildError;
},
onBuildOk: function() {
return onBuildOk;
},
onDevIndicator: function() {
return onDevIndicator;
},
onRefresh: function() {
return onRefresh;
},
onStaticIndicator: function() {
return onStaticIndicator;
},
onVersionInfo: function() {
return onVersionInfo;
},
register: function() {
return register;
},
unregister: function() {
return unregister;
}
});
const _interop_require_wildcard = require("@swc/helpers/_/_interop_require_wildcard");
const _bus = /*#__PURE__*/ _interop_require_wildcard._(require("./bus"));
const _parsestack = require("../utils/parse-stack");
const _parsecomponentstack = require("../utils/parse-component-stack");
const _hydrationerrorinfo = require("../../errors/hydration-error-info");
const _shared = require("../shared");
const _attachhydrationerrorstate = require("../../errors/attach-hydration-error-state");
const _geterrorbytype = require("../utils/get-error-by-type");
const _nodestackframes = require("../utils/node-stack-frames");
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;
}
(0, _attachhydrationerrorstate.attachHydrationErrorState)(error);
const componentStackTrace = error._componentStack || _hydrationerrorinfo.hydrationErrorState.componentStack;
const componentStackFrames = typeof componentStackTrace === 'string' ? (0, _parsecomponentstack.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: _shared.ACTION_UNHANDLED_ERROR,
reason: error,
frames: (0, _parsestack.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];
(0, _hydrationerrorinfo.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: _shared.ACTION_UNHANDLED_REJECTION,
reason: reason,
frames: (0, _parsestack.parseStack)(e.stack)
});
}
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;
}
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;
}
function onBuildOk() {
_bus.emit({
type: _shared.ACTION_BUILD_OK
});
}
function onBuildError(message) {
_bus.emit({
type: _shared.ACTION_BUILD_ERROR,
message
});
}
function onRefresh() {
_bus.emit({
type: _shared.ACTION_REFRESH
});
}
function onBeforeRefresh() {
_bus.emit({
type: _shared.ACTION_BEFORE_REFRESH
});
}
function onVersionInfo(versionInfo) {
_bus.emit({
type: _shared.ACTION_VERSION_INFO,
versionInfo
});
}
function onStaticIndicator(isStatic) {
_bus.emit({
type: _shared.ACTION_STATIC_INDICATOR,
staticIndicator: isStatic
});
}
function onDevIndicator(devIndicatorsState) {
_bus.emit({
type: _shared.ACTION_DEV_INDICATOR,
devIndicator: devIndicatorsState
});
}
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# sourceMappingURL=client.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,6 @@
export declare const usePagesDevOverlay: () => {
state: import("../shared").OverlayState & {
routerType: "pages" | "app";
};
onComponentError: (_error: Error, _componentStack: string | null) => void;
};

View File

@@ -0,0 +1,45 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "usePagesDevOverlay", {
enumerable: true,
get: function() {
return usePagesDevOverlay;
}
});
const _interop_require_default = require("@swc/helpers/_/_interop_require_default");
const _interop_require_wildcard = require("@swc/helpers/_/_interop_require_wildcard");
const _react = /*#__PURE__*/ _interop_require_default._(require("react"));
const _bus = /*#__PURE__*/ _interop_require_wildcard._(require("./bus"));
const _shared = require("../shared");
const _router = require("../../../router");
const usePagesDevOverlay = ()=>{
const [state, dispatch] = (0, _shared.useErrorOverlayReducer)('pages');
_react.default.useEffect(()=>{
_bus.on(dispatch);
const { handleStaticIndicator } = require('./hot-reloader-client');
_router.Router.events.on('routeChangeComplete', handleStaticIndicator);
return function() {
_router.Router.events.off('routeChangeComplete', handleStaticIndicator);
_bus.off(dispatch);
};
}, [
dispatch
]);
const onComponentError = _react.default.useCallback((_error, _componentStack)=>{
// TODO: special handling
}, []);
return {
state,
onComponentError
};
};
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# 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":["usePagesDevOverlay","state","dispatch","useErrorOverlayReducer","React","useEffect","Bus","on","handleStaticIndicator","require","Router","events","off","onComponentError","useCallback","_error","_componentStack"],"mappings":";;;;+BAKaA;;;eAAAA;;;;;gEALK;+DACG;wBACkB;wBAChB;AAEhB,MAAMA,qBAAqB;IAChC,MAAM,CAACC,OAAOC,SAAS,GAAGC,IAAAA,8BAAsB,EAAC;IAEjDC,cAAK,CAACC,SAAS,CAAC;QACdC,KAAIC,EAAE,CAACL;QAEP,MAAM,EAAEM,qBAAqB,EAAE,GAC7BC,QAAQ;QAEVC,cAAM,CAACC,MAAM,CAACJ,EAAE,CAAC,uBAAuBC;QAExC,OAAO;YACLE,cAAM,CAACC,MAAM,CAACC,GAAG,CAAC,uBAAuBJ;YACzCF,KAAIM,GAAG,CAACV;QACV;IACF,GAAG;QAACA;KAAS;IAEb,MAAMW,mBAAmBT,cAAK,CAACU,WAAW,CACxC,CAACC,QAAeC;IACd,yBAAyB;IAC3B,GACA,EAAE;IAGJ,OAAO;QACLf;QACAY;IACF;AACF"}

View File

@@ -0,0 +1,40 @@
/**
* 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.
*/
import type { TurbopackMsgToBrowser } from '../../../../server/dev/hot-reloader-types';
declare global {
const __webpack_hash__: string;
interface Window {
__nextDevClientId: number;
__NEXT_HMR_LATENCY_CB: any;
}
}
export default function connect(mode: 'webpack' | 'turbopack'): {
subscribeToHmrEvent(handler: any): void;
onUnrecoverableError(): void;
addTurbopackMessageListener(cb: (msg: TurbopackMsgToBrowser) => void): void;
sendTurbopackMessage(msg: string): void;
handleUpdateError(err: unknown): void;
};
export declare function handleStaticIndicator(): void;
export declare function performFullReload(err: any): void;

View File

@@ -0,0 +1,466 @@
// 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
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
default: null,
handleStaticIndicator: null,
performFullReload: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
default: function() {
return connect;
},
handleStaticIndicator: function() {
return handleStaticIndicator;
},
performFullReload: function() {
return performFullReload;
}
});
const _interop_require_default = require("@swc/helpers/_/_interop_require_default");
const _client = require("./client");
const _stripansi = /*#__PURE__*/ _interop_require_default._(require("next/dist/compiled/strip-ansi"));
const _websocket = require("./websocket");
const _formatwebpackmessages = /*#__PURE__*/ _interop_require_default._(require("../utils/format-webpack-messages"));
const _hotreloadertypes = require("../../../../server/dev/hot-reloader-types");
const _extractmodulesfromturbopackmessage = require("../../../../server/dev/extract-modules-from-turbopack-message");
const _shared = require("../shared");
const _runtimeerrorhandler = require("../../errors/runtime-error-handler");
window.__nextDevClientId = Math.round(Math.random() * 100 + Date.now());
let customHmrEventHandler;
let turbopackMessageListeners = [];
let MODE = 'webpack';
function connect(mode) {
MODE = mode;
(0, _client.register)();
(0, _websocket.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.RuntimeErrorHandler.hadRuntimeError = true;
},
addTurbopackMessageListener (cb) {
turbopackMessageListeners.push(cb);
},
sendTurbopackMessage (msg) {
(0, _websocket.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
]);
(0, _client.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 = (0, _formatwebpackmessages.default)({
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((0, _stripansi.default)(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 = (0, _formatwebpackmessages.default)({
errors: errors,
warnings: []
});
// Only show the first error.
(0, _client.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((0, _stripansi.default)(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)
(0, _client.onBeforeRefresh)();
}
}
function onFastRefresh(updatedModules) {
if (updatedModules === void 0) updatedModules = [];
(0, _client.onBuildOk)();
if (updatedModules.length === 0) {
return;
}
(0, _client.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");
(0, _websocket.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;
}
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;
(0, _client.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 _hotreloadertypes.HMR_ACTIONS_SENT_TO_BROWSER.ISR_MANIFEST:
{
isrManifest = obj.data;
handleStaticIndicator();
break;
}
case _hotreloadertypes.HMR_ACTIONS_SENT_TO_BROWSER.BUILDING:
{
startLatency = Date.now();
turbopackLastUpdateLatency = null;
turbopackUpdatedModules.clear();
console.log('[Fast Refresh] rebuilding');
break;
}
case _hotreloadertypes.HMR_ACTIONS_SENT_TO_BROWSER.BUILT:
case _hotreloadertypes.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) (0, _client.onVersionInfo)(obj.versionInfo);
if ('devIndicator' in obj) (0, _client.onDevIndicator)(obj.devIndicator);
const hasErrors = Boolean(errors && errors.length);
if (hasErrors) {
(0, _websocket.sendMessage)(JSON.stringify({
event: 'client-error',
errorCount: errors.length,
clientId: window.__nextDevClientId
}));
return handleErrors(errors);
}
const hasWarnings = Boolean(warnings && warnings.length);
if (hasWarnings) {
(0, _websocket.sendMessage)(JSON.stringify({
event: 'client-warning',
warningCount: warnings.length,
clientId: window.__nextDevClientId
}));
return handleWarnings(warnings);
}
(0, _websocket.sendMessage)(JSON.stringify({
event: 'client-success',
clientId: window.__nextDevClientId
}));
return handleSuccess();
}
case _hotreloadertypes.HMR_ACTIONS_SENT_TO_BROWSER.SERVER_COMPONENT_CHANGES:
{
if (hasCompileErrors || _runtimeerrorhandler.RuntimeErrorHandler.hadRuntimeError) {
window.location.reload();
}
return;
}
case _hotreloadertypes.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 _hotreloadertypes.HMR_ACTIONS_SENT_TO_BROWSER.TURBOPACK_CONNECTED:
{
for (const listener of turbopackMessageListeners){
listener({
type: _hotreloadertypes.HMR_ACTIONS_SENT_TO_BROWSER.TURBOPACK_CONNECTED,
data: obj.data
});
}
break;
}
case _hotreloadertypes.HMR_ACTIONS_SENT_TO_BROWSER.TURBOPACK_MESSAGE:
{
const updatedModules = (0, _extractmodulesfromturbopackmessage.extractModulesFromTurbopackMessage)(obj.data);
onBeforeFastRefresh([
...updatedModules
]);
for (const listener of turbopackMessageListeners){
listener({
type: _hotreloadertypes.HMR_ACTIONS_SENT_TO_BROWSER.TURBOPACK_MESSAGE,
data: obj.data
});
}
if (_runtimeerrorhandler.RuntimeErrorHandler.hadRuntimeError) {
console.warn(_shared.REACT_REFRESH_FULL_RELOAD_FROM_ERROR);
performFullReload(null);
}
(0, _client.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()) {
(0, _client.onBuildOk)();
return;
}
function handleApplyUpdates(err, updatedModules) {
if (err || _runtimeerrorhandler.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.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 ? _client.onBuildOk : onHotUpdateSuccess);
} else {
(0, _client.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);
});
}
function performFullReload(err) {
const stackTrace = err && (err.stack && err.stack.split('\n').slice(0, 5).join('\n') || err.message || err + '');
(0, _websocket.sendMessage)(JSON.stringify({
event: 'client-full-reload',
stackTrace,
hadRuntimeError: !!_runtimeerrorhandler.RuntimeErrorHandler.hadRuntimeError,
dependencyChain: err ? err.dependencyChain : undefined
}));
window.location.reload();
}
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# sourceMappingURL=hot-reloader-client.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,21 @@
import React from 'react';
type PagesDevOverlayErrorBoundaryProps = {
children?: React.ReactNode;
onError: (error: Error, componentStack: string | null) => void;
};
type PagesDevOverlayErrorBoundaryState = {
error: Error | null;
};
export declare class PagesDevOverlayErrorBoundary extends React.PureComponent<PagesDevOverlayErrorBoundaryProps, PagesDevOverlayErrorBoundaryState> {
state: {
error: null;
};
static getDerivedStateFromError(error: Error): {
error: Error;
};
componentDidCatch(error: Error, errorInfo?: {
componentStack?: string | null;
}): void;
render(): React.ReactNode;
}
export {};

View File

@@ -0,0 +1,45 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "PagesDevOverlayErrorBoundary", {
enumerable: true,
get: function() {
return PagesDevOverlayErrorBoundary;
}
});
const _interop_require_default = require("@swc/helpers/_/_interop_require_default");
const _react = /*#__PURE__*/ _interop_require_default._(require("react"));
class PagesDevOverlayErrorBoundary extends _react.default.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
};
}
}
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# 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":["PagesDevOverlayErrorBoundary","React","PureComponent","getDerivedStateFromError","error","componentDidCatch","errorInfo","props","onError","componentStack","setState","render","state","children"],"mappings":";;;;+BAQaA;;;eAAAA;;;;gEARK;AAQX,MAAMA,qCAAqCC,cAAK,CAACC,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,7 @@
export type ErrorType = 'runtime' | 'build';
export type PagesDevOverlayType = typeof PagesDevOverlay;
interface PagesDevOverlayProps {
children?: React.ReactNode;
}
export declare function PagesDevOverlay({ children }: PagesDevOverlayProps): import("react/jsx-runtime").JSX.Element;
export {};

View File

@@ -0,0 +1,43 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "PagesDevOverlay", {
enumerable: true,
get: function() {
return PagesDevOverlay;
}
});
const _jsxruntime = require("react/jsx-runtime");
const _react = require("react");
const _pagesdevoverlayerrorboundary = require("./pages-dev-overlay-error-boundary");
const _hooks = require("./hooks");
const _fontstyles = require("../font/font-styles");
const _devoverlay = require("../ui/dev-overlay");
function PagesDevOverlay(param) {
let { children } = param;
const { state, onComponentError } = (0, _hooks.usePagesDevOverlay)();
const [isErrorOverlayOpen, setIsErrorOverlayOpen] = (0, _react.useState)(true);
return /*#__PURE__*/ (0, _jsxruntime.jsxs)(_jsxruntime.Fragment, {
children: [
/*#__PURE__*/ (0, _jsxruntime.jsx)(_pagesdevoverlayerrorboundary.PagesDevOverlayErrorBoundary, {
onError: onComponentError,
children: children != null ? children : null
}),
/*#__PURE__*/ (0, _jsxruntime.jsx)(_fontstyles.FontStyles, {}),
/*#__PURE__*/ (0, _jsxruntime.jsx)(_devoverlay.DevOverlay, {
state: state,
isErrorOverlayOpen: isErrorOverlayOpen,
setIsErrorOverlayOpen: setIsErrorOverlayOpen
})
]
});
}
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# 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":["PagesDevOverlay","children","state","onComponentError","usePagesDevOverlay","isErrorOverlayOpen","setIsErrorOverlayOpen","useState","PagesDevOverlayErrorBoundary","onError","FontStyles","DevOverlay"],"mappings":";;;;+BAcgBA;;;eAAAA;;;;uBAdS;8CACoB;uBACV;4BACR;4BACA;AAUpB,SAASA,gBAAgB,KAAkC;IAAlC,IAAA,EAAEC,QAAQ,EAAwB,GAAlC;IAC9B,MAAM,EAAEC,KAAK,EAAEC,gBAAgB,EAAE,GAAGC,IAAAA,yBAAkB;IAEtD,MAAM,CAACC,oBAAoBC,sBAAsB,GAAGC,IAAAA,eAAQ,EAAC;IAE7D,qBACE;;0BACE,qBAACC,0DAA4B;gBAACC,SAASN;0BACpCF,mBAAAA,WAAY;;0BAIf,qBAACS,sBAAU;0BACX,qBAACC,sBAAU;gBACTT,OAAOA;gBACPG,oBAAoBA;gBACpBC,uBAAuBA;;;;AAI/B"}

View File

@@ -0,0 +1,9 @@
import { type HMR_ACTION_TYPES } from '../../../../server/dev/hot-reloader-types';
type ActionCallback = (action: HMR_ACTION_TYPES) => void;
export declare function addMessageListener(callback: ActionCallback): void;
export declare function sendMessage(data: string): void;
export declare function connectHMR(options: {
path: string;
assetPrefix: string;
}): void;
export {};

View File

@@ -0,0 +1,104 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
addMessageListener: null,
connectHMR: null,
sendMessage: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
addMessageListener: function() {
return addMessageListener;
},
connectHMR: function() {
return connectHMR;
},
sendMessage: function() {
return sendMessage;
}
});
const _hotreloadertypes = require("../../../../server/dev/hot-reloader-types");
const _getsocketurl = require("../utils/get-socket-url");
let source;
const eventCallbacks = [];
function addMessageListener(callback) {
eventCallbacks.push(callback);
}
function sendMessage(data) {
if (!source || source.readyState !== source.OPEN) return;
return source.send(data);
}
let reconnections = 0;
let reloading = false;
let serverSessionId = null;
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 === _hotreloadertypes.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 = (0, _getsocketurl.getSocketUrl)(options.assetPrefix);
source = new window.WebSocket("" + url + options.path);
source.onopen = handleOnline;
source.onerror = handleDisconnect;
source.onclose = handleDisconnect;
source.onmessage = handleMessage;
}
init();
}
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# sourceMappingURL=websocket.js.map

File diff suppressed because one or more lines are too long