@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.
- package/README.md +4 -4
- package/package.json +8 -5
- package/src/domain/paths.ts +0 -15
- package/src/node/agent-activity.ts +46 -0
- package/src/node/archive.ts +33 -0
- package/src/node/authoring-clients.ts +73 -20
- package/src/node/authoring-windows.ts +165 -0
- package/src/node/build.ts +28 -23
- package/src/node/capture.ts +383 -0
- package/src/node/config.ts +136 -50
- package/src/node/document-assets.ts +2 -2
- package/src/node/document-audio.ts +65 -46
- package/src/node/document-authoring.ts +30 -15
- package/src/node/document-check.ts +36 -0
- package/src/node/document-history.ts +32 -5
- package/src/node/document-images.ts +24 -14
- package/src/node/document-import.ts +123 -0
- package/src/node/document-index.ts +644 -0
- package/src/node/document-materials.ts +80 -0
- package/src/node/document-operations.ts +4 -2
- package/src/node/document-transcription.ts +2 -1
- package/src/node/document-voice.ts +121 -13
- package/src/node/git-runner.mjs +19 -0
- package/src/node/git.ts +141 -22
- package/src/node/host-activity.ts +17 -0
- package/src/node/host-upgrade.ts +28 -0
- package/src/node/jobs.ts +40 -8
- package/src/node/local-history.ts +84 -0
- package/src/node/locks.ts +12 -0
- package/src/node/mcp-settings.ts +68 -0
- package/src/node/media-upload-messages.ts +4 -0
- package/src/node/media-upload-page.ts +57 -0
- package/src/node/media-upload.css +4 -0
- package/src/node/media-uploads.ts +116 -0
- package/src/node/page-delete.ts +0 -1
- package/src/node/project-files.ts +2 -2
- package/src/node/projects.ts +20 -5
- package/src/node/review/agent-session-reviews.ts +194 -63
- package/src/node/review/agent-workspace.ts +124 -0
- package/src/node/review/git-review.ts +47 -15
- package/src/node/review/record.ts +5 -1
- package/src/node/review/routes.ts +9 -1
- package/src/node/review/workspace-review.ts +87 -0
- package/src/node/revision-files.ts +54 -0
- package/src/node/revisions.ts +244 -59
- package/src/node/routes.ts +52 -59
- package/src/node/serve.ts +267 -52
- package/src/node/site.ts +5 -5
- package/src/node/source-editor.ts +66 -26
- package/src/node/speech-settings.ts +6 -8
- package/src/node/templates.ts +2 -2
- package/src/node/tree-operations.ts +425 -0
- package/src/node/tree-routes.ts +94 -0
- package/src/node/workbench-api.ts +14 -3
- package/src/node/workspace-changes.ts +130 -0
- package/src/node/workspace-migrate.ts +54 -0
- package/src/node/workspace-source.ts +133 -0
- package/src/node/writer.ts +21 -8
- package/templates/document/default/{lecture.json → index.pmd} +5 -1
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { validateDocument } from '@lincyaw/kernel'
|
|
2
|
+
import type { DocumentIssue, PresmiumDocument } from '@lincyaw/kernel'
|
|
3
|
+
|
|
4
|
+
/** How many recently checked document texts are remembered. */
|
|
5
|
+
const REMEMBERED = 16
|
|
6
|
+
const remembered = new Map<string, { valid: boolean, issues: DocumentIssue[] }>()
|
|
7
|
+
|
|
8
|
+
function remember(text: string, valid: boolean, issues: DocumentIssue[]): void {
|
|
9
|
+
remembered.delete(text)
|
|
10
|
+
remembered.set(text, { valid, issues })
|
|
11
|
+
while (remembered.size > REMEMBERED) remembered.delete(remembered.keys().next().value!)
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* A document file's text parsed and validated. Checking a large document holds the event loop for milliseconds, and a
|
|
16
|
+
* save checks the same text several times (the current file, the candidate, the readback), so the outcome for a
|
|
17
|
+
* recent text is remembered: the text is parsed again (a fresh document every time) and its checks are not repeated.
|
|
18
|
+
*/
|
|
19
|
+
export function checkDocumentText(content: string): { document?: PresmiumDocument, issues: DocumentIssue[], syntax?: true } {
|
|
20
|
+
const text = content.replace(/^/, '')
|
|
21
|
+
let value: unknown
|
|
22
|
+
try { value = JSON.parse(text) } catch { return { issues: [], syntax: true } }
|
|
23
|
+
const known = remembered.get(text)
|
|
24
|
+
if (known) {
|
|
25
|
+
remember(text, known.valid, known.issues)
|
|
26
|
+
return { ...known.valid ? { document: value as PresmiumDocument } : {}, issues: known.issues.map(issue => ({ ...issue })) }
|
|
27
|
+
}
|
|
28
|
+
const checked = validateDocument(value)
|
|
29
|
+
remember(text, Boolean(checked.document), checked.issues.map(issue => ({ ...issue })))
|
|
30
|
+
return checked
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** A text about to be written whose document was just validated: reading it back does not check it again. */
|
|
34
|
+
export function rememberCheckedText(content: string, valid: boolean, issues: DocumentIssue[]): void {
|
|
35
|
+
remember(content.replace(/^/, ''), valid, issues.map(issue => ({ ...issue })))
|
|
36
|
+
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createHash } from 'node:crypto'
|
|
2
|
-
import { DOCUMENT_ENTRY, DOCUMENT_HISTORY_MAX_FILE_BYTES, DOCUMENT_HISTORY_MAX_REQUEST_CHARS, DOCUMENT_HISTORY_MAX_RESPONSE_CHARS, DOCUMENT_HISTORY_PAGE_SIZE, fnv1a64, hasRole, jsonResponse, problemResponse } from '@lincyaw/kernel'
|
|
2
|
+
import { DOCUMENT_ENTRY, DOCUMENT_HISTORY_MAX_FILE_BYTES, DOCUMENT_SCHEMA_VERSION, DOCUMENT_HISTORY_MAX_REQUEST_CHARS, DOCUMENT_HISTORY_MAX_RESPONSE_CHARS, DOCUMENT_HISTORY_PAGE_SIZE, fnv1a64, hasRole, jsonResponse, problemResponse } from '@lincyaw/kernel'
|
|
3
3
|
import type { DocumentHistory, DocumentHistoryAnswer, DocumentHistoryBinding, DocumentHistoryChange, DocumentHistoryChanged, DocumentHistoryFile, DocumentHistorySource, HistoryRevision, Member, Route } from '@lincyaw/kernel'
|
|
4
4
|
import { validateDocumentHistoryChange, validateDocumentHistoryQuery, validateDocumentHistoryRead } from '@lincyaw/kernel/node'
|
|
5
5
|
import { listDocuments } from './config.ts'
|
|
@@ -53,7 +53,14 @@ export function createDocumentHistory(options: DocumentHistoryOptions): { servic
|
|
|
53
53
|
if ((/[\x00-\x1f\x7f]/.test(path) || path.split('/').some(part => part.startsWith('.'))) || documentDirOf(config, path) !== document) throw new RequestError(403, 'history-file-outside-document')
|
|
54
54
|
}
|
|
55
55
|
const compact = (document: string, entry: HistoryRevision, member: Member): HistoryRevision => {
|
|
56
|
-
|
|
56
|
+
// A revision can name every file of the workspace (the baseline does): only this document's files are checked in
|
|
57
|
+
// full, and only until the six shown are found.
|
|
58
|
+
const files: string[] = []
|
|
59
|
+
for (const path of entry.files) {
|
|
60
|
+
if (files.length >= 6) break
|
|
61
|
+
if (path.length > 500 || (document && !path.startsWith(`${document}/`))) continue
|
|
62
|
+
try { pathAllowed(document, path, member); files.push(path) } catch { /* Not shown. */ }
|
|
63
|
+
}
|
|
57
64
|
const message = (entry.message.split('\n')[0] ?? '').slice(0, 240)
|
|
58
65
|
return { id: entry.id, message, author: entry.author.slice(0, 120), date: entry.date, origin: { kind: entry.origin.kind }, files: files.slice(0, 6),
|
|
59
66
|
...entry.revertedBy ? { revertedBy: entry.revertedBy } : {}, ...entry.reverts ? { reverts: entry.reverts } : {}, ...entry.redo ? { redo: true } : {},
|
|
@@ -67,9 +74,25 @@ export function createDocumentHistory(options: DocumentHistoryOptions): { servic
|
|
|
67
74
|
if (origin === 'agent' && options.reviewRequired) throw new RequestError(409, 'authoring-review-required')
|
|
68
75
|
return { key: JSON.stringify([document, member.id, request.id]), signature: digest(JSON.stringify([which, request.id, request.snapshot, request.source.version, request.source.fingerprint, request.expect])) }
|
|
69
76
|
}
|
|
70
|
-
|
|
77
|
+
// A format upgrade (and a document's creation) is a boundary of its history: taking it back would leave the document
|
|
78
|
+
// without its entry file, or in a format this version no longer opens.
|
|
79
|
+
const supportedAt = async (revision: string, document: string): Promise<boolean> => {
|
|
80
|
+
try {
|
|
81
|
+
const bytes = await history().readFile(revision, entryOf(document), DOCUMENT_HISTORY_MAX_FILE_BYTES)
|
|
82
|
+
const value = JSON.parse(new TextDecoder().decode(bytes)) as { schemaVersion?: unknown }
|
|
83
|
+
return value.schemaVersion === DOCUMENT_SCHEMA_VERSION
|
|
84
|
+
} catch { return false }
|
|
85
|
+
}
|
|
86
|
+
const crossesBoundary = async (document: string, revision: string, paths?: string[]): Promise<boolean> => {
|
|
87
|
+
const files = paths ?? await history().filesOf(revision)
|
|
88
|
+
if (!files.includes(entryOf(document))) return false
|
|
89
|
+
const parent = await history().parentOf(revision)
|
|
90
|
+
return !parent || !await supportedAt(parent, document)
|
|
91
|
+
}
|
|
92
|
+
const targetPaths = async (document: string, request: DocumentHistoryChange, member: Member, which: 'undo' | 'redo' | 'revert') => {
|
|
71
93
|
const paths = await history().filesOf(request.expect)
|
|
72
94
|
if (!paths.length) throw new RequestError(404, 'history-revision-not-found')
|
|
95
|
+
if (which !== 'redo' && await crossesBoundary(document, request.expect, paths)) throw new RequestError(409, 'history-format-boundary')
|
|
73
96
|
for (const path of paths) {
|
|
74
97
|
pathAllowed(document, path, member)
|
|
75
98
|
const owners = await Promise.all([history().ownerAt(request.expect, path), history().ownerAt(`${request.expect}^1`, path)])
|
|
@@ -93,6 +116,10 @@ export function createDocumentHistory(options: DocumentHistoryOptions): { servic
|
|
|
93
116
|
if ((query.offset ?? 0) > 0 && !query.snapshot) throw new RequestError(400, 'history-snapshot-required')
|
|
94
117
|
if (query.snapshot !== undefined && query.snapshot !== before.snapshot) throw new RequestError(409, 'history-snapshot-changed')
|
|
95
118
|
const full = await revisions.historyWithUndo({ document }), changes = full.revisions.filter(entry => !entry.reverts), offset = query.offset ?? 0
|
|
119
|
+
// The upgrade from the earlier format is not offered as a step to undo or revert.
|
|
120
|
+
if (full.undo && await crossesBoundary(document, full.undo)) delete full.undo
|
|
121
|
+
const legacy = `${document ? `${document}/` : ''}lecture.json`
|
|
122
|
+
for (const entry of changes) if (entry.files.includes(legacy) && entry.files.includes(entryOf(document))) entry.revertible = false
|
|
96
123
|
if (offset > changes.length) throw new RequestError(400, 'history-offset-invalid')
|
|
97
124
|
const answer: DocumentHistoryAnswer = { document, available: true, historyBinding: before, revisions: [], ...full.undo ? { undo: full.undo } : {}, ...full.redo ? { redo: full.redo } : {} }
|
|
98
125
|
let index = offset
|
|
@@ -134,7 +161,7 @@ export function createDocumentHistory(options: DocumentHistoryOptions): { servic
|
|
|
134
161
|
if (known && !flight && !sameBinding(await binding(document, member), { source: known.answer.source, snapshot: known.answer.snapshot })) throw new RequestError(409, 'history-result-no-longer-current')
|
|
135
162
|
return
|
|
136
163
|
}
|
|
137
|
-
const paths = await targetPaths(document, request, member)
|
|
164
|
+
const paths = await targetPaths(document, request, member, which)
|
|
138
165
|
if (!sameBinding(await binding(document, member), { source: request.source, snapshot: request.snapshot })) throw new RequestError(409, 'history-source-changed')
|
|
139
166
|
const claimed = locks.claimAll(paths.map(path => documentDirOf(config, path)!), 'revision:revert')
|
|
140
167
|
if ('holder' in claimed) throw lockedError(claimed.document, claimed.holder)
|
|
@@ -154,7 +181,7 @@ export function createDocumentHistory(options: DocumentHistoryOptions): { servic
|
|
|
154
181
|
}
|
|
155
182
|
if (pending.size >= MAX_RECEIPTS) throw new RequestError(429, 'history-busy')
|
|
156
183
|
const work = Promise.resolve().then(async () => {
|
|
157
|
-
const paths = await targetPaths(document, request, member)
|
|
184
|
+
const paths = await targetPaths(document, request, member, which)
|
|
158
185
|
const claimed = locks.claimAll(paths.map(path => documentDirOf(config, path)!), 'revision:revert')
|
|
159
186
|
if ('holder' in claimed) throw lockedError(claimed.document, claimed.holder)
|
|
160
187
|
try {
|
|
@@ -4,14 +4,15 @@ import { lstat, open, stat } from 'node:fs/promises'
|
|
|
4
4
|
import { basename, extname, join, relative } from 'node:path'
|
|
5
5
|
import { imageSize } from 'image-size'
|
|
6
6
|
import { ASSET_TITLE_MAX_LENGTH, DOCUMENT_IMAGE_MAX_BYTES, fnv1a64, hasRole, isRecord, jsonResponse } from '@lincyaw/kernel'
|
|
7
|
-
import type { Asset, CanonicalSource, DocumentImageAuthoring, DocumentImageImport, DocumentImageImportAnswer, DocumentWorkspaceImageImport, Member, RequestContext, Route,
|
|
7
|
+
import type { Asset, CanonicalSource, DocumentImageAuthoring, DocumentImageImport, DocumentImageImportAnswer, DocumentWorkspaceImageImport, Member, RequestContext, Route, PresmiumDocument, VerifiedDocumentImageImport } from '@lincyaw/kernel'
|
|
8
8
|
import { productionAssetFile, validateDocumentWorkspaceImageImport, validateDocumentWorkspaceImageInspect } from '@lincyaw/kernel/node'
|
|
9
9
|
import { readAuthoringDocument } from './document-editor.ts'
|
|
10
10
|
import { catchRequestErrors, RequestError } from './errors.ts'
|
|
11
|
+
import type { MediaUploadsOwner } from './media-uploads.ts'
|
|
11
12
|
import type { Revisions } from './revisions.ts'
|
|
12
13
|
import type { SourceEditor, SourceTransactionHistory } from './source-editor.ts'
|
|
13
14
|
|
|
14
|
-
interface Options { root: string, editor: SourceEditor, revisions?: Revisions, reviewRequired?: boolean }
|
|
15
|
+
interface Options { root: string, editor: SourceEditor, revisions?: Revisions, reviewRequired?: boolean, uploads?: MediaUploadsOwner }
|
|
15
16
|
interface ImageFormat { extension: string, mediaType: string }
|
|
16
17
|
interface Receipt { signature: string, assetId: string, version: string, files?: DocumentImageImportAnswer['files'], commit?: DocumentImageImportAnswer['commit'] }
|
|
17
18
|
const FORMATS: Record<string, ImageFormat> = {
|
|
@@ -34,7 +35,7 @@ function inspect(bytes: Uint8Array) {
|
|
|
34
35
|
}
|
|
35
36
|
|
|
36
37
|
/** Original bytes and the canonical asset bank are committed or rolled back together. */
|
|
37
|
-
export function createDocumentImageAuthoring({ root, editor, revisions, reviewRequired = false }: Options): { service: DocumentImageAuthoring, routes: Record<string, Route
|
|
38
|
+
export function createDocumentImageAuthoring({ root, editor, revisions, reviewRequired = false, uploads }: Options): { service: DocumentImageAuthoring, routes: Record<string, Route>, busy(): boolean } {
|
|
38
39
|
const receipts = new Map<string, Receipt>(), pending = new Map<string, { signature: string, done: Promise<DocumentImageImportAnswer> }>()
|
|
39
40
|
const binding = (current: ReturnType<typeof readAuthoringDocument>): CanonicalSource => ({ documentId: current.content.id, version: current.source.version, fingerprint: fnv1a64(current.source.content) })
|
|
40
41
|
const opened = (ctx: RequestContext, version?: string, source?: CanonicalSource) => {
|
|
@@ -77,7 +78,7 @@ export function createDocumentImageAuthoring({ root, editor, revisions, reviewRe
|
|
|
77
78
|
receipts.set(key, receipt)
|
|
78
79
|
while (receipts.size > 64) receipts.delete(receipts.keys().next().value!)
|
|
79
80
|
}
|
|
80
|
-
const history = (ctx: RequestContext, document:
|
|
81
|
+
const history = (ctx: RequestContext, document: PresmiumDocument, signal: AbortSignal, origin: 'editor' | 'agent'): SourceTransactionHistory => ({
|
|
81
82
|
run: work => {
|
|
82
83
|
const guarded = () => { signal.throwIfAborted(); return work() }
|
|
83
84
|
return revisions ? revisions.transaction(guarded) : guarded()
|
|
@@ -86,12 +87,12 @@ export function createDocumentImageAuthoring({ root, editor, revisions, reviewRe
|
|
|
86
87
|
if (!revisions) return undefined
|
|
87
88
|
const ignored = (await Promise.all(paths.map(async path => await revisions.ignores(path) ? path : undefined))).filter((path): path is string => Boolean(path))
|
|
88
89
|
if (ignored.length) throw new RequestError(409, 'document-files-ignored', { ignored })
|
|
89
|
-
return revisions.commitWhileLocked({ paths, summary: document.metadata.lang.startsWith('en') ? 'Import image' : '导入图片', body: '', origin: { kind: origin, member: ctx.member } })
|
|
90
|
+
return revisions.commitWhileLocked({ paths, summary: editor.effective(ctx.document, document).metadata.lang.startsWith('en') ? 'Import image' : '导入图片', body: '', origin: { kind: origin, member: ctx.member } })
|
|
90
91
|
},
|
|
91
92
|
})
|
|
92
|
-
const signatureOf = (change: DocumentImageImport, title: string, hash: string, origin: 'editor' | 'agent', source?: CanonicalSource, inputPath?: string) => createHash('sha256').update(JSON.stringify([change.id, change.baseDocumentVersion, source?.documentId ?? null, source?.fingerprint ?? null, origin, inputPath ?? null, title, hash])).digest('hex')
|
|
93
|
+
const signatureOf = (change: DocumentImageImport, title: string, hash: string, origin: 'editor' | 'agent', source?: CanonicalSource, inputPath?: string | { upload: string }) => createHash('sha256').update(JSON.stringify([change.id, change.baseDocumentVersion, source?.documentId ?? null, source?.fingerprint ?? null, origin, inputPath ?? null, title, hash])).digest('hex')
|
|
93
94
|
const keyOf = (ctx: RequestContext, change: DocumentImageImport) => JSON.stringify([ctx.document, ctx.member.id, change.id])
|
|
94
|
-
const apply = async (ctx: RequestContext, change: DocumentImageImport, title: string, bytes: Uint8Array, image: ReturnType<typeof inspect>, hash: string, signal: AbortSignal, origin: 'editor' | 'agent', source?: CanonicalSource, inputPath?: string): Promise<DocumentImageImportAnswer> => {
|
|
95
|
+
const apply = async (ctx: RequestContext, change: DocumentImageImport, title: string, bytes: Uint8Array, image: ReturnType<typeof inspect>, hash: string, signal: AbortSignal, origin: 'editor' | 'agent', source?: CanonicalSource, inputPath?: string | { upload: string }): Promise<DocumentImageImportAnswer> => {
|
|
95
96
|
const signature = signatureOf(change, title, hash, origin, source, inputPath), key = keyOf(ctx, change)
|
|
96
97
|
const replay = async () => {
|
|
97
98
|
const previous = receipts.get(key)
|
|
@@ -160,10 +161,19 @@ export function createDocumentImageAuthoring({ root, editor, revisions, reviewRe
|
|
|
160
161
|
signal?.throwIfAborted(); return bytes.slice(0, length)
|
|
161
162
|
} finally { await handle.close() }
|
|
162
163
|
}
|
|
164
|
+
const input = async (ctx: RequestContext, source: CanonicalSource, location: { path?: string, upload?: string }, signal?: AbortSignal) => {
|
|
165
|
+
if (location.upload !== undefined) {
|
|
166
|
+
signal?.throwIfAborted()
|
|
167
|
+
if (!uploads) throw new RequestError(503, 'media-upload-unavailable')
|
|
168
|
+
return uploads.read(ctx.document, source.documentId, ctx.member, location.upload, 'image')
|
|
169
|
+
}
|
|
170
|
+
return { bytes: await reader(ctx, location.path!, signal), name: basename(location.path!) }
|
|
171
|
+
}
|
|
163
172
|
const workspaceImport = async (ctx: RequestContext, request: DocumentWorkspaceImageImport, signal?: AbortSignal) => {
|
|
164
|
-
const bytes = await
|
|
173
|
+
const { bytes, name } = await input(ctx, request.source, request.file, signal), sha256 = createHash('sha256').update(bytes).digest('hex')
|
|
165
174
|
if (bytes.length !== request.file.byteLength || sha256 !== request.file.sha256) throw new RequestError(409, 'image-file-changed')
|
|
166
|
-
|
|
175
|
+
if (request.file.upload && request.file.name !== name) throw new RequestError(409, 'image-file-changed')
|
|
176
|
+
const image = inspect(bytes), title = [...name.replace(/[\u0000-\u001f\u007f-\u009f]/g, '').trim()].slice(0, ASSET_TITLE_MAX_LENGTH).join('')
|
|
167
177
|
return { bytes, image, sha256, title }
|
|
168
178
|
}
|
|
169
179
|
let active = 0
|
|
@@ -183,9 +193,9 @@ export function createDocumentImageAuthoring({ root, editor, revisions, reviewRe
|
|
|
183
193
|
if (!validateDocumentWorkspaceImageInspect(request)) throw new RequestError(400, 'document-image-query-invalid')
|
|
184
194
|
return limited(async () => {
|
|
185
195
|
const ctx = ctxOf(document, member); opened(ctx, request.source.version, request.source)
|
|
186
|
-
const bytes = await
|
|
196
|
+
const { bytes, name } = await input(ctx, request.source, request, signal), image = inspect(bytes), sha256 = createHash('sha256').update(bytes).digest('hex')
|
|
187
197
|
signal?.throwIfAborted(); opened(ctx, request.source.version, request.source)
|
|
188
|
-
return { document, source: request.source, file: { path: request.path, sha256, byteLength: bytes.length }, image: { mediaType: image.mediaType, dimensions: image.dimensions } }
|
|
198
|
+
return { document, source: request.source, file: { ...request.upload ? { upload: request.upload, name } : { path: request.path! }, sha256, byteLength: bytes.length }, image: { mediaType: image.mediaType, dimensions: image.dimensions } }
|
|
189
199
|
})
|
|
190
200
|
},
|
|
191
201
|
async checkWorkspaceImport(document, request, member, signal) {
|
|
@@ -195,7 +205,7 @@ export function createDocumentImageAuthoring({ root, editor, revisions, reviewRe
|
|
|
195
205
|
return limited(async () => {
|
|
196
206
|
const ctx = ctxOf(document, member), change = { id: request.id, baseDocumentVersion: request.source.version }, key = keyOf(ctx, change)
|
|
197
207
|
if (!receipts.has(key) && !pending.has(key)) opened(ctx, request.source.version, request.source)
|
|
198
|
-
const { sha256, title } = await workspaceImport(ctx, request, signal), signature = signatureOf(change, title, sha256, 'agent', request.source, request.file.path)
|
|
208
|
+
const { sha256, title } = await workspaceImport(ctx, request, signal), signature = signatureOf(change, title, sha256, 'agent', request.source, request.file.path ?? { upload: request.file.upload! })
|
|
199
209
|
const receipt = receipts.get(key), known = receipt ?? pending.get(key)
|
|
200
210
|
if (known && known.signature !== signature) throw new RequestError(409, 'document-change-id-reused')
|
|
201
211
|
// A receipt of this exact import replays while the source is still the one it saved; an import in flight decides itself.
|
|
@@ -209,7 +219,7 @@ export function createDocumentImageAuthoring({ root, editor, revisions, reviewRe
|
|
|
209
219
|
if (!validateDocumentWorkspaceImageImport(request)) throw new RequestError(400, 'document-image-import-invalid')
|
|
210
220
|
return limited(async () => {
|
|
211
221
|
const ctx = ctxOf(document, member), { bytes, image, sha256, title } = await workspaceImport(ctx, request, signal)
|
|
212
|
-
const result = await apply(ctx, { id: request.id, baseDocumentVersion: request.source.version }, title, bytes, image, sha256, signal ?? new AbortController().signal, 'agent', request.source, request.file.path)
|
|
222
|
+
const result = await apply(ctx, { id: request.id, baseDocumentVersion: request.source.version }, title, bytes, image, sha256, signal ?? new AbortController().signal, 'agent', request.source, request.file.path ?? { upload: request.file.upload! })
|
|
213
223
|
try {
|
|
214
224
|
const current = opened(ctx, result.version), asset = current.content.assets[result.assetId], file = asset && productionAssetFile(join(root, document), asset.location)
|
|
215
225
|
if (!asset || !file || !await matches(ctx, asset, bytes, image, new AbortController().signal)) throw new Error('asset-changed')
|
|
@@ -237,5 +247,5 @@ export function createDocumentImageAuthoring({ root, editor, revisions, reviewRe
|
|
|
237
247
|
return jsonResponse(await apply(ctx, change, title, bytes, image, hash, request.signal, 'editor'))
|
|
238
248
|
}) },
|
|
239
249
|
}
|
|
240
|
-
return { service, routes }
|
|
250
|
+
return { service, routes, busy: () => active > 0 || pending.size > 0 }
|
|
241
251
|
}
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto'
|
|
2
|
+
import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
|
|
3
|
+
import { tmpdir } from 'node:os'
|
|
4
|
+
import { dirname, join } from 'node:path'
|
|
5
|
+
import { importDocuments } from '@lincyaw/compiler'
|
|
6
|
+
import { DOCUMENT_ENTRY, DOCUMENT_IMPORT_MAX_BYTES, DOCUMENT_IMPORT_MAX_FILES, hasRole, jsonResponse, validateDocument } from '@lincyaw/kernel'
|
|
7
|
+
import type { DocumentImportAnswer, Route } from '@lincyaw/kernel'
|
|
8
|
+
import { readWorkspaceConfig } from './config.ts'
|
|
9
|
+
import type { WorkspaceConfig } from './config.ts'
|
|
10
|
+
import { catchRequestErrors, RequestError } from './errors.ts'
|
|
11
|
+
import type { DocumentLocks } from './locks.ts'
|
|
12
|
+
import type { Revisions } from './revisions.ts'
|
|
13
|
+
import type { DocumentWriter } from './writer.ts'
|
|
14
|
+
import type { DocumentsChange } from './document-operations.ts'
|
|
15
|
+
|
|
16
|
+
const bad = (status: number, code: string): never => { throw new RequestError(status, `document-import-${code}`) }
|
|
17
|
+
/** Word and PowerPoint files from before 2007, which the converter cannot read. */
|
|
18
|
+
const LEGACY = /\.(?:doc|ppt|pps)$/i
|
|
19
|
+
const plainPath = (path: unknown): path is string => typeof path === 'string' && path.length > 0 && path.length <= 500
|
|
20
|
+
&& !path.startsWith('/') && !/[\\\0:]/.test(path) && !path.split('/').some(part => !part || part === '.' || part === '..' || ['.git', '.presmium', 'node_modules', 'dist'].includes(part))
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Where a batch goes in the workspace: its folders at the top level under their own names when none is taken (one
|
|
24
|
+
* file imports as `<name>/`); a single folder whose name is taken gets the first free `<name>-<n>`; several folders, any
|
|
25
|
+
* of them taken, go together into the first free `imported`, `imported-<n>` (links between them stay relative).
|
|
26
|
+
*/
|
|
27
|
+
function placement(root: string, tops: string[]): { directory: string, place(path: string): string } {
|
|
28
|
+
const free = (name: string) => { let candidate = name; for (let n = 2; existsSync(join(root, candidate)); n++) candidate = `${name}-${n}`; return candidate }
|
|
29
|
+
if (!tops.some(top => existsSync(join(root, top)))) return { directory: tops.length === 1 ? tops[0]! : '', place: path => path }
|
|
30
|
+
if (tops.length === 1) {
|
|
31
|
+
const directory = free(tops[0]!)
|
|
32
|
+
return { directory, place: path => `${directory}${path.slice(tops[0]!.length)}` }
|
|
33
|
+
}
|
|
34
|
+
const directory = free('imported')
|
|
35
|
+
return { directory, place: path => `${directory}/${path}` }
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Uploaded sources are converted before a single locked, rollback-capable workspace publication. */
|
|
39
|
+
export function documentImportRoute(options: { config: WorkspaceConfig, writer: DocumentWriter, locks: DocumentLocks, revisions?: Revisions, changed(change: DocumentsChange): Promise<void> }): Route {
|
|
40
|
+
const { config, writer, locks, revisions } = options
|
|
41
|
+
return {
|
|
42
|
+
role: 'owner', maxBody: DOCUMENT_IMPORT_MAX_BYTES + (1 << 20),
|
|
43
|
+
handle: (request, ctx) => catchRequestErrors(async () => {
|
|
44
|
+
if (request.method !== 'POST') return bad(405, 'method')
|
|
45
|
+
if (!hasRole(ctx.member, 'owner') || ctx.document !== '') return bad(403, 'forbidden')
|
|
46
|
+
if (config.singleDeck || !revisions) return bad(409, 'unavailable')
|
|
47
|
+
const form = await request.formData().catch(() => bad(400, 'invalid'))
|
|
48
|
+
const raw = form.get('paths')
|
|
49
|
+
if (typeof raw !== 'string' || raw.length > 512_000) return bad(400, 'invalid')
|
|
50
|
+
let paths: unknown
|
|
51
|
+
try { paths = JSON.parse(raw) } catch { return bad(400, 'invalid') }
|
|
52
|
+
const uploads = form.getAll('files')
|
|
53
|
+
if (!Array.isArray(paths) || paths.length === 0 || paths.length > DOCUMENT_IMPORT_MAX_FILES || paths.length !== uploads.length || !paths.every(plainPath)) return bad(400, 'invalid')
|
|
54
|
+
if (new Set(paths.map(path => path.toLowerCase())).size !== paths.length) return bad(400, 'invalid')
|
|
55
|
+
if (uploads.some(file => typeof file === 'string') || uploads.reduce((sum, file) => sum + (typeof file === 'string' ? 0 : file.size), 0) > DOCUMENT_IMPORT_MAX_BYTES) return bad(413, 'limit')
|
|
56
|
+
const temporary = mkdtempSync(join(tmpdir(), 'presmium-import-'))
|
|
57
|
+
try {
|
|
58
|
+
const source = join(temporary, 'source'), output = join(temporary, 'output')
|
|
59
|
+
mkdirSync(source)
|
|
60
|
+
for (const [index, path] of paths.entries()) {
|
|
61
|
+
const file = uploads[index] as File
|
|
62
|
+
request.signal.throwIfAborted()
|
|
63
|
+
mkdirSync(dirname(join(source, path)), { recursive: true })
|
|
64
|
+
writeFileSync(join(source, path), Buffer.from(await file.arrayBuffer()), { flag: 'wx' })
|
|
65
|
+
}
|
|
66
|
+
const report = await importDocuments(source, { out: output, preserveOriginal: true, workspaceRoot: config.root }).catch(() => bad(422, 'conversion'))
|
|
67
|
+
if (report.documents.length === 0) return bad(422, paths.some(path => LEGACY.test(path)) ? 'legacy' : 'empty')
|
|
68
|
+
const files: { path: string, content: Buffer }[] = []
|
|
69
|
+
let bytes = 0
|
|
70
|
+
const walk = (dir: string, path = '') => {
|
|
71
|
+
for (const entry of readdirSync(dir, { withFileTypes: true })) {
|
|
72
|
+
const rel = path ? `${path}/${entry.name}` : entry.name
|
|
73
|
+
if (entry.isDirectory()) walk(join(dir, entry.name), rel)
|
|
74
|
+
else {
|
|
75
|
+
const content = readFileSync(join(dir, entry.name))
|
|
76
|
+
if (files.length >= DOCUMENT_IMPORT_MAX_FILES || (bytes += content.byteLength) > DOCUMENT_IMPORT_MAX_BYTES) bad(413, 'limit')
|
|
77
|
+
files.push({ path: rel, content })
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
walk(output)
|
|
82
|
+
const documents = report.documents.map(dir => {
|
|
83
|
+
const checked = validateDocument(JSON.parse(readFileSync(join(output, dir, DOCUMENT_ENTRY), 'utf8')))
|
|
84
|
+
if (!checked.document || checked.issues.some(issue => issue.severity === 'error')) return bad(422, 'conversion')
|
|
85
|
+
checked.document.id = randomUUID()
|
|
86
|
+
files.find(file => file.path === `${dir}/${DOCUMENT_ENTRY}`)!.content = Buffer.from(`${JSON.stringify(checked.document, null, 2)}\n`)
|
|
87
|
+
return { dir, title: checked.document.metadata.title }
|
|
88
|
+
})
|
|
89
|
+
const release = await locks.acquire('', 'document:import')
|
|
90
|
+
try {
|
|
91
|
+
const answer = await revisions.transaction(async (): Promise<DocumentImportAnswer> => {
|
|
92
|
+
request.signal.throwIfAborted()
|
|
93
|
+
const { directory, place } = placement(config.root, [...new Set(files.map(item => item.path.split('/')[0]!))])
|
|
94
|
+
const placed = files.map(item => ({ ...item, path: place(item.path) }))
|
|
95
|
+
const tops = [...new Set(placed.map(item => item.path.split('/')[0]!))]
|
|
96
|
+
if (tops.some(top => existsSync(join(config.root, top)))) return bad(409, 'changed')
|
|
97
|
+
if (readWorkspaceConfig(config.root).singleDeck) return bad(409, 'unavailable')
|
|
98
|
+
if (await revisions.ignoresAny(placed.map(item => item.path))) return bad(403, 'forbidden')
|
|
99
|
+
await revisions.checkpoint(tops)
|
|
100
|
+
const checkpoint = await writer.checkpoint(tops)
|
|
101
|
+
const before = await revisions.head()
|
|
102
|
+
let committed = false
|
|
103
|
+
try {
|
|
104
|
+
for (const item of placed) { request.signal.throwIfAborted(); await writer.create(item.path, item.content, true) }
|
|
105
|
+
request.signal.throwIfAborted()
|
|
106
|
+
const revision = await revisions.commitWhileLocked({ paths: tops, summary: `Import ${documents.length} documents`, body: '', origin: { kind: 'document', member: ctx.member, operation: { op: 'create', dir: directory || tops[0]! } } })
|
|
107
|
+
if (!revision) return bad(409, 'changed')
|
|
108
|
+
committed = true
|
|
109
|
+
return { directory, documents: documents.map(doc => ({ ...doc, dir: place(doc.dir) })), files: files.length, unresolved: report.unresolved.length, warnings: report.warnings ?? 0, ...revision ? { revision } : {} }
|
|
110
|
+
} catch (error) {
|
|
111
|
+
if (await revisions.head() !== before) { committed = true; throw new RequestError(409, 'document-import-changed', { committed: true }) }
|
|
112
|
+
await checkpoint.restore()
|
|
113
|
+
throw error
|
|
114
|
+
} finally { if (committed || await revisions.head() === before) checkpoint.dispose() }
|
|
115
|
+
})
|
|
116
|
+
try { await options.changed({ removed: [], added: answer.documents.map(doc => doc.dir) }) }
|
|
117
|
+
catch { throw new RequestError(409, 'document-import-changed', { committed: true }) }
|
|
118
|
+
return jsonResponse(answer, 201)
|
|
119
|
+
} finally { release() }
|
|
120
|
+
} finally { rmSync(temporary, { recursive: true, force: true }) }
|
|
121
|
+
}),
|
|
122
|
+
}
|
|
123
|
+
}
|