@crombolo/server 0.50.0 → 0.51.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@crombolo/server",
3
- "version": "0.50.0",
3
+ "version": "0.51.1",
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.1",
35
+ "@crombolo/api-management": "0.51.1",
36
+ "@crombolo/auth": "0.51.1",
37
+ "@crombolo/backoffice-host": "0.51.1",
38
+ "@crombolo/common": "0.51.1",
39
+ "@crombolo/content": "0.51.1",
40
+ "@crombolo/contracts": "0.51.1",
41
+ "@crombolo/core": "0.51.1",
42
+ "@crombolo/data": "0.51.1",
43
+ "@crombolo/render": "0.51.1",
44
+ "@crombolo/schema": "0.51.1",
45
+ "@crombolo/transfer": "0.51.1",
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
  }
@@ -66,9 +66,11 @@ import {
66
66
  revertCode,
67
67
  } from './bundle-code-install.ts'
68
68
  import {
69
+ announceFiles,
69
70
  type CarriedSections,
70
71
  carriedSections,
71
72
  carriesSections,
73
+ changedFileSections,
72
74
  keepDictionary,
73
75
  keptDictionary,
74
76
  planSections,
@@ -76,6 +78,7 @@ import {
76
78
  type RestoredFiles,
77
79
  replacementsNeedingPermission,
78
80
  restoreSectionFiles,
81
+ runFileSections,
79
82
  type SectionFile,
80
83
  type SectionOptions,
81
84
  type SectionPlan,
@@ -673,6 +676,11 @@ export async function installBundleContent(
673
676
  backup,
674
677
  )
675
678
 
679
+ const changedFiles = changedFileSections(config, carried, plan, {
680
+ ...effective,
681
+ replace: Boolean(replace),
682
+ })
683
+
676
684
  // ---- 1. Stage
677
685
  const runDir = stageBackups(config)
678
686
  const staged =
@@ -762,6 +770,7 @@ export async function installBundleContent(
762
770
  swapSections(config, staged)
763
771
  if (staged.next.schema && config.schemaStore)
764
772
  await publishSchema(config.schemaStore, config.schemaDir)
773
+ await announceFiles(db, config, changedFiles)
765
774
  }
766
775
  const kept = promoteStaged(config, runDir, runId)
767
776
  const codeInstalled =
@@ -836,7 +845,9 @@ export async function revertSections(
836
845
  runId: string,
837
846
  ): Promise<RevertedSections> {
838
847
  const swapped = swappedSections(config, runId)
848
+ const touched = runFileSections(config, runId)
839
849
  const files = restoreSectionFiles(config, runId)
850
+ await announceFiles(db, config, touched)
840
851
  let schema: string | undefined
841
852
  if (swapped.includes('schema')) {
842
853
  // A type the install brought has content only in the bin by now, which is
@@ -24,15 +24,17 @@ 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'
30
- import { dirname, join } from 'node:path'
31
- import type { Db } from '@crombolo/data'
31
+ import { dirname, join, sep } from 'node:path'
32
+ import { appendCacheInstruction, type Db } from '@crombolo/data'
32
33
  import type { BundleSection, LoadedBundle } from '@crombolo/transfer'
33
34
  import { BUNDLE_SECTIONS } from '@crombolo/transfer'
34
35
  import type { CromboloConfig } from './config.ts'
35
36
  import { importDictionaryUdt } from './dictionary-transfer.ts'
37
+ import { logger } from './logging.ts'
36
38
  import { checkSchemaDirectory, syncSchemaDirectory } from './schema.ts'
37
39
  import { publishSchema } from './schema-store.ts'
38
40
 
@@ -105,21 +107,25 @@ function destinationOf(config: CromboloConfig, section: BundleSection): string |
105
107
  return config.stylesheetsDir
106
108
  case 'scripts':
107
109
  return config.scriptsDir
110
+ case 'public':
111
+ return config.publicDir
108
112
  case 'dictionary':
109
113
  return undefined
110
114
  }
111
115
  }
112
116
 
113
- const FILE_SECTIONS: readonly BundleSection[] = ['components', 'styles', 'scripts']
117
+ const FILE_SECTIONS: readonly BundleSection[] = ['components', 'styles', 'scripts', 'public']
114
118
 
115
119
  /** The path inside a section, with the section's own directory stripped. */
116
120
  const withinSection = (path: string, section: BundleSection): string =>
117
121
  path.slice(`${BUNDLE_SECTIONS[section]}/`.length)
118
122
 
119
- function actionFor(target: string, content: string): FileAction {
123
+ /** Compared as bytes: a public file is an image as often as it is text. */
124
+ function actionFor(target: string, source: string): FileAction {
120
125
  if (!existsSync(target)) return 'create'
121
126
  try {
122
- return readFileSync(target, 'utf8') === content ? 'unchanged' : 'overwrite'
127
+ if (statSync(target).size !== statSync(source).size) return 'overwrite'
128
+ return readFileSync(target).equals(readFileSync(source)) ? 'unchanged' : 'overwrite'
123
129
  } catch {
124
130
  return 'overwrite'
125
131
  }
@@ -137,12 +143,16 @@ export function carriedSections(loaded: LoadedBundle): CarriedSections {
137
143
  return { carries: loaded.set?.manifest.carries ?? {}, files: loaded.files }
138
144
  }
139
145
 
140
- const read = (carried: CarriedSections, path: string): string => {
146
+ /** The file on disk holding a carried path. */
147
+ const sourceOf = (carried: CarriedSections, path: string): string => {
141
148
  const file = carried.files.get(path)
142
149
  if (!file) throw new Error(`${path} is declared but was not read`)
143
- return readFileSync(file, 'utf8')
150
+ return file
144
151
  }
145
152
 
153
+ const read = (carried: CarriedSections, path: string): string =>
154
+ readFileSync(sourceOf(carried, path), 'utf8')
155
+
146
156
  /** Read-only: what applying the carried sections here would do. */
147
157
  export async function planSections(
148
158
  db: Db,
@@ -159,7 +169,7 @@ export async function planSections(
159
169
  if (!destination) continue
160
170
  for (const path of carried.carries[section] ?? []) {
161
171
  const target = join(destination, withinSection(path, section))
162
- files.push({ path, target, action: actionFor(target, read(carried, path)) })
172
+ files.push({ path, target, action: actionFor(target, sourceOf(carried, path)) })
163
173
  }
164
174
  }
165
175
  }
@@ -168,7 +178,7 @@ export async function planSections(
168
178
  if (!options.withoutSchema) {
169
179
  for (const path of schemaPaths) {
170
180
  const target = join(config.schemaDir, withinSection(path, 'schema'))
171
- files.push({ path, target, action: actionFor(target, read(carried, path)) })
181
+ files.push({ path, target, action: actionFor(target, sourceOf(carried, path)) })
172
182
  }
173
183
  }
174
184
 
@@ -254,8 +264,8 @@ export async function applySections(
254
264
  * site, so a revert re-derives the destination through the same mapping — and
255
265
  * restores to where the file would go now, not where it went then.
256
266
  */
257
- const put = (target: string, content: string, bundlePath: string) => {
258
- const action = actionFor(target, content)
267
+ const put = (target: string, source: string, bundlePath: string) => {
268
+ const action = actionFor(target, source)
259
269
  if (action === 'overwrite' && options.backupDir) {
260
270
  const keep = join(options.backupDir, REPLACED_DIR, bundlePath)
261
271
  mkdirSync(dirname(keep), { recursive: true })
@@ -264,13 +274,13 @@ export async function applySections(
264
274
  }
265
275
  records.push({ path: bundlePath, action })
266
276
  mkdirSync(dirname(target), { recursive: true })
267
- writeFileSync(target, content)
277
+ copyFileSync(source, target)
268
278
  written.push(target)
269
279
  }
270
280
 
271
281
  const schemaPaths = options.withoutSchema ? [] : (carried.carries.schema ?? [])
272
282
  for (const path of schemaPaths)
273
- put(join(config.schemaDir, withinSection(path, 'schema')), read(carried, path), path)
283
+ put(join(config.schemaDir, withinSection(path, 'schema')), sourceOf(carried, path), path)
274
284
 
275
285
  let schema: { action: string } | undefined
276
286
  if (schemaPaths.length > 0) {
@@ -290,7 +300,7 @@ export async function applySections(
290
300
  const destination = destinationOf(config, section)
291
301
  if (!destination) continue
292
302
  for (const path of carried.carries[section] ?? [])
293
- put(join(destination, withinSection(path, section)), read(carried, path), path)
303
+ put(join(destination, withinSection(path, section)), sourceOf(carried, path), path)
294
304
  }
295
305
  }
296
306
 
@@ -437,6 +447,80 @@ export function restoreSectionFiles(config: CromboloConfig, runId: string): Rest
437
447
  return { restored, removed }
438
448
  }
439
449
 
450
+ /**
451
+ * The file sections an install will change here, asked before it moves anything.
452
+ * The plan names what lands; a replace also takes out what the file lacks.
453
+ */
454
+ export function changedFileSections(
455
+ config: CromboloConfig,
456
+ carried: CarriedSections,
457
+ plan: SectionPlan | undefined,
458
+ options: SectionOptions & { replace?: boolean },
459
+ ): BundleSection[] {
460
+ if (options.withoutFiles) return []
461
+ const changed = new Set<BundleSection>()
462
+ for (const file of plan?.files ?? []) {
463
+ const section = sectionFor(file.path)
464
+ if (section && FILE_SECTIONS.includes(section) && file.action !== 'unchanged')
465
+ changed.add(section)
466
+ }
467
+ if (options.replace)
468
+ for (const section of FILE_SECTIONS) {
469
+ const dir = destinationOf(config, section) as string
470
+ if (!existsSync(dir)) continue
471
+ const kept = new Set(carried.carries[section] ?? [])
472
+ for (const path of new Bun.Glob('**/*').scanSync({ cwd: dir, onlyFiles: true, dot: true }))
473
+ if (!kept.has(`${BUNDLE_SECTIONS[section]}/${path.split(sep).join('/')}`)) {
474
+ changed.add(section)
475
+ break
476
+ }
477
+ }
478
+ return [...changed]
479
+ }
480
+
481
+ /** The file sections a run touched, for its revert to announce. */
482
+ export function runFileSections(config: CromboloConfig, runId: string): BundleSection[] {
483
+ const swapped = swappedSections(config, runId)
484
+ const record = join(config.siteDir, RUN_BACKUP_DIR, runId, RECORD_FILE)
485
+ const paths =
486
+ swapped.length === 0 && existsSync(record)
487
+ ? (JSON.parse(readFileSync(record, 'utf8')) as FileRecord[]).map((entry) => entry.path)
488
+ : []
489
+ const sections = [
490
+ ...swapped,
491
+ ...paths.flatMap((path) => {
492
+ const section = sectionFor(path)
493
+ return section ? [section] : []
494
+ }),
495
+ ]
496
+ return [...new Set(sections)].filter((section) => FILE_SECTIONS.includes(section))
497
+ }
498
+
499
+ /**
500
+ * Tells every node the site's files changed (story 285): the only way a view,
501
+ * a stylesheet or a public file reaches a node when the writer is another
502
+ * process, on a folder no watcher sees. Signed so that the node that ran it, if
503
+ * a node did, follows too. The files are in place by now, so a failure is said
504
+ * rather than thrown.
505
+ */
506
+ export async function announceFiles(
507
+ db: Db,
508
+ config: CromboloConfig,
509
+ sections: readonly BundleSection[],
510
+ ): Promise<void> {
511
+ const by = `import:${config.nodeId}`
512
+ try {
513
+ if (sections.some((section) => section !== 'public'))
514
+ await appendCacheInstruction(db, { kind: 'components', by })
515
+ if (sections.includes('public')) await appendCacheInstruction(db, { kind: 'public-files', by })
516
+ } catch (error) {
517
+ logger('transfer').warning(
518
+ 'The files are in place, but the running nodes could not be told; restart them, or import again: {error}',
519
+ { error: error instanceof Error ? error.message : String(error) },
520
+ )
521
+ }
522
+ }
523
+
440
524
  /** The section a bundle path belongs to, by its leading directory. */
441
525
  function sectionFor(path: string): BundleSection | undefined {
442
526
  if (path === `${BUNDLE_SECTIONS.dictionary}.udt`) return 'dictionary'
@@ -515,7 +599,7 @@ export function stageSections(
515
599
  const inside = withinSection(path, section)
516
600
  const target = join(next, inside)
517
601
  mkdirSync(dirname(target), { recursive: true })
518
- writeFileSync(target, read(carried, path))
602
+ copyFileSync(sourceOf(carried, path), target)
519
603
  staged.written.push(join(destination, inside))
520
604
  }
521
605
  staged.next[section] = next
@@ -531,6 +615,7 @@ export function stagedConfig(config: CromboloConfig, staged: StagedSections): Cr
531
615
  componentsDir: staged.next.components ?? config.componentsDir,
532
616
  stylesheetsDir: staged.next.styles ?? config.stylesheetsDir,
533
617
  scriptsDir: staged.next.scripts ?? config.scriptsDir,
618
+ publicDir: staged.next.public ?? config.publicDir,
534
619
  }
535
620
  }
536
621
 
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.1'
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. */
package/src/core.ts CHANGED
@@ -88,6 +88,8 @@ import { createWorkerWatch } from './worker-watch.ts'
88
88
 
89
89
  /** What only the serving half of a node supplies; a worker leaves each out. */
90
90
  export interface CoreHooks {
91
+ /** A site's stylesheets and scripts, or its `public/` folder, changed elsewhere (story 285). */
92
+ onSiteFiles?: (change: 'assets' | 'public') => void
91
93
  /** The published cache was dropped: a server drops its drafts and reloads open pages. */
92
94
  onCacheInvalidate?: () => void
93
95
  /** A newer views generation replaced the one in use. */
@@ -509,10 +511,17 @@ export async function createCore(config: CromboloConfig, hooks: CoreHooks) {
509
511
  // definitions. `views` changes the code that renders it, which is a new
510
512
  // snapshot rather than anything in the published cache.
511
513
  onInstruction: (kind, payload) => {
514
+ if (kind === 'public-files') return hooks.onSiteFiles?.('public')
512
515
  if (kind !== 'components') return cache.invalidate()
513
516
  // The hash only says when to stop looking eagerly; the snapshot is always
514
517
  // of the bytes this node reads, so a superseded one is harmless.
515
518
  snapshots.announce(typeof payload.hash === 'string' ? payload.hash : undefined)
519
+ hooks.onSiteFiles?.('assets')
520
+ },
521
+ onMissed: () => {
522
+ snapshots.announce()
523
+ hooks.onSiteFiles?.('assets')
524
+ hooks.onSiteFiles?.('public')
516
525
  },
517
526
  // Behind the latest committed checkpoint: rebuilt now rather than on the next
518
527
  // read, so an idle node catches up and says so (story 174). A worker builds
@@ -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
+ }