@prunellejs/cms 0.0.0-stage → 0.5.3
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/llms.txt +67 -0
- package/package.json +24 -4
- package/src/assets-js.ts +101 -0
- package/src/assets.ts +576 -0
- package/src/form-data.ts +464 -0
- package/src/handlers.ts +397 -0
- package/src/index.ts +99 -0
- package/src/inline-css.ts +621 -0
- package/src/inline-dom-js.ts +166 -0
- package/src/inline-form-js.ts +465 -0
- package/src/inline-handlers.ts +243 -0
- package/src/inline-js.ts +547 -0
- package/src/render.ts +583 -0
- package/src/sanitize.ts +150 -0
- package/src/schema.ts +487 -0
- package/src/shared.ts +119 -0
- package/README.md +0 -3
package/src/form-data.ts
ADDED
|
@@ -0,0 +1,464 @@
|
|
|
1
|
+
// FormData parsing, coercion, no-JS repeatable row actions, YAML serialization, and safe file-path resolution.
|
|
2
|
+
|
|
3
|
+
import type { ContentCollectionDescriptor } from 'prunelle/config'
|
|
4
|
+
import type { CmsField } from './schema'
|
|
5
|
+
import { existsSync, lstatSync, readlinkSync, realpathSync } from 'node:fs'
|
|
6
|
+
import { dirname, resolve } from 'node:path'
|
|
7
|
+
import { isInside } from 'prunelle/config'
|
|
8
|
+
|
|
9
|
+
const FORBIDDEN_PATH_SEGMENTS = new Set(['__proto__', 'constructor', 'prototype'])
|
|
10
|
+
|
|
11
|
+
const SAFE_LOCALE_RE = /^[a-zA-Z0-9_-]{1,32}$/
|
|
12
|
+
const SAFE_SLUG_SEG_RE = /^[a-zA-Z0-9][a-zA-Z0-9._-]*$/
|
|
13
|
+
const YAML_PLAIN_SAFE_RE = /^[a-zA-Z0-9][a-zA-Z0-9 _./@+-]*$/
|
|
14
|
+
const YAML_RESERVED_RE = /^(?:true|false|yes|no|on|off|null|~|[-+]?(?:\d+\.?\d*|\.\d+)(?:e[-+]?\d+)?|0x[0-9a-f]+|0o[0-7]+|\.inf|-\.inf|\.nan)$/i
|
|
15
|
+
const MAX_REPEATABLE_ROWS = 500
|
|
16
|
+
|
|
17
|
+
export interface ParsedRowAction {
|
|
18
|
+
readonly op: 'add' | 'remove' | 'up' | 'down'
|
|
19
|
+
readonly path: string
|
|
20
|
+
readonly index?: number | undefined
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export interface ResolvedEntryPath {
|
|
24
|
+
readonly ok: true
|
|
25
|
+
readonly filePath: string
|
|
26
|
+
readonly slug: string
|
|
27
|
+
readonly locale?: string | undefined
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export interface EntryPathError {
|
|
31
|
+
readonly ok: false
|
|
32
|
+
readonly status: 400 | 403
|
|
33
|
+
readonly message: string
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Validates a slug (allowing nested `a/b/c` paths) and rejects traversal, empty segments, and unsafe characters. */
|
|
37
|
+
export function validateSlug(raw: string): { ok: true, slug: string } | { ok: false, message: string } {
|
|
38
|
+
const trimmed = raw.trim()
|
|
39
|
+
if (trimmed.length === 0)
|
|
40
|
+
return { ok: false, message: 'Slug is required.' }
|
|
41
|
+
if (trimmed.startsWith('/') || trimmed.endsWith('/') || trimmed.includes('\\') || trimmed.includes('\0'))
|
|
42
|
+
return { ok: false, message: 'Slug contains invalid path characters.' }
|
|
43
|
+
const clean = trimmed.replace(/\.(?:md|markdown)$/i, '')
|
|
44
|
+
const segments = clean.split('/')
|
|
45
|
+
for (const seg of segments) {
|
|
46
|
+
if (seg.length === 0 || seg === '.' || seg === '..' || !SAFE_SLUG_SEG_RE.test(seg))
|
|
47
|
+
return { ok: false, message: `Slug segment "${seg}" is invalid.` }
|
|
48
|
+
}
|
|
49
|
+
return { ok: true, slug: segments.join('/') }
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** Validates a locale identifier against safe characters and optional collection allowlist. */
|
|
53
|
+
export function validateLocale(
|
|
54
|
+
col: ContentCollectionDescriptor,
|
|
55
|
+
rawLocale: string | undefined,
|
|
56
|
+
): { ok: true, locale: string | undefined } | { ok: false, message: string } {
|
|
57
|
+
if (!col.localized)
|
|
58
|
+
return { ok: true, locale: undefined }
|
|
59
|
+
const locale = (rawLocale ?? '').trim() || col.defaultLocale
|
|
60
|
+
if (!SAFE_LOCALE_RE.test(locale))
|
|
61
|
+
return { ok: false, message: `Invalid locale "${locale}".` }
|
|
62
|
+
if (col.locales !== undefined && col.locales.length > 0 && !col.locales.includes(locale))
|
|
63
|
+
return { ok: false, message: `Unknown locale "${locale}" for collection "${col.name}".` }
|
|
64
|
+
return { ok: true, locale }
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function closestExistingDir(targetPath: string): string {
|
|
68
|
+
let cur = dirname(targetPath)
|
|
69
|
+
while (!existsSync(cur)) {
|
|
70
|
+
const parent = dirname(cur)
|
|
71
|
+
if (parent === cur)
|
|
72
|
+
break
|
|
73
|
+
cur = parent
|
|
74
|
+
}
|
|
75
|
+
return cur
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function isPathConfined(targetPath: string, baseDir: string, realBase: string, depth = 0): boolean {
|
|
79
|
+
if (depth > 16)
|
|
80
|
+
return false
|
|
81
|
+
const realAncestor = realpathSync(closestExistingDir(targetPath))
|
|
82
|
+
if (!isInside(realBase, realAncestor, { orSame: true }))
|
|
83
|
+
return false
|
|
84
|
+
|
|
85
|
+
let cur = targetPath
|
|
86
|
+
while (cur !== baseDir && isInside(baseDir, cur)) {
|
|
87
|
+
try {
|
|
88
|
+
const stat = lstatSync(cur)
|
|
89
|
+
if (stat.isSymbolicLink()) {
|
|
90
|
+
const allowSame = cur !== targetPath
|
|
91
|
+
if (existsSync(cur)) {
|
|
92
|
+
if (!isInside(realBase, realpathSync(cur), { orSame: allowSame }))
|
|
93
|
+
return false
|
|
94
|
+
}
|
|
95
|
+
else {
|
|
96
|
+
const realParent = realpathSync(dirname(cur))
|
|
97
|
+
const linkTarget = resolve(realParent, readlinkSync(cur))
|
|
98
|
+
if (!isInside(realBase, linkTarget, { orSame: allowSame }))
|
|
99
|
+
return false
|
|
100
|
+
if (!isPathConfined(linkTarget, realBase, realBase, depth + 1))
|
|
101
|
+
return false
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
catch (err) {
|
|
106
|
+
const code = (err as NodeJS.ErrnoException).code
|
|
107
|
+
if (code !== 'ENOENT' && code !== 'ENOTDIR')
|
|
108
|
+
return false
|
|
109
|
+
}
|
|
110
|
+
const parent = dirname(cur)
|
|
111
|
+
if (parent === cur)
|
|
112
|
+
break
|
|
113
|
+
cur = parent
|
|
114
|
+
}
|
|
115
|
+
return true
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** Resolves a Markdown file path strictly confined inside `col.dir`, preventing path and symlink traversal. */
|
|
119
|
+
export function resolveEntryFilePath(
|
|
120
|
+
col: ContentCollectionDescriptor,
|
|
121
|
+
rawSlug: string,
|
|
122
|
+
rawLocale: string | undefined,
|
|
123
|
+
existingFile?: string | undefined,
|
|
124
|
+
): ResolvedEntryPath | EntryPathError {
|
|
125
|
+
if (col.dir === undefined)
|
|
126
|
+
return { ok: false, status: 403, message: `Collection "${col.name}" is read-only (no filesystem directory).` }
|
|
127
|
+
|
|
128
|
+
const slugCheck = validateSlug(rawSlug)
|
|
129
|
+
if (!slugCheck.ok)
|
|
130
|
+
return { ok: false, status: 400, message: slugCheck.message }
|
|
131
|
+
|
|
132
|
+
const localeCheck = validateLocale(col, rawLocale)
|
|
133
|
+
if (!localeCheck.ok)
|
|
134
|
+
return { ok: false, status: 400, message: localeCheck.message }
|
|
135
|
+
|
|
136
|
+
const baseDir = resolve(col.dir)
|
|
137
|
+
const candidate = existingFile !== undefined
|
|
138
|
+
? resolve(existingFile)
|
|
139
|
+
: resolve(
|
|
140
|
+
baseDir,
|
|
141
|
+
...(localeCheck.locale !== undefined ? [localeCheck.locale] : []),
|
|
142
|
+
`${slugCheck.slug}.md`,
|
|
143
|
+
)
|
|
144
|
+
|
|
145
|
+
if (!isInside(baseDir, candidate))
|
|
146
|
+
return { ok: false, status: 400, message: 'Refused path outside collection directory.' }
|
|
147
|
+
|
|
148
|
+
if (existsSync(baseDir)) {
|
|
149
|
+
const realBase = realpathSync(baseDir)
|
|
150
|
+
if (!isPathConfined(candidate, baseDir, realBase))
|
|
151
|
+
return { ok: false, status: 403, message: 'Refused symlink escaping collection directory.' }
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
return { ok: true, filePath: candidate, slug: slugCheck.slug, locale: localeCheck.locale }
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
function getStringField(formData: FormData, name: string): string | null {
|
|
158
|
+
const val = formData.get(name)
|
|
159
|
+
return typeof val === 'string' ? val : null
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
function findObjectArrayCount(formData: FormData, fieldName: string): number {
|
|
163
|
+
let count = 0
|
|
164
|
+
const declared = getStringField(formData, `__rows:${fieldName}`)
|
|
165
|
+
if (declared !== null) {
|
|
166
|
+
const parsed = Number.parseInt(declared, 10)
|
|
167
|
+
if (Number.isFinite(parsed) && parsed > 0)
|
|
168
|
+
count = Math.min(parsed, MAX_REPEATABLE_ROWS)
|
|
169
|
+
}
|
|
170
|
+
const prefix = `${fieldName}[`
|
|
171
|
+
for (const key of formData.keys()) {
|
|
172
|
+
if (!key.startsWith(prefix))
|
|
173
|
+
continue
|
|
174
|
+
const closeIdx = key.indexOf(']', prefix.length)
|
|
175
|
+
if (closeIdx === -1)
|
|
176
|
+
continue
|
|
177
|
+
const idx = Number.parseInt(key.slice(prefix.length, closeIdx), 10)
|
|
178
|
+
if (Number.isFinite(idx) && idx >= 0 && idx < MAX_REPEATABLE_ROWS)
|
|
179
|
+
count = Math.max(count, idx + 1)
|
|
180
|
+
}
|
|
181
|
+
return count
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
function parseFieldEntry(formData: FormData, field: CmsField, name: string): { value: unknown, present: boolean } {
|
|
185
|
+
switch (field.kind) {
|
|
186
|
+
case 'boolean': {
|
|
187
|
+
const raw = getStringField(formData, name)
|
|
188
|
+
return { value: raw === 'true' || raw === 'on' || raw === '1', present: raw !== null }
|
|
189
|
+
}
|
|
190
|
+
case 'number':
|
|
191
|
+
case 'integer': {
|
|
192
|
+
const raw = getStringField(formData, name)
|
|
193
|
+
if (raw === null)
|
|
194
|
+
return { value: undefined, present: false }
|
|
195
|
+
const trimmed = raw.trim()
|
|
196
|
+
if (trimmed === '')
|
|
197
|
+
return { value: undefined, present: false }
|
|
198
|
+
const num = Number(trimmed)
|
|
199
|
+
return { value: Number.isFinite(num) ? num : raw, present: true }
|
|
200
|
+
}
|
|
201
|
+
case 'enum': {
|
|
202
|
+
const raw = getStringField(formData, name)
|
|
203
|
+
if (raw === null || (raw === '' && !field.required))
|
|
204
|
+
return { value: undefined, present: false }
|
|
205
|
+
if (raw === '')
|
|
206
|
+
return { value: '', present: false }
|
|
207
|
+
if (field.enumType === 'number') {
|
|
208
|
+
const num = Number(raw)
|
|
209
|
+
return { value: Number.isFinite(num) ? num : raw, present: true }
|
|
210
|
+
}
|
|
211
|
+
return { value: raw, present: true }
|
|
212
|
+
}
|
|
213
|
+
case 'tags': {
|
|
214
|
+
const all = formData.getAll(name).filter((v): v is string => typeof v === 'string')
|
|
215
|
+
if (all.length === 0)
|
|
216
|
+
return { value: undefined, present: false }
|
|
217
|
+
const tags: string[] = []
|
|
218
|
+
for (const chunk of all) {
|
|
219
|
+
for (const item of chunk.split(/[,\r\n]+/)) {
|
|
220
|
+
const clean = item.trim()
|
|
221
|
+
if (clean.length > 0)
|
|
222
|
+
tags.push(clean)
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
return { value: tags, present: tags.length > 0 }
|
|
226
|
+
}
|
|
227
|
+
case 'object': {
|
|
228
|
+
const nested: Record<string, unknown> = {}
|
|
229
|
+
let hasAny = false
|
|
230
|
+
for (const child of field.fields ?? []) {
|
|
231
|
+
const entry = parseFieldEntry(formData, child, `${name}.${child.key}`)
|
|
232
|
+
if (entry.value !== undefined)
|
|
233
|
+
nested[child.key] = entry.value
|
|
234
|
+
if (entry.present)
|
|
235
|
+
hasAny = true
|
|
236
|
+
}
|
|
237
|
+
if (hasAny || field.required)
|
|
238
|
+
return { value: nested, present: hasAny }
|
|
239
|
+
return { value: undefined, present: false }
|
|
240
|
+
}
|
|
241
|
+
case 'object-array': {
|
|
242
|
+
const count = findObjectArrayCount(formData, name)
|
|
243
|
+
const rows: Record<string, unknown>[] = []
|
|
244
|
+
for (let i = 0; i < count; i++) {
|
|
245
|
+
const row: Record<string, unknown> = {}
|
|
246
|
+
for (const child of field.fields ?? []) {
|
|
247
|
+
const entry = parseFieldEntry(formData, child, `${name}[${i}].${child.key}`)
|
|
248
|
+
if (entry.value !== undefined)
|
|
249
|
+
row[child.key] = entry.value
|
|
250
|
+
}
|
|
251
|
+
rows.push(row)
|
|
252
|
+
}
|
|
253
|
+
if (rows.length === 0 && !field.required && getStringField(formData, `__rows:${name}`) === null)
|
|
254
|
+
return { value: undefined, present: false }
|
|
255
|
+
return { value: rows, present: rows.length > 0 }
|
|
256
|
+
}
|
|
257
|
+
default: {
|
|
258
|
+
const raw = getStringField(formData, name)
|
|
259
|
+
if (raw === null)
|
|
260
|
+
return { value: undefined, present: false }
|
|
261
|
+
if (raw === '' && !field.required)
|
|
262
|
+
return { value: undefined, present: false }
|
|
263
|
+
return { value: raw, present: raw !== '' }
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/** Parses submitted FormData into a structured frontmatter object according to `fields`. */
|
|
269
|
+
export function parseFormSubmission(formData: FormData, fields: readonly CmsField[]): Record<string, unknown> {
|
|
270
|
+
const out: Record<string, unknown> = {}
|
|
271
|
+
for (const field of fields) {
|
|
272
|
+
const { value } = parseFieldEntry(formData, field, field.key)
|
|
273
|
+
if (value !== undefined)
|
|
274
|
+
out[field.key] = value
|
|
275
|
+
}
|
|
276
|
+
return out
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
/** Parses a `__cms_action` submit button value (`add:<path>`, `remove:<path>:<idx>`, `up:<path>:<idx>`, `down:<path>:<idx>`). */
|
|
280
|
+
export function parseRowAction(raw: string | null): ParsedRowAction | undefined {
|
|
281
|
+
if (raw === null || raw.length === 0)
|
|
282
|
+
return undefined
|
|
283
|
+
const parts = raw.split(':')
|
|
284
|
+
const op = parts[0]
|
|
285
|
+
const path = parts[1]
|
|
286
|
+
if (!path)
|
|
287
|
+
return undefined
|
|
288
|
+
if (op === 'add')
|
|
289
|
+
return { op, path }
|
|
290
|
+
if (op === 'remove' || op === 'up' || op === 'down') {
|
|
291
|
+
const idx = Number.parseInt(parts[2] ?? '', 10)
|
|
292
|
+
if (!Number.isFinite(idx) || idx < 0)
|
|
293
|
+
return undefined
|
|
294
|
+
return { op, path, index: idx }
|
|
295
|
+
}
|
|
296
|
+
return undefined
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
function hasForbiddenPathSegment(segments: readonly string[]): boolean {
|
|
300
|
+
return segments.some(seg => FORBIDDEN_PATH_SEGMENTS.has(seg))
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
function getAtPath(obj: Record<string, unknown>, segments: readonly string[]): unknown {
|
|
304
|
+
if (hasForbiddenPathSegment(segments))
|
|
305
|
+
return undefined
|
|
306
|
+
let cur: unknown = obj
|
|
307
|
+
for (const seg of segments) {
|
|
308
|
+
if (cur === null || typeof cur !== 'object' || Array.isArray(cur) || !Object.hasOwn(cur, seg))
|
|
309
|
+
return undefined
|
|
310
|
+
cur = (cur as Record<string, unknown>)[seg]
|
|
311
|
+
}
|
|
312
|
+
return cur
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
function setAtPath(obj: Record<string, unknown>, segments: readonly string[], value: unknown): void {
|
|
316
|
+
if (segments.length === 0 || hasForbiddenPathSegment(segments))
|
|
317
|
+
return
|
|
318
|
+
let cur: Record<string, unknown> = obj
|
|
319
|
+
for (let i = 0; i < segments.length - 1; i++) {
|
|
320
|
+
const seg = segments[i]!
|
|
321
|
+
const next = Object.hasOwn(cur, seg) ? cur[seg] : undefined
|
|
322
|
+
if (next === null || typeof next !== 'object' || Array.isArray(next)) {
|
|
323
|
+
const created: Record<string, unknown> = {}
|
|
324
|
+
cur[seg] = created
|
|
325
|
+
cur = created
|
|
326
|
+
}
|
|
327
|
+
else {
|
|
328
|
+
cur = next as Record<string, unknown>
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
const last = segments[segments.length - 1]
|
|
332
|
+
if (last !== undefined)
|
|
333
|
+
cur[last] = value
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
/** Applies a no-JS repeatable row action (`add`, `remove`, `up`, `down`) to parsed form data. */
|
|
337
|
+
export function applyRowAction(data: Record<string, unknown>, action: ParsedRowAction): void {
|
|
338
|
+
const segments = action.path.split('.').filter(Boolean)
|
|
339
|
+
if (segments.length === 0 || hasForbiddenPathSegment(segments))
|
|
340
|
+
return
|
|
341
|
+
const existing = getAtPath(data, segments)
|
|
342
|
+
const rows = Array.isArray(existing) ? [...existing] : []
|
|
343
|
+
if (action.op === 'add') {
|
|
344
|
+
if (rows.length < MAX_REPEATABLE_ROWS)
|
|
345
|
+
rows.push({})
|
|
346
|
+
}
|
|
347
|
+
else if (action.op === 'remove' && action.index !== undefined && action.index < rows.length) {
|
|
348
|
+
rows.splice(action.index, 1)
|
|
349
|
+
}
|
|
350
|
+
else if (action.op === 'up' && action.index !== undefined && action.index > 0 && action.index < rows.length) {
|
|
351
|
+
const tmp = rows[action.index - 1]
|
|
352
|
+
rows[action.index - 1] = rows[action.index]
|
|
353
|
+
rows[action.index] = tmp
|
|
354
|
+
}
|
|
355
|
+
else if (action.op === 'down' && action.index !== undefined && action.index >= 0 && action.index + 1 < rows.length) {
|
|
356
|
+
const tmp = rows[action.index + 1]
|
|
357
|
+
rows[action.index + 1] = rows[action.index]
|
|
358
|
+
rows[action.index] = tmp
|
|
359
|
+
}
|
|
360
|
+
setAtPath(data, segments, rows)
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
/** Normalizes dotted issue paths (`items.0.title`) to bracketed input names (`items[0].title`). */
|
|
364
|
+
export function normalizeFieldErrorPath(path: string): string {
|
|
365
|
+
return path.replace(/\.(\d+)(?=\.|$)/g, '[$1]')
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
function serializeYamlScalar(value: unknown): string {
|
|
369
|
+
if (value === null || value === undefined)
|
|
370
|
+
return 'null'
|
|
371
|
+
if (typeof value === 'boolean')
|
|
372
|
+
return value ? 'true' : 'false'
|
|
373
|
+
if (typeof value === 'number')
|
|
374
|
+
return Number.isFinite(value) ? String(value) : 'null'
|
|
375
|
+
if (value instanceof Date)
|
|
376
|
+
return JSON.stringify(value.toISOString())
|
|
377
|
+
const str = String(value)
|
|
378
|
+
if (str.length === 0)
|
|
379
|
+
return '""'
|
|
380
|
+
if (str.includes('\n') || str.includes('\r'))
|
|
381
|
+
return JSON.stringify(str)
|
|
382
|
+
if (str.trim() !== str || YAML_RESERVED_RE.test(str) || !YAML_PLAIN_SAFE_RE.test(str))
|
|
383
|
+
return JSON.stringify(str)
|
|
384
|
+
return str
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
388
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value) && !(value instanceof Date)
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
function serializeYamlObject(obj: Record<string, unknown>, indent: number): string[] {
|
|
392
|
+
const pad = ' '.repeat(indent)
|
|
393
|
+
const lines: string[] = []
|
|
394
|
+
for (const [key, value] of Object.entries(obj)) {
|
|
395
|
+
if (value === undefined)
|
|
396
|
+
continue
|
|
397
|
+
const yamlKey = /^[a-zA-Z0-9_-]+$/.test(key) ? key : JSON.stringify(key)
|
|
398
|
+
if (Array.isArray(value)) {
|
|
399
|
+
if (value.length === 0) {
|
|
400
|
+
lines.push(`${pad}${yamlKey}: []`)
|
|
401
|
+
}
|
|
402
|
+
else {
|
|
403
|
+
lines.push(`${pad}${yamlKey}:`)
|
|
404
|
+
lines.push(...serializeYamlArray(value, indent + 2))
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
else if (isRecord(value)) {
|
|
408
|
+
const inner = serializeYamlObject(value, indent + 2)
|
|
409
|
+
if (inner.length === 0) {
|
|
410
|
+
lines.push(`${pad}${yamlKey}: {}`)
|
|
411
|
+
}
|
|
412
|
+
else {
|
|
413
|
+
lines.push(`${pad}${yamlKey}:`)
|
|
414
|
+
lines.push(...inner)
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
else {
|
|
418
|
+
lines.push(`${pad}${yamlKey}: ${serializeYamlScalar(value)}`)
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
return lines
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
function serializeYamlArray(arr: readonly unknown[], indent: number): string[] {
|
|
425
|
+
const pad = ' '.repeat(indent)
|
|
426
|
+
const lines: string[] = []
|
|
427
|
+
for (const item of arr) {
|
|
428
|
+
if (isRecord(item)) {
|
|
429
|
+
const inner = serializeYamlObject(item, indent + 2)
|
|
430
|
+
if (inner.length === 0) {
|
|
431
|
+
lines.push(`${pad}- {}`)
|
|
432
|
+
}
|
|
433
|
+
else {
|
|
434
|
+
lines.push(`${pad}- ${inner[0]!.slice(indent + 2)}`)
|
|
435
|
+
for (let i = 1; i < inner.length; i++)
|
|
436
|
+
lines.push(inner[i]!)
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
else if (Array.isArray(item)) {
|
|
440
|
+
lines.push(`${pad}- ${JSON.stringify(item)}`)
|
|
441
|
+
}
|
|
442
|
+
else {
|
|
443
|
+
lines.push(`${pad}- ${serializeYamlScalar(item)}`)
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
return lines
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
/** Serializes a frontmatter object into clean YAML text. */
|
|
450
|
+
export function serializeFrontmatterYaml(data: Record<string, unknown>): string {
|
|
451
|
+
return serializeYamlObject(data, 0).join('\n')
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
/** Serializes frontmatter and Markdown body into a `.md` file string. */
|
|
455
|
+
export function serializeMarkdownEntry(data: Record<string, unknown>, body: string): string {
|
|
456
|
+
const yaml = serializeFrontmatterYaml(data)
|
|
457
|
+
const normalizedBody = body.replace(/\r\n/g, '\n')
|
|
458
|
+
const trimmedBody = normalizedBody.endsWith('\n') || normalizedBody.length === 0
|
|
459
|
+
? normalizedBody
|
|
460
|
+
: `${normalizedBody}\n`
|
|
461
|
+
return yaml.length > 0
|
|
462
|
+
? `---\n${yaml}\n---\n\n${trimmedBody}`
|
|
463
|
+
: `---\n---\n\n${trimmedBody}`
|
|
464
|
+
}
|