@crombolo/server 0.64.0 → 0.66.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.
Files changed (46) hide show
  1. package/package.json +15 -14
  2. package/src/access.ts +6 -2
  3. package/src/adapters/blueprints.ts +19 -5
  4. package/src/adapters/elements.ts +49 -36
  5. package/src/adapters/members.ts +37 -3
  6. package/src/adapters/users.ts +18 -0
  7. package/src/approvals.ts +44 -15
  8. package/src/atomic-write.ts +2 -2
  9. package/src/background-jobs.ts +170 -0
  10. package/src/bundle-admin.ts +39 -3
  11. package/src/bundle-reload.ts +2 -1
  12. package/src/bundles.ts +60 -25
  13. package/src/cli-tokens-api.ts +152 -0
  14. package/src/config.ts +52 -3
  15. package/src/content-events.ts +22 -0
  16. package/src/content-operations.ts +26 -1
  17. package/src/core.ts +357 -133
  18. package/src/extension-activity.ts +121 -0
  19. package/src/extension-components.ts +20 -4
  20. package/src/extension-discovery.ts +84 -65
  21. package/src/grant-trust.ts +6 -4
  22. package/src/index.ts +14 -0
  23. package/src/media-access.ts +30 -125
  24. package/src/media-library.ts +953 -0
  25. package/src/member-admin.ts +761 -0
  26. package/src/node-operations.ts +19 -2
  27. package/src/ports.ts +2 -0
  28. package/src/principal.ts +35 -0
  29. package/src/remote-background-jobs.ts +99 -0
  30. package/src/remote-credentials.ts +114 -6
  31. package/src/remote-extension-activity.ts +66 -0
  32. package/src/remote-media-library.ts +297 -0
  33. package/src/remote-media.ts +2 -2
  34. package/src/remote-members.ts +271 -0
  35. package/src/remote-undo.ts +234 -0
  36. package/src/remote-users.ts +229 -0
  37. package/src/remote.ts +141 -3
  38. package/src/routes.ts +22 -3
  39. package/src/seed/values.ts +82 -4
  40. package/src/seo.ts +81 -61
  41. package/src/server.ts +153 -92
  42. package/src/settings.ts +95 -6
  43. package/src/trusted-signers-admin.ts +39 -3
  44. package/src/undo.ts +358 -0
  45. package/src/user-admin.ts +581 -0
  46. package/src/view-as.ts +95 -0
package/src/routes.ts CHANGED
@@ -130,10 +130,12 @@ export function createRoutes<Member extends RouteMember>(
130
130
  declared: readonly DeclaredRoute[],
131
131
  deps: RouteDeps<Member>,
132
132
  ) {
133
- const compiled = declared.map((entry) => ({
133
+ const compile = (entry: DeclaredRoute) => ({
134
134
  ...entry,
135
135
  pattern: new URLPattern({ pathname: entry.route.path }),
136
- }))
136
+ })
137
+ const routes = [...declared]
138
+ const compiled = routes.map(compile)
137
139
  const defaultLimiter =
138
140
  deps.defaultPerMinute > 0
139
141
  ? new RateLimiter({ max: deps.defaultPerMinute, windowMs: MINUTE, now: deps.now })
@@ -433,9 +435,26 @@ export function createRoutes<Member extends RouteMember>(
433
435
  }
434
436
 
435
437
  return {
436
- routes: declared,
438
+ routes: routes as readonly DeclaredRoute[],
437
439
  match,
438
440
  invoke,
441
+ /**
442
+ * Adds routes while the server runs (story 346), checked against those
443
+ * already there; answers why they cannot be, and adds none then.
444
+ */
445
+ add(entries: readonly DeclaredRoute[]): string[] {
446
+ const problems = siteRouteProblems([...routes, ...entries], deps.backOfficePath)
447
+ if (problems.length > 0) return problems
448
+ routes.push(...entries)
449
+ compiled.push(...entries.map(compile))
450
+ return []
451
+ },
452
+ /** Takes out every route one owner declared. */
453
+ remove(owner: string): void {
454
+ for (const list of [routes, compiled])
455
+ for (let at = list.length - 1; at >= 0; at--)
456
+ if (list[at]?.owner === owner) list.splice(at, 1)
457
+ },
439
458
  /** A site request a route answers, or undefined for content finding to have it. */
440
459
  async handle(request: Request, url: URL): Promise<Response | undefined> {
441
460
  const found = match(url.pathname)
@@ -11,10 +11,17 @@ import {
11
11
  dateFromText,
12
12
  isBlockValue,
13
13
  normaliseUuid,
14
+ ObjectTypes,
14
15
  readBlocks,
15
16
  SINGLE_BLOCK_EDITOR_ALIAS,
16
17
  } from '@crombolo/core'
17
- import { ContentTypeRepository, DataTypeRepository, type Db, looksLikeKey } from '@crombolo/data'
18
+ import {
19
+ ContentTypeRepository,
20
+ DataTypeRepository,
21
+ type Db,
22
+ looksLikeKey,
23
+ resolveNodeRef,
24
+ } from '@crombolo/data'
18
25
  import { blockKey, pickKey } from './keys.ts'
19
26
 
20
27
  const isRecord = (value: unknown): value is Record<string, unknown> =>
@@ -33,27 +40,30 @@ export interface PropertyEditor {
33
40
  config: Record<string, unknown>
34
41
  }
35
42
 
43
+ type TypeKind = 'document' | 'media' | 'member'
44
+
36
45
  /** The site's types and their properties' editors, looked up once each. */
37
46
  export function schemaLookup(db: Db) {
38
47
  const repos = {
39
48
  document: new ContentTypeRepository(db),
40
49
  media: new ContentTypeRepository(db, { kind: 'media' }),
50
+ member: new ContentTypeRepository(db, { kind: 'member' }),
41
51
  }
42
52
  const dataTypes = new DataTypeRepository(db)
43
53
  const types = new Map<string, ContentTypeAggregate | undefined>()
44
54
  const editors = new Map<string, Map<string, PropertyEditor>>()
45
55
  return {
46
56
  repos,
47
- async typeOf(kind: 'document' | 'media', alias: string) {
57
+ async typeOf(kind: TypeKind, alias: string) {
48
58
  const key = `${kind}:${alias.toLowerCase()}`
49
59
  if (!types.has(key)) types.set(key, await repos[kind].byAlias(alias))
50
60
  return types.get(key)
51
61
  },
52
- async typeByKey(kind: 'document' | 'media', typeKey: string) {
62
+ async typeByKey(kind: TypeKind, typeKey: string) {
53
63
  return repos[kind].byKey(normaliseUuid(typeKey))
54
64
  },
55
65
  async editorsOf(
56
- kind: 'document' | 'media',
66
+ kind: TypeKind,
57
67
  type: Pick<ContentTypeAggregate, 'key'>,
58
68
  ): Promise<Map<string, PropertyEditor>> {
59
69
  const cached = editors.get(type.key)
@@ -91,6 +101,74 @@ export interface ValueRefs {
91
101
  linkedMedia(ref: string): Promise<string | undefined>
92
102
  }
93
103
 
104
+ const OBJECT_TYPES = {
105
+ content: ObjectTypes.Document,
106
+ library: ObjectTypes.Element,
107
+ media: ObjectTypes.Media,
108
+ } as const
109
+
110
+ /** What a value's paths name, in this site's database. */
111
+ export function siteValueRefs(db: Db): ValueRefs {
112
+ const keyOf = async (ref: string, kind: keyof typeof OBJECT_TYPES) => {
113
+ const resolved = await resolveNodeRef(db, [OBJECT_TYPES[kind]], ref)
114
+ return resolved.ok && resolved.node.objectType === OBJECT_TYPES[kind]
115
+ ? resolved.node.key
116
+ : undefined
117
+ }
118
+ return {
119
+ content: (ref) => keyOf(ref, 'content'),
120
+ library: (ref) => keyOf(ref, 'library'),
121
+ // A Library form by its path or key; anything else is a form's own alias, as before.
122
+ async form(ref) {
123
+ if (looksLikeKey(ref)) return normaliseUuid(ref)
124
+ const key = await keyOf(ref, 'library')
125
+ if (!key) return ref
126
+ const rows = await db.q
127
+ .selectFrom('node as n')
128
+ .innerJoin('content as c', 'c.node_id', 'n.id')
129
+ .innerJoin('content_type as ct', 'ct.node_id', 'c.content_type_id')
130
+ .select('ct.form_key')
131
+ .where('n.unique_id', '=', key)
132
+ .execute()
133
+ return rows[0]?.form_key ? key : undefined
134
+ },
135
+ linkedMedia: (ref) => keyOf(ref, 'media'),
136
+ async media(ref) {
137
+ const key = await keyOf(ref, 'media')
138
+ if (!key) return undefined
139
+ const rows = await db.q
140
+ .selectFrom('node as n')
141
+ .innerJoin('content as c', 'c.node_id', 'n.id')
142
+ .innerJoin('content_type as ct', 'ct.node_id', 'c.content_type_id')
143
+ .select('ct.alias')
144
+ .where('n.unique_id', '=', key)
145
+ .execute()
146
+ return { key, typeAlias: rows[0] ? String(rows[0].alias) : 'Image' }
147
+ },
148
+ }
149
+ }
150
+
151
+ const TEXTUAL = new Set([
152
+ 'Umbraco.TextBox',
153
+ 'Umbraco.TextArea',
154
+ 'Umbraco.RichText',
155
+ 'Umbraco.TinyMCE',
156
+ ])
157
+
158
+ /**
159
+ * A value as typed after `--set alias=`: text as it is for a text or rich text
160
+ * property, JSON where it reads as JSON for the rest (`true`, `3`,
161
+ * `["/a", "/b"]`), and the text itself otherwise, such as a path.
162
+ */
163
+ export function typedValue(editor: string, text: string): unknown {
164
+ if (TEXTUAL.has(editor)) return text
165
+ try {
166
+ return JSON.parse(text)
167
+ } catch {
168
+ return text
169
+ }
170
+ }
171
+
94
172
  /** The shorthand into each editor's stored shape. */
95
173
  export function valueWriter(lookup: SchemaLookup, refs: ValueRefs) {
96
174
  const trimPath = (ref: string) => ref.replace(/^\/+|\/+$/g, '')
package/src/seo.ts CHANGED
@@ -193,11 +193,7 @@ export interface SeoHostOptions {
193
193
  }
194
194
 
195
195
  export interface SeoHost {
196
- settings(): Promise<{
197
- effective: SeoSettings
198
- overrides: SeoSettingsOverrides
199
- sources: Record<keyof SeoSettings, SettingSource>
200
- }>
196
+ settings(): Promise<SeoSettingsState>
201
197
  siteDefaults(): Promise<SeoSiteDefaults>
202
198
  sitemap(request: Request, host: string): Promise<Response>
203
199
  robots(request: Request): Promise<Response>
@@ -224,23 +220,32 @@ export interface SeoHost {
224
220
  handle(request: Request, subpath: string, principal: Principal): Promise<Response | undefined>
225
221
  }
226
222
 
227
- export function createSeoHost(options: SeoHostOptions): SeoHost {
228
- const { db, config, cache } = options
229
- let memo: { at: number; overrides: SeoSettingsOverrides } | undefined
230
-
231
- const readOverrides = async (): Promise<SeoSettingsOverrides> => {
232
- if (memo && Date.now() - memo.at < SETTINGS_TTL_MS) return memo.overrides
233
- const raw = await readKeyValue(db, SEO_SETTINGS_KEY)
234
- let overrides: SeoSettingsOverrides = {}
235
- if (raw) {
236
- const parsed = parseSettingsBody(safeJson(raw))
237
- if (parsed.ok) overrides = parsed.overrides
238
- }
239
- memo = { at: Date.now(), overrides }
240
- return overrides
241
- }
223
+ /** The site-wide settings in force, what is saved, and where each value comes from. */
224
+ export interface SeoSettingsState {
225
+ effective: SeoSettings
226
+ overrides: SeoSettingsOverrides
227
+ sources: Record<keyof SeoSettings, SettingSource>
228
+ }
229
+
230
+ async function readOverrides(db: Db): Promise<SeoSettingsOverrides> {
231
+ const raw = await readKeyValue(db, SEO_SETTINGS_KEY)
232
+ if (!raw) return {}
233
+ const parsed = parseSettingsBody(safeJson(raw))
234
+ return parsed.ok ? parsed.overrides : {}
235
+ }
242
236
 
243
- const defaults = (): SeoSettings => ({
237
+ function resolveSettings(
238
+ config: Pick<CromboloConfig, 'siteName' | 'seo'>,
239
+ overrides: SeoSettingsOverrides,
240
+ ): SeoSettingsState {
241
+ const configured: Partial<SeoSettings> = {}
242
+ for (const field of FIELDS) {
243
+ const value = config.seo?.[field]
244
+ if (value === undefined) continue
245
+ if (field === 'notFoundPage') configured.notFoundPage = parseRules(value) ?? []
246
+ else (configured as Record<string, unknown>)[field] = value
247
+ }
248
+ const effective: SeoSettings = {
244
249
  sitemap: true,
245
250
  indexable: true,
246
251
  robotsTxt: DEFAULT_ROBOTS_TXT,
@@ -248,36 +253,60 @@ export function createSeoHost(options: SeoHostOptions): SeoHost {
248
253
  titleSuffix: '',
249
254
  defaultImage: '',
250
255
  notFoundPage: [],
251
- })
252
-
253
- const fromConfig = (): Partial<SeoSettings> => {
254
- const seo = config.seo ?? {}
255
- const out: Partial<SeoSettings> = {}
256
- for (const field of FIELDS) {
257
- const value = seo[field]
258
- if (value === undefined) continue
259
- if (field === 'notFoundPage') out.notFoundPage = parseRules(value) ?? []
260
- else (out as Record<string, unknown>)[field] = value
261
- }
262
- return out
263
256
  }
257
+ const sources = {} as Record<keyof SeoSettings, SettingSource>
258
+ for (const field of FIELDS) {
259
+ const own = overrides[field]
260
+ if (own !== undefined && own !== null) {
261
+ ;(effective as unknown as Record<string, unknown>)[field] = own
262
+ sources[field] = 'backoffice'
263
+ } else if (configured[field] !== undefined) {
264
+ ;(effective as unknown as Record<string, unknown>)[field] = configured[field]
265
+ sources[field] = 'config'
266
+ } else sources[field] = 'default'
267
+ }
268
+ return { effective, overrides, sources }
269
+ }
270
+
271
+ /** The site-wide settings: each a saved value, else the configuration's, else the default. */
272
+ export async function readSeoSettings(
273
+ db: Db,
274
+ config: Pick<CromboloConfig, 'siteName' | 'seo'>,
275
+ ): Promise<SeoSettingsState> {
276
+ return resolveSettings(config, await readOverrides(db))
277
+ }
278
+
279
+ /**
280
+ * Saves changes to the site-wide settings, a `null` removing a saved value so
281
+ * the configuration applies again; a malformed change is refused, saving nothing.
282
+ */
283
+ export async function saveSeoSettings(
284
+ db: Db,
285
+ config: Pick<CromboloConfig, 'siteName' | 'seo'>,
286
+ changes: unknown,
287
+ ): Promise<{ ok: true; settings: SeoSettingsState } | { ok: false; message: string }> {
288
+ const parsed = parseSettingsBody(changes)
289
+ if (!parsed.ok) return parsed
290
+ const merged: SeoSettingsOverrides = { ...(await readOverrides(db)) }
291
+ for (const field of FIELDS) {
292
+ if (!(field in parsed.overrides)) continue
293
+ const value = parsed.overrides[field]
294
+ if (value === null) delete merged[field]
295
+ else (merged as Record<string, unknown>)[field] = value
296
+ }
297
+ await writeKeyValue(db, SEO_SETTINGS_KEY, JSON.stringify(merged))
298
+ return { ok: true, settings: resolveSettings(config, merged) }
299
+ }
300
+
301
+ export function createSeoHost(options: SeoHostOptions): SeoHost {
302
+ const { db, config, cache } = options
303
+ let memo: { at: number; state: SeoSettingsState } | undefined
264
304
 
265
305
  const settings: SeoHost['settings'] = async () => {
266
- const overrides = await readOverrides()
267
- const configured = fromConfig()
268
- const effective = defaults()
269
- const sources = {} as Record<keyof SeoSettings, SettingSource>
270
- for (const field of FIELDS) {
271
- const own = overrides[field]
272
- if (own !== undefined && own !== null) {
273
- ;(effective as unknown as Record<string, unknown>)[field] = own
274
- sources[field] = 'backoffice'
275
- } else if (configured[field] !== undefined) {
276
- ;(effective as unknown as Record<string, unknown>)[field] = configured[field]
277
- sources[field] = 'config'
278
- } else sources[field] = 'default'
279
- }
280
- return { effective, overrides, sources }
306
+ if (memo && Date.now() - memo.at < SETTINGS_TTL_MS) return memo.state
307
+ const state = await readSeoSettings(db, config)
308
+ memo = { at: Date.now(), state }
309
+ return state
281
310
  }
282
311
 
283
312
  /** A media item's address when given its key, else the address as written. */
@@ -532,19 +561,10 @@ export function createSeoHost(options: SeoHostOptions): SeoHost {
532
561
  if (request.method === 'GET') return Response.json(await settings())
533
562
  if (request.method !== 'PUT')
534
563
  return new Response('Method Not Allowed', { status: 405, headers: { allow: 'GET, PUT' } })
535
- const parsed = parseSettingsBody(await request.json().catch(() => undefined))
536
- if (!parsed.ok) return Response.json({ message: parsed.message }, { status: 400 })
537
- memo = undefined
538
- const merged: SeoSettingsOverrides = { ...(await readOverrides()) }
539
- for (const field of FIELDS) {
540
- if (!(field in parsed.overrides)) continue
541
- const value = parsed.overrides[field]
542
- if (value === null) delete merged[field]
543
- else (merged as Record<string, unknown>)[field] = value
544
- }
545
- await writeKeyValue(db, SEO_SETTINGS_KEY, JSON.stringify(merged))
546
- memo = undefined
547
- return Response.json(await settings())
564
+ const saved = await saveSeoSettings(db, config, await request.json().catch(() => undefined))
565
+ if (!saved.ok) return Response.json({ message: saved.message }, { status: 400 })
566
+ memo = { at: Date.now(), state: saved.settings }
567
+ return Response.json(saved.settings)
548
568
  }
549
569
 
550
570
  return { settings, siteDefaults, sitemap, robots, notFound, details, sitemapItems, handle }