@krate/runtime 0.5.0-rc.14 → 0.5.0-rc.15
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/action-context.js +5 -1
- package/dist/dev/api.d.ts +93 -0
- package/dist/dev/api.js +2 -0
- package/dist/dev/app.d.ts +165 -0
- package/dist/dev/app.js +1204 -0
- package/dist/dev/commands.d.ts +49 -0
- package/dist/dev/commands.js +114 -0
- package/dist/dev/highlight.d.ts +4 -0
- package/dist/dev/highlight.js +126 -0
- package/dist/dev/icons.d.ts +4 -0
- package/dist/dev/icons.js +57 -0
- package/dist/dev/inspect.d.ts +55 -0
- package/dist/dev/inspect.js +256 -0
- package/dist/dev/inspector.d.ts +39 -0
- package/dist/dev/inspector.js +348 -0
- package/dist/dev/issues.d.ts +83 -0
- package/dist/dev/issues.js +166 -0
- package/dist/dev/modal.d.ts +16 -0
- package/dist/dev/modal.js +836 -0
- package/dist/dev/native.d.ts +53 -0
- package/dist/dev/native.js +95 -0
- package/dist/dev/palette.d.ts +9 -0
- package/dist/dev/palette.js +250 -0
- package/dist/dev/panel.d.ts +31 -0
- package/dist/dev/panel.js +848 -0
- package/dist/dev/requests.d.ts +36 -0
- package/dist/dev/requests.js +150 -0
- package/dist/dev/settings.d.ts +32 -0
- package/dist/dev/settings.js +78 -0
- package/dist/dev/sourcemap.d.ts +22 -0
- package/dist/dev/sourcemap.js +148 -0
- package/dist/dev/stack.d.ts +38 -0
- package/dist/dev/stack.js +115 -0
- package/dist/dev/styles.d.ts +1 -0
- package/dist/dev/styles.js +424 -0
- package/dist/dev/util.d.ts +63 -0
- package/dist/dev/util.js +190 -0
- package/dist/dev-overlay.d.ts +9 -83
- package/dist/dev-overlay.js +17 -1038
- package/dist/island-swap.js +7 -1
- package/dist/krate-core.js +1 -1
- package/dist/krate-dev.js +441 -871
- package/dist/krate-f-list.js +1 -1
- package/dist/krate-f-navigation.js +1 -1
- package/dist/krate-hydrate-lite.js +5 -5
- package/dist/krate-hydrate.js +5 -5
- package/dist/krate-island-swap.js +1 -1
- package/dist/krate-runtime.js +5 -5
- package/dist/list.js +23 -1
- package/dist/metadata.js +23 -12
- package/dist/request-context.d.ts +10 -0
- package/dist/request-context.js +24 -0
- package/dist/server-handler.d.ts +2 -0
- package/dist/server-handler.js +1 -1
- package/dist/server-renderer.js +6 -2
- package/dist/server.js +2 -2
- package/dist/signal.d.ts +8 -0
- package/dist/signal.js +4 -0
- package/dist/ssr-core.d.ts +3 -0
- package/dist/ssr-core.js +44 -5
- package/package.json +1 -1
package/dist/dev/app.js
ADDED
|
@@ -0,0 +1,1204 @@
|
|
|
1
|
+
// The dev overlay controller: connection to the dev server, error capture,
|
|
2
|
+
// the dock and the layers it opens. Views live in panel.ts, modal.ts,
|
|
3
|
+
// palette.ts and inspector.ts; they render from the state kept here.
|
|
4
|
+
import { DEFAULT_DOCS_URL } from './api.js';
|
|
5
|
+
import { icon, mark } from './icons.js';
|
|
6
|
+
import { isBuildWarning, issueFromRuntime, issueFromServer, issuesFromDiagnostics, } from './issues.js';
|
|
7
|
+
import { hostStackOf, parseFrames } from './native.js';
|
|
8
|
+
import { RequestLog, captureRequests, rawFetch } from './requests.js';
|
|
9
|
+
import { kbd, loadSettings, nearestCorner, saveSettings, shortcutOf } from './settings.js';
|
|
10
|
+
import { symbolicateStack } from './sourcemap.js';
|
|
11
|
+
import { STYLE } from './styles.js';
|
|
12
|
+
import { basename, clock, devConfig, esc, fmtMs, formatArg, isTypingTarget, plural, routeMatches } from './util.js';
|
|
13
|
+
import { renderPanel, renderPanelBody, panelClick, visibleTabs, refreshLogs, stopPanelTimers, startPanelTimers } from './panel.js';
|
|
14
|
+
import { renderModal, modalClick, modalKey, prepareIssue } from './modal.js';
|
|
15
|
+
import { openPalette, closePalette, paletteKey, paletteClick } from './palette.js';
|
|
16
|
+
import { Inspector } from './inspector.js';
|
|
17
|
+
const IGNORE_KEY = 'krate:dev-ignored';
|
|
18
|
+
export class KrateDev {
|
|
19
|
+
constructor() {
|
|
20
|
+
this.cfg = devConfig();
|
|
21
|
+
this.settings = loadSettings();
|
|
22
|
+
this.inspector = new Inspector(this);
|
|
23
|
+
// connection and builds
|
|
24
|
+
this.conn = 'connecting';
|
|
25
|
+
this.building = false;
|
|
26
|
+
this.buildFiles = [];
|
|
27
|
+
this.builds = [];
|
|
28
|
+
this.activity = 'unknown';
|
|
29
|
+
this.routeFor = '';
|
|
30
|
+
// issues
|
|
31
|
+
this.issues = [];
|
|
32
|
+
this.ignored = new Set();
|
|
33
|
+
this.cur = 0;
|
|
34
|
+
this.modalOpen = false;
|
|
35
|
+
this.seen = new Set();
|
|
36
|
+
this.frames = new Map();
|
|
37
|
+
/** Log lines around a server crash, with their source and time. */
|
|
38
|
+
this.tails = new Map();
|
|
39
|
+
this.fixes = new Map();
|
|
40
|
+
this.busy = new Set();
|
|
41
|
+
this.runtimeTab = 'stack';
|
|
42
|
+
/** Failed fetch/XHR requests of the page, for the runtime error's Request tab. */
|
|
43
|
+
this.requests = new RequestLog();
|
|
44
|
+
/**
|
|
45
|
+
* The build failed and the error overlay was dismissed with "Show last good
|
|
46
|
+
* page": the page on screen is the last good build until a build passes.
|
|
47
|
+
*/
|
|
48
|
+
this.staleView = false;
|
|
49
|
+
/** Registry entries of diagnostic codes (null: unknown), from /code. */
|
|
50
|
+
this.codes = new Map();
|
|
51
|
+
/** The code whose "What this means" popover is open. */
|
|
52
|
+
this.codePop = '';
|
|
53
|
+
this.unfold = new Set();
|
|
54
|
+
// panel
|
|
55
|
+
this.panelOpen = false;
|
|
56
|
+
this.tab = 'route';
|
|
57
|
+
this.hiddenAll = false;
|
|
58
|
+
this.peek = false;
|
|
59
|
+
// logs
|
|
60
|
+
this.serverLogs = [];
|
|
61
|
+
this.localLogs = [];
|
|
62
|
+
this.logSeq = 0;
|
|
63
|
+
this.logsMissing = false;
|
|
64
|
+
this.logFilter = 'all';
|
|
65
|
+
this.logQuery = '';
|
|
66
|
+
this.errorsOnly = false;
|
|
67
|
+
this.logsClearedAt = 0;
|
|
68
|
+
this.logsSeenAt = Date.now();
|
|
69
|
+
this.logOpen = new Set();
|
|
70
|
+
this.localSeq = 0;
|
|
71
|
+
// native
|
|
72
|
+
this.hostSeq = 0;
|
|
73
|
+
this.hostRows = [];
|
|
74
|
+
this.timers = [];
|
|
75
|
+
/** Undo functions for listeners outside the shadow root (destroy). */
|
|
76
|
+
this.unbind = [];
|
|
77
|
+
this.suppressClick = false;
|
|
78
|
+
}
|
|
79
|
+
init() {
|
|
80
|
+
const host = document.createElement('krate-dev');
|
|
81
|
+
host.id = 'krate-dev-root';
|
|
82
|
+
host.style.cssText =
|
|
83
|
+
'position:fixed!important;top:0!important;left:0!important;width:0!important;height:0!important;' +
|
|
84
|
+
'overflow:visible!important;z-index:2147483000!important;pointer-events:none!important;display:block!important;' +
|
|
85
|
+
'margin:0!important;padding:0!important;border:0!important;transform:none!important;filter:none!important';
|
|
86
|
+
(document.body || document.documentElement).appendChild(host);
|
|
87
|
+
this.host = host;
|
|
88
|
+
this.shadow = host.attachShadow({ mode: 'open' });
|
|
89
|
+
const style = document.createElement('style');
|
|
90
|
+
style.textContent = STYLE;
|
|
91
|
+
this.shadow.appendChild(style);
|
|
92
|
+
this.root = document.createElement('div');
|
|
93
|
+
this.root.className = 'kd';
|
|
94
|
+
this.shadow.appendChild(this.root);
|
|
95
|
+
this.applySettings();
|
|
96
|
+
try {
|
|
97
|
+
matchMedia('(prefers-color-scheme: light)').addEventListener('change', () => this.applySettings());
|
|
98
|
+
}
|
|
99
|
+
catch {
|
|
100
|
+
/* without matchMedia, System stays dark */
|
|
101
|
+
}
|
|
102
|
+
try {
|
|
103
|
+
for (const id of JSON.parse(sessionStorage.getItem(IGNORE_KEY) || '[]'))
|
|
104
|
+
this.ignored.add(String(id));
|
|
105
|
+
}
|
|
106
|
+
catch {
|
|
107
|
+
/* session storage is optional */
|
|
108
|
+
}
|
|
109
|
+
if (this.cfg.toolbar) {
|
|
110
|
+
this.dock = document.createElement('div');
|
|
111
|
+
this.dock.className = 'dock';
|
|
112
|
+
this.dock.setAttribute('role', 'toolbar');
|
|
113
|
+
this.dock.setAttribute('aria-label', 'Krate dev tools');
|
|
114
|
+
this.root.appendChild(this.dock);
|
|
115
|
+
this.initDrag(this.dock);
|
|
116
|
+
this.dock.addEventListener('mouseenter', () => this.setPeek(true));
|
|
117
|
+
this.dock.addEventListener('mouseleave', () => this.setPeek(false));
|
|
118
|
+
this.watchLocation();
|
|
119
|
+
}
|
|
120
|
+
this.renderDock();
|
|
121
|
+
this.shadow.addEventListener('click', (e) => this.onClick(e));
|
|
122
|
+
this.shadow.addEventListener('input', (e) => this.onInput(e));
|
|
123
|
+
this.shadow.addEventListener('change', (e) => this.onInput(e));
|
|
124
|
+
this.listen(document, 'keydown', (e) => this.onKey(e), true);
|
|
125
|
+
if (this.cfg.frames)
|
|
126
|
+
this.connectFrames();
|
|
127
|
+
else
|
|
128
|
+
this.connectSSE();
|
|
129
|
+
this.captureRuntimeErrors();
|
|
130
|
+
this.unbind.push(captureRequests(this.requests));
|
|
131
|
+
void this.loadStartup();
|
|
132
|
+
}
|
|
133
|
+
/** Stops timers and removes the overlay (tests). */
|
|
134
|
+
listen(target, type, fn, capture = false) {
|
|
135
|
+
target.addEventListener(type, fn, capture);
|
|
136
|
+
this.unbind.push(() => target.removeEventListener(type, fn, capture));
|
|
137
|
+
}
|
|
138
|
+
destroy() {
|
|
139
|
+
for (const u of this.unbind.splice(0))
|
|
140
|
+
u();
|
|
141
|
+
this.sse?.close();
|
|
142
|
+
for (const t of this.timers)
|
|
143
|
+
clearInterval(t);
|
|
144
|
+
this.timers = [];
|
|
145
|
+
stopPanelTimers(this);
|
|
146
|
+
this.inspector.disable();
|
|
147
|
+
this.host?.remove();
|
|
148
|
+
}
|
|
149
|
+
applySettings() {
|
|
150
|
+
let theme = this.settings.theme;
|
|
151
|
+
if (theme === 'system') {
|
|
152
|
+
try {
|
|
153
|
+
theme = matchMedia('(prefers-color-scheme: light)').matches ? 'light' : 'dark';
|
|
154
|
+
}
|
|
155
|
+
catch {
|
|
156
|
+
theme = 'dark';
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
this.host.setAttribute('data-theme', theme);
|
|
160
|
+
this.root.className = 'kd c-' + this.settings.corner;
|
|
161
|
+
}
|
|
162
|
+
setSettings(patch) {
|
|
163
|
+
this.settings = { ...this.settings, ...patch };
|
|
164
|
+
saveSettings(this.settings);
|
|
165
|
+
this.applySettings();
|
|
166
|
+
this.renderDock();
|
|
167
|
+
if (this.panelOpen)
|
|
168
|
+
renderPanelBody(this);
|
|
169
|
+
}
|
|
170
|
+
// data
|
|
171
|
+
apiURL(path, params) {
|
|
172
|
+
let url = this.cfg.api.replace(/\/+$/, '') + path;
|
|
173
|
+
if (params) {
|
|
174
|
+
const q = Object.entries(params)
|
|
175
|
+
.filter(([, v]) => v !== undefined && v !== '')
|
|
176
|
+
.map(([k, v]) => encodeURIComponent(k) + '=' + encodeURIComponent(String(v)))
|
|
177
|
+
.join('&');
|
|
178
|
+
if (q)
|
|
179
|
+
url += '?' + q;
|
|
180
|
+
}
|
|
181
|
+
return url;
|
|
182
|
+
}
|
|
183
|
+
/** GETs a dev endpoint; null when the host has no such endpoint or it fails. */
|
|
184
|
+
async getJSON(path, params) {
|
|
185
|
+
if (!this.cfg.api)
|
|
186
|
+
return null;
|
|
187
|
+
try {
|
|
188
|
+
const res = await rawFetch(this.apiURL(path, params), { cache: 'no-store', headers: { Accept: 'application/json' } });
|
|
189
|
+
if (!res.ok)
|
|
190
|
+
return null;
|
|
191
|
+
return (await res.json());
|
|
192
|
+
}
|
|
193
|
+
catch {
|
|
194
|
+
return null;
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
async postJSON(path, body) {
|
|
198
|
+
if (!this.cfg.api)
|
|
199
|
+
return { status: 0, data: null };
|
|
200
|
+
try {
|
|
201
|
+
const res = await rawFetch(this.apiURL(path), {
|
|
202
|
+
method: 'POST',
|
|
203
|
+
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
|
|
204
|
+
body: JSON.stringify(body),
|
|
205
|
+
});
|
|
206
|
+
let data = null;
|
|
207
|
+
try {
|
|
208
|
+
data = await res.json();
|
|
209
|
+
}
|
|
210
|
+
catch {
|
|
211
|
+
data = null;
|
|
212
|
+
}
|
|
213
|
+
return { status: res.status, data };
|
|
214
|
+
}
|
|
215
|
+
catch {
|
|
216
|
+
return { status: 0, data: null };
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
async loadStartup() {
|
|
220
|
+
if (!this.cfg.api) {
|
|
221
|
+
this.info = null;
|
|
222
|
+
this.activity = 'missing';
|
|
223
|
+
this.renderDock();
|
|
224
|
+
return;
|
|
225
|
+
}
|
|
226
|
+
const [info, act] = await Promise.all([this.getJSON('/info'), this.getJSON('/activity')]);
|
|
227
|
+
this.info = info;
|
|
228
|
+
if (act && Array.isArray(act.builds)) {
|
|
229
|
+
this.activity = 'ok';
|
|
230
|
+
this.builds = act.builds.slice(-100);
|
|
231
|
+
this.lastBuild = this.builds[this.builds.length - 1];
|
|
232
|
+
this.lastGoodAt = act.lastGoodAt;
|
|
233
|
+
if (act.building)
|
|
234
|
+
this.building = true;
|
|
235
|
+
}
|
|
236
|
+
else {
|
|
237
|
+
this.activity = 'missing';
|
|
238
|
+
}
|
|
239
|
+
if (!this.cfg.page)
|
|
240
|
+
void this.loadRoute();
|
|
241
|
+
this.renderDock();
|
|
242
|
+
if (this.panelOpen)
|
|
243
|
+
renderPanel(this);
|
|
244
|
+
}
|
|
245
|
+
async loadRoute(force = false) {
|
|
246
|
+
const path = location.pathname;
|
|
247
|
+
if (!force && this.routeFor === path && this.route !== undefined)
|
|
248
|
+
return;
|
|
249
|
+
this.routeFor = path;
|
|
250
|
+
const r = await this.getJSON('/route', { path });
|
|
251
|
+
if (this.routeFor !== path)
|
|
252
|
+
return;
|
|
253
|
+
this.route = r;
|
|
254
|
+
this.renderDock();
|
|
255
|
+
if (this.panelOpen && this.tab === 'route')
|
|
256
|
+
renderPanelBody(this);
|
|
257
|
+
}
|
|
258
|
+
async loadRoutes() {
|
|
259
|
+
const r = await this.getJSON('/routes');
|
|
260
|
+
this.routes = Array.isArray(r) ? r : null;
|
|
261
|
+
return this.routes;
|
|
262
|
+
}
|
|
263
|
+
/** The route pattern and mode of the page on screen. */
|
|
264
|
+
pageRoute() {
|
|
265
|
+
const path = location.pathname;
|
|
266
|
+
if (this.route && this.routeFor === path) {
|
|
267
|
+
return { route: this.route.pattern, mode: this.route.mode || '', source: this.route.source };
|
|
268
|
+
}
|
|
269
|
+
const p = this.cfg.page;
|
|
270
|
+
if (p && (!this.routeFor || this.routeFor === path || routeMatches(p.route, path, this.cfg.basePath))) {
|
|
271
|
+
return { route: p.route, mode: p.mode || '', source: p.source };
|
|
272
|
+
}
|
|
273
|
+
return { route: path, mode: '' };
|
|
274
|
+
}
|
|
275
|
+
// editor and actions
|
|
276
|
+
async openInEditor(file, line, col) {
|
|
277
|
+
if (!file)
|
|
278
|
+
return;
|
|
279
|
+
let url = this.cfg.open + '?file=' + encodeURIComponent(file) + '&line=' + encodeURIComponent(String(line || ''));
|
|
280
|
+
if (col)
|
|
281
|
+
url += '&col=' + encodeURIComponent(String(col));
|
|
282
|
+
const ed = this.settings.editor;
|
|
283
|
+
const known = ed && this.info?.editor?.available?.some((e) => e.id === ed);
|
|
284
|
+
try {
|
|
285
|
+
let res = await rawFetch(known ? url + '&editor=' + encodeURIComponent(ed) : url);
|
|
286
|
+
if (!res.ok && known)
|
|
287
|
+
res = await rawFetch(url);
|
|
288
|
+
if (!res.ok)
|
|
289
|
+
this.toast('Could not open the editor', file, 'x');
|
|
290
|
+
}
|
|
291
|
+
catch {
|
|
292
|
+
this.toast('Could not open the editor', file, 'x');
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
async runAction(action, extra = {}) {
|
|
296
|
+
const { status } = await this.postJSON('/action', { action, ...extra });
|
|
297
|
+
const labels = {
|
|
298
|
+
'rebuild-page': 'Rebuilding this page',
|
|
299
|
+
'rebuild-all': 'Rebuilding everything',
|
|
300
|
+
'clear-cache': 'Cache cleared, rebuilding',
|
|
301
|
+
'restart-server': 'Restarting the dev server',
|
|
302
|
+
'restart-sidecar': 'Restarting the sidecar',
|
|
303
|
+
};
|
|
304
|
+
if (status === 202) {
|
|
305
|
+
this.toast(labels[action] || 'Done', '', 'check');
|
|
306
|
+
return true;
|
|
307
|
+
}
|
|
308
|
+
this.toast(status === 409 ? 'Not available right now' : status === 404 ? 'Nothing to do for this page' : 'The dev server refused', action, 'x');
|
|
309
|
+
return false;
|
|
310
|
+
}
|
|
311
|
+
// dock
|
|
312
|
+
renderDock() {
|
|
313
|
+
const d = this.dock;
|
|
314
|
+
if (!d)
|
|
315
|
+
return;
|
|
316
|
+
d.hidden = this.hiddenAll;
|
|
317
|
+
const issues = this.visibleIssues();
|
|
318
|
+
const warnings = issues.filter(isBuildWarning).length;
|
|
319
|
+
const errors = issues.length - warnings;
|
|
320
|
+
const mini = this.settings.collapsed && !this.peek;
|
|
321
|
+
const inspecting = this.inspector.on;
|
|
322
|
+
const down = this.conn === 'down';
|
|
323
|
+
d.className =
|
|
324
|
+
'dock' +
|
|
325
|
+
(mini ? ' mini' : '') +
|
|
326
|
+
(down ? ' off' : errors ? ' error' : warnings ? ' warn' : '') +
|
|
327
|
+
(this.building && !down ? ' building' : '') +
|
|
328
|
+
(inspecting ? ' inspect' : '');
|
|
329
|
+
const markBtn = '<button class="markbtn" type="button" data-act="collapse" title="' +
|
|
330
|
+
(this.settings.collapsed ? 'Expand the dock' : 'Collapse the dock') +
|
|
331
|
+
'" aria-label="Krate">' +
|
|
332
|
+
mark() +
|
|
333
|
+
'</button>';
|
|
334
|
+
if (mini) {
|
|
335
|
+
d.innerHTML =
|
|
336
|
+
markBtn +
|
|
337
|
+
(errors
|
|
338
|
+
? '<i class="pip" aria-label="' + esc(plural(errors, 'issue')) + '"></i>'
|
|
339
|
+
: warnings
|
|
340
|
+
? '<i class="pip w" aria-label="' + esc(plural(warnings, 'warning')) + '"></i>'
|
|
341
|
+
: '');
|
|
342
|
+
return;
|
|
343
|
+
}
|
|
344
|
+
if (down) {
|
|
345
|
+
d.innerHTML =
|
|
346
|
+
markBtn + '<div class="seg idle" role="status"><span>Reconnecting to dev server</span><span class="spin" style="margin-left:4px"></span></div>';
|
|
347
|
+
return;
|
|
348
|
+
}
|
|
349
|
+
const { route, mode } = this.pageRoute();
|
|
350
|
+
let html = markBtn +
|
|
351
|
+
'<button class="seg' +
|
|
352
|
+
(this.panelOpen ? ' open' : '') +
|
|
353
|
+
'" type="button" data-act="panel" aria-expanded="' +
|
|
354
|
+
this.panelOpen +
|
|
355
|
+
'" title="Route details">' +
|
|
356
|
+
(mode ? '<span class="mode ' + esc(mode) + '">' + esc(mode.toUpperCase()) + '</span>' : '') +
|
|
357
|
+
'<span class="route mono">' +
|
|
358
|
+
esc(route) +
|
|
359
|
+
'</span></button><div class="sep"></div>';
|
|
360
|
+
if (inspecting) {
|
|
361
|
+
html +=
|
|
362
|
+
'<button class="seg on" type="button" data-act="inspect" title="Stop inspecting">' +
|
|
363
|
+
icon('mouse-pointer-2') +
|
|
364
|
+
'<span>Inspecting</span><span class="kbd">Esc</span></button>';
|
|
365
|
+
}
|
|
366
|
+
else if (this.building) {
|
|
367
|
+
const n = this.buildFiles.length;
|
|
368
|
+
const what = n === 1 ? ' ' + basename(this.buildFiles[0]) : n > 1 ? ' ' + n + ' files' : '';
|
|
369
|
+
html += '<div class="seg busy" role="status"><span>Rebuilding' + esc(what) + '</span></div>';
|
|
370
|
+
}
|
|
371
|
+
else if (errors) {
|
|
372
|
+
const serverOnly = issues.every((i) => i.kind === 'server' || isBuildWarning(i));
|
|
373
|
+
if (this.staleView && issues.some((i) => i.kind === 'build' && i.severity === 'error')) {
|
|
374
|
+
html +=
|
|
375
|
+
'<div class="seg stale" role="status" title="The build failed; this is the last build that passed">' +
|
|
376
|
+
'<span>Last good build' +
|
|
377
|
+
(this.lastGoodAt ? ' ' + esc(clock(this.lastGoodAt)) : '') +
|
|
378
|
+
'</span></div>';
|
|
379
|
+
}
|
|
380
|
+
html +=
|
|
381
|
+
'<button class="seg" type="button" data-act="issues" title="Show issues"><span class="badge err">' +
|
|
382
|
+
esc(serverOnly ? 'Server down' : plural(errors, 'issue')) +
|
|
383
|
+
'</span></button>';
|
|
384
|
+
}
|
|
385
|
+
else if (warnings) {
|
|
386
|
+
html +=
|
|
387
|
+
'<button class="seg" type="button" data-act="issues" title="Show build warnings"><span class="badge warn">' +
|
|
388
|
+
esc(plural(warnings, 'warning')) +
|
|
389
|
+
'</span></button>';
|
|
390
|
+
}
|
|
391
|
+
else if (this.lastBuild) {
|
|
392
|
+
html +=
|
|
393
|
+
'<button class="seg ok" type="button" data-act="activity" title="Last rebuild ' +
|
|
394
|
+
esc(fmtMs(this.lastBuild.durationMs)) +
|
|
395
|
+
'"><span class="ms mono">' +
|
|
396
|
+
esc(fmtMs(this.lastBuild.durationMs)) +
|
|
397
|
+
'</span></button>';
|
|
398
|
+
}
|
|
399
|
+
else {
|
|
400
|
+
html += '<div class="seg ok"><span class="ms">Ready</span></div>';
|
|
401
|
+
}
|
|
402
|
+
if (!inspecting && !this.building && !errors) {
|
|
403
|
+
html += '<button class="seg kbdseg" type="button" data-act="palette" title="Command menu">' + kbd(['Alt', 'K']) + '</button>';
|
|
404
|
+
}
|
|
405
|
+
d.innerHTML = html;
|
|
406
|
+
}
|
|
407
|
+
setPeek(on) {
|
|
408
|
+
if (!this.settings.collapsed || this.peek === on)
|
|
409
|
+
return;
|
|
410
|
+
this.peek = on;
|
|
411
|
+
this.renderDock();
|
|
412
|
+
}
|
|
413
|
+
initDrag(el) {
|
|
414
|
+
let start = null;
|
|
415
|
+
let dragging = false;
|
|
416
|
+
el.addEventListener('pointerdown', (e) => {
|
|
417
|
+
if (e.button !== 0)
|
|
418
|
+
return;
|
|
419
|
+
const r = el.getBoundingClientRect();
|
|
420
|
+
start = { x: e.clientX, y: e.clientY, dx: e.clientX - r.left, dy: e.clientY - r.top, id: e.pointerId };
|
|
421
|
+
dragging = false;
|
|
422
|
+
});
|
|
423
|
+
el.addEventListener('pointermove', (e) => {
|
|
424
|
+
if (!start || e.pointerId !== start.id)
|
|
425
|
+
return;
|
|
426
|
+
if (!dragging && Math.hypot(e.clientX - start.x, e.clientY - start.y) < 5)
|
|
427
|
+
return;
|
|
428
|
+
if (!dragging) {
|
|
429
|
+
dragging = true;
|
|
430
|
+
try {
|
|
431
|
+
el.setPointerCapture(e.pointerId);
|
|
432
|
+
}
|
|
433
|
+
catch {
|
|
434
|
+
/* capture is a nicety */
|
|
435
|
+
}
|
|
436
|
+
el.classList.add('dragging');
|
|
437
|
+
}
|
|
438
|
+
el.style.left = Math.max(0, e.clientX - start.dx) + 'px';
|
|
439
|
+
el.style.top = Math.max(0, e.clientY - start.dy) + 'px';
|
|
440
|
+
el.style.right = 'auto';
|
|
441
|
+
el.style.bottom = 'auto';
|
|
442
|
+
});
|
|
443
|
+
const end = (e) => {
|
|
444
|
+
if (!start || e.pointerId !== start.id)
|
|
445
|
+
return;
|
|
446
|
+
start = null;
|
|
447
|
+
if (!dragging)
|
|
448
|
+
return;
|
|
449
|
+
dragging = false;
|
|
450
|
+
const r = el.getBoundingClientRect();
|
|
451
|
+
el.classList.remove('dragging');
|
|
452
|
+
el.style.left = el.style.top = el.style.right = el.style.bottom = '';
|
|
453
|
+
this.suppressClick = true;
|
|
454
|
+
setTimeout(() => (this.suppressClick = false), 0);
|
|
455
|
+
this.setSettings({ corner: nearestCorner(r.left + r.width / 2, r.top + r.height / 2, innerWidth, innerHeight) });
|
|
456
|
+
};
|
|
457
|
+
el.addEventListener('pointerup', end);
|
|
458
|
+
el.addEventListener('pointercancel', end);
|
|
459
|
+
}
|
|
460
|
+
// layers
|
|
461
|
+
togglePanel(tab, force) {
|
|
462
|
+
if (!this.cfg.toolbar)
|
|
463
|
+
return;
|
|
464
|
+
const open = force ?? (tab && this.panelOpen ? this.tab !== tab : !this.panelOpen);
|
|
465
|
+
if (tab)
|
|
466
|
+
this.tab = tab;
|
|
467
|
+
if (!visibleTabs(this).includes(this.tab))
|
|
468
|
+
this.tab = 'route';
|
|
469
|
+
this.panelOpen = open;
|
|
470
|
+
if (open) {
|
|
471
|
+
if (!this.panel) {
|
|
472
|
+
this.panel = document.createElement('div');
|
|
473
|
+
this.panel.className = 'panel';
|
|
474
|
+
this.panel.setAttribute('role', 'dialog');
|
|
475
|
+
this.panel.setAttribute('aria-label', 'Krate dev tools');
|
|
476
|
+
this.root.insertBefore(this.panel, this.dock || null);
|
|
477
|
+
}
|
|
478
|
+
this.panel.hidden = this.hiddenAll;
|
|
479
|
+
renderPanel(this);
|
|
480
|
+
startPanelTimers(this);
|
|
481
|
+
if (this.tab === 'route')
|
|
482
|
+
void this.loadRoute();
|
|
483
|
+
}
|
|
484
|
+
else if (this.panel) {
|
|
485
|
+
this.panel.hidden = true;
|
|
486
|
+
stopPanelTimers(this);
|
|
487
|
+
}
|
|
488
|
+
this.renderDock();
|
|
489
|
+
}
|
|
490
|
+
setTab(tab) {
|
|
491
|
+
this.tab = tab;
|
|
492
|
+
if (this.tab === 'logs')
|
|
493
|
+
this.logsSeenAt = Date.now();
|
|
494
|
+
renderPanel(this);
|
|
495
|
+
startPanelTimers(this);
|
|
496
|
+
if (tab === 'route')
|
|
497
|
+
void this.loadRoute();
|
|
498
|
+
}
|
|
499
|
+
visibleIssues() {
|
|
500
|
+
const rank = { build: 0, server: 1, runtime: 2 };
|
|
501
|
+
return this.issues
|
|
502
|
+
.filter((i) => !this.ignored.has(i.id) && (this.settings.showWarnings || !isBuildWarning(i)))
|
|
503
|
+
.sort((a, b) => rank[a.kind] - rank[b.kind] || (a.severity === b.severity ? 0 : a.severity === 'error' ? -1 : 1));
|
|
504
|
+
}
|
|
505
|
+
openModal() {
|
|
506
|
+
const list = this.visibleIssues();
|
|
507
|
+
if (!list.length)
|
|
508
|
+
return;
|
|
509
|
+
if (!this.modalOpen)
|
|
510
|
+
this.restoreFocus = document.activeElement;
|
|
511
|
+
this.modalOpen = true;
|
|
512
|
+
if (this.cur >= list.length)
|
|
513
|
+
this.cur = 0;
|
|
514
|
+
if (!this.modal) {
|
|
515
|
+
this.modal = document.createElement('div');
|
|
516
|
+
this.modal.className = 'ov';
|
|
517
|
+
this.root.appendChild(this.modal);
|
|
518
|
+
}
|
|
519
|
+
this.modal.hidden = this.hiddenAll;
|
|
520
|
+
renderModal(this);
|
|
521
|
+
prepareIssue(this, list[this.cur]);
|
|
522
|
+
const m = this.modal.querySelector('.modal');
|
|
523
|
+
try {
|
|
524
|
+
m?.focus({ preventScroll: true });
|
|
525
|
+
}
|
|
526
|
+
catch {
|
|
527
|
+
/* focus is a nicety */
|
|
528
|
+
}
|
|
529
|
+
}
|
|
530
|
+
closeModal() {
|
|
531
|
+
this.modalOpen = false;
|
|
532
|
+
if (this.modal)
|
|
533
|
+
this.modal.hidden = true;
|
|
534
|
+
const f = this.restoreFocus;
|
|
535
|
+
this.restoreFocus = null;
|
|
536
|
+
try {
|
|
537
|
+
if (f && f.isConnected)
|
|
538
|
+
f.focus({ preventScroll: true });
|
|
539
|
+
}
|
|
540
|
+
catch {
|
|
541
|
+
/* focus is a nicety */
|
|
542
|
+
}
|
|
543
|
+
}
|
|
544
|
+
/** Re-renders whatever shows issues after the list changed. */
|
|
545
|
+
issuesChanged(open) {
|
|
546
|
+
const list = this.visibleIssues();
|
|
547
|
+
if (!list.length) {
|
|
548
|
+
this.closeModal();
|
|
549
|
+
}
|
|
550
|
+
else if (this.modalOpen) {
|
|
551
|
+
if (this.cur >= list.length)
|
|
552
|
+
this.cur = list.length - 1;
|
|
553
|
+
renderModal(this);
|
|
554
|
+
prepareIssue(this, list[this.cur]);
|
|
555
|
+
}
|
|
556
|
+
else if (open && this.cfg.overlay) {
|
|
557
|
+
this.cur = 0;
|
|
558
|
+
this.openModal();
|
|
559
|
+
}
|
|
560
|
+
this.renderDock();
|
|
561
|
+
if (this.panelOpen && this.tab === 'logs')
|
|
562
|
+
refreshLogs(this);
|
|
563
|
+
}
|
|
564
|
+
ignore(id) {
|
|
565
|
+
this.ignored.add(id);
|
|
566
|
+
try {
|
|
567
|
+
sessionStorage.setItem(IGNORE_KEY, JSON.stringify(Array.from(this.ignored).slice(-50)));
|
|
568
|
+
}
|
|
569
|
+
catch {
|
|
570
|
+
/* session storage is optional */
|
|
571
|
+
}
|
|
572
|
+
this.issuesChanged(false);
|
|
573
|
+
}
|
|
574
|
+
toggleHidden() {
|
|
575
|
+
this.hiddenAll = !this.hiddenAll;
|
|
576
|
+
for (const el of [this.dock, this.panel && this.panelOpen ? this.panel : undefined, this.modal && this.modalOpen ? this.modal : undefined])
|
|
577
|
+
if (el)
|
|
578
|
+
el.hidden = this.hiddenAll;
|
|
579
|
+
if (this.hiddenAll) {
|
|
580
|
+
this.inspector.disable();
|
|
581
|
+
closePalette(this);
|
|
582
|
+
}
|
|
583
|
+
this.renderDock();
|
|
584
|
+
}
|
|
585
|
+
toast(text, meta = '', kind = 'check') {
|
|
586
|
+
if (!this.toastEl) {
|
|
587
|
+
this.toastEl = document.createElement('div');
|
|
588
|
+
this.toastEl.className = 'toast';
|
|
589
|
+
this.toastEl.setAttribute('role', 'status');
|
|
590
|
+
this.root.appendChild(this.toastEl);
|
|
591
|
+
}
|
|
592
|
+
this.toastEl.innerHTML =
|
|
593
|
+
icon(kind === 'x' ? 'x' : 'check', kind === 'x' ? 'x' : 'ok') +
|
|
594
|
+
'<span>' +
|
|
595
|
+
esc(text) +
|
|
596
|
+
'</span>' +
|
|
597
|
+
(meta ? '<span class="meta mono">' + esc(meta) + '</span>' : '');
|
|
598
|
+
this.toastEl.hidden = this.hiddenAll || (this.panelOpen && !!this.panel && !this.panel.hidden);
|
|
599
|
+
if (this.toastTimer)
|
|
600
|
+
clearTimeout(this.toastTimer);
|
|
601
|
+
this.toastTimer = setTimeout(() => {
|
|
602
|
+
if (this.toastEl)
|
|
603
|
+
this.toastEl.hidden = true;
|
|
604
|
+
}, 2600);
|
|
605
|
+
}
|
|
606
|
+
// events
|
|
607
|
+
onClick(e) {
|
|
608
|
+
if (this.suppressClick) {
|
|
609
|
+
e.stopPropagation();
|
|
610
|
+
return;
|
|
611
|
+
}
|
|
612
|
+
const t = e.target.closest('[data-act]');
|
|
613
|
+
if (!t) {
|
|
614
|
+
// A click on the scrim closes the layer.
|
|
615
|
+
if (e.target === this.modal)
|
|
616
|
+
this.closeModal();
|
|
617
|
+
if (e.target === this.pal)
|
|
618
|
+
closePalette(this);
|
|
619
|
+
return;
|
|
620
|
+
}
|
|
621
|
+
const act = t.getAttribute('data-act') || '';
|
|
622
|
+
switch (act) {
|
|
623
|
+
case 'collapse':
|
|
624
|
+
this.peek = false;
|
|
625
|
+
this.setSettings({ collapsed: !this.settings.collapsed });
|
|
626
|
+
return;
|
|
627
|
+
case 'panel':
|
|
628
|
+
this.togglePanel('route');
|
|
629
|
+
return;
|
|
630
|
+
case 'activity':
|
|
631
|
+
this.togglePanel(this.activity === 'ok' ? 'activity' : 'route');
|
|
632
|
+
return;
|
|
633
|
+
case 'issues':
|
|
634
|
+
this.openModal();
|
|
635
|
+
return;
|
|
636
|
+
case 'palette':
|
|
637
|
+
openPalette(this);
|
|
638
|
+
return;
|
|
639
|
+
case 'inspect':
|
|
640
|
+
this.inspector.toggle();
|
|
641
|
+
return;
|
|
642
|
+
case 'open':
|
|
643
|
+
void this.openInEditor(t.dataset.file, t.dataset.line, t.dataset.col);
|
|
644
|
+
return;
|
|
645
|
+
}
|
|
646
|
+
if (panelClick(this, act, t, e))
|
|
647
|
+
return;
|
|
648
|
+
if (modalClick(this, act, t, e))
|
|
649
|
+
return;
|
|
650
|
+
paletteClick(this, act, t, e);
|
|
651
|
+
}
|
|
652
|
+
onInput(e) {
|
|
653
|
+
const t = e.target;
|
|
654
|
+
const name = t.getAttribute('data-input');
|
|
655
|
+
if (name === 'logq') {
|
|
656
|
+
this.logQuery = t.value;
|
|
657
|
+
refreshLogs(this);
|
|
658
|
+
}
|
|
659
|
+
else if (name === 'editor' && e.type === 'change') {
|
|
660
|
+
this.setSettings({ editor: t.value });
|
|
661
|
+
}
|
|
662
|
+
}
|
|
663
|
+
onKey(e) {
|
|
664
|
+
if (this.pal && !this.pal.hidden && paletteKey(this, e))
|
|
665
|
+
return;
|
|
666
|
+
const typing = isTypingTarget(e, this.host);
|
|
667
|
+
const sc = shortcutOf(e);
|
|
668
|
+
if (sc && !typing) {
|
|
669
|
+
e.preventDefault();
|
|
670
|
+
e.stopPropagation();
|
|
671
|
+
if (sc === 'hide')
|
|
672
|
+
this.toggleHidden();
|
|
673
|
+
else if (this.hiddenAll)
|
|
674
|
+
return;
|
|
675
|
+
else if (sc === 'menu')
|
|
676
|
+
openPalette(this);
|
|
677
|
+
else if (sc === 'inspect')
|
|
678
|
+
this.inspector.toggle();
|
|
679
|
+
else if (sc === 'issues') {
|
|
680
|
+
if (this.modalOpen)
|
|
681
|
+
this.closeModal();
|
|
682
|
+
else if (this.visibleIssues().length)
|
|
683
|
+
this.openModal();
|
|
684
|
+
else
|
|
685
|
+
this.toast('No issues', '', 'check');
|
|
686
|
+
}
|
|
687
|
+
return;
|
|
688
|
+
}
|
|
689
|
+
if (this.modalOpen && modalKey(this, e, typing))
|
|
690
|
+
return;
|
|
691
|
+
if (e.key === 'Escape' && !typing) {
|
|
692
|
+
if (this.inspector.on) {
|
|
693
|
+
this.inspector.disable();
|
|
694
|
+
e.preventDefault();
|
|
695
|
+
}
|
|
696
|
+
else if (this.panelOpen) {
|
|
697
|
+
this.togglePanel(undefined, false);
|
|
698
|
+
e.preventDefault();
|
|
699
|
+
}
|
|
700
|
+
}
|
|
701
|
+
}
|
|
702
|
+
/** Keep the dock route label in sync with SPA (history) navigation. */
|
|
703
|
+
watchLocation() {
|
|
704
|
+
let last = location.pathname;
|
|
705
|
+
const update = () => {
|
|
706
|
+
if (location.pathname === last)
|
|
707
|
+
return;
|
|
708
|
+
last = location.pathname;
|
|
709
|
+
this.renderDock();
|
|
710
|
+
if (this.cfg.api)
|
|
711
|
+
void this.loadRoute(true);
|
|
712
|
+
this.inspector.refresh();
|
|
713
|
+
};
|
|
714
|
+
this.listen(window, 'popstate', update);
|
|
715
|
+
const h = history;
|
|
716
|
+
const push = h.pushState.bind(history);
|
|
717
|
+
h.pushState = function (...args) {
|
|
718
|
+
const r = push(...args);
|
|
719
|
+
update();
|
|
720
|
+
return r;
|
|
721
|
+
};
|
|
722
|
+
const replace = h.replaceState.bind(history);
|
|
723
|
+
h.replaceState = function (...args) {
|
|
724
|
+
const r = replace(...args);
|
|
725
|
+
update();
|
|
726
|
+
return r;
|
|
727
|
+
};
|
|
728
|
+
// Safety net for routers that swap content without touching history.
|
|
729
|
+
this.timers.push(setInterval(update, 500));
|
|
730
|
+
}
|
|
731
|
+
setConn(c) {
|
|
732
|
+
if (this.conn === c)
|
|
733
|
+
return;
|
|
734
|
+
this.conn = c;
|
|
735
|
+
this.renderDock();
|
|
736
|
+
if (this.panelOpen)
|
|
737
|
+
renderPanel(this);
|
|
738
|
+
}
|
|
739
|
+
connectSSE() {
|
|
740
|
+
let sse;
|
|
741
|
+
try {
|
|
742
|
+
sse = new EventSource(this.cfg.sse);
|
|
743
|
+
}
|
|
744
|
+
catch {
|
|
745
|
+
return;
|
|
746
|
+
}
|
|
747
|
+
this.sse = sse;
|
|
748
|
+
let connectedOnce = false;
|
|
749
|
+
sse.addEventListener('connected', () => {
|
|
750
|
+
// A second "connected" means the stream dropped and came back: the dev
|
|
751
|
+
// server restarted (config or env change), so the page is stale.
|
|
752
|
+
if (connectedOnce)
|
|
753
|
+
location.reload();
|
|
754
|
+
connectedOnce = true;
|
|
755
|
+
this.setConn('open');
|
|
756
|
+
});
|
|
757
|
+
sse.addEventListener('open', () => this.setConn('open'));
|
|
758
|
+
sse.addEventListener('error', () => {
|
|
759
|
+
if (sse.readyState !== 1)
|
|
760
|
+
this.setConn('down');
|
|
761
|
+
});
|
|
762
|
+
const parse = (e) => {
|
|
763
|
+
try {
|
|
764
|
+
return JSON.parse(e.data);
|
|
765
|
+
}
|
|
766
|
+
catch {
|
|
767
|
+
return null;
|
|
768
|
+
}
|
|
769
|
+
};
|
|
770
|
+
sse.addEventListener('reload', (e) => this.onReload(parse(e)));
|
|
771
|
+
sse.addEventListener('build-error', (e) => this.onBuildError(parse(e)));
|
|
772
|
+
sse.addEventListener('build-warnings', (e) => this.onBuildWarnings(parse(e)));
|
|
773
|
+
sse.addEventListener('client-error', (e) => this.onClientError(parse(e)));
|
|
774
|
+
sse.addEventListener('build-start', (e) => this.onBuildStart(parse(e)));
|
|
775
|
+
sse.addEventListener('build-end', (e) => this.onBuildEnd(parse(e)));
|
|
776
|
+
}
|
|
777
|
+
/**
|
|
778
|
+
* Krate Native: the same events as SSE, as `{hmr: {type, ...}}` frames on a
|
|
779
|
+
* streaming fetch. Reconnects after the stream ends; a second "connected"
|
|
780
|
+
* means the shell restarted, so the page is stale.
|
|
781
|
+
*/
|
|
782
|
+
connectFrames() {
|
|
783
|
+
let connectedOnce = false;
|
|
784
|
+
const run = async () => {
|
|
785
|
+
const res = await rawFetch(this.cfg.frames, { cache: 'no-store' });
|
|
786
|
+
if (!res.ok || !res.body)
|
|
787
|
+
throw new Error('hmr stream unavailable');
|
|
788
|
+
const reader = res.body.getReader();
|
|
789
|
+
let buf = new Uint8Array(0);
|
|
790
|
+
for (;;) {
|
|
791
|
+
const { done, value } = await reader.read();
|
|
792
|
+
if (done)
|
|
793
|
+
return;
|
|
794
|
+
const joined = new Uint8Array(buf.length + value.length);
|
|
795
|
+
joined.set(buf);
|
|
796
|
+
joined.set(value, buf.length);
|
|
797
|
+
const parsed = parseFrames(joined);
|
|
798
|
+
buf = parsed.rest;
|
|
799
|
+
for (const v of parsed.values) {
|
|
800
|
+
const m = v?.hmr;
|
|
801
|
+
if (!m || typeof m !== 'object')
|
|
802
|
+
continue;
|
|
803
|
+
if (m.type === 'connected') {
|
|
804
|
+
if (connectedOnce)
|
|
805
|
+
location.reload();
|
|
806
|
+
connectedOnce = true;
|
|
807
|
+
this.setConn('open');
|
|
808
|
+
}
|
|
809
|
+
else if (m.type === 'reload')
|
|
810
|
+
this.onReload(m);
|
|
811
|
+
else if (m.type === 'build-error')
|
|
812
|
+
this.onBuildError(m);
|
|
813
|
+
else if (m.type === 'build-warnings')
|
|
814
|
+
this.onBuildWarnings(m);
|
|
815
|
+
else if (m.type === 'client-error')
|
|
816
|
+
this.onClientError(m);
|
|
817
|
+
else if (m.type === 'build-start')
|
|
818
|
+
this.onBuildStart(m);
|
|
819
|
+
else if (m.type === 'build-end')
|
|
820
|
+
this.onBuildEnd(m);
|
|
821
|
+
}
|
|
822
|
+
}
|
|
823
|
+
};
|
|
824
|
+
const loop = () => {
|
|
825
|
+
run().then(() => {
|
|
826
|
+
this.setConn('down');
|
|
827
|
+
setTimeout(loop, 1000);
|
|
828
|
+
}, () => {
|
|
829
|
+
this.setConn('down');
|
|
830
|
+
setTimeout(loop, 1000);
|
|
831
|
+
});
|
|
832
|
+
};
|
|
833
|
+
loop();
|
|
834
|
+
}
|
|
835
|
+
onBuildStart(d) {
|
|
836
|
+
this.building = true;
|
|
837
|
+
this.buildFiles = d && Array.isArray(d.files) ? d.files : [];
|
|
838
|
+
this.renderDock();
|
|
839
|
+
}
|
|
840
|
+
onBuildEnd(d) {
|
|
841
|
+
this.building = false;
|
|
842
|
+
this.buildFiles = [];
|
|
843
|
+
const b = d?.build;
|
|
844
|
+
if (b && b.kind !== 'noop') {
|
|
845
|
+
this.lastBuild = b;
|
|
846
|
+
this.builds.push(b);
|
|
847
|
+
if (this.builds.length > 100)
|
|
848
|
+
this.builds.shift();
|
|
849
|
+
if (b.ok)
|
|
850
|
+
this.lastGoodAt = b.start + b.durationMs;
|
|
851
|
+
if (this.activity === 'unknown')
|
|
852
|
+
this.activity = this.cfg.api ? 'ok' : 'missing';
|
|
853
|
+
this.route = this.route && this.routeFor === location.pathname ? this.route : undefined;
|
|
854
|
+
this.routeFor = '';
|
|
855
|
+
this.routes = undefined;
|
|
856
|
+
this.frames.clear();
|
|
857
|
+
this.fixes.clear();
|
|
858
|
+
if (b.ok)
|
|
859
|
+
this.staleView = false;
|
|
860
|
+
// Every build reports the warnings it leaves.
|
|
861
|
+
this.setWarnings(d && Array.isArray(d.warnings) ? d.warnings : []);
|
|
862
|
+
}
|
|
863
|
+
this.renderDock();
|
|
864
|
+
if (this.panelOpen && (this.tab === 'activity' || this.tab === 'route')) {
|
|
865
|
+
renderPanelBody(this);
|
|
866
|
+
if (this.tab === 'route')
|
|
867
|
+
void this.loadRoute(true);
|
|
868
|
+
}
|
|
869
|
+
if (this.modalOpen)
|
|
870
|
+
renderModal(this);
|
|
871
|
+
}
|
|
872
|
+
onReload(d) {
|
|
873
|
+
// A rebuild without diagnostics supersedes any compile error on screen,
|
|
874
|
+
// whichever route it touched.
|
|
875
|
+
this.staleView = false;
|
|
876
|
+
if (this.issues.some((i) => i.kind === 'build' && i.severity === 'error')) {
|
|
877
|
+
this.issues = this.issues.filter((i) => !(i.kind === 'build' && i.severity === 'error'));
|
|
878
|
+
this.issuesChanged(false);
|
|
879
|
+
}
|
|
880
|
+
let cssOnly = false;
|
|
881
|
+
if (d) {
|
|
882
|
+
cssOnly = d.cssOnly === true;
|
|
883
|
+
const pages = d.pages;
|
|
884
|
+
if (pages &&
|
|
885
|
+
Array.isArray(pages) &&
|
|
886
|
+
!pages.some((p) => p === '/404' || p === '/500' || routeMatches(p, location.pathname, this.cfg.basePath))) {
|
|
887
|
+
return;
|
|
888
|
+
}
|
|
889
|
+
}
|
|
890
|
+
if (cssOnly) {
|
|
891
|
+
const b = this.lastBuild;
|
|
892
|
+
this.swapStylesheets().then(() => {
|
|
893
|
+
const files = b && b.kind === 'css-only' ? b.files.map(basename).slice(0, 2).join(', ') : '';
|
|
894
|
+
const meta = [files, b && b.kind === 'css-only' ? fmtMs(b.durationMs) : ''].filter(Boolean).join(' \u00B7 ');
|
|
895
|
+
this.toast('Styles updated without a reload', meta, 'check');
|
|
896
|
+
}, () => location.reload());
|
|
897
|
+
return;
|
|
898
|
+
}
|
|
899
|
+
location.reload();
|
|
900
|
+
}
|
|
901
|
+
onBuildError(d) {
|
|
902
|
+
const diags = d && Array.isArray(d.diagnostics) ? d.diagnostics : [];
|
|
903
|
+
const warns = d && Array.isArray(d.warnings) ? d.warnings : [];
|
|
904
|
+
const next = [
|
|
905
|
+
...issuesFromDiagnostics(diags, Date.now()),
|
|
906
|
+
...issuesFromDiagnostics(warns.map((w) => ({ ...w, severity: 'warning' })), Date.now(), diags.length),
|
|
907
|
+
];
|
|
908
|
+
this.replaceBuildIssues(next);
|
|
909
|
+
// Only errors open the overlay; warnings wait in the dock.
|
|
910
|
+
this.issuesChanged(next.some((i) => i.severity === 'error'));
|
|
911
|
+
}
|
|
912
|
+
/** The warnings of the latest build (build-end, build-warnings). */
|
|
913
|
+
onBuildWarnings(d) {
|
|
914
|
+
this.setWarnings(d && Array.isArray(d.warnings) ? d.warnings : []);
|
|
915
|
+
}
|
|
916
|
+
setWarnings(list) {
|
|
917
|
+
const next = issuesFromDiagnostics(list.map((w) => ({ ...w, severity: 'warning' })), Date.now());
|
|
918
|
+
const before = this.issues.filter(isBuildWarning);
|
|
919
|
+
if (before.length === next.length && before.every((b, k) => b.id === next[k].id && b.count === next[k].count))
|
|
920
|
+
return;
|
|
921
|
+
this.issues = [...this.issues.filter((i) => !isBuildWarning(i)), ...next];
|
|
922
|
+
for (const n of next) {
|
|
923
|
+
const old = before.find((i) => i.id === n.id);
|
|
924
|
+
if (old)
|
|
925
|
+
n.time = old.time;
|
|
926
|
+
}
|
|
927
|
+
this.fixes.clear();
|
|
928
|
+
this.issuesChanged(false);
|
|
929
|
+
}
|
|
930
|
+
/** Replaces every build issue (errors and warnings), keeping the times of those already on screen. */
|
|
931
|
+
replaceBuildIssues(next) {
|
|
932
|
+
for (const n of next) {
|
|
933
|
+
const old = this.issues.find((i) => i.id === n.id);
|
|
934
|
+
if (old)
|
|
935
|
+
n.time = old.time;
|
|
936
|
+
}
|
|
937
|
+
this.issues = [...next, ...this.issues.filter((i) => i.kind !== 'build')];
|
|
938
|
+
this.frames.clear();
|
|
939
|
+
this.fixes.clear();
|
|
940
|
+
}
|
|
941
|
+
/** "Show last good page": the overlay closes and the dock says what is on screen. */
|
|
942
|
+
showLastGood() {
|
|
943
|
+
this.staleView = true;
|
|
944
|
+
this.closeModal();
|
|
945
|
+
this.renderDock();
|
|
946
|
+
}
|
|
947
|
+
onClientError(d) {
|
|
948
|
+
if (!d || !d.clientError)
|
|
949
|
+
return;
|
|
950
|
+
const err = d.clientError;
|
|
951
|
+
if (err.kind === 'server') {
|
|
952
|
+
const issue = issueFromServer(err, Date.now());
|
|
953
|
+
const old = this.issues.find((i) => i.id === issue.id);
|
|
954
|
+
if (old)
|
|
955
|
+
issue.count = old.count + 1;
|
|
956
|
+
this.tails.delete(issue.id);
|
|
957
|
+
this.frames.delete((issue.file || '') + ':' + (issue.line || 0));
|
|
958
|
+
this.issues = [...this.issues.filter((i) => i.id !== issue.id), issue];
|
|
959
|
+
this.localLog('error', '[' + (err.source || 'server') + '] ' + err.message);
|
|
960
|
+
this.issuesChanged(true);
|
|
961
|
+
return;
|
|
962
|
+
}
|
|
963
|
+
// This tab reported the error itself and already shows it.
|
|
964
|
+
if (this.seen.has(err.message + '|' + (err.stack || '')))
|
|
965
|
+
return;
|
|
966
|
+
this.addRuntime('remote', err.message, err.stack);
|
|
967
|
+
}
|
|
968
|
+
/**
|
|
969
|
+
* Apply a CSS-only rebuild without a full reload: fetch the freshly built
|
|
970
|
+
* document, add its stylesheet links, and drop the ones it no longer has.
|
|
971
|
+
* Inline <style> changes cannot be diffed safely, so they fall back to a
|
|
972
|
+
* reload (the caller reloads when this rejects).
|
|
973
|
+
*/
|
|
974
|
+
async swapStylesheets() {
|
|
975
|
+
const res = await rawFetch(location.href, { cache: 'no-store', headers: { Accept: 'text/html' } });
|
|
976
|
+
if (!res.ok)
|
|
977
|
+
throw new Error('fetch failed');
|
|
978
|
+
const next = new DOMParser().parseFromString(await res.text(), 'text/html');
|
|
979
|
+
const inline = (d) => Array.from(d.querySelectorAll('style'))
|
|
980
|
+
.map((el) => el.textContent || '')
|
|
981
|
+
.join('\u0000');
|
|
982
|
+
if (inline(next) !== inline(document))
|
|
983
|
+
throw new Error('inline styles changed');
|
|
984
|
+
const abs = (href) => new URL(href, location.href).href;
|
|
985
|
+
const want = Array.from(next.querySelectorAll('link[rel~="stylesheet"]')).map((l) => abs(l.getAttribute('href') || ''));
|
|
986
|
+
const current = Array.from(document.querySelectorAll('link[rel~="stylesheet"]'));
|
|
987
|
+
const have = new Set(current.map((l) => abs(l.getAttribute('href') || '')));
|
|
988
|
+
const loads = [];
|
|
989
|
+
for (const href of want) {
|
|
990
|
+
if (have.has(href))
|
|
991
|
+
continue;
|
|
992
|
+
const link = document.createElement('link');
|
|
993
|
+
link.rel = 'stylesheet';
|
|
994
|
+
link.href = href;
|
|
995
|
+
loads.push(new Promise((resolve, reject) => {
|
|
996
|
+
link.onload = () => resolve();
|
|
997
|
+
link.onerror = () => reject(new Error('stylesheet failed'));
|
|
998
|
+
}));
|
|
999
|
+
document.head.appendChild(link);
|
|
1000
|
+
}
|
|
1001
|
+
await Promise.all(loads);
|
|
1002
|
+
const keep = new Set(want);
|
|
1003
|
+
for (const l of current) {
|
|
1004
|
+
if (!keep.has(abs(l.getAttribute('href') || '')))
|
|
1005
|
+
l.remove();
|
|
1006
|
+
}
|
|
1007
|
+
// A same-named stylesheet is cache-busted in place.
|
|
1008
|
+
for (const l of current) {
|
|
1009
|
+
const href = abs(l.getAttribute('href') || '');
|
|
1010
|
+
if (!keep.has(href) || !l.isConnected)
|
|
1011
|
+
continue;
|
|
1012
|
+
const u = new URL(href);
|
|
1013
|
+
u.searchParams.set('_krate', String(Date.now()));
|
|
1014
|
+
l.href = u.href;
|
|
1015
|
+
}
|
|
1016
|
+
}
|
|
1017
|
+
// runtime errors
|
|
1018
|
+
captureRuntimeErrors() {
|
|
1019
|
+
this.listen(window, 'error', (e) => this.onError(e));
|
|
1020
|
+
this.listen(window, 'unhandledrejection', (e) => this.onRejection(e));
|
|
1021
|
+
// A script or stylesheet that fails to load fires on its element and does
|
|
1022
|
+
// not bubble, so only the capture phase sees it.
|
|
1023
|
+
this.listen(window, 'error', (e) => this.onResourceError(e), true);
|
|
1024
|
+
this.captureConsole();
|
|
1025
|
+
// This bundle loads after the page script, so the page's first render ran
|
|
1026
|
+
// before these listeners existed. The head buffers what happened until now.
|
|
1027
|
+
const early = window.__KRATE_EARLY_ERRORS__;
|
|
1028
|
+
window.__KRATE_EARLY_ERRORS__ = undefined;
|
|
1029
|
+
for (const e of early ?? []) {
|
|
1030
|
+
if (e.type === 'console')
|
|
1031
|
+
this.onConsole(e.message, e.stack);
|
|
1032
|
+
else if (e.type === 'error' && e.target && e.target !== window)
|
|
1033
|
+
this.onResourceError(e);
|
|
1034
|
+
else if (e.type === 'error')
|
|
1035
|
+
this.onError(e);
|
|
1036
|
+
else
|
|
1037
|
+
this.onRejection(e);
|
|
1038
|
+
}
|
|
1039
|
+
}
|
|
1040
|
+
captureConsole() {
|
|
1041
|
+
const c = console;
|
|
1042
|
+
const orig = c.error;
|
|
1043
|
+
c.error = (...args) => {
|
|
1044
|
+
try {
|
|
1045
|
+
const first = args.find((a) => a instanceof Error);
|
|
1046
|
+
this.onConsole(args.map(formatArg).join(' '), first?.stack);
|
|
1047
|
+
}
|
|
1048
|
+
catch {
|
|
1049
|
+
/* never break the page's own logging */
|
|
1050
|
+
}
|
|
1051
|
+
return orig.apply(c, args);
|
|
1052
|
+
};
|
|
1053
|
+
const origWarn = c.warn;
|
|
1054
|
+
c.warn = (...args) => {
|
|
1055
|
+
try {
|
|
1056
|
+
this.localLog('warn', 'console.warn ' + args.map(formatArg).join(' '));
|
|
1057
|
+
}
|
|
1058
|
+
catch {
|
|
1059
|
+
/* never break the page's own logging */
|
|
1060
|
+
}
|
|
1061
|
+
return origWarn.apply(c, args);
|
|
1062
|
+
};
|
|
1063
|
+
this.unbind.push(() => {
|
|
1064
|
+
c.error = orig;
|
|
1065
|
+
c.warn = origWarn;
|
|
1066
|
+
});
|
|
1067
|
+
}
|
|
1068
|
+
localLog(lvl, text) {
|
|
1069
|
+
this.localLogs.push({ seq: ++this.localSeq, t: Date.now(), src: 'browser', lvl, text, local: true });
|
|
1070
|
+
if (this.localLogs.length > 300)
|
|
1071
|
+
this.localLogs.shift();
|
|
1072
|
+
if (this.panelOpen && this.tab === 'logs')
|
|
1073
|
+
refreshLogs(this);
|
|
1074
|
+
else if (this.panel && this.panelOpen)
|
|
1075
|
+
renderPanel(this, true);
|
|
1076
|
+
}
|
|
1077
|
+
onConsole(message, stack) {
|
|
1078
|
+
this.report({ message, stack, url: location.href, kind: 'console' });
|
|
1079
|
+
this.localLog('error', 'console.error ' + message);
|
|
1080
|
+
if (this.settings.consoleIssues)
|
|
1081
|
+
this.addRuntime('console', message, stack);
|
|
1082
|
+
}
|
|
1083
|
+
onResourceError(e) {
|
|
1084
|
+
const t = e.target;
|
|
1085
|
+
if (!t || t === window || !t.tagName)
|
|
1086
|
+
return;
|
|
1087
|
+
const src = t.src || t.href || '';
|
|
1088
|
+
if (!src)
|
|
1089
|
+
return;
|
|
1090
|
+
const message = 'failed to load <' + t.tagName.toLowerCase() + '> ' + src;
|
|
1091
|
+
this.report({ message, url: src, kind: 'resource' });
|
|
1092
|
+
this.localLog('error', message);
|
|
1093
|
+
this.addRuntime('resource', message);
|
|
1094
|
+
}
|
|
1095
|
+
onError(e) {
|
|
1096
|
+
const stack = e.error?.stack || '';
|
|
1097
|
+
const message = e.message || 'Unknown error';
|
|
1098
|
+
const hostStack = hostStackOf(e.error);
|
|
1099
|
+
this.report({
|
|
1100
|
+
message,
|
|
1101
|
+
stack: hostStack ? stack + '\nHost stack:\n' + hostStack : stack,
|
|
1102
|
+
url: e.filename,
|
|
1103
|
+
line: e.lineno,
|
|
1104
|
+
col: e.colno,
|
|
1105
|
+
kind: 'error',
|
|
1106
|
+
});
|
|
1107
|
+
this.localLog('error', message);
|
|
1108
|
+
this.addRuntime('error', message, stack, hostStack);
|
|
1109
|
+
}
|
|
1110
|
+
onRejection(e) {
|
|
1111
|
+
const reason = e.reason;
|
|
1112
|
+
const message = reason instanceof Error ? reason.message : String(reason);
|
|
1113
|
+
const stack = reason instanceof Error ? reason.stack : '';
|
|
1114
|
+
const hostStack = hostStackOf(reason);
|
|
1115
|
+
this.report({ message, stack: hostStack ? (stack || '') + '\nHost stack:\n' + hostStack : stack, url: location.href, kind: 'unhandledrejection' });
|
|
1116
|
+
this.localLog('error', 'Unhandled rejection: ' + message);
|
|
1117
|
+
this.addRuntime('rejection', message, stack, hostStack);
|
|
1118
|
+
}
|
|
1119
|
+
report(payload) {
|
|
1120
|
+
const key = payload.message + '|' + (payload.stack || '');
|
|
1121
|
+
if (this.seen.has(key))
|
|
1122
|
+
return;
|
|
1123
|
+
this.seen.add(key);
|
|
1124
|
+
const win = globalThis.__KRATE_WINDOW__;
|
|
1125
|
+
if (typeof win === 'string' && win)
|
|
1126
|
+
payload.window = win;
|
|
1127
|
+
if (!payload.stack || !payload.stack.includes('.js')) {
|
|
1128
|
+
this.send(payload);
|
|
1129
|
+
return;
|
|
1130
|
+
}
|
|
1131
|
+
// Map the stack to the sources before it reaches the terminal, but never
|
|
1132
|
+
// hold the report back for long: the source maps are best-effort.
|
|
1133
|
+
const raw = payload.stack;
|
|
1134
|
+
Promise.race([symbolicateStack(raw), new Promise((r) => setTimeout(() => r(raw), 1500))])
|
|
1135
|
+
.catch(() => raw)
|
|
1136
|
+
.then((stack) => {
|
|
1137
|
+
// The dev server echoes the report to every tab; this one knows it
|
|
1138
|
+
// by the mapped stack it sent.
|
|
1139
|
+
this.seen.add(payload.message + '|' + stack);
|
|
1140
|
+
this.send({ ...payload, stack });
|
|
1141
|
+
});
|
|
1142
|
+
}
|
|
1143
|
+
send(payload) {
|
|
1144
|
+
const body = JSON.stringify(payload);
|
|
1145
|
+
// sendBeacon throws on the custom scheme of a native webview (WebKitGTK),
|
|
1146
|
+
// so a failed or absent beacon falls back to fetch.
|
|
1147
|
+
try {
|
|
1148
|
+
if (!this.cfg.frames && navigator.sendBeacon) {
|
|
1149
|
+
if (navigator.sendBeacon(this.cfg.errors, new Blob([body], { type: 'application/json' })))
|
|
1150
|
+
return;
|
|
1151
|
+
}
|
|
1152
|
+
}
|
|
1153
|
+
catch {
|
|
1154
|
+
/* fall through to fetch */
|
|
1155
|
+
}
|
|
1156
|
+
try {
|
|
1157
|
+
rawFetch(this.cfg.errors, { method: 'POST', body, headers: { 'Content-Type': 'application/json' }, keepalive: true }).catch(() => { });
|
|
1158
|
+
}
|
|
1159
|
+
catch {
|
|
1160
|
+
/* reporting is best-effort */
|
|
1161
|
+
}
|
|
1162
|
+
}
|
|
1163
|
+
addRuntime(origin, message, stack, hostStack) {
|
|
1164
|
+
const issue = issueFromRuntime(origin, message, stack, hostStack, Date.now());
|
|
1165
|
+
const old = this.issues.find((i) => i.id === issue.id);
|
|
1166
|
+
if (old) {
|
|
1167
|
+
old.count++;
|
|
1168
|
+
old.time = issue.time;
|
|
1169
|
+
this.issuesChanged(false);
|
|
1170
|
+
return;
|
|
1171
|
+
}
|
|
1172
|
+
this.issues.push(issue);
|
|
1173
|
+
if (this.issues.length > 60) {
|
|
1174
|
+
const drop = this.issues.findIndex((i) => i.kind === 'runtime');
|
|
1175
|
+
if (drop !== -1)
|
|
1176
|
+
this.issues.splice(drop, 1);
|
|
1177
|
+
}
|
|
1178
|
+
const open = origin !== 'console' && this.settings.openOnRuntime && !this.ignored.has(issue.id);
|
|
1179
|
+
this.issuesChanged(open);
|
|
1180
|
+
// Render immediately with the raw stack, then upgrade in place if a source
|
|
1181
|
+
// map lets us point at the original location.
|
|
1182
|
+
if (stack) {
|
|
1183
|
+
void symbolicateStack(stack).then((mapped) => {
|
|
1184
|
+
if (!mapped || mapped === stack)
|
|
1185
|
+
return;
|
|
1186
|
+
const upgraded = issueFromRuntime(origin, message, mapped, hostStack, issue.time);
|
|
1187
|
+
issue.stack = mapped;
|
|
1188
|
+
issue.file = upgraded.file;
|
|
1189
|
+
issue.line = upgraded.line;
|
|
1190
|
+
issue.col = upgraded.col;
|
|
1191
|
+
issue.served = upgraded.served;
|
|
1192
|
+
if (upgraded.label !== 'Error')
|
|
1193
|
+
issue.label = upgraded.label;
|
|
1194
|
+
this.issuesChanged(false);
|
|
1195
|
+
});
|
|
1196
|
+
}
|
|
1197
|
+
}
|
|
1198
|
+
docsURL(code) {
|
|
1199
|
+
return (this.info?.docsURL || DEFAULT_DOCS_URL) + code.toLowerCase();
|
|
1200
|
+
}
|
|
1201
|
+
logFile() {
|
|
1202
|
+
return this.info?.logFile === undefined ? '.krate/dev.log' : this.info.logFile;
|
|
1203
|
+
}
|
|
1204
|
+
}
|