@crombolo/server 0.54.1 → 0.56.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 +13 -13
- package/src/actions.ts +6 -1
- package/src/bundle-install.ts +13 -3
- package/src/bundle-sections.ts +30 -4
- package/src/config.ts +21 -1
- package/src/content-events.ts +17 -1
- package/src/core.ts +32 -0
- package/src/index.ts +4 -0
- package/src/outbound-address.ts +182 -0
- package/src/owner-jobs.ts +7 -1
- package/src/remote.ts +8 -2
- package/src/routes.ts +13 -1
- package/src/schema.ts +6 -2
- package/src/server.ts +2 -2
- package/src/site-content-values.ts +97 -0
- package/src/site-content.ts +282 -0
- package/src/site-events.ts +65 -0
- package/src/site-services.ts +4 -0
- package/src/webhooks.ts +167 -17
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `site().content`'s values (story 298): by alias, `{ title: 'Hello' }`, and by
|
|
3
|
+
* culture for a property that varies, `{ title: { 'en-GB': 'Hello' } }`, to and
|
|
4
|
+
* from the stored shape the document operations take. Pure.
|
|
5
|
+
*/
|
|
6
|
+
import type { DocumentAggregate, DocumentValue, FieldError } from '@crombolo/core'
|
|
7
|
+
|
|
8
|
+
/** What the conversion needs of a property: its alias, and whether it varies by culture. */
|
|
9
|
+
export interface ValueProperty {
|
|
10
|
+
alias: string
|
|
11
|
+
variesByCulture: boolean
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
const isRecord = (value: unknown): value is Record<string, unknown> =>
|
|
15
|
+
typeof value === 'object' && value !== null && !Array.isArray(value)
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Site code's values as the operations store them, laid over what the page
|
|
19
|
+
* already holds; or, when a value cannot be placed, the fields that say why.
|
|
20
|
+
*
|
|
21
|
+
* - A property that does not vary takes its value as it is.
|
|
22
|
+
* - One that varies takes a culture-keyed object, or a plain value with `culture`.
|
|
23
|
+
*/
|
|
24
|
+
export function toDocumentValues(
|
|
25
|
+
given: Readonly<Record<string, unknown>>,
|
|
26
|
+
properties: readonly ValueProperty[],
|
|
27
|
+
options: { culture?: string; existing?: readonly DocumentValue[] } = {},
|
|
28
|
+
): { values: DocumentValue[] } | { errors: FieldError[] } {
|
|
29
|
+
const byAlias = new Map(properties.map((p) => [p.alias, p]))
|
|
30
|
+
const errors: FieldError[] = []
|
|
31
|
+
const set = new Map<string, DocumentValue>()
|
|
32
|
+
const keyOf = (alias: string, culture: string | null) => `${alias}|${culture ?? ''}`
|
|
33
|
+
for (const value of options.existing ?? []) {
|
|
34
|
+
if (value.segment) continue
|
|
35
|
+
set.set(keyOf(value.alias, value.culture), value)
|
|
36
|
+
}
|
|
37
|
+
for (const [alias, value] of Object.entries(given)) {
|
|
38
|
+
const property = byAlias.get(alias)
|
|
39
|
+
if (!property) {
|
|
40
|
+
errors.push({ field: alias, message: `The content type has no property "${alias}".` })
|
|
41
|
+
continue
|
|
42
|
+
}
|
|
43
|
+
if (!property.variesByCulture) {
|
|
44
|
+
set.set(keyOf(alias, null), { alias, culture: null, segment: null, value })
|
|
45
|
+
continue
|
|
46
|
+
}
|
|
47
|
+
if (
|
|
48
|
+
isRecord(value) &&
|
|
49
|
+
Object.keys(value).every((key) => /^[a-z]{2,3}(-[A-Za-z0-9]+)*$/.test(key))
|
|
50
|
+
) {
|
|
51
|
+
for (const [culture, inCulture] of Object.entries(value))
|
|
52
|
+
set.set(keyOf(alias, culture), { alias, culture, segment: null, value: inCulture })
|
|
53
|
+
continue
|
|
54
|
+
}
|
|
55
|
+
if (!options.culture) {
|
|
56
|
+
errors.push({
|
|
57
|
+
field: alias,
|
|
58
|
+
message: `"${alias}" varies by culture: give it by culture, { "en-GB": … }, or say which culture.`,
|
|
59
|
+
})
|
|
60
|
+
continue
|
|
61
|
+
}
|
|
62
|
+
set.set(keyOf(alias, options.culture), {
|
|
63
|
+
alias,
|
|
64
|
+
culture: options.culture,
|
|
65
|
+
segment: null,
|
|
66
|
+
value,
|
|
67
|
+
})
|
|
68
|
+
}
|
|
69
|
+
return errors.length > 0 ? { errors } : { values: [...set.values()] }
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** A page's stored values by alias, by culture where its property varies. */
|
|
73
|
+
export function fromDocumentValues(
|
|
74
|
+
values: readonly DocumentValue[],
|
|
75
|
+
properties: readonly ValueProperty[],
|
|
76
|
+
): Record<string, unknown> {
|
|
77
|
+
const varies = new Map(properties.map((p) => [p.alias, p.variesByCulture]))
|
|
78
|
+
const out: Record<string, unknown> = {}
|
|
79
|
+
for (const value of values) {
|
|
80
|
+
if (value.segment) continue
|
|
81
|
+
if (varies.get(value.alias) && value.culture) {
|
|
82
|
+
const byCulture = (out[value.alias] ?? {}) as Record<string, unknown>
|
|
83
|
+
byCulture[value.culture] = value.value
|
|
84
|
+
out[value.alias] = byCulture
|
|
85
|
+
} else if (!value.culture) out[value.alias] = value.value
|
|
86
|
+
}
|
|
87
|
+
return out
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** A page's name: one, or one per culture where its type varies. */
|
|
91
|
+
export function documentName(
|
|
92
|
+
document: Pick<DocumentAggregate, 'variants'>,
|
|
93
|
+
): string | Record<string, string> {
|
|
94
|
+
const named = document.variants.filter((v) => !v.segment)
|
|
95
|
+
if (named.length === 1 && !named[0]?.culture) return named[0]?.name ?? ''
|
|
96
|
+
return Object.fromEntries(named.map((v) => [v.culture ?? '', v.name]))
|
|
97
|
+
}
|
|
@@ -0,0 +1,282 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `site().content` (story 298): the site's own code reading and writing pages,
|
|
3
|
+
* through the document operations the Management API uses, as the API user the
|
|
4
|
+
* config's `content.actAs` names. Its permissions, start nodes, languages and the
|
|
5
|
+
* approval workflows bound what this may do, and the audit names the route,
|
|
6
|
+
* action, job or event that made each change. docs/rendering.md, "Writing content".
|
|
7
|
+
*/
|
|
8
|
+
import { AsyncLocalStorage } from 'node:async_hooks'
|
|
9
|
+
import type { Principal } from '@crombolo/api-management'
|
|
10
|
+
import { canReadDocument } from '@crombolo/api-management'
|
|
11
|
+
import { AuthStore } from '@crombolo/auth'
|
|
12
|
+
import type { DocumentOperations, Refusal } from '@crombolo/content'
|
|
13
|
+
import { userActor } from '@crombolo/content'
|
|
14
|
+
import { normaliseUuid, Outcome, ok, toSectionAliases } from '@crombolo/core'
|
|
15
|
+
import {
|
|
16
|
+
ContentTypeRepository,
|
|
17
|
+
type Db,
|
|
18
|
+
DocumentRepository,
|
|
19
|
+
type DocumentRepositoryOptions,
|
|
20
|
+
UserRepository,
|
|
21
|
+
} from '@crombolo/data'
|
|
22
|
+
import type { SiteContent, SiteDocument } from '@crombolo/render'
|
|
23
|
+
import { createNodeLookup, loadAccess } from './access.ts'
|
|
24
|
+
import {
|
|
25
|
+
documentName,
|
|
26
|
+
fromDocumentValues,
|
|
27
|
+
toDocumentValues,
|
|
28
|
+
type ValueProperty,
|
|
29
|
+
} from './site-content-values.ts'
|
|
30
|
+
|
|
31
|
+
/** Where site code may write from, and what it is: `route POST /api/listings`, `job imports.nightly`. */
|
|
32
|
+
interface WriteScope {
|
|
33
|
+
via: string
|
|
34
|
+
source: 'request' | 'job'
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const writes = new AsyncLocalStorage<WriteScope>()
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Runs site code that may write content: a route, an action, a job or an event
|
|
41
|
+
* handler, named for the audit. A page render runs outside any, and only reads.
|
|
42
|
+
*/
|
|
43
|
+
export function withSiteWrites<T>(scope: WriteScope, run: () => T): T {
|
|
44
|
+
return writes.run(scope, run)
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
|
|
48
|
+
|
|
49
|
+
export interface SiteContentDeps {
|
|
50
|
+
db: Db
|
|
51
|
+
documents: DocumentOperations
|
|
52
|
+
/** The node's schema state, as every document read on it is given. */
|
|
53
|
+
nodeState?: DocumentRepositoryOptions['nodeState']
|
|
54
|
+
nodeId?: string
|
|
55
|
+
/** The API user's client id, from `content.actAs`. */
|
|
56
|
+
actAs?: string
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** The API user a client id names, as the Management API would see it signed in; undefined when none. */
|
|
60
|
+
export async function apiUserPrincipal(db: Db, clientId: string): Promise<Principal | undefined> {
|
|
61
|
+
const owner = await new UserRepository(db).clientCredentialOwner(clientId)
|
|
62
|
+
if (!owner) return undefined
|
|
63
|
+
const store = new AuthStore(db)
|
|
64
|
+
const user = await store.findUserById(owner.userId)
|
|
65
|
+
if (!user || user.isLockedOut || !user.isApproved) return undefined
|
|
66
|
+
const authorization = await store.loadAuthorization(user.id)
|
|
67
|
+
return {
|
|
68
|
+
id: user.key,
|
|
69
|
+
userName: user.login,
|
|
70
|
+
name: user.userName,
|
|
71
|
+
email: user.email,
|
|
72
|
+
isAdmin: authorization.isAdmin,
|
|
73
|
+
languageIsoCode: user.language ?? undefined,
|
|
74
|
+
avatarUrls: [],
|
|
75
|
+
allowedSections: toSectionAliases(authorization.appAliases),
|
|
76
|
+
permissions: authorization.permissions,
|
|
77
|
+
groupKeys: authorization.groupKeys,
|
|
78
|
+
hasAccessToAllLanguages: authorization.hasAccessToAllLanguages,
|
|
79
|
+
...(await loadAccess(db, user.id)),
|
|
80
|
+
} as unknown as Principal
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** An operation's refusal as an `Outcome` site code matches on. */
|
|
84
|
+
function outcomeOf(refusal: Refusal) {
|
|
85
|
+
switch (refusal.kind) {
|
|
86
|
+
case 'notFound':
|
|
87
|
+
return Outcome.notFound(refusal.reason)
|
|
88
|
+
case 'forbidden':
|
|
89
|
+
return Outcome.forbidden(refusal.reason)
|
|
90
|
+
case 'needsApproval':
|
|
91
|
+
return Outcome.badRequest(`This needs approval before it is published: ${refusal.reason}`)
|
|
92
|
+
case 'validation':
|
|
93
|
+
case 'blocked':
|
|
94
|
+
if (refusal.kind === 'blocked' && !refusal.errors?.length)
|
|
95
|
+
return Outcome.badRequest(refusal.reason)
|
|
96
|
+
return Outcome.unprocessableContent(
|
|
97
|
+
(refusal.errors ?? []).flatMap((error) =>
|
|
98
|
+
error.messages.map((message) => ({
|
|
99
|
+
field: error.culture ? `${error.alias}.${error.culture}` : error.alias,
|
|
100
|
+
message,
|
|
101
|
+
})),
|
|
102
|
+
),
|
|
103
|
+
refusal.reason,
|
|
104
|
+
)
|
|
105
|
+
default:
|
|
106
|
+
return Outcome.badRequest(refusal.reason)
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
export function createSiteContent(deps: SiteContentDeps): SiteContent {
|
|
111
|
+
const { db, documents } = deps
|
|
112
|
+
const repo = new DocumentRepository(db, { nodeState: deps.nodeState, nodeId: deps.nodeId })
|
|
113
|
+
const types = new ContentTypeRepository(db)
|
|
114
|
+
const nodes = createNodeLookup(db)
|
|
115
|
+
|
|
116
|
+
const notActing = () =>
|
|
117
|
+
Outcome.forbidden(
|
|
118
|
+
"This site's code cannot change content: name an API user in the config's content.actAs.",
|
|
119
|
+
)
|
|
120
|
+
|
|
121
|
+
const principal = async () => (deps.actAs ? apiUserPrincipal(db, deps.actAs) : undefined)
|
|
122
|
+
|
|
123
|
+
/** Who a write is, inside a route, an action, a job or an event; a refusal elsewhere. */
|
|
124
|
+
const writer = async () => {
|
|
125
|
+
const scope = writes.getStore()
|
|
126
|
+
if (!scope)
|
|
127
|
+
return Outcome.forbidden(
|
|
128
|
+
'A page render reads content and never changes it: write from an action, a route, a job or an event.',
|
|
129
|
+
)
|
|
130
|
+
const who = await principal()
|
|
131
|
+
if (!who) return notActing()
|
|
132
|
+
return userActor(who, { via: scope.via, source: scope.source } as never)
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
const properties = async (typeKey: string): Promise<ValueProperty[]> =>
|
|
136
|
+
(await types.resolveProperties(typeKey)).map((p) => ({
|
|
137
|
+
alias: p.alias,
|
|
138
|
+
variesByCulture: p.variesByCulture,
|
|
139
|
+
}))
|
|
140
|
+
|
|
141
|
+
const read = async (key: string): Promise<SiteDocument | undefined> => {
|
|
142
|
+
const document = await repo.byKey(key)
|
|
143
|
+
if (!document || document.isTrashed) return undefined
|
|
144
|
+
return {
|
|
145
|
+
key: document.key,
|
|
146
|
+
contentType: document.contentTypeAlias,
|
|
147
|
+
parent: document.parentKey,
|
|
148
|
+
name: documentName(document),
|
|
149
|
+
values: fromDocumentValues(document.values, await properties(document.contentTypeKey)),
|
|
150
|
+
published: document.published,
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
const done = (key: string) => ok({ key })
|
|
155
|
+
|
|
156
|
+
return {
|
|
157
|
+
async get(key) {
|
|
158
|
+
const who = await principal()
|
|
159
|
+
if (!who) return notActing()
|
|
160
|
+
if (!UUID.test(key) || !(await canReadDocument(who, key, nodes))) return Outcome.notFound()
|
|
161
|
+
const found = await read(key)
|
|
162
|
+
return found ? ok(found) : Outcome.notFound()
|
|
163
|
+
},
|
|
164
|
+
|
|
165
|
+
async children(key) {
|
|
166
|
+
const who = await principal()
|
|
167
|
+
if (!who) return notActing()
|
|
168
|
+
if (key !== null && (!UUID.test(key) || !(await canReadDocument(who, key, nodes))))
|
|
169
|
+
return Outcome.notFound()
|
|
170
|
+
const page = await repo.children(key, 0, 10_000)
|
|
171
|
+
const out: SiteDocument[] = []
|
|
172
|
+
for (const row of page.items) {
|
|
173
|
+
const childKey = normaliseUuid(row.key)
|
|
174
|
+
if (!(await canReadDocument(who, childKey, nodes))) continue
|
|
175
|
+
const found = await read(childKey)
|
|
176
|
+
if (found) out.push(found)
|
|
177
|
+
}
|
|
178
|
+
return ok(out)
|
|
179
|
+
},
|
|
180
|
+
|
|
181
|
+
async create(input) {
|
|
182
|
+
const actor = await writer()
|
|
183
|
+
if (actor instanceof Outcome) return actor
|
|
184
|
+
const type = await types.byAlias(input.contentType)
|
|
185
|
+
if (!type)
|
|
186
|
+
return Outcome.unprocessableContent(
|
|
187
|
+
[{ field: 'contentType', message: `There is no content type "${input.contentType}".` }],
|
|
188
|
+
`There is no content type "${input.contentType}".`,
|
|
189
|
+
)
|
|
190
|
+
const converted = toDocumentValues(input.values ?? {}, await properties(type.key), {
|
|
191
|
+
culture: input.culture,
|
|
192
|
+
})
|
|
193
|
+
if ('errors' in converted)
|
|
194
|
+
return Outcome.unprocessableContent(converted.errors, 'Some values could not be placed.')
|
|
195
|
+
const key = crypto.randomUUID()
|
|
196
|
+
const result = await documents.create(actor, {
|
|
197
|
+
key,
|
|
198
|
+
contentTypeKey: type.key,
|
|
199
|
+
componentKey: type.defaultComponentKey,
|
|
200
|
+
parentKey: input.parent,
|
|
201
|
+
values: converted.values,
|
|
202
|
+
variants: [
|
|
203
|
+
{
|
|
204
|
+
culture: type.variesByCulture ? (input.culture ?? null) : null,
|
|
205
|
+
segment: null,
|
|
206
|
+
name: input.name,
|
|
207
|
+
},
|
|
208
|
+
],
|
|
209
|
+
})
|
|
210
|
+
return result.ok ? done(result.key) : outcomeOf(result)
|
|
211
|
+
},
|
|
212
|
+
|
|
213
|
+
async update(key, change) {
|
|
214
|
+
const actor = await writer()
|
|
215
|
+
if (actor instanceof Outcome) return actor
|
|
216
|
+
const existing = UUID.test(key) ? await repo.byKey(key) : undefined
|
|
217
|
+
if (!existing) return Outcome.notFound()
|
|
218
|
+
const converted = toDocumentValues(
|
|
219
|
+
change.values ?? {},
|
|
220
|
+
await properties(existing.contentTypeKey),
|
|
221
|
+
{ culture: change.culture, existing: existing.values },
|
|
222
|
+
)
|
|
223
|
+
if ('errors' in converted)
|
|
224
|
+
return Outcome.unprocessableContent(converted.errors, 'Some values could not be placed.')
|
|
225
|
+
const variants = existing.variants
|
|
226
|
+
.filter((v) => !v.segment)
|
|
227
|
+
.map((v) => ({
|
|
228
|
+
culture: v.culture,
|
|
229
|
+
segment: null,
|
|
230
|
+
name:
|
|
231
|
+
change.name !== undefined && (change.culture ?? null) === (v.culture ?? null)
|
|
232
|
+
? change.name
|
|
233
|
+
: v.name,
|
|
234
|
+
}))
|
|
235
|
+
if (
|
|
236
|
+
change.name !== undefined &&
|
|
237
|
+
change.culture &&
|
|
238
|
+
!variants.some((v) => v.culture === change.culture)
|
|
239
|
+
)
|
|
240
|
+
variants.push({ culture: change.culture, segment: null, name: change.name })
|
|
241
|
+
const result = await documents.save(
|
|
242
|
+
actor,
|
|
243
|
+
existing.key,
|
|
244
|
+
{
|
|
245
|
+
key: existing.key,
|
|
246
|
+
contentTypeKey: existing.contentTypeKey,
|
|
247
|
+
componentKey: existing.componentKey,
|
|
248
|
+
parentKey: existing.parentKey,
|
|
249
|
+
values: converted.values,
|
|
250
|
+
variants,
|
|
251
|
+
},
|
|
252
|
+
{ expectedRevision: existing.revision },
|
|
253
|
+
)
|
|
254
|
+
return result.ok ? done(existing.key) : outcomeOf(result)
|
|
255
|
+
},
|
|
256
|
+
|
|
257
|
+
async publish(key, options = {}) {
|
|
258
|
+
const actor = await writer()
|
|
259
|
+
if (actor instanceof Outcome) return actor
|
|
260
|
+
if (!UUID.test(key)) return Outcome.notFound()
|
|
261
|
+
const cultures = options.cultures ?? null
|
|
262
|
+
const result = await documents.publish(actor, key, { cultures })
|
|
263
|
+
return result.ok ? done(key) : outcomeOf(result)
|
|
264
|
+
},
|
|
265
|
+
|
|
266
|
+
async unpublish(key, options = {}) {
|
|
267
|
+
const actor = await writer()
|
|
268
|
+
if (actor instanceof Outcome) return actor
|
|
269
|
+
if (!UUID.test(key)) return Outcome.notFound()
|
|
270
|
+
const result = await documents.unpublish(actor, key, options.cultures ?? null)
|
|
271
|
+
return result.ok ? done(key) : outcomeOf(result)
|
|
272
|
+
},
|
|
273
|
+
|
|
274
|
+
async delete(key) {
|
|
275
|
+
const actor = await writer()
|
|
276
|
+
if (actor instanceof Outcome) return actor
|
|
277
|
+
if (!UUID.test(key)) return Outcome.notFound()
|
|
278
|
+
const result = await documents.trash(actor, key)
|
|
279
|
+
return result.ok ? done(key) : outcomeOf(result)
|
|
280
|
+
},
|
|
281
|
+
}
|
|
282
|
+
}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The site's own content event handlers (story 298): the config's `events`, by
|
|
3
|
+
* the names webhooks use. The outbox dispatcher queues a site job per event
|
|
4
|
+
* (`SITE_EVENT_JOB`), so a handler runs on a node that owns writes, retried as
|
|
5
|
+
* jobs are, with the site's tables and `site()`. docs/rendering.md, "Content events".
|
|
6
|
+
*/
|
|
7
|
+
import { WEBHOOK_EVENT_ALIASES } from '@crombolo/api-management/domain'
|
|
8
|
+
import type { SiteContentEvent, SiteServices } from '@crombolo/render'
|
|
9
|
+
import type { JobHandler, JobInfo } from './owner-jobs.ts'
|
|
10
|
+
import { withSiteWrites } from './site-content.ts'
|
|
11
|
+
|
|
12
|
+
/** What a site's event handler is given besides the event. */
|
|
13
|
+
export interface SiteEventContext {
|
|
14
|
+
/** The site's own tables, when it has any. */
|
|
15
|
+
db?: unknown
|
|
16
|
+
site: SiteServices
|
|
17
|
+
/** The job the event runs as: its id, its attempt, and how to report progress. */
|
|
18
|
+
job: JobInfo
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export type SiteEventHandler = (event: SiteContentEvent, context: SiteEventContext) => unknown
|
|
22
|
+
|
|
23
|
+
/** The site job each content event runs as. Not a `module.export`, so no site job can take it. */
|
|
24
|
+
export const SITE_EVENT_JOB = 'crombolo:event'
|
|
25
|
+
|
|
26
|
+
/** Why the config's `events` cannot be used. Pure. */
|
|
27
|
+
export function siteEventProblems(events: Readonly<Record<string, unknown>> | undefined): string[] {
|
|
28
|
+
const problems: string[] = []
|
|
29
|
+
for (const [alias, handler] of Object.entries(events ?? {})) {
|
|
30
|
+
if (!WEBHOOK_EVENT_ALIASES.has(alias))
|
|
31
|
+
problems.push(`The site handles "${alias}", which is not an event this site raises.`)
|
|
32
|
+
if (typeof handler !== 'function')
|
|
33
|
+
problems.push(`The site's handler for "${alias}" is not a function.`)
|
|
34
|
+
}
|
|
35
|
+
return problems
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** What a handler's own write is said to come from, so its event does not call it again. */
|
|
39
|
+
export const eventVia = (alias: string, key: string): string => `event ${alias} ${key}`
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Whether an event comes from a site event handler's write to the very page the
|
|
43
|
+
* handler was called for: the site does not hear of that, so a handler that
|
|
44
|
+
* updates its page is not called again for its own change. Pure.
|
|
45
|
+
*/
|
|
46
|
+
export function isOwnChange(event: { key: string; via?: string }): boolean {
|
|
47
|
+
const own = /^event \S+ (\S+)$/.exec(event.via ?? '')
|
|
48
|
+
return own !== null && (own[1] ?? '').toLowerCase() === event.key.toLowerCase()
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** The job that calls the site's handler for an event, as the event names the write. */
|
|
52
|
+
export function siteEventJob(events: Readonly<Record<string, SiteEventHandler>>): JobHandler {
|
|
53
|
+
return async (payload: SiteContentEvent, context: SiteEventContext) => {
|
|
54
|
+
const handler = events[payload.alias]
|
|
55
|
+
// A handler taken out of the config since: nothing to call, and nothing to retry.
|
|
56
|
+
if (!handler) return
|
|
57
|
+
await withSiteWrites({ via: eventVia(payload.alias, payload.key), source: 'job' }, () =>
|
|
58
|
+
handler(payload, {
|
|
59
|
+
...(context.db !== undefined ? { db: context.db } : {}),
|
|
60
|
+
site: context.site,
|
|
61
|
+
job: context.job,
|
|
62
|
+
}),
|
|
63
|
+
)
|
|
64
|
+
}
|
|
65
|
+
}
|
package/src/site-services.ts
CHANGED
|
@@ -19,6 +19,7 @@ import {
|
|
|
19
19
|
type PublishedCache,
|
|
20
20
|
type PublishedMedia,
|
|
21
21
|
type RequestMember,
|
|
22
|
+
type SiteContent,
|
|
22
23
|
type SiteJobs,
|
|
23
24
|
type SiteMembers,
|
|
24
25
|
type SiteQueries,
|
|
@@ -37,6 +38,8 @@ export interface SiteServicesDeps {
|
|
|
37
38
|
queries?: (
|
|
38
39
|
member: RequestMember | undefined | (() => Promise<RequestMember | undefined>),
|
|
39
40
|
) => SiteQueries
|
|
41
|
+
/** `site().content` (story 298): one for every caller, acting as the configured API user. */
|
|
42
|
+
content?: SiteContent
|
|
40
43
|
}
|
|
41
44
|
|
|
42
45
|
/** Builds `site()`'s services for one request; undefined `member` is a visitor or a previewing editor. */
|
|
@@ -110,6 +113,7 @@ export function createSiteServices(deps: SiteServicesDeps) {
|
|
|
110
113
|
return who ? `member ${who.username}` : 'a visitor'
|
|
111
114
|
}) ?? unavailableServices<SiteJobs>('jobs'),
|
|
112
115
|
members: unavailableServices<SiteMembers>('members'),
|
|
116
|
+
content: deps.content ?? unavailableServices<SiteContent>('content'),
|
|
113
117
|
}
|
|
114
118
|
return () => services
|
|
115
119
|
}
|