@lincyaw/workspace 1.0.0-rc.14 → 1.0.0-rc.141

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 (60) hide show
  1. package/README.md +4 -4
  2. package/package.json +11 -6
  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 +16 -6
  9. package/src/node/capture.ts +383 -0
  10. package/src/node/config.ts +135 -50
  11. package/src/node/document-assets.ts +2 -2
  12. package/src/node/document-audio.ts +66 -47
  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 +85 -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 +211 -68
  39. package/src/node/review/agent-workspace.ts +151 -0
  40. package/src/node/review/git-review.ts +72 -29
  41. package/src/node/review/record.ts +41 -9
  42. package/src/node/review/routes.ts +9 -1
  43. package/src/node/review/windows-dependencies.ts +163 -0
  44. package/src/node/review/workspace-review.ts +87 -0
  45. package/src/node/revision-files.ts +54 -0
  46. package/src/node/revisions.ts +246 -61
  47. package/src/node/routes.ts +52 -59
  48. package/src/node/serve.ts +267 -52
  49. package/src/node/site.ts +5 -5
  50. package/src/node/source-editor.ts +66 -26
  51. package/src/node/speech-settings.ts +6 -8
  52. package/src/node/templates.ts +2 -2
  53. package/src/node/tree-operations.ts +425 -0
  54. package/src/node/tree-routes.ts +94 -0
  55. package/src/node/workbench-api.ts +14 -3
  56. package/src/node/workspace-changes.ts +130 -0
  57. package/src/node/workspace-migrate.ts +54 -0
  58. package/src/node/workspace-source.ts +133 -0
  59. package/src/node/writer.ts +21 -8
  60. package/templates/document/default/{lecture.json → index.pmd} +5 -1
@@ -0,0 +1,383 @@
1
+ import { mkdirSync, readdirSync, rmSync, statSync, writeFileSync } from 'node:fs'
2
+ import { randomUUID } from 'node:crypto'
3
+ import { basename, join } from 'node:path'
4
+ import { CAPTIONS_PARAM, CAPTURE_HOOK, CAPTURE_MAX_BOXES, CAPTURE_MAX_FRAMES, CAPTURE_MAX_HEIGHT, CAPTURE_MAX_OVERVIEW, CAPTURE_PARAM, CAPTURE_SHEET_SIZE, errorMessage, PREVIEW_APPEARANCE_PARAM, slideShape } from '@lincyaw/kernel'
5
+ import type { CanonicalSource, CaptureEvidence, CapturedBox, CapturedSlide, CaptureHook, DocumentCapture, IRDocument, IRSection, OverviewCaptureRequest, ReadingCaptureRequest, SlideCaptureRequest } from '@lincyaw/kernel'
6
+ import { playwrightChromium } from '@lincyaw/kernel/node'
7
+
8
+ /** What capturing uses of Playwright's Chromium. */
9
+ interface Page {
10
+ goto(url: string, options: { waitUntil: 'load', timeout: number }): Promise<unknown>
11
+ waitForFunction(script: string, arg: undefined, options: { timeout: number }): Promise<unknown>
12
+ evaluate<R, A>(run: (arg: A) => R | Promise<R>, arg: A): Promise<R>
13
+ screenshot(options: { type: 'png', fullPage?: boolean, clip?: { x: number, y: number, width: number, height: number } }): Promise<Buffer>
14
+ setViewportSize(size: { width: number, height: number }): Promise<void>
15
+ setContent(html: string, options: { waitUntil: 'load', timeout: number }): Promise<void>
16
+ on(event: 'pageerror', listener: (error: Error) => void): void
17
+ on(event: 'console', listener: (message: { type(): string, text(): string }) => void): void
18
+ }
19
+ interface Context {
20
+ newPage(): Promise<Page>
21
+ close(): Promise<void>
22
+ }
23
+ interface Browser {
24
+ newContext(options: { viewport: { width: number, height: number }, deviceScaleFactor: number, reducedMotion: 'reduce', colorScheme: 'light' | 'dark', serviceWorkers: 'block' }): Promise<Context>
25
+ close(): Promise<void>
26
+ }
27
+ interface Chromium { launch(): Promise<Browser> }
28
+
29
+ export interface CaptureOptions {
30
+ root: string
31
+ /** The service's own address. */
32
+ url(): string
33
+ /** The viewer page of a document once the page can show it (its path below the address), as previews open it. */
34
+ viewerPage(document: string): Promise<string | undefined>
35
+ /** The document's current runtime snapshot. */
36
+ compiled(document: string): Promise<IRDocument>
37
+ /** Where the pictures are written. */
38
+ dir: string
39
+ }
40
+
41
+ interface View { width: number, height: number, scale: number, appearance: 'light' | 'dark' }
42
+ interface CaptureInput {
43
+ kind: 'slides' | 'reading' | 'overview'
44
+ request: SlideCaptureRequest | ReadingCaptureRequest | OverviewCaptureRequest
45
+ source?: CanonicalSource
46
+ }
47
+ const sameSource = (a: CanonicalSource | undefined, b: CanonicalSource | undefined): boolean =>
48
+ a?.documentId === b?.documentId && a?.version === b?.version && a?.fingerprint === b?.fingerprint
49
+
50
+ const PAGE_MS = 120_000
51
+ const IDLE_MS = 120_000
52
+ const KEEP = 20
53
+ const FIT_ROUNDS = 3
54
+ const READING_WIDTH = 1280
55
+ const READING_HEIGHT = 900
56
+ const MIN_WIDTH = 320
57
+ const MAX_WIDTH = 2560
58
+ const THUMB_WIDTH = 320
59
+ const SHEET_GAP = 16
60
+
61
+ class CaptureError extends Error {
62
+ readonly status: number
63
+ readonly detail?: Record<string, unknown>
64
+ constructor(code: string, status: number, detail?: Record<string, unknown>) {
65
+ super(code)
66
+ this.status = status
67
+ if (detail) this.detail = detail
68
+ }
69
+ }
70
+
71
+ /**
72
+ * Pictures of documents as readers see them, in a headless Chromium kept while it is used: the viewer page of a
73
+ * document, opened with `?capture`, is driven by its capture hook (a slide step by step and moment by moment, so that a
74
+ * picture is the same however often it is taken; a section of the reading page scrolled through and at rest). One request
75
+ * at a time; the pictures stay in `dir`, the last few requests.
76
+ */
77
+ export function createDocumentCapture(options: CaptureOptions): { service: DocumentCapture, close(): Promise<void> } {
78
+ let browser: Promise<Browser> | undefined
79
+ let idle: ReturnType<typeof setTimeout> | undefined
80
+ let queue: Promise<unknown> = Promise.resolve()
81
+ const launch = (): Promise<Browser> => {
82
+ clearTimeout(idle)
83
+ browser ??= playwrightChromium<Chromium>(options.root, import.meta.url).then(chromium => chromium.launch()).catch((error: unknown) => {
84
+ browser = undefined
85
+ throw new CaptureError('capture-browser-unavailable', 503, { reason: errorMessage(error) })
86
+ })
87
+ return browser
88
+ }
89
+ const release = () => {
90
+ clearTimeout(idle)
91
+ idle = setTimeout(() => void close(), IDLE_MS)
92
+ idle.unref?.()
93
+ }
94
+ const close = async () => {
95
+ clearTimeout(idle)
96
+ const open = browser
97
+ browser = undefined
98
+ await (await open?.catch(() => undefined))?.close().catch(() => undefined)
99
+ }
100
+
101
+ /** The section asked for, by id or by its number from 1. */
102
+ const sectionOf = (doc: IRDocument, asked: string) => {
103
+ const section = doc.sections.find(s => s.id === asked) ?? doc.sections[Number(asked) - 1]
104
+ if (!section) throw new CaptureError('capture-section-unknown', 404, { section: asked, sections: doc.sections.map(s => s.id) })
105
+ return section
106
+ }
107
+
108
+ /** The document's viewer page in a form, opened with its capture hook in a new context; `run` uses it, then it closes. */
109
+ const open = async <T extends { images: Uint8Array[] }>(document: string, form: 'web' | 'slides', view: View & { captions?: boolean }, signal: AbortSignal | undefined, run: (tab: Page, problems: Set<string>, out: string, newPage: () => Promise<Page>) => Promise<T>, input: CaptureInput): Promise<T & { capture: CaptureEvidence }> => {
110
+ const page = await options.viewerPage(document).catch((error: unknown) => {
111
+ throw new CaptureError('capture-preview-failed', 409, { reason: errorMessage(error) })
112
+ })
113
+ if (!page) throw new CaptureError('capture-preview-failed', 409)
114
+ signal?.throwIfAborted()
115
+ const context = await (await launch()).newContext({ viewport: { width: view.width, height: view.height }, deviceScaleFactor: view.scale, reducedMotion: 'reduce', colorScheme: view.appearance, serviceWorkers: 'block' })
116
+ const problems = new Set<string>()
117
+ let directory: string | undefined
118
+ let complete = false
119
+ try {
120
+ const tab = await context.newPage()
121
+ tab.on('pageerror', error => problems.add(error.message))
122
+ tab.on('console', message => { if (message.type() === 'error') problems.add(message.text().slice(0, 500)) })
123
+ const address = new URL(page, options.url())
124
+ if (form === 'slides') address.searchParams.set('form', 'slides')
125
+ if (view.captions === false) address.searchParams.set(CAPTIONS_PARAM, 'off')
126
+ address.searchParams.set(CAPTURE_PARAM, '')
127
+ address.searchParams.set(PREVIEW_APPEARANCE_PARAM, view.appearance)
128
+ await tab.goto(address.href, { waitUntil: 'load', timeout: PAGE_MS })
129
+ await tab.waitForFunction(`Boolean(window.${CAPTURE_HOOK})`, undefined, { timeout: PAGE_MS })
130
+ const snapshot = () => tab.evaluate(hook => (window as unknown as Record<string, CaptureHook>)[hook]!.snapshot?.(), CAPTURE_HOOK)
131
+ const before = await snapshot()
132
+ if (before?.source && input.source && !sameSource(before.source, input.source)) throw new CaptureError('capture-source-changed', 409)
133
+ const createdAt = new Date().toISOString()
134
+ const id = `${createdAt.replace(/[:.]/g, '-')}-${randomUUID()}`
135
+ const out = join(options.dir, ...(input.request.retain ? ['retained', id] : [id]))
136
+ directory = out
137
+ mkdirSync(out, { recursive: true })
138
+ const result = await run(tab, problems, out, () => context.newPage())
139
+ signal?.throwIfAborted()
140
+ const after = await snapshot()
141
+ if (!sameSource(before?.source, after?.source) || before?.codeBundle !== after?.codeBundle) throw new CaptureError('capture-source-changed', 409)
142
+ const capture: CaptureEvidence = { id, createdAt, directory: out, manifestFile: join(out, 'capture.json'), retained: input.request.retain === true, ...before }
143
+ const { images: _images, ...details } = result
144
+ writeFileSync(capture.manifestFile, `${JSON.stringify({ capture, kind: input.kind, request: input.request, ...details }, null, 2)}\n`)
145
+ complete = true
146
+ return { ...result, capture }
147
+ } catch (error) {
148
+ if (error instanceof CaptureError || signal?.aborted) throw error
149
+ // A page that loads again while it is driven loses its hook: going back reloaded it.
150
+ if (/context was destroyed|because of a navigation/i.test(errorMessage(error))) throw new CaptureError('capture-page-reloaded', 409, { problems: [...problems] })
151
+ throw new CaptureError('capture-failed', 500, { reason: errorMessage(error), problems: [...problems] })
152
+ } finally {
153
+ await context.close().catch(() => undefined)
154
+ if (!complete && directory) rmSync(directory, { recursive: true, force: true })
155
+ prune(options.dir)
156
+ }
157
+ }
158
+
159
+ const slides: DocumentCapture['slides'] = async (document, request, signal) => {
160
+ if (request.arrive === 'backward' && request.at !== undefined) throw new CaptureError('capture-arrive-moment-conflict', 400)
161
+ const doc = await options.compiled(document)
162
+ const section = sectionOf(doc, request.section)
163
+ const steps = request.steps ?? Array.from({ length: section.steps + 1 }, (_, step) => step)
164
+ const wrong = steps.find(step => !Number.isInteger(step) || step < 0 || step > section.steps)
165
+ if (wrong !== undefined) throw new CaptureError('capture-step-invalid', 400, { step: wrong, last: section.steps })
166
+ const arrive = request.arrive ?? 'direct'
167
+ // Reached backward, a step is at rest: moments apply to steps drawn directly.
168
+ const moments: (number | null)[] = request.at?.length && arrive === 'direct' ? request.at : [null]
169
+ if (moments.some(at => at !== null && (!Number.isFinite(at) || at < 0))) throw new CaptureError('capture-moment-invalid', 400)
170
+ const count = steps.length * moments.length
171
+ if (count === 0 || count > CAPTURE_MAX_FRAMES) throw new CaptureError('capture-too-many-frames', 400, { requested: count, max: CAPTURE_MAX_FRAMES })
172
+ const shape = slideShape(doc)
173
+ const scale = request.scale ?? 1
174
+ return await open(document, 'slides', { width: shape.width, height: shape.height, scale, appearance: request.appearance ?? 'light', captions: request.captions }, signal, async (tab, problems, out) => {
175
+ const show = (step: number, at: number | null, how: 'direct' | 'backward' = 'direct') => tab.evaluate(async ([hook, position]) => await (window as unknown as Record<string, CaptureHook>)[hook]!.show(position), [CAPTURE_HOOK, { section: section.id, step, arrive: how, ...at === null ? {} : { at } }] as const)
176
+ await fit(tab, shape, section.id, steps[0]!, () => show(steps[0]!, moments[0]!))
177
+ const frames: CapturedSlide[] = [], images: Uint8Array[] = []
178
+ for (const step of steps) {
179
+ for (const at of moments) {
180
+ signal?.throwIfAborted()
181
+ const shown = await show(step, at, arrive)
182
+ for (const problem of shown.problems) problems.add(problem)
183
+ const measured = await tab.evaluate(measure, { section: section.id, step, selector: request.measure ?? '', width: shape.width, max: CAPTURE_MAX_BOXES })
184
+ if (!measured) throw new CaptureError('capture-slide-missing', 500, { section: section.id, step })
185
+ const clip = request.clip
186
+ ? { x: measured.slide.x + request.clip.x * measured.slide.scale, y: measured.slide.y + request.clip.y * measured.slide.scale, width: request.clip.width * measured.slide.scale, height: request.clip.height * measured.slide.scale }
187
+ : { x: measured.slide.x, y: measured.slide.y, width: measured.slide.width, height: measured.slide.height }
188
+ const png = await tab.screenshot({ type: 'png', clip })
189
+ const file = join(out, `${section.id}-${step}${at === null ? '' : `-${at}ms`}${arrive === 'backward' ? '-backward' : ''}.png`)
190
+ writeFileSync(file, png)
191
+ images.push(png)
192
+ frames.push({ section: section.id, slide: section.index, step, at, file, narration: narrationOf(section, step), width: Math.round(clip.width * scale), height: Math.round(clip.height * scale), ...request.measure ? { boxes: measured.boxes } : {} })
193
+ }
194
+ }
195
+ return { document, shape: { width: shape.width, height: shape.height }, frames, problems: [...problems], images }
196
+ }, { kind: 'slides', request, source: doc.source })
197
+ }
198
+
199
+ const reading: DocumentCapture['reading'] = async (document, request, signal) => {
200
+ const doc = await options.compiled(document)
201
+ const section = sectionOf(doc, request.section)
202
+ const width = Math.round(request.width ?? READING_WIDTH)
203
+ if (!Number.isFinite(width) || width < MIN_WIDTH || width > MAX_WIDTH) throw new CaptureError('capture-width-invalid', 400, { min: MIN_WIDTH, max: MAX_WIDTH })
204
+ const scale = request.scale ?? 1
205
+ return await open(document, 'web', { width, height: READING_HEIGHT, scale, appearance: request.appearance ?? 'light' }, signal, async (tab, problems, out) => {
206
+ const shown = await tab.evaluate(async ([hook, id]) => await (window as unknown as Record<string, CaptureHook>)[hook]!.read(id), [CAPTURE_HOOK, section.id] as const)
207
+ for (const problem of shown.problems) problems.add(problem)
208
+ const measured = await tab.evaluate(measureSection, { section: section.id, selector: request.measure ?? '', max: CAPTURE_MAX_BOXES })
209
+ if (!measured) throw new CaptureError('capture-slide-missing', 500, { section: section.id })
210
+ const height = Math.min(measured.height, CAPTURE_MAX_HEIGHT)
211
+ const png = await tab.screenshot({ type: 'png', fullPage: true, clip: { x: measured.x, y: measured.y, width: measured.width, height } })
212
+ const file = join(out, `${section.id}-reading-${width}.png`)
213
+ writeFileSync(file, png)
214
+ const frame = { section: section.id, file, width: Math.round(measured.width), height: Math.round(height), cut: measured.height > CAPTURE_MAX_HEIGHT, ...request.measure ? { boxes: measured.boxes } : {} }
215
+ return { document, width, frames: [frame], problems: [...problems], images: [png] }
216
+ }, { kind: 'reading', request, source: doc.source })
217
+ }
218
+
219
+ const overview: DocumentCapture['overview'] = async (document, request, signal) => {
220
+ const doc = await options.compiled(document)
221
+ const every = request.steps === 'all'
222
+ const positions = doc.sections.flatMap(section => (every ? Array.from({ length: section.steps + 1 }, (_, step) => step) : [section.steps]).map(step => ({ section, step })))
223
+ if (positions.length === 0 || positions.length > CAPTURE_MAX_OVERVIEW) throw new CaptureError('capture-too-many-frames', 400, { requested: positions.length, max: CAPTURE_MAX_OVERVIEW })
224
+ const shape = slideShape(doc)
225
+ const appearance = request.appearance ?? 'light'
226
+ const columns = Math.max(1, Math.min(8, Math.round(request.columns ?? 4)))
227
+ return await open(document, 'slides', { width: shape.width, height: shape.height, scale: 1, appearance, captions: request.captions }, signal, async (tab, problems, out, newPage) => {
228
+ const show = (section: string, step: number) => tab.evaluate(async ([hook, position]) => await (window as unknown as Record<string, CaptureHook>)[hook]!.show(position), [CAPTURE_HOOK, { section, step }] as const)
229
+ const first = positions[0]!
230
+ await fit(tab, shape, first.section.id, first.step, () => show(first.section.id, first.step))
231
+ // Names that sort in reading order: the page number (from 1) and the step (from 0, as the tools count it) padded.
232
+ const pageWidth = String(doc.sections.length).length
233
+ const stepWidth = String(Math.max(...doc.sections.map(section => section.steps))).length
234
+ const frames: { section: string, slide: number, step: number, file: string, narration: string }[] = [], pictures: Buffer[] = []
235
+ for (const { section, step } of positions) {
236
+ signal?.throwIfAborted()
237
+ for (const problem of (await show(section.id, step)).problems) problems.add(problem)
238
+ const measured = await tab.evaluate(measure, { section: section.id, step, selector: '', width: shape.width, max: 0 })
239
+ if (!measured) throw new CaptureError('capture-slide-missing', 500, { section: section.id, step })
240
+ const png = await tab.screenshot({ type: 'png', clip: { x: measured.slide.x, y: measured.slide.y, width: measured.slide.width, height: measured.slide.height } })
241
+ const file = join(out, `${String(section.index).padStart(pageWidth, '0')}-${String(step).padStart(stepWidth, '0')}-${section.id}.png`)
242
+ writeFileSync(file, png)
243
+ frames.push({ section: section.id, slide: section.index, step, file, narration: narrationOf(section, step) })
244
+ pictures.push(png)
245
+ }
246
+ // Sheets of thumbnails, each labelled with its page, step and title, for reading the whole piece at a glance.
247
+ const sheets: string[] = [], images: Uint8Array[] = []
248
+ const sheet = await newPage()
249
+ await sheet.setViewportSize({ width: columns * (THUMB_WIDTH + SHEET_GAP) + SHEET_GAP, height: READING_HEIGHT })
250
+ for (let start = 0; start < frames.length; start += CAPTURE_SHEET_SIZE) {
251
+ signal?.throwIfAborted()
252
+ const cells = frames.slice(start, start + CAPTURE_SHEET_SIZE).map((frame, i) => ({ label: `${frame.slide} · ${frame.step} ${doc.sections[frame.slide - 1]?.title ?? ''}`, png: pictures[start + i]! }))
253
+ await sheet.setContent(sheetHtml(cells, columns, appearance), { waitUntil: 'load', timeout: PAGE_MS })
254
+ const png = await sheet.screenshot({ type: 'png', fullPage: true })
255
+ const file = join(out, `sheet-${String(sheets.length + 1).padStart(2, '0')}.png`)
256
+ writeFileSync(file, png)
257
+ sheets.push(file)
258
+ images.push(png)
259
+ }
260
+ // The narration beside the pictures, for a reader who looks at whole slides and reads the script as text.
261
+ const narrationFile = join(out, 'narration.md')
262
+ writeFileSync(narrationFile, frames.map(frame => `## ${basename(frame.file)}\n\n${frame.narration || '—'}\n`).join('\n'))
263
+ return { document, dir: out, frames, narrationFile, sheets, problems: [...problems], images }
264
+ }, { kind: 'overview', request, source: doc.source })
265
+ }
266
+
267
+ /** One capture at a time; the browser closes when none came for a while. */
268
+ const queued = <A extends unknown[], R>(run: (...args: A) => Promise<R>) => (...args: A): Promise<R> => {
269
+ const next = queue.then(async () => {
270
+ try {
271
+ return await run(...args)
272
+ } finally {
273
+ release()
274
+ }
275
+ })
276
+ queue = next.catch(() => undefined)
277
+ return next
278
+ }
279
+
280
+ return {
281
+ service: { slides: queued(slides), reading: queued(reading), overview: queued(overview) },
282
+ close,
283
+ }
284
+ }
285
+
286
+ /**
287
+ * The page fits the slide in its window with a margin: the window is made that much larger, a few times, until the slide
288
+ * shows at its own size.
289
+ */
290
+ async function fit(tab: Page, shape: { width: number, height: number }, section: string, step: number, show: () => Promise<unknown>): Promise<void> {
291
+ let viewport = { width: shape.width, height: shape.height }
292
+ await show()
293
+ for (let round = 0; round < FIT_ROUNDS; round++) {
294
+ const fitted = await tab.evaluate(measure, { section, step, selector: '', width: shape.width, max: 0 })
295
+ if (!fitted || Math.abs(fitted.slide.scale - 1) < 0.005) return
296
+ viewport = { width: Math.round(viewport.width / fitted.slide.scale), height: Math.round(viewport.height / fitted.slide.scale) }
297
+ await tab.setViewportSize(viewport)
298
+ await show()
299
+ }
300
+ }
301
+
302
+ /** A step's narration as text: the script written for it, line by line. */
303
+ function narrationOf(section: IRSection, step: number): string {
304
+ const id = section.stepIds?.[step]
305
+ return (id ? section.stepNarrations?.[id] ?? [] : []).map(line => line.text).join('\n')
306
+ }
307
+
308
+ const escapeHtml = (text: string) => text.replace(/[&<>"]/g, char => `&#${char.charCodeAt(0)};`)
309
+
310
+ /** A sheet of thumbnails with their labels: plain HTML for the capturing browser, not a page of the product. */
311
+ function sheetHtml(cells: { label: string, png: Buffer }[], columns: number, appearance: 'light' | 'dark'): string {
312
+ const [paper, ink, line] = appearance === 'dark' ? ['#16171a', '#e8eaed', '#2e3136'] : ['#ffffff', '#1f2329', '#e3e5e9']
313
+ return `<!doctype html><meta charset="utf-8"><style>
314
+ body { margin: 0; padding: ${SHEET_GAP}px; background: ${paper}; color: ${ink}; font: 13px/1.4 system-ui, sans-serif; }
315
+ main { display: grid; grid-template-columns: repeat(${columns}, ${THUMB_WIDTH}px); gap: ${SHEET_GAP}px; }
316
+ figure { margin: 0; } img { display: block; width: ${THUMB_WIDTH}px; border: 1px solid ${line}; }
317
+ figcaption { margin-top: 4px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
318
+ </style><main>${cells.map(cell => `<figure><img src="data:image/png;base64,${cell.png.toString('base64')}"><figcaption>${escapeHtml(cell.label)}</figcaption></figure>`).join('')}</main>`
319
+ }
320
+
321
+ /** In the page: the slide shown at the step, in viewport pixels, and the boxes of `selector` in it, in slide pixels. */
322
+ function measure({ section, step, selector, width, max }: { section: string, step: number, selector: string, width: number, max: number }): { slide: { x: number, y: number, width: number, height: number, scale: number }, boxes: CapturedBox[] } | undefined {
323
+ const slides = [...document.querySelectorAll<HTMLElement>(`.pm-slide[data-section="${CSS.escape(section)}"]`)]
324
+ const slide = slides.find(element => element.dataset.step === String(step) && element.getBoundingClientRect().width > 0) ?? slides.find(element => element.getBoundingClientRect().width > 0)
325
+ if (!slide) return undefined
326
+ const frame = slide.getBoundingClientRect()
327
+ const scale = frame.width / width
328
+ const round = (value: number) => Math.round(value * 10) / 10
329
+ const boxes: CapturedBox[] = []
330
+ if (selector) {
331
+ for (const element of [...slide.querySelectorAll<HTMLElement>(selector)].slice(0, max)) {
332
+ const box = element.getBoundingClientRect()
333
+ const style = getComputedStyle(element)
334
+ const attributes: Record<string, string> = {}
335
+ for (const attribute of element.attributes) if (attribute.name === 'id' || attribute.name === 'class' || attribute.name.startsWith('data-')) attributes[attribute.name] = attribute.value.slice(0, 200)
336
+ boxes.push({
337
+ x: round((box.left - frame.left) / scale),
338
+ y: round((box.top - frame.top) / scale),
339
+ width: round(box.width / scale),
340
+ height: round(box.height / scale),
341
+ visible: box.width > 0 && box.height > 0 && style.visibility !== 'hidden' && style.display !== 'none' && Number(style.opacity) > 0,
342
+ text: (element.textContent ?? '').replace(/\s+/g, ' ').trim().slice(0, 80),
343
+ attributes,
344
+ })
345
+ }
346
+ }
347
+ return { slide: { x: frame.left, y: frame.top, width: frame.width, height: frame.height, scale }, boxes }
348
+ }
349
+
350
+ /** In the page: the section of the reading page, in page pixels, and the boxes of `selector` in it, relative to it. */
351
+ function measureSection({ section, selector, max }: { section: string, selector: string, max: number }): { x: number, y: number, width: number, height: number, boxes: CapturedBox[] } | undefined {
352
+ const element = document.querySelector<HTMLElement>(`section.pm-section[data-section="${CSS.escape(section)}"]`)
353
+ if (!element) return undefined
354
+ const frame = element.getBoundingClientRect()
355
+ const round = (value: number) => Math.round(value * 10) / 10
356
+ const boxes: CapturedBox[] = []
357
+ if (selector) {
358
+ for (const node of [...element.querySelectorAll<HTMLElement>(selector)].slice(0, max)) {
359
+ const box = node.getBoundingClientRect()
360
+ const style = getComputedStyle(node)
361
+ const attributes: Record<string, string> = {}
362
+ for (const attribute of node.attributes) if (attribute.name === 'id' || attribute.name === 'class' || attribute.name.startsWith('data-')) attributes[attribute.name] = attribute.value.slice(0, 200)
363
+ boxes.push({
364
+ x: round(box.left - frame.left),
365
+ y: round(box.top - frame.top),
366
+ width: round(box.width),
367
+ height: round(box.height),
368
+ visible: box.width > 0 && box.height > 0 && style.visibility !== 'hidden' && style.display !== 'none' && Number(style.opacity) > 0,
369
+ text: (node.textContent ?? '').replace(/\s+/g, ' ').trim().slice(0, 80),
370
+ attributes,
371
+ })
372
+ }
373
+ }
374
+ return { x: frame.left + window.scrollX, y: frame.top + window.scrollY, width: frame.width, height: frame.height, boxes }
375
+ }
376
+
377
+ /** Keeps the pictures of the last few requests. */
378
+ function prune(dir: string): void {
379
+ try {
380
+ const runs = readdirSync(dir, { withFileTypes: true }).filter(entry => entry.isDirectory() && entry.name !== 'retained').map(entry => ({ path: join(dir, entry.name), time: statSync(join(dir, entry.name)).mtimeMs })).sort((a, b) => b.time - a.time)
381
+ for (const run of runs.slice(KEEP)) rmSync(run.path, { recursive: true, force: true })
382
+ } catch {}
383
+ }
@@ -1,28 +1,29 @@
1
- import { existsSync, readdirSync, readFileSync, realpathSync, statSync } from 'node:fs'
1
+ import { existsSync, readFileSync, realpathSync, statSync } from 'node:fs'
2
2
  import { join, resolve } from 'node:path'
3
- import { WORKSPACE_CONFIG } from '@lincyaw/compiler'
4
- import type { OperatorSettings } from '@lincyaw/compiler'
3
+ import { effectiveDocumentIn, providedDocuments, inheritedSettingsIn, settingOriginsIn, WORKSPACE_CONFIG, workspaceDefaults, workspaceDocuments, workspaceSettings } from '@lincyaw/compiler'
4
+ import type { OperatorSettings, WorkspaceDocuments } from '@lincyaw/compiler'
5
5
  import { APPROVAL_KINDS, DOCUMENT_ENTRY, errorMessage, isRecord } from '@lincyaw/kernel'
6
- import type { ApprovalKind, DocumentSummary } from '@lincyaw/kernel'
6
+ import type { ApprovalKind, DocumentDefaults, DocumentSummary, EffectiveDocument, PresmiumDocument, SettingOrigins } from '@lincyaw/kernel'
7
7
  import type { ApprovalPolicy } from '@lincyaw/server'
8
8
  import { parse as parseYaml } from 'yaml'
9
- import { matchesPattern, patternSegments } from '../domain/paths.ts'
10
9
 
11
- export const DEFAULT_DOCUMENTS = [`*/${DOCUMENT_ENTRY}`]
12
-
13
- const SKIPPED = new Set(['node_modules', '.git', '.presmium', 'dist'])
10
+ const SKIPPED = new Set(['node_modules', '.git', '.presmium', 'dist', '.trash'])
14
11
 
15
12
  const POLICIES = new Set<ApprovalPolicy>(['off', 'ask', 'allow'])
16
13
 
17
14
  export interface WorkspaceConfig {
18
15
  root: string
19
16
  title: string
20
- documents: string[]
17
+ /** A folder whose own entry file is the only document. */
21
18
  singleDeck: boolean
22
19
  site: Record<string, unknown>
23
20
  approvals: Partial<Record<ApprovalKind, ApprovalPolicy>>
24
21
  templates?: string
25
22
  settings: OperatorSettings
23
+ /** The root of the documents' inherited settings. */
24
+ defaults: DocumentDefaults
25
+ /** The workspace file still lists `documents:`; `presmium migrate` or Studio's Upgrade removes it. */
26
+ needsMigration: boolean
26
27
  }
27
28
 
28
29
  function strings(value: unknown): string[] {
@@ -41,23 +42,23 @@ export function readWorkspaceConfig(root: string): WorkspaceConfig {
41
42
  throw new Error(`${file}: ${errorMessage(error)}`)
42
43
  }
43
44
  }
44
- const declared = strings(data.documents)
45
- const singleDeck = declared.length === 0 && existsSync(join(dir, DOCUMENT_ENTRY))
45
+ const singleDeck = existsSync(join(dir, DOCUMENT_ENTRY))
46
46
  const approvals = isRecord(data.approvals) ? data.approvals : {}
47
47
  const settings = isRecord(data.settings) ? data.settings : {}
48
48
  const renderers = isRecord(data.renderers) ? data.renderers : {}
49
49
  for (const [path, value] of [['renderers.lecture', renderers.lecture], ['settings.presmium.lecture', settings['presmium.lecture']]] as const) {
50
- if (isRecord(value) && Object.hasOwn(value, 'script')) throw new Error(`${file}: ${path}.script: External lecture scripts are not supported. Author narration in each document's lecture.json narrations.`)
50
+ if (isRecord(value) && Object.hasOwn(value, 'script')) throw new Error(`${file}: ${path}.script: External lecture scripts are not supported. Author narration in each document's narrations.`)
51
51
  }
52
52
  return {
53
53
  root: dir,
54
54
  title: typeof data.title === 'string' && data.title.trim() ? data.title.trim() : dir.split('/').at(-1) ?? 'Presmium',
55
- documents: singleDeck ? [DOCUMENT_ENTRY] : declared.length > 0 ? declared : DEFAULT_DOCUMENTS,
56
55
  singleDeck,
57
56
  site: isRecord(data.site) ? data.site : {},
58
57
  approvals: Object.fromEntries(APPROVAL_KINDS.flatMap(kind => (POLICIES.has(approvals[kind] as ApprovalPolicy) ? [[kind, approvals[kind] as ApprovalPolicy]] : []))),
59
58
  ...typeof data.templates === 'string' && data.templates.trim() ? { templates: resolve(dir, data.templates.trim()) } : {},
60
59
  settings: Object.fromEntries(Object.entries(settings).map(([id, value]) => [id, isRecord(value) ? value : {}])),
60
+ defaults: workspaceDefaults(data.defaults),
61
+ needsMigration: data.documents !== undefined,
61
62
  }
62
63
  }
63
64
 
@@ -70,51 +71,67 @@ export function isWorkspaceRoot(dir: string): boolean {
70
71
  }
71
72
  }
72
73
 
73
- function entries(config: WorkspaceConfig): string[] {
74
- const found: string[] = []
75
- for (const pattern of config.documents) {
76
- const parts = patternSegments(pattern)
77
- const walk = (dir: string, rel: string, i: number): string[] => {
78
- const part = parts[i]!
79
- const last = i === parts.length - 1
80
- const names = typeof part === 'string'
81
- ? [part]
82
- : (() => {
83
- try {
84
- return readdirSync(dir).filter(name => !SKIPPED.has(name) && !name.startsWith('.') && part.test(name)).sort()
85
- } catch {
86
- return []
87
- }
88
- })()
89
- return names.flatMap((name) => {
90
- const path = join(dir, name)
91
- const next = rel ? `${rel}/${name}` : name
92
- if (last) return name === DOCUMENT_ENTRY && existsSync(path) && statSync(path).isFile() ? [next] : []
93
- return existsSync(path) && statSync(path).isDirectory() ? walk(path, next, i + 1) : []
94
- })
95
- }
96
- for (const entry of walk(config.root, '', 0)) if (!found.includes(entry)) found.push(entry)
97
- }
98
- return found
99
- }
100
-
101
74
  export interface DocumentEntry {
102
75
  dir: string
103
76
  entry: string
104
77
  }
105
78
 
106
- export interface FoundDocument extends DocumentSummary, DocumentEntry {}
79
+ export interface FoundDocument extends DocumentSummary, DocumentEntry {
80
+ /** The folder of the document it is under in the tree; absent at the top level. */
81
+ parentDir?: string
82
+ }
83
+
84
+ const entryOf = (path: string): DocumentEntry => ({ dir: path.split('/').slice(0, -1).join('/'), entry: path })
107
85
 
108
- /** The configured documents that exist on disk, without reading their content. */
86
+ /**
87
+ * The documents on disk, without validating them: in a workspace every entry file found by the scan, in tree order
88
+ * (depth first, siblings by rank); entries the tree leaves out (a second document with a taken ID) follow by path.
89
+ */
109
90
  export function listDocumentEntries(config: WorkspaceConfig): DocumentEntry[] {
110
- return entries(config).map(entry => ({ dir: entry.split('/').slice(0, -1).join('/'), entry }))
91
+ if (config.singleDeck) return [{ dir: '', entry: DOCUMENT_ENTRY }]
92
+ const { documents, tree } = workspaceDocuments(config.root)
93
+ const ordered = tree.order.map(node => node.path)
94
+ const listed = new Set(ordered)
95
+ return [...ordered, ...documents.map(document => document.path).filter(path => !listed.has(path))].map(entryOf)
111
96
  }
112
97
 
113
- export function readDocumentSummary(config: WorkspaceConfig, { dir, entry }: DocumentEntry): FoundDocument {
98
+ /** The tree position of every listed document, by folder. */
99
+ export function documentPlaces(config: WorkspaceConfig): Map<string, { id: string, parent: string | null, depth: number, schemaVersion: unknown }> {
100
+ if (config.singleDeck) return new Map()
101
+ const { documents, tree } = workspaceDocuments(config.root)
102
+ const versions = new Map(documents.map(document => [document.path, document.schemaVersion]))
103
+ return new Map(tree.order.map(node => [entryOf(node.path).dir, { id: node.id, parent: node.parent, depth: node.depth, schemaVersion: versions.get(node.path) }]))
104
+ }
105
+
106
+ /** The metadata a document decides with (its language, plugins, renderers), inherited settings filled in. */
107
+ function effectiveMetadata(config: WorkspaceConfig, entry: string, parsed: unknown, scanned?: WorkspaceDocuments): Record<string, unknown> {
108
+ if (!isRecord(parsed) || !isRecord(parsed.metadata)) return {}
109
+ if (!isRecord(parsed.production) || !isRecord(parsed.placement)) return parsed.metadata
110
+ return effectiveDocumentIn(config.root, join(config.root, entry), parsed as unknown as PresmiumDocument, scanned).metadata as unknown as Record<string, unknown>
111
+ }
112
+
113
+ /** What a summary needs of a document file (not its pages or blocks), kept until the file changes. */
114
+ const heads = new Map<string, { mtimeMs: number, size: number, value: unknown }>()
115
+ const headOf = (parsed: unknown) => isRecord(parsed) ? { id: parsed.id, schemaVersion: parsed.schemaVersion, placement: parsed.placement, metadata: parsed.metadata, production: parsed.production } : parsed
116
+ function documentHead(file: string): unknown {
117
+ const stat = statSync(file)
118
+ const known = heads.get(file)
119
+ if (known && known.mtimeMs === stat.mtimeMs && known.size === stat.size) return known.value
120
+ const value = headOf(JSON.parse(readFileSync(file, 'utf8')))
121
+ heads.set(file, { mtimeMs: stat.mtimeMs, size: stat.size, value })
122
+ return value
123
+ }
124
+
125
+ /** A document file another reader (the document index, reading asynchronously) has just parsed: listing it needs no second read. */
126
+ export function primeDocumentHead(file: string, mtimeMs: number, size: number, parsed: unknown): void {
127
+ heads.set(file, { mtimeMs, size, value: headOf(parsed) })
128
+ }
129
+
130
+ /** `scanned`: the workspace scan the caller already has (listing every document must not scan once per document). */
131
+ export function readDocumentSummary(config: WorkspaceConfig, { dir, entry }: DocumentEntry, scanned?: WorkspaceDocuments): FoundDocument {
114
132
  let headmatter: Record<string, unknown> = {}
115
133
  try {
116
- const parsed: unknown = JSON.parse(readFileSync(join(config.root, entry), 'utf8'))
117
- headmatter = isRecord(parsed) && isRecord(parsed.metadata) ? parsed.metadata : {}
134
+ headmatter = effectiveMetadata(config, entry, documentHead(join(config.root, entry)), scanned)
118
135
  } catch {
119
136
  }
120
137
  const tags = strings(headmatter.tags)
@@ -129,14 +146,82 @@ export function readDocumentSummary(config: WorkspaceConfig, { dir, entry }: Doc
129
146
  }
130
147
  }
131
148
 
149
+ const listed = new WeakMap<WorkspaceConfig, { generation: number, settings: unknown, documents: FoundDocument[] }>()
150
+
151
+ /**
152
+ * The documents with their summaries, in tree order. Where the workspace service's index keeps the documents, the list
153
+ * is reused until one of them changes; otherwise each document file is looked at (and read only when it changed).
154
+ */
132
155
  export function listDocuments(config: WorkspaceConfig): FoundDocument[] {
133
- return listDocumentEntries(config).map(entry => readDocumentSummary(config, entry))
156
+ const generation = config.singleDeck ? undefined : providedDocuments(config.root)?.generation
157
+ const settings = workspaceSettings(config.root)
158
+ const known = listed.get(config)
159
+ if (generation !== undefined && known?.generation === generation && known.settings === settings) return known.documents.map(document => ({ ...document }))
160
+ const documents = summarize(config)
161
+ if (generation !== undefined) listed.set(config, { generation, settings, documents })
162
+ return documents.map(document => ({ ...document }))
163
+ }
164
+
165
+ /** Each document's summary with the stamps of its file and its ancestors' files it was made from. */
166
+ const summaries = new WeakMap<WorkspaceConfig, { settings: unknown, entries: Map<string, { key: string, summary: FoundDocument }> }>()
167
+
168
+ function summarize(config: WorkspaceConfig): FoundDocument[] {
169
+ const places = documentPlaces(config)
170
+ const dirs = new Map([...places].map(([dir, place]) => [place.id, dir]))
171
+ // With an index in this process, a summary is made again only when its file or an ancestor's file changed.
172
+ const provided = config.singleDeck ? undefined : providedDocuments(config.root)
173
+ const settings = workspaceSettings(config.root)
174
+ const cache = summaries.get(config)
175
+ const known = cache?.settings === settings ? cache.entries : new Map<string, { key: string, summary: FoundDocument }>()
176
+ summaries.set(config, { settings, entries: known })
177
+ const keyOf = (entry: DocumentEntry): string | undefined => {
178
+ if (!provided) return undefined
179
+ const stamps: string[] = [String(provided.stamps.get(entry.entry))]
180
+ for (let at = places.get(entry.dir)?.parent ?? null, hops = 0; at !== null && hops < 64; hops++) {
181
+ const dir = dirs.get(at)
182
+ if (dir === undefined) break
183
+ stamps.push(String(provided.stamps.get(dir ? `${dir}/${DOCUMENT_ENTRY}` : DOCUMENT_ENTRY)))
184
+ at = places.get(dir)?.parent ?? null
185
+ }
186
+ return stamps.join('|')
187
+ }
188
+ let scanned: WorkspaceDocuments | undefined
189
+ return listDocumentEntries(config).map((entry) => {
190
+ const key = keyOf(entry), cached = known.get(entry.entry)
191
+ const found = key !== undefined && cached?.key === key ? cached.summary : readDocumentSummary(config, entry, scanned ??= config.singleDeck ? undefined : workspaceDocuments(config.root))
192
+ if (key !== undefined) known.set(entry.entry, { key, summary: found })
193
+ const parent = places.get(entry.dir)?.parent
194
+ const parentDir = parent === null || parent === undefined ? undefined : dirs.get(parent)
195
+ return parentDir === undefined ? found : { ...found, parentDir }
196
+ })
134
197
  }
135
198
 
136
199
  export function documentSummaries(config: WorkspaceConfig): DocumentSummary[] {
137
- return listDocuments(config).map(({ entry: _entry, ...document }) => document)
200
+ const places = documentPlaces(config)
201
+ return listDocuments(config).map(({ entry: _entry, ...document }) => {
202
+ const place = places.get(document.dir)
203
+ return place ? { ...document, id: place.id, parent: place.parent, depth: place.depth } : document
204
+ })
138
205
  }
139
206
 
207
+ /** Whether a document may live in this folder: in a workspace any folder outside the skipped ones and translations. */
140
208
  export function isDocumentDir(config: WorkspaceConfig, dir: string): boolean {
141
- return config.documents.some(pattern => matchesPattern(pattern, dir ? `${dir}/${DOCUMENT_ENTRY}` : DOCUMENT_ENTRY))
209
+ if (config.singleDeck) return dir === ''
210
+ const parts = dir.split('/')
211
+ return dir !== '' && !parts.some(part => part === '' || part.startsWith('.') || SKIPPED.has(part)) && !parts.some((part, index) => part === 'locales' && index === parts.length - 2)
212
+ }
213
+
214
+ /** The document in `dir` with the settings it inherits from its ancestors and the workspace defaults; never saved. */
215
+ export function effectiveContent(config: WorkspaceConfig, dir: string, content: PresmiumDocument): EffectiveDocument {
216
+ return effectiveDocumentIn(config.root, join(config.root, dir ? `${dir}/${DOCUMENT_ENTRY}` : DOCUMENT_ENTRY), content)
217
+ }
218
+
219
+ /** What the document in `dir` inherits from its ancestors and the workspace defaults, without its own settings. */
220
+ export function inheritedContent(config: WorkspaceConfig, dir: string, content: PresmiumDocument): DocumentDefaults {
221
+ return inheritedSettingsIn(config.root, join(config.root, dir ? `${dir}/${DOCUMENT_ENTRY}` : DOCUMENT_ENTRY), content)
222
+ }
223
+
224
+ /** Which ancestor (or the workspace defaults, null) each setting the document in `dir` inherits comes from. */
225
+ export function inheritedOrigins(config: WorkspaceConfig, dir: string, content: PresmiumDocument): SettingOrigins {
226
+ return settingOriginsIn(config.root, join(config.root, dir ? `${dir}/${DOCUMENT_ENTRY}` : DOCUMENT_ENTRY), content)
142
227
  }
@@ -2,11 +2,11 @@ import { createReadStream, realpathSync } from 'node:fs'
2
2
  import { basename, isAbsolute, relative, resolve, sep } from 'node:path'
3
3
  import { Readable } from 'node:stream'
4
4
  import { lookup } from 'mime-types'
5
- import type { TeachingDocument } from '@lincyaw/kernel'
5
+ import type { PresmiumDocument } from '@lincyaw/kernel'
6
6
  import { RequestError } from './errors.ts'
7
7
 
8
8
  /** Read only a file registered by the current canonical document, without compiling it. */
9
- export function documentAssetResponse(root: string, directory: string, document: TeachingDocument, id: string, readableFile: (path: string) => string, signal?: AbortSignal): Response {
9
+ export function documentAssetResponse(root: string, directory: string, document: PresmiumDocument, id: string, readableFile: (path: string) => string, signal?: AbortSignal): Response {
10
10
  const asset = document.assets[id]
11
11
  if (!asset) throw new RequestError(404, 'document-asset-missing')
12
12
  if (!asset.location || /^(?:[a-z][a-z\d+.-]*:|\/)/i.test(asset.location)) throw new RequestError(400, 'document-asset-not-local')