@lincyaw/workspace 1.0.0-rc.124 → 1.0.0-rc.126

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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lincyaw/workspace",
3
- "version": "1.0.0-rc.124",
3
+ "version": "1.0.0-rc.126",
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/compiler": "1.0.0-rc.124",
38
- "@lincyaw/kernel": "1.0.0-rc.124",
39
- "@lincyaw/server": "1.0.0-rc.124",
40
- "@lincyaw/design": "1.0.0-rc.124"
38
+ "@lincyaw/kernel": "1.0.0-rc.126",
39
+ "@lincyaw/server": "1.0.0-rc.126",
40
+ "@lincyaw/design": "1.0.0-rc.126",
41
+ "@lincyaw/compiler": "1.0.0-rc.126"
41
42
  },
42
43
  "devDependencies": {
43
44
  "@types/mime-types": "^3.0.1",
44
- "@lincyaw/mcp": "1.0.0-rc.124"
45
+ "@lincyaw/mcp": "1.0.0-rc.126"
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 = `imported-${randomUUID().slice(0, 8)}`
76
- if (existsSync(join(config.root, directory))) return bad(409, 'changed')
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(files.map(item => `${directory}/${item.path}`))) return bad(403, 'forbidden')
79
- await revisions.checkpoint([directory])
80
- const checkpoint = await writer.checkpoint([directory])
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 files) { request.signal.throwIfAborted(); await writer.create(`${directory}/${item.path}`, item.content, true) }
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: [directory], summary: `Import ${documents.length} documents`, body: '', origin: { kind: 'document', member: ctx.member, operation: { op: 'create', dir: directory } } })
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: `${directory}/${doc.dir}` })), files: files.length, unresolved: report.unresolved.length, warnings: report.warnings ?? 0, ...revision ? { revision } : {} }
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
@@ -1,11 +1,12 @@
1
1
  import { createHash, randomBytes } from 'node:crypto'
2
2
  import { createReadStream, existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'
3
3
  import { join, relative, sep } from 'node:path'
4
- import { availableRenderers, build, compileTranslations, documentExporters, exportDocument, serveDirectory } from '@lincyaw/compiler'
4
+ import { availableRenderers, build, compileTranslations, documentExporters, exportDocument, missingOutput, serveDirectory } from '@lincyaw/compiler'
5
5
  import type { Compilation } from '@lincyaw/compiler'
6
- import { errorMessage, fnv1a64 } from '@lincyaw/kernel'
6
+ import { errorMessage, fnv1a64, jobFailureCode } 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.
@@ -200,11 +205,10 @@ export function createJobs(options: JobsOptions): Jobs {
200
205
  const report = await build(compilation, { outDir: dir, to: [job.target], base: `${outputs}${job.id}/${job.target}/`, log })
201
206
  if (controller.signal.aborted) throw new Cancelled()
202
207
  job.warnings = report.findings.filter(finding => finding.severity === 'warning').map(finding => finding.message)
203
- if (!report.outputs.some(output => output.renderer === job.target)) {
204
- throw new Error(report.findings.filter(finding => finding.severity === 'error').map(finding => finding.message).join('\n') || `the ${job.target} renderer made nothing`)
205
- }
208
+ if (!report.outputs.some(output => output.renderer === job.target)) throw await missingOutput(compilation, job.target, report.findings)
206
209
  job.files = listFiles(dir, join(dir, job.target))
207
210
  job.main = mainFile(job.target, job.files)
211
+ if (job.main?.endsWith('/index.html')) await archiveSite(entry, compilation, log, progress)
208
212
  return
209
213
  }
210
214
  const output = await exportDocument(compilation, job.target, { outDir: dir, signal: controller.signal, progress, log })
@@ -217,6 +221,27 @@ export function createJobs(options: JobsOptions): Jobs {
217
221
  if (output.captions) job.captions = Object.fromEntries(Object.entries(output.captions).map(([lang, file]) => [lang, file.split(sep).join('/')]))
218
222
  }
219
223
 
224
+ /**
225
+ * The site of a render job as a ZIP archive beside it, to take elsewhere: built again at the site's own base (the
226
+ * document's, else the root), since the copy the job serves is built for its address below `/__outputs/`.
227
+ */
228
+ const archiveSite = async (entry: Running, compilation: Compilation, log: (line: string) => void, progress: (phase: string) => void) => {
229
+ const { job, dir, controller } = entry
230
+ progress('archive')
231
+ const work = join(dir, ARCHIVE_BUILD)
232
+ try {
233
+ const report = await build(compilation, { outDir: work, to: [job.target], log })
234
+ if (controller.signal.aborted) throw new Cancelled()
235
+ const site = report.outputs.find(output => output.renderer === job.target)
236
+ if (!site) throw await missingOutput(compilation, job.target, report.findings)
237
+ const file = `${job.target}.zip`
238
+ await writeArchive(site.outDir, join(dir, file), controller.signal)
239
+ job.archive = file
240
+ } finally {
241
+ rmSync(work, { recursive: true, force: true })
242
+ }
243
+ }
244
+
220
245
  /** Runs the job once the ones before it have ended. */
221
246
  const schedule = (entry: Running, compilation: Compilation, inputs: Map<string, string | undefined>) => {
222
247
  queue = queue.then(async () => {
@@ -237,7 +262,13 @@ export function createJobs(options: JobsOptions): Jobs {
237
262
  job.state = 'done'
238
263
  } catch (error) {
239
264
  job.state = controller.signal.aborted ? 'cancelled' : 'failed'
240
- if (job.state === 'failed') job.error = errorMessage(error)
265
+ if (job.state === 'failed') {
266
+ job.error = errorMessage(error)
267
+ const code = jobFailureCode(error)
268
+ if (code) job.code = code
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
- const inputFingerprint = fnv1a64(JSON.stringify([outputs, ...[...inputs].sort(([a], [b]) => a.localeCompare(b))]))
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 }
@@ -25,6 +25,13 @@ function stamp(file: string): FileStamp | undefined {
25
25
  if (!stat.isFile()) throw new RequestError(409, 'agent-source-type-changed')
26
26
  return { version: versionOf(readFileSync(file)), ...stat.mode & 0o111 ? { executable: true } : {} }
27
27
  }
28
+ const SANDBOX_STATE = new Set(['.deltabox', '.deltabox-lite-state'])
29
+ /**
30
+ * What a candidate copies of the author's listing: not the candidates themselves, not a sandbox's state (its live
31
+ * tree is a repository of its own), and not another repository inside the workspace, which git lists as `dir/`.
32
+ */
33
+ const isAuthorFile = (path: string) => !!path && !path.endsWith('/') && !path.startsWith('.presmium/agent-workspaces/')
34
+ && !path.split('/').some(part => SANDBOX_STATE.has(part))
28
35
  const same = (a: FileStamp | undefined, b: FileStamp | undefined) => JSON.stringify(a) === JSON.stringify(b)
29
36
  async function sourceStamp(file: string): Promise<FileStamp | undefined> {
30
37
  let stat
@@ -63,7 +70,7 @@ export class AgentWorkspace {
63
70
  async refresh(): Promise<boolean> {
64
71
  const listing = ['ls-files', '--cached', '--others', '--exclude-standard', '-z', '--', '.']
65
72
  const listed = Git.isRepository(this.#config.root) ? await git(this.#config.root, listing) : await (await openLocalHistory(this.#config.root)).output(listing)
66
- const paths = listed.split('\0').filter(path => path && !path.startsWith('.presmium/agent-workspaces/'))
73
+ const paths = listed.split('\0').filter(isAuthorFile)
67
74
  const next: Record<string, FileStamp> = {}
68
75
  for (const path of new Set(paths)) {
69
76
  const current = await sourceStamp(join(this.#config.root, path))
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()