@nuasite/cms-core 0.54.0 → 0.56.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -681,6 +681,20 @@ function applyParsedFieldLayout(field: FieldDefinition, pf: ParsedField): void {
681
681
  if (layout.width !== undefined) field.width = layout.width
682
682
  if (layout.order !== undefined) field.order = layout.order
683
683
  if (layout.sidebar) field.position = 'sidebar'
684
+ if (layout.derivedFrom) {
685
+ // A declared derivation beats `detectDerivedHrefFields`: that pass runs after this one
686
+ // and skips any field already carrying `derivedFrom`, so the config wins by construction.
687
+ field.derivedFrom = layout.derivedFrom
688
+ // A derivation read out of the config is a statement, not the guess `detectDerivedHrefFields`
689
+ // makes from three sampled values — and only a statement is recomputed on write. Mark it so
690
+ // consumers reading the wire definition can tell the two apart; the guess never sets this.
691
+ field.derivedDeclared = true
692
+ if (layout.derivedTransform) field.derivedTransform = layout.derivedTransform
693
+ // The value is computed on every write, so hand-editing it makes no sense — hide it
694
+ // unless the author explicitly asked for the opposite.
695
+ field.hidden = layout.hidden ?? true
696
+ return
697
+ }
684
698
  if (layout.hidden) field.hidden = true
685
699
  }
686
700
 
@@ -3,8 +3,10 @@ import type * as t from '@babel/types'
3
3
  import {
4
4
  type CollectionLayout,
5
5
  type CollectionLayoutSection,
6
+ type DerivedTransform,
6
7
  type FieldHints,
7
8
  type FieldType,
9
+ isDerivedTransform,
8
10
  isFieldType,
9
11
  type PathnameSegment,
10
12
  type PathnameSpec,
@@ -43,6 +45,10 @@ export interface ParsedFieldLayout {
43
45
  width?: 'full' | 'half'
44
46
  order?: number
45
47
  hidden?: boolean
48
+ /** Name of the field this one is computed from (`n.text({ derivedFrom: 'category' })`). */
49
+ derivedFrom?: string
50
+ /** Named transform for the derived value; absent means `slugifyHref`. */
51
+ derivedTransform?: DerivedTransform
46
52
  }
47
53
 
48
54
  export interface ParsedCollection {
@@ -398,9 +404,15 @@ export function parseConfigSource(source: string, _sourcePath?: string): ParsedC
398
404
  continue
399
405
  }
400
406
 
407
+ const fields = parseSchemaFields(schemaObject, bindings)
408
+ // Once per parse of the config file, not once per entry: the parse result is cached by
409
+ // mtime, so a bad declaration is reported when it is read, not on every scan that
410
+ // consults it.
411
+ checkDerivedFromDeclarations(collectionName, fields)
412
+
401
413
  result.set(collectionName, {
402
414
  name: collectionName,
403
- fields: parseSchemaFields(schemaObject, bindings),
415
+ fields,
404
416
  ...(hasSkippedMembers(schemaObject) ? { partialFields: true as const } : {}),
405
417
  loaderPattern,
406
418
  loaderBase,
@@ -998,7 +1010,99 @@ function parseFieldLayoutFromObject(obj: t.ObjectExpression): ParsedFieldLayout
998
1010
  case 'hidden':
999
1011
  if (value.type === 'BooleanLiteral') layout.hidden = value.value
1000
1012
  break
1013
+ case 'derivedFrom':
1014
+ parseDerivedFromValue(value, layout)
1015
+ break
1001
1016
  }
1002
1017
  }
1003
1018
  return Object.keys(layout).length > 0 ? layout : undefined
1004
1019
  }
1020
+
1021
+ /**
1022
+ * Read a `derivedFrom` option in either authoring form:
1023
+ *
1024
+ * ```ts
1025
+ * n.text({ derivedFrom: 'category' }) // → slugifyHref
1026
+ * n.text({ derivedFrom: { field: 'category', transform: 'slug' } })
1027
+ * ```
1028
+ *
1029
+ * `field` is mandatory in the object form — without a source there is nothing to derive
1030
+ * from, so the whole declaration is dropped. An unknown `transform` name is ignored rather
1031
+ * than rejected: the field keeps deriving, on the default transform, instead of silently
1032
+ * dropping out of the recompute because of a typo.
1033
+ */
1034
+ function parseDerivedFromValue(value: t.ObjectProperty['value'], layout: ParsedFieldLayout): void {
1035
+ if (value.type === 'StringLiteral') {
1036
+ if (value.value) layout.derivedFrom = value.value
1037
+ return
1038
+ }
1039
+ if (value.type !== 'ObjectExpression') return
1040
+
1041
+ let field: string | undefined
1042
+ let transform: DerivedTransform | undefined
1043
+ for (const prop of value.properties) {
1044
+ if (prop.type !== 'ObjectProperty') continue
1045
+ const key = propertyKeyName(prop.key)
1046
+ if (prop.value.type !== 'StringLiteral') continue
1047
+ if (key === 'field') field = prop.value.value
1048
+ else if (key === 'transform' && isDerivedTransform(prop.value.value)) transform = prop.value.value
1049
+ }
1050
+
1051
+ if (!field) return
1052
+ layout.derivedFrom = field
1053
+ if (transform) layout.derivedTransform = transform
1054
+ }
1055
+
1056
+ /**
1057
+ * Report the `derivedFrom` declarations the recompute cannot honour, and drop the ones that
1058
+ * would otherwise take effect halfway.
1059
+ *
1060
+ * Two kinds, both silent before:
1061
+ *
1062
+ * - **Unknown source.** `derivedFrom: 'catgory'` parses perfectly well, so the field is
1063
+ * hidden (a declaration implies `hidden`) and then never computed, because no such key ever
1064
+ * appears in the frontmatter. The result is a field that has quietly left the CMS. Warn
1065
+ * rather than throw: a typo in one field must not take the whole config down, and the site
1066
+ * still builds.
1067
+ * - **Nested field.** Deriving is a top-level operation — `applyDerivedFields` reads the
1068
+ * entry's top-level frontmatter, which is the only place a source name is unambiguous.
1069
+ * A `derivedFrom` inside `n.object({ … })` used to hide the sub-field anyway and then never
1070
+ * compute it, so the key disappeared from the file on the next write. Rather than invent
1071
+ * "source relative to the parent object" semantics, the declaration is dropped here: the
1072
+ * nested field stays visible and hand-editable, and the warning says why.
1073
+ *
1074
+ * Emitted over `console.warn` for the same reason as `warnOnPathnameCollisions` in
1075
+ * `collection-scanner.ts`: `cms-core` cannot reach the ErrorCollector in `@nuasite/cms` and
1076
+ * must not grow a dependency on it.
1077
+ */
1078
+ function checkDerivedFromDeclarations(collectionName: string, fields: ParsedField[]): void {
1079
+ const siblingNames = new Set(fields.map(f => f.name))
1080
+ for (const field of fields) {
1081
+ const source = field.layout?.derivedFrom
1082
+ if (source !== undefined && !siblingNames.has(source)) {
1083
+ console.warn(
1084
+ `[cms] collection "${collectionName}": field "${field.name}" derives from "${source}", which is not a field of this collection`
1085
+ + ` — the field is hidden and nothing is ever computed for it`,
1086
+ )
1087
+ }
1088
+ dropNestedDerivedFrom(collectionName, field.name, field.fields)
1089
+ }
1090
+ }
1091
+
1092
+ /** Strip `derivedFrom` from every field below the top level, warning once per declaration. */
1093
+ function dropNestedDerivedFrom(collectionName: string, path: string, fields: ParsedField[] | undefined): void {
1094
+ if (!fields) return
1095
+ for (const field of fields) {
1096
+ const fieldPath = `${path}.${field.name}`
1097
+ const layout = field.layout
1098
+ if (layout?.derivedFrom !== undefined) {
1099
+ console.warn(
1100
+ `[cms] collection "${collectionName}": field "${fieldPath}" declares \`derivedFrom\` on a nested field, which is not supported`
1101
+ + ` — only top-level fields derive, so the declaration is ignored and the field stays editable`,
1102
+ )
1103
+ delete layout.derivedFrom
1104
+ delete layout.derivedTransform
1105
+ }
1106
+ dropNestedDerivedFrom(collectionName, fieldPath, field.fields)
1107
+ }
1108
+ }
@@ -14,15 +14,17 @@
14
14
  * and misses the ones that can — which is why none of it may be reimplemented anywhere.
15
15
  */
16
16
 
17
- import { defaultValueForNewEntry, type WriteModelField } from '@nuasite/cms-types'
17
+ import { blankFieldValue, type WriteModelField } from '@nuasite/cms-types'
18
18
 
19
19
  export {
20
+ blankFieldValue,
20
21
  blankRequiredFields,
21
- defaultValueForNewEntry,
22
22
  isBlankFieldValue,
23
23
  newRepeaterItem,
24
24
  type RepeaterItemField,
25
25
  type RequiredGuardField,
26
+ seedValueForRequiredField,
27
+ withoutBlankArrayItems,
26
28
  type WriteModelField,
27
29
  } from '@nuasite/cms-types'
28
30
 
@@ -32,12 +34,16 @@ export {
32
34
  * `title` is excluded because the create form carries it in its own header field, and
33
35
  * hidden fields are excluded because the form cannot fill them in. Neither is missing from
34
36
  * the finished entry — see `applyCreateRouteFields`, which is what puts `title` back.
37
+ *
38
+ * The values come from `blankFieldValue`, the same function `draftForCreate` in `cms-client`
39
+ * asks. The two used to seed differently, so this — and the check built on it — described a
40
+ * write only one of the two editors ever made.
35
41
  */
36
- export function newEntryFrontmatter(fields: WriteModelField[], today?: () => Date): Record<string, unknown> {
42
+ export function newEntryFrontmatter(fields: WriteModelField[]): Record<string, unknown> {
37
43
  const frontmatter: Record<string, unknown> = {}
38
44
  for (const field of fields) {
39
45
  if (field.name === 'title' || field.hidden) continue
40
- frontmatter[field.name] = defaultValueForNewEntry(field, today)
46
+ frontmatter[field.name] = blankFieldValue(field)
41
47
  }
42
48
  return frontmatter
43
49
  }
@@ -2,11 +2,11 @@ import type { CollectionEntryInfo, ComponentDefinition, MutationResult } from '@
2
2
  import yaml from 'yaml'
3
3
  import { assetBaseDir, resolveAssetCandidates } from '../asset-paths'
4
4
  import { scanCollections } from '../collection-scanner'
5
- import { type ParseCache, parseContentConfig } from '../content-config-ast'
6
- import { blankRequiredFields, newRepeaterItem, type RepeaterItemField } from '../editor-write-model'
5
+ import { type ParseCache, parseContentConfig, type ParsedField } from '../content-config-ast'
6
+ import { blankRequiredFields, isBlankFieldValue, newRepeaterItem, type RepeaterItemField, withoutBlankArrayItems } from '../editor-write-model'
7
7
  import type { CmsFileSystem } from '../fs/types'
8
8
  import { mimeFromExt } from '../media/local'
9
- import { isPlainRecord, relativeImportPath, slugify } from '../shared'
9
+ import { computeDerivedFieldUpdates, isPlainRecord, relativeImportPath, slugify } from '../shared'
10
10
 
11
11
  /** Frontmatter file extensions that hold markdown content (vs. pure data files). */
12
12
  const MARKDOWN_EXTENSIONS = ['md', 'mdx'] as const
@@ -314,6 +314,91 @@ function isIndexStyleGlobPattern(pattern: string): boolean {
314
314
  return pattern.includes('index.{') || pattern.includes('*/index') || pattern.includes('**/index')
315
315
  }
316
316
 
317
+ // ============================================================================
318
+ // Derived-field recompute
319
+ // ============================================================================
320
+
321
+ /**
322
+ * Recompute the collection's **declared** derived fields from `frontmatter`, returning the
323
+ * frontmatter that should actually be written.
324
+ *
325
+ * This lives here — under every write path — on purpose. The recompute used to exist only in
326
+ * the preview editor's form state (`computeDerivedUpdates` in `@nuasite/cms`), so anything
327
+ * writing through the sidecar, the dash or an agent left derived fields holding whatever the
328
+ * previous value was. The editor keeps its copy for instant in-form feedback; this one is
329
+ * authoritative.
330
+ *
331
+ * Rules, all shared with `missingRequiredFields` and enforced by running *before* it:
332
+ *
333
+ * - The input is the **merged** frontmatter (what lands on disk), never the incoming patch —
334
+ * so an update touching only the source field still refreshes the derived one.
335
+ * - A missing, non-string or blank source leaves the derived value untouched; see
336
+ * `computeDerivedFieldUpdates`.
337
+ * - Only `derivedFrom` **declared in the content config** is recomputed. The scanner's
338
+ * `detectDerivedHrefFields` guess deliberately stays out of the write path: it is a
339
+ * heuristic over at most three sampled values, and letting it overwrite files would turn a
340
+ * coincidence into data loss. Declaring the field opts into the recompute.
341
+ * - Only **top-level** fields derive. A `derivedFrom` on a nested field is dropped at parse
342
+ * time (with a warning) — see `content-config-ast.ts` — so nothing here has to guess what
343
+ * a source name would mean inside an object.
344
+ * - `patch` is the incoming update, and its absence means "this is a create". On an update
345
+ * only the fields `shouldRecomputeOnUpdate` accepts are touched; on a create everything
346
+ * declared is computed, because the file does not exist yet and has no authored value to
347
+ * preserve.
348
+ *
349
+ * Reads the config the same way `missingRequiredFields` does (`parseContentConfig` +
350
+ * `deps.parseCache`), so no new dependency enters `EntryOpsDeps`.
351
+ */
352
+ async function applyDerivedFields(
353
+ deps: EntryOpsDeps,
354
+ collection: string,
355
+ frontmatter: Record<string, unknown>,
356
+ patch?: Record<string, unknown>,
357
+ ): Promise<Record<string, unknown>> {
358
+ const parsed = await parseContentConfig(deps.fs, deps.parseCache)
359
+ const parsedCollection = parsed.get(collection)
360
+ if (!parsedCollection) return frontmatter
361
+
362
+ const updates = computeDerivedFieldUpdates(
363
+ parsedCollection.fields
364
+ .filter(field => patch === undefined || shouldRecomputeOnUpdate(field, frontmatter, patch))
365
+ .map(field => ({
366
+ name: field.name,
367
+ derivedFrom: field.layout?.derivedFrom,
368
+ derivedTransform: field.layout?.derivedTransform,
369
+ })),
370
+ frontmatter,
371
+ )
372
+ if (Object.keys(updates).length === 0) return frontmatter
373
+ return { ...frontmatter, ...updates }
374
+ }
375
+
376
+ /**
377
+ * Whether an **update** should recompute this derived field, given the patch it carries and
378
+ * the merged frontmatter that would land on disk.
379
+ *
380
+ * Two cases, and nothing else:
381
+ *
382
+ * 1. The patch carries the source field. The derivation is what the source means, so a write
383
+ * that moves the source moves the derived value with it — even when the patch never names
384
+ * it. (`updateEntry({ frontmatter: { category } })` refreshing `categoryHref` is the whole
385
+ * point of the feature.)
386
+ * 2. The entry holds no derived value yet. Filling a hole is not an edit anybody has to
387
+ * notice, and it is what a create would have written.
388
+ *
389
+ * Everything else is left alone. An update that touches only the body, or only an unrelated
390
+ * field, must not rewrite a value the author put there by hand: `categoryHref:
391
+ * /kategorie/lide` overridden into `/lide` is a diff nobody asked for, produced by a save
392
+ * that had nothing to do with it. `createEntry` skips this check entirely — a new file has no
393
+ * hand-authored value to protect.
394
+ */
395
+ function shouldRecomputeOnUpdate(field: ParsedField, frontmatter: Record<string, unknown>, patch: Record<string, unknown>): boolean {
396
+ const source = field.layout?.derivedFrom
397
+ if (source === undefined) return false
398
+ if (Object.hasOwn(patch, source)) return true
399
+ return isBlankFieldValue(frontmatter[field.name])
400
+ }
401
+
317
402
  // ============================================================================
318
403
  // Required-field validation
319
404
  // ============================================================================
@@ -337,6 +422,9 @@ function isIndexStyleGlobPattern(pattern: string): boolean {
337
422
  *
338
423
  * A collection absent from `content.config.ts` therefore yields `[]` — nobody declared
339
424
  * anything required there, so there is nothing to enforce and the write goes through.
425
+ *
426
+ * The rule itself lives in `blankRequiredFields` (`@nuasite/cms-types`), shared with every
427
+ * collections UI — including which fields are exempt, and why.
340
428
  */
341
429
  async function missingRequiredFields(deps: EntryOpsDeps, collection: string, frontmatter: Record<string, unknown>): Promise<string[]> {
342
430
  const parsed = await parseContentConfig(deps.fs, deps.parseCache)
@@ -397,7 +485,10 @@ export async function getEntry(deps: EntryOpsDeps, collection: string, slug: str
397
485
  }
398
486
 
399
487
  export async function createEntry(deps: EntryOpsDeps, input: CreateEntryInput): Promise<MutationResult> {
400
- const { collection, slug, frontmatter, body = '' } = input
488
+ const { collection, slug, body = '' } = input
489
+ // Before anything reads it: a list may not carry a blank item. See `withoutBlankArrayItems`
490
+ // — an unfilled row appended by "+ Add" arrives as `null` and fails the whole site build.
491
+ const frontmatter = withoutBlankArrayItems(input.frontmatter)
401
492
 
402
493
  const normalizedSlug = slugify(slug)
403
494
  if (!normalizedSlug) {
@@ -409,10 +500,15 @@ export async function createEntry(deps: EntryOpsDeps, input: CreateEntryInput):
409
500
  if (!allowedExtensions.includes(ext)) {
410
501
  return { success: false, error: `Invalid file extension "${ext}". Allowed: ${allowedExtensions.join(', ')}` }
411
502
  }
503
+ // Derived fields first: a required-but-visible derived field must be judged on the value
504
+ // it is about to be given, not on the hole the caller left. `resolved` is what both
505
+ // branches below serialize, so the markdown and the data file agree by construction.
506
+ const resolved = await applyDerivedFields(deps, collection, frontmatter)
507
+
412
508
  // Hard invariant, ahead of every path that could touch the disk — the markdown and
413
- // the data branch below both write exactly `{ ...frontmatter }`, so one check covers
509
+ // the data branch below both write exactly `{ ...resolved }`, so one check covers
414
510
  // `.md`/`.mdx` frontmatter and `.json`/`.yaml`/`.yml` data files alike.
415
- const missing = await missingRequiredFields(deps, collection, frontmatter)
511
+ const missing = await missingRequiredFields(deps, collection, resolved)
416
512
  if (missing.length > 0) {
417
513
  return { success: false, error: missingRequiredMessage(missing) }
418
514
  }
@@ -427,10 +523,10 @@ export async function createEntry(deps: EntryOpsDeps, input: CreateEntryInput):
427
523
  let fileContent: string
428
524
  if (isData) {
429
525
  fileContent = ext === 'json'
430
- ? JSON.stringify({ ...frontmatter }, null, 2) + '\n'
431
- : yaml.stringify({ ...frontmatter })
526
+ ? JSON.stringify({ ...resolved }, null, 2) + '\n'
527
+ : yaml.stringify({ ...resolved })
432
528
  } else {
433
- fileContent = serializeFrontmatter({ ...frontmatter }, body)
529
+ fileContent = serializeFrontmatter({ ...resolved }, body)
434
530
  }
435
531
 
436
532
  if (await deps.fs.exists(sourcePath)) {
@@ -451,23 +547,33 @@ export async function updateEntry(deps: EntryOpsDeps, input: UpdateEntryInput):
451
547
  return { success: false, error: `Entry not found: ${input.collection}/${input.slug}` }
452
548
  }
453
549
 
550
+ // The incoming patch only — never the merged record. Cleaning what is already on disk would
551
+ // rewrite lists this edit never touched, and a save must change what the editor changed.
552
+ const patch = input.frontmatter === undefined ? undefined : withoutBlankArrayItems(input.frontmatter)
553
+
454
554
  try {
455
555
  if (isDataFile(sourcePath)) {
456
556
  const raw = await deps.fs.readFile(sourcePath)
457
557
  const existing = sourcePath.endsWith('.json') ? JSON.parse(raw) : yaml.parse(raw)
458
- const merged: Record<string, unknown> = { ...(existing ?? {}), ...input.frontmatter }
558
+ const merged: Record<string, unknown> = { ...(existing ?? {}), ...patch }
559
+
560
+ // Recompute from the merged result, so a patch that carries only the source field
561
+ // still refreshes the derived one. Ahead of the required check for the same reason
562
+ // as in `createEntry`. The patch goes along so a write that never touches a source
563
+ // leaves the value the author put there alone — see `shouldRecomputeOnUpdate`.
564
+ const resolved = await applyDerivedFields(deps, input.collection, merged, patch ?? {})
459
565
 
460
566
  // Validate the merged result, not the incoming patch: a patch that omits a
461
567
  // required field is fine when the file already carries it, and a patch that
462
568
  // blanks one must be rejected even though the field itself is present.
463
- const missing = await missingRequiredFields(deps, input.collection, merged)
569
+ const missing = await missingRequiredFields(deps, input.collection, resolved)
464
570
  if (missing.length > 0) {
465
571
  return { success: false, error: missingRequiredMessage(missing) }
466
572
  }
467
573
 
468
574
  const output = sourcePath.endsWith('.json')
469
- ? JSON.stringify(merged, null, 2) + '\n'
470
- : yaml.stringify(merged)
575
+ ? JSON.stringify(resolved, null, 2) + '\n'
576
+ : yaml.stringify(resolved)
471
577
  await deps.fs.writeFile(sourcePath, output)
472
578
  } else {
473
579
  const raw = await deps.fs.readFile(sourcePath)
@@ -475,12 +581,15 @@ export async function updateEntry(deps: EntryOpsDeps, input: UpdateEntryInput):
475
581
 
476
582
  const mergedFrontmatter: Record<string, unknown> = {
477
583
  ...existing.frontmatter,
478
- ...input.frontmatter,
584
+ ...patch,
479
585
  }
480
586
 
481
- // Same rule as the data branch: the merged frontmatter is what lands on disk,
482
- // so that is what gets validated.
483
- const missing = await missingRequiredFields(deps, input.collection, mergedFrontmatter)
587
+ // Same rule as the data branch: recompute the derived fields off the merged
588
+ // frontmatter — bounded by the patch, so a body-only save rewrites nothing — then
589
+ // validate what is actually going to disk.
590
+ const resolvedFrontmatter = await applyDerivedFields(deps, input.collection, mergedFrontmatter, patch ?? {})
591
+
592
+ const missing = await missingRequiredFields(deps, input.collection, resolvedFrontmatter)
484
593
  if (missing.length > 0) {
485
594
  return { success: false, error: missingRequiredMessage(missing) }
486
595
  }
@@ -494,7 +603,7 @@ export async function updateEntry(deps: EntryOpsDeps, input: UpdateEntryInput):
494
603
  finalContent = ensureMdxImports(finalContent, sourcePath, componentDefinitions)
495
604
  }
496
605
 
497
- await deps.fs.writeFile(sourcePath, serializeFrontmatter(mergedFrontmatter, finalContent))
606
+ await deps.fs.writeFile(sourcePath, serializeFrontmatter(resolvedFrontmatter, finalContent))
498
607
  }
499
608
 
500
609
  return { success: true, sourcePath }
@@ -651,6 +760,13 @@ export async function addArrayItem(deps: EntryOpsDeps, input: AddArrayItemInput)
651
760
  return { success: false, error: `Field "${input.field}" is not an array` }
652
761
  }
653
762
 
763
+ // A field may be absent; an item in a list may not, so a blank one is frontmatter the next
764
+ // build refuses. Refused rather than dropped: a client that asked for an append should not
765
+ // be told it happened when nothing was written.
766
+ if (isBlankFieldValue(input.value)) {
767
+ return { success: false, error: `Refusing to append an empty item to "${input.field}" — fill it in, or leave the list alone` }
768
+ }
769
+
654
770
  const index = input.index ?? array.length
655
771
  const clamped = Math.max(0, Math.min(index, array.length))
656
772
  array.splice(clamped, 0, seedItem(input.value, await repeaterItemFields(deps, input.collection, input.field)))
package/src/index.ts CHANGED
@@ -28,15 +28,17 @@ export { createCmsCore } from './core'
28
28
  export type { CmsCore, CmsCoreOptions } from './core'
29
29
  export {
30
30
  applyCreateRouteFields,
31
+ blankFieldValue,
31
32
  blankRequiredFields,
32
33
  type CollectionKind,
33
- defaultValueForNewEntry,
34
34
  isBlankFieldValue,
35
35
  newEntryFrontmatter,
36
36
  newRepeaterItem,
37
37
  omitEmptyOnCreate,
38
38
  type RepeaterItemField,
39
39
  type RequiredGuardField,
40
+ seedValueForRequiredField,
41
+ withoutBlankArrayItems,
40
42
  type WriteModelField,
41
43
  } from './editor-write-model'
42
44
  export { globToRegExp } from './fs/glob'
@@ -71,4 +73,14 @@ export {
71
73
  export { parseProjectCmsConfig, parseProjectCmsConfigSource } from './project-config-ast'
72
74
  export { describeIssue, type LiveIssue, type LiveParseResult, type LiveSchema, type LiveSchemas, schemaFor } from './schema-port'
73
75
  export { acceptsMissing, firstAcceptedEntry, governsPath, pointAt, type ProbePoint, rejectsValueAt } from './schema-probe'
74
- export { computePathnameFromSpec, escapeHtml, relativeImportPath, resolvePathnameFromSpec, slugify, slugifyHref } from './shared'
76
+ export {
77
+ applyDerivedTransform,
78
+ computeDerivedFieldUpdates,
79
+ computePathnameFromSpec,
80
+ type DerivedFieldSpec,
81
+ escapeHtml,
82
+ relativeImportPath,
83
+ resolvePathnameFromSpec,
84
+ slugify,
85
+ slugifyHref,
86
+ } from './shared'
package/src/shared.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { CollectionDefinition, PathnameSpec } from '@nuasite/cms-types'
1
+ import { type CollectionDefinition, type DerivedTransform, type PathnameSpec, slugify } from '@nuasite/cms-types'
2
2
 
3
3
  /**
4
4
  * Coerce a frontmatter value into a URL path segment. Strings pass through;
@@ -89,7 +89,65 @@ export function isPlainRecord(value: unknown): value is Record<string, unknown>
89
89
  * Re-exported from `@nuasite/cms-types` so the server and every client slugify identically —
90
90
  * a host deriving a slug locally is predicting this write. See `cms-types/src/slug.ts`.
91
91
  */
92
- export { slugify } from '@nuasite/cms-types'
92
+ export { slugify }
93
+
94
+ /** A field's derived-value declaration, the subset of `FieldDefinition` the recompute reads. */
95
+ export interface DerivedFieldSpec {
96
+ name: string
97
+ derivedFrom?: string
98
+ derivedTransform?: DerivedTransform
99
+ }
100
+
101
+ /**
102
+ * Apply a derived field's named transform to its source value.
103
+ *
104
+ * `slug` reuses `slugify` deliberately, and `slugify` **keeps `/`** — it is written to name
105
+ * files on disk, where a nested entry path has to survive. So `transform: 'slug'` on a value
106
+ * that already contains a slash keeps it (`"news/2024"` → `"news/2024"`). That is a conscious
107
+ * reuse of the existing function, not a bug: the transform is documented as "the `slugifyHref`
108
+ * fold without the leading slash", and every other separator still collapses to `-`.
109
+ */
110
+ export function applyDerivedTransform(value: string, transform: DerivedTransform | undefined): string {
111
+ switch (transform) {
112
+ case 'copy':
113
+ return value
114
+ case 'slug':
115
+ return slugify(value)
116
+ // `slugifyHref` is the default so a declared `derivedFrom: 'category'` produces exactly
117
+ // what `detectDerivedHrefFields` used to infer — migrating an inferred field to a
118
+ // declared one must not rewrite any data.
119
+ default:
120
+ return slugifyHref(value)
121
+ }
122
+ }
123
+
124
+ /**
125
+ * Values every derived field in `fields` should hold given `data`, keyed by field name.
126
+ *
127
+ * The single definition of "recompute derived fields", shared by every write path in
128
+ * `cms-core`. A source field that is missing, not a string, or blank yields no entry at all —
129
+ * the existing value is left alone rather than blanked, because "no source" is not "empty
130
+ * result". An empty source is deliberately in that group: every transform maps `''` to
131
+ * something that looks like a value (`slugifyHref('')` is `'/'`, a link to the site root), and
132
+ * writing that into content is worse than leaving the previous value in place. Whitespace-only
133
+ * counts as empty for the same reason — it slugifies to the same thing.
134
+ *
135
+ * `hidden` is deliberately not consulted: an author who sets `hidden: false` on a declared
136
+ * derived field still gets it computed, they only also get to see it.
137
+ */
138
+ export function computeDerivedFieldUpdates(
139
+ fields: readonly DerivedFieldSpec[],
140
+ data: Record<string, unknown>,
141
+ ): Record<string, unknown> {
142
+ const updates: Record<string, unknown> = {}
143
+ for (const field of fields) {
144
+ if (!field.derivedFrom) continue
145
+ const source = data[field.derivedFrom]
146
+ if (typeof source !== 'string' || source.trim() === '') continue
147
+ updates[field.name] = applyDerivedTransform(source, field.derivedTransform)
148
+ }
149
+ return updates
150
+ }
93
151
 
94
152
  /**
95
153
  * Escape HTML special characters to prevent injection.