Unverified Commit 528c1cdf authored by Sebastian "Sebbie" Silbermann's avatar Sebastian "Sebbie" Silbermann Committed by GitHub

[16.3.x] Stop generating error codes (#97780)

Co-authored-by: 's avatarJiwon Choi <devjiwonchoi@gmail.com>
parent d0ac8828
......@@ -7,6 +7,3 @@ packages/next/compiled/** -text linguist-vendored
# Make next/src/build folder indexable for github search
build/** linguist-generated=false
# Custom merge driver for auto-generated errors.json
packages/next/errors.json merge=errors-json
......@@ -98,8 +98,6 @@
"swc-build-wasm": "tsx scripts/build-wasm.cjs",
"build-turbopack-cli": "cargo build -p turbopack-cli --release",
"sweep": "tsx scripts/sweep.cjs",
"check-error-codes": "node packages/next/check-error-codes.js",
"update-error-codes": "cd packages/next && pnpm taskr compile check_error_codes",
"build-error-code-plugin": "crates/next-error-code-swc-plugin/build-and-move.sh",
"storybook": "turbo run storybook",
"build-storybook": "turbo run build-storybook",
......
const os = require('os')
const path = require('path')
const fs = require('fs/promises')
const errorsDir = path.join(__dirname, '.errors')
// This script checks for new error codes in .errors directory and consolidates them into errors.json.
// It will fail if new error codes are found, after consolidating them, to ensure error codes are
// properly reviewed and committed.
async function main() {
// Check if .errors directory exists
try {
await fs.access(errorsDir)
} catch {
process.exit(0)
}
let existingErrors = {}
// Load existing errors.json if it exists
try {
existingErrors = JSON.parse(
await fs.readFile(path.join(__dirname, 'errors.json'), 'utf8')
)
} catch {
// Start fresh if errors.json doesn't exist
}
// Calculate next error code
const nextInitialCode =
Object.keys(existingErrors).length > 0
? Math.max(...Object.keys(existingErrors).map(Number)) + 1
: 1
// Process new error files
const errorFiles = [...(await fs.readdir(errorsDir))].map((file) =>
path.join(errorsDir, file)
)
let newErrorCount = 0
for (const file of errorFiles) {
const { errorMessage } = JSON.parse(await fs.readFile(file, 'utf8'))
// Check if message already exists
const existingCode = Object.entries(existingErrors).find(
([_, msg]) => msg === errorMessage
)?.[0]
if (!existingCode) {
// Only add if message is new
const code = nextInitialCode + newErrorCount
existingErrors[code] = errorMessage
newErrorCount++
}
}
// Write updated errors and cleanup
await fs.writeFile(
path.join(__dirname, 'errors.json'),
JSON.stringify(existingErrors, null, 2) +
// Formatters would add these anyway
os.EOL
)
await fs.rm(errorsDir, { recursive: true, force: true })
process.exit(1)
}
main().catch(console.error)
......@@ -3,7 +3,6 @@ const glob = require('glob')
const fs = require('fs/promises')
const resolveFrom = require('resolve-from')
const execa = require('execa')
const process = require('process')
const recast = require('recast')
export async function next__polyfill_nomodule(task, opts) {
......@@ -2723,10 +2722,7 @@ export async function diagnostics(task, opts) {
}
export async function build(task, opts) {
await task.serial(
['precompile', 'compile', 'check_error_codes', 'generate_types'],
opts
)
await task.serial(['precompile', 'compile', 'generate_types'], opts)
}
export async function generate_types(task, opts) {
......@@ -2747,25 +2743,6 @@ export async function generate_types(task, opts) {
}
}
export async function check_error_codes(task, opts) {
try {
await execa.command('pnpm -w run check-error-codes', {
stdio: 'inherit',
})
} catch (err) {
if (process.env.CI) {
await execa.command(
'echo check_error_codes FAILED: There are new errors introduced but no corresponding error codes are found in errors.json file, so make sure you run `pnpm build` or `pnpm update-error-codes` and then commit the change in errors.json.',
{
stdio: 'inherit',
}
)
process.exit(1)
}
await task.start('compile', opts)
}
}
export default async function (task) {
const opts = { dev: true }
await task.clear('dist')
......
......@@ -6,14 +6,3 @@ await execa('git', ['config', 'index.skipHash', 'false'], {
stdio: 'inherit',
reject: false,
})
// Enable the errors.json git merge driver.
// It can be disabled by running:
//
// scripts/merge-errors-json/uninstall
//
// or by manually removing the `[merge "errors-json"]` section from your .git/config.
await execa('scripts/merge-errors-json/install', [], {
stdio: 'inherit',
reject: false,
})
#!/bin/sh
driver_name='errors-json'
git config merge."$driver_name".name 'Automatically merge packages/next/errors.json'
git config merge."$driver_name".driver 'node scripts/merge-errors-json/merge.mjs %A %O %B'
// @ts-check
/**
* Git merge driver for packages/next/errors.json
*
* This script automatically resolves merge conflicts in the auto-generated
* errors.json file by reassigning error codes to avoid conflicts.
*
* Usage: node merge-errors-json.mjs <current> <base> <other> [<marker-size>]
*
* Arguments:
* - current: Path to the current version (our changes)
* - base: Path to the common ancestor version
* - other: Path to the other version (their changes)
* - marker-size: Size of conflict markers (optional, defaults to 7)
*
* Exit codes:
* - 0: Merge successful, result written to current file
* - 1: Merge failed, conflicts remain
*/
import { readFileSync, writeFileSync } from 'node:fs'
function main() {
const args = process.argv.slice(2)
if (args.length < 3) {
console.error(
'Usage: node merge-errors-json.mjs <current> <base> <other> [<marker-size>]'
)
process.exit(1)
}
const [currentPath, basePath, otherPath] = args
try {
const base = readJsonSync(basePath)
const current = readJsonSync(currentPath)
const other = readJsonSync(otherPath)
const merged = mergeErrors(base, current, other)
// Git expects the result to be written to the "current" file
writeJsonSync(currentPath, merged)
const addedCount = Object.keys(merged).length - Object.keys(current).length
console.error(
`merge-errors-json: added ${addedCount === 1 ? '1 new message' : `${addedCount} new messages`} to errors.json`
)
process.exit(0)
} catch (error) {
console.error('merge-errors-json: merge failed:', error.message)
console.error()
console.error(
[
'if this error persists, you can disable the merge driver by running',
'',
' scripts/merge-errors-json/uninstall',
'',
'or by manually removing the `[merge "errors-json"]` section from your .git/config.',
].join('\n')
)
process.exit(1)
}
}
/**
* @typedef {Record<string, string>} ErrorsMap
*/
/**
* Merge three versions of errors.json, resolving conflicts by assigning new sequential IDs
* @param {ErrorsMap} base - Base version (common ancestor)
* @param {ErrorsMap} current - Current version (our changes, or the state of the branch we're rebasing onto)
* @param {ErrorsMap} other - Other version (their changes, or the state the branch we're rebasing, a.k.a. "incoming")
* @returns {ErrorsMap}
*/
function mergeErrors(base, current, other) {
/** @type {ErrorsMap} */
const result = { ...current }
/** @type {Set<string>} */
const existingMessages = new Set(Object.values(result))
let nextKey = getMaxNumericKey(result) + 1
for (const message of getNewMessages(base, other)) {
if (existingMessages.has(message)) {
continue
}
const key = nextKey++
result[key] = message
existingMessages.add(message)
}
return result
}
/**
* Returns the largest numeric key in the map, or 0 if there are no numeric
* keys. Existing entries may have gaps (e.g. when error codes were retired),
* so we can't rely on `Object.keys(result).length` to derive the next id.
* @param {ErrorsMap} map
*/
function getMaxNumericKey(map) {
let max = 0
for (const key of Object.keys(map)) {
const n = Number(key)
if (Number.isInteger(n) && n > max) {
max = n
}
}
return max
}
function getNewMessages(
/** @type {ErrorsMap} */ prev,
/** @type {ErrorsMap} */ current
) {
const existing = new Set(Object.values(prev))
return Object.values(current).filter((msg) => !existing.has(msg))
}
function readJsonSync(/** @type {string} */ filePath) {
const content = readFileSync(filePath, 'utf8')
return JSON.parse(content)
}
function writeJsonSync(
/** @type {string} */ filePath,
/** @type {any} */ value
) {
const content = JSON.stringify(value, null, 2) + '\n'
writeFileSync(filePath, content, 'utf8')
}
main()
#!/bin/sh
driver_name='errors-json'
git config --remove-section merge."$driver_name"
......@@ -140,7 +140,7 @@ Confirm the pre-step with `next build`. The build is the proof, not the codemod
After the build passes, confirm the root layout got an opt-out (`grep -n "export const instant" app/layout.*`). The root layout renders every route, including framework routes like `/_not-found`, so if it was missed, add `export const instant = false` to it by hand.
Synthetic routes like `/_not-found` have no user file — when they block, fix the root layout's opt-out, not the synthetic route. Client Components (`"use client"`) get no opt-out (it's a build error — `E1344` — to export `instant` from them), but they are not a rare blocker. The high-frequency case is a client component in the root layout's nav or header calling `usePathname()`/`useSearchParams()`: it blocks _every_ dynamic route with `blocking-prerender-client-hook`, and static routes pass (the pathname is known at prerender), which masks it until you reach a dynamic segment. It's not an ancestor-data fix — follow the [error's docs page](https://nextjs.org/docs/messages/blocking-prerender-client-hook) for the `<Suspense>` recipe. Only when a client route blocks on _server_ data do you fix that data in its ancestor.
Synthetic routes like `/_not-found` have no user file — when they block, fix the root layout's opt-out, not the synthetic route. Client Components (`"use client"`) get no opt-out (it's a build error to export `instant` from them), but they are not a rare blocker. The high-frequency case is a client component in the root layout's nav or header calling `usePathname()`/`useSearchParams()`: it blocks _every_ dynamic route with `blocking-prerender-client-hook`, and static routes pass (the pathname is known at prerender), which masks it until you reach a dynamic segment. It's not an ancestor-data fix — follow the [error's docs page](https://nextjs.org/docs/messages/blocking-prerender-client-hook) for the `<Suspense>` recipe. Only when a client route blocks on _server_ data do you fix that data in its ancestor.
### end of the pre-step: check in
......
import { mkdtempSync, rmSync } from 'fs'
import { writeJSONSync, readJSONSync } from 'fs-extra'
import { join } from 'path'
import { tmpdir } from 'os'
import execa from 'execa'
describe('merge-errors-json driver', () => {
it('should correctly merge errors.json files with conflicting new entries', async () => {
const base = {
'1': 'Original message 1',
'2': 'Original message 2',
}
const current = {
...base,
'3': 'From a conflicting branch that was merged first 1',
'4': 'From a conflicting branch that was merged first 2',
}
const rebased = await simulateRebase({
base,
current,
incoming: {
...base,
'3': 'From our branch 1',
'4': 'From our branch 2',
},
})
expect(rebased).toEqual({
...current,
'5': 'From our branch 1',
'6': 'From our branch 2',
})
})
it('should handle empty base file', async () => {
const base = {}
const current = {
'1': 'Message from a conflicting branch that was merged first',
}
const rebased = await simulateRebase({
base,
current,
incoming: { '1': 'New message from our branch' },
})
expect(rebased).toEqual({
...current,
'2': 'New message from our branch',
})
})
it('should handle stacked PRs', async () => {
const base = {
'1': 'Original message 1',
'2': 'Original message 2',
}
const current = {
...base,
'3': 'Message from a conflicting branch that was merged first',
}
const ourBranch1 = {
...base,
'3': 'New message from our-branch-1',
}
const ourBranch2 = {
...ourBranch1,
'4': 'New message from our-branch-2', // will conflict after our-branch-1 is rebased and its error is renumbered to 4
}
const branch1Rebased = await simulateRebase({
base: base,
current: current,
incoming: ourBranch1,
})
expect(branch1Rebased).toEqual({
...current,
'4': 'New message from our-branch-1',
})
const branch2Rebased = await simulateRebase({
base: ourBranch1,
current: branch1Rebased,
incoming: ourBranch2,
})
expect(branch2Rebased).toEqual({
...branch1Rebased,
'5': 'New message from our-branch-2',
})
})
})
type Contents = Record<string, string>
async function simulateRebase({
base,
current,
incoming,
}: {
base: Contents
current: Contents
incoming: Contents
}) {
const tempDir = mkdtempSync(join(tmpdir(), 'merge-driver-test-'))
const paths = {
base: join(tempDir, 'base.json'),
current: join(tempDir, 'current.json'),
other: join(tempDir, 'other.json'),
}
writeJSONSync(paths.base, base, { spaces: 2 })
// during a rebase, the branch we're rebasing onto will be "current", and our commit will be "other"
writeJSONSync(paths.current, current, { spaces: 2 })
writeJSONSync(paths.other, incoming, { spaces: 2 })
await execa('node', [
'scripts/merge-errors-json/merge.mjs',
paths.current,
paths.base,
paths.other,
])
const result = readJSONSync(paths.current)
rmSync(tempDir, { recursive: true, force: true })
return result
}
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