@nuasite/cms-core 0.64.3 → 0.65.1
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/dist/asset-paths.d.ts.map +1 -0
- package/dist/asset-paths.js +55 -0
- package/dist/astro-source-analysis.d.ts.map +1 -0
- package/dist/astro-source-analysis.js +503 -0
- package/dist/byte-range.d.ts.map +1 -0
- package/dist/byte-range.js +31 -0
- package/dist/{types/check-entries.d.ts → check-entries.d.ts} +3 -3
- package/dist/check-entries.d.ts.map +1 -0
- package/dist/check-entries.js +98 -0
- package/dist/{types/check-live.d.ts → check-live.d.ts} +4 -4
- package/dist/check-live.d.ts.map +1 -0
- package/dist/check-live.js +49 -0
- package/dist/{types/check-shape.d.ts → check-shape.d.ts} +4 -4
- package/dist/check-shape.d.ts.map +1 -0
- package/dist/check-shape.js +119 -0
- package/dist/{types/check-write.d.ts → check-write.d.ts} +4 -4
- package/dist/check-write.d.ts.map +1 -0
- package/dist/check-write.js +273 -0
- package/dist/{types/check.d.ts → check.d.ts} +2 -2
- package/dist/check.d.ts.map +1 -0
- package/dist/check.js +366 -0
- package/dist/{types/collection-scanner.d.ts → collection-scanner.d.ts} +2 -2
- package/dist/collection-scanner.d.ts.map +1 -0
- package/dist/collection-scanner.js +1483 -0
- package/dist/{types/component-registry.d.ts → component-registry.d.ts} +1 -1
- package/dist/component-registry.d.ts.map +1 -0
- package/dist/component-registry.js +271 -0
- package/dist/{types/content-config-ast.d.ts → content-config-ast.d.ts} +1 -1
- package/dist/content-config-ast.d.ts.map +1 -0
- package/dist/content-config-ast.js +1614 -0
- package/dist/{types/core.d.ts → core.d.ts} +3 -3
- package/dist/core.d.ts.map +1 -0
- package/dist/core.js +94 -0
- package/dist/editor-write-model.d.ts.map +1 -0
- package/dist/editor-write-model.js +101 -0
- package/dist/fs/glob.d.ts.map +1 -0
- package/dist/fs/glob.js +79 -0
- package/dist/{types/fs → fs}/node-fs.d.ts +1 -1
- package/dist/fs/node-fs.d.ts.map +1 -0
- package/dist/fs/node-fs.js +199 -0
- package/dist/{types/fs → fs}/staged.d.ts +1 -1
- package/dist/fs/staged.d.ts.map +1 -0
- package/dist/fs/staged.js +203 -0
- package/dist/fs/types.d.ts.map +1 -0
- package/dist/fs/types.js +0 -0
- package/dist/{types/handlers → handlers}/entry-ops.d.ts +2 -2
- package/dist/handlers/entry-ops.d.ts.map +1 -0
- package/dist/handlers/entry-ops.js +846 -0
- package/dist/{types/handlers → handlers}/page-ops.d.ts +1 -1
- package/dist/handlers/page-ops.d.ts.map +1 -0
- package/dist/handlers/page-ops.js +165 -0
- package/dist/{types/handlers → handlers}/redirect-ops.d.ts +1 -1
- package/dist/handlers/redirect-ops.d.ts.map +1 -0
- package/dist/handlers/redirect-ops.js +111 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +4 -0
- package/dist/media/contember.d.ts.map +1 -0
- package/dist/media/contember.js +79 -0
- package/dist/media/errors.d.ts.map +1 -0
- package/dist/media/errors.js +22 -0
- package/dist/{types/media → media}/file-system.d.ts +1 -1
- package/dist/media/file-system.d.ts.map +1 -0
- package/dist/media/file-system.js +124 -0
- package/dist/{types/media → media}/index.d.ts +8 -8
- package/dist/media/index.d.ts.map +1 -0
- package/dist/media/index.js +8 -0
- package/dist/media/local.d.ts.map +1 -0
- package/dist/media/local.js +209 -0
- package/dist/media/mime.d.ts.map +1 -0
- package/dist/media/mime.js +21 -0
- package/dist/media/names.d.ts.map +1 -0
- package/dist/media/names.js +23 -0
- package/dist/{types/media → media}/project-images.d.ts +1 -1
- package/dist/media/project-images.d.ts.map +1 -0
- package/dist/media/project-images.js +99 -0
- package/dist/media/s3.d.ts.map +1 -0
- package/dist/media/s3.js +160 -0
- package/dist/media/type-filter.d.ts.map +1 -0
- package/dist/media/type-filter.js +164 -0
- package/dist/{types/portable.d.ts → portable.d.ts} +25 -25
- package/dist/portable.d.ts.map +1 -0
- package/dist/portable.js +27 -0
- package/dist/{types/project-config-ast.d.ts → project-config-ast.d.ts} +1 -1
- package/dist/project-config-ast.d.ts.map +1 -0
- package/dist/project-config-ast.js +324 -0
- package/dist/public-static-file.d.ts.map +1 -0
- package/dist/public-static-file.js +40 -0
- package/dist/redirects.d.ts.map +1 -0
- package/dist/redirects.js +185 -0
- package/dist/route-scan.d.ts.map +1 -0
- package/dist/route-scan.js +23 -0
- package/dist/schema-port.d.ts.map +1 -0
- package/dist/schema-port.js +30 -0
- package/dist/{types/schema-probe.d.ts → schema-probe.d.ts} +2 -2
- package/dist/schema-probe.d.ts.map +1 -0
- package/dist/schema-probe.js +119 -0
- package/dist/shared.d.ts.map +1 -0
- package/dist/shared.js +163 -0
- package/dist/tsconfig.tsbuildinfo +1 -0
- package/package.json +12 -12
- package/src/check-entries.ts +4 -4
- package/src/check-live.ts +4 -4
- package/src/check-shape.ts +5 -5
- package/src/check-write.ts +6 -6
- package/src/check.ts +15 -9
- package/src/collection-scanner.ts +3 -3
- package/src/component-registry.ts +1 -1
- package/src/content-config-ast.ts +1 -1
- package/src/core.ts +8 -8
- package/src/editor-write-model.ts +1 -1
- package/src/fs/node-fs.ts +2 -2
- package/src/fs/staged.ts +6 -3
- package/src/handlers/entry-ops.ts +7 -7
- package/src/handlers/page-ops.ts +2 -2
- package/src/handlers/redirect-ops.ts +2 -2
- package/src/index.ts +4 -4
- package/src/media/contember.ts +1 -1
- package/src/media/file-system.ts +4 -4
- package/src/media/index.ts +8 -8
- package/src/media/local.ts +3 -3
- package/src/media/project-images.ts +2 -2
- package/src/media/s3.ts +3 -3
- package/src/portable.ts +25 -25
- package/src/project-config-ast.ts +1 -1
- package/src/route-scan.ts +1 -1
- package/src/schema-probe.ts +2 -2
- package/src/tsconfig.json +5 -1
- package/dist/types/asset-paths.d.ts.map +0 -1
- package/dist/types/astro-source-analysis.d.ts.map +0 -1
- package/dist/types/byte-range.d.ts.map +0 -1
- package/dist/types/check-entries.d.ts.map +0 -1
- package/dist/types/check-live.d.ts.map +0 -1
- package/dist/types/check-shape.d.ts.map +0 -1
- package/dist/types/check-write.d.ts.map +0 -1
- package/dist/types/check.d.ts.map +0 -1
- package/dist/types/collection-scanner.d.ts.map +0 -1
- package/dist/types/component-registry.d.ts.map +0 -1
- package/dist/types/content-config-ast.d.ts.map +0 -1
- package/dist/types/core.d.ts.map +0 -1
- package/dist/types/editor-write-model.d.ts.map +0 -1
- package/dist/types/fs/glob.d.ts.map +0 -1
- package/dist/types/fs/node-fs.d.ts.map +0 -1
- package/dist/types/fs/staged.d.ts.map +0 -1
- package/dist/types/fs/types.d.ts.map +0 -1
- package/dist/types/handlers/entry-ops.d.ts.map +0 -1
- package/dist/types/handlers/page-ops.d.ts.map +0 -1
- package/dist/types/handlers/redirect-ops.d.ts.map +0 -1
- package/dist/types/index.d.ts +0 -5
- package/dist/types/index.d.ts.map +0 -1
- package/dist/types/media/contember.d.ts.map +0 -1
- package/dist/types/media/errors.d.ts.map +0 -1
- package/dist/types/media/file-system.d.ts.map +0 -1
- package/dist/types/media/index.d.ts.map +0 -1
- package/dist/types/media/local.d.ts.map +0 -1
- package/dist/types/media/mime.d.ts.map +0 -1
- package/dist/types/media/names.d.ts.map +0 -1
- package/dist/types/media/project-images.d.ts.map +0 -1
- package/dist/types/media/s3.d.ts.map +0 -1
- package/dist/types/media/type-filter.d.ts.map +0 -1
- package/dist/types/portable.d.ts.map +0 -1
- package/dist/types/project-config-ast.d.ts.map +0 -1
- package/dist/types/public-static-file.d.ts.map +0 -1
- package/dist/types/redirects.d.ts.map +0 -1
- package/dist/types/route-scan.d.ts.map +0 -1
- package/dist/types/schema-port.d.ts.map +0 -1
- package/dist/types/schema-probe.d.ts.map +0 -1
- package/dist/types/shared.d.ts.map +0 -1
- package/dist/types/tsconfig.tsbuildinfo +0 -1
- /package/dist/{types/asset-paths.d.ts → asset-paths.d.ts} +0 -0
- /package/dist/{types/astro-source-analysis.d.ts → astro-source-analysis.d.ts} +0 -0
- /package/dist/{types/byte-range.d.ts → byte-range.d.ts} +0 -0
- /package/dist/{types/editor-write-model.d.ts → editor-write-model.d.ts} +0 -0
- /package/dist/{types/fs → fs}/glob.d.ts +0 -0
- /package/dist/{types/fs → fs}/types.d.ts +0 -0
- /package/dist/{types/media → media}/contember.d.ts +0 -0
- /package/dist/{types/media → media}/errors.d.ts +0 -0
- /package/dist/{types/media → media}/local.d.ts +0 -0
- /package/dist/{types/media → media}/mime.d.ts +0 -0
- /package/dist/{types/media → media}/names.d.ts +0 -0
- /package/dist/{types/media → media}/s3.d.ts +0 -0
- /package/dist/{types/media → media}/type-filter.d.ts +0 -0
- /package/dist/{types/public-static-file.d.ts → public-static-file.d.ts} +0 -0
- /package/dist/{types/redirects.d.ts → redirects.d.ts} +0 -0
- /package/dist/{types/route-scan.d.ts → route-scan.d.ts} +0 -0
- /package/dist/{types/schema-port.d.ts → schema-port.d.ts} +0 -0
- /package/dist/{types/shared.d.ts → shared.d.ts} +0 -0
|
@@ -0,0 +1,846 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
import yaml from 'yaml';
|
|
3
|
+
import { assetBaseDir, resolveAssetCandidates } from "../asset-paths.js";
|
|
4
|
+
import { normalizeBasePath, scanCollections } from "../collection-scanner.js";
|
|
5
|
+
import { parseContentConfig } from "../content-config-ast.js";
|
|
6
|
+
import { blankRequiredFields, ENTRY_SLUG_FIELD, isBlankFieldValue, newRepeaterItem, normalizeCreateWrite, withEntrySlug, withoutBlankArrayItems, withRenamedEntrySlug, } from "../editor-write-model.js";
|
|
7
|
+
import { mimeFromExt } from "../media/mime.js";
|
|
8
|
+
import { computeDerivedFieldUpdates, isPlainRecord, relativeImportPath, slugify } from "../shared.js";
|
|
9
|
+
/** Frontmatter file extensions that hold markdown content (vs. pure data files). */
|
|
10
|
+
const MARKDOWN_EXTENSIONS = ['md', 'mdx'];
|
|
11
|
+
// ============================================================================
|
|
12
|
+
// Path / slug resolution
|
|
13
|
+
// ============================================================================
|
|
14
|
+
function fileExtension(filePath) {
|
|
15
|
+
const idx = filePath.lastIndexOf('.');
|
|
16
|
+
return idx >= 0 ? filePath.slice(idx + 1).toLowerCase() : '';
|
|
17
|
+
}
|
|
18
|
+
function isDataFile(filePath) {
|
|
19
|
+
const ext = fileExtension(filePath);
|
|
20
|
+
return ext === 'json' || ext === 'yaml' || ext === 'yml';
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Resolve the root-relative base directory that holds a collection's source files.
|
|
24
|
+
*
|
|
25
|
+
* Honors a glob loader's `base` from the content config — e.g.
|
|
26
|
+
* `glob({ base: './content/blog' })` points outside `contentDir`, and the
|
|
27
|
+
* collection name (`o-virivkach`) need not match the directory. Falls back to the
|
|
28
|
+
* default `<contentDir>/<collection>` layout for collections without a custom
|
|
29
|
+
* loader base. The base goes through the scanner's own `normalizeBasePath`, so the
|
|
30
|
+
* mutation/read path resolves entries in the very same place the listing scan does,
|
|
31
|
+
* the project root (`base: './'`) included.
|
|
32
|
+
*/
|
|
33
|
+
async function resolveCollectionDir(deps, collection) {
|
|
34
|
+
const parsed = await parseContentConfig(deps.fs, deps.parseCache);
|
|
35
|
+
const loaderBase = parsed.get(collection)?.loaderBase;
|
|
36
|
+
if (loaderBase)
|
|
37
|
+
return normalizeBasePath(loaderBase);
|
|
38
|
+
return `${deps.contentDir}/${collection}`;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Resolve a `{collection, slug}` pair to an existing entry's source path.
|
|
42
|
+
*
|
|
43
|
+
* Tries the flat layout first (`<collection>/<slug>.<ext>`) for every supported
|
|
44
|
+
* extension, then the index layout (`<collection>/<slug>/index.{md,mdx}`).
|
|
45
|
+
* Returns `null` when no matching file exists.
|
|
46
|
+
*/
|
|
47
|
+
async function resolveEntryPath(deps, collection, slug) {
|
|
48
|
+
const base = await resolveCollectionDir(deps, collection);
|
|
49
|
+
const flatExts = ['md', 'mdx', 'json', 'yaml', 'yml'];
|
|
50
|
+
for (const ext of flatExts) {
|
|
51
|
+
const candidate = path.posix.join(base, `${slug}.${ext}`);
|
|
52
|
+
if (await deps.fs.exists(candidate))
|
|
53
|
+
return candidate;
|
|
54
|
+
}
|
|
55
|
+
for (const ext of MARKDOWN_EXTENSIONS) {
|
|
56
|
+
const candidate = path.posix.join(base, slug, `index.${ext}`);
|
|
57
|
+
if (await deps.fs.exists(candidate))
|
|
58
|
+
return candidate;
|
|
59
|
+
}
|
|
60
|
+
return null;
|
|
61
|
+
}
|
|
62
|
+
/** First existing candidate read as bytes + content type, or `null` when none exist. */
|
|
63
|
+
async function readAsset(deps, candidates) {
|
|
64
|
+
for (const candidate of candidates) {
|
|
65
|
+
if (await deps.fs.exists(candidate)) {
|
|
66
|
+
return { bytes: await deps.fs.readBytes(candidate), contentType: mimeFromExt(extOf(candidate)) };
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
return null;
|
|
70
|
+
}
|
|
71
|
+
/** Lowercased file extension including the leading dot (e.g. `.webp`), or `''`. */
|
|
72
|
+
function extOf(filePath) {
|
|
73
|
+
const idx = filePath.lastIndexOf('.');
|
|
74
|
+
return idx >= 0 ? filePath.slice(idx).toLowerCase() : '';
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* Read an asset referenced by an entry (an `image`/`file` field value). A
|
|
78
|
+
* root-relative value (`/assets/x.jpeg`) resolves against the project root/`public/`
|
|
79
|
+
* and needs no entry; a relative value (`../../src/assets/x.webp`) resolves against
|
|
80
|
+
* the entry's source directory. Returns the raw bytes plus a content type inferred
|
|
81
|
+
* from the extension, or `null` when the entry or asset does not exist (or the path
|
|
82
|
+
* escapes the project root).
|
|
83
|
+
*/
|
|
84
|
+
export async function getEntryAsset(deps, collection, slug, assetPath) {
|
|
85
|
+
// Root-relative values don't need the entry — resolve directly so they also
|
|
86
|
+
// preview before the entry exists (and survive a missing/renamed source).
|
|
87
|
+
if (assetPath.startsWith('/'))
|
|
88
|
+
return readAsset(deps, resolveAssetCandidates(undefined, assetPath));
|
|
89
|
+
const sourcePath = await resolveEntryPath(deps, collection, slug);
|
|
90
|
+
if (!sourcePath)
|
|
91
|
+
return null;
|
|
92
|
+
return readAsset(deps, resolveAssetCandidates(assetBaseDir(sourcePath), assetPath));
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* Read a project asset by its runtime path (`/assets/x.jpeg`, `/uploads/x.webp`)
|
|
96
|
+
* with no owning entry — for previewing a root-relative value while creating an
|
|
97
|
+
* entry (no slug yet). Only leading-`/` paths resolve; relative paths need an entry.
|
|
98
|
+
*/
|
|
99
|
+
export async function getProjectAsset(deps, assetPath) {
|
|
100
|
+
return readAsset(deps, resolveAssetCandidates(undefined, assetPath));
|
|
101
|
+
}
|
|
102
|
+
// ============================================================================
|
|
103
|
+
// Frontmatter parse / serialize (ported from @nuasite/cms markdown-ops)
|
|
104
|
+
// ============================================================================
|
|
105
|
+
export function parseFrontmatter(raw) {
|
|
106
|
+
const trimmed = raw.trimStart();
|
|
107
|
+
if (!trimmed.startsWith('---')) {
|
|
108
|
+
return { frontmatter: {}, content: raw };
|
|
109
|
+
}
|
|
110
|
+
const lines = trimmed.split('\n');
|
|
111
|
+
let endLineIndex = -1;
|
|
112
|
+
for (let i = 1; i < lines.length; i++) {
|
|
113
|
+
if (lines[i].trimEnd() === '---') {
|
|
114
|
+
endLineIndex = i;
|
|
115
|
+
break;
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
if (endLineIndex === -1) {
|
|
119
|
+
return { frontmatter: {}, content: raw };
|
|
120
|
+
}
|
|
121
|
+
const yamlStr = lines.slice(1, endLineIndex).join('\n').trim();
|
|
122
|
+
const content = lines.slice(endLineIndex + 1).join('\n').replace(/^\r?\n/, '');
|
|
123
|
+
let frontmatter = {};
|
|
124
|
+
try {
|
|
125
|
+
const parsed = yaml.parse(yamlStr);
|
|
126
|
+
if (isPlainRecord(parsed)) {
|
|
127
|
+
frontmatter = parsed;
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
catch {
|
|
131
|
+
// Invalid YAML, return empty frontmatter
|
|
132
|
+
}
|
|
133
|
+
return { frontmatter, content };
|
|
134
|
+
}
|
|
135
|
+
/** Pattern for strings that YAML auto-parses as Date objects */
|
|
136
|
+
const YAML_DATE_PATTERN = /^\d{4}-\d{2}-\d{2}/;
|
|
137
|
+
export function serializeFrontmatter(frontmatter, content) {
|
|
138
|
+
const doc = new yaml.Document(frontmatter);
|
|
139
|
+
yaml.visit(doc, {
|
|
140
|
+
Scalar(_key, node) {
|
|
141
|
+
if (typeof node.value === 'string' && YAML_DATE_PATTERN.test(node.value)) {
|
|
142
|
+
node.type = yaml.Scalar.QUOTE_SINGLE;
|
|
143
|
+
}
|
|
144
|
+
},
|
|
145
|
+
});
|
|
146
|
+
const yamlStr = doc.toString().trim();
|
|
147
|
+
return `---\n${yamlStr}\n---\n${content}`;
|
|
148
|
+
}
|
|
149
|
+
/**
|
|
150
|
+
* Ensure MDX content has import statements for all components used in the body.
|
|
151
|
+
* Scans for `<ComponentName` tags, checks for existing imports, and prepends missing ones.
|
|
152
|
+
*
|
|
153
|
+
* `filePath` and the component `def.file` are both root-relative, forward-slash paths.
|
|
154
|
+
*/
|
|
155
|
+
export function ensureMdxImports(content, filePath, componentDefinitions) {
|
|
156
|
+
const usedComponents = new Set();
|
|
157
|
+
const tagRegex = /<([A-Z][A-Za-z0-9]*)\b/g;
|
|
158
|
+
let match;
|
|
159
|
+
while ((match = tagRegex.exec(content)) !== null) {
|
|
160
|
+
if (match[1])
|
|
161
|
+
usedComponents.add(match[1]);
|
|
162
|
+
}
|
|
163
|
+
if (usedComponents.size === 0)
|
|
164
|
+
return content;
|
|
165
|
+
const importedNames = new Set();
|
|
166
|
+
const importLineRegex = /^import\s+(.+)\s+from\s+/gm;
|
|
167
|
+
let lastImportEnd = -1;
|
|
168
|
+
while ((match = importLineRegex.exec(content)) !== null) {
|
|
169
|
+
lastImportEnd = match.index + match[0].length;
|
|
170
|
+
const fromRest = content.slice(lastImportEnd);
|
|
171
|
+
const lineEnd = fromRest.indexOf('\n');
|
|
172
|
+
if (lineEnd >= 0)
|
|
173
|
+
lastImportEnd += lineEnd;
|
|
174
|
+
else
|
|
175
|
+
lastImportEnd = content.length;
|
|
176
|
+
const clause = match[1];
|
|
177
|
+
const braceMatch = clause.match(/\{([^}]+)\}/);
|
|
178
|
+
if (braceMatch?.[1]) {
|
|
179
|
+
for (const name of braceMatch[1].split(',')) {
|
|
180
|
+
const parts = name.trim().split(/\s+as\s+/);
|
|
181
|
+
const imported = (parts[1] ?? parts[0])?.trim();
|
|
182
|
+
if (imported)
|
|
183
|
+
importedNames.add(imported);
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
const withoutBraces = clause.replace(/\{[^}]*\}/, '').replace(/,/g, ' ').trim();
|
|
187
|
+
for (const token of withoutBraces.split(/\s+/)) {
|
|
188
|
+
if (token === '*' || token === 'as' || token === '')
|
|
189
|
+
continue;
|
|
190
|
+
importedNames.add(token);
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
const missingImports = [];
|
|
194
|
+
for (const name of usedComponents) {
|
|
195
|
+
if (importedNames.has(name))
|
|
196
|
+
continue;
|
|
197
|
+
const def = componentDefinitions[name];
|
|
198
|
+
if (!def)
|
|
199
|
+
continue;
|
|
200
|
+
const rel = relativeImportPath(filePath, def.file);
|
|
201
|
+
missingImports.push(`import ${name} from '${rel}'`);
|
|
202
|
+
}
|
|
203
|
+
if (missingImports.length === 0)
|
|
204
|
+
return content;
|
|
205
|
+
const importBlock = missingImports.join('\n');
|
|
206
|
+
if (lastImportEnd >= 0) {
|
|
207
|
+
return content.slice(0, lastImportEnd) + '\n' + importBlock + content.slice(lastImportEnd);
|
|
208
|
+
}
|
|
209
|
+
return importBlock + '\n\n' + content;
|
|
210
|
+
}
|
|
211
|
+
async function detectCollectionMarkdownLayout(deps, collection) {
|
|
212
|
+
const existingLayout = await inferLayoutFromExistingEntries(deps, collection);
|
|
213
|
+
if (existingLayout)
|
|
214
|
+
return existingLayout;
|
|
215
|
+
const configLayout = await inferLayoutFromContentConfig(deps, collection);
|
|
216
|
+
if (configLayout)
|
|
217
|
+
return configLayout;
|
|
218
|
+
return 'flat';
|
|
219
|
+
}
|
|
220
|
+
async function inferLayoutFromExistingEntries(deps, collection) {
|
|
221
|
+
const collectionPath = await resolveCollectionDir(deps, collection);
|
|
222
|
+
const dirEntries = await deps.fs.list(collectionPath);
|
|
223
|
+
if (dirEntries.length === 0)
|
|
224
|
+
return null;
|
|
225
|
+
let flatCount = 0;
|
|
226
|
+
const flatSlugs = new Set();
|
|
227
|
+
for (const entry of dirEntries) {
|
|
228
|
+
if (entry.isDirectory)
|
|
229
|
+
continue;
|
|
230
|
+
const match = entry.name.match(/^(.+)\.(md|mdx)$/);
|
|
231
|
+
if (!match)
|
|
232
|
+
continue;
|
|
233
|
+
flatCount++;
|
|
234
|
+
flatSlugs.add(match[1]);
|
|
235
|
+
}
|
|
236
|
+
const subdirs = dirEntries.filter(entry => entry.isDirectory && !entry.name.startsWith('_') && !entry.name.startsWith('.'));
|
|
237
|
+
const indexLookups = await Promise.all(subdirs.map(async (dir) => {
|
|
238
|
+
if (flatSlugs.has(dir.name))
|
|
239
|
+
return false;
|
|
240
|
+
for (const ext of MARKDOWN_EXTENSIONS) {
|
|
241
|
+
if (await deps.fs.exists(path.posix.join(collectionPath, dir.name, `index.${ext}`)))
|
|
242
|
+
return true;
|
|
243
|
+
}
|
|
244
|
+
return false;
|
|
245
|
+
}));
|
|
246
|
+
const indexCount = indexLookups.filter(Boolean).length;
|
|
247
|
+
if (indexCount > flatCount)
|
|
248
|
+
return 'index';
|
|
249
|
+
if (flatCount > 0)
|
|
250
|
+
return 'flat';
|
|
251
|
+
return null;
|
|
252
|
+
}
|
|
253
|
+
async function inferLayoutFromContentConfig(deps, collection) {
|
|
254
|
+
const parsed = await parseContentConfig(deps.fs, deps.parseCache);
|
|
255
|
+
const pattern = parsed.get(collection)?.loaderPattern;
|
|
256
|
+
if (!pattern)
|
|
257
|
+
return null;
|
|
258
|
+
return isIndexStyleGlobPattern(pattern) ? 'index' : 'flat';
|
|
259
|
+
}
|
|
260
|
+
function isIndexStyleGlobPattern(pattern) {
|
|
261
|
+
return pattern.includes('index.{') || pattern.includes('*/index') || pattern.includes('**/index');
|
|
262
|
+
}
|
|
263
|
+
// ============================================================================
|
|
264
|
+
// Derived-field recompute
|
|
265
|
+
// ============================================================================
|
|
266
|
+
/**
|
|
267
|
+
* Recompute the collection's **declared** derived fields from `frontmatter`, returning the
|
|
268
|
+
* frontmatter that should actually be written.
|
|
269
|
+
*
|
|
270
|
+
* This lives here — under every write path — on purpose. The recompute used to exist only in
|
|
271
|
+
* the preview editor's form state (`computeDerivedUpdates` in `@nuasite/cms`), so anything
|
|
272
|
+
* writing through the sidecar, the dash or an agent left derived fields holding whatever the
|
|
273
|
+
* previous value was. The editor keeps its copy for instant in-form feedback; this one is
|
|
274
|
+
* authoritative.
|
|
275
|
+
*
|
|
276
|
+
* Rules, all shared with `missingRequiredFields` and enforced by running *before* it:
|
|
277
|
+
*
|
|
278
|
+
* - The input is the **merged** frontmatter (what lands on disk), never the incoming patch —
|
|
279
|
+
* so an update touching only the source field still refreshes the derived one.
|
|
280
|
+
* - A missing, non-string or blank source leaves the derived value untouched; see
|
|
281
|
+
* `computeDerivedFieldUpdates`.
|
|
282
|
+
* - Only `derivedFrom` **declared in the content config** is recomputed. The scanner's
|
|
283
|
+
* `detectDerivedHrefFields` guess deliberately stays out of the write path: it is a
|
|
284
|
+
* heuristic over at most three sampled values, and letting it overwrite files would turn a
|
|
285
|
+
* coincidence into data loss. Declaring the field opts into the recompute.
|
|
286
|
+
* - Only **top-level** fields derive. A `derivedFrom` on a nested field is dropped at parse
|
|
287
|
+
* time (with a warning) — see `content-config-ast.ts` — so nothing here has to guess what
|
|
288
|
+
* a source name would mean inside an object.
|
|
289
|
+
* - `patch` is the incoming update, and its absence means "this is a create". On an update
|
|
290
|
+
* only the fields `shouldRecomputeOnUpdate` accepts are touched; on a create everything
|
|
291
|
+
* declared is computed, because the file does not exist yet and has no authored value to
|
|
292
|
+
* preserve.
|
|
293
|
+
*
|
|
294
|
+
* Reads the config the same way `missingRequiredFields` does (`parseContentConfig` +
|
|
295
|
+
* `deps.parseCache`), so no new dependency enters `EntryOpsDeps`.
|
|
296
|
+
*/
|
|
297
|
+
async function applyDerivedFields(deps, collection, frontmatter, patch) {
|
|
298
|
+
const parsed = await parseContentConfig(deps.fs, deps.parseCache);
|
|
299
|
+
const parsedCollection = parsed.get(collection);
|
|
300
|
+
if (!parsedCollection)
|
|
301
|
+
return frontmatter;
|
|
302
|
+
const updates = computeDerivedFieldUpdates(parsedCollection.fields
|
|
303
|
+
.filter(field => patch === undefined || shouldRecomputeOnUpdate(field, frontmatter, patch))
|
|
304
|
+
.map(field => ({
|
|
305
|
+
name: field.name,
|
|
306
|
+
derivedFrom: field.layout?.derivedFrom,
|
|
307
|
+
derivedTransform: field.layout?.derivedTransform,
|
|
308
|
+
})), frontmatter);
|
|
309
|
+
if (Object.keys(updates).length === 0)
|
|
310
|
+
return frontmatter;
|
|
311
|
+
return { ...frontmatter, ...updates };
|
|
312
|
+
}
|
|
313
|
+
/**
|
|
314
|
+
* Fill a declared `slug` field from the file slug the create is about to write at.
|
|
315
|
+
*
|
|
316
|
+
* The rule itself is `withEntrySlug` in `cms-types`, shared with the create forms so the one they
|
|
317
|
+
* preview is the one that lands. This wrapper only supplies the collection's declared fields, read
|
|
318
|
+
* the same way `applyDerivedFields` and `missingRequiredFields` read them (`parseContentConfig` +
|
|
319
|
+
* `deps.parseCache`), so no new dependency enters `EntryOpsDeps`.
|
|
320
|
+
*
|
|
321
|
+
* Deliberately reads the *config*, not the scan: `scanCollections` infers a field from the entries
|
|
322
|
+
* that exist, and a collection whose first entry is being created has none to infer from.
|
|
323
|
+
*/
|
|
324
|
+
async function applyEntrySlugField(deps, collection, frontmatter, slug) {
|
|
325
|
+
const parsed = await parseContentConfig(deps.fs, deps.parseCache);
|
|
326
|
+
const parsedCollection = parsed.get(collection);
|
|
327
|
+
if (!parsedCollection)
|
|
328
|
+
return frontmatter;
|
|
329
|
+
return withEntrySlug(parsedCollection.fields, frontmatter, slug);
|
|
330
|
+
}
|
|
331
|
+
/**
|
|
332
|
+
* Whether an **update** should recompute this derived field, given the patch it carries and
|
|
333
|
+
* the merged frontmatter that would land on disk.
|
|
334
|
+
*
|
|
335
|
+
* Two cases, and nothing else:
|
|
336
|
+
*
|
|
337
|
+
* 1. The patch carries the source field. The derivation is what the source means, so a write
|
|
338
|
+
* that moves the source moves the derived value with it — even when the patch never names
|
|
339
|
+
* it. (`updateEntry({ frontmatter: { category } })` refreshing `categoryHref` is the whole
|
|
340
|
+
* point of the feature.)
|
|
341
|
+
* 2. The entry holds no derived value yet. Filling a hole is not an edit anybody has to
|
|
342
|
+
* notice, and it is what a create would have written.
|
|
343
|
+
*
|
|
344
|
+
* Everything else is left alone. An update that touches only the body, or only an unrelated
|
|
345
|
+
* field, must not rewrite a value the author put there by hand: `categoryHref:
|
|
346
|
+
* /kategorie/lide` overridden into `/lide` is a diff nobody asked for, produced by a save
|
|
347
|
+
* that had nothing to do with it. `createEntry` skips this check entirely — a new file has no
|
|
348
|
+
* hand-authored value to protect.
|
|
349
|
+
*/
|
|
350
|
+
function shouldRecomputeOnUpdate(field, frontmatter, patch) {
|
|
351
|
+
const source = field.layout?.derivedFrom;
|
|
352
|
+
if (source === undefined)
|
|
353
|
+
return false;
|
|
354
|
+
if (Object.hasOwn(patch, source))
|
|
355
|
+
return true;
|
|
356
|
+
return isBlankFieldValue(frontmatter[field.name]);
|
|
357
|
+
}
|
|
358
|
+
// ============================================================================
|
|
359
|
+
// Required-field validation
|
|
360
|
+
// ============================================================================
|
|
361
|
+
/**
|
|
362
|
+
* Names of the collection's **schema-declared** required fields left empty by `frontmatter`.
|
|
363
|
+
*
|
|
364
|
+
* The predicate itself lives in `editor-write-model.ts`, shared with the content check —
|
|
365
|
+
* see there for which fields the guard deliberately does not cover.
|
|
366
|
+
*
|
|
367
|
+
* Note on where `required` comes from — this reads the content config, never the
|
|
368
|
+
* scanner, and that is the whole point. `scanCollections` *infers* `required` as
|
|
369
|
+
* "the field is present in every scanned entry" (`mergeFieldObservations` in
|
|
370
|
+
* `collection-scanner.ts`), so a collection holding a single entry marks everything
|
|
371
|
+
* that entry happens to carry as required. Enforcing that as a hard invariant would
|
|
372
|
+
* make such a collection impossible to extend — a second entry with a different set
|
|
373
|
+
* of fields could never be written. Schema `required` has no such problem:
|
|
374
|
+
* `applyParsedConfig` filters the scanned fields down to the schema's names and
|
|
375
|
+
* `applyParsedFieldOverrides` then assigns `field.required = pf.required`
|
|
376
|
+
* unconditionally, so `.optional()` → `false` and everything else → `true`.
|
|
377
|
+
*
|
|
378
|
+
* A collection absent from `content.config.ts` therefore yields `[]` — nobody declared
|
|
379
|
+
* anything required there, so there is nothing to enforce and the write goes through.
|
|
380
|
+
*
|
|
381
|
+
* The rule itself lives in `blankRequiredFields` (`@nuasite/cms-types`), shared with every
|
|
382
|
+
* collections UI — including which fields are exempt, and why.
|
|
383
|
+
*/
|
|
384
|
+
async function missingRequiredFields(deps, collection, frontmatter) {
|
|
385
|
+
const parsed = await parseContentConfig(deps.fs, deps.parseCache);
|
|
386
|
+
const parsedCollection = parsed.get(collection);
|
|
387
|
+
if (!parsedCollection)
|
|
388
|
+
return [];
|
|
389
|
+
return blankRequiredFields(parsedCollection.fields, frontmatter);
|
|
390
|
+
}
|
|
391
|
+
/** Name the offending fields — the text reaches the UI verbatim, where "validation failed" would be useless. */
|
|
392
|
+
function missingRequiredMessage(missing) {
|
|
393
|
+
return missing.length === 1
|
|
394
|
+
? `Field "${missing[0]}" is required`
|
|
395
|
+
: `Required fields are empty: ${missing.join(', ')}`;
|
|
396
|
+
}
|
|
397
|
+
function errorMessage(error) {
|
|
398
|
+
return error instanceof Error ? error.message : String(error);
|
|
399
|
+
}
|
|
400
|
+
export async function getEntry(deps, collection, slug) {
|
|
401
|
+
const sourcePath = await resolveEntryPath(deps, collection, slug);
|
|
402
|
+
if (!sourcePath)
|
|
403
|
+
return null;
|
|
404
|
+
const raw = await deps.fs.readFile(sourcePath);
|
|
405
|
+
if (isDataFile(sourcePath)) {
|
|
406
|
+
const data = sourcePath.endsWith('.json') ? JSON.parse(raw) : yaml.parse(raw);
|
|
407
|
+
return {
|
|
408
|
+
content: '',
|
|
409
|
+
frontmatter: (data && typeof data === 'object') ? data : {},
|
|
410
|
+
sourcePath,
|
|
411
|
+
};
|
|
412
|
+
}
|
|
413
|
+
const { frontmatter, content } = parseFrontmatter(raw);
|
|
414
|
+
return { content, frontmatter, sourcePath };
|
|
415
|
+
}
|
|
416
|
+
export async function createEntry(deps, input) {
|
|
417
|
+
const { collection, slug, body = '' } = input;
|
|
418
|
+
// Before anything reads it: what the form left untouched is not written, and a list may not
|
|
419
|
+
// carry a blank item. See `normalizeCreateWrite` and `withoutBlankArrayItems` — an untouched
|
|
420
|
+
// optional object seeded as `{}`, or an unfilled row appended by "+ Add", fails the whole site build.
|
|
421
|
+
const declared = (await parseContentConfig(deps.fs, deps.parseCache)).get(collection)?.fields ?? [];
|
|
422
|
+
const frontmatter = withoutBlankArrayItems(normalizeCreateWrite(declared, input.frontmatter));
|
|
423
|
+
const normalizedSlug = slugify(slug);
|
|
424
|
+
if (!normalizedSlug) {
|
|
425
|
+
return { success: false, error: 'Could not generate a valid slug from the provided slug' };
|
|
426
|
+
}
|
|
427
|
+
const allowedExtensions = ['md', 'mdx', 'json', 'yaml', 'yml'];
|
|
428
|
+
const ext = input.fileExtension ?? 'md';
|
|
429
|
+
if (!allowedExtensions.includes(ext)) {
|
|
430
|
+
return { success: false, error: `Invalid file extension "${ext}". Allowed: ${allowedExtensions.join(', ')}` };
|
|
431
|
+
}
|
|
432
|
+
// The frontmatter copy of the slug first: this is the only place that knows the file name
|
|
433
|
+
// the entry is about to get, and `withEntrySlug` explains why a create is the only write
|
|
434
|
+
// allowed to fill it. Ahead of the derive on purpose — a field declared
|
|
435
|
+
// `derivedFrom: 'slug'` then computes off the address being written instead of the hole the
|
|
436
|
+
// caller left, which is the case that sent entries out with an empty `url_path`.
|
|
437
|
+
const seeded = await applyEntrySlugField(deps, collection, frontmatter, normalizedSlug);
|
|
438
|
+
// Derived fields next: a required-but-visible derived field must be judged on the value
|
|
439
|
+
// it is about to be given, not on the hole the caller left. `resolved` is what both
|
|
440
|
+
// branches below serialize, so the markdown and the data file agree by construction.
|
|
441
|
+
const resolved = await applyDerivedFields(deps, collection, seeded);
|
|
442
|
+
// Hard invariant, ahead of every path that could touch the disk — the markdown and
|
|
443
|
+
// the data branch below both write exactly `{ ...resolved }`, so one check covers
|
|
444
|
+
// `.md`/`.mdx` frontmatter and `.json`/`.yaml`/`.yml` data files alike.
|
|
445
|
+
const missing = await missingRequiredFields(deps, collection, resolved);
|
|
446
|
+
if (missing.length > 0) {
|
|
447
|
+
return { success: false, error: missingRequiredMessage(missing) };
|
|
448
|
+
}
|
|
449
|
+
const isData = ext === 'json' || ext === 'yaml' || ext === 'yml';
|
|
450
|
+
const layout = isData ? 'flat' : await detectCollectionMarkdownLayout(deps, collection);
|
|
451
|
+
const collectionDir = await resolveCollectionDir(deps, collection);
|
|
452
|
+
const sourcePath = layout === 'index'
|
|
453
|
+
? path.posix.join(collectionDir, normalizedSlug, `index.${ext}`)
|
|
454
|
+
: path.posix.join(collectionDir, `${normalizedSlug}.${ext}`);
|
|
455
|
+
let fileContent;
|
|
456
|
+
if (isData) {
|
|
457
|
+
fileContent = ext === 'json'
|
|
458
|
+
? JSON.stringify({ ...resolved }, null, 2) + '\n'
|
|
459
|
+
: yaml.stringify({ ...resolved });
|
|
460
|
+
}
|
|
461
|
+
else {
|
|
462
|
+
fileContent = serializeFrontmatter({ ...resolved }, body);
|
|
463
|
+
}
|
|
464
|
+
if (await deps.fs.exists(sourcePath)) {
|
|
465
|
+
return { success: false, error: `File already exists: ${sourcePath}` };
|
|
466
|
+
}
|
|
467
|
+
try {
|
|
468
|
+
await deps.fs.writeFile(sourcePath, fileContent);
|
|
469
|
+
return { success: true, sourcePath };
|
|
470
|
+
}
|
|
471
|
+
catch (error) {
|
|
472
|
+
return { success: false, error: errorMessage(error) };
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
export async function updateEntry(deps, input) {
|
|
476
|
+
const sourcePath = await resolveEntryPath(deps, input.collection, input.slug);
|
|
477
|
+
if (!sourcePath) {
|
|
478
|
+
return { success: false, error: `Entry not found: ${input.collection}/${input.slug}` };
|
|
479
|
+
}
|
|
480
|
+
// The incoming patch only — never the merged record. Cleaning what is already on disk would
|
|
481
|
+
// rewrite lists this edit never touched, and a save must change what the editor changed.
|
|
482
|
+
const patch = input.frontmatter === undefined ? undefined : withoutBlankArrayItems(input.frontmatter);
|
|
483
|
+
try {
|
|
484
|
+
if (isDataFile(sourcePath)) {
|
|
485
|
+
const raw = await deps.fs.readFile(sourcePath);
|
|
486
|
+
const existing = sourcePath.endsWith('.json') ? JSON.parse(raw) : yaml.parse(raw);
|
|
487
|
+
const merged = { ...(existing ?? {}), ...patch };
|
|
488
|
+
// Recompute from the merged result, so a patch that carries only the source field
|
|
489
|
+
// still refreshes the derived one. Ahead of the required check for the same reason
|
|
490
|
+
// as in `createEntry`. The patch goes along so a write that never touches a source
|
|
491
|
+
// leaves the value the author put there alone — see `shouldRecomputeOnUpdate`.
|
|
492
|
+
const resolved = await applyDerivedFields(deps, input.collection, merged, patch ?? {});
|
|
493
|
+
// Validate the merged result, not the incoming patch: a patch that omits a
|
|
494
|
+
// required field is fine when the file already carries it, and a patch that
|
|
495
|
+
// blanks one must be rejected even though the field itself is present.
|
|
496
|
+
const missing = await missingRequiredFields(deps, input.collection, resolved);
|
|
497
|
+
if (missing.length > 0) {
|
|
498
|
+
return { success: false, error: missingRequiredMessage(missing) };
|
|
499
|
+
}
|
|
500
|
+
const output = sourcePath.endsWith('.json')
|
|
501
|
+
? JSON.stringify(resolved, null, 2) + '\n'
|
|
502
|
+
: yaml.stringify(resolved);
|
|
503
|
+
await deps.fs.writeFile(sourcePath, output);
|
|
504
|
+
}
|
|
505
|
+
else {
|
|
506
|
+
const raw = await deps.fs.readFile(sourcePath);
|
|
507
|
+
const existing = parseFrontmatter(raw);
|
|
508
|
+
const mergedFrontmatter = {
|
|
509
|
+
...existing.frontmatter,
|
|
510
|
+
...patch,
|
|
511
|
+
};
|
|
512
|
+
// Same rule as the data branch: recompute the derived fields off the merged
|
|
513
|
+
// frontmatter — bounded by the patch, so a body-only save rewrites nothing — then
|
|
514
|
+
// validate what is actually going to disk.
|
|
515
|
+
const resolvedFrontmatter = await applyDerivedFields(deps, input.collection, mergedFrontmatter, patch ?? {});
|
|
516
|
+
const missing = await missingRequiredFields(deps, input.collection, resolvedFrontmatter);
|
|
517
|
+
if (missing.length > 0) {
|
|
518
|
+
return { success: false, error: missingRequiredMessage(missing) };
|
|
519
|
+
}
|
|
520
|
+
let finalContent = input.body ?? existing.content;
|
|
521
|
+
if (sourcePath.endsWith('.mdx')) {
|
|
522
|
+
// Resolve component definitions internally (no manifest needed): scan the
|
|
523
|
+
// component directories so MDX imports can be injected for used components.
|
|
524
|
+
const componentDefinitions = await deps.resolveComponentDefinitions();
|
|
525
|
+
finalContent = ensureMdxImports(finalContent, sourcePath, componentDefinitions);
|
|
526
|
+
}
|
|
527
|
+
await deps.fs.writeFile(sourcePath, serializeFrontmatter(resolvedFrontmatter, finalContent));
|
|
528
|
+
}
|
|
529
|
+
return { success: true, sourcePath };
|
|
530
|
+
}
|
|
531
|
+
catch (error) {
|
|
532
|
+
return { success: false, error: errorMessage(error) };
|
|
533
|
+
}
|
|
534
|
+
}
|
|
535
|
+
export async function deleteEntry(deps, collection, slug) {
|
|
536
|
+
const sourcePath = await resolveEntryPath(deps, collection, slug);
|
|
537
|
+
if (!sourcePath) {
|
|
538
|
+
return { success: false, error: `Entry not found: ${collection}/${slug}` };
|
|
539
|
+
}
|
|
540
|
+
try {
|
|
541
|
+
await deps.fs.remove(sourcePath);
|
|
542
|
+
return { success: true, sourcePath };
|
|
543
|
+
}
|
|
544
|
+
catch (error) {
|
|
545
|
+
return { success: false, error: errorMessage(error) };
|
|
546
|
+
}
|
|
547
|
+
}
|
|
548
|
+
export async function renameEntry(deps, collection, from, to) {
|
|
549
|
+
const sourcePath = await resolveEntryPath(deps, collection, from);
|
|
550
|
+
if (!sourcePath) {
|
|
551
|
+
return { success: false, error: `Entry not found: ${collection}/${from}` };
|
|
552
|
+
}
|
|
553
|
+
const normalizedSlug = slugify(to);
|
|
554
|
+
if (!normalizedSlug) {
|
|
555
|
+
return { success: false, error: 'Invalid slug' };
|
|
556
|
+
}
|
|
557
|
+
const { moveFrom, moveTo, previousSlug, newSourcePath } = renameTarget(sourcePath, from, normalizedSlug);
|
|
558
|
+
if (moveFrom === moveTo) {
|
|
559
|
+
return { success: true, sourcePath: newSourcePath };
|
|
560
|
+
}
|
|
561
|
+
if (await deps.fs.exists(moveTo)) {
|
|
562
|
+
return { success: false, error: `Already exists: ${normalizedSlug}` };
|
|
563
|
+
}
|
|
564
|
+
try {
|
|
565
|
+
await deps.fs.rename(moveFrom, moveTo);
|
|
566
|
+
}
|
|
567
|
+
catch (error) {
|
|
568
|
+
return { success: false, error: errorMessage(error) };
|
|
569
|
+
}
|
|
570
|
+
// Outside the try above, and deliberately: the file has moved, so the rename the caller asked
|
|
571
|
+
// for happened. Reporting `success: false` because the frontmatter touch-up hit something
|
|
572
|
+
// would leave the editor showing "rename failed" while pointing at a slug that no longer
|
|
573
|
+
// resolves. `syncRenamedEntrySlug` answers for itself instead — it never throws, and it
|
|
574
|
+
// declines rather than writing a file it did not fully understand.
|
|
575
|
+
await syncRenamedEntrySlug(deps, collection, newSourcePath, previousSlug, normalizedSlug);
|
|
576
|
+
return { success: true, sourcePath: newSourcePath };
|
|
577
|
+
}
|
|
578
|
+
/**
|
|
579
|
+
* Resolve a rename against the entry's layout.
|
|
580
|
+
*
|
|
581
|
+
* Two markdown layouts to answer for, and `createEntry` writes both (see
|
|
582
|
+
* `detectCollectionMarkdownLayout`): a flat `<slug>.md`, and a folder layout where the *directory*
|
|
583
|
+
* carries the slug and the file inside it is always `index.md`.
|
|
584
|
+
*
|
|
585
|
+
* The folder layout is identified the way `resolveEntryPath` found the file to begin with — an
|
|
586
|
+
* `index` file whose parent directory is named for the entry — and not by the file name alone. A
|
|
587
|
+
* flat entry may perfectly well be called `index.md` (a collection's own landing page usually is),
|
|
588
|
+
* `resolveEntryPath` checks the flat candidate first so that is what it resolves to, and reading
|
|
589
|
+
* `'index'` as "this is a folder layout" then treated the *collection* directory as the entry's:
|
|
590
|
+
* renaming it moved the file out of the collection entirely and left a stray directory at the
|
|
591
|
+
* content root.
|
|
592
|
+
*
|
|
593
|
+
* Where it is the folder layout, the folder is what moves. Colocating assets is the reason to use
|
|
594
|
+
* it, and `image()` and relative frontmatter paths resolve against the entry file — moving
|
|
595
|
+
* `index.md` alone would leave `cover: ./cover.jpg` pointing at a file that is no longer beside
|
|
596
|
+
* it, which fails the build rather than the rename.
|
|
597
|
+
*/
|
|
598
|
+
function renameTarget(sourcePath, from, normalizedSlug) {
|
|
599
|
+
const lastSlash = sourcePath.lastIndexOf('/');
|
|
600
|
+
const dir = lastSlash >= 0 ? sourcePath.slice(0, lastSlash) : '';
|
|
601
|
+
const fileName = lastSlash >= 0 ? sourcePath.slice(lastSlash + 1) : sourcePath;
|
|
602
|
+
const ext = fileExtension(fileName);
|
|
603
|
+
const baseName = fileName.slice(0, fileName.length - ext.length - 1);
|
|
604
|
+
const parentSlash = dir.lastIndexOf('/');
|
|
605
|
+
const dirName = parentSlash >= 0 ? dir.slice(parentSlash + 1) : dir;
|
|
606
|
+
if (baseName !== 'index' || dir === '' || dirName !== from) {
|
|
607
|
+
const newSourcePath = dir ? `${dir}/${normalizedSlug}.${ext}` : `${normalizedSlug}.${ext}`;
|
|
608
|
+
return { moveFrom: sourcePath, moveTo: newSourcePath, newSourcePath, previousSlug: baseName };
|
|
609
|
+
}
|
|
610
|
+
const parentDir = parentSlash >= 0 ? dir.slice(0, parentSlash) : '';
|
|
611
|
+
const newDir = parentDir ? `${parentDir}/${normalizedSlug}` : normalizedSlug;
|
|
612
|
+
return { moveFrom: dir, moveTo: newDir, newSourcePath: `${newDir}/index.${ext}`, previousSlug: dirName };
|
|
613
|
+
}
|
|
614
|
+
/**
|
|
615
|
+
* Move the frontmatter copy of the slug along with the file, and recompute what derives from it.
|
|
616
|
+
*
|
|
617
|
+
* `createEntry` seeds a declared `slug` field from the file name, which makes a rename the one
|
|
618
|
+
* operation that can leave the two copies disagreeing: the file becomes `vecirek-2026.md` while
|
|
619
|
+
* the frontmatter still says `vecirek-ve-vile`, and a `pathname` spec or a `derivedFrom: 'slug'`
|
|
620
|
+
* field goes on resolving the old URL. `withRenamedEntrySlug` decides whether the copy is the
|
|
621
|
+
* file's to move (see it for the cases it declines), and the derive runs with the new slug as its
|
|
622
|
+
* patch so it takes the same path an `updateEntry` that moved the source field would.
|
|
623
|
+
*
|
|
624
|
+
* Runs after the rename and writes through the new path, so nothing here depends on the entry
|
|
625
|
+
* being resolvable under its new slug yet. It touches the file only when something changed, and a
|
|
626
|
+
* collection with no declared `slug` field never reaches the write at all.
|
|
627
|
+
*/
|
|
628
|
+
async function syncRenamedEntrySlug(deps, collection, sourcePath, previousSlug, nextSlug) {
|
|
629
|
+
try {
|
|
630
|
+
const parsed = await parseContentConfig(deps.fs, deps.parseCache);
|
|
631
|
+
const parsedCollection = parsed.get(collection);
|
|
632
|
+
// No declared `slug` field, no copy to move — and the file is never opened, so a rename in
|
|
633
|
+
// every other collection stays the pure move it has always been.
|
|
634
|
+
if (!parsedCollection?.fields.some(field => field.name === ENTRY_SLUG_FIELD))
|
|
635
|
+
return;
|
|
636
|
+
const document = openEntryDocument(sourcePath, await deps.fs.readFile(sourcePath));
|
|
637
|
+
if (!document)
|
|
638
|
+
return;
|
|
639
|
+
const moved = withRenamedEntrySlug(parsedCollection.fields, document.record, previousSlug, nextSlug);
|
|
640
|
+
if (moved === document.record)
|
|
641
|
+
return;
|
|
642
|
+
const resolved = await applyDerivedFields(deps, collection, moved, { [ENTRY_SLUG_FIELD]: nextSlug });
|
|
643
|
+
const updates = changedTextKeys(document.record, resolved);
|
|
644
|
+
if (Object.keys(updates).length === 0)
|
|
645
|
+
return;
|
|
646
|
+
await deps.fs.writeFile(sourcePath, document.withKeys(updates));
|
|
647
|
+
}
|
|
648
|
+
catch {
|
|
649
|
+
// The rename itself is done and correct; this is the copy catching up. Leaving it stale is
|
|
650
|
+
// the state every entry was in before the rule existed, and it is the only outcome here
|
|
651
|
+
// that cannot make things worse — so a failure to read or write is swallowed rather than
|
|
652
|
+
// turned into a half-applied entry or a rename reported as failed.
|
|
653
|
+
}
|
|
654
|
+
}
|
|
655
|
+
/** The string-valued keys `after` changed, which is all this write path ever produces. */
|
|
656
|
+
function changedTextKeys(before, after) {
|
|
657
|
+
const updates = {};
|
|
658
|
+
for (const [key, value] of Object.entries(after)) {
|
|
659
|
+
if (typeof value === 'string' && value !== before[key])
|
|
660
|
+
updates[key] = value;
|
|
661
|
+
}
|
|
662
|
+
return updates;
|
|
663
|
+
}
|
|
664
|
+
/**
|
|
665
|
+
* Open an entry for a *targeted* frontmatter edit, or decline.
|
|
666
|
+
*
|
|
667
|
+
* Two reasons this exists rather than `parseFrontmatter` → `serializeFrontmatter`, and both are
|
|
668
|
+
* about a rename being a move, not an edit:
|
|
669
|
+
*
|
|
670
|
+
* - **Comments survive.** `serializeFrontmatter` builds a fresh `yaml.Document` from a plain
|
|
671
|
+
* object, which drops every comment in the block — including the `@position` and `@group`
|
|
672
|
+
* directives `parseFieldDirectives` reads back as layout. A rename that silently restyled the
|
|
673
|
+
* author's frontmatter would be a worse bug than the stale slug it set out to fix.
|
|
674
|
+
* - **An unparseable file is left alone.** `parseFrontmatter` reports invalid YAML as `{}`, and a
|
|
675
|
+
* writer that believes it rewrites the entry down to the one key it just filled in. `null` here
|
|
676
|
+
* means "not understood", and nothing downstream may write.
|
|
677
|
+
*/
|
|
678
|
+
function openEntryDocument(sourcePath, raw) {
|
|
679
|
+
if (sourcePath.endsWith('.json')) {
|
|
680
|
+
let parsed;
|
|
681
|
+
try {
|
|
682
|
+
parsed = JSON.parse(raw);
|
|
683
|
+
}
|
|
684
|
+
catch {
|
|
685
|
+
return null;
|
|
686
|
+
}
|
|
687
|
+
if (!isPlainRecord(parsed))
|
|
688
|
+
return null;
|
|
689
|
+
const record = parsed;
|
|
690
|
+
return { record, withKeys: updates => JSON.stringify({ ...record, ...updates }, null, 2) + '\n' };
|
|
691
|
+
}
|
|
692
|
+
if (isDataFile(sourcePath))
|
|
693
|
+
return openYamlDocument(raw, block => block);
|
|
694
|
+
const leading = raw.length - raw.trimStart().length;
|
|
695
|
+
const lines = raw.slice(leading).split('\n');
|
|
696
|
+
if (lines[0]?.trimEnd() !== '---')
|
|
697
|
+
return null;
|
|
698
|
+
const endLineIndex = lines.findIndex((line, index) => index > 0 && line.trimEnd() === '---');
|
|
699
|
+
if (endLineIndex === -1)
|
|
700
|
+
return null;
|
|
701
|
+
const body = lines.slice(endLineIndex + 1).join('\n');
|
|
702
|
+
return openYamlDocument(lines.slice(1, endLineIndex).join('\n'), block => `---\n${block.trimEnd()}\n---\n${body}`);
|
|
703
|
+
}
|
|
704
|
+
/** A YAML source and the file it sits in, edited key by key so the document's own formatting stays. */
|
|
705
|
+
function openYamlDocument(source, reassemble) {
|
|
706
|
+
const doc = yaml.parseDocument(source);
|
|
707
|
+
if (doc.errors.length > 0)
|
|
708
|
+
return null;
|
|
709
|
+
const parsed = doc.toJS();
|
|
710
|
+
// An empty block parses to `null` and is a map waiting to happen — `doc.set` creates it. A
|
|
711
|
+
// block that parses to a list or a scalar is something else entirely, and not ours to edit.
|
|
712
|
+
if (parsed !== null && !isPlainRecord(parsed))
|
|
713
|
+
return null;
|
|
714
|
+
return {
|
|
715
|
+
record: parsed ?? {},
|
|
716
|
+
withKeys(updates) {
|
|
717
|
+
for (const [key, value] of Object.entries(updates)) {
|
|
718
|
+
const scalar = new yaml.Scalar(value);
|
|
719
|
+
// The quoting `serializeFrontmatter` applies, for the same reason: an unquoted
|
|
720
|
+
// `2026-01-01` reads back as a Date, and a slug is a string.
|
|
721
|
+
if (YAML_DATE_PATTERN.test(value))
|
|
722
|
+
scalar.type = yaml.Scalar.QUOTE_SINGLE;
|
|
723
|
+
doc.set(key, scalar);
|
|
724
|
+
}
|
|
725
|
+
return reassemble(doc.toString());
|
|
726
|
+
},
|
|
727
|
+
};
|
|
728
|
+
}
|
|
729
|
+
/**
|
|
730
|
+
* Read the entry's frontmatter/data object as a plain object, plus the markdown
|
|
731
|
+
* body (empty for data files). Returns the resolved source path so callers can
|
|
732
|
+
* write back through the same representation.
|
|
733
|
+
*/
|
|
734
|
+
async function loadEntryFrontmatter(deps, collection, slug) {
|
|
735
|
+
const sourcePath = await resolveEntryPath(deps, collection, slug);
|
|
736
|
+
if (!sourcePath)
|
|
737
|
+
return null;
|
|
738
|
+
const raw = await deps.fs.readFile(sourcePath);
|
|
739
|
+
if (isDataFile(sourcePath)) {
|
|
740
|
+
const parsed = sourcePath.endsWith('.json') ? JSON.parse(raw) : yaml.parse(raw);
|
|
741
|
+
return { sourcePath, frontmatter: (parsed && typeof parsed === 'object') ? parsed : {}, body: '', data: true };
|
|
742
|
+
}
|
|
743
|
+
const { frontmatter, content } = parseFrontmatter(raw);
|
|
744
|
+
return { sourcePath, frontmatter, body: content, data: false };
|
|
745
|
+
}
|
|
746
|
+
async function writeEntryFrontmatter(deps, loaded) {
|
|
747
|
+
if (loaded.data) {
|
|
748
|
+
const output = loaded.sourcePath.endsWith('.json')
|
|
749
|
+
? JSON.stringify(loaded.frontmatter, null, 2) + '\n'
|
|
750
|
+
: yaml.stringify(loaded.frontmatter);
|
|
751
|
+
await deps.fs.writeFile(loaded.sourcePath, output);
|
|
752
|
+
return;
|
|
753
|
+
}
|
|
754
|
+
await deps.fs.writeFile(loaded.sourcePath, serializeFrontmatter(loaded.frontmatter, loaded.body));
|
|
755
|
+
}
|
|
756
|
+
/**
|
|
757
|
+
* The item fields a repeater declares in `content.config.ts`, or `[]` when it declares none.
|
|
758
|
+
*
|
|
759
|
+
* Only top-level repeaters are resolved, which is the only shape `addArrayItem` is called for.
|
|
760
|
+
*/
|
|
761
|
+
async function repeaterItemFields(deps, collection, field) {
|
|
762
|
+
const parsed = await parseContentConfig(deps.fs, deps.parseCache);
|
|
763
|
+
const declared = parsed.get(collection)?.fields.find(candidate => candidate.name === field);
|
|
764
|
+
if (!declared || declared.type !== 'array' || declared.itemType !== 'object')
|
|
765
|
+
return [];
|
|
766
|
+
return (declared.fields ?? []).map(item => ({
|
|
767
|
+
name: item.name,
|
|
768
|
+
type: item.type,
|
|
769
|
+
required: item.required,
|
|
770
|
+
hidden: item.layout?.hidden,
|
|
771
|
+
}));
|
|
772
|
+
}
|
|
773
|
+
/**
|
|
774
|
+
* Seed the required keys a client left out of an appended item.
|
|
775
|
+
*
|
|
776
|
+
* The backstop for the "+ Add" hole. Both first-party editors now send a seeded item, but this
|
|
777
|
+
* path is reachable by any client — an older editor, a script, the HTTP API directly — and an
|
|
778
|
+
* item missing a required key is frontmatter the next build refuses. Whatever the client did
|
|
779
|
+
* send wins: this only adds keys, never rewrites a value someone chose.
|
|
780
|
+
*/
|
|
781
|
+
function seedItem(value, fields) {
|
|
782
|
+
if (fields.length === 0 || typeof value !== 'object' || value === null || Array.isArray(value))
|
|
783
|
+
return value;
|
|
784
|
+
const item = { ...value };
|
|
785
|
+
for (const [key, seeded] of Object.entries(newRepeaterItem(fields))) {
|
|
786
|
+
if (!Object.hasOwn(item, key) || item[key] === undefined)
|
|
787
|
+
item[key] = seeded;
|
|
788
|
+
}
|
|
789
|
+
return item;
|
|
790
|
+
}
|
|
791
|
+
export async function addArrayItem(deps, input) {
|
|
792
|
+
const loaded = await loadEntryFrontmatter(deps, input.collection, input.slug);
|
|
793
|
+
if (!loaded) {
|
|
794
|
+
return { success: false, error: `Entry not found: ${input.collection}/${input.slug}` };
|
|
795
|
+
}
|
|
796
|
+
const current = loaded.frontmatter[input.field];
|
|
797
|
+
const array = Array.isArray(current) ? current.slice() : current === undefined ? [] : null;
|
|
798
|
+
if (array === null) {
|
|
799
|
+
return { success: false, error: `Field "${input.field}" is not an array` };
|
|
800
|
+
}
|
|
801
|
+
// A field may be absent; an item in a list may not, so a blank one is frontmatter the next
|
|
802
|
+
// build refuses. Refused rather than dropped: a client that asked for an append should not
|
|
803
|
+
// be told it happened when nothing was written.
|
|
804
|
+
if (isBlankFieldValue(input.value)) {
|
|
805
|
+
return { success: false, error: `Refusing to append an empty item to "${input.field}" — fill it in, or leave the list alone` };
|
|
806
|
+
}
|
|
807
|
+
const index = input.index ?? array.length;
|
|
808
|
+
const clamped = Math.max(0, Math.min(index, array.length));
|
|
809
|
+
array.splice(clamped, 0, seedItem(input.value, await repeaterItemFields(deps, input.collection, input.field)));
|
|
810
|
+
loaded.frontmatter[input.field] = array;
|
|
811
|
+
try {
|
|
812
|
+
await writeEntryFrontmatter(deps, loaded);
|
|
813
|
+
return { success: true, sourcePath: loaded.sourcePath };
|
|
814
|
+
}
|
|
815
|
+
catch (error) {
|
|
816
|
+
return { success: false, error: errorMessage(error) };
|
|
817
|
+
}
|
|
818
|
+
}
|
|
819
|
+
export async function removeArrayItem(deps, input) {
|
|
820
|
+
const loaded = await loadEntryFrontmatter(deps, input.collection, input.slug);
|
|
821
|
+
if (!loaded) {
|
|
822
|
+
return { success: false, error: `Entry not found: ${input.collection}/${input.slug}` };
|
|
823
|
+
}
|
|
824
|
+
const current = loaded.frontmatter[input.field];
|
|
825
|
+
if (!Array.isArray(current)) {
|
|
826
|
+
return { success: false, error: `Field "${input.field}" is not an array` };
|
|
827
|
+
}
|
|
828
|
+
if (input.index < 0 || input.index >= current.length) {
|
|
829
|
+
return { success: false, error: `Index out of bounds: ${input.index}` };
|
|
830
|
+
}
|
|
831
|
+
const array = current.slice();
|
|
832
|
+
array.splice(input.index, 1);
|
|
833
|
+
loaded.frontmatter[input.field] = array;
|
|
834
|
+
try {
|
|
835
|
+
await writeEntryFrontmatter(deps, loaded);
|
|
836
|
+
return { success: true, sourcePath: loaded.sourcePath };
|
|
837
|
+
}
|
|
838
|
+
catch (error) {
|
|
839
|
+
return { success: false, error: errorMessage(error) };
|
|
840
|
+
}
|
|
841
|
+
}
|
|
842
|
+
/** Re-export for tests / parity consumers needing the collection's entry list. */
|
|
843
|
+
export async function listCollectionEntries(deps, collection) {
|
|
844
|
+
const collections = await scanCollections(deps.fs, deps.contentDir, deps.parseCache);
|
|
845
|
+
return collections[collection]?.entries ?? [];
|
|
846
|
+
}
|