@nuasite/cms-core 0.53.0 → 0.55.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.
Files changed (42) hide show
  1. package/dist/types/asset-paths.d.ts +28 -0
  2. package/dist/types/asset-paths.d.ts.map +1 -0
  3. package/dist/types/check-entries.d.ts +50 -0
  4. package/dist/types/check-entries.d.ts.map +1 -0
  5. package/dist/types/check-live.d.ts +25 -0
  6. package/dist/types/check-live.d.ts.map +1 -0
  7. package/dist/types/check-shape.d.ts +28 -0
  8. package/dist/types/check-shape.d.ts.map +1 -0
  9. package/dist/types/check-write.d.ts +35 -0
  10. package/dist/types/check-write.d.ts.map +1 -0
  11. package/dist/types/check.d.ts +18 -1
  12. package/dist/types/check.d.ts.map +1 -1
  13. package/dist/types/collection-scanner.d.ts.map +1 -1
  14. package/dist/types/content-config-ast.d.ts +7 -1
  15. package/dist/types/content-config-ast.d.ts.map +1 -1
  16. package/dist/types/editor-write-model.d.ts +48 -0
  17. package/dist/types/editor-write-model.d.ts.map +1 -0
  18. package/dist/types/handlers/entry-ops.d.ts.map +1 -1
  19. package/dist/types/index.d.ts +10 -2
  20. package/dist/types/index.d.ts.map +1 -1
  21. package/dist/types/schema-port.d.ts +43 -0
  22. package/dist/types/schema-port.d.ts.map +1 -0
  23. package/dist/types/schema-probe.d.ts +53 -0
  24. package/dist/types/schema-probe.d.ts.map +1 -0
  25. package/dist/types/shared.d.ts +34 -10
  26. package/dist/types/shared.d.ts.map +1 -1
  27. package/dist/types/tsconfig.tsbuildinfo +1 -1
  28. package/package.json +7 -2
  29. package/src/asset-paths.ts +54 -0
  30. package/src/check-entries.ts +120 -0
  31. package/src/check-live.ts +61 -0
  32. package/src/check-shape.ts +137 -0
  33. package/src/check-write.ts +280 -0
  34. package/src/check.ts +192 -62
  35. package/src/collection-scanner.ts +14 -0
  36. package/src/content-config-ast.ts +301 -18
  37. package/src/editor-write-model.ts +82 -0
  38. package/src/handlers/entry-ops.ts +153 -73
  39. package/src/index.ts +41 -2
  40. package/src/schema-port.ts +46 -0
  41. package/src/schema-probe.ts +133 -0
  42. package/src/shared.ts +60 -18
@@ -1,10 +1,12 @@
1
1
  import type { CollectionEntryInfo, ComponentDefinition, MutationResult } from '@nuasite/cms-types'
2
2
  import yaml from 'yaml'
3
+ import { assetBaseDir, resolveAssetCandidates } from '../asset-paths'
3
4
  import { scanCollections } from '../collection-scanner'
4
- import { type ParseCache, parseContentConfig } from '../content-config-ast'
5
+ import { type ParseCache, parseContentConfig, type ParsedField } from '../content-config-ast'
6
+ import { blankRequiredFields, isBlankFieldValue, newRepeaterItem, type RepeaterItemField } from '../editor-write-model'
5
7
  import type { CmsFileSystem } from '../fs/types'
6
8
  import { mimeFromExt } from '../media/local'
7
- import { isPlainRecord, relativeImportPath, slugify } from '../shared'
9
+ import { computeDerivedFieldUpdates, isPlainRecord, relativeImportPath, slugify } from '../shared'
8
10
 
9
11
  /** Frontmatter file extensions that hold markdown content (vs. pure data files). */
10
12
  const MARKDOWN_EXTENSIONS = ['md', 'mdx'] as const
@@ -84,46 +86,6 @@ async function resolveEntryPath(deps: EntryOpsDeps, collection: string, slug: st
84
86
  return null
85
87
  }
86
88
 
87
- /**
88
- * Resolve a stored asset value (as it appears in frontmatter) to candidate on-disk
89
- * paths, root-relative, in priority order. Handles the shapes that actually occur:
90
- *
91
- * - **Leading `/`** — a runtime URL (`/assets/x.jpeg`, `/uploads/x.webp`). Astro
92
- * serves the `public/` dir at the site root, so try `public/<path>` first, then
93
- * `<path>` from the project root (assets kept outside `public/`). `baseDir` is
94
- * irrelevant, so these resolve without an owning entry.
95
- * - **Relative** (`../../src/assets/x.webp`, `./x.png`, `x.png`) — an Astro
96
- * `image()` value, resolved against `baseDir` (the entry's directory), honoring
97
- * `.`/`..`.
98
- *
99
- * Returns `[]` when the path climbs above the project root, or is relative with no `baseDir`.
100
- */
101
- function resolveAssetCandidates(baseDir: string | undefined, rel: string): string[] {
102
- if (rel.startsWith('/')) {
103
- const fromRoot = normalizeSegments([], rel)
104
- if (fromRoot === null || fromRoot === '') return []
105
- return [`public/${fromRoot}`, fromRoot]
106
- }
107
- if (baseDir === undefined) return []
108
- const joined = normalizeSegments(baseDir.split('/').filter(Boolean), rel)
109
- return joined === null ? [] : [joined]
110
- }
111
-
112
- /** Join `rel` onto `base` segments, applying `.`/`..`; `null` on traversal above root. */
113
- function normalizeSegments(base: string[], rel: string): string | null {
114
- const out = base.slice()
115
- for (const seg of rel.replace(/^\/+/, '').split('/')) {
116
- if (seg === '' || seg === '.') continue
117
- if (seg === '..') {
118
- if (out.length === 0) return null
119
- out.pop()
120
- continue
121
- }
122
- out.push(seg)
123
- }
124
- return out.join('/')
125
- }
126
-
127
89
  /** First existing candidate read as bytes + content type, or `null` when none exist. */
128
90
  async function readAsset(deps: EntryOpsDeps, candidates: string[]): Promise<EntryAsset | null> {
129
91
  for (const candidate of candidates) {
@@ -160,9 +122,7 @@ export async function getEntryAsset(deps: EntryOpsDeps, collection: string, slug
160
122
  if (assetPath.startsWith('/')) return readAsset(deps, resolveAssetCandidates(undefined, assetPath))
161
123
  const sourcePath = await resolveEntryPath(deps, collection, slug)
162
124
  if (!sourcePath) return null
163
- const lastSlash = sourcePath.lastIndexOf('/')
164
- const baseDir = lastSlash >= 0 ? sourcePath.slice(0, lastSlash) : ''
165
- return readAsset(deps, resolveAssetCandidates(baseDir, assetPath))
125
+ return readAsset(deps, resolveAssetCandidates(assetBaseDir(sourcePath), assetPath))
166
126
  }
167
127
 
168
128
  /**
@@ -355,23 +315,100 @@ function isIndexStyleGlobPattern(pattern: string): boolean {
355
315
  }
356
316
 
357
317
  // ============================================================================
358
- // Required-field validation
318
+ // Derived-field recompute
359
319
  // ============================================================================
360
320
 
361
321
  /**
362
- * No value at all — as opposed to an empty collection or a falsy scalar.
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:
363
381
  *
364
- * `false` and `0` are values and pass. `[]` and `{}` are a deliberate "nothing here"
365
- * and pass too. Deliberately identical to the editor-side check so the two sides can
366
- * never disagree about what "empty" means.
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.
367
394
  */
368
- function isBlank(value: unknown): boolean {
369
- return value === undefined || value === null || value === ''
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])
370
400
  }
371
401
 
402
+ // ============================================================================
403
+ // Required-field validation
404
+ // ============================================================================
405
+
372
406
  /**
373
407
  * Names of the collection's **schema-declared** required fields left empty by `frontmatter`.
374
408
  *
409
+ * The predicate itself lives in `editor-write-model.ts`, shared with the content check —
410
+ * see there for which fields the guard deliberately does not cover.
411
+ *
375
412
  * Note on where `required` comes from — this reads the content config, never the
376
413
  * scanner, and that is the whole point. `scanCollections` *infers* `required` as
377
414
  * "the field is present in every scanned entry" (`mergeFieldObservations` in
@@ -386,20 +423,15 @@ function isBlank(value: unknown): boolean {
386
423
  * A collection absent from `content.config.ts` therefore yields `[]` — nobody declared
387
424
  * anything required there, so there is nothing to enforce and the write goes through.
388
425
  *
389
- * Only top-level fields are checked. Nested object/array members are left alone: a
390
- * required key *inside* an object says nothing about whether that object was meant to
391
- * be filled in at all, and rejecting on it would block partial edits.
392
- *
393
- * `hidden` fields are skipped — the form offers no way to fill them in.
426
+ * The rule itself lives in `blankRequiredFields` (`@nuasite/cms-types`), shared with every
427
+ * collections UI — including which fields are exempt, and why.
394
428
  */
395
429
  async function missingRequiredFields(deps: EntryOpsDeps, collection: string, frontmatter: Record<string, unknown>): Promise<string[]> {
396
430
  const parsed = await parseContentConfig(deps.fs, deps.parseCache)
397
431
  const parsedCollection = parsed.get(collection)
398
432
  if (!parsedCollection) return []
399
433
 
400
- return parsedCollection.fields
401
- .filter(field => field.required && !field.layout?.hidden && isBlank(frontmatter[field.name]))
402
- .map(field => field.name)
434
+ return blankRequiredFields(parsedCollection.fields, frontmatter)
403
435
  }
404
436
 
405
437
  /** Name the offending fields — the text reaches the UI verbatim, where "validation failed" would be useless. */
@@ -465,10 +497,15 @@ export async function createEntry(deps: EntryOpsDeps, input: CreateEntryInput):
465
497
  if (!allowedExtensions.includes(ext)) {
466
498
  return { success: false, error: `Invalid file extension "${ext}". Allowed: ${allowedExtensions.join(', ')}` }
467
499
  }
500
+ // Derived fields first: a required-but-visible derived field must be judged on the value
501
+ // it is about to be given, not on the hole the caller left. `resolved` is what both
502
+ // branches below serialize, so the markdown and the data file agree by construction.
503
+ const resolved = await applyDerivedFields(deps, collection, frontmatter)
504
+
468
505
  // Hard invariant, ahead of every path that could touch the disk — the markdown and
469
- // the data branch below both write exactly `{ ...frontmatter }`, so one check covers
506
+ // the data branch below both write exactly `{ ...resolved }`, so one check covers
470
507
  // `.md`/`.mdx` frontmatter and `.json`/`.yaml`/`.yml` data files alike.
471
- const missing = await missingRequiredFields(deps, collection, frontmatter)
508
+ const missing = await missingRequiredFields(deps, collection, resolved)
472
509
  if (missing.length > 0) {
473
510
  return { success: false, error: missingRequiredMessage(missing) }
474
511
  }
@@ -483,10 +520,10 @@ export async function createEntry(deps: EntryOpsDeps, input: CreateEntryInput):
483
520
  let fileContent: string
484
521
  if (isData) {
485
522
  fileContent = ext === 'json'
486
- ? JSON.stringify({ ...frontmatter }, null, 2) + '\n'
487
- : yaml.stringify({ ...frontmatter })
523
+ ? JSON.stringify({ ...resolved }, null, 2) + '\n'
524
+ : yaml.stringify({ ...resolved })
488
525
  } else {
489
- fileContent = serializeFrontmatter({ ...frontmatter }, body)
526
+ fileContent = serializeFrontmatter({ ...resolved }, body)
490
527
  }
491
528
 
492
529
  if (await deps.fs.exists(sourcePath)) {
@@ -513,17 +550,23 @@ export async function updateEntry(deps: EntryOpsDeps, input: UpdateEntryInput):
513
550
  const existing = sourcePath.endsWith('.json') ? JSON.parse(raw) : yaml.parse(raw)
514
551
  const merged: Record<string, unknown> = { ...(existing ?? {}), ...input.frontmatter }
515
552
 
553
+ // Recompute from the merged result, so a patch that carries only the source field
554
+ // still refreshes the derived one. Ahead of the required check for the same reason
555
+ // as in `createEntry`. The patch goes along so a write that never touches a source
556
+ // leaves the value the author put there alone — see `shouldRecomputeOnUpdate`.
557
+ const resolved = await applyDerivedFields(deps, input.collection, merged, input.frontmatter ?? {})
558
+
516
559
  // Validate the merged result, not the incoming patch: a patch that omits a
517
560
  // required field is fine when the file already carries it, and a patch that
518
561
  // blanks one must be rejected even though the field itself is present.
519
- const missing = await missingRequiredFields(deps, input.collection, merged)
562
+ const missing = await missingRequiredFields(deps, input.collection, resolved)
520
563
  if (missing.length > 0) {
521
564
  return { success: false, error: missingRequiredMessage(missing) }
522
565
  }
523
566
 
524
567
  const output = sourcePath.endsWith('.json')
525
- ? JSON.stringify(merged, null, 2) + '\n'
526
- : yaml.stringify(merged)
568
+ ? JSON.stringify(resolved, null, 2) + '\n'
569
+ : yaml.stringify(resolved)
527
570
  await deps.fs.writeFile(sourcePath, output)
528
571
  } else {
529
572
  const raw = await deps.fs.readFile(sourcePath)
@@ -534,9 +577,12 @@ export async function updateEntry(deps: EntryOpsDeps, input: UpdateEntryInput):
534
577
  ...input.frontmatter,
535
578
  }
536
579
 
537
- // Same rule as the data branch: the merged frontmatter is what lands on disk,
538
- // so that is what gets validated.
539
- const missing = await missingRequiredFields(deps, input.collection, mergedFrontmatter)
580
+ // Same rule as the data branch: recompute the derived fields off the merged
581
+ // frontmatter — bounded by the patch, so a body-only save rewrites nothing — then
582
+ // validate what is actually going to disk.
583
+ const resolvedFrontmatter = await applyDerivedFields(deps, input.collection, mergedFrontmatter, input.frontmatter ?? {})
584
+
585
+ const missing = await missingRequiredFields(deps, input.collection, resolvedFrontmatter)
540
586
  if (missing.length > 0) {
541
587
  return { success: false, error: missingRequiredMessage(missing) }
542
588
  }
@@ -550,7 +596,7 @@ export async function updateEntry(deps: EntryOpsDeps, input: UpdateEntryInput):
550
596
  finalContent = ensureMdxImports(finalContent, sourcePath, componentDefinitions)
551
597
  }
552
598
 
553
- await deps.fs.writeFile(sourcePath, serializeFrontmatter(mergedFrontmatter, finalContent))
599
+ await deps.fs.writeFile(sourcePath, serializeFrontmatter(resolvedFrontmatter, finalContent))
554
600
  }
555
601
 
556
602
  return { success: true, sourcePath }
@@ -661,6 +707,40 @@ async function writeEntryFrontmatter(
661
707
  await deps.fs.writeFile(loaded.sourcePath, serializeFrontmatter(loaded.frontmatter, loaded.body))
662
708
  }
663
709
 
710
+ /**
711
+ * The item fields a repeater declares in `content.config.ts`, or `[]` when it declares none.
712
+ *
713
+ * Only top-level repeaters are resolved, which is the only shape `addArrayItem` is called for.
714
+ */
715
+ async function repeaterItemFields(deps: EntryOpsDeps, collection: string, field: string): Promise<RepeaterItemField[]> {
716
+ const parsed = await parseContentConfig(deps.fs, deps.parseCache)
717
+ const declared = parsed.get(collection)?.fields.find(candidate => candidate.name === field)
718
+ if (!declared || declared.type !== 'array' || declared.itemType !== 'object') return []
719
+ return (declared.fields ?? []).map(item => ({
720
+ name: item.name,
721
+ type: item.type,
722
+ required: item.required,
723
+ hidden: item.layout?.hidden,
724
+ }))
725
+ }
726
+
727
+ /**
728
+ * Seed the required keys a client left out of an appended item.
729
+ *
730
+ * The backstop for the "+ Add" hole. Both first-party editors now send a seeded item, but this
731
+ * path is reachable by any client — an older editor, a script, the HTTP API directly — and an
732
+ * item missing a required key is frontmatter the next build refuses. Whatever the client did
733
+ * send wins: this only adds keys, never rewrites a value someone chose.
734
+ */
735
+ function seedItem(value: unknown, fields: RepeaterItemField[]): unknown {
736
+ if (fields.length === 0 || typeof value !== 'object' || value === null || Array.isArray(value)) return value
737
+ const item: Record<string, unknown> = { ...value }
738
+ for (const [key, seeded] of Object.entries(newRepeaterItem(fields))) {
739
+ if (!Object.hasOwn(item, key) || item[key] === undefined) item[key] = seeded
740
+ }
741
+ return item
742
+ }
743
+
664
744
  export async function addArrayItem(deps: EntryOpsDeps, input: AddArrayItemInput): Promise<MutationResult> {
665
745
  const loaded = await loadEntryFrontmatter(deps, input.collection, input.slug)
666
746
  if (!loaded) {
@@ -675,7 +755,7 @@ export async function addArrayItem(deps: EntryOpsDeps, input: AddArrayItemInput)
675
755
 
676
756
  const index = input.index ?? array.length
677
757
  const clamped = Math.max(0, Math.min(index, array.length))
678
- array.splice(clamped, 0, input.value)
758
+ array.splice(clamped, 0, seedItem(input.value, await repeaterItemFields(deps, input.collection, input.field)))
679
759
  loaded.frontmatter[input.field] = array
680
760
 
681
761
  try {
package/src/index.ts CHANGED
@@ -1,4 +1,18 @@
1
- export { checkContent, type CheckFinding, type CheckReport, type CheckSeverity, formatCheckReport } from './check'
1
+ export { resolveAssetCandidates } from './asset-paths'
2
+ export { checkContent, type CheckContentOptions, type CheckFinding, type CheckReport, type CheckSeverity, formatCheckReport } from './check'
3
+ export {
4
+ collectionKind,
5
+ entryStem,
6
+ loadCollections,
7
+ type LoadedCollection,
8
+ type LoadedCollections,
9
+ type LoadedEntry,
10
+ normalizeBase,
11
+ parseEntry,
12
+ } from './check-entries'
13
+ export { checkAgainstSchemas, type LiveCheckInput } from './check-live'
14
+ export { checkFieldShapes, type ShapeCheckInput } from './check-shape'
15
+ export { checkEditorWrites, type WriteCheckInput } from './check-write'
2
16
  export { scanCollections } from './collection-scanner'
3
17
  export { scanComponentDefinitions } from './component-registry'
4
18
  export {
@@ -12,6 +26,19 @@ export {
12
26
  } from './content-config-ast'
13
27
  export { createCmsCore } from './core'
14
28
  export type { CmsCore, CmsCoreOptions } from './core'
29
+ export {
30
+ applyCreateRouteFields,
31
+ blankRequiredFields,
32
+ type CollectionKind,
33
+ defaultValueForNewEntry,
34
+ isBlankFieldValue,
35
+ newEntryFrontmatter,
36
+ newRepeaterItem,
37
+ omitEmptyOnCreate,
38
+ type RepeaterItemField,
39
+ type RequiredGuardField,
40
+ type WriteModelField,
41
+ } from './editor-write-model'
15
42
  export { globToRegExp } from './fs/glob'
16
43
  export { createNodeFs } from './fs/node-fs'
17
44
  export type { CmsFileSystem } from './fs/types'
@@ -42,4 +69,16 @@ export {
42
69
  uploadsDirRelativeToRoot,
43
70
  } from './media/index'
44
71
  export { parseProjectCmsConfig, parseProjectCmsConfigSource } from './project-config-ast'
45
- export { computePathnameFromSpec, escapeHtml, relativeImportPath, resolvePathnameFromSpec, slugify, slugifyHref } from './shared'
72
+ export { describeIssue, type LiveIssue, type LiveParseResult, type LiveSchema, type LiveSchemas, schemaFor } from './schema-port'
73
+ export { acceptsMissing, firstAcceptedEntry, governsPath, pointAt, type ProbePoint, rejectsValueAt } from './schema-probe'
74
+ export {
75
+ applyDerivedTransform,
76
+ computeDerivedFieldUpdates,
77
+ computePathnameFromSpec,
78
+ type DerivedFieldSpec,
79
+ escapeHtml,
80
+ relativeImportPath,
81
+ resolvePathnameFromSpec,
82
+ slugify,
83
+ slugifyHref,
84
+ } from './shared'
@@ -0,0 +1,46 @@
1
+ /**
2
+ * The port through which a project's real collection schemas reach the checker.
3
+ *
4
+ * `cms-core` deliberately does not load them. Getting a live schema means importing the
5
+ * project's `content.config.ts`, which executes project code, needs an `astro:content`
6
+ * stub installed process-wide, and caches the module for the life of the process — all
7
+ * fine in a one-shot CLI, none of it acceptable inside the long-running dev server and
8
+ * sidecar that also load this package. The CLI does the loading and injects the result.
9
+ *
10
+ * `safeParse` is async because that is how Astro validates content
11
+ * (`astro/dist/content/utils.js` calls `safeParseAsync`), so a schema carrying an async
12
+ * refinement is legal and a synchronous parse would throw on it.
13
+ */
14
+
15
+ export interface LiveIssue {
16
+ /** Path to the offending value, as zod reports it: `['stats', 0, 'label']`. */
17
+ path: (string | number)[]
18
+ message: string
19
+ }
20
+
21
+ export type LiveParseResult = { success: true } | { success: false; issues: LiveIssue[] }
22
+
23
+ export interface LiveSchema {
24
+ safeParse(value: unknown): Promise<LiveParseResult>
25
+ }
26
+
27
+ /** Keyed by collection name. A collection missing from here has no live schema and is skipped. */
28
+ export type LiveSchemas = Record<string, LiveSchema>
29
+
30
+ /**
31
+ * Render an issue as a finding's `field` and `message`.
32
+ *
33
+ * Shared so the two live checkers phrase the same rejection identically — they report
34
+ * different actions but the same schema verdict, and a reader comparing them should not
35
+ * have to wonder whether a wording difference means something.
36
+ */
37
+ export function describeIssue(issue: LiveIssue): { field?: string; message: string } {
38
+ if (issue.path.length === 0) return { message: issue.message }
39
+ const field = issue.path.join('.')
40
+ return { field, message: `${field}: ${issue.message}` }
41
+ }
42
+
43
+ /** A collection's live schema, if it has one. Guards against inherited `Object.prototype` keys. */
44
+ export function schemaFor(schemas: LiveSchemas, collection: string): LiveSchema | undefined {
45
+ return Object.hasOwn(schemas, collection) ? schemas[collection] : undefined
46
+ }
@@ -0,0 +1,133 @@
1
+ /**
2
+ * Ask a live schema what it thinks of one field, without the rest of the record answering for it.
3
+ *
4
+ * The static rules read the config's source and the live rules read the schema's verdict on a
5
+ * whole entry. Neither can say what the schema believes about a *single* field, which is what the
6
+ * drift rules need: whether it insists on the key, whether it would take text there.
7
+ *
8
+ * The technique is the same for every question. Start from an entry the schema already accepts,
9
+ * change exactly one value, parse again, and look at where the issues land. Starting from an
10
+ * accepted entry is what makes the answer attributable — on a record the schema already rejects,
11
+ * every probe comes back "rejected" and means nothing. Reading the issue's *path* rather than
12
+ * overall success is the other half: a schema with a cross-field refinement can fail for reasons
13
+ * that have nothing to do with the field being probed.
14
+ *
15
+ * Every function here is total. A schema that throws answers "I don't know", which callers read
16
+ * as "report nothing" — a rule that cannot get evidence has to stay quiet rather than guess.
17
+ */
18
+
19
+ import type { LoadedEntry } from './check-entries'
20
+ import type { LiveSchema } from './schema-port'
21
+
22
+ /** One field in one record: the accepted entry to start from, and where the field sits in it. */
23
+ export interface ProbePoint {
24
+ /** Never mutated — every probe works on a clone. */
25
+ record: Record<string, unknown>
26
+ path: (string | number)[]
27
+ }
28
+
29
+ /** The point for a top-level field of `seed`. The probe sets the key, so the seed need not already carry it. */
30
+ export const pointAt = (seed: Record<string, unknown>, field: string): ProbePoint => ({ record: seed, path: [field] })
31
+
32
+ /**
33
+ * Values chosen so that no realistic schema accepts all four.
34
+ *
35
+ * They answer one question: does the schema have an opinion about this path at all? A field the
36
+ * parser invented, or one landing in a `passthrough()`/`catchall()` object, accepts anything and
37
+ * must not be reported — a rule firing on a field the schema never governs is a false positive on
38
+ * a project that is fine.
39
+ */
40
+ const GOVERNANCE_PROBES: unknown[] = [{ __nuaProbe: true }, ['__nua_probe__'], 918_273.456, null]
41
+
42
+ type Mutation = { set: unknown } | { remove: true }
43
+
44
+ const isContainer = (value: unknown): value is Record<string | number, unknown> => typeof value === 'object' && value !== null
45
+
46
+ /** A copy of the record with one value changed, or `null` when it cannot be built. */
47
+ function mutated(point: ProbePoint, mutation: Mutation): Record<string, unknown> | null {
48
+ let copy: Record<string, unknown>
49
+ try {
50
+ copy = structuredClone(point.record)
51
+ } catch {
52
+ // Frontmatter is plain data, so this should not happen — but an unclonable value must cost
53
+ // this one probe, not the run.
54
+ return null
55
+ }
56
+
57
+ let parent: unknown = copy
58
+ for (const segment of point.path.slice(0, -1)) {
59
+ if (!isContainer(parent)) return null
60
+ parent = parent[segment]
61
+ }
62
+ const last = point.path.at(-1)
63
+ if (last === undefined || !isContainer(parent)) return null
64
+
65
+ if ('remove' in mutation) delete parent[last]
66
+ else parent[last] = mutation.set
67
+ return copy
68
+ }
69
+
70
+ /** What one probe learned. `unknown` is a schema that threw, or a record that could not be built. */
71
+ type ProbeVerdict = 'accepted' | 'rejected-here' | 'rejected-elsewhere' | 'unknown'
72
+
73
+ async function probe(schema: LiveSchema, point: ProbePoint, mutation: Mutation): Promise<ProbeVerdict> {
74
+ const value = mutated(point, mutation)
75
+ if (value === null) return 'unknown'
76
+ try {
77
+ const result = await schema.safeParse(value)
78
+ if (result.success) return 'accepted'
79
+ const here = result.issues.some(issue => point.path.every((segment, index) => issue.path[index] === segment))
80
+ return here ? 'rejected-here' : 'rejected-elsewhere'
81
+ } catch {
82
+ return 'unknown'
83
+ }
84
+ }
85
+
86
+ /**
87
+ * Whether the schema constrains this path at all.
88
+ *
89
+ * True as soon as one probe value is refused *at the path*. False means either a schema that takes
90
+ * anything here or one that could not be asked; both are reasons to report nothing.
91
+ */
92
+ export async function governsPath(schema: LiveSchema, point: ProbePoint): Promise<boolean> {
93
+ for (const value of GOVERNANCE_PROBES) {
94
+ if (await probe(schema, point, { set: value }) === 'rejected-here') return true
95
+ }
96
+ return false
97
+ }
98
+
99
+ /**
100
+ * Whether the schema takes the record with this key removed.
101
+ *
102
+ * Deliberately strict — the whole record has to parse, not merely avoid an issue at this path. The
103
+ * claim built on it is that the editor blocks a save the build would accept, and a record failing
104
+ * elsewhere is not evidence the build would accept anything.
105
+ */
106
+ export async function acceptsMissing(schema: LiveSchema, point: ProbePoint): Promise<boolean> {
107
+ return await probe(schema, point, { remove: true }) === 'accepted'
108
+ }
109
+
110
+ /** Whether the schema refuses `value` *at this path*, as opposed to failing for some unrelated reason. */
111
+ export async function rejectsValueAt(schema: LiveSchema, point: ProbePoint, value: unknown): Promise<boolean> {
112
+ return await probe(schema, point, { set: value }) === 'rejected-here'
113
+ }
114
+
115
+ /**
116
+ * The first entry the schema accepts, or `undefined` when there is none.
117
+ *
118
+ * Shared with the write check so both mean the same thing by "a record the editor is really
119
+ * sitting on". Seeding from a rejected entry would blame every probe for that entry's own
120
+ * problems, which `check-live.ts` already reports.
121
+ */
122
+ export async function firstAcceptedEntry(schema: LiveSchema, entries: LoadedEntry[]): Promise<Record<string, unknown> | undefined> {
123
+ for (const entry of entries) {
124
+ if (!entry.frontmatter) continue
125
+ try {
126
+ const result = await schema.safeParse(entry.frontmatter)
127
+ if (result.success) return entry.frontmatter
128
+ } catch {
129
+ // A schema that throws on an entry has not accepted it; `check-live.ts` reports the throw.
130
+ }
131
+ }
132
+ return undefined
133
+ }
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;
@@ -86,25 +86,67 @@ export function isPlainRecord(value: unknown): value is Record<string, unknown>
86
86
  }
87
87
 
88
88
  /**
89
- * Slugify text for URL paths.
90
- * Folds diacritics, lowercases, strips non-word characters, collapses whitespace/underscores
91
- * to hyphens. Keeps `/`, so a nested entry path survives — that is the only thing separating
92
- * this from `slugifyHref` above.
89
+ * Re-exported from `@nuasite/cms-types` so the server and every client slugify identically —
90
+ * a host deriving a slug locally is predicting this write. See `cms-types/src/slug.ts`.
91
+ */
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.
93
103
  *
94
- * The fold matters because this names the file a new entry is written to: `[^\w\s\-/]` alone
95
- * deletes diacritics rather than folding them, turning "Vedra jako zdravotní i sociální
96
- * problém" into "vedra-jako-zdravotn-i-sociln-problm" — which is what any host deriving a
97
- * slug from a Czech title would have to write to disk.
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 `-`.
98
109
  */
99
- export function slugify(text: string): string {
100
- return text
101
- .normalize('NFD')
102
- .replace(/[\u0300-\u036f]/g, '')
103
- .toLowerCase()
104
- .trim()
105
- .replace(/[^\w\s\-/]/g, '')
106
- .replace(/[\s_]+/g, '-')
107
- .replace(/^[-/]+|[-/]+$/g, '')
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
108
150
  }
109
151
 
110
152
  /**