@dooc-dev/dooc 0.0.28 → 0.0.30

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/from-mdast.js +12 -1
  13. package/dist/engine/compiler/icons.d.ts +7 -7
  14. package/dist/engine/compiler/icons.js +35 -37
  15. package/dist/engine/compiler/manifest.d.ts +1 -0
  16. package/dist/engine/compiler/manifest.js +25 -0
  17. package/dist/engine/compiler/ops.d.ts +2 -2
  18. package/dist/engine/compiler/ops.js +55 -112
  19. package/dist/engine/compiler/resource-index.js +4 -4
  20. package/dist/engine/compiler/root-page.d.ts +13 -0
  21. package/dist/engine/compiler/root-page.js +96 -0
  22. package/dist/engine/compiler/sidebar-removal.d.ts +63 -0
  23. package/dist/engine/compiler/sidebar-removal.js +317 -0
  24. package/dist/engine/compiler/subformats.d.ts +3 -0
  25. package/dist/engine/compiler/subformats.js +126 -32
  26. package/dist/engine/core/blocks.d.ts +5 -0
  27. package/dist/engine/core/content-metadata.d.ts +9 -4
  28. package/dist/engine/core/content-metadata.js +100 -16
  29. package/dist/engine/core/file-embed.d.ts +2 -1
  30. package/dist/engine/core/file-embed.js +4 -0
  31. package/dist/engine/core/files.d.ts +1 -0
  32. package/dist/engine/core/files.js +6 -1
  33. package/dist/engine/core/format-collections.js +2 -2
  34. package/dist/engine/core/formats.d.ts +1 -1
  35. package/dist/engine/core/formats.js +1 -1
  36. package/dist/engine/core/html.d.ts +4 -1
  37. package/dist/engine/core/html.js +13 -6
  38. package/dist/engine/core/icons.d.ts +7 -0
  39. package/dist/engine/core/icons.js +38 -0
  40. package/dist/engine/core/subformats.d.ts +2 -1
  41. package/dist/engine/core/subformats.js +6 -1
  42. package/dist/engine/core/toc-library.d.ts +5 -0
  43. package/dist/engine/core/toc-library.js +27 -0
  44. package/dist/frontend/document-application.d.ts +5 -2
  45. package/dist/frontend/document-application.js +477 -189
  46. package/dist/frontend/edit-dialog.d.ts +1 -0
  47. package/dist/frontend/edit-dialog.js +12 -8
  48. package/dist/frontend/file-references.js +1 -1
  49. package/dist/frontend/locales/eng.json +63 -1
  50. package/dist/frontend/locales/jpn.json +63 -1
  51. package/dist/frontend/locales/zho.json +63 -1
  52. package/dist/frontend/page-jump.js +17 -10
  53. package/dist/frontend/resize.js +38 -12
  54. package/dist/frontend/resource-download.js +7 -1
  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/frontend/toc-ui.js +13 -0
  60. package/dist/manifest.global.js +193 -192
  61. package/dist/mcp-relay.mjs +8 -4
  62. package/dist/plugins.global.js +49 -49
  63. package/dist/server/cli.js +12 -0
  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 +261 -202
  88. package/package.json +2 -2
@@ -0,0 +1,317 @@
1
+ import { isSeq, parseDocument } from "yaml";
2
+ import { findNode, flattenTree, isContentPage, pageUrlKind, serializeManifest, } from "../core/content-metadata.js";
3
+ import { docFile, docIconFile } from "../core/files.js";
4
+ import { docPath, documentPathErrors } from "../core/routing.js";
5
+ import { managedFile, projectFiles, rebaseFileLinks, rewriteFileLinks } from "./files.js";
6
+ import { createHash, dirname, existsSync, join, lstatSync, randomUUID, readFileSync, realpathSync, renameSync, unlinkSync, } from "./host.js";
7
+ import { ownsDocIcon } from "./icons.js";
8
+ import { assertNotIgnored } from "./ignored-files.js";
9
+ import { translationFile, translationFiles, translationLanguages } from "./locales.js";
10
+ import { manifestFile, readManifest, sourceOrigin } from "./manifest.js";
11
+ import { isRemoteSourceFile } from "./remote-manifests.js";
12
+ import { readTextfile, textfilePath, writeTextfile } from "./textfile.js";
13
+ const error = (message, status = 409) => ({
14
+ error: message,
15
+ status,
16
+ });
17
+ function inspect(root, id) {
18
+ const file = manifestFile(root);
19
+ const raw = existsSync(join(root, file)) ? readTextfile(root, file) : "";
20
+ const manifest = readManifest(root);
21
+ if (manifest.errors.length)
22
+ return error(manifest.errors.join(" / "));
23
+ const entries = flattenTree(manifest.tree);
24
+ const node = findNode(manifest.tree, id);
25
+ if (!node)
26
+ return entries.some((entry) => entry.id === id)
27
+ ? error("Edit the included document's own manifest to change its structure")
28
+ : error("Sidebar entry not found", 404);
29
+ if (node.root)
30
+ return error("The root document cannot be removed");
31
+ const langs = translationLanguages(root);
32
+ const localSource = (entry) => isContentPage(entry)
33
+ ? docFile(entry.id, manifest.files)
34
+ : entry.url && pageUrlKind(entry.url) === "file"
35
+ ? entry.url
36
+ : undefined;
37
+ const assets = [
38
+ manifest.icon,
39
+ manifest.licence,
40
+ ...Object.values(manifest.themeIcons ?? {}),
41
+ ...Object.values(manifest.files?.icons ?? {}),
42
+ ...(manifest.includedAssets ?? []),
43
+ ...(manifest.skills ?? []),
44
+ ...(manifest.subformats ?? []).flatMap((format) => [
45
+ format.icon,
46
+ format.schema,
47
+ ...(format.files ?? []),
48
+ ]),
49
+ ...[manifest.formats, ...Object.values(manifest.includedFormats ?? {})].flatMap((settings) => Object.values(settings ?? {}).flatMap((format) => format.files ?? [])),
50
+ ];
51
+ const protectedSources = (ids) => new Set([
52
+ ...assets,
53
+ ...entries.filter((entry) => !ids.has(entry.id) || entry.origin).map(localSource),
54
+ ]);
55
+ const scope = (nodes, protectedSourcesOfBranch) => {
56
+ const removed = flattenTree(nodes);
57
+ const ids = new Set(removed.map((entry) => entry.id));
58
+ const protectedFiles = protectedSourcesOfBranch ?? protectedSources(ids);
59
+ const files = new Set();
60
+ for (const entry of removed) {
61
+ if (entry.origin || entry.resolved)
62
+ continue;
63
+ const source = localSource(entry);
64
+ const paths = [];
65
+ if (source &&
66
+ managedFile(source) &&
67
+ !isRemoteSourceFile(source) &&
68
+ !protectedFiles.has(source)) {
69
+ paths.push(source);
70
+ if (isContentPage(entry))
71
+ paths.push(...langs.map((lang) => translationFile(source, lang)));
72
+ }
73
+ if (ownsDocIcon(entry.id, manifest))
74
+ paths.push(docIconFile(entry.id, manifest.files));
75
+ for (const path of paths)
76
+ if (!protectedFiles.has(path) && existsSync(join(root, path)))
77
+ files.add(path);
78
+ }
79
+ return {
80
+ ids: [...ids],
81
+ files: [...files],
82
+ paths: removed.map((entry) => docPath(entries, entry.id)),
83
+ };
84
+ };
85
+ const entry = scope([{ ...node, children: [] }]);
86
+ const branch = node.children.length ? scope([node]) : entry;
87
+ const protectedFiles = protectedSources(new Set(branch.ids));
88
+ const pages = [];
89
+ const nodes = new Map();
90
+ const visit = (item, parent) => {
91
+ nodes.set(item.id, item);
92
+ pages.push({
93
+ id: item.id,
94
+ parent,
95
+ title: item.title ??
96
+ item.resolved?.title ??
97
+ item.name ??
98
+ localSource(item)?.split("/").pop()?.replace(/\.md$/, "") ??
99
+ item.id,
100
+ ...scope([{ ...item, children: [] }], protectedFiles),
101
+ });
102
+ for (const child of item.children)
103
+ visit(child, item.id);
104
+ };
105
+ visit(node);
106
+ const structure = createHash("sha256").update(raw).update(JSON.stringify(branch)).digest("hex");
107
+ const hash = createHash("sha256").update(structure);
108
+ for (const source of branch.files) {
109
+ const path = textfilePath(root, source);
110
+ if (!lstatSync(path).isFile() || path !== join(realpathSync(root), source))
111
+ return error(`Expected a regular project file: ${source}`);
112
+ hash.update(createHash("sha256").update(readFileSync(path)).digest("hex"));
113
+ }
114
+ return {
115
+ file,
116
+ raw,
117
+ manifest,
118
+ entries,
119
+ node,
120
+ nodes,
121
+ scope,
122
+ preview: {
123
+ entry,
124
+ branch,
125
+ pages,
126
+ structure,
127
+ revision: hash.digest("hex"),
128
+ hasChildren: !!node.children.length,
129
+ },
130
+ };
131
+ }
132
+ export function previewSidebarRemoval(root, id) {
133
+ try {
134
+ const plan = inspect(root, id);
135
+ return "error" in plan ? plan : plan.preview;
136
+ }
137
+ catch (cause) {
138
+ return error(String(cause));
139
+ }
140
+ }
141
+ function planRemoval(root, id, options, forReview = false) {
142
+ try {
143
+ const plan = inspect(root, id);
144
+ if ("error" in plan)
145
+ return plan;
146
+ const { manifest, node, preview } = plan;
147
+ if (options.selected === undefined && !options.children && node.children.length)
148
+ return error("Choose what to do with the children of this entry");
149
+ const selected = new Set(options.selected ?? (options.children === "remove" ? plan.nodes.keys() : [id]));
150
+ if (!selected.size || [...selected].some((key) => !plan.nodes.has(key)))
151
+ return error("Select pages from the reviewed sidebar tree.", 400);
152
+ const removed = plan.scope([...plan.nodes.values()]
153
+ .filter((item) => selected.has(item.id))
154
+ .map((item) => ({ ...item, children: [] })));
155
+ const files = Array.isArray(options.files)
156
+ ? [...new Set(options.files)]
157
+ : options.files === "delete"
158
+ ? removed.files
159
+ : [];
160
+ const eligible = new Set(removed.files);
161
+ if (files.some((path) => !eligible.has(path)))
162
+ return error("Select files from the reviewed sidebar tree.", 400);
163
+ if (options.revision !== undefined &&
164
+ preview.revision !== options.revision &&
165
+ !((forReview || !files.length) && preview.structure === options.revision))
166
+ return error("The sidebar or its files changed. Review the removal again.");
167
+ const retain = (nodes) => nodes.flatMap((item) => {
168
+ const children = retain(item.children);
169
+ return selected.has(item.id) ? children : [{ ...item, children }];
170
+ });
171
+ const next = retain(manifest.tree);
172
+ const remaining = flattenTree(next);
173
+ const issues = documentPathErrors(remaining);
174
+ if (issues.length)
175
+ return error(issues.join("\n"));
176
+ const changes = new Map(files.map((path) => [path, `removed/${path}`]));
177
+ const referencedBy = !files.length
178
+ ? []
179
+ : [
180
+ ...new Set([
181
+ ...projectFiles(root).map((file) => file.path),
182
+ ...translationFiles(root),
183
+ ]),
184
+ ]
185
+ .filter((path) => /\.(md|callouth)$/.test(path) && !changes.has(path))
186
+ .filter((path) => {
187
+ const text = rebaseFileLinks(readFileSync(textfilePath(root, path), "utf8"), sourceOrigin(manifest, path));
188
+ return rewriteFileLinks(text, changes) !== text;
189
+ })
190
+ .sort();
191
+ return { ...plan, selected, removed: { ...removed, files }, next, remaining, referencedBy };
192
+ }
193
+ catch (cause) {
194
+ return error(cause instanceof Error ? cause.message : String(cause));
195
+ }
196
+ }
197
+ function reviewOf(plan, changedTrackedFiles) {
198
+ const files = new Set(plan.removed.files);
199
+ const entries = plan.preview.pages
200
+ .filter((page) => plan.selected.has(page.id) && !page.files.some((path) => files.has(path)))
201
+ .map((page) => ({ id: page.id, title: page.title, path: page.paths[0] ?? "" }));
202
+ const counted = (paths) => ({ count: paths.length, paths });
203
+ const summary = {
204
+ files: {
205
+ ...counted([...files]),
206
+ uncommittedChanges: counted([...files].filter((file) => changedTrackedFiles.has(file))),
207
+ },
208
+ references: { count: entries.length, entries },
209
+ referencedBy: counted(plan.referencedBy),
210
+ };
211
+ const revision = files.size ? plan.preview.revision : plan.preview.structure;
212
+ const confirmation = createHash("sha256")
213
+ .update(JSON.stringify([revision, plan.removed.ids, summary]))
214
+ .digest("hex");
215
+ return { revision, confirmation, summary };
216
+ }
217
+ export function reviewSidebarRemoval(root, id, options, changedTrackedFiles) {
218
+ const plan = planRemoval(root, id, options, true);
219
+ return "error" in plan ? plan : reviewOf(plan, changedTrackedFiles);
220
+ }
221
+ export function removeSidebarEntry(root, id, options, changedTrackedFiles) {
222
+ try {
223
+ const plan = planRemoval(root, id, options);
224
+ if ("error" in plan)
225
+ return plan;
226
+ const { manifest, file, raw, entries, selected, removed, next, remaining, referencedBy } = plan;
227
+ const { files } = removed;
228
+ const review = changedTrackedFiles && reviewOf(plan, changedTrackedFiles);
229
+ if (options.confirmation !== undefined && options.confirmation !== review?.confirmation)
230
+ return error("The deletion summary changed. Review the deletion again.");
231
+ if (referencedBy.length && !options.force && options.confirmation === undefined)
232
+ return {
233
+ ...error("Other documents reference these files"),
234
+ referencedBy: referencedBy.map((path) => path.replace(/^content\//, "")),
235
+ };
236
+ const parent = entries.find((entry) => entry.id === id)?.parent;
237
+ const editor = remaining.find((entry) => entry.id === parent && isContentPage(entry)) ??
238
+ remaining.find(isContentPage);
239
+ const fallback = remaining.find((entry) => entry.id === parent &&
240
+ (!entry.url || ["content", "index", "file"].includes(pageUrlKind(entry.url)))) ??
241
+ editor ??
242
+ remaining.find((entry) => !entry.url || pageUrlKind(entry.url) === "index");
243
+ const moved = Object.fromEntries(remaining.flatMap((entry) => {
244
+ const before = docPath(entries, entry.id);
245
+ const after = docPath(remaining, entry.id);
246
+ return before === after ? [] : [[before, after]];
247
+ }));
248
+ let yaml;
249
+ if (manifest.format) {
250
+ const doc = parseDocument(raw);
251
+ const keys = manifest.format === "document" ? ["document", "children"] : ["center_contents"];
252
+ const update = (siblings, path) => {
253
+ const list = doc.getIn(path, true);
254
+ if (!isSeq(list) || list.items.length !== siblings.length)
255
+ throw new Error("Sidebar entries changed");
256
+ for (const [i, item] of [...siblings.entries()].reverse()) {
257
+ const children = [
258
+ ...path,
259
+ i,
260
+ ...(manifest.format === "document" ? ["document"] : []),
261
+ "children",
262
+ ];
263
+ if (item.children.length)
264
+ update(item.children, children);
265
+ if (selected.has(item.id)) {
266
+ const kept = doc.getIn(children, true);
267
+ list.items.splice(i, 1, ...(isSeq(kept) ? kept.items : []));
268
+ }
269
+ }
270
+ };
271
+ update(manifest.tree[0]?.root ? manifest.tree[0].children : manifest.tree, keys);
272
+ yaml = doc.toString({ lineWidth: 0 });
273
+ }
274
+ else {
275
+ for (const key of removed.ids)
276
+ if (manifest.files) {
277
+ delete manifest.files.documents[key];
278
+ if (manifest.files.icons)
279
+ delete manifest.files.icons[key];
280
+ }
281
+ yaml = serializeManifest(next, manifest);
282
+ }
283
+ const staged = [];
284
+ try {
285
+ for (const source of files) {
286
+ const path = textfilePath(root, source);
287
+ assertNotIgnored(root, source);
288
+ if (path !== join(realpathSync(root), source) || !lstatSync(path).isFile())
289
+ throw new Error(`Expected a regular project file: ${source}`);
290
+ const temp = join(dirname(path), `.remove-${randomUUID()}.tmp`);
291
+ renameSync(path, temp);
292
+ staged.push([path, temp]);
293
+ }
294
+ if (!writeTextfile(root, file, yaml, raw))
295
+ throw new Error("The manifest changed. Review the removal again.");
296
+ }
297
+ catch (cause) {
298
+ for (const [path, temp] of staged.reverse())
299
+ renameSync(temp, path);
300
+ throw cause;
301
+ }
302
+ for (const [, temp] of staged)
303
+ unlinkSync(temp);
304
+ return {
305
+ parent,
306
+ path: fallback ? docPath(remaining, fallback.id) : "/_manifest",
307
+ editorPath: editor && docPath(remaining, editor.id),
308
+ removed,
309
+ moved,
310
+ danglingRefs: referencedBy.length,
311
+ ...(review && { summary: review.summary }),
312
+ };
313
+ }
314
+ catch (cause) {
315
+ return error(cause instanceof Error ? cause.message : String(cause));
316
+ }
317
+ }
@@ -1,4 +1,5 @@
1
1
  import type { ValidateFunction } from "ajv";
2
+ import { type ParsedManifest } from "../core/content-metadata.js";
2
3
  import type { SchemaModel } from "../core/schema-graph.js";
3
4
  import { type Subformat, type SubformatCollection, type SubformatField } from "../core/subformats.js";
4
5
  export { compileSubformatSchema } from "./subformat-schema.js";
@@ -9,6 +10,8 @@ export interface LoadedSubformat extends Subformat {
9
10
  }
10
11
  /** Markup of a subformat's configured icon; throws when the file is not a usable SVG. */
11
12
  export declare const subformatIconSvg: (root: string, config: Subformat) => string | undefined;
13
+ export declare const subformatDirectory: (manifest: ParsedManifest, ext: string) => string | undefined;
14
+ export declare const recordSubformat: (root: string, manifest: ParsedManifest, file: string, domains?: readonly string[]) => Subformat | undefined;
12
15
  export declare const loadSubformat: (root: string, config: Subformat, domains?: readonly string[]) => LoadedSubformat;
13
16
  export declare const validateSubformatRecord: (format: LoadedSubformat, data: Record<string, unknown>) => void;
14
17
  export declare const isSubformatSchemaFile: (root: string, file: string, domains?: readonly string[]) => boolean;
@@ -1,13 +1,14 @@
1
1
  import { stringify as stringifyToml } from "smol-toml";
2
2
  import { Document, isSeq, parseDocument, stringify as stringifyYaml, visit } from "yaml";
3
- import { flattenTree, subformatPageId } from "../core/content-metadata.js";
3
+ import { flattenTree, isManifestFile, subformatPageId, } from "../core/content-metadata.js";
4
4
  import { fileExtension } from "../core/files.js";
5
+ import { formatTraits, inFormatFolder } from "../core/format-collections.js";
5
6
  import { schemaObject } from "../core/schema-fields.js";
6
7
  import { schemaResolver } from "../core/schema-refs.js";
7
8
  import { parseSubformatRecord, setSubformatValue } from "../core/subformat-record.js";
8
9
  import { parseSubformats, SUBFORMAT_SCHEMA_TEMPLATE, } from "../core/subformats.js";
9
- import { filesSnapshot, managedFile } from "./files.js";
10
- import { existsSync, isDeepStrictEqual, pathToFileURL } from "./host.js";
10
+ import { filesSnapshot, managedFile, projectFilePath } from "./files.js";
11
+ import { existsSync, fileURLToPath, isDeepStrictEqual, posix, realpathSync, relative, unlinkSync, } from "./host.js";
11
12
  import { squareSvg } from "./icons.js";
12
13
  import { manifestFile, parseManifestText, readManifest } from "./manifest.js";
13
14
  import { compileSubformatSchema } from "./subformat-schema.js";
@@ -22,6 +23,71 @@ export const subformatIconSvg = (root, config) => {
22
23
  throw new Error(`${config.icon}: expected an SVG with a viewBox or width and height`);
23
24
  return svg;
24
25
  };
26
+ const schemaPath = (manifest, file) => /\.schema\.json$/i.test(file) || !!manifest.subformats?.some((type) => type.schema === file);
27
+ const schemaDependencies = new WeakMap();
28
+ const schemaFiles = (root, manifest, domains) => {
29
+ let scopes = schemaDependencies.get(manifest);
30
+ if (!scopes) {
31
+ scopes = new Map();
32
+ schemaDependencies.set(manifest, scopes);
33
+ }
34
+ const key = JSON.stringify(domains);
35
+ let files = scopes.get(key);
36
+ if (files)
37
+ return files;
38
+ files = new Set();
39
+ const dir = realpathSync(root);
40
+ for (const { schema } of manifest.subformats ?? []) {
41
+ try {
42
+ const { dependencies } = compileSubformatSchema(readTextfile(root, schema), {
43
+ root,
44
+ file: schema,
45
+ domains,
46
+ });
47
+ for (const uri of dependencies.keys())
48
+ if (uri.startsWith("file:"))
49
+ files.add(relative(dir, fileURLToPath(uri)).replaceAll("\\", "/"));
50
+ }
51
+ catch {
52
+ /* The schema's own diagnostics report a broken dependency. */
53
+ }
54
+ }
55
+ scopes.set(key, files);
56
+ return files;
57
+ };
58
+ export const subformatDirectory = (manifest, ext) => manifest.formats?.[ext]?.folders?.[0] ??
59
+ Object.values(manifest.includedFormats ?? {}).find((settings) => settings[ext]?.folders?.length)?.[ext]?.folders?.[0] ??
60
+ manifest.includedRecordSources?.[ext]?.defaultFolder ??
61
+ manifest.includedRecordSources?.[ext]?.directory ??
62
+ manifest.defaultSubformatFolder ??
63
+ manifest.files?.uploadDirectory;
64
+ export const recordSubformat = (root, manifest, file, domains = []) => {
65
+ const ext = fileExtension(file);
66
+ const type = manifest.subformats?.find((format) => format.ext === ext);
67
+ if (!type ||
68
+ isManifestFile(file.split("/").at(-1) ?? "") ||
69
+ schemaPath(manifest, file) ||
70
+ schemaFiles(root, manifest, domains).has(file))
71
+ return;
72
+ const sources = [manifest.formats, ...Object.values(manifest.includedFormats ?? {})].flatMap((settings) => settings?.[ext] ?? []);
73
+ if (type.files?.includes(file) || sources.some((source) => source.files?.includes(file)))
74
+ return type;
75
+ const owner = manifest.includedRecordSources?.[ext];
76
+ const folder = owner ? owner.defaultFolder : manifest.defaultSubformatFolder;
77
+ const folders = sources.flatMap((source) => source.folders ?? []);
78
+ if (folder)
79
+ folders.push(folder);
80
+ if (folder || sources.some((source) => source.files || source.folders))
81
+ return folders.some((path) => inFormatFolder(file, path)) ? type : undefined;
82
+ if (owner && !inFormatFolder(file, owner.directory))
83
+ return;
84
+ if (formatTraits(ext).length ||
85
+ ["json", "yaml", "yml", "toml", "log", "lock", "ini", "conf"].includes(ext))
86
+ return inFormatFolder(file, posix.join(owner?.directory ?? ".", `files/${ext}`))
87
+ ? type
88
+ : undefined;
89
+ return type;
90
+ };
25
91
  export const loadSubformat = (root, config, domains = []) => {
26
92
  const content = readTextfile(root, config.schema);
27
93
  const { schema, validate, context } = compileSubformatSchema(content, {
@@ -33,9 +99,11 @@ export const loadSubformat = (root, config, domains = []) => {
33
99
  // shortcut: controls use top-level properties and refs; extend extraction for composed schemas.
34
100
  const recordFiles = (ext) => {
35
101
  try {
102
+ const manifest = readManifest(root);
36
103
  return filesSnapshot(root)
37
104
  .files.map((file) => file.path)
38
- .filter((file) => fileExtension(file) === ext && file !== config.schema);
105
+ .filter((file) => fileExtension(file) === ext &&
106
+ recordSubformat(root, manifest, file, domains)?.ext === ext);
39
107
  }
40
108
  catch {
41
109
  // Without a readable workspace the field stays a plain value.
@@ -122,30 +190,16 @@ export const validateSubformatRecord = (format, data) => {
122
190
  .join("; "));
123
191
  };
124
192
  export const isSubformatSchemaFile = (root, file, domains = []) => {
125
- const configs = readManifest(root).subformats ?? [];
126
- if (/\.schema\.json$/i.test(file) ||
127
- configs.some((config) => config.schema === file.replace(/^(\.\/)+/, "")))
128
- return true;
129
- const uri = pathToFileURL(textfilePath(root, file)).href;
130
- return configs.some((config) => {
131
- try {
132
- return Object.hasOwn(compileSubformatSchema(readTextfile(root, config.schema), {
133
- root,
134
- file: config.schema,
135
- domains,
136
- }).context.schemas, uri);
137
- }
138
- catch {
139
- // A broken referring schema must not prevent opening a file for repair.
140
- return false;
141
- }
142
- });
193
+ const manifest = readManifest(root);
194
+ const path = file.replace(/^(\.\/)+/, "");
195
+ return schemaPath(manifest, path) || schemaFiles(root, manifest, domains).has(path);
143
196
  };
144
197
  export const validateSubformatFile = (root, file, content, domains = []) => {
145
- const configs = readManifest(root).subformats;
146
- if (isSubformatSchemaFile(root, file, domains))
198
+ if (isSubformatSchemaFile(root, file, domains)) {
147
199
  compileSubformatSchema(content, { root, file, domains });
148
- const config = configs?.find((format) => format.ext === fileExtension(file));
200
+ return;
201
+ }
202
+ const config = recordSubformat(root, readManifest(root), file, domains);
149
203
  if (!config)
150
204
  return;
151
205
  if (!filesSnapshot(root).files.some((file) => file.path === config.schema))
@@ -350,7 +404,7 @@ export const subformatResponse = (root, input, domains = []) => {
350
404
  iconSvg,
351
405
  fields: loaded.fields,
352
406
  template: loaded.template,
353
- defaultFolder: manifest.defaultSubformatFolder,
407
+ defaultFolder: subformatDirectory(manifest, config.ext),
354
408
  records: [],
355
409
  change: "added",
356
410
  },
@@ -360,13 +414,53 @@ export const subformatResponse = (root, input, domains = []) => {
360
414
  if (input?.action === "create") {
361
415
  if (typeof input.file !== "string" || typeof input.content !== "string")
362
416
  throw new Error("A record file and content are required");
363
- const config = readManifest(root).subformats?.find((format) => format.ext === fileExtension(input.file));
364
- if (!config)
365
- throw new Error("Choose a configured subformat extension");
366
- validateSubformatFile(root, input.file, input.content, domains);
417
+ const file = input.file;
418
+ const manifestPath = manifestFile(root);
419
+ const raw = readTextfile(root, manifestPath);
420
+ const manifest = readManifest(root);
421
+ const config = manifest.subformats?.find((format) => format.ext === fileExtension(file));
422
+ if (!config ||
423
+ !managedFile(file) ||
424
+ isManifestFile(file.split("/").at(-1) ?? "") ||
425
+ isSubformatSchemaFile(root, file, domains))
426
+ throw new Error("Choose a configured subformat record path");
427
+ projectFilePath(root, file);
428
+ if (!filesSnapshot(root).files.some((item) => item.path === config.schema))
429
+ throw new Error("Subformat schema is not available in the workspace");
367
430
  const data = parseSubformatRecord(input.content, config.format);
368
- if (!writeTextfile(root, input.file, input.content, null))
431
+ validateSubformatRecord(loadSubformat(root, config, domains), data);
432
+ let update;
433
+ if (!recordSubformat(root, manifest, file, domains)) {
434
+ const yaml = parseDocument(raw);
435
+ const index = manifest.subformats?.findIndex((type) => type.ext === config.ext);
436
+ const key = manifest.format
437
+ ? ["system", "format", config.ext, "files"]
438
+ : ["subformats", index, "files"];
439
+ if (manifest.format &&
440
+ !manifest.defaultSubformatFolder &&
441
+ !manifest.includedRecordSources?.[config.ext]?.defaultFolder &&
442
+ !manifest.formats?.[config.ext]?.folders &&
443
+ !manifest.formats?.[config.ext]?.files)
444
+ yaml.setIn(["system", "format", config.ext, "folders"], [`files/${config.ext}`]);
445
+ if (yaml.hasIn(key))
446
+ yaml.addIn(key, file);
447
+ else
448
+ yaml.setIn(key, [file]);
449
+ update = yaml.toString();
450
+ }
451
+ if (!writeTextfile(root, file, input.content, null))
369
452
  return { status: 409, body: { error: "File already exists" } };
453
+ if (update) {
454
+ try {
455
+ if (!writeTextfile(root, manifestPath, update, raw))
456
+ throw new Error("Manifest changed externally. Try again.");
457
+ }
458
+ catch (error) {
459
+ if (readTextfile(root, file) === input.content)
460
+ unlinkSync(textfilePath(root, file));
461
+ throw error;
462
+ }
463
+ }
370
464
  return { status: 200, body: { content: input.content, data } };
371
465
  }
372
466
  if (typeof input?.file !== "string" ||
@@ -376,7 +470,7 @@ export const subformatResponse = (root, input, domains = []) => {
376
470
  const files = filesSnapshot(root).files.map((file) => file.path);
377
471
  if (!files.includes(input.file))
378
472
  throw new Error("Record file is not available in the workspace");
379
- const config = readManifest(root).subformats?.find((format) => format.ext === fileExtension(input.file));
473
+ const config = recordSubformat(root, readManifest(root), input.file, domains);
380
474
  if (!config || !files.includes(config.schema))
381
475
  throw new Error("Subformat schema is not available in the workspace");
382
476
  const format = loadSubformat(root, config, domains);
@@ -81,6 +81,11 @@ export type Block = {
81
81
  entry: TermEntry;
82
82
  } | {
83
83
  type: "figures";
84
+ } | {
85
+ type: "pageContents";
86
+ file: string;
87
+ recursive: boolean;
88
+ title?: string;
84
89
  } | {
85
90
  type: "schemaGraph";
86
91
  alt?: string;
@@ -40,14 +40,19 @@ export interface ParsedManifest {
40
40
  languages?: string[];
41
41
  /** Color themes offered by the site, with authored variants for embedded files. */
42
42
  themes?: ("light" | "dark")[];
43
+ accentColor?: string;
43
44
  subformats?: Subformat[];
44
45
  defaultSubformatFolder?: string;
45
46
  includedManifests?: string[];
46
47
  includedAssets?: string[];
47
48
  includedSubformats?: string[];
49
+ includedRecordSources?: Record<string, {
50
+ directory: string;
51
+ defaultFolder?: string;
52
+ }>;
48
53
  errors: string[];
49
54
  }
50
- export declare const pageUrlKind: (url: string) => "index" | "content" | "file" | "manifest" | "link" | "redirect";
55
+ export declare const pageUrlKind: (url: string) => "index" | "content" | "file" | "manifest" | "link" | "redirect" | "toc";
51
56
  export declare const isContentPage: (node: {
52
57
  url?: string;
53
58
  subformat?: unknown;
@@ -71,12 +76,13 @@ export declare const parseManifest: (value: unknown) => ParsedManifest;
71
76
  /** Move the former sidebar icon without discarding YAML comments or choosing between duplicates. */
72
77
  export declare const migrateDocumentIcon: (document: Document) => boolean;
73
78
  /** Serialize the authored format; legacy manifests remain readable during migration. */
74
- export declare const serializeManifest: (tree: readonly DocNode[], { format, version, titles, themeIcons, title, icon, defaultLang, licence, skills, libraries, formats, files, languages, themes, subformats, defaultSubformatFolder, includedSubformats, }?: Omit<ParsedManifest, "tree" | "errors">) => string;
79
+ export declare const serializeManifest: (tree: readonly DocNode[], settings?: Omit<ParsedManifest, "tree" | "errors">) => string;
75
80
  /** Flatten the tree into display order (pre-order). parent omitted = top level. */
76
81
  export declare const flattenTree: (tree: readonly DocNode[]) => (Omit<DocNode, "children"> & {
77
82
  parent?: string;
78
83
  depth: number;
79
84
  })[];
85
+ export declare const findNode: (tree: readonly DocNode[], id: string) => DocNode | undefined;
80
86
  /** Append a new doc to the end of parent's children. Duplicate id / missing parent → undefined. */
81
87
  export declare const insertDoc: (tree: readonly DocNode[], id: string, parent?: string, page?: Pick<DocNode, "subformat" | "library" | "format" | "title">) => DocNode[] | undefined;
82
88
  /**
@@ -85,7 +91,6 @@ export declare const insertDoc: (tree: readonly DocNode[], id: string, parent?:
85
91
  * (no partial update).
86
92
  */
87
93
  export declare const moveDoc: (tree: readonly DocNode[], id: string, parent: string | undefined, index: number) => DocNode[] | undefined;
88
- /** Remove a doc. Docs with children are not removed (we don't decide where the children go). */
89
- export declare const removeDoc: (tree: readonly DocNode[], id: string) => DocNode[] | undefined;
94
+ export declare const removeDoc: (tree: readonly DocNode[], id: string, children?: "promote" | "remove") => DocNode[] | undefined;
90
95
  /** Change a doc's id (position and children stay as they are). */
91
96
  export declare const renameDoc: (tree: readonly DocNode[], oldId: string, newId: string) => DocNode[] | undefined;