Unverified Commit abe8b1e0 authored by Quentin's avatar Quentin Committed by GitHub

Improve performance of String.prototype.split uses (#56746)

This PR adds the optional `limit` parameter on String.prototype.split uses.

> If provided, splits the string at each occurrence of the specified separator, but stops when limit entries have been placed in the array. Any leftover text is not included in the array at all.

[MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split#syntax)

While the performance gain may not be significant for small texts, it can be huge for large ones.

I made a benchmark on the following repository : https://github.com/Yovach/benchmark-nodejs

On my machine, I get the following results:
`node index.js`
> normal 1: 570.092ms
> normal 50: 2.284s
> normal 100: 3.543s

`node index-optimized.js`
> optmized 1: 644.301ms
> optmized 50: 929.39ms
> optmized 100: 1.020s

The "benchmarks" numbers are : 
- "lorem-1" file contains 1 paragraph of "lorem ipsum"
- "lorem-50" file contains 50 paragraphes of "lorem ipsum"
- "lorem-100" file contains 100 paragraphes of "lorem ipsum"
parent 8e203457
...@@ -189,7 +189,7 @@ async function prepareDocumentMapEntry( ...@@ -189,7 +189,7 @@ async function prepareDocumentMapEntry(
// Checks if the links point to existing documents // Checks if the links point to existing documents
function validateInternalLink(errors: Errors, href: string): void { function validateInternalLink(errors: Errors, href: string): void {
// /docs/api/example#heading -> ["api/example", "heading""] // /docs/api/example#heading -> ["api/example", "heading""]
const [link, hash] = href.replace(DOCS_PATH, '').split('#') const [link, hash] = href.replace(DOCS_PATH, '').split('#', 2)
let foundPage let foundPage
......
...@@ -33,7 +33,7 @@ export = defineRule({ ...@@ -33,7 +33,7 @@ export = defineRule({
hrefValue.startsWith('https://fonts.googleapis.com/css') hrefValue.startsWith('https://fonts.googleapis.com/css')
if (isGoogleFont) { if (isGoogleFont) {
const params = new URLSearchParams(hrefValue.split('?')[1]) const params = new URLSearchParams(hrefValue.split('?', 2)[1])
const displayValue = params.get('display') const displayValue = params.get('display')
if (!params.has('display')) { if (!params.has('display')) {
......
...@@ -66,7 +66,7 @@ export = defineRule({ ...@@ -66,7 +66,7 @@ export = defineRule({
return return
} }
const document = context.getFilename().split('pages')[1] const document = context.getFilename().split('pages', 2)[1]
if (document && path.parse(document).name.startsWith('_document')) { if (document && path.parse(document).name.startsWith('_document')) {
return return
} }
......
...@@ -20,7 +20,7 @@ export = defineRule({ ...@@ -20,7 +20,7 @@ export = defineRule({
return return
} }
const document = context.getFilename().split('pages')[1] const document = context.getFilename().split('pages', 2)[1]
if (!document) { if (!document) {
return return
} }
......
...@@ -16,7 +16,7 @@ export = defineRule({ ...@@ -16,7 +16,7 @@ export = defineRule({
create(context) { create(context) {
return { return {
JSXOpeningElement(node) { JSXOpeningElement(node) {
const document = context.getFilename().split('pages')[1] const document = context.getFilename().split('pages', 2)[1]
if (!document) { if (!document) {
return return
} }
......
...@@ -73,7 +73,7 @@ export = defineRule({ ...@@ -73,7 +73,7 @@ export = defineRule({
} }
return { return {
ExportNamedDeclaration(node) { ExportNamedDeclaration(node) {
const page = context.getFilename().split('pages')[1] const page = context.getFilename().split('pages', 2)[1]
if (!page || path.parse(page).dir.startsWith('/api')) { if (!page || path.parse(page).dir.startsWith('/api')) {
return return
} }
......
...@@ -43,8 +43,8 @@ export function normalizeURL(url: string) { ...@@ -43,8 +43,8 @@ export function normalizeURL(url: string) {
if (!url) { if (!url) {
return return
} }
url = url.split('?')[0] url = url.split('?', 1)[0]
url = url.split('#')[0] url = url.split('#', 1)[0]
url = url = url.replace(/(\/index\.html)$/, '/') url = url = url.replace(/(\/index\.html)$/, '/')
// Empty URLs should not be trailed with `/`, e.g. `#heading` // Empty URLs should not be trailed with `/`, e.g. `#heading`
if (url === '') { if (url === '') {
......
...@@ -95,7 +95,7 @@ const nextFontGoogleFontLoader: FontLoader = async ({ ...@@ -95,7 +95,7 @@ const nextFontGoogleFontLoader: FontLoader = async ({
} }
// CSS Variables may be set on a body tag, ignore them to keep the CSS module pure // CSS Variables may be set on a body tag, ignore them to keep the CSS module pure
fontFaceDeclarations = fontFaceDeclarations.split('body {')[0] fontFaceDeclarations = fontFaceDeclarations.split('body {', 1)[0]
// Find font files to download, provide the array of subsets we want to preload if preloading is enabled // Find font files to download, provide the array of subsets we want to preload if preloading is enabled
const fontFiles = findFontFilesInCss( const fontFiles = findFontFilesInCss(
......
...@@ -7,8 +7,8 @@ export function sortFontsVariantValues(valA: string, valB: string) { ...@@ -7,8 +7,8 @@ export function sortFontsVariantValues(valA: string, valB: string) {
// If both values contain commas, it indicates they are in "ital,wght" format // If both values contain commas, it indicates they are in "ital,wght" format
if (valA.includes(',') && valB.includes(',')) { if (valA.includes(',') && valB.includes(',')) {
// Split the values into prefix and suffix // Split the values into prefix and suffix
const [aPrefix, aSuffix] = valA.split(',') const [aPrefix, aSuffix] = valA.split(',', 2)
const [bPrefix, bSuffix] = valB.split(',') const [bPrefix, bSuffix] = valB.split(',', 2)
// Compare the prefixes (ital values) // Compare the prefixes (ital values)
if (aPrefix === bPrefix) { if (aPrefix === bPrefix) {
......
...@@ -329,8 +329,7 @@ const plugin = (options: any = {}) => { ...@@ -329,8 +329,7 @@ const plugin = (options: any = {}) => {
return parsedDeclaration return parsedDeclaration
} }
const splittedUrl = url.split(/(\?)?#/) const [pathname, query, hashOrQuery] = url.split(/(\?)?#/, 3)
const [pathname, query, hashOrQuery] = splittedUrl
let hash = query ? '?' : '' let hash = query ? '?' : ''
hash += hashOrQuery ? `#${hashOrQuery}` : '' hash += hashOrQuery ? `#${hashOrQuery}` : ''
......
...@@ -178,7 +178,7 @@ async function createTreeCodeFromPath( ...@@ -178,7 +178,7 @@ async function createTreeCodeFromPath(
rootLayout: string | undefined rootLayout: string | undefined
globalError: string | undefined globalError: string | undefined
}> { }> {
const splittedPath = pagePath.split(/[\\/]/) const splittedPath = pagePath.split(/[\\/]/, 1)
const isNotFoundRoute = page === '/_not-found' const isNotFoundRoute = page === '/_not-found'
const isDefaultNotFound = isAppBuiltinNotFoundPage(pagePath) const isDefaultNotFound = isAppBuiltinNotFoundPage(pagePath)
const appDirPrefix = isDefaultNotFound ? APP_DIR_ALIAS : splittedPath[0] const appDirPrefix = isDefaultNotFound ? APP_DIR_ALIAS : splittedPath[0]
......
...@@ -16,7 +16,7 @@ type MetadataRouteLoaderOptions = { ...@@ -16,7 +16,7 @@ type MetadataRouteLoaderOptions = {
export function getFilenameAndExtension(resourcePath: string) { export function getFilenameAndExtension(resourcePath: string) {
const filename = path.basename(resourcePath) const filename = path.basename(resourcePath)
const [name, ext] = filename.split('.') const [name, ext] = filename.split('.', 2)
return { name, ext } return { name, ext }
} }
......
...@@ -97,7 +97,7 @@ export default async function resolveUrlLoader( ...@@ -97,7 +97,7 @@ export default async function resolveUrlLoader(
(typeof exception === 'string' && exception) || (typeof exception === 'string' && exception) ||
(exception instanceof Error && [ (exception instanceof Error && [
exception.message, exception.message,
(exception as any).stack.split('\n')[1].trim(), (exception as any).stack.split('\n', 2)[1].trim(),
]) || ]) ||
[] []
) )
......
...@@ -13,7 +13,7 @@ export function linkGc() { ...@@ -13,7 +13,7 @@ export function linkGc() {
if (link.dataset.precedence?.startsWith('next')) { if (link.dataset.precedence?.startsWith('next')) {
const href = link.getAttribute('href') const href = link.getAttribute('href')
if (href) { if (href) {
const [resource, version] = href.split('?v=') const [resource, version] = href.split('?v=', 2)
if (version) { if (version) {
const currentOrigin = window.location.origin const currentOrigin = window.location.origin
const allLinks = [ const allLinks = [
...@@ -35,7 +35,7 @@ export function linkGc() { ...@@ -35,7 +35,7 @@ export function linkGc() {
if (otherLink.dataset.precedence?.startsWith('next')) { if (otherLink.dataset.precedence?.startsWith('next')) {
const otherHref = otherLink.getAttribute('href') const otherHref = otherLink.getAttribute('href')
if (otherHref) { if (otherHref) {
const [, otherVersion] = otherHref.split('?v=') const [, otherVersion] = otherHref.split('?v=', 2)
if (!otherVersion || +otherVersion < +version) { if (!otherVersion || +otherVersion < +version) {
// Delay the removal of the stylesheet to avoid FOUC // Delay the removal of the stylesheet to avoid FOUC
// caused by `@font-face` rules, as they seem to be // caused by `@font-face` rules, as they seem to be
......
...@@ -8,7 +8,7 @@ export type TerminalProps = { content: string } ...@@ -8,7 +8,7 @@ export type TerminalProps = { content: string }
function getFile(lines: string[]) { function getFile(lines: string[]) {
const contentFileName = lines.shift() const contentFileName = lines.shift()
if (!contentFileName) return null if (!contentFileName) return null
const [fileName, line, column] = contentFileName.split(':') const [fileName, line, column] = contentFileName.split(':', 3)
const parsedLine = Number(line) const parsedLine = Number(line)
const parsedColumn = Number(column) const parsedColumn = Number(column)
......
...@@ -19,7 +19,7 @@ export function getSocketUrl(assetPrefix: string): string { ...@@ -19,7 +19,7 @@ export function getSocketUrl(assetPrefix: string): string {
}` }`
if (normalizedAssetPrefix.startsWith('http')) { if (normalizedAssetPrefix.startsWith('http')) {
url = `${protocol}://${normalizedAssetPrefix.split('://')[1]}` url = `${protocol}://${normalizedAssetPrefix.split('://', 2)[1]}`
} }
return url return url
......
...@@ -26,7 +26,7 @@ export function parseComponentStack( ...@@ -26,7 +26,7 @@ export function parseComponentStack(
/^(webpack-internal:\/\/\/|file:\/\/)(\(.*\)\/)?/, /^(webpack-internal:\/\/\/|file:\/\/)(\(.*\)\/)?/,
'' ''
) )
const [file, lineNumber, column] = modulePath?.split(':') ?? [] const [file, lineNumber, column] = modulePath?.split(':', 3) ?? []
componentStackFrames.push({ componentStackFrames.push({
component, component,
......
...@@ -104,5 +104,5 @@ export function getRedirectTypeFromError<U extends string>( ...@@ -104,5 +104,5 @@ export function getRedirectTypeFromError<U extends string>(
throw new Error('Not a redirect error') throw new Error('Not a redirect error')
} }
return error.digest.split(';', 3)[1] as RedirectType return error.digest.split(';', 2)[1] as RedirectType
} }
...@@ -41,8 +41,8 @@ export function handleMutable( ...@@ -41,8 +41,8 @@ export function handleMutable(
false, false,
onlyHashChange: onlyHashChange:
!!mutable.hashFragment && !!mutable.hashFragment &&
state.canonicalUrl.split('#')[0] === state.canonicalUrl.split('#', 1)[0] ===
mutable.canonicalUrl?.split('#')[0], mutable.canonicalUrl?.split('#', 1)[0],
hashFragment: shouldScroll hashFragment: shouldScroll
? // Empty hash should trigger default behavior of scrolling layout into view. ? // Empty hash should trigger default behavior of scrolling layout into view.
// #top is handled in layout-router. // #top is handled in layout-router.
......
...@@ -16,7 +16,7 @@ export default function initializeBuildWatcher( ...@@ -16,7 +16,7 @@ export default function initializeBuildWatcher(
position = 'bottom-right' position = 'bottom-right'
) { ) {
const shadowHost = document.createElement('div') const shadowHost = document.createElement('div')
const [verticalProperty, horizontalProperty] = position.split('-') as [ const [verticalProperty, horizontalProperty] = position.split('-', 2) as [
VerticalPosition, VerticalPosition,
HorizonalPosition HorizonalPosition
] ]
......
...@@ -71,7 +71,7 @@ export function connectHMR(options: { path: string; assetPrefix: string }) { ...@@ -71,7 +71,7 @@ export function connectHMR(options: { path: string; assetPrefix: string }) {
}` }`
if (assetPrefix.startsWith('http')) { if (assetPrefix.startsWith('http')) {
url = `${protocol}://${assetPrefix.split('://')[1]}` url = `${protocol}://${assetPrefix.split('://', 2)[1]}`
} }
source = new window.WebSocket(`${url}${options.path}`) source = new window.WebSocket(`${url}${options.path}`)
......
...@@ -163,7 +163,7 @@ function handleLoading( ...@@ -163,7 +163,7 @@ function handleLoading(
function getDynamicProps( function getDynamicProps(
fetchPriority?: string fetchPriority?: string
): Record<string, string | undefined> { ): Record<string, string | undefined> {
const [majorStr, minorStr] = version.split('.') const [majorStr, minorStr] = version.split('.', 2)
const major = parseInt(majorStr, 10) const major = parseInt(majorStr, 10)
const minor = parseInt(minorStr, 10) const minor = parseInt(minorStr, 10)
if (major > 18 || (major === 18 && minor >= 3)) { if (major > 18 || (major === 18 && minor >= 3)) {
......
...@@ -39,7 +39,7 @@ export function resolveHref( ...@@ -39,7 +39,7 @@ export function resolveHref(
? urlAsString.slice(urlProtoMatch[0].length) ? urlAsString.slice(urlProtoMatch[0].length)
: urlAsString : urlAsString
const urlParts = urlAsStringNoProto.split('?') const urlParts = urlAsStringNoProto.split('?', 1)
if ((urlParts[0] || '').match(/(\/\/|\\)/)) { if ((urlParts[0] || '').match(/(\/\/|\\)/)) {
console.error( console.error(
......
...@@ -102,7 +102,7 @@ function getForwardedHeaders( ...@@ -102,7 +102,7 @@ function getForwardedHeaders(
Array.isArray(rawSetCookies) ? rawSetCookies : [rawSetCookies] Array.isArray(rawSetCookies) ? rawSetCookies : [rawSetCookies]
).map((setCookie) => { ).map((setCookie) => {
// remove the suffixes like 'HttpOnly' and 'SameSite' // remove the suffixes like 'HttpOnly' and 'SameSite'
const [cookie] = `${setCookie}`.split(';') const [cookie] = `${setCookie}`.split(';', 1)
return cookie return cookie
}) })
......
...@@ -579,7 +579,7 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -579,7 +579,7 @@ export default abstract class Server<ServerOptions extends Options = Options> {
if (this.i18nProvider) { if (this.i18nProvider) {
// Remove the port from the hostname if present. // Remove the port from the hostname if present.
const hostname = req?.headers.host?.split(':')[0].toLowerCase() const hostname = req?.headers.host?.split(':', 1)[0].toLowerCase()
const domainLocale = this.i18nProvider.detectDomainLocale(hostname) const domainLocale = this.i18nProvider.detectDomainLocale(hostname)
const defaultLocale = const defaultLocale =
...@@ -792,7 +792,7 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -792,7 +792,7 @@ export default abstract class Server<ServerOptions extends Options = Options> {
return origSetHeader(name, val) return origSetHeader(name, val)
} }
const urlParts = (req.url || '').split('?') const urlParts = (req.url || '').split('?', 1)
const urlNoQuery = urlParts[0] const urlNoQuery = urlParts[0]
// this normalizes repeated slashes in the path e.g. hello//world -> // this normalizes repeated slashes in the path e.g. hello//world ->
......
...@@ -55,7 +55,7 @@ export class I18NProvider { ...@@ -55,7 +55,7 @@ export class I18NProvider {
const domain = domainLocale.domain.toLowerCase() const domain = domainLocale.domain.toLowerCase()
return { return {
defaultLocale: domainLocale.defaultLocale.toLowerCase(), defaultLocale: domainLocale.defaultLocale.toLowerCase(),
hostname: domain.split(':')[0], hostname: domain.split(':', 1)[0],
domain, domain,
locales: domainLocale.locales?.map((locale) => locale.toLowerCase()), locales: domainLocale.locales?.map((locale) => locale.toLowerCase()),
http: domainLocale.http, http: domainLocale.http,
...@@ -154,7 +154,7 @@ export class I18NProvider { ...@@ -154,7 +154,7 @@ export class I18NProvider {
// The first segment will be empty, because it has a leading `/`. If // The first segment will be empty, because it has a leading `/`. If
// there is no further segment, there is no locale (or it's the default). // there is no further segment, there is no locale (or it's the default).
const segments = pathname.split('/') const segments = pathname.split('/', 2)
if (!segments[1]) if (!segments[1])
return { return {
detectedLocale, detectedLocale,
......
...@@ -294,7 +294,7 @@ export class ImageOptimizerCache { ...@@ -294,7 +294,7 @@ export class ImageOptimizerCache {
const now = Date.now() const now = Date.now()
for (const file of files) { for (const file of files) {
const [maxAgeSt, expireAtSt, etag, extension] = file.split('.') const [maxAgeSt, expireAtSt, etag, extension] = file.split('.', 4)
const buffer = await promises.readFile(join(cacheDir, file)) const buffer = await promises.readFile(join(cacheDir, file))
const expireAt = Number(expireAtSt) const expireAt = Number(expireAtSt)
const maxAge = Number(maxAgeSt) const maxAge = Number(maxAgeSt)
...@@ -373,7 +373,7 @@ function parseCacheControl(str: string | null): Map<string, string> { ...@@ -373,7 +373,7 @@ function parseCacheControl(str: string | null): Map<string, string> {
return map return map
} }
for (let directive of str.split(',')) { for (let directive of str.split(',')) {
let [key, value] = directive.trim().split('=') let [key, value] = directive.trim().split('=', 2)
key = key.toLowerCase() key = key.toLowerCase()
if (value) { if (value) {
value = value.toLowerCase() value = value.toLowerCase()
...@@ -686,13 +686,13 @@ function getFileNameWithExtension( ...@@ -686,13 +686,13 @@ function getFileNameWithExtension(
url: string, url: string,
contentType: string | null contentType: string | null
): string { ): string {
const [urlWithoutQueryParams] = url.split('?') const [urlWithoutQueryParams] = url.split('?', 1)
const fileNameWithExtension = urlWithoutQueryParams.split('/').pop() const fileNameWithExtension = urlWithoutQueryParams.split('/').pop()
if (!contentType || !fileNameWithExtension) { if (!contentType || !fileNameWithExtension) {
return 'image.bin' return 'image.bin'
} }
const [fileName] = fileNameWithExtension.split('.') const [fileName] = fileNameWithExtension.split('.', 1)
const extension = getExtension(contentType) const extension = getExtension(contentType)
return `${fileName}.${extension}` return `${fileName}.${extension}`
} }
......
...@@ -116,7 +116,7 @@ export function getResolveRoutes( ...@@ -116,7 +116,7 @@ export function getResolveRoutes(
let parsedUrl = url.parse(req.url || '', true) as NextUrlWithParsedQuery let parsedUrl = url.parse(req.url || '', true) as NextUrlWithParsedQuery
let didRewrite = false let didRewrite = false
const urlParts = (req.url || '').split('?') const urlParts = (req.url || '').split('?', 1)
const urlNoQuery = urlParts[0] const urlNoQuery = urlParts[0]
// this normalizes repeated slashes in the path e.g. hello//world -> // this normalizes repeated slashes in the path e.g. hello//world ->
......
...@@ -18,7 +18,7 @@ export const getDebugPort = () => { ...@@ -18,7 +18,7 @@ export const getDebugPort = () => {
localArg.startsWith('--inspect') || localArg.startsWith('--inspect') ||
localArg.startsWith('--inspect-brk') localArg.startsWith('--inspect-brk')
) )
?.split('=')[1] ?? ?.split('=', 2)[1] ??
process.env.NODE_OPTIONS?.match?.(/--inspect(-brk)?(=(\S+))?( |$)/)?.[3] process.env.NODE_OPTIONS?.match?.(/--inspect(-brk)?(=(\S+))?( |$)/)?.[3]
return debugPortStr ? parseInt(debugPortStr, 10) : 9229 return debugPortStr ? parseInt(debugPortStr, 10) : 9229
} }
......
...@@ -1547,7 +1547,8 @@ export async function renderToHTMLImpl( ...@@ -1547,7 +1547,8 @@ export async function renderToHTMLImpl(
} }
const [renderTargetPrefix, renderTargetSuffix] = documentHTML.split( const [renderTargetPrefix, renderTargetSuffix] = documentHTML.split(
'<next-js-internal-body-render-target></next-js-internal-body-render-target>' '<next-js-internal-body-render-target></next-js-internal-body-render-target>',
2
) )
let prefix = '' let prefix = ''
......
...@@ -426,7 +426,7 @@ export async function continueFizzStream( ...@@ -426,7 +426,7 @@ export async function continueFizzStream(
const closeTag = '</body></html>' const closeTag = '</body></html>'
// Suffix itself might contain close tags at the end, so we need to split it. // Suffix itself might contain close tags at the end, so we need to split it.
const suffixUnclosed = suffix ? suffix.split(closeTag)[0] : null const suffixUnclosed = suffix ? suffix.split(closeTag, 1)[0] : null
if (generateStaticHTML) { if (generateStaticHTML) {
await renderStream.allReady await renderStream.allReady
......
...@@ -14,7 +14,7 @@ export function getHostname( ...@@ -14,7 +14,7 @@ export function getHostname(
// hostname. // hostname.
let hostname: string let hostname: string
if (headers?.host && !Array.isArray(headers.host)) { if (headers?.host && !Array.isArray(headers.host)) {
hostname = headers.host.toString().split(':')[0] hostname = headers.host.toString().split(':', 1)[0]
} else if (parsed.hostname) { } else if (parsed.hostname) {
hostname = parsed.hostname hostname = parsed.hostname
} else return } else return
......
...@@ -13,7 +13,7 @@ export function detectDomainLocale( ...@@ -13,7 +13,7 @@ export function detectDomainLocale(
for (const item of domainItems) { for (const item of domainItems) {
// remove port if present // remove port if present
const domainHostname = item.domain?.split(':')[0].toLowerCase() const domainHostname = item.domain?.split(':', 1)[0].toLowerCase()
if ( if (
hostname === domainHostname || hostname === domainHostname ||
detectedLocale === item.defaultLocale.toLowerCase() || detectedLocale === item.defaultLocale.toLowerCase() ||
......
...@@ -2219,8 +2219,8 @@ export default class Router implements BaseRouter { ...@@ -2219,8 +2219,8 @@ export default class Router implements BaseRouter {
onlyAHashChange(as: string): boolean { onlyAHashChange(as: string): boolean {
if (!this.asPath) return false if (!this.asPath) return false
const [oldUrlNoHash, oldHash] = this.asPath.split('#') const [oldUrlNoHash, oldHash] = this.asPath.split('#', 2)
const [newUrlNoHash, newHash] = as.split('#') const [newUrlNoHash, newHash] = as.split('#', 2)
// Makes sure we scroll to the provided hash if the url/hash are the same // Makes sure we scroll to the provided hash if the url/hash are the same
if (newHash && oldUrlNoHash === newUrlNoHash && oldHash === newHash) { if (newHash && oldUrlNoHash === newUrlNoHash && oldHash === newHash) {
...@@ -2240,7 +2240,7 @@ export default class Router implements BaseRouter { ...@@ -2240,7 +2240,7 @@ export default class Router implements BaseRouter {
} }
scrollToHash(as: string): void { scrollToHash(as: string): void {
const [, hash = ''] = as.split('#') const [, hash = ''] = as.split('#', 2)
handleSmoothScroll( handleSmoothScroll(
() => { () => {
......
...@@ -81,7 +81,7 @@ export function matchHas( ...@@ -81,7 +81,7 @@ export function matchHas(
case 'host': { case 'host': {
const { host } = req?.headers || {} const { host } = req?.headers || {}
// remove port from host if present // remove port from host if present
const hostname = host?.split(':')[0].toLowerCase() const hostname = host?.split(':', 1)[0].toLowerCase()
value = hostname value = hostname
break break
} }
...@@ -257,7 +257,7 @@ export function prepareDestination(args: { ...@@ -257,7 +257,7 @@ export function prepareDestination(args: {
try { try {
newUrl = destPathCompiler(args.params) newUrl = destPathCompiler(args.params)
const [pathname, hash] = newUrl.split('#') const [pathname, hash] = newUrl.split('#', 2)
parsedDestination.hostname = destHostnameCompiler(args.params) parsedDestination.hostname = destHostnameCompiler(args.params)
parsedDestination.pathname = pathname parsedDestination.pathname = pathname
parsedDestination.hash = `${hash ? '#' : ''}${hash || ''}` parsedDestination.hash = `${hash ? '#' : ''}${hash || ''}`
......
...@@ -118,7 +118,7 @@ describe('404-page-router', () => { ...@@ -118,7 +118,7 @@ describe('404-page-router', () => {
describe.each(urls)('for $url', ({ url, pathname, asPath }) => { describe.each(urls)('for $url', ({ url, pathname, asPath }) => {
it('should have the correct router parameters after it is ready', async () => { it('should have the correct router parameters after it is ready', async () => {
const query = url.split('?')[1] ?? '' const query = url.split('?', 2)[1] ?? ''
const browser = await webdriver(next.url, url) const browser = await webdriver(next.url, url)
try { try {
......
...@@ -45,7 +45,7 @@ createNextDescribe( ...@@ -45,7 +45,7 @@ createNextDescribe(
await browser.elementByCss('#cookie').click() await browser.elementByCss('#cookie').click()
await check(async () => { await check(async () => {
const res = (await browser.elementByCss('h1').text()) || '' const res = (await browser.elementByCss('h1').text()) || ''
const id = res.split(':') const id = res.split(':', 2)
return id[0] === id[1] && id[0] ? 'same' : 'different' return id[0] === id[1] && id[0] ? 'same' : 'different'
}, 'same') }, 'same')
...@@ -59,7 +59,7 @@ createNextDescribe( ...@@ -59,7 +59,7 @@ createNextDescribe(
await browser.elementByCss('#setCookie').click() await browser.elementByCss('#setCookie').click()
await check(async () => { await check(async () => {
const res = (await browser.elementByCss('h1').text()) || '' const res = (await browser.elementByCss('h1').text()) || ''
const id = res.split(':') const id = res.split(':', 3)
return id[0] === id[1] && id[0] === id[2] && id[0] return id[0] === id[1] && id[0] === id[2] && id[0]
? 'same' ? 'same'
: 'different' : 'different'
......
...@@ -62,7 +62,7 @@ createNextDescribe( ...@@ -62,7 +62,7 @@ createNextDescribe(
'/static/three/data.json', '/static/three/data.json',
])('responds correctly on %s', async (path) => { ])('responds correctly on %s', async (path) => {
expect(JSON.parse(await next.render(basePath + path))).toEqual({ expect(JSON.parse(await next.render(basePath + path))).toEqual({
params: { slug: path.split('/')[2] }, params: { slug: path.split('/', 3)[2] },
now: expect.any(Number), now: expect.any(Number),
}) })
if (isNextStart) { if (isNextStart) {
...@@ -85,7 +85,7 @@ createNextDescribe( ...@@ -85,7 +85,7 @@ createNextDescribe(
])('revalidates correctly on %s', async (path) => { ])('revalidates correctly on %s', async (path) => {
const data = JSON.parse(await next.render(basePath + path)) const data = JSON.parse(await next.render(basePath + path))
expect(data).toEqual({ expect(data).toEqual({
params: { slug: path.split('/')[2] }, params: { slug: path.split('/', 3)[2] },
now: expect.any(Number), now: expect.any(Number),
}) })
......
...@@ -11,13 +11,13 @@ function parseLogsFromCli(cliOutput: string) { ...@@ -11,13 +11,13 @@ function parseLogsFromCli(cliOutput: string) {
return logs.reduce((parsedLogs, log) => { return logs.reduce((parsedLogs, log) => {
if (log.includes('Cache missed reason')) { if (log.includes('Cache missed reason')) {
// cache miss reason // cache miss reason
const reasonSegment = log.split('Cache missed reason: ')[1].trim() const reasonSegment = log.split('Cache missed reason: ', 2)[1].trim()
const reason = reasonSegment.slice(1, -1) const reason = reasonSegment.slice(1, -1)
parsedLogs[parsedLogs.length - 1].cache = reason parsedLogs[parsedLogs.length - 1].cache = reason
} else { } else {
// request info // request info
const trimmedLog = log.replace(/^[^a-zA-Z]+/, '') const trimmedLog = log.replace(/^[^a-zA-Z]+/, '')
const parts = trimmedLog.split(' ') const parts = trimmedLog.split(' ', 5)
const method = parts[0] const method = parts[0]
const url = parts[1] const url = parts[1]
const statusCode = parseInt(parts[2]) const statusCode = parseInt(parts[2])
......
...@@ -1906,7 +1906,7 @@ createNextDescribe( ...@@ -1906,7 +1906,7 @@ createNextDescribe(
it('should skip cache in draft mode', async () => { it('should skip cache in draft mode', async () => {
const draftRes = await next.fetch('/api/draft-mode?status=enable') const draftRes = await next.fetch('/api/draft-mode?status=enable')
const setCookie = draftRes.headers.get('set-cookie') const setCookie = draftRes.headers.get('set-cookie')
const cookieHeader = { Cookie: setCookie?.split(';')[0] } const cookieHeader = { Cookie: setCookie?.split(';', 1)[0] }
expect(cookieHeader.Cookie).toBeTruthy() expect(cookieHeader.Cookie).toBeTruthy()
......
...@@ -22,7 +22,7 @@ createNextDescribe( ...@@ -22,7 +22,7 @@ createNextDescribe(
// convert pretty-bytes format into bytes so we can compare units // convert pretty-bytes format into bytes so we can compare units
const sizeToBytes = (size: string) => { const sizeToBytes = (size: string) => {
const units = ['B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'] const units = ['B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
const [value, unit] = size.split(' ') const [value, unit] = size.split(' ', 2)
const exp = units.indexOf(unit) const exp = units.indexOf(unit)
return parseFloat(value) * Math.pow(1024, exp) return parseFloat(value) * Math.pow(1024, exp)
} }
......
...@@ -152,7 +152,7 @@ createNextDescribe( ...@@ -152,7 +152,7 @@ createNextDescribe(
.toArray() .toArray()
.map((el) => { .map((el) => {
return { return {
href: $(el).attr('href').split('?')[0], href: $(el).attr('href').split('?', 1)[0],
sizes: $(el).attr('sizes'), sizes: $(el).attr('sizes'),
type: $(el).attr('type'), type: $(el).attr('type'),
} }
...@@ -175,7 +175,7 @@ createNextDescribe( ...@@ -175,7 +175,7 @@ createNextDescribe(
.toArray() .toArray()
.map((el) => { .map((el) => {
return { return {
href: $(el).attr('href').split('?')[0], href: $(el).attr('href').split('?', 1)[0],
sizes: $(el).attr('sizes'), sizes: $(el).attr('sizes'),
type: $(el).attr('type'), type: $(el).attr('type'),
} }
......
...@@ -46,7 +46,7 @@ createNextDescribe( ...@@ -46,7 +46,7 @@ createNextDescribe(
clientReferenceManifest.clientModules clientReferenceManifest.clientModules
) )
clientModulesNames.every((name) => { clientModulesNames.every((name) => {
const [, key] = name.split('#') const [, key] = name.split('#', 2)
return key === undefined || key === '' || key === 'default' return key === undefined || key === '' || key === 'default'
}) })
......
...@@ -628,8 +628,8 @@ describe('Middleware Rewrite', () => { ...@@ -628,8 +628,8 @@ describe('Middleware Rewrite', () => {
// node-fetch bundles the cookies as string in the Response // node-fetch bundles the cookies as string in the Response
const cookieArray = res.headers.raw()['set-cookie'] const cookieArray = res.headers.raw()['set-cookie']
for (const cookie of cookieArray) { for (const cookie of cookieArray) {
let individualCookieParams = cookie.split(';') let individualCookieParams = cookie.split(';', 1)
let individualCookie = individualCookieParams[0].split('=') let individualCookie = individualCookieParams[0].split('=', 2)
if (individualCookie[0] === cookieName) { if (individualCookie[0] === cookieName) {
return individualCookie[1] return individualCookie[1]
} }
......
...@@ -114,7 +114,7 @@ export class NextDevInstance extends NextInstance { ...@@ -114,7 +114,7 @@ export class NextDevInstance extends NextInstance {
msg.includes('started server on') && msg.includes('started server on') &&
msg.includes('url:') msg.includes('url:')
) { ) {
this._url = msg.split('url: ').pop().split(/\s/)[0].trim() this._url = msg.split('url: ').pop().split(/\s/, 1)[0].trim()
resolveServer() resolveServer()
} }
} }
......
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