Unverified Commit db2567b0 authored by CommanderRoot's avatar CommanderRoot Committed by GitHub

chore: replace deprecated String.prototype.substr() (#35421)

.substr() is deprecated so we replace it with .slice() which works similarily but isn't deprecated
Signed-off-by: 's avatarTobias Speicher <rootcommander@gmail.com>
Co-authored-by: 's avatarSteven <steven@ceriously.com>
parent f16ee05f
...@@ -20,7 +20,7 @@ const round = (num, places) => { ...@@ -20,7 +20,7 @@ const round = (num, places) => {
const shortenLabel = (itemKey) => const shortenLabel = (itemKey) =>
itemKey.length > 24 itemKey.length > 24
? `${itemKey.substr(0, 12)}..${itemKey.substr(itemKey.length - 12, 12)}` ? `${itemKey.slice(0, 12)}..${itemKey.slice(-12)}`
: itemKey : itemKey
const twoMB = 2 * 1024 * 1024 const twoMB = 2 * 1024 * 1024
......
...@@ -74,8 +74,7 @@ module.exports = async function collectStats( ...@@ -74,8 +74,7 @@ module.exports = async function collectStats(
const responseText = (await res.text()).trim() const responseText = (await res.text()).trim()
let fileName = pathname === '/' ? '/index' : pathname let fileName = pathname === '/' ? '/index' : pathname
if (fileName.endsWith('/')) if (fileName.endsWith('/')) fileName = fileName.slice(0, -1)
fileName = fileName.substr(0, fileName.length - 1)
logger( logger(
`Writing file to ${path.join(fetchedPagesDir, `${fileName}.html`)}` `Writing file to ${path.join(fetchedPagesDir, `${fileName}.html`)}`
) )
......
...@@ -3,7 +3,7 @@ import { setLoginSession } from '../../lib/auth' ...@@ -3,7 +3,7 @@ import { setLoginSession } from '../../lib/auth'
export default async function login(req, res) { export default async function login(req, res) {
try { try {
const didToken = req.headers.authorization.substr(7) const didToken = req.headers.authorization.slice(7)
const metadata = await magic.users.getMetadataByToken(didToken) const metadata = await magic.users.getMetadataByToken(didToken)
const session = { ...metadata } const session = { ...metadata }
......
...@@ -218,7 +218,7 @@ class CraTransform { ...@@ -218,7 +218,7 @@ class CraTransform {
return `${reactName}={\`${value.replace( return `${reactName}={\`${value.replace(
/%([a-zA-Z0-9_]{0,})%/g, /%([a-zA-Z0-9_]{0,})%/g,
(subStr) => { (subStr) => {
return `\${process.env.${subStr.substr(1, subStr.length - 2)}}` return `\${process.env.${subStr.slice(1, -1)}}`
} }
)}\`}` )}\`}`
} }
...@@ -293,7 +293,7 @@ class CraTransform { ...@@ -293,7 +293,7 @@ class CraTransform {
: [...globalCssContext.cssImports] : [...globalCssContext.cssImports]
.map((file) => { .map((file) => {
if (!this.isCra) { if (!this.isCra) {
file = file.startsWith('/') ? file.substr(1) : file file = file.startsWith('/') ? file.slice(1) : file
} }
return `import '${ return `import '${
......
...@@ -13,7 +13,7 @@ const camelCase = (value: string): string => { ...@@ -13,7 +13,7 @@ const camelCase = (value: string): string => {
const val = value.replace(/[-_\s.]+(.)?/g, (_match, chr) => const val = value.replace(/[-_\s.]+(.)?/g, (_match, chr) =>
chr ? chr.toUpperCase() : '' chr ? chr.toUpperCase() : ''
) )
return val.substr(0, 1).toUpperCase() + val.substr(1) return val.slice(0, 1).toUpperCase() + val.slice(1)
} }
const isValidIdentifier = (value: string): boolean => const isValidIdentifier = (value: string): boolean =>
......
...@@ -1659,7 +1659,7 @@ export default async function build( ...@@ -1659,7 +1659,7 @@ export default async function build(
// strip leading / and then recurse number of nested dirs // strip leading / and then recurse number of nested dirs
// to place from base folder // to place from base folder
originPage originPage
.substr(1) .slice(1)
.split('/') .split('/')
.map(() => '..') .map(() => '..')
.join('/') .join('/')
...@@ -1709,7 +1709,7 @@ export default async function build( ...@@ -1709,7 +1709,7 @@ export default async function build(
for (const locale of i18n.locales) { for (const locale of i18n.locales) {
const curPath = `/${locale}${page === '/' ? '' : page}` const curPath = `/${locale}${page === '/' ? '' : page}`
const localeExt = page === '/' ? path.extname(file) : '' const localeExt = page === '/' ? path.extname(file) : ''
const relativeDestNoPages = relativeDest.substr( const relativeDestNoPages = relativeDest.slice(
'pages/'.length 'pages/'.length
) )
......
...@@ -81,7 +81,7 @@ store.subscribe((state) => { ...@@ -81,7 +81,7 @@ store.subscribe((state) => {
const matches = cleanError.match(/\[.*\]=/) const matches = cleanError.match(/\[.*\]=/)
if (matches) { if (matches) {
for (const match of matches) { for (const match of matches) {
const prop = (match.split(']').shift() || '').substr(1) const prop = (match.split(']').shift() || '').slice(1)
console.log( console.log(
`AMP bind syntax [${prop}]='' is not supported in JSX, use 'data-amp-bind-${prop}' instead. https://nextjs.org/docs/messages/amp-bind-jsx-alt` `AMP bind syntax [${prop}]='' is not supported in JSX, use 'data-amp-bind-${prop}' instead. https://nextjs.org/docs/messages/amp-bind-jsx-alt`
) )
......
...@@ -723,7 +723,7 @@ export async function buildStaticPaths( ...@@ -723,7 +723,7 @@ export async function buildStaticPaths(
let cleanedEntry = entry let cleanedEntry = entry
if (localePathResult.detectedLocale) { if (localePathResult.detectedLocale) {
cleanedEntry = entry.substr(localePathResult.detectedLocale.length + 1) cleanedEntry = entry.slice(localePathResult.detectedLocale.length + 1)
} else if (defaultLocale) { } else if (defaultLocale) {
entry = `/${defaultLocale}${entry}` entry = `/${defaultLocale}${entry}`
} }
......
...@@ -55,7 +55,7 @@ const nextServerlessLoader: webpack.loader.Loader = function () { ...@@ -55,7 +55,7 @@ const nextServerlessLoader: webpack.loader.Loader = function () {
i18n, i18n,
reactRoot, reactRoot,
}: ServerlessLoaderQuery = }: ServerlessLoaderQuery =
typeof this.query === 'string' ? parse(this.query.substr(1)) : this.query typeof this.query === 'string' ? parse(this.query.slice(1)) : this.query
const buildManifest = join(distDir, BUILD_MANIFEST).replace(/\\/g, '/') const buildManifest = join(distDir, BUILD_MANIFEST).replace(/\\/g, '/')
const reactLoadableManifest = join(distDir, REACT_LOADABLE_MANIFEST).replace( const reactLoadableManifest = join(distDir, REACT_LOADABLE_MANIFEST).replace(
......
...@@ -274,9 +274,9 @@ export function getUtils({ ...@@ -274,9 +274,9 @@ export function getUtils({
} }
pathname = pathname =
pathname.substr(0, paramIdx) + pathname.slice(0, paramIdx) +
(paramValue || '') + (paramValue || '') +
pathname.substr(paramIdx + builtParam.length) pathname.slice(paramIdx + builtParam.length)
} }
} }
......
...@@ -44,8 +44,8 @@ export function tryParsePattern(pattern: string): Pattern | undefined { ...@@ -44,8 +44,8 @@ export function tryParsePattern(pattern: string): Pattern | undefined {
return indexOfStar === -1 return indexOfStar === -1
? undefined ? undefined
: { : {
prefix: pattern.substr(0, indexOfStar), prefix: pattern.slice(0, indexOfStar),
suffix: pattern.substr(indexOfStar + 1), suffix: pattern.slice(indexOfStar + 1),
} }
} }
......
...@@ -541,7 +541,7 @@ export class TraceEntryPointsPlugin implements webpack5.WebpackPluginInstance { ...@@ -541,7 +541,7 @@ export class TraceEntryPointsPlugin implements webpack5.WebpackPluginInstance {
) { ) {
requestPath = ( requestPath = (
resContext.descriptionFileRoot + resContext.descriptionFileRoot +
request.substr(getPkgName(request)?.length || 0) + request.slice(getPkgName(request)?.length || 0) +
nodePath.sep + nodePath.sep +
'package.json' 'package.json'
) )
...@@ -555,7 +555,7 @@ export class TraceEntryPointsPlugin implements webpack5.WebpackPluginInstance { ...@@ -555,7 +555,7 @@ export class TraceEntryPointsPlugin implements webpack5.WebpackPluginInstance {
(separatorIndex = requestPath.lastIndexOf('/')) > (separatorIndex = requestPath.lastIndexOf('/')) >
rootSeparatorIndex rootSeparatorIndex
) { ) {
requestPath = requestPath.substr(0, separatorIndex) requestPath = requestPath.slice(0, separatorIndex)
const curPackageJsonPath = `${requestPath}/package.json` const curPackageJsonPath = `${requestPath}/package.json`
if (await job.isFile(curPackageJsonPath)) { if (await job.isFile(curPackageJsonPath)) {
await job.emitFile( await job.emitFile(
......
...@@ -48,12 +48,13 @@ async function tryApplyUpdates() { ...@@ -48,12 +48,13 @@ async function tryApplyUpdates() {
).some((mod) => { ).some((mod) => {
return ( return (
mod.indexOf( mod.indexOf(
`pages${curPage.substr(0, 1) === '/' ? curPage : `/${curPage}`}` `pages${curPage.startsWith('/') ? curPage : `/${curPage}`}`
) !== -1 || ) !== -1 ||
mod.indexOf( mod.indexOf(
`pages${ `pages${curPage.startsWith('/') ? curPage : `/${curPage}`}`.replace(
curPage.substr(0, 1) === '/' ? curPage : `/${curPage}` /\//g,
}`.replace(/\//g, '\\') '\\'
)
) !== -1 ) !== -1
) )
}) })
......
...@@ -646,7 +646,7 @@ export default async function exportApp( ...@@ -646,7 +646,7 @@ export default async function exportApp(
// strip leading / and then recurse number of nested dirs // strip leading / and then recurse number of nested dirs
// to place from base folder // to place from base folder
pageName pageName
.substr(1) .slice(1)
.split('/') .split('/')
.map(() => '..') .map(() => '..')
.join('/') .join('/')
......
...@@ -1144,7 +1144,7 @@ export default abstract class Server { ...@@ -1144,7 +1144,7 @@ export default abstract class Server {
// ensure correct status is set when visiting a status page // ensure correct status is set when visiting a status page
// directly e.g. /500 // directly e.g. /500
if (STATIC_STATUS_PAGES.includes(pathname)) { if (STATIC_STATUS_PAGES.includes(pathname)) {
res.statusCode = parseInt(pathname.substr(1), 10) res.statusCode = parseInt(pathname.slice(1), 10)
} }
// static pages can only respond to GET/HEAD // static pages can only respond to GET/HEAD
......
...@@ -733,7 +733,7 @@ export default class HotReloader { ...@@ -733,7 +733,7 @@ export default class HotReloader {
this.send({ this.send({
event: 'serverOnlyChanges', event: 'serverOnlyChanges',
pages: serverOnlyChanges.map((pg) => pages: serverOnlyChanges.map((pg) =>
denormalizePagePath(pg.substr('pages'.length)) denormalizePagePath(pg.slice('pages'.length))
), ),
}) })
} }
......
...@@ -56,7 +56,7 @@ export function replaceBasePath(pathname: string, basePath: string): string { ...@@ -56,7 +56,7 @@ export function replaceBasePath(pathname: string, basePath: string): string {
// and doesn't contain extra chars e.g. basePath /docs // and doesn't contain extra chars e.g. basePath /docs
// should replace for /docs, /docs/, /docs/a but not /docsss // should replace for /docs, /docs/, /docs/a but not /docsss
if (hasBasePath(pathname, basePath)) { if (hasBasePath(pathname, basePath)) {
pathname = pathname.substr(basePath.length) pathname = pathname.slice(basePath.length)
if (!pathname.startsWith('/')) pathname = `/${pathname}` if (!pathname.startsWith('/')) pathname = `/${pathname}`
} }
return pathname return pathname
......
...@@ -121,7 +121,7 @@ function addPathPrefix(path: string, prefix?: string) { ...@@ -121,7 +121,7 @@ function addPathPrefix(path: string, prefix?: string) {
return ( return (
normalizePathTrailingSlash(`${prefix}${pathname}`) + normalizePathTrailingSlash(`${prefix}${pathname}`) +
path.substr(pathname.length) path.slice(pathname.length)
) )
} }
...@@ -177,7 +177,7 @@ export function delLocale(path: string, locale?: string) { ...@@ -177,7 +177,7 @@ export function delLocale(path: string, locale?: string) {
(pathLower.startsWith('/' + localeLower + '/') || (pathLower.startsWith('/' + localeLower + '/') ||
pathLower === '/' + localeLower) pathLower === '/' + localeLower)
? (pathname.length === locale.length + 1 ? '/' : '') + ? (pathname.length === locale.length + 1 ? '/' : '') +
path.substr(locale.length + 1) path.slice(locale.length + 1)
: path : path
} }
return path return path
...@@ -320,7 +320,7 @@ export function resolveHref( ...@@ -320,7 +320,7 @@ export function resolveHref(
// invalid and will never match a Next.js page/file // invalid and will never match a Next.js page/file
const urlProtoMatch = urlAsString.match(/^[a-zA-Z]{1,}:\/\//) const urlProtoMatch = urlAsString.match(/^[a-zA-Z]{1,}:\/\//)
const urlAsStringNoProto = urlProtoMatch const urlAsStringNoProto = urlProtoMatch
? urlAsString.substr(urlProtoMatch[0].length) ? urlAsString.slice(urlProtoMatch[0].length)
: urlAsString : urlAsString
const urlParts = urlAsStringNoProto.split('?') const urlParts = urlAsStringNoProto.split('?')
...@@ -751,7 +751,7 @@ export default class Router implements BaseRouter { ...@@ -751,7 +751,7 @@ export default class Router implements BaseRouter {
if (typeof window !== 'undefined') { if (typeof window !== 'undefined') {
// make sure "as" doesn't start with double slashes or else it can // make sure "as" doesn't start with double slashes or else it can
// throw an error as it's considered invalid // throw an error as it's considered invalid
if (as.substr(0, 2) !== '//') { if (!as.startsWith('//')) {
// in order for `e.state` to work on the `onpopstate` event // in order for `e.state` to work on the `onpopstate` event
// we have to register the initial route upon initialization // we have to register the initial route upon initialization
const options: TransitionOptions = { locale } const options: TransitionOptions = { locale }
......
...@@ -51,7 +51,7 @@ export function formatUrl(urlObj: UrlObject) { ...@@ -51,7 +51,7 @@ export function formatUrl(urlObj: UrlObject) {
let search = urlObj.search || (query && `?${query}`) || '' let search = urlObj.search || (query && `?${query}`) || ''
if (protocol && protocol.substr(-1) !== ':') protocol += ':' if (protocol && !protocol.endsWith(':')) protocol += ':'
if ( if (
urlObj.slashes || urlObj.slashes ||
......
...@@ -109,7 +109,7 @@ export function compileNonPath(value: string, params: Params): string { ...@@ -109,7 +109,7 @@ export function compileNonPath(value: string, params: Params): string {
// the value needs to start with a forward-slash to be compiled // the value needs to start with a forward-slash to be compiled
// correctly // correctly
return compile(`/${value}`, { validate: false })(params).substr(1) return compile(`/${value}`, { validate: false })(params).slice(1)
} }
export function prepareDestination(args: { export function prepareDestination(args: {
......
...@@ -73,7 +73,7 @@ export function getParametrizedRoute(route: string) { ...@@ -73,7 +73,7 @@ export function getParametrizedRoute(route: string) {
if (cleanedKey.length === 0 || cleanedKey.length > 30) { if (cleanedKey.length === 0 || cleanedKey.length > 30) {
invalidKey = true invalidKey = true
} }
if (!isNaN(parseInt(cleanedKey.substr(0, 1)))) { if (!isNaN(parseInt(cleanedKey.slice(0, 1)))) {
invalidKey = true invalidKey = true
} }
......
...@@ -50,7 +50,7 @@ function runTests(dev = false) { ...@@ -50,7 +50,7 @@ function runTests(dev = false) {
expect(res2.headers.get('transfer-encoding')).toBe(null) expect(res2.headers.get('transfer-encoding')).toBe(null)
if (dev) { if (dev) {
expect(stderr.substr(stderrIdx)).toContain( expect(stderr.slice(stderrIdx)).toContain(
'A body was attempted to be set with a 204 statusCode' 'A body was attempted to be set with a 204 statusCode'
) )
} }
...@@ -509,7 +509,7 @@ function runTests(dev = false) { ...@@ -509,7 +509,7 @@ function runTests(dev = false) {
it('should not show warning when the API resolves and the response is piped', async () => { it('should not show warning when the API resolves and the response is piped', async () => {
const startIdx = stderr.length > 0 ? stderr.length - 1 : stderr.length const startIdx = stderr.length > 0 ? stderr.length - 1 : stderr.length
await fetchViaHTTP(appPort, `/api/test-res-pipe`, { port: appPort }) await fetchViaHTTP(appPort, `/api/test-res-pipe`, { port: appPort })
expect(stderr.substr(startIdx)).not.toContain( expect(stderr.slice(startIdx)).not.toContain(
`API resolved without sending a response for /api/test-res-pipe` `API resolved without sending a response for /api/test-res-pipe`
) )
}) })
...@@ -527,7 +527,7 @@ function runTests(dev = false) { ...@@ -527,7 +527,7 @@ function runTests(dev = false) {
const startIdx = stderr.length > 0 ? stderr.length - 1 : stderr.length const startIdx = stderr.length > 0 ? stderr.length - 1 : stderr.length
const apiURL = '/api/external-resolver' const apiURL = '/api/external-resolver'
const req = await fetchViaHTTP(appPort, apiURL) const req = await fetchViaHTTP(appPort, apiURL)
expect(stderr.substr(startIdx)).not.toContain( expect(stderr.slice(startIdx)).not.toContain(
`API resolved without sending a response for ${apiURL}` `API resolved without sending a response for ${apiURL}`
) )
expect(await req.text()).toBe('hello world') expect(await req.text()).toBe('hello world')
......
...@@ -18,7 +18,7 @@ export default function (context) { ...@@ -18,7 +18,7 @@ export default function (context) {
.elementByCss('#about-via-link') .elementByCss('#about-via-link')
.getAttribute('href') .getAttribute('href')
expect(link.substr(link.length - 1)).toBe('/') expect(link.slice(-1)).toBe('/')
}) })
it('should not add trailing slash on Link when disabled', async () => { it('should not add trailing slash on Link when disabled', async () => {
...@@ -27,7 +27,7 @@ export default function (context) { ...@@ -27,7 +27,7 @@ export default function (context) {
.elementByCss('#about-via-link') .elementByCss('#about-via-link')
.getAttribute('href') .getAttribute('href')
expect(link.substr(link.length - 1)).not.toBe('/') expect(link.slice(-1)).not.toBe('/')
}) })
it('should do navigations via Link', async () => { it('should do navigations via Link', async () => {
......
...@@ -18,7 +18,7 @@ export default function (context) { ...@@ -18,7 +18,7 @@ export default function (context) {
.elementByCss('#about-via-link') .elementByCss('#about-via-link')
.getAttribute('href') .getAttribute('href')
expect(link.substr(link.length - 1)).toBe('/') expect(link.slice(-1)).toBe('/')
}) })
it('should not add any slash on hash Link', async () => { it('should not add any slash on hash Link', async () => {
...@@ -52,7 +52,7 @@ export default function (context) { ...@@ -52,7 +52,7 @@ export default function (context) {
.elementByCss('#about-via-link') .elementByCss('#about-via-link')
.getAttribute('href') .getAttribute('href')
expect(link.substr(link.length - 1)).not.toBe('/') expect(link.slice(-1)).not.toBe('/')
}) })
it('should do navigations via Link', async () => { it('should do navigations via Link', async () => {
......
...@@ -49,7 +49,7 @@ describe('server-side dev errors', () => { ...@@ -49,7 +49,7 @@ describe('server-side dev errors', () => {
const browser = await webdriver(appPort, '/gsp') const browser = await webdriver(appPort, '/gsp')
await check(async () => { await check(async () => {
const err = stderr.substr(stderrIdx) const err = stderr.slice(stderrIdx)
return err.includes('pages/gsp.js') && return err.includes('pages/gsp.js') &&
err.includes('6:2') && err.includes('6:2') &&
...@@ -81,7 +81,7 @@ describe('server-side dev errors', () => { ...@@ -81,7 +81,7 @@ describe('server-side dev errors', () => {
const browser = await webdriver(appPort, '/gssp') const browser = await webdriver(appPort, '/gssp')
await check(async () => { await check(async () => {
const err = stderr.substr(stderrIdx) const err = stderr.slice(stderrIdx)
return err.includes('pages/gssp.js') && return err.includes('pages/gssp.js') &&
err.includes('6:2') && err.includes('6:2') &&
...@@ -113,7 +113,7 @@ describe('server-side dev errors', () => { ...@@ -113,7 +113,7 @@ describe('server-side dev errors', () => {
const browser = await webdriver(appPort, '/blog/first') const browser = await webdriver(appPort, '/blog/first')
await check(async () => { await check(async () => {
const err = stderr.substr(stderrIdx) const err = stderr.slice(stderrIdx)
return err.includes('pages/blog/[slug].js') && return err.includes('pages/blog/[slug].js') &&
err.includes('6:2') && err.includes('6:2') &&
...@@ -145,7 +145,7 @@ describe('server-side dev errors', () => { ...@@ -145,7 +145,7 @@ describe('server-side dev errors', () => {
const browser = await webdriver(appPort, '/api/hello') const browser = await webdriver(appPort, '/api/hello')
await check(async () => { await check(async () => {
const err = stderr.substr(stderrIdx) const err = stderr.slice(stderrIdx)
return err.includes('pages/api/hello.js') && return err.includes('pages/api/hello.js') &&
err.includes('2:2') && err.includes('2:2') &&
...@@ -177,7 +177,7 @@ describe('server-side dev errors', () => { ...@@ -177,7 +177,7 @@ describe('server-side dev errors', () => {
const browser = await webdriver(appPort, '/api/blog/first') const browser = await webdriver(appPort, '/api/blog/first')
await check(async () => { await check(async () => {
const err = stderr.substr(stderrIdx) const err = stderr.slice(stderrIdx)
return err.includes('pages/api/blog/[slug].js') && return err.includes('pages/api/blog/[slug].js') &&
err.includes('2:2') && err.includes('2:2') &&
...@@ -202,7 +202,7 @@ describe('server-side dev errors', () => { ...@@ -202,7 +202,7 @@ describe('server-side dev errors', () => {
await webdriver(appPort, '/uncaught-rejection') await webdriver(appPort, '/uncaught-rejection')
await check(async () => { await check(async () => {
const err = stderr.substr(stderrIdx) const err = stderr.slice(stderrIdx)
return err.includes('pages/uncaught-rejection.js') && return err.includes('pages/uncaught-rejection.js') &&
err.includes('7:19') && err.includes('7:19') &&
...@@ -218,7 +218,7 @@ describe('server-side dev errors', () => { ...@@ -218,7 +218,7 @@ describe('server-side dev errors', () => {
await webdriver(appPort, '/uncaught-exception') await webdriver(appPort, '/uncaught-exception')
await check(async () => { await check(async () => {
const err = stderr.substr(stderrIdx) const err = stderr.slice(stderrIdx)
return err.includes('pages/uncaught-exception.js') && return err.includes('pages/uncaught-exception.js') &&
err.includes('7:10') && err.includes('7:10') &&
......
...@@ -142,7 +142,7 @@ export class NextStartInstance extends NextInstance { ...@@ -142,7 +142,7 @@ export class NextStartInstance extends NextInstance {
this.childProcess = undefined this.childProcess = undefined
resolve({ resolve({
exitCode: signal || code, exitCode: signal || code,
cliOutput: this.cliOutput.substr(curOutput), cliOutput: this.cliOutput.slice(curOutput),
}) })
}) })
}) })
......
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