-
Notifications
You must be signed in to change notification settings - Fork 431
Expand file tree
/
Copy pathdebug.ts
More file actions
212 lines (198 loc) · 6.73 KB
/
debug.ts
File metadata and controls
212 lines (198 loc) · 6.73 KB
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
/*
* debug.ts
*
* Copyright (C) 2024 Posit Software, PBC
*
* Debugging utilities.
*/
import * as colors from "fmt/colors";
import { warn } from "../../deno_ral/log.ts";
type StackEntry = {
pos: string;
name: string;
line: string;
col: string;
};
const compareEntry = (prev: StackEntry, next: StackEntry): boolean => {
return prev.pos === next.pos && prev.line === next.line &&
prev.col === next.col;
};
let previousStack: StackEntry[] = [];
// returns the length of the common prefix of the two stacks
const compareStacks = (prev: StackEntry[], next: StackEntry[]): number => {
prev = prev.toReversed();
next = next.toReversed();
let i = 0;
while (i < prev.length && i < next.length && compareEntry(prev[i], next[i])) {
i++;
}
return i;
};
export const getStackAsArray = (
format?: "json" | "raw" | "ansi",
offset?: number,
) => {
let rawStack = (new Error().stack ?? "").split("\n").slice(offset ?? 2);
// now we heuristically try to match the first entry of the stack trace (last in the stack)
// to our expectations of quarto.ts being the entry point.
// This will only happen in dev builds and when
//
// export QUARTO_DENO_V8_OPTIONS=--stack-trace-limit=100
//
// is set.
const m = rawStack[rawStack.length - 1].match(
/^.*at async (.*)src\/quarto.ts:\d+:\d+$/,
);
if (!m) {
warn(
"Could not find quarto.ts in stack trace, is QUARTO_DENO_V8_OPTIONS set with a sufficiently-large stack size?",
);
}
// filter out eventLoopTick
rawStack = rawStack.filter((s) =>
!(s.match(/eventLoopTick/) && s.match(/core\/01_core.js/))
);
if (m && (typeof format !== "undefined") && (format !== "raw")) {
const pathPrefix = m[1];
// first, trim all the path prefixes
rawStack = rawStack.map((s) => s.replace(pathPrefix, ""));
// then, entries can be async or not, and be in the main entry point or not.
// main entry point async entries look like: "at async src/quarto.ts:170:5"
// main entry point sync entries look like: "at src/quarto.ts:170:5"
// other async entries look like: "at async render (src/command/render/render-shared.ts:112:22)"
// other sync entries look like: "at render (src/command/render/render-shared.ts:112:22)"
// we want them all to start with the source file and line number in parentheses
const entries: StackEntry[] = rawStack.map((s) => {
// main entry point? (no parentheses)
const m1 = s.match(/^.*at (async )?(src\/quarto.ts):(\d+):(\d+)$/);
if (m1) {
return {
pos: m1[2],
name: `<main>`,
line: m1[3],
// if async, move the column to the start of the actual function name
col: m1[4] + (m1[1] ? 6 : 0),
};
}
// other stack entry
// (with parentheses)
const m2 = s.match(/^.*at (async )?(.*) \((src\/.+):(\d+):(\d+)\)$/) ||
// without parentheses - async and name will be empty
s.match(/^.*at (async )?(.*)(src\/.+):(\d+):(\d+)$/);
if (m2) {
return {
pos: m2[3],
name: `${m2[2]}`,
line: m2[4],
// if async, move the column to the start of the actual function name
col: m2[5] + (m2[1] ? 6 : 0),
};
}
// links to deno's core?
// FIXME these will generate bad links in vscode
const m3 = s.match(
/^.*at (async )?(.*) \(ext:(core\/.+):(\d+):(\d+)*\)$/,
);
if (m3) {
return {
pos: m3[3],
name: `${m3[2]}`,
line: m3[4],
// if async, move the column to the start of the actual function name
col: m3[5] + (m3[1] ? 6 : 0),
};
}
// at async Command.execute (https://deno.land/x/cliffy@v1.0.0-rc.3/command/command.ts:1948:7)
const m4 = s.match(
/^.*at (async )?(.*) \((http.+):(\d+):(\d+)*\)$/,
);
if (m4) {
return {
pos: m4[3],
name: `${m4[2]}`,
line: m4[4],
// if async, move the column to the start of the actual function name
col: m4[5] + (m4[1] ? 6 : 0),
};
}
// at Array.map (<anonymous>)
const m5 = s.match(
/^.*at (.*)\(<anonymous>\)$/,
);
if (m5) {
return {
pos: "",
name: `${m5[1]}`,
line: "",
col: "",
};
}
throw new Error(`Unexpected stack entry: ${s}`);
});
if (format === "json") {
return entries;
}
const maxPosLength = Math.max(...entries.map((e) => e.pos.length));
const maxLineLength = Math.max(
...entries.map((e) => String(e.line).length),
);
const maxColLength = Math.max(...entries.map((e) => String(e.col).length));
// this one only works in super fancy terminal emulators and vscode, :shrug:
// https://gist.github.com/egmontkob/eb114294efbcd5adb1944c9f3cb5feda
// now we format them all
const accentColor = colors.gray;
const commonPrefixLength = compareStacks(previousStack, entries);
rawStack = entries.map((e, i) => {
const linkedPos = `\x1b]8;;${
pathPrefix.replace("file://", "vscode://file")
}${e.pos}:${e.line}:${e.col}\x1b\\${e.pos}\x1b]8;;\x1b\\`;
const srcPadding = " ".repeat(maxPosLength - e.pos.length);
const linePadding = " ".repeat(maxLineLength - String(e.line).length);
const colPadding = " ".repeat(maxColLength - String(e.col).length);
const isFirstChange = i === entries.length - commonPrefixLength - 1;
if (!isFirstChange) {
return `${srcPadding}${
accentColor(
linkedPos + ":" + linePadding + e.line + colPadding + ":" + e.col +
": " + e.name,
)
}`;
}
return `${srcPadding}${linkedPos}${
accentColor(":")
}${linePadding}${e.line}${accentColor(":")}${colPadding}${e.col}${
accentColor(":")
} ${colors.yellow(e.name)}`;
});
previousStack = entries;
}
return rawStack;
};
export const getStack = (format?: "json" | "raw" | "ansi", offset?: number) => {
return "Stack:\n" +
getStackAsArray(format, offset ? offset + 1 : 3).join("\n");
};
// use debugPrint instead of console["log"] so it's easier to find stray print statements
// on our codebase
//
// deno-lint-ignore no-explicit-any
export const debugPrint = (...data: any[]) => {
// use console["log"] here instead of dot notation
// to allow us to lint for the dot notation usage which
// we want to disallow throughout the codebase
console["log"](...data);
};
export const debugLogWithStack = async (...data: unknown[]) => {
const payload = {
payload: data,
stack: getStackAsArray(),
timestamp: new Date().toISOString(),
};
await Deno.writeTextFile(
"/tmp/stack-debug.json",
JSON.stringify(payload) + "\n",
{
append: true,
},
);
};