@lincyaw/workspace 1.0.0-rc.7 → 1.0.0-rc.72

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.
@@ -0,0 +1,356 @@
1
+ import { mkdirSync, readdirSync, rmSync, statSync, writeFileSync } from 'node:fs'
2
+ import { basename, join } from 'node:path'
3
+ 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'
4
+ import type { CapturedBox, CapturedSlide, CaptureHook, DocumentCapture, IRDocument, IRSection } from '@lincyaw/kernel'
5
+ import { playwrightChromium } from '@lincyaw/kernel/node'
6
+
7
+ /** What capturing uses of Playwright's Chromium. */
8
+ interface Page {
9
+ goto(url: string, options: { waitUntil: 'load', timeout: number }): Promise<unknown>
10
+ waitForFunction(script: string, arg: undefined, options: { timeout: number }): Promise<unknown>
11
+ evaluate<R, A>(run: (arg: A) => R | Promise<R>, arg: A): Promise<R>
12
+ screenshot(options: { type: 'png', fullPage?: boolean, clip?: { x: number, y: number, width: number, height: number } }): Promise<Buffer>
13
+ setViewportSize(size: { width: number, height: number }): Promise<void>
14
+ setContent(html: string, options: { waitUntil: 'load', timeout: number }): Promise<void>
15
+ on(event: 'pageerror', listener: (error: Error) => void): void
16
+ on(event: 'console', listener: (message: { type(): string, text(): string }) => void): void
17
+ }
18
+ interface Context {
19
+ newPage(): Promise<Page>
20
+ close(): Promise<void>
21
+ }
22
+ interface Browser {
23
+ newContext(options: { viewport: { width: number, height: number }, deviceScaleFactor: number, reducedMotion: 'reduce', colorScheme: 'light' | 'dark', serviceWorkers: 'block' }): Promise<Context>
24
+ close(): Promise<void>
25
+ }
26
+ interface Chromium { launch(): Promise<Browser> }
27
+
28
+ export interface CaptureOptions {
29
+ root: string
30
+ /** The service's own address. */
31
+ url(): string
32
+ /** The viewer page of a document once the page can show it (its path below the address), as previews open it. */
33
+ viewerPage(document: string): Promise<string | undefined>
34
+ /** The document's current runtime snapshot. */
35
+ compiled(document: string): Promise<IRDocument>
36
+ /** Where the pictures are written. */
37
+ dir: string
38
+ }
39
+
40
+ interface View { width: number, height: number, scale: number, appearance: 'light' | 'dark' }
41
+
42
+ const PAGE_MS = 120_000
43
+ const IDLE_MS = 120_000
44
+ const KEEP = 20
45
+ const FIT_ROUNDS = 3
46
+ const READING_WIDTH = 1280
47
+ const READING_HEIGHT = 900
48
+ const MIN_WIDTH = 320
49
+ const MAX_WIDTH = 2560
50
+ const THUMB_WIDTH = 320
51
+ const SHEET_GAP = 16
52
+
53
+ class CaptureError extends Error {
54
+ readonly status: number
55
+ readonly detail?: Record<string, unknown>
56
+ constructor(code: string, status: number, detail?: Record<string, unknown>) {
57
+ super(code)
58
+ this.status = status
59
+ if (detail) this.detail = detail
60
+ }
61
+ }
62
+
63
+ /**
64
+ * Pictures of documents as readers see them, in a headless Chromium kept while it is used: the viewer page of a
65
+ * document, opened with `?capture`, is driven by its capture hook (a slide step by step and moment by moment, so that a
66
+ * picture is the same however often it is taken; a section of the reading page scrolled through and at rest). One request
67
+ * at a time; the pictures stay in `dir`, the last few requests.
68
+ */
69
+ export function createDocumentCapture(options: CaptureOptions): { service: DocumentCapture, close(): Promise<void> } {
70
+ let browser: Promise<Browser> | undefined
71
+ let idle: ReturnType<typeof setTimeout> | undefined
72
+ let queue: Promise<unknown> = Promise.resolve()
73
+ const launch = (): Promise<Browser> => {
74
+ clearTimeout(idle)
75
+ browser ??= playwrightChromium<Chromium>(options.root, import.meta.url).then(chromium => chromium.launch()).catch((error: unknown) => {
76
+ browser = undefined
77
+ throw new CaptureError('capture-browser-unavailable', 503, { reason: errorMessage(error) })
78
+ })
79
+ return browser
80
+ }
81
+ const release = () => {
82
+ clearTimeout(idle)
83
+ idle = setTimeout(() => void close(), IDLE_MS)
84
+ idle.unref?.()
85
+ }
86
+ const close = async () => {
87
+ clearTimeout(idle)
88
+ const open = browser
89
+ browser = undefined
90
+ await (await open?.catch(() => undefined))?.close().catch(() => undefined)
91
+ }
92
+
93
+ /** The section asked for, by id or by its number from 1. */
94
+ const sectionOf = (doc: IRDocument, asked: string) => {
95
+ const section = doc.sections.find(s => s.id === asked) ?? doc.sections[Number(asked) - 1]
96
+ if (!section) throw new CaptureError('capture-section-unknown', 404, { section: asked, sections: doc.sections.map(s => s.id) })
97
+ return section
98
+ }
99
+
100
+ /** The document's viewer page in a form, opened with its capture hook in a new context; `run` uses it, then it closes. */
101
+ const open = async <T>(document: string, form: 'web' | 'slides', view: View & { captions?: boolean }, signal: AbortSignal | undefined, run: (tab: Page, problems: Set<string>, out: string) => Promise<T>): Promise<T> => {
102
+ const page = await options.viewerPage(document).catch((error: unknown) => {
103
+ throw new CaptureError('capture-preview-failed', 409, { reason: errorMessage(error) })
104
+ })
105
+ if (!page) throw new CaptureError('capture-preview-failed', 409)
106
+ signal?.throwIfAborted()
107
+ const context = await (await launch()).newContext({ viewport: { width: view.width, height: view.height }, deviceScaleFactor: view.scale, reducedMotion: 'reduce', colorScheme: view.appearance, serviceWorkers: 'block' })
108
+ const problems = new Set<string>()
109
+ try {
110
+ const tab = await context.newPage()
111
+ tab.on('pageerror', error => problems.add(error.message))
112
+ tab.on('console', message => { if (message.type() === 'error') problems.add(message.text().slice(0, 500)) })
113
+ const address = new URL(page, options.url())
114
+ if (form === 'slides') address.searchParams.set('form', 'slides')
115
+ if (view.captions === false) address.searchParams.set(CAPTIONS_PARAM, 'off')
116
+ address.searchParams.set(CAPTURE_PARAM, '')
117
+ address.searchParams.set(PREVIEW_APPEARANCE_PARAM, view.appearance)
118
+ await tab.goto(address.href, { waitUntil: 'load', timeout: PAGE_MS })
119
+ await tab.waitForFunction(`Boolean(window.${CAPTURE_HOOK})`, undefined, { timeout: PAGE_MS })
120
+ const out = join(options.dir, `${new Date().toISOString().replace(/[:.]/g, '-')}-${process.pid}`)
121
+ mkdirSync(out, { recursive: true })
122
+ return await run(tab, problems, out)
123
+ } catch (error) {
124
+ if (error instanceof CaptureError || signal?.aborted) throw error
125
+ // A page that loads again while it is driven loses its hook: going back reloaded it.
126
+ if (/context was destroyed|because of a navigation/i.test(errorMessage(error))) throw new CaptureError('capture-page-reloaded', 409, { problems: [...problems] })
127
+ throw new CaptureError('capture-failed', 500, { reason: errorMessage(error), problems: [...problems] })
128
+ } finally {
129
+ await context.close().catch(() => undefined)
130
+ prune(options.dir)
131
+ }
132
+ }
133
+
134
+ const slides: DocumentCapture['slides'] = async (document, request, signal) => {
135
+ const doc = await options.compiled(document)
136
+ const section = sectionOf(doc, request.section)
137
+ const steps = request.steps ?? Array.from({ length: section.steps + 1 }, (_, step) => step)
138
+ const wrong = steps.find(step => !Number.isInteger(step) || step < 0 || step > section.steps)
139
+ if (wrong !== undefined) throw new CaptureError('capture-step-invalid', 400, { step: wrong, last: section.steps })
140
+ const arrive = request.arrive ?? 'direct'
141
+ // Reached backward, a step is at rest: moments apply to steps drawn directly.
142
+ const moments: (number | null)[] = request.at?.length && arrive === 'direct' ? request.at : [null]
143
+ if (moments.some(at => at !== null && (!Number.isFinite(at) || at < 0))) throw new CaptureError('capture-moment-invalid', 400)
144
+ const count = steps.length * moments.length
145
+ if (count === 0 || count > CAPTURE_MAX_FRAMES) throw new CaptureError('capture-too-many-frames', 400, { requested: count, max: CAPTURE_MAX_FRAMES })
146
+ const shape = slideShape(doc)
147
+ const scale = request.scale ?? 1
148
+ return await open(document, 'slides', { width: shape.width, height: shape.height, scale, appearance: request.appearance ?? 'light', captions: request.captions }, signal, async (tab, problems, out) => {
149
+ 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)
150
+ await fit(tab, shape, section.id, steps[0]!, () => show(steps[0]!, moments[0]!))
151
+ const frames: CapturedSlide[] = [], images: Uint8Array[] = []
152
+ for (const step of steps) {
153
+ for (const at of moments) {
154
+ signal?.throwIfAborted()
155
+ const shown = await show(step, at, arrive)
156
+ for (const problem of shown.problems) problems.add(problem)
157
+ const measured = await tab.evaluate(measure, { section: section.id, step, selector: request.measure ?? '', width: shape.width, max: CAPTURE_MAX_BOXES })
158
+ if (!measured) throw new CaptureError('capture-slide-missing', 500, { section: section.id, step })
159
+ const clip = request.clip
160
+ ? { 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 }
161
+ : { x: measured.slide.x, y: measured.slide.y, width: measured.slide.width, height: measured.slide.height }
162
+ const png = await tab.screenshot({ type: 'png', clip })
163
+ const file = join(out, `${section.id}-${step}${at === null ? '' : `-${at}ms`}${arrive === 'backward' ? '-backward' : ''}.png`)
164
+ writeFileSync(file, png)
165
+ images.push(png)
166
+ 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 } : {} })
167
+ }
168
+ }
169
+ return { document, shape: { width: shape.width, height: shape.height }, frames, problems: [...problems], images }
170
+ })
171
+ }
172
+
173
+ const reading: DocumentCapture['reading'] = async (document, request, signal) => {
174
+ const doc = await options.compiled(document)
175
+ const section = sectionOf(doc, request.section)
176
+ const width = Math.round(request.width ?? READING_WIDTH)
177
+ if (!Number.isFinite(width) || width < MIN_WIDTH || width > MAX_WIDTH) throw new CaptureError('capture-width-invalid', 400, { min: MIN_WIDTH, max: MAX_WIDTH })
178
+ const scale = request.scale ?? 1
179
+ return await open(document, 'web', { width, height: READING_HEIGHT, scale, appearance: request.appearance ?? 'light' }, signal, async (tab, problems, out) => {
180
+ 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)
181
+ for (const problem of shown.problems) problems.add(problem)
182
+ const measured = await tab.evaluate(measureSection, { section: section.id, selector: request.measure ?? '', max: CAPTURE_MAX_BOXES })
183
+ if (!measured) throw new CaptureError('capture-slide-missing', 500, { section: section.id })
184
+ const height = Math.min(measured.height, CAPTURE_MAX_HEIGHT)
185
+ const png = await tab.screenshot({ type: 'png', fullPage: true, clip: { x: measured.x, y: measured.y, width: measured.width, height } })
186
+ const file = join(out, `${section.id}-reading-${width}.png`)
187
+ writeFileSync(file, png)
188
+ 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 } : {} }
189
+ return { document, width, frames: [frame], problems: [...problems], images: [png] }
190
+ })
191
+ }
192
+
193
+ const overview: DocumentCapture['overview'] = async (document, request, signal) => {
194
+ const doc = await options.compiled(document)
195
+ const every = request.steps === 'all'
196
+ const positions = doc.sections.flatMap(section => (every ? Array.from({ length: section.steps + 1 }, (_, step) => step) : [section.steps]).map(step => ({ section, step })))
197
+ if (positions.length === 0 || positions.length > CAPTURE_MAX_OVERVIEW) throw new CaptureError('capture-too-many-frames', 400, { requested: positions.length, max: CAPTURE_MAX_OVERVIEW })
198
+ const shape = slideShape(doc)
199
+ const appearance = request.appearance ?? 'light'
200
+ const columns = Math.max(1, Math.min(8, Math.round(request.columns ?? 4)))
201
+ return await open(document, 'slides', { width: shape.width, height: shape.height, scale: 1, appearance, captions: request.captions }, signal, async (tab, problems, out) => {
202
+ 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)
203
+ const first = positions[0]!
204
+ await fit(tab, shape, first.section.id, first.step, () => show(first.section.id, first.step))
205
+ // Names that sort in reading order: the page number (from 1) and the step (from 0, as the tools count it) padded.
206
+ const pageWidth = String(doc.sections.length).length
207
+ const stepWidth = String(Math.max(...doc.sections.map(section => section.steps))).length
208
+ const frames: { section: string, slide: number, step: number, file: string, narration: string }[] = [], pictures: Buffer[] = []
209
+ for (const { section, step } of positions) {
210
+ signal?.throwIfAborted()
211
+ for (const problem of (await show(section.id, step)).problems) problems.add(problem)
212
+ const measured = await tab.evaluate(measure, { section: section.id, step, selector: '', width: shape.width, max: 0 })
213
+ if (!measured) throw new CaptureError('capture-slide-missing', 500, { section: section.id, step })
214
+ const png = await tab.screenshot({ type: 'png', clip: { x: measured.slide.x, y: measured.slide.y, width: measured.slide.width, height: measured.slide.height } })
215
+ const file = join(out, `${String(section.index).padStart(pageWidth, '0')}-${String(step).padStart(stepWidth, '0')}-${section.id}.png`)
216
+ writeFileSync(file, png)
217
+ frames.push({ section: section.id, slide: section.index, step, file, narration: narrationOf(section, step) })
218
+ pictures.push(png)
219
+ }
220
+ // Sheets of thumbnails, each labelled with its page, step and title, for reading the whole piece at a glance.
221
+ const sheets: string[] = [], images: Uint8Array[] = []
222
+ await tab.setViewportSize({ width: columns * (THUMB_WIDTH + SHEET_GAP) + SHEET_GAP, height: READING_HEIGHT })
223
+ for (let start = 0; start < frames.length; start += CAPTURE_SHEET_SIZE) {
224
+ signal?.throwIfAborted()
225
+ 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]! }))
226
+ await tab.setContent(sheetHtml(cells, columns, appearance), { waitUntil: 'load', timeout: PAGE_MS })
227
+ const png = await tab.screenshot({ type: 'png', fullPage: true })
228
+ const file = join(out, `sheet-${String(sheets.length + 1).padStart(2, '0')}.png`)
229
+ writeFileSync(file, png)
230
+ sheets.push(file)
231
+ images.push(png)
232
+ }
233
+ // The narration beside the pictures, for a reader who looks at whole slides and reads the script as text.
234
+ const narrationFile = join(out, 'narration.md')
235
+ writeFileSync(narrationFile, frames.map(frame => `## ${basename(frame.file)}\n\n${frame.narration || '—'}\n`).join('\n'))
236
+ return { document, dir: out, frames, narrationFile, sheets, problems: [...problems], images }
237
+ })
238
+ }
239
+
240
+ /** One capture at a time; the browser closes when none came for a while. */
241
+ const queued = <A extends unknown[], R>(run: (...args: A) => Promise<R>) => (...args: A): Promise<R> => {
242
+ const next = queue.then(async () => {
243
+ try {
244
+ return await run(...args)
245
+ } finally {
246
+ release()
247
+ }
248
+ })
249
+ queue = next.catch(() => undefined)
250
+ return next
251
+ }
252
+
253
+ return {
254
+ service: { slides: queued(slides), reading: queued(reading), overview: queued(overview) },
255
+ close,
256
+ }
257
+ }
258
+
259
+ /**
260
+ * The page fits the slide in its window with a margin: the window is made that much larger, a few times, until the slide
261
+ * shows at its own size.
262
+ */
263
+ async function fit(tab: Page, shape: { width: number, height: number }, section: string, step: number, show: () => Promise<unknown>): Promise<void> {
264
+ let viewport = { width: shape.width, height: shape.height }
265
+ await show()
266
+ for (let round = 0; round < FIT_ROUNDS; round++) {
267
+ const fitted = await tab.evaluate(measure, { section, step, selector: '', width: shape.width, max: 0 })
268
+ if (!fitted || Math.abs(fitted.slide.scale - 1) < 0.005) return
269
+ viewport = { width: Math.round(viewport.width / fitted.slide.scale), height: Math.round(viewport.height / fitted.slide.scale) }
270
+ await tab.setViewportSize(viewport)
271
+ await show()
272
+ }
273
+ }
274
+
275
+ /** A step's narration as text: the script written for it, line by line. */
276
+ function narrationOf(section: IRSection, step: number): string {
277
+ const id = section.stepIds?.[step]
278
+ return (id ? section.stepNarrations?.[id] ?? [] : []).map(line => line.text).join('\n')
279
+ }
280
+
281
+ const escapeHtml = (text: string) => text.replace(/[&<>"]/g, char => `&#${char.charCodeAt(0)};`)
282
+
283
+ /** A sheet of thumbnails with their labels: plain HTML for the capturing browser, not a page of the product. */
284
+ function sheetHtml(cells: { label: string, png: Buffer }[], columns: number, appearance: 'light' | 'dark'): string {
285
+ const [paper, ink, line] = appearance === 'dark' ? ['#161614', '#ece9e2', '#3a3833'] : ['#f7f5f0', '#1c1b19', '#e3ded3']
286
+ return `<!doctype html><meta charset="utf-8"><style>
287
+ body { margin: 0; padding: ${SHEET_GAP}px; background: ${paper}; color: ${ink}; font: 13px/1.4 system-ui, sans-serif; }
288
+ main { display: grid; grid-template-columns: repeat(${columns}, ${THUMB_WIDTH}px); gap: ${SHEET_GAP}px; }
289
+ figure { margin: 0; } img { display: block; width: ${THUMB_WIDTH}px; border: 1px solid ${line}; }
290
+ figcaption { margin-top: 4px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
291
+ </style><main>${cells.map(cell => `<figure><img src="data:image/png;base64,${cell.png.toString('base64')}"><figcaption>${escapeHtml(cell.label)}</figcaption></figure>`).join('')}</main>`
292
+ }
293
+
294
+ /** In the page: the slide shown at the step, in viewport pixels, and the boxes of `selector` in it, in slide pixels. */
295
+ 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 {
296
+ const slides = [...document.querySelectorAll<HTMLElement>(`.pm-slide[data-section="${CSS.escape(section)}"]`)]
297
+ const slide = slides.find(element => element.dataset.step === String(step) && element.getBoundingClientRect().width > 0) ?? slides.find(element => element.getBoundingClientRect().width > 0)
298
+ if (!slide) return undefined
299
+ const frame = slide.getBoundingClientRect()
300
+ const scale = frame.width / width
301
+ const round = (value: number) => Math.round(value * 10) / 10
302
+ const boxes: CapturedBox[] = []
303
+ if (selector) {
304
+ for (const element of [...slide.querySelectorAll<HTMLElement>(selector)].slice(0, max)) {
305
+ const box = element.getBoundingClientRect()
306
+ const style = getComputedStyle(element)
307
+ const attributes: Record<string, string> = {}
308
+ 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)
309
+ boxes.push({
310
+ x: round((box.left - frame.left) / scale),
311
+ y: round((box.top - frame.top) / scale),
312
+ width: round(box.width / scale),
313
+ height: round(box.height / scale),
314
+ visible: box.width > 0 && box.height > 0 && style.visibility !== 'hidden' && style.display !== 'none' && Number(style.opacity) > 0,
315
+ text: (element.textContent ?? '').replace(/\s+/g, ' ').trim().slice(0, 80),
316
+ attributes,
317
+ })
318
+ }
319
+ }
320
+ return { slide: { x: frame.left, y: frame.top, width: frame.width, height: frame.height, scale }, boxes }
321
+ }
322
+
323
+ /** In the page: the section of the reading page, in page pixels, and the boxes of `selector` in it, relative to it. */
324
+ function measureSection({ section, selector, max }: { section: string, selector: string, max: number }): { x: number, y: number, width: number, height: number, boxes: CapturedBox[] } | undefined {
325
+ const element = document.querySelector<HTMLElement>(`section.pm-section[data-section="${CSS.escape(section)}"]`)
326
+ if (!element) return undefined
327
+ const frame = element.getBoundingClientRect()
328
+ const round = (value: number) => Math.round(value * 10) / 10
329
+ const boxes: CapturedBox[] = []
330
+ if (selector) {
331
+ for (const node of [...element.querySelectorAll<HTMLElement>(selector)].slice(0, max)) {
332
+ const box = node.getBoundingClientRect()
333
+ const style = getComputedStyle(node)
334
+ const attributes: Record<string, string> = {}
335
+ 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)
336
+ boxes.push({
337
+ x: round(box.left - frame.left),
338
+ y: round(box.top - frame.top),
339
+ width: round(box.width),
340
+ height: round(box.height),
341
+ visible: box.width > 0 && box.height > 0 && style.visibility !== 'hidden' && style.display !== 'none' && Number(style.opacity) > 0,
342
+ text: (node.textContent ?? '').replace(/\s+/g, ' ').trim().slice(0, 80),
343
+ attributes,
344
+ })
345
+ }
346
+ }
347
+ return { x: frame.left + window.scrollX, y: frame.top + window.scrollY, width: frame.width, height: frame.height, boxes }
348
+ }
349
+
350
+ /** Keeps the pictures of the last few requests. */
351
+ function prune(dir: string): void {
352
+ try {
353
+ const runs = readdirSync(dir).map(name => ({ path: join(dir, name), time: statSync(join(dir, name)).mtimeMs })).sort((a, b) => b.time - a.time)
354
+ for (const run of runs.slice(KEEP)) rmSync(run.path, { recursive: true, force: true })
355
+ } catch {}
356
+ }
@@ -125,6 +125,7 @@ export function readDocumentSummary(config: WorkspaceConfig, { dir, entry }: Doc
125
125
  ...typeof headmatter.description === 'string' && headmatter.description.trim() ? { description: headmatter.description.trim() } : {},
126
126
  ...typeof headmatter.lang === 'string' && headmatter.lang.trim() ? { lang: headmatter.lang.trim() } : {},
127
127
  ...tags.length > 0 ? { tags } : {},
128
+ ...isRecord(headmatter.renderers) && headmatter.renderers.slides !== undefined ? { slides: true } : {},
128
129
  }
129
130
  }
130
131
 
@@ -8,6 +8,7 @@ import { productionAssetFile, validateDocumentRecordingAdoption, validateDocumen
8
8
  import { readAuthoringDocument } from './document-editor.ts'
9
9
  import { catchRequestErrors, RequestError } from './errors.ts'
10
10
  import type { Revisions } from './revisions.ts'
11
+ import type { MediaUploadsOwner } from './media-uploads.ts'
11
12
  import type { SourceEditor, SourceTransactionHistory } from './source-editor.ts'
12
13
 
13
14
  export interface DocumentAudioServices { audio?: ProductionAudioAuthoring, findings?: Finding[] }
@@ -15,6 +16,7 @@ export interface DocumentAudioAuthoringOptions extends DocumentAudioServices {
15
16
  root: string
16
17
  editor: SourceEditor
17
18
  revisions?: Revisions
19
+ uploads?: MediaUploadsOwner
18
20
  reviewRequired?: boolean
19
21
  services?(document: string, source: CanonicalSource): Promise<DocumentAudioServices>
20
22
  }
@@ -29,8 +31,35 @@ const binding = (current: ReturnType<typeof readAuthoringDocument>): CanonicalSo
29
31
  const titleOf = (name: string) => [...(name.replaceAll('\\', '/').split('/').at(-1) ?? '').replace(/[\u0000-\u001f\u007f-\u009f]/g, '').trim()].slice(0, ASSET_TITLE_MAX_LENGTH).join('')
30
32
  const stamp = (stat: Awaited<ReturnType<Awaited<ReturnType<typeof open>>['stat']>>) => [stat.dev, stat.ino, stat.size, stat.mtimeMs, stat.ctimeMs].join(':')
31
33
 
34
+ /** Scoped bounded audio reads are shared by import, inspection and voice cloning. */
35
+ export async function readDocumentAudioBytes(editor: SourceEditor, ctx: RequestContext, path: string, signal?: AbortSignal, maxBytes = DOCUMENT_AUDIO_MAX_BYTES): Promise<Uint8Array> {
36
+ signal?.throwIfAborted()
37
+ const file = editor.readableFile({ document: ctx.document, home: false }, path, ctx.member)
38
+ const handle = await open(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK).catch(error => {
39
+ if (error.code === 'ELOOP') throw new RequestError(403, 'audio-file-path')
40
+ if (error.code === 'ENOENT' || error.code === 'ENOTDIR') throw new RequestError(404, 'audio-file-missing')
41
+ throw error
42
+ })
43
+ try {
44
+ const before = await handle.stat(), named = await lstat(editor.readableFile({ document: ctx.document, home: false }, path, ctx.member))
45
+ if (!before.isFile() || before.dev !== named.dev || before.ino !== named.ino) throw new RequestError(403, 'audio-file-path')
46
+ if (!before.size || before.size > maxBytes) throw new RequestError(413, 'production.asset-size')
47
+ const bytes = new Uint8Array(before.size + 1); let length = 0
48
+ while (length < bytes.length) {
49
+ signal?.throwIfAborted()
50
+ const read = await handle.read(bytes, length, bytes.length - length, length)
51
+ if (!read.bytesRead) break
52
+ length += read.bytesRead
53
+ }
54
+ const after = await handle.stat(), current = await lstat(editor.readableFile({ document: ctx.document, home: false }, path, ctx.member))
55
+ if (length !== before.size || stamp(before) !== stamp(after) || after.dev !== current.dev || after.ino !== current.ino) throw new RequestError(409, 'audio-file-changed')
56
+ signal?.throwIfAborted()
57
+ return bytes.slice(0, length)
58
+ } finally { await handle.close() }
59
+ }
60
+
32
61
  /** Owns the canonical transaction and receipts; plugin services only inspect actual media. */
33
- export function createDocumentAudioAuthoring({ root, editor, revisions, audio, services, reviewRequired = false }: DocumentAudioAuthoringOptions): { service: DocumentAudioAuthoring, routes: Record<string, Route>, close(): Promise<void> } {
62
+ export function createDocumentAudioAuthoring({ root, editor, revisions, audio, services, reviewRequired = false, uploads }: DocumentAudioAuthoringOptions): { service: DocumentAudioAuthoring, routes: Record<string, Route>, close(): Promise<void> } {
34
63
  const receipts = new Map<string, Receipt>(), imports = new Map<string, { signature: string, source: CanonicalSource, promise: Promise<VerifiedDocumentAudioImport> }>(), operations = new Set<Operation>()
35
64
  const clipChanges = new Map<string, { signature: string, promise: Promise<VerifiedDocumentMediaClipChange> }>()
36
65
  const recordingChanges = new Map<string, { signature: string, promise: Promise<VerifiedDocumentRecordingAdoption> }>()
@@ -64,31 +93,7 @@ export function createDocumentAudioAuthoring({ root, editor, revisions, audio, s
64
93
  editor.assertEditable(scopeOf(document), path, member)
65
94
  if (path.split('/').some(part => part.startsWith('.'))) throw new RequestError(403, 'audio-file-path')
66
95
  }
67
- const reader = async (ctx: RequestContext, path: string, signal?: AbortSignal): Promise<Uint8Array> => {
68
- signal?.throwIfAborted()
69
- const file = editor.readableFile(scopeOf(ctx.document), path, ctx.member)
70
- const handle = await open(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK).catch(error => {
71
- if (error.code === 'ELOOP') throw new RequestError(403, 'audio-file-path')
72
- if (error.code === 'ENOENT' || error.code === 'ENOTDIR') throw new RequestError(404, 'audio-file-missing')
73
- throw error
74
- })
75
- try {
76
- const before = await handle.stat(), named = await lstat(editor.readableFile(scopeOf(ctx.document), path, ctx.member))
77
- if (!before.isFile() || before.dev !== named.dev || before.ino !== named.ino) throw new RequestError(403, 'audio-file-path')
78
- if (!before.size || before.size > DOCUMENT_AUDIO_MAX_BYTES) throw new RequestError(413, 'production.asset-size')
79
- const bytes = new Uint8Array(before.size + 1); let length = 0
80
- while (length < bytes.length) {
81
- signal?.throwIfAborted()
82
- const read = await handle.read(bytes, length, bytes.length - length, length)
83
- if (!read.bytesRead) break
84
- length += read.bytesRead
85
- }
86
- const after = await handle.stat(), current = await lstat(editor.readableFile(scopeOf(ctx.document), path, ctx.member))
87
- if (length !== before.size || stamp(before) !== stamp(after) || after.dev !== current.dev || after.ino !== current.ino) throw new RequestError(409, 'audio-file-changed')
88
- signal?.throwIfAborted()
89
- return bytes.slice(0, length)
90
- } finally { await handle.close() }
91
- }
96
+ const reader = (ctx: RequestContext, path: string, signal?: AbortSignal) => readDocumentAudioBytes(editor, ctx, path, signal)
92
97
  const pathOf = (ctx: RequestContext, asset: Asset) => {
93
98
  const file = productionAssetFile(join(root, ctx.document), asset.location)
94
99
  if (!file) throw new RequestError(422, 'production.asset-path')
@@ -128,7 +133,7 @@ export function createDocumentAudioAuthoring({ root, editor, revisions, audio, s
128
133
  }
129
134
  }
130
135
  const importKey = (ctx: RequestContext, id: string) => JSON.stringify(['audio', ctx.document, ctx.member.id, id])
131
- const importSignature = (change: DocumentAudioImport, source: CanonicalSource, title: string, sha256: string, byteLength: number) => hash(JSON.stringify([change.id, source.documentId, change.baseDocumentVersion, source.fingerprint, title, sha256, byteLength]))
136
+ const importSignature = (change: DocumentAudioImport, source: CanonicalSource, title: string, sha256: string, byteLength: number, upload?: string) => hash(JSON.stringify([change.id, source.documentId, change.baseDocumentVersion, source.fingerprint, title, sha256, byteLength, ...upload ? [upload] : []]))
132
137
  /** A known intent replays (receipt still current) or joins its flight; a different payload under the same ID is refused. */
133
138
  const known = (ctx: RequestContext, signature: string, previous: Receipt | undefined, pending: { signature: string } | undefined) => {
134
139
  if (!previous && !pending) return false
@@ -136,10 +141,10 @@ export function createDocumentAudioAuthoring({ root, editor, revisions, audio, s
136
141
  if (previous) opened(ctx, previous.version)
137
142
  return true
138
143
  }
139
- const once = (ctx: RequestContext, change: DocumentAudioImport, source: CanonicalSource, title: string, sha256: string, byteLength: number, origin: 'editor' | 'agent', run: () => Promise<VerifiedDocumentAudioImport>) => {
144
+ const once = (ctx: RequestContext, change: DocumentAudioImport, source: CanonicalSource, title: string, sha256: string, byteLength: number, origin: 'editor' | 'agent', run: () => Promise<VerifiedDocumentAudioImport>, upload?: string) => {
140
145
  authorize(ctx.member); available()
141
146
  if (origin === 'agent' && reviewRequired) throw new RequestError(409, 'authoring-review-required')
142
- const key = importKey(ctx, change.id), signature = importSignature(change, source, title, sha256, byteLength)
147
+ const key = importKey(ctx, change.id), signature = importSignature(change, source, title, sha256, byteLength, upload)
143
148
  const previous = receipts.get(key)
144
149
  if (previous) {
145
150
  if (previous.signature !== signature) throw new RequestError(409, 'document-change-id-reused')
@@ -152,7 +157,7 @@ export function createDocumentAudioAuthoring({ root, editor, revisions, audio, s
152
157
  imports.set(key, { signature, source, promise })
153
158
  return promise
154
159
  }
155
- const importBytes = async (ctx: RequestContext, change: DocumentAudioImport, title: string, bytes: Uint8Array, source: CanonicalSource, found: DocumentAudioServices, origin: 'editor' | 'agent', signal: AbortSignal) => {
160
+ const importBytes = async (ctx: RequestContext, change: DocumentAudioImport, title: string, bytes: Uint8Array, source: CanonicalSource, found: DocumentAudioServices, origin: 'editor' | 'agent', signal: AbortSignal, upload?: string) => {
156
161
  check(signal)
157
162
  if (!found.audio) throw new RequestError(503, 'production-audio-unavailable')
158
163
  const current = opened(ctx, change.baseDocumentVersion, source), assetId = `audio_${randomUUID().replaceAll('-', '')}`, probed = await found.audio.inspectBytes(assetId, bytes, signal)
@@ -163,7 +168,7 @@ export function createDocumentAudioAuthoring({ root, editor, revisions, audio, s
163
168
  check(signal); opened(ctx, change.baseDocumentVersion, source)
164
169
  const saved = await editor.transactionWithBinary(scopeOf(ctx.document), { path: current.source.path, content, base: current.source.version }, { path, content: bytes }, ctx.member, history(ctx, candidate, origin, async () => { check(signal) }))
165
170
  const version = saved.versions.find(file => file.path === current.source.path)!.version
166
- const receipt: Receipt = { signature: importSignature(change, source, title, hash(bytes), bytes.length), source, version, files: saved.versions, assetId, inspection: probed.inspection, ...saved.revision ? { commit: saved.revision } : {} }
171
+ const receipt: Receipt = { signature: importSignature(change, source, title, hash(bytes), bytes.length, upload), source, version, files: saved.versions, assetId, inspection: probed.inspection, ...saved.revision ? { commit: saved.revision } : {} }
167
172
  remember(importKey(ctx, change.id), receipt)
168
173
  // A committed write is verified even when its request disconnected or shutdown began meanwhile.
169
174
  return readback(ctx, change.id, receipt)
@@ -315,12 +320,25 @@ export function createDocumentAudioAuthoring({ root, editor, revisions, audio, s
315
320
  recordingChanges.set(key, { signature, promise })
316
321
  return promise
317
322
  }
323
+ const mediaInput = async (ctx: RequestContext, source: CanonicalSource, location: { path?: string, upload?: string }, signal?: AbortSignal) => {
324
+ if (location.upload !== undefined) {
325
+ signal?.throwIfAborted()
326
+ if (!uploads) throw new RequestError(503, 'media-upload-unavailable')
327
+ return uploads.read(ctx.document, source.documentId, ctx.member, location.upload, 'audio')
328
+ }
329
+ workspacePath(ctx.document, location.path!, ctx.member)
330
+ return { bytes: await reader(ctx, location.path!, signal), name: titleOf(basename(location.path!)) }
331
+ }
318
332
  const workspaceImport = (document: string, request: DocumentWorkspaceAudioImport, member: Member) => {
319
333
  authorize(member); available()
320
334
  if (!validateDocumentWorkspaceAudioImport(request)) throw new RequestError(400, 'document-audio-import-invalid')
321
335
  if (Buffer.byteLength(JSON.stringify(request)) > DOCUMENT_AUDIO_REQUEST_MAX_BYTES) throw new RequestError(413, 'document-audio-request-size')
322
- workspacePath(document, request.file.path, member)
323
- return { ctx: ctxOf(document, member), title: titleOf(basename(request.file.path)), change: { id: request.id, baseDocumentVersion: request.source.version } }
336
+ if (request.file.path !== undefined) workspacePath(document, request.file.path, member)
337
+ else {
338
+ if (!uploads) throw new RequestError(503, 'media-upload-unavailable')
339
+ if (uploads.read(document, request.source.documentId, member, request.file.upload, 'audio').name !== request.file.name) throw new RequestError(409, 'audio-file-changed')
340
+ }
341
+ return { ctx: ctxOf(document, member), title: request.file.path !== undefined ? titleOf(basename(request.file.path)) : request.file.name, change: { id: request.id, baseDocumentVersion: request.source.version } }
324
342
  }
325
343
  const service: DocumentAudioAuthoring = {
326
344
  capabilities: (document, member) => work(member, undefined, async signal => {
@@ -338,16 +356,15 @@ export function createDocumentAudioAuthoring({ root, editor, revisions, audio, s
338
356
  }),
339
357
  inspectWorkspace: (document, request, member, signal) => work(member, signal, async signal => {
340
358
  if (!validateDocumentWorkspaceAudioInspect(request)) throw new RequestError(400, 'document-audio-query-invalid')
341
- workspacePath(document, request.path, member)
342
359
  const ctx = ctxOf(document, member)
343
360
  opened(ctx, request.source.version, request.source)
344
- const [bytes, found] = await Promise.all([reader(ctx, request.path, signal), resolved(document, request.source, signal)])
361
+ const [{ bytes, name }, found] = await Promise.all([mediaInput(ctx, request.source, request, signal), resolved(document, request.source, signal)])
345
362
  if (!found.audio) throw new RequestError(503, 'production-audio-unavailable')
346
363
  const probed = await found.audio.inspectBytes('workspace-audio-probe', bytes, signal)
347
364
  const { assetId: _assetId, mediaId: _mediaId, ...inspection } = probed.inspection
348
365
  if (inspection.sha256 !== hash(bytes) || inspection.byteLength !== bytes.length) throw new RequestError(409, 'audio-inspection-changed')
349
366
  check(signal); opened(ctx, request.source.version, request.source)
350
- return { document, source: request.source, file: { path: request.path, sha256: inspection.sha256, byteLength: inspection.byteLength }, inspection } satisfies WorkspaceAudioInspectionAnswer
367
+ return { document, source: request.source, file: { ...request.upload ? { upload: request.upload, name } : { path: request.path! }, sha256: inspection.sha256, byteLength: inspection.byteLength }, inspection } satisfies WorkspaceAudioInspectionAnswer
351
368
  }),
352
369
  readProductionPlan: (document, request, member, signal) => work(member, signal, async signal => {
353
370
  if (!validateDocumentProductionPlanQuery(request)) throw new RequestError(400, 'production-query-invalid')
@@ -365,9 +382,10 @@ export function createDocumentAudioAuthoring({ root, editor, revisions, audio, s
365
382
  return work(member, signal, async signal => {
366
383
  if (reviewRequired) throw new RequestError(409, 'authoring-review-required')
367
384
  const key = importKey(ctx, request.id)
368
- if (known(ctx, importSignature(change, request.source, title, request.file.sha256, request.file.byteLength), receipts.get(key), imports.get(key))) return
385
+ if (known(ctx, importSignature(change, request.source, title, request.file.sha256, request.file.byteLength, request.file.upload), receipts.get(key), imports.get(key))) return
369
386
  opened(ctx, request.source.version, request.source)
370
- const [bytes, found] = await Promise.all([reader(ctx, request.file.path, signal), resolved(document, request.source, signal)])
387
+ const [{ bytes, name }, found] = await Promise.all([mediaInput(ctx, request.source, request.file, signal), resolved(document, request.source, signal)])
388
+ if (request.file.upload && name !== request.file.name) throw new RequestError(409, 'audio-file-changed')
371
389
  if (bytes.length !== request.file.byteLength || hash(bytes) !== request.file.sha256) throw new RequestError(409, 'audio-file-changed')
372
390
  if (!found.audio) throw new RequestError(503, 'production-audio-unavailable')
373
391
  await found.audio.inspectBytes('workspace-audio-probe', bytes, signal)
@@ -378,10 +396,11 @@ export function createDocumentAudioAuthoring({ root, editor, revisions, audio, s
378
396
  const { ctx, title, change } = workspaceImport(document, request, member)
379
397
  return work(member, signal, signal => once(ctx, change, request.source, title, request.file.sha256, request.file.byteLength, 'agent', async () => {
380
398
  opened(ctx, request.source.version, request.source)
381
- const [bytes, found] = await Promise.all([reader(ctx, request.file.path, signal), resolved(document, request.source, signal)])
399
+ const [{ bytes, name }, found] = await Promise.all([mediaInput(ctx, request.source, request.file, signal), resolved(document, request.source, signal)])
400
+ if (request.file.upload && name !== request.file.name) throw new RequestError(409, 'audio-file-changed')
382
401
  if (bytes.length !== request.file.byteLength || hash(bytes) !== request.file.sha256) throw new RequestError(409, 'audio-file-changed')
383
- return importBytes(ctx, change, title, bytes, request.source, found, 'agent', signal)
384
- }))
402
+ return importBytes(ctx, change, title, bytes, request.source, found, 'agent', signal, request.file.upload)
403
+ }, request.file.upload))
385
404
  },
386
405
  validateClipChange: (document, request, member, signal) => work(member, signal, async signal => {
387
406
  if (!validateDocumentMediaClipValidation(request)) throw new RequestError(400, 'document-media-clip-invalid')
@@ -1,4 +1,5 @@
1
1
  import { createHash, randomUUID } from 'node:crypto'
2
+ import { isRecord } from '@lincyaw/kernel'
2
3
  import { applyDocumentOperations, AUTHORING_API_VERSION, createDocumentPage, DOCUMENT_ENTRY, DOCUMENT_OPERATION_TYPES, DOCUMENT_READ_MAX_REQUEST_CHARS, DOCUMENT_READ_MAX_RESPONSE_CHARS, DOCUMENT_SCHEMA_VERSION, documentOutline, documentPart, DocumentReadError, duplicateDocumentPage, fnv1a64, hasRole, moveDocumentPage, pageDeletionImpact, removeDocumentPage, renameDocumentPage, validateDocument } from '@lincyaw/kernel'
3
4
  import { validateDocumentChange, validateDocumentPageChange, validateDocumentPageChangeApply, validateDocumentPageDuplication, validateDocumentPageDuplicationApply, validateDocumentOutlineQuery, validateDocumentPartQuery } from '@lincyaw/kernel/node'
4
5
  import type { AppliedDocumentChange, ApplyDocumentChange, CanonicalSource, DocumentAnswer, DocumentAuthoring, DocumentChange, DocumentChangeAnswer, DocumentChangePlan, DocumentIssue, DocumentPageAction, DocumentPageChangePlan, DocumentPageDuplicationPlan, Member, RequestContext, SourceTransactionChange, TeachingDocument } from '@lincyaw/kernel'
@@ -133,7 +134,12 @@ export function createDocumentEditor({ editor, revisions, reviewRequired = false
133
134
  if (receipt) return { ...current, changeId: change.id, files: receipt.files, ...receipt.commit ? { commit: receipt.commit } : {} }
134
135
  const candidate = await filesOf(document, current, change)
135
136
  const ownHistory: SourceTransactionHistory | undefined = revisions ? { run: work => revisions.transaction(work), commit: (paths, lang) => revisions.commitWhileLocked({ paths, summary: lang?.startsWith('en') ? 'Edit document' : '编辑文稿', body: '', origin: { kind: origin, member } }) } : undefined
136
- const saved = await editor.transaction(editor.scope(document), candidate.changes, member, ownHistory)
137
+ const saved = await editor.transaction(editor.scope(document), candidate.changes, member, ownHistory).catch((error: unknown) => {
138
+ if (error instanceof RequestError && error.status === 409 && isRecord(error.detail?.conflict) && error.detail.conflict.path === entryOf(document)) {
139
+ throw new RequestError(409, 'document-version-changed', { version: error.detail.conflict.version })
140
+ }
141
+ throw error
142
+ })
137
143
  const version = saved.versions.find(file => file.path === entryOf(document))!.version
138
144
  remember(receipts, key, { signature, version, files: saved.versions, ...saved.revision ? { commit: saved.revision } : {} })
139
145
  const verified = await read(document, member)