@lincyaw/workspace 1.0.0-rc.124 → 1.0.0-rc.125
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/package.json +7 -6
- package/src/node/archive.ts +33 -0
- package/src/node/document-import.ts +29 -9
- package/src/node/jobs.ts +35 -3
- package/src/node/serve.ts +3 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lincyaw/workspace",
|
|
3
|
-
"version": "1.0.0-rc.
|
|
3
|
+
"version": "1.0.0-rc.125",
|
|
4
4
|
"description": "Presmium's workspace service (presmium serve): documents, their history, reviews and the workspace site",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"repository": {
|
|
@@ -30,17 +30,18 @@
|
|
|
30
30
|
"templates"
|
|
31
31
|
],
|
|
32
32
|
"dependencies": {
|
|
33
|
+
"jszip": "^3.10.2",
|
|
33
34
|
"image-size": "2.0.4",
|
|
34
35
|
"mime-types": "3.0.2",
|
|
35
36
|
"playwright-chromium": "1.64.1",
|
|
36
37
|
"yaml": "^2.9.1",
|
|
37
|
-
"@lincyaw/
|
|
38
|
-
"@lincyaw/
|
|
39
|
-
"@lincyaw/server": "1.0.0-rc.
|
|
40
|
-
"@lincyaw/design": "1.0.0-rc.
|
|
38
|
+
"@lincyaw/kernel": "1.0.0-rc.125",
|
|
39
|
+
"@lincyaw/compiler": "1.0.0-rc.125",
|
|
40
|
+
"@lincyaw/server": "1.0.0-rc.125",
|
|
41
|
+
"@lincyaw/design": "1.0.0-rc.125"
|
|
41
42
|
},
|
|
42
43
|
"devDependencies": {
|
|
43
44
|
"@types/mime-types": "^3.0.1",
|
|
44
|
-
"@lincyaw/mcp": "1.0.0-rc.
|
|
45
|
+
"@lincyaw/mcp": "1.0.0-rc.125"
|
|
45
46
|
}
|
|
46
47
|
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { createReadStream, createWriteStream } from 'node:fs'
|
|
2
|
+
import { readdir } from 'node:fs/promises'
|
|
3
|
+
import { join, relative, sep } from 'node:path'
|
|
4
|
+
import { pipeline } from 'node:stream/promises'
|
|
5
|
+
import JSZip from 'jszip'
|
|
6
|
+
|
|
7
|
+
// Files already compressed are stored as they are: deflating them again costs time and saves nothing.
|
|
8
|
+
const STORED = /\.(?:png|jpe?g|gif|webp|avif|ico|mp4|webm|mov|mp3|m4a|aac|ogg|opus|flac|woff2?|zip|gz|br|pdf|pptx)$/i
|
|
9
|
+
|
|
10
|
+
async function filesBelow(dir: string): Promise<string[]> {
|
|
11
|
+
const found: string[] = []
|
|
12
|
+
for (const entry of (await readdir(dir, { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name))) {
|
|
13
|
+
const path = join(dir, entry.name)
|
|
14
|
+
if (entry.isDirectory()) found.push(...await filesBelow(path))
|
|
15
|
+
else if (entry.isFile()) found.push(path)
|
|
16
|
+
}
|
|
17
|
+
return found
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Writes the files below `dir` into the ZIP archive `file`, their paths relative to `dir`. Each file is read as a
|
|
22
|
+
* stream and written as it is compressed (JSZip's `streamFiles`), in small steps, so a large site neither fills the
|
|
23
|
+
* memory nor holds up the service's other requests.
|
|
24
|
+
*/
|
|
25
|
+
export async function writeArchive(dir: string, file: string, signal?: AbortSignal): Promise<void> {
|
|
26
|
+
const zip = new JSZip()
|
|
27
|
+
for (const path of await filesBelow(dir)) {
|
|
28
|
+
const name = relative(dir, path).split(sep).join('/')
|
|
29
|
+
zip.file(name, createReadStream(path), { binary: true, compression: STORED.test(name) ? 'STORE' : 'DEFLATE', compressionOptions: { level: 6 } })
|
|
30
|
+
}
|
|
31
|
+
signal?.throwIfAborted()
|
|
32
|
+
await pipeline(zip.generateNodeStream({ type: 'nodebuffer', streamFiles: true }), createWriteStream(file), signal ? { signal } : {})
|
|
33
|
+
}
|
|
@@ -14,9 +14,27 @@ import type { DocumentWriter } from './writer.ts'
|
|
|
14
14
|
import type { DocumentsChange } from './document-operations.ts'
|
|
15
15
|
|
|
16
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
|
|
17
19
|
const plainPath = (path: unknown): path is string => typeof path === 'string' && path.length > 0 && path.length <= 500
|
|
18
20
|
&& !path.startsWith('/') && !/[\\\0:]/.test(path) && !path.split('/').some(part => !part || part === '.' || part === '..' || ['.git', '.presmium', 'node_modules', 'dist'].includes(part))
|
|
19
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
|
+
|
|
20
38
|
/** Uploaded sources are converted before a single locked, rollback-capable workspace publication. */
|
|
21
39
|
export function documentImportRoute(options: { config: WorkspaceConfig, writer: DocumentWriter, locks: DocumentLocks, revisions?: Revisions, changed(change: DocumentsChange): Promise<void> }): Route {
|
|
22
40
|
const { config, writer, locks, revisions } = options
|
|
@@ -46,7 +64,7 @@ export function documentImportRoute(options: { config: WorkspaceConfig, writer:
|
|
|
46
64
|
writeFileSync(join(source, path), Buffer.from(await file.arrayBuffer()), { flag: 'wx' })
|
|
47
65
|
}
|
|
48
66
|
const report = await importDocuments(source, { out: output, preserveOriginal: true, workspaceRoot: config.root }).catch(() => bad(422, 'conversion'))
|
|
49
|
-
if (report.documents.length === 0) return bad(422, 'empty')
|
|
67
|
+
if (report.documents.length === 0) return bad(422, paths.some(path => LEGACY.test(path)) ? 'legacy' : 'empty')
|
|
50
68
|
const files: { path: string, content: Buffer }[] = []
|
|
51
69
|
let bytes = 0
|
|
52
70
|
const walk = (dir: string, path = '') => {
|
|
@@ -72,21 +90,23 @@ export function documentImportRoute(options: { config: WorkspaceConfig, writer:
|
|
|
72
90
|
try {
|
|
73
91
|
const answer = await revisions.transaction(async (): Promise<DocumentImportAnswer> => {
|
|
74
92
|
request.signal.throwIfAborted()
|
|
75
|
-
const directory =
|
|
76
|
-
|
|
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')
|
|
77
97
|
if (readWorkspaceConfig(config.root).singleDeck) return bad(409, 'unavailable')
|
|
78
|
-
if (await revisions.ignoresAny(
|
|
79
|
-
await revisions.checkpoint(
|
|
80
|
-
const checkpoint = await writer.checkpoint(
|
|
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)
|
|
81
101
|
const before = await revisions.head()
|
|
82
102
|
let committed = false
|
|
83
103
|
try {
|
|
84
|
-
for (const item of
|
|
104
|
+
for (const item of placed) { request.signal.throwIfAborted(); await writer.create(item.path, item.content, true) }
|
|
85
105
|
request.signal.throwIfAborted()
|
|
86
|
-
const revision = await revisions.commitWhileLocked({ paths:
|
|
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]! } } })
|
|
87
107
|
if (!revision) return bad(409, 'changed')
|
|
88
108
|
committed = true
|
|
89
|
-
return { directory, documents: documents.map(doc => ({ ...doc, dir:
|
|
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 } : {} }
|
|
90
110
|
} catch (error) {
|
|
91
111
|
if (await revisions.head() !== before) { committed = true; throw new RequestError(409, 'document-import-changed', { committed: true }) }
|
|
92
112
|
await checkpoint.restore()
|
package/src/node/jobs.ts
CHANGED
|
@@ -6,6 +6,7 @@ import type { Compilation } from '@lincyaw/compiler'
|
|
|
6
6
|
import { errorMessage, fnv1a64 } from '@lincyaw/kernel'
|
|
7
7
|
import { lookup } from 'mime-types'
|
|
8
8
|
import type { CompileJob, JobFile, JobSource, Logger, OutputJobs, OutputTarget } from '@lincyaw/kernel'
|
|
9
|
+
import { writeArchive } from './archive.ts'
|
|
9
10
|
import { RequestError } from './errors.ts'
|
|
10
11
|
import { versionOf } from './source-editor.ts'
|
|
11
12
|
|
|
@@ -18,6 +19,10 @@ import { versionOf } from './source-editor.ts'
|
|
|
18
19
|
|
|
19
20
|
export const OUTPUTS_PATH = '/__outputs/'
|
|
20
21
|
const JOB_FILE = 'job.json'
|
|
22
|
+
// Where a site job builds the copy it archives, inside the job's directory, removed when the archive is written.
|
|
23
|
+
const ARCHIVE_BUILD = '.archive'
|
|
24
|
+
// Grows when what a job leaves changes, so that an older job of the same source is made again rather than reused.
|
|
25
|
+
const OUTPUT_FORMAT = 2
|
|
21
26
|
// The last lines of a job's log the job keeps.
|
|
22
27
|
const LOG_LINES = 400
|
|
23
28
|
// The jobs a document keeps of each target, with their files.
|
|
@@ -205,6 +210,7 @@ export function createJobs(options: JobsOptions): Jobs {
|
|
|
205
210
|
}
|
|
206
211
|
job.files = listFiles(dir, join(dir, job.target))
|
|
207
212
|
job.main = mainFile(job.target, job.files)
|
|
213
|
+
if (job.main?.endsWith('/index.html')) await archiveSite(entry, compilation, log, progress)
|
|
208
214
|
return
|
|
209
215
|
}
|
|
210
216
|
const output = await exportDocument(compilation, job.target, { outDir: dir, signal: controller.signal, progress, log })
|
|
@@ -217,6 +223,27 @@ export function createJobs(options: JobsOptions): Jobs {
|
|
|
217
223
|
if (output.captions) job.captions = Object.fromEntries(Object.entries(output.captions).map(([lang, file]) => [lang, file.split(sep).join('/')]))
|
|
218
224
|
}
|
|
219
225
|
|
|
226
|
+
/**
|
|
227
|
+
* The site of a render job as a ZIP archive beside it, to take elsewhere: built again at the site's own base (the
|
|
228
|
+
* document's, else the root), since the copy the job serves is built for its address below `/__outputs/`.
|
|
229
|
+
*/
|
|
230
|
+
const archiveSite = async (entry: Running, compilation: Compilation, log: (line: string) => void, progress: (phase: string) => void) => {
|
|
231
|
+
const { job, dir, controller } = entry
|
|
232
|
+
progress('archive')
|
|
233
|
+
const work = join(dir, ARCHIVE_BUILD)
|
|
234
|
+
try {
|
|
235
|
+
const report = await build(compilation, { outDir: work, to: [job.target], log })
|
|
236
|
+
if (controller.signal.aborted) throw new Cancelled()
|
|
237
|
+
const site = report.outputs.find(output => output.renderer === job.target)
|
|
238
|
+
if (!site) throw new Error(report.findings.filter(finding => finding.severity === 'error').map(finding => finding.message).join('\n') || `the ${job.target} renderer made nothing`)
|
|
239
|
+
const file = `${job.target}.zip`
|
|
240
|
+
await writeArchive(site.outDir, join(dir, file), controller.signal)
|
|
241
|
+
job.archive = file
|
|
242
|
+
} finally {
|
|
243
|
+
rmSync(work, { recursive: true, force: true })
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
|
|
220
247
|
/** Runs the job once the ones before it have ended. */
|
|
221
248
|
const schedule = (entry: Running, compilation: Compilation, inputs: Map<string, string | undefined>) => {
|
|
222
249
|
queue = queue.then(async () => {
|
|
@@ -237,7 +264,11 @@ export function createJobs(options: JobsOptions): Jobs {
|
|
|
237
264
|
job.state = 'done'
|
|
238
265
|
} catch (error) {
|
|
239
266
|
job.state = controller.signal.aborted ? 'cancelled' : 'failed'
|
|
240
|
-
if (job.state === 'failed')
|
|
267
|
+
if (job.state === 'failed') {
|
|
268
|
+
job.error = errorMessage(error)
|
|
269
|
+
// The author's Details show why, under the reason the workbench gives in plain words.
|
|
270
|
+
job.log.push(job.error)
|
|
271
|
+
}
|
|
241
272
|
options.log.warn(`the ${job.target} of ${job.document || '.'} ${job.state === 'cancelled' ? 'was cancelled' : `failed: ${job.error}`}`)
|
|
242
273
|
}
|
|
243
274
|
job.finishedAt = now()
|
|
@@ -271,8 +302,9 @@ export function createJobs(options: JobsOptions): Jobs {
|
|
|
271
302
|
confirmed()
|
|
272
303
|
const inputs = await inputVersions([...compilation.inputs.files, ...translations.translations.flatMap(translation => translation.files)].filter(file => !compilation.sourceFiles.includes(file)))
|
|
273
304
|
confirmed()
|
|
274
|
-
// A site is built for the path its files are served at: one made below another base is not reused
|
|
275
|
-
|
|
305
|
+
// A site is built for the path its files are served at: one made below another base is not reused; nor one made
|
|
306
|
+
// before a site job also kept its ZIP archive (OUTPUT_FORMAT).
|
|
307
|
+
const inputFingerprint = fnv1a64(JSON.stringify([outputs, OUTPUT_FORMAT, ...[...inputs].sort(([a], [b]) => a.localeCompare(b))]))
|
|
276
308
|
// The same target of the same revision, made or being made: not again.
|
|
277
309
|
const same = [...jobs.values()].reverse().find(job => job.document === document && job.target === target && job.revision === revision && sameSource(job.source, source) && job.inputFingerprint === inputFingerprint && ['queued', 'running', 'done'].includes(job.state))
|
|
278
310
|
return { compilation, source, revision, known, inputs, inputFingerprint, same }
|
package/src/node/serve.ts
CHANGED
|
@@ -317,6 +317,9 @@ async function startWorkspace(options: ServeOptions): Promise<WorkspaceServer> {
|
|
|
317
317
|
}
|
|
318
318
|
|
|
319
319
|
const documentsChanged = async (change: DocumentsChange): Promise<void> => {
|
|
320
|
+
// Folder events reach the index only for folders it watches; a document written into a new nested folder (an
|
|
321
|
+
// import) would wait for the occasional walk, and the list and the tree would miss it until then.
|
|
322
|
+
await documentIndex.changed([...change.added, ...change.removed])
|
|
320
323
|
for (const dir of change.removed) {
|
|
321
324
|
server?.diagnostics.forget(dir)
|
|
322
325
|
compileSessions.get(dir)?.close()
|