File size: 9,973 Bytes
1e92f2d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 |
import type {
Issue,
PlainTraceItem,
StyledString,
TurbopackResult,
} from '../../../build/swc/types'
import { bold, green, magenta, red } from '../../../lib/picocolors'
import isInternal from '../is-internal'
import {
decodeMagicIdentifier,
MAGIC_IDENTIFIER_REGEX,
} from '../magic-identifier'
import type { EntryKey } from './entry-key'
import * as Log from '../../../build/output/log'
import type { NextConfigComplete } from '../../../server/config-shared'
import loadJsConfig from '../../../build/load-jsconfig'
type IssueKey = `${Issue['severity']}-${Issue['filePath']}-${string}-${string}`
export type IssuesMap = Map<IssueKey, Issue>
export type EntryIssuesMap = Map<EntryKey, IssuesMap>
export type TopLevelIssuesMap = IssuesMap
/**
* An error generated from emitted Turbopack issues. This can include build
* errors caused by issues with user code.
*/
export class ModuleBuildError extends Error {
name = 'ModuleBuildError'
}
/**
* Thin stopgap workaround layer to mimic existing wellknown-errors-plugin in webpack's build
* to emit certain type of errors into cli.
*/
export function isWellKnownError(issue: Issue): boolean {
const { title } = issue
const formattedTitle = renderStyledStringToErrorAnsi(title)
// TODO: add more well known errors
if (
formattedTitle.includes('Module not found') ||
formattedTitle.includes('Unknown module type')
) {
return true
}
return false
}
export function getIssueKey(issue: Issue): IssueKey {
return `${issue.severity}-${issue.filePath}-${JSON.stringify(
issue.title
)}-${JSON.stringify(issue.description)}`
}
export async function getTurbopackJsConfig(
dir: string,
nextConfig: NextConfigComplete
) {
const { jsConfig } = await loadJsConfig(dir, nextConfig)
return jsConfig ?? { compilerOptions: {} }
}
export function processIssues(
currentEntryIssues: EntryIssuesMap,
key: EntryKey,
result: TurbopackResult,
throwIssue: boolean,
logErrors: boolean
) {
const newIssues = new Map<IssueKey, Issue>()
currentEntryIssues.set(key, newIssues)
const relevantIssues = new Set()
for (const issue of result.issues) {
if (
issue.severity !== 'error' &&
issue.severity !== 'fatal' &&
issue.severity !== 'warning'
)
continue
const issueKey = getIssueKey(issue)
newIssues.set(issueKey, issue)
if (issue.severity !== 'warning') {
if (throwIssue) {
const formatted = formatIssue(issue)
relevantIssues.add(formatted)
}
// if we throw the issue it will most likely get handed and logged elsewhere
else if (logErrors && isWellKnownError(issue)) {
const formatted = formatIssue(issue)
Log.error(formatted)
}
}
}
if (relevantIssues.size && throwIssue) {
throw new ModuleBuildError([...relevantIssues].join('\n\n'))
}
}
export function formatIssue(issue: Issue) {
const { filePath, title, description, source, importTraces } = issue
let { documentationLink } = issue
const formattedTitle = renderStyledStringToErrorAnsi(title).replace(
/\n/g,
'\n '
)
// TODO: Use error codes to identify these
// TODO: Generalize adapting Turbopack errors to Next.js errors
if (formattedTitle.includes('Module not found')) {
// For compatiblity with webpack
// TODO: include columns in webpack errors.
documentationLink = 'https://nextjs.org/docs/messages/module-not-found'
}
const formattedFilePath = filePath
.replace('[project]/', './')
.replaceAll('/./', '/')
.replace('\\\\?\\', '')
let message = ''
if (source?.range) {
const { start } = source.range
message = `${formattedFilePath}:${start.line + 1}:${
start.column + 1
}\n${formattedTitle}`
} else if (formattedFilePath) {
message = `${formattedFilePath}\n${formattedTitle}`
} else {
message = formattedTitle
}
message += '\n'
if (
source?.range &&
source.source.content &&
// ignore Next.js/React internals, as these can often be huge bundled files.
!isInternal(filePath)
) {
const { start, end } = source.range
const { codeFrameColumns } =
require('next/dist/compiled/babel/code-frame') as typeof import('next/dist/compiled/babel/code-frame')
message +=
codeFrameColumns(
source.source.content,
{
start: {
line: start.line + 1,
column: start.column + 1,
},
end: {
line: end.line + 1,
column: end.column + 1,
},
},
{ forceColor: true }
).trim() + '\n\n'
}
if (description) {
if (
description.type === 'text' &&
description.value.includes(`Cannot find module 'sass'`)
) {
message +=
"To use Next.js' built-in Sass support, you first need to install `sass`.\n"
message += 'Run `npm i sass` or `yarn add sass` inside your workspace.\n'
message += '\nLearn more: https://nextjs.org/docs/messages/install-sass'
} else {
message += renderStyledStringToErrorAnsi(description) + '\n\n'
}
}
// TODO: make it possible to enable this for debugging, but not in tests.
// if (detail) {
// message += renderStyledStringToErrorAnsi(detail) + '\n\n'
// }
if (importTraces?.length) {
// This is the same logic as in turbopack/crates/turbopack-cli-utils/src/issue.rs
message += formatImportTraces(importTraces)
}
if (documentationLink) {
message += documentationLink + '\n\n'
}
return message
}
export function formatImportTraces(importTraces: PlainTraceItem[][]) {
// We end up with multiple traces when the file with the error is reachable from multiple
// different entry points (e.g. ssr, client)
let message = `Import trace${importTraces.length > 1 ? 's' : ''}:\n`
const everyTraceHasADistinctRootLayer =
new Set(importTraces.map(leafLayerName).filter((l) => l != null)).size ===
importTraces.length
for (let i = 0; i < importTraces.length; i++) {
const trace = importTraces[i]
const layer = leafLayerName(trace)
let traceIndent = ' '
// If this is true, layer must be present
if (everyTraceHasADistinctRootLayer) {
message += ` ${layer}:\n`
} else {
if (importTraces.length > 1) {
// Otherwise use simple 1 based indices to disambiguate
message += ` #${i + 1}`
if (layer) {
message += ` [${layer}]`
}
message += ':\n'
} else if (layer) {
message += ` [${layer}]:\n`
} else {
// If there is a single trace and no layer name just don't indent it.
traceIndent = ' '
}
}
message += formatIssueTrace(trace, traceIndent, !identicalLayers(trace))
}
return message
}
/** Returns the first present layer name in the trace */
function leafLayerName(items: PlainTraceItem[]): string | undefined {
for (const item of items) {
const layer = item.layer
if (layer != null) return layer
}
return undefined
}
/**
* Returns whether or not all items share the same layer.
* If a layer is absent we ignore it in this analysis
*/
function identicalLayers(items: PlainTraceItem[]): boolean {
const firstPresentLayer = items.findIndex((t) => t.layer != null)
if (firstPresentLayer === -1) return true // all layers are absent
const layer = items[firstPresentLayer].layer
for (let i = firstPresentLayer + 1; i < items.length; i++) {
const itemLayer = items[i].layer
if (itemLayer == null || itemLayer !== layer) {
return false
}
}
return true
}
function formatIssueTrace(
items: PlainTraceItem[],
indent: string,
printLayers: boolean
): string {
return `${items
.map((item) => {
let r = indent
if (item.fsName !== 'project') {
r += `[${item.fsName}]/`
} else {
// This is consistent with webpack's output
r += './'
}
r += item.path
if (printLayers && item.layer) {
r += ` [${item.layer}]`
}
return r
})
.join('\n')}\n\n`
}
export function isRelevantWarning(issue: Issue): boolean {
return issue.severity === 'warning' && !isNodeModulesIssue(issue)
}
function isNodeModulesIssue(issue: Issue): boolean {
if (issue.severity === 'warning' && issue.stage === 'config') {
// Override for the externalize issue
// `Package foo (serverExternalPackages or default list) can't be external`
if (
renderStyledStringToErrorAnsi(issue.title).includes("can't be external")
) {
return false
}
}
return (
issue.severity === 'warning' &&
(issue.filePath.match(/^(?:.*[\\/])?node_modules(?:[\\/].*)?$/) !== null ||
// Ignore Next.js itself when running next directly in the monorepo where it is not inside
// node_modules anyway.
// TODO(mischnic) prevent matches when this is published to npm
issue.filePath.startsWith('[project]/packages/next/'))
)
}
export function renderStyledStringToErrorAnsi(string: StyledString): string {
function decodeMagicIdentifiers(str: string): string {
return str.replaceAll(MAGIC_IDENTIFIER_REGEX, (ident) => {
try {
return magenta(`{${decodeMagicIdentifier(ident)}}`)
} catch (e) {
return magenta(`{${ident} (decoding failed: ${e})}`)
}
})
}
switch (string.type) {
case 'text':
return decodeMagicIdentifiers(string.value)
case 'strong':
return bold(red(decodeMagicIdentifiers(string.value)))
case 'code':
return green(decodeMagicIdentifiers(string.value))
case 'line':
return string.value.map(renderStyledStringToErrorAnsi).join('')
case 'stack':
return string.value.map(renderStyledStringToErrorAnsi).join('\n')
default:
throw new Error('Unknown StyledString type', string)
}
}
export function isPersistentCachingEnabled(
config: NextConfigComplete
): boolean {
return config.experimental?.turbopackPersistentCaching || false
}
|