@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
@@ -1,9 +1,11 @@
1
- // A doc's icon (1:1 SVG shown on its sidebar row). It lives at icons/<docId>.svg in the docs root.
2
- // Separate from body-text figures (figures/): one per doc, following the doc's rename / deletion.
3
1
  import { docIconFile } from "../core/files.js";
2
+ import { squareSvg } from "../core/icons.js";
3
+ import { projectFilePath } from "./files.js";
4
4
  import { existsSync, join, readdirSync, readFileSync, relative } from "./host.js";
5
5
  import { assertNotIgnored, ignoredFiles } from "./ignored-files.js";
6
6
  import { readTextfile, textfilePath } from "./textfile.js";
7
+ import { themeVariants } from "./theme-variants.js";
8
+ export { squareSvg };
7
9
  export const ICONS_DIR = "icons";
8
10
  /** Only implicit, unshared icon files belong to a page's lifecycle. */
9
11
  export const ownsDocIcon = (id, manifest) => {
@@ -16,42 +18,34 @@ export const ownsDocIcon = (id, manifest) => {
16
18
  ].includes(file));
17
19
  };
18
20
  const ROOT_SVG_RE = /<svg\b[^>]*>/i;
19
- const num = (v) => {
20
- const n = v == null ? Number.NaN : Number.parseFloat(v);
21
- return Number.isFinite(n) && n > 0 ? n : undefined;
21
+ export const projectIcon = (root, file) => {
22
+ if (typeof file !== "string" || !file.endsWith(".svg"))
23
+ throw new Error("Choose an SVG file");
24
+ projectFilePath(root, file);
25
+ const svg = squareSvg(readTextfile(root, file));
26
+ if (!svg)
27
+ throw new Error("SVG requires a viewBox or width and height");
28
+ return svg;
22
29
  };
23
- /**
24
- * Normalize an SVG to 1:1 (padding is added automatically = the shorter side is widened, centered;
25
- * nothing is cropped). Builds a square viewBox from the root's viewBox (or width / height if it has
26
- * none) and removes fixed width / height (so it scales to the display box). Returns undefined for
27
- * SVGs whose dimensions can't be read.
28
- */
29
- export const squareSvg = (svg) => {
30
- const root = ROOT_SVG_RE.exec(svg)?.[0];
31
- if (!root) {
32
- return undefined;
33
- }
34
- const attr = (name) => new RegExp(`\\s${name}\\s*=\\s*["']([^"']*)["']`, "i").exec(root)?.[1];
35
- const vb = attr("viewBox")
36
- ?.trim()
37
- .split(/[\s,]+/)
38
- .map(Number);
39
- let [x, y, w, h] = vb && vb.length === 4 && vb.every(Number.isFinite)
40
- ? vb
41
- : [0, 0, num(attr("width")), num(attr("height"))];
42
- if (x == null || y == null || w == null || h == null || w <= 0 || h <= 0) {
43
- return undefined;
44
- }
45
- const side = Math.max(w, h);
46
- x -= (side - w) / 2;
47
- y -= (side - h) / 2;
48
- const round = (n) => Math.round(n * 1000) / 1000;
49
- // Rendered via <img> (data URI), so it won't draw without xmlns — add it if missing.
50
- const xmlns = /\sxmlns\s*=/.test(root) ? "" : ' xmlns="http://www.w3.org/2000/svg"';
51
- const next = root
52
- .replace(/\s(viewBox|width|height|preserveAspectRatio)\s*=\s*(["'])[^"']*\2/gi, "")
53
- .replace(/^<svg\b/i, `<svg${xmlns} viewBox="${[x, y, side, side].map(round).join(" ")}" preserveAspectRatio="xMidYMid meet"`);
54
- return svg.replace(root, next);
30
+ export const siteIconAssets = (root, manifest, themes) => {
31
+ if (!manifest.icon)
32
+ return {};
33
+ const svg = (file) => {
34
+ const icon = squareSvg(readTextfile(root, file));
35
+ if (!icon)
36
+ throw new Error(`${file}: expected an SVG with a viewBox or width and height`);
37
+ return icon;
38
+ };
39
+ const icon = svg(manifest.icon);
40
+ const variants = Object.entries(manifest.themeIcons ?? themeVariants(root, manifest.icon, themes, manifest));
41
+ return {
42
+ icon,
43
+ ...(variants.length
44
+ ? {
45
+ iconVariants: Object.fromEntries(variants.map(([theme, file]) => [theme, svg(file)])),
46
+ }
47
+ : {}),
48
+ };
55
49
  };
56
50
  /** Read icons/ (docId → svg markup). An icon with no doc is an error (missed rename / delete). */
57
51
  export const loadIcons = (root, docIds, siteIconFile, layout, siteIcons = []) => {
@@ -84,6 +78,10 @@ export const loadIcons = (root, docIds, siteIconFile, layout, siteIcons = []) =>
84
78
  if (siteIcons.includes(`${ICONS_DIR}/${f}`) ||
85
79
  Object.values(layout?.icons ?? {}).includes(`${ICONS_DIR}/${f}`))
86
80
  continue;
81
+ if (id &&
82
+ (existsSync(join(root, `content/${id}.md`)) ||
83
+ (id.endsWith(".md") && existsSync(join(root, id)))))
84
+ continue;
87
85
  errors.push(`${ICONS_DIR}/${f}: no matching doc (content/${id || f}.md)`);
88
86
  continue;
89
87
  }
@@ -1,5 +1,6 @@
1
1
  import { type DocNode, type ParsedManifest } from "../core/content-metadata.js";
2
2
  export declare const manifestFile: (root: string) => string;
3
+ export declare const hasContentsSource: (manifest: ParsedManifest, owner: string, file: string, exclude?: string) => boolean;
3
4
  export declare const sourceOrigin: (manifest: ParsedManifest, file: string) => string | undefined;
4
5
  export declare const sectionManifest: (root: string, value?: unknown) => string;
5
6
  /** Select the manifest for subsequent operations on its parent directory. */
@@ -5,6 +5,7 @@ import { flattenTree, isContentPage, isManifestFile, MANIFEST_FILE, pageUrlKind,
5
5
  import { docFile, fileDocumentId, parseFileLayout } from "../core/files.js";
6
6
  import { isRemoteManifest } from "../core/remote-manifest.js";
7
7
  import { documentPathErrors } from "../core/routing.js";
8
+ import { tocReference, tocUrl } from "../core/toc-library.js";
8
9
  import { createFileCache } from "./file-cache.js";
9
10
  import { basename, dirname, existsSync, join, posix, resolve, statSync, writeFileSync, } from "./host.js";
10
11
  import { assertNotIgnored } from "./ignored-files.js";
@@ -13,6 +14,10 @@ import { textfilePath } from "./textfile.js";
13
14
  const manifests = new Map();
14
15
  const parsed = createFileCache();
15
16
  export const manifestFile = (root) => manifests.get(resolve(root)) ?? MANIFEST_FILE;
17
+ export const hasContentsSource = (manifest, owner, file, exclude) => file === owner ||
18
+ flattenTree(manifest.tree).some((entry) => entry.id !== exclude &&
19
+ ((entry.resolved && entry.origin === file) ||
20
+ (isContentPage(entry) && docFile(entry.id, manifest.files) === file)));
16
21
  export const sourceOrigin = (manifest, file) => {
17
22
  const page = flattenTree(manifest.tree).find((node) => isContentPage(node) && docFile(node.id, manifest.files) === file);
18
23
  if (page)
@@ -78,6 +83,9 @@ export const readManifest = (root, file = manifestFile(root)) => {
78
83
  for (const node of nodes) {
79
84
  const oldId = node.id;
80
85
  if (imported) {
86
+ const contents = node.url && tocReference(node.url);
87
+ if (contents)
88
+ node.url = tocUrl(qualify(contents.file), contents.recursive);
81
89
  if (isContentPage(node))
82
90
  node.file = qualify(node.file ?? docFile(oldId, manifest.files));
83
91
  if (node.url &&
@@ -132,6 +140,16 @@ export const readManifest = (root, file = manifestFile(root)) => {
132
140
  manifest.includedSubformats ??= [];
133
141
  manifest.subformats.push(format);
134
142
  manifest.includedSubformats.push(format.ext);
143
+ manifest.includedRecordSources ??= {};
144
+ manifest.includedRecordSources[format.ext] = child
145
+ .includedRecordSources?.[format.ext] ?? {
146
+ directory: posix.dirname(included),
147
+ ...(child.defaultSubformatFolder
148
+ ? {
149
+ defaultFolder: posix.join(posix.dirname(included), child.defaultSubformatFolder),
150
+ }
151
+ : {}),
152
+ };
135
153
  }
136
154
  }
137
155
  }
@@ -150,6 +168,8 @@ export const readManifest = (root, file = manifestFile(root)) => {
150
168
  ].flatMap((asset) => (asset ? [qualify(asset)] : []));
151
169
  for (const format of manifest.subformats ?? []) {
152
170
  format.schema = qualify(format.schema);
171
+ if (format.files)
172
+ format.files = format.files.map(qualify);
153
173
  if (format.icon)
154
174
  format.icon = qualify(format.icon);
155
175
  }
@@ -173,6 +193,11 @@ export const readManifest = (root, file = manifestFile(root)) => {
173
193
  try {
174
194
  const manifest = load(file);
175
195
  const pages = flattenTree(manifest.tree);
196
+ for (const entry of pages) {
197
+ const contents = entry.url && tocReference(entry.url);
198
+ if (contents && !hasContentsSource(manifest, file, contents.file))
199
+ manifest.errors.push(`Table of contents source is not in this document: ${contents.file}`);
200
+ }
176
201
  manifest.errors.push(...documentPathErrors(pages).map((error) => `${file}: ${error}`));
177
202
  const ids = pages.map(({ id }) => id);
178
203
  if (new Set(ids).size !== ids.length)
@@ -13,10 +13,10 @@ export declare const createDocOps: (root: string) => {
13
13
  loadTree: () => OpResult<ParsedManifest>;
14
14
  referencingFiles: (id: string, removed: readonly string[]) => string[];
15
15
  figureFiles: () => Map<string, string>;
16
- add: (id: string, title: string, parent?: string, filename?: string) => OpResult<{
16
+ add: (id: string, title: string, parent?: string, filename?: string, placement?: "path" | "reference") => OpResult<{
17
17
  id: string;
18
18
  }>;
19
- addFile: (name: string, title: string, parent?: string) => OpResult<{
19
+ addFile: (name: string, title: string, parent?: string, placement?: "path" | "reference") => OpResult<{
20
20
  id: string;
21
21
  }>;
22
22
  addSubformat: (ext: string, title: string, parent?: string) => OpResult<{
@@ -1,20 +1,20 @@
1
1
  // Write operations on the docs root (create / move / rename / delete docs and save body text;
2
2
  // add / remove figures). Shared by the reader's edit API, the CLI (doc / figure) and MCP.
3
3
  // Failures are returned as { error, status } (status is HTTP-like) with no partial updates.
4
- import { flattenTree, formatPageId, insertDoc, isContentPage, isDocId, libraryPageId, moveDoc, pageUrlKind, removeDoc, renameDoc, subformatPageId, } from "../core/content-metadata.js";
4
+ import { flattenTree, formatPageId, insertDoc, isContentPage, isDocId, libraryPageId, moveDoc, pageUrlKind, renameDoc, subformatPageId, } from "../core/content-metadata.js";
5
5
  import { defaultFilePath, docIconFile, fileDocumentId, isDocumentFileName, parseFileLayout, } from "../core/files.js";
6
6
  import { isFormatSelector } from "../core/format-collections.js";
7
7
  import { isReferenceLibrary } from "../core/formats.js";
8
8
  import { documentPathErrors, docPath as pagePath, parseDocLink, resolveDocPath, } from "../core/routing.js";
9
9
  import { collectDocLinks, compileSite } from "./compile.js";
10
10
  import { figureName, figureUploadName } from "./figures.js";
11
- import { filesSnapshot, projectFiles, rebaseFileLinks, rewriteFileLinks, updateFiles, } from "./files.js";
11
+ import { filesSnapshot, managedFile, projectFilePath, projectFiles, rebaseFileLinks, rewriteFileLinks, updateFiles, } from "./files.js";
12
12
  import { dirname, existsSync, join, mkdirSync, posix, readdirSync, readFileSync, renameSync, unlinkSync, writeFileSync, } from "./host.js";
13
- import { ownsDocIcon } from "./icons.js";
14
13
  import { translationFile, translationFiles, translationLanguages } from "./locales.js";
15
14
  import { docFile, readManifest, sourceOrigin, writeManifest } from "./manifest.js";
16
15
  import { isRemoteSourceFile } from "./remote-manifests.js";
17
- import { textfilePath } from "./textfile.js";
16
+ import { removeSidebarEntry } from "./sidebar-removal.js";
17
+ import { readTextfile, textfilePath } from "./textfile.js";
18
18
  export const isOpError = (r) => typeof r === "object" && r != null && "error" in r;
19
19
  export { assembleDoc } from "./serialize.js";
20
20
  export const createDocOps = (root) => {
@@ -50,14 +50,17 @@ export const createDocOps = (root) => {
50
50
  .map((file) => file.replace(/^content\//, ""));
51
51
  };
52
52
  /** Creates a document and appends it as the last child of parent. */
53
- const add = (id, title, parent, filename) => {
53
+ const add = (id, title, parent, filename, placement) => {
54
54
  if (!title) {
55
55
  return { error: "title is required", status: 400 };
56
56
  }
57
57
  if (!isDocId(id)) {
58
58
  return { error: "id must be lowercase alphanumerics and hyphens", status: 400 };
59
59
  }
60
- if (filename !== undefined && !isDocumentFileName(filename))
60
+ if (filename !== undefined &&
61
+ !(placement
62
+ ? managedFile(filename) && filename.endsWith(".md")
63
+ : isDocumentFileName(filename)))
61
64
  return { error: "Enter a file name ending in .md", status: 400 };
62
65
  if (existsSync(docPath(id))) {
63
66
  return { error: `id "${id}" is already in use`, status: 409 };
@@ -66,44 +69,62 @@ export const createDocOps = (root) => {
66
69
  if (isOpError(loaded)) {
67
70
  return loaded;
68
71
  }
69
- if (loaded.format) {
70
- const file = loaded.files?.defaultLayout !== false
71
- ? defaultFilePath(filename ?? `${id}.md`)
72
- : `content/${filename ?? `${id}.md`}`;
73
- id = fileDocumentId(file);
72
+ const name = filename ?? `${id}.md`;
73
+ const source = placement
74
+ ? name
75
+ : loaded.files?.defaultLayout !== false
76
+ ? defaultFilePath(name)
77
+ : `content/${name}`;
78
+ const existing = flattenTree(loaded.tree).find((node) => isContentPage(node) && docFile(node.id, loaded.files) === source);
79
+ if (existing && placement)
80
+ return { error: "This file already has a page", status: 409 };
81
+ if (loaded.format)
82
+ id = fileDocumentId(source);
83
+ if (loaded.format || filename !== undefined || loaded.files?.defaultLayout !== false) {
74
84
  loaded.files ??= parseFileLayout({});
75
- loaded.files.documents[id] = file;
85
+ loaded.files.documents[id] = source;
76
86
  }
77
- // Only the nested manifest stores document titles.
78
- const tree = insertDoc(loaded.tree, id, parent, { title });
87
+ // Legacy ID-based additions keep their compact tree entry until explicitly renamed.
88
+ const tree = insertDoc(loaded.tree, id, parent, loaded.format || placement ? { title } : undefined);
79
89
  if (!tree) {
80
90
  return { error: `duplicate id "${id}" or missing parent "${parent}"`, status: 409 };
81
91
  }
82
- if (!loaded.format && (filename !== undefined || loaded.files?.defaultLayout !== false)) {
83
- loaded.files ??= parseFileLayout({});
84
- loaded.files.documents[id] = loaded.files.defaultLayout
85
- ? defaultFilePath(filename ?? `${id}.md`)
86
- : `content/${filename}`;
87
- }
88
92
  const invalidPath = pathError(tree, loaded);
89
93
  if (invalidPath)
90
94
  return invalidPath;
91
- const file = textfilePath(root, docFile(id, loaded.files));
92
- if (existsSync(file))
93
- return { error: "File already exists", status: 409 };
94
- mkdirSync(dirname(file), { recursive: true });
95
- writeFileSync(file, "", { flag: "wx" });
96
- writeManifest(root, tree, loaded);
95
+ let created;
96
+ try {
97
+ const file = placement ? projectFilePath(root, source) : textfilePath(root, source);
98
+ if (existsSync(file)) {
99
+ if (!placement)
100
+ return { error: "File already exists", status: 409 };
101
+ readTextfile(root, source);
102
+ }
103
+ else {
104
+ if (placement === "reference")
105
+ return { error: "File no longer exists", status: 404 };
106
+ mkdirSync(dirname(file), { recursive: true });
107
+ writeFileSync(file, "", { flag: "wx" });
108
+ created = file;
109
+ }
110
+ writeManifest(root, tree, loaded);
111
+ }
112
+ catch (error) {
113
+ if (created)
114
+ unlinkSync(created);
115
+ return { error: error instanceof Error ? error.message : String(error), status: 400 };
116
+ }
97
117
  return { id };
98
118
  };
99
- const addFile = (name, title, parent) => {
100
- if (!isDocumentFileName(name))
119
+ const addFile = (name, title, parent, placement) => {
120
+ if (!(placement ? managedFile(name) && name.endsWith(".md") : isDocumentFileName(name)))
101
121
  return { error: "Enter a file name ending in .md", status: 400 };
102
122
  const loaded = loadTree();
103
123
  if (isOpError(loaded))
104
124
  return loaded;
105
125
  const ids = new Set(flattenTree(loaded.tree).map((doc) => doc.id));
106
- const stem = name
126
+ const stem = posix
127
+ .basename(name)
107
128
  .slice(0, -3)
108
129
  .normalize("NFKD")
109
130
  .toLowerCase()
@@ -112,7 +133,7 @@ export const createDocOps = (root) => {
112
133
  let id = stem;
113
134
  for (let index = 2; ids.has(id) || existsSync(docPath(id)); index++)
114
135
  id = `${stem}-${index}`;
115
- return add(id, title, parent, name);
136
+ return add(id, title, parent, name, placement);
116
137
  };
117
138
  const addSubformat = (ext, title, parent) => {
118
139
  const loaded = loadTree();
@@ -328,89 +349,11 @@ export const createDocOps = (root) => {
328
349
  writeFileSync(textfilePath(root, file), body);
329
350
  return { id: newId, updatedRefs };
330
351
  };
331
- /**
332
- * Removes the doc from the manifest and deletes the .md (and icon). Docs with children are
333
- * not deleted. If other docs reference it via file links, refuses without force and returns
334
- * referencedBy. parent = the deleted doc's parent.
335
- */
336
352
  const remove = (id, force = false) => {
337
- const manifest = loadTree();
338
- if (isOpError(manifest))
339
- return manifest;
340
- const selected = flattenTree(manifest.tree).find((node) => node.id === id);
341
- if (selected?.root)
342
- return { error: "The root document cannot be removed", status: 409 };
343
- if (selected?.origin)
344
- return {
345
- error: "Edit the included document's own manifest to change its structure",
346
- status: 409,
347
- };
348
- const page = flattenTree(manifest.tree).find((node) => node.id === id && !isContentPage(node));
349
- if (page) {
350
- const tree = removeDoc(manifest.tree, id);
351
- if (!tree)
352
- return { error: "doc has children (move / delete them first)", status: 409 };
353
- const removedIcon = ownsDocIcon(id, manifest) ? iconPath(id) : undefined;
354
- if (manifest.files?.icons)
355
- delete manifest.files.icons[id];
356
- writeManifest(root, tree, manifest);
357
- if (removedIcon && existsSync(removedIcon))
358
- unlinkSync(removedIcon);
359
- return { parent: page.parent, danglingRefs: 0 };
360
- }
361
- const target = existingDoc(id);
362
- if (isOpError(target)) {
363
- return target;
364
- }
365
- const loaded = loadTree();
366
- if (isOpError(loaded)) {
367
- return loaded;
368
- }
369
- const tree = removeDoc(loaded.tree, id);
370
- if (!tree) {
371
- return { error: "doc has children (move / delete them first)", status: 409 };
372
- }
373
- const file = docFile(id, loaded.files);
374
- let removed;
375
- let referencedBy;
376
- try {
377
- removed = [
378
- file,
379
- ...translationLanguages(root).map((lang) => translationFile(file, lang)),
380
- ];
381
- for (const file of removed)
382
- textfilePath(root, file);
383
- referencedBy = referencingFiles(id, removed);
384
- }
385
- catch (error) {
386
- return { error: String(error), status: 409 };
387
- }
388
- if (referencedBy.length > 0 && !force) {
389
- return {
390
- error: `${referencedBy.length} doc(s) reference it via file links`,
391
- status: 409,
392
- referencedBy,
393
- };
394
- }
395
- const parent = flattenTree(loaded.tree).find((n) => n.id === id)?.parent;
396
- const removedPath = docPath(id);
397
- const removedIcon = ownsDocIcon(id, loaded) ? iconPath(id) : undefined;
398
- if (loaded.files) {
399
- delete loaded.files.documents[id];
400
- if (loaded.files.icons)
401
- delete loaded.files.icons[id];
402
- }
403
- writeManifest(root, tree, loaded);
404
- unlinkSync(removedPath);
405
- if (removedIcon && existsSync(removedIcon)) {
406
- unlinkSync(removedIcon);
407
- }
408
- for (const file of removed.slice(1)) {
409
- const path = textfilePath(root, file);
410
- if (existsSync(path))
411
- unlinkSync(path);
412
- }
413
- return { parent, danglingRefs: referencedBy.length };
353
+ const result = removeSidebarEntry(root, id, { files: "delete", force });
354
+ return isOpError(result)
355
+ ? result
356
+ : { parent: result.parent, danglingRefs: result.danglingRefs };
414
357
  };
415
358
  /** Overwrites an existing doc's full raw text. */
416
359
  const write = (id, raw) => {
@@ -14,7 +14,7 @@ import { statSync } from "./host.js";
14
14
  import { assertNotIgnored } from "./ignored-files.js";
15
15
  import { manifestFile, readManifest, sourceOrigin } from "./manifest.js";
16
16
  import { readProjectSkills } from "./skills.js";
17
- import { loadSubformat, parseSubformatRecord, subformatIconSvg, subformatRelations, validateSubformatRecord, } from "./subformats.js";
17
+ import { loadSubformat, parseSubformatRecord, recordSubformat, subformatDirectory, subformatIconSvg, subformatRelations, validateSubformatRecord, } from "./subformats.js";
18
18
  import { parseTermSource } from "./terms.js";
19
19
  import { readTextfile, selectTextfileRange, textfilePath } from "./textfile.js";
20
20
  /** Index authored content, including files not referenced by any document. */
@@ -96,7 +96,7 @@ export const resourceIndex = (root, files, domains = []) => {
96
96
  ...(iconSvg ? { iconSvg } : {}),
97
97
  fields: loaded.fields,
98
98
  template: loaded.template,
99
- defaultFolder: manifest.defaultSubformatFolder,
99
+ defaultFolder: subformatDirectory(manifest, config.ext),
100
100
  records: [],
101
101
  });
102
102
  }
@@ -153,7 +153,7 @@ export const resourceIndex = (root, files, domains = []) => {
153
153
  try {
154
154
  const ref = parseFileEmbed(preview ? target : (target.split(/[?#]/)[0] ?? target));
155
155
  const referencedFile = ref.file.replace(/^(\.\/)+/, "");
156
- if (formatReference(referencedFile) !== undefined)
156
+ if (ref.kind === "toc" || formatReference(referencedFile) !== undefined)
157
157
  return;
158
158
  if (!preview || ref.kind !== "textfile") {
159
159
  collect(referencedFile, source);
@@ -202,7 +202,7 @@ export const resourceIndex = (root, files, domains = []) => {
202
202
  };
203
203
  for (const file of paths) {
204
204
  const format = formats.get(fileExtension(file));
205
- if (format && !(manifest.subformats ?? []).some((item) => item.schema === file)) {
205
+ if (format && recordSubformat(root, manifest, file, domains)) {
206
206
  try {
207
207
  const content = readTextfile(root, file);
208
208
  collect(file);
@@ -0,0 +1,13 @@
1
+ import type { OpError } from "./ops.js";
2
+ export type RootSource = {
3
+ url: string;
4
+ manifest: string;
5
+ kind: "contents" | "markdown" | "url" | "collection";
6
+ revision: string;
7
+ id?: string;
8
+ };
9
+ export declare function rootPageSource(root: string, input?: {
10
+ kind?: unknown;
11
+ url?: unknown;
12
+ revision?: unknown;
13
+ }): RootSource | OpError;
@@ -0,0 +1,96 @@
1
+ import { isSeq, parseDocument } from "yaml";
2
+ import { flattenTree, isContentPage, pageUrlKind } from "../core/content-metadata.js";
3
+ import { docFile } from "../core/files.js";
4
+ import { tocReference } from "../core/toc-library.js";
5
+ import { projectFilePath } from "./files.js";
6
+ import { createHash, existsSync, join, statSync, unlinkSync } from "./host.js";
7
+ import { hasContentsSource, manifestFile, parseManifestText, readManifest } from "./manifest.js";
8
+ import { readTextfile, writeTextfile } from "./textfile.js";
9
+ export function rootPageSource(root, input) {
10
+ try {
11
+ const file = manifestFile(root);
12
+ const raw = existsSync(join(root, file)) ? readTextfile(root, file) : null;
13
+ const manifest = readManifest(root);
14
+ if (manifest.errors.length)
15
+ return { status: 409, error: manifest.errors.join("\n") };
16
+ const node = manifest.tree.find((entry) => entry.root);
17
+ const url = node?.url ?? "";
18
+ const revision = createHash("sha256")
19
+ .update(raw ?? "")
20
+ .digest("hex");
21
+ const kind = node?.library === "toc" || tocReference(url)
22
+ ? "contents"
23
+ : node?.subformat || node?.library || node?.format
24
+ ? "collection"
25
+ : !url
26
+ ? "contents"
27
+ : pageUrlKind(url) === "content"
28
+ ? "markdown"
29
+ : "url";
30
+ if (!input)
31
+ return { url, kind, manifest: file, revision, id: node?.id };
32
+ if (revision !== input.revision)
33
+ return {
34
+ status: 409,
35
+ error: "The manifest changed. Open the root page settings again.",
36
+ };
37
+ if (typeof input.url !== "string")
38
+ throw new Error("Expected a root page source");
39
+ const next = input.url.trim();
40
+ const type = pageUrlKind(next);
41
+ if (!(input.kind === "contents" && (type === "index" || type === "toc")) &&
42
+ !(input.kind === "markdown" && type === "content") &&
43
+ !(input.kind === "url" && ["link", "redirect", "file"].includes(type)))
44
+ throw new Error("Choose a matching root page source");
45
+ const contents = tocReference(next);
46
+ if (contents && !hasContentsSource(manifest, file, contents.file, node?.id))
47
+ throw new Error("Choose a Markdown page or a manifest in this document");
48
+ if (type === "content" &&
49
+ flattenTree(manifest.tree).some((item) => !item.root && isContentPage(item) && docFile(item.id, manifest.files) === next))
50
+ throw new Error("This Markdown file already has a sidebar entry");
51
+ const path = type === "content" || type === "file" ? projectFilePath(root, next) : undefined;
52
+ if (path && existsSync(path) && type === "content")
53
+ readTextfile(root, next);
54
+ if (path && type === "file" && !statSync(path, { throwIfNoEntry: false })?.isFile())
55
+ throw new Error("Project file not found");
56
+ const doc = parseDocument(raw ?? 'document: {url: ""}');
57
+ if (doc.has("document")) {
58
+ for (const key of ["subformat", "library", "format"])
59
+ doc.deleteIn(["document", key]);
60
+ doc.setIn(["document", "url"], next);
61
+ }
62
+ else {
63
+ if (isSeq(doc.contents) || !doc.contents) {
64
+ const children = doc.contents;
65
+ doc.contents = doc.createNode({ docs: [] });
66
+ if (children)
67
+ doc.set("docs", children);
68
+ }
69
+ doc.set("root_url", next);
70
+ }
71
+ const content = doc.toString({ lineWidth: 0 });
72
+ const parsed = parseManifestText(content, file);
73
+ if (parsed.errors.length)
74
+ throw new Error(parsed.errors.join("\n"));
75
+ const created = path && type === "content" && !existsSync(path) && writeTextfile(root, next, "", null);
76
+ try {
77
+ if (!writeTextfile(root, file, content, raw))
78
+ throw new Error("The manifest changed. Open the root page settings again.");
79
+ }
80
+ catch (error) {
81
+ if (created && path && readTextfile(root, next) === "")
82
+ unlinkSync(path);
83
+ throw error;
84
+ }
85
+ return {
86
+ kind: input.kind,
87
+ url: next,
88
+ manifest: file,
89
+ id: parsed.tree[0]?.id,
90
+ revision: createHash("sha256").update(content).digest("hex"),
91
+ };
92
+ }
93
+ catch (error) {
94
+ return { status: 400, error: error instanceof Error ? error.message : String(error) };
95
+ }
96
+ }
@@ -0,0 +1,63 @@
1
+ import type { OpError } from "./ops.js";
2
+ type Scope = {
3
+ ids: string[];
4
+ files: string[];
5
+ paths: string[];
6
+ };
7
+ type RemovalPage = Scope & {
8
+ id: string;
9
+ parent?: string;
10
+ title: string;
11
+ };
12
+ export type RemovalPreview = {
13
+ revision: string;
14
+ structure: string;
15
+ hasChildren: boolean;
16
+ entry: Scope;
17
+ branch: Scope;
18
+ pages: RemovalPage[];
19
+ };
20
+ export type RemovalOptions = {
21
+ children?: "promote" | "remove";
22
+ selected?: string[];
23
+ files: "keep" | "delete" | string[];
24
+ revision?: string;
25
+ confirmation?: string;
26
+ force?: boolean;
27
+ };
28
+ type CountedPaths = {
29
+ count: number;
30
+ paths: string[];
31
+ };
32
+ export type RemovalSummary = {
33
+ files: CountedPaths & {
34
+ uncommittedChanges: CountedPaths;
35
+ };
36
+ references: {
37
+ count: number;
38
+ entries: {
39
+ id: string;
40
+ title: string;
41
+ path: string;
42
+ }[];
43
+ };
44
+ referencedBy: CountedPaths;
45
+ };
46
+ export type RemovalReview = {
47
+ revision: string;
48
+ confirmation: string;
49
+ summary: RemovalSummary;
50
+ };
51
+ export type RemovalResult = {
52
+ parent?: string;
53
+ path: string;
54
+ editorPath?: string;
55
+ removed: Scope;
56
+ moved: Record<string, string>;
57
+ danglingRefs: number;
58
+ summary?: RemovalSummary;
59
+ };
60
+ export declare function previewSidebarRemoval(root: string, id: string): RemovalPreview | OpError;
61
+ export declare function reviewSidebarRemoval(root: string, id: string, options: RemovalOptions, changedTrackedFiles: ReadonlySet<string>): RemovalReview | OpError;
62
+ export declare function removeSidebarEntry(root: string, id: string, options: RemovalOptions, changedTrackedFiles?: ReadonlySet<string>): RemovalResult | OpError;
63
+ export {};