waygraph 0.15.21 → 0.15.23

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.
@@ -0,0 +1,723 @@
1
+ // Moved verbatim from the former CHAIN_RUNNER_SCRIPT template string in cli.ts (see src/ARCHITECTURE.md).
2
+ // Runs inside the target project's own waygraph copy - keep it dependency-light and self-contained.
3
+ import { installOverlay } from "./overlay-install.js";
4
+ import { join } from "node:path";
5
+ import { applyHighlightStyleDefaults, formatHighlightCaption, hasAuthoredStubOnError, normalizeHighlightTone, runStubPhase } from "../highlights.js";
6
+ import { cycleHighlightRings } from "./rings.js";
7
+
8
+ export async function renderBeforeStep(page, info) {
9
+ await installOverlay(page, info.title);
10
+ // A ring left highlighting the PREVIOUS step's element (and its live
11
+ // resize/scroll tracker) shouldn't linger once a new step's own panel is
12
+ // up - only relevant when a Block's act() doesn't navigate away, since a
13
+ // real navigation already wipes document.documentElement's children.
14
+ await page
15
+ .evaluate(() => {
16
+ if (window.__wgRingTrack) {
17
+ window.removeEventListener("resize", window.__wgRingTrack);
18
+ window.removeEventListener("scroll", window.__wgRingTrack, true);
19
+ window.__wgRingTrack = null;
20
+ }
21
+ if (window.__wgHideRing) window.__wgHideRing();
22
+ if (window.__wgHideCursor) window.__wgHideCursor();
23
+ })
24
+ .catch(() => {});
25
+ // miniStepLabel / todosHtmlFromInfo are Node-only — browser evaluate has no closure.
26
+ const payload = { ...info, stepLabel: miniStepLabel(info) };
27
+ await page
28
+ .evaluate((info) => {
29
+ // Reused in place, not removed + recreated, every step - the old
30
+ // remove()-then-fade-back-in cycle was a real flash on every single
31
+ // transition (Dan: "the appear and disappear... hurts eyes and
32
+ // dizzy"). Updating one persistent element's content has nothing to
33
+ // flash - it only ever fades in ONCE, the first time this page
34
+ // genuinely has no panel yet (a real navigation wiped the whole
35
+ // document, or this is the very first step).
36
+ let panel = document.getElementById("wg-panel");
37
+ const isNewPanel = !panel;
38
+ if (!panel) {
39
+ panel = document.createElement("div");
40
+ panel.id = "wg-panel";
41
+ }
42
+ const pct = Math.round((info.index / info.total) * 100);
43
+ const esc = (s) => String(s).replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;");
44
+ // A real tab bar, not a single text line - every episode this chain
45
+ // touches, the current one reading as active (Dan: "if episode 1 is
46
+ // active, the episode 2 tab is inactive"). Absent entirely for an ad
47
+ // hoc block chain with no named Flows.
48
+ const episodesHtml = info.allEpisodes && info.allEpisodes.length > 0
49
+ ? "<div id=\"wg-episodes\">" +
50
+ info.allEpisodes
51
+ .map((e) => {
52
+ const cls = e.episodeNumber < info.episodeNumber ? "wg-ep-done"
53
+ : e.episodeNumber === info.episodeNumber ? "wg-ep-current"
54
+ : "wg-ep-upcoming";
55
+ // The gentle one-time glow only plays on the tab actually
56
+ // being entered right now, not on every render of it.
57
+ const enteredCls = info.justEnteredEpisode && e.episodeNumber === info.episodeNumber
58
+ ? " wg-ep-entered"
59
+ : "";
60
+ return "<span class=\"wg-ep-tab " + cls + enteredCls + "\">Episode " + e.episodeNumber + ": " +
61
+ esc(e.episodeTitle || "") + "</span>";
62
+ })
63
+ .join("") +
64
+ "</div>"
65
+ : "";
66
+ // Scoped to THIS episode's own blocks (info.allNames is already the
67
+ // episode-local subset the caller computed) - moduleIndex is this
68
+ // step's position WITHIN that subset, not the whole chain's index -
69
+ // "in episode 2 it shows 2nd to the last... it should start from the
70
+ // first block" (Dan).
71
+ const modulesClass = info.stepperMode === "full" ? "wg-modules-full" : "wg-modules-carousel";
72
+ const modulesHtml = info.allNames
73
+ .map((name, idx) => {
74
+ const cls = idx < info.moduleIndex ? "wg-mod-done" : idx === info.moduleIndex ? "wg-mod-current" : "wg-mod-upcoming";
75
+ const desc = info.allDescriptions && info.allDescriptions[idx];
76
+ const titleAttr = desc ? " title=\"" + esc(desc) + "\"" : "";
77
+ return "<span class=\"wg-mod " + cls + "\"" + titleAttr + ">" + name + "</span>";
78
+ })
79
+ .join("");
80
+ const narrationHtml = info.description
81
+ ? "<div class=\"wg-narration\">" + esc(info.description) + "</div>"
82
+ : "";
83
+ const paceHtml =
84
+ info.paceBadge || info.paceLabel
85
+ ? "<div class=\"wg-pace\" data-pace-kind=\"" +
86
+ esc(info.paceKind || "normal") +
87
+ "\"><span class=\"wg-pace-badge\">" +
88
+ esc(info.paceBadge || "1x") +
89
+ "</span><span>" +
90
+ esc(info.paceLabel || "") +
91
+ "</span></div>"
92
+ : "";
93
+ // Todos render into floating #wg-todo-dock via __wgSyncTodos - never
94
+ // inside .wg-body (would vanish under --mini / Hide collapse).
95
+ let html =
96
+ "<div id=\"wg-progress\"><div id=\"wg-progress-bar\" style=\"width:" + pct + "%\"></div></div>" +
97
+ episodesHtml +
98
+ paceHtml +
99
+ "<div id=\"wg-modules\" class=\"" + modulesClass + "\">" + modulesHtml + "</div>" +
100
+ "<h3>Step " + (info.index + 1) + " / " + info.total + " - " + info.blockName + "</h3>" +
101
+ narrationHtml;
102
+ if (info.keys.length === 0) {
103
+ html += "<div class=\"wg-key\">(no MemKeys required)</div>";
104
+ }
105
+ for (const k of info.keys) {
106
+ html +=
107
+ "<div class=\"wg-key\"><label>" + k.name + "</label>" +
108
+ "<textarea data-key=\"" + k.name + "\" rows=\"2\">" +
109
+ k.value.replace(/</g, "&lt;") + "</textarea>" +
110
+ "<div class=\"wg-key-pretty\" data-pretty-for=\"" + esc(k.name) + "\"></div>" +
111
+ "</div>";
112
+ }
113
+ let autoNow = false;
114
+ try {
115
+ autoNow = localStorage.getItem("wg-autoplay") === "1";
116
+ } catch {
117
+ /* private mode / blocked storage - defaults to manual */
118
+ }
119
+ html +=
120
+ "<div class=\"wg-autoplay-row\"><label><input type=\"checkbox\" id=\"wg-autoplay-cb\"" +
121
+ (autoNow ? " checked" : "") +
122
+ "> Auto-advance</label></div>" +
123
+ "<div id=\"wg-gate-manual\"" + (autoNow ? " style=\"display:none\"" : "") +
124
+ "><button id=\"wg-run\">Run this step \u25B6</button></div>" +
125
+ "<div id=\"wg-gate-auto\" class=\"wg-auto\"" + (autoNow ? "" : " style=\"display:none\"") +
126
+ ">Auto-advancing...</div>";
127
+ panel.innerHTML = html;
128
+ if (isNewPanel) {
129
+ document.documentElement.appendChild(panel);
130
+ requestAnimationFrame(() => panel.classList.add("wg-in"));
131
+ } else {
132
+ panel.classList.add("wg-in");
133
+ }
134
+ if (window.__wgWirePanelChrome) {
135
+ window.__wgWirePanelChrome(panel, "wg-panel-hidden", "waygraph demo", {
136
+ stepLabel: info.stepLabel || "",
137
+ forceCollapsed: info.forceCollapsed === true ? true : undefined,
138
+ });
139
+ }
140
+ if (window.__wgSyncTodos) {
141
+ const sync = info.todoSync || (info.todos && info.todos.length ? "set" : "keep");
142
+ // Prefer dock-only payload. Passing list:[] with a dock used to clear
143
+ // marks a frame later (empty-list clear path).
144
+ if (sync === "keep" && !info.todoDock) {
145
+ /* leave floating dock alone */
146
+ } else {
147
+ const payload = {
148
+ sync: sync,
149
+ dock: info.todoDock || null,
150
+ pos: info.todoPos || null,
151
+ todoId: info.todoId || (info.todoDock && info.todoDock.id) || null,
152
+ };
153
+ if (!info.todoDock && info.todos && info.todos.length) {
154
+ payload.list = info.todos;
155
+ }
156
+ window.__wgSyncTodos(payload);
157
+ }
158
+ }
159
+ if (window.__wgStampModal) {
160
+ window.__wgStampModal(panel, "panel", {
161
+ phase: "before",
162
+ step: info.index + 1,
163
+ total: info.total,
164
+ block: info.blockName || "",
165
+ ready: true,
166
+ });
167
+ }
168
+ // Live, human-readable preview of what a MemKey's raw JSON will
169
+ // actually write - object fields become "Field: value" lines
170
+ // (camelCase split the same way state tags already are); a
171
+ // non-object payload (a plain string/number/array) is shown as-is.
172
+ // Hidden entirely in JSON mode - shares the SAME global toggle the
173
+ // result display's own Pretty/JSON buttons already set, not a
174
+ // second, separate preference.
175
+ const prettyMemValue = (raw) => {
176
+ let parsed;
177
+ try {
178
+ parsed = JSON.parse(raw);
179
+ } catch {
180
+ return "<em>(invalid JSON)</em>";
181
+ }
182
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
183
+ return esc(JSON.stringify(parsed));
184
+ }
185
+ return Object.entries(parsed)
186
+ .map(([field, value]) => {
187
+ const label = field.replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/^./, (c) => c.toUpperCase());
188
+ return "<div class=\"wg-key-pretty-row\"><span class=\"wg-key-pretty-label\">" +
189
+ esc(label) + ":</span> " + esc(String(value)) + "</div>";
190
+ })
191
+ .join("");
192
+ };
193
+ const applyKeyPretty = () => {
194
+ const prettyOn = window.__wgPretty !== false;
195
+ panel.querySelectorAll("textarea[data-key]").forEach((ta) => {
196
+ const key = ta.getAttribute("data-key");
197
+ const previewEl = panel.querySelector(".wg-key-pretty[data-pretty-for=\"" + key + "\"]");
198
+ if (!previewEl) return;
199
+ previewEl.style.display = prettyOn ? "" : "none";
200
+ if (prettyOn) previewEl.innerHTML = prettyMemValue(ta.value);
201
+ });
202
+ };
203
+ applyKeyPretty();
204
+ panel.querySelectorAll("textarea[data-key]").forEach((ta) => {
205
+ ta.addEventListener("input", applyKeyPretty);
206
+ });
207
+ const runBtn = document.getElementById("wg-run");
208
+ if (runBtn) {
209
+ runBtn.addEventListener("click", () => {
210
+ const edits = {};
211
+ panel.querySelectorAll("textarea[data-key]").forEach((el) => {
212
+ edits[el.getAttribute("data-key")] = el.value;
213
+ });
214
+ window.__wgNext(edits);
215
+ });
216
+ }
217
+ // Live toggle - flips localStorage immediately so an in-flight gate()
218
+ // poll (on the Node side) picks it up within its next poll slice,
219
+ // without needing this whole panel to re-render. A manual click
220
+ // still always wins over an active autoplay wait, whichever the
221
+ // checkbox says - this is the "hybrid" control: autoplay is a
222
+ // default, not a lockout.
223
+ const cb = document.getElementById("wg-autoplay-cb");
224
+ if (cb) {
225
+ cb.addEventListener("change", () => {
226
+ try {
227
+ localStorage.setItem("wg-autoplay", cb.checked ? "1" : "0");
228
+ } catch {
229
+ /* private mode / blocked storage - toggle still works this page */
230
+ }
231
+ const manual = document.getElementById("wg-gate-manual");
232
+ const auto = document.getElementById("wg-gate-auto");
233
+ if (manual) manual.style.display = cb.checked ? "none" : "";
234
+ if (auto) auto.style.display = cb.checked ? "" : "none";
235
+ });
236
+ }
237
+ }, payload)
238
+ .catch(() => {});
239
+ if (process.env.WAYGRAPH_PROVE_SHOT || process.env.WAYGRAPH_PROVE_EXIT === "1") {
240
+ // Default: prove once on first painted panel. PROVE_EVERY=1 re-checks
241
+ // every step (noisy; useful when hunting a mid-chain blank).
242
+ const proveEvery = process.env.WAYGRAPH_PROVE_EVERY === "1";
243
+ const already = globalThis.__wgProveDone;
244
+ if (!already || proveEvery || process.env.WAYGRAPH_PROVE_EXIT === "1") {
245
+ await page.waitForTimeout(500).catch(() => {});
246
+ if (process.env.WAYGRAPH_PROVE_SHOT) {
247
+ await page.screenshot({ path: process.env.WAYGRAPH_PROVE_SHOT }).catch(() => {});
248
+ }
249
+ const ok = await page
250
+ .evaluate(() => {
251
+ const beacons =
252
+ typeof window.__wgOverlayBeacon === "function" ? window.__wgOverlayBeacon() : [];
253
+ const panel = beacons.find((b) => b.modal === "panel" && b.ready && b.visible);
254
+ const textOk = panel && panel.textLen >= 12;
255
+ const opacityOk = panel && Number(panel.opacity) > 0.5;
256
+ return {
257
+ ok: !!(panel && textOk && opacityOk),
258
+ beacons,
259
+ hasRun: !!document.getElementById("wg-run"),
260
+ readyAttr: document.getElementById("wg-panel")?.getAttribute("data-wg-ready") || null,
261
+ };
262
+ })
263
+ .catch((e) => ({ ok: false, reason: String(e && e.message ? e.message : e) }));
264
+ console.error("WAYGRAPH_PROVE " + JSON.stringify(ok));
265
+ globalThis.__wgProveDone = true;
266
+ if (process.env.WAYGRAPH_PROVE_EXIT === "1") {
267
+ process.exit(ok && ok.ok ? 0 : 2);
268
+ }
269
+ }
270
+ }
271
+ }
272
+
273
+
274
+ function miniStepLabel(info) {
275
+ const ep =
276
+ info.episodeNumber !== undefined && info.episodeNumber !== null
277
+ ? "Ep " + info.episodeNumber + " \u00b7 "
278
+ : "";
279
+ return (
280
+ ep +
281
+ (info.index + 1) +
282
+ " / " +
283
+ info.total +
284
+ (info.blockName ? " \u00b7 " + info.blockName : "") +
285
+ (info.paceBadge ? " \u00b7 " + info.paceBadge : "")
286
+ );
287
+ }
288
+
289
+
290
+ /**
291
+ * stubOnError rings + amber "expected outcome" / red error panel, then wait
292
+ * for Stop/Retry. Used when a step throws OR when withExpectedFailure's last
293
+ * block succeeds on the intentional fail branch (e.g. LoginPage + error banner).
294
+ */
295
+ export async function presentFailPanel(page, opts) {
296
+ const {
297
+ block,
298
+ fixtures,
299
+ error,
300
+ index,
301
+ total,
302
+ blockName,
303
+ message,
304
+ allNames,
305
+ allDescriptions,
306
+ moduleIndex,
307
+ allEpisodes,
308
+ title,
309
+ episodeNumber,
310
+ episodeTitle,
311
+ expectedFailureReason,
312
+ stepperMode,
313
+ gatesFast,
314
+ demoPace,
315
+ gate,
316
+ mem,
317
+ } = opts;
318
+ if (hasAuthoredStubOnError(block, fixtures)) {
319
+ await page
320
+ .evaluate(() => {
321
+ if (window.__wgRingTrack) {
322
+ window.removeEventListener("resize", window.__wgRingTrack);
323
+ window.removeEventListener("scroll", window.__wgRingTrack, true);
324
+ window.__wgRingTrack = null;
325
+ }
326
+ })
327
+ .catch(() => {});
328
+ const errPhase = await runStubPhase(block, "stubOnError", {
329
+ fixtures,
330
+ error,
331
+ out: opts.out,
332
+ mem,
333
+ });
334
+ const errHighlights = errPhase.highlights.map((h) => {
335
+ const styled = applyHighlightStyleDefaults(h, opts.highlightStyle);
336
+ return {
337
+ selector: styled.selector,
338
+ label: formatHighlightCaption(styled),
339
+ duration: styled.duration,
340
+ fastMode: styled.fastMode,
341
+ tone: styled.tone,
342
+ size: styled.size,
343
+ weight: styled.weight,
344
+ zoom: styled.zoom,
345
+ zoomOut: styled.zoomOut,
346
+ focus: !!styled.focus,
347
+ tone: styled.tone,
348
+ color: styled.color,
349
+ detail: styled.detail,
350
+ };
351
+ });
352
+ await cycleHighlightRings(page, errHighlights, !!gatesFast, {
353
+ defaultHoldMs: 2000,
354
+ pace: demoPace,
355
+ todos: errPhase.todos,
356
+ });
357
+ }
358
+ await renderStepError(page, {
359
+ index,
360
+ total,
361
+ blockName,
362
+ message,
363
+ allNames,
364
+ allDescriptions,
365
+ moduleIndex,
366
+ allEpisodes,
367
+ title,
368
+ episodeNumber,
369
+ episodeTitle,
370
+ expectedFailureReason,
371
+ stepperMode,
372
+ });
373
+ return gate();
374
+ }
375
+
376
+
377
+ export async function renderAfterStep(page, info) {
378
+ await installOverlay(page, info.title);
379
+ // Clear any tracker from a previous highlight before cycling through this
380
+ // step's own.
381
+ await page
382
+ .evaluate(() => {
383
+ if (window.__wgRingTrack) {
384
+ window.removeEventListener("resize", window.__wgRingTrack);
385
+ window.removeEventListener("scroll", window.__wgRingTrack, true);
386
+ window.__wgRingTrack = null;
387
+ }
388
+ })
389
+ .catch(() => {});
390
+ const highlights = info.highlights || [];
391
+ const gatesFast = !!info.gatesFast;
392
+ // Cycle through EVERY declared/recovered highlight in order, each shown
393
+ // long enough to actually register - "it highlights something [...] then
394
+ // it highlights something [else] and next," not just the first one.
395
+ // duration / fastMode on stubAfter (or flow fixtures) override the legacy
396
+ // 900ms / 200ms holds when set.
397
+ await cycleHighlightRings(page, highlights, gatesFast, {
398
+ pace: info.pace,
399
+ stepLabel: miniStepLabel(info),
400
+ todoDock: info.todoDock,
401
+ todos: info.todos,
402
+ todoSync: info.todoSync,
403
+ todoDockRef: info.todoDockRef,
404
+ // stubAfter already authored progress - do not re-index by ring 0..n
405
+ advanceTodos: false,
406
+ });
407
+ // After-ring advances may have moved the dock - surface latest for caller.
408
+ if (info.todoDockRef && info.todoDockRef.current) {
409
+ info.todoDock = info.todoDockRef.current;
410
+ }
411
+ const afterPayload = { ...info, stepLabel: miniStepLabel(info) };
412
+ await page
413
+ .evaluate((info) => {
414
+ // Reused in place - see renderBeforeStep's own comment on this.
415
+ let panel = document.getElementById("wg-panel");
416
+ const isNewPanel = !panel;
417
+ if (!panel) {
418
+ panel = document.createElement("div");
419
+ panel.id = "wg-panel";
420
+ }
421
+ const pct = Math.round(((info.index + 1) / info.total) * 100);
422
+ const heading = info.isLast
423
+ ? "End of chain - " + info.total + " / " + info.total + " blocks covered - " + info.blockName + " done"
424
+ : "Step " + (info.index + 1) + " / " + info.total + " - " + info.blockName + " done";
425
+ const buttonLabel = info.isLast ? "Finish" : "Next \u25B6";
426
+ const escA = (s) => String(s).replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;");
427
+ const modulesClass = info.stepperMode === "full" ? "wg-modules-full" : "wg-modules-carousel";
428
+ const modulesHtml = info.allNames
429
+ .map((name, idx) => {
430
+ const cls = idx <= info.moduleIndex ? "wg-mod-done" : "wg-mod-upcoming";
431
+ const desc = info.allDescriptions && info.allDescriptions[idx];
432
+ const titleAttr = desc ? " title=\"" + escA(desc) + "\"" : "";
433
+ return "<span class=\"wg-mod " + cls + "\"" + titleAttr + ">" + name + "</span>";
434
+ })
435
+ .join("");
436
+ // QA-friendly by default ("LoginSuccess" -> "Login Success") - raw
437
+ // JSON is one click away for whoever actually wants __state.
438
+ const stateTag = info.result && info.result.__state ? info.result.__state : "";
439
+ const prettyText = stateTag
440
+ .replace(/([a-z0-9])([A-Z])/g, "$1 $2")
441
+ .replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2") || info.resultTag;
442
+ const pretty = window.__wgPretty !== false;
443
+ const resultHtml =
444
+ "<div class=\"wg-toggle\">" +
445
+ "<button class=\"wg-toggle-btn" + (pretty ? " wg-active" : "") + "\" data-mode=\"pretty\">Pretty</button>" +
446
+ "<button class=\"wg-toggle-btn" + (pretty ? "" : " wg-active") + "\" data-mode=\"json\">JSON</button>" +
447
+ "</div>" +
448
+ "<div class=\"wg-result wg-result-pretty\" style=\"display:" + (pretty ? "block" : "none") + "\">" +
449
+ prettyText + "</div>" +
450
+ "<div class=\"wg-result wg-result-json\" style=\"display:" + (pretty ? "none" : "block") + "\">" +
451
+ info.resultTag + "</div>";
452
+ let autoNow = false;
453
+ try {
454
+ autoNow = localStorage.getItem("wg-autoplay") === "1";
455
+ } catch {
456
+ /* private mode / blocked storage - defaults to manual */
457
+ }
458
+ const gateHtml =
459
+ "<div class=\"wg-autoplay-row\"><label><input type=\"checkbox\" id=\"wg-autoplay-cb\"" +
460
+ (autoNow ? " checked" : "") +
461
+ "> Auto-advance</label></div>" +
462
+ "<div id=\"wg-gate-manual\"" + (autoNow ? " style=\"display:none\"" : "") +
463
+ "><button id=\"wg-run\">" + buttonLabel + "</button></div>" +
464
+ "<div id=\"wg-gate-auto\" class=\"wg-auto\"" + (autoNow ? "" : " style=\"display:none\"") +
465
+ ">Auto-advancing...</div>";
466
+ const episodesHtml = info.allEpisodes && info.allEpisodes.length > 0
467
+ ? "<div id=\"wg-episodes\">" +
468
+ info.allEpisodes
469
+ .map((e) => {
470
+ const cls = e.episodeNumber < info.episodeNumber ? "wg-ep-done"
471
+ : e.episodeNumber === info.episodeNumber ? "wg-ep-current"
472
+ : "wg-ep-upcoming";
473
+ return "<span class=\"wg-ep-tab " + cls + "\">Episode " + e.episodeNumber + ": " +
474
+ escA(e.episodeTitle || "") + "</span>";
475
+ })
476
+ .join("") +
477
+ "</div>"
478
+ : "";
479
+ const paceHtml =
480
+ info.paceBadge || info.paceLabel
481
+ ? "<div class=\"wg-pace\" data-pace-kind=\"" +
482
+ escA(info.paceKind || "normal") +
483
+ "\"><span class=\"wg-pace-badge\">" +
484
+ escA(info.paceBadge || "1x") +
485
+ "</span><span>" +
486
+ escA(info.paceLabel || "") +
487
+ "</span></div>"
488
+ : "";
489
+ const todosHtml = ""; // todos float in #wg-todo-dock via __wgSyncTodos
490
+ panel.innerHTML =
491
+ "<div id=\"wg-progress\"><div id=\"wg-progress-bar\" style=\"width:" + pct + "%\"></div></div>" +
492
+ episodesHtml +
493
+ paceHtml +
494
+ "<div id=\"wg-modules\" class=\"" + modulesClass + "\">" + modulesHtml + "</div>" +
495
+ "<h3>" + heading + "</h3>" +
496
+ todosHtml +
497
+ resultHtml +
498
+ gateHtml;
499
+ if (isNewPanel) {
500
+ document.documentElement.appendChild(panel);
501
+ requestAnimationFrame(() => panel.classList.add("wg-in"));
502
+ } else {
503
+ panel.classList.add("wg-in");
504
+ }
505
+ if (window.__wgWirePanelChrome) {
506
+ window.__wgWirePanelChrome(panel, "wg-panel-hidden", "waygraph demo", {
507
+ stepLabel: info.stepLabel || "",
508
+ forceCollapsed: info.forceCollapsed === true ? true : undefined,
509
+ });
510
+ }
511
+ if (window.__wgSyncTodos) {
512
+ const sync = info.todoSync || (info.todos && info.todos.length ? "set" : "keep");
513
+ // Prefer dock-only payload. Passing list:[] with a dock used to clear
514
+ // marks a frame later (empty-list clear path).
515
+ if (sync === "keep" && !info.todoDock) {
516
+ /* leave floating dock alone */
517
+ } else {
518
+ const payload = {
519
+ sync: sync,
520
+ dock: info.todoDock || null,
521
+ pos: info.todoPos || null,
522
+ todoId: info.todoId || (info.todoDock && info.todoDock.id) || null,
523
+ };
524
+ if (!info.todoDock && info.todos && info.todos.length) {
525
+ payload.list = info.todos;
526
+ }
527
+ window.__wgSyncTodos(payload);
528
+ }
529
+ }
530
+ if (window.__wgStampModal) {
531
+ window.__wgStampModal(panel, "panel", {
532
+ phase: "after",
533
+ step: info.index + 1,
534
+ total: info.total,
535
+ block: info.blockName || "",
536
+ ready: true,
537
+ });
538
+ }
539
+ panel.querySelectorAll(".wg-toggle-btn").forEach((btn) => {
540
+ btn.addEventListener("click", () => {
541
+ const wantPretty = btn.getAttribute("data-mode") === "pretty";
542
+ window.__wgPretty = wantPretty;
543
+ panel.querySelectorAll(".wg-toggle-btn").forEach((b) => b.classList.remove("wg-active"));
544
+ btn.classList.add("wg-active");
545
+ panel.querySelector(".wg-result-pretty").style.display = wantPretty ? "block" : "none";
546
+ panel.querySelector(".wg-result-json").style.display = wantPretty ? "none" : "block";
547
+ });
548
+ });
549
+ const runBtn = document.getElementById("wg-run");
550
+ if (runBtn) runBtn.addEventListener("click", () => window.__wgNext({}));
551
+ const cb = document.getElementById("wg-autoplay-cb");
552
+ if (cb) {
553
+ cb.addEventListener("change", () => {
554
+ try {
555
+ localStorage.setItem("wg-autoplay", cb.checked ? "1" : "0");
556
+ } catch {
557
+ /* private mode / blocked storage - toggle still works this page */
558
+ }
559
+ const manual = document.getElementById("wg-gate-manual");
560
+ const auto = document.getElementById("wg-gate-auto");
561
+ if (manual) manual.style.display = cb.checked ? "none" : "";
562
+ if (auto) auto.style.display = cb.checked ? "" : "none";
563
+ });
564
+ }
565
+ }, afterPayload)
566
+ .catch(() => {});
567
+ }
568
+
569
+
570
+ /**
571
+ * A Block threw - act()/observe() rejected, or Flow.run's own verify Trait
572
+ * check failed. Shown instead of letting it crash the whole Node process
573
+ * silently from a human's point of view (the browser closes right after
574
+ * regardless - main()'s own try/finally - but not before this is visible).
575
+ */
576
+ async function renderStepError(page, info) {
577
+ await installOverlay(page, info.title);
578
+ const errorPayload = { ...info, stepLabel: miniStepLabel(info) };
579
+ await page
580
+ .evaluate((info) => {
581
+ // Reused in place - see renderBeforeStep's own comment on this.
582
+ let panel = document.getElementById("wg-panel");
583
+ const isNewPanel = !panel;
584
+ if (!panel) {
585
+ panel = document.createElement("div");
586
+ panel.id = "wg-panel";
587
+ }
588
+ const isExpected = !!info.expectedFailureReason;
589
+ const errClass = isExpected ? "wg-expected" : "wg-error";
590
+ panel.classList.remove("wg-error", "wg-expected");
591
+ panel.classList.add(errClass);
592
+ if (!isNewPanel) panel.classList.add("wg-in");
593
+ const esc = (s) => String(s).replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;");
594
+ const episodesHtml = info.allEpisodes && info.allEpisodes.length > 0
595
+ ? "<div id=\"wg-episodes\">" +
596
+ info.allEpisodes
597
+ .map((e) => {
598
+ const cls = e.episodeNumber < info.episodeNumber ? "wg-ep-done"
599
+ : e.episodeNumber === info.episodeNumber ? "wg-ep-current"
600
+ : "wg-ep-upcoming";
601
+ return "<span class=\"wg-ep-tab " + cls + "\">Episode " + e.episodeNumber + ": " +
602
+ esc(e.episodeTitle || "") + "</span>";
603
+ })
604
+ .join("") +
605
+ "</div>"
606
+ : "";
607
+ const modulesClass = info.stepperMode === "full" ? "wg-modules-full" : "wg-modules-carousel";
608
+ const modulesHtml = info.allNames
609
+ .map((name, idx) => {
610
+ const cls = idx === info.moduleIndex ? "wg-mod-current" : idx < info.moduleIndex ? "wg-mod-done" : "wg-mod-upcoming";
611
+ const desc = info.allDescriptions && info.allDescriptions[idx];
612
+ const titleAttr = desc ? " title=\"" + esc(desc) + "\"" : "";
613
+ return "<span class=\"wg-mod " + cls + "\"" + titleAttr + ">" + name + "</span>";
614
+ })
615
+ .join("");
616
+ const retryLabel = info.episodeNumber !== undefined ? "Retry Episode " + info.episodeNumber : "Retry";
617
+ const headingText = isExpected
618
+ ? "Expected outcome - Step " + (info.index + 1) + " / " + info.total + " - " + info.blockName + " failed as intended"
619
+ : "Step " + (info.index + 1) + " / " + info.total + " - " + info.blockName + " threw";
620
+ const reasonHtml = isExpected
621
+ ? "<div class=\"wg-expected-reason\">" + esc(info.expectedFailureReason) + "</div>"
622
+ : "";
623
+ panel.innerHTML =
624
+ episodesHtml +
625
+ "<div id=\"wg-modules\" class=\"" + modulesClass + "\">" + modulesHtml + "</div>" +
626
+ "<h3 class=\"" + (isExpected ? "wg-expected-heading" : "wg-error-heading") + "\">" + headingText + "</h3>" +
627
+ reasonHtml +
628
+ "<div class=\"wg-error-msg\">" + esc(info.message) + "</div>" +
629
+ "<div class=\"wg-error-actions\">" +
630
+ "<button id=\"wg-error-retry\" class=\"wg-error-retry\">" + esc(retryLabel) + "</button>" +
631
+ "<button id=\"wg-run\" class=\"wg-error-stop\">Stop</button>" +
632
+ "</div>";
633
+ if (isNewPanel) {
634
+ document.documentElement.appendChild(panel);
635
+ requestAnimationFrame(() => panel.classList.add("wg-in"));
636
+ } else {
637
+ panel.classList.add("wg-in");
638
+ }
639
+ if (window.__wgWirePanelChrome) {
640
+ window.__wgWirePanelChrome(panel, "wg-panel-hidden", "waygraph demo", {
641
+ stepLabel: info.stepLabel || "",
642
+ forceCollapsed: info.forceCollapsed === true ? true : undefined,
643
+ });
644
+ }
645
+ if (window.__wgStampModal) {
646
+ window.__wgStampModal(panel, "panel", {
647
+ phase: "error",
648
+ step: info.index + 1,
649
+ total: info.total,
650
+ block: info.blockName || "",
651
+ ready: true,
652
+ });
653
+ }
654
+ const runBtn = document.getElementById("wg-run");
655
+ if (runBtn) runBtn.addEventListener("click", () => window.__wgNext({}));
656
+ const retryBtn = document.getElementById("wg-error-retry");
657
+ if (retryBtn) retryBtn.addEventListener("click", () => window.__wgNext({ __wgRetry: "1" }));
658
+ }, errorPayload)
659
+ .catch(() => {});
660
+ }
661
+
662
+
663
+ /**
664
+ * A Block's own explicit instruction.highlights, if it declared any -
665
+ * arbitrary, author-controlled highlight points, independent of verify
666
+ * ("remember this ID" isn't a pass/fail check). Takes priority over
667
+ * anything recovered from verify traits below.
668
+ */
669
+ function resolveDeclaredHighlights(block, resultTag) {
670
+ let highlights = block.instruction && block.instruction.highlights;
671
+ if (typeof highlights === "function") {
672
+ try {
673
+ highlights = highlights({ __state: resultTag });
674
+ } catch {
675
+ highlights = [];
676
+ }
677
+ }
678
+ if (!Array.isArray(highlights)) return [];
679
+ return highlights.filter((h) => h && typeof h.selector === "string" && typeof h.label === "string").map((h) => ({
680
+ ...h,
681
+ tone: normalizeHighlightTone(h.tone),
682
+ }));
683
+ }
684
+
685
+
686
+ /**
687
+ * Recovers a DOM selector from a built-in Trait's own .name string -
688
+ * visible(sel) / text-equals(sel, "...") - since Trait.check itself is
689
+ * an opaque closure with no selector field of its own. Best-effort only: a
690
+ * hand-written bespoke Trait, or url-matches(...) (no DOM target), yields
691
+ * nothing to highlight, which is fine - the panel still shows the result.
692
+ * Only used as a FALLBACK when the Block declared no explicit
693
+ * instruction.highlights of its own - see resolveDeclaredHighlights.
694
+ */
695
+ export function extractVerifyHighlights(block, resultTag) {
696
+ const declared = resolveDeclaredHighlights(block, resultTag);
697
+ if (declared.length > 0) return declared;
698
+ let verify = block.instruction && block.instruction.verify;
699
+ if (typeof verify === "function") {
700
+ try {
701
+ verify = verify({ __state: resultTag });
702
+ } catch {
703
+ verify = [];
704
+ }
705
+ }
706
+ if (!Array.isArray(verify)) return [];
707
+ const highlights = [];
708
+ for (const t of verify) {
709
+ const name = t && t.name;
710
+ if (typeof name !== "string") continue;
711
+ let m = /^visible\((.+)\)$/.exec(name);
712
+ if (m) {
713
+ highlights.push({ selector: m[1], label: name, tone: "auto" });
714
+ continue;
715
+ }
716
+ m = /^text-equals\((.+?),\s*"/.exec(name);
717
+ if (m) {
718
+ highlights.push({ selector: m[1], label: name, tone: "auto" });
719
+ continue;
720
+ }
721
+ }
722
+ return highlights;
723
+ }