@dooc-dev/dooc 0.0.27 → 0.0.29

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.
Files changed (88) hide show
  1. package/dist/client.global.js +1 -1
  2. package/dist/edit.global.js +220 -221
  3. package/dist/engine/compiler/check.js +5 -3
  4. package/dist/engine/compiler/compile.d.ts +5 -0
  5. package/dist/engine/compiler/compile.js +44 -23
  6. package/dist/engine/compiler/dialect.js +1 -1
  7. package/dist/engine/compiler/document-diff.d.ts +53 -0
  8. package/dist/engine/compiler/document-diff.js +92 -0
  9. package/dist/engine/compiler/export.js +11 -3
  10. package/dist/engine/compiler/files.d.ts +1 -0
  11. package/dist/engine/compiler/files.js +75 -14
  12. package/dist/engine/compiler/format-collections.js +8 -2
  13. package/dist/engine/compiler/from-mdast.js +12 -1
  14. package/dist/engine/compiler/icons.d.ts +7 -7
  15. package/dist/engine/compiler/icons.js +35 -37
  16. package/dist/engine/compiler/manifest.d.ts +1 -0
  17. package/dist/engine/compiler/manifest.js +25 -0
  18. package/dist/engine/compiler/ops.d.ts +2 -2
  19. package/dist/engine/compiler/ops.js +55 -112
  20. package/dist/engine/compiler/resource-index.js +4 -4
  21. package/dist/engine/compiler/root-page.d.ts +13 -0
  22. package/dist/engine/compiler/root-page.js +96 -0
  23. package/dist/engine/compiler/sidebar-removal.d.ts +63 -0
  24. package/dist/engine/compiler/sidebar-removal.js +317 -0
  25. package/dist/engine/compiler/subformats.d.ts +3 -0
  26. package/dist/engine/compiler/subformats.js +126 -32
  27. package/dist/engine/core/blocks.d.ts +5 -0
  28. package/dist/engine/core/content-metadata.d.ts +9 -4
  29. package/dist/engine/core/content-metadata.js +100 -16
  30. package/dist/engine/core/file-embed.d.ts +2 -1
  31. package/dist/engine/core/file-embed.js +4 -0
  32. package/dist/engine/core/files.d.ts +1 -0
  33. package/dist/engine/core/files.js +6 -1
  34. package/dist/engine/core/format-collections.js +2 -2
  35. package/dist/engine/core/formats.d.ts +1 -1
  36. package/dist/engine/core/formats.js +1 -1
  37. package/dist/engine/core/html.d.ts +1 -0
  38. package/dist/engine/core/html.js +9 -5
  39. package/dist/engine/core/icons.d.ts +7 -0
  40. package/dist/engine/core/icons.js +38 -0
  41. package/dist/engine/core/subformats.d.ts +2 -1
  42. package/dist/engine/core/subformats.js +6 -1
  43. package/dist/engine/core/toc-library.d.ts +5 -0
  44. package/dist/engine/core/toc-library.js +27 -0
  45. package/dist/frontend/document-application.d.ts +5 -2
  46. package/dist/frontend/document-application.js +403 -189
  47. package/dist/frontend/edit-dialog.d.ts +1 -0
  48. package/dist/frontend/edit-dialog.js +12 -8
  49. package/dist/frontend/file-references.js +1 -1
  50. package/dist/frontend/locales/eng.json +62 -1
  51. package/dist/frontend/locales/jpn.json +62 -1
  52. package/dist/frontend/locales/zho.json +62 -1
  53. package/dist/frontend/page-jump.js +17 -10
  54. package/dist/frontend/resize.js +38 -12
  55. package/dist/frontend/resource-library.js +1 -0
  56. package/dist/frontend/search.js +2 -0
  57. package/dist/frontend/theme-picker.d.ts +2 -2
  58. package/dist/frontend/theme-picker.js +2 -2
  59. package/dist/manifest.global.js +193 -192
  60. package/dist/mcp-relay.mjs +8 -4
  61. package/dist/plugins.global.js +49 -49
  62. package/dist/server/build.js +11 -8
  63. package/dist/server/cli.js +18 -1
  64. package/dist/server/document-diff-cli.d.ts +1 -0
  65. package/dist/server/document-diff-cli.js +193 -0
  66. package/dist/server/document-diff-report.d.ts +3 -0
  67. package/dist/server/document-diff-report.js +124 -0
  68. package/dist/server/document-diff-sources.d.ts +40 -0
  69. package/dist/server/document-diff-sources.js +128 -0
  70. package/dist/server/document-versions.d.ts +3 -1
  71. package/dist/server/document-versions.js +19 -70
  72. package/dist/server/git-diff.d.ts +1 -0
  73. package/dist/server/git-diff.js +22 -2
  74. package/dist/server/git-document-snapshot.d.ts +2 -0
  75. package/dist/server/git-document-snapshot.js +63 -0
  76. package/dist/server/operation-log.js +2 -0
  77. package/dist/server/serve.d.ts +2 -2
  78. package/dist/server/serve.js +4 -9
  79. package/dist/server/workspace-server.js +6 -10
  80. package/dist/subformats.global.js +478 -74
  81. package/dist/ui.global.js +435 -80
  82. package/dist/workspace/file-operation.d.ts +10 -0
  83. package/dist/workspace/file-operation.js +47 -0
  84. package/dist/workspace/mcp-tools.js +8 -4
  85. package/dist/workspace/site-icon.js +30 -23
  86. package/dist/workspace/textfile.js +8 -8
  87. package/dist/workspace-worker.global.js +241 -197
  88. package/package.json +2 -2
@@ -17,7 +17,6 @@ import { walkBlocks } from "../engine/core/blocks.js";
17
17
  import { selectCodeGrammars } from "../engine/core/code-grammars.js";
18
18
  import { parseVersionConfig } from "../engine/core/document-version.js";
19
19
  import { isSkillFile } from "../engine/core/files.js";
20
- import { FORMAT_TRAITS } from "../engine/core/format-collections.js";
21
20
  import { fenceFormat } from "../engine/core/formats.js";
22
21
  import { parsePreviewSettings } from "../engine/core/previewers.js";
23
22
  import { loadBuildPlugins, pluginSnapshot } from "./build-plugins.js";
@@ -161,10 +160,14 @@ export const buildBundle = async (root, options) => {
161
160
  name,
162
161
  `data:application/octet-stream;base64,${(downloadSources?.get(name) ?? data).toString("base64")}`,
163
162
  ]));
164
- const formats = new Set(compiled.docs.flatMap((doc) => (doc.format ? [doc.format, fenceFormat(doc.format)] : [])));
165
- const collected = formats.size
163
+ const formats = new Set(compiled.docs.flatMap((doc) => (doc.format ? [doc.format] : [])));
164
+ const registered = new Set(compiled.subformats?.map(({ ext }) => ext));
165
+ const recordFormats = [...formats]
166
+ .flatMap((format) => [format, fenceFormat(format)])
167
+ .filter((format) => registered.has(format));
168
+ const collected = recordFormats.length
166
169
  ? resourceIndex(root, [...linkable])
167
- .codeblocks.filter((item) => formats.has(item.format))
170
+ .codeblocks.filter((item) => recordFormats.includes(item.format))
168
171
  .flatMap((item) => parseContentSource(item.language, item.content, item.source.file)?.blocks ?? [
169
172
  {
170
173
  type: "code",
@@ -173,13 +176,13 @@ export const buildBundle = async (root, options) => {
173
176
  },
174
177
  ])
175
178
  : [];
176
- const traitBlocks = [...formats].flatMap((selector) => selector.includes("/") || Object.hasOwn(FORMAT_TRAITS, selector)
177
- ? readFormatCollection(root, selector).records.flatMap((record) => record.preview ?? [])
178
- : []);
179
+ const formatBlocks = [...formats]
180
+ .filter((selector) => !registered.has(selector))
181
+ .flatMap((selector) => readFormatCollection(root, selector).records.flatMap((record) => record.preview ?? []));
179
182
  const blocks = walkBlocks([
180
183
  ...site.entries.flatMap((entry) => entry.blocks),
181
184
  ...collected,
182
- ...traitBlocks,
185
+ ...formatBlocks,
183
186
  ]);
184
187
  const code = blocks.flatMap((block) => block.type === "code" && block.lang !== "mermaid" && !block.unavailable && !block.subformat
185
188
  ? [block]
@@ -6,7 +6,7 @@ import { parseArgs } from "node:util";
6
6
  import { setDownloadProgressListener } from "../engine/compiler/download-progress.js";
7
7
  import { projectRoot } from "../engine/compiler/manifest.js";
8
8
  import { isManifestFile, MANIFEST_FILE, serializeManifest, } from "../engine/core/content-metadata.js";
9
- import { prebuilt } from "./assets.js";
9
+ import { packageVersion, prebuilt } from "./assets.js";
10
10
  import { outputFile, writeBuildOutput } from "./build-output.js";
11
11
  import { terminal } from "./terminal.js";
12
12
  process.env.NODE_ENV = prebuilt ? "production" : "development";
@@ -43,6 +43,7 @@ commands:
43
43
  --url_preview network|embed keep URL references (default) or capture their content
44
44
  --reader-plugins <module> inject an external build plugin module (embed only)
45
45
  check [dooc.yaml] [options] JSON consistency report (check --help for options)
46
+ diff [<to> | <from> <to>] [options] compare documents (text, JSON, HTML or PDF)
46
47
  plugin manage local plugins
47
48
  pack <built-dir> [zip] package bundled JS and assets as a plugin ZIP
48
49
  add <zip> [dooc.yaml] [port] install a local plugin and print login links
@@ -57,6 +58,7 @@ commands:
57
58
  docs download GitHub docs and open the local reader
58
59
  relay browser MCP relay (relay --help for options)
59
60
  --stdio connect a Desktop MCP host to a browser workspace
61
+ --version, -v print the installed dooc version
60
62
  help, --help, -h show this help`;
61
63
  const fail = (message) => {
62
64
  terminal.close();
@@ -307,6 +309,17 @@ Fonts:
307
309
  }
308
310
  break;
309
311
  }
312
+ case "diff": {
313
+ try {
314
+ const { diffCommand } = await import("./document-diff-cli.js");
315
+ process.exitCode = await diffCommand(args);
316
+ }
317
+ catch (error) {
318
+ console.error(error instanceof Error ? error.message : String(error));
319
+ process.exitCode = 2;
320
+ }
321
+ break;
322
+ }
310
323
  case "check": {
311
324
  const { checkSite } = await import("../engine/compiler/check.js");
312
325
  let report;
@@ -566,6 +579,10 @@ URL handling:
566
579
  case "mcp":
567
580
  fail("dooc mcp has moved: use dooc editor run node --mcp --mcp-transport stdio (or reader for read-only access). Browser relays use dooc relay.");
568
581
  break;
582
+ case "--version":
583
+ case "-v":
584
+ console.log(packageVersion);
585
+ break;
569
586
  case undefined:
570
587
  case "help":
571
588
  case "--help":
@@ -0,0 +1 @@
1
+ export declare const diffCommand: (args: string[]) => Promise<number>;
@@ -0,0 +1,193 @@
1
+ import { execFile } from "node:child_process";
2
+ import { existsSync, lstatSync, mkdtempSync, readFileSync, realpathSync, rmSync, statSync, writeFileSync, } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
5
+ import { fileURLToPath, pathToFileURL } from "node:url";
6
+ import { parseArgs, promisify } from "node:util";
7
+ import { exportEntries } from "../engine/compiler/export.js";
8
+ import { withIgnoredFilesCache } from "../engine/compiler/ignored-files.js";
9
+ import { projectRoot } from "../engine/compiler/manifest.js";
10
+ import { isManifestFile, MANIFEST_FILE } from "../engine/core/content-metadata.js";
11
+ import { outputFile, writeBuildOutput } from "./build-output.js";
12
+ import { diffHtml, diffText } from "./document-diff-report.js";
13
+ import { documentComparison } from "./document-diff-sources.js";
14
+ import { git } from "./git.js";
15
+ import { gitHeadFile } from "./workspace.js";
16
+ const usage = `usage: dooc diff [<to> | <from> <to>] [options]
17
+
18
+ dooc diff committed HEAD to saved working files
19
+ dooc diff latest preceding document version to latest
20
+ dooc diff latest~2 latest compare two document versions in order
21
+ dooc diff git:main git:feature compare two Git commits
22
+
23
+ Selectors: current, latest, latest~N, X.Y.Z, git:<ref>.
24
+ One historical selector shows the change introduced by that version or commit.
25
+ Outside Git, the default compares the latest retained snapshot with saved files.
26
+
27
+ --project <path> project folder or manifest (default: ./dooc.yaml)
28
+ --format text|json|html|pdf output format (default: text)
29
+ --out <file> output path (text/JSON default to stdout;
30
+ HTML/PDF default to build/diff.html or diff.pdf)
31
+ --exit-code exit 1 for changes, 0 for no changes, 2 for errors
32
+ --help, -h show this help
33
+
34
+ PDF requires installed Chrome or Chromium. Set DOOC_CHROMIUM to its executable.`;
35
+ const pdf = async (html) => {
36
+ const temporary = mkdtempSync(join(tmpdir(), "dooc-diff-pdf-"));
37
+ try {
38
+ const input = join(temporary, "review.html");
39
+ const output = join(temporary, "review.pdf");
40
+ writeFileSync(input, html);
41
+ const commands = process.env.DOOC_CHROMIUM
42
+ ? [process.env.DOOC_CHROMIUM]
43
+ : [
44
+ "chromium",
45
+ "google-chrome",
46
+ "chromium-browser",
47
+ ...(process.platform === "darwin"
48
+ ? ["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"]
49
+ : []),
50
+ ...(process.platform === "win32" ? ["chrome.exe"] : []),
51
+ ];
52
+ for (const command of commands) {
53
+ try {
54
+ await promisify(execFile)(command, [
55
+ "--headless",
56
+ "--disable-background-networking",
57
+ "--disable-extensions",
58
+ "--no-first-run",
59
+ `--user-data-dir=${join(temporary, "profile")}`,
60
+ "--no-pdf-header-footer",
61
+ `--print-to-pdf=${output}`,
62
+ pathToFileURL(input).href,
63
+ ], { timeout: 60_000, windowsHide: true });
64
+ }
65
+ catch (error) {
66
+ if (error.code === "ENOENT")
67
+ continue;
68
+ throw new Error(`Chromium PDF export failed: ${error instanceof Error ? error.message : error}`);
69
+ }
70
+ const data = readFileSync(output);
71
+ if (!data.subarray(0, 5).equals(Buffer.from("%PDF-")) ||
72
+ !data.subarray(-32).includes("%%EOF"))
73
+ throw new Error("Chromium did not produce a complete PDF");
74
+ return data;
75
+ }
76
+ throw new Error("PDF export requires Chrome or Chromium. Set DOOC_CHROMIUM to its executable.");
77
+ }
78
+ finally {
79
+ rmSync(temporary, { recursive: true, force: true });
80
+ }
81
+ };
82
+ const canonical = (path) => {
83
+ let parent = path;
84
+ while (!lstatSync(parent, { throwIfNoEntry: false }))
85
+ parent = dirname(parent);
86
+ return resolve(realpathSync(parent), relative(parent, path));
87
+ };
88
+ const inside = (root, path) => {
89
+ const rel = relative(root, path);
90
+ return rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel);
91
+ };
92
+ const checkDestination = async (root, path, comparison) => {
93
+ const physical = canonical(path);
94
+ const reject = () => {
95
+ throw new Error(`Cannot overwrite a source or metadata path: ${path}`);
96
+ };
97
+ for (const name of [path, physical])
98
+ if (isManifestFile(basename(name)) ||
99
+ name.split(sep).some((part) => [".git", ".dooc"].includes(part.toLowerCase())))
100
+ reject();
101
+ const info = lstatSync(path, { throwIfNoEntry: false });
102
+ if (info && !info.isFile())
103
+ reject();
104
+ if (gitHeadFile(root)) {
105
+ const metadata = await git(root, [
106
+ "rev-parse",
107
+ "--path-format=absolute",
108
+ "--git-dir",
109
+ "--git-common-dir",
110
+ ]);
111
+ if (metadata
112
+ .trimEnd()
113
+ .split("\n")
114
+ .some((dir) => inside(realpathSync(dir), physical)))
115
+ reject();
116
+ }
117
+ if (!inside(realpathSync(root), physical))
118
+ return;
119
+ const sources = new Set([...comparison.before.files.keys(), ...comparison.after.files.keys()]);
120
+ if (info &&
121
+ comparison.report.from.revision !== "current" &&
122
+ comparison.report.to.revision !== "current") {
123
+ for (const entry of withIgnoredFilesCache(() => exportEntries(root)))
124
+ sources.add(entry.name);
125
+ }
126
+ for (const source of sources) {
127
+ const original = resolve(root, source);
128
+ if (original === path || (existsSync(original) && realpathSync(original) === physical))
129
+ reject();
130
+ }
131
+ };
132
+ export const diffCommand = async (args) => {
133
+ const { values, positionals } = parseArgs({
134
+ args,
135
+ allowPositionals: true,
136
+ options: {
137
+ help: { type: "boolean", short: "h" },
138
+ project: { type: "string" },
139
+ format: { type: "string", default: "text" },
140
+ out: { type: "string" },
141
+ "exit-code": { type: "boolean" },
142
+ },
143
+ });
144
+ if (values.help) {
145
+ console.log(usage);
146
+ return 0;
147
+ }
148
+ if (positionals.length > 2)
149
+ throw new Error("Expected at most two selectors. See dooc diff --help.");
150
+ const format = values.format ?? "text";
151
+ if (!["text", "json", "html", "pdf"].includes(format))
152
+ throw new Error("Expected --format text, json, html or pdf");
153
+ if (values.out === "" || values.project === "")
154
+ throw new Error("Expected a non-empty path");
155
+ let project = values.project ?? MANIFEST_FILE;
156
+ if (/^file:/i.test(project)) {
157
+ const url = new URL(project);
158
+ if (url.username || url.password || url.search || url.hash)
159
+ throw new Error("Invalid local project URL");
160
+ project = fileURLToPath(url);
161
+ }
162
+ const root = projectRoot(statSync(project, { throwIfNoEntry: false })?.isDirectory()
163
+ ? join(project, MANIFEST_FILE)
164
+ : project);
165
+ const output = values.out
166
+ ? resolve(values.out)
167
+ : format === "html" || format === "pdf"
168
+ ? join(dirname(outputFile(root, "html")), `diff.${format}`)
169
+ : undefined;
170
+ const comparison = await documentComparison(root, positionals);
171
+ const { report, before, after } = comparison;
172
+ if (output)
173
+ await checkDestination(root, output, comparison);
174
+ let data;
175
+ if (format === "text")
176
+ data = diffText(report, !output &&
177
+ !!process.stdout.isTTY &&
178
+ process.env.NO_COLOR === undefined &&
179
+ process.env.TERM !== "dumb");
180
+ else if (format === "json")
181
+ data = `${JSON.stringify(report, null, 2)}\n`;
182
+ else {
183
+ const html = diffHtml(report, before, after);
184
+ data = format === "pdf" ? await pdf(html) : html;
185
+ }
186
+ if (output) {
187
+ writeBuildOutput(output, { data });
188
+ console.error(`${output} (${Buffer.byteLength(data)} bytes)`);
189
+ }
190
+ else
191
+ process.stdout.write(data);
192
+ return values["exit-code"] && report.changes.length ? 1 : 0;
193
+ };
@@ -0,0 +1,3 @@
1
+ import type { DiffSnapshot, DocumentDiff } from "../engine/compiler/document-diff.js";
2
+ export declare const diffText: (report: DocumentDiff, color: boolean) => string;
3
+ export declare const diffHtml: (report: DocumentDiff, before: DiffSnapshot, after: DiffSnapshot) => string;
@@ -0,0 +1,124 @@
1
+ import { FILE_HEADERS_ONLY, formatPatch } from "diff";
2
+ import { toBlocks } from "../engine/compiler/from-mdast.js";
3
+ import { blocksHtml, escapeHtml as esc } from "../engine/core/html.js";
4
+ import { parseMdast } from "../engine/core/markdown.js";
5
+ import { DARK_C, LIGHT_C } from "../frontend/theme-picker.js";
6
+ const endpointLabel = (end) => `${end.selector} (${end.version && end.version !== end.selector ? `${end.version}, ` : ""}${end.revision === "current" ? `saved ${end.contentHash.slice(0, 12)}` : end.revision.slice(0, 12)})`;
7
+ const pathLabel = (change) => change.kind === "renamed"
8
+ ? `${change.fromPath} → ${change.toPath}`
9
+ : (change.toPath ?? change.fromPath ?? "");
10
+ const metadata = (change) => {
11
+ const lines = [];
12
+ if (change.binary)
13
+ lines.push(`Binary content omitted (${change.beforeBytes} → ${change.afterBytes} bytes).`);
14
+ if (change.beforeMode && change.afterMode && change.beforeMode !== change.afterMode)
15
+ lines.push(`Mode ${change.beforeMode} → ${change.afterMode}`);
16
+ if (change.beforeLink !== change.afterLink)
17
+ lines.push(`Symlink ${change.beforeLink ?? "(none)"} → ${change.afterLink ?? "(none)"}`);
18
+ return lines;
19
+ };
20
+ export const diffText = (report, color) => {
21
+ const sections = report.changes.map((change) => {
22
+ const lines = [`${change.kind} ${pathLabel(change)}`, ...metadata(change)];
23
+ if (change.hunks.length) {
24
+ const patch = formatPatch({
25
+ oldFileName: change.fromPath ?? "/dev/null",
26
+ newFileName: change.toPath ?? "/dev/null",
27
+ oldHeader: undefined,
28
+ newHeader: undefined,
29
+ // formatPatch adjusts line numbers in place for empty sides.
30
+ hunks: change.hunks.map((hunk) => ({ ...hunk })),
31
+ }, FILE_HEADERS_ONLY);
32
+ lines.push(patch.slice(0, -1));
33
+ }
34
+ return lines.join("\n");
35
+ });
36
+ const text = `${report.scope.manifest}: ${endpointLabel(report.from)} → ${endpointLabel(report.to)}\n\n${sections.join("\n\n") || "No changes."}\n`;
37
+ if (!color)
38
+ return text;
39
+ return text.replace(/^[+-].*$/gm, (line) => `\x1b[${line.startsWith("+") ? 32 : 31}m${line}\x1b[0m`);
40
+ };
41
+ const excerpt = (change, snapshot, before) => {
42
+ const path = before ? change.fromPath : change.toPath;
43
+ if (!path)
44
+ return `<p>File ${before ? "added" : "removed"}.</p>`;
45
+ const sign = before ? "-" : "+";
46
+ const pieces = change.hunks.map((hunk) => hunk.lines
47
+ .filter((line) => line.startsWith(sign) || line.startsWith(" "))
48
+ .map((line) => line.slice(1))
49
+ .join("\n"));
50
+ const literal = () => pieces.map((piece) => `<pre>${esc(piece)}</pre>`).join("");
51
+ if (!/\.md$/i.test(path))
52
+ return literal();
53
+ const source = snapshot.files.get(path)?.data.toString("utf8") ?? "";
54
+ const changed = new Set();
55
+ for (const hunk of change.hunks) {
56
+ let line = before ? hunk.oldStart : hunk.newStart;
57
+ for (const entry of hunk.lines) {
58
+ if (entry.startsWith(sign))
59
+ changed.add(line++);
60
+ else if (entry.startsWith(" "))
61
+ line++;
62
+ }
63
+ }
64
+ const parts = [];
65
+ for (const block of parseMdast(source).children) {
66
+ const pos = block.position;
67
+ if (!pos)
68
+ continue;
69
+ let line = pos.start.line;
70
+ while (line <= pos.end.line && !changed.has(line))
71
+ line++;
72
+ if (line > pos.end.line)
73
+ continue;
74
+ const raw = source.slice(pos.start.offset, pos.end.offset);
75
+ if (["paragraph", "heading", "list", "blockquote", "table"].includes(block.type)) {
76
+ const { blocks } = toBlocks({ type: "root", children: [block] }, source);
77
+ if (blocks.length) {
78
+ parts.push(blocksHtml(blocks));
79
+ continue;
80
+ }
81
+ }
82
+ parts.push(`<pre>${esc(raw)}</pre>`);
83
+ }
84
+ return parts.join("") || literal();
85
+ };
86
+ const css = `:root{${LIGHT_C}}@media(prefers-color-scheme:dark){:root{${DARK_C}}}
87
+ *{box-sizing:border-box}body{max-width:80rem;margin:auto;padding:1.5rem;color:var(--c-fg);background:var(--c-bg0);font:1rem/1.6 system-ui,sans-serif;overflow-wrap:anywhere}
88
+ h1,h2,h3,p{margin:.5em 0}h1{font-size:1.7rem}h2{font-size:1.15rem}h3{font-size:1rem}a{color:var(--c-accent)}nav ul{padding-left:1.3rem}article{border-top:1px solid var(--c-line);padding:1rem 0}
89
+ .pair{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:1rem}.pair section{min-width:0;padding:.75rem;background:var(--c-bg1)}.pair h3{color:var(--c-fg-muted)}
90
+ pre,code,dd{white-space:pre-wrap;overflow-wrap:anywhere}pre{font:0.88rem/1.55 ui-monospace,monospace}.patch span{display:block;min-height:1em}.added{color:var(--c-ok)}.deleted{color:var(--c-danger)}
91
+ summary{cursor:pointer}dt{font-weight:600}dd{margin-left:0}table{border-collapse:collapse}td,th{padding:.2rem .6rem;border:1px solid var(--c-line)}:focus-visible{outline:2px solid var(--c-accent)}
92
+ @media(max-width:45rem){body{padding:.8rem}.pair{grid-template-columns:1fr}}
93
+ @page{size:A4;margin:14mm}@media print{body{padding:0;font-size:10pt;color:#111;background:white}nav,.review-toggle{display:none}.pair{display:block}.pair section{background:white}h2,h3,summary{break-after:avoid}pre{font-size:8pt}.patch span{break-inside:avoid}a{color:inherit}}`;
94
+ export const diffHtml = (report, before, after) => {
95
+ const links = [];
96
+ const articles = [];
97
+ for (const [i, change] of report.changes.entries()) {
98
+ const title = `${esc(change.kind)} · ${esc(pathLabel(change))}`;
99
+ links.push(`<li><a href="#change-${i}">${title}</a></li>`);
100
+ const details = metadata(change)
101
+ .map((line) => `<p>${esc(line)}</p>`)
102
+ .join("");
103
+ const patch = change.hunks
104
+ .map((hunk) => {
105
+ const lines = hunk.lines
106
+ .map((line) => `<span class="${line.startsWith("+") ? "added" : line.startsWith("-") ? "deleted" : ""}">${esc(line)}</span>`)
107
+ .join("");
108
+ return `<pre class="patch"><span>@@ -${hunk.oldStart},${hunk.oldLines} +${hunk.newStart},${hunk.newLines} @@</span>${lines}</pre>`;
109
+ })
110
+ .join("");
111
+ const pair = patch &&
112
+ `<div class="pair"><section><h3>Before</h3>${excerpt(change, before, true)}</section><section><h3>After</h3>${excerpt(change, after, false)}</section></div>
113
+ <details open><summary>Source diff</summary>${patch}</details>`;
114
+ articles.push(`<article id="change-${i}"><h2>${title}</h2>${details}${pair}</article>`);
115
+ }
116
+ const title = `${esc(report.scope.manifest)} · Document diff`;
117
+ return `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
118
+ <meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'; base-uri 'none'; form-action 'none'">
119
+ <title>${title}</title><style>${css}</style></head><body><header><h1>${title}</h1>
120
+ <p>${esc(endpointLabel(report.from))} → ${esc(endpointLabel(report.to))}</p>
121
+ <details><summary>Comparison identity</summary><dl><dt>From</dt><dd>${esc(report.from.revision)} · ${report.from.contentHash}</dd><dt>To</dt><dd>${esc(report.to.revision)} · ${report.to.contentHash}</dd><dt>Comparison</dt><dd>${report.comparisonId}</dd></dl></details></header>
122
+ ${links.length ? `<nav aria-label="Changed files"><h2>Changed files (${links.length})</h2><ul>${links.join("")}</ul></nav>` : ""}
123
+ <main>${articles.join("") || "<p>No changes.</p>"}</main></body></html>\n`;
124
+ };
@@ -0,0 +1,40 @@
1
+ import { type DiffSnapshot } from "../engine/compiler/document-diff.js";
2
+ export declare const documentComparison: (root: string, operands: string[]) => Promise<{
3
+ report: {
4
+ schemaVersion: number;
5
+ comparisonId: string;
6
+ coverage: string;
7
+ scope: {
8
+ manifest: string;
9
+ };
10
+ from: {
11
+ contentHash: string;
12
+ selector: string;
13
+ revision: string;
14
+ version?: string;
15
+ };
16
+ to: {
17
+ contentHash: string;
18
+ selector: string;
19
+ revision: string;
20
+ version?: string;
21
+ };
22
+ changes: {
23
+ kind: string;
24
+ fromPath: string | null;
25
+ toPath: string | null;
26
+ binary: boolean;
27
+ hunks: import("diff").StructuredPatchHunk[];
28
+ beforeHash: string | null;
29
+ afterHash: string | null;
30
+ beforeBytes: number;
31
+ afterBytes: number;
32
+ beforeMode: string | null;
33
+ afterMode: string | null;
34
+ beforeLink: string | undefined;
35
+ afterLink: string | undefined;
36
+ }[];
37
+ };
38
+ before: DiffSnapshot;
39
+ after: DiffSnapshot;
40
+ }>;
@@ -0,0 +1,128 @@
1
+ import { lstatSync, readlinkSync, realpathSync } from "node:fs";
2
+ import { isAbsolute, join, relative, sep } from "node:path";
3
+ import { compareDocuments, diffHash, } from "../engine/compiler/document-diff.js";
4
+ import { exportEntries } from "../engine/compiler/export.js";
5
+ import { withIgnoredFilesCache } from "../engine/compiler/ignored-files.js";
6
+ import { manifestFile } from "../engine/compiler/manifest.js";
7
+ import { storedDocumentVersions, storedVersionRoot, } from "../engine/compiler/stored-versions.js";
8
+ import { parseDocumentVersion, parseVersionSelection, selectVersions, } from "../engine/core/document-version.js";
9
+ import { createDocumentVersions } from "./document-versions.js";
10
+ import { git } from "./git.js";
11
+ import { gitHeadFile } from "./workspace.js";
12
+ const capture = (root) => {
13
+ const files = new Map();
14
+ const identity = [];
15
+ let bytes = 0;
16
+ const entries = withIgnoredFilesCache(() => exportEntries(root));
17
+ for (const { name, data } of entries.sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0)) {
18
+ bytes += data.length;
19
+ if (bytes > 256 * 1024 * 1024)
20
+ throw new Error("Document comparison exceeds 256 MiB per snapshot");
21
+ const path = join(root, name);
22
+ const stat = lstatSync(path);
23
+ const mode = stat.isSymbolicLink() ? "120000" : stat.mode & 0o100 ? "100755" : "100644";
24
+ let link = stat.isSymbolicLink() ? readlinkSync(path) : undefined;
25
+ if (link && isAbsolute(link))
26
+ link = `<project>/${relative(realpathSync(root), link).split(sep).join("/")}`;
27
+ const hash = diffHash(data);
28
+ files.set(name, { data, hash, mode, link });
29
+ identity.push([name, hash, mode, link]);
30
+ }
31
+ return { files, contentHash: diffHash(JSON.stringify(identity)) };
32
+ };
33
+ export const documentComparison = async (root, operands) => {
34
+ const manifest = manifestFile(root);
35
+ const inGit = !!gitHeadFile(root);
36
+ // Historical comparisons may use captured remote sources, never a fresh copy of a moving branch.
37
+ const catalog = createDocumentVersions(root, manifest, null);
38
+ let rows;
39
+ const versions = () => (rows ??= inGit
40
+ ? catalog.list().then((items) => items.filter((item) => item.revision !== "current"))
41
+ : Promise.resolve(selectVersions(storedDocumentVersions(root, manifest), parseVersionSelection("*"))));
42
+ const commit = async (ref) => {
43
+ if (!inGit)
44
+ throw new Error("A git: selector requires a Git workspace");
45
+ if (!ref || ref.startsWith("-") || /[\s:{}\\?*[\]]|\.\./.test(ref))
46
+ throw new Error(`Invalid Git revision: ${ref}`);
47
+ try {
48
+ return (await git(root, ["rev-parse", "--verify", "--end-of-options", `${ref}^{commit}`])).trim();
49
+ }
50
+ catch {
51
+ throw new Error(`Git commit unavailable: ${ref}. Check the ref and fetch missing history.`);
52
+ }
53
+ };
54
+ const endpoint = async (selector, previous = false) => {
55
+ if (selector === "current")
56
+ return { selector, revision: "current" };
57
+ if (selector.startsWith("git:"))
58
+ return { selector, revision: await commit(selector.slice(4)) };
59
+ const latest = /^latest(?:~(\d+))?$/.exec(selector);
60
+ if (!latest) {
61
+ try {
62
+ parseDocumentVersion(selector);
63
+ }
64
+ catch {
65
+ throw new Error(`Unknown selector '${selector}'. Use current, latest, latest~N, X.Y.Z or git:<ref>.`);
66
+ }
67
+ }
68
+ const items = await versions();
69
+ const i = latest
70
+ ? Number(latest[1] ?? 0)
71
+ : items.findIndex((item) => item.version === selector);
72
+ if (!items[i])
73
+ throw new Error(`Document version unavailable: ${selector}`);
74
+ const row = items[i + Number(previous)];
75
+ if (!row)
76
+ throw new Error(`No preceding document version available for ${selector}`);
77
+ return {
78
+ selector: previous ? row.version : selector,
79
+ version: row.version,
80
+ revision: row.revision,
81
+ };
82
+ };
83
+ try {
84
+ const [first, second] = operands;
85
+ let from;
86
+ let to;
87
+ if (first !== undefined && second !== undefined) {
88
+ from = await endpoint(first);
89
+ to = second === first ? from : await endpoint(second);
90
+ }
91
+ else if (first === undefined || first === "current") {
92
+ if (!inGit && !(await versions()).length)
93
+ throw new Error("Comparison requires a committed Git HEAD or a retained document baseline");
94
+ from = await endpoint(inGit ? "git:HEAD" : "latest");
95
+ to = await endpoint("current");
96
+ }
97
+ else {
98
+ to = await endpoint(first);
99
+ if (first.startsWith("git:")) {
100
+ from = {
101
+ selector: `${first}^1`,
102
+ revision: await commit(`${to.revision}^1`).catch(() => {
103
+ throw new Error(`No first parent available for ${first}. Check for an initial commit or shallow history.`);
104
+ }),
105
+ };
106
+ }
107
+ else
108
+ from = await endpoint(first, true);
109
+ }
110
+ const read = async ({ revision }) => {
111
+ if (revision === "current") {
112
+ const snapshot = capture(root);
113
+ if (capture(root).contentHash !== snapshot.contentHash)
114
+ throw new Error("Working files changed during capture. Run dooc diff again.");
115
+ return snapshot;
116
+ }
117
+ return capture(revision.startsWith("hash-")
118
+ ? storedVersionRoot(root, revision, manifest)
119
+ : await catalog.openCommit(revision));
120
+ };
121
+ const before = await read(from);
122
+ const after = from.revision === to.revision ? before : await read(to);
123
+ return { report: compareDocuments(manifest, from, before, to, after), before, after };
124
+ }
125
+ finally {
126
+ catalog.close();
127
+ }
128
+ };
@@ -1,8 +1,10 @@
1
1
  import { type DocumentRevision } from "../engine/core/document-version.js";
2
+ import { prepareDocumentSources } from "./remote-manifests.js";
2
3
  /** Historical sources live in disposable folders; viewing never changes a checkout. */
3
- export declare const createDocumentVersions: (root: string, name?: string) => {
4
+ export declare const createDocumentVersions: (root: string, name?: string, prepareSources?: typeof prepareDocumentSources | null) => {
4
5
  enabled: () => boolean;
5
6
  list: () => Promise<DocumentRevision[]>;
7
+ openCommit: (revision: string) => Promise<string>;
6
8
  versionAt(revision: string): Promise<string | undefined>;
7
9
  open(revision: string): Promise<string>;
8
10
  close(): void;