@lincyaw/workspace 1.0.0-rc.15 → 1.0.0-rc.151

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 (60) hide show
  1. package/README.md +6 -4
  2. package/package.json +12 -6
  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 +16 -6
  9. package/src/node/capture.ts +383 -0
  10. package/src/node/config.ts +135 -50
  11. package/src/node/document-assets.ts +2 -2
  12. package/src/node/document-audio.ts +66 -47
  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 +654 -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 +85 -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 +211 -68
  39. package/src/node/review/agent-workspace.ts +151 -0
  40. package/src/node/review/git-review.ts +72 -29
  41. package/src/node/review/record.ts +41 -9
  42. package/src/node/review/routes.ts +9 -1
  43. package/src/node/review/windows-dependencies.ts +163 -0
  44. package/src/node/review/workspace-review.ts +87 -0
  45. package/src/node/revision-files.ts +54 -0
  46. package/src/node/revisions.ts +318 -80
  47. package/src/node/routes.ts +52 -59
  48. package/src/node/serve.ts +267 -52
  49. package/src/node/site.ts +5 -5
  50. package/src/node/source-editor.ts +66 -26
  51. package/src/node/speech-settings.ts +6 -8
  52. package/src/node/templates.ts +2 -2
  53. package/src/node/tree-operations.ts +425 -0
  54. package/src/node/tree-routes.ts +107 -0
  55. package/src/node/workbench-api.ts +14 -3
  56. package/src/node/workspace-changes.ts +130 -0
  57. package/src/node/workspace-migrate.ts +54 -0
  58. package/src/node/workspace-source.ts +133 -0
  59. package/src/node/writer.ts +21 -8
  60. package/templates/document/default/{lecture.json → index.pmd} +5 -1
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 }
@@ -0,0 +1,85 @@
1
+ import { execFile } from 'node:child_process'
2
+ import { createHash } from 'node:crypto'
3
+ import { existsSync, lstatSync, rmSync } from 'node:fs'
4
+ import { mkdir, mkdtemp, readFile, rename, rm, writeFile } from 'node:fs/promises'
5
+ import { homedir } from 'node:os'
6
+ import { isAbsolute, join, relative, resolve, sep } from 'node:path'
7
+ import { promisify } from 'node:util'
8
+ import { gitConfigArgs, gitEnvironment } from '@lincyaw/kernel'
9
+ import { Git } from './git.ts'
10
+ import { leavesRoot } from '../domain/paths.ts'
11
+
12
+ /** Editing history owns its index and refs; project commits remain an explicit author action. */
13
+ const historyDirectory = (root: string, env: NodeJS.ProcessEnv) => join(env.XDG_STATE_HOME || join(homedir(), '.local', 'state'), 'presmium', 'history', createHash('sha256').update(root).digest('hex'))
14
+
15
+ /**
16
+ * Removes the index lock a git command of an earlier service left in the workspace's local history when that service
17
+ * was ended in the middle of it; every later command would fail on it. Only the workspace's host (which holds the
18
+ * workspace's lease, so no other service uses this history) may call this. Answers whether there was one.
19
+ */
20
+ export function clearStaleHistoryLock(root: string, env: NodeJS.ProcessEnv = process.env): boolean {
21
+ const lock = join(historyDirectory(root, env), 'index.lock')
22
+ if (!existsSync(lock)) return false
23
+ rmSync(lock, { force: true })
24
+ return true
25
+ }
26
+
27
+ export async function openLocalHistory(root: string, env: NodeJS.ProcessEnv = process.env): Promise<Git> {
28
+ const base = join(env.XDG_STATE_HOME || join(homedir(), '.local', 'state'), 'presmium', 'history')
29
+ const directory = historyDirectory(root, env)
30
+ if (existsSync(join(directory, 'HEAD'))) {
31
+ const top = (await readFile(join(directory, 'presmium-worktree'), 'utf8')).trim()
32
+ return new Git(root, { directory, top })
33
+ }
34
+ await mkdir(base, { recursive: true })
35
+ const temporary = await mkdtemp(join(base, '.prepare-'))
36
+ try {
37
+ const project = Git.isRepository(root) ? new Git(root) : undefined
38
+ const top = project?.top ?? root
39
+ await promisify(execFile)('git', [...gitConfigArgs(), 'init', '--bare', '--quiet', '--initial-branch=main', temporary], { env: gitEnvironment(env) })
40
+ const git = new Git(root, { directory: temporary, top })
41
+ await git.output(['config', 'core.bare', 'false'])
42
+ await git.output(['config', 'core.worktree', top])
43
+ await writeFile(join(temporary, 'presmium-worktree'), `${top}\n`)
44
+ let excluded = ''
45
+ if (project) {
46
+ const head = await project.run(['rev-parse', '--verify', '--quiet', 'HEAD'])
47
+ if (head.code === 0) {
48
+ const source = (await project.output(['rev-parse', '--absolute-git-dir'])).trim()
49
+ await git.output(['fetch', '--quiet', '--no-tags', source, 'HEAD'])
50
+ await git.output(['update-ref', 'refs/heads/main', (await git.output(['rev-parse', 'FETCH_HEAD'])).trim()])
51
+ await git.output(['read-tree', 'HEAD'])
52
+ }
53
+ for (const key of ['user.name', 'user.email', 'core.autocrlf', 'core.eol', 'core.safecrlf', 'core.filemode', 'core.symlinks', 'core.excludesfile']) {
54
+ const value = await project.tryOutput(['config', '--get', key])
55
+ if (value.ok) await git.output(['config', key, value.output.trimEnd()])
56
+ }
57
+ const exclude = (await project.output(['rev-parse', '--git-path', 'info/exclude'])).trim()
58
+ excluded = await readFile(resolve(root, exclude), 'utf8').catch(error => { if (error.code === 'ENOENT') return ''; throw error })
59
+ }
60
+ await writeFile(join(temporary, 'info', 'exclude'), `${excluded}\n.presmium/\nnode_modules/\ndist/\n.deltabox/\n.deltabox-lite-state/\n`)
61
+ // Capture existing files, including unsaved project changes, as a real baseline before the first edit.
62
+ await captureLocalBaseline(git, ['.'], true)
63
+ await rename(temporary, directory)
64
+ return new Git(root, { directory, top })
65
+ } finally { await rm(temporary, { recursive: true, force: true }) }
66
+ }
67
+
68
+ /** Caller owns the history queue. External edits become an explicit undo boundary before a new save. */
69
+ export async function captureLocalBaseline(git: Git, paths: string[], initial = false): Promise<void> {
70
+ if (paths.some(path => isAbsolute(path) || leavesRoot(relative(git.root, resolve(git.root, path)).split(sep).join('/')) || path.split(/[\\/]/).includes('.git'))) throw new Error('history-path-outside-workspace')
71
+ const literal = { GIT_LITERAL_PATHSPECS: '1' }
72
+ if (!initial && !(await git.output(['status', '--porcelain=v1', '-z', '--no-renames', '--untracked-files=all', '--', ...paths], { ...literal, GIT_OPTIONAL_LOCKS: '0' }))) return
73
+ const tracked = new Set((await git.output(['ls-files', '-z', '--', ...paths], literal)).split('\0').filter(Boolean))
74
+ const excluded = await git.run(['check-ignore', '-z', '--stdin'], {}, Buffer.from(paths.map(path => `${path}\0`).join('')))
75
+ if (excluded.code !== 0 && excluded.code !== 1) throw new Error(excluded.stderr)
76
+ const ignored = new Set(excluded.stdout.toString('utf8').split('\0'))
77
+ const selected = paths.filter(path => !ignored.has(path) && (tracked.has(path) || lstatSync(join(git.root, path), { throwIfNoEntry: false })))
78
+ if (selected.length) await git.addAll(selected)
79
+ const tree = (await git.output(['write-tree'])).trim()
80
+ const parent = await git.tryOutput(['rev-parse', '--verify', '--quiet', 'HEAD'])
81
+ if (!initial && parent.ok && tree === (await git.output(['rev-parse', 'HEAD^{tree}'])).trim()) return
82
+ const message = 'Synchronize local editing baseline\n\nPresmium-Baseline: true\n'
83
+ const commit = (await git.output(['-c', 'user.name=Presmium', '-c', 'user.email=history@presmium.invalid', 'commit-tree', tree, ...parent.ok ? ['-p', parent.output.trim()] : [], '-m', message])).trim()
84
+ await git.output(['update-ref', 'refs/heads/main', commit, parent.ok ? parent.output.trim() : '0'.repeat(commit.length)])
85
+ }
package/src/node/locks.ts CHANGED
@@ -4,6 +4,15 @@ import { RequestError } from './errors.ts'
4
4
 
5
5
  export class DocumentLocks implements DocumentLockService {
6
6
  readonly #held = new Map<string, string>()
7
+ readonly #waiters = new Set<() => void>()
8
+
9
+ async acquire(document: string, holder: string): Promise<() => void> {
10
+ for (;;) {
11
+ const release = this.claim(document, holder)
12
+ if (release) return release
13
+ await new Promise<void>(done => this.#waiters.add(done))
14
+ }
15
+ }
7
16
 
8
17
  claim(document: string, holder: string): (() => void) | undefined {
9
18
  if (this.holder(document) !== undefined) return undefined
@@ -13,6 +22,9 @@ export class DocumentLocks implements DocumentLockService {
13
22
  if (released) return
14
23
  released = true
15
24
  this.#held.delete(document)
25
+ const waiting = [...this.#waiters]
26
+ this.#waiters.clear()
27
+ for (const ready of waiting) ready()
16
28
  }
17
29
  }
18
30
 
@@ -0,0 +1,68 @@
1
+ import { createHash } from 'node:crypto'
2
+ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
3
+ import { basename, dirname, isAbsolute, join } from 'node:path'
4
+ import { isRecord, jsonResponse, problemResponse } from '@lincyaw/kernel'
5
+ import type { McpConnectionSettings, McpConnectionChange, Route } from '@lincyaw/kernel'
6
+ import type { PresmiumServer } from '@lincyaw/server'
7
+
8
+ /** A separate MCP listener never changes the editor's address or takes over the stdio host. */
9
+ export async function createMcpSettings(options: { root: string, stateFile: string, server: PresmiumServer, command?: string }) {
10
+ const file = join(options.root, '.presmium', 'mcp-settings.json')
11
+ let preference: { transport: 'stdio' | 'http', port: number } = { transport: 'stdio', port: 0 }
12
+ try {
13
+ const saved: unknown = JSON.parse(readFileSync(file, 'utf8'))
14
+ if (validPreference(saved)) preference = { transport: saved.transport, port: saved.port }
15
+ } catch { /* A missing or invalid preference leaves the default stdio connection usable. */ }
16
+ let listener: Awaited<ReturnType<PresmiumServer['listenMcp']>> | undefined
17
+ let issue: 'mcp-port-unavailable' | undefined
18
+ if (preference.transport === 'http') {
19
+ try { listener = await options.server.listenMcp(preference.port) } catch { issue = 'mcp-port-unavailable' }
20
+ }
21
+ const command = options.command ?? process.argv[1]
22
+ const stdio = command && isAbsolute(command) && basename(command) === 'presmium.mjs' && existsSync(command)
23
+ ? { command: process.execPath, args: [command, 'mcp', options.root] } : undefined
24
+ const revision = () => createHash('sha256').update(JSON.stringify(preference)).digest('hex')
25
+ const read = (): McpConnectionSettings => ({ ...preference, revision: revision(), root: options.root,
26
+ ...(stdio ? { stdio } : {}), ...(listener ? { url: listener.url } : {}), ...(issue ? { issue } : {}), stateFile: options.stateFile })
27
+ let queue = Promise.resolve()
28
+ const change = (body: McpConnectionChange) => {
29
+ const result = queue.then(async () => {
30
+ if (body.revision !== revision()) throw new Error('mcp-settings-conflict')
31
+ const next = body.transport === 'http' && (body.port !== preference.port || !listener) ? await options.server.listenMcp(body.port).catch(() => { throw new Error('mcp-port-unavailable') }) : body.transport === 'http' ? listener : undefined
32
+ try {
33
+ mkdirSync(dirname(file), { recursive: true })
34
+ writeFileSync(`${file}.tmp`, JSON.stringify({ transport: body.transport, port: body.port }) + '\n', { mode: 0o600 })
35
+ renameSync(`${file}.tmp`, file)
36
+ } catch (error) { if (next !== listener) await next?.close(); throw error }
37
+ const previous = listener
38
+ preference = { transport: body.transport, port: body.port }; listener = next; issue = undefined
39
+ if (previous !== listener) await previous?.close()
40
+ return read()
41
+ })
42
+ queue = result.then(() => {}, () => {})
43
+ return result
44
+ }
45
+ const route: Route = { role: 'owner', maxBody: 8192, handle: async request => {
46
+ try {
47
+ if (request.method === 'GET') return jsonResponse(read(), 200, { 'cache-control': 'no-store' })
48
+ if (request.method !== 'POST') return problemResponse(405, 'GET or POST')
49
+ const body: unknown = await request.json().catch(() => undefined)
50
+ if (isRecord(body) && body.action === 'export' && typeof body.revision === 'string' && Object.keys(body).length === 2) {
51
+ await queue
52
+ if (body.revision !== revision()) return problemResponse(409, 'mcp-settings-conflict')
53
+ const connection = preference.transport === 'stdio' ? stdio : listener ? { url: listener.url, headers: { Authorization: `Bearer ${options.server.mcpToken}` } } : undefined
54
+ if (!connection) return problemResponse(409, 'mcp-connection-unavailable')
55
+ return jsonResponse({ mcpServers: { presmium: connection } }, 200, { 'cache-control': 'no-store' })
56
+ }
57
+ if (!validPreference(body) || typeof body.revision !== 'string' || Object.keys(body).some(key => !['revision', 'transport', 'port'].includes(key))) return problemResponse(400, 'mcp-settings-invalid')
58
+ return jsonResponse(await change(body as unknown as McpConnectionChange), 200, { 'cache-control': 'no-store' })
59
+ } catch (error) {
60
+ const code = error instanceof Error && ['mcp-settings-conflict', 'mcp-port-unavailable'].includes(error.message) ? error.message : 'mcp-settings-unavailable'
61
+ return problemResponse(code === 'mcp-settings-unavailable' ? 503 : 409, code)
62
+ }
63
+ } }
64
+ return { route }
65
+ }
66
+ function validPreference(value: unknown): value is { transport: 'stdio' | 'http', port: number, revision?: unknown } {
67
+ return isRecord(value) && ['stdio', 'http'].includes(String(value.transport)) && typeof value.port === 'number' && Number.isInteger(value.port) && value.port >= 0 && value.port <= 65535
68
+ }
@@ -0,0 +1,4 @@
1
+ export const MEDIA_UPLOAD_MESSAGES = {
2
+ 'zh-CN': { image: '上传图片', audio: '上传音频', choose: '选择文件', sending: '正在上传…', ready: '上传完成。请返回助手继续导入。', pending: '选择文件后自动上传,再由助手导入文稿。', failed: '上传未完成。请重新选择文件后重试。', unavailable: '此上传链接已失效,请返回助手重新发起上传。', limit: (size: number) => `文件大小上限:${size} MiB` },
3
+ en: { image: 'Upload Image', audio: 'Upload Audio', choose: 'Choose File', sending: 'Uploading…', ready: 'Upload complete. Return to the assistant to import it.', pending: 'Choose a file to upload it, then return to the assistant to import it.', failed: 'Upload did not finish. Choose the file and try again.', unavailable: 'This upload link expired. Return to the assistant to request another.', limit: (size: number) => `Maximum file size: ${size} MiB` },
4
+ }
@@ -0,0 +1,57 @@
1
+ import { randomBytes } from 'node:crypto'
2
+ import { readFileSync } from 'node:fs'
3
+ import type { MediaUpload } from '@lincyaw/kernel'
4
+ import { MEDIA_UPLOAD_MESSAGES } from './media-upload-messages.ts'
5
+
6
+ const escape = (value: string) => value.replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;').replaceAll('"', '&quot;')
7
+ let styles: string | undefined
8
+ const css = () => styles ??= [readFileSync(new URL(import.meta.resolve('@lincyaw/design/tokens.css')), 'utf8'), readFileSync(new URL(import.meta.resolve('@lincyaw/design/components.css')), 'utf8'), readFileSync(new URL('./media-upload.css', import.meta.url), 'utf8')].join('\n')
9
+ export function mediaUploadPage(value: MediaUpload | undefined, locale: 'zh-CN' | 'en', documentTitle?: string): Response {
10
+ const t = MEDIA_UPLOAD_MESSAGES[locale], nonce = randomBytes(18).toString('base64'), title = value ? t[value.kind] : t.unavailable
11
+ const ready = value?.state === 'ready', uploading = value?.state === 'uploading'
12
+ const script = value ? `
13
+ const form = document.querySelector('form');
14
+ const status = document.querySelector('[role="status"]');
15
+ const input = document.querySelector('input');
16
+ const choose = document.querySelector('button');
17
+ choose?.addEventListener('click', () => input.click());
18
+ form?.addEventListener('submit', async event => {
19
+ event.preventDefault();
20
+ const file = input.files[0];
21
+ if (!file || input.disabled) return;
22
+ if (file.size > ${value.maxBytes}) { status.textContent = ${JSON.stringify(t.limit(value.maxBytes / (1 << 20)))}; input.value = ''; return; }
23
+ input.disabled = true; choose.disabled = true;
24
+ status.textContent = ${JSON.stringify(t.sending)};
25
+ try {
26
+ const answer = await fetch(location.href, { method: 'POST', credentials: 'same-origin', redirect: 'error',
27
+ headers: { 'Content-Type': 'application/octet-stream', 'X-Presmium-Upload-Name': encodeURIComponent(file.name) }, body: file });
28
+ if (!answer.ok) throw Error();
29
+ form.remove();
30
+ status.textContent = ${JSON.stringify(t.ready)};
31
+ } catch {
32
+ status.textContent = ${JSON.stringify(t.failed)};
33
+ input.disabled = false; choose.disabled = false;
34
+ input.value = '';
35
+ }
36
+ });
37
+ input?.addEventListener('change', () => form.requestSubmit());
38
+ ` : ''
39
+ const html = `<!doctype html>
40
+ <html lang="${locale}">
41
+ <head>
42
+ <meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
43
+ <title>${escape(title)}</title><style nonce="${nonce}">${css()}</style>
44
+ <script nonce="${nonce}">
45
+ const theme = matchMedia('(prefers-color-scheme: dark)');
46
+ const update = () => document.documentElement.classList.toggle('dark', theme.matches);
47
+ update(); theme.addEventListener('change', update);
48
+ </script>
49
+ </head>
50
+ <body class="pm-ui pm-media-upload-body"><main class="pm-media-upload">
51
+ <h1>${escape(title)}</h1>${documentTitle ? `<p>${escape(documentTitle)}</p>` : ''}
52
+ ${value ? `<p>${escape(t.limit(value.maxBytes / (1 << 20)))}</p><p>${escape(t.pending)}</p>
53
+ ${ready || uploading ? '' : `<form><button class="pm-ui-button" type="button">${escape(t.choose)}</button><input hidden type="file" name="file" aria-label="${escape(t.choose)}" accept="${value.kind}/*" required></form>`}` : ''}
54
+ <p role="status">${ready ? escape(t.ready) : uploading ? escape(t.sending) : ''}</p>
55
+ </main><script nonce="${nonce}">${script}</script></body></html>`
56
+ return new Response(html, { status: value ? 200 : 410, headers: { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store', 'referrer-policy': 'no-referrer', 'x-content-type-options': 'nosniff', 'content-security-policy': `default-src 'none'; style-src 'nonce-${nonce}'; script-src 'nonce-${nonce}'; connect-src 'self'; form-action 'none'; base-uri 'none'; frame-ancestors 'none'` } })
57
+ }
@@ -0,0 +1,4 @@
1
+ .pm-media-upload-body { margin: 0; padding: var(--pm-space-6); color: var(--pm-color-ink); background: var(--pm-color-bg); font-family: var(--pm-font-sans); }
2
+ .pm-media-upload { max-inline-size: var(--pm-dialog-width); margin-inline: auto; }
3
+ .pm-media-upload form { display: grid; justify-items: start; gap: var(--pm-space-4); }
4
+ .pm-media-upload h1 { font-size: var(--pm-text-lg); }
@@ -0,0 +1,116 @@
1
+ import { randomBytes } from 'node:crypto'
2
+ import { ASSET_TITLE_MAX_LENGTH, DOCUMENT_AUDIO_MAX_BYTES, DOCUMENT_IMAGE_MAX_BYTES, MEDIA_UPLOAD_KINDS, MEDIA_UPLOAD_PATH, hasRole } from '@lincyaw/kernel'
3
+ import type { DocumentMediaUploads, MediaUpload, MediaUploadKind, Member } from '@lincyaw/kernel'
4
+ import { readAuthoringDocument } from './document-editor.ts'
5
+ import type { SourceEditor } from './source-editor.ts'
6
+ import { RequestError } from './errors.ts'
7
+ import { mediaUploadPage } from './media-upload-page.ts'
8
+
9
+ interface Entry { value: MediaUpload, document: string, documentId: string, member: string, locale?: 'zh-CN' | 'en', title: string, bytes?: Uint8Array, reserved: number, controller: AbortController, timer: ReturnType<typeof setTimeout> }
10
+ export interface MediaUploadsOwner extends DocumentMediaUploads {
11
+ read(document: string, documentId: string, member: Member, upload: string, kind: MediaUploadKind): { bytes: Uint8Array, name: string }
12
+ handle(request: Request): Promise<Response>
13
+ close(): void
14
+ }
15
+ const MAX_SLOTS = 64, MAX_BYTES = 64 << 20, LIFETIME_MS = 10 * 60_000
16
+
17
+ /** Bounded temporary input. Only the original media owners may commit these bytes to a document. */
18
+ export function createMediaUploads({ editor, url, lifetimeMs = LIFETIME_MS }: { editor: SourceEditor, url(): string, lifetimeMs?: number }): MediaUploadsOwner {
19
+ if (!Number.isSafeInteger(lifetimeMs) || lifetimeMs < 1 || lifetimeMs > LIFETIME_MS) throw new Error('media-upload-invalid')
20
+ const entries = new Map<string, Entry>()
21
+ let reserved = 0, closed = false
22
+ const fail = (status: number, code: string): never => { throw new RequestError(status, code) }
23
+ const current = (document: string, member: Member) => {
24
+ if (closed) return fail(503, 'media-upload-unavailable')
25
+ if (!hasRole(member, 'editor')) return fail(403, 'media-upload-permission-denied')
26
+ return readAuthoringDocument(editor, { document, member }).effective
27
+ }
28
+ const release = (entry: Entry) => { reserved -= entry.reserved; entry.reserved = 0; delete entry.bytes }
29
+ const retire = (upload: string, entry: Entry) => {
30
+ if (entries.get(upload) !== entry) return
31
+ entries.delete(upload); clearTimeout(entry.timer); entry.controller.abort(); release(entry)
32
+ }
33
+ const lookup = (upload: string): Entry => {
34
+ const entry = entries.get(upload)
35
+ if (!entry || closed || Date.now() >= Date.parse(entry.value.expiresAt)) { if (entry) retire(upload, entry); return fail(410, 'media-upload-unavailable') }
36
+ return entry
37
+ }
38
+ const authorized = (document: string, member: Member, upload: string, documentId = current(document, member).id) => {
39
+ const entry = lookup(upload)
40
+ if (entry.document !== document || entry.documentId !== documentId || entry.member !== member.id) return fail(403, 'media-upload-permission-denied')
41
+ return entry
42
+ }
43
+ return {
44
+ async prepare(document, kind, member) {
45
+ const content = current(document, member)
46
+ if (!MEDIA_UPLOAD_KINDS.includes(kind)) return fail(400, 'media-upload-invalid')
47
+ if (entries.size >= MAX_SLOTS) return fail(503, 'media-upload-busy')
48
+ const upload = randomBytes(32).toString('hex'), expiresAt = new Date(Date.now() + lifetimeMs).toISOString()
49
+ const value: MediaUpload = { upload, kind, url: `${url().replace(/\/$/, '')}${MEDIA_UPLOAD_PATH}/${upload}`, expiresAt, maxBytes: kind === 'audio' ? DOCUMENT_AUDIO_MAX_BYTES : DOCUMENT_IMAGE_MAX_BYTES, state: 'empty' }
50
+ const entry: Entry = { value, document, documentId: content.id, member: member.id, locale: content.metadata.lang?.startsWith('en') ? 'en' : !content.metadata.lang || content.metadata.lang.startsWith('zh') ? 'zh-CN' : undefined, title: content.metadata.title, reserved: 0, controller: new AbortController(), timer: setTimeout(() => retire(upload, entry), lifetimeMs) }
51
+ entry.timer.unref(); entries.set(upload, entry)
52
+ return { ...value }
53
+ },
54
+ async status(document, upload, member) { return { ...authorized(document, member, upload).value } },
55
+ read(document, documentId, member, upload, kind) {
56
+ if (!hasRole(member, 'editor')) return fail(403, 'media-upload-permission-denied')
57
+ if (current(document, member).id !== documentId) return fail(403, 'media-upload-permission-denied')
58
+ const entry = authorized(document, member, upload, documentId)
59
+ if (entry.value.kind !== kind) return fail(400, 'media-upload-kind')
60
+ if (!entry.bytes || entry.value.state !== 'ready' || !entry.value.name) return fail(409, 'media-upload-not-ready')
61
+ return { bytes: new Uint8Array(entry.bytes), name: entry.value.name }
62
+ },
63
+ async handle(request) {
64
+ const headers = { 'cache-control': 'no-store', 'referrer-policy': 'no-referrer', 'access-control-allow-origin': '*', 'access-control-allow-methods': 'POST, OPTIONS', 'access-control-allow-headers': 'Content-Type, X-Presmium-Upload-Name', 'x-content-type-options': 'nosniff' }
65
+ let entry: Entry | undefined
66
+ try {
67
+ const upload = new URL(request.url).pathname.split('/').at(-1) ?? ''
68
+ if (!/^[a-f0-9]{64}$/.test(upload)) return fail(410, 'media-upload-unavailable')
69
+ entry = lookup(upload)
70
+ if (request.method === 'GET') return mediaUploadPage(entry.value, entry.locale ?? (request.headers.get('accept-language')?.startsWith('en') ? 'en' : 'zh-CN'), entry.title)
71
+ if (request.method === 'OPTIONS') return new Response(null, { status: 204, headers })
72
+ if (request.method !== 'POST') return new Response(null, { status: 405, headers })
73
+ if (entry.value.state !== 'empty') return fail(409, 'media-upload-already-written')
74
+ const declared = request.headers.get('content-length')
75
+ if (declared !== null && !/^\d+$/.test(declared)) return fail(400, 'media-upload-invalid')
76
+ const allocation = declared === null ? entry.value.maxBytes : Number(declared)
77
+ if (!Number.isSafeInteger(allocation) || allocation < 1 || allocation > entry.value.maxBytes) return fail(413, 'media-upload-size')
78
+ if (reserved + allocation > MAX_BYTES) return fail(503, 'media-upload-busy')
79
+ const encoded = request.headers.get('x-presmium-upload-name') ?? entry.value.kind
80
+ if (encoded.length > 4096) return fail(400, 'media-upload-invalid')
81
+ let name: string
82
+ try { name = decodeURIComponent(encoded).replaceAll('\\', '/').split('/').at(-1)!.replace(/[\u0000-\u001f\u007f-\u009f]/g, '').trim() } catch { return fail(400, 'media-upload-invalid') }
83
+ name = [...name].slice(0, ASSET_TITLE_MAX_LENGTH).join('') || entry.value.kind
84
+ const reader = request.body?.getReader()
85
+ if (!reader) return fail(400, 'media-upload-invalid')
86
+ const signal = AbortSignal.any([request.signal, entry.controller.signal]), bytes = new Uint8Array(allocation)
87
+ entry.reserved = allocation; reserved += allocation; entry.value.state = 'uploading'
88
+ const abort = () => { void reader.cancel().catch(() => {}) }
89
+ signal.addEventListener('abort', abort, { once: true })
90
+ let length = 0
91
+ try {
92
+ signal.throwIfAborted()
93
+ for (;;) {
94
+ const next = await reader.read(); signal.throwIfAborted()
95
+ if (next.done) break
96
+ if (length + next.value.byteLength > allocation) return fail(413, 'media-upload-size')
97
+ bytes.set(next.value, length); length += next.value.byteLength
98
+ }
99
+ if (!length || declared !== null && length !== allocation) return fail(400, 'media-upload-invalid')
100
+ lookup(upload); signal.throwIfAborted()
101
+ entry.bytes = bytes.subarray(0, length); entry.value = { ...entry.value, state: 'ready', name, byteLength: length }
102
+ return new Response(JSON.stringify({ uploaded: true }), { headers: { ...headers, 'content-type': 'application/json' } })
103
+ } finally {
104
+ signal.removeEventListener('abort', abort)
105
+ if (entry.value.state !== 'ready') { release(entry); if (entries.get(upload) === entry) entry.value.state = 'empty'; await reader.cancel().catch(() => {}) }
106
+ reader.releaseLock()
107
+ }
108
+ } catch (error) {
109
+ if (request.method === 'GET') return mediaUploadPage(undefined, entry?.locale ?? (request.headers.get('accept-language')?.startsWith('en') ? 'en' : 'zh-CN'))
110
+ const status = error instanceof RequestError ? error.status : 400
111
+ return new Response(JSON.stringify({ error: { code: error instanceof RequestError ? error.message : 'media-upload-invalid' } }), { status, headers: { ...headers, 'content-type': 'application/json' } })
112
+ }
113
+ },
114
+ close() { closed = true; for (const [upload, entry] of entries) retire(upload, entry) },
115
+ }
116
+ }
@@ -41,7 +41,6 @@ export function pageDeleteRoute({ config, editor, workbench, locks, revisions }:
41
41
  if (!config.singleDeck) {
42
42
  const workspaceSource = editor.read(editor.scope(''), WORKSPACE_CONFIG, ctx.member)
43
43
  const currentConfig = readWorkspaceConfig(config.root)
44
- if (JSON.stringify(currentConfig.documents) !== JSON.stringify(config.documents)) throw new RequestError(409, 'page-references-unavailable')
45
44
  dependencies.set(workspaceSource.path, workspaceSource.version)
46
45
  const workspaceView = { ...answer.doc, meta: { ...answer.doc.meta, entry: WORKSPACE_CONFIG }, config: { ...answer.doc.config, presmium: { site: currentConfig.site } }, sections: [] }
47
46
  if (pageIncomingReferences(workspaceView, answer.doc.meta.entry, targets).length) references.push({ document: '', section })
@@ -2,7 +2,7 @@ import { createHash } from 'node:crypto'
2
2
  import { existsSync, lstatSync, readFileSync, readdirSync, readlinkSync } from 'node:fs'
3
3
  import { join, posix } from 'node:path'
4
4
  import { DOCUMENT_ENTRY, parseAnchor, validateDocument } from '@lincyaw/kernel'
5
- import type { ProjectOperation, TeachingDocument, DocumentFileChange } from '@lincyaw/kernel'
5
+ import type { ProjectOperation, PresmiumDocument, DocumentFileChange } from '@lincyaw/kernel'
6
6
  import { invalidDocumentDir, isWithin, movedUrl, rewriteLinks } from '../domain/paths.ts'
7
7
  import { isDocumentDir, listDocuments, readWorkspaceConfig } from './config.ts'
8
8
  import type { WorkspaceConfig } from './config.ts'
@@ -62,7 +62,7 @@ export function projectMaterial(config: WorkspaceConfig, operation: ProjectOpera
62
62
  const dirs = operation.op === 'copy' || operation.op === 'rename' ? [operation.dir, operation.to] : [operation.dir]
63
63
  if (operation.op === 'retitle') walk(join(config.root, entry(operation.dir)), entry(operation.dir), operation.dir)
64
64
  else for (const dir of dirs) { safeParents(dir); walk(join(config.root, dir), dir, dir) }
65
- const canonical = new Map<string, TeachingDocument>()
65
+ const canonical = new Map<string, PresmiumDocument>()
66
66
  for (const doc of known) {
67
67
  safeParents(doc.dir)
68
68
  const path = join(config.root, doc.entry), stat = lstatSync(path)
@@ -3,7 +3,7 @@ import { listDocuments } from './config.ts'
3
3
  import { randomUUID } from 'node:crypto'
4
4
  import { existsSync, readFileSync } from 'node:fs'
5
5
  import { join } from 'node:path'
6
- import { PROJECT_MAX_PLANS, PROJECT_PLAN_TTL_MS, PROJECT_MAX_REQUEST_CHARS, PROJECT_MAX_RESPONSE_CHARS, hasRole, jsonResponse, problemResponse, validateDocument } from '@lincyaw/kernel'
6
+ import { PROJECT_MAX_PLANS, PROJECT_PLAN_TTL_MS, PROJECT_MAX_REQUEST_CHARS, PROJECT_MAX_RESPONSE_CHARS, hasRole, jsonResponse, problemResponse, validateDocument, DOCUMENT_ENTRY } from '@lincyaw/kernel'
7
7
  import type { CanonicalSource, DocumentChange, ProjectApplied, ProjectApply, ProjectAuthoring, ProjectCaller, ProjectOperation, ProjectPlan, ProjectPlanRequest, Route } from '@lincyaw/kernel'
8
8
  import { validateProjectApply, validateProjectPlan } from '@lincyaw/kernel/node'
9
9
  import type { WorkspaceConfig } from './config.ts'
@@ -13,6 +13,7 @@ import type { Revisions } from './revisions.ts'
13
13
  import { DOCUMENT_OPERATION_MAX_BACKUP_BYTES, DOCUMENT_OPERATION_MAX_BACKUP_ENTRIES, documentDirOf } from './writer.ts'
14
14
  import { catchRequestErrors, RequestError } from './errors.ts'
15
15
  import { projectConfiguration, projectDigest, projectMaterial } from './project-files.ts'
16
+ import { listTemplates } from './templates.ts'
16
17
 
17
18
  type Admission = { signature: string, admission: Promise<ProjectPlan> }
18
19
  type Stored = { member: string, origin: ProjectCaller['origin'], signature: string, plan: ProjectPlan, material?: ReturnType<typeof projectMaterial>, canonical?: { change: DocumentChange, planId: string, source: CanonicalSource }, receipt?: ProjectApplied, work?: Promise<ProjectApplied> }
@@ -59,14 +60,28 @@ export function createProjectAuthoring(options: { config: WorkspaceConfig, opera
59
60
  }
60
61
  const key = (request: ProjectPlanRequest, caller: ProjectCaller) => JSON.stringify([caller.member.id, caller.origin, request.id])
61
62
  const service: ProjectAuthoring = {
62
- async capabilities(caller) {
63
+ async capabilities(caller, query = {}) {
63
64
  if (closed) throw new RequestError(503, 'project-owner-closed')
65
+ const offset = query.templatesOffset ?? 0
66
+ if (!Number.isSafeInteger(offset) || offset < 0 || Object.keys(query).some(key => key !== 'templatesOffset')) throw new RequestError(400, 'project-request-invalid')
64
67
  const observed = await observation(), directory = reasons(caller), metadata = reasons(caller, { op: 'retitle', dir: caller.boundDocument ?? '', title: 'capability' })
65
68
  if (!observed.snapshot && !directory.includes('project-git-unavailable')) directory.push('project-head-unavailable')
66
69
  const actions = Object.fromEntries(['create', 'copy', 'rename', 'delete', 'retitle'].map(op => { const unavailable = op === 'retitle' ? metadata : directory; return [op, { available: unavailable.length === 0, reasons: unavailable }] })) as import('@lincyaw/kernel').ProjectCapabilities['actions']
67
70
  const available = Object.values(actions).some(action => action.available)
68
- return bounded({ available, actions, reasons: available ? [] : [...new Set([...directory, ...metadata])], observation: observed, verification: 'configuration-only', rootDirectoryOperations: false,
69
- limits: { requestChars: PROJECT_MAX_REQUEST_CHARS, responseChars: PROJECT_MAX_RESPONSE_CHARS, backupEntries: DOCUMENT_OPERATION_MAX_BACKUP_ENTRIES, backupBytes: DOCUMENT_OPERATION_MAX_BACKUP_BYTES, plans: PROJECT_MAX_PLANS, ttlMs: PROJECT_PLAN_TTL_MS } })
71
+ const answer: import('@lincyaw/kernel').ProjectCapabilities = { available, actions, reasons: available ? [] : [...new Set([...directory, ...metadata])], observation: observed, verification: 'configuration-only', rootDirectoryOperations: false,
72
+ limits: { requestChars: PROJECT_MAX_REQUEST_CHARS, responseChars: PROJECT_MAX_RESPONSE_CHARS, backupEntries: DOCUMENT_OPERATION_MAX_BACKUP_ENTRIES, backupBytes: DOCUMENT_OPERATION_MAX_BACKUP_BYTES, plans: PROJECT_MAX_PLANS, ttlMs: PROJECT_PLAN_TTL_MS } }
73
+ if (caller.boundDocument === undefined) {
74
+ const templates = listTemplates(config)
75
+ if (offset > templates.length) throw new RequestError(400, 'project-request-invalid')
76
+ answer.templates = []
77
+ for (const template of templates.slice(offset, offset + 20)) {
78
+ if (JSON.stringify({ ...answer, templates: [...answer.templates, template], nextTemplatesOffset: offset + answer.templates.length + 1 }).length > PROJECT_MAX_RESPONSE_CHARS) break
79
+ answer.templates.push(template)
80
+ }
81
+ if (!answer.templates.length && offset < templates.length) throw new RequestError(413, 'project-response-too-large')
82
+ if (offset + answer.templates.length < templates.length) answer.nextTemplatesOffset = offset + answer.templates.length
83
+ } else if (offset) throw new RequestError(403, 'project-workspace-scope-required')
84
+ return bounded(answer)
70
85
  },
71
86
  async plan(request, caller) {
72
87
  budget(request)
@@ -168,7 +183,7 @@ export function createProjectAuthoring(options: { config: WorkspaceConfig, opera
168
183
  if (op.op === 'rename' || op.op === 'delete') if (existsSync(join(config.root, op.dir))) throw new RequestError(409, 'project-readback-changed', { committed: true })
169
184
  for (const change of stored.material!.changes) if ('content' in change && projectDigest(readFileSync(join(config.root, change.path))) !== projectDigest(change.content)) throw new RequestError(409, 'project-readback-changed', { committed: true })
170
185
  if (stored.plan.documentId && answer.dir) {
171
- const checked = validateDocument(JSON.parse(readFileSync(join(config.root, answer.dir, 'lecture.json'), 'utf8')))
186
+ const checked = validateDocument(JSON.parse(readFileSync(join(config.root, answer.dir, DOCUMENT_ENTRY), 'utf8')))
172
187
  if (checked.document?.id !== stored.plan.documentId) throw new RequestError(409, 'project-readback-changed', { committed: true })
173
188
  }
174
189
  stored.receipt = bounded(receipt)