34 lines
2 KiB
TypeScript
34 lines
2 KiB
TypeScript
// Live-reload developer mode: where a plugin's start failure happened, for the in-page error toast.
|
|
//
|
|
// The host evaluates a plugin with `//# sourceURL=<prefix><file>` (waybetter-host
|
|
// `dev_start_script`), so V8/JavaScriptCore stack frames name that URL with the line and column
|
|
// of the evaluated script; the plugin file's line 1 is line `1 + lineOffset` there.
|
|
|
|
export type DevErrorLocation = { file: string; line: number | null; column: number | null; message: string };
|
|
|
|
/** Default prefix the host uses for plugin source URLs. */
|
|
export const DEV_SOURCE_PREFIX = 'wb-dev/';
|
|
|
|
const escapeRegExp = (value: string) => value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
|
|
/**
|
|
* The first stack frame inside `file` (evaluated as `<prefix><file>`), mapped back to the file's
|
|
* own line numbers. Line is null when no frame names the file (e.g. an error thrown from a timer
|
|
* in other code). The message is one line, at most 300 characters.
|
|
*/
|
|
export function devErrorLocation(error: unknown, file: string, prefix = DEV_SOURCE_PREFIX, lineOffset = 1): DevErrorLocation {
|
|
const text = error instanceof Error ? error.message : String(error);
|
|
const message = `${error instanceof Error && error.name && error.name !== 'Error' ? `${error.name}: ` : ''}${text}`.split('\n')[0]!.slice(0, 300);
|
|
const stack = error instanceof Error && typeof error.stack === 'string' ? error.stack : '';
|
|
const url = `${prefix}${file.replace(/ /g, '%20')}`;
|
|
const match = new RegExp(`${escapeRegExp(url)}:(\\d+):(\\d+)`).exec(stack);
|
|
if (!match) return { file, line: null, column: null, message };
|
|
const line = Number(match[1]) - lineOffset;
|
|
return { file, line: line >= 1 ? line : null, column: Number(match[2]), message };
|
|
}
|
|
|
|
/** `file:line:column — message` (parts that are unknown are left out). */
|
|
export function formatDevError(location: DevErrorLocation): string {
|
|
const where = location.line ? `${location.file}:${location.line}${location.column ? `:${location.column}` : ''}` : location.file;
|
|
return `${where} — ${location.message}`;
|
|
}
|