@crombolo/server 0.51.0 → 0.52.2

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.51.0",
3
+ "version": "0.52.2",
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.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",
34
+ "@crombolo/api-delivery": "0.52.2",
35
+ "@crombolo/api-management": "0.52.2",
36
+ "@crombolo/auth": "0.52.2",
37
+ "@crombolo/backoffice-host": "0.52.2",
38
+ "@crombolo/common": "0.52.2",
39
+ "@crombolo/content": "0.52.2",
40
+ "@crombolo/contracts": "0.52.2",
41
+ "@crombolo/core": "0.52.2",
42
+ "@crombolo/data": "0.52.2",
43
+ "@crombolo/render": "0.52.2",
44
+ "@crombolo/schema": "0.52.2",
45
+ "@crombolo/transfer": "0.52.2",
46
46
  "@logtape/logtape": "^2.3.8",
47
47
  "@opentelemetry/api": "1.10.0",
48
48
  "@opentelemetry/context-async-hooks": "3.0.0",
@@ -619,6 +619,8 @@ export function createPublishedContentSource(
619
619
  contentTypeKey: keyOfType.get(row.contentTypeAlias) as string,
620
620
  contentTypeAlias: row.contentTypeAlias,
621
621
  cultures: row.cultures,
622
+ name: row.name,
623
+ names: row.names,
622
624
  properties: row.values.map((value) => ({
623
625
  alias: value.alias,
624
626
  editorAlias: value.editorAlias ?? '',
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * A file-system area on disk — components, stylesheets or scripts — as the
3
3
  * Management API sees it: paths relative to the area's root, which never
4
- * escape it, and only files of the area's extension.
4
+ * escape it, and only files of the area's extensions.
5
5
  */
6
6
  import { existsSync } from 'node:fs'
7
7
  import { mkdir, readdir, readFile, rename, rm, rmdir, stat, writeFile } from 'node:fs/promises'
@@ -13,6 +13,8 @@ export interface FileAreaOptions {
13
13
  extension: string
14
14
  /** Extensions a name may arrive with that are stored as `extension` instead. */
15
15
  rewrites?: readonly string[]
16
+ /** Other extensions a file here may have, kept as they are. */
17
+ also?: readonly string[]
16
18
  }
17
19
 
18
20
  const INVALID_CHARACTERS = /[<>:"|?*\\/]/
@@ -35,7 +37,7 @@ function segmentsOf(path: string | null): string[] | undefined {
35
37
  const toPath = (segments: readonly string[]) => `/${segments.join('/')}`
36
38
 
37
39
  export function createFileSystemPort(root: string, options: FileAreaOptions): FileSystemPort {
38
- const extension = options.extension.toLowerCase()
40
+ const accepted = [options.extension, ...(options.also ?? [])].map((e) => e.toLowerCase())
39
41
  const locate = (path: string | null) => {
40
42
  const segments = segmentsOf(path)
41
43
  return segments ? { segments, file: join(root, ...segments) } : undefined
@@ -49,14 +51,14 @@ export function createFileSystemPort(root: string, options: FileAreaOptions): Fi
49
51
  }
50
52
  }
51
53
  const visible = (name: string, isFolder: boolean) =>
52
- !name.startsWith('.') && (isFolder || name.toLowerCase().endsWith(extension))
54
+ !name.startsWith('.') && (isFolder || accepted.some((e) => name.toLowerCase().endsWith(e)))
53
55
 
54
56
  /** The name as stored: with the area's extension, whichever accepted one it came with. */
55
57
  const fileName = (name: string): string | 'InvalidName' | 'InvalidFileExtension' => {
56
58
  const trimmed = name.trim()
57
59
  if (!trimmed || trimmed.startsWith('.') || invalidName(trimmed)) return 'InvalidName'
58
60
  const lower = trimmed.toLowerCase()
59
- if (lower.endsWith(extension)) return trimmed
61
+ if (accepted.some((e) => lower.endsWith(e))) return trimmed
60
62
  const rewrite = options.rewrites?.find((r) => lower.endsWith(r.toLowerCase()))
61
63
  if (rewrite) return `${trimmed.slice(0, -rewrite.length)}${options.extension}`
62
64
  return 'InvalidFileExtension'
@@ -193,3 +195,7 @@ export function createFileSystemPort(root: string, options: FileAreaOptions): Fi
193
195
  },
194
196
  }
195
197
  }
198
+
199
+ /** The components tree: its views, and the plain modules they import. */
200
+ export const createComponentsPort = (root: string): FileSystemPort =>
201
+ createFileSystemPort(root, { extension: '.tsx', also: ['.ts'], rewrites: ['.cshtml'] })
@@ -103,7 +103,7 @@ export function createSchemaFileWriter(
103
103
  return {
104
104
  ok: false,
105
105
  status: 409,
106
- reason: `${plural} are defined in schema/ and this environment is read-only; change ${shown} in source control.`,
106
+ reason: `${plural} are kept with this site's files, so they can't be changed here. To change this one, edit ${shown} in the site's code and deploy it.`,
107
107
  }
108
108
  },
109
109
 
@@ -8,7 +8,7 @@
8
8
  * the truth, as for forms, and a read-only schema directory refuses the save.
9
9
  */
10
10
  import { existsSync, mkdirSync, rmSync, writeFileSync } from 'node:fs'
11
- import { join } from 'node:path'
11
+ import { dirname, join } from 'node:path'
12
12
  import type { Principal } from '@crombolo/api-management/domain'
13
13
  import type { SchemaWorkflow } from '@crombolo/core'
14
14
  import {
@@ -27,6 +27,7 @@ import {
27
27
  writeWorkflow,
28
28
  } from '@crombolo/schema'
29
29
  import { ApprovalRefused, type Approvals } from './approvals.ts'
30
+ import { folderAction, folderOf, folderPath, foldersIn } from './definition-folders.ts'
30
31
 
31
32
  export interface ApprovalsApiContext {
32
33
  db: Db
@@ -147,10 +148,30 @@ export async function handleApprovalsApi(
147
148
  return json({ active })
148
149
  }
149
150
 
151
+ const folderIn = (file: string | undefined) =>
152
+ file ? folderOf(ctx.schemaDir, 'workflows', file) : ''
153
+ const folders = /^workflows\/(tree-folders|tree-move)$/.exec(path)
154
+ if (folders) {
155
+ if (!principal.isAdmin)
156
+ return json({ ok: false, message: 'Only administrators change workflows.' }, 403)
157
+ const response = await folderAction('workflows', folders[1] as string, request, {
158
+ schemaDir: ctx.schemaDir,
159
+ writable: ctx.writable,
160
+ onChanged: ctx.onChanged,
161
+ file: (alias) => loadSchemaDirectory(ctx.schemaDir).files.get(`workflow:${alias}`),
162
+ })
163
+ if (response) return response
164
+ }
165
+
150
166
  if (path === 'workflows' && request.method === 'GET') {
151
167
  const loaded = loadSchemaDirectory(ctx.schemaDir)
152
168
  return json({
153
- items: (await readWorkflows(ctx.db)).map((s) => s.workflow),
169
+ items: (await readWorkflows(ctx.db)).map((s) => ({
170
+ ...s.workflow,
171
+ folder: folderIn(loaded.files.get(`workflow:${s.workflow.alias}`)),
172
+ })),
173
+ folders: foldersIn(ctx.schemaDir, 'workflows'),
174
+ readOnlyBecause: ctx.writable ? (principal.isAdmin ? null : 'permission') : 'site',
154
175
  editable: ctx.writable && principal.isAdmin,
155
176
  groups: (await new UserGroupRepository(ctx.db).all()).map((g) => ({
156
177
  alias: g.alias,
@@ -165,7 +186,8 @@ export async function handleApprovalsApi(
165
186
  if (!principal.isAdmin)
166
187
  return json({ ok: false, message: 'Only administrators change workflows.' }, 403)
167
188
  const alias = decodeURIComponent(match[1] as string)
168
- const file = join(ctx.schemaDir, 'workflows', fileNameFor(alias))
189
+ const here = loadSchemaDirectory(ctx.schemaDir).files.get(`workflow:${alias}`)
190
+ const file = here ?? join(ctx.schemaDir, 'workflows', fileNameFor(alias))
169
191
  if (request.method === 'DELETE') {
170
192
  if (match[2])
171
193
  return json({ ok: true, affected: await removalPreview(approvals, principal, alias) })
@@ -205,10 +227,14 @@ export async function handleApprovalsApi(
205
227
  const affected = await changePreview(approvals, principal, workflow)
206
228
  if (match[2]) return json({ ok: true, affected })
207
229
  if (!ctx.writable) return readOnly()
208
- mkdirSync(join(ctx.schemaDir, 'workflows'), { recursive: true })
230
+ // It stays in its folder (story 289); a new one goes in the folder it was made in.
231
+ const dir = here
232
+ ? dirname(here)
233
+ : join(ctx.schemaDir, 'workflows', folderPath(b.folder) ?? '')
234
+ mkdirSync(dir, { recursive: true })
209
235
  // A renamed workflow leaves its old file behind otherwise.
210
236
  if (alias !== workflow.alias && existsSync(file)) rmSync(file)
211
- writeFileSync(join(ctx.schemaDir, 'workflows', fileNameFor(workflow.alias)), source, 'utf8')
237
+ writeFileSync(join(dir, fileNameFor(workflow.alias)), source, 'utf8')
212
238
  await ctx.onChanged?.()
213
239
  return json({ ok: true, affected, report: await syncWorkflowFiles(ctx.db, ctx.schemaDir) })
214
240
  }
@@ -18,7 +18,7 @@ import {
18
18
  writeBundle,
19
19
  writeBundlePackage,
20
20
  } from '@crombolo/transfer'
21
- import { createFileSystemPort } from './adapters/file-system.ts'
21
+ import { createComponentsPort, createFileSystemPort } from './adapters/file-system.ts'
22
22
  import { createTemplateFileStore } from './adapters/template-files.ts'
23
23
  import { loadConfig, VERSION } from './config.ts'
24
24
  import { bootstrapDatabase } from './database.ts'
@@ -138,10 +138,7 @@ export async function buildBundleFromDirectory(
138
138
  {
139
139
  db,
140
140
  componentFiles: createTemplateFileStore(config.componentsDir),
141
- components: createFileSystemPort(config.componentsDir, {
142
- extension: '.tsx',
143
- rewrites: ['.cshtml'],
144
- }),
141
+ components: createComponentsPort(config.componentsDir),
145
142
  stylesheets: createFileSystemPort(config.stylesheetsDir, { extension: '.css' }),
146
143
  scripts: createFileSystemPort(config.scriptsDir, { extension: '.js' }),
147
144
  schemaDir: config.schemaDir,
@@ -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
@@ -28,12 +28,13 @@ import {
28
28
  writeFileSync,
29
29
  } from 'node:fs'
30
30
  import { tmpdir } from 'node:os'
31
- import { dirname, join } from 'node:path'
32
- import type { Db } from '@crombolo/data'
31
+ import { dirname, join, sep } from 'node:path'
32
+ import { appendCacheInstruction, type Db } from '@crombolo/data'
33
33
  import type { BundleSection, LoadedBundle } from '@crombolo/transfer'
34
34
  import { BUNDLE_SECTIONS } from '@crombolo/transfer'
35
35
  import type { CromboloConfig } from './config.ts'
36
36
  import { importDictionaryUdt } from './dictionary-transfer.ts'
37
+ import { logger } from './logging.ts'
37
38
  import { checkSchemaDirectory, syncSchemaDirectory } from './schema.ts'
38
39
  import { publishSchema } from './schema-store.ts'
39
40
 
@@ -446,6 +447,80 @@ export function restoreSectionFiles(config: CromboloConfig, runId: string): Rest
446
447
  return { restored, removed }
447
448
  }
448
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
+
449
524
  /** The section a bundle path belongs to, by its leading directory. */
450
525
  function sectionFor(path: string): BundleSection | undefined {
451
526
  if (path === `${BUNDLE_SECTIONS.dictionary}.udt`) return 'dictionary'
package/src/config.ts CHANGED
@@ -1091,7 +1091,7 @@ export function describeDatabase(
1091
1091
  }
1092
1092
  }
1093
1093
 
1094
- export const VERSION = '0.51.0'
1094
+ export const VERSION = '0.52.2'
1095
1095
 
1096
1096
  /** A whole number of seconds from the environment; undefined when unset or not one. */
1097
1097
  /** A positive number from a setting, else the default. */
package/src/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
@@ -610,6 +619,7 @@ export async function createCore(config: CromboloConfig, hooks: CoreHooks) {
610
619
  nodeState: schema.nodeState,
611
620
  nodeId: schema.nodeId,
612
621
  onContentChanged: () => cache.invalidate(),
622
+ resolveForm: (form) => cache.resolveForm(form),
613
623
  operations: operations.documents,
614
624
  bundleWorkflows: formTypes.workflows,
615
625
  renderEmail: (alias, props) => renderer.renderEmail(alias, props),
@@ -0,0 +1,183 @@
1
+ /**
2
+ * Folders for forms and workflows (story 289): real subfolders of `schema/forms/`
3
+ * and `schema/workflows/`, so a folder travels with the code and shows in a diff.
4
+ * Nothing finds a definition by its path, so moving one changes only where its
5
+ * file sits. `docs/forms.md`, "Folders".
6
+ */
7
+ import { existsSync, mkdirSync, readdirSync, renameSync, rmdirSync } from 'node:fs'
8
+ import { dirname, join, relative, sep } from 'node:path'
9
+
10
+ export type DefinitionKind = 'forms' | 'workflows'
11
+
12
+ export interface FolderOptions {
13
+ schemaDir: string
14
+ writable: boolean
15
+ /** Publishes the directory to a shared store, when there is one. */
16
+ onChanged?: () => Promise<void>
17
+ }
18
+
19
+ export type FolderResult =
20
+ | { ok: true; path?: string }
21
+ | { ok: false; status: 'readOnly' | 'invalid' | 'notFound' | 'conflict'; message: string }
22
+
23
+ const READ_ONLY: FolderResult = {
24
+ ok: false,
25
+ status: 'readOnly',
26
+ message: 'Folders cannot be changed on this site.',
27
+ }
28
+
29
+ /** A folder as `a/b`, or undefined when it is no safe path. `''` is the top. Pure. */
30
+ export function folderPath(raw: unknown): string | undefined {
31
+ if (typeof raw !== 'string') return undefined
32
+ const parts = raw.split('/').map((part) => part.trim())
33
+ if (raw.trim() === '') return ''
34
+ const safe = parts.every((part) => /^[\p{L}\p{N}][\p{L}\p{N} _-]*$/u.test(part))
35
+ return safe ? parts.join('/') : undefined
36
+ }
37
+
38
+ const rootOf = (schemaDir: string, kind: DefinitionKind) => join(schemaDir, kind)
39
+
40
+ /** Every folder under the kind's directory, parents first, empty ones included. */
41
+ export function foldersIn(schemaDir: string, kind: DefinitionKind): string[] {
42
+ const root = rootOf(schemaDir, kind)
43
+ if (!existsSync(root)) return []
44
+ const out: string[] = []
45
+ const walk = (dir: string) => {
46
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
47
+ if (!entry.isDirectory() || entry.name.startsWith('.')) continue
48
+ const path = join(dir, entry.name)
49
+ out.push(relative(root, path).split(sep).join('/'))
50
+ walk(path)
51
+ }
52
+ }
53
+ walk(root)
54
+ return out.sort((a, b) => a.localeCompare(b))
55
+ }
56
+
57
+ /** The folder a definition's file sits in, `''` at the top. */
58
+ export const folderOf = (schemaDir: string, kind: DefinitionKind, file: string): string => {
59
+ const folder = relative(rootOf(schemaDir, kind), dirname(file))
60
+ return folder === '' ? '' : folder.split(sep).join('/')
61
+ }
62
+
63
+ async function changed(options: FolderOptions, path?: string): Promise<FolderResult> {
64
+ await options.onChanged?.()
65
+ return path === undefined ? { ok: true } : { ok: true, path }
66
+ }
67
+
68
+ export async function createFolder(
69
+ kind: DefinitionKind,
70
+ raw: unknown,
71
+ options: FolderOptions,
72
+ ): Promise<FolderResult> {
73
+ if (!options.writable) return READ_ONLY
74
+ const path = folderPath(raw)
75
+ if (!path) return { ok: false, status: 'invalid', message: 'That is not a name for a folder.' }
76
+ const target = join(rootOf(options.schemaDir, kind), path)
77
+ if (existsSync(target))
78
+ return { ok: false, status: 'conflict', message: `There is already a folder ${path}.` }
79
+ mkdirSync(target, { recursive: true })
80
+ return changed(options, path)
81
+ }
82
+
83
+ export async function renameFolder(
84
+ kind: DefinitionKind,
85
+ rawFrom: unknown,
86
+ rawTo: unknown,
87
+ options: FolderOptions,
88
+ ): Promise<FolderResult> {
89
+ if (!options.writable) return READ_ONLY
90
+ const from = folderPath(rawFrom)
91
+ const to = folderPath(rawTo)
92
+ if (!from || !to)
93
+ return { ok: false, status: 'invalid', message: 'That is not a name for a folder.' }
94
+ const root = rootOf(options.schemaDir, kind)
95
+ if (!existsSync(join(root, from)))
96
+ return { ok: false, status: 'notFound', message: `There is no folder ${from}.` }
97
+ if (to === from || to.startsWith(`${from}/`))
98
+ return { ok: false, status: 'invalid', message: 'A folder cannot go inside itself.' }
99
+ if (existsSync(join(root, to)))
100
+ return { ok: false, status: 'conflict', message: `There is already a folder ${to}.` }
101
+ mkdirSync(dirname(join(root, to)), { recursive: true })
102
+ renameSync(join(root, from), join(root, to))
103
+ return changed(options, to)
104
+ }
105
+
106
+ /** Only an empty folder goes: what is in one is someone's work. */
107
+ export async function deleteFolder(
108
+ kind: DefinitionKind,
109
+ raw: unknown,
110
+ options: FolderOptions,
111
+ ): Promise<FolderResult> {
112
+ if (!options.writable) return READ_ONLY
113
+ const path = folderPath(raw)
114
+ if (!path) return { ok: false, status: 'invalid', message: 'That is not a name for a folder.' }
115
+ const target = join(rootOf(options.schemaDir, kind), path)
116
+ if (!existsSync(target))
117
+ return { ok: false, status: 'notFound', message: `There is no folder ${path}.` }
118
+ if (readdirSync(target).some((name) => !name.startsWith('.')))
119
+ return { ok: false, status: 'conflict', message: `${path} is not empty.` }
120
+ rmdirSync(target)
121
+ return changed(options)
122
+ }
123
+
124
+ /** Moves a definition's file to a folder, which is made if it is not there. */
125
+ export async function moveDefinition(
126
+ kind: DefinitionKind,
127
+ file: string | undefined,
128
+ rawFolder: unknown,
129
+ options: FolderOptions,
130
+ ): Promise<FolderResult> {
131
+ if (!options.writable) return READ_ONLY
132
+ if (!file || !existsSync(file))
133
+ return { ok: false, status: 'notFound', message: 'There is nothing to move.' }
134
+ const folder = folderPath(rawFolder)
135
+ if (folder === undefined)
136
+ return { ok: false, status: 'invalid', message: 'That is not a name for a folder.' }
137
+ const dir = join(rootOf(options.schemaDir, kind), folder)
138
+ const target = join(dir, file.slice(dirname(file).length + 1))
139
+ if (target === file) return { ok: true, path: folder }
140
+ if (existsSync(target))
141
+ return {
142
+ ok: false,
143
+ status: 'conflict',
144
+ message: `${folder} already holds a file of that name.`,
145
+ }
146
+ mkdirSync(dir, { recursive: true })
147
+ renameSync(file, target)
148
+ return changed(options, folder)
149
+ }
150
+
151
+ const STATUS = { readOnly: 403, invalid: 400, notFound: 404, conflict: 409 } as const
152
+
153
+ /** A folder change as an answer. */
154
+ export const folderResponse = (result: FolderResult): Response =>
155
+ result.ok
156
+ ? Response.json(result)
157
+ : Response.json({ ok: false, message: result.message }, { status: STATUS[result.status] })
158
+
159
+ /**
160
+ * The tree's folder routes, `tree-folders` and `tree-move`, shared by forms and
161
+ * workflows: hyphenated, so no alias can be mistaken for them. Undefined when the
162
+ * request is neither. `file` finds a definition by alias.
163
+ */
164
+ export async function folderAction(
165
+ kind: DefinitionKind,
166
+ path: string,
167
+ request: Request,
168
+ options: FolderOptions & { file: (alias: string) => string | undefined },
169
+ ): Promise<Response | undefined> {
170
+ if (path !== 'tree-folders' && path !== 'tree-move') return undefined
171
+ const body = (await request.json().catch(() => ({}))) as Record<string, unknown>
172
+ if (path === 'tree-move' && request.method === 'POST')
173
+ return folderResponse(
174
+ await moveDefinition(kind, options.file(String(body.alias)), body.folder, options),
175
+ )
176
+ if (path !== 'tree-folders') return undefined
177
+ if (request.method === 'POST') return folderResponse(await createFolder(kind, body.path, options))
178
+ if (request.method === 'PUT')
179
+ return folderResponse(await renameFolder(kind, body.from, body.to, options))
180
+ if (request.method === 'DELETE')
181
+ return folderResponse(await deleteFolder(kind, body.path, options))
182
+ return undefined
183
+ }
package/src/domains.ts CHANGED
@@ -35,7 +35,7 @@ export const DOMAINS_FILE = 'domains.toml'
35
35
  export interface DomainDeclaration {
36
36
  /** A content path (`/`, `/fr`) or a node uuid; resolved when the file is applied. */
37
37
  node: string
38
- /** A hostname, optionally with a port and a path, and optionally `${VAR}`. */
38
+ /** A hostname, optionally with a port and a path, or a path alone; optionally `${VAR}`. */
39
39
  host: string
40
40
  /** The culture this hostname serves; absent means the site's default. */
41
41
  culture?: string
@@ -13,7 +13,7 @@
13
13
  import { existsSync, readFileSync } from 'node:fs'
14
14
  import { readdir, readFile } from 'node:fs/promises'
15
15
  import { createRequire } from 'node:module'
16
- import { dirname, join } from 'node:path'
16
+ import { dirname, join, sep } from 'node:path'
17
17
  import { fileURLToPath } from 'node:url'
18
18
  import type { FormTypes } from '@crombolo/core'
19
19
  import { intendedTypes } from './models-builder.ts'
@@ -38,6 +38,9 @@ const MODULE_DIR = 'file:///node_modules/@crombolo/crombolo'
38
38
  */
39
39
  export const EDITOR_CONTENT_TYPES = 'file:///schema/content-types.d.ts'
40
40
 
41
+ /** The site's `components/`, which a view is opened inside at its own depth. */
42
+ const EDITOR_COMPONENTS = 'file:///components'
43
+
41
44
  /** Where the render sources' `import type … from 'react'` lands, by TypeScript's `@types` lookup. */
42
45
  const REACT_TYPES_DIR = 'file:///node_modules/@types/react'
43
46
  /** Where React's own `import … from 'csstype'` lands. */
@@ -99,11 +102,30 @@ export function siteJsxImportSource(siteDir: string): JsxImportSource {
99
102
  : '@crombolo/crombolo'
100
103
  }
101
104
 
105
+ /** The site's views, where a view's relative imports land: `../shared/layout.tsx`. */
106
+ async function viewLibs(componentsDir: string): Promise<EditorTypeLib[]> {
107
+ if (!existsSync(componentsDir)) return []
108
+ const files = await readdir(componentsDir, { recursive: true })
109
+ return Promise.all(
110
+ files
111
+ .filter((file) => /\.tsx?$/.test(file))
112
+ .sort()
113
+ .map(async (file) => ({
114
+ path: `${EDITOR_COMPONENTS}/${file.split(sep).join('/')}`,
115
+ content: await readFile(join(componentsDir, file), 'utf8'),
116
+ })),
117
+ )
118
+ }
119
+
102
120
  export async function editorTypeLibs(options: {
103
121
  schemaDir: string
122
+ componentsDir?: string
104
123
  formTypes?: FormTypes
105
124
  }): Promise<EditorTypeLib[]> {
106
- const libs = [...(await moduleLibs())]
125
+ const libs = [
126
+ ...(await moduleLibs()),
127
+ ...(options.componentsDir ? await viewLibs(options.componentsDir) : []),
128
+ ]
107
129
  const intended = intendedTypes(options.schemaDir, options.formTypes)
108
130
  // Left out rather than stubbed when the schema does not generate: a view that
109
131
  // imports it then says the file is missing, which is true, instead of being
package/src/form-files.ts CHANGED
@@ -11,7 +11,7 @@
11
11
  */
12
12
 
13
13
  import { existsSync, mkdirSync, rmSync, writeFileSync } from 'node:fs'
14
- import { join } from 'node:path'
14
+ import { dirname, join } from 'node:path'
15
15
  import type { FormTypes, SchemaForm } from '@crombolo/core'
16
16
  import {
17
17
  fileNameFor,
@@ -22,12 +22,16 @@ import {
22
22
  writeForm,
23
23
  } from '@crombolo/schema'
24
24
 
25
+ import { folderPath } from './definition-folders.ts'
26
+
25
27
  export interface FormFileOptions {
26
28
  schemaDir: string
27
29
  /** False on a deployed node with no schema store: the write would not last. */
28
30
  writable: boolean
29
31
  /** Publishes the directory to a shared store, when there is one. */
30
32
  onChanged?: () => Promise<void>
33
+ /** The folder a new form goes in; one that exists stays where it is. */
34
+ folder?: string
31
35
  /** The field and workflow types the site's wired bundles add. */
32
36
  formTypes?: FormTypes
33
37
  /** The components on disk, so a Send email `template` is held to one that exists. */
@@ -249,9 +253,11 @@ export async function saveForm(
249
253
  })
250
254
  if (problems.length > 0) return { ok: false, status: 'invalid', problems }
251
255
 
252
- const dir = join(options.schemaDir, 'forms')
253
- mkdirSync(dir, { recursive: true })
254
- const file = join(dir, name)
256
+ // A form stays in its folder (story 289); a new one goes in the folder it was made in.
257
+ const file =
258
+ loaded.files.get(`form:${form.alias}`) ??
259
+ join(options.schemaDir, 'forms', folderPath(options.folder) ?? '', name)
260
+ mkdirSync(dirname(file), { recursive: true })
255
261
  writeFileSync(file, writeForm(form), 'utf8')
256
262
  await options.onChanged?.()
257
263
  return { ok: true, file }
@@ -262,7 +268,9 @@ export async function deleteForm(
262
268
  options: FormFileOptions,
263
269
  ): Promise<FormWriteResult> {
264
270
  if (!options.writable) return readOnly()
265
- const file = join(options.schemaDir, 'forms', formFileName(alias))
271
+ const loaded = loadSchemaDirectory(options.schemaDir, { formTypes: options.formTypes })
272
+ const file =
273
+ loaded.files.get(`form:${alias}`) ?? join(options.schemaDir, 'forms', formFileName(alias))
266
274
  if (!existsSync(file))
267
275
  return {
268
276
  ok: false,
@@ -241,6 +241,8 @@ export interface FormSubmitDeps {
241
241
  urlOf?: (key: string) => Promise<string | undefined>
242
242
  /** Fills in the options of choices drawn from a source, as the page rendered them. */
243
243
  resolveForm?: (form: SchemaForm) => Promise<SchemaForm>
244
+ /** The language it was filled in, saved with the entry. */
245
+ culture?: string | null
244
246
  /** A published Library form's form, with its words (story 239). */
245
247
  libraryForm?: (key: string) => Promise<SchemaForm | undefined>
246
248
  }
@@ -397,7 +399,7 @@ export async function submitForm(
397
399
  const entry = await entries.create({
398
400
  formKey: key,
399
401
  formAlias: form.alias,
400
- culture: null,
402
+ culture: deps.culture ?? null,
401
403
  pageKey: null,
402
404
  libraryKey: libraryKey ?? null,
403
405
  ipHash: hashIp(secret, options.ip),
@@ -80,6 +80,8 @@ export interface WorkflowDeps {
80
80
  renderEmail?: (alias: string, props: EmailTemplateProps) => Promise<EmailRenderResult>
81
81
  /** The site's name and address, for an e-mail template. */
82
82
  site?: () => Promise<{ name: string; url: string }>
83
+ /** A form's words in the default language, so a message shows them and not their keys. */
84
+ resolveForm?: (form: SchemaForm) => Promise<SchemaForm>
83
85
  }
84
86
 
85
87
  export type WorkflowResult =
@@ -591,7 +593,7 @@ export function createWorkflowRunner(
591
593
  }
592
594
 
593
595
  const context: WorkflowContext = {
594
- form,
596
+ form: (await deps.resolveForm?.(form)) ?? form,
595
597
  values: run.payload,
596
598
  entryId: run.entryId,
597
599
  ...(run.recipients ? { recipients: run.recipients } : {}),
package/src/index.ts CHANGED
@@ -40,6 +40,7 @@ export * from './content-type-udt.ts'
40
40
  export * from './cron.ts'
41
41
  export * from './custom-tables.ts'
42
42
  export * from './database.ts'
43
+ export * from './definition-folders.ts'
43
44
  export * from './diagnostics.ts'
44
45
  export * from './dictionary-toml.ts'
45
46
  export * from './dictionary-transfer.ts'
@@ -108,6 +109,7 @@ export * from './server.ts'
108
109
  export * from './server-events.ts'
109
110
  export * from './settings.ts'
110
111
  export * from './setup.ts'
112
+ export * from './site-assets.ts'
111
113
  export * from './site-data.ts'
112
114
  export * from './site-file.ts'
113
115
  export * from './site-public.ts'
package/src/ports.ts CHANGED
@@ -56,7 +56,7 @@ import {
56
56
  import { createDictionaryPort } from './adapters/dictionary.ts'
57
57
  import { createDocumentPort } from './adapters/documents.ts'
58
58
  import { createElementPort } from './adapters/elements.ts'
59
- import { createFileSystemPort } from './adapters/file-system.ts'
59
+ import { createComponentsPort, createFileSystemPort } from './adapters/file-system.ts'
60
60
  import { createDiagnosticsPort } from './adapters/health.ts'
61
61
  import { createMediaPort } from './adapters/media.ts'
62
62
  import { createMemberGroupPort } from './adapters/member-groups.ts'
@@ -469,10 +469,7 @@ export function createDeps(options: DepsOptions): ManagementApiDeps {
469
469
  // through the partial-view file API because that one is path-addressed and
470
470
  // already understands folders; the template API is id-addressed and cannot
471
471
  // express a folder at all.
472
- deps.components = createFileSystemPort(options.config.componentsDir, {
473
- extension: '.tsx',
474
- rewrites: ['.cshtml'],
475
- })
472
+ deps.components = createComponentsPort(options.config.componentsDir)
476
473
  deps.componentSnippets = COMPONENT_SNIPPETS
477
474
  deps.stylesheets = createFileSystemPort(options.config.stylesheetsDir, { extension: '.css' })
478
475
  deps.scripts = createFileSystemPort(options.config.scriptsDir, { extension: '.js' })
package/src/schema.ts CHANGED
@@ -24,6 +24,7 @@ import {
24
24
  latestCheckpoint,
25
25
  latestLedgerId,
26
26
  type NodeSchemaState,
27
+ oldestCacheInstructionId,
27
28
  readWritesPaused,
28
29
  touchServer,
29
30
  updateSchemaStateHash,
@@ -251,6 +252,11 @@ export interface CachePollerOptions {
251
252
  role?: string
252
253
  /** Called for instructions other nodes appended. */
253
254
  onInstruction(kind: CacheInstructionKind, payload: Record<string, unknown>): void
255
+ /**
256
+ * Instructions this node never read were pruned (story 285). What has a
257
+ * checkpoint catches up by it; what has none has to look again.
258
+ */
259
+ onMissed?(): void
254
260
  /**
255
261
  * The published cache's freshness (story 174). With it, content and schema
256
262
  * instructions only wake the poll: the node compares the latest committed
@@ -392,6 +398,10 @@ export class CacheInstructionPoller {
392
398
  const { db, nodeId, nodeState, onInstruction } = this.#options
393
399
  // Read first: every instruction numbered up to it has committed, and is visible below.
394
400
  const latest = await latestCheckpoint(db)
401
+ // Pruning keeps the newest row, so the log only starts past this node when
402
+ // it lost rows. A gap in ids makes this a false alarm, which costs a look.
403
+ const oldest = await oldestCacheInstructionId(db)
404
+ if (oldest !== undefined && oldest > this.#cursor + 1) this.#options.onMissed?.()
395
405
  // A row can commit after one with a higher id (Postgres hands ids out
396
406
  // before commit), so a short window behind the cursor is read again and
397
407
  // the ids already seen are skipped.
@@ -9,6 +9,7 @@ import { createHash } from 'node:crypto'
9
9
  import { extname } from 'node:path'
10
10
  import {
11
11
  type ContentTypeAggregate,
12
+ formWordNames,
12
13
  IMAGE_CROPPER_EDITOR_ALIAS,
13
14
  normaliseUuid,
14
15
  ObjectTypes,
@@ -24,6 +25,7 @@ import {
24
25
  NodeRepository,
25
26
  resolveNodeRef,
26
27
  } from '@crombolo/data'
28
+ import { loadSchemaDirectory } from '@crombolo/schema'
27
29
  import {
28
30
  BUNDLE_FORMAT_VERSION,
29
31
  BUNDLE_SECTIONS,
@@ -89,6 +91,28 @@ export async function compileSeed(db: Db, config: CromboloConfig): Promise<SeedB
89
91
  message: problem.message,
90
92
  })
91
93
 
94
+ // The file is the dictionary when a site has one; without it, its items may
95
+ // all be in a database this build can't see.
96
+ if (dictionary) {
97
+ const names = new Set<string>()
98
+ const collect = (entries: readonly DictionaryEntry[]) => {
99
+ for (const entry of entries) {
100
+ names.add(entry.name.toLowerCase())
101
+ collect(entry.children)
102
+ }
103
+ }
104
+ collect(dictionary.entries)
105
+ for (const form of loadSchemaDirectory(config.schemaDir).set.forms ?? [])
106
+ for (const name of formWordNames(form))
107
+ if (!names.has(name.toLowerCase()))
108
+ findings.push({
109
+ file: `schema/forms/${form.alias}.toml`,
110
+ line: 1,
111
+ code: 'unknown-dictionary-item',
112
+ message: `the form "${form.alias}" names #${name}, which is not in ${DICTIONARY_FILE}`,
113
+ })
114
+ }
115
+
92
116
  const state = await currentSchemaState(db)
93
117
  const documentTypes = new ContentTypeRepository(db)
94
118
  const mediaTypes = new ContentTypeRepository(db, { kind: 'media' })
@@ -5,7 +5,7 @@
5
5
  * `content` commands read `--set`; and stored values back into that shorthand,
6
6
  * as `bundle export --source` and `content show` write them.
7
7
  */
8
- import { type ContentTypeAggregate, normaliseUuid } from '@crombolo/core'
8
+ import { type ContentTypeAggregate, dateFromText, normaliseUuid } from '@crombolo/core'
9
9
  import { ContentTypeRepository, DataTypeRepository, type Db, looksLikeKey } from '@crombolo/data'
10
10
  import { blockKey, pickKey } from './keys.ts'
11
11
 
@@ -246,17 +246,14 @@ export function valueWriter(lookup: SchemaLookup, refs: ValueRefs) {
246
246
  : typeof raw === 'string'
247
247
  ? raw
248
248
  : undefined
249
- const at = text === undefined ? Number.NaN : new Date(text).getTime()
250
- if (text === undefined || Number.isNaN(at))
251
- return fail('a date is a TOML date or an ISO 8601 string')
249
+ const at = text === undefined ? undefined : dateFromText(text)
250
+ if (text === undefined || !at) return fail('a date is a TOML date or an ISO 8601 string')
252
251
  // A date picker stores Umbraco's wall clock, as a save does, so a seed
253
252
  // exported and applied again is unchanged; one with a zone keeps ISO.
254
253
  return {
255
254
  ok: true,
256
255
  value:
257
- editor === 'Umbraco.DateTime'
258
- ? new Date(at).toISOString().slice(0, 19).replace('T', ' ')
259
- : text,
256
+ editor === 'Umbraco.DateTime' ? at.toISOString().slice(0, 19).replace('T', ' ') : text,
260
257
  }
261
258
  }
262
259
  case 'Umbraco.Tags':
package/src/server.ts CHANGED
@@ -146,7 +146,7 @@ import {
146
146
  validatorFor,
147
147
  withLiveReload,
148
148
  } from '@crombolo/render'
149
- import type { SyncReport } from '@crombolo/schema'
149
+ import { loadSchemaDirectory, type SyncReport } from '@crombolo/schema'
150
150
  import { choicesFor } from '@crombolo/transfer'
151
151
  import type { Server } from 'bun'
152
152
  import { createNodeLookup, loadAccess } from './access.ts'
@@ -181,6 +181,7 @@ import {
181
181
  import { answerContentQuery, contentQueryScope } from './content-query.ts'
182
182
  import { createCore } from './core.ts'
183
183
  import { closeTables, tablesReport } from './custom-tables.ts'
184
+ import { folderAction, folderOf, foldersIn } from './definition-folders.ts'
184
185
  import { createDeliveryMediaPort } from './delivery-media.ts'
185
186
  import { createDeliveryMemberSecurity } from './delivery-members.ts'
186
187
  import { syncDomainsFile } from './domains.ts'
@@ -362,6 +363,8 @@ export interface ServerOptions {
362
363
  * (story 241); absent when nothing supervises this one.
363
364
  */
364
365
  restart?: () => Promise<RestartOutcome>
366
+ /** Off, a node hears of file changes only through instructions, as on a network folder. */
367
+ watchSiteFiles?: boolean
365
368
  }
366
369
 
367
370
  export async function createServer(
@@ -385,7 +388,11 @@ export async function createServer(
385
388
  // and a template error says which components were rendering.
386
389
  const live = config.liveReload ? createLiveReload() : undefined
387
390
  let drafts: { cache: PublishedCache; version: number } | undefined
391
+ // Set once they exist: a Postgres notification can wake the poller before then,
392
+ // and they read the disk as they start anyway.
393
+ let siteFilesChanged: ((change: 'assets' | 'public') => void) | undefined
388
394
  const core = await createCore(config, {
395
+ onSiteFiles: (change) => siteFilesChanged?.(change),
389
396
  onCacheInvalidate: () => {
390
397
  drafts = undefined
391
398
  live?.changed('content')
@@ -862,13 +869,19 @@ export async function createServer(
862
869
  const generatedScripts = new Map(
863
870
  generatedBodies.map(([path, body]) => [generatedPaths.get(path) as string, body]),
864
871
  )
865
- const siteAssets = new SiteAssets([
866
- { prefix: '/css', dir: config.stylesheetsDir, extension: '.css' },
867
- { prefix: '/scripts', dir: config.scriptsDir, extension: '.js' },
868
- ])
872
+ const siteAssets = new SiteAssets(
873
+ [
874
+ { prefix: '/css', dir: config.stylesheetsDir, extension: '.css' },
875
+ { prefix: '/scripts', dir: config.scriptsDir, extension: '.js' },
876
+ ],
877
+ { watch: serverOptions.watchSiteFiles },
878
+ )
869
879
  siteAssets.start()
870
- const publicFiles = new PublicFiles(config.publicDir, config.backOfficePath)
880
+ const publicFiles = new PublicFiles(config.publicDir, config.backOfficePath, {
881
+ watch: serverOptions.watchSiteFiles,
882
+ })
871
883
  publicFiles.start()
884
+ siteFilesChanged = (change) => (change === 'public' ? publicFiles.changed() : siteAssets.rescan())
872
885
  // A file wins at its path (story 284), so a page it hides is worth saying once.
873
886
  if (config.role !== 'api' && publicFiles.paths().length > 0)
874
887
  void publicFiles
@@ -1961,6 +1974,7 @@ export async function createServer(
1961
1974
  const body = JSON.stringify({
1962
1975
  libs: await editorTypeLibs({
1963
1976
  schemaDir: config.schemaDir,
1977
+ componentsDir: config.componentsDir,
1964
1978
  formTypes: formTypesFor(config),
1965
1979
  }),
1966
1980
  jsxImportSource: siteJsxImportSource(config.siteDir),
@@ -2178,6 +2192,12 @@ export async function createServer(
2178
2192
  )
2179
2193
  }
2180
2194
 
2195
+ // Whether what `schema/` holds can be changed here, for the views that say so (story 289).
2196
+ if (pathname === `${paths.pluginPath}/api/site-files` && request.method === 'GET') {
2197
+ if (!(await authenticate(request))) return new Response('Unauthorized', { status: 401 })
2198
+ return Response.json({ writable: config.schemaWritable })
2199
+ }
2200
+
2181
2201
  if (pathname === `${paths.pluginPath}/api/email` && request.method === 'GET') {
2182
2202
  if (!(await authenticate(request))) return new Response('Unauthorized', { status: 401 })
2183
2203
  return Response.json({
@@ -2247,10 +2267,24 @@ export async function createServer(
2247
2267
 
2248
2268
  // A definition is structure, like a content type: anyone who may open the
2249
2269
  // section may read it, and the picker needs it in the Content section too.
2250
- if (action === '' && request.method === 'GET')
2270
+ if (action === '' && request.method === 'GET') {
2271
+ const files = loadSchemaDirectory(config.schemaDir, { formTypes: formTypes.types }).files
2272
+ const file = (alias: string) => files.get(`form:${alias}`)
2251
2273
  return Response.json({
2252
- items: definitions.map((form) => formSummary(form, formTypes.types)),
2274
+ items: definitions.map((form) => ({
2275
+ ...formSummary(form, formTypes.types),
2276
+ folder: file(form.alias)
2277
+ ? folderOf(config.schemaDir, 'forms', file(form.alias) as string)
2278
+ : '',
2279
+ })),
2280
+ folders: foldersIn(config.schemaDir, 'forms'),
2281
+ readOnlyBecause: !config.schemaWritable
2282
+ ? 'site'
2283
+ : principal.isAdmin || principal.permissions.includes(FormPermissions.Manage)
2284
+ ? null
2285
+ : 'permission',
2253
2286
  })
2287
+ }
2254
2288
  // Hyphenated, so no form alias (letters and digits) can be mistaken for it.
2255
2289
  if (action === 'available-types' && request.method === 'GET')
2256
2290
  return Response.json(describeFormTypes(formTypes.types))
@@ -2303,6 +2337,15 @@ export async function createServer(
2303
2337
  }
2304
2338
  : undefined,
2305
2339
  }
2340
+ // Every dictionary item in the default language, for the designer to suggest.
2341
+ if (action === 'words' && request.method === 'GET') {
2342
+ if (!may(FormPermissions.Manage)) return new Response('Forbidden', { status: 403 })
2343
+ const entries = await cache.dictionaryEntries(null)
2344
+ return Response.json({
2345
+ words: Object.entries(entries).map(([name, text]) => ({ name, text })),
2346
+ })
2347
+ }
2348
+
2306
2349
  const maySeeEntries = may(FormPermissions.EntriesView)
2307
2350
  const mayManageEntries = may(FormPermissions.EntriesManage)
2308
2351
  // The group alias still counts: `sensitiveData` is how Umbraco carries
@@ -2378,7 +2421,7 @@ export async function createServer(
2378
2421
  const form = byKey.get(key)
2379
2422
  if (!form) return new Response('Not Found', { status: 404 })
2380
2423
  const page = await entries.list({ formKey: key, take: 10_000 })
2381
- const result = entriesCsv(form, page.items, {
2424
+ const result = entriesCsv(await cache.resolveForm(form), page.items, {
2382
2425
  includeSensitive: maySeeSensitive,
2383
2426
  types: formTypes.types,
2384
2427
  })
@@ -2407,6 +2450,7 @@ export async function createServer(
2407
2450
  formKey: key,
2408
2451
  ...(library ? { libraryKey: library === 'none' ? null : library } : {}),
2409
2452
  state: parseEntryState(url.searchParams.get('state')),
2453
+ culture: url.searchParams.get('language') || undefined,
2410
2454
  from: since ? new Date(since) : undefined,
2411
2455
  to: until ? new Date(until) : undefined,
2412
2456
  search: url.searchParams.get('search') ?? undefined,
@@ -2417,6 +2461,7 @@ export async function createServer(
2417
2461
  const form = byKey.get(key)
2418
2462
  return Response.json({
2419
2463
  total: page.total,
2464
+ languages: await entries.languages(key),
2420
2465
  items: page.items.map((entry) => ({
2421
2466
  ...entry,
2422
2467
  values: redactSensitive(entry, form, maySeeSensitive),
@@ -2452,10 +2497,22 @@ export async function createServer(
2452
2497
 
2453
2498
  // Designing a form is a developer's job, so it is its own verb rather
2454
2499
  // than something an entry reader can do.
2500
+ if (action === 'tree-folders' || action === 'tree-move') {
2501
+ if (!may(FormPermissions.Manage)) return new Response('Forbidden', { status: 403 })
2502
+ const response = await folderAction('forms', action, request, {
2503
+ ...formFiles,
2504
+ file: (alias) =>
2505
+ loadSchemaDirectory(config.schemaDir, { formTypes: formTypes.types }).files.get(
2506
+ `form:${alias}`,
2507
+ ),
2508
+ })
2509
+ if (response) return response
2510
+ }
2455
2511
  if (request.method === 'POST' || request.method === 'PUT') {
2456
2512
  if (!may(FormPermissions.Manage)) return new Response('Forbidden', { status: 403 })
2457
2513
  const body = await request.json().catch(() => ({}))
2458
- const written = await saveForm(coerceForm(body), formFiles)
2514
+ const folder = url.searchParams.get('folder') ?? undefined
2515
+ const written = await saveForm(coerceForm(body), { ...formFiles, folder })
2459
2516
  if (!written.ok) {
2460
2517
  log.warning('{user} could not save a form: {detail}', {
2461
2518
  user: principal.email,
@@ -3135,6 +3192,20 @@ export async function createServer(
3135
3192
  }
3136
3193
  })()
3137
3194
 
3195
+ // An app says which language it drew the form in; a page's address says it otherwise.
3196
+ const culture = await (async () => {
3197
+ const asked = requestedCulture(request.headers.get('accept-language'))
3198
+ if (asked && (await cache.hasCulture(asked))) return asked
3199
+ try {
3200
+ const referer = request.headers.get('referer')
3201
+ if (!referer) return null
3202
+ const url = new URL(referer)
3203
+ return await cache.cultureFor(url.host, url.pathname)
3204
+ } catch {
3205
+ return null
3206
+ }
3207
+ })()
3208
+
3138
3209
  const outcome = await submitForm(
3139
3210
  {
3140
3211
  db,
@@ -3146,22 +3217,8 @@ export async function createServer(
3146
3217
  libraryForm: (libraryKey) => cache.libraryForm(libraryKey),
3147
3218
  // The page it was sent from names the culture; the keys a source offers
3148
3219
  // are the same in every culture, so only the stored labels depend on it.
3149
- resolveForm: async (form) => {
3150
- // An app says which language it drew the form in; a page's address says it otherwise.
3151
- const asked = requestedCulture(request.headers.get('accept-language'))
3152
- if (asked && (await cache.hasCulture(asked))) return cache.resolveForm(form, asked)
3153
- const referer = request.headers.get('referer')
3154
- let culture: string | null = null
3155
- try {
3156
- if (referer) {
3157
- const url = new URL(referer)
3158
- culture = await cache.cultureFor(url.host, url.pathname)
3159
- }
3160
- } catch {
3161
- culture = null
3162
- }
3163
- return cache.resolveForm(form, culture)
3164
- },
3220
+ resolveForm: (form) => cache.resolveForm(form, culture),
3221
+ culture,
3165
3222
  },
3166
3223
  request,
3167
3224
  key,
@@ -16,18 +16,21 @@ export interface AssetRoot {
16
16
 
17
17
  export class SiteAssets {
18
18
  readonly #roots: readonly AssetRoot[]
19
+ readonly #watch: boolean
19
20
  readonly #hashes = new Map<string, string>()
20
21
  readonly #watchers: FSWatcher[] = []
21
22
 
22
- constructor(roots: readonly AssetRoot[]) {
23
+ constructor(roots: readonly AssetRoot[], options: { watch?: boolean } = {}) {
23
24
  this.#roots = roots
25
+ this.#watch = options.watch !== false
24
26
  }
25
27
 
26
28
  /** Hashes every file, and watches each folder for changes. */
27
29
  start(): void {
30
+ this.rescan()
31
+ if (!this.#watch) return
28
32
  for (const root of this.#roots) {
29
33
  if (!existsSync(root.dir)) continue
30
- for (const file of filesIn(root.dir)) this.#hash(root, file)
31
34
  try {
32
35
  const watcher = watch(root.dir, { recursive: true }, (_event, name) => {
33
36
  if (name) this.#hash(root, join(root.dir, name.toString()))
@@ -40,6 +43,18 @@ export class SiteAssets {
40
43
  }
41
44
  }
42
45
 
46
+ /** Every file hashed again, and one that has gone forgotten: for a change no watcher saw. */
47
+ rescan(): void {
48
+ this.#hashes.clear()
49
+ for (const root of this.#roots) {
50
+ try {
51
+ if (existsSync(root.dir)) for (const file of filesIn(root.dir)) this.#hash(root, file)
52
+ } catch {
53
+ // A file that went while the folder was read: the next change says so.
54
+ }
55
+ }
56
+ }
57
+
43
58
  /** The hashed address of a file the site has, or undefined. */
44
59
  address(path: string): string | undefined {
45
60
  const hash = this.#hashes.get(path)
@@ -52,9 +67,13 @@ export class SiteAssets {
52
67
 
53
68
  #hash(root: AssetRoot, file: string): void {
54
69
  const path = `${root.prefix}/${relative(root.dir, file).split(sep).join('/')}`
55
- if (!file.toLowerCase().endsWith(root.extension)) return
56
70
  try {
57
- if (!statSync(file).isFile()) return
71
+ // A folder moved in reports only its own name.
72
+ if (statSync(file).isDirectory()) {
73
+ for (const inside of filesIn(file)) this.#hash(root, inside)
74
+ return
75
+ }
76
+ if (!file.toLowerCase().endsWith(root.extension)) return
58
77
  this.#hashes.set(path, contentHash(readFileSync(file)))
59
78
  } catch {
60
79
  this.#hashes.delete(path)
package/src/site-file.ts CHANGED
@@ -29,7 +29,7 @@ import {
29
29
  sealBytes,
30
30
  writeManifest,
31
31
  } from '@crombolo/transfer'
32
- import { createFileSystemPort } from './adapters/file-system.ts'
32
+ import { createComponentsPort, createFileSystemPort } from './adapters/file-system.ts'
33
33
  import { createTemplateFileStore } from './adapters/template-files.ts'
34
34
  import { type CromboloConfig, VERSION } from './config.ts'
35
35
  import { mediaStoreFor } from './media-files.ts'
@@ -163,10 +163,7 @@ export async function exportSite(
163
163
  {
164
164
  db,
165
165
  componentFiles: createTemplateFileStore(config.componentsDir),
166
- components: createFileSystemPort(config.componentsDir, {
167
- extension: '.tsx',
168
- rewrites: ['.cshtml'],
169
- }),
166
+ components: createComponentsPort(config.componentsDir),
170
167
  stylesheets: createFileSystemPort(config.stylesheetsDir, { extension: '.css' }),
171
168
  scripts: createFileSystemPort(config.scriptsDir, { extension: '.js' }),
172
169
  schemaDir: config.schemaDir,
@@ -22,6 +22,11 @@ const WELL_KNOWN = '.well-known'
22
22
  /** What git needs to keep an empty folder: it travels with the folder, and is never served. */
23
23
  const FOLDER_KEEPER = '.gitkeep'
24
24
  const RESCAN_DELAY_MS = 25
25
+ /**
26
+ * After a node is told of a change, it lists the folder again at these delays:
27
+ * a shared folder can show another machine's write up to a minute late.
28
+ */
29
+ const RELIST_AFTER_MS = [5_000, 15_000, 30_000, 60_000, 90_000]
25
30
 
26
31
  /** Whether an address is the CMS's own, which no public file can take. */
27
32
  export function isReservedPublicPath(path: string, backOfficePath: string): boolean {
@@ -129,15 +134,25 @@ export class PublicFiles {
129
134
  #folder: FSWatcher | undefined
130
135
  #parent: FSWatcher | undefined
131
136
  #rescan: ReturnType<typeof setTimeout> | undefined
137
+ #relist: ReturnType<typeof setTimeout>[] = []
138
+ readonly #watch: boolean
139
+ readonly #relistAfter: readonly number[]
132
140
 
133
- constructor(root: string, backOfficePath: string) {
141
+ constructor(
142
+ root: string,
143
+ backOfficePath: string,
144
+ options: { watch?: boolean; relistAfterMs?: readonly number[] } = {},
145
+ ) {
134
146
  this.#root = root
135
147
  this.#backOfficePath = backOfficePath
148
+ this.#watch = options.watch !== false
149
+ this.#relistAfter = options.relistAfterMs ?? RELIST_AFTER_MS
136
150
  }
137
151
 
138
152
  /** Lists the folder and watches it, and watches for it being made or replaced. */
139
153
  start(): void {
140
154
  this.#list()
155
+ if (!this.#watch) return
141
156
  this.#watchFolder()
142
157
  try {
143
158
  const name = basename(this.#root)
@@ -152,8 +167,20 @@ export class PublicFiles {
152
167
  }
153
168
  }
154
169
 
170
+ /** The folder changed where no watcher can see: listed now, and again as it settles. */
171
+ changed(): void {
172
+ for (const timer of this.#relist.splice(0)) clearTimeout(timer)
173
+ this.#list()
174
+ this.#relist = this.#relistAfter.map((delay) => {
175
+ const timer = setTimeout(() => this.#list(), delay)
176
+ timer.unref?.()
177
+ return timer
178
+ })
179
+ }
180
+
155
181
  close(): void {
156
182
  clearTimeout(this.#rescan)
183
+ for (const timer of this.#relist.splice(0)) clearTimeout(timer)
157
184
  this.#folder?.close()
158
185
  this.#parent?.close()
159
186
  }