@crombolo/server 0.51.1 → 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.1",
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.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",
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,
package/src/config.ts CHANGED
@@ -1091,7 +1091,7 @@ export function describeDatabase(
1091
1091
  }
1092
1092
  }
1093
1093
 
1094
- export const VERSION = '0.51.1'
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
@@ -619,6 +619,7 @@ export async function createCore(config: CromboloConfig, hooks: CoreHooks) {
619
619
  nodeState: schema.nodeState,
620
620
  nodeId: schema.nodeId,
621
621
  onContentChanged: () => cache.invalidate(),
622
+ resolveForm: (form) => cache.resolveForm(form),
622
623
  operations: operations.documents,
623
624
  bundleWorkflows: formTypes.workflows,
624
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'
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' })
@@ -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'
@@ -1973,6 +1974,7 @@ export async function createServer(
1973
1974
  const body = JSON.stringify({
1974
1975
  libs: await editorTypeLibs({
1975
1976
  schemaDir: config.schemaDir,
1977
+ componentsDir: config.componentsDir,
1976
1978
  formTypes: formTypesFor(config),
1977
1979
  }),
1978
1980
  jsxImportSource: siteJsxImportSource(config.siteDir),
@@ -2190,6 +2192,12 @@ export async function createServer(
2190
2192
  )
2191
2193
  }
2192
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
+
2193
2201
  if (pathname === `${paths.pluginPath}/api/email` && request.method === 'GET') {
2194
2202
  if (!(await authenticate(request))) return new Response('Unauthorized', { status: 401 })
2195
2203
  return Response.json({
@@ -2259,10 +2267,24 @@ export async function createServer(
2259
2267
 
2260
2268
  // A definition is structure, like a content type: anyone who may open the
2261
2269
  // section may read it, and the picker needs it in the Content section too.
2262
- 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}`)
2263
2273
  return Response.json({
2264
- 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',
2265
2286
  })
2287
+ }
2266
2288
  // Hyphenated, so no form alias (letters and digits) can be mistaken for it.
2267
2289
  if (action === 'available-types' && request.method === 'GET')
2268
2290
  return Response.json(describeFormTypes(formTypes.types))
@@ -2315,6 +2337,15 @@ export async function createServer(
2315
2337
  }
2316
2338
  : undefined,
2317
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
+
2318
2349
  const maySeeEntries = may(FormPermissions.EntriesView)
2319
2350
  const mayManageEntries = may(FormPermissions.EntriesManage)
2320
2351
  // The group alias still counts: `sensitiveData` is how Umbraco carries
@@ -2390,7 +2421,7 @@ export async function createServer(
2390
2421
  const form = byKey.get(key)
2391
2422
  if (!form) return new Response('Not Found', { status: 404 })
2392
2423
  const page = await entries.list({ formKey: key, take: 10_000 })
2393
- const result = entriesCsv(form, page.items, {
2424
+ const result = entriesCsv(await cache.resolveForm(form), page.items, {
2394
2425
  includeSensitive: maySeeSensitive,
2395
2426
  types: formTypes.types,
2396
2427
  })
@@ -2419,6 +2450,7 @@ export async function createServer(
2419
2450
  formKey: key,
2420
2451
  ...(library ? { libraryKey: library === 'none' ? null : library } : {}),
2421
2452
  state: parseEntryState(url.searchParams.get('state')),
2453
+ culture: url.searchParams.get('language') || undefined,
2422
2454
  from: since ? new Date(since) : undefined,
2423
2455
  to: until ? new Date(until) : undefined,
2424
2456
  search: url.searchParams.get('search') ?? undefined,
@@ -2429,6 +2461,7 @@ export async function createServer(
2429
2461
  const form = byKey.get(key)
2430
2462
  return Response.json({
2431
2463
  total: page.total,
2464
+ languages: await entries.languages(key),
2432
2465
  items: page.items.map((entry) => ({
2433
2466
  ...entry,
2434
2467
  values: redactSensitive(entry, form, maySeeSensitive),
@@ -2464,10 +2497,22 @@ export async function createServer(
2464
2497
 
2465
2498
  // Designing a form is a developer's job, so it is its own verb rather
2466
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
+ }
2467
2511
  if (request.method === 'POST' || request.method === 'PUT') {
2468
2512
  if (!may(FormPermissions.Manage)) return new Response('Forbidden', { status: 403 })
2469
2513
  const body = await request.json().catch(() => ({}))
2470
- const written = await saveForm(coerceForm(body), formFiles)
2514
+ const folder = url.searchParams.get('folder') ?? undefined
2515
+ const written = await saveForm(coerceForm(body), { ...formFiles, folder })
2471
2516
  if (!written.ok) {
2472
2517
  log.warning('{user} could not save a form: {detail}', {
2473
2518
  user: principal.email,
@@ -3147,6 +3192,20 @@ export async function createServer(
3147
3192
  }
3148
3193
  })()
3149
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
+
3150
3209
  const outcome = await submitForm(
3151
3210
  {
3152
3211
  db,
@@ -3158,22 +3217,8 @@ export async function createServer(
3158
3217
  libraryForm: (libraryKey) => cache.libraryForm(libraryKey),
3159
3218
  // The page it was sent from names the culture; the keys a source offers
3160
3219
  // are the same in every culture, so only the stored labels depend on it.
3161
- resolveForm: async (form) => {
3162
- // An app says which language it drew the form in; a page's address says it otherwise.
3163
- const asked = requestedCulture(request.headers.get('accept-language'))
3164
- if (asked && (await cache.hasCulture(asked))) return cache.resolveForm(form, asked)
3165
- const referer = request.headers.get('referer')
3166
- let culture: string | null = null
3167
- try {
3168
- if (referer) {
3169
- const url = new URL(referer)
3170
- culture = await cache.cultureFor(url.host, url.pathname)
3171
- }
3172
- } catch {
3173
- culture = null
3174
- }
3175
- return cache.resolveForm(form, culture)
3176
- },
3220
+ resolveForm: (form) => cache.resolveForm(form, culture),
3221
+ culture,
3177
3222
  },
3178
3223
  request,
3179
3224
  key,
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,