@crombolo/server 0.50.0 → 0.51.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.50.0",
3
+ "version": "0.51.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.50.0",
35
- "@crombolo/api-management": "0.50.0",
36
- "@crombolo/auth": "0.50.0",
37
- "@crombolo/backoffice-host": "0.50.0",
38
- "@crombolo/common": "0.50.0",
39
- "@crombolo/content": "0.50.0",
40
- "@crombolo/contracts": "0.50.0",
41
- "@crombolo/core": "0.50.0",
42
- "@crombolo/data": "0.50.0",
43
- "@crombolo/render": "0.50.0",
44
- "@crombolo/schema": "0.50.0",
45
- "@crombolo/transfer": "0.50.0",
34
+ "@crombolo/api-delivery": "0.51.0",
35
+ "@crombolo/api-management": "0.51.0",
36
+ "@crombolo/auth": "0.51.0",
37
+ "@crombolo/backoffice-host": "0.51.0",
38
+ "@crombolo/common": "0.51.0",
39
+ "@crombolo/content": "0.51.0",
40
+ "@crombolo/contracts": "0.51.0",
41
+ "@crombolo/core": "0.51.0",
42
+ "@crombolo/data": "0.51.0",
43
+ "@crombolo/render": "0.51.0",
44
+ "@crombolo/schema": "0.51.0",
45
+ "@crombolo/transfer": "0.51.0",
46
46
  "@logtape/logtape": "^2.3.8",
47
47
  "@opentelemetry/api": "1.10.0",
48
48
  "@opentelemetry/context-async-hooks": "3.0.0",
@@ -12,6 +12,7 @@ import {
12
12
  type BundleFile,
13
13
  bundleIdFor,
14
14
  codePatternsOf,
15
+ type PublicFile,
15
16
  readCodeFiles,
16
17
  selectCodeFiles,
17
18
  writeBundle,
@@ -21,8 +22,10 @@ import { createFileSystemPort } from './adapters/file-system.ts'
21
22
  import { createTemplateFileStore } from './adapters/template-files.ts'
22
23
  import { loadConfig, VERSION } from './config.ts'
23
24
  import { bootstrapDatabase } from './database.ts'
25
+ import { applyDictionaryEntries } from './dictionary-transfer.ts'
24
26
  import { syncSchemaDirectory } from './schema.ts'
25
27
  import { compileSeed, type SeedBuild } from './seed/compile.ts'
28
+ import { publicSources } from './site-public.ts'
26
29
  import { siteSections } from './site-sections.ts'
27
30
 
28
31
  export interface BundleBuildOptions {
@@ -52,6 +55,8 @@ export interface BundleBuildResult {
52
55
  name: string
53
56
  /** The site's code the bundle carries, by path; absent when it carries none. */
54
57
  code?: string[]
58
+ /** The files it carries from `public/`. */
59
+ publicFiles?: PublicFile[]
55
60
  }
56
61
 
57
62
  /** What a directory calls its site: `site.json`, then `package.json`, then its folder. */
@@ -101,6 +106,7 @@ export async function buildBundleFromDirectory(
101
106
  componentsDir: join(dir, 'components'),
102
107
  stylesheetsDir: join(dir, 'css'),
103
108
  scriptsDir: join(dir, 'scripts'),
109
+ publicDir: join(dir, 'public'),
104
110
  mediaDir: join(work, 'media'),
105
111
  logsDir: join(work, 'logs'),
106
112
  development: true,
@@ -127,6 +133,7 @@ export async function buildBundleFromDirectory(
127
133
  seed,
128
134
  name,
129
135
  }
136
+ if (seed.dictionary) await applyDictionaryEntries(db, seed.dictionary)
130
137
  const sections = await siteSections(
131
138
  {
132
139
  db,
@@ -149,11 +156,14 @@ export async function buildBundleFromDirectory(
149
156
  createdBy: 'crombolo bundle build',
150
157
  },
151
158
  }
159
+ const publicFiles = publicSources(config.publicDir)
152
160
  const files = writeBundlePackage(
153
- writeBundle(set, options.media === false ? new Map() : seed.blobs, [
154
- ...sections,
155
- ...(code ? readCodeFiles(dir, code.paths) : []),
156
- ]),
161
+ writeBundle(
162
+ set,
163
+ options.media === false ? new Map() : seed.blobs,
164
+ [...sections, ...(code ? readCodeFiles(dir, code.paths) : [])],
165
+ { public: publicFiles },
166
+ ),
157
167
  {
158
168
  name,
159
169
  version: '1.0.0',
@@ -164,7 +174,14 @@ export async function buildBundleFromDirectory(
164
174
  peerRange: `>=${VERSION}`,
165
175
  },
166
176
  )
167
- return { problems: [], seed, files, name, ...(code ? { code: code.paths } : {}) }
177
+ return {
178
+ problems: [],
179
+ seed,
180
+ files,
181
+ name,
182
+ publicFiles,
183
+ ...(code ? { code: code.paths } : {}),
184
+ }
168
185
  } finally {
169
186
  await db.close()
170
187
  }
@@ -24,6 +24,7 @@ import {
24
24
  readFileSync,
25
25
  renameSync,
26
26
  rmSync,
27
+ statSync,
27
28
  writeFileSync,
28
29
  } from 'node:fs'
29
30
  import { tmpdir } from 'node:os'
@@ -105,21 +106,25 @@ function destinationOf(config: CromboloConfig, section: BundleSection): string |
105
106
  return config.stylesheetsDir
106
107
  case 'scripts':
107
108
  return config.scriptsDir
109
+ case 'public':
110
+ return config.publicDir
108
111
  case 'dictionary':
109
112
  return undefined
110
113
  }
111
114
  }
112
115
 
113
- const FILE_SECTIONS: readonly BundleSection[] = ['components', 'styles', 'scripts']
116
+ const FILE_SECTIONS: readonly BundleSection[] = ['components', 'styles', 'scripts', 'public']
114
117
 
115
118
  /** The path inside a section, with the section's own directory stripped. */
116
119
  const withinSection = (path: string, section: BundleSection): string =>
117
120
  path.slice(`${BUNDLE_SECTIONS[section]}/`.length)
118
121
 
119
- function actionFor(target: string, content: string): FileAction {
122
+ /** Compared as bytes: a public file is an image as often as it is text. */
123
+ function actionFor(target: string, source: string): FileAction {
120
124
  if (!existsSync(target)) return 'create'
121
125
  try {
122
- return readFileSync(target, 'utf8') === content ? 'unchanged' : 'overwrite'
126
+ if (statSync(target).size !== statSync(source).size) return 'overwrite'
127
+ return readFileSync(target).equals(readFileSync(source)) ? 'unchanged' : 'overwrite'
123
128
  } catch {
124
129
  return 'overwrite'
125
130
  }
@@ -137,12 +142,16 @@ export function carriedSections(loaded: LoadedBundle): CarriedSections {
137
142
  return { carries: loaded.set?.manifest.carries ?? {}, files: loaded.files }
138
143
  }
139
144
 
140
- const read = (carried: CarriedSections, path: string): string => {
145
+ /** The file on disk holding a carried path. */
146
+ const sourceOf = (carried: CarriedSections, path: string): string => {
141
147
  const file = carried.files.get(path)
142
148
  if (!file) throw new Error(`${path} is declared but was not read`)
143
- return readFileSync(file, 'utf8')
149
+ return file
144
150
  }
145
151
 
152
+ const read = (carried: CarriedSections, path: string): string =>
153
+ readFileSync(sourceOf(carried, path), 'utf8')
154
+
146
155
  /** Read-only: what applying the carried sections here would do. */
147
156
  export async function planSections(
148
157
  db: Db,
@@ -159,7 +168,7 @@ export async function planSections(
159
168
  if (!destination) continue
160
169
  for (const path of carried.carries[section] ?? []) {
161
170
  const target = join(destination, withinSection(path, section))
162
- files.push({ path, target, action: actionFor(target, read(carried, path)) })
171
+ files.push({ path, target, action: actionFor(target, sourceOf(carried, path)) })
163
172
  }
164
173
  }
165
174
  }
@@ -168,7 +177,7 @@ export async function planSections(
168
177
  if (!options.withoutSchema) {
169
178
  for (const path of schemaPaths) {
170
179
  const target = join(config.schemaDir, withinSection(path, 'schema'))
171
- files.push({ path, target, action: actionFor(target, read(carried, path)) })
180
+ files.push({ path, target, action: actionFor(target, sourceOf(carried, path)) })
172
181
  }
173
182
  }
174
183
 
@@ -254,8 +263,8 @@ export async function applySections(
254
263
  * site, so a revert re-derives the destination through the same mapping — and
255
264
  * restores to where the file would go now, not where it went then.
256
265
  */
257
- const put = (target: string, content: string, bundlePath: string) => {
258
- const action = actionFor(target, content)
266
+ const put = (target: string, source: string, bundlePath: string) => {
267
+ const action = actionFor(target, source)
259
268
  if (action === 'overwrite' && options.backupDir) {
260
269
  const keep = join(options.backupDir, REPLACED_DIR, bundlePath)
261
270
  mkdirSync(dirname(keep), { recursive: true })
@@ -264,13 +273,13 @@ export async function applySections(
264
273
  }
265
274
  records.push({ path: bundlePath, action })
266
275
  mkdirSync(dirname(target), { recursive: true })
267
- writeFileSync(target, content)
276
+ copyFileSync(source, target)
268
277
  written.push(target)
269
278
  }
270
279
 
271
280
  const schemaPaths = options.withoutSchema ? [] : (carried.carries.schema ?? [])
272
281
  for (const path of schemaPaths)
273
- put(join(config.schemaDir, withinSection(path, 'schema')), read(carried, path), path)
282
+ put(join(config.schemaDir, withinSection(path, 'schema')), sourceOf(carried, path), path)
274
283
 
275
284
  let schema: { action: string } | undefined
276
285
  if (schemaPaths.length > 0) {
@@ -290,7 +299,7 @@ export async function applySections(
290
299
  const destination = destinationOf(config, section)
291
300
  if (!destination) continue
292
301
  for (const path of carried.carries[section] ?? [])
293
- put(join(destination, withinSection(path, section)), read(carried, path), path)
302
+ put(join(destination, withinSection(path, section)), sourceOf(carried, path), path)
294
303
  }
295
304
  }
296
305
 
@@ -515,7 +524,7 @@ export function stageSections(
515
524
  const inside = withinSection(path, section)
516
525
  const target = join(next, inside)
517
526
  mkdirSync(dirname(target), { recursive: true })
518
- writeFileSync(target, read(carried, path))
527
+ copyFileSync(sourceOf(carried, path), target)
519
528
  staged.written.push(join(destination, inside))
520
529
  }
521
530
  staged.next[section] = next
@@ -531,6 +540,7 @@ export function stagedConfig(config: CromboloConfig, staged: StagedSections): Cr
531
540
  componentsDir: staged.next.components ?? config.componentsDir,
532
541
  stylesheetsDir: staged.next.styles ?? config.stylesheetsDir,
533
542
  scriptsDir: staged.next.scripts ?? config.scriptsDir,
543
+ publicDir: staged.next.public ?? config.publicDir,
534
544
  }
535
545
  }
536
546
 
package/src/config.ts CHANGED
@@ -382,6 +382,8 @@ export interface CromboloConfig {
382
382
  stylesheetsDir: string
383
383
  /** Scripts the Settings section edits, served at `/scripts/`. */
384
384
  scriptsDir: string
385
+ /** The site's public files, served at the root of the site (story 284). */
386
+ publicDir: string
385
387
  /** Umbraco's `UsernameIsEmail`: a user's login is their e-mail address. */
386
388
  usernameIsEmail: boolean
387
389
  /** The site's public URL, which invitation and reset links point at. */
@@ -617,6 +619,7 @@ export const DEFAULTS = {
617
619
  stylesheetsDir: 'css',
618
620
  logsDir: 'logs',
619
621
  scriptsDir: 'scripts',
622
+ publicDir: 'public',
620
623
  marketplaceUrl: 'https://www.npmjs.com/search?q=keywords%3Acrombolo-bundle',
621
624
  packageKeyword: 'crombolo-bundle',
622
625
  npmRegistry: 'https://registry.npmjs.org',
@@ -857,6 +860,7 @@ export function loadConfig(
857
860
  },
858
861
  stylesheetsDir: setting('CROMBOLO_CSS_DIR') ?? DEFAULTS.stylesheetsDir,
859
862
  scriptsDir: setting('CROMBOLO_SCRIPTS_DIR') ?? DEFAULTS.scriptsDir,
863
+ publicDir: setting('CROMBOLO_PUBLIC_DIR') ?? DEFAULTS.publicDir,
860
864
  usernameIsEmail: setting('CROMBOLO_USERNAME_IS_EMAIL') !== 'false',
861
865
  applicationUrl: setting('CROMBOLO_APPLICATION_URL') ?? '',
862
866
  sendUserLink: undefined,
@@ -1032,6 +1036,7 @@ export function loadConfig(
1032
1036
  merged.logsDir = resolve(cwd, merged.logsDir)
1033
1037
  merged.stylesheetsDir = resolve(cwd, merged.stylesheetsDir)
1034
1038
  merged.scriptsDir = resolve(cwd, merged.scriptsDir)
1039
+ merged.publicDir = resolve(cwd, merged.publicDir)
1035
1040
  merged.applicationUrl = (merged.applicationUrl || `http://localhost:${merged.port}`).replace(
1036
1041
  /\/$/,
1037
1042
  '',
@@ -1086,7 +1091,7 @@ export function describeDatabase(
1086
1091
  }
1087
1092
  }
1088
1093
 
1089
- export const VERSION = '0.50.0'
1094
+ export const VERSION = '0.51.0'
1090
1095
 
1091
1096
  /** A whole number of seconds from the environment; undefined when unset or not one. */
1092
1097
  /** A positive number from a setting, else the default. */
@@ -0,0 +1,72 @@
1
+ /**
2
+ * The dictionary as a TOML file a person can write (story 168). A table is an
3
+ * item, named by its whole name; inside it, a string is a translation and a
4
+ * table is a child, so nothing needs a reserved word.
5
+ * docs/content-transfer.md, "The dictionary as a file".
6
+ */
7
+ import type { DictionaryEntry } from './dictionary-transfer.ts'
8
+
9
+ export interface DictionaryFileProblem {
10
+ /** The tables leading to it, for a seed finding's line. */
11
+ path: string[]
12
+ message: string
13
+ }
14
+
15
+ const isTable = (value: unknown): value is Record<string, unknown> =>
16
+ typeof value === 'object' && value !== null && !Array.isArray(value) && !(value instanceof Date)
17
+
18
+ /** The items a file holds, and everything wrong with it. A file with problems is not applied. */
19
+ export function readDictionaryToml(text: string): {
20
+ entries: DictionaryEntry[]
21
+ problems: DictionaryFileProblem[]
22
+ } {
23
+ let root: unknown
24
+ try {
25
+ root = Bun.TOML.parse(text)
26
+ } catch (error) {
27
+ const message = `not valid TOML: ${error instanceof Error ? error.message : String(error)}`
28
+ return { entries: [], problems: [{ path: [], message }] }
29
+ }
30
+ const problems: DictionaryFileProblem[] = []
31
+ const seen = new Set<string>()
32
+ const item = (name: string, table: Record<string, unknown>, path: string[]): DictionaryEntry => {
33
+ // Names are unique across the dictionary, not within a parent.
34
+ if (seen.has(name)) problems.push({ path, message: `"${name}" appears twice` })
35
+ seen.add(name)
36
+ const entry: DictionaryEntry = { name, translations: [], children: [] }
37
+ for (const [key, value] of Object.entries(table)) {
38
+ if (typeof value === 'string') entry.translations.push({ isoCode: key, translation: value })
39
+ else if (isTable(value)) entry.children.push(item(key, value, [...path, key]))
40
+ else
41
+ problems.push({
42
+ path: [...path, key],
43
+ message: `"${key}" under "${name}" is neither a translation nor a child item`,
44
+ })
45
+ }
46
+ return entry
47
+ }
48
+ const entries: DictionaryEntry[] = []
49
+ for (const [name, value] of Object.entries(root as Record<string, unknown>)) {
50
+ if (isTable(value)) entries.push(item(name, value, [name]))
51
+ else problems.push({ path: [name], message: `"${name}" belongs to no item: give it a table` })
52
+ }
53
+ return { entries, problems }
54
+ }
55
+
56
+ const keyOf = (name: string) => (/^[A-Za-z0-9_-]+$/.test(name) ? name : JSON.stringify(name))
57
+
58
+ /** The items as a file, sorted so a diff means something. Reads back as the same items. */
59
+ export function writeDictionaryToml(entries: readonly DictionaryEntry[]): string {
60
+ const blocks: string[] = []
61
+ const write = (entry: DictionaryEntry, parents: string[]) => {
62
+ const path = [...parents, keyOf(entry.name)]
63
+ const lines = [...entry.translations]
64
+ .sort((a, b) => a.isoCode.localeCompare(b.isoCode))
65
+ .map((t) => `${keyOf(t.isoCode)} = ${JSON.stringify(t.translation)}`)
66
+ blocks.push([`[${path.join('.')}]`, ...lines].join('\n'))
67
+ for (const child of [...entry.children].sort((a, b) => a.name.localeCompare(b.name)))
68
+ write(child, path)
69
+ }
70
+ for (const entry of [...entries].sort((a, b) => a.name.localeCompare(b.name))) write(entry, [])
71
+ return `${blocks.join('\n\n')}\n`
72
+ }
@@ -11,7 +11,14 @@
11
11
  * the same `.udt` format Umbraco uses, the same upsert by key, and the same rule
12
12
  * that translations for languages this site does not have are skipped.
13
13
  */
14
- import { type Db, DictionaryRepository } from '@crombolo/data'
14
+ import { normaliseUuid, SEED_NAMESPACE, uuidV5 } from '@crombolo/core'
15
+ import {
16
+ appendCacheInstruction,
17
+ type Db,
18
+ type DictionaryItem,
19
+ DictionaryRepository,
20
+ type DictionaryTranslation,
21
+ } from '@crombolo/data'
15
22
  import { readUdt, type UdtItem, writeUdtAll } from './udt.ts'
16
23
 
17
24
  export interface DictionaryImportOutcome {
@@ -56,6 +63,182 @@ export async function dictionaryToUdt(
56
63
 
57
64
  export const writeDictionaryUdt = writeUdtAll
58
65
 
66
+ /** An item as a person writes it: named, with no key of its own. */
67
+ export interface DictionaryEntry {
68
+ name: string
69
+ translations: DictionaryTranslation[]
70
+ children: DictionaryEntry[]
71
+ }
72
+
73
+ /** What applying named items did, or would do. */
74
+ export interface DictionaryChange {
75
+ ok: boolean
76
+ reason?: string
77
+ created: string[]
78
+ updated: string[]
79
+ moved: string[]
80
+ unchanged: number
81
+ /** Translations dropped because this environment has no such language. */
82
+ skipped: string[]
83
+ }
84
+
85
+ /** A new item's key, the same on every site built from one file. */
86
+ export const dictionaryKey = (name: string) => uuidV5(`dictionary/${name}`, SEED_NAMESPACE)
87
+
88
+ /** Carries a dry run's outcome out of the transaction it rolls back. */
89
+ class Undone<T> extends Error {
90
+ constructor(readonly outcome: T) {
91
+ super('undone')
92
+ }
93
+ }
94
+
95
+ /**
96
+ * One dictionary write in a transaction, telling every node when it changed
97
+ * something (story 174). A failure leaves nothing behind, and a dry run is the
98
+ * real write undone, so it reports exactly what would happen.
99
+ */
100
+ export async function writingDictionary<T extends { ok: boolean }>(
101
+ db: Db,
102
+ options: { dryRun?: boolean; by?: string },
103
+ write: (tx: Db) => Promise<T>,
104
+ changed: (outcome: T) => boolean,
105
+ ): Promise<T> {
106
+ try {
107
+ return await db.transaction(async (tx) => {
108
+ const outcome = await write(tx)
109
+ if (options.dryRun || !outcome.ok) throw new Undone(outcome)
110
+ if (changed(outcome))
111
+ await appendCacheInstruction(tx, {
112
+ kind: 'content',
113
+ payload: { dictionary: true },
114
+ by: options.by,
115
+ })
116
+ return outcome
117
+ })
118
+ } catch (error) {
119
+ if (error instanceof Undone) return error.outcome as T
120
+ throw error
121
+ }
122
+ }
123
+
124
+ const sameKey = (a: string | null, b: string | null) =>
125
+ (a ? normaliseUuid(a) : null) === (b ? normaliseUuid(b) : null)
126
+
127
+ /**
128
+ * Applies items by name. It adds and changes and never deletes, and a language
129
+ * an entry does not name is kept. `keepPlace` leaves an existing top-level item
130
+ * under its parent: `dictionary set` names no place, where a file states one.
131
+ */
132
+ export async function applyDictionaryEntries(
133
+ db: Db,
134
+ entries: readonly DictionaryEntry[],
135
+ options: { parentKey?: string | null; keepPlace?: boolean; dryRun?: boolean; by?: string } = {},
136
+ ): Promise<DictionaryChange> {
137
+ return writingDictionary(
138
+ db,
139
+ options,
140
+ async (tx) => {
141
+ const repo = new DictionaryRepository(tx)
142
+ const languages = new Map(
143
+ (await tx.q.selectFrom('language').select('iso_code').execute()).map((row) => [
144
+ String(row.iso_code).toLowerCase(),
145
+ String(row.iso_code),
146
+ ]),
147
+ )
148
+ const skipped = new Set<string>()
149
+ const known = (entry: DictionaryEntry) =>
150
+ entry.translations.flatMap((t) => {
151
+ const isoCode = languages.get(t.isoCode.toLowerCase())
152
+ if (!isoCode) skipped.add(t.isoCode)
153
+ return isoCode ? [{ isoCode, translation: t.translation }] : []
154
+ })
155
+
156
+ const change: DictionaryChange = {
157
+ ok: true,
158
+ created: [],
159
+ updated: [],
160
+ moved: [],
161
+ unchanged: 0,
162
+ skipped: [],
163
+ }
164
+ const failed = (name: string, result: string) => {
165
+ change.ok = false
166
+ change.reason = `"${name}" could not be written: ${result}`
167
+ }
168
+ const update = async (entry: DictionaryEntry, item: DictionaryItem) => {
169
+ const mine = known(entry)
170
+ const differs = mine.some(
171
+ (t) =>
172
+ item.translations.find((o) => o.isoCode.toLowerCase() === t.isoCode.toLowerCase())
173
+ ?.translation !== t.translation,
174
+ )
175
+ if (!differs) return false
176
+ const result = await repo.update(item.key, {
177
+ name: item.name,
178
+ translations: [
179
+ ...item.translations.filter(
180
+ (t) => !mine.some((n) => n.isoCode.toLowerCase() === t.isoCode.toLowerCase()),
181
+ ),
182
+ ...mine,
183
+ ],
184
+ })
185
+ if (result === 'Success') return true
186
+ failed(entry.name, result)
187
+ return false
188
+ }
189
+ const apply = async (
190
+ entry: DictionaryEntry,
191
+ parent: string | null,
192
+ place: boolean,
193
+ ): Promise<void> => {
194
+ const existing = await repo.byName(entry.name)
195
+ let key = existing?.key
196
+ if (existing) {
197
+ const updated = await update(entry, existing)
198
+ const moves = place && !sameKey(existing.parentKey, parent)
199
+ if (moves) {
200
+ const result = await repo.move(existing.key, parent)
201
+ if (result === 'Success') change.moved.push(entry.name)
202
+ else failed(entry.name, result)
203
+ }
204
+ if (updated) change.updated.push(entry.name)
205
+ else if (!moves) change.unchanged += 1
206
+ } else {
207
+ // A site that renamed an item keeps its key; the name now is a new item.
208
+ const wanted = dictionaryKey(entry.name)
209
+ key = (await repo.get(wanted)) ? crypto.randomUUID() : wanted
210
+ const result = await repo.create({
211
+ key,
212
+ name: entry.name,
213
+ parentKey: parent,
214
+ translations: known(entry),
215
+ })
216
+ if (result === 'Success') change.created.push(entry.name)
217
+ else failed(entry.name, result)
218
+ }
219
+ if (!change.ok) return
220
+ for (const child of entry.children) await apply(child, key as string, true)
221
+ }
222
+ for (const entry of entries) {
223
+ await apply(entry, options.parentKey ?? null, !options.keepPlace)
224
+ if (!change.ok) break
225
+ }
226
+ change.skipped = [...skipped]
227
+ return change
228
+ },
229
+ (change) => change.created.length + change.updated.length + change.moved.length > 0,
230
+ )
231
+ }
232
+
233
+ /** Named items as `.udt` items, keyed as `applyDictionaryEntries` would key them. */
234
+ export const keyedEntries = (entries: readonly DictionaryEntry[]): UdtItem[] =>
235
+ entries.map((entry) => ({
236
+ key: dictionaryKey(entry.name),
237
+ name: entry.name,
238
+ translations: entry.translations,
239
+ children: keyedEntries(entry.children),
240
+ }))
241
+
59
242
  /**
60
243
  * Applies a `.udt` file. Items are upserted by key, so running it twice is a
61
244
  * no-op and an item translated here keeps any language the file does not carry.
package/src/index.ts CHANGED
@@ -41,6 +41,7 @@ export * from './cron.ts'
41
41
  export * from './custom-tables.ts'
42
42
  export * from './database.ts'
43
43
  export * from './diagnostics.ts'
44
+ export * from './dictionary-toml.ts'
44
45
  export * from './dictionary-transfer.ts'
45
46
  export * from './domains.ts'
46
47
  export * from './editor-types.ts'
@@ -109,6 +110,7 @@ export * from './settings.ts'
109
110
  export * from './setup.ts'
110
111
  export * from './site-data.ts'
111
112
  export * from './site-file.ts'
113
+ export * from './site-public.ts'
112
114
  export * from './site-queries.ts'
113
115
  export * from './site-replace.ts'
114
116
  export * from './site-sections.ts'
package/src/remote.ts CHANGED
@@ -58,11 +58,12 @@ import { describeProvenance, provenanceProblem, verifyProvenance } from './prove
58
58
  import { createCiSignIn, readRuleInput, trustedIssuers } from './remote-ci.ts'
59
59
  import { openSecret, sealSecret, usableSecretKey } from './secrets.ts'
60
60
  import { exportSite } from './site-file.ts'
61
+ import { REMOTE_DISCOVERY_PATH } from './site-public.ts'
61
62
  import { replaceSummary } from './site-replace.ts'
62
63
  import { extractTarball } from './tar.ts'
63
64
 
64
65
  export const REMOTE_PROTOCOL_VERSION = '1'
65
- export const REMOTE_DISCOVERY_PATH = '/.well-known/crombolo-remote'
66
+ export { REMOTE_DISCOVERY_PATH }
66
67
  export const REMOTE_API_PATH = '/umbraco/remote/v1'
67
68
 
68
69
  /** How long a finished job's file stays downloadable, and its row with it. */
@@ -1175,6 +1176,7 @@ export function createRemote(options: RemoteOptions): Remote {
1175
1176
  { section: 'components', dir: config.componentsDir },
1176
1177
  { section: 'styles', dir: config.stylesheetsDir },
1177
1178
  { section: 'scripts', dir: config.scriptsDir },
1179
+ { section: 'public', dir: config.publicDir },
1178
1180
  ]
1179
1181
  const summary = await replaceSummary(
1180
1182
  db,
@@ -26,6 +26,7 @@ import {
26
26
  } from '@crombolo/data'
27
27
  import {
28
28
  BUNDLE_FORMAT_VERSION,
29
+ BUNDLE_SECTIONS,
29
30
  type BundleBlob,
30
31
  type BundleFile,
31
32
  type BundleKind,
@@ -38,9 +39,17 @@ import {
38
39
  } from '@crombolo/transfer'
39
40
  import { createMediaPort } from '../adapters/media.ts'
40
41
  import { type CromboloConfig, VERSION } from '../config.ts'
42
+ import { type DictionaryEntry, keyedEntries, writeDictionaryUdt } from '../dictionary-transfer.ts'
41
43
  import { SEED_NAMESPACE, seedKey, uuidV5 } from './keys.ts'
42
44
  import { lineOf } from './lines.ts'
43
- import { kindDir, readSeed, type SeedFinding, type SeedItem } from './read.ts'
45
+ import {
46
+ DICTIONARY_FILE,
47
+ kindDir,
48
+ readSeed,
49
+ readSeedDictionary,
50
+ type SeedFinding,
51
+ type SeedItem,
52
+ } from './read.ts'
44
53
  import { schemaLookup, valueWriter } from './values.ts'
45
54
 
46
55
  export interface SeedBuild {
@@ -52,6 +61,8 @@ export interface SeedBuild {
52
61
  files?: BundleFile[]
53
62
  /** How many items of each kind it holds. */
54
63
  counts: Record<'content' | 'library' | 'media', number>
64
+ /** `content/dictionary.toml`, as the items it holds (story 168). */
65
+ dictionary?: DictionaryEntry[]
55
66
  }
56
67
 
57
68
  /** A word for a file name: `about-us` → `About us`. */
@@ -69,6 +80,15 @@ export async function compileSeed(db: Db, config: CromboloConfig): Promise<SeedB
69
80
  const counts = { content: 0, library: 0, media: 0 }
70
81
  for (const item of tree.items) counts[item.kind] += 1
71
82
 
83
+ const dictionary = readSeedDictionary(config.siteDir)
84
+ for (const problem of dictionary?.problems ?? [])
85
+ findings.push({
86
+ file: DICTIONARY_FILE,
87
+ line: problem.path.length > 0 ? lineOf(dictionary?.text ?? '', problem.path) : 1,
88
+ code: 'bad-dictionary',
89
+ message: problem.message,
90
+ })
91
+
72
92
  const state = await currentSchemaState(db)
73
93
  const documentTypes = new ContentTypeRepository(db)
74
94
  const mediaTypes = new ContentTypeRepository(db, { kind: 'media' })
@@ -89,6 +109,21 @@ export async function compileSeed(db: Db, config: CromboloConfig): Promise<SeedB
89
109
  message,
90
110
  })
91
111
 
112
+ const checkLanguages = (entries: readonly DictionaryEntry[], path: readonly string[]) => {
113
+ for (const entry of entries) {
114
+ for (const { isoCode } of entry.translations)
115
+ if (!languages.has(isoCode.toLowerCase()))
116
+ findings.push({
117
+ file: DICTIONARY_FILE,
118
+ line: lineOf(dictionary?.text ?? '', [...path, entry.name, isoCode]),
119
+ code: 'unknown-language',
120
+ message: `"${entry.name}" has a translation for ${isoCode}, a language this site has not got`,
121
+ })
122
+ checkLanguages(entry.children, [...path, entry.name])
123
+ }
124
+ }
125
+ checkLanguages(dictionary?.entries ?? [], [])
126
+
92
127
  // ---------------------------------------------------------------- keys
93
128
  const keyOf = new Map<SeedItem, string>()
94
129
  const byKey = new Map<string, SeedItem>()
@@ -453,6 +488,7 @@ export async function compileSeed(db: Db, config: CromboloConfig): Promise<SeedB
453
488
  identity.update(`${item.kind}\0${item.path}\0${item.text}\0`)
454
489
  if (item.bytes) identity.update(item.bytes)
455
490
  }
491
+ if (dictionary) identity.update(`dictionary\0${dictionary.text}\0`)
456
492
  const id = uuidV5(`seed:${identity.digest('hex')}`, SEED_NAMESPACE)
457
493
  const tally: Partial<Record<BundleKind, number>> = {}
458
494
  for (const node of bundleNodes) tally[node.kind] = (tally[node.kind] ?? 0) + 1
@@ -491,7 +527,19 @@ export async function compileSeed(db: Db, config: CromboloConfig): Promise<SeedB
491
527
  },
492
528
  nodes: bundleNodes,
493
529
  }
494
- const payload = writeBundle(set, blobs)
530
+ const entries = dictionary?.entries ?? []
531
+ const payload = writeBundle(
532
+ set,
533
+ blobs,
534
+ entries.length > 0
535
+ ? [
536
+ {
537
+ path: `${BUNDLE_SECTIONS.dictionary}.udt`,
538
+ text: writeDictionaryUdt(keyedEntries(entries)),
539
+ },
540
+ ]
541
+ : [],
542
+ )
495
543
  const files = writeBundlePackage(payload, {
496
544
  name: 'crombolo-site-seed',
497
545
  version: '0.0.0',
@@ -501,5 +549,5 @@ export async function compileSeed(db: Db, config: CromboloConfig): Promise<SeedB
501
549
  private: true,
502
550
  peerRange: `>=${VERSION}`,
503
551
  })
504
- return { findings, set, blobs, files, counts }
552
+ return { findings, set, blobs, files, counts, ...(dictionary ? { dictionary: entries } : {}) }
505
553
  }
package/src/seed/read.ts CHANGED
@@ -8,6 +8,8 @@
8
8
  import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'
9
9
  import { join, relative } from 'node:path'
10
10
 
11
+ import { readDictionaryToml } from '../dictionary-toml.ts'
12
+
11
13
  export type SeedKind = 'content' | 'library' | 'media'
12
14
 
13
15
  /** The folder a site's content files are in. */
@@ -200,6 +202,17 @@ export function readSeed(siteDir: string): SeedTree {
200
202
  return { items, findings }
201
203
  }
202
204
 
205
+ /** The dictionary among a site's content files (story 168). */
206
+ export const DICTIONARY_FILE = `${CONTENT_FILES_DIR}/dictionary.toml`
207
+
208
+ /** `content/dictionary.toml`, read, when the site has one. */
209
+ export function readSeedDictionary(siteDir: string) {
210
+ const file = join(siteDir, DICTIONARY_FILE)
211
+ if (!existsSync(file)) return undefined
212
+ const text = readFileSync(file, 'utf8')
213
+ return { text, ...readDictionaryToml(text) }
214
+ }
215
+
203
216
  /** Whether a site has content files at all, where they are or where they were. */
204
217
  export const hasSeed = (siteDir: string) =>
205
218
  existsSync(join(siteDir, CONTENT_FILES_DIR)) || existsSync(join(siteDir, 'seed'))
package/src/server.ts CHANGED
@@ -228,6 +228,7 @@ import { provenanceProblem } from './provenance.ts'
228
228
  import { createRemote, type RestartOutcome } from './remote.ts'
229
229
  import { SiteAssets } from './site-assets.ts'
230
230
  import { unknownHostProvided } from './site-file.ts'
231
+ import { PublicFiles } from './site-public.ts'
231
232
  import {
232
233
  activeSpan,
233
234
  inSpan,
@@ -866,9 +867,20 @@ export async function createServer(
866
867
  { prefix: '/scripts', dir: config.scriptsDir, extension: '.js' },
867
868
  ])
868
869
  siteAssets.start()
870
+ const publicFiles = new PublicFiles(config.publicDir, config.backOfficePath)
871
+ publicFiles.start()
872
+ // A file wins at its path (story 284), so a page it hides is worth saying once.
873
+ if (config.role !== 'api' && publicFiles.paths().length > 0)
874
+ void publicFiles
875
+ .hiding((path) => cache.byRoute(path))
876
+ .then((paths) => {
877
+ for (const path of paths)
878
+ renderLog.warning('The public file {path} hides the page at that address', { path })
879
+ })
880
+ .catch(() => {})
869
881
  const missingAssets = new Set<string>()
870
882
  setAssetResolver((path) => {
871
- const found = generatedPaths.get(path) ?? siteAssets.address(path)
883
+ const found = generatedPaths.get(path) ?? siteAssets.address(path) ?? publicFiles.address(path)
872
884
  if (found) return found
873
885
  if (config.development && !missingAssets.has(path)) {
874
886
  missingAssets.add(path)
@@ -1585,7 +1597,11 @@ export async function createServer(
1585
1597
  if (pathname === BUNDLE_SCRIPT_PATH) return siteScript(BUNDLE_SCRIPT)
1586
1598
 
1587
1599
  // Not on an `api` node, which serves no public site to describe.
1588
- if ((pathname === '/sitemap.xml' || pathname === '/robots.txt') && config.role !== 'api')
1600
+ if (
1601
+ (pathname === '/sitemap.xml' || pathname === '/robots.txt') &&
1602
+ config.role !== 'api' &&
1603
+ !publicFiles.has(pathname)
1604
+ )
1589
1605
  return pathname === '/sitemap.xml' ? seo.sitemap(request, url.host) : seo.robots(request)
1590
1606
 
1591
1607
  if (pathname.startsWith('/media/')) return serveMedia(request, pathname, url.searchParams)
@@ -1692,8 +1708,13 @@ export async function createServer(
1692
1708
  async function siteFiles(request: Request, run?: ChainRun): Promise<Response> {
1693
1709
  const url = new URL(request.url)
1694
1710
  const pathname = url.pathname
1695
- // A route wins at its path (story 211); an `api` node serves no site.
1711
+ // A public file wins at its path (story 284), then a route (story 211); an
1712
+ // `api` node serves no site.
1696
1713
  if (config.role !== 'api') {
1714
+ if (request.method === 'GET' || request.method === 'HEAD') {
1715
+ const file = await publicFiles.serve(request, pathname)
1716
+ if (file) return file
1717
+ }
1697
1718
  const routed = await siteRoutes.handle(request, url)
1698
1719
  if (routed) return routed
1699
1720
  }
@@ -3838,6 +3859,7 @@ export async function createServer(
3838
3859
  watcher?.close()
3839
3860
  viewWatcher?.close()
3840
3861
  siteAssets.close()
3862
+ publicFiles.close()
3841
3863
  typeWatch?.stop()
3842
3864
  live?.close()
3843
3865
  poller.stop()
package/src/settings.ts CHANGED
@@ -300,6 +300,13 @@ const DECLARED = [
300
300
  section: 'Back office and bundles',
301
301
  description: 'The scripts the Settings section edits, served at `/scripts/`.',
302
302
  },
303
+ {
304
+ env: 'CROMBOLO_PUBLIC_DIR',
305
+ kind: 'string',
306
+ default: 'public',
307
+ section: 'Back office and bundles',
308
+ description: "The site's own files, served at the root of the site at the same paths.",
309
+ },
303
310
  {
304
311
  env: 'CROMBOLO_APPLY_BUNDLE_CONTENT',
305
312
  kind: 'boolean',
package/src/site-file.ts CHANGED
@@ -35,6 +35,7 @@ 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
37
  import { readSiteData } from './site-data.ts'
38
+ import { publicSources } from './site-public.ts'
38
39
  import { siteSections } from './site-sections.ts'
39
40
  import { TarballWriter } from './tar.ts'
40
41
 
@@ -232,6 +233,7 @@ export async function exportSite(
232
233
  requires: requiredPackages(config),
233
234
  },
234
235
  }
236
+ const publicFiles = publicSources(config.publicDir)
235
237
  const seal =
236
238
  (people || siteData || options.sealContent) && options.passphrase
237
239
  ? newSeal(options.passphrase)
@@ -240,7 +242,13 @@ export async function exportSite(
240
242
  site,
241
243
  new Map([...stored].map(([key, file]) => [key, file.size])),
242
244
  sections,
243
- { people, siteData, seal, content: options.sealContent ? 'sealed' : 'open' },
245
+ {
246
+ people,
247
+ siteData,
248
+ seal,
249
+ content: options.sealContent ? 'sealed' : 'open',
250
+ public: publicFiles,
251
+ },
244
252
  )
245
253
 
246
254
  const name = options.package?.name ?? packageNameFor(`${config.siteName}-site`)
@@ -291,11 +299,16 @@ export async function exportSite(
291
299
  }
292
300
  hasher.update('\n')
293
301
  }
302
+ // Outside the bundle's hash: `public.json`, inside it, holds each file's own.
303
+ for (const file of publicFiles)
304
+ await writer.addStream(file.path, file.size, Bun.file(file.source).stream())
294
305
  const manifest = { ...planned.manifest, integrity: `sha256-${hasher.digest('hex')}` }
295
306
  await writer.add(MANIFEST_FILE, encoder.encode(writeManifest(manifest)))
296
307
  await writer.add(
297
308
  'package.json',
298
- encoder.encode(`${JSON.stringify(bundlePackageJson(info, paths), null, 2)}\n`),
309
+ encoder.encode(
310
+ `${JSON.stringify(bundlePackageJson(info, [...paths, ...publicFiles.map((file) => file.path)]), null, 2)}\n`,
311
+ ),
299
312
  )
300
313
  await writer.close()
301
314
  await rename(partial, options.out)
@@ -312,6 +325,7 @@ export async function exportSite(
312
325
  )
313
326
  if (section) counted[section] = (counted[section] ?? 0) + 1
314
327
  }
328
+ if (publicFiles.length > 0) counted.public = publicFiles.length
315
329
  return {
316
330
  out: options.out,
317
331
  bundleId: site.manifest.id,
@@ -0,0 +1,282 @@
1
+ /**
2
+ * The site's `public/` folder (story 284): its files at the root of the site,
3
+ * at the same paths. Listed as the server starts and when the folder changes,
4
+ * so a page request asks a map and never the disk, and only a path in the map
5
+ * is ever served. docs/rendering.md, "Public files".
6
+ */
7
+ import { existsSync, type FSWatcher, readdirSync, realpathSync, statSync, watch } from 'node:fs'
8
+ import { basename, dirname, join, relative, sep } from 'node:path'
9
+ import { serveStaticFile } from '@crombolo/backoffice-host'
10
+ import { hashedAddress, splitHashedAddress } from '@crombolo/render'
11
+ import { BUNDLE_SECTIONS, hashFile, type PublicSource } from '@crombolo/transfer'
12
+ import { isSitePath } from './middleware.ts'
13
+
14
+ /** Where a CLI finds out what a server is: never a site's to answer. */
15
+ export const REMOTE_DISCOVERY_PATH = '/.well-known/crombolo-remote'
16
+
17
+ /** Above this, `bundle build` says what is making the bundle heavy. */
18
+ export const PUBLIC_WARNING_BYTES = 100 * 1024 ** 2
19
+
20
+ const IMMUTABLE = 'public, max-age=31536000, immutable'
21
+ const WELL_KNOWN = '.well-known'
22
+ /** What git needs to keep an empty folder: it travels with the folder, and is never served. */
23
+ const FOLDER_KEEPER = '.gitkeep'
24
+ const RESCAN_DELAY_MS = 25
25
+
26
+ /** Whether an address is the CMS's own, which no public file can take. */
27
+ export function isReservedPublicPath(path: string, backOfficePath: string): boolean {
28
+ const lower = path.toLowerCase()
29
+ if (lower === '/robots.txt' || lower === '/sitemap.xml') return false
30
+ return (
31
+ !isSitePath(path, backOfficePath) ||
32
+ lower === REMOTE_DISCOVERY_PATH ||
33
+ ['/css', '/scripts'].some((prefix) => lower === prefix || lower.startsWith(`${prefix}/`))
34
+ )
35
+ }
36
+
37
+ /** A dotfile, and anything in a dot folder, stays private except under `.well-known/`. Pure. */
38
+ const isServable = (relativePath: string): boolean =>
39
+ relativePath
40
+ .split('/')
41
+ .every((part, index) => !part.startsWith('.') || (index === 0 && part === WELL_KNOWN))
42
+
43
+ /** A symlink counts only when it ends inside the folder and at a file. */
44
+ function isInsideFolder(root: string, file: string): boolean {
45
+ try {
46
+ const real = realpathSync(file)
47
+ return real.startsWith(`${realpathSync(root)}${sep}`) && statSync(real).isFile()
48
+ } catch {
49
+ return false
50
+ }
51
+ }
52
+
53
+ /** Every regular file under `root`, relative and `/`-separated, dotfiles included. */
54
+ function filesIn(root: string, dir = root, out: string[] = []): string[] {
55
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
56
+ const path = join(dir, entry.name)
57
+ if (entry.isDirectory()) filesIn(root, path, out)
58
+ else if (entry.isFile() || (entry.isSymbolicLink() && isInsideFolder(root, path)))
59
+ out.push(relative(root, path).split(sep).join('/'))
60
+ }
61
+ return out
62
+ }
63
+
64
+ /** What a bundle carries from the folder: the files that are served, and what keeps it in git. */
65
+ export function publicSources(root: string): PublicSource[] {
66
+ if (!existsSync(root)) return []
67
+ return filesIn(root)
68
+ .filter((path) => isServable(path) || basename(path) === FOLDER_KEEPER)
69
+ .sort()
70
+ .map((path) => {
71
+ const source = join(root, path)
72
+ return {
73
+ path: `${BUNDLE_SECTIONS.public}/${path}`,
74
+ size: statSync(source).size,
75
+ sha256: hashFile(source),
76
+ source,
77
+ }
78
+ })
79
+ }
80
+
81
+ export interface PublicClash {
82
+ /** The file, inside the folder. */
83
+ file: string
84
+ /** `reserved`: it can never answer. `route`: it takes a route's address. `generated`: it replaces what the CMS writes there. */
85
+ kind: 'reserved' | 'route' | 'generated'
86
+ address: string
87
+ }
88
+
89
+ /** Each public file at an address something else answers, from files alone. */
90
+ export function publicClashes(options: {
91
+ publicDir: string
92
+ backOfficePath: string
93
+ routes?: readonly { path: string }[]
94
+ }): PublicClash[] {
95
+ const routes = (options.routes ?? []).map((route) => new URLPattern({ pathname: route.path }))
96
+ return filesFrom(options.publicDir).flatMap((file): PublicClash[] => {
97
+ const address = `/${file}`
98
+ if (isReservedPublicPath(address, options.backOfficePath))
99
+ return [{ file, kind: 'reserved', address }]
100
+ if (address === '/robots.txt' || address === '/sitemap.xml')
101
+ return [{ file, kind: 'generated', address }]
102
+ return routes.some((route) => route.test({ pathname: address }))
103
+ ? [{ file, kind: 'route', address }]
104
+ : []
105
+ })
106
+ }
107
+
108
+ interface PublicEntry {
109
+ file: string
110
+ /** Of the file's bytes, worked out when first asked for and kept until it changes. */
111
+ hash?: string
112
+ size: number
113
+ modified: number
114
+ }
115
+
116
+ /** The URL path of each file, decoded; a malformed escape matches nothing. */
117
+ function decoded(pathname: string): string | undefined {
118
+ try {
119
+ return decodeURIComponent(pathname)
120
+ } catch {
121
+ return undefined
122
+ }
123
+ }
124
+
125
+ export class PublicFiles {
126
+ readonly #root: string
127
+ readonly #backOfficePath: string
128
+ #index = new Map<string, PublicEntry>()
129
+ #folder: FSWatcher | undefined
130
+ #parent: FSWatcher | undefined
131
+ #rescan: ReturnType<typeof setTimeout> | undefined
132
+
133
+ constructor(root: string, backOfficePath: string) {
134
+ this.#root = root
135
+ this.#backOfficePath = backOfficePath
136
+ }
137
+
138
+ /** Lists the folder and watches it, and watches for it being made or replaced. */
139
+ start(): void {
140
+ this.#list()
141
+ this.#watchFolder()
142
+ try {
143
+ const name = basename(this.#root)
144
+ this.#parent = watch(dirname(this.#root), (_event, changed) => {
145
+ if (changed !== null && changed.toString() !== name) return
146
+ this.#watchFolder()
147
+ this.#scheduleRescan()
148
+ })
149
+ this.#parent.on('error', () => {})
150
+ } catch {
151
+ // A folder that cannot be watched keeps the files it started with.
152
+ }
153
+ }
154
+
155
+ close(): void {
156
+ clearTimeout(this.#rescan)
157
+ this.#folder?.close()
158
+ this.#parent?.close()
159
+ }
160
+
161
+ /** Whether a request path is a public file. */
162
+ has(pathname: string): boolean {
163
+ const path = decoded(pathname)
164
+ return path !== undefined && this.#index.has(path)
165
+ }
166
+
167
+ /** The URL paths of the files, sorted. */
168
+ paths(): string[] {
169
+ return [...this.#index.keys()].sort()
170
+ }
171
+
172
+ /** The files at an address that `page` says has a page. */
173
+ async hiding(page: (path: string) => Promise<unknown>): Promise<string[]> {
174
+ const found = await Promise.all(
175
+ this.paths().map(async (path) => ((await page(path)) ? [path] : [])),
176
+ )
177
+ return found.flat()
178
+ }
179
+
180
+ /** The hashed address of a file the site has, or undefined. */
181
+ address(path: string): string | undefined {
182
+ const entry = this.#index.get(path)
183
+ if (!entry) return undefined
184
+ try {
185
+ entry.hash ??= addressHash(entry.file)
186
+ return hashedAddress(path, entry.hash)
187
+ } catch {
188
+ return undefined
189
+ }
190
+ }
191
+
192
+ /**
193
+ * A public file's answer, or undefined when the path is not one. The hashed
194
+ * address answers only while the hash is the file's, and nothing when not.
195
+ */
196
+ async serve(request: Request, pathname: string): Promise<Response | undefined> {
197
+ const path = decoded(pathname)
198
+ if (path === undefined) return undefined
199
+ const own = this.#index.get(path)
200
+ if (own) return this.#send(own, 'no-cache', request)
201
+ const hashed = splitHashedAddress(path)
202
+ const entry = hashed && this.#index.get(hashed.path)
203
+ if (!hashed || !entry) return undefined
204
+ if (this.#hashNow(entry) !== hashed.hash)
205
+ return new Response('Not Found', { status: 404, headers: { 'cache-control': 'no-store' } })
206
+ return this.#send(entry, IMMUTABLE, request)
207
+ }
208
+
209
+ async #send(entry: PublicEntry, cacheControl: string, request: Request) {
210
+ const response = await serveStaticFile({ file: entry.file, cacheControl }, request)
211
+ response?.headers.set('x-content-type-options', 'nosniff')
212
+ return response
213
+ }
214
+
215
+ /** The hash of the bytes as they are now, so a change the watcher missed is never kept. */
216
+ #hashNow(entry: PublicEntry): string | undefined {
217
+ try {
218
+ const stat = statSync(entry.file)
219
+ if (stat.size !== entry.size || stat.mtimeMs !== entry.modified) entry.hash = undefined
220
+ entry.size = stat.size
221
+ entry.modified = stat.mtimeMs
222
+ entry.hash ??= addressHash(entry.file)
223
+ return entry.hash
224
+ } catch {
225
+ return undefined
226
+ }
227
+ }
228
+
229
+ #list(): void {
230
+ const next = new Map<string, PublicEntry>()
231
+ for (const path of filesFrom(this.#root)) {
232
+ const key = `/${path}`
233
+ if (isReservedPublicPath(key, this.#backOfficePath)) continue
234
+ const file = join(this.#root, path)
235
+ try {
236
+ const stat = statSync(file)
237
+ const known = this.#index.get(key)
238
+ const same = known?.size === stat.size && known.modified === stat.mtimeMs
239
+ next.set(key, {
240
+ file,
241
+ size: stat.size,
242
+ modified: stat.mtimeMs,
243
+ ...(same && known.hash ? { hash: known.hash } : {}),
244
+ })
245
+ } catch {
246
+ // Gone between the listing and the look: it is not there.
247
+ }
248
+ }
249
+ this.#index = next
250
+ }
251
+
252
+ #watchFolder(): void {
253
+ this.#folder?.close()
254
+ this.#folder = undefined
255
+ if (!existsSync(this.#root)) return
256
+ try {
257
+ this.#folder = watch(this.#root, { recursive: true }, () => this.#scheduleRescan())
258
+ this.#folder.on('error', () => {})
259
+ } catch {
260
+ // As in `start`.
261
+ }
262
+ }
263
+
264
+ /** Listed again as a whole: a folder moved in reports only its own name. */
265
+ #scheduleRescan(): void {
266
+ clearTimeout(this.#rescan)
267
+ this.#rescan = setTimeout(() => this.#list(), RESCAN_DELAY_MS)
268
+ this.#rescan.unref?.()
269
+ }
270
+ }
271
+
272
+ /** The servable files of a folder, which may not exist. */
273
+ function filesFrom(root: string): string[] {
274
+ try {
275
+ return existsSync(root) ? filesIn(root).filter(isServable) : []
276
+ } catch {
277
+ return []
278
+ }
279
+ }
280
+
281
+ /** `contentHash` of the file's bytes, without holding them in memory. */
282
+ const addressHash = (file: string): string => hashFile(file).slice(0, 8)
@@ -170,7 +170,7 @@ export async function replaceSummary(
170
170
  const filesRemoved: string[] = []
171
171
  for (const { section, dir } of folders) {
172
172
  if (!existsSync(dir)) continue
173
- for (const path of new Bun.Glob('**/*').scanSync({ cwd: dir, onlyFiles: true })) {
173
+ for (const path of new Bun.Glob('**/*').scanSync({ cwd: dir, onlyFiles: true, dot: true })) {
174
174
  const bundlePath = `${section}/${path.split(sep).join('/')}`
175
175
  if (!carriedPaths.has(bundlePath)) filesRemoved.push(join(dir, path))
176
176
  }