dsh-trajectory-traceview-plus 0.0.0-stage → 0.11.0

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/lib/index.js ADDED
@@ -0,0 +1,6 @@
1
+ //#region lib/types/index.js
2
+ /** Host loader entry for the browser-only trace-view plugin. */
3
+ /** Provides no host-side behavior: the "轨迹视图" tab lives entirely in lib/client.js. */
4
+ function apply() {}
5
+ //#endregion
6
+ export { apply };
package/package.json CHANGED
@@ -1,6 +1,69 @@
1
1
  {
2
2
  "name": "dsh-trajectory-traceview-plus",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.11.0",
4
+ "description": "轨迹视图增强版(Plus):在「轨迹」标签旁新增可回放的横向时间轴——minimap、窗口内检索(显式标注覆盖边界)、回放、轮次跳转、跟随模式、历史分页、步骤/子调用耗时与吞吐、时钟轴切换、稳定锚点复制与深链、孤立工具结果站点、提示词变更对比、原始请求分析与 Markdown 导出。基于 AFAP/dsh-trajectory-traceview (MIT) 改造。",
5
+ "type": "module",
6
+ "main": "lib/index.js",
7
+ "exports": {
8
+ ".": "./lib/index.js",
9
+ "./client": "./lib/client.js",
10
+ "./package.json": "./package.json"
11
+ },
12
+ "engines": {
13
+ "dsh": ">=0.2.2-rc.2 <0.2.3-0",
14
+ "node": ">=24.9.0"
15
+ },
16
+ "dsh": {
17
+ "bundle": {
18
+ "patch": "./cordis.patch.yml"
19
+ },
20
+ "client": {
21
+ "platform": "web",
22
+ "inject": [
23
+ "@deepseek-ai/dsh-client-runtime",
24
+ "@deepseek-ai/dsh-client-locale",
25
+ "@deepseek-ai/dsh-client-ui-conversation"
26
+ ]
27
+ }
28
+ },
29
+ "repository": {
30
+ "type": "git",
31
+ "url": "git+https://github.com/MisonL/dsh-trajectory-traceview-plus.git"
32
+ },
33
+ "files": [
34
+ "lib/index.js",
35
+ "lib/client.js",
36
+ "src/",
37
+ "cordis.patch.yml",
38
+ "screenshot/",
39
+ "docs/",
40
+ "scripts/",
41
+ "README.md",
42
+ "README.en.md",
43
+ "CHANGELOG.md",
44
+ "LICENSE"
45
+ ],
46
+ "keywords": [
47
+ "deepseek-harness",
48
+ "dsh",
49
+ "dsh-plugin",
50
+ "trajectory",
51
+ "timeline",
52
+ "replay",
53
+ "minimap",
54
+ "visualization",
55
+ "prompt",
56
+ "plugin"
57
+ ],
58
+ "license": "MIT",
59
+ "devDependencies": {
60
+ "react": "^19.0.0",
61
+ "react-dom": "^19.0.0"
62
+ },
63
+ "scripts": {
64
+ "build": "node scripts/build-client.mjs",
65
+ "check": "node scripts/build-client.mjs --check && node scripts/provenance.mjs --check && node scripts/version-check.mjs && node scripts/doc-ref-check.mjs && node scripts/doc-heading-check.mjs && node test/smoke.test.cjs && node scripts/readme-numbers.mjs",
66
+ "test": "node test/smoke.test.cjs",
67
+ "prepublishOnly": "npm run check"
68
+ }
69
+ }
Binary file
@@ -0,0 +1,141 @@
1
+ /**
2
+ * Benchmark the pure fold that the streaming path repeats: `deriveTraceTree(snapshot)`.
3
+ *
4
+ * Why this exists: DESIGN §13.07 says React-build mode decides whether a component
5
+ * optimisation wins, so the only honest way to size the streaming path is to measure the
6
+ * part that is NOT React at all. The view rebuilds the whole tree every STREAM_REBUILD_MS
7
+ * (120ms) while a reply is streaming (`src/40-view.js` streamTick), and each rebuild
8
+ * allocates a fresh object per station — which is also why memoisation never helps there.
9
+ *
10
+ * This measures that fold alone, in plain Node, with a snapshot the same shape the host
11
+ * hands the view. No React, no browser, no dev-vs-prod variance.
12
+ *
13
+ * node scripts/bench-fold.mjs [--stations 135] [--iters 40]
14
+ */
15
+ import fs from "node:fs";
16
+ import path from "node:path";
17
+ import vm from "node:vm";
18
+ import { fileURLToPath } from "node:url";
19
+
20
+ const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
21
+ const src = fs.readFileSync(path.join(root, "lib", "client.js"), "utf8");
22
+
23
+ const startMarker = "//#region pure helpers: snapshot -> timeline tree";
24
+ const start = src.indexOf(startMarker);
25
+ if (start === -1) throw new Error("helpers region not found");
26
+ const end = src.indexOf("//#endregion", start);
27
+ if (end === -1) throw new Error("helpers endregion not found");
28
+
29
+ const sandbox = {
30
+ console,
31
+ JSON,
32
+ Set,
33
+ Map,
34
+ WeakSet,
35
+ Math,
36
+ String,
37
+ Object,
38
+ Array,
39
+ Number,
40
+ Date,
41
+ RegExp,
42
+ };
43
+ vm.runInNewContext(
44
+ src.slice(start, end) + "\n;(globalThis.__test = { deriveTraceTree });",
45
+ sandbox,
46
+ { filename: "traceview-helpers.js", timeout: 10_000 },
47
+ );
48
+ const { deriveTraceTree } = sandbox.__test;
49
+
50
+ const args = process.argv.slice(2);
51
+ const opt = (name, fallback) => {
52
+ const at = args.indexOf(`--${name}`);
53
+ return at >= 0 && args[at + 1] !== void 0 ? Number(args[at + 1]) : fallback;
54
+ };
55
+ const wantStations = opt("stations", 135);
56
+ const iters = opt("iters", 40);
57
+
58
+ /** A snapshot shaped like the host's: alternating user turn + assistant step with a tool. */
59
+ function buildSnapshot(turns) {
60
+ const nodes = [];
61
+ const requests = [];
62
+ const base = Date.UTC(2026, 10, 20, 2, 0, 0);
63
+ let seq = 0;
64
+ for (let turnNo = 1; turnNo <= turns; turnNo += 1) {
65
+ nodes.push({ kind: "user", seq: ++seq, time: base + turnNo * 10_000, turn: turnNo, content: [{ type: "text", text: `第 ${turnNo} 轮的问题` }] });
66
+ nodes.push({
67
+ kind: "assistant",
68
+ seq: ++seq,
69
+ time: base + turnNo * 10_000 + 800,
70
+ turn: turnNo,
71
+ step: 1,
72
+ messageId: `m${turnNo}`,
73
+ blocks: [
74
+ { kind: "reasoning", text: `第 ${turnNo} 轮先想一想。` },
75
+ { kind: "text", text: `第 ${turnNo} 轮的回答正文。` },
76
+ { kind: "tool-call", callId: `c${turnNo}`, name: "pwsh", argsRaw: `{"cmd":"step-${turnNo}"}` },
77
+ ],
78
+ });
79
+ nodes.push({
80
+ kind: "tool-result",
81
+ seq: ++seq,
82
+ time: base + turnNo * 10_000 + 2600,
83
+ turn: turnNo,
84
+ step: 1,
85
+ callId: `c${turnNo}`,
86
+ callTime: base + turnNo * 10_000 + 900,
87
+ name: "pwsh",
88
+ content: [{ type: "text", text: `第 ${turnNo} 轮的工具输出` }],
89
+ isError: false,
90
+ });
91
+ requests.push({
92
+ purpose: "assistant",
93
+ turn: turnNo,
94
+ step: 1,
95
+ status: "ok",
96
+ startSeq: seq - 2,
97
+ startedAt: base + turnNo * 10_000,
98
+ completedAt: base + turnNo * 10_000 + 2900,
99
+ requestConfig: { model: "deepseek-chat", provider: "deepseek" },
100
+ usage: { input: 120 + turnNo, output: 40 + turnNo },
101
+ prompt: { system: "你是助手。", tools: [{ name: "pwsh", description: "run" }] },
102
+ });
103
+ }
104
+ return {
105
+ eventNodes: nodes,
106
+ requests,
107
+ callSchemas: {},
108
+ runningCalls: [],
109
+ partial: null,
110
+ };
111
+ }
112
+
113
+ const t = (key) => key;
114
+
115
+ // Grow the snapshot until it reaches roughly the station count we want (3 nodes per turn).
116
+ let turns = Math.max(4, Math.round(wantStations / 3));
117
+ let snap = buildSnapshot(turns);
118
+ let stations = deriveTraceTree(snap, t).stations.length;
119
+ while (stations < wantStations && turns < 400) {
120
+ turns += 4;
121
+ snap = buildSnapshot(turns);
122
+ stations = deriveTraceTree(snap, t).stations.length;
123
+ }
124
+
125
+ const samples = [];
126
+ for (let i = 0; i < iters; i += 1) {
127
+ const t0 = performance.now();
128
+ deriveTraceTree(snap, t);
129
+ samples.push(performance.now() - t0);
130
+ }
131
+ samples.sort((a, b) => a - b);
132
+ const at = (q) => samples[Math.min(samples.length - 1, Math.floor(samples.length * q))];
133
+ const ms = (x) => Math.round(x * 100) / 100;
134
+
135
+ const median = at(0.5);
136
+ const perSec = Math.round(1000 / median);
137
+ console.log(
138
+ `bench-fold: stations=${stations} nodes=${snap.eventNodes.length} iters=${iters} ` +
139
+ `median=${ms(median)}ms p90=${ms(at(0.9))}ms max=${ms(samples[samples.length - 1])}ms ` +
140
+ `(≈${perSec}/s; the stream rebuilds at ${120}ms intervals, so this fold uses ≈${Math.round((median / 120) * 100)}% of one core while streaming)`,
141
+ );
@@ -0,0 +1,75 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Drive the real component in a real browser and assert the things a server render
4
+ * cannot see: focus, scroll containment, keyboard auto-scroll, clipboard, intervals,
5
+ * responsive width.
6
+ *
7
+ * node scripts/browser-check.mjs # build + run, exit 1 on any failure
8
+ * node scripts/browser-check.mjs --shots # also save screenshots under test/browser/shots
9
+ *
10
+ * Requires `agent-browser` on PATH (Chrome via CDP). Deliberately NOT part of the smoke
11
+ * suite: the smoke suite must stay runnable without a browser.
12
+ */
13
+ import { spawnSync } from "node:child_process";
14
+ import fs from "node:fs";
15
+ import path from "node:path";
16
+
17
+ const root = path.resolve(import.meta.dirname, "..");
18
+ const shots = process.argv.includes("--shots");
19
+ const run = (cmd, args, input) => spawnSync(cmd, args, { cwd: root, input, encoding: "utf8", timeout: 180000 });
20
+
21
+ const build = run("node", ["scripts/browser-harness.mjs"]);
22
+ if (build.status !== 0) { console.log(build.stdout + build.stderr); process.exit(1); }
23
+
24
+ const url = "file://" + path.join(root, "test/browser/harness.html");
25
+ const open = run("agent-browser", ["open", url]);
26
+ if (open.status !== 0) { console.log("agent-browser open failed:\n" + open.stdout + open.stderr); process.exit(1); }
27
+ run("agent-browser", ["wait", "1200"]);
28
+
29
+ const probe = fs.readFileSync(path.join(root, "test/browser/probe.js"), "utf8");
30
+ const out = run("agent-browser", ["eval", "--stdin"], probe);
31
+ const raw = (out.stdout || "").trim();
32
+ let parsed = null;
33
+ try {
34
+ // agent-browser prints the evaluated value as a JSON-quoted string.
35
+ const outer = JSON.parse(raw);
36
+ parsed = JSON.parse(outer);
37
+ } catch (e) {
38
+ console.log("could not parse the probe result:\n" + raw.slice(0, 800) + "\n" + (out.stderr || ""));
39
+ run("agent-browser", ["close"]);
40
+ process.exit(1);
41
+ }
42
+
43
+ if (shots) {
44
+ fs.mkdirSync(path.join(root, "test/browser/shots"), { recursive: true });
45
+ run("agent-browser", ["screenshot", "--screenshot-dir", "./test/browser/shots"]);
46
+ run("agent-browser", ["set", "viewport", "375", "812"]);
47
+ run("agent-browser", ["wait", "400"]);
48
+ const narrow = run("agent-browser", ["eval", "JSON.stringify({overflow: document.documentElement.scrollWidth > window.innerWidth + 1, w: window.innerWidth})"]);
49
+ run("agent-browser", ["screenshot", "--screenshot-dir", "./test/browser/shots"]);
50
+ try {
51
+ const n = JSON.parse(JSON.parse((narrow.stdout || "").trim()));
52
+ if (n.overflow) parsed.failures.push("at 375px the page scrolls horizontally");
53
+ parsed.info.narrow = n;
54
+ } catch { parsed.failures.push("the 375px probe did not return"); }
55
+ run("agent-browser", ["set", "viewport", "1280", "720"]);
56
+ }
57
+ run("agent-browser", ["close"]);
58
+
59
+ console.log("browser-check: stations=" + parsed.info.stations +
60
+ " clickScroll=" + parsed.info.clickScrollLeft +
61
+ " search=" + parsed.info.search +
62
+ " copied=" + parsed.info.copied +
63
+ " replay=" + parsed.info.replay);
64
+ if (parsed.failures.length === 0) {
65
+ // This count is the number of observation groups in `info`, NOT the number of
66
+ // assertions — probe.js makes 47 of those. Reporting it as "checks" made the
67
+ // README claim "13 项行为" for a file with 47 assertions, which undersold the
68
+ // coverage by 3.5x. Say what it actually counts.
69
+ const groups = Object.keys(parsed.info).length;
70
+ console.log("browser-check: PASS (" + groups + " observation groups recorded, 0 failures)");
71
+ process.exit(0);
72
+ }
73
+ console.log("browser-check: FAIL");
74
+ for (const f of parsed.failures) console.log(" ✗ " + f);
75
+ process.exit(1);
@@ -0,0 +1,162 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Build a standalone HTML page that mounts the REAL TraceMapView in a real browser.
4
+ *
5
+ * Every other test in this repo renders through `react-dom/server`, which means scroll
6
+ * position, focus, clipboard, intervals and layout were never executed. This harness
7
+ * bundles the plugin's built `lib/client.js` plus a minimal CommonJS loader for React 19
8
+ * (which no longer ships UMD builds), so a real Chrome can drive the component.
9
+ *
10
+ * Deliberately NOT part of the smoke suite: it needs a browser.
11
+ * node scripts/browser-harness.mjs # writes test/browser/harness.html
12
+ */
13
+ import fs from "node:fs";
14
+ import path from "node:path";
15
+
16
+ const root = path.resolve(import.meta.dirname, "..");
17
+ const read = (rel) => fs.readFileSync(path.join(root, rel), "utf8");
18
+
19
+ /**
20
+ * CJS sources, keyed by the id our loader will resolve.
21
+ *
22
+ * `--prod` swaps in the PRODUCTION React builds. This matters more than it looks: the
23
+ * development build adds prop validation and dev-only bookkeeping to every render, so a
24
+ * component optimisation measured here can look like a big win and then lose in the real
25
+ * host (DESIGN §13.07 — that mistake cost two shipped-then-reverted commits). Behaviour
26
+ * gates should use the default dev build (it surfaces warnings); a PERFORMANCE number is
27
+ * only worth anything with `--prod`, which is what the host actually ships.
28
+ */
29
+ const PROD = process.argv.includes("--prod");
30
+ const MODULES = {
31
+ react: `node_modules/react/cjs/react.${PROD ? "production" : "development"}.js`,
32
+ "react/jsx-runtime": `node_modules/react/cjs/react-jsx-runtime.${PROD ? "production" : "development"}.js`,
33
+ "react-dom": `node_modules/react-dom/cjs/react-dom.${PROD ? "production" : "development"}.js`,
34
+ "react-dom/client": `node_modules/react-dom/cjs/react-dom-client.${PROD ? "production" : "development"}.js`,
35
+ scheduler: `node_modules/scheduler/cjs/scheduler.${PROD ? "production" : "development"}.js`
36
+ };
37
+
38
+ /**
39
+ * The host's REAL theme stylesheet, when the installed DSH can be found. It defines the
40
+ * `--dsw-static-*` palette plus `body` / `body[data-ds-dark-theme]` alias blocks, so both
41
+ * themes can be exercised faithfully. Without it the harness falls back to a handful of
42
+ * hand-written light values — good enough for layout, not for judging dark contrast.
43
+ */
44
+ function findHostThemeCss() {
45
+ const candidates = [process.env.DSH_THEME_CSS];
46
+
47
+ // Derive it instead of hardcoding. The old version embedded one machine's absolute
48
+ // path, which silently fell back to hand-written colours everywhere else — so dark
49
+ // contrast was only ever judged on one developer's laptop, and a reader of this repo
50
+ // had no way to know the stylesheet was missing.
51
+ //
52
+ // Resolve `dsh` by walking PATH rather than shelling out to `which`: no shell, no
53
+ // quoting surprises, and it works the same on every platform.
54
+ const suffixes = process.platform === "win32" ? [".cmd", ".exe", ""] : [""];
55
+ for (const dir of (process.env.PATH ?? "").split(path.delimiter)) {
56
+ if (dir === "") continue;
57
+ for (const suffix of suffixes) {
58
+ let real;
59
+ try { real = fs.realpathSync(path.join(dir, "dsh" + suffix)); } catch { continue; }
60
+ // <prefix>/lib/node_modules/@deepseek-ai/dsh/lib/bin.js -> <prefix>/lib/node_modules
61
+ const modules = path.dirname(path.dirname(path.dirname(path.dirname(real))));
62
+ candidates.push(path.join(modules, "@deepseek-ai/dsh", "node_modules", "@deepseek-ai/dsh-client-ui-theme", "src", "styles", "design-platform.css"));
63
+ }
64
+ }
65
+
66
+ for (const c of candidates.filter(Boolean)) {
67
+ try { if (fs.statSync(c).size > 0) return fs.readFileSync(c, "utf8"); } catch { /* next */ }
68
+ }
69
+ return null;
70
+ }
71
+ const hostThemeCss = findHostThemeCss();
72
+
73
+ const parts = [];
74
+ for (const [id, rel] of Object.entries(MODULES)) {
75
+ const src = read(rel);
76
+ parts.push(`/* ---- ${id} (${rel}) ---- */`);
77
+ parts.push(`__define(${JSON.stringify(id)}, function (module, exports, require) {\n${src}\n});`);
78
+ }
79
+
80
+ const client = read("lib/client.js");
81
+ const fixture = read("test/browser/fixture.js");
82
+
83
+ const html = `<!doctype html>
84
+ <html lang="zh-CN" data-ds-dark-theme="false">
85
+ <head>
86
+ <meta charset="utf-8">
87
+ <title>TraceMapView harness</title>
88
+ <style>
89
+ /* Stand-in for the host chrome, so the plugin's min-height / scroll containment is
90
+ measured against a realistic page rather than an empty one. */
91
+ html, body { margin: 0; padding: 0; }
92
+ /* The harness chrome follows the same theme attribute the host uses (on <body>), so a
93
+ dark run does not measure the plugin's near-white text against a white seat. */
94
+ body { font: 13px/1.5 -apple-system, "PingFang SC", system-ui, sans-serif; background: var(--dsw-alias-bg-base, #f5f6f8); color: var(--dsw-alias-label-primary, #1b1f24); }
95
+ #hostHead { height: 120px; background: #1b1f24; color: #fff; padding: 10px 16px; box-sizing: border-box; }
96
+ #hostSidebar { position: fixed; left: 0; top: 0; bottom: 0; width: 0; }
97
+ #hostMain { padding: 12px 16px; box-sizing: border-box; }
98
+ /* Host-shaped seat: the flex parent pins the box height, so a view taller than it MUST
99
+ scroll internally. Without this the harness can never reproduce that class of bug. */
100
+ #viewArea { display: flex; overflow-y: hidden; overflow-x: hidden; height: calc(100vh - 235px); }
101
+ #viewArea > #seat { display: contents; }
102
+ html[data-layout="free"] #viewArea { display: block; height: auto; overflow: visible; }
103
+ html[data-layout="free"] #viewArea > #seat { display: block; }
104
+ #seat > * { min-width: 0; }
105
+ #hostComposer { position: fixed; left: 0; right: 0; bottom: 0; height: 96px; background: var(--dsw-alias-bg-layer-2, #eef1f5); border-top: 1px solid var(--dsw-alias-border-l2, #cfd6df); padding: 10px 16px; box-sizing: border-box; }
106
+ /* Host theme tokens: the real stylesheet when the installed DSH is readable,
107
+ otherwise a minimal light set (layout only, not dark-contrast evidence). */
108
+ ${hostThemeCss === null ? `:root {
109
+ --dsw-alias-bg-layer-1: #ffffff; --dsw-alias-bg-layer-2: #f2f4f7;
110
+ --dsw-alias-border-l2: #d8dee6; --dsw-alias-interactive-bg-hover: #edeff3;
111
+ --dsw-alias-label-primary: #1b1f24; --dsw-alias-label-secondary: #5b6472;
112
+ --dsw-alias-markdown-code-block: #f6f8fa;
113
+ }` : hostThemeCss}
114
+ </style>
115
+ </head>
116
+ <body>
117
+ <div id="hostHead"><strong>host chrome</strong> (120px, stands in for the real header)</div>
118
+ <div id="hostMain">
119
+ <!-- The host seats the view in a FLEX column with overflow:hidden and a fixed height.
120
+ append ?layout=free to the URL for the old grow-with-content seating. -->
121
+ <div id="viewArea"><div id="seat"></div></div>
122
+ <div style="height: 2200px">(长页面,用于检验插件不会把整页无限撑高)</div>
123
+ </div>
124
+ <div id="hostComposer"><div class="composerSeat" style="height:100%;display:flex;align-items:center"><strong>host composer</strong> (96px, fixed; class="composerSeat" is what the plugin measures)</div></div>
125
+
126
+ <script>
127
+ /* ---- minimal CommonJS loader: React 19 has no UMD build ---- */
128
+ var process = { env: { NODE_ENV: "%%NODE_ENV%%" } };
129
+ (function () {
130
+ var defs = Object.create(null), cache = Object.create(null);
131
+ window.__define = function (id, fn) { defs[id] = fn; };
132
+ window.require = function (id) {
133
+ if (cache[id] !== void 0) return cache[id].exports;
134
+ if (defs[id] === void 0) throw new Error("harness: unknown module " + id);
135
+ var m = { exports: {} };
136
+ cache[id] = m;
137
+ defs[id](m, m.exports, window.require);
138
+ return m.exports;
139
+ };
140
+ })();
141
+ ${parts.join("\n")}
142
+ /* ---- plugin module loader stand-in ---- */
143
+ window.__ModuleLoader__ = { load: function (entry) { window.__plugin = entry.factory(window.require); } };
144
+ </script>
145
+ <script>
146
+ ${client}
147
+ </script>
148
+ <script>
149
+ ${fixture}
150
+ </script>
151
+ </body>
152
+ </html>
153
+ `;
154
+
155
+ const out = path.join(root, "test/browser/harness.html");
156
+ // The template is a plain string; substitute the build mode once here so `--prod` cannot
157
+ // silently leave `process.env.NODE_ENV` at "development" (which makes React print the
158
+ // dev-only warnings and pick extra code paths even with the production bundle loaded).
159
+ fs.writeFileSync(out, html.split("%%NODE_ENV%%").join(PROD ? "production" : "development"));
160
+ console.log("browser-harness: wrote " + path.relative(root, out) + " (" + (html.length / 1024).toFixed(0) + " KB, host theme " +
161
+ (hostThemeCss === null ? "FALLBACK light only" : "loaded from the installed DSH") +
162
+ ", React " + (PROD ? "production — usable for timing" : "development — behaviour only") + ")");
@@ -0,0 +1,96 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Assemble lib/client.js from src/*.js.
4
+ *
5
+ * The browser artifact must be ONE classic script that calls
6
+ * `window.__ModuleLoader__.load({ id, factory })` — the DSH client module system
7
+ * fetches that file directly and does not resolve nested imports for it. Shipping
8
+ * several files would therefore break the served plugin, so the maintainable
9
+ * sources live in src/ and this script concatenates them into the single file the
10
+ * host actually serves.
11
+ *
12
+ * The sections share one closure scope on purpose: they reference each other's
13
+ * bindings directly (e.g. the view uses helpers, the entry point uses both). That
14
+ * is what makes a naive split into real ES modules unsafe here.
15
+ *
16
+ * Usage:
17
+ * node scripts/build-client.mjs # write lib/client.js
18
+ * node scripts/build-client.mjs --check # fail if lib/client.js is stale
19
+ */
20
+ import fs from "node:fs";
21
+ import path from "node:path";
22
+ import { fileURLToPath } from "node:url";
23
+
24
+ const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
25
+ const OUT = path.join(ROOT, "lib", "client.js");
26
+
27
+ /** Order matters: every section may use bindings declared above it. */
28
+ const SECTIONS = [
29
+ "src/00-locale.js",
30
+ "src/10-styles.js",
31
+ "src/20-fields.js",
32
+ "src/30-helpers.js",
33
+ "src/40-view.js",
34
+ "src/50-entry.js",
35
+ ];
36
+
37
+ const HEADER = `window.__ModuleLoader__.load({
38
+ \tid: "dsh-trajectory-traceview-plus",
39
+ \tfactory: (require) => {
40
+ \t\tvar module = { exports: {} };
41
+ \t\tvar exports = module.exports;
42
+ \t\tlet react_jsx_runtime = require("react/jsx-runtime");
43
+ \t\tlet react = require("react");
44
+ \t\tconst jsx = react_jsx_runtime.jsx;
45
+ \t\tconst jsxs = react_jsx_runtime.jsxs;
46
+ \t\tconst fragment = react.Fragment;
47
+ `;
48
+
49
+ /**
50
+ * The component-level test hook sits between the view and the entry point. It must
51
+ * stay inside the closure (it needs `TraceMapView`) but outside every region so the
52
+ * smoke test can slice regions without dragging the global write along.
53
+ */
54
+ const TEST_HOOK = `
55
+ \t\t// Test hook: lets the smoke test render the real component. Guarded so it is
56
+ \t\t// inert unless a harness asks for it; it exposes nothing to the host runtime.
57
+ \t\tif (typeof globalThis === "object" && globalThis !== null && globalThis.__DTSV_TEST__ === true) {
58
+ \t\t\tglobalThis.__testComponent = { TraceMapView };
59
+ \t\t}
60
+ `;
61
+
62
+ const FOOTER = `\t\treturn module.exports;
63
+ \t}
64
+ });
65
+ `;
66
+
67
+ function build() {
68
+ const pieces = [HEADER];
69
+ for (let i = 0; i < SECTIONS.length; i += 1) {
70
+ const rel = SECTIONS[i];
71
+ const file = path.join(ROOT, rel);
72
+ if (!fs.existsSync(file)) throw new Error(`missing source section: ${rel}`);
73
+ let body = fs.readFileSync(file, "utf8");
74
+ // Normalise the trailing newline so the assembly is deterministic.
75
+ body = body.replace(/\n+$/, "");
76
+ pieces.push(`\n${body}\n`);
77
+ if (rel === "src/40-view.js") pieces.push(TEST_HOOK);
78
+ }
79
+ pieces.push(FOOTER);
80
+ return pieces.join("");
81
+ }
82
+
83
+ const built = build();
84
+
85
+ if (process.argv.includes("--check")) {
86
+ const current = fs.existsSync(OUT) ? fs.readFileSync(OUT, "utf8") : "";
87
+ if (current !== built) {
88
+ console.error("build-client: lib/client.js is stale — run `node scripts/build-client.mjs`");
89
+ process.exit(1);
90
+ }
91
+ console.log("build-client: lib/client.js matches src/");
92
+ } else {
93
+ fs.mkdirSync(path.dirname(OUT), { recursive: true });
94
+ fs.writeFileSync(OUT, built);
95
+ console.log(`build-client: wrote ${path.relative(ROOT, OUT)} (${built.split("\n").length} lines)`);
96
+ }
@@ -0,0 +1,66 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Fail when `docs/DESIGN.md` contains heading-like lines that Markdown will not
4
+ * render as headings.
5
+ *
6
+ * CommonMark requires a space (or end of line) after the `#` run. `###13.25` is
7
+ * therefore **paragraph text**, not a heading — GitHub renders it as a literal
8
+ * `###13.25` paragraph. That is invisible while editing and only shows up when
9
+ * someone reads the document on GitHub and finds no section structure at all.
10
+ *
11
+ * This had already happened here: 10 `###` and 39 `####` headings were written
12
+ * without the space, so most of §13.25–§13.34 rendered as a wall of text, and one
13
+ * prose line beginning `#7 ...` silently became an `<h1>`.
14
+ *
15
+ * Also flags a trailing `#`-closing mismatch, which is the other ATX foot-gun.
16
+ *
17
+ * And it checks code spans, for the same reason: a single-backtick span cannot
18
+ * contain a backtick, so `` `case\`text\`` never closes. The source reads fine and
19
+ * renders as a mess. A code span containing a backtick must use a longer fence.
20
+ *
21
+ * node scripts/doc-heading-check.mjs
22
+ */
23
+ import { readFileSync } from 'node:fs';
24
+ import { dirname, join } from 'node:path';
25
+ import { fileURLToPath } from 'node:url';
26
+
27
+ const ROOT = dirname(dirname(fileURLToPath(import.meta.url)));
28
+ const DOC = join(ROOT, 'docs', 'DESIGN.md');
29
+ const lines = readFileSync(DOC, 'utf8').split('\n');
30
+
31
+ const problems = [];
32
+ let headings = 0;
33
+
34
+ lines.forEach((line, i) => {
35
+ const at = 'line ' + (i + 1) + ': ';
36
+
37
+ // ATX heading that is missing the required space after the # run.
38
+ const noSpace = /^(#{1,6})([^ #\t].*)$/.exec(line);
39
+ if (noSpace !== null) {
40
+ problems.push(at + '`' + line.slice(0, 40) + '` — `#` run must be followed by a space, so this renders as plain text: insert `' + noSpace[1] + ' `');
41
+ return;
42
+ }
43
+
44
+ // A real heading, but with a closing `#` run that does not match the opening one.
45
+ const heading = /^(#{1,6})[ \t]+(.*?)[ \t]*#*[ \t]*$/.exec(line);
46
+ if (heading !== null) {
47
+ headings += 1;
48
+ // A same-line `#` immediately after a number is the usual "#7 ..." mistake.
49
+ if (/^#\d/.test(line)) problems.push(at + '`' + line.slice(0, 40) + '` — prose starting with `#<digit>` becomes a level-1 heading');
50
+ }
51
+
52
+ // Backslash-escaped backticks inside what looks like a code span. A span
53
+ // delimited by N backticks cannot contain a run of N+ backticks, so `a\`b\``
54
+ // never closes and the rest of the line renders as literal backslashes.
55
+ if (/\\`/.test(line)) {
56
+ problems.push(at + '`' + line.slice(0, 40) + '` — a code span delimited by one backtick cannot contain one; use double backticks (``…``) instead of `\\`');
57
+ }
58
+ });
59
+
60
+ console.log('doc-heading-check: ' + headings + ' rendered heading(s)');
61
+ if (problems.length > 0) {
62
+ for (const p of problems) console.error(' ✗ ' + p);
63
+ console.error('doc-heading-check: FAIL (' + problems.length + ' malformed construct(s))');
64
+ process.exit(1);
65
+ }
66
+ console.log('DOC HEADINGS OK');