@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.
Files changed (83) hide show
  1. package/package.json +15 -13
  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 +33 -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-files.ts +6 -1
  21. package/src/adapters/template-query.ts +1 -1
  22. package/src/adapters/users.ts +13 -13
  23. package/src/adapters/webhooks.ts +1 -1
  24. package/src/anonymise-rules.ts +83 -0
  25. package/src/approvals-api.ts +1 -1
  26. package/src/approvals.ts +75 -38
  27. package/src/back-office-url.ts +20 -0
  28. package/src/backup.ts +26 -2
  29. package/src/bundle-code.ts +1 -1
  30. package/src/bundle-grants.ts +265 -0
  31. package/src/bundle-install.ts +13 -2
  32. package/src/bundle-media.ts +12 -11
  33. package/src/bundles.ts +258 -444
  34. package/src/component-snippets.ts +1 -1
  35. package/src/components.ts +48 -7
  36. package/src/config.ts +141 -4
  37. package/src/content-notifications.ts +13 -9
  38. package/src/content-operations.ts +23 -65
  39. package/src/content-query.ts +1 -1
  40. package/src/core.ts +663 -0
  41. package/src/cron.ts +139 -0
  42. package/src/custom-tables.ts +274 -0
  43. package/src/database.ts +22 -14
  44. package/src/dictionary-transfer.ts +1 -1
  45. package/src/git-routes.ts +1 -1
  46. package/src/identity-provider-overrides.ts +18 -16
  47. package/src/imaging.ts +65 -15
  48. package/src/index.ts +14 -1
  49. package/src/islands.ts +197 -0
  50. package/src/job-wake.ts +23 -0
  51. package/src/live-reload.ts +195 -0
  52. package/src/log-viewer.ts +6 -1
  53. package/src/marketplace.ts +82 -10
  54. package/src/media-access.ts +12 -9
  55. package/src/member-auth.ts +6 -4
  56. package/src/middleware.ts +236 -0
  57. package/src/models-builder.ts +1 -1
  58. package/src/node-operations.ts +122 -0
  59. package/src/owner-jobs.ts +428 -0
  60. package/src/ports.ts +39 -154
  61. package/src/preview-tokens.ts +6 -12
  62. package/src/remote.ts +3 -1
  63. package/src/routes.ts +420 -0
  64. package/src/schema.ts +8 -3
  65. package/src/seed/compile.ts +7 -5
  66. package/src/seed/export.ts +6 -4
  67. package/src/seo.ts +2 -2
  68. package/src/server.ts +866 -483
  69. package/src/settings.ts +49 -2
  70. package/src/site-data.ts +195 -0
  71. package/src/site-file.ts +30 -4
  72. package/src/site-queries.ts +140 -0
  73. package/src/site-replace.ts +25 -19
  74. package/src/site-sections.ts +1 -1
  75. package/src/site-services.ts +116 -0
  76. package/src/status-pages.ts +142 -0
  77. package/src/status.ts +11 -9
  78. package/src/url-settings.ts +1 -2
  79. package/src/webhook-files.ts +18 -1
  80. package/src/webhooks.ts +83 -15
  81. package/src/worker-watch.ts +73 -0
  82. package/src/worker.ts +138 -0
  83. package/src/bundle-tables.ts +0 -161
package/src/cron.ts ADDED
@@ -0,0 +1,139 @@
1
+ /**
2
+ * Cron expressions for job schedules (story 187): the standard five fields,
3
+ * read in an IANA timezone, so "02:00 nightly" stays 02:00 local across
4
+ * daylight saving. docs/rendering.md, "Background jobs".
5
+ */
6
+
7
+ export interface Cron {
8
+ readonly source: string
9
+ minutes: Set<number>
10
+ hours: Set<number>
11
+ days: Set<number>
12
+ months: Set<number>
13
+ weekdays: Set<number>
14
+ /** Both day fields restricted: either matching is enough, as cron has always read them. */
15
+ eitherDay: boolean
16
+ }
17
+
18
+ const MONTHS = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec']
19
+ const WEEKDAYS = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat']
20
+
21
+ function field(
22
+ text: string,
23
+ name: string,
24
+ min: number,
25
+ max: number,
26
+ names: readonly string[] = [],
27
+ offset = 0,
28
+ ): Set<number> {
29
+ const out = new Set<number>()
30
+ const value = (part: string) => {
31
+ const named = names.indexOf(part.toLowerCase())
32
+ const n = named >= 0 ? named + offset : Number(part)
33
+ if (!Number.isInteger(n) || n < min || n > max)
34
+ throw new Error(`the ${name} field's "${part}" is not from ${min} to ${max}`)
35
+ return n
36
+ }
37
+ for (const item of text.split(',')) {
38
+ const [range = '', stepText] = item.split('/')
39
+ const step = stepText === undefined ? 1 : Number(stepText)
40
+ if (!Number.isInteger(step) || step < 1)
41
+ throw new Error(`the ${name} field's step "${stepText}" is not a whole number from 1`)
42
+ let from = min
43
+ let to = max
44
+ if (range !== '*') {
45
+ const [a = '', b] = range.split('-')
46
+ from = value(a)
47
+ to = b === undefined ? (stepText === undefined ? from : max) : value(b)
48
+ if (to < from) throw new Error(`the ${name} field's range "${range}" runs backwards`)
49
+ }
50
+ for (let n = from; n <= to; n += step) out.add(n)
51
+ }
52
+ return out
53
+ }
54
+
55
+ /** A cron expression, or an error saying what is wrong with it. */
56
+ export function parseCron(source: string): Cron {
57
+ const parts = source.trim().split(/\s+/)
58
+ if (parts.length !== 5)
59
+ throw new Error(
60
+ `"${source}" has ${parts.length} fields, not the five of minute, hour, day, month and weekday`,
61
+ )
62
+ const [minute, hour, day, month, weekday] = parts as [string, string, string, string, string]
63
+ const weekdays = field(weekday, 'weekday', 0, 7, WEEKDAYS)
64
+ if (weekdays.delete(7)) weekdays.add(0)
65
+ return {
66
+ source,
67
+ minutes: field(minute, 'minute', 0, 59),
68
+ hours: field(hour, 'hour', 0, 23),
69
+ days: field(day, 'day', 1, 31),
70
+ months: field(month, 'month', 1, 12, MONTHS, 1),
71
+ weekdays,
72
+ eitherDay: day !== '*' && weekday !== '*',
73
+ }
74
+ }
75
+
76
+ /** Whether `zone` is an IANA timezone this runtime knows. */
77
+ export function isTimezone(zone: string): boolean {
78
+ try {
79
+ new Intl.DateTimeFormat('en-US', { timeZone: zone })
80
+ return true
81
+ } catch {
82
+ return false
83
+ }
84
+ }
85
+
86
+ const formatters = new Map<string, Intl.DateTimeFormat>()
87
+
88
+ /** The wall-clock parts of an instant in a zone. */
89
+ function wallClock(at: Date, zone: string) {
90
+ let format = formatters.get(zone)
91
+ if (!format) {
92
+ format = new Intl.DateTimeFormat('en-US', {
93
+ timeZone: zone,
94
+ hourCycle: 'h23',
95
+ year: 'numeric',
96
+ month: 'numeric',
97
+ day: 'numeric',
98
+ hour: 'numeric',
99
+ minute: 'numeric',
100
+ weekday: 'short',
101
+ })
102
+ formatters.set(zone, format)
103
+ }
104
+ const parts: Record<string, string> = {}
105
+ for (const part of format.formatToParts(at)) parts[part.type] = part.value
106
+ return {
107
+ month: Number(parts.month),
108
+ day: Number(parts.day),
109
+ hour: Number(parts.hour) % 24,
110
+ minute: Number(parts.minute),
111
+ weekday: WEEKDAYS.indexOf((parts.weekday ?? '').slice(0, 3).toLowerCase()),
112
+ }
113
+ }
114
+
115
+ const MINUTE = 60_000
116
+
117
+ /**
118
+ * The first occurrence strictly after `after`, in `zone`. Walks an hour at a
119
+ * time, and a minute at a time inside an hour that matches, so a yearly
120
+ * schedule costs some thousands of steps rather than half a million.
121
+ */
122
+ export function nextOccurrence(cron: Cron, zone: string, after: Date): Date {
123
+ let at = Math.floor(after.getTime() / MINUTE) * MINUTE + MINUTE
124
+ // Four years and a day: long enough for a schedule that only falls on 29 February.
125
+ const end = at + (4 * 366 + 1) * 24 * 60 * MINUTE
126
+ while (at <= end) {
127
+ const wall = wallClock(new Date(at), zone)
128
+ const dayMatches = cron.eitherDay
129
+ ? cron.days.has(wall.day) || cron.weekdays.has(wall.weekday)
130
+ : cron.days.has(wall.day) && cron.weekdays.has(wall.weekday)
131
+ if (!cron.months.has(wall.month) || !dayMatches || !cron.hours.has(wall.hour)) {
132
+ at += (60 - wall.minute) * MINUTE
133
+ continue
134
+ }
135
+ if (cron.minutes.has(wall.minute)) return new Date(at)
136
+ at += MINUTE
137
+ }
138
+ throw new Error(`"${cron.source}" never falls due`)
139
+ }
@@ -0,0 +1,274 @@
1
+ /**
2
+ * The chains of custom tables (stories 062, 189): the site's own, from
3
+ * `database.tables` in its config, then each wired bundle's that declares
4
+ * tables, in the order `bundles` lists them. Worked out once from the config
5
+ * and the packages, and run after core's.
6
+ *
7
+ * Only a node that owns the database applies them or provisions their places.
8
+ * Every node opens the site's, because named queries run wherever pages render.
9
+ */
10
+ import { existsSync, readFileSync } from 'node:fs'
11
+ import { join } from 'node:path'
12
+ import { type BundlePackage, discoverBundles } from '@crombolo/backoffice-host/registry'
13
+ import {
14
+ type CompiledTables,
15
+ compileTables,
16
+ type Db,
17
+ type Migration,
18
+ type MigrationPlan,
19
+ migrate,
20
+ type OwnerSlot,
21
+ openOwner,
22
+ type PlannedStep,
23
+ pendingMigrations,
24
+ planUpgrade,
25
+ provisionOwner,
26
+ readLedger,
27
+ readState,
28
+ recordedOwner,
29
+ SITE_OWNER,
30
+ type TablesDatabase,
31
+ tablesDatabase,
32
+ tablesPlan,
33
+ } from '@crombolo/data'
34
+ import { anonymiseProblems } from './anonymise-rules.ts'
35
+ import { type ServerBundle, validateServerBundles } from './bundles.ts'
36
+ import { type CromboloConfig, VERSION } from './config.ts'
37
+
38
+ /** One owner's chain, with what it is called and where it runs. */
39
+ export interface TablesChain {
40
+ /** `site`, or the bundle's id. */
41
+ id: string
42
+ name: string
43
+ compiled: CompiledTables
44
+ plan: MigrationPlan
45
+ slot: OwnerSlot
46
+ }
47
+
48
+ /** The site's own version, from its package.json, which its steps may not run past. */
49
+ function siteVersion(siteDir: string | undefined): string | undefined {
50
+ if (!siteDir) return undefined
51
+ const file = join(siteDir, 'package.json')
52
+ if (!existsSync(file)) return undefined
53
+ try {
54
+ const version = (JSON.parse(readFileSync(file, 'utf8')) as { version?: unknown }).version
55
+ return typeof version === 'string' ? version : undefined
56
+ } catch {
57
+ return undefined
58
+ }
59
+ }
60
+
61
+ function chainOf(id: string, name: string, compiled: CompiledTables): TablesChain {
62
+ const slot: OwnerSlot = {}
63
+ return { id, name, compiled, plan: tablesPlan(compiled, slot), slot }
64
+ }
65
+
66
+ /** Why the site's own tables cannot be used: every reason, at once. */
67
+ export function siteTablesProblems(config: Pick<CromboloConfig, 'database' | 'siteDir'>): string[] {
68
+ const tables = config.database?.tables
69
+ const rules = config.database?.anonymise
70
+ if (!tables)
71
+ return rules === undefined
72
+ ? []
73
+ : ['database.anonymise is given, and there is no database.tables for it to describe.']
74
+ if (tables.id !== SITE_OWNER)
75
+ return [`database.tables is "${tables.id}"'s; the site's are made with defineSiteTables`]
76
+ const compiled = compileTables(tables, siteVersion(config.siteDir))
77
+ return [
78
+ ...compiled.problems.map((problem) => `The site's tables: ${problem}.`),
79
+ ...(rules === undefined || compiled.problems.length > 0
80
+ ? []
81
+ : anonymiseProblems(rules, compiled.schema).map((problem) => `The site's ${problem}.`)),
82
+ ]
83
+ }
84
+
85
+ /**
86
+ * The site's chain, then those of every wired bundle that declares tables, in
87
+ * wiring order. Throws when a declaration is invalid; boot reports the reasons
88
+ * first, from `siteTablesProblems` and `validateServerBundles`.
89
+ */
90
+ export function tablesChains(
91
+ config: Pick<CromboloConfig, 'database' | 'siteDir' | 'siteName'>,
92
+ bundles: readonly ServerBundle[],
93
+ packages: readonly BundlePackage[],
94
+ ): TablesChain[] {
95
+ const chains: TablesChain[] = []
96
+ const site = config.database?.tables
97
+ if (site)
98
+ chains.push(
99
+ chainOf(SITE_OWNER, config.siteName, compileTables(site, siteVersion(config.siteDir))),
100
+ )
101
+ for (const bundle of bundles) {
102
+ if (!bundle.tables) continue
103
+ const owner = packages.find((pkg) => pkg.id === bundle.id)
104
+ chains.push(
105
+ chainOf(bundle.id, owner?.name ?? bundle.id, compileTables(bundle.tables, owner?.version)),
106
+ )
107
+ }
108
+ return chains
109
+ }
110
+
111
+ /** The site's tables or bundles cannot be used: every reason, at once. */
112
+ export class BundleConfigurationError extends Error {
113
+ constructor(readonly problems: string[]) {
114
+ super(`The configured tables and bundles cannot be used:\n- ${problems.join('\n- ')}`)
115
+ }
116
+ }
117
+
118
+ /**
119
+ * The chains for a site's configuration, discovering its packages and checking
120
+ * the declarations exactly as boot checks them, so a command off the server
121
+ * refuses what the server would.
122
+ */
123
+ export function tablesChainsFor(
124
+ config: Pick<CromboloConfig, 'bundles' | 'siteDir' | 'database' | 'siteName'>,
125
+ ): TablesChain[] {
126
+ const packages = config.bundles.length > 0 ? discoverBundles(config.siteDir).bundles : []
127
+ const problems = [
128
+ ...siteTablesProblems(config),
129
+ ...(config.bundles.length > 0 ? validateServerBundles(config.bundles, packages, VERSION) : []),
130
+ ]
131
+ if (problems.length > 0) throw new BundleConfigurationError(problems)
132
+ return tablesChains(config, config.bundles, packages)
133
+ }
134
+
135
+ type OwnerConfig = Pick<CromboloConfig, 'siteName' | 'sqliteFile'>
136
+
137
+ /**
138
+ * Finds each chain's place, creating it where `provision` (a node that owns the
139
+ * database), and opens the connection its steps run on. A place never
140
+ * provisioned is left empty on a node that may not provision.
141
+ */
142
+ export async function openTables(
143
+ db: Db,
144
+ config: OwnerConfig,
145
+ chains: readonly TablesChain[],
146
+ options: { provision: boolean },
147
+ ): Promise<void> {
148
+ for (const chain of chains) {
149
+ if (chain.slot.place) continue
150
+ const place = options.provision
151
+ ? await provisionOwner(db, config, chain.id)
152
+ : await recordedOwner(db, config, chain.id)
153
+ if (!place) continue
154
+ chain.slot.place = place
155
+ chain.slot.db = await openOwner(db, place)
156
+ }
157
+ }
158
+
159
+ /** Closes the owners' own SQLite connections; a Postgres one only borrows the pool. */
160
+ export async function closeTables(chains: readonly TablesChain[]): Promise<void> {
161
+ for (const chain of chains) {
162
+ const owned = chain.slot.db
163
+ if (owned && chain.slot.place?.file !== ':memory:') await owned.close()
164
+ chain.slot.db = undefined
165
+ chain.slot.place = undefined
166
+ }
167
+ }
168
+
169
+ /** The owner's tables are not set up on this database. */
170
+ export class TablesNotReadyError extends Error {
171
+ constructor(readonly owner: string) {
172
+ super(
173
+ `The ${owner === SITE_OWNER ? "site's own tables are" : `bundle "${owner}"'s tables are`} not set up on this database yet. Start the node that owns the database, or run \`crombolo upgrade\`.`,
174
+ )
175
+ }
176
+ }
177
+
178
+ /** The Kysely handle on a chain's tables, on the connection that reaches only them. */
179
+ export function databaseFor(chain: TablesChain): TablesDatabase {
180
+ const owned = chain.slot.db
181
+ if (!chain.slot.place || !owned) throw new TablesNotReadyError(chain.id)
182
+ return tablesDatabase(owned, chain.compiled.schema) as TablesDatabase
183
+ }
184
+
185
+ export interface TablesPending {
186
+ id: string
187
+ name: string
188
+ state: string
189
+ pending: Migration[]
190
+ }
191
+
192
+ /** What each chain still has to run. Throws `UpgradeStateError`, naming the owner, when one is ahead. */
193
+ export async function pendingTablesSteps(
194
+ db: Db,
195
+ chains: readonly TablesChain[],
196
+ ): Promise<TablesPending[]> {
197
+ const out: TablesPending[] = []
198
+ for (const chain of chains)
199
+ out.push({
200
+ id: chain.id,
201
+ name: chain.name,
202
+ state: await readState(db, chain.plan),
203
+ pending: await pendingMigrations(db, chain.plan),
204
+ })
205
+ return out
206
+ }
207
+
208
+ /** Provisions each chain's place and runs its pending steps, in order, after core's. */
209
+ export async function migrateTables(
210
+ db: Db,
211
+ config: OwnerConfig,
212
+ chains: readonly TablesChain[],
213
+ options: { by?: string } = {},
214
+ ): Promise<{ id: string; applied: string[] }[]> {
215
+ await openTables(db, config, chains, { provision: true })
216
+ const out: { id: string; applied: string[] }[] = []
217
+ for (const chain of chains) {
218
+ const result = await migrate(db, chain.plan, { by: options.by })
219
+ out.push({ id: chain.id, applied: result.applied })
220
+ }
221
+ return out
222
+ }
223
+
224
+ /** What each chain would run, without running it. */
225
+ export async function planTablesUpgrades(
226
+ db: Db,
227
+ chains: readonly TablesChain[],
228
+ ): Promise<{ id: string; name: string; steps: PlannedStep[] }[]> {
229
+ const out: { id: string; name: string; steps: PlannedStep[] }[] = []
230
+ for (const chain of chains)
231
+ out.push({ id: chain.id, name: chain.name, steps: await planUpgrade(db, chain.plan) })
232
+ return out
233
+ }
234
+
235
+ export interface TablesReport {
236
+ id: string
237
+ name: string
238
+ pending: { name: string; kind: string; release: string | null }[]
239
+ /** What has run here since the owner was last purged, oldest first. */
240
+ applied: { name: string; kind: string; release: string | null; appliedAt: string }[]
241
+ }
242
+
243
+ /** Each chain's steps, applied and pending, as the Changes dashboard shows them. */
244
+ export async function tablesReport(
245
+ db: Db,
246
+ chains: readonly TablesChain[],
247
+ ): Promise<TablesReport[]> {
248
+ const ledger = await readLedger(db)
249
+ const out: TablesReport[] = []
250
+ for (const chain of chains) {
251
+ const rows = ledger.filter((row) => row.bundle === chain.id)
252
+ const purged = rows.map((row) => row.kind).lastIndexOf('purge')
253
+ const releases = new Map(chain.compiled.steps.map((step) => [step.name, step.release]))
254
+ out.push({
255
+ id: chain.id,
256
+ name: chain.name,
257
+ pending: (await pendingMigrations(db, chain.plan)).map((step) => ({
258
+ name: step.name,
259
+ kind: step.kind ?? 'expand',
260
+ release: step.release ?? null,
261
+ })),
262
+ applied: rows
263
+ .slice(purged + 1)
264
+ .filter((row) => row.kind === 'expand' || row.kind === 'contract')
265
+ .map((row) => ({
266
+ name: row.name,
267
+ kind: row.kind,
268
+ release: releases.get(row.name) ?? null,
269
+ appliedAt: row.appliedAt,
270
+ })),
271
+ })
272
+ }
273
+ return out
274
+ }
package/src/database.ts CHANGED
@@ -21,8 +21,8 @@ import {
21
21
  seedIdentity,
22
22
  } from '@crombolo/data'
23
23
  import { ensureApiClient } from './api-client.ts'
24
- import { type BundleChain, migrateBundles, pendingBundleSteps } from './bundle-tables.ts'
25
24
  import { type CromboloConfig, runsOnLocalhost } from './config.ts'
25
+ import { migrateTables, pendingTablesSteps, type TablesChain } from './custom-tables.ts'
26
26
  import { logger } from './logging.ts'
27
27
  import { linkMediaFolders } from './media-folders.ts'
28
28
 
@@ -30,7 +30,7 @@ import { linkMediaFolders } from './media-folders.ts'
30
30
  export class UpgradePendingError extends Error {
31
31
  constructor(
32
32
  readonly steps: string[],
33
- /** Each bundle with steps pending, and those steps. */
33
+ /** The site's own tables and each bundle's with steps pending, and those steps. */
34
34
  readonly bundles: { id: string; steps: string[] }[] = [],
35
35
  ) {
36
36
  const parts: string[] = []
@@ -40,7 +40,7 @@ export class UpgradePendingError extends Error {
40
40
  )
41
41
  for (const bundle of bundles)
42
42
  parts.push(
43
- `The bundle "${bundle.id}" has ${bundle.steps.length} step(s) pending on this database: ${bundle.steps.join(', ')}.`,
43
+ `${bundle.id === 'site' ? "The site's own tables have" : `The bundle "${bundle.id}" has`} ${bundle.steps.length} step(s) pending on this database: ${bundle.steps.join(', ')}.`,
44
44
  )
45
45
  super(
46
46
  `${parts.join(' ')} ` +
@@ -72,31 +72,39 @@ export class DatabaseNotReadyError extends Error {
72
72
  * migrated would race the node that owns the schema, and one that quietly
73
73
  * served an unmigrated database would answer queries against missing tables.
74
74
  */
75
- export async function attachDatabase(config: CromboloConfig): Promise<Bootstrap> {
75
+ export async function attachDatabase(
76
+ config: CromboloConfig,
77
+ chains: readonly TablesChain[] = [],
78
+ ): Promise<Bootstrap> {
76
79
  const db = await connect({ dialect: config.dialect, file: config.sqliteFile })
77
- const pending = await pendingMigrations(db, cromboloPlan)
78
- if (pending.length > 0) {
80
+ try {
81
+ const pending = (await pendingMigrations(db, cromboloPlan)).map((m) => m.name)
82
+ // The site's own tables too: its named queries run on this node.
83
+ for (const chain of await pendingTablesSteps(db, chains))
84
+ pending.push(...chain.pending.map((m) => `${chain.id}: ${m.name}`))
85
+ if (pending.length > 0) throw new DatabaseNotReadyError(pending)
86
+ } catch (error) {
79
87
  await db.close()
80
- throw new DatabaseNotReadyError(pending.map((m) => m.name))
88
+ throw error
81
89
  }
82
90
  return { db, seededAdminPassword: undefined }
83
91
  }
84
92
 
85
93
  /**
86
- * `chains` are the wired bundles' tables, which only a node that mounts bundles
87
- * passes: a bundle's steps pending in production refuse the boot just as
88
- * core's do, and a database ahead of a bundle's code refuses it by name.
94
+ * `chains` are the custom tables: the site's and the wired bundles'. Their
95
+ * steps pending in production refuse the boot just as core's do, and a
96
+ * database ahead of their code refuses it by name.
89
97
  */
90
98
  export async function bootstrapDatabase(
91
99
  config: CromboloConfig,
92
- chains: readonly BundleChain[] = [],
100
+ chains: readonly TablesChain[] = [],
93
101
  ): Promise<Bootstrap> {
94
102
  const db = await connect({ dialect: config.dialect, file: config.sqliteFile })
95
103
  try {
96
104
  // pendingMigrations throws when the database is newer than this code.
97
105
  const pending = await pendingMigrations(db, cromboloPlan)
98
106
  const fresh = (await readState(db)) === INITIAL_STATE
99
- const bundles = fresh ? [] : await pendingBundleSteps(db, chains)
107
+ const bundles = fresh ? [] : await pendingTablesSteps(db, chains)
100
108
  const bundlesPending = bundles.filter((bundle) => bundle.pending.length > 0)
101
109
  if ((pending.length > 0 || bundlesPending.length > 0) && !fresh && !config.development)
102
110
  throw new UpgradePendingError(
@@ -122,11 +130,11 @@ export async function bootstrapDatabase(
122
130
  export async function installDatabase(
123
131
  db: Db,
124
132
  config: CromboloConfig,
125
- chains: readonly BundleChain[] = [],
133
+ chains: readonly TablesChain[] = [],
126
134
  ): Promise<string | undefined> {
127
135
  await migrate(db, cromboloPlan, { by: config.nodeId })
128
136
  // Core first, so a bundle step always runs against a core it declared itself compatible with.
129
- await migrateBundles(db, chains, { by: config.nodeId })
137
+ await migrateTables(db, config, chains, { by: config.nodeId })
130
138
 
131
139
  // In production a password is never made up: the pipeline supplies one, or
132
140
  // the owner sets the site up in the browser (docs/operations.md). With an API
@@ -72,7 +72,7 @@ export async function importDictionaryUdt(
72
72
  return { ok: false, reason: 'the parent item does not exist', imported: 0, skipped: [] }
73
73
 
74
74
  const languages = new Set(
75
- (await db.query<{ iso_code: string }>('SELECT iso_code FROM language')).map((row) =>
75
+ (await db.q.selectFrom('language').select('iso_code').execute()).map((row) =>
76
76
  String(row.iso_code).toLowerCase(),
77
77
  ),
78
78
  )
package/src/git-routes.ts CHANGED
@@ -9,7 +9,7 @@
9
9
  import { existsSync } from 'node:fs'
10
10
  import { readdir, readFile } from 'node:fs/promises'
11
11
  import { join, relative, sep } from 'node:path'
12
- import type { Principal } from '@crombolo/api-management'
12
+ import type { Principal } from '@crombolo/api-management/domain'
13
13
  import { diffFiles, type GitProvider, type RepositoryFile } from './git.ts'
14
14
  import { logger } from './logging.ts'
15
15
 
@@ -5,7 +5,7 @@
5
5
  * the provider; these are only the fields changed, put on top of it at every
6
6
  * sign-in, so a change reaches every node with nothing to invalidate.
7
7
  */
8
- import type { Db, ExternalLoginAudience } from '@crombolo/data'
8
+ import { type Db, type ExternalLoginAudience, now } from '@crombolo/data'
9
9
  import { entraIssuer, type IdentityProvider } from './identity-providers.ts'
10
10
  import { openSecret, SECRET_KEY_VARIABLE, sealSecret, usableSecretKey } from './secrets.ts'
11
11
 
@@ -85,10 +85,11 @@ export class IdentityProviderOverrides {
85
85
  }
86
86
 
87
87
  async #read(audience: ExternalLoginAudience, id: string): Promise<Stored> {
88
- const rows = await this.#db.query<{ value: string | null }>(
89
- 'SELECT value FROM key_value WHERE key = ?',
90
- [keyOf(audience, id)],
91
- )
88
+ const rows = await this.#db.q
89
+ .selectFrom('key_value')
90
+ .select('value')
91
+ .where('key', '=', keyOf(audience, id))
92
+ .execute()
92
93
  try {
93
94
  return rows[0]?.value ? (JSON.parse(rows[0].value) as Stored) : {}
94
95
  } catch {
@@ -148,26 +149,27 @@ export class IdentityProviderOverrides {
148
149
 
149
150
  /** Puts a provider back to what the config says. */
150
151
  async reset(audience: ExternalLoginAudience, id: string): Promise<void> {
151
- await this.#db.exec('DELETE FROM key_value WHERE key = ?', [keyOf(audience, id)])
152
+ await this.#db.q.deleteFrom('key_value').where('key', '=', keyOf(audience, id)).execute()
152
153
  }
153
154
 
154
155
  async #write(audience: ExternalLoginAudience, id: string, stored: Stored): Promise<void> {
155
156
  const key = keyOf(audience, id)
156
- const now = this.#db.dialect.now()
157
157
  if (Object.keys(stored).length === 0) {
158
- await this.#db.exec('DELETE FROM key_value WHERE key = ?', [key])
158
+ await this.#db.q.deleteFrom('key_value').where('key', '=', key).execute()
159
159
  return
160
160
  }
161
161
  const value = JSON.stringify(stored)
162
- const updated = await this.#db.query<{ key: string }>(
163
- `UPDATE key_value SET value = ?, update_date = ${now} WHERE key = ? RETURNING key`,
164
- [value, key],
165
- )
162
+ const updated = await this.#db.q
163
+ .updateTable('key_value')
164
+ .set({ value, update_date: now(this.#db) })
165
+ .where('key', '=', key)
166
+ .returning('key')
167
+ .execute()
166
168
  if (updated.length === 0)
167
- await this.#db.exec(`INSERT INTO key_value (key, value, update_date) VALUES (?, ?, ${now})`, [
168
- key,
169
- value,
170
- ])
169
+ await this.#db.q
170
+ .insertInto('key_value')
171
+ .values({ key, value, update_date: now(this.#db) })
172
+ .execute()
171
173
  }
172
174
  }
173
175