Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

decode magic identifiers #61658

Merged
merged 2 commits into from
Feb 6, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import type { StackFrame } from 'next/dist/compiled/stacktrace-parser'
import stripAnsi from 'next/dist/compiled/strip-ansi'
import { getFrameSource } from '../../helpers/stack-frame'
import { useOpenInEditor } from '../../helpers/use-open-in-editor'
import { HotlinkedText } from '../hot-linked-text'

export type CodeFrameProps = { stackFrame: StackFrame; codeFrame: string }

Expand Down Expand Up @@ -66,7 +67,8 @@ export const CodeFrame: React.FC<CodeFrameProps> = function CodeFrame({
title="Click to open in your editor"
>
<span>
{getFrameSource(stackFrame)} @ {stackFrame.methodName}
{getFrameSource(stackFrame)} @{' '}
<HotlinkedText text={stackFrame.methodName} />
</span>
<svg
xmlns="http://www.w3.org/2000/svg"
Expand Down

This file was deleted.

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,29 +1,51 @@
import React from 'react'
import { getWordsAndWhitespaces } from './get-words-and-whitespaces'
import {
decodeMagicIdentifier,
MAGIC_IDENTIFIER_REGEX,
} from '../../../../../../shared/lib/magic-identifier'

const linkRegex = /https?:\/\/[^\s/$.?#].[^\s"]*/i

const splitRegexp = new RegExp(`(${MAGIC_IDENTIFIER_REGEX.source}|\\s+)`)

export const HotlinkedText: React.FC<{
text: string
}> = function HotlinkedText(props) {
const { text } = props

const wordsAndWhitespaces = getWordsAndWhitespaces(text)
const wordsAndWhitespaces = text.split(splitRegexp)

return (
<>
{linkRegex.test(text)
? wordsAndWhitespaces.map((word, index) => {
if (linkRegex.test(word)) {
return (
<React.Fragment key={`link-${index}`}>
<a href={word}>{word}</a>
</React.Fragment>
)
}
return <React.Fragment key={`text-${index}`}>{word}</React.Fragment>
})
: text}
{wordsAndWhitespaces.map((word, index) => {
if (linkRegex.test(word)) {
return (
<React.Fragment key={`link-${index}`}>
<a href={word}>{word}</a>
</React.Fragment>
)
}
try {
const decodedWord = decodeMagicIdentifier(word)
if (decodedWord !== word) {
return (
<i key={`ident-${index}`}>
{'{'}
{decodedWord}
{'}'}
</i>
)
}
} catch (e) {
return (
<i key={`ident-${index}`}>
{'{'}
{word} (decoding failed: {'' + e}){'}'}
</i>
)
}
return <React.Fragment key={`text-${index}`}>{word}</React.Fragment>
})}
</>
)
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
type OriginalStackFrame,
} from '../../helpers/stack-frame'
import { useOpenInEditor } from '../../helpers/use-open-in-editor'
import { HotlinkedText } from '../../components/hot-linked-text'

export const CallStackFrame: React.FC<{
frame: OriginalStackFrame
Expand All @@ -27,7 +28,7 @@ export const CallStackFrame: React.FC<{
return (
<div data-nextjs-call-stack-frame>
<h3 data-nextjs-frame-expanded={Boolean(frame.expanded)}>
{f.methodName}
<HotlinkedText text={f.methodName} />
</h3>
<div
data-has-source={hasSource ? 'true' : undefined}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import React from 'react'
import type { ComponentStackFrame } from '../../helpers/parse-component-stack'
import { useOpenInEditor } from '../../helpers/use-open-in-editor'
import { HotlinkedText } from '../../components/hot-linked-text'

function EditorLink({
children,
Expand Down Expand Up @@ -94,7 +95,9 @@ export function ComponentStackFrameRow({

return (
<div data-nextjs-component-stack-frame>
<h3>{component}</h3>
<h3>
<HotlinkedText text={component} />
</h3>
<SourceLocation componentStackFrame={componentStackFrame} />
</div>
)
Expand Down
22 changes: 18 additions & 4 deletions packages/next/src/server/lib/router-utils/setup-dev-bundler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -131,12 +131,16 @@ import type { ActionManifest } from '../../../build/webpack/plugins/flight-clien
import { denormalizePagePath } from '../../../shared/lib/page-path/denormalize-page-path'
import type { LoadableManifest } from '../../load-components'
import { generateRandomActionKeyRaw } from '../../app-render/action-encryption-utils'
import { bold, green, red } from '../../../lib/picocolors'
import { bold, green, magenta, red } from '../../../lib/picocolors'
import { writeFileAtomic } from '../../../lib/fs/write-atomic'
import { PAGE_TYPES } from '../../../lib/page-types'
import { trace } from '../../../trace'
import type { VersionInfo } from '../../dev/parse-version-info'
import type { NextFontManifest } from '../../../build/webpack/plugins/next-font-manifest-plugin'
import {
MAGIC_IDENTIFIER_REGEX,
decodeMagicIdentifier,
} from '../../../shared/lib/magic-identifier'

const MILLISECONDS_IN_NANOSECOND = 1_000_000
const wsServer = new ws.Server({ noServer: true })
Expand Down Expand Up @@ -2679,13 +2683,23 @@ export async function setupDevBundler(opts: SetupOpts) {
export type DevBundler = Awaited<ReturnType<typeof setupDevBundler>>

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 string.value
return decodeMagicIdentifiers(string.value)
case 'strong':
return bold(red(string.value))
return bold(red(decodeMagicIdentifiers(string.value)))
case 'code':
return green(string.value)
return green(decodeMagicIdentifiers(string.value))
case 'line':
return string.value.map(renderStyledStringToErrorAnsi).join('')
case 'stack':
Expand Down
95 changes: 95 additions & 0 deletions packages/next/src/shared/lib/magic-identifier.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
function decodeHex(hexStr: string): string {
if (hexStr.trim() === '') {
throw new Error("can't decode empty hex")
}

const num = parseInt(hexStr, 16)
if (isNaN(num)) {
throw new Error(`invalid hex: \`${hexStr}\``)
}

return String.fromCodePoint(num)
}

const enum Mode {
Text,
Underscore,
Hex,
LongHex,
}

const DECODE_REGEX = /^__TURBOPACK__([a-zA-Z0-9_$]+)__$/

export function decodeMagicIdentifier(identifier: string): string {
const matches = identifier.match(DECODE_REGEX)
if (!matches) {
return identifier
}

const inner = matches[1]

let output = ''

let mode: Mode = Mode.Text
let buffer = ''
for (let i = 0; i < inner.length; i++) {
const char = inner[i]

if (mode === Mode.Text) {
if (char === '_') {
mode = Mode.Underscore
} else if (char === '$') {
mode = Mode.Hex
} else {
output += char
}
} else if (mode === Mode.Underscore) {
if (char === '_') {
output += ' '
mode = Mode.Text
} else if (char === '$') {
output += '_'
mode = Mode.Hex
} else {
output += char
mode = Mode.Text
}
} else if (mode === Mode.Hex) {
if (buffer.length === 2) {
output += decodeHex(buffer)
buffer = ''
}

if (char === '_') {
if (buffer !== '') {
throw new Error(`invalid hex: \`${buffer}\``)
}

mode = Mode.LongHex
} else if (char === '$') {
if (buffer !== '') {
throw new Error(`invalid hex: \`${buffer}\``)
}

mode = Mode.Text
} else {
buffer += char
}
} else if (mode === Mode.LongHex) {
if (char === '_') {
throw new Error(`invalid hex: \`${buffer + char}\``)
} else if (char === '$') {
output += decodeHex(buffer)
buffer = ''

mode = Mode.Text
} else {
buffer += char
}
}
}

return output
}

export const MAGIC_IDENTIFIER_REGEX = /__TURBOPACK__[a-zA-Z0-9_$]+__/g
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ https://nextjs.org/docs/messages/module-not-found"
`;

exports[`ReactRefreshLogBox app turbo Should not show __webpack_exports__ when exporting anonymous arrow function 1`] = `
"index.js (3:2) @ __TURBOPACK__default__export__
"index.js (3:2) @ {default export}

1 | export default () => {
2 | if (typeof window !== 'undefined') {
Expand Down