@crombolo/server 0.69.1 → 0.70.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +15 -14
- package/src/adapters/blueprints.ts +51 -5
- package/src/adapters/change-recording.ts +140 -0
- package/src/adapters/content.ts +132 -21
- package/src/adapters/documents.ts +26 -5
- package/src/adapters/elements.ts +3 -0
- package/src/adapters/media.ts +7 -1
- package/src/adapters/schema-files.ts +89 -1
- package/src/adapters/workspace-dictionary.ts +287 -0
- package/src/adapters/workspace-file-port.ts +160 -0
- package/src/adapters/workspace-languages.ts +94 -0
- package/src/approvals-api.ts +16 -7
- package/src/bundle-api.ts +19 -16
- package/src/bundle-install.ts +4 -0
- package/src/change-transfer.ts +676 -0
- package/src/changes-api.ts +258 -0
- package/src/component-templates-api.ts +2 -2
- package/src/config.ts +161 -21
- package/src/content-events.ts +65 -1
- package/src/content-operations.ts +22 -3
- package/src/core.ts +2 -0
- package/src/environment-values-api.ts +161 -0
- package/src/node-operations.ts +150 -2
- package/src/ports.ts +174 -52
- package/src/remote-changes.ts +279 -0
- package/src/remote-schema.ts +126 -0
- package/src/remote-workspaces.ts +82 -0
- package/src/remote.ts +289 -192
- package/src/schema-transfer.ts +240 -41
- package/src/schema.ts +7 -2
- package/src/seed/compile.ts +13 -1
- package/src/seed/values.ts +3 -0
- package/src/server.ts +948 -364
- package/src/settings.ts +123 -5
- package/src/site-sections.ts +1 -1
- package/src/workspace-access.ts +152 -0
- package/src/workspace-checks.ts +299 -0
- package/src/workspace-losses.ts +95 -0
- package/src/workspace-processes.ts +306 -0
- package/src/workspace-render-child.ts +168 -0
- package/src/workspace-schema-dir.ts +100 -0
- package/src/workspace-schema.ts +598 -0
- package/src/workspace-sites.ts +179 -0
- package/src/workspace-views.ts +121 -0
- package/src/workspaces.ts +1031 -0
|
@@ -0,0 +1,1031 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Workspaces in the server (story 375). A Management API request names its
|
|
3
|
+
* workspace with the `Crombolo-Workspace` header; the router asks `scope` once
|
|
4
|
+
* the request is authorised, and the handler runs with the workspace held for
|
|
5
|
+
* it. Only the document port and operations read what is held, and pass it on
|
|
6
|
+
* to the repository explicitly: nothing below them reads it. Opening, listing,
|
|
7
|
+
* sharing and discarding are crombolo's own routes, at `<plugin>/api/workspaces`,
|
|
8
|
+
* as is merging one into Shared (story 380).
|
|
9
|
+
*/
|
|
10
|
+
import { AsyncLocalStorage } from 'node:async_hooks'
|
|
11
|
+
import {
|
|
12
|
+
hasCultureAccess,
|
|
13
|
+
hasSection,
|
|
14
|
+
mayDocumentAt,
|
|
15
|
+
type Principal,
|
|
16
|
+
WORKSPACE_OPERATIONS,
|
|
17
|
+
WORKSPACE_REFUSALS,
|
|
18
|
+
} from '@crombolo/api-management/domain'
|
|
19
|
+
import { fieldWords, type MergePlan } from '@crombolo/content'
|
|
20
|
+
import {
|
|
21
|
+
DocumentPermissions as D,
|
|
22
|
+
normaliseUuid,
|
|
23
|
+
problemDetails,
|
|
24
|
+
problemResponse,
|
|
25
|
+
WorkspacePermissions,
|
|
26
|
+
} from '@crombolo/core'
|
|
27
|
+
import {
|
|
28
|
+
type Db,
|
|
29
|
+
DocumentRepository,
|
|
30
|
+
type NodeSchemaState,
|
|
31
|
+
UserRepository,
|
|
32
|
+
type Workspace,
|
|
33
|
+
WorkspaceFileRepository,
|
|
34
|
+
WorkspaceRefusedError,
|
|
35
|
+
WorkspaceRepository,
|
|
36
|
+
} from '@crombolo/data'
|
|
37
|
+
import { recordAudit } from './adapters/audit.ts'
|
|
38
|
+
import type { WorkspaceMerging } from './node-operations.ts'
|
|
39
|
+
import type { WorkspaceChecks } from './workspace-checks.ts'
|
|
40
|
+
import type { WorkspaceSchema } from './workspace-schema.ts'
|
|
41
|
+
|
|
42
|
+
export const WORKSPACE_HEADER = 'crombolo-workspace'
|
|
43
|
+
|
|
44
|
+
const held = new AsyncLocalStorage<Workspace>()
|
|
45
|
+
|
|
46
|
+
/** The workspace the request being answered works in; undefined for Shared. */
|
|
47
|
+
export const currentWorkspace = (): Workspace | undefined => held.getStore()
|
|
48
|
+
|
|
49
|
+
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
|
|
50
|
+
|
|
51
|
+
/** Whether someone may work in a workspace: its owner or one of its members. */
|
|
52
|
+
export const mayUse = (workspace: Workspace, principal: Principal): boolean => {
|
|
53
|
+
const me = normaliseUuid(principal.id)
|
|
54
|
+
return workspace.ownerKey === me || workspace.memberKeys.includes(me)
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const problem = (status: number, title: string, detail?: string) =>
|
|
58
|
+
problemResponse(problemDetails({ title, status, ...(detail ? { detail } : {}) }))
|
|
59
|
+
|
|
60
|
+
/** The header's word for a person's own unnamed workspace (story 380). */
|
|
61
|
+
export const OWN_WORKSPACE = 'mine'
|
|
62
|
+
|
|
63
|
+
const PUBLISHES = new Set(['PutDocumentByIdPublish', 'PutDocumentByIdUpdateAndPublish'])
|
|
64
|
+
const PAGE_IN_PATH = /\/document\/([0-9a-f-]{36})\//i
|
|
65
|
+
|
|
66
|
+
/** The settings a scope reads, each request. */
|
|
67
|
+
export interface WorkspaceScopeOptions {
|
|
68
|
+
enabled: () => boolean
|
|
69
|
+
/** Shared takes no direct edit of a page; a person edits in a workspace (story 380). */
|
|
70
|
+
required?: () => boolean
|
|
71
|
+
/** Story 388: the site takes its content only by a change. */
|
|
72
|
+
locked?: () => boolean
|
|
73
|
+
/** The merge a publish in a person's own workspace makes, of that page alone. */
|
|
74
|
+
merge?: () => WorkspaceMerging
|
|
75
|
+
/** The workspace's copy of the schema files, taken as it opens (story 376). */
|
|
76
|
+
schema?: () => WorkspaceSchema | undefined
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* The router's scope for a request: undefined without the header, or for an
|
|
81
|
+
* operation the workspace does not change; a refusal where workspaces are off,
|
|
82
|
+
* the workspace is not the caller's, or it cannot hold what the operation does.
|
|
83
|
+
* `mine` names the caller's own workspace, opened at their first change; where a
|
|
84
|
+
* workspace is required, a page changed with none named is refused.
|
|
85
|
+
*/
|
|
86
|
+
export function createWorkspaceScope(db: Db, settings: WorkspaceScopeOptions | (() => boolean)) {
|
|
87
|
+
const options: WorkspaceScopeOptions =
|
|
88
|
+
typeof settings === 'function' ? { enabled: settings } : settings
|
|
89
|
+
const workspaces = new WorkspaceRepository(db)
|
|
90
|
+
return async (
|
|
91
|
+
request: Request,
|
|
92
|
+
principal: Principal | undefined,
|
|
93
|
+
operation: { operationId: string },
|
|
94
|
+
) => {
|
|
95
|
+
const key = request.headers.get(WORKSPACE_HEADER)?.trim()
|
|
96
|
+
const pages = WORKSPACE_OPERATIONS.has(operation.operationId)
|
|
97
|
+
if (options.locked?.() && pages && request.method !== 'GET')
|
|
98
|
+
return problem(409, CONTENT_LOCKED.title, CONTENT_LOCKED.detail)
|
|
99
|
+
if (!key) {
|
|
100
|
+
if (options.enabled() && options.required?.() && pages && request.method !== 'GET')
|
|
101
|
+
return problem(
|
|
102
|
+
409,
|
|
103
|
+
'This site takes changes in a workspace',
|
|
104
|
+
`Name one with the ${WORKSPACE_HEADER} header, or "${OWN_WORKSPACE}" for your own.`,
|
|
105
|
+
)
|
|
106
|
+
return undefined
|
|
107
|
+
}
|
|
108
|
+
if (!options.enabled())
|
|
109
|
+
return problem(400, 'Workspaces are not turned on for this site.', 'Leave out the workspace.')
|
|
110
|
+
const refusal = WORKSPACE_REFUSALS.get(operation.operationId)
|
|
111
|
+
if (!pages && !refusal) return undefined
|
|
112
|
+
const own = key.toLowerCase() === OWN_WORKSPACE
|
|
113
|
+
// A person's own workspace holds their pages; what it cannot hold yet goes to Shared.
|
|
114
|
+
if (own && (refusal || !principal)) return undefined
|
|
115
|
+
let found: Workspace | undefined
|
|
116
|
+
if (own && principal) {
|
|
117
|
+
found = await workspaces.ownOf(principal.id)
|
|
118
|
+
if (!found && request.method === 'GET') return undefined
|
|
119
|
+
if (!found) {
|
|
120
|
+
found = await workspaces.open({
|
|
121
|
+
name: `Changes by ${principal.name}`,
|
|
122
|
+
ownerKey: principal.id,
|
|
123
|
+
personal: true,
|
|
124
|
+
})
|
|
125
|
+
await options.schema?.()?.snapshot(found.id)
|
|
126
|
+
}
|
|
127
|
+
} else found = principal && UUID.test(key) ? await workspaces.byKey(key) : undefined
|
|
128
|
+
// Someone else's workspace answers as one that is not there, so none is revealed.
|
|
129
|
+
if (!found || !principal || !mayUse(found, principal))
|
|
130
|
+
return problem(404, 'There is no such workspace.')
|
|
131
|
+
if (found.state === 'merged')
|
|
132
|
+
return problem(409, 'This workspace was merged', 'Open another to go on working.')
|
|
133
|
+
if (refusal) return problem(409, 'Not in a workspace', refusal)
|
|
134
|
+
// Story 383: a staged change is looked at and applied, never edited where it is staged.
|
|
135
|
+
if (found.stagedReadOnly && request.method !== 'GET')
|
|
136
|
+
return problem(
|
|
137
|
+
409,
|
|
138
|
+
'This workspace holds a staged change',
|
|
139
|
+
'A staged change is not edited here: change it where it was made and stage it again.',
|
|
140
|
+
)
|
|
141
|
+
const workspace = found
|
|
142
|
+
const page = PUBLISHES.has(operation.operationId)
|
|
143
|
+
? new URL(request.url).pathname.match(PAGE_IN_PATH)?.[1]
|
|
144
|
+
: undefined
|
|
145
|
+
return {
|
|
146
|
+
run: async <T>(fn: () => Promise<T>): Promise<T> => {
|
|
147
|
+
const answered = await held.run(workspace, fn)
|
|
148
|
+
const merging = options.merge?.()
|
|
149
|
+
if (!workspace.personal || !page || !merging || !(answered instanceof Response))
|
|
150
|
+
return answered
|
|
151
|
+
if (answered.status < 200 || answered.status >= 300) return answered
|
|
152
|
+
return (await publishOwnPage(db, merging, workspace, principal, page)) ?? answered
|
|
153
|
+
},
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* A publish in a person's own workspace is the merge of that page alone, at once
|
|
160
|
+
* (story 380). Where it cannot go, the page stays published there, and why is said.
|
|
161
|
+
*/
|
|
162
|
+
async function publishOwnPage<T>(
|
|
163
|
+
db: Db,
|
|
164
|
+
merging: WorkspaceMerging,
|
|
165
|
+
workspace: Workspace,
|
|
166
|
+
principal: Principal,
|
|
167
|
+
page: string,
|
|
168
|
+
): Promise<T | undefined> {
|
|
169
|
+
const plan = await merging.preview(workspace)
|
|
170
|
+
const one: MergePlan = {
|
|
171
|
+
pages: plan.pages.filter((p) => p.page.key === normaliseUuid(page)),
|
|
172
|
+
pending: [],
|
|
173
|
+
conflicts: plan.conflicts.filter((c) => c.key === normaliseUuid(page)),
|
|
174
|
+
findings: plan.findings.filter((f) => f.key === normaliseUuid(page)),
|
|
175
|
+
}
|
|
176
|
+
const refusals = await mergeRefusals(db, principal, one)
|
|
177
|
+
const outcome =
|
|
178
|
+
refusals.length > 0
|
|
179
|
+
? undefined
|
|
180
|
+
: await merging.run(workspace, principal, {
|
|
181
|
+
only: normaliseUuid(page),
|
|
182
|
+
...(await userIdOf(db, principal)),
|
|
183
|
+
})
|
|
184
|
+
if (outcome?.ok) return undefined
|
|
185
|
+
return problem(
|
|
186
|
+
409,
|
|
187
|
+
'Published in your own changes, not yet for everyone',
|
|
188
|
+
[...refusals, ...(outcome?.blockers ?? [])].join(' '),
|
|
189
|
+
) as T
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
const userIdOf = async (db: Db, principal: Principal): Promise<{ userId?: number }> => {
|
|
193
|
+
const user = await db.q
|
|
194
|
+
.selectFrom('user_account')
|
|
195
|
+
.select('id')
|
|
196
|
+
.where('key', '=', normaliseUuid(principal.id))
|
|
197
|
+
.execute()
|
|
198
|
+
return user[0] ? { userId: Number(user[0].id) } : {}
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/**
|
|
202
|
+
* An object whose every call goes to the workspace's own when the request
|
|
203
|
+
* holds one: the document port and operations, so a handler written for Shared
|
|
204
|
+
* works in a workspace unchanged.
|
|
205
|
+
*/
|
|
206
|
+
export function inWorkspaces<T extends object>(shared: T, make: (workspace: Workspace) => T): T {
|
|
207
|
+
return new Proxy(shared, {
|
|
208
|
+
get(target, prop, receiver) {
|
|
209
|
+
const workspace = currentWorkspace()
|
|
210
|
+
const actual = workspace ? make(workspace) : target
|
|
211
|
+
const value = Reflect.get(actual, prop, workspace ? actual : receiver)
|
|
212
|
+
return typeof value === 'function' ? value.bind(actual) : value
|
|
213
|
+
},
|
|
214
|
+
})
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/** A workspace as its routes answer it. */
|
|
218
|
+
export interface WorkspaceView {
|
|
219
|
+
key: string
|
|
220
|
+
name: string
|
|
221
|
+
visibility: 'members' | 'editors'
|
|
222
|
+
tellOthers: boolean
|
|
223
|
+
/** Whether the person asking is in it, and may change it. */
|
|
224
|
+
member: boolean
|
|
225
|
+
ownerKey: string
|
|
226
|
+
memberKeys: string[]
|
|
227
|
+
mine: boolean
|
|
228
|
+
state: 'open' | 'merged'
|
|
229
|
+
mergedAt: string | null
|
|
230
|
+
createdAt: string
|
|
231
|
+
updatedAt: string
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/** What a request asks of a workspace's privacy (story 384). */
|
|
235
|
+
function privacyOf(asked: Record<string, unknown>): {
|
|
236
|
+
visibility?: 'members' | 'editors'
|
|
237
|
+
tellOthers?: boolean
|
|
238
|
+
} {
|
|
239
|
+
return {
|
|
240
|
+
...(asked.visibility === 'members' || asked.visibility === 'editors'
|
|
241
|
+
? { visibility: asked.visibility }
|
|
242
|
+
: {}),
|
|
243
|
+
...(typeof asked.tellOthers === 'boolean' ? { tellOthers: asked.tellOthers } : {}),
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
const viewOf = (workspace: Workspace, principal: Principal): WorkspaceView => ({
|
|
248
|
+
key: workspace.key,
|
|
249
|
+
visibility: workspace.visibility,
|
|
250
|
+
tellOthers: workspace.tellOthers,
|
|
251
|
+
member: mayUse(workspace, principal),
|
|
252
|
+
name: workspace.name,
|
|
253
|
+
ownerKey: workspace.ownerKey,
|
|
254
|
+
memberKeys: workspace.memberKeys,
|
|
255
|
+
mine: workspace.ownerKey === normaliseUuid(principal.id),
|
|
256
|
+
state: workspace.state,
|
|
257
|
+
mergedAt: workspace.mergedAt?.toISOString() ?? null,
|
|
258
|
+
createdAt: workspace.createdAt.toISOString(),
|
|
259
|
+
updatedAt: workspace.updatedAt.toISOString(),
|
|
260
|
+
})
|
|
261
|
+
|
|
262
|
+
type Client = { ipAddress: string | null; forwardedFor: string | null }
|
|
263
|
+
|
|
264
|
+
const json = (body: unknown, status = 200) => Response.json(body, { status })
|
|
265
|
+
const refused = (message: string, status: number) => json({ message }, status)
|
|
266
|
+
|
|
267
|
+
/** What a locked site says of a write it refuses (story 388), in the API and the back office. */
|
|
268
|
+
export const CONTENT_LOCKED = {
|
|
269
|
+
title: 'This site takes its content by change',
|
|
270
|
+
detail:
|
|
271
|
+
'Its pages, media, types and code are changed where they are made, and arrive here when that change is applied.',
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
/** One open workspace as an administrator sees it among them all (story 383). */
|
|
275
|
+
export interface PendingWorkspace {
|
|
276
|
+
key: string
|
|
277
|
+
name: string
|
|
278
|
+
ownerKey: string
|
|
279
|
+
ownerName: string | null
|
|
280
|
+
createdAt: string
|
|
281
|
+
/** When anything was last written in it. */
|
|
282
|
+
lastActivity: string
|
|
283
|
+
ageDays: number
|
|
284
|
+
/** The changes from another site it holds, if it was staged with them. */
|
|
285
|
+
staged: Array<{ key: string; name: string | null }> | null
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/** Every workspace still open, the least recently touched first. */
|
|
289
|
+
async function pendingWorkspaces(db: Db): Promise<PendingWorkspace[]> {
|
|
290
|
+
const open = (await new WorkspaceRepository(db).all()).filter((w) => w.state === 'open')
|
|
291
|
+
if (open.length === 0) return []
|
|
292
|
+
const latest = await db.q
|
|
293
|
+
.selectFrom('content_version')
|
|
294
|
+
.select(['workspace_id', (eb) => eb.fn.max('version_date').as('at')])
|
|
295
|
+
.where(
|
|
296
|
+
'workspace_id',
|
|
297
|
+
'in',
|
|
298
|
+
open.map((w) => w.id),
|
|
299
|
+
)
|
|
300
|
+
.groupBy('workspace_id')
|
|
301
|
+
.execute()
|
|
302
|
+
const owners = await new UserRepository(db).byKeys([...new Set(open.map((w) => w.ownerKey))])
|
|
303
|
+
const now = Date.now()
|
|
304
|
+
return open
|
|
305
|
+
.map((w) => {
|
|
306
|
+
const written = latest.find((r) => Number(r.workspace_id) === w.id)?.at
|
|
307
|
+
const at = Math.max(w.updatedAt.getTime(), written ? new Date(String(written)).getTime() : 0)
|
|
308
|
+
return {
|
|
309
|
+
key: w.key,
|
|
310
|
+
name: w.name,
|
|
311
|
+
ownerKey: w.ownerKey,
|
|
312
|
+
ownerName: owners.find((u) => normaliseUuid(u.key) === w.ownerKey)?.name ?? null,
|
|
313
|
+
createdAt: w.createdAt.toISOString(),
|
|
314
|
+
lastActivity: new Date(at).toISOString(),
|
|
315
|
+
ageDays: Math.floor((now - w.createdAt.getTime()) / 86_400_000),
|
|
316
|
+
staged: w.stagedChanges,
|
|
317
|
+
}
|
|
318
|
+
})
|
|
319
|
+
.sort((a, b) => a.lastActivity.localeCompare(b.lastActivity))
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
/** The media files a workspace's own values name (story 390). */
|
|
323
|
+
async function filesNamedBy(db: Db, workspaceId: number): Promise<string[]> {
|
|
324
|
+
const rows = await db.q
|
|
325
|
+
.selectFrom('property_value')
|
|
326
|
+
.select(['varchar_value', 'text_value'])
|
|
327
|
+
.where('workspace_id', '=', workspaceId)
|
|
328
|
+
.execute()
|
|
329
|
+
const found = new Set<string>()
|
|
330
|
+
for (const row of rows)
|
|
331
|
+
for (const text of [row.varchar_value, row.text_value])
|
|
332
|
+
for (const match of String(text ?? '').matchAll(/\/media\/[^"'\s?#]+/g)) found.add(match[0])
|
|
333
|
+
return [...found]
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
/** Whether someone may merge workspaces at all: the permission of its own, which an administrator holds. */
|
|
337
|
+
export const mayMerge = (principal: Principal): boolean =>
|
|
338
|
+
principal.isAdmin || principal.permissions.includes(WorkspacePermissions.Merge)
|
|
339
|
+
|
|
340
|
+
/** A page's place as permissions read it: its ancestors' keys, then its own. */
|
|
341
|
+
async function chainOf(db: Db, nodeId: number): Promise<string[]> {
|
|
342
|
+
const node = await db.q.selectFrom('node').select('path').where('id', '=', nodeId).execute()
|
|
343
|
+
const ids = String(node[0]?.path ?? '')
|
|
344
|
+
.split(',')
|
|
345
|
+
.map(Number)
|
|
346
|
+
.filter((id) => id > 0)
|
|
347
|
+
if (ids.length === 0) return []
|
|
348
|
+
const keys = new Map(
|
|
349
|
+
(
|
|
350
|
+
await db.q.selectFrom('node').select(['id', 'unique_id']).where('id', 'in', ids).execute()
|
|
351
|
+
).map((row) => [Number(row.id), normaliseUuid(String(row.unique_id))]),
|
|
352
|
+
)
|
|
353
|
+
return ids.flatMap((id) => (keys.has(id) ? [keys.get(id) as string] : []))
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
/**
|
|
357
|
+
* What a merge would do that the person could not do directly (story 380): each
|
|
358
|
+
* change needs its own verbs, languages and start nodes at its place.
|
|
359
|
+
*/
|
|
360
|
+
export async function mergeRefusals(
|
|
361
|
+
db: Db,
|
|
362
|
+
principal: Principal,
|
|
363
|
+
plan: MergePlan,
|
|
364
|
+
): Promise<string[]> {
|
|
365
|
+
const out: string[] = []
|
|
366
|
+
for (const { page, name, take, publish, unpublish } of plan.pages) {
|
|
367
|
+
const verbs: string[] = []
|
|
368
|
+
if (page.made || take.length > 0) verbs.push(page.made ? D.Create : D.Update)
|
|
369
|
+
if (publish) verbs.push(D.Publish)
|
|
370
|
+
if (unpublish) verbs.push(D.Unpublish)
|
|
371
|
+
if (verbs.length > 0 && !mayDocumentAt(principal, await chainOf(db, page.nodeId), verbs))
|
|
372
|
+
out.push(`You may not make these changes to "${name}".`)
|
|
373
|
+
const cultures = new Set<string>([
|
|
374
|
+
...take.flatMap((f) => (f.value?.culture ? [f.value.culture] : [])),
|
|
375
|
+
...take.flatMap((f) => (f.field.startsWith('@name:') ? [f.field.slice(6)] : [])),
|
|
376
|
+
...(publish?.cultures ?? []),
|
|
377
|
+
...(unpublish?.cultures ?? []),
|
|
378
|
+
])
|
|
379
|
+
if (!hasCultureAccess(principal, [...cultures]))
|
|
380
|
+
out.push(`"${name}" changes a language you do not work in.`)
|
|
381
|
+
}
|
|
382
|
+
const VERB = { move: D.Move, sort: D.Sort, trash: D.Delete, delete: D.Delete } as const
|
|
383
|
+
for (const { pending } of plan.pending) {
|
|
384
|
+
if (pending.kind === 'gone' || pending.kind === 'orphaned' || pending.key === null) continue
|
|
385
|
+
const verbs = [VERB[pending.kind]]
|
|
386
|
+
const chain = await chainOf(db, pending.nodeId)
|
|
387
|
+
let allowed = mayDocumentAt(principal, chain, verbs)
|
|
388
|
+
if (allowed && pending.kind === 'move' && pending.targetParentId !== null)
|
|
389
|
+
allowed = mayDocumentAt(principal, await chainOf(db, pending.targetParentId), [D.Create])
|
|
390
|
+
if (!allowed)
|
|
391
|
+
out.push(
|
|
392
|
+
`You may not ${pending.kind === 'sort' ? 'reorder' : pending.kind} "${pending.name}".`,
|
|
393
|
+
)
|
|
394
|
+
}
|
|
395
|
+
return out
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
/**
|
|
399
|
+
* What a workspace's files ask of the person merging them (stories 376, 377):
|
|
400
|
+
* Structure for definitions, Code for templates, stylesheets and scripts, and an
|
|
401
|
+
* administrator for the files the site reads only as it starts.
|
|
402
|
+
*/
|
|
403
|
+
export function fileRefusals(principal: Principal, writes: Record<string, unknown>): string[] {
|
|
404
|
+
const keys = Object.keys(writes)
|
|
405
|
+
const out: string[] = []
|
|
406
|
+
if (keys.some((k) => k.startsWith('schema/')) && !hasSection(principal, 'structure'))
|
|
407
|
+
out.push('You may not change the site’s definitions.')
|
|
408
|
+
if (
|
|
409
|
+
keys.some((k) => /^(components|stylesheets|scripts)\//.test(k)) &&
|
|
410
|
+
!hasSection(principal, 'components')
|
|
411
|
+
)
|
|
412
|
+
out.push('You may not change the site’s templates, stylesheets or scripts.')
|
|
413
|
+
if (keys.some((k) => k.startsWith('site/')) && !principal.isAdmin)
|
|
414
|
+
out.push('Only an administrator merges a change to the site’s own code.')
|
|
415
|
+
return out
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
/** A merge's plan as its routes answer it. */
|
|
419
|
+
const planView = (plan: MergePlan) => ({
|
|
420
|
+
pages: plan.pages.map((p) => ({
|
|
421
|
+
key: p.page.key,
|
|
422
|
+
name: p.name,
|
|
423
|
+
made: p.page.made,
|
|
424
|
+
changes: p.take.map((f) => fieldWords(f.field)),
|
|
425
|
+
publish: p.publish,
|
|
426
|
+
unpublish: p.unpublish,
|
|
427
|
+
})),
|
|
428
|
+
pending: plan.pending.map((p) => ({
|
|
429
|
+
key: p.pending.key,
|
|
430
|
+
id: p.pending.nodeId,
|
|
431
|
+
name: p.pending.name,
|
|
432
|
+
kind: p.pending.kind,
|
|
433
|
+
...(p.conflict ? { conflict: p.conflict } : {}),
|
|
434
|
+
})),
|
|
435
|
+
conflicts: plan.conflicts.map((c) => ({ ...c, words: fieldWords(c.field) })),
|
|
436
|
+
findings: plan.findings,
|
|
437
|
+
})
|
|
438
|
+
|
|
439
|
+
/**
|
|
440
|
+
* The workspace routes, under `<plugin>/api/workspaces`: `GET /` lists yours,
|
|
441
|
+
* or every one for an administrator with `?all=true`; `POST / { name }` opens
|
|
442
|
+
* one; `GET`, `PATCH { name }` and `DELETE /{key}`; `POST /{key}/members
|
|
443
|
+
* { userKey }` and `DELETE /{key}/members/{userKey}`; `GET /{key}/changes`.
|
|
444
|
+
* Merging (story 380): `GET /{key}/merge` says what it would do; `POST /{key}/merge
|
|
445
|
+
* { accept, rehearse }` does it; `POST /{key}/conflicts { page, answers }` answers
|
|
446
|
+
* a page's conflicts in the workspace; `DELETE /{key}/pending/{id}` drops a move,
|
|
447
|
+
* reorder or delete, or a marker, so it does not go; `POST /merge { workspaces }`
|
|
448
|
+
* merges several as one; `GET /mine` says whether a workspace is required, and
|
|
449
|
+
* the caller's own.
|
|
450
|
+
*/
|
|
451
|
+
export function createWorkspacesApi(
|
|
452
|
+
db: Db,
|
|
453
|
+
options: {
|
|
454
|
+
enabled: () => boolean
|
|
455
|
+
merge?: () => WorkspaceMerging
|
|
456
|
+
nodeState?: NodeSchemaState
|
|
457
|
+
required?: () => boolean
|
|
458
|
+
/** Story 388: the site takes its content only by a change; where it is edited. */
|
|
459
|
+
locked?: () => boolean
|
|
460
|
+
/** Story 386: the diff, conflicts and checks a command line asks for. */
|
|
461
|
+
checks?: () => WorkspaceChecks
|
|
462
|
+
editedAt?: () => string | null
|
|
463
|
+
schema?: () => WorkspaceSchema | undefined
|
|
464
|
+
/** Renders one page with the workspace's views (story 377). */
|
|
465
|
+
render?: (workspace: { id: number; key: string }, path: string) => Promise<unknown>
|
|
466
|
+
/** Told when a workspace is merged or discarded, for what is held for it. */
|
|
467
|
+
onClosed?: (key: string) => void
|
|
468
|
+
/** The files a discarded workspace's values named, for those nothing else does to go (story 390). */
|
|
469
|
+
onDiscardedFiles?: (urls: string[]) => void
|
|
470
|
+
/** A member's way into the workspace's site (story 379): a link with a single-use token. */
|
|
471
|
+
open?: (
|
|
472
|
+
workspace: { key: string },
|
|
473
|
+
principal: Principal,
|
|
474
|
+
path: string,
|
|
475
|
+
request: Request,
|
|
476
|
+
) => Promise<string | undefined>
|
|
477
|
+
/** Links for someone else to look at the workspace's site (story 379). */
|
|
478
|
+
links?: () => {
|
|
479
|
+
maxDays(): number
|
|
480
|
+
make(
|
|
481
|
+
workspace: { id: number; key: string },
|
|
482
|
+
principal: Principal,
|
|
483
|
+
days: number,
|
|
484
|
+
): Promise<{ id: number; url: string; expiresAt: string }>
|
|
485
|
+
list(workspaceId: number): Promise<
|
|
486
|
+
Array<{
|
|
487
|
+
id: number
|
|
488
|
+
madeBy: string
|
|
489
|
+
expiresAt: Date
|
|
490
|
+
withdrawnAt: Date | null
|
|
491
|
+
createdAt: Date
|
|
492
|
+
}>
|
|
493
|
+
>
|
|
494
|
+
withdraw(workspaceId: number, id: number): Promise<boolean>
|
|
495
|
+
}
|
|
496
|
+
},
|
|
497
|
+
) {
|
|
498
|
+
const workspaces = new WorkspaceRepository(db)
|
|
499
|
+
|
|
500
|
+
const audit = (
|
|
501
|
+
by: Principal,
|
|
502
|
+
action: string,
|
|
503
|
+
workspace: Workspace,
|
|
504
|
+
detail: string,
|
|
505
|
+
client: Client,
|
|
506
|
+
) =>
|
|
507
|
+
recordAudit(db, {
|
|
508
|
+
category: 'content',
|
|
509
|
+
action,
|
|
510
|
+
source: 'request',
|
|
511
|
+
userKey: by.id,
|
|
512
|
+
userName: by.name,
|
|
513
|
+
entityType: 'Workspace',
|
|
514
|
+
entityKey: workspace.key,
|
|
515
|
+
entityName: workspace.name,
|
|
516
|
+
detail,
|
|
517
|
+
ipAddress: client.ipAddress,
|
|
518
|
+
forwardedFor: client.forwardedFor,
|
|
519
|
+
})
|
|
520
|
+
|
|
521
|
+
const nameOf = (body: Record<string, unknown>): string | undefined => {
|
|
522
|
+
const name = typeof body.name === 'string' ? body.name.trim() : ''
|
|
523
|
+
return name.length > 0 && name.length <= 255 ? name : undefined
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
/** Merges one workspace or several as one, as `principal`, auditing each. */
|
|
527
|
+
const mergeNow = async (
|
|
528
|
+
merging: WorkspaceMerging,
|
|
529
|
+
chosen: readonly Workspace[],
|
|
530
|
+
principal: Principal,
|
|
531
|
+
asked: Record<string, unknown>,
|
|
532
|
+
client: Client,
|
|
533
|
+
): Promise<Response> => {
|
|
534
|
+
if (!mayMerge(principal)) return refused('You may not merge workspaces.', 403)
|
|
535
|
+
const accepted = Array.isArray(asked.accept)
|
|
536
|
+
? asked.accept.filter((a): a is string => typeof a === 'string')
|
|
537
|
+
: []
|
|
538
|
+
const refusals: string[] = []
|
|
539
|
+
const schema = options.schema?.()
|
|
540
|
+
for (const one of chosen) {
|
|
541
|
+
const own = await mergeRefusals(db, principal, await merging.preview(one))
|
|
542
|
+
// Its files need what saving them directly would (stories 376, 377).
|
|
543
|
+
if (schema) own.push(...fileRefusals(principal, (await schema.plan(one.id)).writes))
|
|
544
|
+
for (const refusal of own)
|
|
545
|
+
refusals.push(chosen.length > 1 ? `In "${one.name}": ${refusal}` : refusal)
|
|
546
|
+
}
|
|
547
|
+
if (refusals.length > 0)
|
|
548
|
+
return json({ message: 'You may not make every change it holds.', refusals }, 403)
|
|
549
|
+
// Story 383: the changes from other sites it holds are applied by it, each recorded once.
|
|
550
|
+
const appliedChanges = chosen.flatMap((one) => one.stagedChanges ?? [])
|
|
551
|
+
const outcome = await merging.run(chosen, principal, {
|
|
552
|
+
accepted,
|
|
553
|
+
rehearse: asked.rehearse === true,
|
|
554
|
+
...(await userIdOf(db, principal)),
|
|
555
|
+
...(appliedChanges.length > 0 ? { appliedChanges } : {}),
|
|
556
|
+
...(appliedChanges.length === 1 && chosen.length === 1
|
|
557
|
+
? { changeKey: appliedChanges[0]?.key }
|
|
558
|
+
: {}),
|
|
559
|
+
})
|
|
560
|
+
if (!outcome.ok)
|
|
561
|
+
return json(
|
|
562
|
+
{
|
|
563
|
+
message: 'It cannot be merged as it is.',
|
|
564
|
+
blockers: outcome.blockers,
|
|
565
|
+
...planView(outcome.plan),
|
|
566
|
+
},
|
|
567
|
+
409,
|
|
568
|
+
)
|
|
569
|
+
if (!outcome.rehearsed) {
|
|
570
|
+
for (const one of chosen) options.onClosed?.(one.key)
|
|
571
|
+
const together =
|
|
572
|
+
chosen.length > 1 ? ` with ${chosen.map((w) => `"${w.name}"`).join(', ')}` : ''
|
|
573
|
+
for (const one of chosen)
|
|
574
|
+
await audit(
|
|
575
|
+
principal,
|
|
576
|
+
'Merge',
|
|
577
|
+
one,
|
|
578
|
+
`Merged "${one.name}"${together}: ${outcome.merged.length} page(s), ${outcome.done.length} move(s) or delete(s)${outcome.forApproval.length > 0 ? `, ${outcome.forApproval.length} sent for approval` : ''}`,
|
|
579
|
+
client,
|
|
580
|
+
)
|
|
581
|
+
}
|
|
582
|
+
return json(outcome)
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
return {
|
|
586
|
+
async handle(
|
|
587
|
+
request: Request,
|
|
588
|
+
principal: Principal,
|
|
589
|
+
rest: string,
|
|
590
|
+
client: Client,
|
|
591
|
+
): Promise<Response> {
|
|
592
|
+
// What the back office asks at sign-in (story 380): must it work in the person's own?
|
|
593
|
+
// Answered for everyone, so a site without workspaces says no rather than refusing.
|
|
594
|
+
if (rest.replace(/^\/+|\/+$/g, '') === OWN_WORKSPACE && request.method === 'GET') {
|
|
595
|
+
const on = options.enabled() && hasSection(principal, 'content')
|
|
596
|
+
const own = on ? await workspaces.ownOf(principal.id) : undefined
|
|
597
|
+
const locked = options.locked?.() === true
|
|
598
|
+
return json({
|
|
599
|
+
required: on && !locked && options.required?.() === true,
|
|
600
|
+
workspace: own ? viewOf(own, principal) : null,
|
|
601
|
+
// Story 384: whether the switch shows at all, and whether Merge is offered.
|
|
602
|
+
enabled: on,
|
|
603
|
+
mayMerge: on && mayMerge(principal),
|
|
604
|
+
// Story 388: what the back office shows each item as, and where it links.
|
|
605
|
+
contentLocked: locked,
|
|
606
|
+
editedAt: locked ? (options.editedAt?.() ?? null) : null,
|
|
607
|
+
})
|
|
608
|
+
}
|
|
609
|
+
if (!options.enabled()) return refused('Workspaces are not turned on for this site.', 404)
|
|
610
|
+
if (!hasSection(principal, 'content'))
|
|
611
|
+
return refused('Workspaces are for people who look after content.', 403)
|
|
612
|
+
const body = async () =>
|
|
613
|
+
((await request.json().catch(() => ({}))) ?? {}) as Record<string, unknown>
|
|
614
|
+
const parts = rest.split('/').filter(Boolean).map(decodeURIComponent)
|
|
615
|
+
|
|
616
|
+
if (parts.length === 0) {
|
|
617
|
+
if (request.method === 'GET') {
|
|
618
|
+
const all = new URL(request.url).searchParams.get('all') === 'true'
|
|
619
|
+
if (all && !principal.isAdmin)
|
|
620
|
+
return refused('Only an administrator lists them all.', 403)
|
|
621
|
+
const mine = all ? await workspaces.all() : await workspaces.forUser(principal.id)
|
|
622
|
+
// Story 384: and those their owners show to every editor.
|
|
623
|
+
const shown = all
|
|
624
|
+
? []
|
|
625
|
+
: (await workspaces.all()).filter(
|
|
626
|
+
(w) => w.visibility === 'editors' && w.state === 'open' && !mayUse(w, principal),
|
|
627
|
+
)
|
|
628
|
+
return json({ items: [...mine, ...shown].map((w) => viewOf(w, principal)) })
|
|
629
|
+
}
|
|
630
|
+
if (request.method === 'POST') {
|
|
631
|
+
if (options.locked?.())
|
|
632
|
+
return refused(
|
|
633
|
+
`${CONTENT_LOCKED.title}: a workspace is opened where its content is made.`,
|
|
634
|
+
409,
|
|
635
|
+
)
|
|
636
|
+
const asked = await body()
|
|
637
|
+
const name = nameOf(asked)
|
|
638
|
+
if (!name) return refused('A workspace needs a name of up to 255 characters.', 400)
|
|
639
|
+
const opened = await workspaces.open({
|
|
640
|
+
name,
|
|
641
|
+
ownerKey: principal.id,
|
|
642
|
+
...privacyOf(asked),
|
|
643
|
+
})
|
|
644
|
+
// Its copy of the schema files, the base its changes to them merge from (story 376).
|
|
645
|
+
await options.schema?.()?.snapshot(opened.id)
|
|
646
|
+
await audit(principal, 'Open', opened, `Opened "${name}"`, client)
|
|
647
|
+
return json(viewOf(opened, principal), 201)
|
|
648
|
+
}
|
|
649
|
+
return new Response(null, { status: 405 })
|
|
650
|
+
}
|
|
651
|
+
|
|
652
|
+
// Several merged as one (story 380): `POST /merge { workspaces: [key], accept }`.
|
|
653
|
+
if (parts.length === 1 && parts[0] === 'merge' && request.method === 'POST') {
|
|
654
|
+
const merging = options.merge?.()
|
|
655
|
+
if (!merging) return refused('Merging is not available here.', 404)
|
|
656
|
+
const asked = await body()
|
|
657
|
+
const keys = Array.isArray(asked.workspaces)
|
|
658
|
+
? asked.workspaces.filter((k): k is string => typeof k === 'string' && UUID.test(k))
|
|
659
|
+
: []
|
|
660
|
+
const chosen: Workspace[] = []
|
|
661
|
+
for (const k of new Set(keys.map(normaliseUuid))) {
|
|
662
|
+
const one = await workspaces.byKey(k)
|
|
663
|
+
if (!one || !mayUse(one, principal)) return refused('There is no such workspace.', 404)
|
|
664
|
+
if (one.state === 'merged') return refused(`"${one.name}" was merged already.`, 409)
|
|
665
|
+
chosen.push(one)
|
|
666
|
+
}
|
|
667
|
+
if (chosen.length === 0) return refused('Name the workspaces to merge.', 400)
|
|
668
|
+
return mergeNow(merging, chosen, principal, asked, client)
|
|
669
|
+
}
|
|
670
|
+
|
|
671
|
+
// Story 384: which other people's workspaces changed a page, by whose, never what.
|
|
672
|
+
if (parts[0] === 'touched' && parts[1] && UUID.test(parts[1]) && request.method === 'GET') {
|
|
673
|
+
const node = await db.q
|
|
674
|
+
.selectFrom('node')
|
|
675
|
+
.select('id')
|
|
676
|
+
.where('unique_id', '=', normaliseUuid(parts[1]))
|
|
677
|
+
.where('workspace_id', 'is', null)
|
|
678
|
+
.executeTakeFirst()
|
|
679
|
+
const touching = node ? await workspaces.touching(Number(node.id), principal.id) : []
|
|
680
|
+
const owners = await new UserRepository(db).byKeys(touching.map((w) => w.ownerKey))
|
|
681
|
+
return json({
|
|
682
|
+
items: touching.map((w) => ({
|
|
683
|
+
owner: owners.find((u) => normaliseUuid(u.key) === w.ownerKey)?.name ?? 'someone',
|
|
684
|
+
...(w.visibility === 'editors' ? { workspace: { key: w.key, name: w.name } } : {}),
|
|
685
|
+
})),
|
|
686
|
+
})
|
|
687
|
+
}
|
|
688
|
+
|
|
689
|
+
// Story 383: every workspace still open, staged changes included, and those idle too long cleared.
|
|
690
|
+
if (parts[0] === 'pending' && parts.length <= 2) {
|
|
691
|
+
if (!principal.isAdmin) return refused('Only an administrator looks after them all.', 403)
|
|
692
|
+
const open = await pendingWorkspaces(db)
|
|
693
|
+
if (parts.length === 1 && request.method === 'GET') return json({ items: open })
|
|
694
|
+
if (parts[1] === 'discard' && request.method === 'POST') {
|
|
695
|
+
const days = Number((await body()).olderThanDays)
|
|
696
|
+
if (!Number.isFinite(days) || days < 0)
|
|
697
|
+
return refused('Say how many days old, as olderThanDays.', 400)
|
|
698
|
+
const before = Date.now() - days * 86_400_000
|
|
699
|
+
const discarded: string[] = []
|
|
700
|
+
for (const one of open) {
|
|
701
|
+
if (new Date(one.lastActivity).getTime() >= before) continue
|
|
702
|
+
const found = await workspaces.byKey(one.key)
|
|
703
|
+
if (found?.state !== 'open') continue
|
|
704
|
+
const files = await filesNamedBy(db, found.id)
|
|
705
|
+
await workspaces.discard(found.id)
|
|
706
|
+
options.onClosed?.(found.key)
|
|
707
|
+
options.onDiscardedFiles?.(files)
|
|
708
|
+
await audit(
|
|
709
|
+
principal,
|
|
710
|
+
'Discard',
|
|
711
|
+
found,
|
|
712
|
+
`Discarded "${found.name}", idle since ${one.lastActivity}`,
|
|
713
|
+
client,
|
|
714
|
+
)
|
|
715
|
+
discarded.push(found.key)
|
|
716
|
+
}
|
|
717
|
+
return json({ discarded })
|
|
718
|
+
}
|
|
719
|
+
return new Response(null, { status: 405 })
|
|
720
|
+
}
|
|
721
|
+
|
|
722
|
+
const [key, sub, member] = parts as [string, string | undefined, string | undefined]
|
|
723
|
+
const found = UUID.test(key) ? await workspaces.byKey(key) : undefined
|
|
724
|
+
// An administrator may list and discard any, to clear one left behind, never read it.
|
|
725
|
+
const usable = found && mayUse(found, principal)
|
|
726
|
+
const discardable = found && (usable || principal.isAdmin)
|
|
727
|
+
// Story 384: one its owner shows to every editor is read by them, and changed by its members.
|
|
728
|
+
const readable =
|
|
729
|
+
found?.visibility === 'editors' &&
|
|
730
|
+
request.method === 'GET' &&
|
|
731
|
+
(sub === undefined || ['changes', 'diff', 'merge', 'members', 'conflicts'].includes(sub))
|
|
732
|
+
if (!found || (!usable && !readable && !(discardable && request.method === 'DELETE' && !sub)))
|
|
733
|
+
return refused('There is no such workspace.', 404)
|
|
734
|
+
const owner = found.ownerKey === normaliseUuid(principal.id)
|
|
735
|
+
|
|
736
|
+
if (!sub) {
|
|
737
|
+
if (request.method === 'GET') return json(viewOf(found, principal))
|
|
738
|
+
if (request.method === 'PATCH') {
|
|
739
|
+
if (!owner) return refused('Only its owner changes a workspace.', 403)
|
|
740
|
+
const asked = await body()
|
|
741
|
+
// Story 384: who sees it, and whether others are told, changed by its owner.
|
|
742
|
+
const privacy = privacyOf(asked)
|
|
743
|
+
await workspaces.setPrivacy(found.id, privacy)
|
|
744
|
+
if (asked.name === undefined && Object.keys(privacy).length > 0) {
|
|
745
|
+
await audit(principal, 'Privacy', found, `Privacy of "${found.name}" changed`, client)
|
|
746
|
+
return json(viewOf((await workspaces.byKey(found.key)) as Workspace, principal))
|
|
747
|
+
}
|
|
748
|
+
const name = nameOf(asked)
|
|
749
|
+
if (!name) return refused('A workspace needs a name of up to 255 characters.', 400)
|
|
750
|
+
await workspaces.rename(found.id, name)
|
|
751
|
+
await audit(principal, 'Rename', found, `Renamed "${found.name}" to "${name}"`, client)
|
|
752
|
+
return json(viewOf((await workspaces.byKey(found.key)) as Workspace, principal))
|
|
753
|
+
}
|
|
754
|
+
if (request.method === 'DELETE') {
|
|
755
|
+
if (!owner && !principal.isAdmin)
|
|
756
|
+
return refused('Only its owner discards a workspace.', 403)
|
|
757
|
+
const files = await filesNamedBy(db, found.id)
|
|
758
|
+
await workspaces.discard(found.id)
|
|
759
|
+
options.onClosed?.(found.key)
|
|
760
|
+
options.onDiscardedFiles?.(files)
|
|
761
|
+
await audit(principal, 'Discard', found, `Discarded "${found.name}"`, client)
|
|
762
|
+
return new Response(null, { status: 204 })
|
|
763
|
+
}
|
|
764
|
+
return new Response(null, { status: 405 })
|
|
765
|
+
}
|
|
766
|
+
|
|
767
|
+
if (sub === 'changes' && !member && request.method === 'GET')
|
|
768
|
+
return json({ items: await workspaces.changes(found.id) })
|
|
769
|
+
// Story 384: "Drop this change": the page goes back to Shared's, here.
|
|
770
|
+
if (sub === 'changes' && member && UUID.test(member) && request.method === 'DELETE') {
|
|
771
|
+
if (!usable) return refused('Only its members change a workspace.', 403)
|
|
772
|
+
const node = await db.q
|
|
773
|
+
.selectFrom('node')
|
|
774
|
+
.select('id')
|
|
775
|
+
.where('unique_id', '=', normaliseUuid(member))
|
|
776
|
+
.executeTakeFirst()
|
|
777
|
+
if (!node) return refused('There is no such page.', 404)
|
|
778
|
+
await workspaces.dropPage(found.id, Number(node.id))
|
|
779
|
+
return new Response(null, { status: 204 })
|
|
780
|
+
}
|
|
781
|
+
|
|
782
|
+
// Story 386: what a command line asks before merging.
|
|
783
|
+
const checks = options.checks?.()
|
|
784
|
+
if (checks && !member) {
|
|
785
|
+
const query = new URL(request.url).searchParams
|
|
786
|
+
if (sub === 'diff' && request.method === 'GET') {
|
|
787
|
+
const against = query.get('against') === 'base' ? 'base' : 'shared'
|
|
788
|
+
return json(await checks.diff(found, against))
|
|
789
|
+
}
|
|
790
|
+
if (sub === 'conflicts' && request.method === 'GET')
|
|
791
|
+
return json({ items: await checks.conflicts(found) })
|
|
792
|
+
if (sub === 'check' && request.method === 'POST') {
|
|
793
|
+
const asked = await body()
|
|
794
|
+
return json(await checks.check(found, asked.all === true))
|
|
795
|
+
}
|
|
796
|
+
if (sub === 'pages' && request.method === 'GET') {
|
|
797
|
+
const pages = await checks.pages(found, query.get('all') === 'true')
|
|
798
|
+
return json({
|
|
799
|
+
items: query.get('failing') === 'true' ? pages.filter((p) => !p.ok) : pages,
|
|
800
|
+
})
|
|
801
|
+
}
|
|
802
|
+
if (sub === 'errors' && request.method === 'GET') {
|
|
803
|
+
const since = query.get('since') ? new Date(query.get('since') as string) : undefined
|
|
804
|
+
return json({
|
|
805
|
+
items: checks.errors(
|
|
806
|
+
found,
|
|
807
|
+
since && !Number.isNaN(since.getTime()) ? since : undefined,
|
|
808
|
+
),
|
|
809
|
+
})
|
|
810
|
+
}
|
|
811
|
+
}
|
|
812
|
+
|
|
813
|
+
// Story 376: its definition files, brought up to Shared's, and a file's conflict answered.
|
|
814
|
+
const schema = options.schema?.()
|
|
815
|
+
if (schema && sub === 'files' && !member && request.method === 'GET') {
|
|
816
|
+
const planned = await schema.plan(found.id)
|
|
817
|
+
return json({
|
|
818
|
+
changes: (await new WorkspaceFileRepository(db).changes(found.id)).map((c) => ({
|
|
819
|
+
path: schema.shown(c.path),
|
|
820
|
+
class: c.class ?? 'none',
|
|
821
|
+
added: c.base === null,
|
|
822
|
+
removed: c.now === null,
|
|
823
|
+
// Read only as the site starts (story 377): it takes effect when merged.
|
|
824
|
+
...(c.path.startsWith('site/') ? { takesEffect: 'at merge' } : {}),
|
|
825
|
+
})),
|
|
826
|
+
conflicts: planned.conflicts,
|
|
827
|
+
problems: planned.problems,
|
|
828
|
+
})
|
|
829
|
+
}
|
|
830
|
+
// Story 377: a file the site reads only as it starts, carried to the merge.
|
|
831
|
+
if (schema && sub === 'site-files' && !member && request.method === 'PUT') {
|
|
832
|
+
if (!principal.isAdmin)
|
|
833
|
+
return refused('Only an administrator changes the site’s own code.', 403)
|
|
834
|
+
if (found.state === 'merged') return refused('This workspace was merged already.', 409)
|
|
835
|
+
const asked = await body()
|
|
836
|
+
const path = typeof asked.path === 'string' ? asked.path : ''
|
|
837
|
+
const text =
|
|
838
|
+
typeof asked.text === 'string' ? asked.text : asked.text === null ? null : undefined
|
|
839
|
+
if (text === undefined || !(await schema.carry(found.id, path, text)))
|
|
840
|
+
return refused(
|
|
841
|
+
'Name the package, the config, or a route, job or middleware file, with its text or null.',
|
|
842
|
+
400,
|
|
843
|
+
)
|
|
844
|
+
return json({ path, takesEffect: 'at merge' })
|
|
845
|
+
}
|
|
846
|
+
// Story 379: a member opens the workspace's site; links let someone else look.
|
|
847
|
+
if (sub === 'open' && !member && request.method === 'POST' && options.open) {
|
|
848
|
+
if (found.state === 'merged') return refused('This workspace was merged already.', 409)
|
|
849
|
+
const asked = await body()
|
|
850
|
+
const path = typeof asked.path === 'string' && asked.path.startsWith('/') ? asked.path : '/'
|
|
851
|
+
const url = await options.open(found, principal, path, request)
|
|
852
|
+
return url ? json({ url }) : refused('You may not open it.', 403)
|
|
853
|
+
}
|
|
854
|
+
if (sub === 'links' && options.links) {
|
|
855
|
+
const links = options.links()
|
|
856
|
+
if (!member && request.method === 'GET')
|
|
857
|
+
return json({
|
|
858
|
+
items: (await links.list(found.id)).map((l) => ({
|
|
859
|
+
id: l.id,
|
|
860
|
+
madeBy: l.madeBy,
|
|
861
|
+
createdAt: l.createdAt.toISOString(),
|
|
862
|
+
expiresAt: l.expiresAt.toISOString(),
|
|
863
|
+
withdrawn: l.withdrawnAt !== null,
|
|
864
|
+
})),
|
|
865
|
+
})
|
|
866
|
+
if (!member && request.method === 'POST') {
|
|
867
|
+
if (found.state === 'merged') return refused('This workspace was merged already.', 409)
|
|
868
|
+
const most = links.maxDays()
|
|
869
|
+
if (most <= 0) return refused('This site does not make links to a workspace.', 403)
|
|
870
|
+
const asked = await body()
|
|
871
|
+
const days = typeof asked.days === 'number' ? asked.days : most
|
|
872
|
+
if (!(days > 0) || days > most)
|
|
873
|
+
return refused(`A link lasts at most ${most} day(s) here.`, 400)
|
|
874
|
+
const made = await links.make(found, principal, days)
|
|
875
|
+
await audit(
|
|
876
|
+
principal,
|
|
877
|
+
'Link',
|
|
878
|
+
found,
|
|
879
|
+
`A link to "${found.name}" for ${days} day(s)`,
|
|
880
|
+
client,
|
|
881
|
+
)
|
|
882
|
+
return json(made, 201)
|
|
883
|
+
}
|
|
884
|
+
if (member && request.method === 'DELETE') {
|
|
885
|
+
if (!(await links.withdraw(found.id, Number(member))))
|
|
886
|
+
return refused('There is no such link.', 404)
|
|
887
|
+
await audit(principal, 'Unlink', found, `Withdrew a link to "${found.name}"`, client)
|
|
888
|
+
return new Response(null, { status: 204 })
|
|
889
|
+
}
|
|
890
|
+
}
|
|
891
|
+
// Story 377: one page as the workspace's views render it, before it has an address (379).
|
|
892
|
+
if (sub === 'render' && !member && request.method === 'GET' && options.render) {
|
|
893
|
+
const path = new URL(request.url).searchParams.get('path') ?? '/'
|
|
894
|
+
return json(await options.render({ id: found.id, key: found.key }, path))
|
|
895
|
+
}
|
|
896
|
+
if (schema && sub === 'update' && !member && request.method === 'POST') {
|
|
897
|
+
if (found.state === 'merged') return refused('This workspace was merged already.', 409)
|
|
898
|
+
return json(await schema.updateFromShared({ id: found.id, key: found.key }))
|
|
899
|
+
}
|
|
900
|
+
if (schema && sub === 'files' && member === 'resolve' && request.method === 'POST') {
|
|
901
|
+
const asked = await body()
|
|
902
|
+
const path = typeof asked.path === 'string' ? asked.path : ''
|
|
903
|
+
const answer: { text: string } | { side: 'mine' | 'theirs' } | undefined =
|
|
904
|
+
typeof asked.text === 'string'
|
|
905
|
+
? { text: asked.text }
|
|
906
|
+
: asked.side === 'mine' || asked.side === 'theirs'
|
|
907
|
+
? { side: asked.side }
|
|
908
|
+
: undefined
|
|
909
|
+
if (!path || !answer)
|
|
910
|
+
return refused('Name the file, and keep "mine", "theirs" or a text.', 400)
|
|
911
|
+
if (!(await schema.resolve({ id: found.id, key: found.key }, path, answer)))
|
|
912
|
+
return refused('The text still holds conflict markers.', 400)
|
|
913
|
+
return json({ ok: true })
|
|
914
|
+
}
|
|
915
|
+
|
|
916
|
+
if (sub === 'merge' || sub === 'conflicts' || sub === 'pending') {
|
|
917
|
+
const merging = options.merge?.()
|
|
918
|
+
if (!merging) return refused('Merging is not available here.', 404)
|
|
919
|
+
if (found.state === 'merged') return refused('This workspace was merged already.', 409)
|
|
920
|
+
if (sub === 'merge' && !member && request.method === 'GET') {
|
|
921
|
+
const plan = await merging.preview(found)
|
|
922
|
+
const files = schema ? await schema.plan(found.id) : undefined
|
|
923
|
+
return json({
|
|
924
|
+
...planView(plan),
|
|
925
|
+
files: files
|
|
926
|
+
? {
|
|
927
|
+
writes: Object.keys(files.writes).map((key) => schema?.shown(key) ?? key),
|
|
928
|
+
conflicts: files.conflicts,
|
|
929
|
+
problems: files.problems,
|
|
930
|
+
class: files.change,
|
|
931
|
+
// Story 382: each item, its class, and whether it must be accepted.
|
|
932
|
+
items: files.items,
|
|
933
|
+
}
|
|
934
|
+
: { writes: [], conflicts: [], problems: [], class: 'none', items: [] },
|
|
935
|
+
mayMerge: mayMerge(principal),
|
|
936
|
+
refusals: [
|
|
937
|
+
...(await mergeRefusals(db, principal, plan)),
|
|
938
|
+
...(files ? fileRefusals(principal, files.writes) : []),
|
|
939
|
+
],
|
|
940
|
+
})
|
|
941
|
+
}
|
|
942
|
+
if (sub === 'merge' && !member && request.method === 'POST')
|
|
943
|
+
return mergeNow(merging, [found], principal, await body(), client)
|
|
944
|
+
if (sub === 'conflicts' && !member && request.method === 'POST') {
|
|
945
|
+
const asked = await body()
|
|
946
|
+
const page = typeof asked.page === 'string' ? asked.page : ''
|
|
947
|
+
const answers: Record<string, 'mine' | 'theirs'> = {}
|
|
948
|
+
if (asked.answers && typeof asked.answers === 'object')
|
|
949
|
+
for (const [field, side] of Object.entries(asked.answers as Record<string, unknown>))
|
|
950
|
+
if (side === 'mine' || side === 'theirs') answers[field] = side
|
|
951
|
+
const docs = new DocumentRepository(db, { nodeState: options.nodeState }).inWorkspace(
|
|
952
|
+
found.id,
|
|
953
|
+
)
|
|
954
|
+
try {
|
|
955
|
+
if (!UUID.test(page) || !(await docs.rebaseWorkspacePage(page, answers)))
|
|
956
|
+
return refused('The workspace has not changed that page.', 404)
|
|
957
|
+
} catch (error) {
|
|
958
|
+
if (error instanceof WorkspaceRefusedError) return refused(error.message, 409)
|
|
959
|
+
throw error
|
|
960
|
+
}
|
|
961
|
+
return json(planView(await merging.preview(found)))
|
|
962
|
+
}
|
|
963
|
+
if (sub === 'pending' && member && request.method === 'DELETE') {
|
|
964
|
+
const id = Number(member)
|
|
965
|
+
if (!Number.isInteger(id)) return refused('There is nothing here.', 404)
|
|
966
|
+
await workspaces.dropPending(found.id, id)
|
|
967
|
+
return new Response(null, { status: 204 })
|
|
968
|
+
}
|
|
969
|
+
}
|
|
970
|
+
|
|
971
|
+
if (sub === 'members') {
|
|
972
|
+
// Who is in it (story 386), for anyone in it.
|
|
973
|
+
if (!member && request.method === 'GET') {
|
|
974
|
+
const people = await new UserRepository(db).byKeys([found.ownerKey, ...found.memberKeys])
|
|
975
|
+
return json({
|
|
976
|
+
items: people.map((u) => ({
|
|
977
|
+
key: normaliseUuid(u.key),
|
|
978
|
+
name: u.name,
|
|
979
|
+
email: u.email,
|
|
980
|
+
owner: normaliseUuid(u.key) === found.ownerKey,
|
|
981
|
+
})),
|
|
982
|
+
})
|
|
983
|
+
}
|
|
984
|
+
if (!owner) return refused('Only its owner shares a workspace.', 403)
|
|
985
|
+
if (!member && request.method === 'POST') {
|
|
986
|
+
const asked = await body()
|
|
987
|
+
// By their key, or (story 386, from the command line) by their email.
|
|
988
|
+
const email = typeof asked.email === 'string' ? asked.email.trim().toLowerCase() : ''
|
|
989
|
+
const byEmail = email
|
|
990
|
+
? await db.q
|
|
991
|
+
.selectFrom('user_account')
|
|
992
|
+
.select('key')
|
|
993
|
+
.where('email', '=', email)
|
|
994
|
+
.executeTakeFirst()
|
|
995
|
+
: undefined
|
|
996
|
+
const userKey = byEmail
|
|
997
|
+
? String(byEmail.key)
|
|
998
|
+
: typeof asked.userKey === 'string'
|
|
999
|
+
? asked.userKey
|
|
1000
|
+
: ''
|
|
1001
|
+
if (email && !byEmail) return refused(`Nobody here has the email ${email}.`, 404)
|
|
1002
|
+
if (!UUID.test(userKey)) return refused('Name the person by their key or email.', 400)
|
|
1003
|
+
const known = await db.q
|
|
1004
|
+
.selectFrom('user_account')
|
|
1005
|
+
.select('key')
|
|
1006
|
+
.where('key', '=', normaliseUuid(userKey))
|
|
1007
|
+
.execute()
|
|
1008
|
+
if (known.length === 0) return refused('There is no such person.', 404)
|
|
1009
|
+
if (normaliseUuid(userKey) === found.ownerKey)
|
|
1010
|
+
return refused('Its owner is in it already.', 400)
|
|
1011
|
+
if (await workspaces.addMember(found.id, userKey))
|
|
1012
|
+
await audit(principal, 'Share', found, `Shared with ${normaliseUuid(userKey)}`, client)
|
|
1013
|
+
return json(viewOf((await workspaces.byKey(found.key)) as Workspace, principal))
|
|
1014
|
+
}
|
|
1015
|
+
if (member && request.method === 'DELETE') {
|
|
1016
|
+
if (!(await workspaces.removeMember(found.id, member)))
|
|
1017
|
+
return refused('They are not a member.', 404)
|
|
1018
|
+
await audit(
|
|
1019
|
+
principal,
|
|
1020
|
+
'Unshare',
|
|
1021
|
+
found,
|
|
1022
|
+
`No longer shared with ${normaliseUuid(member)}`,
|
|
1023
|
+
client,
|
|
1024
|
+
)
|
|
1025
|
+
return new Response(null, { status: 204 })
|
|
1026
|
+
}
|
|
1027
|
+
}
|
|
1028
|
+
return refused('There is nothing here.', 404)
|
|
1029
|
+
},
|
|
1030
|
+
}
|
|
1031
|
+
}
|