Unverified Commit ad63effb authored by Will Binns-Smith's avatar Will Binns-Smith Committed by GitHub

Remove unneeded next-dev js in next-core (#56039)

x-ref:
https://github.com/vercel/next.js/pull/55983#issuecomment-1734766241


Closes WEB-1661
parent 778a3c55
/**
* Build npm package to be able to embed them in the binary
*/
import { mkdir, writeFile, rm, readFile } from 'node:fs/promises'
import { existsSync } from 'node:fs'
import { createRequire } from 'node:module'
import { join, dirname, basename, extname } from 'node:path'
import { fileURLToPath } from 'node:url'
import ncc from '@vercel/ncc'
import { findUp } from 'find-up'
const __dirname = dirname(fileURLToPath(import.meta.url))
const require = createRequire(import.meta.url)
/**
* @type {{
* name: string;
* type: "cjs" | "module" | "module-default";
* types?: string;
* }[]}
*/
const packages = [
{
name: 'anser',
type: 'cjs',
},
{
name: 'css.escape',
type: 'cjs',
types: 'export = CSS.escape',
},
{
name: 'platform',
type: 'cjs',
},
{
name: 'source-map',
type: 'module',
},
{
name: 'stacktrace-parser',
type: 'module',
},
{
name: 'strip-ansi',
type: 'module-default',
},
]
const externals = Object.fromEntries(
packages.map((pkg) => [
pkg.name,
`@vercel/turbopack-next/compiled/${pkg.name}`,
])
)
// adapted from https://github.com/vercel/next.js/blob/8fb5ef18e7958a19874e11b8037ac0f71c48baef/packages/next/taskfile-ncc.js
async function writePackageManifest(packageName, main) {
// some newer packages fail to include package.json in the exports
// so we can't reliably use require.resolve here
let packagePath
try {
packagePath = require.resolve(packageName + '/package.json')
} catch (_) {
packagePath = await findUp('package.json', {
cwd: dirname(require.resolve(packageName)),
})
}
const { name, author, license } = require(packagePath)
const compiledPackagePath = join(__dirname, `src/compiled/${packageName}`)
const potentialLicensePath = join(dirname(packagePath), './LICENSE')
if (existsSync(potentialLicensePath)) {
await writeFile(
join(compiledPackagePath, 'LICENSE'),
await readFile(potentialLicensePath, 'utf8')
)
} else {
// license might be lower case and not able to be found on case-sensitive
// file systems (ubuntu)
const otherPotentialLicensePath = join(dirname(packagePath), './license')
if (existsSync(otherPotentialLicensePath)) {
await writeFile(
join(compiledPackagePath, 'LICENSE'),
await readFile(otherPotentialLicensePath, 'utf8')
)
}
}
await writeFile(
join(compiledPackagePath, 'package.json'),
JSON.stringify(
Object.assign(
{},
{ name, main: `${basename(main, '.' + extname(main))}` },
author ? { author } : undefined,
license ? { license } : undefined
)
) + '\n'
)
}
async function main() {
const baseDir = join(__dirname, 'src/compiled')
await rm(baseDir, {
force: true,
recursive: true,
})
let types = '/* GENERATED FILE, DO NOT EDIT */\n'
for (const pkg of packages) {
const input = require.resolve(pkg.name)
const outputDir = join(baseDir, pkg.name)
await mkdir(outputDir, { recursive: true })
const { code, assets } = await ncc(input, {
minify: true,
assetBuilds: true,
quiet: true,
externals,
})
await writeFile(join(outputDir, 'index.js'), code)
for (const key in assets) {
await writeFile(join(outputDir, key), assets[key].source)
}
await writePackageManifest(pkg.name, 'index.js')
types += `\ndeclare module '@vercel/turbopack-next/compiled/${pkg.name}' {\n`
if (pkg.types) {
types += ` ${pkg.types}\n`
} else if (pkg.type === 'module-default') {
types += ` import m from '${pkg.name}'\n`
types += ` export default m\n`
} else if (pkg.type === 'module') {
types += ` export * from '${pkg.name}'\n`
} else if (pkg.type === 'cjs') {
types += ` import m from '${pkg.name}'\n`
types += ` export = m\n`
} else {
throw new Error(`unknown package type ${pkg.type} for ${pkg.name}`)
}
types += `}\n`
console.log(`built ${pkg.name}`)
}
await writeFile(join(__dirname, 'types', 'compiled.d.ts'), types)
}
main().catch((e) => {
console.dir(e)
process.exit(1)
})
......@@ -5,29 +5,6 @@
"license": "UNLICENSED",
"private": true,
"scripts": {
"build": "pnpm build:compiled && pnpm check",
"build:compiled": "node build.mjs",
"check": "tsc --noEmit"
},
"dependencies": {
"@vercel/turbopack-ecmascript-runtime": "https://gitpkg-fork.vercel.sh/vercel/turbo/crates/turbopack-ecmascript-runtime/js?turbopack-230922.2",
"@vercel/turbopack-node": "https://gitpkg-fork.vercel.sh/vercel/turbo/crates/turbopack-node/js?turbopack-230922.2",
"anser": "^2.1.1",
"css.escape": "^1.5.1",
"next": "*",
"platform": "1.3.6",
"react-dom": "^18.2.0",
"react": "^18.2.0",
"source-map": "0.8.0-beta.0",
"stacktrace-parser": "^0.1.10",
"strip-ansi": "^7.0.1"
},
"devDependencies": {
"@types/node": "^18.11.11",
"@types/platform": "^1.3.4",
"@types/react": "18.2.5",
"@types/react-dom": "18.2.3",
"@vercel/ncc": "^0.36.0",
"find-up": "^6.3.0"
}
}
The MIT License (MIT)
Copyright (c) 2012-22 Ionică Bizău <bizauionica@gmail.com> (https://ionicabizau.net)
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.
(()=>{"use strict";var e={281:e=>{var r=function(){function defineProperties(e,r){for(var s=0;s<r.length;s++){var n=r[s];n.enumerable=n.enumerable||false;n.configurable=true;if("value"in n)n.writable=true;Object.defineProperty(e,n.key,n)}}return function(e,r,s){if(r)defineProperties(e.prototype,r);if(s)defineProperties(e,s);return e}}();function _classCallCheck(e,r){if(!(e instanceof r)){throw new TypeError("Cannot call a class as a function")}}var s=[[{color:"0, 0, 0",class:"ansi-black"},{color:"187, 0, 0",class:"ansi-red"},{color:"0, 187, 0",class:"ansi-green"},{color:"187, 187, 0",class:"ansi-yellow"},{color:"0, 0, 187",class:"ansi-blue"},{color:"187, 0, 187",class:"ansi-magenta"},{color:"0, 187, 187",class:"ansi-cyan"},{color:"255,255,255",class:"ansi-white"}],[{color:"85, 85, 85",class:"ansi-bright-black"},{color:"255, 85, 85",class:"ansi-bright-red"},{color:"0, 255, 0",class:"ansi-bright-green"},{color:"255, 255, 85",class:"ansi-bright-yellow"},{color:"85, 85, 255",class:"ansi-bright-blue"},{color:"255, 85, 255",class:"ansi-bright-magenta"},{color:"85, 255, 255",class:"ansi-bright-cyan"},{color:"255, 255, 255",class:"ansi-bright-white"}]];var n=function(){r(Anser,null,[{key:"escapeForHtml",value:function escapeForHtml(e){return(new Anser).escapeForHtml(e)}},{key:"linkify",value:function linkify(e){return(new Anser).linkify(e)}},{key:"ansiToHtml",value:function ansiToHtml(e,r){return(new Anser).ansiToHtml(e,r)}},{key:"ansiToJson",value:function ansiToJson(e,r){return(new Anser).ansiToJson(e,r)}},{key:"ansiToText",value:function ansiToText(e){return(new Anser).ansiToText(e)}}]);function Anser(){_classCallCheck(this,Anser);this.fg=this.bg=this.fg_truecolor=this.bg_truecolor=null;this.bright=0;this.decorations=[]}r(Anser,[{key:"setupPalette",value:function setupPalette(){this.PALETTE_COLORS=[];for(var e=0;e<2;++e){for(var r=0;r<8;++r){this.PALETTE_COLORS.push(s[e][r].color)}}var n=[0,95,135,175,215,255];var o=function format(e,r,s){return n[e]+", "+n[r]+", "+n[s]};var i=void 0,t=void 0,a=void 0;for(var l=0;l<6;++l){for(var c=0;c<6;++c){for(var u=0;u<6;++u){this.PALETTE_COLORS.push(o(l,c,u))}}}var f=8;for(var h=0;h<24;++h,f+=10){this.PALETTE_COLORS.push(o(f,f,f))}}},{key:"escapeForHtml",value:function escapeForHtml(e){return e.replace(/[&<>\"]/gm,(function(e){return e=="&"?"&amp;":e=='"'?"&quot;":e=="<"?"&lt;":e==">"?"&gt;":""}))}},{key:"linkify",value:function linkify(e){return e.replace(/(https?:\/\/[^\s]+)/gm,(function(e){return'<a href="'+e+'">'+e+"</a>"}))}},{key:"ansiToHtml",value:function ansiToHtml(e,r){return this.process(e,r,true)}},{key:"ansiToJson",value:function ansiToJson(e,r){r=r||{};r.json=true;r.clearLine=false;return this.process(e,r,true)}},{key:"ansiToText",value:function ansiToText(e){return this.process(e,{},false)}},{key:"process",value:function process(e,r,s){var n=this;var o=this;var i=e.split(/\033\[/);var t=i.shift();if(r===undefined||r===null){r={}}r.clearLine=/\r/.test(e);var a=i.map((function(e){return n.processChunk(e,r,s)}));if(r&&r.json){var l=o.processChunkJson("");l.content=t;l.clearLine=r.clearLine;a.unshift(l);if(r.remove_empty){a=a.filter((function(e){return!e.isEmpty()}))}return a}else{a.unshift(t)}return a.join("")}},{key:"processChunkJson",value:function processChunkJson(e,r,n){r=typeof r=="undefined"?{}:r;var o=r.use_classes=typeof r.use_classes!="undefined"&&r.use_classes;var i=r.key=o?"class":"color";var t={content:e,fg:null,bg:null,fg_truecolor:null,bg_truecolor:null,isInverted:false,clearLine:r.clearLine,decoration:null,decorations:[],was_processed:false,isEmpty:function isEmpty(){return!t.content}};var a=e.match(/^([!\x3c-\x3f]*)([\d;]*)([\x20-\x2c]*[\x40-\x7e])([\s\S]*)/m);if(!a)return t;var l=t.content=a[4];var c=a[2].split(";");if(a[1]!==""||a[3]!=="m"){return t}if(!n){return t}var u=this;while(c.length>0){var f=c.shift();var h=parseInt(f);if(isNaN(h)||h===0){u.fg=u.bg=null;u.decorations=[]}else if(h===1){u.decorations.push("bold")}else if(h===2){u.decorations.push("dim")}else if(h===3){u.decorations.push("italic")}else if(h===4){u.decorations.push("underline")}else if(h===5){u.decorations.push("blink")}else if(h===7){u.decorations.push("reverse")}else if(h===8){u.decorations.push("hidden")}else if(h===9){u.decorations.push("strikethrough")}else if(h===21){u.removeDecoration("bold")}else if(h===22){u.removeDecoration("bold");u.removeDecoration("dim")}else if(h===23){u.removeDecoration("italic")}else if(h===24){u.removeDecoration("underline")}else if(h===25){u.removeDecoration("blink")}else if(h===27){u.removeDecoration("reverse")}else if(h===28){u.removeDecoration("hidden")}else if(h===29){u.removeDecoration("strikethrough")}else if(h===39){u.fg=null}else if(h===49){u.bg=null}else if(h>=30&&h<38){u.fg=s[0][h%10][i]}else if(h>=90&&h<98){u.fg=s[1][h%10][i]}else if(h>=40&&h<48){u.bg=s[0][h%10][i]}else if(h>=100&&h<108){u.bg=s[1][h%10][i]}else if(h===38||h===48){var v=h===38;if(c.length>=1){var g=c.shift();if(g==="5"&&c.length>=1){var p=parseInt(c.shift());if(p>=0&&p<=255){if(!o){if(!this.PALETTE_COLORS){u.setupPalette()}if(v){u.fg=this.PALETTE_COLORS[p]}else{u.bg=this.PALETTE_COLORS[p]}}else{var d=p>=16?"ansi-palette-"+p:s[p>7?1:0][p%8]["class"];if(v){u.fg=d}else{u.bg=d}}}}else if(g==="2"&&c.length>=3){var b=parseInt(c.shift());var _=parseInt(c.shift());var m=parseInt(c.shift());if(b>=0&&b<=255&&_>=0&&_<=255&&m>=0&&m<=255){var k=b+", "+_+", "+m;if(!o){if(v){u.fg=k}else{u.bg=k}}else{if(v){u.fg="ansi-truecolor";u.fg_truecolor=k}else{u.bg="ansi-truecolor";u.bg_truecolor=k}}}}}}}if(u.fg===null&&u.bg===null&&u.decorations.length===0){return t}else{var y=[];var T=[];var w={};t.fg=u.fg;t.bg=u.bg;t.fg_truecolor=u.fg_truecolor;t.bg_truecolor=u.bg_truecolor;t.decorations=u.decorations;t.decoration=u.decorations.slice(-1).pop()||null;t.was_processed=true;return t}}},{key:"processChunk",value:function processChunk(e,r,n){var o=this;r=r||{};var i=this.processChunkJson(e,r,n);var t=r.use_classes;i.decorations=i.decorations.filter((function(e){if(e==="reverse"){if(!i.fg){i.fg=s[0][7][t?"class":"color"]}if(!i.bg){i.bg=s[0][0][t?"class":"color"]}var r=i.fg;i.fg=i.bg;i.bg=r;var n=i.fg_truecolor;i.fg_truecolor=i.bg_truecolor;i.bg_truecolor=n;i.isInverted=true;return false}return true}));if(r.json){return i}if(i.isEmpty()){return""}if(!i.was_processed){return i.content}var a=[];var l=[];var c=[];var u={};var f=function render_data(e){var r=[];var s=void 0;for(s in e){if(e.hasOwnProperty(s)){r.push("data-"+s+'="'+o.escapeForHtml(e[s])+'"')}}return r.length>0?" "+r.join(" "):""};if(i.isInverted){u["ansi-is-inverted"]="true"}if(i.fg){if(t){a.push(i.fg+"-fg");if(i.fg_truecolor!==null){u["ansi-truecolor-fg"]=i.fg_truecolor;i.fg_truecolor=null}}else{a.push("color:rgb("+i.fg+")")}}if(i.bg){if(t){a.push(i.bg+"-bg");if(i.bg_truecolor!==null){u["ansi-truecolor-bg"]=i.bg_truecolor;i.bg_truecolor=null}}else{a.push("background-color:rgb("+i.bg+")")}}i.decorations.forEach((function(e){if(t){l.push("ansi-"+e);return}if(e==="bold"){l.push("font-weight:bold")}else if(e==="dim"){l.push("opacity:0.5")}else if(e==="italic"){l.push("font-style:italic")}else if(e==="hidden"){l.push("visibility:hidden")}else if(e==="strikethrough"){c.push("line-through")}else{c.push(e)}}));if(c.length){l.push("text-decoration:"+c.join(" "))}if(t){return'<span class="'+a.concat(l).join(" ")+'"'+f(u)+">"+i.content+"</span>"}else{return'<span style="'+a.concat(l).join(";")+'"'+f(u)+">"+i.content+"</span>"}}},{key:"removeDecoration",value:function removeDecoration(e){var r=this.decorations.indexOf(e);if(r>=0){this.decorations.splice(r,1)}}}]);return Anser}();e.exports=n}};var r={};function __nccwpck_require__(s){var n=r[s];if(n!==undefined){return n.exports}var o=r[s]={exports:{}};var i=true;try{e[s](o,o.exports,__nccwpck_require__);i=false}finally{if(i)delete r[s]}return o.exports}if(typeof __nccwpck_require__!=="undefined")__nccwpck_require__.ab=__dirname+"/";var s=__nccwpck_require__(281);module.exports=s})();
\ No newline at end of file
{"name":"anser","main":"index.js","author":"Ionică Bizău <bizauionica@gmail.com> (https://ionicabizau.net)","license":"MIT"}
(()=>{var e={196:function(e){(function(r,t){if(true){e.exports=t(r)}else{}})(typeof global!="undefined"?global:this,(function(e){if(e.CSS&&e.CSS.escape){return e.CSS.escape}var cssEscape=function(e){if(arguments.length==0){throw new TypeError("`CSS.escape` requires an argument.")}var r=String(e);var t=r.length;var n=-1;var a;var i="";var u=r.charCodeAt(0);while(++n<t){a=r.charCodeAt(n);if(a==0){i+="�";continue}if(a>=1&&a<=31||a==127||n==0&&a>=48&&a<=57||n==1&&a>=48&&a<=57&&u==45){i+="\\"+a.toString(16)+" ";continue}if(n==0&&t==1&&a==45){i+="\\"+r.charAt(n);continue}if(a>=128||a==45||a==95||a>=48&&a<=57||a>=65&&a<=90||a>=97&&a<=122){i+=r.charAt(n);continue}i+="\\"+r.charAt(n)}return i};if(!e.CSS){e.CSS={}}e.CSS.escape=cssEscape;return cssEscape}))}};var r={};function __nccwpck_require__(t){var n=r[t];if(n!==undefined){return n.exports}var a=r[t]={exports:{}};var i=true;try{e[t].call(a.exports,a,a.exports,__nccwpck_require__);i=false}finally{if(i)delete r[t]}return a.exports}if(typeof __nccwpck_require__!=="undefined")__nccwpck_require__.ab=__dirname+"/";var t=__nccwpck_require__(196);module.exports=t})();
\ No newline at end of file
{"name":"css.escape","main":"index.js","author":{"name":"Mathias Bynens","url":"https://mathiasbynens.be/"},"license":"MIT"}
Copyright 2014-2020 Benjamin Tan
Copyright 2011-2013 John-David Dalton
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.
{"name":"platform","main":"index.js","author":"Benjamin Tan <demoneaux@gmail.com>","license":"MIT"}
Copyright (c) 2009-2011, Mozilla Foundation and contributors
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the names of the Mozilla Foundation nor the names of project
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
{"name":"source-map","main":"index.js","author":"Nick Fitzgerald <nfitzgerald@mozilla.com>","license":"BSD-3-Clause"}
MIT License
Copyright (c) 2014-2019 Georg Tavonius
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.
(()=>{"use strict";if(typeof __nccwpck_require__!=="undefined")__nccwpck_require__.ab=__dirname+"/";var e={};(()=>{var r=e;Object.defineProperty(r,"__esModule",{value:true});var n="<unknown>";function parse(e){var r=e.split("\n");return r.reduce((function(e,r){var n=parseChrome(r)||parseWinjs(r)||parseGecko(r)||parseNode(r)||parseJSC(r);if(n){e.push(n)}return e}),[])}var a=/^\s*at (.*?) ?\(((?:file|https?|blob|chrome-extension|native|eval|webpack|<anonymous>|\/|[a-z]:\\|\\\\).*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i;var l=/\((\S*)(?::(\d+))(?::(\d+))\)/;function parseChrome(e){var r=a.exec(e);if(!r){return null}var u=r[2]&&r[2].indexOf("native")===0;var t=r[2]&&r[2].indexOf("eval")===0;var i=l.exec(r[2]);if(t&&i!=null){r[2]=i[1];r[3]=i[2];r[4]=i[3]}return{file:!u?r[2]:null,methodName:r[1]||n,arguments:u?[r[2]]:[],lineNumber:r[3]?+r[3]:null,column:r[4]?+r[4]:null}}var u=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:file|ms-appx|https?|webpack|blob):.*?):(\d+)(?::(\d+))?\)?\s*$/i;function parseWinjs(e){var r=u.exec(e);if(!r){return null}return{file:r[2],methodName:r[1]||n,arguments:[],lineNumber:+r[3],column:r[4]?+r[4]:null}}var t=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)((?:file|https?|blob|chrome|webpack|resource|\[native).*?|[^@]*bundle)(?::(\d+))?(?::(\d+))?\s*$/i;var i=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i;function parseGecko(e){var r=t.exec(e);if(!r){return null}var a=r[3]&&r[3].indexOf(" > eval")>-1;var l=i.exec(r[3]);if(a&&l!=null){r[3]=l[1];r[4]=l[2];r[5]=null}return{file:r[3],methodName:r[1]||n,arguments:r[2]?r[2].split(","):[],lineNumber:r[4]?+r[4]:null,column:r[5]?+r[5]:null}}var s=/^\s*(?:([^@]*)(?:\((.*?)\))?@)?(\S.*?):(\d+)(?::(\d+))?\s*$/i;function parseJSC(e){var r=s.exec(e);if(!r){return null}return{file:r[3],methodName:r[1]||n,arguments:[],lineNumber:+r[4],column:r[5]?+r[5]:null}}var o=/^\s*at (?:((?:\[object object\])?[^\\/]+(?: \[as \S+\])?) )?\(?(.*?):(\d+)(?::(\d+))?\)?\s*$/i;function parseNode(e){var r=o.exec(e);if(!r){return null}return{file:r[2],methodName:r[1]||n,arguments:[],lineNumber:+r[3],column:r[4]?+r[4]:null}}r.parse=parse})();module.exports=e})();
\ No newline at end of file
{"name":"stacktrace-parser","main":"index.js","author":"Georg Tavonius <g.tavonius@gmail.com> (http://jaz-lounge.com)","license":"MIT"}
MIT License
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com)
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.
var e={};(()=>{e.d=(t,r)=>{for(var n in r){if(e.o(r,n)&&!e.o(t,n)){Object.defineProperty(t,n,{enumerable:true,get:r[n]})}}}})();(()=>{e.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t)})();if(typeof e!=="undefined")e.ab=new URL(".",import.meta.url).pathname.slice(import.meta.url.match(/^file:\/\/\/\w:/)?1:0,-1)+"/";var t={};e.d(t,{Z:()=>stripAnsi});function ansiRegex({onlyFirst:e=false}={}){const t=["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)","(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))"].join("|");return new RegExp(t,e?undefined:"g")}function stripAnsi(e){if(typeof e!=="string"){throw new TypeError(`Expected a \`string\`, got \`${typeof e}\``)}return e.replace(ansiRegex(),"")}var r=t.Z;export{r as default};
\ No newline at end of file
{"name":"strip-ansi","main":"index.js","author":{"name":"Sindre Sorhus","email":"sindresorhus@gmail.com","url":"https://sindresorhus.com"},"license":"MIT"}
import { initializeHMR } from './client'
initializeHMR({
assetPrefix: '',
})
import { connect } from '@vercel/turbopack-ecmascript-runtime/dev/client/hmr-client'
import {
connectHMR,
addMessageListener,
sendMessage,
} from '@vercel/turbopack-ecmascript-runtime/dev/client/websocket'
import { register, ReactDevOverlay } from '../overlay/client'
export function initializeHMR(options: { assetPrefix: string }) {
connect({
addMessageListener,
sendMessage,
})
connectHMR({
assetPrefix: options.assetPrefix,
log: true,
path: '/turbopack-hmr',
})
register()
}
export { ReactDevOverlay }
'use client'
import type React from 'react'
import { useRouter, usePathname } from 'next/dist/client/components/navigation'
import { useEffect } from 'react'
import { subscribeToUpdate } from '@vercel/turbopack-ecmascript-runtime/dev/client/hmr-client'
import { ReactDevOverlay } from './client'
import { sendMessage } from '@vercel/turbopack-ecmascript-runtime/dev/client/websocket'
type HotReloadProps = React.PropsWithChildren<{
assetPrefix?: string
}>
export default function HotReload({ children }: HotReloadProps) {
const router = useRouter()
const path = usePathname()!.slice(1)
useEffect(() => {
const unsubscribe = subscribeToUpdate(
{
path,
headers: {
rsc: '1',
},
},
sendMessage,
(update) => {
if (update.type !== 'issues') {
router.refresh()
}
}
)
return unsubscribe
}, [router, path])
return <ReactDevOverlay globalOverlay={true}>{children}</ReactDevOverlay>
}
// IPC need to be the first import to allow it to catch errors happening during
// the other imports
import startOperationStreamHandler from '../internal/operation-stream'
import 'next/dist/server/node-polyfill-fetch'
import { join } from 'path'
import { parse as parseUrl } from 'node:url'
import { runEdgeFunction } from '../internal/edge'
import { headersFromEntries, initProxiedHeaders } from '../internal/headers'
import { NodeNextRequest } from 'next/dist/server/base-http/node'
import type { IncomingMessage } from 'node:http'
import type { RenderData } from 'types/turbopack'
import chunkGroup from 'INNER_EDGE_CHUNK_GROUP'
import { attachRequestMeta } from '../internal/next-request-helpers'
import { Readable } from 'stream'
startOperationStreamHandler(async (renderData: RenderData, respond) => {
const { response } = await runOperation(renderData)
if (response == null) {
throw new Error('no html returned')
}
const channel = respond({
status: response.status,
// @ts-expect-error Headers is iterable since node.js 18
headers: [...response.headers],
})
if (response.body) {
const reader = response.body.getReader()
for (;;) {
let { done, value } = await reader.read()
if (done) {
break
}
channel.chunk(Buffer.from(value!))
}
}
channel.end()
})
async function runOperation(renderData: RenderData) {
const edgeInfo = {
name: 'edge',
paths: chunkGroup
.filter((chunk) => chunk.endsWith('.js'))
.map((chunk: string) => join(process.cwd(), '.next/server/app', chunk)),
wasm: [],
env: Object.keys(process.env),
assets: [],
}
const parsedUrl = parseUrl(renderData.originalUrl, true)
const incoming = new Readable() as IncomingMessage
incoming.push(null)
incoming.url = renderData.originalUrl
incoming.method = renderData.method
incoming.headers = initProxiedHeaders(
headersFromEntries(renderData.rawHeaders),
renderData.data?.serverInfo
)
const req = new NodeNextRequest(incoming)
attachRequestMeta(req, parsedUrl, req.headers.host!)
const res = await runEdgeFunction({
edgeInfo,
outputDir: 'edge-pages',
req,
query: renderData.rawQuery,
params: renderData.params,
path: renderData.path,
onWarning(warning) {
console.warn(warning)
},
})
return res as { response: Response }
}
// IPC need to be the first import to allow it to catch errors happening during
// the other imports
import startOperationStreamHandler from '../internal/operation-stream'
import '../polyfill/app-polyfills.ts'
import 'next/dist/server/require-hook'
import type { IncomingMessage } from 'node:http'
import type { RenderData } from 'types/turbopack'
import type { RenderOpts } from 'next/dist/server/app-render/types'
import { RSC_VARY_HEADER } from 'next/dist/client/components/app-router-headers'
import { headersFromEntries, initProxiedHeaders } from '../internal/headers'
import { parse, ParsedUrlQuery } from 'node:querystring'
import { PassThrough } from 'node:stream'
;('TURBOPACK { chunking-type: isolatedParallel }')
import entry from 'APP_ENTRY'
import BOOTSTRAP from 'APP_BOOTSTRAP'
import { createServerResponse } from '../internal/http'
import { createManifests, installRequireAndChunkLoad } from './app/manifest'
import { join } from 'node:path'
import { nodeFs } from 'next/dist/server/lib/node-fs-methods'
import { IncrementalCache } from 'next/dist/server/lib/incremental-cache'
const {
renderToHTMLOrFlight,
} = require('next/dist/compiled/next-server/app-page.runtime.dev')
installRequireAndChunkLoad()
const MIME_TEXT_HTML_UTF8 = 'text/html; charset=utf-8'
startOperationStreamHandler(async (renderData: RenderData, respond) => {
const result = await runOperation(renderData)
if (result == null) {
throw new Error('no html returned')
}
const channel = respond({
status: result.statusCode,
headers: result.headers,
})
for await (const chunk of result.body) {
channel.chunk(chunk as Buffer)
}
channel.end()
})
async function runOperation(renderData: RenderData) {
const { clientReferenceManifest } = createManifests()
const req: IncomingMessage = {
url: renderData.originalUrl,
method: renderData.method,
headers: initProxiedHeaders(
headersFromEntries(renderData.rawHeaders),
renderData.data?.serverInfo
),
} as any
const url = new URL(renderData.originalUrl, 'next://')
const res = createServerResponse(req, renderData.path)
const query = parse(renderData.rawQuery)
const renderOpt: Omit<
RenderOpts,
'App' | 'Document' | 'Component' | 'page'
> & {
params: ParsedUrlQuery
} = {
// TODO: give an actual buildId when next build is supported
buildId: 'development',
basePath: '',
params: renderData.params,
supportsDynamicHTML: true,
dev: true,
buildManifest: {
polyfillFiles: [],
rootMainFiles: BOOTSTRAP.filter((path) => path.endsWith('.js')),
devFiles: [],
ampDevFiles: [],
lowPriorityFiles: [],
pages: {
'/_app': [],
},
ampFirstPages: [],
},
ComponentMod: {
...entry,
__next_app__: {
require: __next_require__,
loadChunk: __next_chunk_load__,
},
pages: ['page.js'],
},
incrementalCache: new IncrementalCache({
fs: nodeFs,
dev: true,
requestHeaders: { ...req.headers },
requestProtocol: url.protocol.replace(/:$/, '') as 'http' | 'https',
appDir: true,
allowedRevalidateHeaderKeys: renderData.data?.allowedRevalidateHeaderKeys,
minimalMode: false,
serverDistDir: join(process.cwd(), '.next/server'),
fetchCache: true,
fetchCacheKeyPrefix: renderData.data?.fetchCacheKeyPrefix,
maxMemoryCacheSize: renderData.data?.isrMemoryCacheSize,
flushToDisk: false,
getPrerenderManifest: () => ({
version: 4,
routes: {},
dynamicRoutes: {},
preview: {
previewModeEncryptionKey: '',
previewModeId: '',
previewModeSigningKey: '',
},
notFoundRoutes: [],
}),
CurCacheHandler: undefined,
}),
clientReferenceManifest,
runtime: 'nodejs',
serverComponents: true,
assetPrefix: '',
pageConfig: {},
reactLoadableManifest: {},
nextConfigOutput: renderData.data?.nextConfigOutput,
}
const result = await renderToHTMLOrFlight(
req,
res,
renderData.path,
query,
renderOpt as any as RenderOpts
)
if (!result || result.isNull) throw new Error('rendering was not successful')
const body = new PassThrough()
if (result.isDynamic) {
result.pipe(body)
} else {
body.write(result.toUnchunkedString())
}
return {
statusCode: res.statusCode,
headers: [
['Content-Type', result.contentType ?? MIME_TEXT_HTML_UTF8],
['Vary', RSC_VARY_HEADER],
] as [string, string][],
body,
}
}
import { adapter } from 'next/dist/server/web/adapter'
import { RSC_VARY_HEADER } from 'next/dist/client/components/app-router-headers'
import { IncrementalCache } from 'next/dist/server/lib/incremental-cache'
import { renderToHTMLOrFlight } from 'next/dist/server/app-render/app-render'
;('TURBOPACK { chunking-type: isolatedParallel }')
import entry from 'APP_ENTRY'
import BOOTSTRAP from 'APP_BOOTSTRAP'
import { createManifests, installRequireAndChunkLoad } from './manifest'
import type { NextRequest, NextFetchEvent } from 'next/server'
import type { RenderOpts } from 'next/dist/server/app-render/types'
import type { ParsedUrlQuery } from 'querystring'
installRequireAndChunkLoad()
// avoid limiting stack traces to 10 lines
Error.stackTraceLimit = 100
const { clientReferenceManifest } = createManifests()
const MIME_TEXT_HTML_UTF8 = 'text/html; charset=utf-8'
async function render(request: NextRequest, event: NextFetchEvent) {
const renderOpt: Omit<
RenderOpts,
'App' | 'Document' | 'Component' | 'page'
> & { params: ParsedUrlQuery } = {
// TODO(WEB-1195) params
params: {},
supportsDynamicHTML: true,
dev: true,
buildId: 'development',
basePath: '',
buildManifest: {
polyfillFiles: [],
rootMainFiles: BOOTSTRAP.filter((path) => path.endsWith('.js')),
devFiles: [],
ampDevFiles: [],
lowPriorityFiles: [],
pages: {
'/_app': [],
},
ampFirstPages: [],
},
ComponentMod: {
...entry,
__next_app__: {
require: __next_require__,
loadChunk: __next_chunk_load__,
},
pages: ['page.js'],
},
clientReferenceManifest,
runtime: 'nodejs',
serverComponents: true,
assetPrefix: '',
pageConfig: {},
reactLoadableManifest: {},
// TODO nextConfigOutput
nextConfigOutput: undefined,
}
const tranform = new TransformStream()
const response = new Response(tranform.readable)
let { pathname, search: query } = new URL(request.url, 'next://')
const result = await renderToHTMLOrFlight(
// @ts-expect-error - TODO renderToHTMLOrFlight types should accept web platform types
request,
response,
pathname,
// TODO(WEB-1195) query
{},
renderOpt as any as RenderOpts
)
response.headers.append(
'Content-Type',
result.contentType || MIME_TEXT_HTML_UTF8
)
response.headers.append('Vary', RSC_VARY_HEADER)
const writer = tranform.writable.getWriter()
let innerClose: undefined | (() => void)
const target = {
write: (chunk: Uint8Array) => writer.write(chunk),
end: () => writer.close(),
on(_event: 'close', cb: () => void) {
innerClose = cb
},
off(_event: 'close', _cb: () => void) {
innerClose = undefined
},
}
const onClose = () => {
innerClose?.()
}
// No, this cannot be replaced with `finally`, because early cancelling
// the stream will create a rejected promise, and finally will create an
// unhandled rejection.
writer.closed.then(onClose, onClose)
result.pipe(target)
return response
}
// adapter uses this to detect edge rendering
self.__BUILD_MANIFEST = {}
// @ts-expect-error - exposed for edge support
globalThis._ENTRIES = {
middleware_edge: {
default: function (opts: any) {
return adapter({
...opts,
IncrementalCache,
handler: render,
})
},
},
}
import { EdgeRouteModuleWrapper } from 'next/dist/server/web/edge-route-module-wrapper'
import { AppRouteRouteModule } from 'next/dist/server/future/route-modules/app-route/module'
import { RouteKind } from 'next/dist/server/future/route-kind'
import * as userland from 'ENTRY'
import { PAGE, PATHNAME } from 'BOOTSTRAP_CONFIG'
// TODO: (wyattjoh) - perform the option construction in Rust to allow other modules to accept different options
const routeModule = new AppRouteRouteModule({
userland,
definition: {
kind: RouteKind.APP_ROUTE,
page: PAGE,
pathname: PATHNAME,
// The following aren't used in production.
filename: '',
bundlePath: '',
},
resolvedPagePath: `app/${PAGE}`,
nextConfigOutput: undefined,
})
// @ts-expect-error - exposed for edge support
globalThis._ENTRIES = {
middleware_edge: {
default: EdgeRouteModuleWrapper.wrap(routeModule, {
page: `/${PAGE}`,
}),
},
}
// IPC need to be the first import to allow it to catch errors happening during
// the other imports
import startHandler from '../../internal/api-server-handler'
import 'next/dist/server/node-polyfill-fetch.js'
import { join } from 'path'
import { parse as parseUrl } from 'node:url'
import {
NodeNextRequest,
NodeNextResponse,
} from 'next/dist/server/base-http/node'
import { runEdgeFunction, updateResponse } from '../../internal/edge'
import { attachRequestMeta } from '../../internal/next-request-helpers'
import chunkGroup from 'ROUTE_CHUNK_GROUP'
startHandler(async ({ request, response, query, params, path }) => {
const req = new NodeNextRequest(request)
const res = new NodeNextResponse(response)
const parsedUrl = parseUrl(req.url!, true)
attachRequestMeta(req, parsedUrl, request.headers.host!)
const edgeInfo = {
name: 'edge',
paths: chunkGroup.map((chunk) =>
join(process.cwd(), '.next/server/app', chunk)
),
wasm: [],
env: Object.keys(process.env),
assets: [],
}
const result = await runEdgeFunction({
edgeInfo,
outputDir: 'app',
req,
query,
params,
path,
onWarning(warning) {
console.warn(warning)
},
})
updateResponse(res, result)
})
import ReactDOMClient from 'react-dom/client'
import React, { use } from 'react'
import type { ReactElement } from 'react'
import { version } from 'next/package.json'
import { createFromReadableStream } from 'next/dist/compiled/react-server-dom-webpack/client'
import { callServer } from 'next/dist/client/app-call-server'
import { linkGc } from 'next/dist/client/app-link-gc'
import { HeadManagerContext } from 'next/dist/shared/lib/head-manager-context.shared-runtime'
import { initializeHMR } from '@vercel/turbopack-next/dev/client'
initializeHMR({
assetPrefix: '',
})
window.next = {
version,
appDir: true,
}
globalThis.__next_require__ = (data) => {
const [client_id] = JSON.parse(data)
return __turbopack_require__(client_id)
}
globalThis.__next_chunk_load__ = __turbopack_load__
const appElement = document
const getCacheKey = () => {
const { pathname, search } = location
return pathname + search
}
const encoder = new TextEncoder()
let initialServerDataBuffer: string[] | undefined = undefined
let initialServerDataWriter: ReadableStreamDefaultController | undefined =
undefined
let initialServerDataLoaded = false
let initialServerDataFlushed = false
let initialFormStateData: null | any = null
function nextServerDataCallback(
seg:
| [isBootStrap: 0]
| [isNotBootstrap: 1, responsePartial: string]
| [isFormState: 2, formState: any]
): number {
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]
}
return 0
}
function nextServerDataRegisterWriter(ctr: ReadableStreamDefaultController) {
if (initialServerDataBuffer) {
initialServerDataBuffer.forEach((val) => {
ctr.enqueue(encoder.encode(val))
})
if (initialServerDataLoaded && !initialServerDataFlushed) {
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 {
DOMContentLoaded()
}
const nextServerDataLoadingGlobal = (self.__next_f = self.__next_f || [])
nextServerDataLoadingGlobal.forEach(nextServerDataCallback)
nextServerDataLoadingGlobal.push = nextServerDataCallback
function createResponseCache() {
return new Map()
}
const rscCache = createResponseCache()
function useInitialServerResponse(cacheKey: string) {
const response = rscCache.get(cacheKey)
if (response) return response
const readable = new ReadableStream({
start(controller) {
nextServerDataRegisterWriter(controller)
},
})
const newResponse = createFromReadableStream(readable, { callServer })
rscCache.set(cacheKey, newResponse)
return newResponse
}
function ServerRoot({ cacheKey }: { cacheKey: string }) {
React.useEffect(() => {
rscCache.delete(cacheKey)
})
const response = useInitialServerResponse(cacheKey)
const root = use(response) as ReactElement
return root
}
function RSCComponent() {
const cacheKey = getCacheKey()
return <ServerRoot cacheKey={cacheKey} />
}
function hydrate() {
const reactEl = (
<React.StrictMode>
<HeadManagerContext.Provider
value={{
appDir: true,
}}
>
<RSCComponent />
</HeadManagerContext.Provider>
</React.StrictMode>
)
const isError = document.documentElement.id === '__next_error__'
if (isError) {
// cast necessary because of a typing bug
const reactRoot = ReactDOMClient.createRoot(
appElement as unknown as DocumentFragment
)
reactRoot.render(reactEl)
} else {
React.startTransition(() => {
;(ReactDOMClient as any).hydrateRoot(appElement, reactEl, {
experimental_formState: initialFormStateData,
})
})
}
linkGc()
}
window.next = {
version: 'turbo',
appDir: true,
}
hydrate()
// this file is just here to make typescript happy about the wrapped/virtual assets (import ".")
declare var Anything: any
export = Anything
export const __turbopack_module_id__: string | number
export const chunks: string[]
import type { ClientReferenceManifest } from 'next/dist/build/webpack/plugins/flight-manifest-plugin'
export function createManifests() {
const proxyMethodsForModule = (
id: string
): ProxyHandler<ClientReferenceManifest['ssrModuleMapping']> => {
return {
get(_target, prop: string) {
return {
id,
chunks: JSON.parse(id)[1],
name: prop,
}
},
}
}
const availableModules = new Set()
const toPath = (chunk: ChunkData) =>
typeof chunk === 'string' ? chunk : chunk.path
/// determines if a chunk is needed based on the current available modules
const filterAvailable = (chunk: ChunkData) => {
if (typeof chunk === 'string') {
return true
} else {
let includedList = chunk.included || []
if (includedList.length === 0) {
return true
}
let needed = false
for (const item of includedList) {
if (!availableModules.has(item)) {
availableModules.add(item)
needed = true
}
}
return needed
}
}
const proxyMethodsNested = (
type: 'ssrModuleMapping' | 'clientModules' | 'entryCSSFiles'
): ProxyHandler<
| ClientReferenceManifest['ssrModuleMapping']
| ClientReferenceManifest['clientModules']
| ClientReferenceManifest['entryCSSFiles']
> => {
return {
get(_target, key: string) {
if (type === 'ssrModuleMapping') {
return new Proxy({}, proxyMethodsForModule(key as string))
}
if (type === 'clientModules') {
// The key is a `${file}#${name}`, but `file` can contain `#` itself.
// There are 2 possibilities:
// "file#" => id = "file", name = ""
// "file#foo" => id = "file", name = "foo"
const pos = key.lastIndexOf('#')
let id = key
let name = ''
if (pos !== -1) {
id = key.slice(0, pos)
name = key.slice(pos + 1)
} else {
throw new Error('keys need to be formatted as {file}#{name}')
}
return {
id,
name,
chunks: JSON.parse(id)[1],
}
}
if (type === 'entryCSSFiles') {
const cssChunks = JSON.parse(key)
// TODO(WEB-856) subscribe to changes
return cssChunks.filter(filterAvailable).map(toPath)
}
},
}
}
const proxyMethods = (): ProxyHandler<ClientReferenceManifest> => {
const clientModulesProxy = new Proxy(
{},
proxyMethodsNested('clientModules')
)
const ssrModuleMappingProxy = new Proxy(
{},
proxyMethodsNested('ssrModuleMapping')
)
const entryCSSFilesProxy = new Proxy(
{},
proxyMethodsNested('entryCSSFiles')
)
return {
get(_target: any, prop: string) {
if (prop === 'ssrModuleMapping') {
return ssrModuleMappingProxy
}
if (prop === 'clientModules') {
return clientModulesProxy
}
if (prop === 'entryCSSFiles') {
return entryCSSFilesProxy
}
},
}
}
const clientReferenceManifest: ClientReferenceManifest = new Proxy(
{} as any,
proxyMethods()
)
return { clientReferenceManifest }
}
export function installRequireAndChunkLoad() {
globalThis.__next_require__ = (data) => {
const [, , ssr_id] = JSON.parse(data)
return __turbopack_require__(ssr_id)
}
globalThis.__next_chunk_load__ = () => Promise.resolve()
}
// IPC need to be the first import to allow it to catch errors happening during
// the other imports
import startHandler from '../../internal/nodejs-proxy-handler'
import AppRouteRouteModule from 'next/dist/server/future/route-modules/app-route/module'
import { RouteKind } from 'next/dist/server/future/route-kind'
import * as userland from 'ENTRY'
import { PAGE, PATHNAME } from 'BOOTSTRAP_CONFIG'
const routeModule = new AppRouteRouteModule({
userland,
definition: {
kind: RouteKind.APP_ROUTE,
page: PAGE,
pathname: PATHNAME,
// The following aren't used in production.
filename: '',
bundlePath: '',
},
resolvedPagePath: `app/${PAGE}`,
nextConfigOutput: undefined,
})
startHandler(routeModule)
declare module 'CLIENT_MODULE' {
export const __turbopack_module_id__: string
}
declare module 'CLIENT_CHUNKS' {
const moduleId: string
export default moduleId
export const chunks: any[]
}
/// <reference path="./server-to-client-ssr.d.ts" />
import { createProxy } from 'next/dist/build/webpack/loaders/next-flight-loader/module-proxy'
;('TURBOPACK { chunking-type: isolatedParallel }')
import { __turbopack_module_id__ as id } from 'CLIENT_MODULE'
import client_id, { chunks } from 'CLIENT_CHUNKS'
export default createProxy(JSON.stringify([client_id, chunks, id]))
declare module 'CLIENT_CHUNKS' {
const moduleId: string
export default moduleId
export const chunks: any[]
}
/// <reference path="./server-to-client.d.ts" />
import { createProxy } from 'next/dist/build/webpack/loaders/next-flight-loader/module-proxy'
import client_id, { chunks } from 'CLIENT_CHUNKS'
export default createProxy(JSON.stringify([client_id, chunks]))
import 'next/dist/server/web/globals'
import { adapter } from 'next/dist/server/web/adapter'
import { NAME, PAGE } from 'BOOTSTRAP_CONFIG'
var mod = require('ENTRY')
var handler = mod.middleware || mod.default
if (typeof handler !== 'function') {
throw new Error(
`The Edge Function "pages/${PAGE}" must export a \`default\` function`
)
}
// @ts-ignore
globalThis._ENTRIES = {
[`middleware_${NAME}`]: {
default: function (opts: any) {
return adapter({
...opts,
page: `/${PAGE}`,
handler,
})
},
},
}
// TODO(alexkirsz) export * would be preferrable here once supported.
export {
default,
// @ts-expect-error
getStaticProps,
// @ts-expect-error
__N_SSG,
// @ts-expect-error
__N_SSP,
} from '@vercel/turbopack-next/pages/_error'
import '../internal/shims-client'
import { createRoot } from 'react-dom/client'
import { initializeHMR, ReactDevOverlay } from '../dev/client'
import { subscribeToUpdate } from '@vercel/turbopack-ecmascript-runtime/dev/client/hmr-client'
import { sendMessage } from '@vercel/turbopack-ecmascript-runtime/dev/client/websocket'
const pageChunkPath = location.pathname.slice(1)
subscribeToUpdate(
{
path: pageChunkPath,
headers: {
accept: 'text/html',
},
},
sendMessage,
(update) => {
if (update.type === 'restart' || update.type === 'notFound') {
location.reload()
}
}
)
initializeHMR({
assetPrefix: '',
})
const el = document.getElementById('__next')!
const innerHtml = {
__html: el.innerHTML,
}
createRoot(el).render(
<ReactDevOverlay>
<div dangerouslySetInnerHTML={innerHtml}></div>
</ReactDevOverlay>
)
// this file is just here to make typescript happy about the wrapped/virtual assets (import ".")
declare var Anything: any
export = Anything
;((manifest) => {
// adapted from https://github.com/vercel/next.js/blob/canary/packages/next/src/build/webpack/plugins/build-manifest-plugin.ts#L54-L54
function processRoute(rewrite) {
// omit external rewrite destinations since these aren't
// handled client-side
if (!rewrite.destination.startsWith('/')) {
delete rewrite.destination
}
return rewrite
}
manifest.__rewrites.beforeFiles.map(processRoute)
manifest.__rewrites.afterFiles.map(processRoute)
manifest.__rewrites.fallback.map(processRoute)
self.__BUILD_MANIFEST = manifest
self.__BUILD_MANIFEST_CB && self.__BUILD_MANIFEST_CB()
})($$MANIFEST$$)
import '../internal/shims-client'
import { initialize, hydrate, router, emitter, version } from 'next/dist/client'
import type { Router } from 'next/dist/client/router'
import {
assign,
urlQueryToSearchParams,
} from 'next/dist/shared/lib/router/utils/querystring'
import { formatWithValidation } from 'next/dist/shared/lib/router/utils/format-url'
import { initializeHMR } from '../dev/client'
import { subscribeToUpdate } from '@vercel/turbopack-ecmascript-runtime/dev/client/hmr-client'
import { sendMessage } from '@vercel/turbopack-ecmascript-runtime/dev/client/websocket'
;(self as any).__next_set_public_path__ = () => {}
async function loadPageChunk(assetPrefix: string, chunkData: ChunkData) {
if (typeof chunkData === 'string') {
const fullPath = assetPrefix + chunkData
await __turbopack_load__(fullPath)
} else {
let fullChunkData = {
...chunkData,
path: assetPrefix + chunkData.path,
}
await __turbopack_load__(fullChunkData)
}
}
;(async () => {
console.debug('Initializing Next.js')
window.next = {
version: version || '',
get router() {
return router
},
emitter,
}
const { assetPrefix } = await initialize({
devClient: {
// Expected when `process.env.NODE_ENV === 'development'`
onUnrecoverableError() {},
},
})
initializeHMR({
assetPrefix,
})
// for the page loader
window.__turbopack_load_page_chunks__ = (page, chunksData) => {
const chunkPromises = chunksData.map(loadPageChunk.bind(null, assetPrefix))
Promise.all(chunkPromises).catch((err) =>
console.error('failed to load chunks for page ' + page, err)
)
}
const pagePath = window.__NEXT_DATA__.page
window.__NEXT_P.push([
'/_app',
() => require('@vercel/turbopack-next/pages/_app'),
])
window.__NEXT_P.push([pagePath, () => require('PAGE')])
console.debug('Hydrating the page')
await hydrate({})
// This needs to happen after hydration because the router is initialized
// during hydration. To make this dependency clearer, we pass `router` as an
// explicit argument instead of relying on the `router` import binding.
subscribeToCurrentPageData({ assetPrefix, router })
subscribeToPageManifest({ assetPrefix })
console.debug('The page has been hydrated')
})().catch((err) => console.error(err))
function subscribeToPageManifest({ assetPrefix }: { assetPrefix: string }) {
// adapted from https://github.com/vercel/next.js/blob/836ac9cc7f290e95b564a61341fa95a5f4f0327e/packages/next/src/client/next-dev.ts#L57
subscribeToUpdate(
{
path: '_next/static/development/_devPagesManifest.json',
},
sendMessage,
(update) => {
if (['restart', 'notFound', 'partial'].includes(update.type)) {
return
}
fetch(`${assetPrefix}/_next/static/development/_devPagesManifest.json`)
.then((res) => res.json())
.then((manifest) => {
window.__DEV_PAGES_MANIFEST = manifest
})
.catch((err) => {
console.log(`Failed to fetch devPagesManifest`, err)
})
}
)
}
/**
* Subscribes to the current page's data updates from the HMR server.
*
* Updates on route change.
*/
function subscribeToCurrentPageData({
router,
assetPrefix,
}: {
router: Router
assetPrefix: string
}) {
let dataPath = getCurrentPageDataHref()
let unsubscribe = subscribeToPageData({
router,
dataPath,
assetPrefix,
})
router.events.on('routeChangeComplete', () => {
const nextDataPath = getCurrentPageDataHref()
if (dataPath === nextDataPath) {
return
}
dataPath = nextDataPath
unsubscribe()
unsubscribe = subscribeToPageData({
router,
dataPath,
assetPrefix,
})
})
}
function getCurrentPageDataHref(): string {
return router.pageLoader.getDataHref({
asPath: router.asPath,
href: formatWithValidation({
// No need to pass `router.query` when `skipInterpolation` is true.
pathname: router.pathname,
}),
skipInterpolation: true,
})
}
/**
* TODO(alexkirsz): Handle assetPrefix/basePath.
*/
function subscribeToPageData({
router,
dataPath,
assetPrefix,
}: {
router: Router
dataPath: string
assetPrefix: string
}): () => void {
return subscribeToUpdate(
{
// We need to remove the leading / from the data path as Turbopack
// resources are not prefixed with a /.
path: dataPath.slice(1),
headers: {
// This header is used by the Next.js server to determine whether this
// is a data request.
'x-nextjs-data': '1',
},
},
sendMessage,
(update) => {
if (update.type !== 'restart') {
return
}
// This triggers a reload of the page data.
// Adapted from next.js/packages/next/client/next-dev.js.
router
.replace(
router.pathname +
'?' +
String(
assign(
urlQueryToSearchParams(router.query),
new URLSearchParams(location.search)
)
),
router.asPath,
{ scroll: false }
)
.catch(() => {
// trigger hard reload when failing to refresh data
// to show error overlay properly
location.reload()
})
}
)
}
import type { Ipc, StructuredError } from '@vercel/turbopack-node/ipc/index'
import type { IncomingMessage } from 'node:http'
import { Buffer } from 'node:buffer'
import { createServer, makeRequest, type ServerInfo } from '../internal/server'
import { toPairs } from '../internal/headers'
import { makeResolver } from 'next/dist/server/lib/route-resolver'
import loadConfig from 'next/dist/server/config'
import { PHASE_DEVELOPMENT_SERVER } from 'next/dist/shared/lib/constants'
import 'next/dist/server/node-polyfill-fetch.js'
import middlewareChunkGroup from 'MIDDLEWARE_CHUNK_GROUP'
import middlewareConfig from 'MIDDLEWARE_CONFIG'
type Resolver = Awaited<
ReturnType<typeof import('next/dist/server/lib/route-resolver').makeResolver>
>
type RouterRequest = {
method: string
pathname: string
rawHeaders: [string, string][]
rawQuery: string
body: number[][]
}
type IpcOutgoingMessage = {
type: 'value'
data: string | Buffer
}
type MessageData =
| { type: 'middleware-headers'; data: MiddlewareHeadersResponse }
| { type: 'middleware-body'; data: Uint8Array }
| {
type: 'rewrite'
data: RewriteResponse
}
| {
type: 'error'
error: StructuredError
}
| { type: 'none' }
type RewriteResponse = {
url: string
headers: [string, string][]
}
type MiddlewareHeadersResponse = {
statusCode: number
headers: [string, string][]
}
let resolveRouteMemo: Promise<Resolver>
async function getResolveRoute(
dir: string,
serverInfo: ServerInfo
): Promise<Resolver> {
const nextConfig = await loadConfig(PHASE_DEVELOPMENT_SERVER, process.cwd())
const middlewareCfg = {
files: middlewareChunkGroup.filter((f) => /\.[mc]?js$/.test(f)),
matcher: middlewareConfig.matcher,
}
return await makeResolver(dir, nextConfig, middlewareCfg, serverInfo)
}
export default async function route(
ipc: Ipc<RouterRequest, IpcOutgoingMessage>,
routerRequest: RouterRequest,
dir: string,
serverInfo: ServerInfo
) {
const [resolveRoute, server] = await Promise.all([
(resolveRouteMemo ??= getResolveRoute(dir, serverInfo)),
createServer(),
])
try {
const {
clientRequest,
clientResponsePromise,
serverRequest,
serverResponse,
} = await makeRequest(
server,
routerRequest.method,
routerRequest.pathname,
routerRequest.rawQuery,
routerRequest.rawHeaders,
serverInfo
)
const body = Buffer.concat(
routerRequest.body.map((arr) => Buffer.from(arr))
)
// Send the clientRequest, so the server parses everything. We can then pass
// the serverRequest to Next.js to handle.
clientRequest.end(body)
// The route promise must not block us from starting the middleware
// response handling, so we cannot await it yet. By making the call, we
// allow Next.js to start writing to the response whenever it's ready.
const routePromise = resolveRoute(serverRequest, serverResponse)
// Now that the Next.js has started processing the route, the middleware
// response promise will resolve once they write data and then we can begin
// streaming.
// We again cannot await directly on the promise, because an error may
// occur in the routePromise while we're waiting.
const middlewarePromise = clientResponsePromise.then((c) =>
handleMiddlewareResponse(ipc, c)
)
// Now that both promises are in progress, we await both so that a
// rejection in either will end the routing.
const [routeResult] = await Promise.all([routePromise, middlewarePromise])
server.close()
if (routeResult) {
switch (routeResult.type) {
case 'none':
case 'error':
return routeResult
case 'rewrite':
return {
type: 'rewrite',
data: {
url: routeResult.url,
headers: Object.entries(routeResult.headers)
.filter(([, val]) => val != null)
.map(([name, value]) => [name, value!.toString()]),
},
}
default:
// @ts-expect-error data.type is never
throw new Error(`unknown route result type: ${data.type}`)
}
}
} catch (e) {
// Server doesn't need to be closed, because the sendError will terminate
// the process.
ipc.sendError(e as Error)
}
}
async function handleMiddlewareResponse(
ipc: Ipc<RouterRequest, IpcOutgoingMessage>,
clientResponse: IncomingMessage
): Promise<void> {
// If this header is specified, we know that the response was not handled by
// middleware. The headers and body of the response are useless.
if (clientResponse.headers['x-nextjs-route-result']) {
return
}
const responseHeaders: MiddlewareHeadersResponse = {
statusCode: clientResponse.statusCode!,
headers: toPairs(clientResponse.rawHeaders),
}
await ipc.send({
type: 'value',
data: JSON.stringify({
type: 'middleware-headers',
data: responseHeaders,
}),
})
for await (const chunk of clientResponse) {
await ipc.send({
type: 'value',
data: JSON.stringify({
type: 'middleware-body',
data: (chunk as Buffer).toJSON().data,
}),
})
}
}
// IPC need to be the first import to allow it to catch errors happening during
// the other imports
import startHandler from '../internal/api-server-handler'
import 'next/dist/server/node-polyfill-fetch.js'
import { parse as parseQuery } from 'node:querystring'
import { parse as parseUrl } from 'node:url'
import { apiResolver } from 'next/dist/server/api-utils/node'
import {
NodeNextRequest,
NodeNextResponse,
} from 'next/dist/server/base-http/node'
import { attachRequestMeta } from '../internal/next-request-helpers'
import * as allExports from 'INNER'
startHandler(({ request, response, query, params, path }) => {
const parsedQuery = parseQuery(query)
const mergedQuery = { ...parsedQuery, ...params }
// This enables `req.cookies` in API routes.
const req = new NodeNextRequest(request)
const res = new NodeNextResponse(response)
const parsedUrl = parseUrl(req.url!, true)
attachRequestMeta(req, parsedUrl, request.headers.host!)
return apiResolver(
req.originalRequest,
res.originalResponse,
mergedQuery,
allExports,
{
previewModeId: '',
previewModeEncryptionKey: '',
previewModeSigningKey: '',
},
false,
true,
path
)
})
// IPC need to be the first import to allow it to catch errors happening during
// the other imports
import startHandler from '../internal/page-server-handler'
// eslint-disable-next-line
import Document from 'next/document'
import App from 'next/app'
startHandler({
isDataReq: true,
App,
Document,
mod: () => {
return import('INNER').then((namespace) => ({
Component: () => null,
namespace,
}))
},
})
// IPC need to be the first import to allow it to catch errors happening during
// the other imports
import startHandler from '../internal/api-server-handler'
import 'next/dist/server/node-polyfill-fetch.js'
import { join } from 'node:path'
import { parse as parseUrl } from 'node:url'
import {
NodeNextRequest,
NodeNextResponse,
} from 'next/dist/server/base-http/node'
import { attachRequestMeta } from '../internal/next-request-helpers'
import { runEdgeFunction, updateResponse } from '../internal/edge'
import chunkGroup from 'INNER_EDGE_CHUNK_GROUP'
startHandler(async ({ request, response, query, params, path }) => {
const req = new NodeNextRequest(request)
const res = new NodeNextResponse(response)
const parsedUrl = parseUrl(req.url!, true)
attachRequestMeta(req, parsedUrl, request.headers.host!)
const edgeInfo = {
name: 'edge',
paths: chunkGroup.map((chunk: string) =>
join(process.cwd(), '.next/server/pages', chunk)
),
wasm: [],
env: Object.keys(process.env),
assets: [],
}
const result = await runEdgeFunction({
edgeInfo,
outputDir: 'pages',
req,
query,
params,
path,
onWarning(warning) {
console.warn(warning)
},
})
await updateResponse(res, result)
})
// IPC need to be the first import to allow it to catch errors happening during
// the other imports
import startHandler from '../internal/page-server-handler'
import Document from '@vercel/turbopack-next/pages/_document'
import App from '@vercel/turbopack-next/pages/_app'
import chunkGroup from 'INNER_CLIENT_CHUNK_GROUP'
startHandler({
isDataReq: false,
App,
Document,
mod: () => {
return import('INNER').then((namespace) => ({
Component: namespace.default as any,
namespace,
}))
},
chunkGroup,
})
// IPC need to be the first import to allow it to catch errors happening during
// the other imports
import startOperationStreamHandler from './operation-stream'
import type { ClientRequest, IncomingMessage, Server } from 'node:http'
import type { ServerResponse } from 'node:http'
import { Buffer } from 'node:buffer'
import type { RenderData } from 'types/turbopack'
import { createServer, makeRequest } from '../internal/server'
import { toPairs } from '../internal/headers'
type Handler = (data: {
request: IncomingMessage
response: ServerResponse<IncomingMessage>
query: string
params: Record<string, string | string[]>
path: string
}) => Promise<void>
type Operation = {
clientRequest: ClientRequest
clientResponsePromise: Promise<IncomingMessage>
apiOperation: Promise<void>
server: Server
}
type ResponseHeaders = {
status: number
headers: [string, string][]
}
export default function startHandler(handler: Handler): void {
startOperationStreamHandler(
async (renderData: RenderData, respond, reportError) => {
const operationPromise = (async function createOperation() {
const server = await createServer()
const {
clientRequest,
clientResponsePromise,
serverRequest,
serverResponse,
} = await makeRequest(
server,
renderData.method,
renderData.path,
renderData.rawQuery,
renderData.rawHeaders,
renderData.data?.serverInfo
)
return {
clientRequest,
server,
clientResponsePromise,
apiOperation: handler({
request: serverRequest,
response: serverResponse,
query: renderData.rawQuery,
params: renderData.params,
path: renderData.path,
}),
}
})()
function handleClientResponse(
server: Server,
clientResponse: IncomingMessage
) {
const responseHeaders: ResponseHeaders = {
status: clientResponse.statusCode!,
headers: toPairs(clientResponse.rawHeaders),
}
const channel = respond(responseHeaders)
clientResponse.on('data', (chunk) => {
channel.chunk(chunk)
})
clientResponse.once('end', () => {
channel.end()
server.close()
})
clientResponse.once('error', (err) => {
reportError(err)
})
}
/**
* Ends an operation by writing the response body to the client and waiting for the Next.js API resolver to finish.
*/
async function endOperation(operation: Operation, body: Buffer) {
operation.clientRequest.end(body)
try {
await operation.apiOperation
} catch (error) {
await reportError(error)
return
}
}
return {
streamRequest: false,
onBody: async (body) => {
const operation = await operationPromise
await Promise.all([
endOperation(operation, body),
operation.clientResponsePromise.then((clientResponse) =>
handleClientResponse(operation.server, clientResponse)
),
])
},
}
}
)
}
import { join } from 'path'
import type {
BaseNextRequest,
BaseNextResponse,
} from 'next/dist/server/base-http'
import type {
NodeNextRequest,
NodeNextResponse,
} from 'next/dist/server/base-http/node'
import { parse, ParsedUrlQuery } from 'querystring'
import type { Params } from 'next/dist/shared/lib/router/utils/route-matcher'
import type { FetchEventResult } from 'next/dist/server/web/types'
import { getCloneableBody } from 'next/dist/server/body-streams'
// This is an adapted version of a similar function in next-dev-server.
// TODO exposes this method from next.js instead
export async function runEdgeFunction({
edgeInfo,
outputDir,
req,
query,
params,
path,
onWarning,
}: {
edgeInfo: {
name: string
paths: string[]
wasm: unknown[]
env: unknown[]
assets: unknown[]
}
outputDir: string
req: BaseNextRequest | NodeNextRequest
query: string
path: string
params: Params | undefined
onWarning?: (warning: Error) => void
}): Promise<FetchEventResult> {
// For edge to "fetch" we must always provide an absolute URL
const initialUrl = new URL(path, 'http://n')
const parsedQuery = parse(query)
const queryString = urlQueryToSearchParams({
...Object.fromEntries(initialUrl.searchParams),
...parsedQuery,
}).toString()
initialUrl.search = queryString
const url = initialUrl.toString()
if (!url.startsWith('http')) {
throw new Error(
'To use middleware you must provide a `hostname` and `port` to the Next.js Server'
)
}
const { run } = require('next/dist/server/web/sandbox')
const result = (await run({
distDir: join(process.cwd(), '.next/server', outputDir),
name: edgeInfo.name,
paths: edgeInfo.paths,
env: edgeInfo.env,
edgeFunctionEntry: edgeInfo,
request: {
headers: req.headers,
method: req.method,
nextConfig: {
basePath: '/',
i18n: undefined,
trailingSlash: true,
},
url,
page: {
name: path,
...(params && { params: params }),
},
body: getCloneableBody(req.body),
},
useCache: false,
onWarning,
})) as FetchEventResult
return result
}
export async function updateResponse(
response: BaseNextResponse<any> | NodeNextResponse,
result: FetchEventResult
) {
response.statusCode = result.response.status
response.statusMessage = result.response.statusText
result.response.headers.forEach((value: string, key) => {
// the append handling is special cased for `set-cookie`
if (key.toLowerCase() === 'set-cookie') {
response.setHeader(key, value)
} else {
response.appendHeader(key, value)
}
})
if (result.response.body) {
// TODO(gal): not sure that we always need to stream
const nodeResStream = (response as NodeNextResponse).originalResponse
const {
consumeUint8ArrayReadableStream,
} = require('next/dist/compiled/edge-runtime')
try {
for await (const chunk of consumeUint8ArrayReadableStream(
result.response.body
)) {
nodeResStream.write(chunk)
}
} finally {
nodeResStream.end()
}
} else {
;(response as NodeNextResponse).originalResponse.end()
}
}
function stringifyUrlQueryParam(param: unknown): string {
if (
typeof param === 'string' ||
(typeof param === 'number' && !isNaN(param)) ||
typeof param === 'boolean'
) {
return String(param)
} else {
return ''
}
}
function urlQueryToSearchParams(urlQuery: ParsedUrlQuery): URLSearchParams {
const result = new URLSearchParams()
Object.entries(urlQuery).forEach(([key, value]) => {
if (Array.isArray(value)) {
value.forEach((item) => result.append(key, stringifyUrlQueryParam(item)))
} else {
result.set(key, stringifyUrlQueryParam(value))
}
})
return result
}
import { ServerInfo } from './server'
export type Headers = Record<string, string | string[]>
/**
* Converts an array of raw header entries to a map of header names to values.
*/
export function headersFromEntries(entries: Array<[string, string]>): Headers {
const headers: Record<string, string | string[]> = Object.create(null)
for (const [key, value] of entries) {
if (key in headers) {
const prevValue = headers[key]
if (typeof prevValue === 'string') {
headers[key] = [prevValue, value]
} else {
prevValue.push(value)
}
} else {
headers[key] = value
}
}
return headers
}
/**
* Transforms an array of elements into an array of pairs of elements.
*
* ## Example
*
* ```ts
* toPairs(["a", "b", "c", "d"]) // => [["a", "b"], ["c", "d"]]
* ```
*/
export function toPairs<T>(arr: T[]): Array<[T, T]> {
if (arr.length % 2 !== 0) {
throw new Error('toPairs: expected an even number of elements')
}
const pairs: Array<[T, T]> = []
for (let i = 0; i < arr.length; i += 2) {
pairs.push([arr[i], arr[i + 1]])
}
return pairs
}
/**
* These headers are provided by default to match the http-proxy behavior
* https://github.com/http-party/node-http-proxy/blob/9b96cd72/lib/http-proxy/passes/web-incoming.js#L58-L86
*/
export function initProxiedHeaders(
headers: Headers,
proxiedFor: ServerInfo | null | undefined
): Headers {
const hostname = proxiedFor?.hostname || 'localhost'
const port = String(proxiedFor?.port || 3000)
headers['x-forwarded-for'] = proxiedFor?.ip || '::1'
headers['x-forwarded-host'] = `${hostname}:${port}`
headers['x-forwarded-port'] = port
headers['x-forwarded-proto'] = proxiedFor?.protocol || 'http'
return headers
}
import type { IncomingMessage, ServerResponse } from 'node:http'
/**
* Shim for Node.js's http.ServerResponse
*
* @type {ServerResponse}
*/
class ServerResponseShim {
headersSent = false
#headers: Map<string, number | string | ReadonlyArray<string>> = new Map()
#statusCode: number = 200
req: IncomingMessage
constructor(req: IncomingMessage) {
this.req = req
}
setHeader(name: string, value: number | string | ReadonlyArray<string>) {
this.#headers.set(name.toLowerCase(), value)
return this
}
getHeader(name: string) {
return this.#headers.get(name.toLowerCase())
}
getHeaderNames() {
return Array.from(this.#headers.keys())
}
getHeaders() {
return Object.fromEntries(this.#headers)
}
hasHeader(name: string) {
return this.#headers.has(name.toLowerCase())
}
removeHeader(name: string) {
this.#headers.delete(name.toLowerCase())
}
get statusCode() {
return this.#statusCode
}
set statusCode(code) {
this.#statusCode = code
}
get statusMessage() {
throw new Error('statusMessage is not implemented')
}
set statusMessage(message) {
throw new Error('set statusMessage is not implemented')
}
get socket() {
throw new Error('socket is not implemented')
}
get sendDate() {
throw new Error('sendDate is not implemented')
}
flushHeaders() {
throw new Error('flushHeaders is not implemented')
}
end() {
throw new Error('end is not implemented')
}
cork() {
throw new Error('cork is not implemented')
}
uncork() {
throw new Error('uncork is not implemented')
}
addTrailers() {
throw new Error('addTrailers is not implemented')
}
setTimeout(_msecs: any, _callback: any) {
throw new Error('setTimeout is not implemented')
}
get writableEnded() {
throw new Error('writableEnded is not implemented')
}
get writableFinished() {
throw new Error('writableFinished is not implemented')
}
write(_chunk: any, _encoding: any, _callback: any) {
throw new Error('write is not implemented')
}
writeContinue() {
throw new Error('writeContinue is not implemented')
}
writeHead(_statusCode: any, _statusMessage: any, _headers: any) {
throw new Error('writeHead is not implemented')
}
writeProcessing() {
throw new Error('writeProcessing is not implemented')
}
}
function getStatusCodeForPath(pathname: string): number {
if (pathname === '/404' || pathname === '/_error') {
return 404
}
return 200
}
/**
* Creates a `ServerResponse` object for a given request and pathname.
*/
export function createServerResponse(
req: IncomingMessage,
pathname: string
): ServerResponse {
const statusCode = getStatusCodeForPath(pathname)
const res = new ServerResponseShim(req) as any
// For pages, setting the status code on the response object is necessary for
// `Error.getInitialProps` to detect the status code.
res.statusCode = statusCode
return res as ServerResponse
}
import { TLSSocket } from 'tls'
import {
addRequestMeta,
NextUrlWithParsedQuery,
} from 'next/dist/server/request-meta'
import { NodeNextRequest } from 'next/dist/server/base-http/node'
import { BaseNextRequest } from 'next/dist/server/base-http'
import { getCloneableBody } from 'next/dist/server/body-streams'
import { formatHostname } from 'next/dist/server/lib/format-hostname'
export function attachRequestMeta(
req: BaseNextRequest,
parsedUrl: NextUrlWithParsedQuery,
hostname: string
) {
const protocol = (
(req as NodeNextRequest).originalRequest?.socket as TLSSocket
)?.encrypted
? 'https'
: 'http'
const initUrl = `${protocol}://${formatHostname(hostname)}${req.url}`
addRequestMeta(req, '__NEXT_INIT_URL', initUrl)
addRequestMeta(req, '__NEXT_INIT_QUERY', { ...parsedUrl.query })
addRequestMeta(req, '_protocol', protocol)
addRequestMeta(req, '__NEXT_CLONABLE_BODY', getCloneableBody(req.body))
}
// IPC need to be the first import to allow it to catch errors happening during
// the other imports
import startHandler from './api-server-handler'
import '../polyfill/app-polyfills'
import { parse as parseUrl } from 'node:url'
import {
NodeNextRequest,
NodeNextResponse,
} from 'next/dist/server/base-http/node'
import { sendResponse } from 'next/dist/server/send-response'
import {
NextRequestAdapter,
signalFromNodeResponse,
} from 'next/dist/server/web/spec-extension/adapters/next-request'
import { attachRequestMeta } from './next-request-helpers'
import type {
AppRouteRouteHandlerContext,
AppRouteRouteModule,
} from 'next/dist/server/future/route-modules/app-route/module'
export default (routeModule: AppRouteRouteModule) => {
startHandler(async ({ request, response, params }) => {
const req = new NodeNextRequest(request)
const res = new NodeNextResponse(response)
const parsedUrl = parseUrl(req.url!, true)
attachRequestMeta(req, parsedUrl, request.headers.host!)
const context: AppRouteRouteHandlerContext = {
params,
prerenderManifest: {
version: -1 as any, // letting us know this doesn't conform to spec
routes: {},
dynamicRoutes: {},
notFoundRoutes: [],
preview: {
previewModeId: 'development-id',
} as any,
},
staticGenerationContext: {
supportsDynamicHTML: true,
},
}
const routeResponse = await routeModule.handle(
NextRequestAdapter.fromNodeNextRequest(
req,
signalFromNodeResponse(response)
),
context
)
await sendResponse(req, res, routeResponse)
})
}
// IPC need to be the first import to allow it to catch errors happening during
// the other imports
import { IPC } from '@vercel/turbopack-node/ipc/index'
import { Buffer } from 'node:buffer'
import type { Ipc } from '@vercel/turbopack-node/ipc/index'
type Operation =
| {
streamRequest: true
onChunk?: (chunk: Buffer) => Promise<void>
onEnd?: () => Promise<void>
}
| {
streamRequest?: false
onBody?: (body: Buffer) => Promise<void>
}
type IpcIncomingMessage<T> =
| {
type: 'headers'
data: T
}
| {
type: 'bodyChunk'
data: number[]
}
| {
type: 'bodyText'
data: number[]
}
| { type: 'bodyEnd' }
type IpcOutgoingMessage<R> =
| {
type: 'headers'
data: R
}
| {
type: 'bodyChunk'
data: number[]
}
| {
type: 'bodyEnd'
}
interface Response {
chunk: (data: Buffer) => Promise<void>
end: () => Promise<void>
}
export default function startHandler<T, R>(
createOperation: (
data: T,
respond: (data: R) => Response,
reportError: (error: unknown) => Promise<never>
) => Promise<Operation | void>
) {
const ipc = IPC as Ipc<IpcIncomingMessage<T>, IpcOutgoingMessage<R>>
;(async () => {
while (true) {
let operation: Operation | void
{
const msg = await ipc.recv()
switch (msg.type) {
case 'headers': {
operation = await createOperation(
msg.data,
(data) => {
ipc.send({
type: 'headers',
data,
})
return {
chunk: (buf: Buffer) => {
return ipc.send({
type: 'bodyChunk',
data: buf.toJSON().data,
})
},
end: () => {
return ipc.send({ type: 'bodyEnd' })
},
}
},
(error) => {
return ipc.sendError(
error instanceof Error
? error
: new Error(`an unknown error occurred: ${error}`)
)
}
)
break
}
default: {
console.error('unexpected message type', msg.type)
process.exit(1)
}
}
}
if (operation) {
if (operation.streamRequest) {
loop: while (true) {
const msg = await ipc.recv()
switch (msg.type) {
case 'bodyChunk':
case 'bodyText': {
await operation.onChunk?.(Buffer.from(msg.data))
break
}
case 'bodyEnd': {
await operation.onEnd?.()
break loop
}
default: {
console.error('unexpected message type', msg.type)
process.exit(1)
}
}
}
} else {
let body = Buffer.alloc(0)
loop: while (true) {
const msg = await ipc.recv()
switch (msg.type) {
case 'bodyChunk':
case 'bodyText': {
body = Buffer.concat([body, Buffer.from(msg.data)])
break
}
case 'bodyEnd': {
await operation.onBody?.(body)
break loop
}
default: {
console.error('unexpected message type', msg.type)
process.exit(1)
}
}
}
}
}
}
})().catch((err) => {
ipc.sendError(err)
})
}
import type { ClientRequest, IncomingMessage, Server } from 'node:http'
import type { AddressInfo } from 'node:net'
import http, { ServerResponse } from 'node:http'
import { headersFromEntries, initProxiedHeaders } from './headers'
export type ServerInfo = Partial<{
hostname: string
port: number
ip: string
protocol: string
}>
/**
* Creates a server that listens a random port.
*/
export function createServer(): Promise<Server> {
return new Promise((resolve) => {
const server = http.createServer()
server.listen(0, () => {
resolve(server)
})
})
}
/**
* Creates a request to a server, and returns the (req, res) pairs from both
* the client's and server's perspective.
*/
export function makeRequest(
server: Server,
method: string,
path: string,
rawQuery?: string,
rawHeaders?: [string, string][],
proxiedFor?: ServerInfo
): Promise<{
clientRequest: ClientRequest
clientResponsePromise: Promise<IncomingMessage>
serverRequest: IncomingMessage
serverResponse: ServerResponse<IncomingMessage>
}> {
return new Promise((resolve, reject) => {
let clientResponseResolve: (value: IncomingMessage) => void
let clientResponseReject: (error: Error) => void
const clientResponsePromise = new Promise<IncomingMessage>(
(resolve, reject) => {
clientResponseResolve = resolve
clientResponseReject = reject
}
)
const errorListener = (err: Error) => {
server.removeListener('request', requestListener)
reject(err)
}
const requestListener = (
req: IncomingMessage,
res: ServerResponse<IncomingMessage>
) => {
server.removeListener('error', errorListener)
resolve({
clientRequest,
clientResponsePromise,
serverRequest: req,
serverResponse: res,
})
}
server.once('request', requestListener)
server.once('error', errorListener)
const address = server.address() as AddressInfo
const headers = headersFromEntries(rawHeaders ?? [])
initProxiedHeaders(headers, proxiedFor)
const clientRequest = http.request({
host: 'localhost',
port: address.port,
method,
path: rawQuery?.length ? `${path}?${rawQuery}` : path,
headers,
})
// Otherwise Node.js waits for the first chunk of data to be written before sending the request.
clientRequest.flushHeaders()
const clientResponseErrorListener = (err: Error) => {
clientRequest.removeListener('response', responseListener)
clientResponseReject(err)
}
const responseListener = (res: IncomingMessage) => {
clientRequest.removeListener('error', clientResponseErrorListener)
clientResponseResolve(res)
}
clientRequest.once('response', responseListener)
clientRequest.once('error', clientResponseErrorListener)
})
}
import './shims'
// Necessary for Next.js to accept and handle the `webpackHMR` option properly
// in next-hydrate.js.
// @ts-expect-error next.js sets this as readonly in their `global.d.ts`
process.env.NODE_ENV = 'development'
// This is a fix for web-vitals.js not being linked properly.
globalThis.__dirname = ''
// This ensures Next.js uses React 18's APIs (hydrateRoot) instead of React 17's
// (hydrate).
process.env.__NEXT_REACT_ROOT = 'true'
# Turbopack Next Dev Overlay
Adapted from [next.js](https://github.com/vercel/next.js/tree/canary/packages/react-dev-overlay)
import * as Bus from './internal/bus'
import { parseStack } from './internal/helpers/parseStack'
import { setHooks } from '@vercel/turbopack-ecmascript-runtime/dev/client/hmr-client'
let isRegistered = false
let stackTraceLimit: number | undefined = undefined
function onUnhandledError(ev: ErrorEvent) {
const error = ev?.error
if (!error || !(error instanceof Error) || typeof error.stack !== 'string') {
// A non-error was thrown, we don't have anything to show. :-(
return
}
if (
error.message.match(/(hydration|content does not match|did not match)/i)
) {
error.message += `\n\nSee more info here: https://nextjs.org/docs/messages/react-hydration-error`
}
const e = error
Bus.emit({
type: Bus.TYPE_UNHANDLED_ERROR,
reason: error,
frames: parseStack(e.stack!),
})
}
function onUnhandledRejection(ev: PromiseRejectionEvent) {
const reason = 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: Bus.TYPE_UNHANDLED_REJECTION,
reason: reason,
frames: parseStack(e.stack!),
})
}
function register() {
if (isRegistered) {
return
}
isRegistered = true
try {
const limit = Error.stackTraceLimit
Error.stackTraceLimit = 50
stackTraceLimit = limit
// eslint-disable-next-line no-empty
} catch {}
window.addEventListener('error', onUnhandledError)
window.addEventListener('unhandledrejection', onUnhandledRejection)
setHooks({
beforeRefresh: onBeforeRefresh,
refresh: onRefresh,
buildOk: onBuildOk,
issues: onTurbopackIssues,
})
}
function unregister() {
if (!isRegistered) {
return
}
isRegistered = false
if (stackTraceLimit !== undefined) {
try {
Error.stackTraceLimit = stackTraceLimit
// eslint-disable-next-line no-empty
} catch {}
stackTraceLimit = undefined
}
window.removeEventListener('error', onUnhandledError)
window.removeEventListener('unhandledrejection', onUnhandledRejection)
}
function onBuildOk() {
Bus.emit({ type: Bus.TYPE_BUILD_OK })
}
function onTurbopackIssues(issues: Issue[]) {
Bus.emit({ type: Bus.TYPE_TURBOPACK_ISSUES, issues })
}
function onBeforeRefresh() {
Bus.emit({ type: Bus.TYPE_BEFORE_REFRESH })
}
function onRefresh() {
Bus.emit({ type: Bus.TYPE_REFRESH })
}
export { getErrorByType } from './internal/helpers/getErrorByType'
export { getServerError } from './internal/helpers/nodeStackFrames'
export { default as ReactDevOverlay } from './internal/ReactDevOverlay'
export { register, unregister }
import React from 'react'
type ErrorBoundaryProps = {
error: Error | null
onError: (error: Error, componentStack: string | null) => void
fallback: React.ReactNode | null
children?: React.ReactNode
}
type ErrorBoundaryState = {
error: Error | null
lastPropsError: Error | null
}
class ErrorBoundary extends React.PureComponent<
ErrorBoundaryProps,
ErrorBoundaryState
> {
static getDerivedStateFromError(error: Error) {
return { error }
}
state = {
error: null,
lastPropsError: null,
}
componentDidCatch(
error: Error,
// Loosely typed because it depends on the React version and was
// accidentally excluded in some versions.
errorInfo?: { componentStack?: string | null }
) {
this.props.onError(error, errorInfo?.componentStack ?? null)
}
// I don't like this, but it works to clear the error boundary
//
// props.error is only set 1 render after state.error, so we can't treat it as the source of truth all the time.
// to get around this we store the error from props in state and only accept updates if the stored error from props
// matches the error in state.
//
// this is definitely not a controlled component and it only works if the error matches exactly
static getDerivedStateFromProps(
props: ErrorBoundaryProps,
state: ErrorBoundaryState
): ErrorBoundaryState | null {
if (state.lastPropsError === props.error) {
return null
}
let error = state.error
if (state.error === state.lastPropsError) {
error = props.error
}
return {
error,
lastPropsError: props.error,
}
}
render() {
const { error } = this.state
const { fallback } = this.props
// The component has to be unmounted or else it would continue to error
if (error != null) {
return fallback
}
return this.props.children
}
}
export { ErrorBoundary }
import * as React from 'react'
import * as Bus from './bus'
import { ShadowPortal } from './components/ShadowPortal'
import { Errors, SupportedErrorEvent } from './container/Errors'
import { ErrorBoundary } from './ErrorBoundary'
import { Base } from './styles/Base'
import { ComponentStyles } from './styles/ComponentStyles'
import { CssReset } from './styles/CssReset'
type RefreshState =
| {
// No refresh in progress.
type: 'idle'
}
| {
// The refresh process has been triggered, but the new code has not been
// executed yet.
type: 'pending'
errors: SupportedErrorEvent[]
reactError: Error | null
}
type OverlayState = {
nextId: number
// issues are from turbopack
issues: Issue[]
// errors are client side
errors: SupportedErrorEvent[]
refreshState: RefreshState
reactError: Error | null
notFound?: boolean
}
function pushErrorFilterDuplicates(
errors: SupportedErrorEvent[],
err: SupportedErrorEvent
): SupportedErrorEvent[] {
return [
...errors.filter((e) => {
// Filter out duplicate errors
return e.event.reason !== err.event.reason
}),
err,
]
}
function reducer(state: OverlayState, ev: Bus.BusEvent): OverlayState {
switch (ev.type) {
case Bus.TYPE_BUILD_OK: {
return { ...state, notFound: false }
}
case Bus.TYPE_TURBOPACK_ISSUES: {
return { ...state, issues: ev.issues }
}
case Bus.TYPE_BEFORE_REFRESH: {
return {
...state,
refreshState: { type: 'pending', errors: [], reactError: null },
}
}
case Bus.TYPE_REFRESH: {
return {
...state,
notFound: false,
errors:
// Errors can come in during updates. In this case, UNHANDLED_ERROR
// and UNHANDLED_REJECTION events might be dispatched between the
// BEFORE_REFRESH and the REFRESH event. We want to keep those errors
// around until the next refresh. Otherwise we run into a race
// condition where those errors would be cleared on refresh completion
// before they can be displayed.
state.refreshState.type === 'pending'
? state.refreshState.errors
: [],
reactError:
state.refreshState.type === 'pending'
? state.refreshState.reactError
: null,
refreshState: { type: 'idle' },
}
}
case Bus.TYPE_UNHANDLED_ERROR:
case Bus.TYPE_UNHANDLED_REJECTION: {
switch (state.refreshState.type) {
case 'idle': {
return {
...state,
nextId: state.nextId + 1,
errors: pushErrorFilterDuplicates(state.errors, {
id: state.nextId,
event: ev,
}),
}
}
case 'pending': {
return {
...state,
nextId: state.nextId + 1,
refreshState: {
...state.refreshState,
errors: pushErrorFilterDuplicates(state.refreshState.errors, {
id: state.nextId,
event: ev,
}),
},
}
}
default:
return state
}
}
case Bus.TYPE_NOT_FOUND: {
return { ...state, notFound: true }
}
case Bus.TYPE_REACT_ERROR: {
switch (state.refreshState.type) {
case 'idle': {
return {
...state,
reactError: ev.error,
}
}
case 'pending': {
return {
...state,
refreshState: {
...state.refreshState,
reactError: ev.error,
},
}
}
default:
return state
}
}
default: {
return state
}
}
}
type ErrorType = 'runtime' | 'build'
const shouldPreventDisplay = (
errorType?: ErrorType | null,
preventType?: ErrorType[] | null
) => {
if (!preventType || !errorType) {
return false
}
return preventType.includes(errorType)
}
type ReactDevOverlayProps = {
globalOverlay?: boolean
preventDisplay?: ErrorType[]
children?: React.ReactNode
}
export default function ReactDevOverlay({
children,
preventDisplay,
globalOverlay,
}: ReactDevOverlayProps) {
const [state, dispatch] = React.useReducer<
React.Reducer<OverlayState, Bus.BusEvent>
>(reducer, {
nextId: 1,
issues: [],
errors: [],
refreshState: {
type: 'idle',
},
reactError: null,
})
React.useEffect(() => {
Bus.on(dispatch)
return function () {
Bus.off(dispatch)
}
}, [dispatch])
const onComponentError = React.useCallback(
(error: Error, componentStack: string | null) => {
Bus.emit({
type: Bus.TYPE_REACT_ERROR,
error,
componentStack,
})
},
[]
)
const hasBuildError = state.issues.length > 0
const hasRuntimeErrors = state.errors.length > 0
const errorType = hasBuildError
? 'build'
: hasRuntimeErrors
? 'runtime'
: null
const isMounted = hasBuildError || hasRuntimeErrors
return (
<React.Fragment>
<ErrorBoundary
error={state.reactError}
onError={onComponentError}
fallback={
// When the overlay is global for the application and it wraps a component rendering `<html>`
// we have to render the html shell otherwise the shadow root will not be able to attach
globalOverlay ? (
<html>
<body></body>
</html>
) : null
}
>
{children ?? null}
</ErrorBoundary>
{isMounted ? (
<ShadowPortal
// setting key ensures that ShadowPortal is re-mounted when the error changes
// this is necessary as nextjs-portal need to be reinjected when we re-render <body>
key={'' + !state.reactError}
globalOverlay={globalOverlay}
>
<CssReset />
<Base />
<ComponentStyles />
{shouldPreventDisplay(errorType, preventDisplay) ? null : (
<Errors issues={state.issues} errors={state.errors} />
)}
</ShadowPortal>
) : null}
</React.Fragment>
)
}
import { StackFrame } from 'stacktrace-parser'
export const TYPE_BUILD_OK = 'build-ok'
export const TYPE_TURBOPACK_ISSUES = 'turbopack-error'
export const TYPE_BEFORE_REFRESH = 'before-fast-refresh'
export const TYPE_REFRESH = 'fast-refresh'
export const TYPE_UNHANDLED_ERROR = 'unhandled-error'
export const TYPE_UNHANDLED_REJECTION = 'unhandled-rejection'
export const TYPE_REACT_ERROR = 'react-error'
export const TYPE_NOT_FOUND = 'not-found'
export type BuildOk = { type: typeof TYPE_BUILD_OK }
export type TurbopackIssues = {
type: typeof TYPE_TURBOPACK_ISSUES
issues: Issue[]
}
export type BeforeFastRefresh = { type: typeof TYPE_BEFORE_REFRESH }
export type FastRefresh = { type: typeof TYPE_REFRESH }
export type UnhandledError = {
type: typeof TYPE_UNHANDLED_ERROR
reason: Error
frames: StackFrame[]
}
export type UnhandledRejection = {
type: typeof TYPE_UNHANDLED_REJECTION
reason: Error
frames: StackFrame[]
}
export type ReactError = {
type: typeof TYPE_REACT_ERROR
error: Error
componentStack: string | null
}
export type NotFoundAction = {
type: typeof TYPE_NOT_FOUND
}
export type BusEvent =
| BuildOk
| TurbopackIssues
| BeforeFastRefresh
| FastRefresh
| UnhandledError
| UnhandledRejection
| ReactError
| NotFoundAction
export type BusEventHandler = (ev: BusEvent) => void
const handlers: Set<BusEventHandler> = new Set()
const queue: BusEvent[] = []
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: BusEvent): void {
queue.push(Object.freeze({ ...ev }))
drain()
}
export function on(fn: BusEventHandler): boolean {
if (handlers.has(fn)) {
return false
}
handlers.add(fn)
drain()
return true
}
export function off(fn: BusEventHandler): boolean {
if (handlers.has(fn)) {
handlers.delete(fn)
return true
}
return false
}
import Anser from '@vercel/turbopack-next/compiled/anser'
import * as React from 'react'
import { StackFrame } from '@vercel/turbopack-next/compiled/stacktrace-parser'
import stripAnsi from '@vercel/turbopack-next/compiled/strip-ansi'
import { getFrameSource } from '../../helpers/stack-frame'
export type CodeFrameProps = { stackFrame: StackFrame; codeFrame: string }
export function CodeFrame({ stackFrame, codeFrame }: CodeFrameProps) {
// Strip leading spaces out of the code frame:
const formattedFrame = React.useMemo<string>(() => {
const lines = codeFrame.split(/\r?\n/g)
const prefixLength = 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)
if (prefixLength > 1) {
const p = ' '.repeat(prefixLength)
return lines
.map((line, a) =>
~(a = line.indexOf('|'))
? line.substring(0, a) + line.substring(a).replace(p, '')
: 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 = React.useCallback(() => {
const params = new URLSearchParams()
for (const key in stackFrame) {
params.append(key, ((stackFrame as any)[key] ?? '').toString())
}
self
.fetch(
`${
process.env.__NEXT_ROUTER_BASEPATH || ''
}/__nextjs_launch-editor?${params.toString()}`
)
.then(
() => {},
() => {
console.error('There was an issue opening this code in your editor.')
}
)
}, [stackFrame])
// TODO: make the caret absolute
return (
<div data-nextjs-codeframe className="codeframe">
<div>
<p
role="link"
onClick={open}
tabIndex={1}
title="Click to open in your editor"
>
<span>
{getFrameSource(stackFrame)} @ {stackFrame.methodName}
</span>
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
>
<path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"></path>
<polyline points="15 3 21 3 21 9"></polyline>
<line x1="10" y1="14" x2="21" y2="3"></line>
</svg>
</p>
</div>
<pre>
{decoded.map((entry, index) => (
<span
key={`frame-${index}`}
style={{
color: entry.fg ? `var(--color-${entry.fg})` : undefined,
...(entry.decoration === 'bold'
? { fontWeight: 800 }
: entry.decoration === 'italic'
? { fontStyle: 'italic' }
: undefined),
}}
>
{entry.content}
</span>
))}
</pre>
</div>
)
}
export { CodeFrame } from './CodeFrame'
export { styles } from './styles'
import { noop as css } from '../../helpers/noop-template'
const styles = css`
.codeframe {
overflow: auto;
border-radius: var(--size-gap-half);
background-color: var(--color-ansi-bg);
color: var(--color-ansi-fg);
}
.codeframe::selection,
.codeframe *::selection {
background-color: var(--color-ansi-selection);
}
.codeframe * {
color: inherit;
background-color: transparent;
font-family: var(--font-mono);
}
.codeframe > * {
margin: 0;
padding: calc(var(--size-gap) + var(--size-gap-half))
calc(var(--size-gap-double) + var(--size-gap-half));
}
.codeframe > div {
display: inline-block;
width: auto;
min-width: 100%;
border-bottom: 1px solid var(--color-ansi-bright-black);
}
.codeframe > div > p {
display: flex;
align-items: center;
justify-content: space-between;
cursor: pointer;
margin: 0;
}
.codeframe > div > p:hover {
text-decoration: underline dotted;
}
.codeframe div > p > svg {
width: auto;
height: 1em;
margin-left: 8px;
}
.codeframe div > pre {
overflow: hidden;
display: inline-block;
}
`
export { styles }
import * as React from 'react'
import { useOnClickOutside } from '../../hooks/use-on-click-outside'
import { clsx } from '../../helpers/clsx'
import { noop as css } from '../../helpers/noop-template'
export type DialogProps = {
'aria-labelledby': string
'aria-describedby': string
onClose?: (e: MouseEvent | TouchEvent) => void
className?: string
children?: React.ReactNode | undefined
}
export function Dialog({
children,
onClose,
className,
...props
}: DialogProps) {
const [dialog, setDialog] = React.useState<HTMLDivElement | null>(null)
const [role, setRole] = React.useState<string | undefined>(
typeof document !== 'undefined' && document.hasFocus()
? 'dialog'
: undefined
)
const onDialog = React.useCallback(
(node: React.SetStateAction<HTMLDivElement | null>) => {
setDialog(node)
},
[]
)
useOnClickOutside(dialog, onClose)
// Make HTMLElements with `role=link` accessible to be triggered by the
// keyboard, i.e. [Enter].
React.useEffect(() => {
if (dialog == null) {
return
}
const root = dialog.getRootNode()
// Always true, but we do this for TypeScript:
if (!(root instanceof ShadowRoot)) {
return
}
const shadowRoot = root
function handler(e: KeyboardEvent) {
const el = shadowRoot.activeElement
if (
e.key === 'Enter' &&
el instanceof HTMLElement &&
el.getAttribute('role') === 'link'
) {
e.preventDefault()
e.stopPropagation()
el.click()
}
}
function handleFocus() {
// safari will force itself as the active application when a background page triggers any sort of autofocus
// this is a workaround to only set the dialog role if the document has focus
setRole(document.hasFocus() ? 'dialog' : undefined)
}
shadowRoot.addEventListener('keydown', handler as EventListener)
window.addEventListener('focus', handleFocus)
window.addEventListener('blur', handleFocus)
return () => {
shadowRoot.removeEventListener('keydown', handler as EventListener)
window.removeEventListener('focus', handleFocus)
window.removeEventListener('blur', handleFocus)
}
}, [dialog])
return (
<div
ref={onDialog}
tabIndex={-1}
role={role}
aria-labelledby={props['aria-labelledby']}
aria-describedby={props['aria-describedby']}
aria-modal="true"
className={clsx('dialog', className)}
>
{children}
</div>
)
}
export const styles = css`
.dialog {
display: flex;
flex-direction: column;
width: 100%;
margin-right: auto;
margin-left: auto;
outline: none;
background: white;
border-radius: var(--size-gap);
box-shadow: 0 var(--size-gap-half) var(--size-gap-double)
rgba(0, 0, 0, 0.25);
max-height: calc(100% - 56px);
overflow-y: hidden;
}
@media (max-height: 812px) {
.dialog-overlay {
max-height: calc(100% - 15px);
}
}
@media (min-width: 576px) {
.dialog {
max-width: 540px;
box-shadow: 0 var(--size-gap) var(--size-gap-quad) rgba(0, 0, 0, 0.25);
}
}
@media (min-width: 768px) {
.dialog {
max-width: 720px;
}
}
@media (min-width: 992px) {
.dialog {
max-width: 960px;
}
}
`
import * as React from 'react'
import { clsx } from '../../helpers/clsx'
import { noop as css } from '../../helpers/noop-template'
export type DialogBodyProps = {
className?: string
children?: React.ReactNode
} & React.HTMLProps<HTMLDivElement>
export function DialogBody({ children, className, ...rest }: DialogBodyProps) {
return (
<div className={clsx('dialog-body', className)} {...rest}>
{children}
</div>
)
}
export const styles = css`
.dialog-content > .dialog-body {
position: relative;
flex: 1 1 auto;
padding: var(--size-gap-double);
}
`
import * as React from 'react'
import { clsx } from '../../helpers/clsx'
import { noop as css } from '../../helpers/noop-template'
export type DialogContentProps = {
className?: string
children?: React.ReactNode
} & React.HTMLProps<HTMLDivElement>
export function DialogContent({
className,
children,
...rest
}: DialogContentProps) {
return (
<div className={clsx('dialog-content', className)} {...rest}>
{children}
</div>
)
}
export const styles = css`
.dialog-content {
display: flex;
flex-direction: column;
overflow-y: hidden;
border: none;
margin: 0;
padding: 0;
height: 100%;
}
`
import * as React from 'react'
import { clsx } from '../../helpers/clsx'
import { CloseIcon } from '../../icons'
import { noop as css } from '../../helpers/noop-template'
export type DialogHeaderProps = {
close?: () => void
className?: string
children: React.ReactNode
}
export function DialogHeader({
children,
className,
close,
}: DialogHeaderProps) {
const buttonClose = React.useRef<HTMLButtonElement | null>(null)
React.useEffect(() => {
if (buttonClose.current == null) {
return
}
const root = buttonClose.current.getRootNode()
const d = self.document
function handler(e: KeyboardEvent) {
if (e.key === 'Escape') {
e.stopPropagation()
if (root instanceof ShadowRoot) {
const a = root.activeElement
if (a && a !== buttonClose.current && a instanceof HTMLElement) {
a.blur()
return
}
}
if (close) {
close()
}
}
}
root.addEventListener('keydown', handler as EventListener)
if (root !== d) {
d.addEventListener('keydown', handler)
}
return function () {
root.removeEventListener('keydown', handler as EventListener)
if (root !== d) {
d.removeEventListener('keydown', handler)
}
}
}, [close, buttonClose])
return (
<div data-nextjs-dialog-header className={clsx('dialog-header', className)}>
{children}
<div className="filler">&nbsp;</div>
{close ? (
<button
ref={buttonClose}
type="button"
onClick={close}
aria-label="Close"
className="close-button"
>
<span aria-hidden="true">
<CloseIcon />
</span>
</button>
) : null}
</div>
)
}
export const styles = css`
.dialog-content > .dialog-header {
flex-shrink: 0;
}
.dialog-header {
--local-padding: var(--size-gap-big);
display: flex;
flex-direction: row;
align-content: center;
align-items: center;
justify-content: space-between;
height: calc(
var(--size-icon) + var(--local-padding) * 2 + var(--border) * 2
);
background-color: var(--color-bg-secondary);
}
.dialog-header > * {
height: 100%;
padding: var(--local-padding);
border-bottom: var(--border);
}
.dialog-header > *:not(:first-child):not(.close-button) {
border-left: var(--border-half);
}
.dialog-header
> *:not(:last-child):not(:nth-last-child(2):before(.close-button)) {
border-right: var(--border-half);
}
.dialog-header > .filler {
display: flex;
flex: 1 0 auto;
flex-grow: 1;
align-self: stretch;
padding-left: 0;
padding-right: 0;
}
.dialog-header > .filler > div {
display: flex;
flex: 1 0 auto;
flex-grow: 1;
align-self: stretch;
padding: var(--local-padding);
padding-left: 0;
padding-right: 0;
border-bottom: var(--border);
}
.dialog-header > button:last-of-type {
border: none;
border-bottom: var(--border);
background-color: transparent;
appearance: none;
}
.dialog-header > button:last-of-type > span {
display: flex;
opacity: 0.4;
transition: opacity 0.25s ease;
}
.dialog-header > button:last-of-type:hover > span {
opacity: 0.7;
}
`
import * as React from 'react'
import { noop as css } from '../../helpers/noop-template'
import { clsx } from '../../helpers/clsx'
import { TabList } from '../Tabs'
export type DialogHeaderTabListProps = {
className?: string
children: React.ReactNode
}
export function DialogHeaderTabList({
className,
children,
}: DialogHeaderTabListProps) {
return (
<TabList className={clsx('dialog-header-tab-list', className)}>
{children}
</TabList>
)
}
export const styles = css`
.dialog-header > .dialog-header-tab-list {
padding: 0;
border: none !important;
}
.dialog-header-tab-list {
height: 100%;
display: flex;
justify-content: start;
align-content: center;
border-bottom: 0;
}
.dialog-header-tab-list > .tab {
display: flex;
align-items: center;
padding-left: calc(var(--local-padding) + var(--size-gap));
padding-right: calc(var(--local-padding) + var(--size-gap));
/* slight offset for the severity top border on the tabs */
padding-top: calc(var(--local-padding) + var(--size-border));
padding-bottom: calc(var(--local-padding) - var(--size-border));
height: 100%;
border-top: none;
border-bottom: var(--border);
border-left: var(--border-half);
border-right: var(--border-half);
color: var(--color-text-dim);
background-color: transparent;
}
.dialog-header-tab-list > .tab:first-child {
border-left: none;
}
.tab::after {
position: absolute;
left: 0;
top: 0;
right: 0;
border-top: var(--size-border-double) solid transparent;
content: ' ';
}
.dialog-header-tab-list > .tab:hover {
background-color: var(--color-bg-secondary-hover);
}
.dialog-header-tab-list > .tab[aria-selected='true'] {
color: var(--color-text);
background-color: var(--color-bg);
border-bottom-color: transparent;
}
`
export { Dialog, DialogProps } from './Dialog'
export { DialogBody, DialogBodyProps } from './DialogBody'
export { DialogContent, DialogContentProps } from './DialogContent'
export { DialogHeader, DialogHeaderProps } from './DialogHeader'
export {
DialogHeaderTabList,
DialogHeaderTabListProps,
} from './DialogHeaderTabList'
export { styles } from './styles'
import { noop as css } from '../../helpers/noop-template'
import { styles as dialogStyles } from './Dialog'
import { styles as bodyStyles } from './DialogBody'
import { styles as contentStyles } from './DialogContent'
import { styles as headerStyles } from './DialogHeader'
import { styles as tabListStyles } from './DialogHeaderTabList'
const styles = css`
${dialogStyles}
${bodyStyles}
${contentStyles}
${headerStyles}
${tabListStyles}
`
export { styles }
import * as React from 'react'
import { clsx } from '../../helpers/clsx'
export type LeftRightDialogHeaderProps = {
hidden?: boolean
previous?: (() => void) | null
next?: (() => void) | null
severity: 'warning' | 'error'
className?: string
children: React.ReactNode
}
export function LeftRightDialogHeader({
hidden = false,
previous,
next,
severity,
className,
children,
}: LeftRightDialogHeaderProps) {
const buttonLeft = React.useRef<HTMLButtonElement | null>(null)
const buttonRight = React.useRef<HTMLButtonElement | null>(null)
const [nav, setNav] = React.useState<HTMLElement | null>(null)
const onNav = React.useCallback((el: HTMLElement) => {
setNav(el)
}, [])
React.useEffect(() => {
if (nav == null || hidden) {
return
}
const root = nav.getRootNode()
const d = self.document
function handler(e: KeyboardEvent) {
if (e.key === 'ArrowLeft') {
e.stopPropagation()
if (buttonLeft.current) {
buttonLeft.current.focus()
}
previous && previous()
} else if (e.key === 'ArrowRight') {
e.stopPropagation()
if (buttonRight.current) {
buttonRight.current.focus()
}
next && next()
}
}
root.addEventListener('keydown', handler as EventListener)
if (root !== d) {
d.addEventListener('keydown', handler)
}
return function () {
root.removeEventListener('keydown', handler as EventListener)
if (root !== d) {
d.removeEventListener('keydown', handler)
}
}
}, [hidden, nav, next, previous])
// Unlock focus for browsers like Firefox, that break all user focus if the
// currently focused item becomes disabled.
React.useEffect(() => {
if (nav == null) {
return
}
const root = nav.getRootNode()
// Always true, but we do this for TypeScript:
if (root instanceof ShadowRoot) {
const a = root.activeElement
if (previous == null) {
if (buttonLeft.current && a === buttonLeft.current) {
buttonLeft.current.blur()
}
} else if (next == null) {
if (buttonRight.current && a === buttonRight.current) {
buttonRight.current.blur()
}
}
}
}, [nav, next, previous])
return (
<nav
ref={onNav}
data-severity={severity}
className={clsx('dialog-left-right', className)}
>
{children}
&nbsp;
<button
ref={buttonLeft}
type="button"
disabled={previous == null ? true : undefined}
aria-disabled={previous == null ? true : undefined}
onClick={previous ?? undefined}
>
<ArrowLeft />
</button>
<button
ref={buttonRight}
type="button"
disabled={next == null ? true : undefined}
aria-disabled={next == null ? true : undefined}
onClick={next ?? undefined}
>
<ArrowRight />
</button>
</nav>
)
}
function ArrowLeft() {
return (
<svg
viewBox="0 0 14 14"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
xmlns="http://www.w3.org/2000/svg"
>
<path d="M6.99996 1.16666L1.16663 6.99999L6.99996 12.8333M12.8333 6.99999H1.99996H12.8333Z" />
</svg>
)
}
function ArrowRight() {
return (
<svg
viewBox="0 0 14 14"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
xmlns="http://www.w3.org/2000/svg"
>
<path d="M6.99996 1.16666L12.8333 6.99999L6.99996 12.8333M1.16663 6.99999H12H1.16663Z" />
</svg>
)
}
export { LeftRightDialogHeader } from './LeftRightDialogHeader'
export { styles } from './styles'
import { noop as css } from '../../helpers/noop-template'
const styles = css`
.dialog-left-right {
white-space: nowrap;
}
.dialog-left-right > button {
--bg-alpha: 0.1;
--fg-alpha: 1;
display: inline-flex;
align-items: center;
justify-content: center;
width: calc(var(--size-gap-double) + var(--size-gap));
height: calc(var(--size-gap-double) + var(--size-gap));
font-size: 0;
border: none;
background-color: hsla(var(--color-base), var(--bg-alpha));
color: hsla(var(--color-base), var(--fg-alpha));
cursor: pointer;
transition: background-color 0.25s ease;
}
.dialog-left-right[data-severity='error'] > button {
--color-base: var(--color-error-bright-hsl);
}
.dialog-left-right[data-severity='warning'] > button {
--color-base: var(--color-warning-bright-hsl);
}
.dialog-left-right > button:hover {
--bg-alpha: 0.2;
}
.dialog-left-right > button:disabled {
--bg-alpha: 0.1;
--fg-alpha: 0.4;
cursor: not-allowed;
}
.dialog-left-right > button:first-of-type {
border-radius: var(--size-gap-half) 0 0 var(--size-gap-half);
margin-right: 1px;
}
.dialog-left-right > button:last-of-type {
border-radius: 0 var(--size-gap-half) var(--size-gap-half) 0;
}
.dialog-left-right > button > svg {
width: auto;
height: var(--size-icon-small);
}
`
export { styles }
import * as React from 'react'
import { lock, unlock } from './body-locker'
import allyTrap from './maintain--tab-focus'
import { clsx } from '../../helpers/clsx'
export type OverlayProps = React.PropsWithChildren & {
className?: string
fixed?: boolean
}
export function Overlay({ className, children, fixed }: OverlayProps) {
React.useEffect(() => {
lock()
return () => {
unlock()
}
}, [])
const [overlay, setOverlay] = React.useState<HTMLDivElement | null>(null)
const onOverlay = React.useCallback((el: HTMLDivElement) => {
setOverlay(el)
}, [])
React.useEffect(() => {
if (overlay == null) {
return
}
const handle2 = allyTrap({ context: overlay })
return () => {
handle2.disengage()
}
}, [overlay])
return (
<div className={clsx('dialog-overlay', className)} ref={onOverlay}>
<div
className={'dialog-backdrop'}
data-dialog-backdrop-fixed={fixed ? true : undefined}
/>
{children}
</div>
)
}
let previousBodyPaddingRight: string | undefined
let previousBodyOverflowSetting: string | undefined
let activeLocks = 0
export function lock() {
setTimeout(() => {
if (activeLocks++ > 0) {
return
}
const scrollBarGap =
window.innerWidth - document.documentElement.clientWidth
if (scrollBarGap > 0) {
previousBodyPaddingRight = document.body.style.paddingRight
document.body.style.paddingRight = `${scrollBarGap}px`
}
previousBodyOverflowSetting = document.body.style.overflow
document.body.style.overflow = 'hidden'
})
}
export function unlock() {
setTimeout(() => {
if (activeLocks === 0 || --activeLocks !== 0) {
return
}
if (previousBodyPaddingRight !== undefined) {
document.body.style.paddingRight = previousBodyPaddingRight
previousBodyPaddingRight = undefined
}
if (previousBodyOverflowSetting !== undefined) {
document.body.style.overflow = previousBodyOverflowSetting
previousBodyOverflowSetting = undefined
}
})
}
export { Overlay } from './Overlay'
export { styles } from './styles'
import { noop as css } from '../../helpers/noop-template'
const styles = css`
.dialog-overlay {
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
overflow: auto;
z-index: 9000;
display: flex;
align-content: center;
align-items: center;
flex-direction: column;
padding: 10vh 15px 0;
}
@media (max-height: 812px) {
.dialog-overlay {
padding: 15px 15px 0;
}
}
.dialog-backdrop {
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
background-color: rgba(17, 17, 17, 0.2);
pointer-events: all;
z-index: -1;
}
.dialog-backdrop[data-dialog-backdrop-fixed] {
cursor: not-allowed;
-webkit-backdrop-filter: blur(8px);
backdrop-filter: blur(8px);
}
`
export { styles }
import * as React from 'react'
import { createPortal } from 'react-dom'
export type ShadowPortalProps = {
children: React.ReactNode
globalOverlay?: boolean
}
export function ShadowPortal({ children, globalOverlay }: ShadowPortalProps) {
const mountNode = React.useRef<HTMLDivElement | null>(null)
const portalNode = React.useRef<HTMLElement | null>(null)
const shadowNode = React.useRef<ShadowRoot | null>(null)
const [, forceUpdate] = React.useState<{} | undefined>()
React.useLayoutEffect(() => {
const ownerDocument = globalOverlay
? document
: mountNode.current!.ownerDocument!
portalNode.current = ownerDocument.createElement('nextjs-portal')
shadowNode.current = portalNode.current.attachShadow({ mode: 'open' })
ownerDocument.body.appendChild(portalNode.current)
forceUpdate({})
return () => {
if (
portalNode.current &&
portalNode.current.ownerDocument &&
portalNode.current.parentNode
) {
portalNode.current.ownerDocument.body.removeChild(portalNode.current)
}
}
}, [globalOverlay])
return shadowNode.current ? (
createPortal(children, shadowNode.current as any)
) : globalOverlay ? null : (
<span ref={mountNode} />
)
}
// TODO: replace with `@react/tabs`
import * as React from 'react'
import { noop as css } from '../../helpers/noop-template'
import { createContext } from '../../hooks/context'
import { clsx } from '../../helpers/clsx'
type Merge<P1 = {}, P2 = {}> = Omit<P1, keyof P2> & P2
type PropsWithAs<As, OwnProps = {}> = As extends ''
? { as: keyof JSX.IntrinsicElements }
: As extends React.JSXElementConstructor<infer P>
? Merge<P, OwnProps & { as: As }>
: As extends keyof JSX.IntrinsicElements
? Merge<JSX.IntrinsicElements[As], OwnProps & { as: As }>
: never
type TabRefs = Record<string, HTMLElement | undefined>
type TabsContextType = {
selectedId: string
registerTabRef: (id: string, el: HTMLElement | null) => void
onSelectTab: (id: string) => void
}
const [TabsProvider, useTabsContext] = createContext<TabsContextType>('Tabs')
export type TabsProps = {
defaultId: string
selectedId?: string
onChange?: (id: string) => void
children: React.ReactNode
}
export function Tabs({
defaultId,
selectedId: controlledId,
onChange,
children,
}: TabsProps) {
const [selectedId, setSelectedId] = React.useState(controlledId ?? defaultId)
const [shouldCheckId, setShouldShouldCheckId] = React.useState(false)
const tabRefs = React.useRef<TabRefs>({})
const onSelectTabUnchecked = React.useCallback(
(id: string) => {
onChange && onChange(id)
setSelectedId(id)
},
[onChange]
)
const onSelectTab = React.useCallback(
(id: string) => {
if (id == selectedId) return
const tab = tabRefs.current[id]
if (!tab) {
console.error(
`Tried selecting invalid tab id "${id}", only ${JSON.stringify(
Object.keys(tabRefs.current)
)} are available.`
)
return
}
setTimeout(() => {
tab.focus()
}, 0)
onSelectTabUnchecked(id)
},
[selectedId, onSelectTabUnchecked]
)
const registerTabRef = React.useCallback(
(id: string, el: HTMLElement | null) => {
if (el == null) {
delete tabRefs.current[id]
setShouldShouldCheckId(true)
} else {
tabRefs.current[id] = el
}
},
[]
)
React.useEffect(() => {
if (!shouldCheckId) return
const currentTabRef = tabRefs.current[selectedId]
if (currentTabRef == null) {
const availableIds = Object.keys(tabRefs.current)
if (availableIds.length > 0) {
onSelectTabUnchecked(availableIds[0])
}
}
setShouldShouldCheckId(false)
}, [shouldCheckId, selectedId, onSelectTabUnchecked])
React.useEffect(() => {
if (controlledId && controlledId != selectedId) {
onSelectTabUnchecked(controlledId)
}
}, [controlledId, selectedId, onSelectTabUnchecked])
return (
<TabsProvider
selectedId={selectedId}
registerTabRef={registerTabRef}
onSelectTab={onSelectTab}
>
{children}
</TabsProvider>
)
}
export type TabListProps = {
className?: string
children: React.ReactNode
}
export function TabList({ className, children }: TabListProps) {
return (
<div role="tablist" className={clsx('tab-list', className)}>
{children}
</div>
)
}
export type TabProps = {
id: string
next?: string
prev?: string
className?: string
children: React.ReactNode
}
export function Tab({
id,
next,
prev,
className,
children,
...rest
}: TabProps & React.HTMLProps<HTMLButtonElement>) {
const { selectedId, registerTabRef, onSelectTab } = useTabsContext('Tab')
const selected = id == selectedId
const click = React.useCallback(
(ev: React.MouseEvent<any>) => {
ev.preventDefault()
onSelectTab(id)
},
[id, onSelectTab]
)
const keyDown = React.useCallback(
(ev: React.KeyboardEvent<any>) => {
if (prev && ev.key === 'ArrowLeft') {
ev.stopPropagation()
onSelectTab(prev)
} else if (next && ev.key === 'ArrowRight') {
ev.stopPropagation()
onSelectTab(next)
}
},
[next, prev, onSelectTab]
)
const ref = React.useCallback(
(el: HTMLElement | null) => registerTabRef(id, el),
[id, registerTabRef]
)
return (
<button
{...rest}
type="button"
ref={ref}
aria-controls={id}
id={`tab-${id}`}
role="tab"
aria-selected={selected}
tabIndex={selected ? 0 : -1}
className={clsx('tab', className)}
onClick={click}
onKeyDown={keyDown}
>
{children}
</button>
)
}
export type TabPanelPropsBase = {
id: string
className?: string
}
export function TabPanel<
As extends
| keyof JSX.IntrinsicElements
| React.JSXElementConstructor<any> = 'div'
>({
as: Comp = 'div',
id,
className,
children,
...rest
}: PropsWithAs<As, TabPanelPropsBase>) {
const { selectedId } = useTabsContext('Tab')
const selected = id == selectedId
return (
<Comp
{...rest}
id={id}
aria-labelledby={`tab-${id}`}
role="tabpanel"
className={clsx('tab-panel', className)}
data-hidden={!selected}
>
{children}
</Comp>
)
}
export const styles = css`
.tab-panel[data-hidden='true'] {
display: none;
}
`
import Anser from '@vercel/turbopack-next/compiled/anser'
import * as React from 'react'
export type TerminalProps = { content: string }
export function Terminal({ content }: TerminalProps) {
const decoded = React.useMemo(() => {
return Anser.ansiToJson(content, {
json: true,
use_classes: true,
remove_empty: true,
})
}, [content])
return (
<div data-nextjs-terminal className="terminal">
<pre>
{decoded.map((entry, index) => (
<span
key={`terminal-entry-${index}`}
style={{
color: entry.fg ? `var(--color-${entry.fg})` : undefined,
...(entry.decoration === 'bold'
? { fontWeight: 800 }
: entry.decoration === 'italic'
? { fontStyle: 'italic' }
: undefined),
}}
>
{entry.content}
</span>
))}
</pre>
</div>
)
}
export { Terminal } from './Terminal'
export { styles } from './styles'
import { noop as css } from '../../helpers/noop-template'
const styles = css`
.terminal {
display: flex;
overflow-y: hidden;
border-radius: var(--size-gap-half);
background-color: var(--color-ansi-bg);
color: var(--color-ansi-fg);
}
.terminal::selection,
.terminal *::selection {
background-color: var(--color-ansi-selection);
}
.terminal * {
color: inherit;
background-color: transparent;
font-family: var(--font-mono);
}
.terminal > * {
margin: 0;
padding: calc(var(--size-gap) + var(--size-gap-half))
calc(var(--size-gap-double) + var(--size-gap-half));
}
.terminal pre {
width: 100%;
white-space: pre-wrap;
word-break: break-word;
overflow-y: scroll;
}
`
export { styles }
import * as React from 'react'
import { clsx } from '../../helpers/clsx'
export type ToastProps = React.PropsWithChildren & {
onClick?: (ev: React.MouseEvent<HTMLDivElement, MouseEvent>) => void
className?: string
}
export function Toast({
onClick,
children,
className,
...rest
}: ToastProps & React.HTMLProps<HTMLDivElement>) {
return (
<div
{...rest}
data-nextjs-toast
onClick={onClick}
className={clsx('toast', className)}
>
<div data-nextjs-toast-wrapper className="toast-wrapper">
{children}
</div>
</div>
)
}
export { styles } from './styles'
export { Toast } from './Toast'
import { noop as css } from '../../helpers/noop-template'
const styles = css`
.toast {
position: fixed;
bottom: var(--size-gap-double);
left: var(--size-gap-double);
max-width: 420px;
z-index: 9000;
}
@media (max-width: 440px) {
.toast {
max-width: 90vw;
left: 5vw;
}
}
.toast-wrapper {
padding: 16px;
border-radius: var(--size-gap-half);
font-weight: 600;
box-shadow: 0px var(--size-gap-double) var(--size-gap-quad)
rgba(0, 0, 0, 0.25);
}
.toast[data-severity='error'] > .toast-wrapper {
color: var(--color-text-white);
background-color: var(--color-error);
}
.toast[data-severity='warning'] > .toast-wrapper {
color: var(--color-text-white);
background-color: var(--color-warning);
}
`
export { styles }
export function noop(
strings: TemplateStringsArray,
...keys: readonly string[]
) {
const lastIndex = strings.length - 1
return (
strings.slice(0, lastIndex).reduce((p, s, i) => p + s + keys[i], '') +
strings[lastIndex]
)
}
import {
parse,
StackFrame,
} from '@vercel/turbopack-next/compiled/stacktrace-parser'
const regexNextStatic = /\/_next(\/static\/.+)/g
export function parseStack(stack: string): StackFrame[] {
const frames = parse(stack)
return frames.map((frame) => {
try {
const url = new URL(frame.file!)
const res = regexNextStatic.exec(url.pathname)
if (res) {
const distDir = process.env.__NEXT_DIST_DIR
?.replace(/\\/g, '/')
?.replace(/\/$/, '')
if (distDir) {
frame.file = 'file://' + distDir.concat(res.pop()!)
}
}
} catch {}
return frame
})
}
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment