@crombolo/server 0.53.2 → 0.55.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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@crombolo/server",
3
- "version": "0.53.2",
3
+ "version": "0.55.0",
4
4
  "description": "Internal to crombolo, with no compatibility promise: use @crombolo/crombolo. The crombolo HTTP server: routing, configuration, media stores and background jobs.",
5
5
  "license": "MIT",
6
6
  "author": "Crombolo",
@@ -31,18 +31,18 @@
31
31
  "access": "public"
32
32
  },
33
33
  "dependencies": {
34
- "@crombolo/api-delivery": "0.53.2",
35
- "@crombolo/api-management": "0.53.2",
36
- "@crombolo/auth": "0.53.2",
37
- "@crombolo/backoffice-host": "0.53.2",
38
- "@crombolo/common": "0.53.2",
39
- "@crombolo/content": "0.53.2",
40
- "@crombolo/contracts": "0.53.2",
41
- "@crombolo/core": "0.53.2",
42
- "@crombolo/data": "0.53.2",
43
- "@crombolo/render": "0.53.2",
44
- "@crombolo/schema": "0.53.2",
45
- "@crombolo/transfer": "0.53.2",
34
+ "@crombolo/api-delivery": "0.55.0",
35
+ "@crombolo/api-management": "0.55.0",
36
+ "@crombolo/auth": "0.55.0",
37
+ "@crombolo/backoffice-host": "0.55.0",
38
+ "@crombolo/common": "0.55.0",
39
+ "@crombolo/content": "0.55.0",
40
+ "@crombolo/contracts": "0.55.0",
41
+ "@crombolo/core": "0.55.0",
42
+ "@crombolo/data": "0.55.0",
43
+ "@crombolo/render": "0.55.0",
44
+ "@crombolo/schema": "0.55.0",
45
+ "@crombolo/transfer": "0.55.0",
46
46
  "@logtape/logtape": "^2.3.8",
47
47
  "@opentelemetry/api": "1.10.0",
48
48
  "@opentelemetry/context-async-hooks": "3.0.0",
@@ -145,6 +145,18 @@ export async function handleApprovalsApi(
145
145
  return json(await approvals.finished(principal, skip, take))
146
146
  }
147
147
 
148
+ if (path === 'requests' && request.method === 'GET') {
149
+ const url = new URL(request.url)
150
+ const skip = Math.max(0, Number(url.searchParams.get('skip') ?? 0) || 0)
151
+ const take = Math.min(100, Math.max(1, Number(url.searchParams.get('take') ?? 25) || 25))
152
+ const flag = (name: string, otherwise: boolean) => {
153
+ const value = url.searchParams.get(name)
154
+ return value === null ? otherwise : value === 'true'
155
+ }
156
+ const include = { pending: flag('pending', true), decided: flag('decided', false) }
157
+ return json(await approvals.requests(principal, include, skip, take))
158
+ }
159
+
148
160
  // Whether Approvals and a page's Workflow tab show: a workflow, or a request still open.
149
161
  if (path === 'active' && request.method === 'GET') {
150
162
  const active =
package/src/approvals.ts CHANGED
@@ -203,6 +203,13 @@ export interface Approvals {
203
203
  skip: number,
204
204
  take: number,
205
205
  ): Promise<{ total: number; items: RequestView[] }>
206
+ /** One page of requests: the pending first, oldest first, then the decided, newest first. */
207
+ requests(
208
+ principal: Principal,
209
+ include: { pending: boolean; decided: boolean },
210
+ skip: number,
211
+ take: number,
212
+ ): Promise<{ total: number; items: RequestView[] }>
206
213
  }
207
214
 
208
215
  const SWEEP_GRACE_MS = 5 * 60_000
@@ -1167,6 +1174,22 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
1167
1174
  items: await Promise.all(page.items.map((r) => view(principal, r))),
1168
1175
  }
1169
1176
  },
1177
+
1178
+ async requests(principal, include, skip, take) {
1179
+ const pending = include.pending ? await requests().open() : []
1180
+ const shown = pending.slice(skip, skip + take)
1181
+ const decidedSkip = Math.max(0, skip - pending.length)
1182
+ const decidedTake = take - shown.length
1183
+ // Asked even for none, since its total counts toward the pages.
1184
+ const decided = include.decided
1185
+ ? await requests().finished(decidedSkip, Math.max(1, decidedTake))
1186
+ : { total: 0, items: [] }
1187
+ const page = [...shown, ...(decidedTake > 0 ? decided.items : [])]
1188
+ return {
1189
+ total: pending.length + decided.total,
1190
+ items: await Promise.all(page.map((r) => view(principal, r))),
1191
+ }
1192
+ },
1170
1193
  }
1171
1194
  }
1172
1195
 
@@ -0,0 +1,56 @@
1
+ /**
2
+ * `<backoffice>/crombolo/api/templates` (outside the contract): every component
3
+ * on disk, for a page's template picker, with the template a content type would
4
+ * name it by, where it has one. A component nothing names yet has no template
5
+ * row; registering one makes the row, as the schema sync would when a type first
6
+ * names it, and leaves the file alone.
7
+ */
8
+ import { hasSection, type Principal } from '@crombolo/api-management'
9
+ import { ComponentRepository, type Db } from '@crombolo/data'
10
+ import { listComponents } from './components.ts'
11
+
12
+ export interface ComponentTemplate {
13
+ alias: string
14
+ /** The template's key, or null for a component no template row names yet. */
15
+ id: string | null
16
+ }
17
+
18
+ /** Every component on disk and every template row, joined by alias, by alias. Pure. */
19
+ export function componentTemplates(
20
+ onDisk: readonly string[],
21
+ rows: readonly { key: string; alias: string }[],
22
+ ): ComponentTemplate[] {
23
+ const keys = new Map(rows.map((row) => [row.alias, row.key]))
24
+ const aliases = new Set([...onDisk, ...rows.map((row) => row.alias)])
25
+ return [...aliases].sort().map((alias) => ({ alias, id: keys.get(alias) ?? null }))
26
+ }
27
+
28
+ export async function handleComponentTemplates(
29
+ request: Request,
30
+ principal: Principal,
31
+ options: { db: Db; componentsDir: string },
32
+ ): Promise<Response> {
33
+ const repo = new ComponentRepository(options.db)
34
+ const onDisk = listComponents(options.componentsDir).map((file) => file.alias)
35
+
36
+ if (request.method === 'GET')
37
+ return Response.json({ items: componentTemplates(onDisk, await repo.all()) })
38
+
39
+ if (request.method === 'POST') {
40
+ // As changing which templates a type allows: Structure, which Settings brings.
41
+ if (!hasSection(principal, 'structure') && !hasSection(principal, 'settings'))
42
+ return Response.json(
43
+ { message: 'Making a component a template needs access to Structure.' },
44
+ { status: 403 },
45
+ )
46
+ const body = (await request.json().catch(() => ({}))) as { alias?: unknown }
47
+ const alias = typeof body.alias === 'string' ? body.alias : ''
48
+ if (!onDisk.includes(alias))
49
+ return Response.json({ message: 'There is no component with that name.' }, { status: 404 })
50
+ const existing = await repo.byAlias(alias)
51
+ if (existing) return Response.json({ id: existing.key })
52
+ const saved = await repo.save({ key: crypto.randomUUID(), name: alias, alias, content: null })
53
+ return Response.json({ id: saved.key }, { status: 201 })
54
+ }
55
+ return new Response('Method Not Allowed', { status: 405 })
56
+ }
package/src/config.ts CHANGED
@@ -1091,7 +1091,7 @@ export function describeDatabase(
1091
1091
  }
1092
1092
  }
1093
1093
 
1094
- export const VERSION = '0.53.2'
1094
+ export const VERSION = '0.55.0'
1095
1095
 
1096
1096
  /** A whole number of seconds from the environment; undefined when unset or not one. */
1097
1097
  /** A positive number from a setting, else the default. */
package/src/database.ts CHANGED
@@ -4,6 +4,7 @@
4
4
  * Migration and seeding run at startup rather than through the install wizard;
5
5
  * the wizard is story 080. Both are idempotent, so restarting is safe.
6
6
  */
7
+
7
8
  import { hashPassword, passwordConfigJson } from '@crombolo/auth'
8
9
  import {
9
10
  connect,
@@ -25,6 +26,7 @@ import {
25
26
  import { ensureApiClient } from './api-client.ts'
26
27
  import { type CromboloConfig, runsOnLocalhost } from './config.ts'
27
28
  import { migrateTables, pendingTablesSteps, type TablesChain } from './custom-tables.ts'
29
+ import { upgradeFormWords } from './form-word-upgrade.ts'
28
30
  import { logger } from './logging.ts'
29
31
  import { linkMediaFolders } from './media-folders.ts'
30
32
 
@@ -164,6 +166,13 @@ export async function installDatabase(
164
166
  await migrate(db, cromboloPlan, { by: config.nodeId })
165
167
  // Core first, so a bundle step always runs against a core it declared itself compatible with.
166
168
  await migrateTables(db, config, chains, { by: config.nodeId })
169
+ // Forms' `#key` is `{#key}` now (story 297). A shared schema store is left to
170
+ // the designer's next save, which writes it the new way.
171
+ if (config.schemaWritable && !config.schemaStore) {
172
+ const upgraded = await upgradeFormWords(db, config.schemaDir)
173
+ if (upgraded.length > 0)
174
+ logger('install').info(`Wrote dictionary words as {#key} in ${upgraded.length} form file(s)`)
175
+ }
167
176
 
168
177
  // In production a password is never made up: the pipeline supplies one, or
169
178
  // the owner sets the site up in the browser (docs/operations.md). With an API
@@ -0,0 +1,119 @@
1
+ /**
2
+ * `<backoffice>/crombolo/api/dictionary/…` (story 297): what a `{#key}` chip shows
3
+ * and changes. Anyone signed in reads the items and their words; changing them
4
+ * asks for Translation or Settings, as Umbraco's dictionary editor does. Outside
5
+ * the contract.
6
+ */
7
+ import { hasSection, type Principal } from '@crombolo/api-management'
8
+ import {
9
+ appendCacheInstruction,
10
+ type Db,
11
+ DictionaryRepository,
12
+ LanguageRepository,
13
+ } from '@crombolo/data'
14
+
15
+ export interface DictionaryWordsOptions {
16
+ db: Db
17
+ /** Tells this node's cache the dictionary changed. */
18
+ onChange?: () => void
19
+ nodeId?: string
20
+ }
21
+
22
+ /** The words of each language for the editor: every language, '' where none is set. Pure. */
23
+ export function wordsByLanguage(
24
+ languages: readonly { isoCode: string; cultureName: string; isDefault: boolean }[],
25
+ translations: readonly { isoCode: string; translation: string }[],
26
+ ): { isoCode: string; name: string; isDefault: boolean; text: string }[] {
27
+ const text = new Map(translations.map((t) => [t.isoCode.toLowerCase(), t.translation]))
28
+ return [...languages]
29
+ .sort(
30
+ (a, b) =>
31
+ Number(b.isDefault) - Number(a.isDefault) || a.cultureName.localeCompare(b.cultureName),
32
+ )
33
+ .map((l) => ({
34
+ isoCode: l.isoCode,
35
+ name: l.cultureName,
36
+ isDefault: l.isDefault,
37
+ text: text.get(l.isoCode.toLowerCase()) ?? '',
38
+ }))
39
+ }
40
+
41
+ export async function handleDictionaryWords(
42
+ request: Request,
43
+ path: string,
44
+ principal: Principal,
45
+ options: DictionaryWordsOptions,
46
+ ): Promise<Response | undefined> {
47
+ const { db } = options
48
+ const repo = new DictionaryRepository(db)
49
+ const languages = await new LanguageRepository(db).all()
50
+ const defaultIso = languages.find((l) => l.isDefault)?.isoCode.toLowerCase()
51
+
52
+ if (path === '/words' && request.method === 'GET') {
53
+ const items = await repo.all()
54
+ return Response.json({
55
+ words: items
56
+ .map((item) => ({
57
+ name: item.name,
58
+ text:
59
+ item.translations.find((t) => t.isoCode.toLowerCase() === defaultIso)?.translation ??
60
+ '',
61
+ }))
62
+ .sort((a, b) => a.name.localeCompare(b.name)),
63
+ })
64
+ }
65
+
66
+ const match = /^\/words\/([^/]+)$/.exec(path)
67
+ if (!match) return undefined
68
+ const item = await repo.byName(decodeURIComponent(match[1] as string))
69
+ if (!item) return Response.json({ message: 'No dictionary item has this name.' }, { status: 404 })
70
+ // As the Management API's dictionary: Translation, or Settings.
71
+ const mayChange = hasSection(principal, 'translation') || hasSection(principal, 'settings')
72
+
73
+ if (request.method === 'GET')
74
+ return Response.json({
75
+ name: item.name,
76
+ mayChange,
77
+ languages: wordsByLanguage(languages, item.translations),
78
+ })
79
+
80
+ if (request.method === 'PUT') {
81
+ if (!mayChange)
82
+ return Response.json(
83
+ { message: 'Changing the dictionary needs access to Translation.' },
84
+ { status: 403 },
85
+ )
86
+ const body = (await request.json().catch(() => ({}))) as { words?: unknown }
87
+ const given = body.words && typeof body.words === 'object' ? body.words : {}
88
+ const known = new Map(languages.map((l) => [l.isoCode.toLowerCase(), l.isoCode]))
89
+ const next = new Map(item.translations.map((t) => [t.isoCode.toLowerCase(), t]))
90
+ for (const [iso, text] of Object.entries(given as Record<string, unknown>)) {
91
+ const isoCode = known.get(iso.toLowerCase())
92
+ if (!isoCode || typeof text !== 'string')
93
+ return Response.json({ message: `There is no language ${iso}.` }, { status: 400 })
94
+ if (text.trim()) next.set(isoCode.toLowerCase(), { isoCode, translation: text })
95
+ else next.delete(isoCode.toLowerCase())
96
+ }
97
+ const result = await db.transaction(async (tx) => {
98
+ const done = await new DictionaryRepository(tx).update(item.key, {
99
+ name: item.name,
100
+ translations: [...next.values()],
101
+ })
102
+ if (done === 'Success')
103
+ await appendCacheInstruction(tx, {
104
+ kind: 'content',
105
+ payload: { dictionary: true },
106
+ by: options.nodeId,
107
+ })
108
+ return done
109
+ })
110
+ if (result !== 'Success') return Response.json({ message: result }, { status: 400 })
111
+ options.onChange?.()
112
+ return Response.json({
113
+ name: item.name,
114
+ mayChange,
115
+ languages: wordsByLanguage(languages, [...next.values()]),
116
+ })
117
+ }
118
+ return new Response('Method Not Allowed', { status: 405 })
119
+ }
@@ -0,0 +1,69 @@
1
+ /**
2
+ * Forms wrote a dictionary item as a whole text of `#key` (story 293); they write
3
+ * `{#key}` now (story 297). On a site whose schema it may write, the server
4
+ * rewrites each such text that names an item, in place, so a file keeps its
5
+ * layout and comments. A `#` naming no item is only text, and is left alone.
6
+ */
7
+ import { readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs'
8
+ import { join } from 'node:path'
9
+ import { type Db, DictionaryRepository } from '@crombolo/data'
10
+
11
+ /** The keys a form file holds words under: a choice's value is compared, never read. */
12
+ const WORD_KEYS = [
13
+ 'caption',
14
+ 'help-text',
15
+ 'placeholder',
16
+ 'content',
17
+ 'mandatory-message',
18
+ 'pattern-message',
19
+ 'submit-label',
20
+ 'next-label',
21
+ 'previous-label',
22
+ 'message-on-submit',
23
+ ]
24
+
25
+ /** `key = "#name"`, the whole string `#name`, in either kind of quotes. */
26
+ const BARE = new RegExp(
27
+ `^(\\s*(?:${WORD_KEYS.join('|')})\\s*=\\s*)(["'])#([^\\s"'{}]+)\\2(\\s*(?:#.*)?)$`,
28
+ 'gm',
29
+ )
30
+
31
+ /** The file's text with each word written `"#key"` that names an item as `"{#key}"`. Pure. */
32
+ export function braceFormWords(text: string, isItem: (name: string) => boolean): string {
33
+ return text.replace(BARE, (whole, start: string, quote: string, name: string, end: string) =>
34
+ isItem(name) ? `${start}${quote}{#${name}}${quote}${end}` : whole,
35
+ )
36
+ }
37
+
38
+ function tomlFiles(dir: string): string[] {
39
+ let entries: string[]
40
+ try {
41
+ entries = readdirSync(dir)
42
+ } catch {
43
+ return []
44
+ }
45
+ return entries.flatMap((name) => {
46
+ const path = join(dir, name)
47
+ if (statSync(path).isDirectory()) return tomlFiles(path)
48
+ return name.endsWith('.toml') ? [path] : []
49
+ })
50
+ }
51
+
52
+ /** Rewrites the forms under `schemaDir`; the files it changed. */
53
+ export async function upgradeFormWords(db: Db, schemaDir: string): Promise<string[]> {
54
+ const files = tomlFiles(join(schemaDir, 'forms'))
55
+ if (files.length === 0) return []
56
+ const names = new Set(
57
+ (await new DictionaryRepository(db).outline()).map((item) => item.name.toLowerCase()),
58
+ )
59
+ if (names.size === 0) return []
60
+ const changed: string[] = []
61
+ for (const file of files) {
62
+ const text = readFileSync(file, 'utf8')
63
+ const next = braceFormWords(text, (name) => names.has(name.toLowerCase()))
64
+ if (next === text) continue
65
+ writeFileSync(file, next)
66
+ changed.push(file)
67
+ }
68
+ return changed
69
+ }
package/src/index.ts CHANGED
@@ -29,6 +29,7 @@ export * from './bundle-reload.ts'
29
29
  export * from './bundle-sections.ts'
30
30
  export * from './bundles.ts'
31
31
  export * from './busy.ts'
32
+ export { componentTemplates } from './component-templates-api.ts'
32
33
  export * from './components.ts'
33
34
  export * from './config.ts'
34
35
  export * from './content-dispatch.ts'
@@ -59,6 +60,7 @@ export * from './file-intake.ts'
59
60
  export * from './form-files.ts'
60
61
  export * from './form-submit.ts'
61
62
  export * from './form-types.ts'
63
+ export { braceFormWords, upgradeFormWords } from './form-word-upgrade.ts'
62
64
  export * from './form-workflows.ts'
63
65
  export * from './forms.ts'
64
66
  export * from './git.ts'
@@ -8,8 +8,9 @@
8
8
  import { createHash } from 'node:crypto'
9
9
  import { extname } from 'node:path'
10
10
  import {
11
+ bareFormWords,
12
+ bracedFormWordNames,
11
13
  type ContentTypeAggregate,
12
- formWordNames,
13
14
  IMAGE_CROPPER_EDITOR_ALIAS,
14
15
  normaliseUuid,
15
16
  ObjectTypes,
@@ -98,15 +99,26 @@ export async function compileSeed(db: Db, config: CromboloConfig): Promise<SeedB
98
99
  }
99
100
  }
100
101
  collect(dictionary.entries)
101
- for (const form of loadSchemaDirectory(config.schemaDir).set.forms ?? [])
102
- for (const name of formWordNames(form))
102
+ for (const form of loadSchemaDirectory(config.schemaDir).set.forms ?? []) {
103
+ const file = `schema/forms/${form.alias}.toml`
104
+ for (const name of bracedFormWordNames(form))
103
105
  if (!names.has(name.toLowerCase()))
104
106
  findings.push({
105
- file: `schema/forms/${form.alias}.toml`,
107
+ file,
106
108
  line: 1,
107
109
  code: 'unknown-dictionary-item',
108
- message: `the form "${form.alias}" names #${name}, which is not in ${DICTIONARY_FILE}`,
110
+ message: `the form "${form.alias}" names {#${name}}, which is not in ${DICTIONARY_FILE}`,
109
111
  })
112
+ // Forms wrote `#key` before story 297; the server rewrites it when it starts.
113
+ for (const name of bareFormWords(form))
114
+ if (names.has(name.toLowerCase()))
115
+ findings.push({
116
+ file,
117
+ line: 1,
118
+ code: 'bare-dictionary-word',
119
+ message: `the form "${form.alias}" writes #${name}; write it as {#${name}}`,
120
+ })
121
+ }
110
122
  }
111
123
 
112
124
  const state = await currentSchemaState(db)
package/src/server.ts CHANGED
@@ -170,6 +170,7 @@ import { CommandError, installBundleContent } from './bundle-install.ts'
170
170
  import { BUNDLES_CHANGED_EVENT, type BundleReload, createBundleReloader } from './bundle-reload.ts'
171
171
  import { bundleRouteGroups } from './bundles.ts'
172
172
  import { busyResponse } from './busy.ts'
173
+ import { handleComponentTemplates } from './component-templates-api.ts'
173
174
  import { checkTypes, listEmailTemplates } from './components.ts'
174
175
  import {
175
176
  type CromboloConfig,
@@ -184,6 +185,7 @@ import { closeTables, tablesReport } from './custom-tables.ts'
184
185
  import { folderAction, folderOf, foldersIn } from './definition-folders.ts'
185
186
  import { createDeliveryMediaPort } from './delivery-media.ts'
186
187
  import { createDeliveryMemberSecurity } from './delivery-members.ts'
188
+ import { handleDictionaryWords } from './dictionary-words-api.ts'
187
189
  import { syncDomainsFile } from './domains.ts'
188
190
  import { editorTypeLibs, siteJsxImportSource } from './editor-types.ts'
189
191
  import { emailAvailability } from './email.ts'
@@ -1927,6 +1929,29 @@ export async function createServer(
1927
1929
  if (response) return response
1928
1930
  }
1929
1931
 
1932
+ // Non-contract, signed-in: every component, for a page's template picker.
1933
+ if (pathname === `${paths.pluginPath}/api/templates`) {
1934
+ const principal = await authenticate(request)
1935
+ if (!principal) return new Response('Unauthorized', { status: 401 })
1936
+ return handleComponentTemplates(request, principal, {
1937
+ db,
1938
+ componentsDir: config.componentsDir,
1939
+ })
1940
+ }
1941
+
1942
+ // Non-contract, signed-in: a dictionary item's words, for a `{#key}` chip (story 297).
1943
+ if (pathname.startsWith(`${paths.pluginPath}/api/dictionary/`)) {
1944
+ const principal = await authenticate(request)
1945
+ if (!principal) return new Response('Unauthorized', { status: 401 })
1946
+ const response = await handleDictionaryWords(
1947
+ request,
1948
+ pathname.slice(`${paths.pluginPath}/api/dictionary`.length),
1949
+ principal,
1950
+ { db, onChange: () => cache.invalidate(), nodeId: schema.nodeId },
1951
+ )
1952
+ if (response) return response
1953
+ }
1954
+
1930
1955
  // Non-contract, signed-in: import the schema files into this database. A GET
1931
1956
  // asks what would happen and changes nothing; a POST applies it. Never
1932
1957
  // automatic — see `importSchema`.