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

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
@@ -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)
@@ -125,17 +142,86 @@ export function readDocumentSummary(config: WorkspaceConfig, { dir, entry }: Doc
125
142
  ...typeof headmatter.description === 'string' && headmatter.description.trim() ? { description: headmatter.description.trim() } : {},
126
143
  ...typeof headmatter.lang === 'string' && headmatter.lang.trim() ? { lang: headmatter.lang.trim() } : {},
127
144
  ...tags.length > 0 ? { tags } : {},
145
+ ...isRecord(headmatter.renderers) && headmatter.renderers.slides !== undefined ? { slides: true } : {},
128
146
  }
129
147
  }
130
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
+ */
131
155
  export function listDocuments(config: WorkspaceConfig): FoundDocument[] {
132
- 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
+ })
133
197
  }
134
198
 
135
199
  export function documentSummaries(config: WorkspaceConfig): DocumentSummary[] {
136
- 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
+ })
137
205
  }
138
206
 
207
+ /** Whether a document may live in this folder: in a workspace any folder outside the skipped ones and translations. */
139
208
  export function isDocumentDir(config: WorkspaceConfig, dir: string): boolean {
140
- 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)
141
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')
@@ -3,11 +3,12 @@ import { constants } from 'node:fs'
3
3
  import { lstat, open } from 'node:fs/promises'
4
4
  import { basename, join, relative } from 'node:path'
5
5
  import { ASSET_TITLE_MAX_LENGTH, DOCUMENT_AUDIO_MAX_BYTES, DOCUMENT_AUDIO_REQUEST_MAX_BYTES, fnv1a64, hasRole, isRecord, jsonResponse, ProductionAudioRefusal, recordingSourceRange, recordingStepIssue, validateDocument } from '@lincyaw/kernel'
6
- import type { Asset, CanonicalSource, DocumentRecordingAdoption, VerifiedDocumentRecordingAdoption, DocumentAudioAuthoring, DocumentAudioCapabilities, DocumentAudioImport, DocumentAudioInspectionAnswer, DocumentChangeAnswer, DocumentMediaClipEdit, DocumentMediaClipValidation, DocumentMediaClipValidationAnswer, DocumentWorkspaceAudioImport, Finding, Member, ProductionAudioAuthoring, RequestContext, Route, TeachingDocument, VerifiedDocumentAudioImport, VerifiedDocumentMediaClipChange, WorkspaceAudioInspectionAnswer } from '@lincyaw/kernel'
6
+ import type { Asset, CanonicalSource, DocumentRecordingAdoption, VerifiedDocumentRecordingAdoption, DocumentAudioAuthoring, DocumentAudioCapabilities, DocumentAudioImport, DocumentAudioInspectionAnswer, DocumentChangeAnswer, DocumentMediaClipEdit, DocumentMediaClipValidation, DocumentMediaClipValidationAnswer, DocumentWorkspaceAudioImport, Finding, Member, ProductionAudioAuthoring, RequestContext, Route, PresmiumDocument, VerifiedDocumentAudioImport, VerifiedDocumentMediaClipChange, WorkspaceAudioInspectionAnswer } from '@lincyaw/kernel'
7
7
  import { productionAssetFile, validateDocumentRecordingAdoption, validateDocumentAudioInspect, validateDocumentWorkspaceAudioImport, validateDocumentWorkspaceAudioInspect, validateDocumentMediaClipValidation, validateDocumentMediaClipEdit, validateDocumentProductionPlanQuery } from '@lincyaw/kernel/node'
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>, busy(): boolean, 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')
@@ -103,13 +108,13 @@ export function createDocumentAudioAuthoring({ root, editor, revisions, audio, s
103
108
  check(signal); opened(ctx, source.version, source)
104
109
  return inspection
105
110
  }
106
- const history = (ctx: RequestContext, content: TeachingDocument, origin: 'editor' | 'agent', validate?: () => Promise<void>): SourceTransactionHistory => ({
111
+ const history = (ctx: RequestContext, content: PresmiumDocument, origin: 'editor' | 'agent', validate?: () => Promise<void>): SourceTransactionHistory => ({
107
112
  run: work => { const guarded = async () => { await validate?.(); return work() }; return revisions ? revisions.transaction(guarded) : guarded() },
108
113
  commit: async paths => {
109
114
  if (!revisions) return undefined
110
115
  const ignored = (await Promise.all(paths.map(async path => await revisions.ignores(path) ? path : undefined))).filter((path): path is string => Boolean(path))
111
116
  if (ignored.length) throw new RequestError(409, 'document-files-ignored', { ignored })
112
- return revisions.commitWhileLocked({ paths, summary: content.metadata.lang?.startsWith('en') ? 'Edit audio media' : '编辑音频素材', body: '', origin: { kind: origin, member: ctx.member } })
117
+ return revisions.commitWhileLocked({ paths, summary: editor.effective(ctx.document, content).metadata.lang.startsWith('en') ? 'Edit audio media' : '编辑音频素材', body: '', origin: { kind: origin, member: ctx.member } })
113
118
  },
114
119
  })
115
120
  const remember = (key: string, receipt: Receipt) => { receipts.set(key, receipt); while (receipts.size > MAX_RECEIPTS) receipts.delete(receipts.keys().next().value!) }
@@ -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)
@@ -273,7 +278,7 @@ export function createDocumentAudioAuthoring({ root, editor, revisions, audio, s
273
278
  const current = opened(ctx, request.source.version, request.source), step = current.content.steps[request.stepId], asset = current.content.assets[request.assetId]
274
279
  if (!step) throw new RequestError(404, 'document-step-missing')
275
280
  if (!asset) throw new RequestError(404, 'production.asset-missing')
276
- const original = current.content.production.stepOverrides[step.id]?.voiceSource ?? current.content.production.sectionOverrides?.[step.sectionId]?.voiceSource ?? current.content.production.defaults.voiceSource
281
+ const original = current.content.production.stepOverrides[step.id]?.voiceSource ?? current.content.production.sectionOverrides?.[step.sectionId]?.voiceSource ?? current.effective.production.defaults.voiceSource
277
282
  if (request.sourceRange && (original?.type !== 'recording' || original.assetId !== asset.id)) throw new RequestError(409, 'recording-source-changed')
278
283
  const issue = recordingStepIssue(current.content, request.stepId)
279
284
  if (issue) throw new RequestError(422, issue)
@@ -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')
@@ -469,5 +488,5 @@ export function createDocumentAudioAuthoring({ root, editor, revisions, audio, s
469
488
  }),
470
489
  },
471
490
  }
472
- return { service, routes, async close() { closed = true; for (const operation of operations) operation.controller.abort(); await Promise.allSettled([...operations].map(operation => operation.finished)); receipts.clear() } }
491
+ return { service, routes, busy: () => operations.size > 0, async close() { closed = true; for (const operation of operations) operation.controller.abort(); await Promise.allSettled([...operations].map(operation => operation.finished)); receipts.clear() } }
473
492
  }
@@ -1,8 +1,11 @@
1
1
  import { createHash, randomUUID } from 'node:crypto'
2
- 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'
2
+ import { setImmediate as nextTurn } from 'node:timers/promises'
3
+ import { isRecord } from '@lincyaw/kernel'
4
+ import { applyDocumentOperations, AUTHORING_API_VERSION, documentSettings, 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
5
  import { validateDocumentChange, validateDocumentPageChange, validateDocumentPageChangeApply, validateDocumentPageDuplication, validateDocumentPageDuplicationApply, validateDocumentOutlineQuery, validateDocumentPartQuery } from '@lincyaw/kernel/node'
4
- import type { AppliedDocumentChange, ApplyDocumentChange, CanonicalSource, DocumentAnswer, DocumentAuthoring, DocumentChange, DocumentChangeAnswer, DocumentChangePlan, DocumentIssue, DocumentPageAction, DocumentPageChangePlan, DocumentPageDuplicationPlan, Member, RequestContext, SourceTransactionChange, TeachingDocument } from '@lincyaw/kernel'
6
+ import type { AppliedDocumentChange, ApplyDocumentChange, CanonicalSource, DocumentAnswer, DocumentAuthoring, DocumentChange, DocumentChangeAnswer, DocumentChangePlan, DocumentIssue, DocumentPageAction, DocumentPageChangePlan, DocumentPageDuplicationPlan, Member, RequestContext, SourceTransactionChange, PresmiumDocument } from '@lincyaw/kernel'
5
7
  import { RequestError } from './errors.ts'
8
+ import { checkDocumentText, rememberCheckedText } from './document-check.ts'
6
9
  import { applyDocumentAuthoringAction, DOCUMENT_ACTION_MAX_REQUEST_CHARS, DOCUMENT_ACTION_MAX_RESPONSE_CHARS, DOCUMENT_AUTHORING_ACTION_TYPES, DOCUMENT_PARAMETER_MAX_CHANGES, DOCUMENT_PARAMETER_MAX_PATH_DEPTH, DocumentCommentError, DocumentComponentError, DocumentCaptionTimingError, ProductionAudioRefusal } from '@lincyaw/kernel'
7
10
  import { validateDocumentAuthoringAction, validateDocumentAuthoringActionReference, validateDocumentAuthoringActionImpact } from '@lincyaw/kernel/node'
8
11
  import type { AppliedDocumentAuthoringAction, DocumentAuthoringActionReference, DocumentPageChangeReference, DocumentPageDuplicationReference, DocumentAuthoringActionPlan, DocumentComponentImpactAnswer, DocumentAuthoringAction, ProductionPlan } from '@lincyaw/kernel'
@@ -17,11 +20,10 @@ const signatureOf = (change: DocumentChange) => createHash('sha256').update(JSON
17
20
  const keyOf = (document: string, member: Member, id: string) => JSON.stringify([document, member.id, id])
18
21
  const sourceOf = (answer: DocumentAnswer) => ({ documentId: answer.content.id, version: answer.version, fingerprint: answer.fingerprint })
19
22
 
20
- export function decodeAuthoringDocument(content: string): { document?: TeachingDocument, issues: DocumentIssue[] } {
21
- let value: unknown
22
- try { value = JSON.parse(content.replace(/^\uFEFF/, '')) }
23
- catch { return { issues: [{ path: '', code: 'json-syntax', message: 'The document is not valid JSON.', severity: 'error' }] } }
24
- return validateDocument(value)
23
+ export function decodeAuthoringDocument(content: string): { document?: PresmiumDocument, issues: DocumentIssue[] } {
24
+ const checked = checkDocumentText(content)
25
+ if (checked.syntax) return { issues: [{ path: '', code: 'json-syntax', message: 'The document is not valid JSON.', severity: 'error' }] }
26
+ return checked.document ? { document: checked.document, issues: checked.issues } : { issues: checked.issues }
25
27
  }
26
28
 
27
29
  export function readAuthoringDocument(editor: SourceEditor, ctx: Pick<RequestContext, 'document' | 'member'>) {
@@ -29,7 +31,7 @@ export function readAuthoringDocument(editor: SourceEditor, ctx: Pick<RequestCon
29
31
  const source = editor.read(editor.scope(ctx.document), entryOf(ctx.document), ctx.member)
30
32
  const checked = decodeAuthoringDocument(source.content)
31
33
  if (!checked.document || checked.issues.some(issue => issue.severity === 'error')) throw new RequestError(422, 'document-invalid', { issues: checked.issues })
32
- return { source, content: checked.document, issues: checked.issues }
34
+ return { source, content: checked.document, effective: editor.effective(ctx.document, checked.document), issues: checked.issues }
33
35
  }
34
36
 
35
37
  export interface DocumentEditor extends DocumentAuthoring {
@@ -58,10 +60,10 @@ export function createDocumentEditor({ editor, revisions, reviewRequired = false
58
60
  while (table.size > MAX_RECEIPTS) table.delete(table.keys().next().value!)
59
61
  }
60
62
  const read = async (document: string, member: Member): Promise<DocumentAnswer> => {
61
- const { source, content, issues } = readAuthoringDocument(editor, { document, member })
62
- return { document, version: source.version, fingerprint: fnv1a64(source.content), content, issues }
63
+ const { source, content, effective, issues } = readAuthoringDocument(editor, { document, member })
64
+ return { document, version: source.version, fingerprint: fnv1a64(source.content), content, settings: documentSettings(effective), inherited: editor.inherited(document, content), inheritedFrom: editor.inheritedFrom(document, content), issues }
63
65
  }
64
- const readSelection = <T>(document: string, expected: CanonicalSource | undefined, member: Member, select: (content: TeachingDocument, source: CanonicalSource) => T): T => {
66
+ const readSelection = <T>(document: string, expected: CanonicalSource | undefined, member: Member, select: (content: PresmiumDocument, source: CanonicalSource) => T): T => {
65
67
  if (!hasRole(member, 'editor')) throw new RequestError(403, 'authoring-permission-denied')
66
68
  const scope = editor.scope(document), path = entryOf(document)
67
69
  const readSource = () => {
@@ -93,7 +95,8 @@ export function createDocumentEditor({ editor, revisions, reviewRequired = false
93
95
  if (!checked.change) throw new RequestError(400, 'document-change-invalid', { issues: checked.issues })
94
96
  return checked.change
95
97
  }
96
- const filesOf = async (document: string, current: DocumentAnswer, change: DocumentChange): Promise<{ content: TeachingDocument, issues: DocumentIssue[], changes: SourceTransactionChange[] }> => {
98
+ const filesOf = async (document: string, current: DocumentAnswer, change: DocumentChange): Promise<{ content: PresmiumDocument, issues: DocumentIssue[], changes: SourceTransactionChange[] }> => {
99
+ await nextTurn()
97
100
  if (current.version !== change.baseDocumentVersion) throw new RequestError(409, 'document-version-changed', { version: current.version })
98
101
  let candidate: unknown = change.replacement
99
102
  if (change.operations) {
@@ -106,6 +109,8 @@ export function createDocumentEditor({ editor, revisions, reviewRequired = false
106
109
  const path = entryOf(document), fileChanges = change.fileChanges ?? []
107
110
  if (fileChanges.some(file => file.path === path)) throw new RequestError(422, 'document-file-repeated')
108
111
  const changes = [{ path, content: `${JSON.stringify(checked.document, null, 2)}\n`, base: current.version }, ...fileChanges]
112
+ // The text written is the document just validated: its checks are not repeated when it is read back.
113
+ rememberCheckedText(changes[0]!.content, true, checked.issues)
109
114
  if (revisions) {
110
115
  const ignored = (await Promise.all(changes.map(async file => await revisions.ignores(file.path) ? file.path : undefined))).filter((path): path is string => Boolean(path))
111
116
  if (ignored.length) throw new RequestError(409, 'document-files-ignored', { ignored })
@@ -128,14 +133,24 @@ export function createDocumentEditor({ editor, revisions, reviewRequired = false
128
133
  await editor.planTransaction(editor.scope(document), candidate.changes, member)
129
134
  }
130
135
  const saveChange = async (document: string, raw: DocumentChange, member: Member, origin: 'editor' | 'agent' = 'editor'): Promise<DocumentChangeAnswer> => {
131
- const change = checkedChange(raw), current = await read(document, member)
136
+ // Validating a large document takes milliseconds; each check gets its own turn of the event loop.
137
+ const change = checkedChange(raw)
138
+ await nextTurn()
139
+ const current = await read(document, member)
140
+ await nextTurn()
132
141
  const signature = signatureOf(change), key = keyOf(document, member, change.id), receipt = replayOf(document, change, member, current)
133
142
  if (receipt) return { ...current, changeId: change.id, files: receipt.files, ...receipt.commit ? { commit: receipt.commit } : {} }
134
143
  const candidate = await filesOf(document, current, change)
135
144
  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)
145
+ const saved = await editor.transaction(editor.scope(document), candidate.changes, member, ownHistory).catch((error: unknown) => {
146
+ if (error instanceof RequestError && error.status === 409 && isRecord(error.detail?.conflict) && error.detail.conflict.path === entryOf(document)) {
147
+ throw new RequestError(409, 'document-version-changed', { version: error.detail.conflict.version })
148
+ }
149
+ throw error
150
+ })
137
151
  const version = saved.versions.find(file => file.path === entryOf(document))!.version
138
152
  remember(receipts, key, { signature, version, files: saved.versions, ...saved.revision ? { commit: saved.revision } : {} })
153
+ await nextTurn()
139
154
  const verified = await read(document, member)
140
155
  if (verified.version !== version || saved.versions.some(file => editor.read(editor.scope(document), file.path, member).version !== file.version)) throw new RequestError(409, 'document-readback-changed', { changeId: change.id, committed: true, version, currentVersion: verified.version })
141
156
  return { ...verified, changeId: change.id, files: saved.versions, ...saved.revision ? { commit: saved.revision } : {} }
@@ -320,7 +335,7 @@ export function createDocumentEditor({ editor, revisions, reviewRequired = false
320
335
  })
321
336
  const planId = randomUUID(), record: Plan = { key, signature: '', expires: Date.now() + PLAN_LIFETIME_MS, ready: false }
322
337
  const result = (async (): Promise<DocumentPageChangePlan> => {
323
- let candidate: TeachingDocument, sectionId: string, created
338
+ let candidate: PresmiumDocument, sectionId: string, created
324
339
  try {
325
340
  if (action.type === 'create') { const next = createDocumentPage(current, action.after ?? null, action.title, randomUUID); candidate = next.document; created = next.ids; sectionId = next.ids.sectionId }
326
341
  else {