@crombolo/server 0.51.1 → 0.53.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.53.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.53.2",
35
+ "@crombolo/api-management": "0.53.2",
36
+ "@crombolo/auth": "0.53.2",
37
+ "@crombolo/backoffice-host": "0.53.2",
38
+ "@crombolo/common": "0.53.2",
39
+ "@crombolo/content": "0.53.2",
40
+ "@crombolo/contracts": "0.53.2",
41
+ "@crombolo/core": "0.53.2",
42
+ "@crombolo/data": "0.53.2",
43
+ "@crombolo/render": "0.53.2",
44
+ "@crombolo/schema": "0.53.2",
45
+ "@crombolo/transfer": "0.53.2",
46
46
  "@logtape/logtape": "^2.3.8",
47
47
  "@opentelemetry/api": "1.10.0",
48
48
  "@opentelemetry/context-async-hooks": "3.0.0",
@@ -32,6 +32,7 @@ import {
32
32
  type ContentTypeRepositoryOptions,
33
33
  DataTypeRepository,
34
34
  type Db,
35
+ FORM_LIBRARY_FOLDER,
35
36
  FolderRepository,
36
37
  Locks,
37
38
  type NodeRepository,
@@ -199,6 +200,19 @@ export interface ContentTypePortOptions extends ContentTypeRepositoryOptions {
199
200
  componentFiles?: ComponentFileStore
200
201
  }
201
202
 
203
+ /** Whether a tree item is the folder holding the types made from forms, and nothing else. */
204
+ async function madeFromForms(db: Db, item: TreeItem): Promise<boolean> {
205
+ if (!item.isFolder || item.name !== FORM_LIBRARY_FOLDER) return false
206
+ const rows = await db.q
207
+ .selectFrom('node as folder')
208
+ .innerJoin('node as child', 'child.parent_id', 'folder.id')
209
+ .leftJoin('content_type as type', 'type.node_id', 'child.id')
210
+ .select('type.form_key')
211
+ .where('folder.unique_id', '=', item.key)
212
+ .execute()
213
+ return rows.length > 0 && rows.every((row) => row.form_key)
214
+ }
215
+
202
216
  export function createContentTypePort(
203
217
  db: Db,
204
218
  schemaFiles?: SchemaFiles,
@@ -508,7 +522,15 @@ export function createContentTypePort(
508
522
  'renameFolder',
509
523
  'deleteFolder',
510
524
  ]),
511
- treeRoot: tree.treeRoot,
525
+ async treeRoot(paging: TreePage): Promise<Page<TreeItem>> {
526
+ const page = await tree.treeRoot(paging)
527
+ if (kind !== 'document') return page
528
+ // Forms sit beside content types in Structure, so the types made from them
529
+ // aren't shown twice. Library and the pickers read them directly.
530
+ const shown: TreeItem[] = []
531
+ for (const item of page.items) if (!(await madeFromForms(db, item))) shown.push(item)
532
+ return { total: page.total - (page.items.length - shown.length), items: shown }
533
+ },
512
534
  treeChildren: tree.treeChildren,
513
535
 
514
536
  async root(paging: SkipTake): Promise<Page<TreeItem>> {
@@ -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,8 +8,8 @@
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'
12
- import type { Principal } from '@crombolo/api-management/domain'
11
+ import { dirname, join } from 'node:path'
12
+ import { hasSection, type Principal } from '@crombolo/api-management/domain'
13
13
  import type { SchemaWorkflow } from '@crombolo/core'
14
14
  import {
15
15
  type ApprovalScheduleEntry,
@@ -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
@@ -50,6 +51,10 @@ export async function syncWorkflowFiles(db: Db, schemaDir: string) {
50
51
  }
51
52
 
52
53
  /** What saving a workflow would do to the requests in flight under it. */
54
+ /** Setting up workflows, which a group can be given (story 296). Deciding on a page is separate. */
55
+ const mayDesignWorkflows = (principal: Principal): boolean =>
56
+ principal.isAdmin || hasSection(principal, 'workflowSetup')
57
+
53
58
  async function changePreview(approvals: Approvals, principal: Principal, workflow: SchemaWorkflow) {
54
59
  const id = workflow.key ?? workflow.alias
55
60
  const stored = (await approvals.workflows()).find(
@@ -147,11 +152,35 @@ export async function handleApprovalsApi(
147
152
  return json({ active })
148
153
  }
149
154
 
155
+ const folderIn = (file: string | undefined) =>
156
+ file ? folderOf(ctx.schemaDir, 'workflows', file) : ''
157
+ const folders = /^workflows\/(tree-folders|tree-move)$/.exec(path)
158
+ if (folders) {
159
+ if (!mayDesignWorkflows(principal))
160
+ return json({ ok: false, message: 'You do not have access to set up workflows.' }, 403)
161
+ const response = await folderAction('workflows', folders[1] as string, request, {
162
+ schemaDir: ctx.schemaDir,
163
+ writable: ctx.writable,
164
+ onChanged: ctx.onChanged,
165
+ file: (alias) => loadSchemaDirectory(ctx.schemaDir).files.get(`workflow:${alias}`),
166
+ })
167
+ if (response) return response
168
+ }
169
+
150
170
  if (path === 'workflows' && request.method === 'GET') {
151
171
  const loaded = loadSchemaDirectory(ctx.schemaDir)
152
172
  return json({
153
- items: (await readWorkflows(ctx.db)).map((s) => s.workflow),
154
- editable: ctx.writable && principal.isAdmin,
173
+ items: (await readWorkflows(ctx.db)).map((s) => ({
174
+ ...s.workflow,
175
+ folder: folderIn(loaded.files.get(`workflow:${s.workflow.alias}`)),
176
+ })),
177
+ folders: foldersIn(ctx.schemaDir, 'workflows'),
178
+ readOnlyBecause: ctx.writable
179
+ ? mayDesignWorkflows(principal)
180
+ ? null
181
+ : 'permission'
182
+ : 'site',
183
+ editable: ctx.writable && mayDesignWorkflows(principal),
155
184
  groups: (await new UserGroupRepository(ctx.db).all()).map((g) => ({
156
185
  alias: g.alias,
157
186
  name: g.name,
@@ -162,10 +191,11 @@ export async function handleApprovalsApi(
162
191
 
163
192
  match = /^workflows\/([^/]+)(\/preview)?$/.exec(path)
164
193
  if (match) {
165
- if (!principal.isAdmin)
166
- return json({ ok: false, message: 'Only administrators change workflows.' }, 403)
194
+ if (!mayDesignWorkflows(principal))
195
+ return json({ ok: false, message: 'You do not have access to set up workflows.' }, 403)
167
196
  const alias = decodeURIComponent(match[1] as string)
168
- const file = join(ctx.schemaDir, 'workflows', fileNameFor(alias))
197
+ const here = loadSchemaDirectory(ctx.schemaDir).files.get(`workflow:${alias}`)
198
+ const file = here ?? join(ctx.schemaDir, 'workflows', fileNameFor(alias))
169
199
  if (request.method === 'DELETE') {
170
200
  if (match[2])
171
201
  return json({ ok: true, affected: await removalPreview(approvals, principal, alias) })
@@ -205,10 +235,14 @@ export async function handleApprovalsApi(
205
235
  const affected = await changePreview(approvals, principal, workflow)
206
236
  if (match[2]) return json({ ok: true, affected })
207
237
  if (!ctx.writable) return readOnly()
208
- mkdirSync(join(ctx.schemaDir, 'workflows'), { recursive: true })
238
+ // It stays in its folder (story 289); a new one goes in the folder it was made in.
239
+ const dir = here
240
+ ? dirname(here)
241
+ : join(ctx.schemaDir, 'workflows', folderPath(b.folder) ?? '')
242
+ mkdirSync(dir, { recursive: true })
209
243
  // A renamed workflow leaves its old file behind otherwise.
210
244
  if (alias !== workflow.alias && existsSync(file)) rmSync(file)
211
- writeFileSync(join(ctx.schemaDir, 'workflows', fileNameFor(workflow.alias)), source, 'utf8')
245
+ writeFileSync(join(dir, fileNameFor(workflow.alias)), source, 'utf8')
212
246
  await ctx.onChanged?.()
213
247
  return json({ ok: true, affected, report: await syncWorkflowFiles(ctx.db, ctx.schemaDir) })
214
248
  }
@@ -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.53.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
@@ -27,6 +27,7 @@ import {
27
27
  import type { EventSink } from '@crombolo/content'
28
28
  import {
29
29
  CORE_SECTION_ALIASES,
30
+ clientSections,
30
31
  DEFAULT_UPLOAD_SETTINGS,
31
32
  hasAccessToSensitiveData,
32
33
  isUploadAllowed,
@@ -56,7 +57,7 @@ import {
56
57
  import { createDictionaryPort } from './adapters/dictionary.ts'
57
58
  import { createDocumentPort } from './adapters/documents.ts'
58
59
  import { createElementPort } from './adapters/elements.ts'
59
- import { createFileSystemPort } from './adapters/file-system.ts'
60
+ import { createComponentsPort, createFileSystemPort } from './adapters/file-system.ts'
60
61
  import { createDiagnosticsPort } from './adapters/health.ts'
61
62
  import { createMediaPort } from './adapters/media.ts'
62
63
  import { createMemberGroupPort } from './adapters/member-groups.ts'
@@ -255,7 +256,7 @@ function createCurrentUserPort(
255
256
  hasAccessToSensitiveData: hasAccessToSensitiveData(principal.groups),
256
257
  fallbackPermissions: principal.permissions,
257
258
  permissions,
258
- allowedSections: principal.allowedSections,
259
+ allowedSections: clientSections(principal),
259
260
  userGroupIds: principal.groupKeys.map((id) => ({ id })),
260
261
  }
261
262
  },
@@ -469,10 +470,7 @@ export function createDeps(options: DepsOptions): ManagementApiDeps {
469
470
  // through the partial-view file API because that one is path-addressed and
470
471
  // already understands folders; the template API is id-addressed and cannot
471
472
  // express a folder at all.
472
- deps.components = createFileSystemPort(options.config.componentsDir, {
473
- extension: '.tsx',
474
- rewrites: ['.cshtml'],
475
- })
473
+ deps.components = createComponentsPort(options.config.componentsDir)
476
474
  deps.componentSnippets = COMPONENT_SNIPPETS
477
475
  deps.stylesheets = createFileSystemPort(options.config.stylesheetsDir, { extension: '.css' })
478
476
  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,
@@ -33,6 +35,7 @@ import {
33
35
  type BundleNode,
34
36
  type BundleValue,
35
37
  type ContentSet,
38
+ ELEMENT_FOLDER_TYPE,
36
39
  referenceCandidates,
37
40
  writeBundle,
38
41
  writeBundlePackage,
@@ -45,6 +48,7 @@ import { lineOf } from './lines.ts'
45
48
  import {
46
49
  DICTIONARY_FILE,
47
50
  kindDir,
51
+ nameFromSegment,
48
52
  readSeed,
49
53
  readSeedDictionary,
50
54
  type SeedFinding,
@@ -65,12 +69,6 @@ export interface SeedBuild {
65
69
  dictionary?: DictionaryEntry[]
66
70
  }
67
71
 
68
- /** A word for a file name: `about-us` → `About us`. */
69
- const nameFromSegment = (segment: string) => {
70
- const words = segment.replace(/[-_]+/g, ' ').trim()
71
- return words.charAt(0).toUpperCase() + words.slice(1)
72
- }
73
-
74
72
  const isRecord = (value: unknown): value is Record<string, unknown> =>
75
73
  typeof value === 'object' && value !== null && !Array.isArray(value) && !(value instanceof Date)
76
74
 
@@ -89,6 +87,28 @@ export async function compileSeed(db: Db, config: CromboloConfig): Promise<SeedB
89
87
  message: problem.message,
90
88
  })
91
89
 
90
+ // The file is the dictionary when a site has one; without it, its items may
91
+ // all be in a database this build can't see.
92
+ if (dictionary) {
93
+ const names = new Set<string>()
94
+ const collect = (entries: readonly DictionaryEntry[]) => {
95
+ for (const entry of entries) {
96
+ names.add(entry.name.toLowerCase())
97
+ collect(entry.children)
98
+ }
99
+ }
100
+ collect(dictionary.entries)
101
+ for (const form of loadSchemaDirectory(config.schemaDir).set.forms ?? [])
102
+ for (const name of formWordNames(form))
103
+ if (!names.has(name.toLowerCase()))
104
+ findings.push({
105
+ file: `schema/forms/${form.alias}.toml`,
106
+ line: 1,
107
+ code: 'unknown-dictionary-item',
108
+ message: `the form "${form.alias}" names #${name}, which is not in ${DICTIONARY_FILE}`,
109
+ })
110
+ }
111
+
92
112
  const state = await currentSchemaState(db)
93
113
  const documentTypes = new ContentTypeRepository(db)
94
114
  const mediaTypes = new ContentTypeRepository(db, { kind: 'media' })
@@ -190,16 +210,42 @@ export async function compileSeed(db: Db, config: CromboloConfig): Promise<SeedB
190
210
  }
191
211
  const libraryKey = async (ref: string, why: string) => {
192
212
  const seeded = libraryByPath.get(trimPath(ref))
193
- if (seeded) return keyOf.get(seeded)
213
+ if (seeded) return seeded.folder ? undefined : keyOf.get(seeded)
194
214
  if (looksLikeKey(ref)) return normaliseUuid(ref)
195
215
  return siteNode(ref, ObjectTypes.Element, why)
196
216
  }
217
+ const forms = loadSchemaDirectory(config.schemaDir).set.forms ?? []
218
+ /** A Library form by its path, else a form by its alias: what a form picker stores. */
219
+ const formKey = async (ref: string, why: string) => {
220
+ if (looksLikeKey(ref)) return normaliseUuid(ref)
221
+ const seeded = libraryByPath.get(trimPath(ref))
222
+ if (seeded && !seeded.folder) {
223
+ const type =
224
+ typeof seeded.data.type === 'string'
225
+ ? await typeOf(documentTypes, seeded.data.type)
226
+ : undefined
227
+ return type?.formKey ? keyOf.get(seeded) : undefined
228
+ }
229
+ const form = forms.find((f) => f.alias.toLowerCase() === trimPath(ref))
230
+ if (form) return form.key ?? form.alias
231
+ const key = await siteNode(ref, ObjectTypes.Element, why)
232
+ if (!key) return undefined
233
+ const rows = await db.q
234
+ .selectFrom('node as n')
235
+ .innerJoin('content as c', 'c.node_id', 'n.id')
236
+ .innerJoin('content_type as ct', 'ct.node_id', 'c.content_type_id')
237
+ .select('ct.form_key')
238
+ .where('n.unique_id', '=', key)
239
+ .execute()
240
+ return rows[0]?.form_key ? key : undefined
241
+ }
197
242
 
198
243
  // ---------------------------------------------------------------- values
199
244
  const { convert } = valueWriter(lookup, {
200
245
  content: contentKey,
201
246
  media: mediaRef,
202
247
  library: libraryKey,
248
+ form: formKey,
203
249
  linkedMedia: async (path) => {
204
250
  const media = mediaByPath.get(path.toLowerCase())
205
251
  return media ? keyOf.get(media) : undefined
@@ -268,6 +314,29 @@ export async function compileSeed(db: Db, config: CromboloConfig): Promise<SeedB
268
314
  for (const item of tree.items) {
269
315
  const key = keyOf.get(item) as string
270
316
  let type = typeOfItem.get(item)
317
+ if (item.kind === 'library' && item.folder) {
318
+ // A Library folder: a name and a place, as story 283 carries it.
319
+ bundleNodes.push({
320
+ key,
321
+ kind: 'element-folder',
322
+ contentType: { ...ELEMENT_FOLDER_TYPE },
323
+ parent: item.parent
324
+ ? (keyOf.get(libraryByPath.get(item.parent.toLowerCase()) as SeedItem) ?? null)
325
+ : null,
326
+ sortOrder: 0,
327
+ template: null,
328
+ variants: [
329
+ {
330
+ culture: null,
331
+ segment: null,
332
+ name: nameOf(item)[0]?.name ?? item.path,
333
+ published: false,
334
+ },
335
+ ],
336
+ values: [],
337
+ })
338
+ continue
339
+ }
271
340
  if (item.kind !== 'media') {
272
341
  if (typeof item.data.type !== 'string') {
273
342
  find(item, [], 'no-type', 'an item names its content type: type = "<alias>"')
@@ -420,14 +489,16 @@ export async function compileSeed(db: Db, config: CromboloConfig): Promise<SeedB
420
489
  if (template) usedComponents.add(template)
421
490
  // Media has no published state: it is live as soon as it lands.
422
491
  const published = item.kind !== 'media' && item.data.published !== false
423
- const parent =
424
- item.kind === 'library' || !item.parent
425
- ? null
426
- : (keyOf.get(
427
- (item.kind === 'media' ? mediaByPath : contentByPath).get(
428
- item.parent.toLowerCase(),
429
- ) as SeedItem,
430
- ) ?? null)
492
+ const parent = !item.parent
493
+ ? null
494
+ : (keyOf.get(
495
+ (item.kind === 'media'
496
+ ? mediaByPath
497
+ : item.kind === 'library'
498
+ ? libraryByPath
499
+ : contentByPath
500
+ ).get(item.parent.toLowerCase()) as SeedItem,
501
+ ) ?? null)
431
502
  const names = nameOf(item)
432
503
  // A renamed file is a new key: say so where a page of that name is already here.
433
504
  if (item.kind === 'content') {
@@ -22,7 +22,14 @@ import {
22
22
  } from '@crombolo/data'
23
23
  import type { MediaFileStore } from '../media-files.ts'
24
24
  import { seedKey } from './keys.ts'
25
- import { CONTENT_FILES_DIR, KIND_DIRS, kindDir, type SeedKind } from './read.ts'
25
+ import {
26
+ CONTENT_FILES_DIR,
27
+ KIND_DIRS,
28
+ kindDir,
29
+ LIBRARY_FOLDER_FILE,
30
+ nameFromSegment,
31
+ type SeedKind,
32
+ } from './read.ts'
26
33
  import { schemaLookup, shorthandReader } from './values.ts'
27
34
 
28
35
  /** A URL segment from a name: `About us` → `about-us`. */
@@ -150,10 +157,31 @@ export async function exportSeed(
150
157
  }
151
158
  for (const [index, root] of options.pages.entries()) await walkPages(root, null, index)
152
159
 
160
+ /** Library folders, which are directories rather than files (story 242). */
161
+ const libraryFolders = new Set<string>()
153
162
  if (options.library) {
154
- const roots = await nodes.children(-1, ObjectTypes.Element, 0, Number.MAX_SAFE_INTEGER)
155
- for (const [index, element] of roots.items.entries())
156
- place('library', element, null, index, segmentOf(element.text ?? element.key))
163
+ const walkLibrary = async (parentId: number, parent: string | null) => {
164
+ const folders = await nodes.children(
165
+ parentId,
166
+ ObjectTypes.ElementContainer,
167
+ 0,
168
+ Number.MAX_SAFE_INTEGER,
169
+ )
170
+ for (const [index, folder] of folders.items.entries()) {
171
+ libraryFolders.add(folder.key)
172
+ const path = place('library', folder, parent, index, segmentOf(folder.text ?? folder.key))
173
+ await walkLibrary(folder.id, path)
174
+ }
175
+ const elements = await nodes.children(
176
+ parentId,
177
+ ObjectTypes.Element,
178
+ 0,
179
+ Number.MAX_SAFE_INTEGER,
180
+ )
181
+ for (const [index, element] of elements.items.entries())
182
+ place('library', element, parent, index, segmentOf(element.text ?? element.key))
183
+ }
184
+ await walkLibrary(-1, null)
157
185
  }
158
186
 
159
187
  const mediaFile = new Map<string, string>()
@@ -237,8 +265,19 @@ export async function exportSeed(
237
265
  }
238
266
 
239
267
  for (const { kind, node, path, order } of entries) {
240
- const doc = await repos[kind].byKey(node.key)
241
268
  const derived = seedKey(`${kind}/${path}`)
269
+ if (kind === 'library' && libraryFolders.has(node.key)) {
270
+ // A folder is its directory; `.folder.toml` only for what the directory can't say.
271
+ mkdirSync(under(`library/${path}`), { recursive: true })
272
+ const own: string[] = []
273
+ if (normaliseUuid(node.key) !== derived) own.push(`key = ${JSON.stringify(node.key)}`)
274
+ const segment = path.split('/').at(-1) as string
275
+ if ((node.text ?? '') !== nameFromSegment(segment))
276
+ own.push(`name = ${JSON.stringify(node.text ?? '')}`)
277
+ if (own.length > 0) write(`library/${path}/${LIBRARY_FOLDER_FILE}`, `${own.join('\n')}\n`)
278
+ continue
279
+ }
280
+ const doc = await repos[kind].byKey(node.key)
242
281
  const lines: string[] = []
243
282
  if (kind === 'media') {
244
283
  const src = mediaFile.get(node.key)
package/src/seed/read.ts CHANGED
@@ -40,7 +40,7 @@ export interface SeedItem {
40
40
  data: Record<string, unknown>
41
41
  /** A media file's bytes. */
42
42
  bytes?: Uint8Array
43
- /** A media folder: a directory under `content/media/`. */
43
+ /** A folder: a directory under `content/media/` or `content/library/`. */
44
44
  folder?: boolean
45
45
  }
46
46
 
@@ -58,6 +58,9 @@ export interface SeedTree {
58
58
 
59
59
  const SKIPPED = (name: string) => name.startsWith('.')
60
60
 
61
+ /** What keeps a Library folder's key, when it isn't the one its path gives. */
62
+ export const LIBRARY_FOLDER_FILE = '.folder.toml'
63
+
61
64
  /**
62
65
  * The line a TOML syntax error is on: the first prefix of the file that does
63
66
  * not parse. The parser's own position is not always the file's.
@@ -118,12 +121,20 @@ export function readSeed(siteDir: string): SeedTree {
118
121
  const path = join(dir, name)
119
122
  if (statSync(path).isDirectory()) {
120
123
  if (kind === 'library') {
121
- findings.push({
122
- file: shown(path),
123
- line: 1,
124
- code: 'library-folder',
125
- message: 'Library elements sit at the top of content/library: folders are not read yet',
124
+ // A Library folder (story 242). `.folder.toml` in it keeps a key of its own.
125
+ const itemPath = parent ? `${parent}/${name}` : name
126
+ const own = join(path, LIBRARY_FOLDER_FILE)
127
+ const parsed = existsSync(own) ? parse(own) : undefined
128
+ items.push({
129
+ kind,
130
+ path: itemPath,
131
+ parent,
132
+ file: parsed ? shown(own) : null,
133
+ text: parsed?.text ?? '',
134
+ data: parsed?.data ?? {},
135
+ folder: true,
126
136
  })
137
+ content(kind, path, itemPath)
127
138
  continue
128
139
  }
129
140
  if (!names.includes(`${name}.toml`))
@@ -216,3 +227,9 @@ export function readSeedDictionary(siteDir: string) {
216
227
  /** Whether a site has content files at all, where they are or where they were. */
217
228
  export const hasSeed = (siteDir: string) =>
218
229
  existsSync(join(siteDir, CONTENT_FILES_DIR)) || existsSync(join(siteDir, 'seed'))
230
+
231
+ /** A word for a file name: `about-us` → `About us`. */
232
+ export const nameFromSegment = (segment: string) => {
233
+ const words = segment.replace(/[-_]+/g, ' ').trim()
234
+ return words.charAt(0).toUpperCase() + words.slice(1)
235
+ }
@@ -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
 
@@ -82,6 +82,8 @@ export interface ValueRefs {
82
82
  content(ref: string, why: string): Promise<string | undefined>
83
83
  media(ref: string, why: string): Promise<{ key: string; typeAlias: string } | undefined>
84
84
  library(ref: string, why: string): Promise<string | undefined>
85
+ /** A form picker's value: a Library form's path, or a form's alias or key (story 242). */
86
+ form(ref: string, why: string): Promise<string | undefined>
85
87
  /** A link's path as media, before it is tried as a page. */
86
88
  linkedMedia(ref: string): Promise<string | undefined>
87
89
  }
@@ -246,17 +248,14 @@ export function valueWriter(lookup: SchemaLookup, refs: ValueRefs) {
246
248
  : typeof raw === 'string'
247
249
  ? raw
248
250
  : 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')
251
+ const at = text === undefined ? undefined : dateFromText(text)
252
+ if (text === undefined || !at) return fail('a date is a TOML date or an ISO 8601 string')
252
253
  // A date picker stores Umbraco's wall clock, as a save does, so a seed
253
254
  // exported and applied again is unchanged; one with a zone keeps ISO.
254
255
  return {
255
256
  ok: true,
256
257
  value:
257
- editor === 'Umbraco.DateTime'
258
- ? new Date(at).toISOString().slice(0, 19).replace('T', ' ')
259
- : text,
258
+ editor === 'Umbraco.DateTime' ? at.toISOString().slice(0, 19).replace('T', ' ') : text,
260
259
  }
261
260
  }
262
261
  case 'Umbraco.Tags':
@@ -299,6 +298,16 @@ export function valueWriter(lookup: SchemaLookup, refs: ValueRefs) {
299
298
  }
300
299
  return { ok: true, value: keys }
301
300
  }
301
+ case 'Crombolo.FormPicker': {
302
+ if (typeof raw !== 'string')
303
+ return fail("a form picker takes a Library form's path, or a form's alias")
304
+ const key = await refs.form(raw, why)
305
+ if (!key)
306
+ return fail(
307
+ `"${raw}" is not a Library form or a form, in the content files or on the site`,
308
+ )
309
+ return { ok: true, value: key }
310
+ }
302
311
  case 'Umbraco.MultiUrlPicker': {
303
312
  const links: unknown[] = []
304
313
  for (const entry of list(raw)) {
@@ -407,6 +416,10 @@ export function shorthandReader(
407
416
  if (paths.length === 0 || paths.some((p) => p === undefined)) return value
408
417
  return paths.length === 1 ? paths[0] : paths
409
418
  }
419
+ case 'Crombolo.FormPicker': {
420
+ if (typeof value !== 'string') return value
421
+ return (await where(value, 'library')) ?? value
422
+ }
410
423
  case 'Umbraco.MultiUrlPicker': {
411
424
  if (!Array.isArray(value)) return value
412
425
  const out: unknown[] = []
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,