Skip to content
This repository was archived by the owner on Jan 11, 2023. It is now read-only.
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
96 changes: 86 additions & 10 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
"html-minifier": "^4.0.0",
"http-link-header": "^1.0.2",
"shimport": "^1.0.1",
"source-map": "^0.6.1",
"sourcemap-codec": "^1.4.6",
"string-hash": "^1.1.3"
},
Expand Down
5 changes: 5 additions & 0 deletions runtime/src/server/middleware/get_page_handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import devalue from 'devalue';
import fetch from 'node-fetch';
import URL from 'url';
import { Manifest, Page, Req, Res } from './types';
import { sourcemap_stacktrace } from './sourcemap_stacktrace';
import { build_dir, dev, src_dir } from '@sapper/internal/manifest-server';
import App from '@sapper/internal/App.svelte';

Expand Down Expand Up @@ -233,6 +234,10 @@ export function get_page_handler(
l++;
});

if (error instanceof Error && error.stack) {
error.stack = sourcemap_stacktrace(error.stack);
}

const props = {
stores: {
page: {
Expand Down
96 changes: 96 additions & 0 deletions runtime/src/server/middleware/sourcemap_stacktrace.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
import fs from 'fs';
import path from 'path';
import { SourceMapConsumer, RawSourceMap } from 'source-map';

function get_sourcemap_url(contents: string) {
const reversed = contents
.split('\n')
.reverse()
.join('\n');

const match = /\/[/*]#[ \t]+sourceMappingURL=([^\s'"]+?)(?:[ \t]+|$)/gm.exec(reversed);
if (match) return match[1];

return undefined;
}

const file_cache = new Map<string, string>();

function get_file_contents(path: string) {
if (file_cache.has(path)) {
return file_cache.get(path);
}

try {
const data = fs.readFileSync(path, 'utf8');
file_cache.set(path, data);
return data;
} catch {
return undefined;
}
}

export function sourcemap_stacktrace(stack: string) {
const replace = (line: string) =>
line.replace(
/^ {4}at (?:(.+?)\s+\()?(?:(.+?):(\d+)(?::(\d+))?)\)?/,
(input, var_name, file_path, line, column) => {
if (!file_path) return input;

const contents = get_file_contents(file_path);
if (!contents) return input;

const sourcemap_url = get_sourcemap_url(contents);
if (!sourcemap_url) return input;

let dir = path.dirname(file_path);
let sourcemap_data: string;

if (/^data:application\/json[^,]+base64,/.test(sourcemap_url)) {
const raw_data = sourcemap_url.slice(sourcemap_url.indexOf(',') + 1);
try {
sourcemap_data = Buffer.from(raw_data, 'base64').toString();
} catch {
return input;
}
} else {
const sourcemap_path = path.resolve(dir, sourcemap_url);
const data = get_file_contents(sourcemap_path);

if (!data) return input;

sourcemap_data = data;
dir = path.dirname(sourcemap_path);
}

let raw_sourcemap: RawSourceMap;
try {
raw_sourcemap = JSON.parse(sourcemap_data);
} catch {
return input;
}

const consumer = new SourceMapConsumer(raw_sourcemap);
const pos = consumer.originalPositionFor({
line: Number(line),
column: Number(column),
bias: SourceMapConsumer.LEAST_UPPER_BOUND
});

if (!pos.source) return input;

const source_path = path.resolve(dir, pos.source);
const source = `${source_path}:${pos.line || 0}:${pos.column || 0}`;

if (!var_name) return ` at ${source}`;
return ` at ${var_name} (${source})`;
}
);

file_cache.clear();
Copy link
Member

@benmccann benmccann Aug 4, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not really sure what the point of the file_cache is if it's cleared everytime we try to source map an exception

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I noticed that in a stack trace, sometimes you can hit the same file with different lines and cols. The file_cache there is just a means to avoid rereading that file multiple times in a single call to sourcemap_stacktrace.


return stack
.split('\n')
.map(replace)
.join('\n');
}
2 changes: 1 addition & 1 deletion test/apps/errors/rollup.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ export default {

server: {
input: config.server.input(),
output: config.server.output(),
output: Object.assign({}, config.server.output(), { sourcemap: true }),
plugins: [
replace({
'process.browser': false,
Expand Down
2 changes: 2 additions & 0 deletions test/apps/errors/src/routes/_error.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,5 @@
<h2>{mounted}</h2>

<p>{error.message}</p>

<span>{error.stack}</span>
3 changes: 3 additions & 0 deletions test/apps/errors/src/routes/_trace.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export function oops() {
throw new Error('oops');
}
3 changes: 2 additions & 1 deletion test/apps/errors/src/routes/index.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,5 @@
<a href="nope">nope</a>
<a href="blog/nope">blog/nope</a>
<a href="throw">throw</a>
<a href="preload-reject">preload-reject</a>
<a href="preload-reject">preload-reject</a>
<a href="trace">trace</a>
7 changes: 7 additions & 0 deletions test/apps/errors/src/routes/trace.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
<script context="module">
import { oops } from './_trace';

export function preload() {
oops();
}
</script>
9 changes: 9 additions & 0 deletions test/apps/errors/test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,15 @@ describe('errors', function() {
);
});

it('display correct stack trace sequences on server error referring to source file', async () => {
await r.load('/trace');

const stack = (await r.text('span')).split('\n');

assert.ok(stack[1] && stack[1].includes('_trace.js:2:11'));
assert.ok(stack[2] && stack[2].includes('trace.svelte:5:6'));
});

it('handles error on client', async () => {
await r.load('/');
await r.sapper.start();
Expand Down