From db2567b01b2dd0a0c4f5862dc161b4584b9227f1 Mon Sep 17 00:00:00 2001 From: CommanderRoot Date: Thu, 24 Mar 2022 22:49:38 +0100 Subject: [PATCH] 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: Tobias Speicher Co-authored-by: Steven --- .../actions/next-stats-action/src/add-comment.js | 2 +- .../next-stats-action/src/run/collect-stats.js | 3 +-- examples/with-magic/pages/api/login.js | 2 +- packages/next-codemod/transforms/cra-to-next.ts | 4 ++-- .../transforms/name-default-component.ts | 2 +- packages/next/build/index.ts | 4 ++-- packages/next/build/output/store.ts | 2 +- packages/next/build/utils.ts | 2 +- .../loaders/next-serverless-loader/index.ts | 2 +- .../loaders/next-serverless-loader/utils.ts | 4 ++-- .../build/webpack/plugins/jsconfig-paths-plugin.ts | 4 ++-- .../plugins/next-trace-entrypoints-plugin.ts | 4 ++-- packages/next/client/dev/amp-dev.js | 9 +++++---- packages/next/export/index.ts | 2 +- packages/next/server/base-server.ts | 2 +- packages/next/server/dev/hot-reloader.ts | 2 +- packages/next/server/router.ts | 2 +- packages/next/shared/lib/router/router.ts | 8 ++++---- .../next/shared/lib/router/utils/format-url.ts | 2 +- .../shared/lib/router/utils/prepare-destination.ts | 2 +- .../next/shared/lib/router/utils/route-regex.ts | 2 +- test/integration/api-support/test/index.test.js | 6 +++--- test/integration/export-serverless/test/browser.js | 4 ++-- test/integration/export/test/browser.js | 4 ++-- .../server-side-dev-errors/test/index.test.js | 14 +++++++------- test/lib/next-modes/next-start.ts | 2 +- 26 files changed, 48 insertions(+), 48 deletions(-) diff --git a/.github/actions/next-stats-action/src/add-comment.js b/.github/actions/next-stats-action/src/add-comment.js index 2f2d9afc1578..a87306703404 100644 --- a/.github/actions/next-stats-action/src/add-comment.js +++ b/.github/actions/next-stats-action/src/add-comment.js @@ -20,7 +20,7 @@ const round = (num, places) => { const shortenLabel = (itemKey) => itemKey.length > 24 - ? `${itemKey.substr(0, 12)}..${itemKey.substr(itemKey.length - 12, 12)}` + ? `${itemKey.slice(0, 12)}..${itemKey.slice(-12)}` : itemKey const twoMB = 2 * 1024 * 1024 diff --git a/.github/actions/next-stats-action/src/run/collect-stats.js b/.github/actions/next-stats-action/src/run/collect-stats.js index d01d1a5e4fd2..0b585864d47b 100644 --- a/.github/actions/next-stats-action/src/run/collect-stats.js +++ b/.github/actions/next-stats-action/src/run/collect-stats.js @@ -74,8 +74,7 @@ module.exports = async function collectStats( const responseText = (await res.text()).trim() let fileName = pathname === '/' ? '/index' : pathname - if (fileName.endsWith('/')) - fileName = fileName.substr(0, fileName.length - 1) + if (fileName.endsWith('/')) fileName = fileName.slice(0, -1) logger( `Writing file to ${path.join(fetchedPagesDir, `${fileName}.html`)}` ) diff --git a/examples/with-magic/pages/api/login.js b/examples/with-magic/pages/api/login.js index b66975fa1fd3..ae6997950d55 100644 --- a/examples/with-magic/pages/api/login.js +++ b/examples/with-magic/pages/api/login.js @@ -3,7 +3,7 @@ import { setLoginSession } from '../../lib/auth' export default async function login(req, res) { try { - const didToken = req.headers.authorization.substr(7) + const didToken = req.headers.authorization.slice(7) const metadata = await magic.users.getMetadataByToken(didToken) const session = { ...metadata } diff --git a/packages/next-codemod/transforms/cra-to-next.ts b/packages/next-codemod/transforms/cra-to-next.ts index 7f218fb8d060..dc7c681fe451 100644 --- a/packages/next-codemod/transforms/cra-to-next.ts +++ b/packages/next-codemod/transforms/cra-to-next.ts @@ -218,7 +218,7 @@ class CraTransform { return `${reactName}={\`${value.replace( /%([a-zA-Z0-9_]{0,})%/g, (subStr) => { - return `\${process.env.${subStr.substr(1, subStr.length - 2)}}` + return `\${process.env.${subStr.slice(1, -1)}}` } )}\`}` } @@ -293,7 +293,7 @@ class CraTransform { : [...globalCssContext.cssImports] .map((file) => { if (!this.isCra) { - file = file.startsWith('/') ? file.substr(1) : file + file = file.startsWith('/') ? file.slice(1) : file } return `import '${ diff --git a/packages/next-codemod/transforms/name-default-component.ts b/packages/next-codemod/transforms/name-default-component.ts index ef81c9a6799f..01bd3482f577 100644 --- a/packages/next-codemod/transforms/name-default-component.ts +++ b/packages/next-codemod/transforms/name-default-component.ts @@ -13,7 +13,7 @@ const camelCase = (value: string): string => { const val = value.replace(/[-_\s.]+(.)?/g, (_match, chr) => 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 => diff --git a/packages/next/build/index.ts b/packages/next/build/index.ts index e1176656fe08..ab9f40a27a6b 100644 --- a/packages/next/build/index.ts +++ b/packages/next/build/index.ts @@ -1659,7 +1659,7 @@ export default async function build( // strip leading / and then recurse number of nested dirs // to place from base folder originPage - .substr(1) + .slice(1) .split('/') .map(() => '..') .join('/') @@ -1709,7 +1709,7 @@ export default async function build( for (const locale of i18n.locales) { const curPath = `/${locale}${page === '/' ? '' : page}` const localeExt = page === '/' ? path.extname(file) : '' - const relativeDestNoPages = relativeDest.substr( + const relativeDestNoPages = relativeDest.slice( 'pages/'.length ) diff --git a/packages/next/build/output/store.ts b/packages/next/build/output/store.ts index ff2edad64ed0..4c0af9268030 100644 --- a/packages/next/build/output/store.ts +++ b/packages/next/build/output/store.ts @@ -81,7 +81,7 @@ store.subscribe((state) => { const matches = cleanError.match(/\[.*\]=/) if (matches) { for (const match of matches) { - const prop = (match.split(']').shift() || '').substr(1) + const prop = (match.split(']').shift() || '').slice(1) 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` ) diff --git a/packages/next/build/utils.ts b/packages/next/build/utils.ts index 618a826307de..a2bf0c53337b 100644 --- a/packages/next/build/utils.ts +++ b/packages/next/build/utils.ts @@ -723,7 +723,7 @@ export async function buildStaticPaths( let cleanedEntry = entry if (localePathResult.detectedLocale) { - cleanedEntry = entry.substr(localePathResult.detectedLocale.length + 1) + cleanedEntry = entry.slice(localePathResult.detectedLocale.length + 1) } else if (defaultLocale) { entry = `/${defaultLocale}${entry}` } diff --git a/packages/next/build/webpack/loaders/next-serverless-loader/index.ts b/packages/next/build/webpack/loaders/next-serverless-loader/index.ts index e9f8630262fc..08e517fabed8 100644 --- a/packages/next/build/webpack/loaders/next-serverless-loader/index.ts +++ b/packages/next/build/webpack/loaders/next-serverless-loader/index.ts @@ -55,7 +55,7 @@ const nextServerlessLoader: webpack.loader.Loader = function () { i18n, reactRoot, }: 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 reactLoadableManifest = join(distDir, REACT_LOADABLE_MANIFEST).replace( diff --git a/packages/next/build/webpack/loaders/next-serverless-loader/utils.ts b/packages/next/build/webpack/loaders/next-serverless-loader/utils.ts index c5c2b5197906..13afb72bfa34 100644 --- a/packages/next/build/webpack/loaders/next-serverless-loader/utils.ts +++ b/packages/next/build/webpack/loaders/next-serverless-loader/utils.ts @@ -274,9 +274,9 @@ export function getUtils({ } pathname = - pathname.substr(0, paramIdx) + + pathname.slice(0, paramIdx) + (paramValue || '') + - pathname.substr(paramIdx + builtParam.length) + pathname.slice(paramIdx + builtParam.length) } } diff --git a/packages/next/build/webpack/plugins/jsconfig-paths-plugin.ts b/packages/next/build/webpack/plugins/jsconfig-paths-plugin.ts index 7089cdfa42bb..43b2f594de47 100644 --- a/packages/next/build/webpack/plugins/jsconfig-paths-plugin.ts +++ b/packages/next/build/webpack/plugins/jsconfig-paths-plugin.ts @@ -44,8 +44,8 @@ export function tryParsePattern(pattern: string): Pattern | undefined { return indexOfStar === -1 ? undefined : { - prefix: pattern.substr(0, indexOfStar), - suffix: pattern.substr(indexOfStar + 1), + prefix: pattern.slice(0, indexOfStar), + suffix: pattern.slice(indexOfStar + 1), } } diff --git a/packages/next/build/webpack/plugins/next-trace-entrypoints-plugin.ts b/packages/next/build/webpack/plugins/next-trace-entrypoints-plugin.ts index 21b14ad40165..0e25b554f149 100644 --- a/packages/next/build/webpack/plugins/next-trace-entrypoints-plugin.ts +++ b/packages/next/build/webpack/plugins/next-trace-entrypoints-plugin.ts @@ -541,7 +541,7 @@ export class TraceEntryPointsPlugin implements webpack5.WebpackPluginInstance { ) { requestPath = ( resContext.descriptionFileRoot + - request.substr(getPkgName(request)?.length || 0) + + request.slice(getPkgName(request)?.length || 0) + nodePath.sep + 'package.json' ) @@ -555,7 +555,7 @@ export class TraceEntryPointsPlugin implements webpack5.WebpackPluginInstance { (separatorIndex = requestPath.lastIndexOf('/')) > rootSeparatorIndex ) { - requestPath = requestPath.substr(0, separatorIndex) + requestPath = requestPath.slice(0, separatorIndex) const curPackageJsonPath = `${requestPath}/package.json` if (await job.isFile(curPackageJsonPath)) { await job.emitFile( diff --git a/packages/next/client/dev/amp-dev.js b/packages/next/client/dev/amp-dev.js index 36b9af20b048..03cc51b47499 100644 --- a/packages/next/client/dev/amp-dev.js +++ b/packages/next/client/dev/amp-dev.js @@ -48,12 +48,13 @@ async function tryApplyUpdates() { ).some((mod) => { return ( mod.indexOf( - `pages${curPage.substr(0, 1) === '/' ? curPage : `/${curPage}`}` + `pages${curPage.startsWith('/') ? curPage : `/${curPage}`}` ) !== -1 || mod.indexOf( - `pages${ - curPage.substr(0, 1) === '/' ? curPage : `/${curPage}` - }`.replace(/\//g, '\\') + `pages${curPage.startsWith('/') ? curPage : `/${curPage}`}`.replace( + /\//g, + '\\' + ) ) !== -1 ) }) diff --git a/packages/next/export/index.ts b/packages/next/export/index.ts index 937c01ab089c..f2e468fe187d 100644 --- a/packages/next/export/index.ts +++ b/packages/next/export/index.ts @@ -646,7 +646,7 @@ export default async function exportApp( // strip leading / and then recurse number of nested dirs // to place from base folder pageName - .substr(1) + .slice(1) .split('/') .map(() => '..') .join('/') diff --git a/packages/next/server/base-server.ts b/packages/next/server/base-server.ts index 5168da0997e9..68d1eca05ffa 100644 --- a/packages/next/server/base-server.ts +++ b/packages/next/server/base-server.ts @@ -1144,7 +1144,7 @@ export default abstract class Server { // ensure correct status is set when visiting a status page // directly e.g. /500 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 diff --git a/packages/next/server/dev/hot-reloader.ts b/packages/next/server/dev/hot-reloader.ts index bcd58454ab57..d2ca2c8f3d55 100644 --- a/packages/next/server/dev/hot-reloader.ts +++ b/packages/next/server/dev/hot-reloader.ts @@ -733,7 +733,7 @@ export default class HotReloader { this.send({ event: 'serverOnlyChanges', pages: serverOnlyChanges.map((pg) => - denormalizePagePath(pg.substr('pages'.length)) + denormalizePagePath(pg.slice('pages'.length)) ), }) } diff --git a/packages/next/server/router.ts b/packages/next/server/router.ts index b101f838544e..075d307a14cd 100644 --- a/packages/next/server/router.ts +++ b/packages/next/server/router.ts @@ -56,7 +56,7 @@ export function replaceBasePath(pathname: string, basePath: string): string { // and doesn't contain extra chars e.g. basePath /docs // should replace for /docs, /docs/, /docs/a but not /docsss if (hasBasePath(pathname, basePath)) { - pathname = pathname.substr(basePath.length) + pathname = pathname.slice(basePath.length) if (!pathname.startsWith('/')) pathname = `/${pathname}` } return pathname diff --git a/packages/next/shared/lib/router/router.ts b/packages/next/shared/lib/router/router.ts index 804f18a0d67c..4abfb6c2e07c 100644 --- a/packages/next/shared/lib/router/router.ts +++ b/packages/next/shared/lib/router/router.ts @@ -121,7 +121,7 @@ function addPathPrefix(path: string, prefix?: string) { return ( normalizePathTrailingSlash(`${prefix}${pathname}`) + - path.substr(pathname.length) + path.slice(pathname.length) ) } @@ -177,7 +177,7 @@ export function delLocale(path: string, locale?: string) { (pathLower.startsWith('/' + localeLower + '/') || pathLower === '/' + localeLower) ? (pathname.length === locale.length + 1 ? '/' : '') + - path.substr(locale.length + 1) + path.slice(locale.length + 1) : path } return path @@ -320,7 +320,7 @@ export function resolveHref( // invalid and will never match a Next.js page/file const urlProtoMatch = urlAsString.match(/^[a-zA-Z]{1,}:\/\//) const urlAsStringNoProto = urlProtoMatch - ? urlAsString.substr(urlProtoMatch[0].length) + ? urlAsString.slice(urlProtoMatch[0].length) : urlAsString const urlParts = urlAsStringNoProto.split('?') @@ -751,7 +751,7 @@ export default class Router implements BaseRouter { if (typeof window !== 'undefined') { // make sure "as" doesn't start with double slashes or else it can // 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 // we have to register the initial route upon initialization const options: TransitionOptions = { locale } diff --git a/packages/next/shared/lib/router/utils/format-url.ts b/packages/next/shared/lib/router/utils/format-url.ts index 205ab30a7142..efc9df8c4ea4 100644 --- a/packages/next/shared/lib/router/utils/format-url.ts +++ b/packages/next/shared/lib/router/utils/format-url.ts @@ -51,7 +51,7 @@ export function formatUrl(urlObj: UrlObject) { let search = urlObj.search || (query && `?${query}`) || '' - if (protocol && protocol.substr(-1) !== ':') protocol += ':' + if (protocol && !protocol.endsWith(':')) protocol += ':' if ( urlObj.slashes || diff --git a/packages/next/shared/lib/router/utils/prepare-destination.ts b/packages/next/shared/lib/router/utils/prepare-destination.ts index f91526c4d353..5653948c4fd9 100644 --- a/packages/next/shared/lib/router/utils/prepare-destination.ts +++ b/packages/next/shared/lib/router/utils/prepare-destination.ts @@ -109,7 +109,7 @@ export function compileNonPath(value: string, params: Params): string { // the value needs to start with a forward-slash to be compiled // correctly - return compile(`/${value}`, { validate: false })(params).substr(1) + return compile(`/${value}`, { validate: false })(params).slice(1) } export function prepareDestination(args: { diff --git a/packages/next/shared/lib/router/utils/route-regex.ts b/packages/next/shared/lib/router/utils/route-regex.ts index ca26d12a1e1f..0787b623437b 100644 --- a/packages/next/shared/lib/router/utils/route-regex.ts +++ b/packages/next/shared/lib/router/utils/route-regex.ts @@ -73,7 +73,7 @@ export function getParametrizedRoute(route: string) { if (cleanedKey.length === 0 || cleanedKey.length > 30) { invalidKey = true } - if (!isNaN(parseInt(cleanedKey.substr(0, 1)))) { + if (!isNaN(parseInt(cleanedKey.slice(0, 1)))) { invalidKey = true } diff --git a/test/integration/api-support/test/index.test.js b/test/integration/api-support/test/index.test.js index b81e387c7f82..09df1e904625 100644 --- a/test/integration/api-support/test/index.test.js +++ b/test/integration/api-support/test/index.test.js @@ -50,7 +50,7 @@ function runTests(dev = false) { expect(res2.headers.get('transfer-encoding')).toBe(null) if (dev) { - expect(stderr.substr(stderrIdx)).toContain( + expect(stderr.slice(stderrIdx)).toContain( 'A body was attempted to be set with a 204 statusCode' ) } @@ -509,7 +509,7 @@ function runTests(dev = false) { 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 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` ) }) @@ -527,7 +527,7 @@ function runTests(dev = false) { const startIdx = stderr.length > 0 ? stderr.length - 1 : stderr.length const apiURL = '/api/external-resolver' 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}` ) expect(await req.text()).toBe('hello world') diff --git a/test/integration/export-serverless/test/browser.js b/test/integration/export-serverless/test/browser.js index 4749bd0cd63a..c39e0286a036 100644 --- a/test/integration/export-serverless/test/browser.js +++ b/test/integration/export-serverless/test/browser.js @@ -18,7 +18,7 @@ export default function (context) { .elementByCss('#about-via-link') .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 () => { @@ -27,7 +27,7 @@ export default function (context) { .elementByCss('#about-via-link') .getAttribute('href') - expect(link.substr(link.length - 1)).not.toBe('/') + expect(link.slice(-1)).not.toBe('/') }) it('should do navigations via Link', async () => { diff --git a/test/integration/export/test/browser.js b/test/integration/export/test/browser.js index d6418e631679..a95ea501de85 100644 --- a/test/integration/export/test/browser.js +++ b/test/integration/export/test/browser.js @@ -18,7 +18,7 @@ export default function (context) { .elementByCss('#about-via-link') .getAttribute('href') - expect(link.substr(link.length - 1)).toBe('/') + expect(link.slice(-1)).toBe('/') }) it('should not add any slash on hash Link', async () => { @@ -52,7 +52,7 @@ export default function (context) { .elementByCss('#about-via-link') .getAttribute('href') - expect(link.substr(link.length - 1)).not.toBe('/') + expect(link.slice(-1)).not.toBe('/') }) it('should do navigations via Link', async () => { diff --git a/test/integration/server-side-dev-errors/test/index.test.js b/test/integration/server-side-dev-errors/test/index.test.js index 11a40d4f08c0..f2570ffcd184 100644 --- a/test/integration/server-side-dev-errors/test/index.test.js +++ b/test/integration/server-side-dev-errors/test/index.test.js @@ -49,7 +49,7 @@ describe('server-side dev errors', () => { const browser = await webdriver(appPort, '/gsp') await check(async () => { - const err = stderr.substr(stderrIdx) + const err = stderr.slice(stderrIdx) return err.includes('pages/gsp.js') && err.includes('6:2') && @@ -81,7 +81,7 @@ describe('server-side dev errors', () => { const browser = await webdriver(appPort, '/gssp') await check(async () => { - const err = stderr.substr(stderrIdx) + const err = stderr.slice(stderrIdx) return err.includes('pages/gssp.js') && err.includes('6:2') && @@ -113,7 +113,7 @@ describe('server-side dev errors', () => { const browser = await webdriver(appPort, '/blog/first') await check(async () => { - const err = stderr.substr(stderrIdx) + const err = stderr.slice(stderrIdx) return err.includes('pages/blog/[slug].js') && err.includes('6:2') && @@ -145,7 +145,7 @@ describe('server-side dev errors', () => { const browser = await webdriver(appPort, '/api/hello') await check(async () => { - const err = stderr.substr(stderrIdx) + const err = stderr.slice(stderrIdx) return err.includes('pages/api/hello.js') && err.includes('2:2') && @@ -177,7 +177,7 @@ describe('server-side dev errors', () => { const browser = await webdriver(appPort, '/api/blog/first') await check(async () => { - const err = stderr.substr(stderrIdx) + const err = stderr.slice(stderrIdx) return err.includes('pages/api/blog/[slug].js') && err.includes('2:2') && @@ -202,7 +202,7 @@ describe('server-side dev errors', () => { await webdriver(appPort, '/uncaught-rejection') await check(async () => { - const err = stderr.substr(stderrIdx) + const err = stderr.slice(stderrIdx) return err.includes('pages/uncaught-rejection.js') && err.includes('7:19') && @@ -218,7 +218,7 @@ describe('server-side dev errors', () => { await webdriver(appPort, '/uncaught-exception') await check(async () => { - const err = stderr.substr(stderrIdx) + const err = stderr.slice(stderrIdx) return err.includes('pages/uncaught-exception.js') && err.includes('7:10') && diff --git a/test/lib/next-modes/next-start.ts b/test/lib/next-modes/next-start.ts index 4317a28fb1ea..a1b89f25a9f4 100644 --- a/test/lib/next-modes/next-start.ts +++ b/test/lib/next-modes/next-start.ts @@ -142,7 +142,7 @@ export class NextStartInstance extends NextInstance { this.childProcess = undefined resolve({ exitCode: signal || code, - cliOutput: this.cliOutput.substr(curOutput), + cliOutput: this.cliOutput.slice(curOutput), }) }) })