Skip to content

Commit

Permalink
Merge branch 'canary' into fix-dynamic-middleware-routing.patch
Browse files Browse the repository at this point in the history
  • Loading branch information
nkzawa committed Mar 25, 2022
2 parents c3a0769 + b21e3c2 commit 4900888
Show file tree
Hide file tree
Showing 28 changed files with 57 additions and 50 deletions.
9 changes: 8 additions & 1 deletion .eslintrc.json
Expand Up @@ -203,7 +203,14 @@
"no-octal-escape": "warn",
"no-redeclare": ["warn", { "builtinGlobals": false }],
"no-regex-spaces": "warn",
"no-restricted-syntax": ["warn", "WithStatement"],
"no-restricted-syntax": [
"warn",
"WithStatement",
{
"message": "substr() is deprecated, use slice() or substring() instead",
"selector": "MemberExpression > Identifier[name='substr']"
}
],
"no-script-url": "warn",
"no-self-assign": "warn",
"no-self-compare": "warn",
Expand Down
2 changes: 1 addition & 1 deletion .github/actions/next-stats-action/src/add-comment.js
Expand Up @@ -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
Expand Down
3 changes: 1 addition & 2 deletions .github/actions/next-stats-action/src/run/collect-stats.js
Expand Up @@ -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`)}`
)
Expand Down
2 changes: 1 addition & 1 deletion examples/with-magic/pages/api/login.js
Expand Up @@ -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 }

Expand Down
4 changes: 2 additions & 2 deletions packages/next-codemod/transforms/cra-to-next.ts
Expand Up @@ -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)}}`
}
)}\`}`
}
Expand Down Expand Up @@ -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 '${
Expand Down
2 changes: 1 addition & 1 deletion packages/next-codemod/transforms/name-default-component.ts
Expand Up @@ -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 =>
Expand Down
4 changes: 2 additions & 2 deletions packages/next/build/index.ts
Expand Up @@ -1665,7 +1665,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('/')
Expand Down Expand Up @@ -1715,7 +1715,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
)

Expand Down
2 changes: 1 addition & 1 deletion packages/next/build/output/store.ts
Expand Up @@ -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`
)
Expand Down
2 changes: 1 addition & 1 deletion packages/next/build/utils.ts
Expand Up @@ -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}`
}
Expand Down
Expand Up @@ -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(
Expand Down
Expand Up @@ -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)
}
}

Expand Down
4 changes: 2 additions & 2 deletions packages/next/build/webpack/plugins/jsconfig-paths-plugin.ts
Expand Up @@ -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),
}
}

Expand Down
Expand Up @@ -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'
)
Expand All @@ -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(
Expand Down
9 changes: 5 additions & 4 deletions packages/next/client/dev/amp-dev.js
Expand Up @@ -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
)
})
Expand Down
2 changes: 1 addition & 1 deletion packages/next/export/index.ts
Expand Up @@ -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('/')
Expand Down
2 changes: 1 addition & 1 deletion packages/next/server/base-server.ts
Expand Up @@ -1145,7 +1145,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
Expand Down
2 changes: 1 addition & 1 deletion packages/next/server/dev/hot-reloader.ts
Expand Up @@ -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))
),
})
}
Expand Down
2 changes: 1 addition & 1 deletion packages/next/server/router-utils.ts
Expand Up @@ -3,7 +3,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
Expand Down
2 changes: 1 addition & 1 deletion packages/next/server/router.ts
Expand Up @@ -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
Expand Down
8 changes: 4 additions & 4 deletions packages/next/shared/lib/router/router.ts
Expand Up @@ -121,7 +121,7 @@ function addPathPrefix(path: string, prefix?: string) {

return (
normalizePathTrailingSlash(`${prefix}${pathname}`) +
path.substr(pathname.length)
path.slice(pathname.length)
)
}

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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('?')
Expand Down Expand Up @@ -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 }
Expand Down
2 changes: 1 addition & 1 deletion packages/next/shared/lib/router/utils/format-url.ts
Expand Up @@ -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 ||
Expand Down
Expand Up @@ -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: {
Expand Down
2 changes: 1 addition & 1 deletion packages/next/shared/lib/router/utils/route-regex.ts
Expand Up @@ -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
}

Expand Down
6 changes: 3 additions & 3 deletions test/integration/api-support/test/index.test.js
Expand Up @@ -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'
)
}
Expand Down Expand Up @@ -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`
)
})
Expand All @@ -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')
Expand Down
4 changes: 2 additions & 2 deletions test/integration/export-serverless/test/browser.js
Expand Up @@ -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 () => {
Expand All @@ -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 () => {
Expand Down
4 changes: 2 additions & 2 deletions test/integration/export/test/browser.js
Expand Up @@ -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 () => {
Expand Down Expand Up @@ -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 () => {
Expand Down

0 comments on commit 4900888

Please sign in to comment.