@lincyaw/workspace 1.0.0-rc.11 → 1.0.0-rc.111

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 (40) hide show
  1. package/package.json +7 -5
  2. package/src/node/agent-activity.ts +46 -0
  3. package/src/node/authoring-clients.ts +73 -20
  4. package/src/node/authoring-windows.ts +165 -0
  5. package/src/node/build.ts +54 -24
  6. package/src/node/capture.ts +383 -0
  7. package/src/node/config.ts +1 -0
  8. package/src/node/document-audio.ts +60 -41
  9. package/src/node/document-authoring.ts +7 -1
  10. package/src/node/document-images.ts +20 -10
  11. package/src/node/document-import.ts +120 -0
  12. package/src/node/document-operations.ts +1 -0
  13. package/src/node/document-voice.ts +104 -6
  14. package/src/node/git.ts +23 -4
  15. package/src/node/local-history.ts +70 -0
  16. package/src/node/locks.ts +12 -0
  17. package/src/node/mcp-settings.ts +68 -0
  18. package/src/node/media-upload-messages.ts +4 -0
  19. package/src/node/media-upload-page.ts +57 -0
  20. package/src/node/media-upload.css +4 -0
  21. package/src/node/media-uploads.ts +116 -0
  22. package/src/node/projects.ts +18 -3
  23. package/src/node/review/agent-session-reviews.ts +194 -63
  24. package/src/node/review/agent-workspace.ts +117 -0
  25. package/src/node/review/git-review.ts +41 -11
  26. package/src/node/review/record.ts +5 -1
  27. package/src/node/review/routes.ts +9 -1
  28. package/src/node/review/workspace-review.ts +87 -0
  29. package/src/node/revision-files.ts +54 -0
  30. package/src/node/revisions.ts +233 -58
  31. package/src/node/routes.ts +35 -58
  32. package/src/node/serve.ts +197 -49
  33. package/src/node/site.ts +1 -1
  34. package/src/node/source-editor.ts +46 -20
  35. package/src/node/speech-settings.ts +6 -8
  36. package/src/node/templates.ts +2 -2
  37. package/src/node/workbench-api.ts +14 -3
  38. package/src/node/workspace-changes.ts +130 -0
  39. package/src/node/workspace-source.ts +133 -0
  40. package/src/node/writer.ts +3 -3
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lincyaw/workspace",
3
- "version": "1.0.0-rc.11",
3
+ "version": "1.0.0-rc.111",
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": {
@@ -32,13 +32,15 @@
32
32
  "dependencies": {
33
33
  "image-size": "2.0.4",
34
34
  "mime-types": "3.0.2",
35
+ "playwright-chromium": "1.64.1",
35
36
  "yaml": "^2.9.1",
36
- "@lincyaw/kernel": "1.0.0-rc.11",
37
- "@lincyaw/compiler": "1.0.0-rc.11",
38
- "@lincyaw/server": "1.0.0-rc.11"
37
+ "@lincyaw/kernel": "1.0.0-rc.111",
38
+ "@lincyaw/server": "1.0.0-rc.111",
39
+ "@lincyaw/design": "1.0.0-rc.111",
40
+ "@lincyaw/compiler": "1.0.0-rc.111"
39
41
  },
40
42
  "devDependencies": {
41
43
  "@types/mime-types": "^3.0.1",
42
- "@lincyaw/mcp": "1.0.0-rc.11"
44
+ "@lincyaw/mcp": "1.0.0-rc.111"
43
45
  }
44
46
  }
@@ -0,0 +1,46 @@
1
+ import { pushStream, sseResponse, problemResponse, randomUUID } from '@lincyaw/kernel'
2
+ import type { AgentActivity, AgentActivityObserver, AgentActivitySnapshot, Route } from '@lincyaw/kernel'
3
+
4
+ /** One workspace lifetime, bounded observations, and member-scoped readers on the existing event transport. */
5
+ export function createAgentActivity() {
6
+ const entries = new Map<string, { member: string, value: AgentActivity, timer: ReturnType<typeof setTimeout> }>()
7
+ const readers = new Set<{ member: string, send(snapshot: AgentActivitySnapshot): void, end(): void }>()
8
+ let closed = false
9
+ const snapshot = (member: string): AgentActivitySnapshot => ({ activities: [...entries.values()].filter(entry => entry.member === member).map(entry => structuredClone(entry.value)) })
10
+ const publish = (member: string) => { for (const reader of readers) if (reader.member === member) reader.send(snapshot(member)) }
11
+ const remove = (id: string) => {
12
+ const entry = entries.get(id)
13
+ if (!entry) return
14
+ clearTimeout(entry.timer); entries.delete(id); publish(entry.member)
15
+ }
16
+ const service: AgentActivityObserver = {
17
+ begin(input, member) {
18
+ if (closed) return () => {}
19
+ if (entries.size >= 64) remove(entries.keys().next().value!)
20
+ const id = randomUUID(), value: AgentActivity = { ...structuredClone(input), id, state: 'running', startedAt: Date.now() }
21
+ const entry = { member: member.id, value, timer: setTimeout(() => remove(id), 600_000) }
22
+ entry.timer.unref(); entries.set(id, entry); publish(member.id)
23
+ return state => {
24
+ if (closed || entries.get(id) !== entry || entry.value.state !== 'running') return
25
+ clearTimeout(entry.timer)
26
+ entry.value = { ...entry.value, state, finishedAt: Date.now() }
27
+ entry.timer = setTimeout(() => remove(id), 6000); entry.timer.unref(); publish(member.id)
28
+ }
29
+ },
30
+ }
31
+ const route: Route = { role: 'owner', handle: async (request, ctx) => {
32
+ if (request.method !== 'GET') return problemResponse(405, 'GET')
33
+ if (closed) return problemResponse(503, 'agent-activity-closed')
34
+ const stream = pushStream<{ event: string, data: AgentActivitySnapshot }>(push => {
35
+ const reader = { member: ctx.member.id, send: (data: AgentActivitySnapshot) => push({ event: 'agent-activity', data }), end: () => stream.end() }
36
+ readers.add(reader); reader.send(snapshot(reader.member))
37
+ return () => { readers.delete(reader) }
38
+ }, { signal: request.signal, latestOnly: true })
39
+ return sseResponse(stream, request.signal)
40
+ } }
41
+ return { service, routes: { 'agent-activity/events': route }, close() {
42
+ closed = true
43
+ for (const entry of entries.values()) clearTimeout(entry.timer)
44
+ entries.clear(); for (const reader of readers) reader.end(); readers.clear()
45
+ } }
46
+ }
@@ -1,5 +1,5 @@
1
1
  import { randomBytes, randomUUID, createHash } from 'node:crypto'
2
- import { AUTHORING_CLIENT_ACK_MAX_BYTES, AUTHORING_CLIENT_MAX_CLIENTS, AUTHORING_CLIENT_MAX_REQUESTS, AUTHORING_CLIENT_MAX_REQUEST_CHARS, AUTHORING_CLIENT_MAX_RESPONSE_CHARS, AUTHORING_CLIENT_REQUEST_TIMEOUT_MS, authoringClientResultFits, DOCUMENT_ENTRY, fnv1a64, hasRole, isRecord, jsonResponse, problemResponse, pushStream, sseResponse } from '@lincyaw/kernel'
2
+ import { AUTHORING_CLIENT_ACK_MAX_BYTES, AUTHORING_CLIENT_MAX_CLIENTS, AUTHORING_CLIENT_MAX_REQUESTS, AUTHORING_CLIENT_MAX_REQUEST_CHARS, AUTHORING_CLIENT_MAX_RESPONSE_CHARS, AUTHORING_CLIENT_REQUEST_TIMEOUT_MS, authoringClientActionChangesSource, authoringClientActionMutatesDraft, authoringClientActionUsesLocalDraft, authoringClientResultFits, DOCUMENT_ENTRY, fnv1a64, hasRole, isRecord, jsonResponse, problemResponse, pushStream, sseResponse } from '@lincyaw/kernel'
3
3
  import type { AuthoringClientAcknowledgement, AuthoringClientConnection, AuthoringClientDescriptor, AuthoringClientEvent, AuthoringClientLease, AuthoringClientOpen, AuthoringClientReport, AuthoringClientRequest, AuthoringClientRequestResult, AuthoringClients, CanonicalSource, Member, PushStream, Route } from '@lincyaw/kernel'
4
4
  import { validateAuthoringClientAcknowledgement, validateAuthoringClientLease, validateAuthoringClientOpen, validateAuthoringClientQuery, validateAuthoringClientReport, validateAuthoringClientRequest, validateAuthoringClientRequestQuery } from '@lincyaw/kernel/node'
5
5
  import { readAuthoringDocument } from './document-editor.ts'
@@ -7,7 +7,7 @@ import { catchRequestErrors, RequestError } from './errors.ts'
7
7
  import type { SourceEditor } from './source-editor.ts'
8
8
 
9
9
  type Client = { member: string, credential: string, value: AuthoringClientDescriptor, sequence: number, lastSignature?: string, send?(value: AuthoringClientEvent): void, close?(): void }
10
- type Pending = { member: string, signature: string, request: AuthoringClientRequest, value: AuthoringClientRequestResult, timer?: ReturnType<typeof setTimeout> }
10
+ type Pending = { member: string, signature: string, request: AuthoringClientRequest, value: AuthoringClientRequestResult, timer?: ReturnType<typeof setTimeout>, done: Promise<void>, resolve(): void }
11
11
  const sameSource = (a: CanonicalSource, b: CanonicalSource) => a.documentId === b.documentId && a.version === b.version && a.fingerprint === b.fingerprint
12
12
  const size = (value: unknown) => JSON.stringify(value, null, 2).length
13
13
  const budget = (value: unknown, maximum = AUTHORING_CLIENT_MAX_REQUEST_CHARS) => { const text = JSON.stringify(value); if (text === undefined) throw new RequestError(400, 'client-request-invalid'); if (text.length > maximum) throw new RequestError(413, 'client-request-too-large') }
@@ -15,7 +15,8 @@ const digest = (value: unknown) => createHash('sha256').update(JSON.stringify(va
15
15
  const terminal = (pending: Pending) => !['sent', 'executing'].includes(pending.value.state)
16
16
 
17
17
  /** Ephemeral live-client control. It owns no document writer, compilation or durable task ledger. */
18
- export function createAuthoringClients(editor: SourceEditor) {
18
+ export function createAuthoringClients(editor: SourceEditor, options: { reviewRequired?: boolean } = {}) {
19
+ const requiresReview = (type: import('@lincyaw/kernel').AuthoringClientActionType) => options.reviewRequired && authoringClientActionChangesSource(type) && type !== 'source.flush'
19
20
  const clients = new Map<string, Client>(), requests = new Map<string, Pending>()
20
21
  let closed = false
21
22
  const clientKey = (member: string, clientId: string) => JSON.stringify([member, clientId])
@@ -41,6 +42,7 @@ export function createAuthoringClients(editor: SourceEditor) {
41
42
  if (terminal(pending)) return
42
43
  clearTimeout(pending.timer); pending.timer = undefined
43
44
  pending.value = { ...pending.value, state, ...code ? { error: { code } } : {} }
45
+ pending.resolve()
44
46
  if (state === 'expired') clients.get(clientKey(pending.member, pending.request.clientId))?.send?.({ type: 'cancel', requestId: pending.request.requestId, connectionId: pending.request.expectedClientState.connectionId })
45
47
  }
46
48
  const disconnect = (client: Client, connectionId: string) => {
@@ -68,9 +70,15 @@ export function createAuthoringClients(editor: SourceEditor) {
68
70
  if (!validateAuthoringClientQuery(query)) throw new RequestError(400, 'client-query-invalid')
69
71
  const all = [...clients.values()].filter(client => client.member === member.id && client.value.document === document && (!query.clientId || client.value.clientId === query.clientId)
70
72
  && (!query.after || client.value.clientId > query.after)).sort((a, b) => a.value.clientId.localeCompare(b.value.clientId))
71
- const answer = { document, clients: [] as AuthoringClientDescriptor[], unavailable: ['recording', 'new-comment-restore', 'active-comment-discard', 'timing-drafts', 'recording-drafts', 'review', 'open-document'] }
73
+ const answer = { document, clients: [] as AuthoringClientDescriptor[], unavailable: ['other-form-drafts', 'review', 'open-document', ...options.reviewRequired ? ['source-writes-require-review'] : []] }
72
74
  for (const client of all) {
73
75
  const row = structuredClone(client.value)
76
+ row.snapshot.actions = row.snapshot.actions.filter(type => !requiresReview(type))
77
+ const pending = [...requests.values()].find(pending => pending.member === member.id && pending.value.document === document && pending.value.clientId === row.clientId && pending.value.epoch === row.epoch && !terminal(pending))
78
+ if (pending) {
79
+ row.pendingRequest = { requestId: pending.value.requestId, action: pending.value.action, ...pending.value.cancellationRequested ? { cancellationRequested: true } : {} }
80
+ row.snapshot.actions = []
81
+ }
74
82
  if (size({ ...answer, clients: [...answer.clients, row], nextAfter: row.clientId }) > AUTHORING_CLIENT_MAX_RESPONSE_CHARS) break
75
83
  answer.clients.push(row)
76
84
  }
@@ -78,14 +86,15 @@ export function createAuthoringClients(editor: SourceEditor) {
78
86
  return { ...answer, ...answer.clients.length < all.length ? { nextAfter: answer.clients.at(-1)!.clientId } : {} }
79
87
  },
80
88
  async request(document, request, member) {
81
- const actual = current(document, member); budget(request)
89
+ authorize(document, member); budget(request)
82
90
  if (!validateAuthoringClientRequest(request)) throw new RequestError(400, 'client-request-invalid')
91
+ if (requiresReview(request.action.type)) throw new RequestError(409, 'authoring-review-required')
83
92
  const key = requestKey(member.id, document, request), signature = digest(request), known = requests.get(key)
84
- if (known) { if (known.signature !== signature) throw new RequestError(409, 'client-request-id-reused'); return readResult(known, actual) }
93
+ if (known) { if (known.signature !== signature) throw new RequestError(409, 'client-request-id-reused'); return readResult(known, authoringClientActionUsesLocalDraft(request.action.type) ? undefined : current(document, member)) }
85
94
  const client = clients.get(clientKey(member.id, request.clientId)), state = client?.value
86
95
  if (!client || !state?.connected || state.document !== document || state.epoch !== request.epoch) throw new RequestError(409, 'client-unavailable')
87
96
  if (state.connectionId !== request.expectedClientState.connectionId || state.snapshot.revision !== request.expectedClientState.revision) throw new RequestError(409, 'client-state-changed')
88
- if (!sameSource(actual, request.source) || !sameSource(state.snapshot.source, request.source)) throw new RequestError(409, 'client-source-changed')
97
+ if (!authoringClientActionUsesLocalDraft(request.action.type) && !sameSource(current(document, member), request.source) || (request.action.type === 'body-drafts.retry' ? state.snapshot.source.documentId !== request.source.documentId : !sameSource(state.snapshot.source, request.source))) throw new RequestError(409, 'client-source-changed')
89
98
  if (!state.snapshot.actions.includes(request.action.type)) throw new RequestError(409, 'client-action-unavailable')
90
99
  if ([...requests.values()].some(value => !terminal(value) && value.member === member.id && value.request.clientId === request.clientId)) throw new RequestError(409, 'client-busy')
91
100
  while (requests.size >= AUTHORING_CLIENT_MAX_REQUESTS) {
@@ -95,11 +104,13 @@ export function createAuthoringClients(editor: SourceEditor) {
95
104
  }
96
105
  const now = Date.now(), value: AuthoringClientRequestResult = { document, clientId: state.clientId, epoch: state.epoch, connectionId: state.connectionId, requestId: request.requestId, action: request.action.type, source: request.source,
97
106
  state: 'sent', admittedAt: new Date(now).toISOString(), expiresAt: new Date(now + AUTHORING_CLIENT_REQUEST_TIMEOUT_MS).toISOString(), verification: 'not-acknowledged', current: false }
98
- const pending: Pending = { member: member.id, signature, request: structuredClone(request), value }
107
+ let resolve!: () => void
108
+ const done = new Promise<void>(finish => resolve = finish)
109
+ const pending: Pending = { member: member.id, signature, request: structuredClone(request), value, done, resolve }
99
110
  pending.timer = setTimeout(() => finish(pending, 'expired', 'client-request-timeout'), AUTHORING_CLIENT_REQUEST_TIMEOUT_MS)
100
111
  requests.set(key, pending)
101
112
  client.send?.({ type: 'request', request: pending.request, expiresAt: value.expiresAt })
102
- return readResult(pending, actual)
113
+ return readResult(pending, authoringClientActionUsesLocalDraft(request.action.type) ? undefined : current(document, member))
103
114
  },
104
115
  async get(document, query, member) {
105
116
  authorize(document, member); budget(query)
@@ -110,6 +121,21 @@ export function createAuthoringClients(editor: SourceEditor) {
110
121
  try { actual = current(document, member) } catch { /* An old receipt stays readable if the current source is invalid. */ }
111
122
  return readResult(pending, actual)
112
123
  },
124
+ async cancel(document, query, member) {
125
+ if (closed) throw new RequestError(503, 'client-owner-closed')
126
+ if (!hasRole(member, 'editor')) throw new RequestError(403, 'client-permission-denied')
127
+ budget(query)
128
+ if (!validateAuthoringClientRequestQuery(query)) throw new RequestError(400, 'client-request-query-invalid')
129
+ const pending = requests.get(requestKey(member.id, document, query))
130
+ if (!pending) throw new RequestError(404, 'client-request-not-found')
131
+ if (!terminal(pending) && !pending.value.cancellationRequested) {
132
+ pending.value.cancellationRequested = true
133
+ clients.get(clientKey(member.id, query.clientId))?.send?.({ type: 'cancel', requestId: query.requestId, connectionId: pending.value.connectionId })
134
+ }
135
+ let actual: CanonicalSource | undefined
136
+ try { actual = current(document, member) } catch { /* Cancelling the caller's original request does not require a valid new source. */ }
137
+ return readResult(pending, actual)
138
+ },
113
139
  }
114
140
  const register = (document: string, value: AuthoringClientOpen, member: Member): AuthoringClientLease => {
115
141
  const source = current(document, member)
@@ -147,28 +173,39 @@ export function createAuthoringClients(editor: SourceEditor) {
147
173
  if (pending && Date.now() >= Date.parse(pending.value.expiresAt)) finish(pending, 'expired', 'client-request-timeout')
148
174
  if (!pending || terminal(pending) || pending.request.expectedClientState.connectionId !== lease.connectionId) throw new RequestError(409, 'client-request-expired')
149
175
  if (ack.state === 'executing' && pending.value.state !== 'sent' || ack.state === 'done' && pending.value.state !== 'executing') throw new RequestError(409, 'client-ack-state-invalid')
150
- if ((ack.state === 'executing' || ack.state === 'done') && !sameSource(ack.snapshot.source, pending.request.source) && !(ack.state === 'done' && pending.request.action.type === 'source.flush' && ack.snapshot.source.documentId === pending.request.source.documentId)) throw new RequestError(409, 'client-source-changed')
151
- const actual = ack.state === 'executing' || ack.state === 'done' ? current(document, member) : undefined
152
- if (ack.state === 'executing' && (ack.snapshot.revision !== pending.request.expectedClientState.revision || !actual || !sameSource(actual, pending.request.source))) throw new RequestError(409, 'client-state-changed')
153
- if (ack.state === 'done' && (!actual || !sameSource(actual, ack.snapshot.source))) throw new RequestError(409, 'client-source-changed')
176
+ if ((ack.state === 'executing' || ack.state === 'done') && !sameSource(ack.snapshot.source, pending.request.source) && !(ack.state === 'executing' && pending.request.action.type === 'body-drafts.retry' && ack.snapshot.source.documentId === pending.request.source.documentId) && !(ack.state === 'done' && (authoringClientActionChangesSource(pending.request.action.type) || authoringClientActionUsesLocalDraft(pending.request.action.type)) && ack.snapshot.source.documentId === pending.request.source.documentId)) throw new RequestError(409, 'client-source-changed')
177
+ const localDraft = authoringClientActionUsesLocalDraft(pending.request.action.type)
178
+ const actual = !localDraft && (ack.state === 'executing' || ack.state === 'done') ? current(document, member) : undefined
179
+ if (ack.state === 'executing' && (ack.snapshot.revision !== pending.request.expectedClientState.revision || !localDraft && (!actual || !sameSource(actual, pending.request.source)))) throw new RequestError(409, 'client-state-changed')
180
+ if (ack.state === 'done' && !localDraft && (!actual || !sameSource(actual, ack.snapshot.source))) throw new RequestError(409, 'client-source-changed')
154
181
  const action = pending.request.action
155
- const family = action.type.startsWith('comment-drafts.') ? 'comment' : action.type.startsWith('component-drafts.') ? 'component' : undefined
182
+ const family = action.type.startsWith('production-drafts.') ? 'production' : action.type.startsWith('body-drafts.') ? 'body' : action.type.startsWith('comment-drafts.') ? 'comment' : action.type.startsWith('component-drafts.') ? 'component' : undefined
156
183
  if (ack.result && (!family || ack.state !== 'done' || ack.result.type !== action.type || ack.result.family !== family)) throw new RequestError(400, 'client-result-invalid')
157
184
  if (family && ack.state === 'done') {
158
185
  const result = ack.result
159
- const mutation = action.type === 'component-drafts.restore' || action.type === 'component-drafts.discard' || action.type === 'comment-drafts.restore' || action.type === 'comment-drafts.discard'
186
+ const mutation = authoringClientActionMutatesDraft(action.type)
160
187
  if (!result || (mutation ? ack.snapshot.revision <= pending.request.expectedClientState.revision : ack.snapshot.revision !== pending.request.expectedClientState.revision)) throw new RequestError(409, `client-${family}-drafts-changed`)
161
188
  if (!authoringClientResultFits({ request: pending.request, connection: client.value, document, snapshot: ack.snapshot }, result)) throw new RequestError(413, `client-${family}-result-too-large`)
189
+ if ((action.type === 'body-drafts.read' || action.type === 'production-drafts.read') && (result.type !== action.type || result.draft !== action.draft
190
+ || result.offset !== action.offset || result.endOffset !== result.offset + result.jsonText.length || result.endOffset > result.totalUtf16
191
+ || result.jsonText.length > (action.maxChars ?? 2048))) throw new RequestError(400, 'client-result-invalid')
162
192
  if ((action.type === 'comment-drafts.read' || action.type === 'component-drafts.read') && (result.type !== action.type || result.draft.id !== action.draft.id || result.draft.revision !== action.draft.revision || result.draft.token !== action.draft.token
163
193
  || action.type === 'component-drafts.read' && (result.type !== action.type || result.draft.blockId !== action.draft.blockId || result.draft.stepId !== action.draft.stepId)
164
194
  || result.offset !== action.offset || result.endOffset !== result.offset + result.jsonText.length || result.endOffset > result.totalUtf16
165
195
  || result.jsonText.length > (action.maxChars ?? 2048))) throw new RequestError(400, 'client-result-invalid')
166
- if ((action.type === 'comment-drafts.inspect' || action.type === 'component-drafts.inspect') && (result.type !== action.type || result.drafts.length > (action.limit ?? 10)
196
+ if ((action.type === 'comment-drafts.inspect' || action.type === 'component-drafts.inspect' || action.type === 'body-drafts.inspect' || action.type === 'production-drafts.inspect') && (result.type !== action.type || result.drafts.length > (action.limit ?? 10)
167
197
  || action.cursor && action.cursor.token !== result.token || result.next && result.next.token !== result.token)) throw new RequestError(400, 'client-result-invalid')
198
+ if (action.type === 'body-drafts.restore' || action.type === 'body-drafts.discard' || action.type === 'body-drafts.retry') {
199
+ if (result.type !== action.type || !('outcome' in result) || result.draft !== action.draft
200
+ || (action.type === 'body-drafts.restore' ? !['restored', 'already-saved'].includes(result.outcome)
201
+ : action.type === 'body-drafts.discard' ? !['source-restored', 'backup-discarded'].includes(result.outcome) : result.outcome !== 'saved')) throw new RequestError(400, 'client-result-invalid')
202
+ }
203
+ if (action.type === 'production-drafts.discard' && (result.type !== action.type || result.draft !== action.draft || !result.discarded)) throw new RequestError(400, 'client-result-invalid')
168
204
  const sameComment = (a: import('@lincyaw/kernel').ClientCommentDraftReference | null, b: import('@lincyaw/kernel').ClientCommentDraftReference | null) => a === null || b === null ? a === b
169
205
  : a.id === b.id && a.revision === b.revision && a.token === b.token
170
- if (action.type === 'comment-drafts.restore' && (result.type !== action.type || !sameComment(result.draft, action.draft) || result.composerId !== action.composerId
171
- || !sameComment(result.preservedCurrent, action.expectedCurrent) || result.restored.revision !== 1 || result.restored.id === action.draft.id || result.restored.id === action.expectedCurrent?.id)) throw new RequestError(400, 'client-result-invalid')
206
+ if (action.type === 'comment-drafts.restore' && (result.type !== action.type || !sameComment(result.draft, action.draft)
207
+ || action.composerId !== undefined && (result.composerId !== action.composerId || !sameComment(result.preservedCurrent, action.expectedCurrent ?? null))
208
+ || result.restored.revision !== 1 || result.restored.id === action.draft.id || result.restored.id === result.preservedCurrent?.id)) throw new RequestError(400, 'client-result-invalid')
172
209
  if (action.type === 'comment-drafts.discard' && (result.type !== action.type || !sameComment(result.draft, action.draft) || !result.discarded)) throw new RequestError(400, 'client-result-invalid')
173
210
  const sameDraft = (a: import('@lincyaw/kernel').ClientComponentDraftReference | null, b: import('@lincyaw/kernel').ClientComponentDraftReference | null) => a === null || b === null ? a === b
174
211
  : a.id === b.id && a.revision === b.revision && a.token === b.token && a.blockId === b.blockId && a.stepId === b.stepId
@@ -194,7 +231,23 @@ export function createAuthoringClients(editor: SourceEditor) {
194
231
  if (!validateAuthoringClientReport(value.report)) throw new RequestError(400, 'client-report-invalid')
195
232
  report(connection(ctx.document, value.connection, ctx.member), value.report, digest(value.report)); return jsonResponse({ accepted: true })
196
233
  }) })
197
- return { service, routes: {
234
+ return { service,
235
+ async flush(documents: string[], member: Member): Promise<void> {
236
+ const active = [...clients.values()].filter(client => client.member === member.id && client.value.connected && documents.includes(client.value.document))
237
+ await Promise.all(active.map(async client => {
238
+ const state = client.value
239
+ if (!state.snapshot.actions.includes('source.flush')) {
240
+ if (state.snapshot.editing.dirty || state.snapshot.editing.saving || state.snapshot.editing.composing || state.snapshot.editing.conflicted) throw new RequestError(409, 'agent-author-editing', { next: 'The author has unconfirmed input. Read the current author files and retry after that input is saved. Nothing was published.' })
241
+ return
242
+ }
243
+ const request: AuthoringClientRequest = { clientId: state.clientId, epoch: state.epoch, requestId: randomUUID(), source: state.snapshot.source,
244
+ expectedClientState: { connectionId: state.connectionId, revision: state.snapshot.revision }, action: { type: 'source.flush' } }
245
+ await service.request(state.document, request, member)
246
+ const pending = requests.get(requestKey(member.id, state.document, request))!
247
+ await pending.done
248
+ if (pending.value.state !== 'done') throw new RequestError(409, 'agent-author-editing', { next: 'The author client could not confirm its saved input. Read the current author files and retry. Nothing was published.' })
249
+ }))
250
+ }, routes: {
198
251
  'authoring-clients/register': post('register'), 'authoring-clients/report': post('report'), 'authoring-clients/ack': post('ack'),
199
252
  'authoring-clients/events': { role: 'editor', handle: (request, ctx) => catchRequestErrors(async () => {
200
253
  if (request.method !== 'GET') return problemResponse(405, 'GET')
@@ -202,5 +255,5 @@ export function createAuthoringClients(editor: SourceEditor) {
202
255
  if (!validateAuthoringClientLease(lease)) throw new RequestError(400, 'client-connection-invalid')
203
256
  return sseResponse(open(ctx.document, lease, ctx.member, request.signal), request.signal)
204
257
  }) } satisfies Route,
205
- }, async close() { closed = true; for (const client of clients.values()) client.close?.(); for (const pending of requests.values()) clearTimeout(pending.timer); requests.clear(); clients.clear() } }
258
+ }, async close() { closed = true; for (const client of clients.values()) client.close?.(); for (const pending of requests.values()) finish(pending, 'expired', 'client-owner-closed'); requests.clear(); clients.clear() } }
206
259
  }
@@ -0,0 +1,165 @@
1
+ import { randomBytes, randomUUID, createHash } from 'node:crypto'
2
+ import { AUTHORING_CLIENT_MAX_CLIENTS, AUTHORING_CLIENT_MAX_REQUESTS, AUTHORING_CLIENT_MAX_REQUEST_CHARS, AUTHORING_CLIENT_MAX_RESPONSE_CHARS, AUTHORING_CLIENT_REQUEST_TIMEOUT_MS, hasRole, isRecord, jsonResponse, problemResponse, pushStream, sseResponse } from '@lincyaw/kernel'
3
+ import type { AuthoringWindowAcknowledgement, AuthoringWindowDescriptor, AuthoringWindowEvent, AuthoringWindowLease, AuthoringWindowOpen, AuthoringWindowReference, AuthoringWindowReport, AuthoringWindowRequest, AuthoringWindowRequestResult, AuthoringWindows, Member, Route } from '@lincyaw/kernel'
4
+ import { validateAuthoringClientLease, validateAuthoringClientQuery, validateAuthoringClientRequestQuery, validateAuthoringWindowAcknowledgement, validateAuthoringWindowHandle, validateAuthoringWindowOpen, validateAuthoringWindowReport, validateAuthoringWindowRequest } from '@lincyaw/kernel/node'
5
+ import { catchRequestErrors, RequestError } from './errors.ts'
6
+
7
+ type Client = { member: string, credential: string, sequence: number, signature?: string, value: AuthoringWindowDescriptor, send?(event: AuthoringWindowEvent): void, close?(): void }
8
+ type Pending = { member: string, signature: string, request: AuthoringWindowRequest, value: AuthoringWindowRequestResult, timer?: ReturnType<typeof setTimeout> }
9
+ const terminal = (value: Pending) => !['sent', 'executing'].includes(value.value.state)
10
+ const size = (value: unknown) => JSON.stringify(value, null, 2).length
11
+ const digest = (value: unknown) => createHash('sha256').update(JSON.stringify(value, (_, item) => isRecord(item) ? Object.fromEntries(Object.entries(item).sort(([a], [b]) => a.localeCompare(b))) : item)).digest('hex')
12
+ const budget = (value: unknown, maximum = AUTHORING_CLIENT_MAX_REQUEST_CHARS) => { if (value === undefined || size(value) > maximum) throw new RequestError(413, 'window-request-too-large') }
13
+
14
+ /** Root window control has its own lifetime, not the currently attached document's authority. */
15
+ export function createAuthoringWindows(target: (document: string, member: Member) => string) {
16
+ const clients = new Map<string, Client>(), requests = new Map<string, Pending>()
17
+ let closed = false
18
+ const authorize = (member: Member) => { if (closed) throw new RequestError(503, 'window-owner-closed'); if (!hasRole(member, 'owner')) throw new RequestError(403, 'window-permission-denied') }
19
+ const clientKey = (member: string, clientId: string) => JSON.stringify([member, clientId])
20
+ const requestKey = (member: string, value: AuthoringWindowReference) => JSON.stringify([member, value.clientId, value.epoch, value.requestId])
21
+ const finish = (pending: Pending, state: AuthoringWindowRequestResult['state'], code?: string) => {
22
+ if (terminal(pending)) return
23
+ clearTimeout(pending.timer); pending.timer = undefined
24
+ pending.value = { ...pending.value, state, ...code ? { error: { code } } : {} }
25
+ if (state === 'expired') clients.get(clientKey(pending.member, pending.request.clientId))?.send?.({ type: 'cancel', requestId: pending.request.requestId, connectionId: pending.request.connectionId })
26
+ }
27
+ const disconnect = (client: Client, connectionId: string) => {
28
+ if (client.value.connectionId !== connectionId) return
29
+ client.value = { ...client.value, connected: false }; client.send = undefined; client.close = undefined
30
+ for (const pending of requests.values()) if (!terminal(pending) && pending.member === client.member && pending.request.clientId === client.value.clientId && pending.request.connectionId === connectionId) finish(pending, 'expired', 'window-disconnected')
31
+ }
32
+ const connection = (lease: AuthoringWindowLease, member: Member) => {
33
+ authorize(member)
34
+ const client = clients.get(clientKey(member.id, lease.clientId))
35
+ if (!client?.value.connected || client.value.epoch !== lease.epoch || client.value.connectionId !== lease.connectionId || client.credential !== lease.credential) throw new RequestError(409, 'window-connection-changed')
36
+ return client
37
+ }
38
+ const targetCurrent = (request: AuthoringWindowRequest, member: Member) => {
39
+ if (request.action.type === 'document.open') {
40
+ if (!request.target || request.target.document !== request.action.document || target(request.target.document, member) !== request.target.documentId) throw new RequestError(409, 'window-target-changed')
41
+ } else if (request.target) throw new RequestError(400, 'window-request-invalid')
42
+ }
43
+ const readResult = (pending: Pending, member: Member): AuthoringWindowRequestResult => {
44
+ const client = clients.get(clientKey(member.id, pending.request.clientId)), value = pending.value
45
+ let current = Boolean(client?.value.connected && client.value.epoch === value.epoch && client.value.connectionId === value.connectionId && value.snapshot && digest(client.value.snapshot) === digest(value.snapshot))
46
+ try { targetCurrent(pending.request, member) } catch { current = false }
47
+ return structuredClone({ ...value, current })
48
+ }
49
+ const report = (client: Client, value: AuthoringWindowReport) => {
50
+ const signature = digest(value)
51
+ if (value.sequence < client.sequence || value.sequence === client.sequence && signature !== client.signature || value.snapshot.revision < client.value.snapshot.revision) throw new RequestError(409, 'window-report-superseded')
52
+ if (value.sequence === client.sequence) return
53
+ client.sequence = value.sequence; client.signature = signature
54
+ client.value = { ...client.value, snapshot: structuredClone(value.snapshot), observedAt: new Date().toISOString() }
55
+ }
56
+ const retained = (reference: AuthoringWindowReference | string, member: Member) => {
57
+ authorize(member); budget(reference)
58
+ if (typeof reference === 'string') {
59
+ if (!validateAuthoringWindowHandle(reference)) throw new RequestError(400, 'window-query-invalid')
60
+ const matches = [...requests.values()].filter(value => value.member === member.id && value.request.requestId === reference)
61
+ if (matches.length > 1) throw new RequestError(409, 'window-query-ambiguous')
62
+ if (!matches[0]) throw new RequestError(404, 'window-request-not-found')
63
+ return matches[0]
64
+ }
65
+ if (!validateAuthoringClientRequestQuery(reference)) throw new RequestError(400, 'window-query-invalid')
66
+ const pending = requests.get(requestKey(member.id, reference))
67
+ if (!pending) throw new RequestError(404, 'window-request-not-found')
68
+ return pending
69
+ }
70
+ const service: AuthoringWindows = {
71
+ async list(query, member) {
72
+ authorize(member); budget(query)
73
+ if (!validateAuthoringClientQuery(query)) throw new RequestError(400, 'window-query-invalid')
74
+ const all = [...clients.values()].filter(client => client.member === member.id && (!query.clientId || client.value.clientId === query.clientId) && (!query.after || client.value.clientId > query.after)).sort((a, b) => a.value.clientId.localeCompare(b.value.clientId))
75
+ const answer = { scope: 'workspace' as const, clients: [] as AuthoringWindowDescriptor[] }
76
+ for (const client of all) {
77
+ const value = structuredClone(client.value), pending = [...requests.values()].find(request => request.member === member.id && request.request.clientId === value.clientId && !terminal(request))
78
+ if (pending) { value.pendingRequest = { requestId: pending.request.requestId, action: pending.request.action.type, ...pending.value.cancellationRequested ? { cancellationRequested: true } : {} }; value.snapshot.actions = [] }
79
+ if (size({ ...answer, clients: [...answer.clients, value], nextAfter: value.clientId }) > AUTHORING_CLIENT_MAX_RESPONSE_CHARS) break
80
+ answer.clients.push(value)
81
+ }
82
+ if (all.length && !answer.clients.length) throw new RequestError(413, 'window-state-too-large')
83
+ return { ...answer, ...answer.clients.length < all.length ? { nextAfter: answer.clients.at(-1)!.clientId } : {} }
84
+ },
85
+ async request(request, member) {
86
+ authorize(member); budget(request)
87
+ if (!validateAuthoringWindowRequest(request)) throw new RequestError(400, 'window-request-invalid')
88
+ const key = requestKey(member.id, request), signature = digest(request), known = requests.get(key)
89
+ if (known) { if (signature !== known.signature) throw new RequestError(409, 'window-request-id-reused'); return readResult(known, member) }
90
+ const client = clients.get(clientKey(member.id, request.clientId)), state = client?.value
91
+ if (!state?.connected || state.epoch !== request.epoch || state.connectionId !== request.connectionId) throw new RequestError(409, 'window-unavailable')
92
+ if (state.snapshot.revision !== request.revision) throw new RequestError(409, 'window-state-changed')
93
+ if (!state.snapshot.actions.includes(request.action.type)) throw new RequestError(409, 'window-action-unavailable')
94
+ if ([...requests.values()].some(value => value.member === member.id && value.request.clientId === request.clientId && !terminal(value))) throw new RequestError(409, 'window-busy')
95
+ targetCurrent(request, member)
96
+ while (requests.size >= AUTHORING_CLIENT_MAX_REQUESTS) { const old = [...requests].find(([, value]) => terminal(value)); if (!old) throw new RequestError(429, 'window-request-capacity'); requests.delete(old[0]) }
97
+ const now = Date.now(), value: AuthoringWindowRequestResult = { clientId: state.clientId, epoch: state.epoch, connectionId: state.connectionId, requestId: request.requestId, action: request.action.type,
98
+ state: 'sent', admittedAt: new Date(now).toISOString(), expiresAt: new Date(now + AUTHORING_CLIENT_REQUEST_TIMEOUT_MS).toISOString(), acknowledged: false, current: false }
99
+ const pending: Pending = { member: member.id, signature, request: structuredClone(request), value }
100
+ pending.timer = setTimeout(() => finish(pending, 'expired', 'window-request-timeout'), AUTHORING_CLIENT_REQUEST_TIMEOUT_MS)
101
+ requests.set(key, pending); client!.send?.({ type: 'request', request: pending.request, expiresAt: value.expiresAt })
102
+ return readResult(pending, member)
103
+ },
104
+ async get(reference, member) { return readResult(retained(reference, member), member) },
105
+ async cancel(reference, member) {
106
+ const pending = retained(reference, member)
107
+ if (!terminal(pending) && !pending.value.cancellationRequested) { pending.value.cancellationRequested = true; clients.get(clientKey(member.id, pending.request.clientId))?.send?.({ type: 'cancel', requestId: pending.request.requestId, connectionId: pending.value.connectionId }) }
108
+ return readResult(pending, member)
109
+ },
110
+ }
111
+ const register = (value: AuthoringWindowOpen, member: Member): AuthoringWindowLease => {
112
+ authorize(member)
113
+ const key = clientKey(member.id, value.clientId), old = clients.get(key)
114
+ if (!old && clients.size >= AUTHORING_CLIENT_MAX_CLIENTS) { const disposable = [...clients].find(([, client]) => !client.value.connected); if (!disposable) throw new RequestError(429, 'window-capacity'); clients.delete(disposable[0]) }
115
+ old?.close?.()
116
+ const credential = randomBytes(32).toString('base64url'), connectionId = randomUUID()
117
+ clients.set(key, { member: member.id, credential, sequence: -1, value: { clientId: value.clientId, epoch: value.epoch, connectionId, connected: false, snapshot: structuredClone(value.snapshot), observedAt: new Date().toISOString() } })
118
+ return { clientId: value.clientId, epoch: value.epoch, connectionId, credential }
119
+ }
120
+ const acknowledge = (lease: AuthoringWindowLease, value: AuthoringWindowAcknowledgement, member: Member) => {
121
+ const client = connection(lease, member), pending = requests.get(requestKey(member.id, { ...lease, requestId: value.requestId }))
122
+ if (pending && Date.now() >= Date.parse(pending.value.expiresAt)) finish(pending, 'expired', 'window-request-timeout')
123
+ if (!pending || terminal(pending) || pending.request.connectionId !== lease.connectionId) throw new RequestError(409, 'window-request-expired')
124
+ if (value.state === 'executing' && pending.value.cancellationRequested) throw new RequestError(409, 'window-request-cancelled')
125
+ if (value.state === 'executing' && pending.value.state !== 'sent' || value.state === 'done' && pending.value.state !== 'executing') throw new RequestError(409, 'window-ack-state-invalid')
126
+ if (value.state !== 'done' && value.outcome !== undefined || (value.state === 'done' || value.state === 'executing') && value.error) throw new RequestError(400, 'window-ack-invalid')
127
+ if (value.state === 'executing' && (value.snapshot.revision !== pending.request.revision || digest(value.snapshot) !== digest(client.value.snapshot))) throw new RequestError(409, 'window-state-changed')
128
+ if (value.state === 'executing' || value.state === 'done') targetCurrent(pending.request, member)
129
+ if (value.state === 'done') {
130
+ const action = pending.request.action, location = value.snapshot.location
131
+ if (value.snapshot.revision < pending.request.revision || action.type === 'window.read' && (value.outcome !== 'observed' || value.snapshot.revision !== pending.request.revision)
132
+ || action.type === 'document.open' && (!['opened', 'unchanged'].includes(value.outcome ?? '') || location.type !== 'document' || location.status !== 'ready' || location.document !== action.document || location.documentId !== pending.request.target?.documentId)
133
+ || action.type === 'document.close' && (!['closed', 'unchanged'].includes(value.outcome ?? '') || location.type !== 'home')) throw new RequestError(409, 'window-action-not-verified')
134
+ }
135
+ report(client, value)
136
+ pending.value = { ...pending.value, snapshot: structuredClone(value.snapshot), ...value.outcome ? { outcome: value.outcome } : {}, ...value.error ? { error: value.error } : {}, acknowledged: true }
137
+ if (value.state === 'executing') pending.value.state = 'executing'; else finish(pending, value.state)
138
+ return { accepted: true }
139
+ }
140
+ const post = (kind: 'register' | 'report' | 'ack'): Route => ({ role: 'owner', maxBody: 16384, handle: (request, ctx) => catchRequestErrors(async () => {
141
+ if (request.method !== 'POST') return problemResponse(405, 'POST')
142
+ const value: unknown = await request.json().catch(() => undefined); budget(value, AUTHORING_CLIENT_MAX_RESPONSE_CHARS)
143
+ if (kind === 'register') { if (!validateAuthoringWindowOpen(value)) throw new RequestError(400, 'window-open-invalid'); return jsonResponse(register(value, ctx.member)) }
144
+ if (!isRecord(value) || Object.keys(value).some(key => !['connection', 'report'].includes(key)) || !validateAuthoringClientLease(value.connection)) throw new RequestError(400, 'window-connection-invalid')
145
+ if (kind === 'ack') { if (!validateAuthoringWindowAcknowledgement(value.report)) throw new RequestError(400, 'window-ack-invalid'); return jsonResponse(acknowledge(value.connection, value.report, ctx.member)) }
146
+ if (!validateAuthoringWindowReport(value.report)) throw new RequestError(400, 'window-report-invalid')
147
+ report(connection(value.connection, ctx.member), value.report); return jsonResponse({ accepted: true })
148
+ }) })
149
+ return { service, routes: {
150
+ 'authoring-windows/register': post('register'), 'authoring-windows/report': post('report'), 'authoring-windows/ack': post('ack'),
151
+ 'authoring-windows/events': { role: 'owner', handle: (request, ctx) => catchRequestErrors(async () => {
152
+ authorize(ctx.member)
153
+ if (request.method !== 'GET') return problemResponse(405, 'GET')
154
+ const query = new URL(request.url).searchParams, lease = { clientId: query.get('clientId'), epoch: query.get('epoch'), connectionId: query.get('connectionId'), credential: request.headers.get('X-Presmium-Authoring-Client') }
155
+ if (!validateAuthoringClientLease(lease)) throw new RequestError(400, 'window-connection-invalid')
156
+ const client = clients.get(clientKey(ctx.member.id, lease.clientId))
157
+ if (!client || client.value.epoch !== lease.epoch || client.credential !== lease.credential) throw new RequestError(409, 'window-connection-changed')
158
+ client.close?.(); const connectionId = randomUUID()
159
+ client.value = { ...client.value, connected: true, connectionId }
160
+ const stream = pushStream<{ event: string, data: AuthoringWindowEvent }>(push => { client.send = data => push({ event: 'authoring-client', data }); return () => disconnect(client, connectionId) }, { signal: request.signal })
161
+ client.close = () => stream.end(); client.send?.({ type: 'connected', connectionId })
162
+ return sseResponse(stream, request.signal)
163
+ }) } satisfies Route,
164
+ }, async close() { closed = true; for (const client of clients.values()) client.close?.(); for (const pending of requests.values()) finish(pending, 'expired', 'window-owner-closed'); clients.clear(); requests.clear() } }
165
+ }
package/src/node/build.ts CHANGED
@@ -1,9 +1,10 @@
1
- import { cpSync, existsSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
1
+ import { cpSync, existsSync, readdirSync, rmSync } from 'node:fs'
2
2
  import { isAbsolute, join, resolve } from 'node:path'
3
- import { build, Compiler } from '@lincyaw/compiler'
3
+ import { build, Compiler, WORKSPACE_CONFIG } from '@lincyaw/compiler'
4
4
  import type { Compilation, RunStats } from '@lincyaw/compiler'
5
- import { errorMessage, isRecord } from '@lincyaw/kernel'
6
- import type { Finding } from '@lincyaw/kernel'
5
+ import { APP_DIR, errorMessage, isRecord, SLIDES_DIR } from '@lincyaw/kernel'
6
+ import type { Finding, IRDocument, SiteSpec } from '@lincyaw/kernel'
7
+ import { relativePath } from '../domain/paths.ts'
7
8
  import { listDocuments, readWorkspaceConfig } from './config.ts'
8
9
  import { siteContext, siteDocument, siteIR, siteSpec, siteTranslations, webRenderer } from './site.ts'
9
10
 
@@ -21,9 +22,11 @@ export async function buildWorkspace(root: string, options: { outDir?: string, b
21
22
  const site = siteSpec(config, [])
22
23
  const base = siteBase(config.site.base)
23
24
  const forms: { dir: string, compilation: Compilation, to: string[] }[] = []
25
+ const compilations: Compilation[] = []
24
26
  for (const document of found) {
25
27
  const compilation = await new Compiler(join(config.root, document.entry), { bundled: options.bundled, settings: config.settings }).compile({ pruneCache: true })
26
- const to = presentations(compilation, `${base}${urlPath(document.dir)}/`, siteLook(config.site, config.root))
28
+ compilations.push(compilation)
29
+ const to = presentations(compilation, base, `${base}${urlPath(document.dir)}/`, siteLook(config.site, config.root, document.dir))
27
30
  if (to.length > 0) forms.push({ dir: document.dir, compilation, to })
28
31
  const translated = await siteTranslations(compilation)
29
32
  findings.push(...compilation.doc.diagnostics, ...translated.findings)
@@ -33,6 +36,7 @@ export async function buildWorkspace(root: string, options: { outDir?: string, b
33
36
  const outDir = join(resolve(options.outDir ?? join(config.root, 'dist')), 'web')
34
37
  const renderer = await webRenderer(config.root, options.bundled)
35
38
  const ctx = siteContext({ root: config.root, outDir, workDir: join(config.root, '.presmium', 'site'), base, findings })
39
+ ctx.pluginDirs = pluginsByName(site, compilations)
36
40
  try {
37
41
  await renderer.buildSite!(site, ctx)
38
42
  } catch (error) {
@@ -47,7 +51,7 @@ export async function buildWorkspace(root: string, options: { outDir?: string, b
47
51
  const report = await build(compilation, { outDir: work, to })
48
52
  findings.push(...report.findings)
49
53
  for (const form of to) if (existsSync(join(work, form))) cpSync(join(work, form), join(outDir, dir, form), { recursive: true })
50
- if (to.includes('slides')) shareSlidesApp(join(outDir, dir, 'slides'), `${base}${urlPath(dir)}/slides/`, outDir, base)
54
+ if (to.includes('slides')) moveApps(join(outDir, dir, SLIDES_DIR), outDir)
51
55
  } catch (error) {
52
56
  findings.push({ checkId: 'presmium.render', severity: 'error', message: `document ${dir}: its ${to.join(' and ')} failed: ${errorMessage(error)}` })
53
57
  }
@@ -55,41 +59,67 @@ export async function buildWorkspace(root: string, options: { outDir?: string, b
55
59
  return { outDir, documents, findings }
56
60
  }
57
61
 
62
+ /**
63
+ * The site's documents name their plugins by package, as a presentation built alone does, so the pages and the
64
+ * presentations share one viewer app (its key follows the plugin names); the site resolves each name to the directory
65
+ * it was loaded from. A name that two documents load from different directories stays a directory, to tell them apart.
66
+ */
67
+ function pluginsByName(site: SiteSpec, compilations: readonly Compilation[]): Record<string, string> {
68
+ const dirs = new Map<string, Set<string>>(), names = new Map<string, string>()
69
+ for (const { plugins } of compilations) for (const { name, dir } of plugins) {
70
+ let own = dirs.get(name)
71
+ if (!own) dirs.set(name, own = new Set())
72
+ own.add(dir)
73
+ names.set(dir, name)
74
+ }
75
+ const unique = new Map([...dirs].filter(([, own]) => own.size === 1).map(([name, own]) => [name, [...own][0]!]))
76
+ const byName = (doc: IRDocument): IRDocument => ({ ...doc, config: { ...doc.config, plugins: doc.config.plugins.map(dir => names.has(dir) && unique.has(names.get(dir)!) ? names.get(dir)! : dir) } })
77
+ for (const entry of site.documents) {
78
+ if (entry.doc) entry.doc = byName(entry.doc)
79
+ for (const translation of entry.translations ?? []) translation.doc = byName(translation.doc)
80
+ }
81
+ return Object.fromEntries(unique)
82
+ }
83
+
58
84
  const PRESENTATIONS = ['slides', 'lecture']
59
85
 
60
- /** The site's theme and its parameters, for its presentations to look like its pages; a theme directory made absolute. */
61
- function siteLook(site: Record<string, unknown>, root: string): Record<string, unknown> {
86
+ /**
87
+ * The site's theme and its parameters, for the presentations of the document in `dir` to look like its pages: a theme
88
+ * directory made absolute, and the parameters with the file they are written in (`siteFile`, relative to the document),
89
+ * for their paths (`logo`) to resolve against it.
90
+ */
91
+ function siteLook(site: Record<string, unknown>, root: string, dir: string): Record<string, unknown> {
62
92
  const theme = typeof site.theme === 'string' && (site.theme.startsWith('.') || isAbsolute(site.theme)) ? resolve(root, site.theme) : site.theme
63
- return { ...theme !== undefined ? { theme } : {}, ...isRecord(site.params) ? { params: site.params } : {} }
93
+ return { ...theme !== undefined ? { theme } : {}, ...isRecord(site.params) ? { params: site.params, siteFile: relativePath(dir, WORKSPACE_CONFIG) } : {} }
64
94
  }
65
95
 
66
96
  const urlPath = (dir: string) => dir.split('/').map(encodeURIComponent).join('/')
67
97
 
68
- /**
69
- * Every document's slides run the same viewer app: it moves to the site's `_app/<key>/`, beside the web pages' own,
70
- * so a reader downloads it once for all the presentations of the site, and the slides' page points there.
71
- */
72
- function shareSlidesApp(slides: string, slidesBase: string, outDir: string, base: string): void {
73
- const app = join(slides, '_app')
74
- if (!existsSync(app)) return
75
- for (const key of readdirSync(app)) if (!existsSync(join(outDir, '_app', key))) cpSync(join(app, key), join(outDir, '_app', key), { recursive: true })
76
- rmSync(app, { recursive: true, force: true })
77
- const page = join(slides, 'index.html')
78
- writeFileSync(page, readFileSync(page, 'utf8').replaceAll(`${slidesBase}_app/`, `${base}_app/`))
98
+ /** The presentation's viewer app goes where its page names it (`appBase`): with the site's own, downloaded once for all. */
99
+ function moveApps(presentation: string, outDir: string): void {
100
+ const apps = join(presentation, APP_DIR)
101
+ if (!existsSync(apps)) return
102
+ for (const key of readdirSync(apps)) if (!existsSync(join(outDir, APP_DIR, key))) cpSync(join(apps, key), join(outDir, APP_DIR, key), { recursive: true })
103
+ rmSync(apps, { recursive: true, force: true })
79
104
  }
80
105
 
81
106
  /**
82
107
  * The presentation forms a document asks for (`metadata.renderers.slides` or `lecture`), set to be served below its
83
- * pages at `prefix`: the slides at `slides/`, and the web pages and the slides linked to each other.
108
+ * pages at `prefix`, with its viewer app below the site's `base`: the slides at `slides/`, and the web pages and the slides linked to each other.
84
109
  */
85
- function presentations(compilation: Compilation, prefix: string, look: Record<string, unknown>): string[] {
110
+ function presentations(compilation: Compilation, base: string, prefix: string, look: Record<string, unknown>): string[] {
86
111
  const { renderers } = compilation.doc.config
87
112
  const to = PRESENTATIONS.filter(form => renderers[form] !== undefined)
88
113
  if (to.length === 0) return to
89
- if (to.includes('slides')) renderers.slides = { ...look, ...isRecord(renderers.slides) ? renderers.slides : {}, base: `${prefix}slides/` }
114
+ if (to.includes('slides')) {
115
+ const own = isRecord(renderers.slides) ? renderers.slides : {}
116
+ // Parameters the document sets for its slides are written in its lecture.json, not in the workspace's file.
117
+ const { siteFile, ...shared } = look
118
+ renderers.slides = { ...shared, ...own.params === undefined && siteFile !== undefined ? { siteFile } : {}, ...own, base: `${prefix}${SLIDES_DIR}/`, appBase: base }
119
+ }
90
120
  const settings = compilation.doc.config.presmium ??= {}
91
121
  const web = isRecord(settings['presmium.web']) ? settings['presmium.web'] : {}
92
- settings['presmium.web'] = { ...web, webUrl: prefix, ...to.includes('slides') ? { slidesUrl: `${prefix}slides/` } : {} }
122
+ settings['presmium.web'] = { ...web, webUrl: prefix, ...to.includes('slides') ? { slidesUrl: `${prefix}${SLIDES_DIR}/` } : {} }
93
123
  // The slides find the lecture where it is built, without probing `slides/lecture/` first.
94
124
  if (to.includes('lecture')) {
95
125
  const lecture = isRecord(settings['presmium.lecture']) ? settings['presmium.lecture'] : {}