@lincyaw/workspace 1.0.0-rc.13 → 1.0.0-rc.131

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 (59) hide show
  1. package/README.md +4 -4
  2. package/package.json +8 -5
  3. package/src/domain/paths.ts +0 -15
  4. package/src/node/agent-activity.ts +46 -0
  5. package/src/node/archive.ts +33 -0
  6. package/src/node/authoring-clients.ts +73 -20
  7. package/src/node/authoring-windows.ts +165 -0
  8. package/src/node/build.ts +28 -23
  9. package/src/node/capture.ts +383 -0
  10. package/src/node/config.ts +136 -50
  11. package/src/node/document-assets.ts +2 -2
  12. package/src/node/document-audio.ts +65 -46
  13. package/src/node/document-authoring.ts +30 -15
  14. package/src/node/document-check.ts +36 -0
  15. package/src/node/document-history.ts +32 -5
  16. package/src/node/document-images.ts +24 -14
  17. package/src/node/document-import.ts +123 -0
  18. package/src/node/document-index.ts +644 -0
  19. package/src/node/document-materials.ts +80 -0
  20. package/src/node/document-operations.ts +4 -2
  21. package/src/node/document-transcription.ts +2 -1
  22. package/src/node/document-voice.ts +121 -13
  23. package/src/node/git-runner.mjs +19 -0
  24. package/src/node/git.ts +141 -22
  25. package/src/node/host-activity.ts +17 -0
  26. package/src/node/host-upgrade.ts +28 -0
  27. package/src/node/jobs.ts +40 -8
  28. package/src/node/local-history.ts +84 -0
  29. package/src/node/locks.ts +12 -0
  30. package/src/node/mcp-settings.ts +68 -0
  31. package/src/node/media-upload-messages.ts +4 -0
  32. package/src/node/media-upload-page.ts +57 -0
  33. package/src/node/media-upload.css +4 -0
  34. package/src/node/media-uploads.ts +116 -0
  35. package/src/node/page-delete.ts +0 -1
  36. package/src/node/project-files.ts +2 -2
  37. package/src/node/projects.ts +20 -5
  38. package/src/node/review/agent-session-reviews.ts +194 -63
  39. package/src/node/review/agent-workspace.ts +124 -0
  40. package/src/node/review/git-review.ts +47 -15
  41. package/src/node/review/record.ts +5 -1
  42. package/src/node/review/routes.ts +9 -1
  43. package/src/node/review/workspace-review.ts +87 -0
  44. package/src/node/revision-files.ts +54 -0
  45. package/src/node/revisions.ts +244 -59
  46. package/src/node/routes.ts +52 -59
  47. package/src/node/serve.ts +267 -52
  48. package/src/node/site.ts +5 -5
  49. package/src/node/source-editor.ts +66 -26
  50. package/src/node/speech-settings.ts +6 -8
  51. package/src/node/templates.ts +2 -2
  52. package/src/node/tree-operations.ts +425 -0
  53. package/src/node/tree-routes.ts +94 -0
  54. package/src/node/workbench-api.ts +14 -3
  55. package/src/node/workspace-changes.ts +130 -0
  56. package/src/node/workspace-migrate.ts +54 -0
  57. package/src/node/workspace-source.ts +133 -0
  58. package/src/node/writer.ts +21 -8
  59. package/templates/document/default/{lecture.json → index.pmd} +5 -1
@@ -0,0 +1,644 @@
1
+ import { existsSync, readFileSync, watch } from 'node:fs'
2
+ import type { FSWatcher } from 'node:fs'
3
+ import { readdir, readFile, realpath, stat } from 'node:fs/promises'
4
+ import { join } from 'node:path'
5
+ import { setImmediate as yieldToEvents } from 'node:timers/promises'
6
+ import { provideDocumentEntries } from '@lincyaw/compiler'
7
+ import type { ScannedDocument } from '@lincyaw/compiler'
8
+ import { blockFirstText, blockSubtree, DOCUMENT_ENTRY, documentCitationSites, documentSearchText, documentTree, isRecord, targetExcerpt } from '@lincyaw/kernel'
9
+ import type { AttentionCount, BlockId, DocumentCitation, DocumentId, DocumentLinks, DocumentPlacement, DocumentPreview, DocumentSearchHit, DocumentTree, EmbedSource, OutgoingLink, PlacementTree, PresmiumDocument, ReferenceTarget, SectionId, TrashEntry, TreeIssue, TreeNode, WorkspaceAttention } from '@lincyaw/kernel'
10
+ import { primeDocumentHead } from './config.ts'
11
+ import type { WorkspaceConfig } from './config.ts'
12
+
13
+ /** The workspace folder trashed documents are moved to, one folder per document ID. */
14
+ export const TRASH_DIR = '.trash'
15
+ /** The record beside a trashed document: where it came from and where it sat in the tree. */
16
+ export const TRASH_RECORD = 'trashed.json'
17
+ /** Folders discovery never enters, as in the compiler's scan; `locales/<lang>/` holds translations. */
18
+ const SKIPPED = new Set(['node_modules', '.git', '.presmium', 'dist', TRASH_DIR])
19
+ /** How long file events are gathered before the index reads the files they name. */
20
+ const SETTLE_MS = 40
21
+ /** A walk of the whole workspace also runs this often, for what file events cannot tell (watching unavailable, new folders deep in a document). */
22
+ const SWEEP_MS = 30_000
23
+ /** Work done between two yields to the event loop while reading many files. */
24
+ const SLICE_MS = 8
25
+ const READ_CONCURRENCY = 8
26
+
27
+ export interface TrashRecord {
28
+ deletedAt: string
29
+ /** The document folder it was trashed from, relative to the workspace root. */
30
+ from: string
31
+ parent: DocumentId | null
32
+ rank: string
33
+ /** The documents trashed with it, its descendants at the time. */
34
+ children: DocumentId[]
35
+ /** Set on a descendant: the document whose trashing took it along. */
36
+ with?: DocumentId
37
+ }
38
+
39
+ /** A reference or synced block in a document, as the index keeps it. */
40
+ interface Site { kind: 'reference' | 'embed', target: ReferenceTarget, block: BlockId, section?: SectionId, excerpt: string, label?: string, fallback?: string }
41
+
42
+ /** What the index keeps of one document: never the whole document, which is read again when needed. */
43
+ export interface IndexEntry {
44
+ id: DocumentId
45
+ /** The document folder, relative to the workspace root. */
46
+ dir: string
47
+ title: string
48
+ placement: DocumentPlacement
49
+ sites: Site[]
50
+ /** The current titles its pages and blocks give references to them. */
51
+ pages: Map<SectionId, string>
52
+ blocks: Map<BlockId, string>
53
+ /** The first text of the document and of each page, for previews. */
54
+ excerpt: string
55
+ pageExcerpts: Map<SectionId, string>
56
+ steps: number
57
+ /** Lowercase search text: the title, then everything (for a quick test), then page titles and blocks. */
58
+ search: { title: string, all: string, pages: { id: SectionId, title: string, lower: string }[], blocks: { id: BlockId, section?: SectionId, text: string, lower: string }[] }
59
+ schemaVersion: unknown
60
+ /** What a client's tree shows of it; a change of this is a change of the tree. */
61
+ treeKey: string
62
+ /** What references to it show; a change of this can make other documents' fallbacks outdated. */
63
+ titleKey: string
64
+ }
65
+
66
+ export interface TrashedEntry extends IndexEntry { record: TrashRecord }
67
+
68
+ interface FileState { mtimeMs: number, size: number, entry?: IndexEntry }
69
+
70
+ const dirOf = (entry: string) => entry.split('/').slice(0, -1).join('/')
71
+
72
+ /** The index's view of one parsed document. */
73
+ function indexEntry(document: PresmiumDocument, dir: string): IndexEntry {
74
+ const sites = documentCitationSites(document).map(site => ({ kind: site.kind, target: site.target, block: site.block, ...site.section !== undefined ? { section: site.section } : {}, excerpt: site.excerpt, ...site.node?.label !== undefined ? { label: site.node.label } : {}, ...site.node ? { fallback: site.node.fallback } : {} }))
75
+ const text = documentSearchText(document)
76
+ const pages = new Map(document.sectionOrder.flatMap(id => document.sections[id] ? [[id, document.sections[id]!.title] as const] : []))
77
+ const blocks = new Map(Object.keys(document.blocks).map(id => [id, blockFirstText(document, id) || document.metadata.title]))
78
+ const pageExcerpts = new Map(document.sectionOrder.map(id => [id, targetExcerpt(document, { section: id })]))
79
+ const title = document.metadata.title
80
+ const searchPages = text.pages.map(page => ({ ...page, lower: page.title.toLowerCase() }))
81
+ const searchBlocks = text.blocks.map(block => ({ ...block, lower: block.text.toLowerCase() }))
82
+ return {
83
+ id: document.id, dir, title, placement: document.placement, sites, pages, blocks, schemaVersion: document.schemaVersion,
84
+ excerpt: targetExcerpt(document, {}), pageExcerpts,
85
+ steps: document.sectionOrder.reduce((sum, section) => sum + (document.sections[section]?.stepOrder.length ?? 0), 0),
86
+ search: { title: title.toLowerCase(), all: [title, ...text.pages.map(page => page.title), ...text.blocks.map(block => block.text)].join('\n').toLowerCase(), pages: searchPages, blocks: searchBlocks },
87
+ treeKey: JSON.stringify([document.id, title, document.placement?.parent ?? null, document.placement?.rank ?? '', dir]),
88
+ titleKey: JSON.stringify([title, [...pages], [...blocks]]),
89
+ }
90
+ }
91
+
92
+ function parseDocument(text: string): PresmiumDocument | undefined {
93
+ let value: unknown
94
+ try { value = JSON.parse(text.replace(/^/, '')) } catch { return undefined }
95
+ if (!isRecord(value) || typeof value.id !== 'string' || !isRecord(value.metadata) || !isRecord(value.blocks) || !isRecord(value.sections) || !Array.isArray(value.sectionOrder) || !isRecord(value.steps) || !isRecord(value.definitions)) return undefined
96
+ return value as unknown as PresmiumDocument
97
+ }
98
+
99
+ function trashRecord(value: unknown): TrashRecord | undefined {
100
+ if (!isRecord(value) || typeof value.from !== 'string') return undefined
101
+ return { deletedAt: typeof value.deletedAt === 'string' ? value.deletedAt : '', from: value.from, parent: typeof value.parent === 'string' ? value.parent : null, rank: typeof value.rank === 'string' ? value.rank : '', children: Array.isArray(value.children) ? value.children.filter((id): id is string => typeof id === 'string') : [], ...typeof value.with === 'string' ? { with: value.with } : {} }
102
+ }
103
+
104
+ /** The tree, the references in both directions, and what is derived from them; rebuilt only when what they depend on changed. */
105
+ interface Derived {
106
+ documents: Map<DocumentId, IndexEntry>
107
+ order: DocumentId[]
108
+ tree?: PlacementTree
109
+ incoming: Map<DocumentId, { citing: IndexEntry, site: Site }[]>
110
+ clientTree?: DocumentTree
111
+ /** Every entry file as the compiler's scan describes it. */
112
+ scanned: ScannedDocument[]
113
+ }
114
+
115
+ /**
116
+ * The workspace's document index (docs/authoring-actions.md, section 15): the tree from every document's placement,
117
+ * the trash, the references and synced blocks between documents in both directions, and a search over titles and text.
118
+ * Derived from the files and never stored. File events on the document folders (and on the folders that hold them)
119
+ * mark what to read again; reading is asynchronous, parses only the files that changed and yields to the event loop
120
+ * between slices, and every answer is computed from what is already in memory. A slow walk of the whole workspace
121
+ * now and then catches what file events cannot report.
122
+ */
123
+ export class DocumentIndex {
124
+ readonly #config: WorkspaceConfig
125
+ /** Every entry file found, by its path relative to the root. */
126
+ readonly #files = new Map<string, FileState>()
127
+ readonly #trash = new Map<string, TrashedEntry>()
128
+ readonly #watchers = new Map<string, FSWatcher>()
129
+ readonly #listeners = new Set<() => void>()
130
+ readonly #titleListeners = new Set<(changed: DocumentId[]) => void>()
131
+ readonly #attentionListeners = new Set<() => void>()
132
+ /** The attention summary of one generation of the index, with its text to tell a change. */
133
+ #attention?: { generation: number, value: WorkspaceAttention, text: string }
134
+ #derived?: Derived
135
+ #dirty = new Set<string>()
136
+ readonly #folders = new Set<string>()
137
+ #walk = true
138
+ #trashDirty = true
139
+ #pending?: Promise<void>
140
+ #timer?: ReturnType<typeof setTimeout>
141
+ #sweep?: ReturnType<typeof setInterval>
142
+ #watching = true
143
+ #closed = false
144
+ /** What the compiler's scans see of each file: its time and size. */
145
+ readonly #stamps = new Map<string, string>()
146
+ readonly #trashStamps = new Map<string, string>()
147
+ #generation = 0
148
+ #stopProviding?: () => void
149
+
150
+ constructor(config: WorkspaceConfig) {
151
+ this.#config = config
152
+ }
153
+
154
+ /** Starts watching and the occasional walk, and builds the index; until this, `ready` builds it on first use. */
155
+ async start(): Promise<void> {
156
+ this.#sweep = setInterval(() => { this.#walk = true; this.#trashDirty = true; this.#schedule() }, SWEEP_MS)
157
+ this.#sweep.unref()
158
+ // The compiler's scans in this process list the documents from the index instead of walking the workspace.
159
+ if (!this.#config.singleDeck) this.#stopProviding = provideDocumentEntries(this.#config.root, () => this.#derived && !this.#walk ? { generation: this.#generation, documents: this.#derived.scanned, stamps: this.#stamps } : undefined)
160
+ await this.ready()
161
+ }
162
+
163
+ close(): void {
164
+ this.#closed = true
165
+ clearTimeout(this.#timer)
166
+ clearInterval(this.#sweep)
167
+ this.#stopProviding?.()
168
+ for (const watcher of this.#watchers.values()) watcher.close()
169
+ this.#watchers.clear()
170
+ this.#listeners.clear()
171
+ this.#titleListeners.clear()
172
+ this.#attentionListeners.clear()
173
+ }
174
+
175
+ /** Resolves once everything known to have changed has been read. */
176
+ ready(): Promise<void> {
177
+ if (!this.#derived || this.#walk || this.#dirty.size || this.#folders.size || this.#trashDirty) return this.#refresh()
178
+ return this.#pending ?? Promise.resolve()
179
+ }
180
+
181
+ /** Tell the index which files an operation of this process changed (paths relative to the root); `structure` when folders appeared or went. */
182
+ async changed(paths: string[], structure = false): Promise<void> {
183
+ for (const path of paths) {
184
+ if (path.startsWith(`${TRASH_DIR}/`) || path === TRASH_DIR) this.#trashDirty = true
185
+ else this.#dirty.add(path.endsWith(DOCUMENT_ENTRY) ? path : path ? `${path}/${DOCUMENT_ENTRY}` : DOCUMENT_ENTRY)
186
+ }
187
+ if (structure) this.#walk = true
188
+ await this.#refresh()
189
+ }
190
+
191
+ #schedule(): void {
192
+ if (this.#closed || this.#timer) return
193
+ this.#timer = setTimeout(() => { this.#timer = undefined; void this.#refresh().catch(() => {}) }, SETTLE_MS)
194
+ this.#timer.unref?.()
195
+ }
196
+
197
+ #refresh(): Promise<void> {
198
+ const run = (this.#pending ?? Promise.resolve()).then(() => this.#update())
199
+ const tracked: Promise<void> = run.finally(() => { if (this.#pending === tracked) this.#pending = undefined })
200
+ this.#pending = tracked
201
+ return tracked
202
+ }
203
+
204
+ #watch(dir: string, onEvent: (name: string | null) => void): void {
205
+ if (!this.#watching || this.#watchers.has(dir)) return
206
+ try {
207
+ const watcher = watch(join(this.#config.root, dir), { persistent: false }, (_event, name) => onEvent(name === null ? null : String(name)))
208
+ watcher.on('error', () => { watcher.close(); this.#watchers.delete(dir); this.#walk = true; this.#schedule() })
209
+ this.#watchers.set(dir, watcher)
210
+ } catch (error) {
211
+ // Too many watches (or none at all): the occasional walk keeps the index current, if later. A folder that is
212
+ // gone by now is simply not watched.
213
+ const code = (error as NodeJS.ErrnoException).code
214
+ if (code === 'ENOSPC' || code === 'EMFILE' || code === 'ENOSYS') this.#watching = false
215
+ }
216
+ }
217
+
218
+ /** Every entry file and the folders worth watching, walked without blocking. */
219
+ async #discover(): Promise<{ entries: string[], containers: string[] }> {
220
+ const root = this.#config.root
221
+ if (this.#config.singleDeck) return { entries: [DOCUMENT_ENTRY], containers: [] }
222
+ const entries: string[] = [], containers: string[] = [], seen = new Set<string>()
223
+ const walk = async (rel: string, inDocument: boolean): Promise<void> => {
224
+ const path = rel ? join(root, rel) : root
225
+ let names
226
+ try {
227
+ const real = await realpath(path)
228
+ if (seen.has(real)) return
229
+ seen.add(real)
230
+ names = await readdir(path, { withFileTypes: true })
231
+ } catch { return }
232
+ const holds = names.some(item => item.name === DOCUMENT_ENTRY && (item.isFile() || item.isSymbolicLink()))
233
+ if (holds) entries.push(rel ? `${rel}/${DOCUMENT_ENTRY}` : DOCUMENT_ENTRY)
234
+ if (!inDocument || holds) containers.push(rel)
235
+ const folders = names.filter(item => !SKIPPED.has(item.name) && !item.name.startsWith('.') && item.name !== DOCUMENT_ENTRY && (item.isDirectory() || item.isSymbolicLink()))
236
+ for (const item of folders.sort((a, b) => a.name < b.name ? -1 : 1)) {
237
+ const next = rel ? `${rel}/${item.name}` : item.name
238
+ if (item.isSymbolicLink()) { try { if (!(await stat(join(root, next))).isDirectory()) continue } catch { continue } }
239
+ if (item.name !== 'locales') await walk(next, inDocument || holds)
240
+ }
241
+ }
242
+ await walk('', false)
243
+ return { entries, containers }
244
+ }
245
+
246
+ /** Reads the given entry files (relative paths), in slices that leave the event loop free. */
247
+ async #read(paths: string[], into: (path: string, state: FileState | undefined) => void): Promise<void> {
248
+ let slice = performance.now()
249
+ for (let at = 0; at < paths.length; at += READ_CONCURRENCY) {
250
+ const batch = paths.slice(at, at + READ_CONCURRENCY)
251
+ const read = await Promise.all(batch.map(async (path) => {
252
+ const file = join(this.#config.root, path)
253
+ try {
254
+ const info = await stat(file)
255
+ const known = this.#files.get(path)
256
+ if (known && known.mtimeMs === info.mtimeMs && known.size === info.size) return { path, state: known, text: undefined }
257
+ return { path, state: { mtimeMs: info.mtimeMs, size: info.size } as FileState, text: await readFile(file, 'utf8') }
258
+ } catch { return { path, state: undefined, text: undefined } }
259
+ }))
260
+ for (const { path, state, text } of read) {
261
+ if (state && text !== undefined) {
262
+ const document = parseDocument(text)
263
+ try { if (document) state.entry = indexEntry(document, dirOf(path)) } catch { /* Indexed as a file without a document. */ }
264
+ // The document list reads the same file's metadata; it finds it parsed already.
265
+ if (document) primeDocumentHead(join(this.#config.root, path), state.mtimeMs, state.size, document)
266
+ }
267
+ into(path, state)
268
+ if (performance.now() - slice > SLICE_MS) { await yieldToEvents(); slice = performance.now() }
269
+ }
270
+ }
271
+ }
272
+
273
+ /** The callback of a watched folder that holds documents (`document`: it is one itself). */
274
+ #folderEvents(dir: string, document: boolean): (name: string | null) => void {
275
+ const entryOf = (folder: string) => folder ? `${folder}/${DOCUMENT_ENTRY}` : DOCUMENT_ENTRY
276
+ return (name) => {
277
+ // An entry file written here: this folder's document (new or changed).
278
+ if (name === DOCUMENT_ENTRY) this.#dirty.add(entryOf(dir))
279
+ else if (name === null) this.#walk = true
280
+ // A folder appeared or went: looked at when the index next reads (an operation of this process has usually told it already).
281
+ else if (!document) this.#folders.add(dir ? `${dir}/${name}` : name)
282
+ this.#schedule()
283
+ }
284
+ }
285
+
286
+ /** Folders file events named: their documents are read again; only a folder that may hold documents deeper is walked. */
287
+ #lookAtFolders(): void {
288
+ for (const folder of this.#folders) {
289
+ // The trash folder itself appeared (or went): it is read, and watched while it exists.
290
+ if (folder === TRASH_DIR) { this.#trashDirty = true; continue }
291
+ const entry = `${folder}/${DOCUMENT_ENTRY}`
292
+ if (existsSync(join(this.#config.root, entry))) { if (!this.#files.has(entry)) this.#dirty.add(entry) }
293
+ else if (existsSync(join(this.#config.root, folder))) {
294
+ // A new folder without a document yet: watched, so the document written into it is seen (deeper ones by the walk).
295
+ const name = folder.split('/').at(-1)!
296
+ if (!SKIPPED.has(name) && !name.startsWith('.') && name !== 'locales') this.#watch(folder, this.#folderEvents(folder, false))
297
+ }
298
+ else for (const path of this.#files.keys()) if (path.startsWith(`${folder}/`)) this.#dirty.add(path)
299
+ }
300
+ this.#folders.clear()
301
+ }
302
+
303
+ async #update(): Promise<void> {
304
+ if (this.#closed) return
305
+ this.#lookAtFolders()
306
+ const before = this.#derived
307
+ const changes: { path: string, before?: IndexEntry, after?: IndexEntry }[] = []
308
+ let structural = false
309
+ if (this.#walk) {
310
+ this.#walk = false
311
+ const { entries, containers } = await this.#discover()
312
+ const found = new Set(entries)
313
+ for (const [path, state] of [...this.#files]) if (!found.has(path)) { this.#files.delete(path); this.#stamps.delete(path); changes.push({ path, ...state.entry ? { before: state.entry } : {} }); structural = true }
314
+ // Watched folders: those that hold documents, and those on the way to them; never a document's own subfolders.
315
+ const wanted = new Set(containers)
316
+ for (const [dir, watcher] of this.#watchers) if (dir !== TRASH_DIR && !wanted.has(dir)) { watcher.close(); this.#watchers.delete(dir) }
317
+ for (const dir of containers) this.#watch(dir, this.#folderEvents(dir, found.has(dir ? `${dir}/${DOCUMENT_ENTRY}` : DOCUMENT_ENTRY)))
318
+ for (const entry of entries) if (!this.#files.has(entry)) this.#dirty.add(entry)
319
+ // Known files are looked at again only on the occasional walk (their events may have been missed).
320
+ if (before) for (const entry of entries) this.#dirty.add(entry)
321
+ }
322
+ if (this.#dirty.size) {
323
+ const paths = [...this.#dirty]
324
+ this.#dirty.clear()
325
+ await this.#read(paths, (path, state) => {
326
+ const known = this.#files.get(path)
327
+ if (state === known) return
328
+ changes.push({ path, ...known?.entry ? { before: known.entry } : {}, ...state?.entry ? { after: state.entry } : {} })
329
+ if (state) {
330
+ if (!known) {
331
+ structural = true
332
+ // A document this index did not know: watch its folder and the folder holding it.
333
+ const dir = dirOf(path)
334
+ this.#watch(dir, this.#folderEvents(dir, true))
335
+ const parent = dirOf(dir)
336
+ if (dir) this.#watch(parent, this.#folderEvents(parent, this.#files.has(parent ? `${parent}/${DOCUMENT_ENTRY}` : DOCUMENT_ENTRY)))
337
+ }
338
+ this.#files.set(path, state)
339
+ this.#stamps.set(path, `${state.mtimeMs}:${state.size}`)
340
+ } else {
341
+ this.#stamps.delete(path)
342
+ structural = true
343
+ this.#files.delete(path)
344
+ this.#watchers.get(dirOf(path))?.close()
345
+ this.#watchers.delete(dirOf(path))
346
+ }
347
+ })
348
+ }
349
+ let trashChanged = false
350
+ if (this.#trashDirty) {
351
+ this.#trashDirty = false
352
+ trashChanged = await this.#readTrash()
353
+ }
354
+ if (before && !changes.length && !trashChanged) return
355
+ this.#generation++
356
+ const treeChanged = !before || structural || trashChanged || changes.some(change => change.before?.treeKey !== change.after?.treeKey)
357
+ if (treeChanged) this.#derived = this.#derive()
358
+ else for (const change of changes) if (change.before && change.after) this.#replace(before, change.before, change.after)
359
+ const titleChanged = changes.flatMap(change => change.after && change.before?.titleKey !== change.after.titleKey ? [change.after.id] : [])
360
+ if (before && treeChanged) for (const listener of [...this.#listeners]) listener()
361
+ if (before && titleChanged.length) for (const listener of [...this.#titleListeners]) listener(titleChanged)
362
+ if (before && this.#attentionListeners.size) {
363
+ const was = this.#attention?.text
364
+ this.attention()
365
+ if (this.#attention!.text !== was) for (const listener of [...this.#attentionListeners]) listener()
366
+ }
367
+ }
368
+
369
+ /** One document changed without changing the tree: only its own entries are replaced. */
370
+ #replace(derived: Derived, before: IndexEntry, after: IndexEntry): void {
371
+ if (derived.documents.get(after.id) !== before) return
372
+ derived.documents.set(after.id, after)
373
+ for (const site of before.sites) {
374
+ const list = derived.incoming.get(site.target.document)
375
+ if (!list) continue
376
+ const kept = list.filter(item => item.citing !== before)
377
+ if (kept.length) derived.incoming.set(site.target.document, kept)
378
+ else derived.incoming.delete(site.target.document)
379
+ }
380
+ for (const site of after.sites) {
381
+ const list = derived.incoming.get(site.target.document)
382
+ if (list) list.push({ citing: after, site })
383
+ else derived.incoming.set(site.target.document, [{ citing: after, site }])
384
+ }
385
+ }
386
+
387
+ async #readTrash(): Promise<boolean> {
388
+ const folder = join(this.#config.root, TRASH_DIR)
389
+ let names: string[] = []
390
+ try {
391
+ names = (await readdir(folder)).sort()
392
+ this.#watch(TRASH_DIR, () => { this.#trashDirty = true; this.#schedule() })
393
+ } catch {
394
+ // No trash (any more): the workspace root's watcher reports when it appears.
395
+ this.#watchers.get(TRASH_DIR)?.close()
396
+ this.#watchers.delete(TRASH_DIR)
397
+ }
398
+ const signature = [...this.#trash.values()].map(entry => entry.treeKey + entry.record.deletedAt).join()
399
+ const known = new Map([...this.#trash.values()].map(entry => [entry.dir, entry]))
400
+ this.#trash.clear()
401
+ for (const name of names) {
402
+ const dir = `${TRASH_DIR}/${name}`
403
+ try {
404
+ const record = trashRecord(JSON.parse(await readFile(join(this.#config.root, dir, TRASH_RECORD), 'utf8')))
405
+ const info = await stat(join(this.#config.root, dir, DOCUMENT_ENTRY))
406
+ const stamp = `${info.mtimeMs}:${info.size}`
407
+ const reused = known.get(dir)
408
+ // A trashed document is parsed once; only its record is read again.
409
+ const entry = reused && this.#trashStamps.get(dir) === stamp ? reused : (() => { const document = parseDocument(readFileSync(join(this.#config.root, dir, DOCUMENT_ENTRY), 'utf8')); return document && indexEntry(document, dir) })()
410
+ if (record && entry) { this.#trash.set(entry.id, { ...entry, record }); this.#trashStamps.set(dir, stamp) }
411
+ } catch { /* Not a trashed document. */ }
412
+ }
413
+ return signature !== [...this.#trash.values()].map(entry => entry.treeKey + entry.record.deletedAt).join()
414
+ }
415
+
416
+ /** The tree, the references and the compiler's scan, from every document: when the tree changed. */
417
+ #derive(): Derived {
418
+ const entries = [...this.#files.entries()].flatMap(([path, state]) => state.entry ? [{ path, entry: state.entry }] : [])
419
+ const documents = new Map<DocumentId, IndexEntry>()
420
+ let tree: PlacementTree | undefined
421
+ if (this.#config.singleDeck) for (const { entry } of entries) documents.set(entry.id, entry)
422
+ else {
423
+ tree = documentTree(entries.map(({ path, entry }) => ({ id: entry.id, path, title: entry.title, placement: { parent: entry.placement?.parent ?? null, rank: entry.placement?.rank ?? '' } })))
424
+ for (const { entry } of entries) if (!documents.has(entry.id) && tree!.byId.get(entry.id)?.path === (entry.dir ? `${entry.dir}/${DOCUMENT_ENTRY}` : DOCUMENT_ENTRY)) documents.set(entry.id, entry)
425
+ }
426
+ const incoming = new Map<DocumentId, { citing: IndexEntry, site: Site }[]>()
427
+ for (const citing of documents.values()) for (const site of citing.sites) {
428
+ const list = incoming.get(site.target.document)
429
+ if (list) list.push({ citing, site })
430
+ else incoming.set(site.target.document, [{ citing, site }])
431
+ }
432
+ const order = tree ? tree.order.map(node => node.id) : [...documents.keys()]
433
+ const scanned = [...this.#files.entries()].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([path, state]): ScannedDocument => state.entry
434
+ ? { id: state.entry.id, path, title: state.entry.title.trim() || dirOf(path) || path, placement: { parent: state.entry.placement?.parent ?? null, rank: state.entry.placement?.rank ?? '' }, schemaVersion: state.entry.schemaVersion }
435
+ : { id: `path:${path}`, path, title: dirOf(path) || path, placement: { parent: null, rank: '' }, schemaVersion: undefined, problem: 'not a document' })
436
+ return { documents, order, scanned, ...tree ? { tree } : {}, incoming }
437
+ }
438
+
439
+ #now(): Derived {
440
+ if (!this.#derived) throw new Error('document-index-not-ready')
441
+ return this.#derived
442
+ }
443
+
444
+ /** The documents in the workspace (not in the trash) and the tree their placements make. */
445
+ scan(): { documents: Map<DocumentId, IndexEntry>, tree?: PlacementTree, order: DocumentId[] } {
446
+ const { documents, tree, order } = this.#now()
447
+ return { documents, ...tree ? { tree } : {}, order }
448
+ }
449
+
450
+ /** Every trashed document by ID, the ones trashed along with an ancestor included. */
451
+ trashed(): Map<DocumentId, TrashedEntry> {
452
+ this.#now()
453
+ return this.#trash
454
+ }
455
+
456
+ /** The whole document by ID, read from its file (in the workspace or in the trash). */
457
+ async read(id: DocumentId): Promise<{ document: PresmiumDocument, dir: string, trashed: boolean } | undefined> {
458
+ const entry = this.#now().documents.get(id) ?? this.#trash.get(id)
459
+ if (!entry) return undefined
460
+ try {
461
+ const document = parseDocument(await readFile(join(this.#config.root, entry.dir, DOCUMENT_ENTRY), 'utf8'))
462
+ return document && document.id === id ? { document, dir: entry.dir, trashed: !this.#now().documents.has(id) } : undefined
463
+ } catch { return undefined }
464
+ }
465
+
466
+ tree(): DocumentTree {
467
+ const derived = this.#now()
468
+ if (derived.clientTree) return derived.clientTree
469
+ const { documents, tree } = derived
470
+ const nodes: Record<DocumentId, TreeNode> = {}
471
+ if (!tree) {
472
+ for (const entry of documents.values()) nodes[entry.id] = { id: entry.id, title: entry.title, path: entry.dir, parent: null, rank: entry.placement?.rank ?? '', depth: 0, children: [] }
473
+ return derived.clientTree = { roots: Object.keys(nodes), nodes, trash: [] }
474
+ }
475
+ const issues = new Map<DocumentId, TreeIssue[]>()
476
+ const add = (id: DocumentId, issue: TreeIssue) => issues.set(id, [...issues.get(id) ?? [], issue])
477
+ for (const problem of tree.problems) {
478
+ if (problem.code === 'tree.duplicate-id') add(problem.id, { code: problem.code, message: `Two documents have the ID ${problem.id}: ${problem.paths.join(' and ')}; only the first is in the tree.` })
479
+ else if (problem.code === 'tree.unknown-parent') add(problem.id, { code: problem.code, message: `The parent ${problem.parent} does not exist; the document is shown at the top level.` })
480
+ else add(problem.id, { code: problem.code, message: 'The document is placed under its own descendant; it is shown at the top level.' })
481
+ }
482
+ for (const node of tree.order) {
483
+ nodes[node.id] = { id: node.id, title: node.title, path: dirOf(node.path), parent: node.parent, rank: node.placement.rank, depth: node.depth, children: [...tree.children.get(node.id) ?? []], ...issues.has(node.id) ? { issues: issues.get(node.id) } : {} }
484
+ }
485
+ const trash: TrashEntry[] = [...this.#trash.values()].filter(entry => !entry.record.with).map((entry) => {
486
+ const parent = entry.record.parent
487
+ return { id: entry.id, title: entry.title, deletedAt: entry.record.deletedAt, from: entry.record.from, parent, children: entry.record.children, ...parent !== null && !documents.has(parent) && this.#trash.has(parent) ? { parentTrashed: true } : {} }
488
+ })
489
+ trash.sort((a, b) => a.deletedAt < b.deletedAt ? 1 : a.deletedAt > b.deletedAt ? -1 : 0)
490
+ return derived.clientTree = { roots: [...tree.children.get(null) ?? []], nodes, trash }
491
+ }
492
+
493
+ /** The titles of the document's ancestors, root first. */
494
+ ancestors(id: DocumentId): string[] {
495
+ const { tree } = this.#now()
496
+ return tree && tree.byId.has(id) ? tree.ancestors(id).map(node => node.title) : []
497
+ }
498
+
499
+ /** The current title of a reference's target, or undefined when the document, page or block is gone (or trashed, with `live`). */
500
+ titleOf(target: ReferenceTarget, live = false): string | undefined {
501
+ const entry = this.#now().documents.get(target.document) ?? (live ? undefined : this.#trash.get(target.document))
502
+ if (!entry) return undefined
503
+ if (target.block !== undefined) return entry.blocks.get(target.block)
504
+ if (target.section !== undefined) return entry.pages.get(target.section)
505
+ return entry.title
506
+ }
507
+
508
+ links(id: DocumentId): DocumentLinks {
509
+ const { documents, incoming } = this.#now()
510
+ const own = documents.get(id) ?? this.#trash.get(id)
511
+ if (!own) return { document: id, incoming: [], outgoing: [] }
512
+ const outgoing: OutgoingLink[] = own.sites.map((site) => {
513
+ const title = this.titleOf(site.target)
514
+ const trashed = !documents.has(site.target.document) && this.#trash.has(site.target.document)
515
+ return { kind: site.kind, target: site.target, title: site.label ?? title ?? site.fallback ?? site.target.document, missing: title === undefined, ...trashed ? { trashed: true } : {} }
516
+ })
517
+ const cited: DocumentCitation[] = (incoming.get(id) ?? []).map(({ citing, site }) => ({
518
+ kind: site.kind, document: citing.id, title: citing.title, ...site.section !== undefined ? { section: site.section } : {}, block: site.block,
519
+ excerpt: site.kind === 'embed' ? (site.target.block !== undefined ? own.blocks.get(site.target.block) ?? '' : '') : site.excerpt,
520
+ }))
521
+ return { document: id, incoming: cited, outgoing }
522
+ }
523
+
524
+ /** Titles first (in tree order), then page titles and block text; the text was made lowercase when it was indexed. */
525
+ search(query: string, limit: number): DocumentSearchHit[] {
526
+ const q = query.trim().toLowerCase()
527
+ if (!q) return []
528
+ const { documents, order } = this.#now()
529
+ const hits: DocumentSearchHit[] = []
530
+ for (const id of order) {
531
+ if (hits.length >= limit) return hits
532
+ const entry = documents.get(id)
533
+ if (entry?.search.title.includes(q)) hits.push({ id, title: entry.title, ancestors: this.ancestors(id), match: 'title' })
534
+ }
535
+ const titled = new Set(hits.map(hit => hit.id))
536
+ for (const id of order) {
537
+ if (hits.length >= limit) break
538
+ const entry = documents.get(id)
539
+ if (!entry || titled.has(id) || !entry.search.all.includes(q)) continue
540
+ const page = entry.search.pages.find(page => page.lower.includes(q))
541
+ const block = page ? undefined : entry.search.blocks.find(block => block.lower.includes(q))
542
+ if (!page && !block) continue
543
+ hits.push({ id, title: entry.title, ancestors: this.ancestors(id), match: 'content', excerpt: page ? page.title : sentenceOf(block!.text, block!.lower.indexOf(q)), ...page ? { section: page.id } : block!.section !== undefined ? { section: block!.section, block: block!.id } : { block: block!.id } })
544
+ }
545
+ return hits
546
+ }
547
+
548
+ preview(id: DocumentId, target: { section?: SectionId, block?: BlockId }): DocumentPreview {
549
+ const { documents, incoming } = this.#now()
550
+ const entry = documents.get(id) ?? this.#trash.get(id)
551
+ if (!entry) return { id, title: '', ancestors: [], excerpt: '', pages: 0, steps: 0, citedBy: 0, missing: true }
552
+ const trashed = !documents.has(id)
553
+ const missing = (target.block !== undefined && !entry.blocks.has(target.block)) || (target.section !== undefined && !entry.pages.has(target.section))
554
+ const excerpt = missing ? '' : target.block !== undefined ? entry.blocks.get(target.block)! : target.section !== undefined ? entry.pageExcerpts.get(target.section) ?? '' : entry.excerpt
555
+ return {
556
+ id,
557
+ title: (target.block !== undefined ? entry.blocks.get(target.block) : target.section !== undefined ? entry.pages.get(target.section) : undefined) ?? entry.title,
558
+ ancestors: trashed ? [] : this.ancestors(id),
559
+ excerpt,
560
+ pages: entry.pages.size,
561
+ steps: entry.steps,
562
+ citedBy: new Set((incoming.get(id) ?? []).map(item => item.citing.id)).size,
563
+ ...trashed ? { trashed: true } : {},
564
+ ...missing ? { missing: true } : {},
565
+ }
566
+ }
567
+
568
+ async embedSource(id: DocumentId, block: BlockId): Promise<EmbedSource> {
569
+ const located = await this.read(id)
570
+ const blocks = located && blockSubtree(located.document, block)
571
+ if (!located || !blocks) return { document: id, title: located?.document.metadata.title ?? '', block, missing: true, ...located?.trashed ? { trashed: true } : {} }
572
+ const { document } = located
573
+ const root = blocks[block]!
574
+ const used = Object.values(blocks).flatMap(item => item.type === 'image' && item.assetId && Object.hasOwn(document.assets, item.assetId) ? [item.assetId] : [])
575
+ // Relative to the workspace routes, as the client reaches the document's own assets.
576
+ const assets = located.trashed ? {} : Object.fromEntries(used.map(asset => [asset, `document/asset?${new URLSearchParams({ document: located.dir, asset })}`]))
577
+ const states = root.type === 'component' ? document.definitions[root.definitionId]?.states.map(state => state.id) : undefined
578
+ return { document: id, title: document.metadata.title, block, blocks, ...Object.keys(assets).length ? { assets } : {}, ...states ? { states } : {}, ...located.trashed ? { trashed: true } : {} }
579
+ }
580
+
581
+ /**
582
+ * References and synced blocks whose target is gone or in the trash, counted across the workspace. One pass over the
583
+ * references the index keeps, at most once per change of the index.
584
+ */
585
+ attention(): WorkspaceAttention {
586
+ const { documents, order } = this.#now()
587
+ if (this.#attention?.generation === this.#generation) return this.#attention.value
588
+ const counts = { reference: undefined as AttentionCount | undefined, embed: undefined as AttentionCount | undefined }
589
+ for (const id of order) {
590
+ const entry = documents.get(id)
591
+ if (!entry) continue
592
+ const counted = new Set<'reference' | 'embed'>()
593
+ for (const site of entry.sites) {
594
+ if (this.titleOf(site.target, true) !== undefined) continue
595
+ const count = counts[site.kind] ??= { places: 0, documents: 0, first: { document: id, ...site.section !== undefined ? { section: site.section } : {}, block: site.block } }
596
+ count.places++
597
+ if (!counted.has(site.kind)) { counted.add(site.kind); count.documents++ }
598
+ }
599
+ }
600
+ const value: WorkspaceAttention = { ...counts.reference ? { references: counts.reference } : {}, ...counts.embed ? { embeds: counts.embed } : {} }
601
+ this.#attention = { generation: this.#generation, value, text: JSON.stringify(value) }
602
+ return value
603
+ }
604
+
605
+ /** Called whenever what `attention` answers has changed. */
606
+ onAttention(listener: () => void): () => void {
607
+ this.#attentionListeners.add(listener)
608
+ return () => { this.#attentionListeners.delete(listener) }
609
+ }
610
+
611
+ /** The documents whose references may show an outdated fallback after the titles of `changed` changed: those citing them, and themselves. */
612
+ citing(changed: DocumentId[]): IndexEntry[] {
613
+ const { documents, incoming } = this.#now()
614
+ const out = new Map<DocumentId, IndexEntry>()
615
+ for (const id of changed) {
616
+ const own = documents.get(id)
617
+ if (own?.sites.some(site => site.kind === 'reference')) out.set(id, own)
618
+ for (const { citing, site } of incoming.get(id) ?? []) if (site.kind === 'reference') out.set(citing.id, citing)
619
+ }
620
+ return [...out.values()]
621
+ }
622
+
623
+ /** Called with no argument whenever the tree or the trash has changed. */
624
+ subscribe(listener: () => void): () => void {
625
+ this.#listeners.add(listener)
626
+ return () => { this.#listeners.delete(listener) }
627
+ }
628
+
629
+ /** Called with the documents whose titles (document, pages or blocks) changed. */
630
+ onTitles(listener: (changed: DocumentId[]) => void): () => void {
631
+ this.#titleListeners.add(listener)
632
+ return () => { this.#titleListeners.delete(listener) }
633
+ }
634
+ }
635
+
636
+ /** The sentence of `text` around `at`, at most about 120 characters. */
637
+ function sentenceOf(text: string, at: number): string {
638
+ const ends = /[.!?。!?;;\n]/
639
+ let start = at, end = at
640
+ while (start > 0 && !ends.test(text[start - 1]!)) start--
641
+ while (end < text.length && !ends.test(text[end]!)) end++
642
+ const sentence = text.slice(start, Math.min(text.length, end + 1)).trim()
643
+ return [...sentence].length <= 120 ? sentence : `${[...sentence].slice(0, 119).join('')}…`
644
+ }