use Biome to format Bun's codebase instead of Prettier (#8494)

* Ignore

* Create biome.json

* Ignore

* biome

* [autofix.ci] apply automated fixes

---------

Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
This commit is contained in:
Jarred Sumner
2024-01-25 19:15:26 -08:00
committed by GitHub
parent 045672cf67
commit e3188c918a
65 changed files with 839 additions and 1786 deletions

View File

@@ -11,11 +11,7 @@ import type {
StackFrame,
WebsocketMessageBuildFailure,
} from "../../src/api/schema";
import {
messagesToMarkdown,
problemsToMarkdown,
withBunInfo,
} from "./markdown";
import { messagesToMarkdown, problemsToMarkdown, withBunInfo } from "./markdown";
import { fetchAllMappings, remapPosition, sourceMappings } from "./sourcemap";
export enum StackFrameScope {
@@ -82,9 +78,7 @@ enum ErrorTagType {
}
const ErrorTag = ({ type }: { type: ErrorTagType }) => (
<div className={`BunError-ErrorTag BunError-ErrorTag--${ErrorTagType[type]}`}>
{ErrorTagType[type]}
</div>
<div className={`BunError-ErrorTag BunError-ErrorTag--${ErrorTagType[type]}`}>{ErrorTagType[type]}</div>
);
const errorTags = [
@@ -133,11 +127,7 @@ function hasColumnOrLine(filename: string) {
return /:\d+/.test(filename);
}
function appendLineColumnIfNeeded(
base: string,
line?: number,
column?: number,
) {
function appendLineColumnIfNeeded(base: string, line?: number, column?: number) {
if (hasColumnOrLine(base)) return base;
return appendLineColumn(base, line, column);
@@ -155,11 +145,7 @@ function appendLineColumn(base: string, line?: number, column?: number) {
return base;
}
const blobFileURL = (
filename: string,
line?: number,
column?: number,
): string => {
const blobFileURL = (filename: string, line?: number, column?: number): string => {
var base = `/blob:${filename}`;
base = appendLineColumnIfNeeded(base, line, column);
@@ -167,11 +153,7 @@ const blobFileURL = (
return new URL(base, globalThis.location.href).href;
};
const maybeBlobFileURL = (
filename: string,
line?: number,
column?: number,
): string => {
const maybeBlobFileURL = (filename: string, line?: number, column?: number): string => {
if (filename.includes(".bun")) {
return blobFileURL(filename, line, column);
}
@@ -183,9 +165,7 @@ const maybeBlobFileURL = (
return srcFileURL(filename, line, column);
};
const openWithoutFlashOfNewTab: React.MouseEventHandler<HTMLAnchorElement> = (
event,
) => {
const openWithoutFlashOfNewTab: React.MouseEventHandler<HTMLAnchorElement> = event => {
const target = event.currentTarget;
const href = target.getAttribute("href");
if (!href || event.button !== 0) {
@@ -216,18 +196,13 @@ const openWithoutFlashOfNewTab: React.MouseEventHandler<HTMLAnchorElement> = (
})
.then(
() => {},
(er) => {},
er => {},
);
return false;
};
const srcFileURL = (
filename: string,
line?: number,
column?: number,
): string => {
if (filename.startsWith("http://") || filename.startsWith("https://"))
return appendLineColumnIfNeeded(filename);
const srcFileURL = (filename: string, line?: number, column?: number): string => {
if (filename.startsWith("http://") || filename.startsWith("https://")) return appendLineColumnIfNeeded(filename);
if (filename.endsWith(".bun")) {
return new URL("/" + filename, globalThis.location.href).href;
@@ -272,10 +247,7 @@ class FancyTypeError {
const nextWord = /(["a-zA-Z0-9_\.]+)\)$/.exec(partial);
if (nextWord && nextWord[0]) {
this.runtimeTypeName = nextWord[0];
this.runtimeTypeName = this.runtimeTypeName.substring(
0,
this.runtimeTypeName.length - 1,
);
this.runtimeTypeName = this.runtimeTypeName.substring(0, this.runtimeTypeName.length - 1);
switch (this.runtimeTypeName.toLowerCase()) {
case "undefined": {
this.runtimeType = RuntimeType.Undefined;
@@ -312,15 +284,12 @@ class FancyTypeError {
}
}
this.message = exception.message.substring(0, i);
this.message = this.message.substring(
0,
this.message.lastIndexOf("(In "),
);
this.message = this.message.substring(0, this.message.lastIndexOf("(In "));
}
}
}
export const clientURL = (filename) => {
export const clientURL = filename => {
if (filename.includes(".bun")) {
return `/${filename.replace(/^(\/)?/g, "")}`;
}
@@ -368,22 +337,17 @@ const AsyncSourceLines = ({
Accept: "text/plain",
},
})
.then((resp) => {
.then(resp => {
return resp.text();
})
.then((text) => {
.then(text => {
if (cancelled) return;
// TODO: make this faster
const lines = text.split("\n");
const startLineNumber = Math.max(
Math.min(Math.max(highlight - 4, 0), lines.length - 1),
0,
);
const startLineNumber = Math.max(Math.min(Math.max(highlight - 4, 0), lines.length - 1), 0);
const endLineNumber = Math.min(startLineNumber + 8, lines.length);
const sourceLines: SourceLine[] = new Array(
endLineNumber - startLineNumber,
);
const sourceLines: SourceLine[] = new Array(endLineNumber - startLineNumber);
var index = 0;
for (let i = startLineNumber; i < endLineNumber; i++) {
const currentLine = lines[i - 1];
@@ -394,14 +358,10 @@ const AsyncSourceLines = ({
};
}
setSourceLines(
index !== sourceLines.length
? sourceLines.slice(0, index)
: sourceLines,
);
setSourceLines(index !== sourceLines.length ? sourceLines.slice(0, index) : sourceLines);
setLoadState(LoadState.loaded);
})
.catch((err) => {
.catch(err => {
if (!cancelled) {
console.error(err);
setLoadState(LoadState.failed);
@@ -499,8 +459,7 @@ const SourceLines = ({
}
}
const leftPad =
maxLineNumber.toString(10).length - minLineNumber.toString(10).length;
const leftPad = maxLineNumber.toString(10).length - minLineNumber.toString(10).length;
const _sourceLines = sourceLines.slice(start, end);
const lines = new Array(_sourceLines.length + React.Children.count(children));
@@ -520,15 +479,10 @@ const SourceLines = ({
data-line={line}
data-column={classes.highlight ? highlightColumnStart : dedent}
title={`Open line ${line} in editor`}
href={buildURL(
line,
classes.highlight ? highlightColumnStart : dedent,
)}
href={buildURL(line, classes.highlight ? highlightColumnStart : dedent)}
onClickCapture={openWithoutFlashOfNewTab}
key={"highlight-number-" + line}
className={`BunError-SourceLine-number ${
classes.empty ? "BunError-SourceLine-number--empty" : ""
} ${
className={`BunError-SourceLine-number ${classes.empty ? "BunError-SourceLine-number--empty" : ""} ${
classes.highlight ? "BunError-SourceLine-number--highlight" : ""
}`}
>
@@ -536,9 +490,9 @@ const SourceLines = ({
</a>
<div
tabIndex={i}
className={`BunError-SourceLine-text ${
classes.empty ? "BunError-SourceLine-text--empty" : ""
} ${classes.highlight ? "BunError-SourceLine-text--highlight" : ""}`}
className={`BunError-SourceLine-text ${classes.empty ? "BunError-SourceLine-text--empty" : ""} ${
classes.highlight ? "BunError-SourceLine-text--highlight" : ""
}`}
>
{_text}
</div>
@@ -549,9 +503,7 @@ const SourceLines = ({
return (
<IndentationContext.Provider value={dedent}>
<div className="BunError-SourceLines">
<div
className={`BunError-SourceLines-highlighter--${highlightI}`}
></div>
<div className={`BunError-SourceLines-highlighter--${highlightI}`}></div>
{lines}
</div>
@@ -568,10 +520,7 @@ const BuildErrorSourceLines = ({
}) => {
const { line, line_text, column } = location;
const sourceLines: SourceLine[] = [{ line, text: line_text }];
const buildURL = React.useCallback(
(line, column) => srcFileURL(filename, line, column),
[srcFileURL, filename],
);
const buildURL = React.useCallback((line, column) => srcFileURL(filename, line, column), [srcFileURL, filename]);
return (
<SourceLines
sourceLines={sourceLines}
@@ -613,8 +562,7 @@ export const StackFrameIdentifier = ({
}) => {
switch (scope) {
case StackFrameScope.Constructor: {
functionName =
markdown && functionName ? "`" + functionName + "`" : functionName;
functionName = markdown && functionName ? "`" + functionName + "`" : functionName;
return functionName ? `new ${functionName}` : "new (anonymous)";
}
@@ -636,16 +584,12 @@ export const StackFrameIdentifier = ({
case StackFrameScope.Function:
default: {
return functionName
? markdown
? "`" + functionName + "`"
: functionName
: "λ()";
return functionName ? (markdown ? "`" + functionName + "`" : functionName) : "λ()";
}
}
};
const getNativeStackFrameIdentifier = (frame) => {
const getNativeStackFrameIdentifier = frame => {
const { file, function_name: functionName, scope } = frame;
return StackFrameIdentifier({
@@ -673,11 +617,7 @@ const NativeStackFrame = ({
} = frame;
const fileName = normalizedFilename(file, cwd);
return (
<div
className={`BunError-StackFrame ${
fileName.endsWith(".bun") ? "BunError-StackFrame--muted" : ""
}`}
>
<div className={`BunError-StackFrame ${fileName.endsWith(".bun") ? "BunError-StackFrame--muted" : ""}`}>
<div
title={StackFrameScope[scope]}
className="BunError-StackFrame-identifier"
@@ -700,9 +640,7 @@ const NativeStackFrame = ({
<div className="BunError-StackFrame-link-content">
<div className={`BunError-StackFrame-file`}>{fileName}</div>
{line > -1 && <div className="BunError-StackFrame-line">:{line}</div>}
{column > -1 && (
<div className="BunError-StackFrame-column">:{column}</div>
)}
{column > -1 && <div className="BunError-StackFrame-column">:{column}</div>}
</div>
</a>
</div>
@@ -714,21 +652,11 @@ const NativeStackFrames = ({ frames, urlBuilder }) => {
var maxLength = 0;
for (let i = 0; i < frames.length; i++) {
maxLength = Math.max(
getNativeStackFrameIdentifier(frames[i]).length,
maxLength,
);
maxLength = Math.max(getNativeStackFrameIdentifier(frames[i]).length, maxLength);
}
for (let i = 0; i < frames.length; i++) {
items[i] = (
<NativeStackFrame
maxLength={maxLength}
urlBuilder={urlBuilder}
key={i}
frame={frames[i]}
/>
);
items[i] = <NativeStackFrame maxLength={maxLength} urlBuilder={urlBuilder} key={i} frame={frames[i]} />;
}
return (
@@ -756,10 +684,7 @@ const NativeStackTrace = ({
const filename = normalizedFilename(file, cwd);
const urlBuilder = isClient ? clientURL : maybeBlobFileURL;
const ref = React.useRef<HTMLDivElement>(null);
const buildURL = React.useCallback(
(line, column) => urlBuilder(file, line, column),
[file, urlBuilder],
);
const buildURL = React.useCallback((line, column) => urlBuilder(file, line, column), [file, urlBuilder]);
return (
<div ref={ref} className={`BunError-NativeStackTrace`}>
@@ -797,9 +722,7 @@ const NativeStackTrace = ({
{children}
</AsyncSourceLines>
)}
{frames.length > 1 && (
<NativeStackFrames urlBuilder={urlBuilder} frames={frames} />
)}
{frames.length > 1 && <NativeStackFrames urlBuilder={urlBuilder} frames={frames} />}
</div>
);
};
@@ -822,9 +745,7 @@ const JSException = ({
isClient: boolean;
}) => {
const tag = isClient ? ErrorTagType.client : ErrorTagType.server;
const [sourceLines, _setSourceLines] = React.useState(
value?.stack?.source_lines ?? [],
);
const [sourceLines, _setSourceLines] = React.useState(value?.stack?.source_lines ?? []);
var message = value.message || "";
var name = value.name || "";
if (!name && !message) {
@@ -849,25 +770,17 @@ const JSException = ({
if (fancyTypeError.runtimeType !== RuntimeType.Nothing) {
return (
<div
className={`BunError-JSException BunError-JSException--TypeError`}
>
<div className={`BunError-JSException BunError-JSException--TypeError`}>
<div className="BunError-error-header">
<div className={`BunError-error-code`}>TypeError</div>
{errorTags[tag]}
</div>
<div className={`BunError-error-message`}>
{fancyTypeError.message}
</div>
<div className={`BunError-error-message`}>{fancyTypeError.message}</div>
{fancyTypeError.runtimeTypeName.length && (
<div className={`BunError-error-subtitle`}>
It's{" "}
<span className="BunError-error-typename">
{fancyTypeError.runtimeTypeName}
</span>
.
It's <span className="BunError-error-typename">{fancyTypeError.runtimeTypeName}</span>.
</div>
)}
@@ -879,9 +792,7 @@ const JSException = ({
setSourceLines={setSourceLines}
>
<Indent by={value.stack.frames[0].position.column_start}>
<span className="BunError-error-typename">
{fancyTypeError.runtimeTypeName}
</span>
<span className="BunError-error-typename">{fancyTypeError.runtimeTypeName}</span>
</Indent>
</NativeStackTrace>
)}
@@ -956,17 +867,8 @@ const Summary = ({
{errorCount}&nbsp;error{errorCount > 1 ? "s" : ""}&nbsp;on this page
</div>
<a
href="https://bun.sh/discord"
target="_blank"
className="BunError-Summary-help"
>
<svg
width="18"
viewBox="0 0 71 55"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<a href="https://bun.sh/discord" target="_blank" className="BunError-Summary-help">
<svg width="18" viewBox="0 0 71 55" fill="none" xmlns="http://www.w3.org/2000/svg">
<g clip-path="url(#clip0)">
<path
d="M60.1045 4.8978C55.5792 2.8214 50.7265 1.2916 45.6527 0.41542C45.5603 0.39851 45.468 0.440769 45.4204 0.525289C44.7963 1.6353 44.105 3.0834 43.6209 4.2216C38.1637 3.4046 32.7345 3.4046 27.3892 4.2216C26.905 3.0581 26.1886 1.6353 25.5617 0.525289C25.5141 0.443589 25.4218 0.40133 25.3294 0.41542C20.2584 1.2888 15.4057 2.8186 10.8776 4.8978C10.8384 4.9147 10.8048 4.9429 10.7825 4.9795C1.57795 18.7309 -0.943561 32.1443 0.293408 45.3914C0.299005 45.4562 0.335386 45.5182 0.385761 45.5576C6.45866 50.0174 12.3413 52.7249 18.1147 54.5195C18.2071 54.5477 18.305 54.5139 18.3638 54.4378C19.7295 52.5728 20.9469 50.6063 21.9907 48.5383C22.0523 48.4172 21.9935 48.2735 21.8676 48.2256C19.9366 47.4931 18.0979 46.6 16.3292 45.5858C16.1893 45.5041 16.1781 45.304 16.3068 45.2082C16.679 44.9293 17.0513 44.6391 17.4067 44.3461C17.471 44.2926 17.5606 44.2813 17.6362 44.3151C29.2558 49.6202 41.8354 49.6202 53.3179 44.3151C53.3935 44.2785 53.4831 44.2898 53.5502 44.3433C53.9057 44.6363 54.2779 44.9293 54.6529 45.2082C54.7816 45.304 54.7732 45.5041 54.6333 45.5858C52.8646 46.6197 51.0259 47.4931 49.0921 48.2228C48.9662 48.2707 48.9102 48.4172 48.9718 48.5383C50.038 50.6034 51.2554 52.5699 52.5959 54.435C52.6519 54.5139 52.7526 54.5477 52.845 54.5195C58.6464 52.7249 64.529 50.0174 70.6019 45.5576C70.6551 45.5182 70.6887 45.459 70.6943 45.3942C72.1747 30.0791 68.2147 16.7757 60.1968 4.9823C60.1772 4.9429 60.1437 4.9147 60.1045 4.8978ZM23.7259 37.3253C20.2276 37.3253 17.3451 34.1136 17.3451 30.1693C17.3451 26.225 20.1717 23.0133 23.7259 23.0133C27.308 23.0133 30.1626 26.2532 30.1066 30.1693C30.1066 34.1136 27.28 37.3253 23.7259 37.3253ZM47.3178 37.3253C43.8196 37.3253 40.9371 34.1136 40.9371 30.1693C40.9371 26.225 43.7636 23.0133 47.3178 23.0133C50.9 23.0133 53.7545 26.2532 53.6986 30.1693C53.6986 34.1136 50.9 37.3253 47.3178 37.3253Z"
@@ -1005,13 +907,9 @@ const BuildError = ({ message }: { message: Message }) => {
<div className={`BunError-error-message`}>{title}</div>
{subtitle.length > 0 && (
<div className={`BunError-error-subtitle`}>{subtitle}</div>
)}
{subtitle.length > 0 && <div className={`BunError-error-subtitle`}>{subtitle}</div>}
{message.data.location && (
<BuildErrorStackTrace location={message.data.location} />
)}
{message.data.location && <BuildErrorStackTrace location={message.data.location} />}
</div>
);
};
@@ -1034,16 +932,12 @@ const ResolveError = ({ message }: { message: Message }) => {
<div className={`BunError-error-message`}>
Can't import{" "}
<span className="BunError-error-message--mono BunError-error-message--quoted">
"{message.on.resolve}"
</span>
<span className="BunError-error-message--mono BunError-error-message--quoted">"{message.on.resolve}"</span>
</div>
{subtitle && <div className={`BunError-error-subtitle`}>{subtitle}</div>}
{message.data.location && (
<BuildErrorStackTrace location={message.data.location} />
)}
{message.data.location && <BuildErrorStackTrace location={message.data.location} />}
</div>
);
};
@@ -1052,9 +946,7 @@ const OverlayMessageContainer = ({
reason,
isClient = false,
}: FallbackMessageContainer & { isClient: boolean }) => {
const errorCount = problems
? problems.exceptions.length + problems.build.errors
: 0;
const errorCount = problems ? problems.exceptions.length + problems.build.errors : 0;
return (
<div id="BunErrorOverlay-container">
<div className="BunError-content">
@@ -1086,7 +978,7 @@ function copyToClipboard(input: string | Promise<string>) {
if (!input) return;
if (typeof input === "object" && "then" in input) {
return input.then((str) => copyToClipboard(str));
return input.then(str => copyToClipboard(str));
}
return navigator.clipboard.writeText(input).then(() => {});
@@ -1148,9 +1040,7 @@ function renderWithFunc(func) {
reactRoot = document.createElement("div");
reactRoot.id = BUN_ERROR_CONTAINER_ID;
const fallbackStyleSheet = document.querySelector(
"style[data-has-bun-fallback-style]",
);
const fallbackStyleSheet = document.querySelector("style[data-has-bun-fallback-style]");
if (!fallbackStyleSheet) {
reactRoot.style.visibility = "hidden";
}
@@ -1204,7 +1094,7 @@ import { parse as getStackTrace } from "./stack-trace-parser";
var runtimeErrorController: AbortController | null = null;
var pending: { stopped: boolean }[] = [];
var onIdle = globalThis.requestIdleCallback || ((cb) => setTimeout(cb, 32));
var onIdle = globalThis.requestIdleCallback || (cb => setTimeout(cb, 32));
function clearSourceMappings() {
sourceMappings.clear();
}
@@ -1270,8 +1160,7 @@ export function renderRuntimeError(error: Error) {
exception.stack.frames[0].position.line = error[lineNumberProperty];
if (Number.isFinite(error[columnNumberProperty])) {
exception.stack.frames[0].position.column_start =
error[columnNumberProperty];
exception.stack.frames[0].position.column_start = error[columnNumberProperty];
}
}
}
@@ -1308,20 +1197,18 @@ export function renderRuntimeError(error: Error) {
// Rely on the cached ones
// and don't fetch them again
const framePromises = fetchAllMappings(
exception.stack.frames.map((frame) =>
normalizedFilename(frame.file, thisCwd),
),
exception.stack.frames.map(frame => normalizedFilename(frame.file, thisCwd)),
signal,
)
.map((frame, i) => {
if (stopThis.stopped) return null;
return [frame, i];
})
.map((result) => {
.map(result => {
if (!result) return;
const [mappings, frameIndex] = result;
if (mappings?.then) {
return mappings.then((mappings) => {
return mappings.then(mappings => {
if (!mappings || stopThis.stopped) {
return null;
}
@@ -1391,10 +1278,7 @@ export function dismissError() {
}
}
export const renderBuildFailure = (
failure: WebsocketMessageBuildFailure,
cwd: string,
) => {
export const renderBuildFailure = (failure: WebsocketMessageBuildFailure, cwd: string) => {
thisCwd = cwd;
renderWithFunc(() => (
<ErrorGroupContext.Provider value={{ cwd }}>

View File

@@ -1,15 +1,5 @@
import {
normalizedFilename,
StackFrameIdentifier,
thisCwd,
StackFrameScope,
} from "./index";
import type {
JSException,
JSException as JSExceptionType,
Message,
Problems,
} from "../../src/api/schema";
import { normalizedFilename, StackFrameIdentifier, thisCwd, StackFrameScope } from "./index";
import type { JSException, JSException as JSExceptionType, Message, Problems } from "../../src/api/schema";
export function problemsToMarkdown(problems: Problems) {
var markdown = "";
@@ -27,14 +17,14 @@ export function problemsToMarkdown(problems: Problems) {
export function messagesToMarkdown(messages: Message[]): string {
return messages
.map(messageToMarkdown)
.map((a) => a.trim())
.map(a => a.trim())
.join("\n");
}
export function exceptionsToMarkdown(exceptions: JSExceptionType[]): string {
return exceptions
.map(exceptionToMarkdown)
.map((a) => a.trim())
.map(a => a.trim())
.join("\n");
}
@@ -73,11 +63,7 @@ function exceptionToMarkdown(exception: JSException): string {
const {
file: _file = "",
function_name = "",
position: {
line = -1,
column_start: column = -1,
column_stop: columnEnd = column,
} = {
position: { line = -1, column_start: column = -1, column_stop: columnEnd = column } = {
line: -1,
column_start: -1,
column_stop: -1,
@@ -114,23 +100,17 @@ function exceptionToMarkdown(exception: JSException): string {
markdown += "\n```";
markdown += extname;
markdown += "\n";
stack.source_lines.forEach((sourceLine) => {
stack.source_lines.forEach(sourceLine => {
const lineText = sourceLine.text.trimEnd();
markdown += lineText + "\n";
if (sourceLine.line === line && stack.source_lines.length > 1) {
// the comment should start at the first non-whitespace character
// ideally it should be length the original line
// but it may not be
var prefix = "".padStart(
lineText.length - lineText.trimStart().length,
" ",
);
var prefix = "".padStart(lineText.length - lineText.trimStart().length, " ");
prefix +=
"/* ".padEnd(column - 1 - prefix.length, " ") +
"^ happened here ";
markdown +=
prefix.padEnd(Math.max(lineText.length, 1) - 1, " ") + "*/\n";
prefix += "/* ".padEnd(column - 1 - prefix.length, " ") + "^ happened here ";
markdown += prefix.padEnd(Math.max(lineText.length, 1) - 1, " ") + "*/\n";
}
});
markdown = markdown.trimEnd() + "\n```";
@@ -240,11 +220,9 @@ function messageToMarkdown(message: Message): string {
if (message.data.location.line_text.length) {
const extnameI = message.data.location.file.lastIndexOf(".");
const extname =
extnameI > -1 ? message.data.location.file.slice(extnameI + 1) : "";
const extname = extnameI > -1 ? message.data.location.file.slice(extnameI + 1) : "";
markdown +=
"\n```" + extname + "\n" + message.data.location.line_text + "\n```\n";
markdown += "\n```" + extname + "\n" + message.data.location.line_text + "\n```\n";
} else {
markdown += "\n";
}
@@ -257,14 +235,14 @@ function messageToMarkdown(message: Message): string {
return markdown;
}
export const withBunInfo = (text) => {
export const withBunInfo = text => {
const bunInfo = getBunInfo();
const trimmed = text.trim();
if (bunInfo && "then" in bunInfo) {
return bunInfo.then(
(info) => {
info => {
const markdown = bunInfoToMarkdown(info).trim();
return trimmed + "\n" + markdown + "\n";
},
@@ -379,8 +357,8 @@ function getBunInfo() {
Accept: "application/json",
},
})
.then((resp) => resp.json())
.then((bunInfo) => {
.then(resp => resp.json())
.then(bunInfo => {
clearTimeout(id);
bunInfoMemoized = bunInfo;
if ("sessionStorage" in globalThis) {

View File

@@ -1,10 +1,6 @@
// Based on https://github.com/stacktracejs/error-stack-parser/blob/master/error-stack-parser.js
import type {
StackFrame as StackFrameType,
StackFramePosition,
StackFrameScope,
} from "../../src/api/schema";
import type { StackFrame as StackFrameType, StackFramePosition, StackFrameScope } from "../../src/api/schema";
export class StackFrame implements StackFrameType {
function_name: string;
@@ -89,9 +85,7 @@ export default class RuntimeError {
return filtered.map(function (line) {
if (line.indexOf("(eval ") > -1) {
// Throw away eval information until we implement stacktrace.js/stackframe#8
line = line
.replace(/eval code/g, "eval")
.replace(/(\(eval at [^()]*)|(\),.*$)/g, "");
line = line.replace(/eval code/g, "eval").replace(/(\(eval at [^()]*)|(\),.*$)/g, "");
}
var sanitizedLine = line.replace(/^\s+/, "").replace(/\(eval code/g, "(");
@@ -100,20 +94,13 @@ export default class RuntimeError {
var location = sanitizedLine.match(/ (\((.+):(\d+):(\d+)\)$)/);
// remove the parenthesized location from the line, if it was matched
sanitizedLine = location
? sanitizedLine.replace(location[0], "")
: sanitizedLine;
sanitizedLine = location ? sanitizedLine.replace(location[0], "") : sanitizedLine;
var tokens = sanitizedLine.split(/\s+/).slice(1);
// if a location was matched, pass it to extractLocation() otherwise pop the last token
var locationParts = this.extractLocation(
location ? location[1] : tokens.pop(),
);
var locationParts = this.extractLocation(location ? location[1] : tokens.pop());
var functionName = tokens.join(" ") || undefined;
var fileName =
["eval", "<anonymous>"].indexOf(locationParts[0]) > -1
? undefined
: locationParts[0];
var fileName = ["eval", "<anonymous>"].indexOf(locationParts[0]) > -1 ? undefined : locationParts[0];
return new StackFrame({
functionName: functionName,
@@ -133,10 +120,7 @@ export default class RuntimeError {
return filtered.map(function (line) {
// Throw away eval information until we implement stacktrace.js/stackframe#8
if (line.indexOf(" > eval") > -1) {
line = line.replace(
/ line (\d+)(?: > eval line \d+)* > eval:\d+:\d+/g,
":$1",
);
line = line.replace(/ line (\d+)(?: > eval line \d+)* > eval:\d+:\d+/g, ":$1");
}
if (line.indexOf("@") === -1 && line.indexOf(":") === -1) {
@@ -148,9 +132,7 @@ export default class RuntimeError {
var functionNameRegex = /((.*".+"[^@]*)?[^@]*)(?:@)/;
var matches = line.match(functionNameRegex);
var functionName = matches && matches[1] ? matches[1] : undefined;
var locationParts = this.extractLocation(
line.replace(functionNameRegex, ""),
);
var locationParts = this.extractLocation(line.replace(functionNameRegex, ""));
return new StackFrame({
functionName: functionName,

View File

@@ -1,7 +1,6 @@
// Accelerate VLQ decoding with a lookup table
const vlqTable = new Uint8Array(128);
const vlqChars =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
const vlqChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
vlqTable.fill(0xff);
for (let i = 0; i < vlqChars.length; i++) vlqTable[vlqChars.charCodeAt(i)] = i;
@@ -10,10 +9,7 @@ export function parseSourceMap(json) {
throw new Error("Invalid source map");
}
if (
!(json.sources instanceof Array) ||
json.sources.some((x) => typeof x !== "string")
) {
if (!(json.sources instanceof Array) || json.sources.some(x => typeof x !== "string")) {
throw new Error("Invalid source map");
}
@@ -147,8 +143,7 @@ export function decodeMappings(mappings, sourcesCount) {
// Read the original source
const originalSourceDelta = decodeVLQ();
originalSource += originalSourceDelta;
if (originalSource < 0 || originalSource >= sourcesCount)
decodeError("Invalid original source");
if (originalSource < 0 || originalSource >= sourcesCount) decodeError("Invalid original source");
// Read the original line
const originalLineDelta = decodeVLQ();
@@ -211,11 +206,7 @@ export function decodeMappings(mappings, sourcesCount) {
return data.subarray(0, dataLength);
}
export function remapPosition(
decodedMappings: Int32Array,
line: number,
column: number,
) {
export function remapPosition(decodedMappings: Int32Array, line: number, column: number) {
if (!(decodedMappings instanceof Int32Array)) {
throw new Error("decodedMappings must be an Int32Array");
}
@@ -260,7 +251,7 @@ export function fetchMappings(file, signal) {
return sourceMappings.get(file);
}
return fetchRemoteSourceMap(file, signal).then((json) => {
return fetchRemoteSourceMap(file, signal).then(json => {
if (!json) return null;
const { data } = parseSourceMap(json);
sourceMappings.set(file, data);
@@ -285,11 +276,11 @@ export function fetchAllMappings(files, signal) {
var resolvers = [];
for (let i = 0; i < indices.length; i++) {
results[indices[i]] = new Promise((resolve, reject) => {
resolvers[i] = (res) => resolve(res ? [res, i] : null);
resolvers[i] = res => resolve(res ? [res, i] : null);
});
}
mapped.finally((a) => {
mapped.finally(a => {
for (let resolve of resolvers) {
try {
resolve(a);
@@ -320,10 +311,7 @@ function indexOfMapping(mappings: Int32Array, line: number, column: number) {
var i = index + step;
// this multiply is slow but it's okay for now
var j = i * 6;
if (
mappings[j] < line ||
(mappings[j] == line && mappings[j + 1] <= column)
) {
if (mappings[j] < line || (mappings[j] == line && mappings[j + 1] <= column)) {
index = i + 1;
count -= step + 1;
} else {

View File

@@ -17,12 +17,7 @@ export function parse(stackString): StackFrame[] {
const lines = stackString.split("\n");
return lines.reduce((stack, line) => {
const parseResult =
parseChrome(line) ||
parseWinjs(line) ||
parseGecko(line) ||
parseNode(line) ||
parseJSC(line);
const parseResult = parseChrome(line) || parseWinjs(line) || parseGecko(line) || parseNode(line) || parseJSC(line);
if (parseResult) {
stack.push(parseResult);
@@ -32,15 +27,14 @@ export function parse(stackString): StackFrame[] {
}, []);
}
const formatFile = (file) => {
const formatFile = file => {
if (!file) {
return "";
}
if (file.startsWith("blob:")) {
if (globalThis["__BUN"]?.client) {
const replacement =
globalThis["__BUN"]?.client.dependencies.getFilePathFromBlob(file);
const replacement = globalThis["__BUN"]?.client.dependencies.getFilePathFromBlob(file);
if (replacement) {
file = replacement;
}
@@ -146,8 +140,7 @@ function parseGecko(line) {
};
}
const javaScriptCoreRe =
/^\s*(?:([^@]*)(?:\((.*?)\))?@)?(\S.*?):(\d+)(?::(\d+))?\s*$/i;
const javaScriptCoreRe = /^\s*(?:([^@]*)(?:\((.*?)\))?@)?(\S.*?):(\d+)(?::(\d+))?\s*$/i;
function parseJSC(line) {
const parts = javaScriptCoreRe.exec(line);
@@ -166,8 +159,7 @@ function parseJSC(line) {
};
}
const nodeRe =
/^\s*at (?:((?:\[object object\])?[^\\/]+(?: \[as \S+\])?) )?\(?(.*?):(\d+)(?::(\d+))?\)?\s*$/i;
const nodeRe = /^\s*at (?:((?:\[object object\])?[^\\/]+(?: \[as \S+\])?) )?\(?(.*?):(\d+)(?::(\d+))?\)?\s*$/i;
function parseNode(line) {
const parts = nodeRe.exec(line);