@crombolo/server 0.37.0 → 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.
Files changed (79) hide show
  1. package/package.json +15 -14
  2. package/src/access.ts +29 -27
  3. package/src/adapters/audit.ts +1 -1
  4. package/src/adapters/blueprints.ts +22 -13
  5. package/src/adapters/content.ts +1 -1
  6. package/src/adapters/dictionary.ts +1 -1
  7. package/src/adapters/documents.ts +17 -10
  8. package/src/adapters/elements.ts +47 -37
  9. package/src/adapters/file-system.ts +1 -1
  10. package/src/adapters/health.ts +10 -5
  11. package/src/adapters/media.ts +12 -8
  12. package/src/adapters/member-groups.ts +8 -6
  13. package/src/adapters/members.ts +6 -4
  14. package/src/adapters/public-access.ts +7 -5
  15. package/src/adapters/redirects.ts +1 -1
  16. package/src/adapters/references.ts +1 -1
  17. package/src/adapters/relations.ts +1 -1
  18. package/src/adapters/schema-files.ts +33 -1
  19. package/src/adapters/search-index.ts +1 -1
  20. package/src/adapters/template-query.ts +1 -1
  21. package/src/adapters/users.ts +13 -13
  22. package/src/adapters/webhooks.ts +1 -1
  23. package/src/anonymise-rules.ts +83 -0
  24. package/src/approvals-api.ts +1 -1
  25. package/src/approvals.ts +75 -38
  26. package/src/back-office-url.ts +20 -0
  27. package/src/backup.ts +26 -2
  28. package/src/bundle-code.ts +1 -1
  29. package/src/bundle-grants.ts +265 -0
  30. package/src/bundle-install.ts +13 -2
  31. package/src/bundle-media.ts +12 -11
  32. package/src/bundles.ts +126 -43
  33. package/src/component-snippets.ts +1 -1
  34. package/src/components.ts +6 -1
  35. package/src/config.ts +61 -3
  36. package/src/content-notifications.ts +13 -9
  37. package/src/content-operations.ts +23 -65
  38. package/src/content-query.ts +1 -1
  39. package/src/core.ts +663 -0
  40. package/src/cron.ts +139 -0
  41. package/src/custom-tables.ts +274 -0
  42. package/src/database.ts +22 -14
  43. package/src/dictionary-transfer.ts +1 -1
  44. package/src/git-routes.ts +1 -1
  45. package/src/identity-provider-overrides.ts +18 -16
  46. package/src/imaging.ts +65 -15
  47. package/src/index.ts +10 -1
  48. package/src/job-wake.ts +23 -0
  49. package/src/live-reload.ts +195 -0
  50. package/src/log-viewer.ts +6 -1
  51. package/src/marketplace.ts +82 -10
  52. package/src/media-access.ts +12 -9
  53. package/src/member-auth.ts +6 -4
  54. package/src/models-builder.ts +1 -1
  55. package/src/node-operations.ts +122 -0
  56. package/src/owner-jobs.ts +428 -0
  57. package/src/ports.ts +36 -154
  58. package/src/preview-tokens.ts +6 -12
  59. package/src/remote.ts +3 -1
  60. package/src/schema.ts +8 -3
  61. package/src/seed/compile.ts +7 -5
  62. package/src/seed/export.ts +6 -4
  63. package/src/seo.ts +2 -2
  64. package/src/server.ts +333 -452
  65. package/src/settings.ts +18 -2
  66. package/src/site-data.ts +195 -0
  67. package/src/site-file.ts +30 -4
  68. package/src/site-queries.ts +140 -0
  69. package/src/site-replace.ts +25 -19
  70. package/src/site-sections.ts +1 -1
  71. package/src/site-services.ts +23 -6
  72. package/src/status-pages.ts +19 -5
  73. package/src/status.ts +11 -9
  74. package/src/url-settings.ts +1 -2
  75. package/src/webhook-files.ts +1 -1
  76. package/src/webhooks.ts +31 -23
  77. package/src/worker-watch.ts +73 -0
  78. package/src/worker.ts +138 -0
  79. package/src/bundle-tables.ts +0 -161
package/src/settings.ts CHANGED
@@ -76,11 +76,20 @@ const DECLARED = [
76
76
  {
77
77
  env: 'CROMBOLO_ROLE',
78
78
  kind: 'enum',
79
- values: ['all', 'api', 'web'],
79
+ values: ['all', 'api', 'web', 'worker'],
80
80
  default: 'all',
81
81
  section: 'Server',
82
82
  description:
83
- 'What this process serves: everything, the back office and its API, or the public site alone. Splitting needs Postgres; a misspelt role stops the server.',
83
+ 'What this process serves: everything, the back office and its API, the public site alone, or only the background jobs. Splitting needs Postgres; a misspelt role stops the server.',
84
+ },
85
+ {
86
+ env: 'CROMBOLO_JOBS',
87
+ kind: 'enum',
88
+ values: ['on', 'off'],
89
+ default: 'on',
90
+ section: 'Server',
91
+ description:
92
+ 'Whether an all or api node runs the background jobs. Off leaves them to a worker; the node still queues them.',
84
93
  },
85
94
  {
86
95
  env: 'CROMBOLO_NODE_ID',
@@ -733,6 +742,13 @@ const DECLARED = [
733
742
  description:
734
743
  "Shows a server error's message, the template file and line, and the stack on the error page. On in development, off otherwise; with it off a visitor sees only the error's reference, which the log carries too.",
735
744
  },
745
+ {
746
+ env: 'CROMBOLO_LIVE_RELOAD',
747
+ kind: 'boolean',
748
+ section: 'Public site',
749
+ description:
750
+ 'Reloads open pages when the components, the schema or the content change, and shows type errors on them. On in development, off in production and under `bun test`.',
751
+ },
736
752
  {
737
753
  env: 'CROMBOLO_SITEMAP',
738
754
  kind: 'boolean',
@@ -0,0 +1,195 @@
1
+ /**
2
+ * The site's and bundles' own tables in a site file (story 189): read out
3
+ * through each owner's handle for `export --with-site-data`, and written back
4
+ * when a file carrying them is applied. docs/content-transfer.md, "Site data".
5
+ */
6
+ import { discoverBundles } from '@crombolo/backoffice-host/registry'
7
+ import {
8
+ type ColumnSpec,
9
+ type Db,
10
+ openOwner,
11
+ ownerTablesIn,
12
+ recordedOwner,
13
+ SITE_OWNER,
14
+ } from '@crombolo/data'
15
+ import {
16
+ type AnonymiseRules,
17
+ type SanitiseSiteData,
18
+ type SiteDataRow,
19
+ type SiteDataTable,
20
+ siteDataName,
21
+ } from '@crombolo/transfer'
22
+ import { emptyValue } from './anonymise-rules.ts'
23
+ import type { CromboloConfig } from './config.ts'
24
+ import { closeTables, databaseFor, type TablesChain, tablesChainsFor } from './custom-tables.ts'
25
+
26
+ type SiteDataConfig = Pick<
27
+ CromboloConfig,
28
+ 'bundles' | 'siteDir' | 'database' | 'siteName' | 'sqliteFile'
29
+ >
30
+
31
+ /**
32
+ * The chains whose tables exist here, each opened, with the tables it has.
33
+ * An owner never set up is left out rather than created.
34
+ */
35
+ async function openPresent(
36
+ db: Db,
37
+ config: SiteDataConfig,
38
+ ): Promise<{ chains: TablesChain[]; present: Map<string, Set<string>> }> {
39
+ const chains = tablesChainsFor(config)
40
+ const present = new Map<string, Set<string>>()
41
+ for (const chain of chains) {
42
+ const place = await recordedOwner(db, config, chain.id)
43
+ if (!place) continue
44
+ const tables = await ownerTablesIn(db, place)
45
+ if (tables.length === 0) continue
46
+ chain.slot.place = place
47
+ chain.slot.db = await openOwner(db, place)
48
+ present.set(chain.id, new Set(tables))
49
+ }
50
+ return { chains, present }
51
+ }
52
+
53
+ /** Each owner's anonymise rules: the site's from its config, a bundle's from its package.json. */
54
+ function rulesFor(config: SiteDataConfig): Record<string, AnonymiseRules | undefined> {
55
+ const rules: Record<string, AnonymiseRules | undefined> = {
56
+ [SITE_OWNER]: config.database?.anonymise,
57
+ }
58
+ if (config.bundles.length > 0)
59
+ for (const pkg of discoverBundles(config.siteDir).bundles)
60
+ if (pkg.field.anonymise) rules[pkg.id] = pkg.field.anonymise
61
+ return rules
62
+ }
63
+
64
+ /** Every row of every owner's tables, in declaration order, with what anonymising them needs. */
65
+ export async function readSiteData(db: Db, config: SiteDataConfig): Promise<SanitiseSiteData> {
66
+ const { chains, present } = await openPresent(db, config)
67
+ const specs = new Map<string, ColumnSpec>()
68
+ const tables: SiteDataTable[] = []
69
+ try {
70
+ for (const chain of chains) {
71
+ const here = present.get(chain.id)
72
+ if (!here) continue
73
+ const handle = databaseFor(chain) as unknown as {
74
+ selectFrom: (table: string) => {
75
+ selectAll: () => { execute: () => Promise<SiteDataRow[]> }
76
+ }
77
+ }
78
+ for (const [table, declared] of chain.compiled.schema.tables) {
79
+ if (!here.has(table)) continue
80
+ for (const [column, resolved] of declared.columns)
81
+ specs.set(`${chain.id}\0${table}\0${column}`, resolved.spec)
82
+ tables.push({
83
+ owner: chain.id,
84
+ table,
85
+ rows: await handle.selectFrom(table).selectAll().execute(),
86
+ })
87
+ }
88
+ }
89
+ } finally {
90
+ await closeTables(chains)
91
+ }
92
+ return {
93
+ tables,
94
+ rules: rulesFor(config),
95
+ empty: (owner, table, column) => {
96
+ const spec = specs.get(`${owner}\0${table}\0${column}`)
97
+ return spec ? emptyValue(spec) : null
98
+ },
99
+ }
100
+ }
101
+
102
+ /** A value read from the file as the column's handle writes it. */
103
+ function writable(spec: ColumnSpec, value: unknown): unknown {
104
+ if (value === null || value === undefined) return null
105
+ if (spec.type === 'timestamp' && typeof value === 'string') return new Date(value)
106
+ // Stringified here, so a JSON string or number is stored as JSON rather than as itself.
107
+ if (spec.type === 'json') return JSON.stringify(value)
108
+ return value
109
+ }
110
+
111
+ export interface SiteDataApplied {
112
+ /** Tables written, and the rows in them. */
113
+ tables: number
114
+ rows: number
115
+ /** What the file carries and this site has no place for: owners, tables and columns. */
116
+ skipped: string[]
117
+ /** Owners whose tables could not be written, each with why; their tables are as they were. */
118
+ failed: string[]
119
+ }
120
+
121
+ type Writer = {
122
+ deleteFrom: (table: string) => { execute: () => Promise<unknown> }
123
+ insertInto: (table: string) => {
124
+ values: (row: SiteDataRow) => { execute: () => Promise<unknown> }
125
+ }
126
+ }
127
+
128
+ /**
129
+ * Replaces each owner's tables with the file's rows, one owner per
130
+ * transaction: every table of an owner the file carries is emptied, children
131
+ * first, then filled, parents first. An owner or table this site lacks is
132
+ * skipped and named, as is a column it does not declare.
133
+ */
134
+ export async function applySiteData(
135
+ db: Db,
136
+ config: SiteDataConfig,
137
+ carried: readonly SiteDataTable[],
138
+ ): Promise<SiteDataApplied> {
139
+ const result: SiteDataApplied = { tables: 0, rows: 0, skipped: [], failed: [] }
140
+ const { chains, present } = await openPresent(db, config)
141
+ try {
142
+ const byOwner = new Map<string, Map<string, SiteDataRow[]>>()
143
+ for (const t of carried) {
144
+ const tables = byOwner.get(t.owner) ?? new Map<string, SiteDataRow[]>()
145
+ tables.set(t.table, t.rows)
146
+ byOwner.set(t.owner, tables)
147
+ }
148
+ for (const [owner, tables] of byOwner) {
149
+ const chain = chains.find((c) => c.id === owner)
150
+ const here = present.get(owner)
151
+ if (!chain || !here) {
152
+ result.skipped.push(owner)
153
+ continue
154
+ }
155
+ const declared = [...chain.compiled.schema.tables.values()].filter((t) => here.has(t.name))
156
+ for (const table of tables.keys())
157
+ if (!declared.some((t) => t.name === table)) result.skipped.push(siteDataName(owner, table))
158
+ const fills = declared.flatMap((t) => {
159
+ const rows = tables.get(t.name)
160
+ if (!rows) return []
161
+ const unknown = new Set<string>()
162
+ const values = rows.map((row) => {
163
+ const out: SiteDataRow = {}
164
+ for (const [column, value] of Object.entries(row)) {
165
+ const spec = t.columns.get(column)?.spec
166
+ if (spec) out[column] = writable(spec, value)
167
+ else unknown.add(column)
168
+ }
169
+ return out
170
+ })
171
+ for (const column of unknown)
172
+ result.skipped.push(`${siteDataName(owner, t.name)}.${column}`)
173
+ return [{ table: t.name, rows: values }]
174
+ })
175
+ try {
176
+ await databaseFor(chain)
177
+ .transaction()
178
+ .execute(async (trx) => {
179
+ const k = trx as unknown as Writer
180
+ for (const t of [...declared].reverse()) await k.deleteFrom(t.name).execute()
181
+ // One row at a time: SQLite cannot default a column in a multi-row insert.
182
+ for (const fill of fills)
183
+ for (const row of fill.rows) await k.insertInto(fill.table).values(row).execute()
184
+ })
185
+ result.tables += fills.length
186
+ result.rows += fills.reduce((total, fill) => total + fill.rows.length, 0)
187
+ } catch (error) {
188
+ result.failed.push(`${owner}: ${error instanceof Error ? error.message : String(error)}`)
189
+ }
190
+ }
191
+ } finally {
192
+ await closeTables(chains)
193
+ }
194
+ return result
195
+ }
package/src/site-file.ts CHANGED
@@ -10,7 +10,7 @@
10
10
  * failed export never leaves a file that looks whole.
11
11
  */
12
12
  import { rename, rm } from 'node:fs/promises'
13
- import { discoverBundles } from '@crombolo/backoffice-host'
13
+ import { discoverBundles } from '@crombolo/backoffice-host/registry'
14
14
  import { type Db, NodeRepository, type NodeRow, ObjectTypes } from '@crombolo/data'
15
15
  import {
16
16
  BUNDLE_SECTIONS,
@@ -34,6 +34,7 @@ import { createTemplateFileStore } from './adapters/template-files.ts'
34
34
  import { type CromboloConfig, VERSION } from './config.ts'
35
35
  import { mediaStoreFor } from './media-files.ts'
36
36
  import { type StoredFile, streamOf } from './media-store.ts'
37
+ import { readSiteData } from './site-data.ts'
37
38
  import { siteSections } from './site-sections.ts'
38
39
  import { TarballWriter } from './tar.ts'
39
40
 
@@ -50,6 +51,8 @@ export interface SiteExportOptions {
50
51
  drafts?: boolean
51
52
  withMembers?: boolean
52
53
  withUsers?: boolean
54
+ /** The site's and bundles' own tables (story 189): sealed, as people are. */
55
+ withSiteData?: boolean
53
56
  /** Replace every personal value before anything is written (`sanitise`). */
54
57
  anonymise?: boolean
55
58
  /**
@@ -73,6 +76,11 @@ export interface SiteExportResult {
73
76
  people: { members: number; users: number }
74
77
  /** How many distinct email addresses `--anonymise` replaced. */
75
78
  anonymised?: number
79
+ /**
80
+ * With `withSiteData`: the tables carried and their rows. `emptied` names, as
81
+ * `owner.table`, each table `--anonymise` had no rule for, which travels empty.
82
+ */
83
+ siteData?: { tables: number; rows: number; emptied: string[] }
76
84
  }
77
85
 
78
86
  /** The content kinds a whole site carries, each from its tree's top. */
@@ -133,6 +141,8 @@ export async function exportSite(
133
141
  const carryUsers = Boolean(options.withUsers) && !options.anonymise
134
142
  if ((carryMembers || carryUsers) && !options.passphrase)
135
143
  throw new Error('Members and users travel sealed: give a passphrase.')
144
+ if (options.withSiteData && !options.passphrase)
145
+ throw new Error("The site's own data travels sealed: give a passphrase.")
136
146
  if (options.sealContent && !options.passphrase)
137
147
  throw new Error('Sealed content needs a passphrase.')
138
148
 
@@ -167,13 +177,18 @@ export async function exportSite(
167
177
  carryMembers || carryUsers
168
178
  ? await exportPeople(db, { members: carryMembers, users: carryUsers })
169
179
  : undefined
180
+ const read = options.withSiteData ? await readSiteData(db, config) : undefined
181
+ let siteData = read?.tables
182
+ let emptied: string[] = []
170
183
  let anonymised: number | undefined
171
184
  if (options.anonymise) {
172
185
  const dictionaryPath = `${BUNDLE_SECTIONS.dictionary}.udt`
173
186
  const dictionary = sections.find((file) => file.path === dictionaryPath)
174
- const clean = sanitise({ set, people, dictionary: dictionary?.text })
187
+ const clean = sanitise({ set, people, dictionary: dictionary?.text, siteData: read })
175
188
  set = clean.set
176
189
  people = clean.people
190
+ siteData = clean.siteData
191
+ emptied = clean.emptied
177
192
  anonymised = clean.emails
178
193
  if (dictionary && clean.dictionary !== undefined)
179
194
  sections = sections.map((file) =>
@@ -217,12 +232,14 @@ export async function exportSite(
217
232
  },
218
233
  }
219
234
  const seal =
220
- (people || options.sealContent) && options.passphrase ? newSeal(options.passphrase) : undefined
235
+ (people || siteData || options.sealContent) && options.passphrase
236
+ ? newSeal(options.passphrase)
237
+ : undefined
221
238
  const planned = planStreamedBundle(
222
239
  site,
223
240
  new Map([...stored].map(([key, file]) => [key, file.size])),
224
241
  sections,
225
- { people, seal, content: options.sealContent ? 'sealed' : 'open' },
242
+ { people, siteData, seal, content: options.sealContent ? 'sealed' : 'open' },
226
243
  )
227
244
 
228
245
  const name = options.package?.name ?? packageNameFor(`${config.siteName}-site`)
@@ -303,5 +320,14 @@ export async function exportSite(
303
320
  media: { carried: stored.size, bytes, missing, omitted: !withMedia },
304
321
  people: { members: people?.members.length ?? 0, users: people?.users.length ?? 0 },
305
322
  ...(anonymised !== undefined ? { anonymised } : {}),
323
+ ...(siteData
324
+ ? {
325
+ siteData: {
326
+ tables: siteData.length,
327
+ rows: siteData.reduce((total, t) => total + t.rows.length, 0),
328
+ emptied,
329
+ },
330
+ }
331
+ : {}),
306
332
  }
307
333
  }
@@ -0,0 +1,140 @@
1
+ /**
2
+ * The site's named queries (story 189): modules the config lists, each export
3
+ * run as `site().queries.<module>.<export>(…)` with the site's own tables and
4
+ * who is asking supplied. docs/rendering.md, "Named queries".
5
+ */
6
+ import { isOk, isOutcome } from '@crombolo/core'
7
+ import type { SiteTables, TablesDatabase } from '@crombolo/data'
8
+ import {
9
+ currentCulture,
10
+ markPersonal,
11
+ type QueryCaller,
12
+ type RequestMember,
13
+ type SiteQueries,
14
+ } from '@crombolo/render'
15
+ import type { AnonymiseRules } from '@crombolo/transfer'
16
+ import { databaseFor, type TablesChain } from './custom-tables.ts'
17
+
18
+ export type { AnonymiseColumn, AnonymiseRules, AnonymiseTable } from '@crombolo/transfer'
19
+
20
+ export interface SiteDatabaseConfig {
21
+ /** From `defineSiteTables`. */
22
+ tables?: SiteTables
23
+ /** Under `--anonymise`, each table that may travel, and how. */
24
+ anonymise?: AnonymiseRules
25
+ }
26
+
27
+ /** Module namespaces, by the name `site().queries` calls them. */
28
+ export type SiteQueryModules = Readonly<Record<string, Readonly<Record<string, unknown>>>>
29
+
30
+ const MODULE_NAME = /^[A-Za-z_$][\w$]*$/
31
+
32
+ /** Every reason the config's queries cannot be used. */
33
+ export function queryProblems(config: {
34
+ queries?: SiteQueryModules
35
+ database?: SiteDatabaseConfig
36
+ }): string[] {
37
+ const problems: string[] = []
38
+ const modules = Object.entries(config.queries ?? {})
39
+ if (modules.length > 0 && !config.database?.tables)
40
+ problems.push('queries are listed, but there is no database.tables for them to query')
41
+ const seen = new Map<unknown, string>()
42
+ for (const [name, module] of modules) {
43
+ if (!MODULE_NAME.test(name))
44
+ problems.push(`the query module "${name}" is not a name: letters, digits, _ and $`)
45
+ if (!module || typeof module !== 'object') {
46
+ problems.push(`queries.${name} is not a module: list it as \`import * as ${name} from …\``)
47
+ continue
48
+ }
49
+ for (const [key, value] of Object.entries(module)) {
50
+ const id = `${name}.${key}`
51
+ if (typeof value !== 'function') {
52
+ problems.push(`queries.${id} is not a function`)
53
+ continue
54
+ }
55
+ const other = seen.get(value)
56
+ if (other) problems.push(`queries.${id} is the same query as queries.${other}`)
57
+ else seen.set(value, id)
58
+ }
59
+ }
60
+ return problems.map((problem) => `${problem}.`)
61
+ }
62
+
63
+ /** A named query failed: its id is what an error page names. */
64
+ export class NamedQueryError extends Error {
65
+ constructor(
66
+ readonly query: string,
67
+ cause: unknown,
68
+ ) {
69
+ super(
70
+ `site().queries.${query} failed: ${cause instanceof Error ? cause.message : String(cause)}`,
71
+ { cause },
72
+ )
73
+ }
74
+ }
75
+
76
+ type Member = RequestMember | undefined
77
+
78
+ /**
79
+ * `site().queries` for one request, as `member` (or a visitor). The site's
80
+ * tables are opened at the first call.
81
+ */
82
+ export function createSiteQueries(options: {
83
+ queries: SiteQueryModules | undefined
84
+ chain: TablesChain | undefined
85
+ }): (member: Member | (() => Promise<Member>)) => SiteQueries {
86
+ const modules = Object.entries(options.queries ?? {})
87
+ let handle: TablesDatabase | undefined
88
+ const database = () => {
89
+ if (!options.chain) throw new Error('the site declares no tables')
90
+ handle ??= databaseFor(options.chain)
91
+ return handle
92
+ }
93
+
94
+ return (member) => {
95
+ let found: Promise<Member> | undefined
96
+ const caller: QueryCaller = Object.freeze({
97
+ member: async () => {
98
+ markPersonal()
99
+ found ??= typeof member === 'function' ? member() : Promise.resolve(member)
100
+ const who = await found
101
+ return who
102
+ ? Object.freeze({
103
+ key: who.key,
104
+ name: who.name,
105
+ username: who.username,
106
+ email: who.email,
107
+ roles: Object.freeze([...who.roles]) as string[],
108
+ })
109
+ : undefined
110
+ },
111
+ locale: currentCulture(),
112
+ })
113
+ const queries: Record<string, Record<string, unknown>> = {}
114
+ for (const [name, module] of modules) {
115
+ const bound: Record<string, unknown> = {}
116
+ for (const [key, fn] of Object.entries(module)) {
117
+ if (typeof fn !== 'function') continue
118
+ const id = `${name}.${key}`
119
+ bound[key] = async (...args: unknown[]) => {
120
+ let result: unknown
121
+ try {
122
+ result = await fn(database(), caller, ...args)
123
+ } catch (error) {
124
+ throw new NamedQueryError(id, error)
125
+ }
126
+ if (!isOk(result as never) && !isOutcome(result))
127
+ throw new NamedQueryError(
128
+ id,
129
+ new Error(
130
+ 'it returned something other than a Result: return ok(value) or an Outcome',
131
+ ),
132
+ )
133
+ return result
134
+ }
135
+ }
136
+ queries[name] = Object.freeze(bound)
137
+ }
138
+ return Object.freeze(queries) as unknown as SiteQueries
139
+ }
140
+ }
@@ -8,7 +8,7 @@
8
8
  */
9
9
  import { existsSync } from 'node:fs'
10
10
  import { join, sep } from 'node:path'
11
- import { discoverBundles } from '@crombolo/backoffice-host'
11
+ import { discoverBundles } from '@crombolo/backoffice-host/registry'
12
12
  import {
13
13
  currentSchemaState,
14
14
  type Db,
@@ -77,10 +77,12 @@ export async function pruneSite(
77
77
  const nodeState = { version: state.version, revision: state.revision }
78
78
  const pruned: PrunedNode[] = []
79
79
  for (const { objectType, kind } of PRUNED_KINDS) {
80
- const rows = await tx.query<{ id: number; unique_id: string; parent_id: number }>(
81
- 'SELECT id, unique_id, parent_id FROM node WHERE node_object_type = ? AND trashed = ?',
82
- [objectType, tx.dialect.boolValue(false)],
83
- )
80
+ const rows = await tx.q
81
+ .selectFrom('node')
82
+ .select(['id', 'unique_id', 'parent_id'])
83
+ .where('node_object_type', '=', objectType)
84
+ .where('trashed', '=', tx.dialect.boolValue(false) as boolean)
85
+ .execute()
84
86
  const leaving = rows.filter((row) => !inFile.has(String(row.unique_id).toLowerCase()))
85
87
  const leavingIds = new Set(leaving.map((row) => Number(row.id)))
86
88
  // The top of each branch: recycling or deleting it takes its children too.
@@ -108,15 +110,16 @@ export async function prunePeople(tx: Db, people: BundlePeople | undefined): Pro
108
110
  const memberRepo = new MemberRepository(tx, {
109
111
  nodeState: { version: state.version, revision: state.revision },
110
112
  })
111
- const memberRows = await tx.query<{ unique_id: string }>(
112
- 'SELECT unique_id FROM node WHERE node_object_type = ?',
113
- [ObjectTypes.Member],
114
- )
113
+ const memberRows = await tx.q
114
+ .selectFrom('node')
115
+ .select('unique_id')
116
+ .where('node_object_type', '=', ObjectTypes.Member)
117
+ .execute()
115
118
  for (const row of memberRows)
116
119
  if (!members.has(String(row.unique_id).toLowerCase()))
117
120
  await memberRepo.delete(String(row.unique_id))
118
121
  const userRepo = new UserRepository(tx)
119
- for (const row of await tx.query<{ key: string }>('SELECT key FROM user_account'))
122
+ for (const row of await tx.q.selectFrom('user_account').select('key').execute())
120
123
  if (!users.has(String(row.key).toLowerCase())) await userRepo.delete(String(row.key))
121
124
  }
122
125
 
@@ -155,10 +158,12 @@ export async function replaceSummary(
155
158
  const inFile = new Set(set.nodes.map((node) => node.key.toLowerCase()))
156
159
  const leaving: Record<string, number> = {}
157
160
  for (const { objectType, kind } of PRUNED_KINDS) {
158
- const rows = await db.query<{ unique_id: string }>(
159
- 'SELECT unique_id FROM node WHERE node_object_type = ? AND trashed = ?',
160
- [objectType, db.dialect.boolValue(false)],
161
- )
161
+ const rows = await db.q
162
+ .selectFrom('node')
163
+ .select('unique_id')
164
+ .where('node_object_type', '=', objectType)
165
+ .where('trashed', '=', db.dialect.boolValue(false) as boolean)
166
+ .execute()
162
167
  const count = rows.filter((row) => !inFile.has(String(row.unique_id).toLowerCase())).length
163
168
  if (count > 0) leaving[kind] = count
164
169
  }
@@ -174,11 +179,12 @@ export async function replaceSummary(
174
179
  if (mode === 'replace-all') {
175
180
  const members = new Set((set.people?.members ?? []).map((m) => m.key.toLowerCase()))
176
181
  const users = new Set((set.people?.users ?? []).map((u) => u.key.toLowerCase()))
177
- const memberRows = await db.query<{ unique_id: string }>(
178
- 'SELECT unique_id FROM node WHERE node_object_type = ?',
179
- [ObjectTypes.Member],
180
- )
181
- const userRows = await db.query<{ key: string }>('SELECT key FROM user_account')
182
+ const memberRows = await db.q
183
+ .selectFrom('node')
184
+ .select('unique_id')
185
+ .where('node_object_type', '=', ObjectTypes.Member)
186
+ .execute()
187
+ const userRows = await db.q.selectFrom('user_account').select('key').execute()
182
188
  people = {
183
189
  members: memberRows.filter((r) => !members.has(String(r.unique_id).toLowerCase())).length,
184
190
  users: userRows.filter((r) => !users.has(String(r.key).toLowerCase())).length,
@@ -6,7 +6,7 @@
6
6
  */
7
7
  import { readdir, readFile } from 'node:fs/promises'
8
8
  import { join, relative, sep } from 'node:path'
9
- import type { FileSystemPort } from '@crombolo/api-management'
9
+ import type { FileSystemPort } from '@crombolo/api-management/domain'
10
10
  import {
11
11
  type ComponentFileStore,
12
12
  ComponentRepository,
@@ -19,9 +19,10 @@ import {
19
19
  type PublishedCache,
20
20
  type PublishedMedia,
21
21
  type RequestMember,
22
+ type SiteJobs,
22
23
  type SiteMembers,
24
+ type SiteQueries,
23
25
  type SiteServices,
24
- type SiteSql,
25
26
  unavailableServices,
26
27
  } from '@crombolo/render'
27
28
 
@@ -30,6 +31,12 @@ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
30
31
  export interface SiteServicesDeps {
31
32
  db: Db
32
33
  cache: PublishedCache
34
+ /** `site().jobs`, recording who queued (story 187). */
35
+ jobs?: (queuedBy: () => Promise<string>) => SiteJobs
36
+ /** `site().queries` for a member or a visitor (story 189). */
37
+ queries?: (
38
+ member: RequestMember | undefined | (() => Promise<RequestMember | undefined>),
39
+ ) => SiteQueries
33
40
  }
34
41
 
35
42
  /** Builds `site()`'s services for one request; undefined `member` is a visitor or a previewing editor. */
@@ -75,10 +82,15 @@ export function createSiteServices(deps: SiteServicesDeps) {
75
82
  if (!UUID.test(folderKey)) return notFound
76
83
  const folder = await cache.media?.byKey(folderKey)
77
84
  if (!folder || !(await readable(folder))) return notFound
78
- const rows = await db.query<{ unique_id: string }>(
79
- 'SELECT unique_id FROM node WHERE parent_id = ? AND node_object_type = ? AND trashed = ? ORDER BY sort_order, id',
80
- [folder.id, ObjectTypes.Media, db.dialect.boolValue(false)],
81
- )
85
+ const rows = await db.q
86
+ .selectFrom('node')
87
+ .select('unique_id')
88
+ .where('parent_id', '=', folder.id)
89
+ .where('node_object_type', '=', ObjectTypes.Media)
90
+ .where('trashed', '=', db.dialect.boolValue(false) as boolean)
91
+ .orderBy('sort_order')
92
+ .orderBy('id')
93
+ .execute()
82
94
  const found = (await cache.media?.byKeys(rows.map((row) => row.unique_id))) ?? new Map()
83
95
  const items: PublishedMedia[] = []
84
96
  for (const row of rows) {
@@ -91,7 +103,12 @@ export function createSiteServices(deps: SiteServicesDeps) {
91
103
 
92
104
  const services: SiteServices = {
93
105
  media,
94
- sql: unavailableServices<SiteSql>('sql'),
106
+ queries: deps.queries?.(member) ?? ({} as SiteQueries),
107
+ jobs:
108
+ deps.jobs?.(async () => {
109
+ const who = await (typeof member === 'function' ? member() : Promise.resolve(member))
110
+ return who ? `member ${who.username}` : 'a visitor'
111
+ }) ?? unavailableServices<SiteJobs>('jobs'),
95
112
  members: unavailableServices<SiteMembers>('members'),
96
113
  }
97
114
  return () => services
@@ -103,14 +103,28 @@ export function genericStatusPage(outcome: PageOutcome): string {
103
103
  .join('')}</ul>`,
104
104
  )
105
105
  if (outcome.details) {
106
- parts.push(`<p>${escapeHtml(outcome.details.message)}</p>`)
107
- if (outcome.details.location)
108
- parts.push(`<p><code>${escapeHtml(outcome.details.location)}</code></p>`)
109
- if (outcome.details.stack) parts.push(`<pre>${escapeHtml(outcome.details.stack)}</pre>`)
106
+ const { message, location, code, components, stack } = outcome.details
107
+ parts.push(`<p>${escapeHtml(message)}</p>`)
108
+ if (location) parts.push(`<p><code>${escapeHtml(location)}</code></p>`)
109
+ if (code) parts.push(codeFrame(code))
110
+ if (components?.length)
111
+ parts.push(`<p>While rendering <code>${escapeHtml(components.join(' › '))}</code></p>`)
112
+ if (stack) parts.push(`<pre>${escapeHtml(stack)}</pre>`)
110
113
  }
111
114
  if (outcome.reference)
112
115
  parts.push(`<p>Reference: <code>${escapeHtml(outcome.reference)}</code></p>`)
113
- return `<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="robots" content="noindex"><title>${escapeHtml(heading)}</title><style>body{font-family:system-ui,sans-serif;max-width:40rem;margin:4rem auto;padding:0 1rem;line-height:1.5;color:#222}pre{overflow:auto;background:#f4f4f4;padding:1rem;font-size:.85rem}</style></head><body><main>${parts.join('')}</main></body></html>`
116
+ return `<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="robots" content="noindex"><title>${escapeHtml(heading)}</title><style>body{font-family:system-ui,sans-serif;max-width:40rem;margin:4rem auto;padding:0 1rem;line-height:1.5;color:#222}pre{overflow:auto;background:#f4f4f4;padding:1rem;font-size:.85rem}.code span{display:block}.code .at{background:#fde2e2;font-weight:600}</style></head><body><main>${parts.join('')}</main></body></html>`
117
+ }
118
+
119
+ /** The lines around a failing one, numbered, that line marked. */
120
+ function codeFrame(code: NonNullable<PageOutcome['details']>['code'] & object): string {
121
+ const width = String(code.lines.at(-1)?.number ?? code.line).length
122
+ const rows = code.lines.map(({ number, text }) => {
123
+ const mark = number === code.line ? '>' : ' '
124
+ const label = `${mark} ${String(number).padStart(width)} | `
125
+ return `<span${number === code.line ? ' class="at"' : ''}>${escapeHtml(label + text)}</span>`
126
+ })
127
+ return `<pre class="code">${rows.join('')}</pre>`
114
128
  }
115
129
 
116
130
  const REDIRECT_NAMES: Record<number, string> = {