@crombolo/server 0.36.2 → 0.38.1
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 -13
- package/src/access.ts +29 -27
- package/src/adapters/audit.ts +1 -1
- package/src/adapters/blueprints.ts +22 -13
- package/src/adapters/content.ts +1 -1
- package/src/adapters/dictionary.ts +1 -1
- package/src/adapters/documents.ts +17 -10
- package/src/adapters/elements.ts +47 -37
- package/src/adapters/file-system.ts +1 -1
- package/src/adapters/health.ts +33 -5
- package/src/adapters/media.ts +12 -8
- package/src/adapters/member-groups.ts +8 -6
- package/src/adapters/members.ts +6 -4
- package/src/adapters/public-access.ts +7 -5
- package/src/adapters/redirects.ts +1 -1
- package/src/adapters/references.ts +1 -1
- package/src/adapters/relations.ts +1 -1
- package/src/adapters/schema-files.ts +33 -1
- package/src/adapters/search-index.ts +1 -1
- package/src/adapters/template-files.ts +6 -1
- package/src/adapters/template-query.ts +1 -1
- package/src/adapters/users.ts +13 -13
- package/src/adapters/webhooks.ts +1 -1
- package/src/anonymise-rules.ts +83 -0
- package/src/approvals-api.ts +1 -1
- package/src/approvals.ts +75 -38
- package/src/back-office-url.ts +20 -0
- package/src/backup.ts +26 -2
- package/src/bundle-code.ts +1 -1
- package/src/bundle-grants.ts +265 -0
- package/src/bundle-install.ts +13 -2
- package/src/bundle-media.ts +12 -11
- package/src/bundles.ts +258 -444
- package/src/component-snippets.ts +1 -1
- package/src/components.ts +48 -7
- package/src/config.ts +141 -4
- package/src/content-notifications.ts +13 -9
- package/src/content-operations.ts +23 -65
- package/src/content-query.ts +1 -1
- package/src/core.ts +663 -0
- package/src/cron.ts +139 -0
- package/src/custom-tables.ts +274 -0
- package/src/database.ts +22 -14
- package/src/dictionary-transfer.ts +1 -1
- package/src/git-routes.ts +1 -1
- package/src/identity-provider-overrides.ts +18 -16
- package/src/imaging.ts +65 -15
- package/src/index.ts +14 -1
- package/src/islands.ts +197 -0
- package/src/job-wake.ts +23 -0
- package/src/live-reload.ts +195 -0
- package/src/log-viewer.ts +6 -1
- package/src/marketplace.ts +82 -10
- package/src/media-access.ts +12 -9
- package/src/member-auth.ts +6 -4
- package/src/middleware.ts +236 -0
- package/src/models-builder.ts +1 -1
- package/src/node-operations.ts +122 -0
- package/src/owner-jobs.ts +428 -0
- package/src/ports.ts +39 -154
- package/src/preview-tokens.ts +6 -12
- package/src/remote.ts +3 -1
- package/src/routes.ts +420 -0
- package/src/schema.ts +8 -3
- package/src/seed/compile.ts +7 -5
- package/src/seed/export.ts +6 -4
- package/src/seo.ts +2 -2
- package/src/server.ts +866 -483
- package/src/settings.ts +49 -2
- package/src/site-data.ts +195 -0
- package/src/site-file.ts +30 -4
- package/src/site-queries.ts +140 -0
- package/src/site-replace.ts +25 -19
- package/src/site-sections.ts +1 -1
- package/src/site-services.ts +116 -0
- package/src/status-pages.ts +142 -0
- package/src/status.ts +11 -9
- package/src/url-settings.ts +1 -2
- package/src/webhook-files.ts +18 -1
- package/src/webhooks.ts +83 -15
- package/src/worker-watch.ts +73 -0
- package/src/worker.ts +138 -0
- package/src/bundle-tables.ts +0 -161
package/src/routes.ts
ADDED
|
@@ -0,0 +1,420 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Route handlers (story 211): a site's own endpoints and a server bundle's, at
|
|
3
|
+
* the paths they declare. One pipeline for both: the method, the rate limit,
|
|
4
|
+
* the member check, CSRF, the handler under a time limit, and its answer made a
|
|
5
|
+
* response — a `Result`'s value as JSON, an outcome as its status, an error as
|
|
6
|
+
* problem+json or the status page. docs/rendering.md, "Route handlers".
|
|
7
|
+
*/
|
|
8
|
+
import { type CorsPolicy, isPreflight, preflightResponse, withCors } from '@crombolo/api-delivery'
|
|
9
|
+
import {
|
|
10
|
+
type CookieOptions,
|
|
11
|
+
type FieldError,
|
|
12
|
+
isOutcome,
|
|
13
|
+
Ok,
|
|
14
|
+
type Outcome,
|
|
15
|
+
type RouteMethod,
|
|
16
|
+
type RouteOptions,
|
|
17
|
+
type SiteRoute,
|
|
18
|
+
} from '@crombolo/common'
|
|
19
|
+
import { ANTIFORGERY_HEADER, type PageOutcome, requestScope } from '@crombolo/render'
|
|
20
|
+
import { isSitePath, requestCookies } from './middleware.ts'
|
|
21
|
+
import { RateLimiter } from './rate-limit.ts'
|
|
22
|
+
|
|
23
|
+
/** A member as a route sees them: their key, for limits, and their group names. */
|
|
24
|
+
export interface RouteMember {
|
|
25
|
+
key: string
|
|
26
|
+
roles: readonly string[]
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export interface RouteDeps<Member extends RouteMember> {
|
|
30
|
+
backOfficePath: string
|
|
31
|
+
/** The handler's time limit; 0 for none. */
|
|
32
|
+
timeoutMs: number
|
|
33
|
+
/** The site-wide limit per caller a minute; 0 for none. */
|
|
34
|
+
defaultPerMinute: number
|
|
35
|
+
/** The site's services for a caller, the member looked up when asked. */
|
|
36
|
+
siteFor(member: () => Promise<Member | undefined>): () => unknown
|
|
37
|
+
/** The member signed in by cookie, and how to check their anti-forgery token. */
|
|
38
|
+
session(
|
|
39
|
+
request: Request,
|
|
40
|
+
): Promise<{ member: Member; verify(token: string | null): Promise<boolean> } | undefined>
|
|
41
|
+
/** The member a bearer token names. */
|
|
42
|
+
memberByToken?(token: string): Promise<Member | undefined>
|
|
43
|
+
callerAddress(request: Request): string
|
|
44
|
+
/** 206's status page for a request that prefers HTML. */
|
|
45
|
+
statusPage(request: Request, outcome: PageOutcome): Promise<Response>
|
|
46
|
+
logError(message: string, properties: Record<string, unknown>): void
|
|
47
|
+
showDetails: boolean
|
|
48
|
+
/** The origins a route with `cors: true` answers. */
|
|
49
|
+
cors?: CorsPolicy
|
|
50
|
+
now?: () => number
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** A route with what it needs added to its context, such as a bundle's capabilities. */
|
|
54
|
+
export interface DeclaredRoute {
|
|
55
|
+
route: SiteRoute
|
|
56
|
+
/** Who declared it, for errors and logs: the site, or a bundle by id. */
|
|
57
|
+
owner: string
|
|
58
|
+
extra?: (caller: { member?: RouteMember; via: 'cookie' | 'token' }) => Record<string, unknown>
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
const BEARER = /^Bearer\s+(\S+)$/i
|
|
62
|
+
const UNSAFE = new Set(['POST', 'PUT', 'PATCH', 'DELETE'])
|
|
63
|
+
const MINUTE = 60_000
|
|
64
|
+
|
|
65
|
+
/** Every reason a set of site routes cannot be mounted: reserved paths and two routes on one path. */
|
|
66
|
+
export function siteRouteProblems(
|
|
67
|
+
routes: readonly DeclaredRoute[],
|
|
68
|
+
backOfficePath: string,
|
|
69
|
+
): string[] {
|
|
70
|
+
const problems: string[] = []
|
|
71
|
+
const seen = new Map<string, string>()
|
|
72
|
+
for (const { route, owner } of routes) {
|
|
73
|
+
if (!route.path.startsWith('/') || route.path.startsWith('//'))
|
|
74
|
+
problems.push(`${owner}: the route "${route.path}" must be a path starting with /.`)
|
|
75
|
+
else if (!isSitePath(route.path.replace(/[:*(].*$/, ''), backOfficePath))
|
|
76
|
+
problems.push(
|
|
77
|
+
`${owner}: the route "${route.path}" is under one of crombolo's own paths (/umbraco, /crombolo, /media or the back office).`,
|
|
78
|
+
)
|
|
79
|
+
try {
|
|
80
|
+
new URLPattern({ pathname: route.path })
|
|
81
|
+
} catch {
|
|
82
|
+
problems.push(`${owner}: "${route.path}" is not a path pattern.`)
|
|
83
|
+
}
|
|
84
|
+
const key = route.path.toLowerCase().replace(/:[^/]+/g, ':')
|
|
85
|
+
const other = seen.get(key)
|
|
86
|
+
if (other) problems.push(`${owner} and ${other} both claim the route "${route.path}".`)
|
|
87
|
+
else seen.set(key, owner)
|
|
88
|
+
}
|
|
89
|
+
return problems
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** The methods a route answers, `HEAD` and `OPTIONS` included. */
|
|
93
|
+
function allowed(route: SiteRoute): string {
|
|
94
|
+
const methods = new Set(Object.keys(route.handlers))
|
|
95
|
+
if (methods.has('GET')) methods.add('HEAD')
|
|
96
|
+
methods.add('OPTIONS')
|
|
97
|
+
return [...methods].join(', ')
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
const TITLES: Record<number, string> = {
|
|
101
|
+
400: 'Bad Request',
|
|
102
|
+
401: 'Unauthorized',
|
|
103
|
+
403: 'Forbidden',
|
|
104
|
+
404: 'Not Found',
|
|
105
|
+
405: 'Method Not Allowed',
|
|
106
|
+
410: 'Gone',
|
|
107
|
+
422: 'Unprocessable Content',
|
|
108
|
+
429: 'Too Many Requests',
|
|
109
|
+
500: 'Internal Server Error',
|
|
110
|
+
504: 'Gateway Timeout',
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
const prefersHtml = (request: Request) => {
|
|
114
|
+
const accept = request.headers.get('accept') ?? ''
|
|
115
|
+
const html = accept.indexOf('text/html')
|
|
116
|
+
const json = accept.search(/application\/(problem\+)?json/)
|
|
117
|
+
return html >= 0 && (json < 0 || html < json)
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** Builds the site's route pipeline over its routes and its bundles'. */
|
|
121
|
+
export function createRoutes<Member extends RouteMember>(
|
|
122
|
+
declared: readonly DeclaredRoute[],
|
|
123
|
+
deps: RouteDeps<Member>,
|
|
124
|
+
) {
|
|
125
|
+
const compiled = declared.map((entry) => ({
|
|
126
|
+
...entry,
|
|
127
|
+
pattern: new URLPattern({ pathname: entry.route.path }),
|
|
128
|
+
}))
|
|
129
|
+
const defaultLimiter =
|
|
130
|
+
deps.defaultPerMinute > 0
|
|
131
|
+
? new RateLimiter({ max: deps.defaultPerMinute, windowMs: MINUTE, now: deps.now })
|
|
132
|
+
: undefined
|
|
133
|
+
const ownLimiters = new Map<SiteRoute, RateLimiter>()
|
|
134
|
+
const limiterFor = (route: SiteRoute): RateLimiter | undefined => {
|
|
135
|
+
const limit = route.options.rateLimit
|
|
136
|
+
if (limit === false) return undefined
|
|
137
|
+
if (!limit) return defaultLimiter
|
|
138
|
+
let own = ownLimiters.get(route)
|
|
139
|
+
if (!own) {
|
|
140
|
+
own = new RateLimiter({ max: limit.perMinute, windowMs: MINUTE, now: deps.now })
|
|
141
|
+
ownLimiters.set(route, own)
|
|
142
|
+
}
|
|
143
|
+
return own
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** A refusal or failure, as problem+json, or as the status page for a browser. */
|
|
147
|
+
const problem = async (
|
|
148
|
+
request: Request,
|
|
149
|
+
status: number,
|
|
150
|
+
details: {
|
|
151
|
+
message?: string
|
|
152
|
+
errors?: readonly FieldError[]
|
|
153
|
+
reference?: string
|
|
154
|
+
headers?: Record<string, string>
|
|
155
|
+
} = {},
|
|
156
|
+
): Promise<Response> => {
|
|
157
|
+
const headers = { 'cache-control': 'private, no-store', ...details.headers }
|
|
158
|
+
if (prefersHtml(request) && status !== 405 && status !== 429) {
|
|
159
|
+
const page = await deps.statusPage(request, {
|
|
160
|
+
status,
|
|
161
|
+
name: status === 500 ? 'serverError' : (TITLES[status] ?? 'error'),
|
|
162
|
+
message: details.message,
|
|
163
|
+
errors: details.errors ?? [],
|
|
164
|
+
...(details.reference ? { reference: details.reference } : {}),
|
|
165
|
+
})
|
|
166
|
+
const out = new Headers(page.headers)
|
|
167
|
+
for (const [name, value] of Object.entries(headers)) out.set(name, value)
|
|
168
|
+
return new Response(page.body, { status, headers: out })
|
|
169
|
+
}
|
|
170
|
+
return Response.json(
|
|
171
|
+
{
|
|
172
|
+
type: 'about:blank',
|
|
173
|
+
title: TITLES[status] ?? 'Error',
|
|
174
|
+
status,
|
|
175
|
+
...(details.message ? { detail: details.message } : {}),
|
|
176
|
+
...(details.errors?.length ? { errors: details.errors } : {}),
|
|
177
|
+
...(details.reference ? { reference: details.reference } : {}),
|
|
178
|
+
},
|
|
179
|
+
{ status, headers: { 'content-type': 'application/problem+json', ...headers } },
|
|
180
|
+
)
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
const fromOutcome = (request: Request, outcome: Outcome) =>
|
|
184
|
+
outcome.isRedirect
|
|
185
|
+
? new Response(null, {
|
|
186
|
+
status: outcome.status,
|
|
187
|
+
headers: { location: outcome.location as string, 'cache-control': 'no-store' },
|
|
188
|
+
})
|
|
189
|
+
: problem(request, outcome.status, { message: outcome.message, errors: outcome.errors })
|
|
190
|
+
|
|
191
|
+
/** Whether an unsafe, cookie-authenticated request came from a page of this site. */
|
|
192
|
+
const fromThisSite = async (
|
|
193
|
+
request: Request,
|
|
194
|
+
url: URL,
|
|
195
|
+
verify: (token: string | null) => Promise<boolean>,
|
|
196
|
+
): Promise<boolean> => {
|
|
197
|
+
const site = request.headers.get('sec-fetch-site')
|
|
198
|
+
if (site === 'same-origin') return true
|
|
199
|
+
const origin = request.headers.get('origin')
|
|
200
|
+
if (!site && origin && origin === url.origin) return true
|
|
201
|
+
if (await verify(request.headers.get(ANTIFORGERY_HEADER))) return true
|
|
202
|
+
const type = request.headers.get('content-type') ?? ''
|
|
203
|
+
if (/application\/x-www-form-urlencoded|multipart\/form-data/.test(type)) {
|
|
204
|
+
const form = await request
|
|
205
|
+
.clone()
|
|
206
|
+
.formData()
|
|
207
|
+
.catch(() => undefined)
|
|
208
|
+
const token = form?.get('__antiforgery')
|
|
209
|
+
if (typeof token === 'string' && (await verify(token))) return true
|
|
210
|
+
}
|
|
211
|
+
return false
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/**
|
|
215
|
+
* Answers a request with one route: everything but matching, which
|
|
216
|
+
* `handle` does for site routes and a bundle does for its back-office ones.
|
|
217
|
+
*/
|
|
218
|
+
async function invoke(
|
|
219
|
+
entry: DeclaredRoute,
|
|
220
|
+
request: Request,
|
|
221
|
+
url: URL,
|
|
222
|
+
params: Record<string, string>,
|
|
223
|
+
options: { checks: boolean; extra?: Record<string, unknown> } = { checks: true },
|
|
224
|
+
): Promise<Response> {
|
|
225
|
+
const policy = entry.route.options.cors ? deps.cors : undefined
|
|
226
|
+
if (!policy) return answer(entry, request, url, params, options)
|
|
227
|
+
if (isPreflight(request)) return preflightResponse(policy, request, allowed(entry.route))
|
|
228
|
+
return withCors(policy, request, await answer(entry, request, url, params, options))
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
async function answer(
|
|
232
|
+
entry: DeclaredRoute,
|
|
233
|
+
request: Request,
|
|
234
|
+
url: URL,
|
|
235
|
+
params: Record<string, string>,
|
|
236
|
+
options: { checks: boolean; extra?: Record<string, unknown> },
|
|
237
|
+
): Promise<Response> {
|
|
238
|
+
const { route } = entry
|
|
239
|
+
const method = request.method.toUpperCase() as RouteMethod
|
|
240
|
+
let handler = route.handlers[method]
|
|
241
|
+
if (!handler && method === 'HEAD') handler = route.handlers.GET
|
|
242
|
+
if (!handler && method === 'OPTIONS')
|
|
243
|
+
return new Response(null, { status: 204, headers: { allow: allowed(route) } })
|
|
244
|
+
if (!handler)
|
|
245
|
+
return problem(request, 405, {
|
|
246
|
+
message: `${url.pathname} answers ${allowed(route)}.`,
|
|
247
|
+
headers: { allow: allowed(route) },
|
|
248
|
+
})
|
|
249
|
+
|
|
250
|
+
// Who is calling: a bearer token, or the member's session cookie, looked up once.
|
|
251
|
+
const bearer = BEARER.exec(request.headers.get('authorization') ?? '')?.[1]
|
|
252
|
+
let identified:
|
|
253
|
+
| Promise<{ member: Member | undefined; verify?: (token: string | null) => Promise<boolean> }>
|
|
254
|
+
| undefined
|
|
255
|
+
const identify = () => {
|
|
256
|
+
identified ??= bearer
|
|
257
|
+
? (deps.memberByToken?.(bearer) ?? Promise.resolve(undefined)).then((member) => ({
|
|
258
|
+
member,
|
|
259
|
+
}))
|
|
260
|
+
: deps
|
|
261
|
+
.session(request)
|
|
262
|
+
.then((session) => ({ member: session?.member, verify: session?.verify }))
|
|
263
|
+
return identified
|
|
264
|
+
}
|
|
265
|
+
const member = async () => (await identify()).member
|
|
266
|
+
|
|
267
|
+
if (options.checks) {
|
|
268
|
+
const limiter = limiterFor(route)
|
|
269
|
+
if (limiter) {
|
|
270
|
+
const signedIn = await member()
|
|
271
|
+
const limit = route.options.rateLimit
|
|
272
|
+
const by = limit ? limit.by : undefined
|
|
273
|
+
const key =
|
|
274
|
+
signedIn && by !== 'caller'
|
|
275
|
+
? `member:${signedIn.key.toLowerCase()}`
|
|
276
|
+
: `caller:${deps.callerAddress(request)}`
|
|
277
|
+
const wait = limiter.take(key)
|
|
278
|
+
if (wait)
|
|
279
|
+
return problem(request, 429, {
|
|
280
|
+
message: 'Too many requests. Try again in a moment.',
|
|
281
|
+
headers: { 'retry-after': String(wait) },
|
|
282
|
+
})
|
|
283
|
+
}
|
|
284
|
+
const required = route.options.members
|
|
285
|
+
if (required) {
|
|
286
|
+
const signedIn = await member()
|
|
287
|
+
if (!signedIn) return problem(request, 401, { message: 'Sign in to continue.' })
|
|
288
|
+
if (
|
|
289
|
+
typeof required === 'object' &&
|
|
290
|
+
!required.groups.some((group) =>
|
|
291
|
+
signedIn.roles.some((role) => role.toLowerCase() === group.toLowerCase()),
|
|
292
|
+
)
|
|
293
|
+
)
|
|
294
|
+
return problem(request, 403, { message: 'Your account does not have access to this.' })
|
|
295
|
+
}
|
|
296
|
+
if (route.options.csrf !== false && UNSAFE.has(method) && !bearer) {
|
|
297
|
+
const { member: cookieMember, verify } = await identify()
|
|
298
|
+
if (cookieMember && verify && !(await fromThisSite(request, url, verify)))
|
|
299
|
+
return problem(request, 403, {
|
|
300
|
+
message:
|
|
301
|
+
'This request was refused because it did not come from a page of this site. Send it with crombolo.fetch from /crombolo/bundle.js, or include the anti-forgery token.',
|
|
302
|
+
})
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
const cookies: string[] = []
|
|
307
|
+
const deadline = new AbortController()
|
|
308
|
+
const signal = AbortSignal.any([request.signal, deadline.signal])
|
|
309
|
+
const site = deps.siteFor(member)
|
|
310
|
+
const context = {
|
|
311
|
+
params,
|
|
312
|
+
url,
|
|
313
|
+
cookies: requestCookies(request),
|
|
314
|
+
setCookie: (name: string, value: string, cookie: CookieOptions = {}) => {
|
|
315
|
+
const parts = [`${name}=${encodeURIComponent(value)}`, `Path=${cookie.path ?? '/'}`]
|
|
316
|
+
if (cookie.maxAge !== undefined) parts.push(`Max-Age=${Math.floor(cookie.maxAge)}`)
|
|
317
|
+
if (cookie.expires) parts.push(`Expires=${cookie.expires.toUTCString()}`)
|
|
318
|
+
if (cookie.domain) parts.push(`Domain=${cookie.domain}`)
|
|
319
|
+
if (cookie.secure ?? true) parts.push('Secure')
|
|
320
|
+
if (cookie.httpOnly ?? true) parts.push('HttpOnly')
|
|
321
|
+
parts.push(`SameSite=${cookie.sameSite ?? 'Lax'}`)
|
|
322
|
+
cookies.push(parts.join('; '))
|
|
323
|
+
},
|
|
324
|
+
site,
|
|
325
|
+
member,
|
|
326
|
+
signal,
|
|
327
|
+
...(entry.extra?.({ member: await member(), via: bearer ? 'token' : 'cookie' }) ?? {}),
|
|
328
|
+
...options.extra,
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
let timer: ReturnType<typeof setTimeout> | undefined
|
|
332
|
+
const overran = new Promise<'overran'>((resolve) => {
|
|
333
|
+
if (deps.timeoutMs > 0)
|
|
334
|
+
timer = setTimeout(() => {
|
|
335
|
+
deadline.abort(new Error(`${url.pathname} took longer than ${deps.timeoutMs}ms.`))
|
|
336
|
+
resolve('overran')
|
|
337
|
+
}, deps.timeoutMs)
|
|
338
|
+
})
|
|
339
|
+
let response: Response
|
|
340
|
+
try {
|
|
341
|
+
const work = Promise.resolve().then(() =>
|
|
342
|
+
requestScope({ headers: request.headers }, site, () => handler(request, context as never)),
|
|
343
|
+
)
|
|
344
|
+
work.catch(() => {})
|
|
345
|
+
const answer = await Promise.race([work, overran])
|
|
346
|
+
if (answer === 'overran')
|
|
347
|
+
response = await problem(request, 504, { message: 'This took too long to answer.' })
|
|
348
|
+
else if (answer instanceof Response) response = answer
|
|
349
|
+
else if (isOutcome(answer)) response = await fromOutcome(request, answer)
|
|
350
|
+
else if (answer instanceof Ok) response = Response.json(answer.value)
|
|
351
|
+
else
|
|
352
|
+
throw new Error(
|
|
353
|
+
`${entry.owner}'s ${method} ${route.path} answered with neither a Response nor a Result.`,
|
|
354
|
+
)
|
|
355
|
+
} catch (error) {
|
|
356
|
+
if (isOutcome(error)) response = await fromOutcome(request, error)
|
|
357
|
+
else {
|
|
358
|
+
const reference = crypto.randomUUID().replaceAll('-', '').slice(0, 10).toUpperCase()
|
|
359
|
+
const message = error instanceof Error ? error.message : String(error)
|
|
360
|
+
deps.logError(
|
|
361
|
+
'The route {method} {path} ({owner}) failed, reference {reference}: {error}',
|
|
362
|
+
{
|
|
363
|
+
method,
|
|
364
|
+
path: url.pathname,
|
|
365
|
+
owner: entry.owner,
|
|
366
|
+
reference,
|
|
367
|
+
error: error instanceof Error ? (error.stack ?? message) : message,
|
|
368
|
+
},
|
|
369
|
+
)
|
|
370
|
+
response = await problem(request, 500, {
|
|
371
|
+
reference,
|
|
372
|
+
...(deps.showDetails ? { message } : {}),
|
|
373
|
+
})
|
|
374
|
+
}
|
|
375
|
+
} finally {
|
|
376
|
+
clearTimeout(timer)
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
const headers = new Headers(response.headers)
|
|
380
|
+
for (const cookie of cookies) headers.append('set-cookie', cookie)
|
|
381
|
+
// Kept only where the handler said so, and only for a read.
|
|
382
|
+
if (!headers.has('cache-control') || (method !== 'GET' && method !== 'HEAD'))
|
|
383
|
+
headers.set('cache-control', 'private, no-store')
|
|
384
|
+
const body = method === 'HEAD' ? null : response.body
|
|
385
|
+
return new Response(body, { status: response.status, statusText: response.statusText, headers })
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
/** The route a site path matches, with its params. */
|
|
389
|
+
function match(pathname: string) {
|
|
390
|
+
for (const entry of compiled) {
|
|
391
|
+
const found = entry.pattern.exec({ pathname })
|
|
392
|
+
if (found)
|
|
393
|
+
return {
|
|
394
|
+
entry,
|
|
395
|
+
params: Object.fromEntries(
|
|
396
|
+
Object.entries(found.pathname.groups).filter(
|
|
397
|
+
(pair): pair is [string, string] =>
|
|
398
|
+
typeof pair[1] === 'string' && !/^\d+$/.test(pair[0]),
|
|
399
|
+
),
|
|
400
|
+
),
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
return undefined
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
return {
|
|
407
|
+
routes: declared,
|
|
408
|
+
match,
|
|
409
|
+
invoke,
|
|
410
|
+
/** A site request a route answers, or undefined for content finding to have it. */
|
|
411
|
+
async handle(request: Request, url: URL): Promise<Response | undefined> {
|
|
412
|
+
const found = match(url.pathname)
|
|
413
|
+
if (!found) return undefined
|
|
414
|
+
return invoke(found.entry, request, url, found.params)
|
|
415
|
+
},
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
export type SiteRoutes = ReturnType<typeof createRoutes>
|
|
420
|
+
export type { RouteOptions }
|
package/src/schema.ts
CHANGED
|
@@ -252,7 +252,8 @@ export interface CachePollerOptions {
|
|
|
252
252
|
*/
|
|
253
253
|
content?: {
|
|
254
254
|
served(): { checkpoint: number | undefined; builtAt: Date } | undefined
|
|
255
|
-
|
|
255
|
+
/** Resolves once the rebuild it starts has finished, so a poll ends caught up. */
|
|
256
|
+
behind(latest: number): Promise<void> | void
|
|
256
257
|
/**
|
|
257
258
|
* Told that every change from the one it serves up to `checkpoint` left the
|
|
258
259
|
* pages alone — media only (story 197) — so its snapshot holds them too.
|
|
@@ -302,6 +303,7 @@ export class CacheInstructionPoller {
|
|
|
302
303
|
#paused: WritesPaused | undefined
|
|
303
304
|
/** The checkpoint this node last asked its cache to catch up to, and when. */
|
|
304
305
|
#asked: { checkpoint: number; at: number } | undefined
|
|
306
|
+
#catchingUp: Promise<void> | void = undefined
|
|
305
307
|
#latest: number | undefined
|
|
306
308
|
/** The checkpoint whose changes have all been read for the caches; undefined before the start. */
|
|
307
309
|
#followed: number | undefined
|
|
@@ -400,7 +402,10 @@ export class CacheInstructionPoller {
|
|
|
400
402
|
}
|
|
401
403
|
for (const id of this.#seen) if (id <= this.#cursor - CURSOR_WINDOW) this.#seen.delete(id)
|
|
402
404
|
await this.#follow(latest)
|
|
403
|
-
|
|
405
|
+
this.#catchUp(latest)
|
|
406
|
+
await this.#catchingUp
|
|
407
|
+
this.#catchingUp = undefined
|
|
408
|
+
const served = this.#options.content?.served()
|
|
404
409
|
await touchServer(db, {
|
|
405
410
|
nodeId,
|
|
406
411
|
...nodeState,
|
|
@@ -480,7 +485,7 @@ export class CacheInstructionPoller {
|
|
|
480
485
|
const asked = this.#asked
|
|
481
486
|
if (!asked || asked.checkpoint < latest || Date.now() - asked.at > REASK_AFTER_MS) {
|
|
482
487
|
this.#asked = { checkpoint: latest, at: Date.now() }
|
|
483
|
-
content.behind(latest)
|
|
488
|
+
this.#catchingUp = content.behind(latest)
|
|
484
489
|
}
|
|
485
490
|
return served
|
|
486
491
|
}
|
package/src/seed/compile.ts
CHANGED
|
@@ -170,11 +170,13 @@ export async function compileSeed(db: Db, config: CromboloConfig): Promise<SeedB
|
|
|
170
170
|
return { key: keyOf.get(seeded) as string, typeAlias: mediaTypeAlias.get(seeded) ?? 'Image' }
|
|
171
171
|
const key = looksLikeKey(ref) ? normaliseUuid(ref) : await siteNode(ref, ObjectTypes.Media, why)
|
|
172
172
|
if (!key) return undefined
|
|
173
|
-
const rows = await db.
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
173
|
+
const rows = await db.q
|
|
174
|
+
.selectFrom('node as n')
|
|
175
|
+
.innerJoin('content as c', 'c.node_id', 'n.id')
|
|
176
|
+
.innerJoin('content_type as ct', 'ct.node_id', 'c.content_type_id')
|
|
177
|
+
.select('ct.alias')
|
|
178
|
+
.where('n.unique_id', '=', key)
|
|
179
|
+
.execute()
|
|
178
180
|
return { key, typeAlias: rows[0] ? String(rows[0].alias) : 'Image' }
|
|
179
181
|
}
|
|
180
182
|
const libraryKey = async (ref: string, why: string) => {
|
package/src/seed/export.ts
CHANGED
|
@@ -114,10 +114,12 @@ export async function exportSeed(
|
|
|
114
114
|
const aliasOf = async (typeKey: string) => {
|
|
115
115
|
const key = normaliseUuid(typeKey)
|
|
116
116
|
if (!typeAliases.has(key)) {
|
|
117
|
-
const rows = await db.
|
|
118
|
-
'
|
|
119
|
-
|
|
120
|
-
|
|
117
|
+
const rows = await db.q
|
|
118
|
+
.selectFrom('node as n')
|
|
119
|
+
.innerJoin('content_type as ct', 'ct.node_id', 'n.id')
|
|
120
|
+
.select('ct.alias')
|
|
121
|
+
.where('n.unique_id', '=', key)
|
|
122
|
+
.execute()
|
|
121
123
|
typeAliases.set(key, rows[0] ? String(rows[0].alias) : typeKey)
|
|
122
124
|
}
|
|
123
125
|
return typeAliases.get(key) as string
|
package/src/seo.ts
CHANGED
|
@@ -6,8 +6,8 @@
|
|
|
6
6
|
* backoffice; an override is stored in `key_value` as JSON, field by field, so
|
|
7
7
|
* clearing one falls back to the config again.
|
|
8
8
|
*/
|
|
9
|
-
import type { Principal } from '@crombolo/api-management'
|
|
10
|
-
import { hasSection } from '@crombolo/api-management'
|
|
9
|
+
import type { Principal } from '@crombolo/api-management/domain'
|
|
10
|
+
import { hasSection } from '@crombolo/api-management/domain'
|
|
11
11
|
import { SYSTEM_CONTENT_TYPE_KEYS } from '@crombolo/core'
|
|
12
12
|
import { ContentTypeRepository, type Db, readKeyValue, writeKeyValue } from '@crombolo/data'
|
|
13
13
|
import {
|